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