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