1 //===--- ParseTemplate.cpp - Template Parsing -----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements parsing of C++ templates.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclTemplate.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/Parse/ParseDiagnostic.h"
17 #include "clang/Parse/Parser.h"
18 #include "clang/Parse/RAIIObjectsForParser.h"
19 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/ParsedTemplate.h"
21 #include "clang/Sema/Scope.h"
22 #include "llvm/Support/TimeProfiler.h"
23 using namespace clang;
24 
25 /// Parse a template declaration, explicit instantiation, or
26 /// explicit specialization.
27 Decl *Parser::ParseDeclarationStartingWithTemplate(
28     DeclaratorContext Context, SourceLocation &DeclEnd,
29     ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
30   ObjCDeclContextSwitch ObjCDC(*this);
31 
32   if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
33     return ParseExplicitInstantiation(Context, SourceLocation(), ConsumeToken(),
34                                       DeclEnd, AccessAttrs, AS);
35   }
36   return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AccessAttrs,
37                                                   AS);
38 }
39 
40 /// Parse a template declaration or an explicit specialization.
41 ///
42 /// Template declarations include one or more template parameter lists
43 /// and either the function or class template declaration. Explicit
44 /// specializations contain one or more 'template < >' prefixes
45 /// followed by a (possibly templated) declaration. Since the
46 /// syntactic form of both features is nearly identical, we parse all
47 /// of the template headers together and let semantic analysis sort
48 /// the declarations from the explicit specializations.
49 ///
50 ///       template-declaration: [C++ temp]
51 ///         'export'[opt] 'template' '<' template-parameter-list '>' declaration
52 ///
53 ///       template-declaration: [C++2a]
54 ///         template-head declaration
55 ///         template-head concept-definition
56 ///
57 ///       TODO: requires-clause
58 ///       template-head: [C++2a]
59 ///         'template' '<' template-parameter-list '>'
60 ///             requires-clause[opt]
61 ///
62 ///       explicit-specialization: [ C++ temp.expl.spec]
63 ///         'template' '<' '>' declaration
64 Decl *Parser::ParseTemplateDeclarationOrSpecialization(
65     DeclaratorContext Context, SourceLocation &DeclEnd,
66     ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
67   assert(Tok.isOneOf(tok::kw_export, tok::kw_template) &&
68          "Token does not start a template declaration.");
69 
70   // Enter template-parameter scope.
71   ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
72 
73   // Tell the action that names should be checked in the context of
74   // the declaration to come.
75   ParsingDeclRAIIObject
76     ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
77 
78   // Parse multiple levels of template headers within this template
79   // parameter scope, e.g.,
80   //
81   //   template<typename T>
82   //     template<typename U>
83   //       class A<T>::B { ... };
84   //
85   // We parse multiple levels non-recursively so that we can build a
86   // single data structure containing all of the template parameter
87   // lists to easily differentiate between the case above and:
88   //
89   //   template<typename T>
90   //   class A {
91   //     template<typename U> class B;
92   //   };
93   //
94   // In the first case, the action for declaring A<T>::B receives
95   // both template parameter lists. In the second case, the action for
96   // defining A<T>::B receives just the inner template parameter list
97   // (and retrieves the outer template parameter list from its
98   // context).
99   bool isSpecialization = true;
100   bool LastParamListWasEmpty = false;
101   TemplateParameterLists ParamLists;
102   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
103 
104   do {
105     // Consume the 'export', if any.
106     SourceLocation ExportLoc;
107     TryConsumeToken(tok::kw_export, ExportLoc);
108 
109     // Consume the 'template', which should be here.
110     SourceLocation TemplateLoc;
111     if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
112       Diag(Tok.getLocation(), diag::err_expected_template);
113       return nullptr;
114     }
115 
116     // Parse the '<' template-parameter-list '>'
117     SourceLocation LAngleLoc, RAngleLoc;
118     SmallVector<NamedDecl*, 4> TemplateParams;
119     if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
120                                 TemplateParams, LAngleLoc, RAngleLoc)) {
121       // Skip until the semi-colon or a '}'.
122       SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
123       TryConsumeToken(tok::semi);
124       return nullptr;
125     }
126 
127     ExprResult OptionalRequiresClauseConstraintER;
128     if (!TemplateParams.empty()) {
129       isSpecialization = false;
130       ++CurTemplateDepthTracker;
131 
132       if (TryConsumeToken(tok::kw_requires)) {
133         OptionalRequiresClauseConstraintER =
134             Actions.CorrectDelayedTyposInExpr(
135                 ParseConstraintLogicalOrExpression(
136                     /*IsTrailingRequiresClause=*/false));
137         if (!OptionalRequiresClauseConstraintER.isUsable()) {
138           // Skip until the semi-colon or a '}'.
139           SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
140           TryConsumeToken(tok::semi);
141           return nullptr;
142         }
143       }
144     } else {
145       LastParamListWasEmpty = true;
146     }
147 
148     ParamLists.push_back(Actions.ActOnTemplateParameterList(
149         CurTemplateDepthTracker.getDepth(), ExportLoc, TemplateLoc, LAngleLoc,
150         TemplateParams, RAngleLoc, OptionalRequiresClauseConstraintER.get()));
151   } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
152 
153   unsigned NewFlags = getCurScope()->getFlags() & ~Scope::TemplateParamScope;
154   ParseScopeFlags TemplateScopeFlags(this, NewFlags, isSpecialization);
155 
156   // Parse the actual template declaration.
157   if (Tok.is(tok::kw_concept))
158     return ParseConceptDefinition(
159         ParsedTemplateInfo(&ParamLists, isSpecialization,
160                            LastParamListWasEmpty),
161         DeclEnd);
162 
163   return ParseSingleDeclarationAfterTemplate(
164       Context,
165       ParsedTemplateInfo(&ParamLists, isSpecialization, LastParamListWasEmpty),
166       ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
167 }
168 
169 /// Parse a single declaration that declares a template,
170 /// template specialization, or explicit instantiation of a template.
171 ///
172 /// \param DeclEnd will receive the source location of the last token
173 /// within this declaration.
174 ///
175 /// \param AS the access specifier associated with this
176 /// declaration. Will be AS_none for namespace-scope declarations.
177 ///
178 /// \returns the new declaration.
179 Decl *Parser::ParseSingleDeclarationAfterTemplate(
180     DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
181     ParsingDeclRAIIObject &DiagsFromTParams, SourceLocation &DeclEnd,
182     ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
183   assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
184          "Template information required");
185 
186   if (Tok.is(tok::kw_static_assert)) {
187     // A static_assert declaration may not be templated.
188     Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
189       << TemplateInfo.getSourceRange();
190     // Parse the static_assert declaration to improve error recovery.
191     return ParseStaticAssertDeclaration(DeclEnd);
192   }
193 
194   if (Context == DeclaratorContext::MemberContext) {
195     // We are parsing a member template.
196     ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
197                                    &DiagsFromTParams);
198     return nullptr;
199   }
200 
201   ParsedAttributesWithRange prefixAttrs(AttrFactory);
202   MaybeParseCXX11Attributes(prefixAttrs);
203 
204   if (Tok.is(tok::kw_using)) {
205     auto usingDeclPtr = ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
206                                                          prefixAttrs);
207     if (!usingDeclPtr || !usingDeclPtr.get().isSingleDecl())
208       return nullptr;
209     return usingDeclPtr.get().getSingleDecl();
210   }
211 
212   // Parse the declaration specifiers, stealing any diagnostics from
213   // the template parameters.
214   ParsingDeclSpec DS(*this, &DiagsFromTParams);
215 
216   ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
217                              getDeclSpecContextFromDeclaratorContext(Context));
218 
219   if (Tok.is(tok::semi)) {
220     ProhibitAttributes(prefixAttrs);
221     DeclEnd = ConsumeToken();
222     RecordDecl *AnonRecord = nullptr;
223     Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
224         getCurScope(), AS, DS,
225         TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
226                                     : MultiTemplateParamsArg(),
227         TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
228         AnonRecord);
229     assert(!AnonRecord &&
230            "Anonymous unions/structs should not be valid with template");
231     DS.complete(Decl);
232     return Decl;
233   }
234 
235   // Move the attributes from the prefix into the DS.
236   if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
237     ProhibitAttributes(prefixAttrs);
238   else
239     DS.takeAttributesFrom(prefixAttrs);
240 
241   // Parse the declarator.
242   ParsingDeclarator DeclaratorInfo(*this, DS, (DeclaratorContext)Context);
243   if (TemplateInfo.TemplateParams)
244     DeclaratorInfo.setTemplateParameterLists(*TemplateInfo.TemplateParams);
245   ParseDeclarator(DeclaratorInfo);
246   // Error parsing the declarator?
247   if (!DeclaratorInfo.hasName()) {
248     // If so, skip until the semi-colon or a }.
249     SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
250     if (Tok.is(tok::semi))
251       ConsumeToken();
252     return nullptr;
253   }
254 
255   llvm::TimeTraceScope TimeScope("ParseTemplate", [&]() {
256     return std::string(DeclaratorInfo.getIdentifier() != nullptr
257                            ? DeclaratorInfo.getIdentifier()->getName()
258                            : "<unknown>");
259   });
260 
261   LateParsedAttrList LateParsedAttrs(true);
262   if (DeclaratorInfo.isFunctionDeclarator()) {
263     if (Tok.is(tok::kw_requires))
264       ParseTrailingRequiresClause(DeclaratorInfo);
265 
266     MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
267   }
268 
269   if (DeclaratorInfo.isFunctionDeclarator() &&
270       isStartOfFunctionDefinition(DeclaratorInfo)) {
271 
272     // Function definitions are only allowed at file scope and in C++ classes.
273     // The C++ inline method definition case is handled elsewhere, so we only
274     // need to handle the file scope definition case.
275     if (Context != DeclaratorContext::FileContext) {
276       Diag(Tok, diag::err_function_definition_not_allowed);
277       SkipMalformedDecl();
278       return nullptr;
279     }
280 
281     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
282       // Recover by ignoring the 'typedef'. This was probably supposed to be
283       // the 'typename' keyword, which we should have already suggested adding
284       // if it's appropriate.
285       Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
286         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
287       DS.ClearStorageClassSpecs();
288     }
289 
290     if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
291       if (DeclaratorInfo.getName().getKind() !=
292           UnqualifiedIdKind::IK_TemplateId) {
293         // If the declarator-id is not a template-id, issue a diagnostic and
294         // recover by ignoring the 'template' keyword.
295         Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
296         return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
297                                        &LateParsedAttrs);
298       } else {
299         SourceLocation LAngleLoc
300           = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
301         Diag(DeclaratorInfo.getIdentifierLoc(),
302              diag::err_explicit_instantiation_with_definition)
303             << SourceRange(TemplateInfo.TemplateLoc)
304             << FixItHint::CreateInsertion(LAngleLoc, "<>");
305 
306         // Recover as if it were an explicit specialization.
307         TemplateParameterLists FakedParamLists;
308         FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
309             0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
310             LAngleLoc, nullptr));
311 
312         return ParseFunctionDefinition(
313             DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
314                                                /*isSpecialization=*/true,
315                                                /*lastParameterListWasEmpty=*/true),
316             &LateParsedAttrs);
317       }
318     }
319     return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
320                                    &LateParsedAttrs);
321   }
322 
323   // Parse this declaration.
324   Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
325                                                    TemplateInfo);
326 
327   if (Tok.is(tok::comma)) {
328     Diag(Tok, diag::err_multiple_template_declarators)
329       << (int)TemplateInfo.Kind;
330     SkipUntil(tok::semi);
331     return ThisDecl;
332   }
333 
334   // Eat the semi colon after the declaration.
335   ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
336   if (LateParsedAttrs.size() > 0)
337     ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
338   DeclaratorInfo.complete(ThisDecl);
339   return ThisDecl;
340 }
341 
342 /// \brief Parse a single declaration that declares a concept.
343 ///
344 /// \param DeclEnd will receive the source location of the last token
345 /// within this declaration.
346 ///
347 /// \returns the new declaration.
348 Decl *
349 Parser::ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
350                                SourceLocation &DeclEnd) {
351   assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
352          "Template information required");
353   assert(Tok.is(tok::kw_concept) &&
354          "ParseConceptDefinition must be called when at a 'concept' keyword");
355 
356   ConsumeToken(); // Consume 'concept'
357 
358   SourceLocation BoolKWLoc;
359   if (TryConsumeToken(tok::kw_bool, BoolKWLoc))
360     Diag(Tok.getLocation(), diag::ext_concept_legacy_bool_keyword) <<
361         FixItHint::CreateRemoval(SourceLocation(BoolKWLoc));
362 
363   DiagnoseAndSkipCXX11Attributes();
364 
365   CXXScopeSpec SS;
366   if (ParseOptionalCXXScopeSpecifier(
367           SS, /*ObjectType=*/nullptr,
368           /*ObjectHadErrors=*/false, /*EnteringContext=*/false,
369           /*MayBePseudoDestructor=*/nullptr,
370           /*IsTypename=*/false, /*LastII=*/nullptr, /*OnlyNamespace=*/true) ||
371       SS.isInvalid()) {
372     SkipUntil(tok::semi);
373     return nullptr;
374   }
375 
376   if (SS.isNotEmpty())
377     Diag(SS.getBeginLoc(),
378          diag::err_concept_definition_not_identifier);
379 
380   UnqualifiedId Result;
381   if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
382                          /*ObjectHadErrors=*/false, /*EnteringContext=*/false,
383                          /*AllowDestructorName=*/false,
384                          /*AllowConstructorName=*/false,
385                          /*AllowDeductionGuide=*/false,
386                          /*TemplateKWLoc=*/nullptr, Result)) {
387     SkipUntil(tok::semi);
388     return nullptr;
389   }
390 
391   if (Result.getKind() != UnqualifiedIdKind::IK_Identifier) {
392     Diag(Result.getBeginLoc(), diag::err_concept_definition_not_identifier);
393     SkipUntil(tok::semi);
394     return nullptr;
395   }
396 
397   IdentifierInfo *Id = Result.Identifier;
398   SourceLocation IdLoc = Result.getBeginLoc();
399 
400   DiagnoseAndSkipCXX11Attributes();
401 
402   if (!TryConsumeToken(tok::equal)) {
403     Diag(Tok.getLocation(), diag::err_expected) << tok::equal;
404     SkipUntil(tok::semi);
405     return nullptr;
406   }
407 
408   ExprResult ConstraintExprResult =
409       Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
410   if (ConstraintExprResult.isInvalid()) {
411     SkipUntil(tok::semi);
412     return nullptr;
413   }
414 
415   DeclEnd = Tok.getLocation();
416   ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
417   Expr *ConstraintExpr = ConstraintExprResult.get();
418   return Actions.ActOnConceptDefinition(getCurScope(),
419                                         *TemplateInfo.TemplateParams,
420                                         Id, IdLoc, ConstraintExpr);
421 }
422 
423 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
424 /// angle brackets. Depth is the depth of this template-parameter-list, which
425 /// is the number of template headers directly enclosing this template header.
426 /// TemplateParams is the current list of template parameters we're building.
427 /// The template parameter we parse will be added to this list. LAngleLoc and
428 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
429 /// that enclose this template parameter list.
430 ///
431 /// \returns true if an error occurred, false otherwise.
432 bool Parser::ParseTemplateParameters(
433     unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams,
434     SourceLocation &LAngleLoc, SourceLocation &RAngleLoc) {
435   // Get the template parameter list.
436   if (!TryConsumeToken(tok::less, LAngleLoc)) {
437     Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
438     return true;
439   }
440 
441   // Try to parse the template parameter list.
442   bool Failed = false;
443   if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
444     Failed = ParseTemplateParameterList(Depth, TemplateParams);
445 
446   if (Tok.is(tok::greatergreater)) {
447     // No diagnostic required here: a template-parameter-list can only be
448     // followed by a declaration or, for a template template parameter, the
449     // 'class' keyword. Therefore, the second '>' will be diagnosed later.
450     // This matters for elegant diagnosis of:
451     //   template<template<typename>> struct S;
452     Tok.setKind(tok::greater);
453     RAngleLoc = Tok.getLocation();
454     Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
455   } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
456     Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
457     return true;
458   }
459   return false;
460 }
461 
462 /// ParseTemplateParameterList - Parse a template parameter list. If
463 /// the parsing fails badly (i.e., closing bracket was left out), this
464 /// will try to put the token stream in a reasonable position (closing
465 /// a statement, etc.) and return false.
466 ///
467 ///       template-parameter-list:    [C++ temp]
468 ///         template-parameter
469 ///         template-parameter-list ',' template-parameter
470 bool
471 Parser::ParseTemplateParameterList(const unsigned Depth,
472                              SmallVectorImpl<NamedDecl*> &TemplateParams) {
473   while (1) {
474 
475     if (NamedDecl *TmpParam
476           = ParseTemplateParameter(Depth, TemplateParams.size())) {
477       TemplateParams.push_back(TmpParam);
478     } else {
479       // If we failed to parse a template parameter, skip until we find
480       // a comma or closing brace.
481       SkipUntil(tok::comma, tok::greater, tok::greatergreater,
482                 StopAtSemi | StopBeforeMatch);
483     }
484 
485     // Did we find a comma or the end of the template parameter list?
486     if (Tok.is(tok::comma)) {
487       ConsumeToken();
488     } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
489       // Don't consume this... that's done by template parser.
490       break;
491     } else {
492       // Somebody probably forgot to close the template. Skip ahead and
493       // try to get out of the expression. This error is currently
494       // subsumed by whatever goes on in ParseTemplateParameter.
495       Diag(Tok.getLocation(), diag::err_expected_comma_greater);
496       SkipUntil(tok::comma, tok::greater, tok::greatergreater,
497                 StopAtSemi | StopBeforeMatch);
498       return false;
499     }
500   }
501   return true;
502 }
503 
504 /// Determine whether the parser is at the start of a template
505 /// type parameter.
506 Parser::TPResult Parser::isStartOfTemplateTypeParameter() {
507   if (Tok.is(tok::kw_class)) {
508     // "class" may be the start of an elaborated-type-specifier or a
509     // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
510     switch (NextToken().getKind()) {
511     case tok::equal:
512     case tok::comma:
513     case tok::greater:
514     case tok::greatergreater:
515     case tok::ellipsis:
516       return TPResult::True;
517 
518     case tok::identifier:
519       // This may be either a type-parameter or an elaborated-type-specifier.
520       // We have to look further.
521       break;
522 
523     default:
524       return TPResult::False;
525     }
526 
527     switch (GetLookAheadToken(2).getKind()) {
528     case tok::equal:
529     case tok::comma:
530     case tok::greater:
531     case tok::greatergreater:
532       return TPResult::True;
533 
534     default:
535       return TPResult::False;
536     }
537   }
538 
539   if (TryAnnotateTypeConstraint())
540     return TPResult::Error;
541 
542   if (isTypeConstraintAnnotation() &&
543       // Next token might be 'auto' or 'decltype', indicating that this
544       // type-constraint is in fact part of a placeholder-type-specifier of a
545       // non-type template parameter.
546       !GetLookAheadToken(Tok.is(tok::annot_cxxscope) ? 2 : 1)
547            .isOneOf(tok::kw_auto, tok::kw_decltype))
548     return TPResult::True;
549 
550   // 'typedef' is a reasonably-common typo/thinko for 'typename', and is
551   // ill-formed otherwise.
552   if (Tok.isNot(tok::kw_typename) && Tok.isNot(tok::kw_typedef))
553     return TPResult::False;
554 
555   // C++ [temp.param]p2:
556   //   There is no semantic difference between class and typename in a
557   //   template-parameter. typename followed by an unqualified-id
558   //   names a template type parameter. typename followed by a
559   //   qualified-id denotes the type in a non-type
560   //   parameter-declaration.
561   Token Next = NextToken();
562 
563   // If we have an identifier, skip over it.
564   if (Next.getKind() == tok::identifier)
565     Next = GetLookAheadToken(2);
566 
567   switch (Next.getKind()) {
568   case tok::equal:
569   case tok::comma:
570   case tok::greater:
571   case tok::greatergreater:
572   case tok::ellipsis:
573     return TPResult::True;
574 
575   case tok::kw_typename:
576   case tok::kw_typedef:
577   case tok::kw_class:
578     // These indicate that a comma was missed after a type parameter, not that
579     // we have found a non-type parameter.
580     return TPResult::True;
581 
582   default:
583     return TPResult::False;
584   }
585 }
586 
587 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
588 ///
589 ///       template-parameter: [C++ temp.param]
590 ///         type-parameter
591 ///         parameter-declaration
592 ///
593 ///       type-parameter: (See below)
594 ///         type-parameter-key ...[opt] identifier[opt]
595 ///         type-parameter-key identifier[opt] = type-id
596 /// (C++2a) type-constraint ...[opt] identifier[opt]
597 /// (C++2a) type-constraint identifier[opt] = type-id
598 ///         'template' '<' template-parameter-list '>' type-parameter-key
599 ///               ...[opt] identifier[opt]
600 ///         'template' '<' template-parameter-list '>' type-parameter-key
601 ///               identifier[opt] '=' id-expression
602 ///
603 ///       type-parameter-key:
604 ///         class
605 ///         typename
606 ///
607 NamedDecl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
608 
609   switch (isStartOfTemplateTypeParameter()) {
610   case TPResult::True:
611     // Is there just a typo in the input code? ('typedef' instead of
612     // 'typename')
613     if (Tok.is(tok::kw_typedef)) {
614       Diag(Tok.getLocation(), diag::err_expected_template_parameter);
615 
616       Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
617           << FixItHint::CreateReplacement(CharSourceRange::getCharRange(
618                                               Tok.getLocation(),
619                                               Tok.getEndLoc()),
620                                           "typename");
621 
622       Tok.setKind(tok::kw_typename);
623     }
624 
625     return ParseTypeParameter(Depth, Position);
626   case TPResult::False:
627     break;
628 
629   case TPResult::Error: {
630     // We return an invalid parameter as opposed to null to avoid having bogus
631     // diagnostics about an empty template parameter list.
632     // FIXME: Fix ParseTemplateParameterList to better handle nullptr results
633     //  from here.
634     // Return a NTTP as if there was an error in a scope specifier, the user
635     // probably meant to write the type of a NTTP.
636     DeclSpec DS(getAttrFactory());
637     DS.SetTypeSpecError();
638     Declarator D(DS, DeclaratorContext::TemplateParamContext);
639     D.SetIdentifier(nullptr, Tok.getLocation());
640     D.setInvalidType(true);
641     NamedDecl *ErrorParam = Actions.ActOnNonTypeTemplateParameter(
642         getCurScope(), D, Depth, Position, /*EqualLoc=*/SourceLocation(),
643         /*DefaultArg=*/nullptr);
644     ErrorParam->setInvalidDecl(true);
645     SkipUntil(tok::comma, tok::greater, tok::greatergreater,
646               StopAtSemi | StopBeforeMatch);
647     return ErrorParam;
648   }
649 
650   case TPResult::Ambiguous:
651     llvm_unreachable("template param classification can't be ambiguous");
652   }
653 
654   if (Tok.is(tok::kw_template))
655     return ParseTemplateTemplateParameter(Depth, Position);
656 
657   // If it's none of the above, then it must be a parameter declaration.
658   // NOTE: This will pick up errors in the closure of the template parameter
659   // list (e.g., template < ; Check here to implement >> style closures.
660   return ParseNonTypeTemplateParameter(Depth, Position);
661 }
662 
663 /// Check whether the current token is a template-id annotation denoting a
664 /// type-constraint.
665 bool Parser::isTypeConstraintAnnotation() {
666   const Token &T = Tok.is(tok::annot_cxxscope) ? NextToken() : Tok;
667   if (T.isNot(tok::annot_template_id))
668     return false;
669   const auto *ExistingAnnot =
670       static_cast<TemplateIdAnnotation *>(T.getAnnotationValue());
671   return ExistingAnnot->Kind == TNK_Concept_template;
672 }
673 
674 /// Try parsing a type-constraint at the current location.
675 ///
676 ///     type-constraint:
677 ///       nested-name-specifier[opt] concept-name
678 ///       nested-name-specifier[opt] concept-name
679 ///           '<' template-argument-list[opt] '>'[opt]
680 ///
681 /// \returns true if an error occurred, and false otherwise.
682 bool Parser::TryAnnotateTypeConstraint() {
683   if (!getLangOpts().CPlusPlus20)
684     return false;
685   CXXScopeSpec SS;
686   bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
687   if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
688                                      /*ObjectHadErrors=*/false,
689                                      /*EnteringContext=*/false,
690                                      /*MayBePseudoDestructor=*/nullptr,
691                                      // If this is not a type-constraint, then
692                                      // this scope-spec is part of the typename
693                                      // of a non-type template parameter
694                                      /*IsTypename=*/true, /*LastII=*/nullptr,
695                                      // We won't find concepts in
696                                      // non-namespaces anyway, so might as well
697                                      // parse this correctly for possible type
698                                      // names.
699                                      /*OnlyNamespace=*/false))
700     return true;
701 
702   if (Tok.is(tok::identifier)) {
703     UnqualifiedId PossibleConceptName;
704     PossibleConceptName.setIdentifier(Tok.getIdentifierInfo(),
705                                       Tok.getLocation());
706 
707     TemplateTy PossibleConcept;
708     bool MemberOfUnknownSpecialization = false;
709     auto TNK = Actions.isTemplateName(getCurScope(), SS,
710                                       /*hasTemplateKeyword=*/false,
711                                       PossibleConceptName,
712                                       /*ObjectType=*/ParsedType(),
713                                       /*EnteringContext=*/false,
714                                       PossibleConcept,
715                                       MemberOfUnknownSpecialization,
716                                       /*Disambiguation=*/true);
717     if (MemberOfUnknownSpecialization || !PossibleConcept ||
718         TNK != TNK_Concept_template) {
719       if (SS.isNotEmpty())
720         AnnotateScopeToken(SS, !WasScopeAnnotation);
721       return false;
722     }
723 
724     // At this point we're sure we're dealing with a constrained parameter. It
725     // may or may not have a template parameter list following the concept
726     // name.
727     if (AnnotateTemplateIdToken(PossibleConcept, TNK, SS,
728                                    /*TemplateKWLoc=*/SourceLocation(),
729                                    PossibleConceptName,
730                                    /*AllowTypeAnnotation=*/false,
731                                    /*TypeConstraint=*/true))
732       return true;
733   }
734 
735   if (SS.isNotEmpty())
736     AnnotateScopeToken(SS, !WasScopeAnnotation);
737   return false;
738 }
739 
740 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
741 /// Other kinds of template parameters are parsed in
742 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
743 ///
744 ///       type-parameter:     [C++ temp.param]
745 ///         'class' ...[opt][C++0x] identifier[opt]
746 ///         'class' identifier[opt] '=' type-id
747 ///         'typename' ...[opt][C++0x] identifier[opt]
748 ///         'typename' identifier[opt] '=' type-id
749 NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
750   assert((Tok.isOneOf(tok::kw_class, tok::kw_typename) ||
751           isTypeConstraintAnnotation()) &&
752          "A type-parameter starts with 'class', 'typename' or a "
753          "type-constraint");
754 
755   CXXScopeSpec TypeConstraintSS;
756   TemplateIdAnnotation *TypeConstraint = nullptr;
757   bool TypenameKeyword = false;
758   SourceLocation KeyLoc;
759   ParseOptionalCXXScopeSpecifier(TypeConstraintSS, /*ObjectType=*/nullptr,
760                                  /*ObjectHadErrors=*/false,
761                                  /*EnteringContext*/ false);
762   if (Tok.is(tok::annot_template_id)) {
763     // Consume the 'type-constraint'.
764     TypeConstraint =
765         static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
766     assert(TypeConstraint->Kind == TNK_Concept_template &&
767            "stray non-concept template-id annotation");
768     KeyLoc = ConsumeAnnotationToken();
769   } else {
770     assert(TypeConstraintSS.isEmpty() &&
771            "expected type constraint after scope specifier");
772 
773     // Consume the 'class' or 'typename' keyword.
774     TypenameKeyword = Tok.is(tok::kw_typename);
775     KeyLoc = ConsumeToken();
776   }
777 
778   // Grab the ellipsis (if given).
779   SourceLocation EllipsisLoc;
780   if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
781     Diag(EllipsisLoc,
782          getLangOpts().CPlusPlus11
783            ? diag::warn_cxx98_compat_variadic_templates
784            : diag::ext_variadic_templates);
785   }
786 
787   // Grab the template parameter name (if given)
788   SourceLocation NameLoc = Tok.getLocation();
789   IdentifierInfo *ParamName = nullptr;
790   if (Tok.is(tok::identifier)) {
791     ParamName = Tok.getIdentifierInfo();
792     ConsumeToken();
793   } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
794                          tok::greatergreater)) {
795     // Unnamed template parameter. Don't have to do anything here, just
796     // don't consume this token.
797   } else {
798     Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
799     return nullptr;
800   }
801 
802   // Recover from misplaced ellipsis.
803   bool AlreadyHasEllipsis = EllipsisLoc.isValid();
804   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
805     DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
806 
807   // Grab a default argument (if available).
808   // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
809   // we introduce the type parameter into the local scope.
810   SourceLocation EqualLoc;
811   ParsedType DefaultArg;
812   if (TryConsumeToken(tok::equal, EqualLoc))
813     DefaultArg = ParseTypeName(/*Range=*/nullptr,
814                                DeclaratorContext::TemplateTypeArgContext)
815                      .get();
816 
817   NamedDecl *NewDecl = Actions.ActOnTypeParameter(getCurScope(),
818                                                   TypenameKeyword, EllipsisLoc,
819                                                   KeyLoc, ParamName, NameLoc,
820                                                   Depth, Position, EqualLoc,
821                                                   DefaultArg,
822                                                   TypeConstraint != nullptr);
823 
824   if (TypeConstraint) {
825     Actions.ActOnTypeConstraint(TypeConstraintSS, TypeConstraint,
826                                 cast<TemplateTypeParmDecl>(NewDecl),
827                                 EllipsisLoc);
828   }
829 
830   return NewDecl;
831 }
832 
833 /// ParseTemplateTemplateParameter - Handle the parsing of template
834 /// template parameters.
835 ///
836 ///       type-parameter:    [C++ temp.param]
837 ///         'template' '<' template-parameter-list '>' type-parameter-key
838 ///                  ...[opt] identifier[opt]
839 ///         'template' '<' template-parameter-list '>' type-parameter-key
840 ///                  identifier[opt] = id-expression
841 ///       type-parameter-key:
842 ///         'class'
843 ///         'typename'       [C++1z]
844 NamedDecl *
845 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
846   assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
847 
848   // Handle the template <...> part.
849   SourceLocation TemplateLoc = ConsumeToken();
850   SmallVector<NamedDecl*,8> TemplateParams;
851   SourceLocation LAngleLoc, RAngleLoc;
852   {
853     ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
854     if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
855                                RAngleLoc)) {
856       return nullptr;
857     }
858   }
859 
860   // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
861   // Generate a meaningful error if the user forgot to put class before the
862   // identifier, comma, or greater. Provide a fixit if the identifier, comma,
863   // or greater appear immediately or after 'struct'. In the latter case,
864   // replace the keyword with 'class'.
865   if (!TryConsumeToken(tok::kw_class)) {
866     bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
867     const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
868     if (Tok.is(tok::kw_typename)) {
869       Diag(Tok.getLocation(),
870            getLangOpts().CPlusPlus17
871                ? diag::warn_cxx14_compat_template_template_param_typename
872                : diag::ext_template_template_param_typename)
873         << (!getLangOpts().CPlusPlus17
874                 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
875                 : FixItHint());
876     } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
877                             tok::greatergreater, tok::ellipsis)) {
878       Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
879         << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
880                     : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
881     } else
882       Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
883 
884     if (Replace)
885       ConsumeToken();
886   }
887 
888   // Parse the ellipsis, if given.
889   SourceLocation EllipsisLoc;
890   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
891     Diag(EllipsisLoc,
892          getLangOpts().CPlusPlus11
893            ? diag::warn_cxx98_compat_variadic_templates
894            : diag::ext_variadic_templates);
895 
896   // Get the identifier, if given.
897   SourceLocation NameLoc = Tok.getLocation();
898   IdentifierInfo *ParamName = nullptr;
899   if (Tok.is(tok::identifier)) {
900     ParamName = Tok.getIdentifierInfo();
901     ConsumeToken();
902   } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
903                          tok::greatergreater)) {
904     // Unnamed template parameter. Don't have to do anything here, just
905     // don't consume this token.
906   } else {
907     Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
908     return nullptr;
909   }
910 
911   // Recover from misplaced ellipsis.
912   bool AlreadyHasEllipsis = EllipsisLoc.isValid();
913   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
914     DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
915 
916   TemplateParameterList *ParamList =
917     Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
918                                        TemplateLoc, LAngleLoc,
919                                        TemplateParams,
920                                        RAngleLoc, nullptr);
921 
922   // Grab a default argument (if available).
923   // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
924   // we introduce the template parameter into the local scope.
925   SourceLocation EqualLoc;
926   ParsedTemplateArgument DefaultArg;
927   if (TryConsumeToken(tok::equal, EqualLoc)) {
928     DefaultArg = ParseTemplateTemplateArgument();
929     if (DefaultArg.isInvalid()) {
930       Diag(Tok.getLocation(),
931            diag::err_default_template_template_parameter_not_template);
932       SkipUntil(tok::comma, tok::greater, tok::greatergreater,
933                 StopAtSemi | StopBeforeMatch);
934     }
935   }
936 
937   return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
938                                                 ParamList, EllipsisLoc,
939                                                 ParamName, NameLoc, Depth,
940                                                 Position, EqualLoc, DefaultArg);
941 }
942 
943 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
944 /// template parameters (e.g., in "template<int Size> class array;").
945 ///
946 ///       template-parameter:
947 ///         ...
948 ///         parameter-declaration
949 NamedDecl *
950 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
951   // Parse the declaration-specifiers (i.e., the type).
952   // FIXME: The type should probably be restricted in some way... Not all
953   // declarators (parts of declarators?) are accepted for parameters.
954   DeclSpec DS(AttrFactory);
955   ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
956                              DeclSpecContext::DSC_template_param);
957 
958   // Parse this as a typename.
959   Declarator ParamDecl(DS, DeclaratorContext::TemplateParamContext);
960   ParseDeclarator(ParamDecl);
961   if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
962     Diag(Tok.getLocation(), diag::err_expected_template_parameter);
963     return nullptr;
964   }
965 
966   // Recover from misplaced ellipsis.
967   SourceLocation EllipsisLoc;
968   if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
969     DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
970 
971   // If there is a default value, parse it.
972   // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
973   // we introduce the template parameter into the local scope.
974   SourceLocation EqualLoc;
975   ExprResult DefaultArg;
976   if (TryConsumeToken(tok::equal, EqualLoc)) {
977     // C++ [temp.param]p15:
978     //   When parsing a default template-argument for a non-type
979     //   template-parameter, the first non-nested > is taken as the
980     //   end of the template-parameter-list rather than a greater-than
981     //   operator.
982     GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
983     EnterExpressionEvaluationContext ConstantEvaluated(
984         Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
985 
986     DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
987     if (DefaultArg.isInvalid())
988       SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
989   }
990 
991   // Create the parameter.
992   return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
993                                                Depth, Position, EqualLoc,
994                                                DefaultArg.get());
995 }
996 
997 void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
998                                        SourceLocation CorrectLoc,
999                                        bool AlreadyHasEllipsis,
1000                                        bool IdentifierHasName) {
1001   FixItHint Insertion;
1002   if (!AlreadyHasEllipsis)
1003     Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
1004   Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
1005       << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
1006       << !IdentifierHasName;
1007 }
1008 
1009 void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
1010                                                    Declarator &D) {
1011   assert(EllipsisLoc.isValid());
1012   bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
1013   if (!AlreadyHasEllipsis)
1014     D.setEllipsisLoc(EllipsisLoc);
1015   DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
1016                             AlreadyHasEllipsis, D.hasName());
1017 }
1018 
1019 /// Parses a '>' at the end of a template list.
1020 ///
1021 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
1022 /// to determine if these tokens were supposed to be a '>' followed by
1023 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
1024 ///
1025 /// \param RAngleLoc the location of the consumed '>'.
1026 ///
1027 /// \param ConsumeLastToken if true, the '>' is consumed.
1028 ///
1029 /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
1030 /// type parameter or type argument list, rather than a C++ template parameter
1031 /// or argument list.
1032 ///
1033 /// \returns true, if current token does not start with '>', false otherwise.
1034 bool Parser::ParseGreaterThanInTemplateList(SourceLocation LAngleLoc,
1035                                             SourceLocation &RAngleLoc,
1036                                             bool ConsumeLastToken,
1037                                             bool ObjCGenericList) {
1038   // What will be left once we've consumed the '>'.
1039   tok::TokenKind RemainingToken;
1040   const char *ReplacementStr = "> >";
1041   bool MergeWithNextToken = false;
1042 
1043   switch (Tok.getKind()) {
1044   default:
1045     Diag(getEndOfPreviousToken(), diag::err_expected) << tok::greater;
1046     Diag(LAngleLoc, diag::note_matching) << tok::less;
1047     return true;
1048 
1049   case tok::greater:
1050     // Determine the location of the '>' token. Only consume this token
1051     // if the caller asked us to.
1052     RAngleLoc = Tok.getLocation();
1053     if (ConsumeLastToken)
1054       ConsumeToken();
1055     return false;
1056 
1057   case tok::greatergreater:
1058     RemainingToken = tok::greater;
1059     break;
1060 
1061   case tok::greatergreatergreater:
1062     RemainingToken = tok::greatergreater;
1063     break;
1064 
1065   case tok::greaterequal:
1066     RemainingToken = tok::equal;
1067     ReplacementStr = "> =";
1068 
1069     // Join two adjacent '=' tokens into one, for cases like:
1070     //   void (*p)() = f<int>;
1071     //   return f<int>==p;
1072     if (NextToken().is(tok::equal) &&
1073         areTokensAdjacent(Tok, NextToken())) {
1074       RemainingToken = tok::equalequal;
1075       MergeWithNextToken = true;
1076     }
1077     break;
1078 
1079   case tok::greatergreaterequal:
1080     RemainingToken = tok::greaterequal;
1081     break;
1082   }
1083 
1084   // This template-id is terminated by a token that starts with a '>'.
1085   // Outside C++11 and Objective-C, this is now error recovery.
1086   //
1087   // C++11 allows this when the token is '>>', and in CUDA + C++11 mode, we
1088   // extend that treatment to also apply to the '>>>' token.
1089   //
1090   // Objective-C allows this in its type parameter / argument lists.
1091 
1092   SourceLocation TokBeforeGreaterLoc = PrevTokLocation;
1093   SourceLocation TokLoc = Tok.getLocation();
1094   Token Next = NextToken();
1095 
1096   // Whether splitting the current token after the '>' would undesirably result
1097   // in the remaining token pasting with the token after it. This excludes the
1098   // MergeWithNextToken cases, which we've already handled.
1099   bool PreventMergeWithNextToken =
1100       (RemainingToken == tok::greater ||
1101        RemainingToken == tok::greatergreater) &&
1102       (Next.isOneOf(tok::greater, tok::greatergreater,
1103                     tok::greatergreatergreater, tok::equal, tok::greaterequal,
1104                     tok::greatergreaterequal, tok::equalequal)) &&
1105       areTokensAdjacent(Tok, Next);
1106 
1107   // Diagnose this situation as appropriate.
1108   if (!ObjCGenericList) {
1109     // The source range of the replaced token(s).
1110     CharSourceRange ReplacementRange = CharSourceRange::getCharRange(
1111         TokLoc, Lexer::AdvanceToTokenCharacter(TokLoc, 2, PP.getSourceManager(),
1112                                                getLangOpts()));
1113 
1114     // A hint to put a space between the '>>'s. In order to make the hint as
1115     // clear as possible, we include the characters either side of the space in
1116     // the replacement, rather than just inserting a space at SecondCharLoc.
1117     FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
1118                                                    ReplacementStr);
1119 
1120     // A hint to put another space after the token, if it would otherwise be
1121     // lexed differently.
1122     FixItHint Hint2;
1123     if (PreventMergeWithNextToken)
1124       Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
1125 
1126     unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
1127     if (getLangOpts().CPlusPlus11 &&
1128         (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
1129       DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
1130     else if (Tok.is(tok::greaterequal))
1131       DiagId = diag::err_right_angle_bracket_equal_needs_space;
1132     Diag(TokLoc, DiagId) << Hint1 << Hint2;
1133   }
1134 
1135   // Find the "length" of the resulting '>' token. This is not always 1, as it
1136   // can contain escaped newlines.
1137   unsigned GreaterLength = Lexer::getTokenPrefixLength(
1138       TokLoc, 1, PP.getSourceManager(), getLangOpts());
1139 
1140   // Annotate the source buffer to indicate that we split the token after the
1141   // '>'. This allows us to properly find the end of, and extract the spelling
1142   // of, the '>' token later.
1143   RAngleLoc = PP.SplitToken(TokLoc, GreaterLength);
1144 
1145   // Strip the initial '>' from the token.
1146   bool CachingTokens = PP.IsPreviousCachedToken(Tok);
1147 
1148   Token Greater = Tok;
1149   Greater.setLocation(RAngleLoc);
1150   Greater.setKind(tok::greater);
1151   Greater.setLength(GreaterLength);
1152 
1153   unsigned OldLength = Tok.getLength();
1154   if (MergeWithNextToken) {
1155     ConsumeToken();
1156     OldLength += Tok.getLength();
1157   }
1158 
1159   Tok.setKind(RemainingToken);
1160   Tok.setLength(OldLength - GreaterLength);
1161 
1162   // Split the second token if lexing it normally would lex a different token
1163   // (eg, the fifth token in 'A<B>>>' should re-lex as '>', not '>>').
1164   SourceLocation AfterGreaterLoc = TokLoc.getLocWithOffset(GreaterLength);
1165   if (PreventMergeWithNextToken)
1166     AfterGreaterLoc = PP.SplitToken(AfterGreaterLoc, Tok.getLength());
1167   Tok.setLocation(AfterGreaterLoc);
1168 
1169   // Update the token cache to match what we just did if necessary.
1170   if (CachingTokens) {
1171     // If the previous cached token is being merged, delete it.
1172     if (MergeWithNextToken)
1173       PP.ReplacePreviousCachedToken({});
1174 
1175     if (ConsumeLastToken)
1176       PP.ReplacePreviousCachedToken({Greater, Tok});
1177     else
1178       PP.ReplacePreviousCachedToken({Greater});
1179   }
1180 
1181   if (ConsumeLastToken) {
1182     PrevTokLocation = RAngleLoc;
1183   } else {
1184     PrevTokLocation = TokBeforeGreaterLoc;
1185     PP.EnterToken(Tok, /*IsReinject=*/true);
1186     Tok = Greater;
1187   }
1188 
1189   return false;
1190 }
1191 
1192 
1193 /// Parses a template-id that after the template name has
1194 /// already been parsed.
1195 ///
1196 /// This routine takes care of parsing the enclosed template argument
1197 /// list ('<' template-parameter-list [opt] '>') and placing the
1198 /// results into a form that can be transferred to semantic analysis.
1199 ///
1200 /// \param ConsumeLastToken if true, then we will consume the last
1201 /// token that forms the template-id. Otherwise, we will leave the
1202 /// last token in the stream (e.g., so that it can be replaced with an
1203 /// annotation token).
1204 bool
1205 Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
1206                                          SourceLocation &LAngleLoc,
1207                                          TemplateArgList &TemplateArgs,
1208                                          SourceLocation &RAngleLoc) {
1209   assert(Tok.is(tok::less) && "Must have already parsed the template-name");
1210 
1211   // Consume the '<'.
1212   LAngleLoc = ConsumeToken();
1213 
1214   // Parse the optional template-argument-list.
1215   bool Invalid = false;
1216   {
1217     GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
1218     if (!Tok.isOneOf(tok::greater, tok::greatergreater,
1219                      tok::greatergreatergreater, tok::greaterequal,
1220                      tok::greatergreaterequal))
1221       Invalid = ParseTemplateArgumentList(TemplateArgs);
1222 
1223     if (Invalid) {
1224       // Try to find the closing '>'.
1225       if (getLangOpts().CPlusPlus11)
1226         SkipUntil(tok::greater, tok::greatergreater,
1227                   tok::greatergreatergreater, StopAtSemi | StopBeforeMatch);
1228       else
1229         SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
1230     }
1231   }
1232 
1233   return ParseGreaterThanInTemplateList(LAngleLoc, RAngleLoc, ConsumeLastToken,
1234                                         /*ObjCGenericList=*/false) ||
1235          Invalid;
1236 }
1237 
1238 /// Replace the tokens that form a simple-template-id with an
1239 /// annotation token containing the complete template-id.
1240 ///
1241 /// The first token in the stream must be the name of a template that
1242 /// is followed by a '<'. This routine will parse the complete
1243 /// simple-template-id and replace the tokens with a single annotation
1244 /// token with one of two different kinds: if the template-id names a
1245 /// type (and \p AllowTypeAnnotation is true), the annotation token is
1246 /// a type annotation that includes the optional nested-name-specifier
1247 /// (\p SS). Otherwise, the annotation token is a template-id
1248 /// annotation that does not include the optional
1249 /// nested-name-specifier.
1250 ///
1251 /// \param Template  the declaration of the template named by the first
1252 /// token (an identifier), as returned from \c Action::isTemplateName().
1253 ///
1254 /// \param TNK the kind of template that \p Template
1255 /// refers to, as returned from \c Action::isTemplateName().
1256 ///
1257 /// \param SS if non-NULL, the nested-name-specifier that precedes
1258 /// this template name.
1259 ///
1260 /// \param TemplateKWLoc if valid, specifies that this template-id
1261 /// annotation was preceded by the 'template' keyword and gives the
1262 /// location of that keyword. If invalid (the default), then this
1263 /// template-id was not preceded by a 'template' keyword.
1264 ///
1265 /// \param AllowTypeAnnotation if true (the default), then a
1266 /// simple-template-id that refers to a class template, template
1267 /// template parameter, or other template that produces a type will be
1268 /// replaced with a type annotation token. Otherwise, the
1269 /// simple-template-id is always replaced with a template-id
1270 /// annotation token.
1271 ///
1272 /// \param TypeConstraint if true, then this is actually a type-constraint,
1273 /// meaning that the template argument list can be omitted (and the template in
1274 /// question must be a concept).
1275 ///
1276 /// If an unrecoverable parse error occurs and no annotation token can be
1277 /// formed, this function returns true.
1278 ///
1279 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
1280                                      CXXScopeSpec &SS,
1281                                      SourceLocation TemplateKWLoc,
1282                                      UnqualifiedId &TemplateName,
1283                                      bool AllowTypeAnnotation,
1284                                      bool TypeConstraint) {
1285   assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
1286   assert((Tok.is(tok::less) || TypeConstraint) &&
1287          "Parser isn't at the beginning of a template-id");
1288   assert(!(TypeConstraint && AllowTypeAnnotation) && "type-constraint can't be "
1289                                                      "a type annotation");
1290   assert((!TypeConstraint || TNK == TNK_Concept_template) && "type-constraint "
1291          "must accompany a concept name");
1292   assert((Template || TNK == TNK_Non_template) && "missing template name");
1293 
1294   // Consume the template-name.
1295   SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
1296 
1297   // Parse the enclosed template argument list.
1298   SourceLocation LAngleLoc, RAngleLoc;
1299   TemplateArgList TemplateArgs;
1300   bool ArgsInvalid = false;
1301   if (!TypeConstraint || Tok.is(tok::less)) {
1302     ArgsInvalid = ParseTemplateIdAfterTemplateName(false, LAngleLoc,
1303                                                    TemplateArgs, RAngleLoc);
1304     // If we couldn't recover from invalid arguments, don't form an annotation
1305     // token -- we don't know how much to annotate.
1306     // FIXME: This can lead to duplicate diagnostics if we retry parsing this
1307     // template-id in another context. Try to annotate anyway?
1308     if (RAngleLoc.isInvalid())
1309       return true;
1310   }
1311 
1312   ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1313 
1314   // Build the annotation token.
1315   if (TNK == TNK_Type_template && AllowTypeAnnotation) {
1316     TypeResult Type = ArgsInvalid
1317                           ? TypeError()
1318                           : Actions.ActOnTemplateIdType(
1319                                 getCurScope(), SS, TemplateKWLoc, Template,
1320                                 TemplateName.Identifier, TemplateNameLoc,
1321                                 LAngleLoc, TemplateArgsPtr, RAngleLoc);
1322 
1323     Tok.setKind(tok::annot_typename);
1324     setTypeAnnotation(Tok, Type);
1325     if (SS.isNotEmpty())
1326       Tok.setLocation(SS.getBeginLoc());
1327     else if (TemplateKWLoc.isValid())
1328       Tok.setLocation(TemplateKWLoc);
1329     else
1330       Tok.setLocation(TemplateNameLoc);
1331   } else {
1332     // Build a template-id annotation token that can be processed
1333     // later.
1334     Tok.setKind(tok::annot_template_id);
1335 
1336     IdentifierInfo *TemplateII =
1337         TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1338             ? TemplateName.Identifier
1339             : nullptr;
1340 
1341     OverloadedOperatorKind OpKind =
1342         TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1343             ? OO_None
1344             : TemplateName.OperatorFunctionId.Operator;
1345 
1346     TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
1347         TemplateKWLoc, TemplateNameLoc, TemplateII, OpKind, Template, TNK,
1348         LAngleLoc, RAngleLoc, TemplateArgs, ArgsInvalid, TemplateIds);
1349 
1350     Tok.setAnnotationValue(TemplateId);
1351     if (TemplateKWLoc.isValid())
1352       Tok.setLocation(TemplateKWLoc);
1353     else
1354       Tok.setLocation(TemplateNameLoc);
1355   }
1356 
1357   // Common fields for the annotation token
1358   Tok.setAnnotationEndLoc(RAngleLoc);
1359 
1360   // In case the tokens were cached, have Preprocessor replace them with the
1361   // annotation token.
1362   PP.AnnotateCachedTokens(Tok);
1363   return false;
1364 }
1365 
1366 /// Replaces a template-id annotation token with a type
1367 /// annotation token.
1368 ///
1369 /// If there was a failure when forming the type from the template-id,
1370 /// a type annotation token will still be created, but will have a
1371 /// NULL type pointer to signify an error.
1372 ///
1373 /// \param SS The scope specifier appearing before the template-id, if any.
1374 ///
1375 /// \param IsClassName Is this template-id appearing in a context where we
1376 /// know it names a class, such as in an elaborated-type-specifier or
1377 /// base-specifier? ('typename' and 'template' are unneeded and disallowed
1378 /// in those contexts.)
1379 void Parser::AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS,
1380                                            bool IsClassName) {
1381   assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1382 
1383   TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1384   assert(TemplateId->mightBeType() &&
1385          "Only works for type and dependent templates");
1386 
1387   ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1388                                      TemplateId->NumArgs);
1389 
1390   TypeResult Type =
1391       TemplateId->isInvalid()
1392           ? TypeError()
1393           : Actions.ActOnTemplateIdType(
1394                 getCurScope(), SS, TemplateId->TemplateKWLoc,
1395                 TemplateId->Template, TemplateId->Name,
1396                 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc,
1397                 TemplateArgsPtr, TemplateId->RAngleLoc,
1398                 /*IsCtorOrDtorName*/ false, IsClassName);
1399   // Create the new "type" annotation token.
1400   Tok.setKind(tok::annot_typename);
1401   setTypeAnnotation(Tok, Type);
1402   if (SS.isNotEmpty()) // it was a C++ qualified type name.
1403     Tok.setLocation(SS.getBeginLoc());
1404   // End location stays the same
1405 
1406   // Replace the template-id annotation token, and possible the scope-specifier
1407   // that precedes it, with the typename annotation token.
1408   PP.AnnotateCachedTokens(Tok);
1409 }
1410 
1411 /// Determine whether the given token can end a template argument.
1412 static bool isEndOfTemplateArgument(Token Tok) {
1413   // FIXME: Handle '>>>'.
1414   return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater,
1415                      tok::greatergreatergreater);
1416 }
1417 
1418 /// Parse a C++ template template argument.
1419 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1420   if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1421       !Tok.is(tok::annot_cxxscope))
1422     return ParsedTemplateArgument();
1423 
1424   // C++0x [temp.arg.template]p1:
1425   //   A template-argument for a template template-parameter shall be the name
1426   //   of a class template or an alias template, expressed as id-expression.
1427   //
1428   // We parse an id-expression that refers to a class template or alias
1429   // template. The grammar we parse is:
1430   //
1431   //   nested-name-specifier[opt] template[opt] identifier ...[opt]
1432   //
1433   // followed by a token that terminates a template argument, such as ',',
1434   // '>', or (in some cases) '>>'.
1435   CXXScopeSpec SS; // nested-name-specifier, if present
1436   ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1437                                  /*ObjectHadErrors=*/false,
1438                                  /*EnteringContext=*/false);
1439 
1440   ParsedTemplateArgument Result;
1441   SourceLocation EllipsisLoc;
1442   if (SS.isSet() && Tok.is(tok::kw_template)) {
1443     // Parse the optional 'template' keyword following the
1444     // nested-name-specifier.
1445     SourceLocation TemplateKWLoc = ConsumeToken();
1446 
1447     if (Tok.is(tok::identifier)) {
1448       // We appear to have a dependent template name.
1449       UnqualifiedId Name;
1450       Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1451       ConsumeToken(); // the identifier
1452 
1453       TryConsumeToken(tok::ellipsis, EllipsisLoc);
1454 
1455       // If the next token signals the end of a template argument, then we have
1456       // a (possibly-dependent) template name that could be a template template
1457       // argument.
1458       TemplateTy Template;
1459       if (isEndOfTemplateArgument(Tok) &&
1460           Actions.ActOnTemplateName(getCurScope(), SS, TemplateKWLoc, Name,
1461                                     /*ObjectType=*/nullptr,
1462                                     /*EnteringContext=*/false, Template))
1463         Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1464     }
1465   } else if (Tok.is(tok::identifier)) {
1466     // We may have a (non-dependent) template name.
1467     TemplateTy Template;
1468     UnqualifiedId Name;
1469     Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1470     ConsumeToken(); // the identifier
1471 
1472     TryConsumeToken(tok::ellipsis, EllipsisLoc);
1473 
1474     if (isEndOfTemplateArgument(Tok)) {
1475       bool MemberOfUnknownSpecialization;
1476       TemplateNameKind TNK = Actions.isTemplateName(
1477           getCurScope(), SS,
1478           /*hasTemplateKeyword=*/false, Name,
1479           /*ObjectType=*/nullptr,
1480           /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
1481       if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1482         // We have an id-expression that refers to a class template or
1483         // (C++0x) alias template.
1484         Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1485       }
1486     }
1487   }
1488 
1489   // If this is a pack expansion, build it as such.
1490   if (EllipsisLoc.isValid() && !Result.isInvalid())
1491     Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1492 
1493   return Result;
1494 }
1495 
1496 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1497 ///
1498 ///       template-argument: [C++ 14.2]
1499 ///         constant-expression
1500 ///         type-id
1501 ///         id-expression
1502 ParsedTemplateArgument Parser::ParseTemplateArgument() {
1503   // C++ [temp.arg]p2:
1504   //   In a template-argument, an ambiguity between a type-id and an
1505   //   expression is resolved to a type-id, regardless of the form of
1506   //   the corresponding template-parameter.
1507   //
1508   // Therefore, we initially try to parse a type-id - and isCXXTypeId might look
1509   // up and annotate an identifier as an id-expression during disambiguation,
1510   // so enter the appropriate context for a constant expression template
1511   // argument before trying to disambiguate.
1512 
1513   EnterExpressionEvaluationContext EnterConstantEvaluated(
1514     Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated,
1515     /*LambdaContextDecl=*/nullptr,
1516     /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
1517   if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1518     TypeResult TypeArg = ParseTypeName(
1519         /*Range=*/nullptr, DeclaratorContext::TemplateArgContext);
1520     return Actions.ActOnTemplateTypeArgument(TypeArg);
1521   }
1522 
1523   // Try to parse a template template argument.
1524   {
1525     TentativeParsingAction TPA(*this);
1526 
1527     ParsedTemplateArgument TemplateTemplateArgument
1528       = ParseTemplateTemplateArgument();
1529     if (!TemplateTemplateArgument.isInvalid()) {
1530       TPA.Commit();
1531       return TemplateTemplateArgument;
1532     }
1533 
1534     // Revert this tentative parse to parse a non-type template argument.
1535     TPA.Revert();
1536   }
1537 
1538   // Parse a non-type template argument.
1539   SourceLocation Loc = Tok.getLocation();
1540   ExprResult ExprArg = ParseConstantExpressionInExprEvalContext(MaybeTypeCast);
1541   if (ExprArg.isInvalid() || !ExprArg.get()) {
1542     return ParsedTemplateArgument();
1543   }
1544 
1545   return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1546                                 ExprArg.get(), Loc);
1547 }
1548 
1549 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1550 /// (C++ [temp.names]). Returns true if there was an error.
1551 ///
1552 ///       template-argument-list: [C++ 14.2]
1553 ///         template-argument
1554 ///         template-argument-list ',' template-argument
1555 bool
1556 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1557 
1558   ColonProtectionRAIIObject ColonProtection(*this, false);
1559 
1560   do {
1561     ParsedTemplateArgument Arg = ParseTemplateArgument();
1562     SourceLocation EllipsisLoc;
1563     if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1564       Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1565 
1566     if (Arg.isInvalid())
1567       return true;
1568 
1569     // Save this template argument.
1570     TemplateArgs.push_back(Arg);
1571 
1572     // If the next token is a comma, consume it and keep reading
1573     // arguments.
1574   } while (TryConsumeToken(tok::comma));
1575 
1576   return false;
1577 }
1578 
1579 /// Parse a C++ explicit template instantiation
1580 /// (C++ [temp.explicit]).
1581 ///
1582 ///       explicit-instantiation:
1583 ///         'extern' [opt] 'template' declaration
1584 ///
1585 /// Note that the 'extern' is a GNU extension and C++11 feature.
1586 Decl *Parser::ParseExplicitInstantiation(DeclaratorContext Context,
1587                                          SourceLocation ExternLoc,
1588                                          SourceLocation TemplateLoc,
1589                                          SourceLocation &DeclEnd,
1590                                          ParsedAttributes &AccessAttrs,
1591                                          AccessSpecifier AS) {
1592   // This isn't really required here.
1593   ParsingDeclRAIIObject
1594     ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1595 
1596   return ParseSingleDeclarationAfterTemplate(
1597       Context, ParsedTemplateInfo(ExternLoc, TemplateLoc),
1598       ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
1599 }
1600 
1601 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1602   if (TemplateParams)
1603     return getTemplateParamsRange(TemplateParams->data(),
1604                                   TemplateParams->size());
1605 
1606   SourceRange R(TemplateLoc);
1607   if (ExternLoc.isValid())
1608     R.setBegin(ExternLoc);
1609   return R;
1610 }
1611 
1612 void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1613   ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1614 }
1615 
1616 /// Late parse a C++ function template in Microsoft mode.
1617 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1618   if (!LPT.D)
1619      return;
1620 
1621   // Destroy TemplateIdAnnotations when we're done, if possible.
1622   DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
1623 
1624   // Get the FunctionDecl.
1625   FunctionDecl *FunD = LPT.D->getAsFunction();
1626   // Track template parameter depth.
1627   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1628 
1629   // To restore the context after late parsing.
1630   Sema::ContextRAII GlobalSavedContext(
1631       Actions, Actions.Context.getTranslationUnitDecl());
1632 
1633   SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1634 
1635   // Get the list of DeclContexts to reenter. For inline methods, we only want
1636   // to push the DeclContext of the outermost class. This matches the way the
1637   // parser normally parses bodies of inline methods when the outermost class is
1638   // complete.
1639   struct ContainingDC {
1640     ContainingDC(DeclContext *DC, bool ShouldPush) : Pair(DC, ShouldPush) {}
1641     llvm::PointerIntPair<DeclContext *, 1, bool> Pair;
1642     DeclContext *getDC() { return Pair.getPointer(); }
1643     bool shouldPushDC() { return Pair.getInt(); }
1644   };
1645   SmallVector<ContainingDC, 4> DeclContextsToReenter;
1646   DeclContext *DD = FunD;
1647   DeclContext *NextContaining = Actions.getContainingDC(DD);
1648   while (DD && !DD->isTranslationUnit()) {
1649     bool ShouldPush = DD == NextContaining;
1650     DeclContextsToReenter.push_back({DD, ShouldPush});
1651     if (ShouldPush)
1652       NextContaining = Actions.getContainingDC(DD);
1653     DD = DD->getLexicalParent();
1654   }
1655 
1656   // Reenter template scopes from outermost to innermost.
1657   for (ContainingDC CDC : reverse(DeclContextsToReenter)) {
1658     TemplateParamScopeStack.push_back(
1659         new ParseScope(this, Scope::TemplateParamScope));
1660     unsigned NumParamLists = Actions.ActOnReenterTemplateScope(
1661         getCurScope(), cast<Decl>(CDC.getDC()));
1662     CurTemplateDepthTracker.addDepth(NumParamLists);
1663     if (CDC.shouldPushDC()) {
1664       TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1665       Actions.PushDeclContext(Actions.getCurScope(), CDC.getDC());
1666     }
1667   }
1668 
1669   assert(!LPT.Toks.empty() && "Empty body!");
1670 
1671   // Append the current token at the end of the new token stream so that it
1672   // doesn't get lost.
1673   LPT.Toks.push_back(Tok);
1674   PP.EnterTokenStream(LPT.Toks, true, /*IsReinject*/true);
1675 
1676   // Consume the previously pushed token.
1677   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1678   assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1679          "Inline method not starting with '{', ':' or 'try'");
1680 
1681   // Parse the method body. Function body parsing code is similar enough
1682   // to be re-used for method bodies as well.
1683   ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
1684                                Scope::CompoundStmtScope);
1685 
1686   // Recreate the containing function DeclContext.
1687   Sema::ContextRAII FunctionSavedContext(Actions,
1688                                          Actions.getContainingDC(FunD));
1689 
1690   Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1691 
1692   if (Tok.is(tok::kw_try)) {
1693     ParseFunctionTryBlock(LPT.D, FnScope);
1694   } else {
1695     if (Tok.is(tok::colon))
1696       ParseConstructorInitializer(LPT.D);
1697     else
1698       Actions.ActOnDefaultCtorInitializers(LPT.D);
1699 
1700     if (Tok.is(tok::l_brace)) {
1701       assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1702               cast<FunctionTemplateDecl>(LPT.D)
1703                       ->getTemplateParameters()
1704                       ->getDepth() == TemplateParameterDepth - 1) &&
1705              "TemplateParameterDepth should be greater than the depth of "
1706              "current template being instantiated!");
1707       ParseFunctionStatementBody(LPT.D, FnScope);
1708       Actions.UnmarkAsLateParsedTemplate(FunD);
1709     } else
1710       Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1711   }
1712 
1713   // Exit scopes.
1714   FnScope.Exit();
1715   SmallVectorImpl<ParseScope *>::reverse_iterator I =
1716    TemplateParamScopeStack.rbegin();
1717   for (; I != TemplateParamScopeStack.rend(); ++I)
1718     delete *I;
1719 }
1720 
1721 /// Lex a delayed template function for late parsing.
1722 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1723   tok::TokenKind kind = Tok.getKind();
1724   if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1725     // Consume everything up to (and including) the matching right brace.
1726     ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1727   }
1728 
1729   // If we're in a function-try-block, we need to store all the catch blocks.
1730   if (kind == tok::kw_try) {
1731     while (Tok.is(tok::kw_catch)) {
1732       ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1733       ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1734     }
1735   }
1736 }
1737 
1738 /// We've parsed something that could plausibly be intended to be a template
1739 /// name (\p LHS) followed by a '<' token, and the following code can't possibly
1740 /// be an expression. Determine if this is likely to be a template-id and if so,
1741 /// diagnose it.
1742 bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
1743   TentativeParsingAction TPA(*this);
1744   // FIXME: We could look at the token sequence in a lot more detail here.
1745   if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater,
1746                 StopAtSemi | StopBeforeMatch)) {
1747     TPA.Commit();
1748 
1749     SourceLocation Greater;
1750     ParseGreaterThanInTemplateList(Less, Greater, true, false);
1751     Actions.diagnoseExprIntendedAsTemplateName(getCurScope(), LHS,
1752                                                Less, Greater);
1753     return true;
1754   }
1755 
1756   // There's no matching '>' token, this probably isn't supposed to be
1757   // interpreted as a template-id. Parse it as an (ill-formed) comparison.
1758   TPA.Revert();
1759   return false;
1760 }
1761 
1762 void Parser::checkPotentialAngleBracket(ExprResult &PotentialTemplateName) {
1763   assert(Tok.is(tok::less) && "not at a potential angle bracket");
1764 
1765   bool DependentTemplateName = false;
1766   if (!Actions.mightBeIntendedToBeTemplateName(PotentialTemplateName,
1767                                                DependentTemplateName))
1768     return;
1769 
1770   // OK, this might be a name that the user intended to be parsed as a
1771   // template-name, followed by a '<' token. Check for some easy cases.
1772 
1773   // If we have potential_template<>, then it's supposed to be a template-name.
1774   if (NextToken().is(tok::greater) ||
1775       (getLangOpts().CPlusPlus11 &&
1776        NextToken().isOneOf(tok::greatergreater, tok::greatergreatergreater))) {
1777     SourceLocation Less = ConsumeToken();
1778     SourceLocation Greater;
1779     ParseGreaterThanInTemplateList(Less, Greater, true, false);
1780     Actions.diagnoseExprIntendedAsTemplateName(
1781         getCurScope(), PotentialTemplateName, Less, Greater);
1782     // FIXME: Perform error recovery.
1783     PotentialTemplateName = ExprError();
1784     return;
1785   }
1786 
1787   // If we have 'potential_template<type-id', assume it's supposed to be a
1788   // template-name if there's a matching '>' later on.
1789   {
1790     // FIXME: Avoid the tentative parse when NextToken() can't begin a type.
1791     TentativeParsingAction TPA(*this);
1792     SourceLocation Less = ConsumeToken();
1793     if (isTypeIdUnambiguously() &&
1794         diagnoseUnknownTemplateId(PotentialTemplateName, Less)) {
1795       TPA.Commit();
1796       // FIXME: Perform error recovery.
1797       PotentialTemplateName = ExprError();
1798       return;
1799     }
1800     TPA.Revert();
1801   }
1802 
1803   // Otherwise, remember that we saw this in case we see a potentially-matching
1804   // '>' token later on.
1805   AngleBracketTracker::Priority Priority =
1806       (DependentTemplateName ? AngleBracketTracker::DependentName
1807                              : AngleBracketTracker::PotentialTypo) |
1808       (Tok.hasLeadingSpace() ? AngleBracketTracker::SpaceBeforeLess
1809                              : AngleBracketTracker::NoSpaceBeforeLess);
1810   AngleBrackets.add(*this, PotentialTemplateName.get(), Tok.getLocation(),
1811                     Priority);
1812 }
1813 
1814 bool Parser::checkPotentialAngleBracketDelimiter(
1815     const AngleBracketTracker::Loc &LAngle, const Token &OpToken) {
1816   // If a comma in an expression context is followed by a type that can be a
1817   // template argument and cannot be an expression, then this is ill-formed,
1818   // but might be intended to be part of a template-id.
1819   if (OpToken.is(tok::comma) && isTypeIdUnambiguously() &&
1820       diagnoseUnknownTemplateId(LAngle.TemplateName, LAngle.LessLoc)) {
1821     AngleBrackets.clear(*this);
1822     return true;
1823   }
1824 
1825   // If a context that looks like a template-id is followed by '()', then
1826   // this is ill-formed, but might be intended to be a template-id
1827   // followed by '()'.
1828   if (OpToken.is(tok::greater) && Tok.is(tok::l_paren) &&
1829       NextToken().is(tok::r_paren)) {
1830     Actions.diagnoseExprIntendedAsTemplateName(
1831         getCurScope(), LAngle.TemplateName, LAngle.LessLoc,
1832         OpToken.getLocation());
1833     AngleBrackets.clear(*this);
1834     return true;
1835   }
1836 
1837   // After a '>' (etc), we're no longer potentially in a construct that's
1838   // intended to be treated as a template-id.
1839   if (OpToken.is(tok::greater) ||
1840       (getLangOpts().CPlusPlus11 &&
1841        OpToken.isOneOf(tok::greatergreater, tok::greatergreatergreater)))
1842     AngleBrackets.clear(*this);
1843   return false;
1844 }
1845