clang 23.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.
57 ParsingDeclRAIIObject
58 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
59
60 // Parse multiple levels of template headers within this template
61 // parameter scope, e.g.,
62 //
63 // template<typename T>
64 // template<typename U>
65 // class A<T>::B { ... };
66 //
67 // We parse multiple levels non-recursively so that we can build a
68 // single data structure containing all of the template parameter
69 // lists to easily differentiate between the case above and:
70 //
71 // template<typename T>
72 // class A {
73 // template<typename U> class B;
74 // };
75 //
76 // In the first case, the action for declaring A<T>::B receives
77 // both template parameter lists. In the second case, the action for
78 // defining A<T>::B receives just the inner template parameter list
79 // (and retrieves the outer template parameter list from its
80 // context).
81 bool isSpecialization = true;
82 bool LastParamListWasEmpty = false;
83 TemplateParameterLists ParamLists;
84 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
85
86 do {
87 // Consume the 'export', if any.
88 SourceLocation ExportLoc;
89 TryConsumeToken(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 =
117 Actions.ActOnRequiresClause(ParseConstraintLogicalOrExpression(
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.takeAttributesAppendingingFrom(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;
208 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
210 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
213 AnonRecord);
214 Actions.ActOnDefinedDeclarationSpecifier(Decl);
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) <<
244 FixItHint::CreateRemoval(SourceLocation(BoolKWLoc));
245
246 DiagnoseAndSkipCXX11Attributes();
247
248 CXXScopeSpec SS;
249 if (ParseOptionalCXXScopeSpecifier(
250 SS, /*ObjectType=*/nullptr,
251 /*ObjectHasErrors=*/false, /*EnteringContext=*/false,
252 /*MayBePseudoDestructor=*/nullptr,
253 /*IsTypename=*/false, /*LastII=*/nullptr, /*OnlyNamespace=*/true) ||
254 SS.isInvalid()) {
255 SkipUntil(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.
285 ConceptDecl *D = Actions.ActOnStartConceptDefinition(
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();
344 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
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)
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.
496 DeclSpec DS(getAttrFactory());
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 // The type constraint may declare template parameters, notably
537 // if it contains a generic lambda, so we need to increment
538 // the template depth as these parameters would not be instantiated
539 // at the current depth.
540 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
541 ++CurTemplateDepthTracker;
542 CXXScopeSpec SS;
543 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
544 if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
545 /*ObjectHasErrors=*/false,
546 /*EnteringContext=*/false,
547 /*MayBePseudoDestructor=*/nullptr,
548 // If this is not a type-constraint, then
549 // this scope-spec is part of the typename
550 // of a non-type template parameter
551 /*IsTypename=*/true, /*LastII=*/nullptr,
552 // We won't find concepts in
553 // non-namespaces anyway, so might as well
554 // parse this correctly for possible type
555 // names.
556 /*OnlyNamespace=*/false))
557 return true;
558
559 if (Tok.is(tok::identifier)) {
560 UnqualifiedId PossibleConceptName;
561 PossibleConceptName.setIdentifier(Tok.getIdentifierInfo(),
562 Tok.getLocation());
563
564 TemplateTy PossibleConcept;
565 bool MemberOfUnknownSpecialization = false;
566 auto TNK = Actions.isTemplateName(
567 getCurScope(), SS,
568 /*hasTemplateKeyword=*/false, PossibleConceptName,
569 /*ObjectType=*/ParsedType(),
570 /*EnteringContext=*/false, PossibleConcept,
571 MemberOfUnknownSpecialization,
572 /*AllowTypoCorrection=*/false);
573 if (MemberOfUnknownSpecialization || !PossibleConcept ||
574 TNK != TNK_Concept_template) {
575 if (SS.isNotEmpty())
576 AnnotateScopeToken(SS, !WasScopeAnnotation);
577 return false;
578 }
579
580 // At this point we're sure we're dealing with a constrained parameter. It
581 // may or may not have a template parameter list following the concept
582 // name.
583 if (AnnotateTemplateIdToken(PossibleConcept, TNK, SS,
584 /*TemplateKWLoc=*/SourceLocation(),
585 PossibleConceptName,
586 /*AllowTypeAnnotation=*/false,
587 /*TypeConstraint=*/true))
588 return true;
589 }
590
591 if (SS.isNotEmpty())
592 AnnotateScopeToken(SS, !WasScopeAnnotation);
593 return false;
594}
595
596NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
597 assert((Tok.isOneOf(tok::kw_class, tok::kw_typename) ||
598 isTypeConstraintAnnotation()) &&
599 "A type-parameter starts with 'class', 'typename' or a "
600 "type-constraint");
601
602 CXXScopeSpec TypeConstraintSS;
603 TemplateIdAnnotation *TypeConstraint = nullptr;
604 bool TypenameKeyword = false;
605 SourceLocation KeyLoc;
606 ParseOptionalCXXScopeSpecifier(TypeConstraintSS, /*ObjectType=*/nullptr,
607 /*ObjectHasErrors=*/false,
608 /*EnteringContext*/ false);
609 if (Tok.is(tok::annot_template_id)) {
610 // Consume the 'type-constraint'.
611 TypeConstraint =
612 static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
613 assert(TypeConstraint->Kind == TNK_Concept_template &&
614 "stray non-concept template-id annotation");
615 KeyLoc = ConsumeAnnotationToken();
616 } else {
617 assert(TypeConstraintSS.isEmpty() &&
618 "expected type constraint after scope specifier");
619
620 // Consume the 'class' or 'typename' keyword.
621 TypenameKeyword = Tok.is(tok::kw_typename);
622 KeyLoc = ConsumeToken();
623 }
624
625 // Grab the ellipsis (if given).
626 SourceLocation EllipsisLoc;
627 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
628 Diag(EllipsisLoc,
630 ? diag::warn_cxx98_compat_variadic_templates
631 : diag::ext_variadic_templates);
632 }
633
634 // Grab the template parameter name (if given)
635 SourceLocation NameLoc = Tok.getLocation();
636 IdentifierInfo *ParamName = nullptr;
637 if (Tok.is(tok::identifier)) {
638 ParamName = Tok.getIdentifierInfo();
639 ConsumeToken();
640 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
641 tok::greatergreater)) {
642 // Unnamed template parameter. Don't have to do anything here, just
643 // don't consume this token.
644 } else {
645 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
646 return nullptr;
647 }
648
649 // Recover from misplaced ellipsis.
650 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
651 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
652 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
653
654 // Grab a default argument (if available).
655 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
656 // we introduce the type parameter into the local scope.
657 SourceLocation EqualLoc;
658 ParsedType DefaultArg;
659 std::optional<DelayTemplateIdDestructionRAII> DontDestructTemplateIds;
660 if (TryConsumeToken(tok::equal, EqualLoc)) {
661 // The default argument might contain a lambda declaration; avoid destroying
662 // parsed template ids at the end of that declaration because they can be
663 // used in a type constraint later.
664 DontDestructTemplateIds.emplace(*this, /*DelayTemplateIdDestruction=*/true);
665 // The default argument may declare template parameters, notably
666 // if it contains a generic lambda, so we need to increase
667 // the template depth as these parameters would not be instantiated
668 // at the current level.
669 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
670 ++CurTemplateDepthTracker;
671 DefaultArg =
673 .get();
674 }
675
676 NamedDecl *NewDecl = Actions.ActOnTypeParameter(getCurScope(),
677 TypenameKeyword, EllipsisLoc,
678 KeyLoc, ParamName, NameLoc,
679 Depth, Position, EqualLoc,
680 DefaultArg,
681 TypeConstraint != nullptr);
682
683 if (TypeConstraint) {
684 Actions.ActOnTypeConstraint(TypeConstraintSS, TypeConstraint,
686 EllipsisLoc);
687 }
688
689 return NewDecl;
690}
691
692NamedDecl *Parser::ParseTemplateTemplateParameter(unsigned Depth,
693 unsigned Position) {
694 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
695
696 // Handle the template <...> part.
697 SourceLocation TemplateLoc = ConsumeToken();
698 SmallVector<NamedDecl*,8> TemplateParams;
699 SourceLocation LAngleLoc, RAngleLoc;
700 ExprResult OptionalRequiresClauseConstraintER;
701 {
702 MultiParseScope TemplateParmScope(*this);
703 if (ParseTemplateParameters(TemplateParmScope, Depth + 1, TemplateParams,
704 LAngleLoc, RAngleLoc)) {
705 return nullptr;
706 }
707 if (TryConsumeToken(tok::kw_requires)) {
708 OptionalRequiresClauseConstraintER =
709 Actions.ActOnRequiresClause(ParseConstraintLogicalOrExpression(
710 /*IsTrailingRequiresClause=*/false));
711 if (!OptionalRequiresClauseConstraintER.isUsable()) {
712 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
714 return nullptr;
715 }
716 }
717 }
718
720 SourceLocation NameLoc;
721 IdentifierInfo *ParamName = nullptr;
722 SourceLocation EllipsisLoc;
723 bool TypenameKeyword = false;
724
725 if (TryConsumeToken(tok::kw_class)) {
727 } else {
728
729 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
730 // Generate a meaningful error if the user forgot to put class before the
731 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
732 // or greater appear immediately or after 'struct'. In the latter case,
733 // replace the keyword with 'class'.
734 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
735 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
736 if (Tok.is(tok::kw_typename)) {
737 TypenameKeyword = true;
739 Diag(Tok.getLocation(),
741 ? diag::warn_cxx14_compat_template_template_param_typename
742 : diag::ext_template_template_param_typename)
743 << (!getLangOpts().CPlusPlus17
744 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
745 : FixItHint());
747 } else if (TryConsumeToken(tok::kw_concept)) {
749 } else if (TryConsumeToken(tok::kw_auto)) {
751 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
752 tok::greatergreater, tok::ellipsis)) {
753 // Provide a fixit if the identifier, comma,
754 // or greater appear immediately or after 'struct'. In the latter case,
755 // replace the keyword with 'class'.
756 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
757 << getLangOpts().CPlusPlus17
758 << (Replace
759 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
760 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
761 }
762 if (Replace)
763 ConsumeToken();
764 }
765
766 if (!getLangOpts().CPlusPlus26 &&
769 Diag(PrevTokLocation, diag::err_cxx26_template_template_params)
771 }
772
773 // Parse the ellipsis, if given.
774 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
775 Diag(EllipsisLoc,
777 ? diag::warn_cxx98_compat_variadic_templates
778 : diag::ext_variadic_templates);
779
780 // Get the identifier, if given.
781 NameLoc = Tok.getLocation();
782 if (Tok.is(tok::identifier)) {
783 ParamName = Tok.getIdentifierInfo();
784 ConsumeToken();
785 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
786 tok::greatergreater)) {
787 // Unnamed template parameter. Don't have to do anything here, just
788 // don't consume this token.
789 } else {
790 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
791 return nullptr;
792 }
793
794 // Recover from misplaced ellipsis.
795 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
796 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
797 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
798
799 TemplateParameterList *ParamList = Actions.ActOnTemplateParameterList(
800 Depth, SourceLocation(), TemplateLoc, LAngleLoc, TemplateParams,
801 RAngleLoc, OptionalRequiresClauseConstraintER.get());
802
803 // Grab a default argument (if available).
804 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
805 // we introduce the template parameter into the local scope.
806 SourceLocation EqualLoc;
807 ParsedTemplateArgument DefaultArg;
808 if (TryConsumeToken(tok::equal, EqualLoc)) {
809 DefaultArg = ParseTemplateTemplateArgument();
810 if (DefaultArg.isInvalid()) {
811 Diag(Tok.getLocation(),
812 diag::err_default_template_template_parameter_not_template);
813 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
815 }
816 }
817
818 return Actions.ActOnTemplateTemplateParameter(
819 getCurScope(), TemplateLoc, Kind, TypenameKeyword, ParamList, EllipsisLoc,
820 ParamName, NameLoc, Depth, Position, EqualLoc, DefaultArg);
821}
822
823NamedDecl *
824Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
825 // Parse the declaration-specifiers (i.e., the type).
826 // FIXME: The type should probably be restricted in some way... Not all
827 // declarators (parts of declarators?) are accepted for parameters.
828 DeclSpec DS(AttrFactory);
829 ParsedTemplateInfo TemplateInfo;
830 ParseDeclarationSpecifiers(DS, TemplateInfo, AS_none,
831 DeclSpecContext::DSC_template_param);
832
833 // Parse this as a typename.
836 ParseDeclarator(ParamDecl);
837 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
838 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
839 return nullptr;
840 }
841
842 // Recover from misplaced ellipsis.
843 SourceLocation EllipsisLoc;
844 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
845 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
846
847 // If there is a default value, parse it.
848 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
849 // we introduce the template parameter into the local scope.
850 SourceLocation EqualLoc;
851 ExprResult DefaultArg;
852 if (TryConsumeToken(tok::equal, EqualLoc)) {
853 if (Tok.is(tok::l_paren) && NextToken().is(tok::l_brace)) {
854 Diag(Tok.getLocation(), diag::err_stmt_expr_in_default_arg) << 1;
855 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
856 } else {
857 // C++ [temp.param]p15:
858 // When parsing a default template-argument for a non-type
859 // template-parameter, the first non-nested > is taken as the
860 // end of the template-parameter-list rather than a greater-than
861 // operator.
862 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
863
864 // The default argument may declare template parameters, notably
865 // if it contains a generic lambda, so we need to increase
866 // the template depth as these parameters would not be instantiated
867 // at the current level.
868 TemplateParameterDepthRAII CurTemplateDepthTracker(
869 TemplateParameterDepth);
870 ++CurTemplateDepthTracker;
871 EnterExpressionEvaluationContext ConstantEvaluated(
873 DefaultArg = Actions.ActOnConstantExpression(ParseInitializer());
874 if (DefaultArg.isInvalid())
875 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
876 }
877 }
878
879 // Create the parameter.
880 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
881 Depth, Position, EqualLoc,
882 DefaultArg.get());
883}
884
885void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
886 SourceLocation CorrectLoc,
887 bool AlreadyHasEllipsis,
888 bool IdentifierHasName) {
889 FixItHint Insertion;
890 if (!AlreadyHasEllipsis)
891 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
892 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
893 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
894 << !IdentifierHasName;
895}
896
897void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
898 Declarator &D) {
899 assert(EllipsisLoc.isValid());
900 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
901 if (!AlreadyHasEllipsis)
902 D.setEllipsisLoc(EllipsisLoc);
903 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
904 AlreadyHasEllipsis, D.hasName());
905}
906
907bool Parser::ParseGreaterThanInTemplateList(SourceLocation LAngleLoc,
908 SourceLocation &RAngleLoc,
909 bool ConsumeLastToken,
910 bool ObjCGenericList) {
911 // What will be left once we've consumed the '>'.
912 tok::TokenKind RemainingToken;
913 const char *ReplacementStr = "> >";
914 bool MergeWithNextToken = false;
915
916 switch (Tok.getKind()) {
917 default:
918 Diag(getEndOfPreviousToken(), diag::err_expected) << tok::greater;
919 Diag(LAngleLoc, diag::note_matching) << tok::less;
920 return true;
921
922 case tok::greater:
923 // Determine the location of the '>' token. Only consume this token
924 // if the caller asked us to.
925 RAngleLoc = Tok.getLocation();
926 if (ConsumeLastToken)
927 ConsumeToken();
928 return false;
929
930 case tok::greatergreater:
931 RemainingToken = tok::greater;
932 break;
933
934 case tok::greatergreatergreater:
935 RemainingToken = tok::greatergreater;
936 break;
937
938 case tok::greaterequal:
939 RemainingToken = tok::equal;
940 ReplacementStr = "> =";
941
942 // Join two adjacent '=' tokens into one, for cases like:
943 // void (*p)() = f<int>;
944 // return f<int>==p;
945 if (NextToken().is(tok::equal) &&
946 areTokensAdjacent(Tok, NextToken())) {
947 RemainingToken = tok::equalequal;
948 MergeWithNextToken = true;
949 }
950 break;
951
952 case tok::greatergreaterequal:
953 RemainingToken = tok::greaterequal;
954 break;
955 }
956
957 // This template-id is terminated by a token that starts with a '>'.
958 // Outside C++11 and Objective-C, this is now error recovery.
959 //
960 // C++11 allows this when the token is '>>', and in CUDA + C++11 mode, we
961 // extend that treatment to also apply to the '>>>' token.
962 //
963 // Objective-C allows this in its type parameter / argument lists.
964
965 SourceLocation TokBeforeGreaterLoc = PrevTokLocation;
966 SourceLocation TokLoc = Tok.getLocation();
967 Token Next = NextToken();
968
969 // Whether splitting the current token after the '>' would undesirably result
970 // in the remaining token pasting with the token after it. This excludes the
971 // MergeWithNextToken cases, which we've already handled.
972 bool PreventMergeWithNextToken =
973 (RemainingToken == tok::greater ||
974 RemainingToken == tok::greatergreater) &&
975 (Next.isOneOf(tok::greater, tok::greatergreater,
976 tok::greatergreatergreater, tok::equal, tok::greaterequal,
977 tok::greatergreaterequal, tok::equalequal)) &&
978 areTokensAdjacent(Tok, Next);
979
980 // Diagnose this situation as appropriate.
981 if (!ObjCGenericList) {
982 // The source range of the replaced token(s).
983 CharSourceRange ReplacementRange = CharSourceRange::getCharRange(
984 TokLoc, Lexer::AdvanceToTokenCharacter(TokLoc, 2, PP.getSourceManager(),
985 getLangOpts()));
986
987 // A hint to put a space between the '>>'s. In order to make the hint as
988 // clear as possible, we include the characters either side of the space in
989 // the replacement, rather than just inserting a space at SecondCharLoc.
990 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
991 ReplacementStr);
992
993 // A hint to put another space after the token, if it would otherwise be
994 // lexed differently.
995 FixItHint Hint2;
996 if (PreventMergeWithNextToken)
997 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
998
999 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
1000 if (getLangOpts().CPlusPlus11 &&
1001 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
1002 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
1003 else if (Tok.is(tok::greaterequal))
1004 DiagId = diag::err_right_angle_bracket_equal_needs_space;
1005 Diag(TokLoc, DiagId) << Hint1 << Hint2;
1006 }
1007
1008 // Find the "length" of the resulting '>' token. This is not always 1, as it
1009 // can contain escaped newlines.
1010 unsigned GreaterLength = Lexer::getTokenPrefixLength(
1011 TokLoc, 1, PP.getSourceManager(), getLangOpts());
1012
1013 // Annotate the source buffer to indicate that we split the token after the
1014 // '>'. This allows us to properly find the end of, and extract the spelling
1015 // of, the '>' token later.
1016 RAngleLoc = PP.SplitToken(TokLoc, GreaterLength);
1017
1018 // Strip the initial '>' from the token.
1019 bool CachingTokens = PP.IsPreviousCachedToken(Tok);
1020
1021 Token Greater = Tok;
1022 Greater.setLocation(RAngleLoc);
1023 Greater.setKind(tok::greater);
1024 Greater.setLength(GreaterLength);
1025
1026 unsigned OldLength = Tok.getLength();
1027 if (MergeWithNextToken) {
1028 ConsumeToken();
1029 OldLength += Tok.getLength();
1030 }
1031
1032 Tok.setKind(RemainingToken);
1033 Tok.setLength(OldLength - GreaterLength);
1034
1035 // Split the second token if lexing it normally would lex a different token
1036 // (eg, the fifth token in 'A<B>>>' should re-lex as '>', not '>>').
1037 SourceLocation AfterGreaterLoc = TokLoc.getLocWithOffset(GreaterLength);
1038 if (PreventMergeWithNextToken)
1039 AfterGreaterLoc = PP.SplitToken(AfterGreaterLoc, Tok.getLength());
1040 Tok.setLocation(AfterGreaterLoc);
1041
1042 // Update the token cache to match what we just did if necessary.
1043 if (CachingTokens) {
1044 // If the previous cached token is being merged, delete it.
1045 if (MergeWithNextToken)
1046 PP.ReplacePreviousCachedToken({});
1047
1048 if (ConsumeLastToken)
1049 PP.ReplacePreviousCachedToken({Greater, Tok});
1050 else
1051 PP.ReplacePreviousCachedToken({Greater});
1052 }
1053
1054 if (ConsumeLastToken) {
1055 PrevTokLocation = RAngleLoc;
1056 } else {
1057 PrevTokLocation = TokBeforeGreaterLoc;
1058 PP.EnterToken(Tok, /*IsReinject=*/true);
1059 Tok = Greater;
1060 }
1061
1062 return false;
1063}
1064
1065bool Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
1066 SourceLocation &LAngleLoc,
1067 TemplateArgList &TemplateArgs,
1068 SourceLocation &RAngleLoc,
1069 TemplateTy Template) {
1070 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
1071
1072 // Consume the '<'.
1073 LAngleLoc = ConsumeToken();
1074
1075 // Parse the optional template-argument-list.
1076 bool Invalid = false;
1077 {
1078 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
1079 if (!Tok.isOneOf(tok::greater, tok::greatergreater,
1080 tok::greatergreatergreater, tok::greaterequal,
1081 tok::greatergreaterequal))
1082 Invalid = ParseTemplateArgumentList(TemplateArgs, Template, LAngleLoc);
1083
1084 if (Invalid) {
1085 // Try to find the closing '>'.
1087 SkipUntil(tok::greater, tok::greatergreater,
1088 tok::greatergreatergreater, StopAtSemi | StopBeforeMatch);
1089 else
1090 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
1091 }
1092 }
1093
1094 return ParseGreaterThanInTemplateList(LAngleLoc, RAngleLoc, ConsumeLastToken,
1095 /*ObjCGenericList=*/false) ||
1096 Invalid;
1097}
1098
1099bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
1100 CXXScopeSpec &SS,
1101 SourceLocation TemplateKWLoc,
1103 bool AllowTypeAnnotation,
1104 bool TypeConstraint) {
1105 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
1106 assert((Tok.is(tok::less) || TypeConstraint) &&
1107 "Parser isn't at the beginning of a template-id");
1108 assert(!(TypeConstraint && AllowTypeAnnotation) && "type-constraint can't be "
1109 "a type annotation");
1110 assert((!TypeConstraint || TNK == TNK_Concept_template) && "type-constraint "
1111 "must accompany a concept name");
1112 assert((Template || TNK == TNK_Non_template) && "missing template name");
1113
1114 // Consume the template-name.
1115 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
1116
1117 // Parse the enclosed template argument list.
1118 SourceLocation LAngleLoc, RAngleLoc;
1119 TemplateArgList TemplateArgs;
1120 bool ArgsInvalid = false;
1121 if (!TypeConstraint || Tok.is(tok::less)) {
1122 ArgsInvalid = ParseTemplateIdAfterTemplateName(
1123 false, LAngleLoc, TemplateArgs, RAngleLoc, Template);
1124 // If we couldn't recover from invalid arguments, don't form an annotation
1125 // token -- we don't know how much to annotate.
1126 // FIXME: This can lead to duplicate diagnostics if we retry parsing this
1127 // template-id in another context. Try to annotate anyway?
1128 if (RAngleLoc.isInvalid())
1129 return true;
1130 }
1131
1132 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1133
1134 // Build the annotation token.
1135 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
1137 ArgsInvalid
1138 ? TypeError()
1139 : Actions.ActOnTemplateIdType(
1141 /*ElaboratedKeywordLoc=*/SourceLocation(), SS, TemplateKWLoc,
1142 Template, TemplateName.Identifier, TemplateNameLoc, LAngleLoc,
1143 TemplateArgsPtr, RAngleLoc);
1144
1145 Tok.setKind(tok::annot_typename);
1146 setTypeAnnotation(Tok, Type);
1147 if (SS.isNotEmpty())
1148 Tok.setLocation(SS.getBeginLoc());
1149 else if (TemplateKWLoc.isValid())
1150 Tok.setLocation(TemplateKWLoc);
1151 else
1152 Tok.setLocation(TemplateNameLoc);
1153 } else {
1154 // Build a template-id annotation token that can be processed
1155 // later.
1156 Tok.setKind(tok::annot_template_id);
1157
1158 const IdentifierInfo *TemplateII =
1160 ? TemplateName.Identifier
1161 : nullptr;
1162
1163 OverloadedOperatorKind OpKind =
1165 ? OO_None
1166 : TemplateName.OperatorFunctionId.Operator;
1167
1168 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
1169 TemplateKWLoc, TemplateNameLoc, TemplateII, OpKind, Template, TNK,
1170 LAngleLoc, RAngleLoc, TemplateArgs, ArgsInvalid, TemplateIds);
1171
1172 Tok.setAnnotationValue(TemplateId);
1173 if (TemplateKWLoc.isValid())
1174 Tok.setLocation(TemplateKWLoc);
1175 else
1176 Tok.setLocation(TemplateNameLoc);
1177 }
1178
1179 // Common fields for the annotation token
1180 Tok.setAnnotationEndLoc(RAngleLoc);
1181
1182 // In case the tokens were cached, have Preprocessor replace them with the
1183 // annotation token.
1184 PP.AnnotateCachedTokens(Tok);
1185 return false;
1186}
1187
1188void Parser::AnnotateTemplateIdTokenAsType(
1189 CXXScopeSpec &SS, ImplicitTypenameContext AllowImplicitTypename,
1190 bool IsClassName) {
1191 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1192
1193 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1194 assert(TemplateId->mightBeType() &&
1195 "Only works for type and dependent templates");
1196
1197 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1198 TemplateId->NumArgs);
1199
1201 TemplateId->isInvalid()
1202 ? TypeError()
1203 : Actions.ActOnTemplateIdType(
1205 /*ElaboratedKeywordLoc=*/SourceLocation(), SS,
1206 TemplateId->TemplateKWLoc, TemplateId->Template,
1207 TemplateId->Name, TemplateId->TemplateNameLoc,
1208 TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->RAngleLoc,
1209 /*IsCtorOrDtorName=*/false, IsClassName, AllowImplicitTypename);
1210 // Create the new "type" annotation token.
1211 Tok.setKind(tok::annot_typename);
1212 setTypeAnnotation(Tok, Type);
1213 if (SS.isNotEmpty()) // it was a C++ qualified type name.
1214 Tok.setLocation(SS.getBeginLoc());
1215 // End location stays the same
1216
1217 // Replace the template-id annotation token, and possible the scope-specifier
1218 // that precedes it, with the typename annotation token.
1219 PP.AnnotateCachedTokens(Tok);
1220}
1221
1222/// Determine whether the given token can end a template argument.
1224 // FIXME: Handle '>>>'.
1225 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater,
1226 tok::greatergreatergreater);
1227}
1228
1229ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1230 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1231 !Tok.is(tok::annot_cxxscope) && !Tok.is(tok::annot_template_id) &&
1232 !Tok.is(tok::annot_non_type))
1233 return ParsedTemplateArgument();
1234
1235 // C++0x [temp.arg.template]p1:
1236 // A template-argument for a template template-parameter shall be the name
1237 // of a class template or an alias template, expressed as id-expression.
1238 //
1239 // We parse an id-expression that refers to a class template or alias
1240 // template. The grammar we parse is:
1241 //
1242 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1243 //
1244 // followed by a token that terminates a template argument, such as ',',
1245 // '>', or (in some cases) '>>'.
1246 CXXScopeSpec SS; // nested-name-specifier, if present
1247 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1248 /*ObjectHasErrors=*/false,
1249 /*EnteringContext=*/false);
1250
1251 ParsedTemplateArgument Result;
1252 SourceLocation EllipsisLoc;
1253 if (SS.isSet() && Tok.is(tok::kw_template)) {
1254 // Parse the optional 'template' keyword following the
1255 // nested-name-specifier.
1256 SourceLocation TemplateKWLoc = ConsumeToken();
1257
1258 if (Tok.is(tok::identifier)) {
1259 // We appear to have a dependent template name.
1260 UnqualifiedId Name;
1261 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1262 ConsumeToken(); // the identifier
1263
1264 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1265
1266 // If the next token signals the end of a template argument, then we have
1267 // a (possibly-dependent) template name that could be a template template
1268 // argument.
1270 if (isEndOfTemplateArgument(Tok) &&
1271 Actions.ActOnTemplateName(getCurScope(), SS, TemplateKWLoc, Name,
1272 /*ObjectType=*/nullptr,
1273 /*EnteringContext=*/false, Template))
1274 Result = ParsedTemplateArgument(TemplateKWLoc, SS, Template,
1275 Name.StartLocation);
1276 }
1277 } else if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) ||
1278 Tok.is(tok::annot_non_type)) {
1279 // We may have a (non-dependent) template name.
1281 UnqualifiedId Name;
1282 if (Tok.is(tok::annot_non_type)) {
1283 NamedDecl *ND = getNonTypeAnnotation(Tok);
1284 if (!isa<VarTemplateDecl>(ND))
1285 return Result;
1286 Name.setIdentifier(ND->getIdentifier(), Tok.getLocation());
1287 ConsumeAnnotationToken();
1288 } else if (Tok.is(tok::annot_template_id)) {
1289 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1290 if (TemplateId->LAngleLoc.isValid())
1291 return Result;
1292 Name.setIdentifier(TemplateId->Name, Tok.getLocation());
1293 ConsumeAnnotationToken();
1294 } else {
1295 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1296 ConsumeToken(); // the identifier
1297 }
1298
1299 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1300
1301 if (isEndOfTemplateArgument(Tok)) {
1302 bool MemberOfUnknownSpecialization;
1303 TemplateNameKind TNK = Actions.isTemplateName(
1304 getCurScope(), SS,
1305 /*hasTemplateKeyword=*/false, Name,
1306 /*ObjectType=*/nullptr,
1307 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
1308 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template ||
1309 TNK == TNK_Var_template || TNK == TNK_Concept_template) {
1310 // We have an id-expression that refers to a class template or
1311 // (C++0x) alias template.
1312 Result = ParsedTemplateArgument(/*TemplateKwLoc=*/SourceLocation(), SS,
1313 Template, Name.StartLocation);
1314 }
1315 }
1316 }
1317
1318 Result = Actions.ActOnTemplateTemplateArgument(Result);
1319
1320 // If this is a pack expansion, build it as such.
1321 if (EllipsisLoc.isValid() && !Result.isInvalid())
1322 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1323
1324 return Result;
1325}
1326
1327ParsedTemplateArgument Parser::ParseTemplateArgument() {
1328 // C++ [temp.arg]p2:
1329 // In a template-argument, an ambiguity between a type-id and an
1330 // expression is resolved to a type-id, regardless of the form of
1331 // the corresponding template-parameter.
1332 //
1333 // Therefore, we initially try to parse a type-id - and isCXXTypeId might look
1334 // up and annotate an identifier as an id-expression during disambiguation,
1335 // so enter the appropriate context for a constant expression template
1336 // argument before trying to disambiguate.
1337
1338 EnterExpressionEvaluationContext EnterConstantEvaluated(
1340 /*LambdaContextDecl=*/nullptr,
1343 TypeResult TypeArg = ParseTypeName(
1344 /*Range=*/nullptr, DeclaratorContext::TemplateArg);
1345 return Actions.ActOnTemplateTypeArgument(TypeArg);
1346 }
1347
1348 // Try to parse a template template argument.
1349 {
1350 TentativeParsingAction TPA(*this);
1351
1352 ParsedTemplateArgument TemplateTemplateArgument =
1353 ParseTemplateTemplateArgument();
1354 if (!TemplateTemplateArgument.isInvalid()) {
1355 TPA.Commit();
1357 }
1358 // Revert this tentative parse to parse a non-type template argument.
1359 TPA.Revert();
1360 }
1361
1362 // Parse a non-type template argument.
1363 ExprResult ExprArg;
1364 SourceLocation Loc = Tok.getLocation();
1365 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))
1366 ExprArg = ParseBraceInitializer();
1367 else
1370 if (ExprArg.isInvalid() || !ExprArg.get()) {
1371 return ParsedTemplateArgument();
1372 }
1373
1374 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1375 ExprArg.get(), Loc);
1376}
1377
1378bool Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
1379 TemplateTy Template,
1380 SourceLocation OpenLoc) {
1381
1382 ColonProtectionRAIIObject ColonProtection(*this, false);
1383
1384 auto RunSignatureHelp = [&] {
1385 if (!Template)
1386 return QualType();
1387 CalledSignatureHelp = true;
1388 return Actions.CodeCompletion().ProduceTemplateArgumentSignatureHelp(
1389 Template, TemplateArgs, OpenLoc);
1390 };
1391
1392 do {
1393 PreferredType.enterFunctionArgument(Tok.getLocation(), RunSignatureHelp);
1394 ParsedTemplateArgument Arg = ParseTemplateArgument();
1395 SourceLocation EllipsisLoc;
1396 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1397 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1398
1399 if (Arg.isInvalid()) {
1400 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1401 RunSignatureHelp();
1402 return true;
1403 }
1404
1405 // Save this template argument.
1406 TemplateArgs.push_back(Arg);
1407
1408 // If the next token is a comma, consume it and keep reading
1409 // arguments.
1410 } while (TryConsumeToken(tok::comma));
1411
1412 return false;
1413}
1414
1415Parser::DeclGroupPtrTy Parser::ParseExplicitInstantiation(
1416 DeclaratorContext Context, SourceLocation ExternLoc,
1417 SourceLocation TemplateLoc, SourceLocation &DeclEnd,
1418 ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
1419 // This isn't really required here.
1420 ParsingDeclRAIIObject
1421 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1422 ParsedTemplateInfo TemplateInfo(ExternLoc, TemplateLoc);
1423 return ParseDeclarationAfterTemplate(
1424 Context, TemplateInfo, ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
1425}
1426
1427SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1428 if (TemplateParams)
1429 return getTemplateParamsRange(TemplateParams->data(),
1430 TemplateParams->size());
1431
1432 SourceRange R(TemplateLoc);
1433 if (ExternLoc.isValid())
1434 R.setBegin(ExternLoc);
1435 return R;
1436}
1437
1438void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1439 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1440}
1441
1442void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1443 if (!LPT.D)
1444 return;
1445
1446 // Destroy TemplateIdAnnotations when we're done, if possible.
1447 DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(*this);
1448
1449 // Get the FunctionDecl.
1450 FunctionDecl *FunD = LPT.D->getAsFunction();
1451 // Track template parameter depth.
1452 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1453
1454 // To restore the context after late parsing.
1455 Sema::ContextRAII GlobalSavedContext(
1456 Actions, Actions.Context.getTranslationUnitDecl());
1457
1458 MultiParseScope Scopes(*this);
1459
1460 // Get the list of DeclContexts to reenter.
1461 SmallVector<DeclContext*, 4> DeclContextsToReenter;
1462 for (DeclContext *DC = FunD; DC && !DC->isTranslationUnit();
1463 DC = DC->getLexicalParent())
1464 DeclContextsToReenter.push_back(DC);
1465
1466 // Reenter scopes from outermost to innermost.
1467 for (DeclContext *DC : reverse(DeclContextsToReenter)) {
1468 CurTemplateDepthTracker.addDepth(
1469 ReenterTemplateScopes(Scopes, cast<Decl>(DC)));
1470 Scopes.Enter(Scope::DeclScope);
1471 // We'll reenter the function context itself below.
1472 if (DC != FunD)
1473 Actions.PushDeclContext(Actions.getCurScope(), DC);
1474 }
1475
1476 // Parsing should occur with empty FP pragma stack and FP options used in the
1477 // point of the template definition.
1478 Sema::FpPragmaStackSaveRAII SavedStack(Actions);
1479 Actions.resetFPOptions(LPT.FPO);
1480
1481 assert(!LPT.Toks.empty() && "Empty body!");
1482
1483 // Append the current token at the end of the new token stream so that it
1484 // doesn't get lost.
1485 LPT.Toks.push_back(Tok);
1486 PP.EnterTokenStream(LPT.Toks, true, /*IsReinject*/true);
1487
1488 // Consume the previously pushed token.
1489 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1490 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1491 "Inline method not starting with '{', ':' or 'try'");
1492
1493 // Parse the method body. Function body parsing code is similar enough
1494 // to be re-used for method bodies as well.
1497
1498 // Recreate the containing function DeclContext.
1499 Sema::ContextRAII FunctionSavedContext(Actions, FunD->getLexicalParent());
1500
1501 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1502
1503 if (Tok.is(tok::kw_try)) {
1504 ParseFunctionTryBlock(LPT.D, FnScope);
1505 } else {
1506 if (Tok.is(tok::colon))
1507 ParseConstructorInitializer(LPT.D);
1508 else
1509 Actions.ActOnDefaultCtorInitializers(LPT.D);
1510
1511 if (Tok.is(tok::l_brace)) {
1512 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1514 ->getTemplateParameters()
1515 ->getDepth() == TemplateParameterDepth - 1) &&
1516 "TemplateParameterDepth should be greater than the depth of "
1517 "current template being instantiated!");
1518 ParseFunctionStatementBody(LPT.D, FnScope);
1519 Actions.UnmarkAsLateParsedTemplate(FunD);
1520 } else
1521 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1522 }
1523}
1524
1525void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1526 tok::TokenKind kind = Tok.getKind();
1527 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1528 // Consume everything up to (and including) the matching right brace.
1529 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1530 }
1531
1532 // If we're in a function-try-block, we need to store all the catch blocks.
1533 if (kind == tok::kw_try) {
1534 while (Tok.is(tok::kw_catch)) {
1535 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1536 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1537 }
1538 }
1539}
1540
1541bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
1542 TentativeParsingAction TPA(*this);
1543 // FIXME: We could look at the token sequence in a lot more detail here.
1544 if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater,
1546 TPA.Commit();
1547
1548 SourceLocation Greater;
1549 ParseGreaterThanInTemplateList(Less, Greater, true, false);
1550 Actions.diagnoseExprIntendedAsTemplateName(getCurScope(), LHS,
1551 Less, Greater);
1552 return true;
1553 }
1554
1555 // There's no matching '>' token, this probably isn't supposed to be
1556 // interpreted as a template-id. Parse it as an (ill-formed) comparison.
1557 TPA.Revert();
1558 return false;
1559}
1560
1561void Parser::checkPotentialAngleBracket(ExprResult &PotentialTemplateName) {
1562 assert(Tok.is(tok::less) && "not at a potential angle bracket");
1563
1564 bool DependentTemplateName = false;
1565 if (!Actions.mightBeIntendedToBeTemplateName(PotentialTemplateName,
1566 DependentTemplateName))
1567 return;
1568
1569 // OK, this might be a name that the user intended to be parsed as a
1570 // template-name, followed by a '<' token. Check for some easy cases.
1571
1572 // If we have potential_template<>, then it's supposed to be a template-name.
1573 if (NextToken().is(tok::greater) ||
1575 NextToken().isOneOf(tok::greatergreater, tok::greatergreatergreater))) {
1576 SourceLocation Less = ConsumeToken();
1577 SourceLocation Greater;
1578 ParseGreaterThanInTemplateList(Less, Greater, true, false);
1579 Actions.diagnoseExprIntendedAsTemplateName(
1580 getCurScope(), PotentialTemplateName, Less, Greater);
1581 // FIXME: Perform error recovery.
1582 PotentialTemplateName = ExprError();
1583 return;
1584 }
1585
1586 // If we have 'potential_template<type-id', assume it's supposed to be a
1587 // template-name if there's a matching '>' later on.
1588 {
1589 // FIXME: Avoid the tentative parse when NextToken() can't begin a type.
1590 TentativeParsingAction TPA(*this);
1591 SourceLocation Less = ConsumeToken();
1592 if (isTypeIdUnambiguously() &&
1593 diagnoseUnknownTemplateId(PotentialTemplateName, Less)) {
1594 TPA.Commit();
1595 // FIXME: Perform error recovery.
1596 PotentialTemplateName = ExprError();
1597 return;
1598 }
1599 TPA.Revert();
1600 }
1601
1602 // Otherwise, remember that we saw this in case we see a potentially-matching
1603 // '>' token later on.
1604 AngleBracketTracker::Priority Priority =
1605 (DependentTemplateName ? AngleBracketTracker::DependentName
1606 : AngleBracketTracker::PotentialTypo) |
1607 (Tok.hasLeadingSpace() ? AngleBracketTracker::SpaceBeforeLess
1608 : AngleBracketTracker::NoSpaceBeforeLess);
1609 AngleBrackets.add(*this, PotentialTemplateName.get(), Tok.getLocation(),
1610 Priority);
1611}
1612
1613bool Parser::checkPotentialAngleBracketDelimiter(
1614 const AngleBracketTracker::Loc &LAngle, const Token &OpToken) {
1615 // If a comma in an expression context is followed by a type that can be a
1616 // template argument and cannot be an expression, then this is ill-formed,
1617 // but might be intended to be part of a template-id.
1618 if (OpToken.is(tok::comma) && isTypeIdUnambiguously() &&
1619 diagnoseUnknownTemplateId(LAngle.TemplateName, LAngle.LessLoc)) {
1620 AngleBrackets.clear(*this);
1621 return true;
1622 }
1623
1624 // If a context that looks like a template-id is followed by '()', then
1625 // this is ill-formed, but might be intended to be a template-id
1626 // followed by '()'.
1627 if (OpToken.is(tok::greater) && Tok.is(tok::l_paren) &&
1628 NextToken().is(tok::r_paren)) {
1629 Actions.diagnoseExprIntendedAsTemplateName(
1630 getCurScope(), LAngle.TemplateName, LAngle.LessLoc,
1631 OpToken.getLocation());
1632 AngleBrackets.clear(*this);
1633 return true;
1634 }
1635
1636 // After a '>' (etc), we're no longer potentially in a construct that's
1637 // intended to be treated as a template-id.
1638 if (OpToken.is(tok::greater) ||
1640 OpToken.isOneOf(tok::greatergreater, tok::greatergreatergreater)))
1641 AngleBrackets.clear(*this);
1642 return false;
1643}
Defines the clang::ASTContext interface.
static Decl::Kind getKind(const Decl *D)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
bool is(tok::TokenKind Kind) const
Token Tok
The Token.
bool isNot(T Kind) const
FormatToken * Next
The next token in the unwrapped line.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
static bool isEndOfTemplateArgument(Token Tok)
Determine whether the given token can end a template argument.
static constexpr bool isOneOf()
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:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
static CharSourceRange getCharRange(SourceRange R)
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2142
static const TST TST_unspecified
Definition DeclSpec.h:251
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:178
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1952
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2388
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2778
bool hasName() const
hasName - Whether this declarator has a name, which might be an identifier (accessible via getIdentif...
Definition DeclSpec.h:2372
void setEllipsisLoc(SourceLocation EL)
Definition DeclSpec.h:2779
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:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
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:105
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:407
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:822
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
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:528
void Enter(unsigned ScopeFlags)
Definition Parser.h:536
ParseScope - Introduces a new scope for parsing.
Definition Parser.h:492
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:88
SourceLocation getEndOfPreviousToken() const
Definition Parser.cpp:1844
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition Parser.h:347
Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies)
Definition Parser.cpp:59
AttributeFactory & getAttrFactory()
Definition Parser.h:293
ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-or-expression.
ExprResult ParseConstantExpressionInExprEvalContext(TypoCorrectionTypeBehavior CorrectionBehavior=TypoCorrectionTypeBehavior::AllowNonTypes)
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.
friend class ColonProtectionRAIIObject
Definition Parser.h:281
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition Parser.h:375
const Token & GetLookAheadToken(unsigned N)
GetLookAheadToken - This peeks ahead N tokens and returns that token without consuming any tokens.
Definition Parser.h:401
bool TryConsumeToken(tok::TokenKind Expected)
Definition Parser.h:355
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Parser.h:304
Scope * getCurScope() const
Definition Parser.h:296
OpaquePtr< TemplateName > TemplateTy
Definition Parser.h:305
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:591
friend class ObjCDeclContextSwitch
Definition Parser.h:5399
const LangOptions & getLangOpts() const
Definition Parser.h:289
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition Parser.h:572
@ StopAtSemi
Stop skipping at semicolon.
Definition Parser.h:570
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition Parser.h:409
ExprResult ParseConstraintExpression()
Parse a constraint-expression.
SmallVector< TemplateParameterList *, 4 > TemplateParameterLists
Definition Parser.h:7865
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.
@ 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
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6818
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.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:142
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:104
void * getAnnotationValue() const
Definition Token.h:244
bool isOneOf(Ts... Ks) const
Definition Token.h:105
bool isNot(tok::TokenKind K) const
Definition Token.h:111
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:227
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1039
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1127
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1097
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
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:1935
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus26
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
@ TemplateTemplateArgument
Definition Sema.h:613
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1017
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_none
Definition Specifiers.h:128
TypeResult TypeError()
Definition Ownership.h:267
DeclaratorContext
Definition DeclSpec.h:1902
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ ExplicitInstantiation
We are parsing an explicit instantiation.
Definition Parser.h:85
@ NonTemplate
We are not parsing a template at all.
Definition Parser.h:79
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:564
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
@ TNK_Dependent_template_name
The name refers to a dependent template name:
@ TNK_Concept_template
The name refers to a concept.
@ TNK_Non_template
The name does not refer to a template.
U cast(CodeGen::Address addr)
Definition Address.h:327
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:1256
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5970
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
#define false
Definition stdbool.h:26
FPOptions FPO
Floating-point options in the point of definition.
Definition Sema.h:15822
Decl * D
The template function declaration to be late parsed.
Definition Sema.h:15820
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.