1 //===--- ParseTemplate.cpp - Template Parsing -----------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements parsing of C++ templates.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclTemplate.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/Parse/ParseDiagnostic.h"
17 #include "clang/Parse/Parser.h"
18 #include "clang/Parse/RAIIObjectsForParser.h"
19 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/ParsedTemplate.h"
21 #include "clang/Sema/Scope.h"
22 #include "llvm/Support/TimeProfiler.h"
23 using namespace clang;
25 /// Parse a template declaration, explicit instantiation, or
26 /// explicit specialization.
27 Decl *Parser::ParseDeclarationStartingWithTemplate(
28 DeclaratorContext Context, SourceLocation &DeclEnd,
29 ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
30 ObjCDeclContextSwitch ObjCDC(*this);
32 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
33 return ParseExplicitInstantiation(Context, SourceLocation(), ConsumeToken(),
34 DeclEnd, AccessAttrs, AS);
36 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AccessAttrs,
40 /// Parse a template declaration or an explicit specialization.
42 /// Template declarations include one or more template parameter lists
43 /// and either the function or class template declaration. Explicit
44 /// specializations contain one or more 'template < >' prefixes
45 /// followed by a (possibly templated) declaration. Since the
46 /// syntactic form of both features is nearly identical, we parse all
47 /// of the template headers together and let semantic analysis sort
48 /// the declarations from the explicit specializations.
50 /// template-declaration: [C++ temp]
51 /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
53 /// template-declaration: [C++2a]
54 /// template-head declaration
55 /// template-head concept-definition
57 /// TODO: requires-clause
58 /// template-head: [C++2a]
59 /// 'template' '<' template-parameter-list '>'
60 /// requires-clause[opt]
62 /// explicit-specialization: [ C++ temp.expl.spec]
63 /// 'template' '<' '>' declaration
64 Decl *Parser::ParseTemplateDeclarationOrSpecialization(
65 DeclaratorContext Context, SourceLocation &DeclEnd,
66 ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
67 assert(Tok.isOneOf(tok::kw_export, tok::kw_template) &&
68 "Token does not start a template declaration.");
70 // Enter template-parameter scope.
71 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
73 // Tell the action that names should be checked in the context of
74 // the declaration to come.
76 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
78 // Parse multiple levels of template headers within this template
79 // parameter scope, e.g.,
81 // template<typename T>
82 // template<typename U>
83 // class A<T>::B { ... };
85 // We parse multiple levels non-recursively so that we can build a
86 // single data structure containing all of the template parameter
87 // lists to easily differentiate between the case above and:
89 // template<typename T>
91 // template<typename U> class B;
94 // In the first case, the action for declaring A<T>::B receives
95 // both template parameter lists. In the second case, the action for
96 // defining A<T>::B receives just the inner template parameter list
97 // (and retrieves the outer template parameter list from its
99 bool isSpecialization = true;
100 bool LastParamListWasEmpty = false;
101 TemplateParameterLists ParamLists;
102 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
105 // Consume the 'export', if any.
106 SourceLocation ExportLoc;
107 TryConsumeToken(tok::kw_export, ExportLoc);
109 // Consume the 'template', which should be here.
110 SourceLocation TemplateLoc;
111 if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
112 Diag(Tok.getLocation(), diag::err_expected_template);
116 // Parse the '<' template-parameter-list '>'
117 SourceLocation LAngleLoc, RAngleLoc;
118 SmallVector<NamedDecl*, 4> TemplateParams;
119 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
120 TemplateParams, LAngleLoc, RAngleLoc)) {
121 // Skip until the semi-colon or a '}'.
122 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
123 TryConsumeToken(tok::semi);
127 ExprResult OptionalRequiresClauseConstraintER;
128 if (!TemplateParams.empty()) {
129 isSpecialization = false;
130 ++CurTemplateDepthTracker;
132 if (TryConsumeToken(tok::kw_requires)) {
133 OptionalRequiresClauseConstraintER =
134 Actions.CorrectDelayedTyposInExpr(
135 ParseConstraintLogicalOrExpression(
136 /*IsTrailingRequiresClause=*/false));
137 if (!OptionalRequiresClauseConstraintER.isUsable()) {
138 // Skip until the semi-colon or a '}'.
139 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
140 TryConsumeToken(tok::semi);
145 LastParamListWasEmpty = true;
148 ParamLists.push_back(Actions.ActOnTemplateParameterList(
149 CurTemplateDepthTracker.getDepth(), ExportLoc, TemplateLoc, LAngleLoc,
150 TemplateParams, RAngleLoc, OptionalRequiresClauseConstraintER.get()));
151 } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
153 unsigned NewFlags = getCurScope()->getFlags() & ~Scope::TemplateParamScope;
154 ParseScopeFlags TemplateScopeFlags(this, NewFlags, isSpecialization);
156 // Parse the actual template declaration.
157 if (Tok.is(tok::kw_concept))
158 return ParseConceptDefinition(
159 ParsedTemplateInfo(&ParamLists, isSpecialization,
160 LastParamListWasEmpty),
163 return ParseSingleDeclarationAfterTemplate(
165 ParsedTemplateInfo(&ParamLists, isSpecialization, LastParamListWasEmpty),
166 ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
169 /// Parse a single declaration that declares a template,
170 /// template specialization, or explicit instantiation of a template.
172 /// \param DeclEnd will receive the source location of the last token
173 /// within this declaration.
175 /// \param AS the access specifier associated with this
176 /// declaration. Will be AS_none for namespace-scope declarations.
178 /// \returns the new declaration.
179 Decl *Parser::ParseSingleDeclarationAfterTemplate(
180 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
181 ParsingDeclRAIIObject &DiagsFromTParams, SourceLocation &DeclEnd,
182 ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
183 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
184 "Template information required");
186 if (Tok.is(tok::kw_static_assert)) {
187 // A static_assert declaration may not be templated.
188 Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
189 << TemplateInfo.getSourceRange();
190 // Parse the static_assert declaration to improve error recovery.
191 return ParseStaticAssertDeclaration(DeclEnd);
194 if (Context == DeclaratorContext::MemberContext) {
195 // We are parsing a member template.
196 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
201 ParsedAttributesWithRange prefixAttrs(AttrFactory);
202 MaybeParseCXX11Attributes(prefixAttrs);
204 if (Tok.is(tok::kw_using)) {
205 auto usingDeclPtr = ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
207 if (!usingDeclPtr || !usingDeclPtr.get().isSingleDecl())
209 return usingDeclPtr.get().getSingleDecl();
212 // Parse the declaration specifiers, stealing any diagnostics from
213 // the template parameters.
214 ParsingDeclSpec DS(*this, &DiagsFromTParams);
216 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
217 getDeclSpecContextFromDeclaratorContext(Context));
219 if (Tok.is(tok::semi)) {
220 ProhibitAttributes(prefixAttrs);
221 DeclEnd = ConsumeToken();
222 RecordDecl *AnonRecord = nullptr;
223 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
224 getCurScope(), AS, DS,
225 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
226 : MultiTemplateParamsArg(),
227 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
229 assert(!AnonRecord &&
230 "Anonymous unions/structs should not be valid with template");
235 // Move the attributes from the prefix into the DS.
236 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
237 ProhibitAttributes(prefixAttrs);
239 DS.takeAttributesFrom(prefixAttrs);
241 // Parse the declarator.
242 ParsingDeclarator DeclaratorInfo(*this, DS, (DeclaratorContext)Context);
243 if (TemplateInfo.TemplateParams)
244 DeclaratorInfo.setTemplateParameterLists(*TemplateInfo.TemplateParams);
245 ParseDeclarator(DeclaratorInfo);
246 // Error parsing the declarator?
247 if (!DeclaratorInfo.hasName()) {
248 // If so, skip until the semi-colon or a }.
249 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
250 if (Tok.is(tok::semi))
255 llvm::TimeTraceScope TimeScope("ParseTemplate", [&]() {
256 return DeclaratorInfo.getIdentifier() != nullptr
257 ? DeclaratorInfo.getIdentifier()->getName()
261 LateParsedAttrList LateParsedAttrs(true);
262 if (DeclaratorInfo.isFunctionDeclarator()) {
263 if (Tok.is(tok::kw_requires))
264 ParseTrailingRequiresClause(DeclaratorInfo);
266 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
269 if (DeclaratorInfo.isFunctionDeclarator() &&
270 isStartOfFunctionDefinition(DeclaratorInfo)) {
272 // Function definitions are only allowed at file scope and in C++ classes.
273 // The C++ inline method definition case is handled elsewhere, so we only
274 // need to handle the file scope definition case.
275 if (Context != DeclaratorContext::FileContext) {
276 Diag(Tok, diag::err_function_definition_not_allowed);
281 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
282 // Recover by ignoring the 'typedef'. This was probably supposed to be
283 // the 'typename' keyword, which we should have already suggested adding
284 // if it's appropriate.
285 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
286 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
287 DS.ClearStorageClassSpecs();
290 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
291 if (DeclaratorInfo.getName().getKind() !=
292 UnqualifiedIdKind::IK_TemplateId) {
293 // If the declarator-id is not a template-id, issue a diagnostic and
294 // recover by ignoring the 'template' keyword.
295 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
296 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
299 SourceLocation LAngleLoc
300 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
301 Diag(DeclaratorInfo.getIdentifierLoc(),
302 diag::err_explicit_instantiation_with_definition)
303 << SourceRange(TemplateInfo.TemplateLoc)
304 << FixItHint::CreateInsertion(LAngleLoc, "<>");
306 // Recover as if it were an explicit specialization.
307 TemplateParameterLists FakedParamLists;
308 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
309 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
310 LAngleLoc, nullptr));
312 return ParseFunctionDefinition(
313 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
314 /*isSpecialization=*/true,
315 /*lastParameterListWasEmpty=*/true),
319 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
323 // Parse this declaration.
324 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
327 if (Tok.is(tok::comma)) {
328 Diag(Tok, diag::err_multiple_template_declarators)
329 << (int)TemplateInfo.Kind;
330 SkipUntil(tok::semi);
334 // Eat the semi colon after the declaration.
335 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
336 if (LateParsedAttrs.size() > 0)
337 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
338 DeclaratorInfo.complete(ThisDecl);
342 /// \brief Parse a single declaration that declares a concept.
344 /// \param DeclEnd will receive the source location of the last token
345 /// within this declaration.
347 /// \returns the new declaration.
349 Parser::ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
350 SourceLocation &DeclEnd) {
351 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
352 "Template information required");
353 assert(Tok.is(tok::kw_concept) &&
354 "ParseConceptDefinition must be called when at a 'concept' keyword");
356 ConsumeToken(); // Consume 'concept'
358 SourceLocation BoolKWLoc;
359 if (TryConsumeToken(tok::kw_bool, BoolKWLoc))
360 Diag(Tok.getLocation(), diag::ext_concept_legacy_bool_keyword) <<
361 FixItHint::CreateRemoval(SourceLocation(BoolKWLoc));
363 DiagnoseAndSkipCXX11Attributes();
366 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
367 /*EnteringContext=*/false, /*MayBePseudoDestructor=*/nullptr,
368 /*IsTypename=*/false, /*LastII=*/nullptr, /*OnlyNamespace=*/true) ||
370 SkipUntil(tok::semi);
375 Diag(SS.getBeginLoc(),
376 diag::err_concept_definition_not_identifier);
378 UnqualifiedId Result;
379 if (ParseUnqualifiedId(SS, /*EnteringContext=*/false,
380 /*AllowDestructorName=*/false,
381 /*AllowConstructorName=*/false,
382 /*AllowDeductionGuide=*/false,
383 /*ObjectType=*/ParsedType(), /*TemplateKWLoc=*/nullptr,
385 SkipUntil(tok::semi);
389 if (Result.getKind() != UnqualifiedIdKind::IK_Identifier) {
390 Diag(Result.getBeginLoc(), diag::err_concept_definition_not_identifier);
391 SkipUntil(tok::semi);
395 IdentifierInfo *Id = Result.Identifier;
396 SourceLocation IdLoc = Result.getBeginLoc();
398 DiagnoseAndSkipCXX11Attributes();
400 if (!TryConsumeToken(tok::equal)) {
401 Diag(Tok.getLocation(), diag::err_expected) << tok::equal;
402 SkipUntil(tok::semi);
406 ExprResult ConstraintExprResult =
407 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
408 if (ConstraintExprResult.isInvalid()) {
409 SkipUntil(tok::semi);
413 DeclEnd = Tok.getLocation();
414 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
415 Expr *ConstraintExpr = ConstraintExprResult.get();
416 return Actions.ActOnConceptDefinition(getCurScope(),
417 *TemplateInfo.TemplateParams,
418 Id, IdLoc, ConstraintExpr);
421 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
422 /// angle brackets. Depth is the depth of this template-parameter-list, which
423 /// is the number of template headers directly enclosing this template header.
424 /// TemplateParams is the current list of template parameters we're building.
425 /// The template parameter we parse will be added to this list. LAngleLoc and
426 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
427 /// that enclose this template parameter list.
429 /// \returns true if an error occurred, false otherwise.
430 bool Parser::ParseTemplateParameters(
431 unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams,
432 SourceLocation &LAngleLoc, SourceLocation &RAngleLoc) {
433 // Get the template parameter list.
434 if (!TryConsumeToken(tok::less, LAngleLoc)) {
435 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
439 // Try to parse the template parameter list.
441 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
442 Failed = ParseTemplateParameterList(Depth, TemplateParams);
444 if (Tok.is(tok::greatergreater)) {
445 // No diagnostic required here: a template-parameter-list can only be
446 // followed by a declaration or, for a template template parameter, the
447 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
448 // This matters for elegant diagnosis of:
449 // template<template<typename>> struct S;
450 Tok.setKind(tok::greater);
451 RAngleLoc = Tok.getLocation();
452 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
453 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
454 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
460 /// ParseTemplateParameterList - Parse a template parameter list. If
461 /// the parsing fails badly (i.e., closing bracket was left out), this
462 /// will try to put the token stream in a reasonable position (closing
463 /// a statement, etc.) and return false.
465 /// template-parameter-list: [C++ temp]
466 /// template-parameter
467 /// template-parameter-list ',' template-parameter
469 Parser::ParseTemplateParameterList(const unsigned Depth,
470 SmallVectorImpl<NamedDecl*> &TemplateParams) {
473 if (NamedDecl *TmpParam
474 = ParseTemplateParameter(Depth, TemplateParams.size())) {
475 TemplateParams.push_back(TmpParam);
477 // If we failed to parse a template parameter, skip until we find
478 // a comma or closing brace.
479 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
480 StopAtSemi | StopBeforeMatch);
483 // Did we find a comma or the end of the template parameter list?
484 if (Tok.is(tok::comma)) {
486 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
487 // Don't consume this... that's done by template parser.
490 // Somebody probably forgot to close the template. Skip ahead and
491 // try to get out of the expression. This error is currently
492 // subsumed by whatever goes on in ParseTemplateParameter.
493 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
494 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
495 StopAtSemi | StopBeforeMatch);
502 /// Determine whether the parser is at the start of a template
504 Parser::TPResult Parser::isStartOfTemplateTypeParameter() {
505 if (Tok.is(tok::kw_class)) {
506 // "class" may be the start of an elaborated-type-specifier or a
507 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
508 switch (NextToken().getKind()) {
512 case tok::greatergreater:
514 return TPResult::True;
516 case tok::identifier:
517 // This may be either a type-parameter or an elaborated-type-specifier.
518 // We have to look further.
522 return TPResult::False;
525 switch (GetLookAheadToken(2).getKind()) {
529 case tok::greatergreater:
530 return TPResult::True;
533 return TPResult::False;
537 if (TryAnnotateTypeConstraint())
538 return TPResult::Error;
540 if (isTypeConstraintAnnotation() &&
541 // Next token might be 'auto' or 'decltype', indicating that this
542 // type-constraint is in fact part of a placeholder-type-specifier of a
543 // non-type template parameter.
544 !GetLookAheadToken(Tok.is(tok::annot_cxxscope) ? 2 : 1)
545 .isOneOf(tok::kw_auto, tok::kw_decltype))
546 return TPResult::True;
548 // 'typedef' is a reasonably-common typo/thinko for 'typename', and is
549 // ill-formed otherwise.
550 if (Tok.isNot(tok::kw_typename) && Tok.isNot(tok::kw_typedef))
551 return TPResult::False;
553 // C++ [temp.param]p2:
554 // There is no semantic difference between class and typename in a
555 // template-parameter. typename followed by an unqualified-id
556 // names a template type parameter. typename followed by a
557 // qualified-id denotes the type in a non-type
558 // parameter-declaration.
559 Token Next = NextToken();
561 // If we have an identifier, skip over it.
562 if (Next.getKind() == tok::identifier)
563 Next = GetLookAheadToken(2);
565 switch (Next.getKind()) {
569 case tok::greatergreater:
571 return TPResult::True;
573 case tok::kw_typename:
574 case tok::kw_typedef:
576 // These indicate that a comma was missed after a type parameter, not that
577 // we have found a non-type parameter.
578 return TPResult::True;
581 return TPResult::False;
585 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
587 /// template-parameter: [C++ temp.param]
589 /// parameter-declaration
591 /// type-parameter: (See below)
592 /// type-parameter-key ...[opt] identifier[opt]
593 /// type-parameter-key identifier[opt] = type-id
594 /// (C++2a) type-constraint ...[opt] identifier[opt]
595 /// (C++2a) type-constraint identifier[opt] = type-id
596 /// 'template' '<' template-parameter-list '>' type-parameter-key
597 /// ...[opt] identifier[opt]
598 /// 'template' '<' template-parameter-list '>' type-parameter-key
599 /// identifier[opt] '=' id-expression
601 /// type-parameter-key:
605 NamedDecl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
607 switch (isStartOfTemplateTypeParameter()) {
609 // Is there just a typo in the input code? ('typedef' instead of
611 if (Tok.is(tok::kw_typedef)) {
612 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
614 Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
615 << FixItHint::CreateReplacement(CharSourceRange::getCharRange(
620 Tok.setKind(tok::kw_typename);
623 return ParseTypeParameter(Depth, Position);
624 case TPResult::False:
627 case TPResult::Error: {
628 // We return an invalid parameter as opposed to null to avoid having bogus
629 // diagnostics about an empty template parameter list.
630 // FIXME: Fix ParseTemplateParameterList to better handle nullptr results
632 // Return a NTTP as if there was an error in a scope specifier, the user
633 // probably meant to write the type of a NTTP.
634 DeclSpec DS(getAttrFactory());
635 DS.SetTypeSpecError();
636 Declarator D(DS, DeclaratorContext::TemplateParamContext);
637 D.SetIdentifier(nullptr, Tok.getLocation());
638 D.setInvalidType(true);
639 NamedDecl *ErrorParam = Actions.ActOnNonTypeTemplateParameter(
640 getCurScope(), D, Depth, Position, /*EqualLoc=*/SourceLocation(),
641 /*DefaultArg=*/nullptr);
642 ErrorParam->setInvalidDecl(true);
643 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
644 StopAtSemi | StopBeforeMatch);
648 case TPResult::Ambiguous:
649 llvm_unreachable("template param classification can't be ambiguous");
652 if (Tok.is(tok::kw_template))
653 return ParseTemplateTemplateParameter(Depth, Position);
655 // If it's none of the above, then it must be a parameter declaration.
656 // NOTE: This will pick up errors in the closure of the template parameter
657 // list (e.g., template < ; Check here to implement >> style closures.
658 return ParseNonTypeTemplateParameter(Depth, Position);
661 /// Check whether the current token is a template-id annotation denoting a
663 bool Parser::isTypeConstraintAnnotation() {
664 const Token &T = Tok.is(tok::annot_cxxscope) ? NextToken() : Tok;
665 if (T.isNot(tok::annot_template_id))
667 const auto *ExistingAnnot =
668 static_cast<TemplateIdAnnotation *>(T.getAnnotationValue());
669 return ExistingAnnot->Kind == TNK_Concept_template;
672 /// Try parsing a type-constraint at the current location.
675 /// nested-name-specifier[opt] concept-name
676 /// nested-name-specifier[opt] concept-name
677 /// '<' template-argument-list[opt] '>'[opt]
679 /// \returns true if an error occurred, and false otherwise.
680 bool Parser::TryAnnotateTypeConstraint() {
681 if (!getLangOpts().CPlusPlus2a)
684 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
685 if (ParseOptionalCXXScopeSpecifier(
687 /*EnteringContext=*/false,
688 /*MayBePseudoDestructor=*/nullptr,
689 // If this is not a type-constraint, then
690 // this scope-spec is part of the typename
691 // of a non-type template parameter
692 /*IsTypename=*/true, /*LastII=*/nullptr,
693 // We won't find concepts in
694 // non-namespaces anyway, so might as well
695 // parse this correctly for possible type
697 /*OnlyNamespace=*/false))
700 if (Tok.is(tok::identifier)) {
701 UnqualifiedId PossibleConceptName;
702 PossibleConceptName.setIdentifier(Tok.getIdentifierInfo(),
705 TemplateTy PossibleConcept;
706 bool MemberOfUnknownSpecialization = false;
707 auto TNK = Actions.isTemplateName(getCurScope(), SS,
708 /*hasTemplateKeyword=*/false,
710 /*ObjectType=*/ParsedType(),
711 /*EnteringContext=*/false,
713 MemberOfUnknownSpecialization);
714 if (MemberOfUnknownSpecialization || !PossibleConcept ||
715 TNK != TNK_Concept_template) {
717 AnnotateScopeToken(SS, !WasScopeAnnotation);
721 // At this point we're sure we're dealing with a constrained parameter. It
722 // may or may not have a template parameter list following the concept
724 if (AnnotateTemplateIdToken(PossibleConcept, TNK, SS,
725 /*TemplateKWLoc=*/SourceLocation(),
727 /*AllowTypeAnnotation=*/false,
728 /*TypeConstraint=*/true))
733 AnnotateScopeToken(SS, !WasScopeAnnotation);
737 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
738 /// Other kinds of template parameters are parsed in
739 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
741 /// type-parameter: [C++ temp.param]
742 /// 'class' ...[opt][C++0x] identifier[opt]
743 /// 'class' identifier[opt] '=' type-id
744 /// 'typename' ...[opt][C++0x] identifier[opt]
745 /// 'typename' identifier[opt] '=' type-id
746 NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
747 assert((Tok.isOneOf(tok::kw_class, tok::kw_typename) ||
748 isTypeConstraintAnnotation()) &&
749 "A type-parameter starts with 'class', 'typename' or a "
752 CXXScopeSpec TypeConstraintSS;
753 TemplateIdAnnotation *TypeConstraint = nullptr;
754 bool TypenameKeyword = false;
755 SourceLocation KeyLoc;
756 ParseOptionalCXXScopeSpecifier(TypeConstraintSS, nullptr,
757 /*EnteringContext*/ false);
758 if (Tok.is(tok::annot_template_id)) {
759 // Consume the 'type-constraint'.
761 static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
762 assert(TypeConstraint->Kind == TNK_Concept_template &&
763 "stray non-concept template-id annotation");
764 KeyLoc = ConsumeAnnotationToken();
766 assert(TypeConstraintSS.isEmpty() &&
767 "expected type constraint after scope specifier");
769 // Consume the 'class' or 'typename' keyword.
770 TypenameKeyword = Tok.is(tok::kw_typename);
771 KeyLoc = ConsumeToken();
774 // Grab the ellipsis (if given).
775 SourceLocation EllipsisLoc;
776 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
778 getLangOpts().CPlusPlus11
779 ? diag::warn_cxx98_compat_variadic_templates
780 : diag::ext_variadic_templates);
783 // Grab the template parameter name (if given)
784 SourceLocation NameLoc = Tok.getLocation();
785 IdentifierInfo *ParamName = nullptr;
786 if (Tok.is(tok::identifier)) {
787 ParamName = Tok.getIdentifierInfo();
789 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
790 tok::greatergreater)) {
791 // Unnamed template parameter. Don't have to do anything here, just
792 // don't consume this token.
794 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
798 // Recover from misplaced ellipsis.
799 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
800 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
801 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
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 type parameter into the local scope.
806 SourceLocation EqualLoc;
807 ParsedType DefaultArg;
808 if (TryConsumeToken(tok::equal, EqualLoc))
809 DefaultArg = ParseTypeName(/*Range=*/nullptr,
810 DeclaratorContext::TemplateTypeArgContext)
813 NamedDecl *NewDecl = Actions.ActOnTypeParameter(getCurScope(),
814 TypenameKeyword, EllipsisLoc,
815 KeyLoc, ParamName, NameLoc,
816 Depth, Position, EqualLoc,
818 TypeConstraint != nullptr);
820 if (TypeConstraint) {
821 Actions.ActOnTypeConstraint(TypeConstraintSS, TypeConstraint,
822 cast<TemplateTypeParmDecl>(NewDecl),
829 /// ParseTemplateTemplateParameter - Handle the parsing of template
830 /// template parameters.
832 /// type-parameter: [C++ temp.param]
833 /// 'template' '<' template-parameter-list '>' type-parameter-key
834 /// ...[opt] identifier[opt]
835 /// 'template' '<' template-parameter-list '>' type-parameter-key
836 /// identifier[opt] = id-expression
837 /// type-parameter-key:
839 /// 'typename' [C++1z]
841 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
842 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
844 // Handle the template <...> part.
845 SourceLocation TemplateLoc = ConsumeToken();
846 SmallVector<NamedDecl*,8> TemplateParams;
847 SourceLocation LAngleLoc, RAngleLoc;
849 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
850 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
856 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
857 // Generate a meaningful error if the user forgot to put class before the
858 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
859 // or greater appear immediately or after 'struct'. In the latter case,
860 // replace the keyword with 'class'.
861 if (!TryConsumeToken(tok::kw_class)) {
862 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
863 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
864 if (Tok.is(tok::kw_typename)) {
865 Diag(Tok.getLocation(),
866 getLangOpts().CPlusPlus17
867 ? diag::warn_cxx14_compat_template_template_param_typename
868 : diag::ext_template_template_param_typename)
869 << (!getLangOpts().CPlusPlus17
870 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
872 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
873 tok::greatergreater, tok::ellipsis)) {
874 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
875 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
876 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
878 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
884 // Parse the ellipsis, if given.
885 SourceLocation EllipsisLoc;
886 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
888 getLangOpts().CPlusPlus11
889 ? diag::warn_cxx98_compat_variadic_templates
890 : diag::ext_variadic_templates);
892 // Get the identifier, if given.
893 SourceLocation NameLoc = Tok.getLocation();
894 IdentifierInfo *ParamName = nullptr;
895 if (Tok.is(tok::identifier)) {
896 ParamName = Tok.getIdentifierInfo();
898 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
899 tok::greatergreater)) {
900 // Unnamed template parameter. Don't have to do anything here, just
901 // don't consume this token.
903 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
907 // Recover from misplaced ellipsis.
908 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
909 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
910 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
912 TemplateParameterList *ParamList =
913 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
914 TemplateLoc, LAngleLoc,
918 // Grab a default argument (if available).
919 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
920 // we introduce the template parameter into the local scope.
921 SourceLocation EqualLoc;
922 ParsedTemplateArgument DefaultArg;
923 if (TryConsumeToken(tok::equal, EqualLoc)) {
924 DefaultArg = ParseTemplateTemplateArgument();
925 if (DefaultArg.isInvalid()) {
926 Diag(Tok.getLocation(),
927 diag::err_default_template_template_parameter_not_template);
928 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
929 StopAtSemi | StopBeforeMatch);
933 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
934 ParamList, EllipsisLoc,
935 ParamName, NameLoc, Depth,
936 Position, EqualLoc, DefaultArg);
939 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
940 /// template parameters (e.g., in "template<int Size> class array;").
942 /// template-parameter:
944 /// parameter-declaration
946 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
947 // Parse the declaration-specifiers (i.e., the type).
948 // FIXME: The type should probably be restricted in some way... Not all
949 // declarators (parts of declarators?) are accepted for parameters.
950 DeclSpec DS(AttrFactory);
951 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
952 DeclSpecContext::DSC_template_param);
954 // Parse this as a typename.
955 Declarator ParamDecl(DS, DeclaratorContext::TemplateParamContext);
956 ParseDeclarator(ParamDecl);
957 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
958 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
962 // Recover from misplaced ellipsis.
963 SourceLocation EllipsisLoc;
964 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
965 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
967 // If there is a default value, parse it.
968 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
969 // we introduce the template parameter into the local scope.
970 SourceLocation EqualLoc;
971 ExprResult DefaultArg;
972 if (TryConsumeToken(tok::equal, EqualLoc)) {
973 // C++ [temp.param]p15:
974 // When parsing a default template-argument for a non-type
975 // template-parameter, the first non-nested > is taken as the
976 // end of the template-parameter-list rather than a greater-than
978 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
979 EnterExpressionEvaluationContext ConstantEvaluated(
980 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
982 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
983 if (DefaultArg.isInvalid())
984 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
987 // Create the parameter.
988 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
989 Depth, Position, EqualLoc,
993 void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
994 SourceLocation CorrectLoc,
995 bool AlreadyHasEllipsis,
996 bool IdentifierHasName) {
998 if (!AlreadyHasEllipsis)
999 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
1000 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
1001 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
1002 << !IdentifierHasName;
1005 void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
1007 assert(EllipsisLoc.isValid());
1008 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
1009 if (!AlreadyHasEllipsis)
1010 D.setEllipsisLoc(EllipsisLoc);
1011 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
1012 AlreadyHasEllipsis, D.hasName());
1015 /// Parses a '>' at the end of a template list.
1017 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
1018 /// to determine if these tokens were supposed to be a '>' followed by
1019 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
1021 /// \param RAngleLoc the location of the consumed '>'.
1023 /// \param ConsumeLastToken if true, the '>' is consumed.
1025 /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
1026 /// type parameter or type argument list, rather than a C++ template parameter
1027 /// or argument list.
1029 /// \returns true, if current token does not start with '>', false otherwise.
1030 bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
1031 bool ConsumeLastToken,
1032 bool ObjCGenericList) {
1033 // What will be left once we've consumed the '>'.
1034 tok::TokenKind RemainingToken;
1035 const char *ReplacementStr = "> >";
1036 bool MergeWithNextToken = false;
1038 switch (Tok.getKind()) {
1040 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
1044 // Determine the location of the '>' token. Only consume this token
1045 // if the caller asked us to.
1046 RAngleLoc = Tok.getLocation();
1047 if (ConsumeLastToken)
1051 case tok::greatergreater:
1052 RemainingToken = tok::greater;
1055 case tok::greatergreatergreater:
1056 RemainingToken = tok::greatergreater;
1059 case tok::greaterequal:
1060 RemainingToken = tok::equal;
1061 ReplacementStr = "> =";
1063 // Join two adjacent '=' tokens into one, for cases like:
1064 // void (*p)() = f<int>;
1065 // return f<int>==p;
1066 if (NextToken().is(tok::equal) &&
1067 areTokensAdjacent(Tok, NextToken())) {
1068 RemainingToken = tok::equalequal;
1069 MergeWithNextToken = true;
1073 case tok::greatergreaterequal:
1074 RemainingToken = tok::greaterequal;
1078 // This template-id is terminated by a token that starts with a '>'.
1079 // Outside C++11 and Objective-C, this is now error recovery.
1081 // C++11 allows this when the token is '>>', and in CUDA + C++11 mode, we
1082 // extend that treatment to also apply to the '>>>' token.
1084 // Objective-C allows this in its type parameter / argument lists.
1086 SourceLocation TokBeforeGreaterLoc = PrevTokLocation;
1087 SourceLocation TokLoc = Tok.getLocation();
1088 Token Next = NextToken();
1090 // Whether splitting the current token after the '>' would undesirably result
1091 // in the remaining token pasting with the token after it. This excludes the
1092 // MergeWithNextToken cases, which we've already handled.
1093 bool PreventMergeWithNextToken =
1094 (RemainingToken == tok::greater ||
1095 RemainingToken == tok::greatergreater) &&
1096 (Next.isOneOf(tok::greater, tok::greatergreater,
1097 tok::greatergreatergreater, tok::equal, tok::greaterequal,
1098 tok::greatergreaterequal, tok::equalequal)) &&
1099 areTokensAdjacent(Tok, Next);
1101 // Diagnose this situation as appropriate.
1102 if (!ObjCGenericList) {
1103 // The source range of the replaced token(s).
1104 CharSourceRange ReplacementRange = CharSourceRange::getCharRange(
1105 TokLoc, Lexer::AdvanceToTokenCharacter(TokLoc, 2, PP.getSourceManager(),
1108 // A hint to put a space between the '>>'s. In order to make the hint as
1109 // clear as possible, we include the characters either side of the space in
1110 // the replacement, rather than just inserting a space at SecondCharLoc.
1111 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
1114 // A hint to put another space after the token, if it would otherwise be
1115 // lexed differently.
1117 if (PreventMergeWithNextToken)
1118 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
1120 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
1121 if (getLangOpts().CPlusPlus11 &&
1122 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
1123 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
1124 else if (Tok.is(tok::greaterequal))
1125 DiagId = diag::err_right_angle_bracket_equal_needs_space;
1126 Diag(TokLoc, DiagId) << Hint1 << Hint2;
1129 // Find the "length" of the resulting '>' token. This is not always 1, as it
1130 // can contain escaped newlines.
1131 unsigned GreaterLength = Lexer::getTokenPrefixLength(
1132 TokLoc, 1, PP.getSourceManager(), getLangOpts());
1134 // Annotate the source buffer to indicate that we split the token after the
1135 // '>'. This allows us to properly find the end of, and extract the spelling
1136 // of, the '>' token later.
1137 RAngleLoc = PP.SplitToken(TokLoc, GreaterLength);
1139 // Strip the initial '>' from the token.
1140 bool CachingTokens = PP.IsPreviousCachedToken(Tok);
1142 Token Greater = Tok;
1143 Greater.setLocation(RAngleLoc);
1144 Greater.setKind(tok::greater);
1145 Greater.setLength(GreaterLength);
1147 unsigned OldLength = Tok.getLength();
1148 if (MergeWithNextToken) {
1150 OldLength += Tok.getLength();
1153 Tok.setKind(RemainingToken);
1154 Tok.setLength(OldLength - GreaterLength);
1156 // Split the second token if lexing it normally would lex a different token
1157 // (eg, the fifth token in 'A<B>>>' should re-lex as '>', not '>>').
1158 SourceLocation AfterGreaterLoc = TokLoc.getLocWithOffset(GreaterLength);
1159 if (PreventMergeWithNextToken)
1160 AfterGreaterLoc = PP.SplitToken(AfterGreaterLoc, Tok.getLength());
1161 Tok.setLocation(AfterGreaterLoc);
1163 // Update the token cache to match what we just did if necessary.
1164 if (CachingTokens) {
1165 // If the previous cached token is being merged, delete it.
1166 if (MergeWithNextToken)
1167 PP.ReplacePreviousCachedToken({});
1169 if (ConsumeLastToken)
1170 PP.ReplacePreviousCachedToken({Greater, Tok});
1172 PP.ReplacePreviousCachedToken({Greater});
1175 if (ConsumeLastToken) {
1176 PrevTokLocation = RAngleLoc;
1178 PrevTokLocation = TokBeforeGreaterLoc;
1179 PP.EnterToken(Tok, /*IsReinject=*/true);
1187 /// Parses a template-id that after the template name has
1188 /// already been parsed.
1190 /// This routine takes care of parsing the enclosed template argument
1191 /// list ('<' template-parameter-list [opt] '>') and placing the
1192 /// results into a form that can be transferred to semantic analysis.
1194 /// \param ConsumeLastToken if true, then we will consume the last
1195 /// token that forms the template-id. Otherwise, we will leave the
1196 /// last token in the stream (e.g., so that it can be replaced with an
1197 /// annotation token).
1199 Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
1200 SourceLocation &LAngleLoc,
1201 TemplateArgList &TemplateArgs,
1202 SourceLocation &RAngleLoc) {
1203 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
1206 LAngleLoc = ConsumeToken();
1208 // Parse the optional template-argument-list.
1209 bool Invalid = false;
1211 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
1212 if (!Tok.isOneOf(tok::greater, tok::greatergreater,
1213 tok::greatergreatergreater, tok::greaterequal,
1214 tok::greatergreaterequal))
1215 Invalid = ParseTemplateArgumentList(TemplateArgs);
1218 // Try to find the closing '>'.
1219 if (ConsumeLastToken)
1220 SkipUntil(tok::greater, StopAtSemi);
1222 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
1227 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
1228 /*ObjCGenericList=*/false);
1231 /// Replace the tokens that form a simple-template-id with an
1232 /// annotation token containing the complete template-id.
1234 /// The first token in the stream must be the name of a template that
1235 /// is followed by a '<'. This routine will parse the complete
1236 /// simple-template-id and replace the tokens with a single annotation
1237 /// token with one of two different kinds: if the template-id names a
1238 /// type (and \p AllowTypeAnnotation is true), the annotation token is
1239 /// a type annotation that includes the optional nested-name-specifier
1240 /// (\p SS). Otherwise, the annotation token is a template-id
1241 /// annotation that does not include the optional
1242 /// nested-name-specifier.
1244 /// \param Template the declaration of the template named by the first
1245 /// token (an identifier), as returned from \c Action::isTemplateName().
1247 /// \param TNK the kind of template that \p Template
1248 /// refers to, as returned from \c Action::isTemplateName().
1250 /// \param SS if non-NULL, the nested-name-specifier that precedes
1251 /// this template name.
1253 /// \param TemplateKWLoc if valid, specifies that this template-id
1254 /// annotation was preceded by the 'template' keyword and gives the
1255 /// location of that keyword. If invalid (the default), then this
1256 /// template-id was not preceded by a 'template' keyword.
1258 /// \param AllowTypeAnnotation if true (the default), then a
1259 /// simple-template-id that refers to a class template, template
1260 /// template parameter, or other template that produces a type will be
1261 /// replaced with a type annotation token. Otherwise, the
1262 /// simple-template-id is always replaced with a template-id
1263 /// annotation token.
1265 /// \param TypeConstraint if true, then this is actually a type-constraint,
1266 /// meaning that the template argument list can be omitted (and the template in
1267 /// question must be a concept).
1269 /// If an unrecoverable parse error occurs and no annotation token can be
1270 /// formed, this function returns true.
1272 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
1274 SourceLocation TemplateKWLoc,
1275 UnqualifiedId &TemplateName,
1276 bool AllowTypeAnnotation,
1277 bool TypeConstraint) {
1278 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
1279 assert(Template && (Tok.is(tok::less) || TypeConstraint) &&
1280 "Parser isn't at the beginning of a template-id");
1281 assert(!(TypeConstraint && AllowTypeAnnotation) && "type-constraint can't be "
1282 "a type annotation");
1283 assert((!TypeConstraint || TNK == TNK_Concept_template) && "type-constraint "
1284 "must accompany a concept name");
1286 // Consume the template-name.
1287 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
1289 // Parse the enclosed template argument list.
1290 SourceLocation LAngleLoc, RAngleLoc;
1291 TemplateArgList TemplateArgs;
1292 if (!TypeConstraint || Tok.is(tok::less)) {
1293 bool Invalid = ParseTemplateIdAfterTemplateName(false, LAngleLoc,
1298 // If we failed to parse the template ID but skipped ahead to a >, we're not
1299 // going to be able to form a token annotation. Eat the '>' if present.
1300 TryConsumeToken(tok::greater);
1301 // FIXME: Annotate the token stream so we don't produce the same errors
1302 // again if we're doing this annotation as part of a tentative parse.
1307 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1309 // Build the annotation token.
1310 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
1311 TypeResult Type = Actions.ActOnTemplateIdType(
1312 getCurScope(), SS, TemplateKWLoc, Template, TemplateName.Identifier,
1313 TemplateNameLoc, LAngleLoc, TemplateArgsPtr, RAngleLoc);
1314 if (Type.isInvalid()) {
1315 // If we failed to parse the template ID but skipped ahead to a >, we're
1316 // not going to be able to form a token annotation. Eat the '>' if
1318 TryConsumeToken(tok::greater);
1319 // FIXME: Annotate the token stream so we don't produce the same errors
1320 // again if we're doing this annotation as part of a tentative parse.
1324 Tok.setKind(tok::annot_typename);
1325 setTypeAnnotation(Tok, Type.get());
1326 if (SS.isNotEmpty())
1327 Tok.setLocation(SS.getBeginLoc());
1328 else if (TemplateKWLoc.isValid())
1329 Tok.setLocation(TemplateKWLoc);
1331 Tok.setLocation(TemplateNameLoc);
1333 // Build a template-id annotation token that can be processed
1335 Tok.setKind(tok::annot_template_id);
1337 IdentifierInfo *TemplateII =
1338 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1339 ? TemplateName.Identifier
1342 OverloadedOperatorKind OpKind =
1343 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1345 : TemplateName.OperatorFunctionId.Operator;
1347 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
1348 TemplateKWLoc, TemplateNameLoc, TemplateII, OpKind, Template, TNK,
1349 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
1351 Tok.setAnnotationValue(TemplateId);
1352 if (TemplateKWLoc.isValid())
1353 Tok.setLocation(TemplateKWLoc);
1355 Tok.setLocation(TemplateNameLoc);
1358 // Common fields for the annotation token
1359 Tok.setAnnotationEndLoc(RAngleLoc);
1361 // In case the tokens were cached, have Preprocessor replace them with the
1362 // annotation token.
1363 PP.AnnotateCachedTokens(Tok);
1367 /// Replaces a template-id annotation token with a type
1368 /// annotation token.
1370 /// If there was a failure when forming the type from the template-id,
1371 /// a type annotation token will still be created, but will have a
1372 /// NULL type pointer to signify an error.
1374 /// \param SS The scope specifier appearing before the template-id, if any.
1376 /// \param IsClassName Is this template-id appearing in a context where we
1377 /// know it names a class, such as in an elaborated-type-specifier or
1378 /// base-specifier? ('typename' and 'template' are unneeded and disallowed
1379 /// in those contexts.)
1380 void Parser::AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS,
1382 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1384 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1385 assert((TemplateId->Kind == TNK_Type_template ||
1386 TemplateId->Kind == TNK_Dependent_template_name ||
1387 TemplateId->Kind == TNK_Undeclared_template) &&
1388 "Only works for type and dependent templates");
1390 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1391 TemplateId->NumArgs);
1394 = Actions.ActOnTemplateIdType(getCurScope(),
1396 TemplateId->TemplateKWLoc,
1397 TemplateId->Template,
1399 TemplateId->TemplateNameLoc,
1400 TemplateId->LAngleLoc,
1402 TemplateId->RAngleLoc,
1403 /*IsCtorOrDtorName*/false,
1405 // Create the new "type" annotation token.
1406 Tok.setKind(tok::annot_typename);
1407 setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
1408 if (SS.isNotEmpty()) // it was a C++ qualified type name.
1409 Tok.setLocation(SS.getBeginLoc());
1410 // End location stays the same
1412 // Replace the template-id annotation token, and possible the scope-specifier
1413 // that precedes it, with the typename annotation token.
1414 PP.AnnotateCachedTokens(Tok);
1417 /// Determine whether the given token can end a template argument.
1418 static bool isEndOfTemplateArgument(Token Tok) {
1419 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
1422 /// Parse a C++ template template argument.
1423 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1424 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1425 !Tok.is(tok::annot_cxxscope))
1426 return ParsedTemplateArgument();
1428 // C++0x [temp.arg.template]p1:
1429 // A template-argument for a template template-parameter shall be the name
1430 // of a class template or an alias template, expressed as id-expression.
1432 // We parse an id-expression that refers to a class template or alias
1433 // template. The grammar we parse is:
1435 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1437 // followed by a token that terminates a template argument, such as ',',
1438 // '>', or (in some cases) '>>'.
1439 CXXScopeSpec SS; // nested-name-specifier, if present
1440 ParseOptionalCXXScopeSpecifier(SS, nullptr,
1441 /*EnteringContext=*/false);
1443 ParsedTemplateArgument Result;
1444 SourceLocation EllipsisLoc;
1445 if (SS.isSet() && Tok.is(tok::kw_template)) {
1446 // Parse the optional 'template' keyword following the
1447 // nested-name-specifier.
1448 SourceLocation TemplateKWLoc = ConsumeToken();
1450 if (Tok.is(tok::identifier)) {
1451 // We appear to have a dependent template name.
1453 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1454 ConsumeToken(); // the identifier
1456 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1458 // If the next token signals the end of a template argument,
1459 // then we have a dependent template name that could be a template
1460 // template argument.
1461 TemplateTy Template;
1462 if (isEndOfTemplateArgument(Tok) &&
1463 Actions.ActOnDependentTemplateName(
1464 getCurScope(), SS, TemplateKWLoc, Name,
1465 /*ObjectType=*/nullptr,
1466 /*EnteringContext=*/false, Template))
1467 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1469 } else if (Tok.is(tok::identifier)) {
1470 // We may have a (non-dependent) template name.
1471 TemplateTy Template;
1473 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1474 ConsumeToken(); // the identifier
1476 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1478 if (isEndOfTemplateArgument(Tok)) {
1479 bool MemberOfUnknownSpecialization;
1480 TemplateNameKind TNK = Actions.isTemplateName(
1482 /*hasTemplateKeyword=*/false, Name,
1483 /*ObjectType=*/nullptr,
1484 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
1485 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1486 // We have an id-expression that refers to a class template or
1487 // (C++0x) alias template.
1488 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1493 // If this is a pack expansion, build it as such.
1494 if (EllipsisLoc.isValid() && !Result.isInvalid())
1495 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1500 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1502 /// template-argument: [C++ 14.2]
1503 /// constant-expression
1506 ParsedTemplateArgument Parser::ParseTemplateArgument() {
1507 // C++ [temp.arg]p2:
1508 // In a template-argument, an ambiguity between a type-id and an
1509 // expression is resolved to a type-id, regardless of the form of
1510 // the corresponding template-parameter.
1512 // Therefore, we initially try to parse a type-id - and isCXXTypeId might look
1513 // up and annotate an identifier as an id-expression during disambiguation,
1514 // so enter the appropriate context for a constant expression template
1515 // argument before trying to disambiguate.
1517 EnterExpressionEvaluationContext EnterConstantEvaluated(
1518 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated,
1519 /*LambdaContextDecl=*/nullptr,
1520 /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
1521 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1522 TypeResult TypeArg = ParseTypeName(
1523 /*Range=*/nullptr, DeclaratorContext::TemplateArgContext);
1524 return Actions.ActOnTemplateTypeArgument(TypeArg);
1527 // Try to parse a template template argument.
1529 TentativeParsingAction TPA(*this);
1531 ParsedTemplateArgument TemplateTemplateArgument
1532 = ParseTemplateTemplateArgument();
1533 if (!TemplateTemplateArgument.isInvalid()) {
1535 return TemplateTemplateArgument;
1538 // Revert this tentative parse to parse a non-type template argument.
1542 // Parse a non-type template argument.
1543 SourceLocation Loc = Tok.getLocation();
1544 ExprResult ExprArg = ParseConstantExpressionInExprEvalContext(MaybeTypeCast);
1545 if (ExprArg.isInvalid() || !ExprArg.get()) {
1546 return ParsedTemplateArgument();
1549 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1550 ExprArg.get(), Loc);
1553 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1554 /// (C++ [temp.names]). Returns true if there was an error.
1556 /// template-argument-list: [C++ 14.2]
1557 /// template-argument
1558 /// template-argument-list ',' template-argument
1560 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1562 ColonProtectionRAIIObject ColonProtection(*this, false);
1565 ParsedTemplateArgument Arg = ParseTemplateArgument();
1566 SourceLocation EllipsisLoc;
1567 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1568 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1570 if (Arg.isInvalid()) {
1571 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
1575 // Save this template argument.
1576 TemplateArgs.push_back(Arg);
1578 // If the next token is a comma, consume it and keep reading
1580 } while (TryConsumeToken(tok::comma));
1585 /// Parse a C++ explicit template instantiation
1586 /// (C++ [temp.explicit]).
1588 /// explicit-instantiation:
1589 /// 'extern' [opt] 'template' declaration
1591 /// Note that the 'extern' is a GNU extension and C++11 feature.
1592 Decl *Parser::ParseExplicitInstantiation(DeclaratorContext Context,
1593 SourceLocation ExternLoc,
1594 SourceLocation TemplateLoc,
1595 SourceLocation &DeclEnd,
1596 ParsedAttributes &AccessAttrs,
1597 AccessSpecifier AS) {
1598 // This isn't really required here.
1599 ParsingDeclRAIIObject
1600 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1602 return ParseSingleDeclarationAfterTemplate(
1603 Context, ParsedTemplateInfo(ExternLoc, TemplateLoc),
1604 ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
1607 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1609 return getTemplateParamsRange(TemplateParams->data(),
1610 TemplateParams->size());
1612 SourceRange R(TemplateLoc);
1613 if (ExternLoc.isValid())
1614 R.setBegin(ExternLoc);
1618 void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1619 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1622 /// Late parse a C++ function template in Microsoft mode.
1623 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1627 // Get the FunctionDecl.
1628 FunctionDecl *FunD = LPT.D->getAsFunction();
1629 // Track template parameter depth.
1630 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1632 // To restore the context after late parsing.
1633 Sema::ContextRAII GlobalSavedContext(
1634 Actions, Actions.Context.getTranslationUnitDecl());
1636 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1638 // Get the list of DeclContexts to reenter. For inline methods, we only want
1639 // to push the DeclContext of the outermost class. This matches the way the
1640 // parser normally parses bodies of inline methods when the outermost class is
1642 struct ContainingDC {
1643 ContainingDC(DeclContext *DC, bool ShouldPush) : Pair(DC, ShouldPush) {}
1644 llvm::PointerIntPair<DeclContext *, 1, bool> Pair;
1645 DeclContext *getDC() { return Pair.getPointer(); }
1646 bool shouldPushDC() { return Pair.getInt(); }
1648 SmallVector<ContainingDC, 4> DeclContextsToReenter;
1649 DeclContext *DD = FunD;
1650 DeclContext *NextContaining = Actions.getContainingDC(DD);
1651 while (DD && !DD->isTranslationUnit()) {
1652 bool ShouldPush = DD == NextContaining;
1653 DeclContextsToReenter.push_back({DD, ShouldPush});
1655 NextContaining = Actions.getContainingDC(DD);
1656 DD = DD->getLexicalParent();
1659 // Reenter template scopes from outermost to innermost.
1660 for (ContainingDC CDC : reverse(DeclContextsToReenter)) {
1661 TemplateParamScopeStack.push_back(
1662 new ParseScope(this, Scope::TemplateParamScope));
1663 unsigned NumParamLists = Actions.ActOnReenterTemplateScope(
1664 getCurScope(), cast<Decl>(CDC.getDC()));
1665 CurTemplateDepthTracker.addDepth(NumParamLists);
1666 if (CDC.shouldPushDC()) {
1667 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1668 Actions.PushDeclContext(Actions.getCurScope(), CDC.getDC());
1672 assert(!LPT.Toks.empty() && "Empty body!");
1674 // Append the current token at the end of the new token stream so that it
1675 // doesn't get lost.
1676 LPT.Toks.push_back(Tok);
1677 PP.EnterTokenStream(LPT.Toks, true, /*IsReinject*/true);
1679 // Consume the previously pushed token.
1680 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1681 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1682 "Inline method not starting with '{', ':' or 'try'");
1684 // Parse the method body. Function body parsing code is similar enough
1685 // to be re-used for method bodies as well.
1686 ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
1687 Scope::CompoundStmtScope);
1689 // Recreate the containing function DeclContext.
1690 Sema::ContextRAII FunctionSavedContext(Actions,
1691 Actions.getContainingDC(FunD));
1693 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1695 if (Tok.is(tok::kw_try)) {
1696 ParseFunctionTryBlock(LPT.D, FnScope);
1698 if (Tok.is(tok::colon))
1699 ParseConstructorInitializer(LPT.D);
1701 Actions.ActOnDefaultCtorInitializers(LPT.D);
1703 if (Tok.is(tok::l_brace)) {
1704 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1705 cast<FunctionTemplateDecl>(LPT.D)
1706 ->getTemplateParameters()
1707 ->getDepth() == TemplateParameterDepth - 1) &&
1708 "TemplateParameterDepth should be greater than the depth of "
1709 "current template being instantiated!");
1710 ParseFunctionStatementBody(LPT.D, FnScope);
1711 Actions.UnmarkAsLateParsedTemplate(FunD);
1713 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1718 SmallVectorImpl<ParseScope *>::reverse_iterator I =
1719 TemplateParamScopeStack.rbegin();
1720 for (; I != TemplateParamScopeStack.rend(); ++I)
1724 /// Lex a delayed template function for late parsing.
1725 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1726 tok::TokenKind kind = Tok.getKind();
1727 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1728 // Consume everything up to (and including) the matching right brace.
1729 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1732 // If we're in a function-try-block, we need to store all the catch blocks.
1733 if (kind == tok::kw_try) {
1734 while (Tok.is(tok::kw_catch)) {
1735 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1736 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1741 /// We've parsed something that could plausibly be intended to be a template
1742 /// name (\p LHS) followed by a '<' token, and the following code can't possibly
1743 /// be an expression. Determine if this is likely to be a template-id and if so,
1745 bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
1746 TentativeParsingAction TPA(*this);
1747 // FIXME: We could look at the token sequence in a lot more detail here.
1748 if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater,
1749 StopAtSemi | StopBeforeMatch)) {
1752 SourceLocation Greater;
1753 ParseGreaterThanInTemplateList(Greater, true, false);
1754 Actions.diagnoseExprIntendedAsTemplateName(getCurScope(), LHS,
1759 // There's no matching '>' token, this probably isn't supposed to be
1760 // interpreted as a template-id. Parse it as an (ill-formed) comparison.
1765 void Parser::checkPotentialAngleBracket(ExprResult &PotentialTemplateName) {
1766 assert(Tok.is(tok::less) && "not at a potential angle bracket");
1768 bool DependentTemplateName = false;
1769 if (!Actions.mightBeIntendedToBeTemplateName(PotentialTemplateName,
1770 DependentTemplateName))
1773 // OK, this might be a name that the user intended to be parsed as a
1774 // template-name, followed by a '<' token. Check for some easy cases.
1776 // If we have potential_template<>, then it's supposed to be a template-name.
1777 if (NextToken().is(tok::greater) ||
1778 (getLangOpts().CPlusPlus11 &&
1779 NextToken().isOneOf(tok::greatergreater, tok::greatergreatergreater))) {
1780 SourceLocation Less = ConsumeToken();
1781 SourceLocation Greater;
1782 ParseGreaterThanInTemplateList(Greater, true, false);
1783 Actions.diagnoseExprIntendedAsTemplateName(
1784 getCurScope(), PotentialTemplateName, Less, Greater);
1785 // FIXME: Perform error recovery.
1786 PotentialTemplateName = ExprError();
1790 // If we have 'potential_template<type-id', assume it's supposed to be a
1791 // template-name if there's a matching '>' later on.
1793 // FIXME: Avoid the tentative parse when NextToken() can't begin a type.
1794 TentativeParsingAction TPA(*this);
1795 SourceLocation Less = ConsumeToken();
1796 if (isTypeIdUnambiguously() &&
1797 diagnoseUnknownTemplateId(PotentialTemplateName, Less)) {
1799 // FIXME: Perform error recovery.
1800 PotentialTemplateName = ExprError();
1806 // Otherwise, remember that we saw this in case we see a potentially-matching
1807 // '>' token later on.
1808 AngleBracketTracker::Priority Priority =
1809 (DependentTemplateName ? AngleBracketTracker::DependentName
1810 : AngleBracketTracker::PotentialTypo) |
1811 (Tok.hasLeadingSpace() ? AngleBracketTracker::SpaceBeforeLess
1812 : AngleBracketTracker::NoSpaceBeforeLess);
1813 AngleBrackets.add(*this, PotentialTemplateName.get(), Tok.getLocation(),
1817 bool Parser::checkPotentialAngleBracketDelimiter(
1818 const AngleBracketTracker::Loc &LAngle, const Token &OpToken) {
1819 // If a comma in an expression context is followed by a type that can be a
1820 // template argument and cannot be an expression, then this is ill-formed,
1821 // but might be intended to be part of a template-id.
1822 if (OpToken.is(tok::comma) && isTypeIdUnambiguously() &&
1823 diagnoseUnknownTemplateId(LAngle.TemplateName, LAngle.LessLoc)) {
1824 AngleBrackets.clear(*this);
1828 // If a context that looks like a template-id is followed by '()', then
1829 // this is ill-formed, but might be intended to be a template-id
1830 // followed by '()'.
1831 if (OpToken.is(tok::greater) && Tok.is(tok::l_paren) &&
1832 NextToken().is(tok::r_paren)) {
1833 Actions.diagnoseExprIntendedAsTemplateName(
1834 getCurScope(), LAngle.TemplateName, LAngle.LessLoc,
1835 OpToken.getLocation());
1836 AngleBrackets.clear(*this);
1840 // After a '>' (etc), we're no longer potentially in a construct that's
1841 // intended to be treated as a template-id.
1842 if (OpToken.is(tok::greater) ||
1843 (getLangOpts().CPlusPlus11 &&
1844 OpToken.isOneOf(tok::greatergreater, tok::greatergreatergreater)))
1845 AngleBrackets.clear(*this);