1 //===--- ParseTemplate.cpp - Template Parsing -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements parsing of C++ templates.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/Parse/ParseDiagnostic.h"
20 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/ParsedTemplate.h"
22 #include "clang/Sema/Scope.h"
23 using namespace clang;
24 
25 /// \brief Parse a template declaration, explicit instantiation, or
26 /// explicit specialization.
27 Decl *
28 Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
29                                              SourceLocation &DeclEnd,
30                                              AccessSpecifier AS,
31                                              AttributeList *AccessAttrs) {
32   ObjCDeclContextSwitch ObjCDC(*this);
33 
34   if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
35     return ParseExplicitInstantiation(Context,
36                                       SourceLocation(), ConsumeToken(),
37                                       DeclEnd, AS);
38   }
39   return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
40                                                   AccessAttrs);
41 }
42 
43 
44 
45 /// \brief Parse a template declaration or an explicit specialization.
46 ///
47 /// Template declarations include one or more template parameter lists
48 /// and either the function or class template declaration. Explicit
49 /// specializations contain one or more 'template < >' prefixes
50 /// followed by a (possibly templated) declaration. Since the
51 /// syntactic form of both features is nearly identical, we parse all
52 /// of the template headers together and let semantic analysis sort
53 /// the declarations from the explicit specializations.
54 ///
55 ///       template-declaration: [C++ temp]
56 ///         'export'[opt] 'template' '<' template-parameter-list '>' declaration
57 ///
58 ///       explicit-specialization: [ C++ temp.expl.spec]
59 ///         'template' '<' '>' declaration
60 Decl *
61 Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
62                                                  SourceLocation &DeclEnd,
63                                                  AccessSpecifier AS,
64                                                  AttributeList *AccessAttrs) {
65   assert(Tok.isOneOf(tok::kw_export, tok::kw_template) &&
66          "Token does not start a template declaration.");
67 
68   // Enter template-parameter scope.
69   ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
70 
71   // Tell the action that names should be checked in the context of
72   // the declaration to come.
73   ParsingDeclRAIIObject
74     ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
75 
76   // Parse multiple levels of template headers within this template
77   // parameter scope, e.g.,
78   //
79   //   template<typename T>
80   //     template<typename U>
81   //       class A<T>::B { ... };
82   //
83   // We parse multiple levels non-recursively so that we can build a
84   // single data structure containing all of the template parameter
85   // lists to easily differentiate between the case above and:
86   //
87   //   template<typename T>
88   //   class A {
89   //     template<typename U> class B;
90   //   };
91   //
92   // In the first case, the action for declaring A<T>::B receives
93   // both template parameter lists. In the second case, the action for
94   // defining A<T>::B receives just the inner template parameter list
95   // (and retrieves the outer template parameter list from its
96   // context).
97   bool isSpecialization = true;
98   bool LastParamListWasEmpty = false;
99   TemplateParameterLists ParamLists;
100   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
101 
102   do {
103     // Consume the 'export', if any.
104     SourceLocation ExportLoc;
105     TryConsumeToken(tok::kw_export, ExportLoc);
106 
107     // Consume the 'template', which should be here.
108     SourceLocation TemplateLoc;
109     if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
110       Diag(Tok.getLocation(), diag::err_expected_template);
111       return nullptr;
112     }
113 
114     // Parse the '<' template-parameter-list '>'
115     SourceLocation LAngleLoc, RAngleLoc;
116     SmallVector<Decl*, 4> TemplateParams;
117     if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
118                                 TemplateParams, LAngleLoc, RAngleLoc)) {
119       // Skip until the semi-colon or a '}'.
120       SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
121       TryConsumeToken(tok::semi);
122       return nullptr;
123     }
124 
125     ParamLists.push_back(
126       Actions.ActOnTemplateParameterList(CurTemplateDepthTracker.getDepth(),
127                                          ExportLoc,
128                                          TemplateLoc, LAngleLoc,
129                                          TemplateParams, RAngleLoc));
130 
131     if (!TemplateParams.empty()) {
132       isSpecialization = false;
133       ++CurTemplateDepthTracker;
134 
135       if (TryConsumeToken(tok::kw_requires)) {
136         ExprResult ER =
137             Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
138         if (!ER.isUsable()) {
139           // Skip until the semi-colon or a '}'.
140           SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
141           TryConsumeToken(tok::semi);
142           return nullptr;
143         }
144       }
145     } else {
146       LastParamListWasEmpty = true;
147     }
148   } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
149 
150   // Parse the actual template declaration.
151   return ParseSingleDeclarationAfterTemplate(Context,
152                                              ParsedTemplateInfo(&ParamLists,
153                                                              isSpecialization,
154                                                          LastParamListWasEmpty),
155                                              ParsingTemplateParams,
156                                              DeclEnd, AS, AccessAttrs);
157 }
158 
159 /// \brief Parse a single declaration that declares a template,
160 /// template specialization, or explicit instantiation of a template.
161 ///
162 /// \param DeclEnd will receive the source location of the last token
163 /// within this declaration.
164 ///
165 /// \param AS the access specifier associated with this
166 /// declaration. Will be AS_none for namespace-scope declarations.
167 ///
168 /// \returns the new declaration.
169 Decl *
170 Parser::ParseSingleDeclarationAfterTemplate(
171                                        unsigned Context,
172                                        const ParsedTemplateInfo &TemplateInfo,
173                                        ParsingDeclRAIIObject &DiagsFromTParams,
174                                        SourceLocation &DeclEnd,
175                                        AccessSpecifier AS,
176                                        AttributeList *AccessAttrs) {
177   assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
178          "Template information required");
179 
180   if (Tok.is(tok::kw_static_assert)) {
181     // A static_assert declaration may not be templated.
182     Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
183       << TemplateInfo.getSourceRange();
184     // Parse the static_assert declaration to improve error recovery.
185     return ParseStaticAssertDeclaration(DeclEnd);
186   }
187 
188   if (Context == Declarator::MemberContext) {
189     // We are parsing a member template.
190     ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
191                                    &DiagsFromTParams);
192     return nullptr;
193   }
194 
195   ParsedAttributesWithRange prefixAttrs(AttrFactory);
196   MaybeParseCXX11Attributes(prefixAttrs);
197 
198   if (Tok.is(tok::kw_using))
199     return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
200                                             prefixAttrs);
201 
202   // Parse the declaration specifiers, stealing any diagnostics from
203   // the template parameters.
204   ParsingDeclSpec DS(*this, &DiagsFromTParams);
205 
206   ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
207                              getDeclSpecContextFromDeclaratorContext(Context));
208 
209   if (Tok.is(tok::semi)) {
210     ProhibitAttributes(prefixAttrs);
211     DeclEnd = ConsumeToken();
212     RecordDecl *AnonRecord = nullptr;
213     Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
214         getCurScope(), AS, DS,
215         TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
216                                     : MultiTemplateParamsArg(),
217         TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
218         AnonRecord);
219     assert(!AnonRecord &&
220            "Anonymous unions/structs should not be valid with template");
221     DS.complete(Decl);
222     return Decl;
223   }
224 
225   // Move the attributes from the prefix into the DS.
226   if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
227     ProhibitAttributes(prefixAttrs);
228   else
229     DS.takeAttributesFrom(prefixAttrs);
230 
231   // Parse the declarator.
232   ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
233   ParseDeclarator(DeclaratorInfo);
234   // Error parsing the declarator?
235   if (!DeclaratorInfo.hasName()) {
236     // If so, skip until the semi-colon or a }.
237     SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
238     if (Tok.is(tok::semi))
239       ConsumeToken();
240     return nullptr;
241   }
242 
243   LateParsedAttrList LateParsedAttrs(true);
244   if (DeclaratorInfo.isFunctionDeclarator())
245     MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
246 
247   if (DeclaratorInfo.isFunctionDeclarator() &&
248       isStartOfFunctionDefinition(DeclaratorInfo)) {
249 
250     // Function definitions are only allowed at file scope and in C++ classes.
251     // The C++ inline method definition case is handled elsewhere, so we only
252     // need to handle the file scope definition case.
253     if (Context != Declarator::FileContext) {
254       Diag(Tok, diag::err_function_definition_not_allowed);
255       SkipMalformedDecl();
256       return nullptr;
257     }
258 
259     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
260       // Recover by ignoring the 'typedef'. This was probably supposed to be
261       // the 'typename' keyword, which we should have already suggested adding
262       // if it's appropriate.
263       Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
264         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
265       DS.ClearStorageClassSpecs();
266     }
267 
268     if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
269       if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
270         // If the declarator-id is not a template-id, issue a diagnostic and
271         // recover by ignoring the 'template' keyword.
272         Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
273         return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
274                                        &LateParsedAttrs);
275       } else {
276         SourceLocation LAngleLoc
277           = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
278         Diag(DeclaratorInfo.getIdentifierLoc(),
279              diag::err_explicit_instantiation_with_definition)
280             << SourceRange(TemplateInfo.TemplateLoc)
281             << FixItHint::CreateInsertion(LAngleLoc, "<>");
282 
283         // Recover as if it were an explicit specialization.
284         TemplateParameterLists FakedParamLists;
285         FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
286             0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
287             LAngleLoc));
288 
289         return ParseFunctionDefinition(
290             DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
291                                                /*isSpecialization=*/true,
292                                                /*LastParamListWasEmpty=*/true),
293             &LateParsedAttrs);
294       }
295     }
296     return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
297                                    &LateParsedAttrs);
298   }
299 
300   // Parse this declaration.
301   Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
302                                                    TemplateInfo);
303 
304   if (Tok.is(tok::comma)) {
305     Diag(Tok, diag::err_multiple_template_declarators)
306       << (int)TemplateInfo.Kind;
307     SkipUntil(tok::semi);
308     return ThisDecl;
309   }
310 
311   // Eat the semi colon after the declaration.
312   ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
313   if (LateParsedAttrs.size() > 0)
314     ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
315   DeclaratorInfo.complete(ThisDecl);
316   return ThisDecl;
317 }
318 
319 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
320 /// angle brackets. Depth is the depth of this template-parameter-list, which
321 /// is the number of template headers directly enclosing this template header.
322 /// TemplateParams is the current list of template parameters we're building.
323 /// The template parameter we parse will be added to this list. LAngleLoc and
324 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
325 /// that enclose this template parameter list.
326 ///
327 /// \returns true if an error occurred, false otherwise.
328 bool Parser::ParseTemplateParameters(unsigned Depth,
329                                SmallVectorImpl<Decl*> &TemplateParams,
330                                      SourceLocation &LAngleLoc,
331                                      SourceLocation &RAngleLoc) {
332   // Get the template parameter list.
333   if (!TryConsumeToken(tok::less, LAngleLoc)) {
334     Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
335     return true;
336   }
337 
338   // Try to parse the template parameter list.
339   bool Failed = false;
340   if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
341     Failed = ParseTemplateParameterList(Depth, TemplateParams);
342 
343   if (Tok.is(tok::greatergreater)) {
344     // No diagnostic required here: a template-parameter-list can only be
345     // followed by a declaration or, for a template template parameter, the
346     // 'class' keyword. Therefore, the second '>' will be diagnosed later.
347     // This matters for elegant diagnosis of:
348     //   template<template<typename>> struct S;
349     Tok.setKind(tok::greater);
350     RAngleLoc = Tok.getLocation();
351     Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
352   } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
353     Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
354     return true;
355   }
356   return false;
357 }
358 
359 /// ParseTemplateParameterList - Parse a template parameter list. If
360 /// the parsing fails badly (i.e., closing bracket was left out), this
361 /// will try to put the token stream in a reasonable position (closing
362 /// a statement, etc.) and return false.
363 ///
364 ///       template-parameter-list:    [C++ temp]
365 ///         template-parameter
366 ///         template-parameter-list ',' template-parameter
367 bool
368 Parser::ParseTemplateParameterList(unsigned Depth,
369                              SmallVectorImpl<Decl*> &TemplateParams) {
370   while (1) {
371     if (Decl *TmpParam
372           = ParseTemplateParameter(Depth, TemplateParams.size())) {
373       TemplateParams.push_back(TmpParam);
374     } else {
375       // If we failed to parse a template parameter, skip until we find
376       // a comma or closing brace.
377       SkipUntil(tok::comma, tok::greater, tok::greatergreater,
378                 StopAtSemi | StopBeforeMatch);
379     }
380 
381     // Did we find a comma or the end of the template parameter list?
382     if (Tok.is(tok::comma)) {
383       ConsumeToken();
384     } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
385       // Don't consume this... that's done by template parser.
386       break;
387     } else {
388       // Somebody probably forgot to close the template. Skip ahead and
389       // try to get out of the expression. This error is currently
390       // subsumed by whatever goes on in ParseTemplateParameter.
391       Diag(Tok.getLocation(), diag::err_expected_comma_greater);
392       SkipUntil(tok::comma, tok::greater, tok::greatergreater,
393                 StopAtSemi | StopBeforeMatch);
394       return false;
395     }
396   }
397   return true;
398 }
399 
400 /// \brief Determine whether the parser is at the start of a template
401 /// type parameter.
402 bool Parser::isStartOfTemplateTypeParameter() {
403   if (Tok.is(tok::kw_class)) {
404     // "class" may be the start of an elaborated-type-specifier or a
405     // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
406     switch (NextToken().getKind()) {
407     case tok::equal:
408     case tok::comma:
409     case tok::greater:
410     case tok::greatergreater:
411     case tok::ellipsis:
412       return true;
413 
414     case tok::identifier:
415       // This may be either a type-parameter or an elaborated-type-specifier.
416       // We have to look further.
417       break;
418 
419     default:
420       return false;
421     }
422 
423     switch (GetLookAheadToken(2).getKind()) {
424     case tok::equal:
425     case tok::comma:
426     case tok::greater:
427     case tok::greatergreater:
428       return true;
429 
430     default:
431       return false;
432     }
433   }
434 
435   if (Tok.isNot(tok::kw_typename))
436     return false;
437 
438   // C++ [temp.param]p2:
439   //   There is no semantic difference between class and typename in a
440   //   template-parameter. typename followed by an unqualified-id
441   //   names a template type parameter. typename followed by a
442   //   qualified-id denotes the type in a non-type
443   //   parameter-declaration.
444   Token Next = NextToken();
445 
446   // If we have an identifier, skip over it.
447   if (Next.getKind() == tok::identifier)
448     Next = GetLookAheadToken(2);
449 
450   switch (Next.getKind()) {
451   case tok::equal:
452   case tok::comma:
453   case tok::greater:
454   case tok::greatergreater:
455   case tok::ellipsis:
456     return true;
457 
458   default:
459     return false;
460   }
461 }
462 
463 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
464 ///
465 ///       template-parameter: [C++ temp.param]
466 ///         type-parameter
467 ///         parameter-declaration
468 ///
469 ///       type-parameter: (see below)
470 ///         'class' ...[opt] identifier[opt]
471 ///         'class' identifier[opt] '=' type-id
472 ///         'typename' ...[opt] identifier[opt]
473 ///         'typename' identifier[opt] '=' type-id
474 ///         'template' '<' template-parameter-list '>'
475 ///               'class' ...[opt] identifier[opt]
476 ///         'template' '<' template-parameter-list '>' 'class' identifier[opt]
477 ///               = id-expression
478 Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
479   if (isStartOfTemplateTypeParameter())
480     return ParseTypeParameter(Depth, Position);
481 
482   if (Tok.is(tok::kw_template))
483     return ParseTemplateTemplateParameter(Depth, Position);
484 
485   // If it's none of the above, then it must be a parameter declaration.
486   // NOTE: This will pick up errors in the closure of the template parameter
487   // list (e.g., template < ; Check here to implement >> style closures.
488   return ParseNonTypeTemplateParameter(Depth, Position);
489 }
490 
491 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
492 /// Other kinds of template parameters are parsed in
493 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
494 ///
495 ///       type-parameter:     [C++ temp.param]
496 ///         'class' ...[opt][C++0x] identifier[opt]
497 ///         'class' identifier[opt] '=' type-id
498 ///         'typename' ...[opt][C++0x] identifier[opt]
499 ///         'typename' identifier[opt] '=' type-id
500 Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
501   assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
502          "A type-parameter starts with 'class' or 'typename'");
503 
504   // Consume the 'class' or 'typename' keyword.
505   bool TypenameKeyword = Tok.is(tok::kw_typename);
506   SourceLocation KeyLoc = ConsumeToken();
507 
508   // Grab the ellipsis (if given).
509   SourceLocation EllipsisLoc;
510   if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
511     Diag(EllipsisLoc,
512          getLangOpts().CPlusPlus11
513            ? diag::warn_cxx98_compat_variadic_templates
514            : diag::ext_variadic_templates);
515   }
516 
517   // Grab the template parameter name (if given)
518   SourceLocation NameLoc;
519   IdentifierInfo *ParamName = nullptr;
520   if (Tok.is(tok::identifier)) {
521     ParamName = Tok.getIdentifierInfo();
522     NameLoc = ConsumeToken();
523   } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
524                          tok::greatergreater)) {
525     // Unnamed template parameter. Don't have to do anything here, just
526     // don't consume this token.
527   } else {
528     Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
529     return nullptr;
530   }
531 
532   // Recover from misplaced ellipsis.
533   bool AlreadyHasEllipsis = EllipsisLoc.isValid();
534   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
535     DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
536 
537   // Grab a default argument (if available).
538   // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
539   // we introduce the type parameter into the local scope.
540   SourceLocation EqualLoc;
541   ParsedType DefaultArg;
542   if (TryConsumeToken(tok::equal, EqualLoc))
543     DefaultArg = ParseTypeName(/*Range=*/nullptr,
544                                Declarator::TemplateTypeArgContext).get();
545 
546   return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
547                                     KeyLoc, ParamName, NameLoc, Depth, Position,
548                                     EqualLoc, DefaultArg);
549 }
550 
551 /// ParseTemplateTemplateParameter - Handle the parsing of template
552 /// template parameters.
553 ///
554 ///       type-parameter:    [C++ temp.param]
555 ///         'template' '<' template-parameter-list '>' type-parameter-key
556 ///                  ...[opt] identifier[opt]
557 ///         'template' '<' template-parameter-list '>' type-parameter-key
558 ///                  identifier[opt] = id-expression
559 ///       type-parameter-key:
560 ///         'class'
561 ///         'typename'       [C++1z]
562 Decl *
563 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
564   assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
565 
566   // Handle the template <...> part.
567   SourceLocation TemplateLoc = ConsumeToken();
568   SmallVector<Decl*,8> TemplateParams;
569   SourceLocation LAngleLoc, RAngleLoc;
570   {
571     ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
572     if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
573                                RAngleLoc)) {
574       return nullptr;
575     }
576   }
577 
578   // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
579   // Generate a meaningful error if the user forgot to put class before the
580   // identifier, comma, or greater. Provide a fixit if the identifier, comma,
581   // or greater appear immediately or after 'struct'. In the latter case,
582   // replace the keyword with 'class'.
583   if (!TryConsumeToken(tok::kw_class)) {
584     bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
585     const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
586     if (Tok.is(tok::kw_typename)) {
587       Diag(Tok.getLocation(),
588            getLangOpts().CPlusPlus1z
589                ? diag::warn_cxx14_compat_template_template_param_typename
590                : diag::ext_template_template_param_typename)
591         << (!getLangOpts().CPlusPlus1z
592                 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
593                 : FixItHint());
594     } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
595                             tok::greatergreater, tok::ellipsis)) {
596       Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
597         << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
598                     : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
599     } else
600       Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
601 
602     if (Replace)
603       ConsumeToken();
604   }
605 
606   // Parse the ellipsis, if given.
607   SourceLocation EllipsisLoc;
608   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
609     Diag(EllipsisLoc,
610          getLangOpts().CPlusPlus11
611            ? diag::warn_cxx98_compat_variadic_templates
612            : diag::ext_variadic_templates);
613 
614   // Get the identifier, if given.
615   SourceLocation NameLoc;
616   IdentifierInfo *ParamName = nullptr;
617   if (Tok.is(tok::identifier)) {
618     ParamName = Tok.getIdentifierInfo();
619     NameLoc = ConsumeToken();
620   } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
621                          tok::greatergreater)) {
622     // Unnamed template parameter. Don't have to do anything here, just
623     // don't consume this token.
624   } else {
625     Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
626     return nullptr;
627   }
628 
629   // Recover from misplaced ellipsis.
630   bool AlreadyHasEllipsis = EllipsisLoc.isValid();
631   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
632     DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
633 
634   TemplateParameterList *ParamList =
635     Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
636                                        TemplateLoc, LAngleLoc,
637                                        TemplateParams,
638                                        RAngleLoc);
639 
640   // Grab a default argument (if available).
641   // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
642   // we introduce the template parameter into the local scope.
643   SourceLocation EqualLoc;
644   ParsedTemplateArgument DefaultArg;
645   if (TryConsumeToken(tok::equal, EqualLoc)) {
646     DefaultArg = ParseTemplateTemplateArgument();
647     if (DefaultArg.isInvalid()) {
648       Diag(Tok.getLocation(),
649            diag::err_default_template_template_parameter_not_template);
650       SkipUntil(tok::comma, tok::greater, tok::greatergreater,
651                 StopAtSemi | StopBeforeMatch);
652     }
653   }
654 
655   return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
656                                                 ParamList, EllipsisLoc,
657                                                 ParamName, NameLoc, Depth,
658                                                 Position, EqualLoc, DefaultArg);
659 }
660 
661 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
662 /// template parameters (e.g., in "template<int Size> class array;").
663 ///
664 ///       template-parameter:
665 ///         ...
666 ///         parameter-declaration
667 Decl *
668 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
669   // Parse the declaration-specifiers (i.e., the type).
670   // FIXME: The type should probably be restricted in some way... Not all
671   // declarators (parts of declarators?) are accepted for parameters.
672   DeclSpec DS(AttrFactory);
673   ParseDeclarationSpecifiers(DS);
674 
675   // Parse this as a typename.
676   Declarator ParamDecl(DS, Declarator::TemplateParamContext);
677   ParseDeclarator(ParamDecl);
678   if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
679     Diag(Tok.getLocation(), diag::err_expected_template_parameter);
680     return nullptr;
681   }
682 
683   // Recover from misplaced ellipsis.
684   SourceLocation EllipsisLoc;
685   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
686     DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
687 
688   // If there is a default value, parse it.
689   // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
690   // we introduce the template parameter into the local scope.
691   SourceLocation EqualLoc;
692   ExprResult DefaultArg;
693   if (TryConsumeToken(tok::equal, EqualLoc)) {
694     // C++ [temp.param]p15:
695     //   When parsing a default template-argument for a non-type
696     //   template-parameter, the first non-nested > is taken as the
697     //   end of the template-parameter-list rather than a greater-than
698     //   operator.
699     GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
700     EnterExpressionEvaluationContext ConstantEvaluated(Actions,
701                                                        Sema::ConstantEvaluated);
702 
703     DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
704     if (DefaultArg.isInvalid())
705       SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
706   }
707 
708   // Create the parameter.
709   return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
710                                                Depth, Position, EqualLoc,
711                                                DefaultArg.get());
712 }
713 
714 void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
715                                        SourceLocation CorrectLoc,
716                                        bool AlreadyHasEllipsis,
717                                        bool IdentifierHasName) {
718   FixItHint Insertion;
719   if (!AlreadyHasEllipsis)
720     Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
721   Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
722       << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
723       << !IdentifierHasName;
724 }
725 
726 void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
727                                                    Declarator &D) {
728   assert(EllipsisLoc.isValid());
729   bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
730   if (!AlreadyHasEllipsis)
731     D.setEllipsisLoc(EllipsisLoc);
732   DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
733                             AlreadyHasEllipsis, D.hasName());
734 }
735 
736 /// \brief Parses a '>' at the end of a template list.
737 ///
738 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
739 /// to determine if these tokens were supposed to be a '>' followed by
740 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
741 ///
742 /// \param RAngleLoc the location of the consumed '>'.
743 ///
744 /// \param ConsumeLastToken if true, the '>' is consumed.
745 ///
746 /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
747 /// type parameter or type argument list, rather than a C++ template parameter
748 /// or argument list.
749 ///
750 /// \returns true, if current token does not start with '>', false otherwise.
751 bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
752                                             bool ConsumeLastToken,
753                                             bool ObjCGenericList) {
754   // What will be left once we've consumed the '>'.
755   tok::TokenKind RemainingToken;
756   const char *ReplacementStr = "> >";
757 
758   switch (Tok.getKind()) {
759   default:
760     Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
761     return true;
762 
763   case tok::greater:
764     // Determine the location of the '>' token. Only consume this token
765     // if the caller asked us to.
766     RAngleLoc = Tok.getLocation();
767     if (ConsumeLastToken)
768       ConsumeToken();
769     return false;
770 
771   case tok::greatergreater:
772     RemainingToken = tok::greater;
773     break;
774 
775   case tok::greatergreatergreater:
776     RemainingToken = tok::greatergreater;
777     break;
778 
779   case tok::greaterequal:
780     RemainingToken = tok::equal;
781     ReplacementStr = "> =";
782     break;
783 
784   case tok::greatergreaterequal:
785     RemainingToken = tok::greaterequal;
786     break;
787   }
788 
789   // This template-id is terminated by a token which starts with a '>'. Outside
790   // C++11, this is now error recovery, and in C++11, this is error recovery if
791   // the token isn't '>>' or '>>>'.
792   // '>>>' is for CUDA, where this sequence of characters is parsed into
793   // tok::greatergreatergreater, rather than two separate tokens.
794   //
795   // We always allow this for Objective-C type parameter and type argument
796   // lists.
797   RAngleLoc = Tok.getLocation();
798   Token Next = NextToken();
799   if (!ObjCGenericList) {
800     // The source range of the '>>' or '>=' at the start of the token.
801     CharSourceRange ReplacementRange =
802         CharSourceRange::getCharRange(RAngleLoc,
803             Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
804                                            getLangOpts()));
805 
806     // A hint to put a space between the '>>'s. In order to make the hint as
807     // clear as possible, we include the characters either side of the space in
808     // the replacement, rather than just inserting a space at SecondCharLoc.
809     FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
810                                                    ReplacementStr);
811 
812     // A hint to put another space after the token, if it would otherwise be
813     // lexed differently.
814     FixItHint Hint2;
815     if ((RemainingToken == tok::greater ||
816          RemainingToken == tok::greatergreater) &&
817         (Next.isOneOf(tok::greater, tok::greatergreater,
818                       tok::greatergreatergreater, tok::equal,
819                       tok::greaterequal, tok::greatergreaterequal,
820                       tok::equalequal)) &&
821         areTokensAdjacent(Tok, Next))
822       Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
823 
824     unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
825     if (getLangOpts().CPlusPlus11 &&
826         (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
827       DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
828     else if (Tok.is(tok::greaterequal))
829       DiagId = diag::err_right_angle_bracket_equal_needs_space;
830     Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
831   }
832 
833   // Strip the initial '>' from the token.
834   Token PrevTok = Tok;
835   if (RemainingToken == tok::equal && Next.is(tok::equal) &&
836       areTokensAdjacent(Tok, Next)) {
837     // Join two adjacent '=' tokens into one, for cases like:
838     //   void (*p)() = f<int>;
839     //   return f<int>==p;
840     ConsumeToken();
841     Tok.setKind(tok::equalequal);
842     Tok.setLength(Tok.getLength() + 1);
843   } else {
844     Tok.setKind(RemainingToken);
845     Tok.setLength(Tok.getLength() - 1);
846   }
847   Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
848                                                  PP.getSourceManager(),
849                                                  getLangOpts()));
850 
851   // The advance from '>>' to '>' in a ObjectiveC template argument list needs
852   // to be properly reflected in the token cache to allow correct interaction
853   // between annotation and backtracking.
854   if (ObjCGenericList && PrevTok.getKind() == tok::greatergreater &&
855       RemainingToken == tok::greater && PP.IsPreviousCachedToken(PrevTok)) {
856     PrevTok.setKind(RemainingToken);
857     PrevTok.setLength(1);
858     // Break tok::greatergreater into two tok::greater but only add the second
859     // one in case the client asks to consume the last token.
860     if (ConsumeLastToken)
861       PP.ReplacePreviousCachedToken({PrevTok, Tok});
862     else
863       PP.ReplacePreviousCachedToken({PrevTok});
864   }
865 
866   if (!ConsumeLastToken) {
867     // Since we're not supposed to consume the '>' token, we need to push
868     // this token and revert the current token back to the '>'.
869     PP.EnterToken(Tok);
870     Tok.setKind(tok::greater);
871     Tok.setLength(1);
872     Tok.setLocation(RAngleLoc);
873   }
874   return false;
875 }
876 
877 
878 /// \brief Parses a template-id that after the template name has
879 /// already been parsed.
880 ///
881 /// This routine takes care of parsing the enclosed template argument
882 /// list ('<' template-parameter-list [opt] '>') and placing the
883 /// results into a form that can be transferred to semantic analysis.
884 ///
885 /// \param Template the template declaration produced by isTemplateName
886 ///
887 /// \param TemplateNameLoc the source location of the template name
888 ///
889 /// \param SS if non-NULL, the nested-name-specifier preceding the
890 /// template name.
891 ///
892 /// \param ConsumeLastToken if true, then we will consume the last
893 /// token that forms the template-id. Otherwise, we will leave the
894 /// last token in the stream (e.g., so that it can be replaced with an
895 /// annotation token).
896 bool
897 Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
898                                          SourceLocation TemplateNameLoc,
899                                          const CXXScopeSpec &SS,
900                                          bool ConsumeLastToken,
901                                          SourceLocation &LAngleLoc,
902                                          TemplateArgList &TemplateArgs,
903                                          SourceLocation &RAngleLoc) {
904   assert(Tok.is(tok::less) && "Must have already parsed the template-name");
905 
906   // Consume the '<'.
907   LAngleLoc = ConsumeToken();
908 
909   // Parse the optional template-argument-list.
910   bool Invalid = false;
911   {
912     GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
913     if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
914       Invalid = ParseTemplateArgumentList(TemplateArgs);
915 
916     if (Invalid) {
917       // Try to find the closing '>'.
918       if (ConsumeLastToken)
919         SkipUntil(tok::greater, StopAtSemi);
920       else
921         SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
922       return true;
923     }
924   }
925 
926   return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
927                                         /*ObjCGenericList=*/false);
928 }
929 
930 /// \brief Replace the tokens that form a simple-template-id with an
931 /// annotation token containing the complete template-id.
932 ///
933 /// The first token in the stream must be the name of a template that
934 /// is followed by a '<'. This routine will parse the complete
935 /// simple-template-id and replace the tokens with a single annotation
936 /// token with one of two different kinds: if the template-id names a
937 /// type (and \p AllowTypeAnnotation is true), the annotation token is
938 /// a type annotation that includes the optional nested-name-specifier
939 /// (\p SS). Otherwise, the annotation token is a template-id
940 /// annotation that does not include the optional
941 /// nested-name-specifier.
942 ///
943 /// \param Template  the declaration of the template named by the first
944 /// token (an identifier), as returned from \c Action::isTemplateName().
945 ///
946 /// \param TNK the kind of template that \p Template
947 /// refers to, as returned from \c Action::isTemplateName().
948 ///
949 /// \param SS if non-NULL, the nested-name-specifier that precedes
950 /// this template name.
951 ///
952 /// \param TemplateKWLoc if valid, specifies that this template-id
953 /// annotation was preceded by the 'template' keyword and gives the
954 /// location of that keyword. If invalid (the default), then this
955 /// template-id was not preceded by a 'template' keyword.
956 ///
957 /// \param AllowTypeAnnotation if true (the default), then a
958 /// simple-template-id that refers to a class template, template
959 /// template parameter, or other template that produces a type will be
960 /// replaced with a type annotation token. Otherwise, the
961 /// simple-template-id is always replaced with a template-id
962 /// annotation token.
963 ///
964 /// If an unrecoverable parse error occurs and no annotation token can be
965 /// formed, this function returns true.
966 ///
967 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
968                                      CXXScopeSpec &SS,
969                                      SourceLocation TemplateKWLoc,
970                                      UnqualifiedId &TemplateName,
971                                      bool AllowTypeAnnotation) {
972   assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
973   assert(Template && Tok.is(tok::less) &&
974          "Parser isn't at the beginning of a template-id");
975 
976   // Consume the template-name.
977   SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
978 
979   // Parse the enclosed template argument list.
980   SourceLocation LAngleLoc, RAngleLoc;
981   TemplateArgList TemplateArgs;
982   bool Invalid = ParseTemplateIdAfterTemplateName(Template,
983                                                   TemplateNameLoc,
984                                                   SS, false, LAngleLoc,
985                                                   TemplateArgs,
986                                                   RAngleLoc);
987 
988   if (Invalid) {
989     // If we failed to parse the template ID but skipped ahead to a >, we're not
990     // going to be able to form a token annotation.  Eat the '>' if present.
991     TryConsumeToken(tok::greater);
992     return true;
993   }
994 
995   ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
996 
997   // Build the annotation token.
998   if (TNK == TNK_Type_template && AllowTypeAnnotation) {
999     TypeResult Type
1000       = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
1001                                     Template, TemplateNameLoc,
1002                                     LAngleLoc, TemplateArgsPtr, RAngleLoc);
1003     if (Type.isInvalid()) {
1004       // If we failed to parse the template ID but skipped ahead to a >, we're not
1005       // going to be able to form a token annotation.  Eat the '>' if present.
1006       TryConsumeToken(tok::greater);
1007       return true;
1008     }
1009 
1010     Tok.setKind(tok::annot_typename);
1011     setTypeAnnotation(Tok, Type.get());
1012     if (SS.isNotEmpty())
1013       Tok.setLocation(SS.getBeginLoc());
1014     else if (TemplateKWLoc.isValid())
1015       Tok.setLocation(TemplateKWLoc);
1016     else
1017       Tok.setLocation(TemplateNameLoc);
1018   } else {
1019     // Build a template-id annotation token that can be processed
1020     // later.
1021     Tok.setKind(tok::annot_template_id);
1022     TemplateIdAnnotation *TemplateId
1023       = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
1024     TemplateId->TemplateNameLoc = TemplateNameLoc;
1025     if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
1026       TemplateId->Name = TemplateName.Identifier;
1027       TemplateId->Operator = OO_None;
1028     } else {
1029       TemplateId->Name = nullptr;
1030       TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
1031     }
1032     TemplateId->SS = SS;
1033     TemplateId->TemplateKWLoc = TemplateKWLoc;
1034     TemplateId->Template = Template;
1035     TemplateId->Kind = TNK;
1036     TemplateId->LAngleLoc = LAngleLoc;
1037     TemplateId->RAngleLoc = RAngleLoc;
1038     ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1039     for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
1040       Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
1041     Tok.setAnnotationValue(TemplateId);
1042     if (TemplateKWLoc.isValid())
1043       Tok.setLocation(TemplateKWLoc);
1044     else
1045       Tok.setLocation(TemplateNameLoc);
1046   }
1047 
1048   // Common fields for the annotation token
1049   Tok.setAnnotationEndLoc(RAngleLoc);
1050 
1051   // In case the tokens were cached, have Preprocessor replace them with the
1052   // annotation token.
1053   PP.AnnotateCachedTokens(Tok);
1054   return false;
1055 }
1056 
1057 /// \brief Replaces a template-id annotation token with a type
1058 /// annotation token.
1059 ///
1060 /// If there was a failure when forming the type from the template-id,
1061 /// a type annotation token will still be created, but will have a
1062 /// NULL type pointer to signify an error.
1063 void Parser::AnnotateTemplateIdTokenAsType() {
1064   assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1065 
1066   TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1067   assert((TemplateId->Kind == TNK_Type_template ||
1068           TemplateId->Kind == TNK_Dependent_template_name) &&
1069          "Only works for type and dependent templates");
1070 
1071   ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1072                                      TemplateId->NumArgs);
1073 
1074   TypeResult Type
1075     = Actions.ActOnTemplateIdType(TemplateId->SS,
1076                                   TemplateId->TemplateKWLoc,
1077                                   TemplateId->Template,
1078                                   TemplateId->TemplateNameLoc,
1079                                   TemplateId->LAngleLoc,
1080                                   TemplateArgsPtr,
1081                                   TemplateId->RAngleLoc);
1082   // Create the new "type" annotation token.
1083   Tok.setKind(tok::annot_typename);
1084   setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
1085   if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1086     Tok.setLocation(TemplateId->SS.getBeginLoc());
1087   // End location stays the same
1088 
1089   // Replace the template-id annotation token, and possible the scope-specifier
1090   // that precedes it, with the typename annotation token.
1091   PP.AnnotateCachedTokens(Tok);
1092 }
1093 
1094 /// \brief Determine whether the given token can end a template argument.
1095 static bool isEndOfTemplateArgument(Token Tok) {
1096   return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
1097 }
1098 
1099 /// \brief Parse a C++ template template argument.
1100 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1101   if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1102       !Tok.is(tok::annot_cxxscope))
1103     return ParsedTemplateArgument();
1104 
1105   // C++0x [temp.arg.template]p1:
1106   //   A template-argument for a template template-parameter shall be the name
1107   //   of a class template or an alias template, expressed as id-expression.
1108   //
1109   // We parse an id-expression that refers to a class template or alias
1110   // template. The grammar we parse is:
1111   //
1112   //   nested-name-specifier[opt] template[opt] identifier ...[opt]
1113   //
1114   // followed by a token that terminates a template argument, such as ',',
1115   // '>', or (in some cases) '>>'.
1116   CXXScopeSpec SS; // nested-name-specifier, if present
1117   ParseOptionalCXXScopeSpecifier(SS, nullptr,
1118                                  /*EnteringContext=*/false);
1119 
1120   ParsedTemplateArgument Result;
1121   SourceLocation EllipsisLoc;
1122   if (SS.isSet() && Tok.is(tok::kw_template)) {
1123     // Parse the optional 'template' keyword following the
1124     // nested-name-specifier.
1125     SourceLocation TemplateKWLoc = ConsumeToken();
1126 
1127     if (Tok.is(tok::identifier)) {
1128       // We appear to have a dependent template name.
1129       UnqualifiedId Name;
1130       Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1131       ConsumeToken(); // the identifier
1132 
1133       TryConsumeToken(tok::ellipsis, EllipsisLoc);
1134 
1135       // If the next token signals the end of a template argument,
1136       // then we have a dependent template name that could be a template
1137       // template argument.
1138       TemplateTy Template;
1139       if (isEndOfTemplateArgument(Tok) &&
1140           Actions.ActOnDependentTemplateName(
1141               getCurScope(), SS, TemplateKWLoc, Name,
1142               /*ObjectType=*/nullptr,
1143               /*EnteringContext=*/false, Template))
1144         Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1145     }
1146   } else if (Tok.is(tok::identifier)) {
1147     // We may have a (non-dependent) template name.
1148     TemplateTy Template;
1149     UnqualifiedId Name;
1150     Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1151     ConsumeToken(); // the identifier
1152 
1153     TryConsumeToken(tok::ellipsis, EllipsisLoc);
1154 
1155     if (isEndOfTemplateArgument(Tok)) {
1156       bool MemberOfUnknownSpecialization;
1157       TemplateNameKind TNK = Actions.isTemplateName(
1158           getCurScope(), SS,
1159           /*hasTemplateKeyword=*/false, Name,
1160           /*ObjectType=*/nullptr,
1161           /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
1162       if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1163         // We have an id-expression that refers to a class template or
1164         // (C++0x) alias template.
1165         Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1166       }
1167     }
1168   }
1169 
1170   // If this is a pack expansion, build it as such.
1171   if (EllipsisLoc.isValid() && !Result.isInvalid())
1172     Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1173 
1174   return Result;
1175 }
1176 
1177 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1178 ///
1179 ///       template-argument: [C++ 14.2]
1180 ///         constant-expression
1181 ///         type-id
1182 ///         id-expression
1183 ParsedTemplateArgument Parser::ParseTemplateArgument() {
1184   // C++ [temp.arg]p2:
1185   //   In a template-argument, an ambiguity between a type-id and an
1186   //   expression is resolved to a type-id, regardless of the form of
1187   //   the corresponding template-parameter.
1188   //
1189   // Therefore, we initially try to parse a type-id.
1190   if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1191     SourceLocation Loc = Tok.getLocation();
1192     TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
1193                                        Declarator::TemplateTypeArgContext);
1194     if (TypeArg.isInvalid())
1195       return ParsedTemplateArgument();
1196 
1197     return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1198                                   TypeArg.get().getAsOpaquePtr(),
1199                                   Loc);
1200   }
1201 
1202   // Try to parse a template template argument.
1203   {
1204     TentativeParsingAction TPA(*this);
1205 
1206     ParsedTemplateArgument TemplateTemplateArgument
1207       = ParseTemplateTemplateArgument();
1208     if (!TemplateTemplateArgument.isInvalid()) {
1209       TPA.Commit();
1210       return TemplateTemplateArgument;
1211     }
1212 
1213     // Revert this tentative parse to parse a non-type template argument.
1214     TPA.Revert();
1215   }
1216 
1217   // Parse a non-type template argument.
1218   SourceLocation Loc = Tok.getLocation();
1219   ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1220   if (ExprArg.isInvalid() || !ExprArg.get())
1221     return ParsedTemplateArgument();
1222 
1223   return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1224                                 ExprArg.get(), Loc);
1225 }
1226 
1227 /// \brief Determine whether the current tokens can only be parsed as a
1228 /// template argument list (starting with the '<') and never as a '<'
1229 /// expression.
1230 bool Parser::IsTemplateArgumentList(unsigned Skip) {
1231   struct AlwaysRevertAction : TentativeParsingAction {
1232     AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1233     ~AlwaysRevertAction() { Revert(); }
1234   } Tentative(*this);
1235 
1236   while (Skip) {
1237     ConsumeToken();
1238     --Skip;
1239   }
1240 
1241   // '<'
1242   if (!TryConsumeToken(tok::less))
1243     return false;
1244 
1245   // An empty template argument list.
1246   if (Tok.is(tok::greater))
1247     return true;
1248 
1249   // See whether we have declaration specifiers, which indicate a type.
1250   while (isCXXDeclarationSpecifier() == TPResult::True)
1251     ConsumeToken();
1252 
1253   // If we have a '>' or a ',' then this is a template argument list.
1254   return Tok.isOneOf(tok::greater, tok::comma);
1255 }
1256 
1257 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1258 /// (C++ [temp.names]). Returns true if there was an error.
1259 ///
1260 ///       template-argument-list: [C++ 14.2]
1261 ///         template-argument
1262 ///         template-argument-list ',' template-argument
1263 bool
1264 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1265   // Template argument lists are constant-evaluation contexts.
1266   EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
1267   ColonProtectionRAIIObject ColonProtection(*this, false);
1268 
1269   do {
1270     ParsedTemplateArgument Arg = ParseTemplateArgument();
1271     SourceLocation EllipsisLoc;
1272     if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1273       Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1274 
1275     if (Arg.isInvalid()) {
1276       SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
1277       return true;
1278     }
1279 
1280     // Save this template argument.
1281     TemplateArgs.push_back(Arg);
1282 
1283     // If the next token is a comma, consume it and keep reading
1284     // arguments.
1285   } while (TryConsumeToken(tok::comma));
1286 
1287   return false;
1288 }
1289 
1290 /// \brief Parse a C++ explicit template instantiation
1291 /// (C++ [temp.explicit]).
1292 ///
1293 ///       explicit-instantiation:
1294 ///         'extern' [opt] 'template' declaration
1295 ///
1296 /// Note that the 'extern' is a GNU extension and C++11 feature.
1297 Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1298                                          SourceLocation ExternLoc,
1299                                          SourceLocation TemplateLoc,
1300                                          SourceLocation &DeclEnd,
1301                                          AccessSpecifier AS) {
1302   // This isn't really required here.
1303   ParsingDeclRAIIObject
1304     ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1305 
1306   return ParseSingleDeclarationAfterTemplate(Context,
1307                                              ParsedTemplateInfo(ExternLoc,
1308                                                                 TemplateLoc),
1309                                              ParsingTemplateParams,
1310                                              DeclEnd, AS);
1311 }
1312 
1313 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1314   if (TemplateParams)
1315     return getTemplateParamsRange(TemplateParams->data(),
1316                                   TemplateParams->size());
1317 
1318   SourceRange R(TemplateLoc);
1319   if (ExternLoc.isValid())
1320     R.setBegin(ExternLoc);
1321   return R;
1322 }
1323 
1324 void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1325   ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1326 }
1327 
1328 /// \brief Late parse a C++ function template in Microsoft mode.
1329 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1330   if (!LPT.D)
1331      return;
1332 
1333   // Get the FunctionDecl.
1334   FunctionDecl *FunD = LPT.D->getAsFunction();
1335   // Track template parameter depth.
1336   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1337 
1338   // To restore the context after late parsing.
1339   Sema::ContextRAII GlobalSavedContext(
1340       Actions, Actions.Context.getTranslationUnitDecl());
1341 
1342   SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1343 
1344   // Get the list of DeclContexts to reenter.
1345   SmallVector<DeclContext*, 4> DeclContextsToReenter;
1346   DeclContext *DD = FunD;
1347   while (DD && !DD->isTranslationUnit()) {
1348     DeclContextsToReenter.push_back(DD);
1349     DD = DD->getLexicalParent();
1350   }
1351 
1352   // Reenter template scopes from outermost to innermost.
1353   SmallVectorImpl<DeclContext *>::reverse_iterator II =
1354       DeclContextsToReenter.rbegin();
1355   for (; II != DeclContextsToReenter.rend(); ++II) {
1356     TemplateParamScopeStack.push_back(new ParseScope(this,
1357           Scope::TemplateParamScope));
1358     unsigned NumParamLists =
1359       Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1360     CurTemplateDepthTracker.addDepth(NumParamLists);
1361     if (*II != FunD) {
1362       TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1363       Actions.PushDeclContext(Actions.getCurScope(), *II);
1364     }
1365   }
1366 
1367   assert(!LPT.Toks.empty() && "Empty body!");
1368 
1369   // Append the current token at the end of the new token stream so that it
1370   // doesn't get lost.
1371   LPT.Toks.push_back(Tok);
1372   PP.EnterTokenStream(LPT.Toks, true);
1373 
1374   // Consume the previously pushed token.
1375   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1376   assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1377          "Inline method not starting with '{', ':' or 'try'");
1378 
1379   // Parse the method body. Function body parsing code is similar enough
1380   // to be re-used for method bodies as well.
1381   ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1382 
1383   // Recreate the containing function DeclContext.
1384   Sema::ContextRAII FunctionSavedContext(Actions,
1385                                          Actions.getContainingDC(FunD));
1386 
1387   Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1388 
1389   if (Tok.is(tok::kw_try)) {
1390     ParseFunctionTryBlock(LPT.D, FnScope);
1391   } else {
1392     if (Tok.is(tok::colon))
1393       ParseConstructorInitializer(LPT.D);
1394     else
1395       Actions.ActOnDefaultCtorInitializers(LPT.D);
1396 
1397     if (Tok.is(tok::l_brace)) {
1398       assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1399               cast<FunctionTemplateDecl>(LPT.D)
1400                       ->getTemplateParameters()
1401                       ->getDepth() == TemplateParameterDepth - 1) &&
1402              "TemplateParameterDepth should be greater than the depth of "
1403              "current template being instantiated!");
1404       ParseFunctionStatementBody(LPT.D, FnScope);
1405       Actions.UnmarkAsLateParsedTemplate(FunD);
1406     } else
1407       Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1408   }
1409 
1410   // Exit scopes.
1411   FnScope.Exit();
1412   SmallVectorImpl<ParseScope *>::reverse_iterator I =
1413    TemplateParamScopeStack.rbegin();
1414   for (; I != TemplateParamScopeStack.rend(); ++I)
1415     delete *I;
1416 }
1417 
1418 /// \brief Lex a delayed template function for late parsing.
1419 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1420   tok::TokenKind kind = Tok.getKind();
1421   if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1422     // Consume everything up to (and including) the matching right brace.
1423     ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1424   }
1425 
1426   // If we're in a function-try-block, we need to store all the catch blocks.
1427   if (kind == tok::kw_try) {
1428     while (Tok.is(tok::kw_catch)) {
1429       ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1430       ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1431     }
1432   }
1433 }
1434