blob: 297410471b8568e694a51330801529b6d5337b55 [file] [log] [blame]
Douglas Gregordd861062008-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 Gregord406b032009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor1b21c7f2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000017#include "clang/AST/DeclTemplate.h"
Douglas Gregordd861062008-12-05 18:15:24 +000018#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
20
21using namespace clang;
22
Douglas Gregor2fa10442008-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 Gregor8e458f42009-02-09 18:46:07 +000028Sema::TemplateNameKind Sema::isTemplateName(IdentifierInfo &II, Scope *S,
29 DeclTy *&Template,
30 const CXXScopeSpec *SS) {
Douglas Gregor09be81b2009-02-04 17:27:36 +000031 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregor2fa10442008-12-18 19:37:40 +000032
33 if (IIDecl) {
Douglas Gregor8e458f42009-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 Gregor279272e2009-02-04 19:02:06 +000045
Douglas Gregor8e458f42009-02-09 18:46:07 +000046 // FIXME: What follows is a gross hack.
Douglas Gregor2fa10442008-12-18 19:37:40 +000047 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
Douglas Gregor8e458f42009-02-09 18:46:07 +000048 if (FD->getType()->isDependentType()) {
49 Template = FD;
50 return TNK_Function_template;
51 }
Douglas Gregor2fa10442008-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 Gregor8e458f42009-02-09 18:46:07 +000057 if ((*F)->getType()->isDependentType()) {
58 Template = Ovl;
59 return TNK_Function_template;
60 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000061 }
62 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000063 }
Douglas Gregor8e458f42009-02-09 18:46:07 +000064 return TNK_Non_template;
Douglas Gregor2fa10442008-12-18 19:37:40 +000065}
66
Douglas Gregordd861062008-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 Gregor2715a1f2008-12-08 18:40:42 +000072 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-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 Gregor279272e2009-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 Gregordd861062008-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 Gregor52473432008-12-24 02:52:09 +0000111 SourceLocation ParamNameLoc,
112 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-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 Gregor09be81b2009-02-04 17:27:36 +0000118 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000119 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000120 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
121 PrevDecl);
122 }
123
Douglas Gregord406b032009-02-06 22:42:48 +0000124 SourceLocation Loc = ParamNameLoc;
125 if (!ParamName)
126 Loc = KeyLoc;
127
Douglas Gregordd861062008-12-05 18:15:24 +0000128 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000129 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregor279272e2009-02-04 19:02:06 +0000130 Depth, Position, ParamName, Typename);
Douglas Gregordd861062008-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 Gregor52473432008-12-24 02:52:09 +0000147Sema::DeclTy *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
148 unsigned Depth,
149 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000150 QualType T = GetTypeForDeclarator(D, S);
151
Douglas Gregor279272e2009-02-04 19:02:06 +0000152 assert(S->isTemplateParamScope() &&
153 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000154 bool Invalid = false;
155
156 IdentifierInfo *ParamName = D.getIdentifier();
157 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000158 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000159 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000160 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000161 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000162 }
163
164 NonTypeTemplateParmDecl *Param
165 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000166 Depth, Position, ParamName, T);
Douglas Gregordd861062008-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 Gregor52473432008-12-24 02:52:09 +0000177
Douglas Gregor279272e2009-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 Gregor52473432008-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 Gregord406b032009-02-06 22:42:48 +0000230 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
231 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000232}
Douglas Gregor279272e2009-02-04 19:02:06 +0000233
Douglas Gregord406b032009-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 Gregor35d81bb2009-02-09 23:23:08 +0000359
360
Douglas Gregor8e458f42009-02-09 18:46:07 +0000361Action::TypeTy *
362Sema::ActOnClassTemplateSpecialization(DeclTy *TemplateD,
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000363 SourceLocation TemplateLoc,
Douglas Gregor8e458f42009-02-09 18:46:07 +0000364 SourceLocation LAngleLoc,
Douglas Gregor6f37b582009-02-09 19:34:22 +0000365 ASTTemplateArgsPtr TemplateArgs,
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000366 SourceLocation *TemplateArgLocs,
Douglas Gregor8e458f42009-02-09 18:46:07 +0000367 SourceLocation RAngleLoc,
368 const CXXScopeSpec *SS) {
369 TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
370
Douglas Gregor35d81bb2009-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 Gregor8e458f42009-02-09 18:46:07 +0000377 // Yes, all class template specializations are just silly sugar for
378 // 'int'. Gotta problem wit dat?
Douglas Gregor6f37b582009-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 Gregor8e458f42009-02-09 18:46:07 +0000387}
388
Douglas Gregor35d81bb2009-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);
461 Diag((*Param)->getLocation(), diag::note_template_parameter_here);
462 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);
487 Diag((*Param)->getLocation(), diag::note_template_parameter_here);
488 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) {
558 return false;
559}
560
Douglas Gregord406b032009-02-06 22:42:48 +0000561/// \brief Determine whether the given template parameter lists are
562/// equivalent.
563///
564/// \param New The new template parameter list, typically written in the
565/// source code as part of a new template declaration.
566///
567/// \param Old The old template parameter list, typically found via
568/// name lookup of the template declared with this template parameter
569/// list.
570///
571/// \param Complain If true, this routine will produce a diagnostic if
572/// the template parameter lists are not equivalent.
573///
574/// \returns True if the template parameter lists are equal, false
575/// otherwise.
576bool
577Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
578 TemplateParameterList *Old,
579 bool Complain,
580 bool IsTemplateTemplateParm) {
581 if (Old->size() != New->size()) {
582 if (Complain) {
583 Diag(New->getTemplateLoc(), diag::err_template_param_list_different_arity)
584 << (New->size() > Old->size())
585 << IsTemplateTemplateParm
586 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
587 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
588 << IsTemplateTemplateParm
589 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
590 }
591
592 return false;
593 }
594
595 for (TemplateParameterList::iterator OldParm = Old->begin(),
596 OldParmEnd = Old->end(), NewParm = New->begin();
597 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
598 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
599 Diag((*NewParm)->getLocation(), diag::err_template_param_different_kind)
600 << IsTemplateTemplateParm;
601 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
602 << IsTemplateTemplateParm;
603 return false;
604 }
605
606 if (isa<TemplateTypeParmDecl>(*OldParm)) {
607 // Okay; all template type parameters are equivalent (since we
608 // know we're at the same depth/level).
609#ifndef NDEBUG
610 QualType OldParmType
611 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
612 QualType NewParmType
613 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
614 assert(Context.getCanonicalType(OldParmType) ==
615 Context.getCanonicalType(NewParmType) &&
616 "type parameter mismatch?");
617#endif
618 } else if (NonTypeTemplateParmDecl *OldNTTP
619 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
620 // The types of non-type template parameters must agree.
621 NonTypeTemplateParmDecl *NewNTTP
622 = cast<NonTypeTemplateParmDecl>(*NewParm);
623 if (Context.getCanonicalType(OldNTTP->getType()) !=
624 Context.getCanonicalType(NewNTTP->getType())) {
625 if (Complain) {
626 Diag(NewNTTP->getLocation(),
627 diag::err_template_nontype_parm_different_type)
628 << NewNTTP->getType()
629 << IsTemplateTemplateParm;
630 Diag(OldNTTP->getLocation(),
631 diag::note_template_nontype_parm_prev_declaration)
632 << OldNTTP->getType();
633 }
634 return false;
635 }
636 } else {
637 // The template parameter lists of template template
638 // parameters must agree.
639 // FIXME: Could we perform a faster "type" comparison here?
640 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
641 "Only template template parameters handled here");
642 TemplateTemplateParmDecl *OldTTP
643 = cast<TemplateTemplateParmDecl>(*OldParm);
644 TemplateTemplateParmDecl *NewTTP
645 = cast<TemplateTemplateParmDecl>(*NewParm);
646 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
647 OldTTP->getTemplateParameters(),
648 Complain,
649 /*IsTemplateTemplateParm=*/true))
650 return false;
651 }
652 }
653
654 return true;
655}
656
657/// \brief Check whether a template can be declared within this scope.
658///
659/// If the template declaration is valid in this scope, returns
660/// false. Otherwise, issues a diagnostic and returns true.
661bool
662Sema::CheckTemplateDeclScope(Scope *S,
663 MultiTemplateParamsArg &TemplateParameterLists) {
664 assert(TemplateParameterLists.size() > 0 && "Not a template");
665
666 // Find the nearest enclosing declaration scope.
667 while ((S->getFlags() & Scope::DeclScope) == 0 ||
668 (S->getFlags() & Scope::TemplateParamScope) != 0)
669 S = S->getParent();
670
671 TemplateParameterList *TemplateParams =
672 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
673 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
674 SourceRange TemplateRange
675 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
676
677 // C++ [temp]p2:
678 // A template-declaration can appear only as a namespace scope or
679 // class scope declaration.
680 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
681 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
682 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
683 return Diag(TemplateLoc, diag::err_template_linkage)
684 << TemplateRange;
685
686 Ctx = Ctx->getParent();
687 }
688
689 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
690 return false;
691
692 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
693 << TemplateRange;
694}