blob: 6b6a50130abfcfb6dea01c9daf99a7eaa0b42a58 [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 Gregor8e458f42009-02-09 18:46:07 +0000234Sema::OwningTemplateArgResult Sema::ActOnTypeTemplateArgument(TypeTy *Type) {
235 return Owned(new (Context) TemplateArg(QualType::getFromOpaquePtr(Type)));
236}
237
238Sema::OwningTemplateArgResult
239Sema::ActOnExprTemplateArgument(ExprArg Value) {
240 return Owned(new (Context) TemplateArg(static_cast<Expr *>(Value.release())));
241}
242
Douglas Gregord406b032009-02-06 22:42:48 +0000243Sema::DeclTy *
244Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
245 SourceLocation KWLoc, const CXXScopeSpec &SS,
246 IdentifierInfo *Name, SourceLocation NameLoc,
247 AttributeList *Attr,
248 MultiTemplateParamsArg TemplateParameterLists) {
249 assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
250 assert(TK != TK_Reference && "Can only declare or define class templates");
251
252 // Check that we can declare a template here.
253 if (CheckTemplateDeclScope(S, TemplateParameterLists))
254 return 0;
255
256 TagDecl::TagKind Kind;
257 switch (TagSpec) {
258 default: assert(0 && "Unknown tag type!");
259 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
260 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
261 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
262 }
263
264 // There is no such thing as an unnamed class template.
265 if (!Name) {
266 Diag(KWLoc, diag::err_template_unnamed_class);
267 return 0;
268 }
269
270 // Find any previous declaration with this name.
271 LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
272 true);
273 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
274 NamedDecl *PrevDecl = 0;
275 if (Previous.begin() != Previous.end())
276 PrevDecl = *Previous.begin();
277
278 DeclContext *SemanticContext = CurContext;
279 if (SS.isNotEmpty() && !SS.isInvalid()) {
280 SemanticContext = static_cast<DeclContext*>(SS.getScopeRep());
281
282 // FIXME: need to match up several levels of template parameter
283 // lists here.
284 }
285
286 // FIXME: member templates!
287 TemplateParameterList *TemplateParams
288 = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
289
290 // If there is a previous declaration with the same name, check
291 // whether this is a valid redeclaration.
292 ClassTemplateDecl *PrevClassTemplate
293 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
294 if (PrevClassTemplate) {
295 // Ensure that the template parameter lists are compatible.
296 if (!TemplateParameterListsAreEqual(TemplateParams,
297 PrevClassTemplate->getTemplateParameters(),
298 /*Complain=*/true))
299 return 0;
300
301 // C++ [temp.class]p4:
302 // In a redeclaration, partial specialization, explicit
303 // specialization or explicit instantiation of a class template,
304 // the class-key shall agree in kind with the original class
305 // template declaration (7.1.5.3).
306 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
307 if (PrevRecordDecl->getTagKind() != Kind) {
308 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
309 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
310 return 0;
311 }
312
313
314 // Check for redefinition of this class template.
315 if (TK == TK_Definition) {
316 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
317 Diag(NameLoc, diag::err_redefinition) << Name;
318 Diag(Def->getLocation(), diag::note_previous_definition);
319 // FIXME: Would it make sense to try to "forget" the previous
320 // definition, as part of error recovery?
321 return 0;
322 }
323 }
324 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
325 // Maybe we will complain about the shadowed template parameter.
326 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
327 // Just pretend that we didn't see the previous declaration.
328 PrevDecl = 0;
329 } else if (PrevDecl) {
330 // C++ [temp]p5:
331 // A class template shall not have the same name as any other
332 // template, class, function, object, enumeration, enumerator,
333 // namespace, or type in the same scope (3.3), except as specified
334 // in (14.5.4).
335 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
336 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
337 return 0;
338 }
339
340 // If we had a scope specifier, we better have a previous template
341 // declaration!
342
343 TagDecl *NewClass =
344 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
345 PrevClassTemplate?
346 PrevClassTemplate->getTemplatedDecl() : 0);
347
348 ClassTemplateDecl *NewTemplate
349 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
350 DeclarationName(Name), TemplateParams,
351 NewClass);
352
353 // Set the lexical context of these templates
354 NewClass->setLexicalDeclContext(CurContext);
355 NewTemplate->setLexicalDeclContext(CurContext);
356
357 if (TK == TK_Definition)
358 NewClass->startDefinition();
359
360 if (Attr)
361 ProcessDeclAttributeList(NewClass, Attr);
362
363 PushOnScopeChains(NewTemplate, S);
364
365 return NewTemplate;
366}
367
Douglas Gregor8e458f42009-02-09 18:46:07 +0000368Action::TypeTy *
369Sema::ActOnClassTemplateSpecialization(DeclTy *TemplateD,
370 SourceLocation LAngleLoc,
371 MultiTemplateArgsArg TemplateArgsIn,
372 SourceLocation RAngleLoc,
373 const CXXScopeSpec *SS) {
374 TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
375
376 // FIXME: Not happy about this. We should teach the parser to pass
377 // us opaque pointers + bools for template argument lists.
378 // FIXME: Also not happy about the fact that we leak these
379 // TemplateArg structures. Fixing the above will fix this, too.
380 llvm::SmallVector<uintptr_t, 16> Args;
381 llvm::SmallVector<bool, 16> ArgIsType;
382 unsigned NumArgs = TemplateArgsIn.size();
383 TemplateArg **TemplateArgs
384 = reinterpret_cast<TemplateArg **>(TemplateArgsIn.release());
385 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
386 if (Expr *ExprArg = TemplateArgs[Arg]->getAsExpr()) {
387 Args.push_back(reinterpret_cast<uintptr_t>(ExprArg));
388 ArgIsType.push_back(false);
389 } else {
390 QualType T = TemplateArgs[Arg]->getAsType();
391 Args.push_back(reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()));
392 ArgIsType.push_back(true);
393 }
394 }
395
396 // Yes, all class template specializations are just silly sugar for
397 // 'int'. Gotta problem wit dat?
398 return Context.getClassTemplateSpecializationType(Template, NumArgs,
399 &Args[0], &ArgIsType[0],
400 Context.IntTy)
401 .getAsOpaquePtr();
402}
403
Douglas Gregord406b032009-02-06 22:42:48 +0000404/// \brief Determine whether the given template parameter lists are
405/// equivalent.
406///
407/// \param New The new template parameter list, typically written in the
408/// source code as part of a new template declaration.
409///
410/// \param Old The old template parameter list, typically found via
411/// name lookup of the template declared with this template parameter
412/// list.
413///
414/// \param Complain If true, this routine will produce a diagnostic if
415/// the template parameter lists are not equivalent.
416///
417/// \returns True if the template parameter lists are equal, false
418/// otherwise.
419bool
420Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
421 TemplateParameterList *Old,
422 bool Complain,
423 bool IsTemplateTemplateParm) {
424 if (Old->size() != New->size()) {
425 if (Complain) {
426 Diag(New->getTemplateLoc(), diag::err_template_param_list_different_arity)
427 << (New->size() > Old->size())
428 << IsTemplateTemplateParm
429 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
430 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
431 << IsTemplateTemplateParm
432 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
433 }
434
435 return false;
436 }
437
438 for (TemplateParameterList::iterator OldParm = Old->begin(),
439 OldParmEnd = Old->end(), NewParm = New->begin();
440 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
441 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
442 Diag((*NewParm)->getLocation(), diag::err_template_param_different_kind)
443 << IsTemplateTemplateParm;
444 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
445 << IsTemplateTemplateParm;
446 return false;
447 }
448
449 if (isa<TemplateTypeParmDecl>(*OldParm)) {
450 // Okay; all template type parameters are equivalent (since we
451 // know we're at the same depth/level).
452#ifndef NDEBUG
453 QualType OldParmType
454 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
455 QualType NewParmType
456 = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
457 assert(Context.getCanonicalType(OldParmType) ==
458 Context.getCanonicalType(NewParmType) &&
459 "type parameter mismatch?");
460#endif
461 } else if (NonTypeTemplateParmDecl *OldNTTP
462 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
463 // The types of non-type template parameters must agree.
464 NonTypeTemplateParmDecl *NewNTTP
465 = cast<NonTypeTemplateParmDecl>(*NewParm);
466 if (Context.getCanonicalType(OldNTTP->getType()) !=
467 Context.getCanonicalType(NewNTTP->getType())) {
468 if (Complain) {
469 Diag(NewNTTP->getLocation(),
470 diag::err_template_nontype_parm_different_type)
471 << NewNTTP->getType()
472 << IsTemplateTemplateParm;
473 Diag(OldNTTP->getLocation(),
474 diag::note_template_nontype_parm_prev_declaration)
475 << OldNTTP->getType();
476 }
477 return false;
478 }
479 } else {
480 // The template parameter lists of template template
481 // parameters must agree.
482 // FIXME: Could we perform a faster "type" comparison here?
483 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
484 "Only template template parameters handled here");
485 TemplateTemplateParmDecl *OldTTP
486 = cast<TemplateTemplateParmDecl>(*OldParm);
487 TemplateTemplateParmDecl *NewTTP
488 = cast<TemplateTemplateParmDecl>(*NewParm);
489 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
490 OldTTP->getTemplateParameters(),
491 Complain,
492 /*IsTemplateTemplateParm=*/true))
493 return false;
494 }
495 }
496
497 return true;
498}
499
500/// \brief Check whether a template can be declared within this scope.
501///
502/// If the template declaration is valid in this scope, returns
503/// false. Otherwise, issues a diagnostic and returns true.
504bool
505Sema::CheckTemplateDeclScope(Scope *S,
506 MultiTemplateParamsArg &TemplateParameterLists) {
507 assert(TemplateParameterLists.size() > 0 && "Not a template");
508
509 // Find the nearest enclosing declaration scope.
510 while ((S->getFlags() & Scope::DeclScope) == 0 ||
511 (S->getFlags() & Scope::TemplateParamScope) != 0)
512 S = S->getParent();
513
514 TemplateParameterList *TemplateParams =
515 static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
516 SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
517 SourceRange TemplateRange
518 = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
519
520 // C++ [temp]p2:
521 // A template-declaration can appear only as a namespace scope or
522 // class scope declaration.
523 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
524 while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
525 if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
526 return Diag(TemplateLoc, diag::err_template_linkage)
527 << TemplateRange;
528
529 Ctx = Ctx->getParent();
530 }
531
532 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
533 return false;
534
535 return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
536 << TemplateRange;
537}