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