SemaTemplate.cpp 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847
  1. //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //===----------------------------------------------------------------------===/
  8. //
  9. // This file implements semantic analysis for C++ templates.
  10. //===----------------------------------------------------------------------===/
  11. #include "Sema.h"
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/Expr.h"
  14. #include "clang/AST/ExprCXX.h"
  15. #include "clang/AST/DeclTemplate.h"
  16. #include "clang/Parse/DeclSpec.h"
  17. #include "clang/Basic/LangOptions.h"
  18. using namespace clang;
  19. /// isTemplateName - Determines whether the identifier II is a
  20. /// template name in the current scope, and returns the template
  21. /// declaration if II names a template. An optional CXXScope can be
  22. /// passed to indicate the C++ scope in which the identifier will be
  23. /// found.
  24. TemplateNameKind Sema::isTemplateName(const IdentifierInfo &II, Scope *S,
  25. TemplateTy &TemplateResult,
  26. const CXXScopeSpec *SS) {
  27. NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
  28. TemplateNameKind TNK = TNK_Non_template;
  29. TemplateDecl *Template = 0;
  30. if (IIDecl) {
  31. if ((Template = dyn_cast<TemplateDecl>(IIDecl))) {
  32. if (isa<FunctionTemplateDecl>(IIDecl))
  33. TNK = TNK_Function_template;
  34. else if (isa<ClassTemplateDecl>(IIDecl) ||
  35. isa<TemplateTemplateParmDecl>(IIDecl))
  36. TNK = TNK_Type_template;
  37. else
  38. assert(false && "Unknown template declaration kind");
  39. } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(IIDecl)) {
  40. // C++ [temp.local]p1:
  41. // Like normal (non-template) classes, class templates have an
  42. // injected-class-name (Clause 9). The injected-class-name
  43. // can be used with or without a template-argument-list. When
  44. // it is used without a template-argument-list, it is
  45. // equivalent to the injected-class-name followed by the
  46. // template-parameters of the class template enclosed in
  47. // <>. When it is used with a template-argument-list, it
  48. // refers to the specified class template specialization,
  49. // which could be the current specialization or another
  50. // specialization.
  51. if (Record->isInjectedClassName()) {
  52. Record = cast<CXXRecordDecl>(Context.getCanonicalDecl(Record));
  53. if ((Template = Record->getDescribedClassTemplate()))
  54. TNK = TNK_Type_template;
  55. else if (ClassTemplateSpecializationDecl *Spec
  56. = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
  57. Template = Spec->getSpecializedTemplate();
  58. TNK = TNK_Type_template;
  59. }
  60. }
  61. }
  62. // FIXME: What follows is a gross hack.
  63. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
  64. if (FD->getType()->isDependentType()) {
  65. TemplateResult = TemplateTy::make(FD);
  66. return TNK_Function_template;
  67. }
  68. } else if (OverloadedFunctionDecl *Ovl
  69. = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
  70. for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
  71. FEnd = Ovl->function_end();
  72. F != FEnd; ++F) {
  73. if ((*F)->getType()->isDependentType()) {
  74. TemplateResult = TemplateTy::make(Ovl);
  75. return TNK_Function_template;
  76. }
  77. }
  78. }
  79. if (TNK != TNK_Non_template) {
  80. if (SS && SS->isSet() && !SS->isInvalid()) {
  81. NestedNameSpecifier *Qualifier
  82. = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
  83. TemplateResult
  84. = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier,
  85. false,
  86. Template));
  87. } else
  88. TemplateResult = TemplateTy::make(TemplateName(Template));
  89. }
  90. }
  91. return TNK;
  92. }
  93. /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
  94. /// that the template parameter 'PrevDecl' is being shadowed by a new
  95. /// declaration at location Loc. Returns true to indicate that this is
  96. /// an error, and false otherwise.
  97. bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
  98. assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
  99. // Microsoft Visual C++ permits template parameters to be shadowed.
  100. if (getLangOptions().Microsoft)
  101. return false;
  102. // C++ [temp.local]p4:
  103. // A template-parameter shall not be redeclared within its
  104. // scope (including nested scopes).
  105. Diag(Loc, diag::err_template_param_shadow)
  106. << cast<NamedDecl>(PrevDecl)->getDeclName();
  107. Diag(PrevDecl->getLocation(), diag::note_template_param_here);
  108. return true;
  109. }
  110. /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
  111. /// the parameter D to reference the templated declaration and return a pointer
  112. /// to the template declaration. Otherwise, do nothing to D and return null.
  113. TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
  114. if (TemplateDecl *Temp = dyn_cast<TemplateDecl>(D.getAs<Decl>())) {
  115. D = DeclPtrTy::make(Temp->getTemplatedDecl());
  116. return Temp;
  117. }
  118. return 0;
  119. }
  120. /// ActOnTypeParameter - Called when a C++ template type parameter
  121. /// (e.g., "typename T") has been parsed. Typename specifies whether
  122. /// the keyword "typename" was used to declare the type parameter
  123. /// (otherwise, "class" was used), and KeyLoc is the location of the
  124. /// "class" or "typename" keyword. ParamName is the name of the
  125. /// parameter (NULL indicates an unnamed template parameter) and
  126. /// ParamName is the location of the parameter name (if any).
  127. /// If the type parameter has a default argument, it will be added
  128. /// later via ActOnTypeParameterDefault.
  129. Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
  130. SourceLocation EllipsisLoc,
  131. SourceLocation KeyLoc,
  132. IdentifierInfo *ParamName,
  133. SourceLocation ParamNameLoc,
  134. unsigned Depth, unsigned Position) {
  135. assert(S->isTemplateParamScope() &&
  136. "Template type parameter not in template parameter scope!");
  137. bool Invalid = false;
  138. if (ParamName) {
  139. NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
  140. if (PrevDecl && PrevDecl->isTemplateParameter())
  141. Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
  142. PrevDecl);
  143. }
  144. SourceLocation Loc = ParamNameLoc;
  145. if (!ParamName)
  146. Loc = KeyLoc;
  147. TemplateTypeParmDecl *Param
  148. = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
  149. Depth, Position, ParamName, Typename,
  150. Ellipsis);
  151. if (Invalid)
  152. Param->setInvalidDecl();
  153. if (ParamName) {
  154. // Add the template parameter into the current scope.
  155. S->AddDecl(DeclPtrTy::make(Param));
  156. IdResolver.AddDecl(Param);
  157. }
  158. return DeclPtrTy::make(Param);
  159. }
  160. /// ActOnTypeParameterDefault - Adds a default argument (the type
  161. /// Default) to the given template type parameter (TypeParam).
  162. void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
  163. SourceLocation EqualLoc,
  164. SourceLocation DefaultLoc,
  165. TypeTy *DefaultT) {
  166. TemplateTypeParmDecl *Parm
  167. = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
  168. QualType Default = QualType::getFromOpaquePtr(DefaultT);
  169. // C++0x [temp.param]p9:
  170. // A default template-argument may be specified for any kind of
  171. // template-parameter that is not a template parameter pack.
  172. if (Parm->isParameterPack()) {
  173. Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
  174. return;
  175. }
  176. // C++ [temp.param]p14:
  177. // A template-parameter shall not be used in its own default argument.
  178. // FIXME: Implement this check! Needs a recursive walk over the types.
  179. // Check the template argument itself.
  180. if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
  181. Parm->setInvalidDecl();
  182. return;
  183. }
  184. Parm->setDefaultArgument(Default, DefaultLoc, false);
  185. }
  186. /// \brief Check that the type of a non-type template parameter is
  187. /// well-formed.
  188. ///
  189. /// \returns the (possibly-promoted) parameter type if valid;
  190. /// otherwise, produces a diagnostic and returns a NULL type.
  191. QualType
  192. Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
  193. // C++ [temp.param]p4:
  194. //
  195. // A non-type template-parameter shall have one of the following
  196. // (optionally cv-qualified) types:
  197. //
  198. // -- integral or enumeration type,
  199. if (T->isIntegralType() || T->isEnumeralType() ||
  200. // -- pointer to object or pointer to function,
  201. (T->isPointerType() &&
  202. (T->getAsPointerType()->getPointeeType()->isObjectType() ||
  203. T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
  204. // -- reference to object or reference to function,
  205. T->isReferenceType() ||
  206. // -- pointer to member.
  207. T->isMemberPointerType() ||
  208. // If T is a dependent type, we can't do the check now, so we
  209. // assume that it is well-formed.
  210. T->isDependentType())
  211. return T;
  212. // C++ [temp.param]p8:
  213. //
  214. // A non-type template-parameter of type "array of T" or
  215. // "function returning T" is adjusted to be of type "pointer to
  216. // T" or "pointer to function returning T", respectively.
  217. else if (T->isArrayType())
  218. // FIXME: Keep the type prior to promotion?
  219. return Context.getArrayDecayedType(T);
  220. else if (T->isFunctionType())
  221. // FIXME: Keep the type prior to promotion?
  222. return Context.getPointerType(T);
  223. Diag(Loc, diag::err_template_nontype_parm_bad_type)
  224. << T;
  225. return QualType();
  226. }
  227. /// ActOnNonTypeTemplateParameter - Called when a C++ non-type
  228. /// template parameter (e.g., "int Size" in "template<int Size>
  229. /// class Array") has been parsed. S is the current scope and D is
  230. /// the parsed declarator.
  231. Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
  232. unsigned Depth,
  233. unsigned Position) {
  234. QualType T = GetTypeForDeclarator(D, S);
  235. assert(S->isTemplateParamScope() &&
  236. "Non-type template parameter not in template parameter scope!");
  237. bool Invalid = false;
  238. IdentifierInfo *ParamName = D.getIdentifier();
  239. if (ParamName) {
  240. NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
  241. if (PrevDecl && PrevDecl->isTemplateParameter())
  242. Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  243. PrevDecl);
  244. }
  245. T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
  246. if (T.isNull()) {
  247. T = Context.IntTy; // Recover with an 'int' type.
  248. Invalid = true;
  249. }
  250. NonTypeTemplateParmDecl *Param
  251. = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
  252. Depth, Position, ParamName, T);
  253. if (Invalid)
  254. Param->setInvalidDecl();
  255. if (D.getIdentifier()) {
  256. // Add the template parameter into the current scope.
  257. S->AddDecl(DeclPtrTy::make(Param));
  258. IdResolver.AddDecl(Param);
  259. }
  260. return DeclPtrTy::make(Param);
  261. }
  262. /// \brief Adds a default argument to the given non-type template
  263. /// parameter.
  264. void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
  265. SourceLocation EqualLoc,
  266. ExprArg DefaultE) {
  267. NonTypeTemplateParmDecl *TemplateParm
  268. = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
  269. Expr *Default = static_cast<Expr *>(DefaultE.get());
  270. // C++ [temp.param]p14:
  271. // A template-parameter shall not be used in its own default argument.
  272. // FIXME: Implement this check! Needs a recursive walk over the types.
  273. // Check the well-formedness of the default template argument.
  274. TemplateArgument Converted;
  275. if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
  276. Converted)) {
  277. TemplateParm->setInvalidDecl();
  278. return;
  279. }
  280. TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
  281. }
  282. /// ActOnTemplateTemplateParameter - Called when a C++ template template
  283. /// parameter (e.g. T in template <template <typename> class T> class array)
  284. /// has been parsed. S is the current scope.
  285. Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
  286. SourceLocation TmpLoc,
  287. TemplateParamsTy *Params,
  288. IdentifierInfo *Name,
  289. SourceLocation NameLoc,
  290. unsigned Depth,
  291. unsigned Position)
  292. {
  293. assert(S->isTemplateParamScope() &&
  294. "Template template parameter not in template parameter scope!");
  295. // Construct the parameter object.
  296. TemplateTemplateParmDecl *Param =
  297. TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
  298. Position, Name,
  299. (TemplateParameterList*)Params);
  300. // Make sure the parameter is valid.
  301. // FIXME: Decl object is not currently invalidated anywhere so this doesn't
  302. // do anything yet. However, if the template parameter list or (eventual)
  303. // default value is ever invalidated, that will propagate here.
  304. bool Invalid = false;
  305. if (Invalid) {
  306. Param->setInvalidDecl();
  307. }
  308. // If the tt-param has a name, then link the identifier into the scope
  309. // and lookup mechanisms.
  310. if (Name) {
  311. S->AddDecl(DeclPtrTy::make(Param));
  312. IdResolver.AddDecl(Param);
  313. }
  314. return DeclPtrTy::make(Param);
  315. }
  316. /// \brief Adds a default argument to the given template template
  317. /// parameter.
  318. void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
  319. SourceLocation EqualLoc,
  320. ExprArg DefaultE) {
  321. TemplateTemplateParmDecl *TemplateParm
  322. = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
  323. // Since a template-template parameter's default argument is an
  324. // id-expression, it must be a DeclRefExpr.
  325. DeclRefExpr *Default
  326. = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
  327. // C++ [temp.param]p14:
  328. // A template-parameter shall not be used in its own default argument.
  329. // FIXME: Implement this check! Needs a recursive walk over the types.
  330. // Check the well-formedness of the template argument.
  331. if (!isa<TemplateDecl>(Default->getDecl())) {
  332. Diag(Default->getSourceRange().getBegin(),
  333. diag::err_template_arg_must_be_template)
  334. << Default->getSourceRange();
  335. TemplateParm->setInvalidDecl();
  336. return;
  337. }
  338. if (CheckTemplateArgument(TemplateParm, Default)) {
  339. TemplateParm->setInvalidDecl();
  340. return;
  341. }
  342. DefaultE.release();
  343. TemplateParm->setDefaultArgument(Default);
  344. }
  345. /// ActOnTemplateParameterList - Builds a TemplateParameterList that
  346. /// contains the template parameters in Params/NumParams.
  347. Sema::TemplateParamsTy *
  348. Sema::ActOnTemplateParameterList(unsigned Depth,
  349. SourceLocation ExportLoc,
  350. SourceLocation TemplateLoc,
  351. SourceLocation LAngleLoc,
  352. DeclPtrTy *Params, unsigned NumParams,
  353. SourceLocation RAngleLoc) {
  354. if (ExportLoc.isValid())
  355. Diag(ExportLoc, diag::note_template_export_unsupported);
  356. return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
  357. (Decl**)Params, NumParams, RAngleLoc);
  358. }
  359. Sema::DeclResult
  360. Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
  361. SourceLocation KWLoc, const CXXScopeSpec &SS,
  362. IdentifierInfo *Name, SourceLocation NameLoc,
  363. AttributeList *Attr,
  364. MultiTemplateParamsArg TemplateParameterLists,
  365. AccessSpecifier AS) {
  366. assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
  367. assert(TK != TK_Reference && "Can only declare or define class templates");
  368. bool Invalid = false;
  369. // Check that we can declare a template here.
  370. if (CheckTemplateDeclScope(S, TemplateParameterLists))
  371. return true;
  372. TagDecl::TagKind Kind;
  373. switch (TagSpec) {
  374. default: assert(0 && "Unknown tag type!");
  375. case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
  376. case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
  377. case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
  378. }
  379. // There is no such thing as an unnamed class template.
  380. if (!Name) {
  381. Diag(KWLoc, diag::err_template_unnamed_class);
  382. return true;
  383. }
  384. // Find any previous declaration with this name.
  385. LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
  386. true);
  387. assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
  388. NamedDecl *PrevDecl = 0;
  389. if (Previous.begin() != Previous.end())
  390. PrevDecl = *Previous.begin();
  391. DeclContext *SemanticContext = CurContext;
  392. if (SS.isNotEmpty() && !SS.isInvalid()) {
  393. SemanticContext = computeDeclContext(SS);
  394. // FIXME: need to match up several levels of template parameter lists here.
  395. }
  396. // FIXME: member templates!
  397. TemplateParameterList *TemplateParams
  398. = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
  399. // If there is a previous declaration with the same name, check
  400. // whether this is a valid redeclaration.
  401. ClassTemplateDecl *PrevClassTemplate
  402. = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
  403. if (PrevClassTemplate) {
  404. // Ensure that the template parameter lists are compatible.
  405. if (!TemplateParameterListsAreEqual(TemplateParams,
  406. PrevClassTemplate->getTemplateParameters(),
  407. /*Complain=*/true))
  408. return true;
  409. // C++ [temp.class]p4:
  410. // In a redeclaration, partial specialization, explicit
  411. // specialization or explicit instantiation of a class template,
  412. // the class-key shall agree in kind with the original class
  413. // template declaration (7.1.5.3).
  414. RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
  415. if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
  416. Diag(KWLoc, diag::err_use_with_wrong_tag)
  417. << Name
  418. << CodeModificationHint::CreateReplacement(KWLoc,
  419. PrevRecordDecl->getKindName());
  420. Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
  421. Kind = PrevRecordDecl->getTagKind();
  422. }
  423. // Check for redefinition of this class template.
  424. if (TK == TK_Definition) {
  425. if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
  426. Diag(NameLoc, diag::err_redefinition) << Name;
  427. Diag(Def->getLocation(), diag::note_previous_definition);
  428. // FIXME: Would it make sense to try to "forget" the previous
  429. // definition, as part of error recovery?
  430. return true;
  431. }
  432. }
  433. } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
  434. // Maybe we will complain about the shadowed template parameter.
  435. DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
  436. // Just pretend that we didn't see the previous declaration.
  437. PrevDecl = 0;
  438. } else if (PrevDecl) {
  439. // C++ [temp]p5:
  440. // A class template shall not have the same name as any other
  441. // template, class, function, object, enumeration, enumerator,
  442. // namespace, or type in the same scope (3.3), except as specified
  443. // in (14.5.4).
  444. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  445. Diag(PrevDecl->getLocation(), diag::note_previous_definition);
  446. return true;
  447. }
  448. // Check the template parameter list of this declaration, possibly
  449. // merging in the template parameter list from the previous class
  450. // template declaration.
  451. if (CheckTemplateParameterList(TemplateParams,
  452. PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
  453. Invalid = true;
  454. // FIXME: If we had a scope specifier, we better have a previous template
  455. // declaration!
  456. CXXRecordDecl *NewClass =
  457. CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
  458. PrevClassTemplate?
  459. PrevClassTemplate->getTemplatedDecl() : 0,
  460. /*DelayTypeCreation=*/true);
  461. ClassTemplateDecl *NewTemplate
  462. = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
  463. DeclarationName(Name), TemplateParams,
  464. NewClass, PrevClassTemplate);
  465. NewClass->setDescribedClassTemplate(NewTemplate);
  466. // Build the type for the class template declaration now.
  467. QualType T =
  468. Context.getTypeDeclType(NewClass,
  469. PrevClassTemplate?
  470. PrevClassTemplate->getTemplatedDecl() : 0);
  471. assert(T->isDependentType() && "Class template type is not dependent?");
  472. (void)T;
  473. // Set the access specifier.
  474. SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
  475. // Set the lexical context of these templates
  476. NewClass->setLexicalDeclContext(CurContext);
  477. NewTemplate->setLexicalDeclContext(CurContext);
  478. if (TK == TK_Definition)
  479. NewClass->startDefinition();
  480. if (Attr)
  481. ProcessDeclAttributeList(NewClass, Attr);
  482. PushOnScopeChains(NewTemplate, S);
  483. if (Invalid) {
  484. NewTemplate->setInvalidDecl();
  485. NewClass->setInvalidDecl();
  486. }
  487. return DeclPtrTy::make(NewTemplate);
  488. }
  489. /// \brief Checks the validity of a template parameter list, possibly
  490. /// considering the template parameter list from a previous
  491. /// declaration.
  492. ///
  493. /// If an "old" template parameter list is provided, it must be
  494. /// equivalent (per TemplateParameterListsAreEqual) to the "new"
  495. /// template parameter list.
  496. ///
  497. /// \param NewParams Template parameter list for a new template
  498. /// declaration. This template parameter list will be updated with any
  499. /// default arguments that are carried through from the previous
  500. /// template parameter list.
  501. ///
  502. /// \param OldParams If provided, template parameter list from a
  503. /// previous declaration of the same template. Default template
  504. /// arguments will be merged from the old template parameter list to
  505. /// the new template parameter list.
  506. ///
  507. /// \returns true if an error occurred, false otherwise.
  508. bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
  509. TemplateParameterList *OldParams) {
  510. bool Invalid = false;
  511. // C++ [temp.param]p10:
  512. // The set of default template-arguments available for use with a
  513. // template declaration or definition is obtained by merging the
  514. // default arguments from the definition (if in scope) and all
  515. // declarations in scope in the same way default function
  516. // arguments are (8.3.6).
  517. bool SawDefaultArgument = false;
  518. SourceLocation PreviousDefaultArgLoc;
  519. bool SawParameterPack = false;
  520. SourceLocation ParameterPackLoc;
  521. // Dummy initialization to avoid warnings.
  522. TemplateParameterList::iterator OldParam = NewParams->end();
  523. if (OldParams)
  524. OldParam = OldParams->begin();
  525. for (TemplateParameterList::iterator NewParam = NewParams->begin(),
  526. NewParamEnd = NewParams->end();
  527. NewParam != NewParamEnd; ++NewParam) {
  528. // Variables used to diagnose redundant default arguments
  529. bool RedundantDefaultArg = false;
  530. SourceLocation OldDefaultLoc;
  531. SourceLocation NewDefaultLoc;
  532. // Variables used to diagnose missing default arguments
  533. bool MissingDefaultArg = false;
  534. // C++0x [temp.param]p11:
  535. // If a template parameter of a class template is a template parameter pack,
  536. // it must be the last template parameter.
  537. if (SawParameterPack) {
  538. Diag(ParameterPackLoc,
  539. diag::err_template_param_pack_must_be_last_template_parameter);
  540. Invalid = true;
  541. }
  542. // Merge default arguments for template type parameters.
  543. if (TemplateTypeParmDecl *NewTypeParm
  544. = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
  545. TemplateTypeParmDecl *OldTypeParm
  546. = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
  547. if (NewTypeParm->isParameterPack()) {
  548. assert(!NewTypeParm->hasDefaultArgument() &&
  549. "Parameter packs can't have a default argument!");
  550. SawParameterPack = true;
  551. ParameterPackLoc = NewTypeParm->getLocation();
  552. } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
  553. NewTypeParm->hasDefaultArgument()) {
  554. OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
  555. NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
  556. SawDefaultArgument = true;
  557. RedundantDefaultArg = true;
  558. PreviousDefaultArgLoc = NewDefaultLoc;
  559. } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
  560. // Merge the default argument from the old declaration to the
  561. // new declaration.
  562. SawDefaultArgument = true;
  563. NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
  564. OldTypeParm->getDefaultArgumentLoc(),
  565. true);
  566. PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
  567. } else if (NewTypeParm->hasDefaultArgument()) {
  568. SawDefaultArgument = true;
  569. PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
  570. } else if (SawDefaultArgument)
  571. MissingDefaultArg = true;
  572. }
  573. // Merge default arguments for non-type template parameters
  574. else if (NonTypeTemplateParmDecl *NewNonTypeParm
  575. = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
  576. NonTypeTemplateParmDecl *OldNonTypeParm
  577. = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
  578. if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
  579. NewNonTypeParm->hasDefaultArgument()) {
  580. OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
  581. NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
  582. SawDefaultArgument = true;
  583. RedundantDefaultArg = true;
  584. PreviousDefaultArgLoc = NewDefaultLoc;
  585. } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
  586. // Merge the default argument from the old declaration to the
  587. // new declaration.
  588. SawDefaultArgument = true;
  589. // FIXME: We need to create a new kind of "default argument"
  590. // expression that points to a previous template template
  591. // parameter.
  592. NewNonTypeParm->setDefaultArgument(
  593. OldNonTypeParm->getDefaultArgument());
  594. PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
  595. } else if (NewNonTypeParm->hasDefaultArgument()) {
  596. SawDefaultArgument = true;
  597. PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
  598. } else if (SawDefaultArgument)
  599. MissingDefaultArg = true;
  600. }
  601. // Merge default arguments for template template parameters
  602. else {
  603. TemplateTemplateParmDecl *NewTemplateParm
  604. = cast<TemplateTemplateParmDecl>(*NewParam);
  605. TemplateTemplateParmDecl *OldTemplateParm
  606. = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
  607. if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
  608. NewTemplateParm->hasDefaultArgument()) {
  609. OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
  610. NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
  611. SawDefaultArgument = true;
  612. RedundantDefaultArg = true;
  613. PreviousDefaultArgLoc = NewDefaultLoc;
  614. } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
  615. // Merge the default argument from the old declaration to the
  616. // new declaration.
  617. SawDefaultArgument = true;
  618. // FIXME: We need to create a new kind of "default argument" expression
  619. // that points to a previous template template parameter.
  620. NewTemplateParm->setDefaultArgument(
  621. OldTemplateParm->getDefaultArgument());
  622. PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
  623. } else if (NewTemplateParm->hasDefaultArgument()) {
  624. SawDefaultArgument = true;
  625. PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
  626. } else if (SawDefaultArgument)
  627. MissingDefaultArg = true;
  628. }
  629. if (RedundantDefaultArg) {
  630. // C++ [temp.param]p12:
  631. // A template-parameter shall not be given default arguments
  632. // by two different declarations in the same scope.
  633. Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
  634. Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
  635. Invalid = true;
  636. } else if (MissingDefaultArg) {
  637. // C++ [temp.param]p11:
  638. // If a template-parameter has a default template-argument,
  639. // all subsequent template-parameters shall have a default
  640. // template-argument supplied.
  641. Diag((*NewParam)->getLocation(),
  642. diag::err_template_param_default_arg_missing);
  643. Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
  644. Invalid = true;
  645. }
  646. // If we have an old template parameter list that we're merging
  647. // in, move on to the next parameter.
  648. if (OldParams)
  649. ++OldParam;
  650. }
  651. return Invalid;
  652. }
  653. /// \brief Translates template arguments as provided by the parser
  654. /// into template arguments used by semantic analysis.
  655. static void
  656. translateTemplateArguments(ASTTemplateArgsPtr &TemplateArgsIn,
  657. SourceLocation *TemplateArgLocs,
  658. llvm::SmallVector<TemplateArgument, 16> &TemplateArgs) {
  659. TemplateArgs.reserve(TemplateArgsIn.size());
  660. void **Args = TemplateArgsIn.getArgs();
  661. bool *ArgIsType = TemplateArgsIn.getArgIsType();
  662. for (unsigned Arg = 0, Last = TemplateArgsIn.size(); Arg != Last; ++Arg) {
  663. TemplateArgs.push_back(
  664. ArgIsType[Arg]? TemplateArgument(TemplateArgLocs[Arg],
  665. QualType::getFromOpaquePtr(Args[Arg]))
  666. : TemplateArgument(reinterpret_cast<Expr *>(Args[Arg])));
  667. }
  668. }
  669. /// \brief Build a canonical version of a template argument list.
  670. ///
  671. /// This function builds a canonical version of the given template
  672. /// argument list, where each of the template arguments has been
  673. /// converted into its canonical form. This routine is typically used
  674. /// to canonicalize a template argument list when the template name
  675. /// itself is dependent. When the template name refers to an actual
  676. /// template declaration, Sema::CheckTemplateArgumentList should be
  677. /// used to check and canonicalize the template arguments.
  678. ///
  679. /// \param TemplateArgs The incoming template arguments.
  680. ///
  681. /// \param NumTemplateArgs The number of template arguments in \p
  682. /// TemplateArgs.
  683. ///
  684. /// \param Canonical A vector to be filled with the canonical versions
  685. /// of the template arguments.
  686. ///
  687. /// \param Context The ASTContext in which the template arguments live.
  688. static void CanonicalizeTemplateArguments(const TemplateArgument *TemplateArgs,
  689. unsigned NumTemplateArgs,
  690. llvm::SmallVectorImpl<TemplateArgument> &Canonical,
  691. ASTContext &Context) {
  692. Canonical.reserve(NumTemplateArgs);
  693. for (unsigned Idx = 0; Idx < NumTemplateArgs; ++Idx) {
  694. switch (TemplateArgs[Idx].getKind()) {
  695. case TemplateArgument::Null:
  696. assert(false && "Should never see a NULL template argument here");
  697. break;
  698. case TemplateArgument::Expression:
  699. // FIXME: Build canonical expression (!)
  700. Canonical.push_back(TemplateArgs[Idx]);
  701. break;
  702. case TemplateArgument::Declaration:
  703. Canonical.push_back(
  704. TemplateArgument(SourceLocation(),
  705. Context.getCanonicalDecl(TemplateArgs[Idx].getAsDecl())));
  706. break;
  707. case TemplateArgument::Integral:
  708. Canonical.push_back(TemplateArgument(SourceLocation(),
  709. *TemplateArgs[Idx].getAsIntegral(),
  710. TemplateArgs[Idx].getIntegralType()));
  711. break;
  712. case TemplateArgument::Type: {
  713. QualType CanonType
  714. = Context.getCanonicalType(TemplateArgs[Idx].getAsType());
  715. Canonical.push_back(TemplateArgument(SourceLocation(), CanonType));
  716. break;
  717. }
  718. }
  719. }
  720. }
  721. QualType Sema::CheckTemplateIdType(TemplateName Name,
  722. SourceLocation TemplateLoc,
  723. SourceLocation LAngleLoc,
  724. const TemplateArgument *TemplateArgs,
  725. unsigned NumTemplateArgs,
  726. SourceLocation RAngleLoc) {
  727. TemplateDecl *Template = Name.getAsTemplateDecl();
  728. if (!Template) {
  729. // The template name does not resolve to a template, so we just
  730. // build a dependent template-id type.
  731. // Canonicalize the template arguments to build the canonical
  732. // template-id type.
  733. llvm::SmallVector<TemplateArgument, 16> CanonicalTemplateArgs;
  734. CanonicalizeTemplateArguments(TemplateArgs, NumTemplateArgs,
  735. CanonicalTemplateArgs, Context);
  736. TemplateName CanonName = Context.getCanonicalTemplateName(Name);
  737. QualType CanonType
  738. = Context.getTemplateSpecializationType(CanonName,
  739. &CanonicalTemplateArgs[0],
  740. CanonicalTemplateArgs.size());
  741. // Build the dependent template-id type.
  742. return Context.getTemplateSpecializationType(Name, TemplateArgs,
  743. NumTemplateArgs, CanonType);
  744. }
  745. // Check that the template argument list is well-formed for this
  746. // template.
  747. TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
  748. if (CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
  749. TemplateArgs, NumTemplateArgs, RAngleLoc,
  750. ConvertedTemplateArgs))
  751. return QualType();
  752. assert((ConvertedTemplateArgs.size() ==
  753. Template->getTemplateParameters()->size()) &&
  754. "Converted template argument list is too short!");
  755. QualType CanonType;
  756. if (TemplateSpecializationType::anyDependentTemplateArguments(
  757. TemplateArgs,
  758. NumTemplateArgs)) {
  759. // This class template specialization is a dependent
  760. // type. Therefore, its canonical type is another class template
  761. // specialization type that contains all of the converted
  762. // arguments in canonical form. This ensures that, e.g., A<T> and
  763. // A<T, T> have identical types when A is declared as:
  764. //
  765. // template<typename T, typename U = T> struct A;
  766. TemplateName CanonName = Context.getCanonicalTemplateName(Name);
  767. CanonType = Context.getTemplateSpecializationType(CanonName,
  768. ConvertedTemplateArgs.getFlatArgumentList(),
  769. ConvertedTemplateArgs.flatSize());
  770. } else if (ClassTemplateDecl *ClassTemplate
  771. = dyn_cast<ClassTemplateDecl>(Template)) {
  772. // Find the class template specialization declaration that
  773. // corresponds to these arguments.
  774. llvm::FoldingSetNodeID ID;
  775. ClassTemplateSpecializationDecl::Profile(ID,
  776. ConvertedTemplateArgs.getFlatArgumentList(),
  777. ConvertedTemplateArgs.flatSize());
  778. void *InsertPos = 0;
  779. ClassTemplateSpecializationDecl *Decl
  780. = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
  781. if (!Decl) {
  782. // This is the first time we have referenced this class template
  783. // specialization. Create the canonical declaration and add it to
  784. // the set of specializations.
  785. Decl = ClassTemplateSpecializationDecl::Create(Context,
  786. ClassTemplate->getDeclContext(),
  787. TemplateLoc,
  788. ClassTemplate,
  789. ConvertedTemplateArgs, 0);
  790. ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
  791. Decl->setLexicalDeclContext(CurContext);
  792. }
  793. CanonType = Context.getTypeDeclType(Decl);
  794. }
  795. // Build the fully-sugared type for this class template
  796. // specialization, which refers back to the class template
  797. // specialization we created or found.
  798. return Context.getTemplateSpecializationType(Name, TemplateArgs,
  799. NumTemplateArgs, CanonType);
  800. }
  801. Action::TypeResult
  802. Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
  803. SourceLocation LAngleLoc,
  804. ASTTemplateArgsPtr TemplateArgsIn,
  805. SourceLocation *TemplateArgLocs,
  806. SourceLocation RAngleLoc) {
  807. TemplateName Template = TemplateD.getAsVal<TemplateName>();
  808. // Translate the parser's template argument list in our AST format.
  809. llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
  810. translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
  811. QualType Result = CheckTemplateIdType(Template, TemplateLoc, LAngleLoc,
  812. TemplateArgs.data(),
  813. TemplateArgs.size(),
  814. RAngleLoc);
  815. TemplateArgsIn.release();
  816. if (Result.isNull())
  817. return true;
  818. return Result.getAsOpaquePtr();
  819. }
  820. /// \brief Form a dependent template name.
  821. ///
  822. /// This action forms a dependent template name given the template
  823. /// name and its (presumably dependent) scope specifier. For
  824. /// example, given "MetaFun::template apply", the scope specifier \p
  825. /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
  826. /// of the "template" keyword, and "apply" is the \p Name.
  827. Sema::TemplateTy
  828. Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
  829. const IdentifierInfo &Name,
  830. SourceLocation NameLoc,
  831. const CXXScopeSpec &SS) {
  832. if (!SS.isSet() || SS.isInvalid())
  833. return TemplateTy();
  834. NestedNameSpecifier *Qualifier
  835. = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
  836. // FIXME: member of the current instantiation
  837. if (!Qualifier->isDependent()) {
  838. // C++0x [temp.names]p5:
  839. // If a name prefixed by the keyword template is not the name of
  840. // a template, the program is ill-formed. [Note: the keyword
  841. // template may not be applied to non-template members of class
  842. // templates. -end note ] [ Note: as is the case with the
  843. // typename prefix, the template prefix is allowed in cases
  844. // where it is not strictly necessary; i.e., when the
  845. // nested-name-specifier or the expression on the left of the ->
  846. // or . is not dependent on a template-parameter, or the use
  847. // does not appear in the scope of a template. -end note]
  848. //
  849. // Note: C++03 was more strict here, because it banned the use of
  850. // the "template" keyword prior to a template-name that was not a
  851. // dependent name. C++ DR468 relaxed this requirement (the
  852. // "template" keyword is now permitted). We follow the C++0x
  853. // rules, even in C++03 mode, retroactively applying the DR.
  854. TemplateTy Template;
  855. TemplateNameKind TNK = isTemplateName(Name, 0, Template, &SS);
  856. if (TNK == TNK_Non_template) {
  857. Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
  858. << &Name;
  859. return TemplateTy();
  860. }
  861. return Template;
  862. }
  863. return TemplateTy::make(Context.getDependentTemplateName(Qualifier, &Name));
  864. }
  865. bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
  866. const TemplateArgument &Arg,
  867. TemplateArgumentListBuilder &Converted) {
  868. // Check template type parameter.
  869. if (Arg.getKind() != TemplateArgument::Type) {
  870. // C++ [temp.arg.type]p1:
  871. // A template-argument for a template-parameter which is a
  872. // type shall be a type-id.
  873. // We have a template type parameter but the template argument
  874. // is not a type.
  875. Diag(Arg.getLocation(), diag::err_template_arg_must_be_type);
  876. Diag(Param->getLocation(), diag::note_template_param_here);
  877. return true;
  878. }
  879. if (CheckTemplateArgument(Param, Arg.getAsType(), Arg.getLocation()))
  880. return true;
  881. // Add the converted template type argument.
  882. Converted.push_back(
  883. TemplateArgument(Arg.getLocation(),
  884. Context.getCanonicalType(Arg.getAsType())));
  885. return false;
  886. }
  887. /// \brief Check that the given template argument list is well-formed
  888. /// for specializing the given template.
  889. bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
  890. SourceLocation TemplateLoc,
  891. SourceLocation LAngleLoc,
  892. const TemplateArgument *TemplateArgs,
  893. unsigned NumTemplateArgs,
  894. SourceLocation RAngleLoc,
  895. TemplateArgumentListBuilder &Converted) {
  896. TemplateParameterList *Params = Template->getTemplateParameters();
  897. unsigned NumParams = Params->size();
  898. unsigned NumArgs = NumTemplateArgs;
  899. bool Invalid = false;
  900. bool HasParameterPack =
  901. NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
  902. if ((NumArgs > NumParams && !HasParameterPack) ||
  903. NumArgs < Params->getMinRequiredArguments()) {
  904. // FIXME: point at either the first arg beyond what we can handle,
  905. // or the '>', depending on whether we have too many or too few
  906. // arguments.
  907. SourceRange Range;
  908. if (NumArgs > NumParams)
  909. Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
  910. Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
  911. << (NumArgs > NumParams)
  912. << (isa<ClassTemplateDecl>(Template)? 0 :
  913. isa<FunctionTemplateDecl>(Template)? 1 :
  914. isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
  915. << Template << Range;
  916. Diag(Template->getLocation(), diag::note_template_decl_here)
  917. << Params->getSourceRange();
  918. Invalid = true;
  919. }
  920. // C++ [temp.arg]p1:
  921. // [...] The type and form of each template-argument specified in
  922. // a template-id shall match the type and form specified for the
  923. // corresponding parameter declared by the template in its
  924. // template-parameter-list.
  925. unsigned ArgIdx = 0;
  926. for (TemplateParameterList::iterator Param = Params->begin(),
  927. ParamEnd = Params->end();
  928. Param != ParamEnd; ++Param, ++ArgIdx) {
  929. // Decode the template argument
  930. TemplateArgument Arg;
  931. if (ArgIdx >= NumArgs) {
  932. // Retrieve the default template argument from the template
  933. // parameter.
  934. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
  935. if (TTP->isParameterPack()) {
  936. // We have an empty parameter pack.
  937. Converted.BeginParameterPack();
  938. Converted.EndParameterPack();
  939. break;
  940. }
  941. if (!TTP->hasDefaultArgument())
  942. break;
  943. QualType ArgType = TTP->getDefaultArgument();
  944. // If the argument type is dependent, instantiate it now based
  945. // on the previously-computed template arguments.
  946. if (ArgType->isDependentType()) {
  947. InstantiatingTemplate Inst(*this, TemplateLoc,
  948. Template, Converted.getFlatArgumentList(),
  949. Converted.flatSize(),
  950. SourceRange(TemplateLoc, RAngleLoc));
  951. TemplateArgumentList TemplateArgs(Context, Converted,
  952. /*CopyArgs=*/false,
  953. /*FlattenArgs=*/false);
  954. ArgType = InstantiateType(ArgType, TemplateArgs,
  955. TTP->getDefaultArgumentLoc(),
  956. TTP->getDeclName());
  957. }
  958. if (ArgType.isNull())
  959. return true;
  960. Arg = TemplateArgument(TTP->getLocation(), ArgType);
  961. } else if (NonTypeTemplateParmDecl *NTTP
  962. = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
  963. if (!NTTP->hasDefaultArgument())
  964. break;
  965. InstantiatingTemplate Inst(*this, TemplateLoc,
  966. Template, Converted.getFlatArgumentList(),
  967. Converted.flatSize(),
  968. SourceRange(TemplateLoc, RAngleLoc));
  969. TemplateArgumentList TemplateArgs(Context, Converted,
  970. /*CopyArgs=*/false,
  971. /*FlattenArgs=*/false);
  972. Sema::OwningExprResult E = InstantiateExpr(NTTP->getDefaultArgument(),
  973. TemplateArgs);
  974. if (E.isInvalid())
  975. return true;
  976. Arg = TemplateArgument(E.takeAs<Expr>());
  977. } else {
  978. TemplateTemplateParmDecl *TempParm
  979. = cast<TemplateTemplateParmDecl>(*Param);
  980. if (!TempParm->hasDefaultArgument())
  981. break;
  982. // FIXME: Instantiate default argument
  983. Arg = TemplateArgument(TempParm->getDefaultArgument());
  984. }
  985. } else {
  986. // Retrieve the template argument produced by the user.
  987. Arg = TemplateArgs[ArgIdx];
  988. }
  989. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
  990. if (TTP->isParameterPack()) {
  991. Converted.BeginParameterPack();
  992. // Check all the remaining arguments (if any).
  993. for (; ArgIdx < NumArgs; ++ArgIdx) {
  994. if (CheckTemplateTypeArgument(TTP, TemplateArgs[ArgIdx], Converted))
  995. Invalid = true;
  996. }
  997. Converted.EndParameterPack();
  998. } else {
  999. if (CheckTemplateTypeArgument(TTP, Arg, Converted))
  1000. Invalid = true;
  1001. }
  1002. } else if (NonTypeTemplateParmDecl *NTTP
  1003. = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
  1004. // Check non-type template parameters.
  1005. // Instantiate the type of the non-type template parameter with
  1006. // the template arguments we've seen thus far.
  1007. QualType NTTPType = NTTP->getType();
  1008. if (NTTPType->isDependentType()) {
  1009. // Instantiate the type of the non-type template parameter.
  1010. InstantiatingTemplate Inst(*this, TemplateLoc,
  1011. Template, Converted.getFlatArgumentList(),
  1012. Converted.flatSize(),
  1013. SourceRange(TemplateLoc, RAngleLoc));
  1014. TemplateArgumentList TemplateArgs(Context, Converted,
  1015. /*CopyArgs=*/false,
  1016. /*FlattenArgs=*/false);
  1017. NTTPType = InstantiateType(NTTPType, TemplateArgs,
  1018. NTTP->getLocation(),
  1019. NTTP->getDeclName());
  1020. // If that worked, check the non-type template parameter type
  1021. // for validity.
  1022. if (!NTTPType.isNull())
  1023. NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
  1024. NTTP->getLocation());
  1025. if (NTTPType.isNull()) {
  1026. Invalid = true;
  1027. break;
  1028. }
  1029. }
  1030. switch (Arg.getKind()) {
  1031. case TemplateArgument::Null:
  1032. assert(false && "Should never see a NULL template argument here");
  1033. break;
  1034. case TemplateArgument::Expression: {
  1035. Expr *E = Arg.getAsExpr();
  1036. TemplateArgument Result;
  1037. if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
  1038. Invalid = true;
  1039. else
  1040. Converted.push_back(Result);
  1041. break;
  1042. }
  1043. case TemplateArgument::Declaration:
  1044. case TemplateArgument::Integral:
  1045. // We've already checked this template argument, so just copy
  1046. // it to the list of converted arguments.
  1047. Converted.push_back(Arg);
  1048. break;
  1049. case TemplateArgument::Type:
  1050. // We have a non-type template parameter but the template
  1051. // argument is a type.
  1052. // C++ [temp.arg]p2:
  1053. // In a template-argument, an ambiguity between a type-id and
  1054. // an expression is resolved to a type-id, regardless of the
  1055. // form of the corresponding template-parameter.
  1056. //
  1057. // We warn specifically about this case, since it can be rather
  1058. // confusing for users.
  1059. if (Arg.getAsType()->isFunctionType())
  1060. Diag(Arg.getLocation(), diag::err_template_arg_nontype_ambig)
  1061. << Arg.getAsType();
  1062. else
  1063. Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr);
  1064. Diag((*Param)->getLocation(), diag::note_template_param_here);
  1065. Invalid = true;
  1066. }
  1067. } else {
  1068. // Check template template parameters.
  1069. TemplateTemplateParmDecl *TempParm
  1070. = cast<TemplateTemplateParmDecl>(*Param);
  1071. switch (Arg.getKind()) {
  1072. case TemplateArgument::Null:
  1073. assert(false && "Should never see a NULL template argument here");
  1074. break;
  1075. case TemplateArgument::Expression: {
  1076. Expr *ArgExpr = Arg.getAsExpr();
  1077. if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
  1078. isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
  1079. if (CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
  1080. Invalid = true;
  1081. // Add the converted template argument.
  1082. Decl *D
  1083. = Context.getCanonicalDecl(cast<DeclRefExpr>(ArgExpr)->getDecl());
  1084. Converted.push_back(TemplateArgument(Arg.getLocation(), D));
  1085. continue;
  1086. }
  1087. }
  1088. // fall through
  1089. case TemplateArgument::Type: {
  1090. // We have a template template parameter but the template
  1091. // argument does not refer to a template.
  1092. Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
  1093. Invalid = true;
  1094. break;
  1095. }
  1096. case TemplateArgument::Declaration:
  1097. // We've already checked this template argument, so just copy
  1098. // it to the list of converted arguments.
  1099. Converted.push_back(Arg);
  1100. break;
  1101. case TemplateArgument::Integral:
  1102. assert(false && "Integral argument with template template parameter");
  1103. break;
  1104. }
  1105. }
  1106. }
  1107. return Invalid;
  1108. }
  1109. /// \brief Check a template argument against its corresponding
  1110. /// template type parameter.
  1111. ///
  1112. /// This routine implements the semantics of C++ [temp.arg.type]. It
  1113. /// returns true if an error occurred, and false otherwise.
  1114. bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
  1115. QualType Arg, SourceLocation ArgLoc) {
  1116. // C++ [temp.arg.type]p2:
  1117. // A local type, a type with no linkage, an unnamed type or a type
  1118. // compounded from any of these types shall not be used as a
  1119. // template-argument for a template type-parameter.
  1120. //
  1121. // FIXME: Perform the recursive and no-linkage type checks.
  1122. const TagType *Tag = 0;
  1123. if (const EnumType *EnumT = Arg->getAsEnumType())
  1124. Tag = EnumT;
  1125. else if (const RecordType *RecordT = Arg->getAsRecordType())
  1126. Tag = RecordT;
  1127. if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
  1128. return Diag(ArgLoc, diag::err_template_arg_local_type)
  1129. << QualType(Tag, 0);
  1130. else if (Tag && !Tag->getDecl()->getDeclName() &&
  1131. !Tag->getDecl()->getTypedefForAnonDecl()) {
  1132. Diag(ArgLoc, diag::err_template_arg_unnamed_type);
  1133. Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
  1134. return true;
  1135. }
  1136. return false;
  1137. }
  1138. /// \brief Checks whether the given template argument is the address
  1139. /// of an object or function according to C++ [temp.arg.nontype]p1.
  1140. bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg,
  1141. NamedDecl *&Entity) {
  1142. bool Invalid = false;
  1143. // See through any implicit casts we added to fix the type.
  1144. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
  1145. Arg = Cast->getSubExpr();
  1146. // C++0x allows nullptr, and there's no further checking to be done for that.
  1147. if (Arg->getType()->isNullPtrType())
  1148. return false;
  1149. // C++ [temp.arg.nontype]p1:
  1150. //
  1151. // A template-argument for a non-type, non-template
  1152. // template-parameter shall be one of: [...]
  1153. //
  1154. // -- the address of an object or function with external
  1155. // linkage, including function templates and function
  1156. // template-ids but excluding non-static class members,
  1157. // expressed as & id-expression where the & is optional if
  1158. // the name refers to a function or array, or if the
  1159. // corresponding template-parameter is a reference; or
  1160. DeclRefExpr *DRE = 0;
  1161. // Ignore (and complain about) any excess parentheses.
  1162. while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
  1163. if (!Invalid) {
  1164. Diag(Arg->getSourceRange().getBegin(),
  1165. diag::err_template_arg_extra_parens)
  1166. << Arg->getSourceRange();
  1167. Invalid = true;
  1168. }
  1169. Arg = Parens->getSubExpr();
  1170. }
  1171. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
  1172. if (UnOp->getOpcode() == UnaryOperator::AddrOf)
  1173. DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
  1174. } else
  1175. DRE = dyn_cast<DeclRefExpr>(Arg);
  1176. if (!DRE || !isa<ValueDecl>(DRE->getDecl()))
  1177. return Diag(Arg->getSourceRange().getBegin(),
  1178. diag::err_template_arg_not_object_or_func_form)
  1179. << Arg->getSourceRange();
  1180. // Cannot refer to non-static data members
  1181. if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl()))
  1182. return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
  1183. << Field << Arg->getSourceRange();
  1184. // Cannot refer to non-static member functions
  1185. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
  1186. if (!Method->isStatic())
  1187. return Diag(Arg->getSourceRange().getBegin(),
  1188. diag::err_template_arg_method)
  1189. << Method << Arg->getSourceRange();
  1190. // Functions must have external linkage.
  1191. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
  1192. if (Func->getStorageClass() == FunctionDecl::Static) {
  1193. Diag(Arg->getSourceRange().getBegin(),
  1194. diag::err_template_arg_function_not_extern)
  1195. << Func << Arg->getSourceRange();
  1196. Diag(Func->getLocation(), diag::note_template_arg_internal_object)
  1197. << true;
  1198. return true;
  1199. }
  1200. // Okay: we've named a function with external linkage.
  1201. Entity = Func;
  1202. return Invalid;
  1203. }
  1204. if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
  1205. if (!Var->hasGlobalStorage()) {
  1206. Diag(Arg->getSourceRange().getBegin(),
  1207. diag::err_template_arg_object_not_extern)
  1208. << Var << Arg->getSourceRange();
  1209. Diag(Var->getLocation(), diag::note_template_arg_internal_object)
  1210. << true;
  1211. return true;
  1212. }
  1213. // Okay: we've named an object with external linkage
  1214. Entity = Var;
  1215. return Invalid;
  1216. }
  1217. // We found something else, but we don't know specifically what it is.
  1218. Diag(Arg->getSourceRange().getBegin(),
  1219. diag::err_template_arg_not_object_or_func)
  1220. << Arg->getSourceRange();
  1221. Diag(DRE->getDecl()->getLocation(),
  1222. diag::note_template_arg_refers_here);
  1223. return true;
  1224. }
  1225. /// \brief Checks whether the given template argument is a pointer to
  1226. /// member constant according to C++ [temp.arg.nontype]p1.
  1227. bool
  1228. Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, NamedDecl *&Member) {
  1229. bool Invalid = false;
  1230. // See through any implicit casts we added to fix the type.
  1231. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
  1232. Arg = Cast->getSubExpr();
  1233. // C++0x allows nullptr, and there's no further checking to be done for that.
  1234. if (Arg->getType()->isNullPtrType())
  1235. return false;
  1236. // C++ [temp.arg.nontype]p1:
  1237. //
  1238. // A template-argument for a non-type, non-template
  1239. // template-parameter shall be one of: [...]
  1240. //
  1241. // -- a pointer to member expressed as described in 5.3.1.
  1242. QualifiedDeclRefExpr *DRE = 0;
  1243. // Ignore (and complain about) any excess parentheses.
  1244. while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
  1245. if (!Invalid) {
  1246. Diag(Arg->getSourceRange().getBegin(),
  1247. diag::err_template_arg_extra_parens)
  1248. << Arg->getSourceRange();
  1249. Invalid = true;
  1250. }
  1251. Arg = Parens->getSubExpr();
  1252. }
  1253. if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg))
  1254. if (UnOp->getOpcode() == UnaryOperator::AddrOf)
  1255. DRE = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr());
  1256. if (!DRE)
  1257. return Diag(Arg->getSourceRange().getBegin(),
  1258. diag::err_template_arg_not_pointer_to_member_form)
  1259. << Arg->getSourceRange();
  1260. if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
  1261. assert((isa<FieldDecl>(DRE->getDecl()) ||
  1262. !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
  1263. "Only non-static member pointers can make it here");
  1264. // Okay: this is the address of a non-static member, and therefore
  1265. // a member pointer constant.
  1266. Member = DRE->getDecl();
  1267. return Invalid;
  1268. }
  1269. // We found something else, but we don't know specifically what it is.
  1270. Diag(Arg->getSourceRange().getBegin(),
  1271. diag::err_template_arg_not_pointer_to_member_form)
  1272. << Arg->getSourceRange();
  1273. Diag(DRE->getDecl()->getLocation(),
  1274. diag::note_template_arg_refers_here);
  1275. return true;
  1276. }
  1277. /// \brief Check a template argument against its corresponding
  1278. /// non-type template parameter.
  1279. ///
  1280. /// This routine implements the semantics of C++ [temp.arg.nontype].
  1281. /// It returns true if an error occurred, and false otherwise. \p
  1282. /// InstantiatedParamType is the type of the non-type template
  1283. /// parameter after it has been instantiated.
  1284. ///
  1285. /// If no error was detected, Converted receives the converted template argument.
  1286. bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
  1287. QualType InstantiatedParamType, Expr *&Arg,
  1288. TemplateArgument &Converted) {
  1289. SourceLocation StartLoc = Arg->getSourceRange().getBegin();
  1290. // If either the parameter has a dependent type or the argument is
  1291. // type-dependent, there's nothing we can check now.
  1292. // FIXME: Add template argument to Converted!
  1293. if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
  1294. // FIXME: Produce a cloned, canonical expression?
  1295. Converted = TemplateArgument(Arg);
  1296. return false;
  1297. }
  1298. // C++ [temp.arg.nontype]p5:
  1299. // The following conversions are performed on each expression used
  1300. // as a non-type template-argument. If a non-type
  1301. // template-argument cannot be converted to the type of the
  1302. // corresponding template-parameter then the program is
  1303. // ill-formed.
  1304. //
  1305. // -- for a non-type template-parameter of integral or
  1306. // enumeration type, integral promotions (4.5) and integral
  1307. // conversions (4.7) are applied.
  1308. QualType ParamType = InstantiatedParamType;
  1309. QualType ArgType = Arg->getType();
  1310. if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
  1311. // C++ [temp.arg.nontype]p1:
  1312. // A template-argument for a non-type, non-template
  1313. // template-parameter shall be one of:
  1314. //
  1315. // -- an integral constant-expression of integral or enumeration
  1316. // type; or
  1317. // -- the name of a non-type template-parameter; or
  1318. SourceLocation NonConstantLoc;
  1319. llvm::APSInt Value;
  1320. if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
  1321. Diag(Arg->getSourceRange().getBegin(),
  1322. diag::err_template_arg_not_integral_or_enumeral)
  1323. << ArgType << Arg->getSourceRange();
  1324. Diag(Param->getLocation(), diag::note_template_param_here);
  1325. return true;
  1326. } else if (!Arg->isValueDependent() &&
  1327. !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
  1328. Diag(NonConstantLoc, diag::err_template_arg_not_ice)
  1329. << ArgType << Arg->getSourceRange();
  1330. return true;
  1331. }
  1332. // FIXME: We need some way to more easily get the unqualified form
  1333. // of the types without going all the way to the
  1334. // canonical type.
  1335. if (Context.getCanonicalType(ParamType).getCVRQualifiers())
  1336. ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
  1337. if (Context.getCanonicalType(ArgType).getCVRQualifiers())
  1338. ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
  1339. // Try to convert the argument to the parameter's type.
  1340. if (ParamType == ArgType) {
  1341. // Okay: no conversion necessary
  1342. } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
  1343. !ParamType->isEnumeralType()) {
  1344. // This is an integral promotion or conversion.
  1345. ImpCastExprToType(Arg, ParamType);
  1346. } else {
  1347. // We can't perform this conversion.
  1348. Diag(Arg->getSourceRange().getBegin(),
  1349. diag::err_template_arg_not_convertible)
  1350. << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
  1351. Diag(Param->getLocation(), diag::note_template_param_here);
  1352. return true;
  1353. }
  1354. QualType IntegerType = Context.getCanonicalType(ParamType);
  1355. if (const EnumType *Enum = IntegerType->getAsEnumType())
  1356. IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
  1357. if (!Arg->isValueDependent()) {
  1358. // Check that an unsigned parameter does not receive a negative
  1359. // value.
  1360. if (IntegerType->isUnsignedIntegerType()
  1361. && (Value.isSigned() && Value.isNegative())) {
  1362. Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative)
  1363. << Value.toString(10) << Param->getType()
  1364. << Arg->getSourceRange();
  1365. Diag(Param->getLocation(), diag::note_template_param_here);
  1366. return true;
  1367. }
  1368. // Check that we don't overflow the template parameter type.
  1369. unsigned AllowedBits = Context.getTypeSize(IntegerType);
  1370. if (Value.getActiveBits() > AllowedBits) {
  1371. Diag(Arg->getSourceRange().getBegin(),
  1372. diag::err_template_arg_too_large)
  1373. << Value.toString(10) << Param->getType()
  1374. << Arg->getSourceRange();
  1375. Diag(Param->getLocation(), diag::note_template_param_here);
  1376. return true;
  1377. }
  1378. if (Value.getBitWidth() != AllowedBits)
  1379. Value.extOrTrunc(AllowedBits);
  1380. Value.setIsSigned(IntegerType->isSignedIntegerType());
  1381. }
  1382. // Add the value of this argument to the list of converted
  1383. // arguments. We use the bitwidth and signedness of the template
  1384. // parameter.
  1385. if (Arg->isValueDependent()) {
  1386. // The argument is value-dependent. Create a new
  1387. // TemplateArgument with the converted expression.
  1388. Converted = TemplateArgument(Arg);
  1389. return false;
  1390. }
  1391. Converted = TemplateArgument(StartLoc, Value,
  1392. ParamType->isEnumeralType() ? ParamType
  1393. : IntegerType);
  1394. return false;
  1395. }
  1396. // Handle pointer-to-function, reference-to-function, and
  1397. // pointer-to-member-function all in (roughly) the same way.
  1398. if (// -- For a non-type template-parameter of type pointer to
  1399. // function, only the function-to-pointer conversion (4.3) is
  1400. // applied. If the template-argument represents a set of
  1401. // overloaded functions (or a pointer to such), the matching
  1402. // function is selected from the set (13.4).
  1403. // In C++0x, any std::nullptr_t value can be converted.
  1404. (ParamType->isPointerType() &&
  1405. ParamType->getAsPointerType()->getPointeeType()->isFunctionType()) ||
  1406. // -- For a non-type template-parameter of type reference to
  1407. // function, no conversions apply. If the template-argument
  1408. // represents a set of overloaded functions, the matching
  1409. // function is selected from the set (13.4).
  1410. (ParamType->isReferenceType() &&
  1411. ParamType->getAsReferenceType()->getPointeeType()->isFunctionType()) ||
  1412. // -- For a non-type template-parameter of type pointer to
  1413. // member function, no conversions apply. If the
  1414. // template-argument represents a set of overloaded member
  1415. // functions, the matching member function is selected from
  1416. // the set (13.4).
  1417. // Again, C++0x allows a std::nullptr_t value.
  1418. (ParamType->isMemberPointerType() &&
  1419. ParamType->getAsMemberPointerType()->getPointeeType()
  1420. ->isFunctionType())) {
  1421. if (Context.hasSameUnqualifiedType(ArgType,
  1422. ParamType.getNonReferenceType())) {
  1423. // We don't have to do anything: the types already match.
  1424. } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() ||
  1425. ParamType->isMemberPointerType())) {
  1426. ArgType = ParamType;
  1427. ImpCastExprToType(Arg, ParamType);
  1428. } else if (ArgType->isFunctionType() && ParamType->isPointerType()) {
  1429. ArgType = Context.getPointerType(ArgType);
  1430. ImpCastExprToType(Arg, ArgType);
  1431. } else if (FunctionDecl *Fn
  1432. = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
  1433. if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
  1434. return true;
  1435. FixOverloadedFunctionReference(Arg, Fn);
  1436. ArgType = Arg->getType();
  1437. if (ArgType->isFunctionType() && ParamType->isPointerType()) {
  1438. ArgType = Context.getPointerType(Arg->getType());
  1439. ImpCastExprToType(Arg, ArgType);
  1440. }
  1441. }
  1442. if (!Context.hasSameUnqualifiedType(ArgType,
  1443. ParamType.getNonReferenceType())) {
  1444. // We can't perform this conversion.
  1445. Diag(Arg->getSourceRange().getBegin(),
  1446. diag::err_template_arg_not_convertible)
  1447. << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
  1448. Diag(Param->getLocation(), diag::note_template_param_here);
  1449. return true;
  1450. }
  1451. if (ParamType->isMemberPointerType()) {
  1452. NamedDecl *Member = 0;
  1453. if (CheckTemplateArgumentPointerToMember(Arg, Member))
  1454. return true;
  1455. Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
  1456. Converted = TemplateArgument(StartLoc, Member);
  1457. return false;
  1458. }
  1459. NamedDecl *Entity = 0;
  1460. if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
  1461. return true;
  1462. Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
  1463. Converted = TemplateArgument(StartLoc, Entity);
  1464. return false;
  1465. }
  1466. if (ParamType->isPointerType()) {
  1467. // -- for a non-type template-parameter of type pointer to
  1468. // object, qualification conversions (4.4) and the
  1469. // array-to-pointer conversion (4.2) are applied.
  1470. // C++0x also allows a value of std::nullptr_t.
  1471. assert(ParamType->getAsPointerType()->getPointeeType()->isObjectType() &&
  1472. "Only object pointers allowed here");
  1473. if (ArgType->isNullPtrType()) {
  1474. ArgType = ParamType;
  1475. ImpCastExprToType(Arg, ParamType);
  1476. } else if (ArgType->isArrayType()) {
  1477. ArgType = Context.getArrayDecayedType(ArgType);
  1478. ImpCastExprToType(Arg, ArgType);
  1479. }
  1480. if (IsQualificationConversion(ArgType, ParamType)) {
  1481. ArgType = ParamType;
  1482. ImpCastExprToType(Arg, ParamType);
  1483. }
  1484. if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) {
  1485. // We can't perform this conversion.
  1486. Diag(Arg->getSourceRange().getBegin(),
  1487. diag::err_template_arg_not_convertible)
  1488. << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
  1489. Diag(Param->getLocation(), diag::note_template_param_here);
  1490. return true;
  1491. }
  1492. NamedDecl *Entity = 0;
  1493. if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
  1494. return true;
  1495. Entity = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Entity));
  1496. Converted = TemplateArgument(StartLoc, Entity);
  1497. return false;
  1498. }
  1499. if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
  1500. // -- For a non-type template-parameter of type reference to
  1501. // object, no conversions apply. The type referred to by the
  1502. // reference may be more cv-qualified than the (otherwise
  1503. // identical) type of the template-argument. The
  1504. // template-parameter is bound directly to the
  1505. // template-argument, which must be an lvalue.
  1506. assert(ParamRefType->getPointeeType()->isObjectType() &&
  1507. "Only object references allowed here");
  1508. if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
  1509. Diag(Arg->getSourceRange().getBegin(),
  1510. diag::err_template_arg_no_ref_bind)
  1511. << InstantiatedParamType << Arg->getType()
  1512. << Arg->getSourceRange();
  1513. Diag(Param->getLocation(), diag::note_template_param_here);
  1514. return true;
  1515. }
  1516. unsigned ParamQuals
  1517. = Context.getCanonicalType(ParamType).getCVRQualifiers();
  1518. unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
  1519. if ((ParamQuals | ArgQuals) != ParamQuals) {
  1520. Diag(Arg->getSourceRange().getBegin(),
  1521. diag::err_template_arg_ref_bind_ignores_quals)
  1522. << InstantiatedParamType << Arg->getType()
  1523. << Arg->getSourceRange();
  1524. Diag(Param->getLocation(), diag::note_template_param_here);
  1525. return true;
  1526. }
  1527. NamedDecl *Entity = 0;
  1528. if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity))
  1529. return true;
  1530. Entity = cast<NamedDecl>(Context.getCanonicalDecl(Entity));
  1531. Converted = TemplateArgument(StartLoc, Entity);
  1532. return false;
  1533. }
  1534. // -- For a non-type template-parameter of type pointer to data
  1535. // member, qualification conversions (4.4) are applied.
  1536. // C++0x allows std::nullptr_t values.
  1537. assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
  1538. if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
  1539. // Types match exactly: nothing more to do here.
  1540. } else if (ArgType->isNullPtrType()) {
  1541. ImpCastExprToType(Arg, ParamType);
  1542. } else if (IsQualificationConversion(ArgType, ParamType)) {
  1543. ImpCastExprToType(Arg, ParamType);
  1544. } else {
  1545. // We can't perform this conversion.
  1546. Diag(Arg->getSourceRange().getBegin(),
  1547. diag::err_template_arg_not_convertible)
  1548. << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
  1549. Diag(Param->getLocation(), diag::note_template_param_here);
  1550. return true;
  1551. }
  1552. NamedDecl *Member = 0;
  1553. if (CheckTemplateArgumentPointerToMember(Arg, Member))
  1554. return true;
  1555. Member = cast_or_null<NamedDecl>(Context.getCanonicalDecl(Member));
  1556. Converted = TemplateArgument(StartLoc, Member);
  1557. return false;
  1558. }
  1559. /// \brief Check a template argument against its corresponding
  1560. /// template template parameter.
  1561. ///
  1562. /// This routine implements the semantics of C++ [temp.arg.template].
  1563. /// It returns true if an error occurred, and false otherwise.
  1564. bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
  1565. DeclRefExpr *Arg) {
  1566. assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
  1567. TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
  1568. // C++ [temp.arg.template]p1:
  1569. // A template-argument for a template template-parameter shall be
  1570. // the name of a class template, expressed as id-expression. Only
  1571. // primary class templates are considered when matching the
  1572. // template template argument with the corresponding parameter;
  1573. // partial specializations are not considered even if their
  1574. // parameter lists match that of the template template parameter.
  1575. //
  1576. // Note that we also allow template template parameters here, which
  1577. // will happen when we are dealing with, e.g., class template
  1578. // partial specializations.
  1579. if (!isa<ClassTemplateDecl>(Template) &&
  1580. !isa<TemplateTemplateParmDecl>(Template)) {
  1581. assert(isa<FunctionTemplateDecl>(Template) &&
  1582. "Only function templates are possible here");
  1583. Diag(Arg->getSourceRange().getBegin(),
  1584. diag::note_template_arg_refers_here_func)
  1585. << Template;
  1586. }
  1587. return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
  1588. Param->getTemplateParameters(),
  1589. true, true,
  1590. Arg->getSourceRange().getBegin());
  1591. }
  1592. /// \brief Determine whether the given template parameter lists are
  1593. /// equivalent.
  1594. ///
  1595. /// \param New The new template parameter list, typically written in the
  1596. /// source code as part of a new template declaration.
  1597. ///
  1598. /// \param Old The old template parameter list, typically found via
  1599. /// name lookup of the template declared with this template parameter
  1600. /// list.
  1601. ///
  1602. /// \param Complain If true, this routine will produce a diagnostic if
  1603. /// the template parameter lists are not equivalent.
  1604. ///
  1605. /// \param IsTemplateTemplateParm If true, this routine is being
  1606. /// called to compare the template parameter lists of a template
  1607. /// template parameter.
  1608. ///
  1609. /// \param TemplateArgLoc If this source location is valid, then we
  1610. /// are actually checking the template parameter list of a template
  1611. /// argument (New) against the template parameter list of its
  1612. /// corresponding template template parameter (Old). We produce
  1613. /// slightly different diagnostics in this scenario.
  1614. ///
  1615. /// \returns True if the template parameter lists are equal, false
  1616. /// otherwise.
  1617. bool
  1618. Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
  1619. TemplateParameterList *Old,
  1620. bool Complain,
  1621. bool IsTemplateTemplateParm,
  1622. SourceLocation TemplateArgLoc) {
  1623. if (Old->size() != New->size()) {
  1624. if (Complain) {
  1625. unsigned NextDiag = diag::err_template_param_list_different_arity;
  1626. if (TemplateArgLoc.isValid()) {
  1627. Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
  1628. NextDiag = diag::note_template_param_list_different_arity;
  1629. }
  1630. Diag(New->getTemplateLoc(), NextDiag)
  1631. << (New->size() > Old->size())
  1632. << IsTemplateTemplateParm
  1633. << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
  1634. Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
  1635. << IsTemplateTemplateParm
  1636. << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
  1637. }
  1638. return false;
  1639. }
  1640. for (TemplateParameterList::iterator OldParm = Old->begin(),
  1641. OldParmEnd = Old->end(), NewParm = New->begin();
  1642. OldParm != OldParmEnd; ++OldParm, ++NewParm) {
  1643. if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
  1644. unsigned NextDiag = diag::err_template_param_different_kind;
  1645. if (TemplateArgLoc.isValid()) {
  1646. Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
  1647. NextDiag = diag::note_template_param_different_kind;
  1648. }
  1649. Diag((*NewParm)->getLocation(), NextDiag)
  1650. << IsTemplateTemplateParm;
  1651. Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
  1652. << IsTemplateTemplateParm;
  1653. return false;
  1654. }
  1655. if (isa<TemplateTypeParmDecl>(*OldParm)) {
  1656. // Okay; all template type parameters are equivalent (since we
  1657. // know we're at the same index).
  1658. #if 0
  1659. // FIXME: Enable this code in debug mode *after* we properly go through
  1660. // and "instantiate" the template parameter lists of template template
  1661. // parameters. It's only after this instantiation that (1) any dependent
  1662. // types within the template parameter list of the template template
  1663. // parameter can be checked, and (2) the template type parameter depths
  1664. // will match up.
  1665. QualType OldParmType
  1666. = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
  1667. QualType NewParmType
  1668. = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
  1669. assert(Context.getCanonicalType(OldParmType) ==
  1670. Context.getCanonicalType(NewParmType) &&
  1671. "type parameter mismatch?");
  1672. #endif
  1673. } else if (NonTypeTemplateParmDecl *OldNTTP
  1674. = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
  1675. // The types of non-type template parameters must agree.
  1676. NonTypeTemplateParmDecl *NewNTTP
  1677. = cast<NonTypeTemplateParmDecl>(*NewParm);
  1678. if (Context.getCanonicalType(OldNTTP->getType()) !=
  1679. Context.getCanonicalType(NewNTTP->getType())) {
  1680. if (Complain) {
  1681. unsigned NextDiag = diag::err_template_nontype_parm_different_type;
  1682. if (TemplateArgLoc.isValid()) {
  1683. Diag(TemplateArgLoc,
  1684. diag::err_template_arg_template_params_mismatch);
  1685. NextDiag = diag::note_template_nontype_parm_different_type;
  1686. }
  1687. Diag(NewNTTP->getLocation(), NextDiag)
  1688. << NewNTTP->getType()
  1689. << IsTemplateTemplateParm;
  1690. Diag(OldNTTP->getLocation(),
  1691. diag::note_template_nontype_parm_prev_declaration)
  1692. << OldNTTP->getType();
  1693. }
  1694. return false;
  1695. }
  1696. } else {
  1697. // The template parameter lists of template template
  1698. // parameters must agree.
  1699. // FIXME: Could we perform a faster "type" comparison here?
  1700. assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
  1701. "Only template template parameters handled here");
  1702. TemplateTemplateParmDecl *OldTTP
  1703. = cast<TemplateTemplateParmDecl>(*OldParm);
  1704. TemplateTemplateParmDecl *NewTTP
  1705. = cast<TemplateTemplateParmDecl>(*NewParm);
  1706. if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
  1707. OldTTP->getTemplateParameters(),
  1708. Complain,
  1709. /*IsTemplateTemplateParm=*/true,
  1710. TemplateArgLoc))
  1711. return false;
  1712. }
  1713. }
  1714. return true;
  1715. }
  1716. /// \brief Check whether a template can be declared within this scope.
  1717. ///
  1718. /// If the template declaration is valid in this scope, returns
  1719. /// false. Otherwise, issues a diagnostic and returns true.
  1720. bool
  1721. Sema::CheckTemplateDeclScope(Scope *S,
  1722. MultiTemplateParamsArg &TemplateParameterLists) {
  1723. assert(TemplateParameterLists.size() > 0 && "Not a template");
  1724. // Find the nearest enclosing declaration scope.
  1725. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  1726. (S->getFlags() & Scope::TemplateParamScope) != 0)
  1727. S = S->getParent();
  1728. TemplateParameterList *TemplateParams =
  1729. static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
  1730. SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
  1731. SourceRange TemplateRange
  1732. = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
  1733. // C++ [temp]p2:
  1734. // A template-declaration can appear only as a namespace scope or
  1735. // class scope declaration.
  1736. DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
  1737. while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
  1738. if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
  1739. return Diag(TemplateLoc, diag::err_template_linkage)
  1740. << TemplateRange;
  1741. Ctx = Ctx->getParent();
  1742. }
  1743. if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
  1744. return false;
  1745. return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
  1746. << TemplateRange;
  1747. }
  1748. /// \brief Check whether a class template specialization or explicit
  1749. /// instantiation in the current context is well-formed.
  1750. ///
  1751. /// This routine determines whether a class template specialization or
  1752. /// explicit instantiation can be declared in the current context
  1753. /// (C++ [temp.expl.spec]p2, C++0x [temp.explicit]p2) and emits
  1754. /// appropriate diagnostics if there was an error. It returns true if
  1755. // there was an error that we cannot recover from, and false otherwise.
  1756. bool
  1757. Sema::CheckClassTemplateSpecializationScope(ClassTemplateDecl *ClassTemplate,
  1758. ClassTemplateSpecializationDecl *PrevDecl,
  1759. SourceLocation TemplateNameLoc,
  1760. SourceRange ScopeSpecifierRange,
  1761. bool PartialSpecialization,
  1762. bool ExplicitInstantiation) {
  1763. // C++ [temp.expl.spec]p2:
  1764. // An explicit specialization shall be declared in the namespace
  1765. // of which the template is a member, or, for member templates, in
  1766. // the namespace of which the enclosing class or enclosing class
  1767. // template is a member. An explicit specialization of a member
  1768. // function, member class or static data member of a class
  1769. // template shall be declared in the namespace of which the class
  1770. // template is a member. Such a declaration may also be a
  1771. // definition. If the declaration is not a definition, the
  1772. // specialization may be defined later in the name- space in which
  1773. // the explicit specialization was declared, or in a namespace
  1774. // that encloses the one in which the explicit specialization was
  1775. // declared.
  1776. if (CurContext->getLookupContext()->isFunctionOrMethod()) {
  1777. int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
  1778. Diag(TemplateNameLoc, diag::err_template_spec_decl_function_scope)
  1779. << Kind << ClassTemplate;
  1780. return true;
  1781. }
  1782. DeclContext *DC = CurContext->getEnclosingNamespaceContext();
  1783. DeclContext *TemplateContext
  1784. = ClassTemplate->getDeclContext()->getEnclosingNamespaceContext();
  1785. if ((!PrevDecl || PrevDecl->getSpecializationKind() == TSK_Undeclared) &&
  1786. !ExplicitInstantiation) {
  1787. // There is no prior declaration of this entity, so this
  1788. // specialization must be in the same context as the template
  1789. // itself.
  1790. if (DC != TemplateContext) {
  1791. if (isa<TranslationUnitDecl>(TemplateContext))
  1792. Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope_global)
  1793. << PartialSpecialization
  1794. << ClassTemplate << ScopeSpecifierRange;
  1795. else if (isa<NamespaceDecl>(TemplateContext))
  1796. Diag(TemplateNameLoc, diag::err_template_spec_decl_out_of_scope)
  1797. << PartialSpecialization << ClassTemplate
  1798. << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
  1799. Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
  1800. }
  1801. return false;
  1802. }
  1803. // We have a previous declaration of this entity. Make sure that
  1804. // this redeclaration (or definition) occurs in an enclosing namespace.
  1805. if (!CurContext->Encloses(TemplateContext)) {
  1806. // FIXME: In C++98, we would like to turn these errors into warnings,
  1807. // dependent on a -Wc++0x flag.
  1808. bool SuppressedDiag = false;
  1809. int Kind = ExplicitInstantiation? 2 : PartialSpecialization? 1 : 0;
  1810. if (isa<TranslationUnitDecl>(TemplateContext)) {
  1811. if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
  1812. Diag(TemplateNameLoc, diag::err_template_spec_redecl_global_scope)
  1813. << Kind << ClassTemplate << ScopeSpecifierRange;
  1814. else
  1815. SuppressedDiag = true;
  1816. } else if (isa<NamespaceDecl>(TemplateContext)) {
  1817. if (!ExplicitInstantiation || getLangOptions().CPlusPlus0x)
  1818. Diag(TemplateNameLoc, diag::err_template_spec_redecl_out_of_scope)
  1819. << Kind << ClassTemplate
  1820. << cast<NamedDecl>(TemplateContext) << ScopeSpecifierRange;
  1821. else
  1822. SuppressedDiag = true;
  1823. }
  1824. if (!SuppressedDiag)
  1825. Diag(ClassTemplate->getLocation(), diag::note_template_decl_here);
  1826. }
  1827. return false;
  1828. }
  1829. /// \brief Check the non-type template arguments of a class template
  1830. /// partial specialization according to C++ [temp.class.spec]p9.
  1831. ///
  1832. /// \param TemplateParams the template parameters of the primary class
  1833. /// template.
  1834. ///
  1835. /// \param TemplateArg the template arguments of the class template
  1836. /// partial specialization.
  1837. ///
  1838. /// \param MirrorsPrimaryTemplate will be set true if the class
  1839. /// template partial specialization arguments are identical to the
  1840. /// implicit template arguments of the primary template. This is not
  1841. /// necessarily an error (C++0x), and it is left to the caller to diagnose
  1842. /// this condition when it is an error.
  1843. ///
  1844. /// \returns true if there was an error, false otherwise.
  1845. bool Sema::CheckClassTemplatePartialSpecializationArgs(
  1846. TemplateParameterList *TemplateParams,
  1847. const TemplateArgument *TemplateArgs,
  1848. bool &MirrorsPrimaryTemplate) {
  1849. // FIXME: the interface to this function will have to change to
  1850. // accommodate variadic templates.
  1851. MirrorsPrimaryTemplate = true;
  1852. for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
  1853. // Determine whether the template argument list of the partial
  1854. // specialization is identical to the implicit argument list of
  1855. // the primary template. The caller may need to diagnostic this as
  1856. // an error per C++ [temp.class.spec]p9b3.
  1857. if (MirrorsPrimaryTemplate) {
  1858. if (TemplateTypeParmDecl *TTP
  1859. = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
  1860. if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
  1861. Context.getCanonicalType(TemplateArgs[I].getAsType()))
  1862. MirrorsPrimaryTemplate = false;
  1863. } else if (TemplateTemplateParmDecl *TTP
  1864. = dyn_cast<TemplateTemplateParmDecl>(
  1865. TemplateParams->getParam(I))) {
  1866. // FIXME: We should settle on either Declaration storage or
  1867. // Expression storage for template template parameters.
  1868. TemplateTemplateParmDecl *ArgDecl
  1869. = dyn_cast_or_null<TemplateTemplateParmDecl>(
  1870. TemplateArgs[I].getAsDecl());
  1871. if (!ArgDecl)
  1872. if (DeclRefExpr *DRE
  1873. = dyn_cast_or_null<DeclRefExpr>(TemplateArgs[I].getAsExpr()))
  1874. ArgDecl = dyn_cast<TemplateTemplateParmDecl>(DRE->getDecl());
  1875. if (!ArgDecl ||
  1876. ArgDecl->getIndex() != TTP->getIndex() ||
  1877. ArgDecl->getDepth() != TTP->getDepth())
  1878. MirrorsPrimaryTemplate = false;
  1879. }
  1880. }
  1881. NonTypeTemplateParmDecl *Param
  1882. = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
  1883. if (!Param) {
  1884. continue;
  1885. }
  1886. Expr *ArgExpr = TemplateArgs[I].getAsExpr();
  1887. if (!ArgExpr) {
  1888. MirrorsPrimaryTemplate = false;
  1889. continue;
  1890. }
  1891. // C++ [temp.class.spec]p8:
  1892. // A non-type argument is non-specialized if it is the name of a
  1893. // non-type parameter. All other non-type arguments are
  1894. // specialized.
  1895. //
  1896. // Below, we check the two conditions that only apply to
  1897. // specialized non-type arguments, so skip any non-specialized
  1898. // arguments.
  1899. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
  1900. if (NonTypeTemplateParmDecl *NTTP
  1901. = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
  1902. if (MirrorsPrimaryTemplate &&
  1903. (Param->getIndex() != NTTP->getIndex() ||
  1904. Param->getDepth() != NTTP->getDepth()))
  1905. MirrorsPrimaryTemplate = false;
  1906. continue;
  1907. }
  1908. // C++ [temp.class.spec]p9:
  1909. // Within the argument list of a class template partial
  1910. // specialization, the following restrictions apply:
  1911. // -- A partially specialized non-type argument expression
  1912. // shall not involve a template parameter of the partial
  1913. // specialization except when the argument expression is a
  1914. // simple identifier.
  1915. if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
  1916. Diag(ArgExpr->getLocStart(),
  1917. diag::err_dependent_non_type_arg_in_partial_spec)
  1918. << ArgExpr->getSourceRange();
  1919. return true;
  1920. }
  1921. // -- The type of a template parameter corresponding to a
  1922. // specialized non-type argument shall not be dependent on a
  1923. // parameter of the specialization.
  1924. if (Param->getType()->isDependentType()) {
  1925. Diag(ArgExpr->getLocStart(),
  1926. diag::err_dependent_typed_non_type_arg_in_partial_spec)
  1927. << Param->getType()
  1928. << ArgExpr->getSourceRange();
  1929. Diag(Param->getLocation(), diag::note_template_param_here);
  1930. return true;
  1931. }
  1932. MirrorsPrimaryTemplate = false;
  1933. }
  1934. return false;
  1935. }
  1936. Sema::DeclResult
  1937. Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagKind TK,
  1938. SourceLocation KWLoc,
  1939. const CXXScopeSpec &SS,
  1940. TemplateTy TemplateD,
  1941. SourceLocation TemplateNameLoc,
  1942. SourceLocation LAngleLoc,
  1943. ASTTemplateArgsPtr TemplateArgsIn,
  1944. SourceLocation *TemplateArgLocs,
  1945. SourceLocation RAngleLoc,
  1946. AttributeList *Attr,
  1947. MultiTemplateParamsArg TemplateParameterLists) {
  1948. // Find the class template we're specializing
  1949. TemplateName Name = TemplateD.getAsVal<TemplateName>();
  1950. ClassTemplateDecl *ClassTemplate
  1951. = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
  1952. bool isPartialSpecialization = false;
  1953. // Check the validity of the template headers that introduce this
  1954. // template.
  1955. // FIXME: Once we have member templates, we'll need to check
  1956. // C++ [temp.expl.spec]p17-18, where we could have multiple levels of
  1957. // template<> headers.
  1958. if (TemplateParameterLists.size() == 0)
  1959. Diag(KWLoc, diag::err_template_spec_needs_header)
  1960. << CodeModificationHint::CreateInsertion(KWLoc, "template<> ");
  1961. else {
  1962. TemplateParameterList *TemplateParams
  1963. = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
  1964. if (TemplateParameterLists.size() > 1) {
  1965. Diag(TemplateParams->getTemplateLoc(),
  1966. diag::err_template_spec_extra_headers);
  1967. return true;
  1968. }
  1969. if (TemplateParams->size() > 0) {
  1970. isPartialSpecialization = true;
  1971. // C++ [temp.class.spec]p10:
  1972. // The template parameter list of a specialization shall not
  1973. // contain default template argument values.
  1974. for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
  1975. Decl *Param = TemplateParams->getParam(I);
  1976. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
  1977. if (TTP->hasDefaultArgument()) {
  1978. Diag(TTP->getDefaultArgumentLoc(),
  1979. diag::err_default_arg_in_partial_spec);
  1980. TTP->setDefaultArgument(QualType(), SourceLocation(), false);
  1981. }
  1982. } else if (NonTypeTemplateParmDecl *NTTP
  1983. = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  1984. if (Expr *DefArg = NTTP->getDefaultArgument()) {
  1985. Diag(NTTP->getDefaultArgumentLoc(),
  1986. diag::err_default_arg_in_partial_spec)
  1987. << DefArg->getSourceRange();
  1988. NTTP->setDefaultArgument(0);
  1989. DefArg->Destroy(Context);
  1990. }
  1991. } else {
  1992. TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
  1993. if (Expr *DefArg = TTP->getDefaultArgument()) {
  1994. Diag(TTP->getDefaultArgumentLoc(),
  1995. diag::err_default_arg_in_partial_spec)
  1996. << DefArg->getSourceRange();
  1997. TTP->setDefaultArgument(0);
  1998. DefArg->Destroy(Context);
  1999. }
  2000. }
  2001. }
  2002. }
  2003. }
  2004. // Check that the specialization uses the same tag kind as the
  2005. // original template.
  2006. TagDecl::TagKind Kind;
  2007. switch (TagSpec) {
  2008. default: assert(0 && "Unknown tag type!");
  2009. case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
  2010. case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
  2011. case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
  2012. }
  2013. if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
  2014. Kind, KWLoc,
  2015. *ClassTemplate->getIdentifier())) {
  2016. Diag(KWLoc, diag::err_use_with_wrong_tag)
  2017. << ClassTemplate
  2018. << CodeModificationHint::CreateReplacement(KWLoc,
  2019. ClassTemplate->getTemplatedDecl()->getKindName());
  2020. Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
  2021. diag::note_previous_use);
  2022. Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
  2023. }
  2024. // Translate the parser's template argument list in our AST format.
  2025. llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
  2026. translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
  2027. // Check that the template argument list is well-formed for this
  2028. // template.
  2029. TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
  2030. if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
  2031. &TemplateArgs[0], TemplateArgs.size(),
  2032. RAngleLoc, ConvertedTemplateArgs))
  2033. return true;
  2034. assert((ConvertedTemplateArgs.size() ==
  2035. ClassTemplate->getTemplateParameters()->size()) &&
  2036. "Converted template argument list is too short!");
  2037. // Find the class template (partial) specialization declaration that
  2038. // corresponds to these arguments.
  2039. llvm::FoldingSetNodeID ID;
  2040. if (isPartialSpecialization) {
  2041. bool MirrorsPrimaryTemplate;
  2042. if (CheckClassTemplatePartialSpecializationArgs(
  2043. ClassTemplate->getTemplateParameters(),
  2044. ConvertedTemplateArgs.getFlatArgumentList(),
  2045. MirrorsPrimaryTemplate))
  2046. return true;
  2047. if (MirrorsPrimaryTemplate) {
  2048. // C++ [temp.class.spec]p9b3:
  2049. //
  2050. // -- The argument list of the specialization shall not be identical
  2051. // to the implicit argument list of the primary template.
  2052. Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
  2053. << (TK == TK_Definition)
  2054. << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc,
  2055. RAngleLoc));
  2056. return ActOnClassTemplate(S, TagSpec, TK, KWLoc, SS,
  2057. ClassTemplate->getIdentifier(),
  2058. TemplateNameLoc,
  2059. Attr,
  2060. move(TemplateParameterLists),
  2061. AS_none);
  2062. }
  2063. // FIXME: Template parameter list matters, too
  2064. ClassTemplatePartialSpecializationDecl::Profile(ID,
  2065. ConvertedTemplateArgs.getFlatArgumentList(),
  2066. ConvertedTemplateArgs.flatSize());
  2067. }
  2068. else
  2069. ClassTemplateSpecializationDecl::Profile(ID,
  2070. ConvertedTemplateArgs.getFlatArgumentList(),
  2071. ConvertedTemplateArgs.flatSize());
  2072. void *InsertPos = 0;
  2073. ClassTemplateSpecializationDecl *PrevDecl = 0;
  2074. if (isPartialSpecialization)
  2075. PrevDecl
  2076. = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
  2077. InsertPos);
  2078. else
  2079. PrevDecl
  2080. = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
  2081. ClassTemplateSpecializationDecl *Specialization = 0;
  2082. // Check whether we can declare a class template specialization in
  2083. // the current scope.
  2084. if (CheckClassTemplateSpecializationScope(ClassTemplate, PrevDecl,
  2085. TemplateNameLoc,
  2086. SS.getRange(),
  2087. isPartialSpecialization,
  2088. /*ExplicitInstantiation=*/false))
  2089. return true;
  2090. if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
  2091. // Since the only prior class template specialization with these
  2092. // arguments was referenced but not declared, reuse that
  2093. // declaration node as our own, updating its source location to
  2094. // reflect our new declaration.
  2095. Specialization = PrevDecl;
  2096. Specialization->setLocation(TemplateNameLoc);
  2097. PrevDecl = 0;
  2098. } else if (isPartialSpecialization) {
  2099. // Create a new class template partial specialization declaration node.
  2100. TemplateParameterList *TemplateParams
  2101. = static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
  2102. ClassTemplatePartialSpecializationDecl *PrevPartial
  2103. = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
  2104. ClassTemplatePartialSpecializationDecl *Partial
  2105. = ClassTemplatePartialSpecializationDecl::Create(Context,
  2106. ClassTemplate->getDeclContext(),
  2107. TemplateNameLoc,
  2108. TemplateParams,
  2109. ClassTemplate,
  2110. ConvertedTemplateArgs,
  2111. PrevPartial);
  2112. if (PrevPartial) {
  2113. ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
  2114. ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
  2115. } else {
  2116. ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
  2117. }
  2118. Specialization = Partial;
  2119. // Check that all of the template parameters of the class template
  2120. // partial specialization are deducible from the template
  2121. // arguments. If not, this class template partial specialization
  2122. // will never be used.
  2123. llvm::SmallVector<bool, 8> DeducibleParams;
  2124. DeducibleParams.resize(TemplateParams->size());
  2125. MarkDeducedTemplateParameters(Partial->getTemplateArgs(), DeducibleParams);
  2126. unsigned NumNonDeducible = 0;
  2127. for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
  2128. if (!DeducibleParams[I])
  2129. ++NumNonDeducible;
  2130. if (NumNonDeducible) {
  2131. Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
  2132. << (NumNonDeducible > 1)
  2133. << SourceRange(TemplateNameLoc, RAngleLoc);
  2134. for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
  2135. if (!DeducibleParams[I]) {
  2136. NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
  2137. if (Param->getDeclName())
  2138. Diag(Param->getLocation(),
  2139. diag::note_partial_spec_unused_parameter)
  2140. << Param->getDeclName();
  2141. else
  2142. Diag(Param->getLocation(),
  2143. diag::note_partial_spec_unused_parameter)
  2144. << std::string("<anonymous>");
  2145. }
  2146. }
  2147. }
  2148. } else {
  2149. // Create a new class template specialization declaration node for
  2150. // this explicit specialization.
  2151. Specialization
  2152. = ClassTemplateSpecializationDecl::Create(Context,
  2153. ClassTemplate->getDeclContext(),
  2154. TemplateNameLoc,
  2155. ClassTemplate,
  2156. ConvertedTemplateArgs,
  2157. PrevDecl);
  2158. if (PrevDecl) {
  2159. ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
  2160. ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
  2161. } else {
  2162. ClassTemplate->getSpecializations().InsertNode(Specialization,
  2163. InsertPos);
  2164. }
  2165. }
  2166. // Note that this is an explicit specialization.
  2167. Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
  2168. // Check that this isn't a redefinition of this specialization.
  2169. if (TK == TK_Definition) {
  2170. if (RecordDecl *Def = Specialization->getDefinition(Context)) {
  2171. // FIXME: Should also handle explicit specialization after implicit
  2172. // instantiation with a special diagnostic.
  2173. SourceRange Range(TemplateNameLoc, RAngleLoc);
  2174. Diag(TemplateNameLoc, diag::err_redefinition)
  2175. << Context.getTypeDeclType(Specialization) << Range;
  2176. Diag(Def->getLocation(), diag::note_previous_definition);
  2177. Specialization->setInvalidDecl();
  2178. return true;
  2179. }
  2180. }
  2181. // Build the fully-sugared type for this class template
  2182. // specialization as the user wrote in the specialization
  2183. // itself. This means that we'll pretty-print the type retrieved
  2184. // from the specialization's declaration the way that the user
  2185. // actually wrote the specialization, rather than formatting the
  2186. // name based on the "canonical" representation used to store the
  2187. // template arguments in the specialization.
  2188. QualType WrittenTy
  2189. = Context.getTemplateSpecializationType(Name,
  2190. &TemplateArgs[0],
  2191. TemplateArgs.size(),
  2192. Context.getTypeDeclType(Specialization));
  2193. Specialization->setTypeAsWritten(WrittenTy);
  2194. TemplateArgsIn.release();
  2195. // C++ [temp.expl.spec]p9:
  2196. // A template explicit specialization is in the scope of the
  2197. // namespace in which the template was defined.
  2198. //
  2199. // We actually implement this paragraph where we set the semantic
  2200. // context (in the creation of the ClassTemplateSpecializationDecl),
  2201. // but we also maintain the lexical context where the actual
  2202. // definition occurs.
  2203. Specialization->setLexicalDeclContext(CurContext);
  2204. // We may be starting the definition of this specialization.
  2205. if (TK == TK_Definition)
  2206. Specialization->startDefinition();
  2207. // Add the specialization into its lexical context, so that it can
  2208. // be seen when iterating through the list of declarations in that
  2209. // context. However, specializations are not found by name lookup.
  2210. CurContext->addDecl(Context, Specialization);
  2211. return DeclPtrTy::make(Specialization);
  2212. }
  2213. // Explicit instantiation of a class template specialization
  2214. Sema::DeclResult
  2215. Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
  2216. unsigned TagSpec,
  2217. SourceLocation KWLoc,
  2218. const CXXScopeSpec &SS,
  2219. TemplateTy TemplateD,
  2220. SourceLocation TemplateNameLoc,
  2221. SourceLocation LAngleLoc,
  2222. ASTTemplateArgsPtr TemplateArgsIn,
  2223. SourceLocation *TemplateArgLocs,
  2224. SourceLocation RAngleLoc,
  2225. AttributeList *Attr) {
  2226. // Find the class template we're specializing
  2227. TemplateName Name = TemplateD.getAsVal<TemplateName>();
  2228. ClassTemplateDecl *ClassTemplate
  2229. = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
  2230. // Check that the specialization uses the same tag kind as the
  2231. // original template.
  2232. TagDecl::TagKind Kind;
  2233. switch (TagSpec) {
  2234. default: assert(0 && "Unknown tag type!");
  2235. case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
  2236. case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
  2237. case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
  2238. }
  2239. if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
  2240. Kind, KWLoc,
  2241. *ClassTemplate->getIdentifier())) {
  2242. Diag(KWLoc, diag::err_use_with_wrong_tag)
  2243. << ClassTemplate
  2244. << CodeModificationHint::CreateReplacement(KWLoc,
  2245. ClassTemplate->getTemplatedDecl()->getKindName());
  2246. Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
  2247. diag::note_previous_use);
  2248. Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
  2249. }
  2250. // C++0x [temp.explicit]p2:
  2251. // [...] An explicit instantiation shall appear in an enclosing
  2252. // namespace of its template. [...]
  2253. //
  2254. // This is C++ DR 275.
  2255. if (CheckClassTemplateSpecializationScope(ClassTemplate, 0,
  2256. TemplateNameLoc,
  2257. SS.getRange(),
  2258. /*PartialSpecialization=*/false,
  2259. /*ExplicitInstantiation=*/true))
  2260. return true;
  2261. // Translate the parser's template argument list in our AST format.
  2262. llvm::SmallVector<TemplateArgument, 16> TemplateArgs;
  2263. translateTemplateArguments(TemplateArgsIn, TemplateArgLocs, TemplateArgs);
  2264. // Check that the template argument list is well-formed for this
  2265. // template.
  2266. TemplateArgumentListBuilder ConvertedTemplateArgs(Context);
  2267. if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, LAngleLoc,
  2268. TemplateArgs.data(), TemplateArgs.size(),
  2269. RAngleLoc, ConvertedTemplateArgs))
  2270. return true;
  2271. assert((ConvertedTemplateArgs.size() ==
  2272. ClassTemplate->getTemplateParameters()->size()) &&
  2273. "Converted template argument list is too short!");
  2274. // Find the class template specialization declaration that
  2275. // corresponds to these arguments.
  2276. llvm::FoldingSetNodeID ID;
  2277. ClassTemplateSpecializationDecl::Profile(ID,
  2278. ConvertedTemplateArgs.getFlatArgumentList(),
  2279. ConvertedTemplateArgs.flatSize());
  2280. void *InsertPos = 0;
  2281. ClassTemplateSpecializationDecl *PrevDecl
  2282. = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
  2283. ClassTemplateSpecializationDecl *Specialization = 0;
  2284. bool SpecializationRequiresInstantiation = true;
  2285. if (PrevDecl) {
  2286. if (PrevDecl->getSpecializationKind() == TSK_ExplicitInstantiation) {
  2287. // This particular specialization has already been declared or
  2288. // instantiated. We cannot explicitly instantiate it.
  2289. Diag(TemplateNameLoc, diag::err_explicit_instantiation_duplicate)
  2290. << Context.getTypeDeclType(PrevDecl);
  2291. Diag(PrevDecl->getLocation(),
  2292. diag::note_previous_explicit_instantiation);
  2293. return DeclPtrTy::make(PrevDecl);
  2294. }
  2295. if (PrevDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
  2296. // C++ DR 259, C++0x [temp.explicit]p4:
  2297. // For a given set of template parameters, if an explicit
  2298. // instantiation of a template appears after a declaration of
  2299. // an explicit specialization for that template, the explicit
  2300. // instantiation has no effect.
  2301. if (!getLangOptions().CPlusPlus0x) {
  2302. Diag(TemplateNameLoc,
  2303. diag::ext_explicit_instantiation_after_specialization)
  2304. << Context.getTypeDeclType(PrevDecl);
  2305. Diag(PrevDecl->getLocation(),
  2306. diag::note_previous_template_specialization);
  2307. }
  2308. // Create a new class template specialization declaration node
  2309. // for this explicit specialization. This node is only used to
  2310. // record the existence of this explicit instantiation for
  2311. // accurate reproduction of the source code; we don't actually
  2312. // use it for anything, since it is semantically irrelevant.
  2313. Specialization
  2314. = ClassTemplateSpecializationDecl::Create(Context,
  2315. ClassTemplate->getDeclContext(),
  2316. TemplateNameLoc,
  2317. ClassTemplate,
  2318. ConvertedTemplateArgs, 0);
  2319. Specialization->setLexicalDeclContext(CurContext);
  2320. CurContext->addDecl(Context, Specialization);
  2321. return DeclPtrTy::make(Specialization);
  2322. }
  2323. // If we have already (implicitly) instantiated this
  2324. // specialization, there is less work to do.
  2325. if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation)
  2326. SpecializationRequiresInstantiation = false;
  2327. // Since the only prior class template specialization with these
  2328. // arguments was referenced but not declared, reuse that
  2329. // declaration node as our own, updating its source location to
  2330. // reflect our new declaration.
  2331. Specialization = PrevDecl;
  2332. Specialization->setLocation(TemplateNameLoc);
  2333. PrevDecl = 0;
  2334. } else {
  2335. // Create a new class template specialization declaration node for
  2336. // this explicit specialization.
  2337. Specialization
  2338. = ClassTemplateSpecializationDecl::Create(Context,
  2339. ClassTemplate->getDeclContext(),
  2340. TemplateNameLoc,
  2341. ClassTemplate,
  2342. ConvertedTemplateArgs, 0);
  2343. ClassTemplate->getSpecializations().InsertNode(Specialization,
  2344. InsertPos);
  2345. }
  2346. // Build the fully-sugared type for this explicit instantiation as
  2347. // the user wrote in the explicit instantiation itself. This means
  2348. // that we'll pretty-print the type retrieved from the
  2349. // specialization's declaration the way that the user actually wrote
  2350. // the explicit instantiation, rather than formatting the name based
  2351. // on the "canonical" representation used to store the template
  2352. // arguments in the specialization.
  2353. QualType WrittenTy
  2354. = Context.getTemplateSpecializationType(Name,
  2355. TemplateArgs.data(),
  2356. TemplateArgs.size(),
  2357. Context.getTypeDeclType(Specialization));
  2358. Specialization->setTypeAsWritten(WrittenTy);
  2359. TemplateArgsIn.release();
  2360. // Add the explicit instantiation into its lexical context. However,
  2361. // since explicit instantiations are never found by name lookup, we
  2362. // just put it into the declaration context directly.
  2363. Specialization->setLexicalDeclContext(CurContext);
  2364. CurContext->addDecl(Context, Specialization);
  2365. // C++ [temp.explicit]p3:
  2366. // A definition of a class template or class member template
  2367. // shall be in scope at the point of the explicit instantiation of
  2368. // the class template or class member template.
  2369. //
  2370. // This check comes when we actually try to perform the
  2371. // instantiation.
  2372. if (SpecializationRequiresInstantiation)
  2373. InstantiateClassTemplateSpecialization(Specialization, true);
  2374. else // Instantiate the members of this class template specialization.
  2375. InstantiateClassTemplateSpecializationMembers(TemplateLoc, Specialization);
  2376. return DeclPtrTy::make(Specialization);
  2377. }
  2378. // Explicit instantiation of a member class of a class template.
  2379. Sema::DeclResult
  2380. Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation TemplateLoc,
  2381. unsigned TagSpec,
  2382. SourceLocation KWLoc,
  2383. const CXXScopeSpec &SS,
  2384. IdentifierInfo *Name,
  2385. SourceLocation NameLoc,
  2386. AttributeList *Attr) {
  2387. bool Owned = false;
  2388. DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TK_Reference,
  2389. KWLoc, SS, Name, NameLoc, Attr, AS_none, Owned);
  2390. if (!TagD)
  2391. return true;
  2392. TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
  2393. if (Tag->isEnum()) {
  2394. Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
  2395. << Context.getTypeDeclType(Tag);
  2396. return true;
  2397. }
  2398. if (Tag->isInvalidDecl())
  2399. return true;
  2400. CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
  2401. CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
  2402. if (!Pattern) {
  2403. Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
  2404. << Context.getTypeDeclType(Record);
  2405. Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
  2406. return true;
  2407. }
  2408. // C++0x [temp.explicit]p2:
  2409. // [...] An explicit instantiation shall appear in an enclosing
  2410. // namespace of its template. [...]
  2411. //
  2412. // This is C++ DR 275.
  2413. if (getLangOptions().CPlusPlus0x) {
  2414. // FIXME: In C++98, we would like to turn these errors into warnings,
  2415. // dependent on a -Wc++0x flag.
  2416. DeclContext *PatternContext
  2417. = Pattern->getDeclContext()->getEnclosingNamespaceContext();
  2418. if (!CurContext->Encloses(PatternContext)) {
  2419. Diag(TemplateLoc, diag::err_explicit_instantiation_out_of_scope)
  2420. << Record << cast<NamedDecl>(PatternContext) << SS.getRange();
  2421. Diag(Pattern->getLocation(), diag::note_previous_declaration);
  2422. }
  2423. }
  2424. if (!Record->getDefinition(Context)) {
  2425. // If the class has a definition, instantiate it (and all of its
  2426. // members, recursively).
  2427. Pattern = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context));
  2428. if (Pattern && InstantiateClass(TemplateLoc, Record, Pattern,
  2429. getTemplateInstantiationArgs(Record),
  2430. /*ExplicitInstantiation=*/true))
  2431. return true;
  2432. } else // Instantiate all of the members of class.
  2433. InstantiateClassMembers(TemplateLoc, Record,
  2434. getTemplateInstantiationArgs(Record));
  2435. // FIXME: We don't have any representation for explicit instantiations of
  2436. // member classes. Such a representation is not needed for compilation, but it
  2437. // should be available for clients that want to see all of the declarations in
  2438. // the source code.
  2439. return TagD;
  2440. }
  2441. Sema::TypeResult
  2442. Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
  2443. const IdentifierInfo &II, SourceLocation IdLoc) {
  2444. NestedNameSpecifier *NNS
  2445. = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
  2446. if (!NNS)
  2447. return true;
  2448. QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc));
  2449. if (T.isNull())
  2450. return true;
  2451. return T.getAsOpaquePtr();
  2452. }
  2453. Sema::TypeResult
  2454. Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
  2455. SourceLocation TemplateLoc, TypeTy *Ty) {
  2456. QualType T = QualType::getFromOpaquePtr(Ty);
  2457. NestedNameSpecifier *NNS
  2458. = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
  2459. const TemplateSpecializationType *TemplateId
  2460. = T->getAsTemplateSpecializationType();
  2461. assert(TemplateId && "Expected a template specialization type");
  2462. if (NNS->isDependent())
  2463. return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr();
  2464. return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr();
  2465. }
  2466. /// \brief Build the type that describes a C++ typename specifier,
  2467. /// e.g., "typename T::type".
  2468. QualType
  2469. Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II,
  2470. SourceRange Range) {
  2471. CXXRecordDecl *CurrentInstantiation = 0;
  2472. if (NNS->isDependent()) {
  2473. CurrentInstantiation = getCurrentInstantiationOf(NNS);
  2474. // If the nested-name-specifier does not refer to the current
  2475. // instantiation, then build a typename type.
  2476. if (!CurrentInstantiation)
  2477. return Context.getTypenameType(NNS, &II);
  2478. }
  2479. DeclContext *Ctx = 0;
  2480. if (CurrentInstantiation)
  2481. Ctx = CurrentInstantiation;
  2482. else {
  2483. CXXScopeSpec SS;
  2484. SS.setScopeRep(NNS);
  2485. SS.setRange(Range);
  2486. if (RequireCompleteDeclContext(SS))
  2487. return QualType();
  2488. Ctx = computeDeclContext(SS);
  2489. }
  2490. assert(Ctx && "No declaration context?");
  2491. DeclarationName Name(&II);
  2492. LookupResult Result = LookupQualifiedName(Ctx, Name, LookupOrdinaryName,
  2493. false);
  2494. unsigned DiagID = 0;
  2495. Decl *Referenced = 0;
  2496. switch (Result.getKind()) {
  2497. case LookupResult::NotFound:
  2498. if (Ctx->isTranslationUnit())
  2499. DiagID = diag::err_typename_nested_not_found_global;
  2500. else
  2501. DiagID = diag::err_typename_nested_not_found;
  2502. break;
  2503. case LookupResult::Found:
  2504. if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getAsDecl())) {
  2505. // We found a type. Build a QualifiedNameType, since the
  2506. // typename-specifier was just sugar. FIXME: Tell
  2507. // QualifiedNameType that it has a "typename" prefix.
  2508. return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type));
  2509. }
  2510. DiagID = diag::err_typename_nested_not_type;
  2511. Referenced = Result.getAsDecl();
  2512. break;
  2513. case LookupResult::FoundOverloaded:
  2514. DiagID = diag::err_typename_nested_not_type;
  2515. Referenced = *Result.begin();
  2516. break;
  2517. case LookupResult::AmbiguousBaseSubobjectTypes:
  2518. case LookupResult::AmbiguousBaseSubobjects:
  2519. case LookupResult::AmbiguousReference:
  2520. DiagnoseAmbiguousLookup(Result, Name, Range.getEnd(), Range);
  2521. return QualType();
  2522. }
  2523. // If we get here, it's because name lookup did not find a
  2524. // type. Emit an appropriate diagnostic and return an error.
  2525. if (NamedDecl *NamedCtx = dyn_cast<NamedDecl>(Ctx))
  2526. Diag(Range.getEnd(), DiagID) << Range << Name << NamedCtx;
  2527. else
  2528. Diag(Range.getEnd(), DiagID) << Range << Name;
  2529. if (Referenced)
  2530. Diag(Referenced->getLocation(), diag::note_typename_refers_here)
  2531. << Name;
  2532. return QualType();
  2533. }