SemaTemplate.cpp revision d8c8c0991a09d7d1697b44b0342a48701bfd054c
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2
3//
4//                     The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
8//+//===----------------------------------------------------------------------===/
9
10//
11//  This file implements semantic analysis for C++ templates.
12//+//===----------------------------------------------------------------------===/
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/Parse/DeclSpec.h"
19#include "clang/Basic/LangOptions.h"
20
21using namespace clang;
22
23/// 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::TemplateNameKind Sema::isTemplateName(IdentifierInfo &II, Scope *S,
29                                            DeclTy *&Template,
30                                            const CXXScopeSpec *SS) {
31  NamedDecl *IIDecl = LookupParsedName(S, SS, &II, LookupOrdinaryName);
32
33  if (IIDecl) {
34    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    }
45
46    // FIXME: What follows is a gross hack.
47    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(IIDecl)) {
48      if (FD->getType()->isDependentType()) {
49        Template = FD;
50        return TNK_Function_template;
51      }
52    } 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) {
57        if ((*F)->getType()->isDependentType()) {
58          Template = Ovl;
59          return TNK_Function_template;
60        }
61      }
62    }
63  }
64  return TNK_Non_template;
65}
66
67/// 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) {
72  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
73
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
87/// 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
99/// 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,
111				       SourceLocation ParamNameLoc,
112                                       unsigned Depth, unsigned Position) {
113  assert(S->isTemplateParamScope() &&
114	 "Template type parameter not in template parameter scope!");
115  bool Invalid = false;
116
117  if (ParamName) {
118    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
119    if (PrevDecl && PrevDecl->isTemplateParameter())
120      Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
121							   PrevDecl);
122  }
123
124  SourceLocation Loc = ParamNameLoc;
125  if (!ParamName)
126    Loc = KeyLoc;
127
128  TemplateTypeParmDecl *Param
129    = TemplateTypeParmDecl::Create(Context, CurContext, Loc,
130                                   Depth, Position, ParamName, Typename);
131  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/// ActOnTypeParameterDefault - Adds a default argument (the type
144/// Default) to the given template type parameter (TypeParam).
145void Sema::ActOnTypeParameterDefault(DeclTy *TypeParam,
146                                     SourceLocation EqualLoc,
147                                     SourceLocation DefaultLoc,
148                                     TypeTy *DefaultT) {
149  TemplateTypeParmDecl *Parm
150    = cast<TemplateTypeParmDecl>(static_cast<Decl *>(TypeParam));
151  QualType Default = QualType::getFromOpaquePtr(DefaultT);
152
153  // C++ [temp.param]p14:
154  //   A template-parameter shall not be used in its own default argument.
155  // FIXME: Implement this check! Needs a recursive walk over the types.
156
157  // Check the template argument itself.
158  if (CheckTemplateArgument(Parm, Default, DefaultLoc)) {
159    Parm->setInvalidDecl();
160    return;
161  }
162
163  Parm->setDefaultArgument(Default, DefaultLoc, false);
164}
165
166/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
167/// template parameter (e.g., "int Size" in "template<int Size>
168/// class Array") has been parsed. S is the current scope and D is
169/// the parsed declarator.
170Sema::DeclTy *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
171                                                  unsigned Depth,
172                                                  unsigned Position) {
173  QualType T = GetTypeForDeclarator(D, S);
174
175  assert(S->isTemplateParamScope() &&
176         "Non-type template parameter not in template parameter scope!");
177  bool Invalid = false;
178
179  IdentifierInfo *ParamName = D.getIdentifier();
180  if (ParamName) {
181    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
182    if (PrevDecl && PrevDecl->isTemplateParameter())
183      Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
184                                                           PrevDecl);
185  }
186
187  // C++ [temp.param]p4:
188  //
189  // A non-type template-parameter shall have one of the following
190  // (optionally cv-qualified) types:
191  //
192  //       -- integral or enumeration type,
193  if (T->isIntegralType() || T->isEnumeralType() ||
194      //   -- pointer to object or pointer to function,
195      (T->isPointerType() &&
196       (T->getAsPointerType()->getPointeeType()->isObjectType() ||
197        T->getAsPointerType()->getPointeeType()->isFunctionType())) ||
198      //   -- reference to object or reference to function,
199      T->isReferenceType() ||
200      //   -- pointer to member.
201      T->isMemberPointerType() ||
202      // If T is a dependent type, we can't do the check now, so we
203      // assume that it is well-formed.
204      T->isDependentType()) {
205    // Okay: The template parameter is well-formed.
206  }
207  // C++ [temp.param]p8:
208  //
209  //   A non-type template-parameter of type "array of T" or
210  //   "function returning T" is adjusted to be of type "pointer to
211  //   T" or "pointer to function returning T", respectively.
212  else if (T->isArrayType())
213    // FIXME: Keep the type prior to promotion?
214    T = Context.getArrayDecayedType(T);
215  else if (T->isFunctionType())
216    // FIXME: Keep the type prior to promotion?
217    T = Context.getPointerType(T);
218  else {
219    Diag(D.getIdentifierLoc(), diag::err_template_nontype_parm_bad_type)
220      << T;
221    return 0;
222  }
223
224  NonTypeTemplateParmDecl *Param
225    = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
226                                      Depth, Position, ParamName, T);
227  if (Invalid)
228    Param->setInvalidDecl();
229
230  if (D.getIdentifier()) {
231    // Add the template parameter into the current scope.
232    S->AddDecl(Param);
233    IdResolver.AddDecl(Param);
234  }
235  return Param;
236}
237
238/// \brief Adds a default argument to the given non-type template
239/// parameter.
240void Sema::ActOnNonTypeTemplateParameterDefault(DeclTy *TemplateParamD,
241                                                SourceLocation EqualLoc,
242                                                ExprArg DefaultE) {
243  NonTypeTemplateParmDecl *TemplateParm
244    = cast<NonTypeTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
245  Expr *Default = static_cast<Expr *>(DefaultE.get());
246
247  // C++ [temp.param]p14:
248  //   A template-parameter shall not be used in its own default argument.
249  // FIXME: Implement this check! Needs a recursive walk over the types.
250
251  // Check the well-formedness of the default template argument.
252  if (CheckTemplateArgument(TemplateParm, Default)) {
253    TemplateParm->setInvalidDecl();
254    return;
255  }
256
257  TemplateParm->setDefaultArgument(static_cast<Expr *>(DefaultE.release()));
258}
259
260
261/// ActOnTemplateTemplateParameter - Called when a C++ template template
262/// parameter (e.g. T in template <template <typename> class T> class array)
263/// has been parsed. S is the current scope.
264Sema::DeclTy *Sema::ActOnTemplateTemplateParameter(Scope* S,
265                                                   SourceLocation TmpLoc,
266                                                   TemplateParamsTy *Params,
267                                                   IdentifierInfo *Name,
268                                                   SourceLocation NameLoc,
269                                                   unsigned Depth,
270                                                   unsigned Position)
271{
272  assert(S->isTemplateParamScope() &&
273         "Template template parameter not in template parameter scope!");
274
275  // Construct the parameter object.
276  TemplateTemplateParmDecl *Param =
277    TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth,
278                                     Position, Name,
279                                     (TemplateParameterList*)Params);
280
281  // Make sure the parameter is valid.
282  // FIXME: Decl object is not currently invalidated anywhere so this doesn't
283  // do anything yet. However, if the template parameter list or (eventual)
284  // default value is ever invalidated, that will propagate here.
285  bool Invalid = false;
286  if (Invalid) {
287    Param->setInvalidDecl();
288  }
289
290  // If the tt-param has a name, then link the identifier into the scope
291  // and lookup mechanisms.
292  if (Name) {
293    S->AddDecl(Param);
294    IdResolver.AddDecl(Param);
295  }
296
297  return Param;
298}
299
300/// \brief Adds a default argument to the given template template
301/// parameter.
302void Sema::ActOnTemplateTemplateParameterDefault(DeclTy *TemplateParamD,
303                                                 SourceLocation EqualLoc,
304                                                 ExprArg DefaultE) {
305  TemplateTemplateParmDecl *TemplateParm
306    = cast<TemplateTemplateParmDecl>(static_cast<Decl *>(TemplateParamD));
307
308  // Since a template-template parameter's default argument is an
309  // id-expression, it must be a DeclRefExpr.
310  DeclRefExpr *Default
311    = cast<DeclRefExpr>(static_cast<Expr *>(DefaultE.get()));
312
313  // C++ [temp.param]p14:
314  //   A template-parameter shall not be used in its own default argument.
315  // FIXME: Implement this check! Needs a recursive walk over the types.
316
317  // Check the well-formedness of the template argument.
318  if (!isa<TemplateDecl>(Default->getDecl())) {
319    Diag(Default->getSourceRange().getBegin(),
320         diag::err_template_arg_must_be_template)
321      << Default->getSourceRange();
322    TemplateParm->setInvalidDecl();
323    return;
324  }
325  if (CheckTemplateArgument(TemplateParm, Default)) {
326    TemplateParm->setInvalidDecl();
327    return;
328  }
329
330  DefaultE.release();
331  TemplateParm->setDefaultArgument(Default);
332}
333
334/// ActOnTemplateParameterList - Builds a TemplateParameterList that
335/// contains the template parameters in Params/NumParams.
336Sema::TemplateParamsTy *
337Sema::ActOnTemplateParameterList(unsigned Depth,
338                                 SourceLocation ExportLoc,
339                                 SourceLocation TemplateLoc,
340                                 SourceLocation LAngleLoc,
341                                 DeclTy **Params, unsigned NumParams,
342                                 SourceLocation RAngleLoc) {
343  if (ExportLoc.isValid())
344    Diag(ExportLoc, diag::note_template_export_unsupported);
345
346  return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
347                                       (Decl**)Params, NumParams, RAngleLoc);
348}
349
350Sema::DeclTy *
351Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
352                         SourceLocation KWLoc, const CXXScopeSpec &SS,
353                         IdentifierInfo *Name, SourceLocation NameLoc,
354                         AttributeList *Attr,
355                         MultiTemplateParamsArg TemplateParameterLists) {
356  assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
357  assert(TK != TK_Reference && "Can only declare or define class templates");
358  bool Invalid = false;
359
360  // Check that we can declare a template here.
361  if (CheckTemplateDeclScope(S, TemplateParameterLists))
362    return 0;
363
364  TagDecl::TagKind Kind;
365  switch (TagSpec) {
366  default: assert(0 && "Unknown tag type!");
367  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
368  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
369  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
370  }
371
372  // There is no such thing as an unnamed class template.
373  if (!Name) {
374    Diag(KWLoc, diag::err_template_unnamed_class);
375    return 0;
376  }
377
378  // Find any previous declaration with this name.
379  LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
380                                           true);
381  assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
382  NamedDecl *PrevDecl = 0;
383  if (Previous.begin() != Previous.end())
384    PrevDecl = *Previous.begin();
385
386  DeclContext *SemanticContext = CurContext;
387  if (SS.isNotEmpty() && !SS.isInvalid()) {
388    SemanticContext = static_cast<DeclContext*>(SS.getScopeRep());
389
390    // FIXME: need to match up several levels of template parameter
391    // lists here.
392  }
393
394  // FIXME: member templates!
395  TemplateParameterList *TemplateParams
396    = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
397
398  // If there is a previous declaration with the same name, check
399  // whether this is a valid redeclaration.
400  ClassTemplateDecl *PrevClassTemplate
401    = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
402  if (PrevClassTemplate) {
403    // Ensure that the template parameter lists are compatible.
404    if (!TemplateParameterListsAreEqual(TemplateParams,
405                                   PrevClassTemplate->getTemplateParameters(),
406                                        /*Complain=*/true))
407      return 0;
408
409    // C++ [temp.class]p4:
410    //   In a redeclaration, partial specialization, explicit
411    //   specialization or explicit instantiation of a class template,
412    //   the class-key shall agree in kind with the original class
413    //   template declaration (7.1.5.3).
414    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
415    if (PrevRecordDecl->getTagKind() != Kind) {
416      Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
417      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
418      return 0;
419    }
420
421
422    // Check for redefinition of this class template.
423    if (TK == TK_Definition) {
424      if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
425        Diag(NameLoc, diag::err_redefinition) << Name;
426        Diag(Def->getLocation(), diag::note_previous_definition);
427        // FIXME: Would it make sense to try to "forget" the previous
428        // definition, as part of error recovery?
429        return 0;
430      }
431    }
432  } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
433    // Maybe we will complain about the shadowed template parameter.
434    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
435    // Just pretend that we didn't see the previous declaration.
436    PrevDecl = 0;
437  } else if (PrevDecl) {
438    // C++ [temp]p5:
439    //   A class template shall not have the same name as any other
440    //   template, class, function, object, enumeration, enumerator,
441    //   namespace, or type in the same scope (3.3), except as specified
442    //   in (14.5.4).
443    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
444    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
445    return 0;
446  }
447
448  // Check the template parameter list of this declaration, possibly
449  // merging in the template parameter list from the previous class
450  // template declaration.
451  if (CheckTemplateParameterList(TemplateParams,
452            PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0))
453    Invalid = true;
454
455  // If we had a scope specifier, we better have a previous template
456  // declaration!
457
458  TagDecl *NewClass =
459    CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
460                          PrevClassTemplate?
461                            PrevClassTemplate->getTemplatedDecl() : 0);
462
463  ClassTemplateDecl *NewTemplate
464    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
465                                DeclarationName(Name), TemplateParams,
466                                NewClass);
467
468  // Set the lexical context of these templates
469  NewClass->setLexicalDeclContext(CurContext);
470  NewTemplate->setLexicalDeclContext(CurContext);
471
472  if (TK == TK_Definition)
473    NewClass->startDefinition();
474
475  if (Attr)
476    ProcessDeclAttributeList(NewClass, Attr);
477
478  PushOnScopeChains(NewTemplate, S);
479
480  if (Invalid) {
481    NewTemplate->setInvalidDecl();
482    NewClass->setInvalidDecl();
483  }
484  return NewTemplate;
485}
486
487/// \brief Checks the validity of a template parameter list, possibly
488/// considering the template parameter list from a previous
489/// declaration.
490///
491/// If an "old" template parameter list is provided, it must be
492/// equivalent (per TemplateParameterListsAreEqual) to the "new"
493/// template parameter list.
494///
495/// \param NewParams Template parameter list for a new template
496/// declaration. This template parameter list will be updated with any
497/// default arguments that are carried through from the previous
498/// template parameter list.
499///
500/// \param OldParams If provided, template parameter list from a
501/// previous declaration of the same template. Default template
502/// arguments will be merged from the old template parameter list to
503/// the new template parameter list.
504///
505/// \returns true if an error occurred, false otherwise.
506bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
507                                      TemplateParameterList *OldParams) {
508  bool Invalid = false;
509
510  // C++ [temp.param]p10:
511  //   The set of default template-arguments available for use with a
512  //   template declaration or definition is obtained by merging the
513  //   default arguments from the definition (if in scope) and all
514  //   declarations in scope in the same way default function
515  //   arguments are (8.3.6).
516  bool SawDefaultArgument = false;
517  SourceLocation PreviousDefaultArgLoc;
518
519  TemplateParameterList::iterator OldParam;
520  if (OldParams)
521    OldParam = OldParams->begin();
522
523  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
524                                    NewParamEnd = NewParams->end();
525       NewParam != NewParamEnd; ++NewParam) {
526    // Variables used to diagnose redundant default arguments
527    bool RedundantDefaultArg = false;
528    SourceLocation OldDefaultLoc;
529    SourceLocation NewDefaultLoc;
530
531    // Variables used to diagnose missing default arguments
532    bool MissingDefaultArg = false;
533
534    // Merge default arguments for template type parameters.
535    if (TemplateTypeParmDecl *NewTypeParm
536          = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
537      TemplateTypeParmDecl *OldTypeParm
538          = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
539
540      if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
541          NewTypeParm->hasDefaultArgument()) {
542        OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
543        NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
544        SawDefaultArgument = true;
545        RedundantDefaultArg = true;
546        PreviousDefaultArgLoc = NewDefaultLoc;
547      } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
548        // Merge the default argument from the old declaration to the
549        // new declaration.
550        SawDefaultArgument = true;
551        NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgument(),
552                                        OldTypeParm->getDefaultArgumentLoc(),
553                                        true);
554        PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
555      } else if (NewTypeParm->hasDefaultArgument()) {
556        SawDefaultArgument = true;
557        PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
558      } else if (SawDefaultArgument)
559        MissingDefaultArg = true;
560    }
561    // Merge default arguments for non-type template parameters
562    else if (NonTypeTemplateParmDecl *NewNonTypeParm
563               = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
564      NonTypeTemplateParmDecl *OldNonTypeParm
565        = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
566      if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
567          NewNonTypeParm->hasDefaultArgument()) {
568        OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
569        NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
570        SawDefaultArgument = true;
571        RedundantDefaultArg = true;
572        PreviousDefaultArgLoc = NewDefaultLoc;
573      } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
574        // Merge the default argument from the old declaration to the
575        // new declaration.
576        SawDefaultArgument = true;
577        // FIXME: We need to create a new kind of "default argument"
578        // expression that points to a previous template template
579        // parameter.
580        NewNonTypeParm->setDefaultArgument(
581                                        OldNonTypeParm->getDefaultArgument());
582        PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
583      } else if (NewNonTypeParm->hasDefaultArgument()) {
584        SawDefaultArgument = true;
585        PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
586      } else if (SawDefaultArgument)
587        MissingDefaultArg = true;
588    }
589    // Merge default arguments for template template parameters
590    else {
591      TemplateTemplateParmDecl *NewTemplateParm
592        = cast<TemplateTemplateParmDecl>(*NewParam);
593      TemplateTemplateParmDecl *OldTemplateParm
594        = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
595      if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
596          NewTemplateParm->hasDefaultArgument()) {
597        OldDefaultLoc = OldTemplateParm->getDefaultArgumentLoc();
598        NewDefaultLoc = NewTemplateParm->getDefaultArgumentLoc();
599        SawDefaultArgument = true;
600        RedundantDefaultArg = true;
601        PreviousDefaultArgLoc = NewDefaultLoc;
602      } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
603        // Merge the default argument from the old declaration to the
604        // new declaration.
605        SawDefaultArgument = true;
606        // FIXME: We need to create a new kind of "default argument"
607        // expression that points to a previous template template
608        // parameter.
609        NewTemplateParm->setDefaultArgument(
610                                        OldTemplateParm->getDefaultArgument());
611        PreviousDefaultArgLoc = OldTemplateParm->getDefaultArgumentLoc();
612      } else if (NewTemplateParm->hasDefaultArgument()) {
613        SawDefaultArgument = true;
614        PreviousDefaultArgLoc = NewTemplateParm->getDefaultArgumentLoc();
615      } else if (SawDefaultArgument)
616        MissingDefaultArg = true;
617    }
618
619    if (RedundantDefaultArg) {
620      // C++ [temp.param]p12:
621      //   A template-parameter shall not be given default arguments
622      //   by two different declarations in the same scope.
623      Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
624      Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
625      Invalid = true;
626    } else if (MissingDefaultArg) {
627      // C++ [temp.param]p11:
628      //   If a template-parameter has a default template-argument,
629      //   all subsequent template-parameters shall have a default
630      //   template-argument supplied.
631      Diag((*NewParam)->getLocation(),
632           diag::err_template_param_default_arg_missing);
633      Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
634      Invalid = true;
635    }
636
637    // If we have an old template parameter list that we're merging
638    // in, move on to the next parameter.
639    if (OldParams)
640      ++OldParam;
641  }
642
643  return Invalid;
644}
645
646Action::TypeTy *
647Sema::ActOnClassTemplateSpecialization(DeclTy *TemplateD,
648                                       SourceLocation TemplateLoc,
649                                       SourceLocation LAngleLoc,
650                                       ASTTemplateArgsPtr TemplateArgs,
651                                       SourceLocation *TemplateArgLocs,
652                                       SourceLocation RAngleLoc,
653                                       const CXXScopeSpec *SS) {
654  TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
655
656  // Check that the template argument list is well-formed for this
657  // template.
658  if (!CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
659                                 TemplateArgs, TemplateArgLocs, RAngleLoc))
660    return 0;
661
662  // Yes, all class template specializations are just silly sugar for
663  // 'int'. Gotta problem wit dat?
664  QualType Result
665    = Context.getClassTemplateSpecializationType(Template,
666                                                 TemplateArgs.size(),
667                    reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()),
668                                                 TemplateArgs.getArgIsType(),
669                                                 Context.IntTy);
670  TemplateArgs.release();
671  return Result.getAsOpaquePtr();
672}
673
674/// \brief Check that the given template argument list is well-formed
675/// for specializing the given template.
676bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
677                                     SourceLocation TemplateLoc,
678                                     SourceLocation LAngleLoc,
679                                     ASTTemplateArgsPtr& Args,
680                                     SourceLocation *TemplateArgLocs,
681                                     SourceLocation RAngleLoc) {
682  TemplateParameterList *Params = Template->getTemplateParameters();
683  unsigned NumParams = Params->size();
684  unsigned NumArgs = Args.size();
685  bool Invalid = false;
686
687  if (NumArgs > NumParams ||
688      NumArgs < NumParams /*FIXME: default arguments! */) {
689    // FIXME: point at either the first arg beyond what we can handle,
690    // or the '>', depending on whether we have too many or too few
691    // arguments.
692    SourceRange Range;
693    if (NumArgs > NumParams)
694      Range = SourceRange(TemplateArgLocs[NumParams], RAngleLoc);
695    Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
696      << (NumArgs > NumParams)
697      << (isa<ClassTemplateDecl>(Template)? 0 :
698          isa<FunctionTemplateDecl>(Template)? 1 :
699          isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
700      << Template << Range;
701
702    Invalid = true;
703  }
704
705  // C++ [temp.arg]p1:
706  //   [...] The type and form of each template-argument specified in
707  //   a template-id shall match the type and form specified for the
708  //   corresponding parameter declared by the template in its
709  //   template-parameter-list.
710  unsigned ArgIdx = 0;
711  for (TemplateParameterList::iterator Param = Params->begin(),
712                                       ParamEnd = Params->end();
713       Param != ParamEnd; ++Param, ++ArgIdx) {
714    // Decode the template argument
715    QualType ArgType;
716    Expr *ArgExpr = 0;
717    SourceLocation ArgLoc;
718    if (ArgIdx >= NumArgs) {
719      // FIXME: Get the default argument here, which might
720      // (eventually) require instantiation.
721      break;
722    } else
723      ArgLoc = TemplateArgLocs[ArgIdx];
724
725    if (Args.getArgIsType()[ArgIdx])
726      ArgType = QualType::getFromOpaquePtr(Args.getArgs()[ArgIdx]);
727    else
728      ArgExpr = reinterpret_cast<Expr *>(Args.getArgs()[ArgIdx]);
729
730    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
731      // Check template type parameters.
732      if (!ArgType.isNull()) {
733        if (!CheckTemplateArgument(TTP, ArgType, ArgLoc))
734          Invalid = true;
735        continue;
736      }
737
738      // C++ [temp.arg.type]p1:
739      //   A template-argument for a template-parameter which is a
740      //   type shall be a type-id.
741
742      // We have a template type parameter but the template argument
743      // is an expression.
744      Diag(ArgExpr->getSourceRange().getBegin(),
745           diag::err_template_arg_must_be_type);
746      Diag((*Param)->getLocation(), diag::note_template_param_here);
747      Invalid = true;
748    } else if (NonTypeTemplateParmDecl *NTTP
749                 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
750      // Check non-type template parameters.
751      if (ArgExpr) {
752        if (!CheckTemplateArgument(NTTP, ArgExpr))
753          Invalid = true;
754        continue;
755      }
756
757      // We have a non-type template parameter but the template
758      // argument is a type.
759
760      // C++ [temp.arg]p2:
761      //   In a template-argument, an ambiguity between a type-id and
762      //   an expression is resolved to a type-id, regardless of the
763      //   form of the corresponding template-parameter.
764      //
765      // We warn specifically about this case, since it can be rather
766      // confusing for users.
767      if (ArgType->isFunctionType())
768        Diag(ArgLoc, diag::err_template_arg_nontype_ambig)
769          << ArgType;
770      else
771        Diag(ArgLoc, diag::err_template_arg_must_be_expr);
772      Diag((*Param)->getLocation(), diag::note_template_param_here);
773      Invalid = true;
774    } else {
775      // Check template template parameters.
776      TemplateTemplateParmDecl *TempParm
777        = cast<TemplateTemplateParmDecl>(*Param);
778
779      if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
780          isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
781        if (!CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
782          Invalid = true;
783        continue;
784      }
785
786      // We have a template template parameter but the template
787      // argument does not refer to a template.
788      Diag(ArgLoc, diag::err_template_arg_must_be_template);
789      Invalid = true;
790    }
791  }
792
793  return Invalid;
794}
795
796/// \brief Check a template argument against its corresponding
797/// template type parameter.
798///
799/// This routine implements the semantics of C++ [temp.arg.type]. It
800/// returns true if an error occurred, and false otherwise.
801bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
802                                 QualType Arg, SourceLocation ArgLoc) {
803  // C++ [temp.arg.type]p2:
804  //   A local type, a type with no linkage, an unnamed type or a type
805  //   compounded from any of these types shall not be used as a
806  //   template-argument for a template type-parameter.
807  //
808  // FIXME: Perform the recursive and no-linkage type checks.
809  const TagType *Tag = 0;
810  if (const EnumType *EnumT = Arg->getAsEnumType())
811    Tag = EnumT;
812  else if (const RecordType *RecordT = Arg->getAsRecordType())
813    Tag = RecordT;
814  if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
815    return Diag(ArgLoc, diag::err_template_arg_local_type)
816      << QualType(Tag, 0);
817  else if (Tag && !Tag->getDecl()->getDeclName()) {
818    Diag(ArgLoc, diag::err_template_arg_unnamed_type);
819    Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
820    return true;
821  }
822
823  return false;
824}
825
826/// \brief Check a template argument against its corresponding
827/// non-type template parameter.
828///
829/// This routine implements the semantics of C++ [temp.arg.nontype].
830/// It returns true if an error occurred, and false otherwise.
831bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
832                                 Expr *&Arg) {
833  // If either the parameter has a dependent type or the argument is
834  // type-dependent, there's nothing we can check now.
835  if (Param->getType()->isDependentType() || Arg->isTypeDependent())
836    return false;
837
838  // C++ [temp.arg.nontype]p5:
839  //   The following conversions are performed on each expression used
840  //   as a non-type template-argument. If a non-type
841  //   template-argument cannot be converted to the type of the
842  //   corresponding template-parameter then the program is
843  //   ill-formed.
844  //
845  //     -- for a non-type template-parameter of integral or
846  //        enumeration type, integral promotions (4.5) and integral
847  //        conversions (4.7) are applied.
848  QualType ParamType = Param->getType();
849  QualType ArgType = Arg->getType();
850  if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
851    // C++ [temp.arg.nontype]p1:
852    //   A template-argument for a non-type, non-template
853    //   template-parameter shall be one of:
854    //
855    //     -- an integral constant-expression of integral or enumeration
856    //        type; or
857    //     -- the name of a non-type template-parameter; or
858    SourceLocation NonConstantLoc;
859    if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
860      Diag(Arg->getSourceRange().getBegin(),
861           diag::err_template_arg_not_integral_or_enumeral)
862        << ArgType << Arg->getSourceRange();
863      Diag(Param->getLocation(), diag::note_template_param_here);
864      return true;
865    } else if (!Arg->isValueDependent() &&
866               !Arg->isIntegerConstantExpr(Context, &NonConstantLoc)) {
867      Diag(NonConstantLoc, diag::err_template_arg_not_ice)
868        << ArgType << Arg->getSourceRange();
869      return true;
870    }
871
872    // FIXME: We need some way to more easily get the unqualified form
873    // of the types without going all the way to the
874    // canonical type.
875    if (Context.getCanonicalType(ParamType).getCVRQualifiers())
876      ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType();
877    if (Context.getCanonicalType(ArgType).getCVRQualifiers())
878      ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType();
879
880    // Try to convert the argument to the parameter's type.
881    if (ParamType == ArgType) {
882      // Okay: no conversion necessary
883    } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
884               !ParamType->isEnumeralType()) {
885      // This is an integral promotion or conversion.
886      ImpCastExprToType(Arg, ParamType);
887    } else {
888      // We can't perform this conversion.
889      Diag(Arg->getSourceRange().getBegin(),
890           diag::err_template_arg_not_convertible)
891        << Arg->getType() << Param->getType() << Arg->getSourceRange();
892      Diag(Param->getLocation(), diag::note_template_param_here);
893      return true;
894    }
895
896    return false;
897  }
898
899  if (const PointerType *ParamPtrType = ParamType->getAsPointerType()) {
900    if (ParamPtrType->getPointeeType()->isObjectType()) {
901      // -- for a non-type template-parameter of type pointer to
902      //    object, qualification conversions (4.4) and the
903      //    array-to-pointer conversion (4.2) are applied.
904      if (ArgType->isArrayType()) {
905        ArgType = Context.getArrayDecayedType(ArgType);
906        ImpCastExprToType(Arg, ArgType);
907      }
908
909      if (IsQualificationConversion(ArgType, ParamType)) {
910        ArgType = ParamType;
911        ImpCastExprToType(Arg, ParamType);
912      }
913
914      if (!hasSameUnqualifiedType(ArgType, ParamType)) {
915        // We can't perform this conversion.
916        Diag(Arg->getSourceRange().getBegin(),
917             diag::err_template_arg_not_convertible)
918          << Arg->getType() << Param->getType() << Arg->getSourceRange();
919        Diag(Param->getLocation(), diag::note_template_param_here);
920        return true;
921      }
922
923      // FIXME: Check the restrictions in p1!
924      return false;
925    }
926
927    assert(ParamPtrType->getPointeeType()->isFunctionType() &&
928           "Only function pointers remain");
929    //   -- For a non-type template-parameter of type pointer to
930    //      function, only the function-to-pointer conversion (4.3) is
931    //      applied. If the template-argument represents a set of
932    //      overloaded functions (or a pointer to such), the matching
933    //      function is selected from the set (13.4).
934    if (hasSameUnqualifiedType(ArgType, ParamType)) {
935      // We don't have to do anything: the types already match.
936    }
937    else if (ArgType->isFunctionType()) {
938      ArgType = Context.getPointerType(ArgType);
939      ImpCastExprToType(Arg, ArgType);
940    } else if (FunctionDecl *Fn
941                 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) {
942      FixOverloadedFunctionReference(Arg, Fn);
943      ArgType = Arg->getType();
944      if (ArgType->isFunctionType()) {
945        ArgType = Context.getPointerType(Arg->getType());
946        ImpCastExprToType(Arg, ArgType);
947      }
948    }
949
950    if (!hasSameUnqualifiedType(ArgType, ParamType)) {
951      // We can't perform this conversion.
952      Diag(Arg->getSourceRange().getBegin(),
953           diag::err_template_arg_not_convertible)
954        << Arg->getType() << Param->getType() << Arg->getSourceRange();
955      Diag(Param->getLocation(), diag::note_template_param_here);
956      return true;
957    }
958
959    // FIXME: Check the restrictions in p1!
960    return false;
961  }
962
963  if (const ReferenceType *ParamRefType = ParamType->getAsReferenceType()) {
964    if (ParamRefType->getPointeeType()->isObjectType()) {
965      // -- For a non-type template-parameter of type reference to
966      //    object, no conversions apply. The type referred to by the
967      //    reference may be more cv-qualified than the (otherwise
968      //    identical) type of the template-argument. The
969      //    template-parameter is bound directly to the
970      //    template-argument, which must be an lvalue.
971      if (!hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) {
972        Diag(Arg->getSourceRange().getBegin(),
973             diag::err_template_arg_no_ref_bind)
974          << Param->getType() << Arg->getType()
975          << Arg->getSourceRange();
976        Diag(Param->getLocation(), diag::note_template_param_here);
977        return true;
978      }
979
980      unsigned ParamQuals
981        = Context.getCanonicalType(ParamType).getCVRQualifiers();
982      unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers();
983
984      if ((ParamQuals | ArgQuals) != ParamQuals) {
985        Diag(Arg->getSourceRange().getBegin(),
986             diag::err_template_arg_ref_bind_ignores_quals)
987          << Param->getType() << Arg->getType()
988          << Arg->getSourceRange();
989        Diag(Param->getLocation(), diag::note_template_param_here);
990        return true;
991      }
992
993      // FIXME: Check the restrictions in p1!
994      // CheckAddressConstantExpression(Lvalue) can be modified to do
995      // this.
996      return false;
997    }
998  }
999
1000  // FIXME: p5 has a lot more checks to perform!
1001
1002  return false;
1003}
1004
1005/// \brief Check a template argument against its corresponding
1006/// template template parameter.
1007///
1008/// This routine implements the semantics of C++ [temp.arg.template].
1009/// It returns true if an error occurred, and false otherwise.
1010bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
1011                                 DeclRefExpr *Arg) {
1012  assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
1013  TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
1014
1015  // C++ [temp.arg.template]p1:
1016  //   A template-argument for a template template-parameter shall be
1017  //   the name of a class template, expressed as id-expression. Only
1018  //   primary class templates are considered when matching the
1019  //   template template argument with the corresponding parameter;
1020  //   partial specializations are not considered even if their
1021  //   parameter lists match that of the template template parameter.
1022  if (!isa<ClassTemplateDecl>(Template)) {
1023    assert(isa<FunctionTemplateDecl>(Template) &&
1024           "Only function templates are possible here");
1025    Diag(Arg->getSourceRange().getBegin(), diag::note_template_arg_refers_here)
1026      << Template;
1027  }
1028
1029  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
1030                                         Param->getTemplateParameters(),
1031                                         true, true,
1032                                         Arg->getSourceRange().getBegin());
1033}
1034
1035/// \brief Determine whether the given template parameter lists are
1036/// equivalent.
1037///
1038/// \param New  The new template parameter list, typically written in the
1039/// source code as part of a new template declaration.
1040///
1041/// \param Old  The old template parameter list, typically found via
1042/// name lookup of the template declared with this template parameter
1043/// list.
1044///
1045/// \param Complain  If true, this routine will produce a diagnostic if
1046/// the template parameter lists are not equivalent.
1047///
1048/// \param IsTemplateTemplateParm  If true, this routine is being
1049/// called to compare the template parameter lists of a template
1050/// template parameter.
1051///
1052/// \param TemplateArgLoc If this source location is valid, then we
1053/// are actually checking the template parameter list of a template
1054/// argument (New) against the template parameter list of its
1055/// corresponding template template parameter (Old). We produce
1056/// slightly different diagnostics in this scenario.
1057///
1058/// \returns True if the template parameter lists are equal, false
1059/// otherwise.
1060bool
1061Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
1062                                     TemplateParameterList *Old,
1063                                     bool Complain,
1064                                     bool IsTemplateTemplateParm,
1065                                     SourceLocation TemplateArgLoc) {
1066  if (Old->size() != New->size()) {
1067    if (Complain) {
1068      unsigned NextDiag = diag::err_template_param_list_different_arity;
1069      if (TemplateArgLoc.isValid()) {
1070        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1071        NextDiag = diag::note_template_param_list_different_arity;
1072      }
1073      Diag(New->getTemplateLoc(), NextDiag)
1074          << (New->size() > Old->size())
1075          << IsTemplateTemplateParm
1076          << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
1077      Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
1078        << IsTemplateTemplateParm
1079        << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
1080    }
1081
1082    return false;
1083  }
1084
1085  for (TemplateParameterList::iterator OldParm = Old->begin(),
1086         OldParmEnd = Old->end(), NewParm = New->begin();
1087       OldParm != OldParmEnd; ++OldParm, ++NewParm) {
1088    if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
1089      unsigned NextDiag = diag::err_template_param_different_kind;
1090      if (TemplateArgLoc.isValid()) {
1091        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
1092        NextDiag = diag::note_template_param_different_kind;
1093      }
1094      Diag((*NewParm)->getLocation(), NextDiag)
1095        << IsTemplateTemplateParm;
1096      Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
1097        << IsTemplateTemplateParm;
1098      return false;
1099    }
1100
1101    if (isa<TemplateTypeParmDecl>(*OldParm)) {
1102      // Okay; all template type parameters are equivalent (since we
1103      // know we're at the same index).
1104#if 0
1105      // FIXME: Enable this code in debug mode *after* we properly go
1106      // through and "instantiate" the template parameter lists of
1107      // template template parameters. It's only after this
1108      // instantiation that (1) any dependent types within the
1109      // template parameter list of the template template parameter
1110      // can be checked, and (2) the template type parameter depths
1111      // will match up.
1112      QualType OldParmType
1113        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
1114      QualType NewParmType
1115        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
1116      assert(Context.getCanonicalType(OldParmType) ==
1117             Context.getCanonicalType(NewParmType) &&
1118             "type parameter mismatch?");
1119#endif
1120    } else if (NonTypeTemplateParmDecl *OldNTTP
1121                 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
1122      // The types of non-type template parameters must agree.
1123      NonTypeTemplateParmDecl *NewNTTP
1124        = cast<NonTypeTemplateParmDecl>(*NewParm);
1125      if (Context.getCanonicalType(OldNTTP->getType()) !=
1126            Context.getCanonicalType(NewNTTP->getType())) {
1127        if (Complain) {
1128          unsigned NextDiag = diag::err_template_nontype_parm_different_type;
1129          if (TemplateArgLoc.isValid()) {
1130            Diag(TemplateArgLoc,
1131                 diag::err_template_arg_template_params_mismatch);
1132            NextDiag = diag::note_template_nontype_parm_different_type;
1133          }
1134          Diag(NewNTTP->getLocation(), NextDiag)
1135            << NewNTTP->getType()
1136            << IsTemplateTemplateParm;
1137          Diag(OldNTTP->getLocation(),
1138               diag::note_template_nontype_parm_prev_declaration)
1139            << OldNTTP->getType();
1140        }
1141        return false;
1142      }
1143    } else {
1144      // The template parameter lists of template template
1145      // parameters must agree.
1146      // FIXME: Could we perform a faster "type" comparison here?
1147      assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
1148             "Only template template parameters handled here");
1149      TemplateTemplateParmDecl *OldTTP
1150        = cast<TemplateTemplateParmDecl>(*OldParm);
1151      TemplateTemplateParmDecl *NewTTP
1152        = cast<TemplateTemplateParmDecl>(*NewParm);
1153      if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
1154                                          OldTTP->getTemplateParameters(),
1155                                          Complain,
1156                                          /*IsTemplateTemplateParm=*/true,
1157                                          TemplateArgLoc))
1158        return false;
1159    }
1160  }
1161
1162  return true;
1163}
1164
1165/// \brief Check whether a template can be declared within this scope.
1166///
1167/// If the template declaration is valid in this scope, returns
1168/// false. Otherwise, issues a diagnostic and returns true.
1169bool
1170Sema::CheckTemplateDeclScope(Scope *S,
1171                             MultiTemplateParamsArg &TemplateParameterLists) {
1172  assert(TemplateParameterLists.size() > 0 && "Not a template");
1173
1174  // Find the nearest enclosing declaration scope.
1175  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1176         (S->getFlags() & Scope::TemplateParamScope) != 0)
1177    S = S->getParent();
1178
1179  TemplateParameterList *TemplateParams =
1180    static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
1181  SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
1182  SourceRange TemplateRange
1183    = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
1184
1185  // C++ [temp]p2:
1186  //   A template-declaration can appear only as a namespace scope or
1187  //   class scope declaration.
1188  DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
1189  while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
1190    if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
1191      return Diag(TemplateLoc, diag::err_template_linkage)
1192        << TemplateRange;
1193
1194    Ctx = Ctx->getParent();
1195  }
1196
1197  if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
1198    return false;
1199
1200  return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
1201    << TemplateRange;
1202}
1203