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 std::optional<DelayTemplateIdDestructionRAII> DontDestructTemplateIds;
845 if (TryConsumeToken(Expected: tok::equal, Loc&: EqualLoc)) {
846 // The default argument might contain a lambda declaration; avoid destroying
847 // parsed template ids at the end of that declaration because they can be
848 // used in the type constraint of the parameter's placeholder type later.
849 DontDestructTemplateIds.emplace(args&: *this, /*DelayTemplateIdDestruction=*/args: true);
850 if (Tok.is(K: tok::l_paren) && NextToken().is(K: tok::l_brace)) {
851 Diag(Loc: Tok.getLocation(), DiagID: diag::err_stmt_expr_in_default_arg) << 1;
852 SkipUntil(T1: tok::comma, T2: tok::greater, Flags: StopAtSemi | StopBeforeMatch);
853 } else {
854 // C++ [temp.param]p15:
855 // When parsing a default template-argument for a non-type
856 // template-parameter, the first non-nested > is taken as the
857 // end of the template-parameter-list rather than a greater-than
858 // operator.
859 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
860
861 // The default argument may declare template parameters, notably
862 // if it contains a generic lambda, so we need to increase
863 // the template depth as these parameters would not be instantiated
864 // at the current level.
865 TemplateParameterDepthRAII CurTemplateDepthTracker(
866 TemplateParameterDepth);
867 ++CurTemplateDepthTracker;
868 EnterExpressionEvaluationContext ConstantEvaluated(
869 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
870 DefaultArg = Actions.ActOnConstantExpression(Res: ParseInitializer());
871 if (DefaultArg.isInvalid())
872 SkipUntil(T1: tok::comma, T2: tok::greater, Flags: StopAtSemi | StopBeforeMatch);
873 }
874 }
875
876 // Create the parameter.
877 return Actions.ActOnNonTypeTemplateParameter(S: getCurScope(), D&: ParamDecl,
878 Depth, Position, EqualLoc,
879 DefaultArg: DefaultArg.get());
880}
881
882void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
883 SourceLocation CorrectLoc,
884 bool AlreadyHasEllipsis,
885 bool IdentifierHasName) {
886 FixItHint Insertion;
887 if (!AlreadyHasEllipsis)
888 Insertion = FixItHint::CreateInsertion(InsertionLoc: CorrectLoc, Code: "...");
889 Diag(Loc: EllipsisLoc, DiagID: diag::err_misplaced_ellipsis_in_declaration)
890 << FixItHint::CreateRemoval(RemoveRange: EllipsisLoc) << Insertion
891 << !IdentifierHasName;
892}
893
894void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
895 Declarator &D) {
896 assert(EllipsisLoc.isValid());
897 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
898 if (!AlreadyHasEllipsis)
899 D.setEllipsisLoc(EllipsisLoc);
900 DiagnoseMisplacedEllipsis(EllipsisLoc, CorrectLoc: D.getIdentifierLoc(),
901 AlreadyHasEllipsis, IdentifierHasName: D.hasName());
902}
903
904bool Parser::ParseGreaterThanInTemplateList(SourceLocation LAngleLoc,
905 SourceLocation &RAngleLoc,
906 bool ConsumeLastToken,
907 bool ObjCGenericList) {
908 // What will be left once we've consumed the '>'.
909 tok::TokenKind RemainingToken;
910 const char *ReplacementStr = "> >";
911 bool MergeWithNextToken = false;
912
913 switch (Tok.getKind()) {
914 default:
915 Diag(Loc: getEndOfPreviousToken(), DiagID: diag::err_expected) << tok::greater;
916 Diag(Loc: LAngleLoc, DiagID: diag::note_matching) << tok::less;
917 return true;
918
919 case tok::greater:
920 // Determine the location of the '>' token. Only consume this token
921 // if the caller asked us to.
922 RAngleLoc = Tok.getLocation();
923 if (ConsumeLastToken)
924 ConsumeToken();
925 return false;
926
927 case tok::greatergreater:
928 RemainingToken = tok::greater;
929 break;
930
931 case tok::greatergreatergreater:
932 RemainingToken = tok::greatergreater;
933 break;
934
935 case tok::greaterequal:
936 RemainingToken = tok::equal;
937 ReplacementStr = "> =";
938
939 // Join two adjacent '=' tokens into one, for cases like:
940 // void (*p)() = f<int>;
941 // return f<int>==p;
942 if (NextToken().is(K: tok::equal) &&
943 areTokensAdjacent(A: Tok, B: NextToken())) {
944 RemainingToken = tok::equalequal;
945 MergeWithNextToken = true;
946 }
947 break;
948
949 case tok::greatergreaterequal:
950 RemainingToken = tok::greaterequal;
951 break;
952 }
953
954 // This template-id is terminated by a token that starts with a '>'.
955 // Outside C++11 and Objective-C, this is now error recovery.
956 //
957 // C++11 allows this when the token is '>>', and in CUDA + C++11 mode, we
958 // extend that treatment to also apply to the '>>>' token.
959 //
960 // Objective-C allows this in its type parameter / argument lists.
961
962 SourceLocation TokBeforeGreaterLoc = PrevTokLocation;
963 SourceLocation TokLoc = Tok.getLocation();
964 Token Next = NextToken();
965
966 // Whether splitting the current token after the '>' would undesirably result
967 // in the remaining token pasting with the token after it. This excludes the
968 // MergeWithNextToken cases, which we've already handled.
969 bool PreventMergeWithNextToken =
970 (RemainingToken == tok::greater ||
971 RemainingToken == tok::greatergreater) &&
972 (Next.isOneOf(Ks: tok::greater, Ks: tok::greatergreater,
973 Ks: tok::greatergreatergreater, Ks: tok::equal, Ks: tok::greaterequal,
974 Ks: tok::greatergreaterequal, Ks: tok::equalequal)) &&
975 areTokensAdjacent(A: Tok, B: Next);
976
977 // Diagnose this situation as appropriate.
978 if (!ObjCGenericList) {
979 // The source range of the replaced token(s).
980 CharSourceRange ReplacementRange = CharSourceRange::getCharRange(
981 B: TokLoc, E: Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: 2, SM: PP.getSourceManager(),
982 LangOpts: getLangOpts()));
983
984 // A hint to put a space between the '>>'s. In order to make the hint as
985 // clear as possible, we include the characters either side of the space in
986 // the replacement, rather than just inserting a space at SecondCharLoc.
987 FixItHint Hint1 = FixItHint::CreateReplacement(RemoveRange: ReplacementRange,
988 Code: ReplacementStr);
989
990 // A hint to put another space after the token, if it would otherwise be
991 // lexed differently.
992 FixItHint Hint2;
993 if (PreventMergeWithNextToken)
994 Hint2 = FixItHint::CreateInsertion(InsertionLoc: Next.getLocation(), Code: " ");
995
996 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
997 if (getLangOpts().CPlusPlus11 &&
998 (Tok.is(K: tok::greatergreater) || Tok.is(K: tok::greatergreatergreater)))
999 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
1000 else if (Tok.is(K: tok::greaterequal))
1001 DiagId = diag::err_right_angle_bracket_equal_needs_space;
1002 Diag(Loc: TokLoc, DiagID: DiagId) << Hint1 << Hint2;
1003 }
1004
1005 // Find the "length" of the resulting '>' token. This is not always 1, as it
1006 // can contain escaped newlines.
1007 unsigned GreaterLength = Lexer::getTokenPrefixLength(
1008 TokStart: TokLoc, CharNo: 1, SM: PP.getSourceManager(), LangOpts: getLangOpts());
1009
1010 // Annotate the source buffer to indicate that we split the token after the
1011 // '>'. This allows us to properly find the end of, and extract the spelling
1012 // of, the '>' token later.
1013 RAngleLoc = PP.SplitToken(TokLoc, Length: GreaterLength);
1014
1015 // Strip the initial '>' from the token.
1016 bool CachingTokens = PP.IsPreviousCachedToken(Tok);
1017
1018 Token Greater = Tok;
1019 Greater.setLocation(RAngleLoc);
1020 Greater.setKind(tok::greater);
1021 Greater.setLength(GreaterLength);
1022
1023 unsigned OldLength = Tok.getLength();
1024 if (MergeWithNextToken) {
1025 ConsumeToken();
1026 OldLength += Tok.getLength();
1027 }
1028
1029 Tok.setKind(RemainingToken);
1030 Tok.setLength(OldLength - GreaterLength);
1031
1032 // Split the second token if lexing it normally would lex a different token
1033 // (eg, the fifth token in 'A<B>>>' should re-lex as '>', not '>>').
1034 SourceLocation AfterGreaterLoc = TokLoc.getLocWithOffset(Offset: GreaterLength);
1035 if (PreventMergeWithNextToken)
1036 AfterGreaterLoc = PP.SplitToken(TokLoc: AfterGreaterLoc, Length: Tok.getLength());
1037 Tok.setLocation(AfterGreaterLoc);
1038
1039 // Update the token cache to match what we just did if necessary.
1040 if (CachingTokens) {
1041 // If the previous cached token is being merged, delete it.
1042 if (MergeWithNextToken)
1043 PP.ReplacePreviousCachedToken(NewToks: {});
1044
1045 if (ConsumeLastToken)
1046 PP.ReplacePreviousCachedToken(NewToks: {Greater, Tok});
1047 else
1048 PP.ReplacePreviousCachedToken(NewToks: {Greater});
1049 }
1050
1051 if (ConsumeLastToken) {
1052 PrevTokLocation = RAngleLoc;
1053 } else {
1054 PrevTokLocation = TokBeforeGreaterLoc;
1055 PP.EnterToken(Tok, /*IsReinject=*/true);
1056 Tok = Greater;
1057 }
1058
1059 return false;
1060}
1061
1062bool Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
1063 SourceLocation &LAngleLoc,
1064 TemplateArgList &TemplateArgs,
1065 SourceLocation &RAngleLoc,
1066 TemplateTy Template) {
1067 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
1068
1069 // Consume the '<'.
1070 LAngleLoc = ConsumeToken();
1071
1072 // Parse the optional template-argument-list.
1073 bool Invalid = false;
1074 {
1075 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
1076 if (!Tok.isOneOf(Ks: tok::greater, Ks: tok::greatergreater,
1077 Ks: tok::greatergreatergreater, Ks: tok::greaterequal,
1078 Ks: tok::greatergreaterequal))
1079 Invalid = ParseTemplateArgumentList(TemplateArgs, Template, OpenLoc: LAngleLoc);
1080
1081 if (Invalid) {
1082 // Try to find the closing '>'.
1083 if (getLangOpts().CPlusPlus11)
1084 SkipUntil(T1: tok::greater, T2: tok::greatergreater,
1085 T3: tok::greatergreatergreater, Flags: StopAtSemi | StopBeforeMatch);
1086 else
1087 SkipUntil(T: tok::greater, Flags: StopAtSemi | StopBeforeMatch);
1088 }
1089 }
1090
1091 return ParseGreaterThanInTemplateList(LAngleLoc, RAngleLoc, ConsumeLastToken,
1092 /*ObjCGenericList=*/false) ||
1093 Invalid;
1094}
1095
1096bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
1097 CXXScopeSpec &SS,
1098 SourceLocation TemplateKWLoc,
1099 UnqualifiedId &TemplateName,
1100 bool AllowTypeAnnotation,
1101 bool TypeConstraint) {
1102 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
1103 assert((Tok.is(tok::less) || TypeConstraint) &&
1104 "Parser isn't at the beginning of a template-id");
1105 assert(!(TypeConstraint && AllowTypeAnnotation) && "type-constraint can't be "
1106 "a type annotation");
1107 assert((!TypeConstraint || TNK == TNK_Concept_template) && "type-constraint "
1108 "must accompany a concept name");
1109 assert((Template || TNK == TNK_Non_template) && "missing template name");
1110
1111 // Consume the template-name.
1112 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
1113
1114 // Parse the enclosed template argument list.
1115 SourceLocation LAngleLoc, RAngleLoc;
1116 TemplateArgList TemplateArgs;
1117 bool ArgsInvalid = false;
1118 if (!TypeConstraint || Tok.is(K: tok::less)) {
1119 ArgsInvalid = ParseTemplateIdAfterTemplateName(
1120 ConsumeLastToken: false, LAngleLoc, TemplateArgs, RAngleLoc, Template);
1121 // If we couldn't recover from invalid arguments, don't form an annotation
1122 // token -- we don't know how much to annotate.
1123 // FIXME: This can lead to duplicate diagnostics if we retry parsing this
1124 // template-id in another context. Try to annotate anyway?
1125 if (RAngleLoc.isInvalid())
1126 return true;
1127 }
1128
1129 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1130
1131 // Build the annotation token.
1132 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
1133 TypeResult Type =
1134 ArgsInvalid
1135 ? TypeError()
1136 : Actions.ActOnTemplateIdType(
1137 S: getCurScope(), ElaboratedKeyword: ElaboratedTypeKeyword::None,
1138 /*ElaboratedKeywordLoc=*/SourceLocation(), SS, TemplateKWLoc,
1139 Template, TemplateII: TemplateName.Identifier, TemplateIILoc: TemplateNameLoc, LAngleLoc,
1140 TemplateArgs: TemplateArgsPtr, RAngleLoc);
1141
1142 Tok.setKind(tok::annot_typename);
1143 setTypeAnnotation(Tok, T: Type);
1144 if (SS.isNotEmpty())
1145 Tok.setLocation(SS.getBeginLoc());
1146 else if (TemplateKWLoc.isValid())
1147 Tok.setLocation(TemplateKWLoc);
1148 else
1149 Tok.setLocation(TemplateNameLoc);
1150 } else {
1151 // Build a template-id annotation token that can be processed
1152 // later.
1153 Tok.setKind(tok::annot_template_id);
1154
1155 const IdentifierInfo *TemplateII =
1156 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1157 ? TemplateName.Identifier
1158 : nullptr;
1159
1160 OverloadedOperatorKind OpKind =
1161 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1162 ? OO_None
1163 : TemplateName.OperatorFunctionId.Operator;
1164
1165 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
1166 TemplateKWLoc, TemplateNameLoc, Name: TemplateII, OperatorKind: OpKind, OpaqueTemplateName: Template, TemplateKind: TNK,
1167 LAngleLoc, RAngleLoc, TemplateArgs, ArgsInvalid, CleanupList&: TemplateIds);
1168
1169 Tok.setAnnotationValue(TemplateId);
1170 if (TemplateKWLoc.isValid())
1171 Tok.setLocation(TemplateKWLoc);
1172 else
1173 Tok.setLocation(TemplateNameLoc);
1174 }
1175
1176 // Common fields for the annotation token
1177 Tok.setAnnotationEndLoc(RAngleLoc);
1178
1179 // In case the tokens were cached, have Preprocessor replace them with the
1180 // annotation token.
1181 PP.AnnotateCachedTokens(Tok);
1182 return false;
1183}
1184
1185void Parser::AnnotateTemplateIdTokenAsType(
1186 CXXScopeSpec &SS, ImplicitTypenameContext AllowImplicitTypename,
1187 bool IsClassName) {
1188 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1189
1190 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(tok: Tok);
1191 assert(TemplateId->mightBeType() &&
1192 "Only works for type and dependent templates");
1193
1194 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1195 TemplateId->NumArgs);
1196
1197 TypeResult Type =
1198 TemplateId->isInvalid()
1199 ? TypeError()
1200 : Actions.ActOnTemplateIdType(
1201 S: getCurScope(), ElaboratedKeyword: ElaboratedTypeKeyword::None,
1202 /*ElaboratedKeywordLoc=*/SourceLocation(), SS,
1203 TemplateKWLoc: TemplateId->TemplateKWLoc, Template: TemplateId->Template,
1204 TemplateII: TemplateId->Name, TemplateIILoc: TemplateId->TemplateNameLoc,
1205 LAngleLoc: TemplateId->LAngleLoc, TemplateArgs: TemplateArgsPtr, RAngleLoc: TemplateId->RAngleLoc,
1206 /*IsCtorOrDtorName=*/false, IsClassName, AllowImplicitTypename);
1207 // Create the new "type" annotation token.
1208 Tok.setKind(tok::annot_typename);
1209 setTypeAnnotation(Tok, T: Type);
1210 if (SS.isNotEmpty()) // it was a C++ qualified type name.
1211 Tok.setLocation(SS.getBeginLoc());
1212 // End location stays the same
1213
1214 // Replace the template-id annotation token, and possible the scope-specifier
1215 // that precedes it, with the typename annotation token.
1216 PP.AnnotateCachedTokens(Tok);
1217}
1218
1219/// Determine whether the given token can end a template argument.
1220static bool isEndOfTemplateArgument(Token Tok) {
1221 // FIXME: Handle '>>>'.
1222 return Tok.isOneOf(Ks: tok::comma, Ks: tok::greater, Ks: tok::greatergreater,
1223 Ks: tok::greatergreatergreater);
1224}
1225
1226ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1227 if (!Tok.is(K: tok::identifier) && !Tok.is(K: tok::coloncolon) &&
1228 !Tok.is(K: tok::annot_cxxscope) && !Tok.is(K: tok::annot_template_id) &&
1229 !Tok.is(K: tok::annot_non_type))
1230 return ParsedTemplateArgument();
1231
1232 // C++0x [temp.arg.template]p1:
1233 // A template-argument for a template template-parameter shall be the name
1234 // of a class template or an alias template, expressed as id-expression.
1235 //
1236 // We parse an id-expression that refers to a class template or alias
1237 // template. The grammar we parse is:
1238 //
1239 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1240 //
1241 // followed by a token that terminates a template argument, such as ',',
1242 // '>', or (in some cases) '>>'.
1243 CXXScopeSpec SS; // nested-name-specifier, if present
1244 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1245 /*ObjectHasErrors=*/false,
1246 /*EnteringContext=*/false);
1247
1248 ParsedTemplateArgument Result;
1249 SourceLocation EllipsisLoc;
1250 if (SS.isSet() && Tok.is(K: tok::kw_template)) {
1251 // Parse the optional 'template' keyword following the
1252 // nested-name-specifier.
1253 SourceLocation TemplateKWLoc = ConsumeToken();
1254
1255 if (Tok.is(K: tok::identifier)) {
1256 // We appear to have a dependent template name.
1257 UnqualifiedId Name;
1258 Name.setIdentifier(Id: Tok.getIdentifierInfo(), IdLoc: Tok.getLocation());
1259 ConsumeToken(); // the identifier
1260
1261 TryConsumeToken(Expected: tok::ellipsis, Loc&: EllipsisLoc);
1262
1263 // If the next token signals the end of a template argument, then we have
1264 // a (possibly-dependent) template name that could be a template template
1265 // argument.
1266 TemplateTy Template;
1267 if (isEndOfTemplateArgument(Tok) &&
1268 Actions.ActOnTemplateName(S: getCurScope(), SS, TemplateKWLoc, Name,
1269 /*ObjectType=*/nullptr,
1270 /*EnteringContext=*/false, Template))
1271 Result = ParsedTemplateArgument(TemplateKWLoc, SS, Template,
1272 Name.StartLocation);
1273 }
1274 } else if (Tok.is(K: tok::identifier) || Tok.is(K: tok::annot_template_id) ||
1275 Tok.is(K: tok::annot_non_type)) {
1276 // We may have a (non-dependent) template name.
1277 TemplateTy Template;
1278 UnqualifiedId Name;
1279 bool IsPackIndexingTemplateName = false;
1280 if (Tok.is(K: tok::annot_non_type)) {
1281 NamedDecl *ND = getNonTypeAnnotation(Tok);
1282 if (!isa<VarTemplateDecl>(Val: ND))
1283 return Result;
1284 Name.setIdentifier(Id: ND->getIdentifier(), IdLoc: Tok.getLocation());
1285 ConsumeAnnotationToken();
1286 } else if (Tok.is(K: tok::annot_template_id)) {
1287 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(tok: Tok);
1288 if (TemplateId->LAngleLoc.isValid())
1289 return Result;
1290 if (TemplateId->Template &&
1291 TemplateId->Template.get().getAsPackIndexingTemplate()) {
1292 Template = TemplateId->Template;
1293 IsPackIndexingTemplateName = true;
1294 }
1295 Name.setIdentifier(Id: TemplateId->Name, IdLoc: Tok.getLocation());
1296 ConsumeAnnotationToken();
1297 } else {
1298 Name.setIdentifier(Id: Tok.getIdentifierInfo(), IdLoc: Tok.getLocation());
1299 ConsumeToken(); // the identifier
1300 }
1301
1302 TryConsumeToken(Expected: tok::ellipsis, Loc&: EllipsisLoc);
1303
1304 if (isEndOfTemplateArgument(Tok)) {
1305 if (IsPackIndexingTemplateName) {
1306 Result = ParsedTemplateArgument(/*TemplateKwLoc=*/SourceLocation(), SS,
1307 Template, Name.StartLocation);
1308 } else {
1309 bool MemberOfUnknownSpecialization;
1310 TemplateNameKind TNK = Actions.isTemplateName(
1311 S: getCurScope(), SS,
1312 /*hasTemplateKeyword=*/false, Name,
1313 /*ObjectType=*/nullptr,
1314 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
1315 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template ||
1316 TNK == TNK_Var_template || TNK == TNK_Concept_template) {
1317 // We have an id-expression that refers to a class template or
1318 // (C++0x) alias template.
1319 Result = ParsedTemplateArgument(/*TemplateKwLoc=*/SourceLocation(),
1320 SS, Template, Name.StartLocation);
1321 }
1322 }
1323 }
1324 }
1325
1326 Result = Actions.ActOnTemplateTemplateArgument(Arg: Result);
1327
1328 // If this is a pack expansion, build it as such.
1329 if (EllipsisLoc.isValid() && !Result.isInvalid())
1330 Result = Actions.ActOnPackExpansion(Arg: Result, EllipsisLoc);
1331
1332 return Result;
1333}
1334
1335ParsedTemplateArgument Parser::ParseTemplateArgument() {
1336 // C++ [temp.arg]p2:
1337 // In a template-argument, an ambiguity between a type-id and an
1338 // expression is resolved to a type-id, regardless of the form of
1339 // the corresponding template-parameter.
1340 //
1341 // Therefore, we initially try to parse a type-id - and isCXXTypeId might look
1342 // up and annotate an identifier as an id-expression during disambiguation,
1343 // so enter the appropriate context for a constant expression template
1344 // argument before trying to disambiguate.
1345
1346 EnterExpressionEvaluationContext EnterConstantEvaluated(
1347 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated,
1348 /*LambdaContextDecl=*/nullptr,
1349 /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
1350 if (isCXXTypeId(Context: TentativeCXXTypeIdContext::AsTemplateArgument)) {
1351 TypeResult TypeArg = ParseTypeName(
1352 /*Range=*/nullptr, Context: DeclaratorContext::TemplateArg);
1353 return Actions.ActOnTemplateTypeArgument(ParsedType: TypeArg);
1354 }
1355
1356 // Try to parse a template template argument.
1357 {
1358 TentativeParsingAction TPA(*this);
1359
1360 ParsedTemplateArgument TemplateTemplateArgument =
1361 ParseTemplateTemplateArgument();
1362 if (!TemplateTemplateArgument.isInvalid()) {
1363 TPA.Commit();
1364 return TemplateTemplateArgument;
1365 }
1366 // Revert this tentative parse to parse a non-type template argument.
1367 TPA.Revert();
1368 }
1369
1370 // Parse a non-type template argument.
1371 ExprResult ExprArg;
1372 SourceLocation Loc = Tok.getLocation();
1373 if (getLangOpts().CPlusPlus11 && Tok.is(K: tok::l_brace))
1374 ExprArg = ParseBraceInitializer();
1375 else
1376 ExprArg = ParseConstantExpressionInExprEvalContext(
1377 CorrectionBehavior: TypoCorrectionTypeBehavior::AllowBoth);
1378 if (ExprArg.isInvalid() || !ExprArg.get()) {
1379 return ParsedTemplateArgument();
1380 }
1381
1382 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1383 ExprArg.get(), Loc);
1384}
1385
1386bool Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
1387 TemplateTy Template,
1388 SourceLocation OpenLoc) {
1389
1390 ColonProtectionRAIIObject ColonProtection(*this, false);
1391
1392 auto RunSignatureHelp = [&] {
1393 if (!Template)
1394 return QualType();
1395 CalledSignatureHelp = true;
1396 return Actions.CodeCompletion().ProduceTemplateArgumentSignatureHelp(
1397 Template, TemplateArgs, LAngleLoc: OpenLoc);
1398 };
1399
1400 do {
1401 PreferredType.enterFunctionArgument(Tok: Tok.getLocation(), ComputeType: RunSignatureHelp);
1402 ParsedTemplateArgument Arg = ParseTemplateArgument();
1403 SourceLocation EllipsisLoc;
1404 if (TryConsumeToken(Expected: tok::ellipsis, Loc&: EllipsisLoc))
1405 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1406
1407 if (Arg.isInvalid()) {
1408 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1409 RunSignatureHelp();
1410 return true;
1411 }
1412
1413 // Save this template argument.
1414 TemplateArgs.push_back(Elt: Arg);
1415
1416 // If the next token is a comma, consume it and keep reading
1417 // arguments.
1418 } while (TryConsumeToken(Expected: tok::comma));
1419
1420 return false;
1421}
1422
1423Parser::DeclGroupPtrTy Parser::ParseExplicitInstantiation(
1424 DeclaratorContext Context, SourceLocation ExternLoc,
1425 SourceLocation TemplateLoc, SourceLocation &DeclEnd,
1426 ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
1427 // This isn't really required here.
1428 ParsingDeclRAIIObject
1429 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1430 ParsedTemplateInfo TemplateInfo(ExternLoc, TemplateLoc);
1431 return ParseDeclarationAfterTemplate(
1432 Context, TemplateInfo, DiagsFromTParams&: ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
1433}
1434
1435SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1436 if (TemplateParams)
1437 return getTemplateParamsRange(Params: TemplateParams->data(),
1438 NumParams: TemplateParams->size());
1439
1440 SourceRange R(TemplateLoc);
1441 if (ExternLoc.isValid())
1442 R.setBegin(ExternLoc);
1443 return R;
1444}
1445
1446void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1447 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1448}
1449
1450void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1451 if (!LPT.D)
1452 return;
1453
1454 // Destroy TemplateIdAnnotations when we're done, if possible.
1455 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
1456
1457 // Get the FunctionDecl.
1458 FunctionDecl *FunD = LPT.D->getAsFunction();
1459 // Track template parameter depth.
1460 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1461
1462 MultiParseScope Scopes(*this);
1463
1464 // Get the list of DeclContexts to reenter.
1465 SmallVector<DeclContext*, 4> DeclContextsToReenter;
1466 DeclContext *LexicalTU = nullptr;
1467 for (DeclContext *DC = FunD; DC; DC = DC->getLexicalParent()) {
1468 if (DC->isTranslationUnit()) {
1469 LexicalTU = DC;
1470 break;
1471 }
1472 DeclContextsToReenter.push_back(Elt: DC);
1473 }
1474
1475 if (!LexicalTU) {
1476 LexicalTU = Actions.Context.getTranslationUnitDecl();
1477 }
1478
1479 // To restore the context after late parsing.
1480 Sema::ContextRAII GlobalSavedContext(Actions, LexicalTU);
1481
1482 // Reenter scopes from outermost to innermost.
1483 for (DeclContext *DC : reverse(C&: DeclContextsToReenter)) {
1484 CurTemplateDepthTracker.addDepth(
1485 D: ReenterTemplateScopes(S&: Scopes, D: cast<Decl>(Val: DC)));
1486 Scopes.Enter(ScopeFlags: Scope::DeclScope);
1487 // We'll reenter the function context itself below.
1488 if (DC != FunD)
1489 Actions.PushDeclContext(S: Actions.getCurScope(), DC);
1490 }
1491
1492 // Parsing should occur with empty FP pragma stack and FP options used in the
1493 // point of the template definition.
1494 Sema::FpPragmaStackSaveRAII SavedStack(Actions);
1495 Actions.resetFPOptions(FPO: LPT.FPO);
1496
1497 assert(!LPT.Toks.empty() && "Empty body!");
1498
1499 // Append the current token at the end of the new token stream so that it
1500 // doesn't get lost.
1501 LPT.Toks.push_back(Elt: Tok);
1502 PP.EnterTokenStream(Toks: LPT.Toks, DisableMacroExpansion: true, /*IsReinject*/true);
1503
1504 // Consume the previously pushed token.
1505 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1506 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1507 "Inline method not starting with '{', ':' or 'try'");
1508
1509 // Parse the method body. Function body parsing code is similar enough
1510 // to be re-used for method bodies as well.
1511 ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
1512 Scope::CompoundStmtScope);
1513
1514 // Recreate the containing function DeclContext.
1515 Sema::ContextRAII FunctionSavedContext(Actions, FunD->getLexicalParent());
1516
1517 Actions.ActOnStartOfFunctionDef(S: getCurScope(), D: FunD);
1518
1519 assert(
1520 (!isa<FunctionTemplateDecl>(LPT.D) ||
1521 cast<FunctionTemplateDecl>(LPT.D)->getTemplateParameters()->getDepth() ==
1522 TemplateParameterDepth - 1) &&
1523 "TemplateParameterDepth should be greater than the depth of "
1524 "current template being instantiated!");
1525
1526 ParseFunctionBody(D: LPT.D, BodyScope&: FnScope);
1527 Actions.UnmarkAsLateParsedTemplate(FD: FunD);
1528}
1529
1530void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1531 tok::TokenKind kind = Tok.getKind();
1532 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1533 // Consume everything up to (and including) the matching right brace.
1534 ConsumeAndStoreUntil(T1: tok::r_brace, Toks, /*StopAtSemi=*/false);
1535 }
1536
1537 // If we're in a function-try-block, we need to store all the catch blocks.
1538 if (kind == tok::kw_try) {
1539 while (Tok.is(K: tok::kw_catch)) {
1540 ConsumeAndStoreUntil(T1: tok::l_brace, Toks, /*StopAtSemi=*/false);
1541 ConsumeAndStoreUntil(T1: tok::r_brace, Toks, /*StopAtSemi=*/false);
1542 }
1543 }
1544}
1545
1546bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
1547 TentativeParsingAction TPA(*this);
1548 // FIXME: We could look at the token sequence in a lot more detail here.
1549 if (SkipUntil(T1: tok::greater, T2: tok::greatergreater, T3: tok::greatergreatergreater,
1550 Flags: StopAtSemi | StopBeforeMatch)) {
1551 TPA.Commit();
1552
1553 SourceLocation Greater;
1554 ParseGreaterThanInTemplateList(LAngleLoc: Less, RAngleLoc&: Greater, ConsumeLastToken: true, ObjCGenericList: false);
1555 Actions.diagnoseExprIntendedAsTemplateName(S: getCurScope(), TemplateName: LHS,
1556 Less, Greater);
1557 return true;
1558 }
1559
1560 // There's no matching '>' token, this probably isn't supposed to be
1561 // interpreted as a template-id. Parse it as an (ill-formed) comparison.
1562 TPA.Revert();
1563 return false;
1564}
1565
1566void Parser::checkPotentialAngleBracket(ExprResult &PotentialTemplateName) {
1567 assert(Tok.is(tok::less) && "not at a potential angle bracket");
1568
1569 bool DependentTemplateName = false;
1570 if (!Actions.mightBeIntendedToBeTemplateName(E: PotentialTemplateName,
1571 Dependent&: DependentTemplateName))
1572 return;
1573
1574 // OK, this might be a name that the user intended to be parsed as a
1575 // template-name, followed by a '<' token. Check for some easy cases.
1576
1577 // If we have potential_template<>, then it's supposed to be a template-name.
1578 if (NextToken().is(K: tok::greater) ||
1579 (getLangOpts().CPlusPlus11 &&
1580 NextToken().isOneOf(Ks: tok::greatergreater, Ks: tok::greatergreatergreater))) {
1581 SourceLocation Less = ConsumeToken();
1582 SourceLocation Greater;
1583 ParseGreaterThanInTemplateList(LAngleLoc: Less, RAngleLoc&: Greater, ConsumeLastToken: true, ObjCGenericList: false);
1584 Actions.diagnoseExprIntendedAsTemplateName(
1585 S: getCurScope(), TemplateName: PotentialTemplateName, Less, Greater);
1586 // FIXME: Perform error recovery.
1587 PotentialTemplateName = ExprError();
1588 return;
1589 }
1590
1591 // If we have 'potential_template<type-id', assume it's supposed to be a
1592 // template-name if there's a matching '>' later on.
1593 {
1594 // FIXME: Avoid the tentative parse when NextToken() can't begin a type.
1595 TentativeParsingAction TPA(*this);
1596 SourceLocation Less = ConsumeToken();
1597 if (isTypeIdUnambiguously() &&
1598 diagnoseUnknownTemplateId(LHS: PotentialTemplateName, Less)) {
1599 TPA.Commit();
1600 // FIXME: Perform error recovery.
1601 PotentialTemplateName = ExprError();
1602 return;
1603 }
1604 TPA.Revert();
1605 }
1606
1607 // Otherwise, remember that we saw this in case we see a potentially-matching
1608 // '>' token later on.
1609 AngleBracketTracker::Priority Priority =
1610 (DependentTemplateName ? AngleBracketTracker::DependentName
1611 : AngleBracketTracker::PotentialTypo) |
1612 (Tok.hasLeadingSpace() ? AngleBracketTracker::SpaceBeforeLess
1613 : AngleBracketTracker::NoSpaceBeforeLess);
1614 AngleBrackets.add(P&: *this, TemplateName: PotentialTemplateName.get(), LessLoc: Tok.getLocation(),
1615 Prio: Priority);
1616}
1617
1618bool Parser::checkPotentialAngleBracketDelimiter(
1619 const AngleBracketTracker::Loc &LAngle, const Token &OpToken) {
1620 // If a comma in an expression context is followed by a type that can be a
1621 // template argument and cannot be an expression, then this is ill-formed,
1622 // but might be intended to be part of a template-id.
1623 if (OpToken.is(K: tok::comma) && isTypeIdUnambiguously() &&
1624 diagnoseUnknownTemplateId(LHS: LAngle.TemplateName, Less: LAngle.LessLoc)) {
1625 AngleBrackets.clear(P&: *this);
1626 return true;
1627 }
1628
1629 // If a context that looks like a template-id is followed by '()', then
1630 // this is ill-formed, but might be intended to be a template-id
1631 // followed by '()'.
1632 if (OpToken.is(K: tok::greater) && Tok.is(K: tok::l_paren) &&
1633 NextToken().is(K: tok::r_paren)) {
1634 Actions.diagnoseExprIntendedAsTemplateName(
1635 S: getCurScope(), TemplateName: LAngle.TemplateName, Less: LAngle.LessLoc,
1636 Greater: OpToken.getLocation());
1637 AngleBrackets.clear(P&: *this);
1638 return true;
1639 }
1640
1641 // After a '>' (etc), we're no longer potentially in a construct that's
1642 // intended to be treated as a template-id.
1643 if (OpToken.is(K: tok::greater) ||
1644 (getLangOpts().CPlusPlus11 &&
1645 OpToken.isOneOf(Ks: tok::greatergreater, Ks: tok::greatergreatergreater)))
1646 AngleBrackets.clear(P&: *this);
1647 return false;
1648}
1649