blob: ecbc860d1df0db30f5e0cec0c01794c6ed208207 [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- 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"
Douglas Gregorddc29e12009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
20
21using namespace clang;
22
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000023/// isTemplateName - Determines whether the identifier II is a
24/// template name in the current scope, and returns the template
25/// declaration if II names a template. An optional CXXScope can be
26/// passed to indicate the C++ scope in which the identifier will be
27/// found.
Douglas Gregor55f6b142009-02-09 18:46:07 +000028Sema::TemplateNameKind Sema::isTemplateName(IdentifierInfo &II, Scope *S,
29 DeclTy *&Template,
30 const CXXScopeSpec *SS) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +000031 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000032
33 if (IIDecl) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000034 if (isa<TemplateDecl>(IIDecl)) {
35 Template = IIDecl;
36 if (isa<FunctionTemplateDecl>(IIDecl))
37 return TNK_Function_template;
38 else if (isa<ClassTemplateDecl>(IIDecl))
39 return TNK_Class_template;
40 else if (isa<TemplateTemplateParmDecl>(IIDecl))
41 return TNK_Template_template_parm;
42 else
43 assert(false && "Unknown TemplateDecl");
44 }
Douglas Gregoraaba5e32009-02-04 19:02:06 +000045
Douglas Gregor55f6b142009-02-09 18:46:07 +000046 // FIXME: What follows is a gross hack.
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000047 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000048 if (FD->getType()->isDependentType()) {
49 Template = FD;
50 return TNK_Function_template;
51 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000052 } else if (OverloadedFunctionDecl *Ovl
53 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
54 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
55 FEnd = Ovl->function_end();
56 F != FEnd; ++F) {
Douglas Gregor55f6b142009-02-09 18:46:07 +000057 if ((*F)->getType()->isDependentType()) {
58 Template = Ovl;
59 return TNK_Function_template;
60 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000061 }
62 }
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000063 }
Douglas Gregor55f6b142009-02-09 18:46:07 +000064 return TNK_Non_template;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +000065}
66
Douglas Gregor72c3f312008-12-05 18:15:24 +000067/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
68/// that the template parameter 'PrevDecl' is being shadowed by a new
69/// declaration at location Loc. Returns true to indicate that this is
70/// an error, and false otherwise.
71bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +000072 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +000073
74 // Microsoft Visual C++ permits template parameters to be shadowed.
75 if (getLangOptions().Microsoft)
76 return false;
77
78 // C++ [temp.local]p4:
79 // A template-parameter shall not be redeclared within its
80 // scope (including nested scopes).
81 Diag(Loc, diag::err_template_param_shadow)
82 << cast<NamedDecl>(PrevDecl)->getDeclName();
83 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
84 return true;
85}
86
Douglas Gregoraaba5e32009-02-04 19:02:06 +000087/// AdjustDeclForTemplates - If the given decl happens to be a template, reset
88/// the parameter D to reference the templated declaration and return a pointer
89/// to the template declaration. Otherwise, do nothing to D and return null.
90TemplateDecl *Sema::AdjustDeclIfTemplate(DeclTy *&D)
91{
92 if(TemplateDecl *Temp = dyn_cast<TemplateDecl>(static_cast<Decl*>(D))) {
93 D = Temp->getTemplatedDecl();
94 return Temp;
95 }
96 return 0;
97}
98
Douglas Gregor72c3f312008-12-05 18:15:24 +000099/// ActOnTypeParameter - Called when a C++ template type parameter
100/// (e.g., "typename T") has been parsed. Typename specifies whether
101/// the keyword "typename" was used to declare the type parameter
102/// (otherwise, "class" was used), and KeyLoc is the location of the
103/// "class" or "typename" keyword. ParamName is the name of the
104/// parameter (NULL indicates an unnamed template parameter) and
105/// ParamName is the location of the parameter name (if any).
106/// If the type parameter has a default argument, it will be added
107/// later via ActOnTypeParameterDefault.
108Sema::DeclTy *Sema::ActOnTypeParameter(Scope *S, bool Typename,
109 SourceLocation KeyLoc,
110 IdentifierInfo *ParamName,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000111 SourceLocation ParamNameLoc,
112 unsigned Depth, unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000113 assert(S->isTemplateParamScope() &&
114 "Template type parameter not in template parameter scope!");
115 bool Invalid = false;
116
117 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000118 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000119 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000120 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
121 PrevDecl);
122 }
123
Douglas Gregorddc29e12009-02-06 22:42:48 +0000124 SourceLocation Loc = ParamNameLoc;
125 if (!ParamName)
126 Loc = KeyLoc;
127
Douglas Gregor72c3f312008-12-05 18:15:24 +0000128 TemplateTypeParmDecl *Param
Douglas Gregorddc29e12009-02-06 22:42:48 +0000129 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000130 Depth, Position, ParamName, Typename);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000131 if (Invalid)
132 Param->setInvalidDecl();
133
134 if (ParamName) {
135 // Add the template parameter into the current scope.
136 S->AddDecl(Param);
137 IdResolver.AddDecl(Param);
138 }
139
140 return Param;
141}
142
143/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
144/// template parameter (e.g., "int Size" in "template<int Size>
145/// class Array") has been parsed. S is the current scope and D is
146/// the parsed declarator.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000147Sema::DeclTy *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
148 unsigned Depth,
149 unsigned Position) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000150 QualType T = GetTypeForDeclarator(D, S);
151
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000152 assert(S->isTemplateParamScope() &&
153 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000154 bool Invalid = false;
155
156 IdentifierInfo *ParamName = D.getIdentifier();
157 if (ParamName) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000158 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000159 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000160 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000161 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000162 }
163
164 NonTypeTemplateParmDecl *Param
165 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000166 Depth, Position, ParamName, T);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000167 if (Invalid)
168 Param->setInvalidDecl();
169
170 if (D.getIdentifier()) {
171 // Add the template parameter into the current scope.
172 S->AddDecl(Param);
173 IdResolver.AddDecl(Param);
174 }
175 return Param;
176}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000177
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000178
179/// ActOnTemplateTemplateParameter - Called when a C++ template template
180/// parameter (e.g. T in template <template <typename> class T> class array)
181/// has been parsed. S is the current scope.
182Sema::DeclTy *Sema::ActOnTemplateTemplateParameter(Scope* S,
183 SourceLocation TmpLoc,
184 TemplateParamsTy *Params,
185 IdentifierInfo *Name,
186 SourceLocation NameLoc,
187 unsigned Depth,
188 unsigned Position)
189{
190 assert(S->isTemplateParamScope() &&
191 "Template template parameter not in template parameter scope!");
192
193 // Construct the parameter object.
194 TemplateTemplateParmDecl *Param =
195 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
196 Position, Name,
197 (TemplateParameterList*)Params);
198
199 // Make sure the parameter is valid.
200 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
201 // do anything yet. However, if the template parameter list or (eventual)
202 // default value is ever invalidated, that will propagate here.
203 bool Invalid = false;
204 if (Invalid) {
205 Param->setInvalidDecl();
206 }
207
208 // If the tt-param has a name, then link the identifier into the scope
209 // and lookup mechanisms.
210 if (Name) {
211 S->AddDecl(Param);
212 IdResolver.AddDecl(Param);
213 }
214
215 return Param;
216}
217
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000218/// ActOnTemplateParameterList - Builds a TemplateParameterList that
219/// contains the template parameters in Params/NumParams.
220Sema::TemplateParamsTy *
221Sema::ActOnTemplateParameterList(unsigned Depth,
222 SourceLocation ExportLoc,
223 SourceLocation TemplateLoc,
224 SourceLocation LAngleLoc,
225 DeclTy **Params, unsigned NumParams,
226 SourceLocation RAngleLoc) {
227 if (ExportLoc.isValid())
228 Diag(ExportLoc, diag::note_template_export_unsupported);
229
Douglas Gregorddc29e12009-02-06 22:42:48 +0000230 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
231 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000232}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000233
Douglas Gregorddc29e12009-02-06 22:42:48 +0000234Sema::DeclTy *
235Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
236 SourceLocation KWLoc, const CXXScopeSpec &SS,
237 IdentifierInfo *Name, SourceLocation NameLoc,
238 AttributeList *Attr,
239 MultiTemplateParamsArg TemplateParameterLists) {
240 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
241 assert(TK != TK_Reference && "Can only declare or define class templates");
242
243 // Check that we can declare a template here.
244 if (CheckTemplateDeclScope(S, TemplateParameterLists))
245 return 0;
246
247 TagDecl::TagKind Kind;
248 switch (TagSpec) {
249 default: assert(0 && "Unknown tag type!");
250 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
251 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
252 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
253 }
254
255 // There is no such thing as an unnamed class template.
256 if (!Name) {
257 Diag(KWLoc, diag::err_template_unnamed_class);
258 return 0;
259 }
260
261 // Find any previous declaration with this name.
262 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
263 true);
264 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
265 NamedDecl *PrevDecl = 0;
266 if (Previous.begin() != Previous.end())
267 PrevDecl = *Previous.begin();
268
269 DeclContext *SemanticContext = CurContext;
270 if (SS.isNotEmpty() && !SS.isInvalid()) {
271 SemanticContext = static_cast<DeclContext*>(SS.getScopeRep());
272
273 // FIXME: need to match up several levels of template parameter
274 // lists here.
275 }
276
277 // FIXME: member templates!
278 TemplateParameterList *TemplateParams
279 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
280
281 // If there is a previous declaration with the same name, check
282 // whether this is a valid redeclaration.
283 ClassTemplateDecl *PrevClassTemplate
284 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
285 if (PrevClassTemplate) {
286 // Ensure that the template parameter lists are compatible.
287 if (!TemplateParameterListsAreEqual(TemplateParams,
288 PrevClassTemplate->getTemplateParameters(),
289 /*Complain=*/true))
290 return 0;
291
292 // C++ [temp.class]p4:
293 // In a redeclaration, partial specialization, explicit
294 // specialization or explicit instantiation of a class template,
295 // the class-key shall agree in kind with the original class
296 // template declaration (7.1.5.3).
297 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
298 if (PrevRecordDecl->getTagKind() != Kind) {
299 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
300 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
301 return 0;
302 }
303
304
305 // Check for redefinition of this class template.
306 if (TK == TK_Definition) {
307 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
308 Diag(NameLoc, diag::err_redefinition) << Name;
309 Diag(Def->getLocation(), diag::note_previous_definition);
310 // FIXME: Would it make sense to try to "forget" the previous
311 // definition, as part of error recovery?
312 return 0;
313 }
314 }
315 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
316 // Maybe we will complain about the shadowed template parameter.
317 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
318 // Just pretend that we didn't see the previous declaration.
319 PrevDecl = 0;
320 } else if (PrevDecl) {
321 // C++ [temp]p5:
322 // A class template shall not have the same name as any other
323 // template, class, function, object, enumeration, enumerator,
324 // namespace, or type in the same scope (3.3), except as specified
325 // in (14.5.4).
326 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
327 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
328 return 0;
329 }
330
331 // If we had a scope specifier, we better have a previous template
332 // declaration!
333
334 TagDecl *NewClass =
335 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
336 PrevClassTemplate?
337 PrevClassTemplate->getTemplatedDecl() : 0);
338
339 ClassTemplateDecl *NewTemplate
340 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
341 DeclarationName(Name), TemplateParams,
342 NewClass);
343
344 // Set the lexical context of these templates
345 NewClass->setLexicalDeclContext(CurContext);
346 NewTemplate->setLexicalDeclContext(CurContext);
347
348 if (TK == TK_Definition)
349 NewClass->startDefinition();
350
351 if (Attr)
352 ProcessDeclAttributeList(NewClass, Attr);
353
354 PushOnScopeChains(NewTemplate, S);
355
356 return NewTemplate;
357}
358
Douglas Gregorc15cb382009-02-09 23:23:08 +0000359
360
Douglas Gregor55f6b142009-02-09 18:46:07 +0000361Action::TypeTy *
362Sema::ActOnClassTemplateSpecialization(DeclTy *TemplateD,
Douglas Gregorc15cb382009-02-09 23:23:08 +0000363 SourceLocation TemplateLoc,
Douglas Gregor55f6b142009-02-09 18:46:07 +0000364 SourceLocation LAngleLoc,
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000365 ASTTemplateArgsPtr TemplateArgs,
Douglas Gregorc15cb382009-02-09 23:23:08 +0000366 SourceLocation *TemplateArgLocs,
Douglas Gregor55f6b142009-02-09 18:46:07 +0000367 SourceLocation RAngleLoc,
368 const CXXScopeSpec *SS) {
369 TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
370
Douglas Gregorc15cb382009-02-09 23:23:08 +0000371 // Check that the template argument list is well-formed for this
372 // template.
373 if (!CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
374 TemplateArgs, TemplateArgLocs, RAngleLoc))
375 return 0;
376
Douglas Gregor55f6b142009-02-09 18:46:07 +0000377 // Yes, all class template specializations are just silly sugar for
378 // 'int'. Gotta problem wit dat?
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000379 QualType Result
380 = Context.getClassTemplateSpecializationType(Template,
381 TemplateArgs.size(),
382 reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()),
383 TemplateArgs.getArgIsType(),
384 Context.IntTy);
385 TemplateArgs.release();
386 return Result.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000387}
388
Douglas Gregorc15cb382009-02-09 23:23:08 +0000389/// \brief Check that the given template argument list is well-formed
390/// for specializing the given template.
391bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
392 SourceLocation TemplateLoc,
393 SourceLocation LAngleLoc,
394 ASTTemplateArgsPtr& Args,
395 SourceLocation *TemplateArgLocs,
396 SourceLocation RAngleLoc) {
397 TemplateParameterList *Params = Template->getTemplateParameters();
398 unsigned NumParams = Params->size();
399 unsigned NumArgs = Args.size();
400 bool Invalid = false;
401
402 if (NumArgs > NumParams ||
403 NumArgs < NumParams /*FIXME: default arguments! */) {
404 // FIXME: point at either the first arg beyond what we can handle,
405 // or the '>', depending on whether we have too many or too few
406 // arguments.
407 SourceRange Range;
408 if (NumArgs > NumParams)
409 Range = SourceRange(TemplateArgLocs[NumParams], RAngleLoc);
410 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
411 << (NumArgs > NumParams)
412 << (isa<ClassTemplateDecl>(Template)? 0 :
413 isa<FunctionTemplateDecl>(Template)? 1 :
414 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
415 << Template << Range;
416
417 Invalid = true;
418 }
419
420 // C++ [temp.arg]p1:
421 // [...] The type and form of each template-argument specified in
422 // a template-id shall match the type and form specified for the
423 // corresponding parameter declared by the template in its
424 // template-parameter-list.
425 unsigned ArgIdx = 0;
426 for (TemplateParameterList::iterator Param = Params->begin(),
427 ParamEnd = Params->end();
428 Param != ParamEnd; ++Param, ++ArgIdx) {
429 // Decode the template argument
430 QualType ArgType;
431 Expr *ArgExpr = 0;
432 SourceLocation ArgLoc;
433 if (ArgIdx >= NumArgs) {
434 // FIXME: Get the default argument here, which might
435 // (eventually) require instantiation.
436 break;
437 } else
438 ArgLoc = TemplateArgLocs[ArgIdx];
439
440 if (Args.getArgIsType()[ArgIdx])
441 ArgType = QualType::getFromOpaquePtr(Args.getArgs()[ArgIdx]);
442 else
443 ArgExpr = reinterpret_cast<Expr *>(Args.getArgs()[ArgIdx]);
444
445 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
446 // Check template type parameters.
447 if (!ArgType.isNull()) {
448 if (!CheckTemplateArgument(TTP, ArgType, ArgLoc))
449 Invalid = true;
450 continue;
451 }
452
453 // C++ [temp.arg.type]p1:
454 // A template-argument for a template-parameter which is a
455 // type shall be a type-id.
456
457 // We have a template type parameter but the template argument
458 // is an expression.
459 Diag(ArgExpr->getSourceRange().getBegin(),
460 diag::err_template_arg_must_be_type);
Douglas Gregor8b642592009-02-10 00:53:15 +0000461 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000462 Invalid = true;
463 } else if (NonTypeTemplateParmDecl *NTTP
464 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
465 // Check non-type template parameters.
466 if (ArgExpr) {
467 if (!CheckTemplateArgument(NTTP, ArgExpr))
468 Invalid = true;
469 continue;
470 }
471
472 // We have a non-type template parameter but the template
473 // argument is a type.
474
475 // C++ [temp.arg]p2:
476 // In a template-argument, an ambiguity between a type-id and
477 // an expression is resolved to a type-id, regardless of the
478 // form of the corresponding template-parameter.
479 //
480 // We warn specifically about this case, since it can be rather
481 // confusing for users.
482 if (ArgType->isFunctionType())
483 Diag(ArgLoc, diag::err_template_arg_nontype_ambig)
484 << ArgType;
485 else
486 Diag(ArgLoc, diag::err_template_arg_must_be_expr);
Douglas Gregor8b642592009-02-10 00:53:15 +0000487 Diag((*Param)->getLocation(), diag::note_template_param_here);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000488 Invalid = true;
489 } else {
490 // Check template template parameters.
491 TemplateTemplateParmDecl *TempParm
492 = cast<TemplateTemplateParmDecl>(*Param);
493
494 if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
495 isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
496 if (!CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
497 Invalid = true;
498 continue;
499 }
500
501 // We have a template template parameter but the template
502 // argument does not refer to a template.
503 Diag(ArgLoc, diag::err_template_arg_must_be_template);
504 Invalid = true;
505 }
506 }
507
508 return Invalid;
509}
510
511/// \brief Check a template argument against its corresponding
512/// template type parameter.
513///
514/// This routine implements the semantics of C++ [temp.arg.type]. It
515/// returns true if an error occurred, and false otherwise.
516bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
517 QualType Arg, SourceLocation ArgLoc) {
518 // C++ [temp.arg.type]p2:
519 // A local type, a type with no linkage, an unnamed type or a type
520 // compounded from any of these types shall not be used as a
521 // template-argument for a template type-parameter.
522 //
523 // FIXME: Perform the recursive and no-linkage type checks.
524 const TagType *Tag = 0;
525 if (const EnumType *EnumT = Arg->getAsEnumType())
526 Tag = EnumT;
527 else if (const RecordType *RecordT = Arg->getAsRecordType())
528 Tag = RecordT;
529 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
530 return Diag(ArgLoc, diag::err_template_arg_local_type)
531 << QualType(Tag, 0);
532 else if (Tag && !Tag->getDecl()->getDeclName()) {
533 Diag(ArgLoc, diag::err_template_arg_unnamed_type);
534 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
535 return true;
536 }
537
538 return false;
539}
540
541/// \brief Check a template argument against its corresponding
542/// non-type template parameter.
543///
544/// This routine implements the semantics of C++ [temp.arg.nontype].
545/// It returns true if an error occurred, and false otherwise.
546bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
547 Expr *Arg) {
548 return false;
549}
550
551/// \brief Check a template argument against its corresponding
552/// template template parameter.
553///
554/// This routine implements the semantics of C++ [temp.arg.template].
555/// It returns true if an error occurred, and false otherwise.
556bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
557 DeclRefExpr *Arg) {
Douglas Gregordd0574e2009-02-10 00:24:35 +0000558 assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
559 TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
560
561 // C++ [temp.arg.template]p1:
562 // A template-argument for a template template-parameter shall be
563 // the name of a class template, expressed as id-expression. Only
564 // primary class templates are considered when matching the
565 // template template argument with the corresponding parameter;
566 // partial specializations are not considered even if their
567 // parameter lists match that of the template template parameter.
568 if (!isa<ClassTemplateDecl>(Template)) {
569 assert(isa<FunctionTemplateDecl>(Template) &&
570 "Only function templates are possible here");
571 Diag(Arg->getSourceRange().getBegin(), diag::note_template_arg_refers_here)
572 << Template;
573 }
574
575 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
576 Param->getTemplateParameters(),
577 true, true,
578 Arg->getSourceRange().getBegin());
Douglas Gregorc15cb382009-02-09 23:23:08 +0000579}
580
Douglas Gregorddc29e12009-02-06 22:42:48 +0000581/// \brief Determine whether the given template parameter lists are
582/// equivalent.
583///
584/// \param New The new template parameter list, typically written in the
585/// source code as part of a new template declaration.
586///
587/// \param Old The old template parameter list, typically found via
588/// name lookup of the template declared with this template parameter
589/// list.
590///
591/// \param Complain If true, this routine will produce a diagnostic if
592/// the template parameter lists are not equivalent.
593///
Douglas Gregordd0574e2009-02-10 00:24:35 +0000594/// \param IsTemplateTemplateParm If true, this routine is being
595/// called to compare the template parameter lists of a template
596/// template parameter.
597///
598/// \param TemplateArgLoc If this source location is valid, then we
599/// are actually checking the template parameter list of a template
600/// argument (New) against the template parameter list of its
601/// corresponding template template parameter (Old). We produce
602/// slightly different diagnostics in this scenario.
603///
Douglas Gregorddc29e12009-02-06 22:42:48 +0000604/// \returns True if the template parameter lists are equal, false
605/// otherwise.
606bool
607Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
608 TemplateParameterList *Old,
609 bool Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +0000610 bool IsTemplateTemplateParm,
611 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000612 if (Old->size() != New->size()) {
613 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +0000614 unsigned NextDiag = diag::err_template_param_list_different_arity;
615 if (TemplateArgLoc.isValid()) {
616 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
617 NextDiag = diag::note_template_param_list_different_arity;
618 }
619 Diag(New->getTemplateLoc(), NextDiag)
620 << (New->size() > Old->size())
621 << IsTemplateTemplateParm
622 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000623 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
624 << IsTemplateTemplateParm
625 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
626 }
627
628 return false;
629 }
630
631 for (TemplateParameterList::iterator OldParm = Old->begin(),
632 OldParmEnd = Old->end(), NewParm = New->begin();
633 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
634 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregordd0574e2009-02-10 00:24:35 +0000635 unsigned NextDiag = diag::err_template_param_different_kind;
636 if (TemplateArgLoc.isValid()) {
637 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
638 NextDiag = diag::note_template_param_different_kind;
639 }
640 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000641 << IsTemplateTemplateParm;
642 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
643 << IsTemplateTemplateParm;
644 return false;
645 }
646
647 if (isa<TemplateTypeParmDecl>(*OldParm)) {
648 // Okay; all template type parameters are equivalent (since we
Douglas Gregordd0574e2009-02-10 00:24:35 +0000649 // know we're at the same index).
650#if 0
651 // FIXME: Enable this code in debug mode *after* we properly go
652 // through and "instantiate" the template parameter lists of
653 // template template parameters. It's only after this
654 // instantiation that (1) any dependent types within the
655 // template parameter list of the template template parameter
656 // can be checked, and (2) the template type parameter depths
657 // will match up.
Douglas Gregorddc29e12009-02-06 22:42:48 +0000658 QualType OldParmType
659 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
660 QualType NewParmType
661 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
662 assert(Context.getCanonicalType(OldParmType) ==
663 Context.getCanonicalType(NewParmType) &&
664 "type parameter mismatch?");
665#endif
666 } else if (NonTypeTemplateParmDecl *OldNTTP
667 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
668 // The types of non-type template parameters must agree.
669 NonTypeTemplateParmDecl *NewNTTP
670 = cast<NonTypeTemplateParmDecl>(*NewParm);
671 if (Context.getCanonicalType(OldNTTP->getType()) !=
672 Context.getCanonicalType(NewNTTP->getType())) {
673 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +0000674 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
675 if (TemplateArgLoc.isValid()) {
676 Diag(TemplateArgLoc,
677 diag::err_template_arg_template_params_mismatch);
678 NextDiag = diag::note_template_nontype_parm_different_type;
679 }
680 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000681 << NewNTTP->getType()
682 << IsTemplateTemplateParm;
683 Diag(OldNTTP->getLocation(),
684 diag::note_template_nontype_parm_prev_declaration)
685 << OldNTTP->getType();
686 }
687 return false;
688 }
689 } else {
690 // The template parameter lists of template template
691 // parameters must agree.
692 // FIXME: Could we perform a faster "type" comparison here?
693 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
694 "Only template template parameters handled here");
695 TemplateTemplateParmDecl *OldTTP
696 = cast<TemplateTemplateParmDecl>(*OldParm);
697 TemplateTemplateParmDecl *NewTTP
698 = cast<TemplateTemplateParmDecl>(*NewParm);
699 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
700 OldTTP->getTemplateParameters(),
701 Complain,
Douglas Gregordd0574e2009-02-10 00:24:35 +0000702 /*IsTemplateTemplateParm=*/true,
703 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +0000704 return false;
705 }
706 }
707
708 return true;
709}
710
711/// \brief Check whether a template can be declared within this scope.
712///
713/// If the template declaration is valid in this scope, returns
714/// false. Otherwise, issues a diagnostic and returns true.
715bool
716Sema::CheckTemplateDeclScope(Scope *S,
717 MultiTemplateParamsArg &TemplateParameterLists) {
718 assert(TemplateParameterLists.size() > 0 && "Not a template");
719
720 // Find the nearest enclosing declaration scope.
721 while ((S->getFlags() & Scope::DeclScope) == 0 ||
722 (S->getFlags() & Scope::TemplateParamScope) != 0)
723 S = S->getParent();
724
725 TemplateParameterList *TemplateParams =
726 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
727 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
728 SourceRange TemplateRange
729 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
730
731 // C++ [temp]p2:
732 // A template-declaration can appear only as a namespace scope or
733 // class scope declaration.
734 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
735 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
736 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
737 return Diag(TemplateLoc, diag::err_template_linkage)
738 << TemplateRange;
739
740 Ctx = Ctx->getParent();
741 }
742
743 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
744 return false;
745
746 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
747 << TemplateRange;
748}