SemaTemplate.cpp revision dd0574e76439f31c02ba54bd7708725176f9531f
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/// 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.
147Sema::DeclTy *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
148                                                  unsigned Depth,
149                                                  unsigned Position) {
150  QualType T = GetTypeForDeclarator(D, S);
151
152  assert(S->isTemplateParamScope() &&
153         "Non-type template parameter not in template parameter scope!");
154  bool Invalid = false;
155
156  IdentifierInfo *ParamName = D.getIdentifier();
157  if (ParamName) {
158    NamedDecl *PrevDecl = LookupName(S, ParamName, LookupTagName);
159    if (PrevDecl && PrevDecl->isTemplateParameter())
160      Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
161                                                           PrevDecl);
162  }
163
164  NonTypeTemplateParmDecl *Param
165    = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(),
166                                      Depth, Position, ParamName, T);
167  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}
177
178
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
218/// 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
230  return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
231                                       (Decl**)Params, NumParams, RAngleLoc);
232}
233
234Sema::DeclTy *
235Sema::ActOnClassTemplate(Scope *S, unsigned TagSpec, TagKind TK,
236                         SourceLocation KWLoc, const CXXScopeSpec &SS,
237                         IdentifierInfo *Name, SourceLocation NameLoc,
238                         AttributeList *Attr,
239                         MultiTemplateParamsArg TemplateParameterLists) {
240  assert(TemplateParameterLists.size() > 0 && "No template parameter lists?");
241  assert(TK != TK_Reference && "Can only declare or define class templates");
242
243  // Check that we can declare a template here.
244  if (CheckTemplateDeclScope(S, TemplateParameterLists))
245    return 0;
246
247  TagDecl::TagKind Kind;
248  switch (TagSpec) {
249  default: assert(0 && "Unknown tag type!");
250  case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
251  case DeclSpec::TST_union:  Kind = TagDecl::TK_union; break;
252  case DeclSpec::TST_class:  Kind = TagDecl::TK_class; break;
253  }
254
255  // There is no such thing as an unnamed class template.
256  if (!Name) {
257    Diag(KWLoc, diag::err_template_unnamed_class);
258    return 0;
259  }
260
261  // Find any previous declaration with this name.
262  LookupResult Previous = LookupParsedName(S, &SS, Name, LookupOrdinaryName,
263                                           true);
264  assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?");
265  NamedDecl *PrevDecl = 0;
266  if (Previous.begin() != Previous.end())
267    PrevDecl = *Previous.begin();
268
269  DeclContext *SemanticContext = CurContext;
270  if (SS.isNotEmpty() && !SS.isInvalid()) {
271    SemanticContext = static_cast<DeclContext*>(SS.getScopeRep());
272
273    // FIXME: need to match up several levels of template parameter
274    // lists here.
275  }
276
277  // FIXME: member templates!
278  TemplateParameterList *TemplateParams
279    = static_cast<TemplateParameterList *>(*TemplateParameterLists.release());
280
281  // If there is a previous declaration with the same name, check
282  // whether this is a valid redeclaration.
283  ClassTemplateDecl *PrevClassTemplate
284    = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
285  if (PrevClassTemplate) {
286    // Ensure that the template parameter lists are compatible.
287    if (!TemplateParameterListsAreEqual(TemplateParams,
288                                   PrevClassTemplate->getTemplateParameters(),
289                                        /*Complain=*/true))
290      return 0;
291
292    // C++ [temp.class]p4:
293    //   In a redeclaration, partial specialization, explicit
294    //   specialization or explicit instantiation of a class template,
295    //   the class-key shall agree in kind with the original class
296    //   template declaration (7.1.5.3).
297    RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
298    if (PrevRecordDecl->getTagKind() != Kind) {
299      Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
300      Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
301      return 0;
302    }
303
304
305    // Check for redefinition of this class template.
306    if (TK == TK_Definition) {
307      if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) {
308        Diag(NameLoc, diag::err_redefinition) << Name;
309        Diag(Def->getLocation(), diag::note_previous_definition);
310        // FIXME: Would it make sense to try to "forget" the previous
311        // definition, as part of error recovery?
312        return 0;
313      }
314    }
315  } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
316    // Maybe we will complain about the shadowed template parameter.
317    DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
318    // Just pretend that we didn't see the previous declaration.
319    PrevDecl = 0;
320  } else if (PrevDecl) {
321    // C++ [temp]p5:
322    //   A class template shall not have the same name as any other
323    //   template, class, function, object, enumeration, enumerator,
324    //   namespace, or type in the same scope (3.3), except as specified
325    //   in (14.5.4).
326    Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
327    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
328    return 0;
329  }
330
331  // If we had a scope specifier, we better have a previous template
332  // declaration!
333
334  TagDecl *NewClass =
335    CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name,
336                          PrevClassTemplate?
337                            PrevClassTemplate->getTemplatedDecl() : 0);
338
339  ClassTemplateDecl *NewTemplate
340    = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
341                                DeclarationName(Name), TemplateParams,
342                                NewClass);
343
344  // Set the lexical context of these templates
345  NewClass->setLexicalDeclContext(CurContext);
346  NewTemplate->setLexicalDeclContext(CurContext);
347
348  if (TK == TK_Definition)
349    NewClass->startDefinition();
350
351  if (Attr)
352    ProcessDeclAttributeList(NewClass, Attr);
353
354  PushOnScopeChains(NewTemplate, S);
355
356  return NewTemplate;
357}
358
359
360
361Action::TypeTy *
362Sema::ActOnClassTemplateSpecialization(DeclTy *TemplateD,
363                                       SourceLocation TemplateLoc,
364                                       SourceLocation LAngleLoc,
365                                       ASTTemplateArgsPtr TemplateArgs,
366                                       SourceLocation *TemplateArgLocs,
367                                       SourceLocation RAngleLoc,
368                                       const CXXScopeSpec *SS) {
369  TemplateDecl *Template = cast<TemplateDecl>(static_cast<Decl *>(TemplateD));
370
371  // Check that the template argument list is well-formed for this
372  // template.
373  if (!CheckTemplateArgumentList(Template, TemplateLoc, LAngleLoc,
374                                 TemplateArgs, TemplateArgLocs, RAngleLoc))
375    return 0;
376
377  // Yes, all class template specializations are just silly sugar for
378  // 'int'. Gotta problem wit dat?
379  QualType Result
380    = Context.getClassTemplateSpecializationType(Template,
381                                                 TemplateArgs.size(),
382                    reinterpret_cast<uintptr_t *>(TemplateArgs.getArgs()),
383                                                 TemplateArgs.getArgIsType(),
384                                                 Context.IntTy);
385  TemplateArgs.release();
386  return Result.getAsOpaquePtr();
387}
388
389/// \brief Check that the given template argument list is well-formed
390/// for specializing the given template.
391bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
392                                     SourceLocation TemplateLoc,
393                                     SourceLocation LAngleLoc,
394                                     ASTTemplateArgsPtr& Args,
395                                     SourceLocation *TemplateArgLocs,
396                                     SourceLocation RAngleLoc) {
397  TemplateParameterList *Params = Template->getTemplateParameters();
398  unsigned NumParams = Params->size();
399  unsigned NumArgs = Args.size();
400  bool Invalid = false;
401
402  if (NumArgs > NumParams ||
403      NumArgs < NumParams /*FIXME: default arguments! */) {
404    // FIXME: point at either the first arg beyond what we can handle,
405    // or the '>', depending on whether we have too many or too few
406    // arguments.
407    SourceRange Range;
408    if (NumArgs > NumParams)
409      Range = SourceRange(TemplateArgLocs[NumParams], RAngleLoc);
410    Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
411      << (NumArgs > NumParams)
412      << (isa<ClassTemplateDecl>(Template)? 0 :
413          isa<FunctionTemplateDecl>(Template)? 1 :
414          isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
415      << Template << Range;
416
417    Invalid = true;
418  }
419
420  // C++ [temp.arg]p1:
421  //   [...] The type and form of each template-argument specified in
422  //   a template-id shall match the type and form specified for the
423  //   corresponding parameter declared by the template in its
424  //   template-parameter-list.
425  unsigned ArgIdx = 0;
426  for (TemplateParameterList::iterator Param = Params->begin(),
427                                       ParamEnd = Params->end();
428       Param != ParamEnd; ++Param, ++ArgIdx) {
429    // Decode the template argument
430    QualType ArgType;
431    Expr *ArgExpr = 0;
432    SourceLocation ArgLoc;
433    if (ArgIdx >= NumArgs) {
434      // FIXME: Get the default argument here, which might
435      // (eventually) require instantiation.
436      break;
437    } else
438      ArgLoc = TemplateArgLocs[ArgIdx];
439
440    if (Args.getArgIsType()[ArgIdx])
441      ArgType = QualType::getFromOpaquePtr(Args.getArgs()[ArgIdx]);
442    else
443      ArgExpr = reinterpret_cast<Expr *>(Args.getArgs()[ArgIdx]);
444
445    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
446      // Check template type parameters.
447      if (!ArgType.isNull()) {
448        if (!CheckTemplateArgument(TTP, ArgType, ArgLoc))
449          Invalid = true;
450        continue;
451      }
452
453      // C++ [temp.arg.type]p1:
454      //   A template-argument for a template-parameter which is a
455      //   type shall be a type-id.
456
457      // We have a template type parameter but the template argument
458      // is an expression.
459      Diag(ArgExpr->getSourceRange().getBegin(),
460           diag::err_template_arg_must_be_type);
461      Diag((*Param)->getLocation(), diag::note_template_parameter_here);
462      Invalid = true;
463    } else if (NonTypeTemplateParmDecl *NTTP
464                 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
465      // Check non-type template parameters.
466      if (ArgExpr) {
467        if (!CheckTemplateArgument(NTTP, ArgExpr))
468          Invalid = true;
469        continue;
470      }
471
472      // We have a non-type template parameter but the template
473      // argument is a type.
474
475      // C++ [temp.arg]p2:
476      //   In a template-argument, an ambiguity between a type-id and
477      //   an expression is resolved to a type-id, regardless of the
478      //   form of the corresponding template-parameter.
479      //
480      // We warn specifically about this case, since it can be rather
481      // confusing for users.
482      if (ArgType->isFunctionType())
483        Diag(ArgLoc, diag::err_template_arg_nontype_ambig)
484          << ArgType;
485      else
486        Diag(ArgLoc, diag::err_template_arg_must_be_expr);
487      Diag((*Param)->getLocation(), diag::note_template_parameter_here);
488      Invalid = true;
489    } else {
490      // Check template template parameters.
491      TemplateTemplateParmDecl *TempParm
492        = cast<TemplateTemplateParmDecl>(*Param);
493
494      if (ArgExpr && isa<DeclRefExpr>(ArgExpr) &&
495          isa<TemplateDecl>(cast<DeclRefExpr>(ArgExpr)->getDecl())) {
496        if (!CheckTemplateArgument(TempParm, cast<DeclRefExpr>(ArgExpr)))
497          Invalid = true;
498        continue;
499      }
500
501      // We have a template template parameter but the template
502      // argument does not refer to a template.
503      Diag(ArgLoc, diag::err_template_arg_must_be_template);
504      Invalid = true;
505    }
506  }
507
508  return Invalid;
509}
510
511/// \brief Check a template argument against its corresponding
512/// template type parameter.
513///
514/// This routine implements the semantics of C++ [temp.arg.type]. It
515/// returns true if an error occurred, and false otherwise.
516bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
517                                 QualType Arg, SourceLocation ArgLoc) {
518  // C++ [temp.arg.type]p2:
519  //   A local type, a type with no linkage, an unnamed type or a type
520  //   compounded from any of these types shall not be used as a
521  //   template-argument for a template type-parameter.
522  //
523  // FIXME: Perform the recursive and no-linkage type checks.
524  const TagType *Tag = 0;
525  if (const EnumType *EnumT = Arg->getAsEnumType())
526    Tag = EnumT;
527  else if (const RecordType *RecordT = Arg->getAsRecordType())
528    Tag = RecordT;
529  if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod())
530    return Diag(ArgLoc, diag::err_template_arg_local_type)
531      << QualType(Tag, 0);
532  else if (Tag && !Tag->getDecl()->getDeclName()) {
533    Diag(ArgLoc, diag::err_template_arg_unnamed_type);
534    Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
535    return true;
536  }
537
538  return false;
539}
540
541/// \brief Check a template argument against its corresponding
542/// non-type template parameter.
543///
544/// This routine implements the semantics of C++ [temp.arg.nontype].
545/// It returns true if an error occurred, and false otherwise.
546bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
547                                 Expr *Arg) {
548  return false;
549}
550
551/// \brief Check a template argument against its corresponding
552/// template template parameter.
553///
554/// This routine implements the semantics of C++ [temp.arg.template].
555/// It returns true if an error occurred, and false otherwise.
556bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
557                                 DeclRefExpr *Arg) {
558  assert(isa<TemplateDecl>(Arg->getDecl()) && "Only template decls allowed");
559  TemplateDecl *Template = cast<TemplateDecl>(Arg->getDecl());
560
561  // C++ [temp.arg.template]p1:
562  //   A template-argument for a template template-parameter shall be
563  //   the name of a class template, expressed as id-expression. Only
564  //   primary class templates are considered when matching the
565  //   template template argument with the corresponding parameter;
566  //   partial specializations are not considered even if their
567  //   parameter lists match that of the template template parameter.
568  if (!isa<ClassTemplateDecl>(Template)) {
569    assert(isa<FunctionTemplateDecl>(Template) &&
570           "Only function templates are possible here");
571    Diag(Arg->getSourceRange().getBegin(), diag::note_template_arg_refers_here)
572      << Template;
573  }
574
575  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
576                                         Param->getTemplateParameters(),
577                                         true, true,
578                                         Arg->getSourceRange().getBegin());
579}
580
581/// \brief Determine whether the given template parameter lists are
582/// equivalent.
583///
584/// \param New  The new template parameter list, typically written in the
585/// source code as part of a new template declaration.
586///
587/// \param Old  The old template parameter list, typically found via
588/// name lookup of the template declared with this template parameter
589/// list.
590///
591/// \param Complain  If true, this routine will produce a diagnostic if
592/// the template parameter lists are not equivalent.
593///
594/// \param IsTemplateTemplateParm  If true, this routine is being
595/// called to compare the template parameter lists of a template
596/// template parameter.
597///
598/// \param TemplateArgLoc If this source location is valid, then we
599/// are actually checking the template parameter list of a template
600/// argument (New) against the template parameter list of its
601/// corresponding template template parameter (Old). We produce
602/// slightly different diagnostics in this scenario.
603///
604/// \returns True if the template parameter lists are equal, false
605/// otherwise.
606bool
607Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
608                                     TemplateParameterList *Old,
609                                     bool Complain,
610                                     bool IsTemplateTemplateParm,
611                                     SourceLocation TemplateArgLoc) {
612  if (Old->size() != New->size()) {
613    if (Complain) {
614      unsigned NextDiag = diag::err_template_param_list_different_arity;
615      if (TemplateArgLoc.isValid()) {
616        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
617        NextDiag = diag::note_template_param_list_different_arity;
618      }
619      Diag(New->getTemplateLoc(), NextDiag)
620          << (New->size() > Old->size())
621          << IsTemplateTemplateParm
622          << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
623      Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
624        << IsTemplateTemplateParm
625        << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
626    }
627
628    return false;
629  }
630
631  for (TemplateParameterList::iterator OldParm = Old->begin(),
632         OldParmEnd = Old->end(), NewParm = New->begin();
633       OldParm != OldParmEnd; ++OldParm, ++NewParm) {
634    if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
635      unsigned NextDiag = diag::err_template_param_different_kind;
636      if (TemplateArgLoc.isValid()) {
637        Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
638        NextDiag = diag::note_template_param_different_kind;
639      }
640      Diag((*NewParm)->getLocation(), NextDiag)
641        << IsTemplateTemplateParm;
642      Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
643        << IsTemplateTemplateParm;
644      return false;
645    }
646
647    if (isa<TemplateTypeParmDecl>(*OldParm)) {
648      // Okay; all template type parameters are equivalent (since we
649      // know we're at the same index).
650#if 0
651      // FIXME: Enable this code in debug mode *after* we properly go
652      // through and "instantiate" the template parameter lists of
653      // template template parameters. It's only after this
654      // instantiation that (1) any dependent types within the
655      // template parameter list of the template template parameter
656      // can be checked, and (2) the template type parameter depths
657      // will match up.
658      QualType OldParmType
659        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*OldParm));
660      QualType NewParmType
661        = Context.getTypeDeclType(cast<TemplateTypeParmDecl>(*NewParm));
662      assert(Context.getCanonicalType(OldParmType) ==
663             Context.getCanonicalType(NewParmType) &&
664             "type parameter mismatch?");
665#endif
666    } else if (NonTypeTemplateParmDecl *OldNTTP
667                 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
668      // The types of non-type template parameters must agree.
669      NonTypeTemplateParmDecl *NewNTTP
670        = cast<NonTypeTemplateParmDecl>(*NewParm);
671      if (Context.getCanonicalType(OldNTTP->getType()) !=
672            Context.getCanonicalType(NewNTTP->getType())) {
673        if (Complain) {
674          unsigned NextDiag = diag::err_template_nontype_parm_different_type;
675          if (TemplateArgLoc.isValid()) {
676            Diag(TemplateArgLoc,
677                 diag::err_template_arg_template_params_mismatch);
678            NextDiag = diag::note_template_nontype_parm_different_type;
679          }
680          Diag(NewNTTP->getLocation(), NextDiag)
681            << NewNTTP->getType()
682            << IsTemplateTemplateParm;
683          Diag(OldNTTP->getLocation(),
684               diag::note_template_nontype_parm_prev_declaration)
685            << OldNTTP->getType();
686        }
687        return false;
688      }
689    } else {
690      // The template parameter lists of template template
691      // parameters must agree.
692      // FIXME: Could we perform a faster "type" comparison here?
693      assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
694             "Only template template parameters handled here");
695      TemplateTemplateParmDecl *OldTTP
696        = cast<TemplateTemplateParmDecl>(*OldParm);
697      TemplateTemplateParmDecl *NewTTP
698        = cast<TemplateTemplateParmDecl>(*NewParm);
699      if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
700                                          OldTTP->getTemplateParameters(),
701                                          Complain,
702                                          /*IsTemplateTemplateParm=*/true,
703                                          TemplateArgLoc))
704        return false;
705    }
706  }
707
708  return true;
709}
710
711/// \brief Check whether a template can be declared within this scope.
712///
713/// If the template declaration is valid in this scope, returns
714/// false. Otherwise, issues a diagnostic and returns true.
715bool
716Sema::CheckTemplateDeclScope(Scope *S,
717                             MultiTemplateParamsArg &TemplateParameterLists) {
718  assert(TemplateParameterLists.size() > 0 && "Not a template");
719
720  // Find the nearest enclosing declaration scope.
721  while ((S->getFlags() & Scope::DeclScope) == 0 ||
722         (S->getFlags() & Scope::TemplateParamScope) != 0)
723    S = S->getParent();
724
725  TemplateParameterList *TemplateParams =
726    static_cast<TemplateParameterList*>(*TemplateParameterLists.get());
727  SourceLocation TemplateLoc = TemplateParams->getTemplateLoc();
728  SourceRange TemplateRange
729    = SourceRange(TemplateLoc, TemplateParams->getRAngleLoc());
730
731  // C++ [temp]p2:
732  //   A template-declaration can appear only as a namespace scope or
733  //   class scope declaration.
734  DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
735  while (Ctx && isa<LinkageSpecDecl>(Ctx)) {
736    if (cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
737      return Diag(TemplateLoc, diag::err_template_linkage)
738        << TemplateRange;
739
740    Ctx = Ctx->getParent();
741  }
742
743  if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
744    return false;
745
746  return Diag(TemplateLoc, diag::err_template_outside_namespace_or_class_scope)
747    << TemplateRange;
748}
749