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