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