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