blob: 6c5f90afa5a0fd8bf4ab0ad6f15718962d4ce086 [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.
28Sema::DeclTy *Sema::isTemplateName(IdentifierInfo &II, Scope *S,
29 const CXXScopeSpec *SS) {
30 DeclContext *DC = 0;
Steve Naroffc349ee22009-01-29 00:07:50 +000031
Douglas Gregor2fa10442008-12-18 19:37:40 +000032 if (SS) {
33 if (SS->isInvalid())
34 return 0;
35 DC = static_cast<DeclContext*>(SS->getScopeRep());
36 }
Douglas Gregor09be81b2009-02-04 17:27:36 +000037 NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
Douglas Gregor2fa10442008-12-18 19:37:40 +000038
39 if (IIDecl) {
40 // FIXME: We need to represent templates via some kind of
41 // TemplateDecl, because what follows is a hack that only works in
42 // one specific case.
Douglas Gregor279272e2009-02-04 19:02:06 +000043 if (isa<TemplateDecl>(IIDecl))
44 return IIDecl;
45
Douglas Gregor2fa10442008-12-18 19:37:40 +000046 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
47 if (FD->getType()->isDependentType())
48 return FD;
49 } else if (OverloadedFunctionDecl *Ovl
50 = dyn_cast<OverloadedFunctionDecl>(IIDecl)) {
51 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
52 FEnd = Ovl->function_end();
53 F != FEnd; ++F) {
54 if ((*F)->getType()->isDependentType())
55 return Ovl;
56 }
57 }
Douglas Gregor2fa10442008-12-18 19:37:40 +000058 }
59 return 0;
60}
61
Douglas Gregordd861062008-12-05 18:15:24 +000062/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
63/// that the template parameter 'PrevDecl' is being shadowed by a new
64/// declaration at location Loc. Returns true to indicate that this is
65/// an error, and false otherwise.
66bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +000067 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregordd861062008-12-05 18:15:24 +000068
69 // Microsoft Visual C++ permits template parameters to be shadowed.
70 if (getLangOptions().Microsoft)
71 return false;
72
73 // C++ [temp.local]p4:
74 // A template-parameter shall not be redeclared within its
75 // scope (including nested scopes).
76 Diag(Loc, diag::err_template_param_shadow)
77 << cast<NamedDecl>(PrevDecl)->getDeclName();
78 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
79 return true;
80}
81
Douglas Gregor279272e2009-02-04 19:02:06 +000082/// AdjustDeclForTemplates - If the given decl happens to be a template, reset
83/// the parameter D to reference the templated declaration and return a pointer
84/// to the template declaration. Otherwise, do nothing to D and return null.
85TemplateDecl *Sema::AdjustDeclIfTemplate(DeclTy *&D)
86{
87 if(TemplateDecl *Temp = dyn_cast<TemplateDecl>(static_cast<Decl*>(D))) {
88 D = Temp->getTemplatedDecl();
89 return Temp;
90 }
91 return 0;
92}
93
Douglas Gregordd861062008-12-05 18:15:24 +000094/// ActOnTypeParameter - Called when a C++ template type parameter
95/// (e.g., "typename T") has been parsed. Typename specifies whether
96/// the keyword "typename" was used to declare the type parameter
97/// (otherwise, "class" was used), and KeyLoc is the location of the
98/// "class" or "typename" keyword. ParamName is the name of the
99/// parameter (NULL indicates an unnamed template parameter) and
100/// ParamName is the location of the parameter name (if any).
101/// If the type parameter has a default argument, it will be added
102/// later via ActOnTypeParameterDefault.
103Sema::DeclTy *Sema::ActOnTypeParameter(Scope *S, bool Typename,
104 SourceLocation KeyLoc,
105 IdentifierInfo *ParamName,
Douglas Gregor52473432008-12-24 02:52:09 +0000106 SourceLocation ParamNameLoc,
107 unsigned Depth, unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000108 assert(S->isTemplateParamScope() &&
109 "Template type parameter not in template parameter scope!");
110 bool Invalid = false;
111
112 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000113 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000114 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000115 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
116 PrevDecl);
117 }
118
Douglas Gregord406b032009-02-06 22:42:48 +0000119 SourceLocation Loc = ParamNameLoc;
120 if (!ParamName)
121 Loc = KeyLoc;
122
Douglas Gregordd861062008-12-05 18:15:24 +0000123 TemplateTypeParmDecl *Param
Douglas Gregord406b032009-02-06 22:42:48 +0000124 = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
Douglas Gregor279272e2009-02-04 19:02:06 +0000125 Depth, Position, ParamName, Typename);
Douglas Gregordd861062008-12-05 18:15:24 +0000126 if (Invalid)
127 Param->setInvalidDecl();
128
129 if (ParamName) {
130 // Add the template parameter into the current scope.
131 S->AddDecl(Param);
132 IdResolver.AddDecl(Param);
133 }
134
135 return Param;
136}
137
138/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
139/// template parameter (e.g., "int Size" in "template<int Size>
140/// class Array") has been parsed. S is the current scope and D is
141/// the parsed declarator.
Douglas Gregor52473432008-12-24 02:52:09 +0000142Sema::DeclTy *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
143 unsigned Depth,
144 unsigned Position) {
Douglas Gregordd861062008-12-05 18:15:24 +0000145 QualType T = GetTypeForDeclarator(D, S);
146
Douglas Gregor279272e2009-02-04 19:02:06 +0000147 assert(S->isTemplateParamScope() &&
148 "Non-type template parameter not in template parameter scope!");
Douglas Gregordd861062008-12-05 18:15:24 +0000149 bool Invalid = false;
150
151 IdentifierInfo *ParamName = D.getIdentifier();
152 if (ParamName) {
Douglas Gregor09be81b2009-02-04 17:27:36 +0000153 NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
Douglas Gregor2715a1f2008-12-08 18:40:42 +0000154 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregordd861062008-12-05 18:15:24 +0000155 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000156 PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +0000157 }
158
159 NonTypeTemplateParmDecl *Param
160 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor279272e2009-02-04 19:02:06 +0000161 Depth, Position, ParamName, T);
Douglas Gregordd861062008-12-05 18:15:24 +0000162 if (Invalid)
163 Param->setInvalidDecl();
164
165 if (D.getIdentifier()) {
166 // Add the template parameter into the current scope.
167 S->AddDecl(Param);
168 IdResolver.AddDecl(Param);
169 }
170 return Param;
171}
Douglas Gregor52473432008-12-24 02:52:09 +0000172
Douglas Gregor279272e2009-02-04 19:02:06 +0000173
174/// ActOnTemplateTemplateParameter - Called when a C++ template template
175/// parameter (e.g. T in template <template <typename> class T> class array)
176/// has been parsed. S is the current scope.
177Sema::DeclTy *Sema::ActOnTemplateTemplateParameter(Scope* S,
178 SourceLocation TmpLoc,
179 TemplateParamsTy *Params,
180 IdentifierInfo *Name,
181 SourceLocation NameLoc,
182 unsigned Depth,
183 unsigned Position)
184{
185 assert(S->isTemplateParamScope() &&
186 "Template template parameter not in template parameter scope!");
187
188 // Construct the parameter object.
189 TemplateTemplateParmDecl *Param =
190 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
191 Position, Name,
192 (TemplateParameterList*)Params);
193
194 // Make sure the parameter is valid.
195 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
196 // do anything yet. However, if the template parameter list or (eventual)
197 // default value is ever invalidated, that will propagate here.
198 bool Invalid = false;
199 if (Invalid) {
200 Param->setInvalidDecl();
201 }
202
203 // If the tt-param has a name, then link the identifier into the scope
204 // and lookup mechanisms.
205 if (Name) {
206 S->AddDecl(Param);
207 IdResolver.AddDecl(Param);
208 }
209
210 return Param;
211}
212
Douglas Gregor52473432008-12-24 02:52:09 +0000213/// ActOnTemplateParameterList - Builds a TemplateParameterList that
214/// contains the template parameters in Params/NumParams.
215Sema::TemplateParamsTy *
216Sema::ActOnTemplateParameterList(unsigned Depth,
217 SourceLocation ExportLoc,
218 SourceLocation TemplateLoc,
219 SourceLocation LAngleLoc,
220 DeclTy **Params, unsigned NumParams,
221 SourceLocation RAngleLoc) {
222 if (ExportLoc.isValid())
223 Diag(ExportLoc, diag::note_template_export_unsupported);
224
Douglas Gregord406b032009-02-06 22:42:48 +0000225 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
226 (Decl**)Params, NumParams, RAngleLoc);
Douglas Gregor52473432008-12-24 02:52:09 +0000227}
Douglas Gregor279272e2009-02-04 19:02:06 +0000228
Douglas Gregord406b032009-02-06 22:42:48 +0000229Sema::DeclTy *
230Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
231 SourceLocation KWLoc, const CXXScopeSpec &SS,
232 IdentifierInfo *Name, SourceLocation NameLoc,
233 AttributeList *Attr,
234 MultiTemplateParamsArg TemplateParameterLists) {
235 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
236 assert(TK != TK_Reference && "Can only declare or define class templates");
237
238 // Check that we can declare a template here.
239 if (CheckTemplateDeclScope(S, TemplateParameterLists))
240 return 0;
241
242 TagDecl::TagKind Kind;
243 switch (TagSpec) {
244 default: assert(0 && "Unknown tag type!");
245 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
246 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
247 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
248 }
249
250 // There is no such thing as an unnamed class template.
251 if (!Name) {
252 Diag(KWLoc, diag::err_template_unnamed_class);
253 return 0;
254 }
255
256 // Find any previous declaration with this name.
257 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
258 true);
259 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
260 NamedDecl *PrevDecl = 0;
261 if (Previous.begin() != Previous.end())
262 PrevDecl = *Previous.begin();
263
264 DeclContext *SemanticContext = CurContext;
265 if (SS.isNotEmpty() && !SS.isInvalid()) {
266 SemanticContext = static_cast<DeclContext*>(SS.getScopeRep());
267
268 // FIXME: need to match up several levels of template parameter
269 // lists here.
270 }
271
272 // FIXME: member templates!
273 TemplateParameterList *TemplateParams
274 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
275
276 // If there is a previous declaration with the same name, check
277 // whether this is a valid redeclaration.
278 ClassTemplateDecl *PrevClassTemplate
279 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
280 if (PrevClassTemplate) {
281 // Ensure that the template parameter lists are compatible.
282 if (!TemplateParameterListsAreEqual(TemplateParams,
283 PrevClassTemplate->getTemplateParameters(),
284 /*Complain=*/true))
285 return 0;
286
287 // C++ [temp.class]p4:
288 // In a redeclaration, partial specialization, explicit
289 // specialization or explicit instantiation of a class template,
290 // the class-key shall agree in kind with the original class
291 // template declaration (7.1.5.3).
292 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
293 if (PrevRecordDecl->getTagKind() != Kind) {
294 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
295 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
296 return 0;
297 }
298
299
300 // Check for redefinition of this class template.
301 if (TK == TK_Definition) {
302 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
303 Diag(NameLoc, diag::err_redefinition) << Name;
304 Diag(Def->getLocation(), diag::note_previous_definition);
305 // FIXME: Would it make sense to try to "forget" the previous
306 // definition, as part of error recovery?
307 return 0;
308 }
309 }
310 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
311 // Maybe we will complain about the shadowed template parameter.
312 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
313 // Just pretend that we didn't see the previous declaration.
314 PrevDecl = 0;
315 } else if (PrevDecl) {
316 // C++ [temp]p5:
317 // A class template shall not have the same name as any other
318 // template, class, function, object, enumeration, enumerator,
319 // namespace, or type in the same scope (3.3), except as specified
320 // in (14.5.4).
321 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
322 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
323 return 0;
324 }
325
326 // If we had a scope specifier, we better have a previous template
327 // declaration!
328
329 TagDecl *NewClass =
330 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
331 PrevClassTemplate?
332 PrevClassTemplate->getTemplatedDecl() : 0);
333
334 ClassTemplateDecl *NewTemplate
335 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
336 DeclarationName(Name), TemplateParams,
337 NewClass);
338
339 // Set the lexical context of these templates
340 NewClass->setLexicalDeclContext(CurContext);
341 NewTemplate->setLexicalDeclContext(CurContext);
342
343 if (TK == TK_Definition)
344 NewClass->startDefinition();
345
346 if (Attr)
347 ProcessDeclAttributeList(NewClass, Attr);
348
349 PushOnScopeChains(NewTemplate, S);
350
351 return NewTemplate;
352}
353
354/// \brief Determine whether the given template parameter lists are
355/// equivalent.
356///
357/// \param New The new template parameter list, typically written in the
358/// source code as part of a new template declaration.
359///
360/// \param Old The old template parameter list, typically found via
361/// name lookup of the template declared with this template parameter
362/// list.
363///
364/// \param Complain If true, this routine will produce a diagnostic if
365/// the template parameter lists are not equivalent.
366///
367/// \returns True if the template parameter lists are equal, false
368/// otherwise.
369bool
370Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
371 TemplateParameterList *Old,
372 bool Complain,
373 bool IsTemplateTemplateParm) {
374 if (Old->size() != New->size()) {
375 if (Complain) {
376 Diag(New->getTemplateLoc(), diag::err_template_param_list_different_arity)
377 << (New->size() > Old->size())
378 << IsTemplateTemplateParm
379 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
380 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
381 << IsTemplateTemplateParm
382 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
383 }
384
385 return false;
386 }
387
388 for (TemplateParameterList::iterator OldParm = Old->begin(),
389 OldParmEnd = Old->end(), NewParm = New->begin();
390 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
391 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
392 Diag((*NewParm)->getLocation(), diag::err_template_param_different_kind)
393 << IsTemplateTemplateParm;
394 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
395 << IsTemplateTemplateParm;
396 return false;
397 }
398
399 if (isa<TemplateTypeParmDecl>(*OldParm)) {
400 // Okay; all template type parameters are equivalent (since we
401 // know we're at the same depth/level).
402#ifndef NDEBUG
403 QualType OldParmType
404 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
405 QualType NewParmType
406 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
407 assert(Context.getCanonicalType(OldParmType) ==
408 Context.getCanonicalType(NewParmType) &&
409 "type parameter mismatch?");
410#endif
411 } else if (NonTypeTemplateParmDecl *OldNTTP
412 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
413 // The types of non-type template parameters must agree.
414 NonTypeTemplateParmDecl *NewNTTP
415 = cast<NonTypeTemplateParmDecl>(*NewParm);
416 if (Context.getCanonicalType(OldNTTP->getType()) !=
417 Context.getCanonicalType(NewNTTP->getType())) {
418 if (Complain) {
419 Diag(NewNTTP->getLocation(),
420 diag::err_template_nontype_parm_different_type)
421 << NewNTTP->getType()
422 << IsTemplateTemplateParm;
423 Diag(OldNTTP->getLocation(),
424 diag::note_template_nontype_parm_prev_declaration)
425 << OldNTTP->getType();
426 }
427 return false;
428 }
429 } else {
430 // The template parameter lists of template template
431 // parameters must agree.
432 // FIXME: Could we perform a faster "type" comparison here?
433 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
434 "Only template template parameters handled here");
435 TemplateTemplateParmDecl *OldTTP
436 = cast<TemplateTemplateParmDecl>(*OldParm);
437 TemplateTemplateParmDecl *NewTTP
438 = cast<TemplateTemplateParmDecl>(*NewParm);
439 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
440 OldTTP->getTemplateParameters(),
441 Complain,
442 /*IsTemplateTemplateParm=*/true))
443 return false;
444 }
445 }
446
447 return true;
448}
449
450/// \brief Check whether a template can be declared within this scope.
451///
452/// If the template declaration is valid in this scope, returns
453/// false. Otherwise, issues a diagnostic and returns true.
454bool
455Sema::CheckTemplateDeclScope(Scope *S,
456 MultiTemplateParamsArg &TemplateParameterLists) {
457 assert(TemplateParameterLists.size() > 0 && "Not a template");
458
459 // Find the nearest enclosing declaration scope.
460 while ((S->getFlags() & Scope::DeclScope) == 0 ||
461 (S->getFlags() & Scope::TemplateParamScope) != 0)
462 S = S->getParent();
463
464 TemplateParameterList *TemplateParams =
465 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
466 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
467 SourceRange TemplateRange
468 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
469
470 // C++ [temp]p2:
471 // A template-declaration can appear only as a namespace scope or
472 // class scope declaration.
473 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
474 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
475 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
476 return Diag(TemplateLoc, diag::err_template_linkage)
477 << TemplateRange;
478
479 Ctx = Ctx->getParent();
480 }
481
482 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
483 return false;
484
485 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
486 << TemplateRange;
487}