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