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