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 ParseDeclarator(DeclaratorInfo);
244 // Error parsing the declarator?
245 if (!DeclaratorInfo.hasName()) {
246 // If so, skip until the semi-colon or a }.
247 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
248 if (Tok.is(tok::semi))
253 llvm::TimeTraceScope TimeScope("ParseTemplate", [&]() {
254 return DeclaratorInfo.getIdentifier() != nullptr
255 ? DeclaratorInfo.getIdentifier()->getName()
259 LateParsedAttrList LateParsedAttrs(true);
260 if (DeclaratorInfo.isFunctionDeclarator()) {
261 if (Tok.is(tok::kw_requires))
262 ParseTrailingRequiresClause(DeclaratorInfo);
264 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
267 if (DeclaratorInfo.isFunctionDeclarator() &&
268 isStartOfFunctionDefinition(DeclaratorInfo)) {
270 // Function definitions are only allowed at file scope and in C++ classes.
271 // The C++ inline method definition case is handled elsewhere, so we only
272 // need to handle the file scope definition case.
273 if (Context != DeclaratorContext::FileContext) {
274 Diag(Tok, diag::err_function_definition_not_allowed);
279 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
280 // Recover by ignoring the 'typedef'. This was probably supposed to be
281 // the 'typename' keyword, which we should have already suggested adding
282 // if it's appropriate.
283 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
284 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
285 DS.ClearStorageClassSpecs();
288 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
289 if (DeclaratorInfo.getName().getKind() !=
290 UnqualifiedIdKind::IK_TemplateId) {
291 // If the declarator-id is not a template-id, issue a diagnostic and
292 // recover by ignoring the 'template' keyword.
293 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
294 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
297 SourceLocation LAngleLoc
298 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
299 Diag(DeclaratorInfo.getIdentifierLoc(),
300 diag::err_explicit_instantiation_with_definition)
301 << SourceRange(TemplateInfo.TemplateLoc)
302 << FixItHint::CreateInsertion(LAngleLoc, "<>");
304 // Recover as if it were an explicit specialization.
305 TemplateParameterLists FakedParamLists;
306 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
307 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
308 LAngleLoc, nullptr));
310 return ParseFunctionDefinition(
311 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
312 /*isSpecialization=*/true,
313 /*lastParameterListWasEmpty=*/true),
317 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
321 // Parse this declaration.
322 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
325 if (Tok.is(tok::comma)) {
326 Diag(Tok, diag::err_multiple_template_declarators)
327 << (int)TemplateInfo.Kind;
328 SkipUntil(tok::semi);
332 // Eat the semi colon after the declaration.
333 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
334 if (LateParsedAttrs.size() > 0)
335 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
336 DeclaratorInfo.complete(ThisDecl);
340 /// \brief Parse a single declaration that declares a concept.
342 /// \param DeclEnd will receive the source location of the last token
343 /// within this declaration.
345 /// \returns the new declaration.
347 Parser::ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
348 SourceLocation &DeclEnd) {
349 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
350 "Template information required");
351 assert(Tok.is(tok::kw_concept) &&
352 "ParseConceptDefinition must be called when at a 'concept' keyword");
354 ConsumeToken(); // Consume 'concept'
356 SourceLocation BoolKWLoc;
357 if (TryConsumeToken(tok::kw_bool, BoolKWLoc))
358 Diag(Tok.getLocation(), diag::ext_concept_legacy_bool_keyword) <<
359 FixItHint::CreateRemoval(SourceLocation(BoolKWLoc));
361 DiagnoseAndSkipCXX11Attributes();
364 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
365 /*EnteringContext=*/false, /*MayBePseudoDestructor=*/nullptr,
366 /*IsTypename=*/false, /*LastII=*/nullptr, /*OnlyNamespace=*/true) ||
368 SkipUntil(tok::semi);
373 Diag(SS.getBeginLoc(),
374 diag::err_concept_definition_not_identifier);
376 UnqualifiedId Result;
377 if (ParseUnqualifiedId(SS, /*EnteringContext=*/false,
378 /*AllowDestructorName=*/false,
379 /*AllowConstructorName=*/false,
380 /*AllowDeductionGuide=*/false,
381 /*ObjectType=*/ParsedType(), /*TemplateKWLoc=*/nullptr,
383 SkipUntil(tok::semi);
387 if (Result.getKind() != UnqualifiedIdKind::IK_Identifier) {
388 Diag(Result.getBeginLoc(), diag::err_concept_definition_not_identifier);
389 SkipUntil(tok::semi);
393 IdentifierInfo *Id = Result.Identifier;
394 SourceLocation IdLoc = Result.getBeginLoc();
396 DiagnoseAndSkipCXX11Attributes();
398 if (!TryConsumeToken(tok::equal)) {
399 Diag(Tok.getLocation(), diag::err_expected) << tok::equal;
400 SkipUntil(tok::semi);
404 ExprResult ConstraintExprResult =
405 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
406 if (ConstraintExprResult.isInvalid()) {
407 SkipUntil(tok::semi);
411 DeclEnd = Tok.getLocation();
412 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
413 Expr *ConstraintExpr = ConstraintExprResult.get();
414 return Actions.ActOnConceptDefinition(getCurScope(),
415 *TemplateInfo.TemplateParams,
416 Id, IdLoc, ConstraintExpr);
419 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
420 /// angle brackets. Depth is the depth of this template-parameter-list, which
421 /// is the number of template headers directly enclosing this template header.
422 /// TemplateParams is the current list of template parameters we're building.
423 /// The template parameter we parse will be added to this list. LAngleLoc and
424 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
425 /// that enclose this template parameter list.
427 /// \returns true if an error occurred, false otherwise.
428 bool Parser::ParseTemplateParameters(
429 unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams,
430 SourceLocation &LAngleLoc, SourceLocation &RAngleLoc) {
431 // Get the template parameter list.
432 if (!TryConsumeToken(tok::less, LAngleLoc)) {
433 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
437 // Try to parse the template parameter list.
439 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
440 Failed = ParseTemplateParameterList(Depth, TemplateParams);
442 if (Tok.is(tok::greatergreater)) {
443 // No diagnostic required here: a template-parameter-list can only be
444 // followed by a declaration or, for a template template parameter, the
445 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
446 // This matters for elegant diagnosis of:
447 // template<template<typename>> struct S;
448 Tok.setKind(tok::greater);
449 RAngleLoc = Tok.getLocation();
450 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
451 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
452 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
458 /// ParseTemplateParameterList - Parse a template parameter list. If
459 /// the parsing fails badly (i.e., closing bracket was left out), this
460 /// will try to put the token stream in a reasonable position (closing
461 /// a statement, etc.) and return false.
463 /// template-parameter-list: [C++ temp]
464 /// template-parameter
465 /// template-parameter-list ',' template-parameter
467 Parser::ParseTemplateParameterList(const unsigned Depth,
468 SmallVectorImpl<NamedDecl*> &TemplateParams) {
471 if (NamedDecl *TmpParam
472 = ParseTemplateParameter(Depth, TemplateParams.size())) {
473 TemplateParams.push_back(TmpParam);
475 // If we failed to parse a template parameter, skip until we find
476 // a comma or closing brace.
477 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
478 StopAtSemi | StopBeforeMatch);
481 // Did we find a comma or the end of the template parameter list?
482 if (Tok.is(tok::comma)) {
484 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
485 // Don't consume this... that's done by template parser.
488 // Somebody probably forgot to close the template. Skip ahead and
489 // try to get out of the expression. This error is currently
490 // subsumed by whatever goes on in ParseTemplateParameter.
491 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
492 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
493 StopAtSemi | StopBeforeMatch);
500 /// Determine whether the parser is at the start of a template
502 /// \param ScopeError will receive true if there was an error parsing a
503 /// scope specifier at the current location.
504 bool Parser::isStartOfTemplateTypeParameter(bool &ScopeError) {
506 if (Tok.is(tok::kw_class)) {
507 // "class" may be the start of an elaborated-type-specifier or a
508 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
509 switch (NextToken().getKind()) {
513 case tok::greatergreater:
517 case tok::identifier:
518 // This may be either a type-parameter or an elaborated-type-specifier.
519 // We have to look further.
526 switch (GetLookAheadToken(2).getKind()) {
530 case tok::greatergreater:
538 bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope);
541 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
542 /*EnteringContext=*/false,
543 /*MayBePseudoDestructor=*/nullptr,
544 // If this is not a type-constraint, then
545 // this scope-spec is part of the typename
546 // of a non-type template parameter
547 /*IsTypename=*/true, /*LastII=*/nullptr,
548 // We won't find concepts in
549 // non-namespaces anyway, so might as well
550 // parse this correctly for possible type
552 /*OnlyNamespace=*/false);
555 if (TryAnnotateTypeConstraint(SS))
557 bool IsTypeConstraint = isTypeConstraintAnnotation();
558 if (!IsTypeConstraint && SS.isNotEmpty()) {
559 // This isn't a type-constraint but we've already parsed this scope
560 // specifier - annotate it.
561 AnnotateScopeToken(SS, /*isNewAnnotation=*/!WasScopeAnnotation);
565 if (IsTypeConstraint &&
566 // Next token might be 'auto' or 'decltype', indicating that this
567 // type-constraint is in fact part of a placeholder-type-specifier of a
568 // non-type template parameter.
569 !NextToken().isOneOf(tok::kw_auto, tok::kw_decltype))
572 // 'typedef' is a reasonably-common typo/thinko for 'typename', and is
573 // ill-formed otherwise.
574 if (Tok.isNot(tok::kw_typename) && Tok.isNot(tok::kw_typedef))
577 // C++ [temp.param]p2:
578 // There is no semantic difference between class and typename in a
579 // template-parameter. typename followed by an unqualified-id
580 // names a template type parameter. typename followed by a
581 // qualified-id denotes the type in a non-type
582 // parameter-declaration.
583 Token Next = NextToken();
585 // If we have an identifier, skip over it.
586 if (Next.getKind() == tok::identifier)
587 Next = GetLookAheadToken(2);
589 switch (Next.getKind()) {
593 case tok::greatergreater:
597 case tok::kw_typename:
598 case tok::kw_typedef:
600 // These indicate that a comma was missed after a type parameter, not that
601 // we have found a non-type parameter.
609 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
611 /// template-parameter: [C++ temp.param]
613 /// parameter-declaration
615 /// type-parameter: (See below)
616 /// type-parameter-key ...[opt] identifier[opt]
617 /// type-parameter-key identifier[opt] = type-id
618 /// (C++2a) type-constraint ...[opt] identifier[opt]
619 /// (C++2a) type-constraint identifier[opt] = type-id
620 /// 'template' '<' template-parameter-list '>' type-parameter-key
621 /// ...[opt] identifier[opt]
622 /// 'template' '<' template-parameter-list '>' type-parameter-key
623 /// identifier[opt] '=' id-expression
625 /// type-parameter-key:
629 NamedDecl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
630 // We could be facing a type-constraint, which (could) start a type parameter.
631 // Annotate it now (we might end up not using it if we determine this
632 // type-constraint is in fact part of a placeholder-type-specifier of a
633 // non-type template parameter.
636 if (isStartOfTemplateTypeParameter(ScopeError)) {
637 // Is there just a typo in the input code? ('typedef' instead of
639 if (Tok.is(tok::kw_typedef)) {
640 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
642 Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
643 << FixItHint::CreateReplacement(CharSourceRange::getCharRange(
648 Tok.setKind(tok::kw_typename);
651 return ParseTypeParameter(Depth, Position);
654 // We return an invalid parameter as opposed to null to avoid having bogus
655 // diagnostics about an empty template parameter list.
656 // FIXME: Fix ParseTemplateParameterList to better handle nullptr results
658 // Return a NTTP as if there was an error in a scope specifier, the user
659 // probably meant to write the type of a NTTP.
660 DeclSpec DS(getAttrFactory());
661 DS.SetTypeSpecError();
662 Declarator D(DS, DeclaratorContext::TemplateParamContext);
663 D.SetIdentifier(nullptr, Tok.getLocation());
664 D.setInvalidType(true);
665 NamedDecl *ErrorParam = Actions.ActOnNonTypeTemplateParameter(
666 getCurScope(), D, Depth, Position, /*EqualLoc=*/SourceLocation(),
667 /*DefaultArg=*/nullptr);
668 ErrorParam->setInvalidDecl(true);
669 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
670 StopAtSemi | StopBeforeMatch);
673 if (Tok.is(tok::kw_template))
674 return ParseTemplateTemplateParameter(Depth, Position);
676 // If it's none of the above, then it must be a parameter declaration.
677 // NOTE: This will pick up errors in the closure of the template parameter
678 // list (e.g., template < ; Check here to implement >> style closures.
679 return ParseNonTypeTemplateParameter(Depth, Position);
682 /// Check whether the current token is a template-id annotation denoting a
684 bool Parser::isTypeConstraintAnnotation() {
685 if (Tok.isNot(tok::annot_template_id))
687 const auto *ExistingAnnot =
688 static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
689 return ExistingAnnot->Kind == TNK_Concept_template;
692 /// Try parsing a type-constraint construct at the current location, after the
693 /// optional scope specifier.
696 /// nested-name-specifier[opt] concept-name
697 /// nested-name-specifier[opt] concept-name
698 /// '<' template-argument-list[opt] '>'[opt]
700 /// \returns true if an error occurred, and false otherwise.
701 bool Parser::TryAnnotateTypeConstraint(CXXScopeSpec &SS) {
702 if (!getLangOpts().ConceptsTS || Tok.isNot(tok::identifier))
705 UnqualifiedId PossibleConceptName;
706 PossibleConceptName.setIdentifier(Tok.getIdentifierInfo(),
709 TemplateTy PossibleConcept;
710 bool MemberOfUnknownSpecialization = false;
711 auto TNK = Actions.isTemplateName(getCurScope(), SS,
712 /*hasTemplateKeyword=*/false,
714 /*ObjectType=*/ParsedType(),
715 /*EnteringContext=*/false,
717 MemberOfUnknownSpecialization);
718 assert(!MemberOfUnknownSpecialization
719 && "Member when we only allowed namespace scope qualifiers??");
720 if (!PossibleConcept || TNK != TNK_Concept_template)
723 // At this point we're sure we're dealing with a constrained parameter. It
724 // may or may not have a template parameter list following the concept name.
725 return AnnotateTemplateIdToken(PossibleConcept, TNK, SS,
726 /*TemplateKWLoc=*/SourceLocation(),
728 /*AllowTypeAnnotation=*/false,
729 /*TypeConstraint=*/true);
732 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
733 /// Other kinds of template parameters are parsed in
734 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
736 /// type-parameter: [C++ temp.param]
737 /// 'class' ...[opt][C++0x] identifier[opt]
738 /// 'class' identifier[opt] '=' type-id
739 /// 'typename' ...[opt][C++0x] identifier[opt]
740 /// 'typename' identifier[opt] '=' type-id
741 NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
742 assert(Tok.isOneOf(tok::kw_class, tok::kw_typename, tok::annot_template_id) &&
743 "A type-parameter starts with 'class', 'typename' or a "
746 TemplateIdAnnotation *TypeConstraint = nullptr;
747 bool TypenameKeyword = false;
748 SourceLocation KeyLoc;
749 if (Tok.is(tok::annot_template_id)) {
750 // Consume the 'type-constraint'.
752 static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
753 assert(TypeConstraint->Kind == TNK_Concept_template &&
754 "stray non-concept template-id annotation");
755 KeyLoc = ConsumeAnnotationToken();
757 // Consume the 'class' or 'typename' keyword.
758 TypenameKeyword = Tok.is(tok::kw_typename);
759 KeyLoc = ConsumeToken();
762 // Grab the ellipsis (if given).
763 SourceLocation EllipsisLoc;
764 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
766 getLangOpts().CPlusPlus11
767 ? diag::warn_cxx98_compat_variadic_templates
768 : diag::ext_variadic_templates);
771 // Grab the template parameter name (if given)
772 SourceLocation NameLoc = Tok.getLocation();
773 IdentifierInfo *ParamName = nullptr;
774 if (Tok.is(tok::identifier)) {
775 ParamName = Tok.getIdentifierInfo();
777 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
778 tok::greatergreater)) {
779 // Unnamed template parameter. Don't have to do anything here, just
780 // don't consume this token.
782 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
786 // Recover from misplaced ellipsis.
787 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
788 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
789 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
791 // Grab a default argument (if available).
792 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
793 // we introduce the type parameter into the local scope.
794 SourceLocation EqualLoc;
795 ParsedType DefaultArg;
796 if (TryConsumeToken(tok::equal, EqualLoc))
797 DefaultArg = ParseTypeName(/*Range=*/nullptr,
798 DeclaratorContext::TemplateTypeArgContext).get();
800 NamedDecl *NewDecl = Actions.ActOnTypeParameter(getCurScope(),
801 TypenameKeyword, EllipsisLoc,
802 KeyLoc, ParamName, NameLoc,
803 Depth, Position, EqualLoc,
805 TypeConstraint != nullptr);
808 Actions.ActOnTypeConstraint(TypeConstraint,
809 cast<TemplateTypeParmDecl>(NewDecl),
815 /// ParseTemplateTemplateParameter - Handle the parsing of template
816 /// template parameters.
818 /// type-parameter: [C++ temp.param]
819 /// 'template' '<' template-parameter-list '>' type-parameter-key
820 /// ...[opt] identifier[opt]
821 /// 'template' '<' template-parameter-list '>' type-parameter-key
822 /// identifier[opt] = id-expression
823 /// type-parameter-key:
825 /// 'typename' [C++1z]
827 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
828 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
830 // Handle the template <...> part.
831 SourceLocation TemplateLoc = ConsumeToken();
832 SmallVector<NamedDecl*,8> TemplateParams;
833 SourceLocation LAngleLoc, RAngleLoc;
835 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
836 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
842 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
843 // Generate a meaningful error if the user forgot to put class before the
844 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
845 // or greater appear immediately or after 'struct'. In the latter case,
846 // replace the keyword with 'class'.
847 if (!TryConsumeToken(tok::kw_class)) {
848 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
849 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
850 if (Tok.is(tok::kw_typename)) {
851 Diag(Tok.getLocation(),
852 getLangOpts().CPlusPlus17
853 ? diag::warn_cxx14_compat_template_template_param_typename
854 : diag::ext_template_template_param_typename)
855 << (!getLangOpts().CPlusPlus17
856 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
858 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
859 tok::greatergreater, tok::ellipsis)) {
860 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
861 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
862 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
864 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
870 // Parse the ellipsis, if given.
871 SourceLocation EllipsisLoc;
872 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
874 getLangOpts().CPlusPlus11
875 ? diag::warn_cxx98_compat_variadic_templates
876 : diag::ext_variadic_templates);
878 // Get the identifier, if given.
879 SourceLocation NameLoc = Tok.getLocation();
880 IdentifierInfo *ParamName = nullptr;
881 if (Tok.is(tok::identifier)) {
882 ParamName = Tok.getIdentifierInfo();
884 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
885 tok::greatergreater)) {
886 // Unnamed template parameter. Don't have to do anything here, just
887 // don't consume this token.
889 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
893 // Recover from misplaced ellipsis.
894 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
895 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
896 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
898 TemplateParameterList *ParamList =
899 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
900 TemplateLoc, LAngleLoc,
904 // Grab a default argument (if available).
905 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
906 // we introduce the template parameter into the local scope.
907 SourceLocation EqualLoc;
908 ParsedTemplateArgument DefaultArg;
909 if (TryConsumeToken(tok::equal, EqualLoc)) {
910 DefaultArg = ParseTemplateTemplateArgument();
911 if (DefaultArg.isInvalid()) {
912 Diag(Tok.getLocation(),
913 diag::err_default_template_template_parameter_not_template);
914 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
915 StopAtSemi | StopBeforeMatch);
919 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
920 ParamList, EllipsisLoc,
921 ParamName, NameLoc, Depth,
922 Position, EqualLoc, DefaultArg);
925 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
926 /// template parameters (e.g., in "template<int Size> class array;").
928 /// template-parameter:
930 /// parameter-declaration
932 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
933 // Parse the declaration-specifiers (i.e., the type).
934 // FIXME: The type should probably be restricted in some way... Not all
935 // declarators (parts of declarators?) are accepted for parameters.
936 DeclSpec DS(AttrFactory);
937 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
938 DeclSpecContext::DSC_template_param);
940 // Parse this as a typename.
941 Declarator ParamDecl(DS, DeclaratorContext::TemplateParamContext);
942 ParseDeclarator(ParamDecl);
943 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
944 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
948 // Recover from misplaced ellipsis.
949 SourceLocation EllipsisLoc;
950 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
951 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
953 // If there is a default value, parse it.
954 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
955 // we introduce the template parameter into the local scope.
956 SourceLocation EqualLoc;
957 ExprResult DefaultArg;
958 if (TryConsumeToken(tok::equal, EqualLoc)) {
959 // C++ [temp.param]p15:
960 // When parsing a default template-argument for a non-type
961 // template-parameter, the first non-nested > is taken as the
962 // end of the template-parameter-list rather than a greater-than
964 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
965 EnterExpressionEvaluationContext ConstantEvaluated(
966 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
968 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
969 if (DefaultArg.isInvalid())
970 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
973 // Create the parameter.
974 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
975 Depth, Position, EqualLoc,
979 void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
980 SourceLocation CorrectLoc,
981 bool AlreadyHasEllipsis,
982 bool IdentifierHasName) {
984 if (!AlreadyHasEllipsis)
985 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
986 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
987 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
988 << !IdentifierHasName;
991 void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
993 assert(EllipsisLoc.isValid());
994 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
995 if (!AlreadyHasEllipsis)
996 D.setEllipsisLoc(EllipsisLoc);
997 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
998 AlreadyHasEllipsis, D.hasName());
1001 /// Parses a '>' at the end of a template list.
1003 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
1004 /// to determine if these tokens were supposed to be a '>' followed by
1005 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
1007 /// \param RAngleLoc the location of the consumed '>'.
1009 /// \param ConsumeLastToken if true, the '>' is consumed.
1011 /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
1012 /// type parameter or type argument list, rather than a C++ template parameter
1013 /// or argument list.
1015 /// \returns true, if current token does not start with '>', false otherwise.
1016 bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
1017 bool ConsumeLastToken,
1018 bool ObjCGenericList) {
1019 // What will be left once we've consumed the '>'.
1020 tok::TokenKind RemainingToken;
1021 const char *ReplacementStr = "> >";
1022 bool MergeWithNextToken = false;
1024 switch (Tok.getKind()) {
1026 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
1030 // Determine the location of the '>' token. Only consume this token
1031 // if the caller asked us to.
1032 RAngleLoc = Tok.getLocation();
1033 if (ConsumeLastToken)
1037 case tok::greatergreater:
1038 RemainingToken = tok::greater;
1041 case tok::greatergreatergreater:
1042 RemainingToken = tok::greatergreater;
1045 case tok::greaterequal:
1046 RemainingToken = tok::equal;
1047 ReplacementStr = "> =";
1049 // Join two adjacent '=' tokens into one, for cases like:
1050 // void (*p)() = f<int>;
1051 // return f<int>==p;
1052 if (NextToken().is(tok::equal) &&
1053 areTokensAdjacent(Tok, NextToken())) {
1054 RemainingToken = tok::equalequal;
1055 MergeWithNextToken = true;
1059 case tok::greatergreaterequal:
1060 RemainingToken = tok::greaterequal;
1064 // This template-id is terminated by a token that starts with a '>'.
1065 // Outside C++11 and Objective-C, this is now error recovery.
1067 // C++11 allows this when the token is '>>', and in CUDA + C++11 mode, we
1068 // extend that treatment to also apply to the '>>>' token.
1070 // Objective-C allows this in its type parameter / argument lists.
1072 SourceLocation TokBeforeGreaterLoc = PrevTokLocation;
1073 SourceLocation TokLoc = Tok.getLocation();
1074 Token Next = NextToken();
1076 // Whether splitting the current token after the '>' would undesirably result
1077 // in the remaining token pasting with the token after it. This excludes the
1078 // MergeWithNextToken cases, which we've already handled.
1079 bool PreventMergeWithNextToken =
1080 (RemainingToken == tok::greater ||
1081 RemainingToken == tok::greatergreater) &&
1082 (Next.isOneOf(tok::greater, tok::greatergreater,
1083 tok::greatergreatergreater, tok::equal, tok::greaterequal,
1084 tok::greatergreaterequal, tok::equalequal)) &&
1085 areTokensAdjacent(Tok, Next);
1087 // Diagnose this situation as appropriate.
1088 if (!ObjCGenericList) {
1089 // The source range of the replaced token(s).
1090 CharSourceRange ReplacementRange = CharSourceRange::getCharRange(
1091 TokLoc, Lexer::AdvanceToTokenCharacter(TokLoc, 2, PP.getSourceManager(),
1094 // A hint to put a space between the '>>'s. In order to make the hint as
1095 // clear as possible, we include the characters either side of the space in
1096 // the replacement, rather than just inserting a space at SecondCharLoc.
1097 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
1100 // A hint to put another space after the token, if it would otherwise be
1101 // lexed differently.
1103 if (PreventMergeWithNextToken)
1104 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
1106 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
1107 if (getLangOpts().CPlusPlus11 &&
1108 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
1109 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
1110 else if (Tok.is(tok::greaterequal))
1111 DiagId = diag::err_right_angle_bracket_equal_needs_space;
1112 Diag(TokLoc, DiagId) << Hint1 << Hint2;
1115 // Find the "length" of the resulting '>' token. This is not always 1, as it
1116 // can contain escaped newlines.
1117 unsigned GreaterLength = Lexer::getTokenPrefixLength(
1118 TokLoc, 1, PP.getSourceManager(), getLangOpts());
1120 // Annotate the source buffer to indicate that we split the token after the
1121 // '>'. This allows us to properly find the end of, and extract the spelling
1122 // of, the '>' token later.
1123 RAngleLoc = PP.SplitToken(TokLoc, GreaterLength);
1125 // Strip the initial '>' from the token.
1126 bool CachingTokens = PP.IsPreviousCachedToken(Tok);
1128 Token Greater = Tok;
1129 Greater.setLocation(RAngleLoc);
1130 Greater.setKind(tok::greater);
1131 Greater.setLength(GreaterLength);
1133 unsigned OldLength = Tok.getLength();
1134 if (MergeWithNextToken) {
1136 OldLength += Tok.getLength();
1139 Tok.setKind(RemainingToken);
1140 Tok.setLength(OldLength - GreaterLength);
1142 // Split the second token if lexing it normally would lex a different token
1143 // (eg, the fifth token in 'A<B>>>' should re-lex as '>', not '>>').
1144 SourceLocation AfterGreaterLoc = TokLoc.getLocWithOffset(GreaterLength);
1145 if (PreventMergeWithNextToken)
1146 AfterGreaterLoc = PP.SplitToken(AfterGreaterLoc, Tok.getLength());
1147 Tok.setLocation(AfterGreaterLoc);
1149 // Update the token cache to match what we just did if necessary.
1150 if (CachingTokens) {
1151 // If the previous cached token is being merged, delete it.
1152 if (MergeWithNextToken)
1153 PP.ReplacePreviousCachedToken({});
1155 if (ConsumeLastToken)
1156 PP.ReplacePreviousCachedToken({Greater, Tok});
1158 PP.ReplacePreviousCachedToken({Greater});
1161 if (ConsumeLastToken) {
1162 PrevTokLocation = RAngleLoc;
1164 PrevTokLocation = TokBeforeGreaterLoc;
1165 PP.EnterToken(Tok, /*IsReinject=*/true);
1173 /// Parses a template-id that after the template name has
1174 /// already been parsed.
1176 /// This routine takes care of parsing the enclosed template argument
1177 /// list ('<' template-parameter-list [opt] '>') and placing the
1178 /// results into a form that can be transferred to semantic analysis.
1180 /// \param ConsumeLastToken if true, then we will consume the last
1181 /// token that forms the template-id. Otherwise, we will leave the
1182 /// last token in the stream (e.g., so that it can be replaced with an
1183 /// annotation token).
1185 Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
1186 SourceLocation &LAngleLoc,
1187 TemplateArgList &TemplateArgs,
1188 SourceLocation &RAngleLoc) {
1189 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
1192 LAngleLoc = ConsumeToken();
1194 // Parse the optional template-argument-list.
1195 bool Invalid = false;
1197 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
1198 if (!Tok.isOneOf(tok::greater, tok::greatergreater,
1199 tok::greatergreatergreater, tok::greaterequal,
1200 tok::greatergreaterequal))
1201 Invalid = ParseTemplateArgumentList(TemplateArgs);
1204 // Try to find the closing '>'.
1205 if (ConsumeLastToken)
1206 SkipUntil(tok::greater, StopAtSemi);
1208 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
1213 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
1214 /*ObjCGenericList=*/false);
1217 /// Replace the tokens that form a simple-template-id with an
1218 /// annotation token containing the complete template-id.
1220 /// The first token in the stream must be the name of a template that
1221 /// is followed by a '<'. This routine will parse the complete
1222 /// simple-template-id and replace the tokens with a single annotation
1223 /// token with one of two different kinds: if the template-id names a
1224 /// type (and \p AllowTypeAnnotation is true), the annotation token is
1225 /// a type annotation that includes the optional nested-name-specifier
1226 /// (\p SS). Otherwise, the annotation token is a template-id
1227 /// annotation that does not include the optional
1228 /// nested-name-specifier.
1230 /// \param Template the declaration of the template named by the first
1231 /// token (an identifier), as returned from \c Action::isTemplateName().
1233 /// \param TNK the kind of template that \p Template
1234 /// refers to, as returned from \c Action::isTemplateName().
1236 /// \param SS if non-NULL, the nested-name-specifier that precedes
1237 /// this template name.
1239 /// \param TemplateKWLoc if valid, specifies that this template-id
1240 /// annotation was preceded by the 'template' keyword and gives the
1241 /// location of that keyword. If invalid (the default), then this
1242 /// template-id was not preceded by a 'template' keyword.
1244 /// \param AllowTypeAnnotation if true (the default), then a
1245 /// simple-template-id that refers to a class template, template
1246 /// template parameter, or other template that produces a type will be
1247 /// replaced with a type annotation token. Otherwise, the
1248 /// simple-template-id is always replaced with a template-id
1249 /// annotation token.
1251 /// \param TypeConstraint if true, then this is actually a type-constraint,
1252 /// meaning that the template argument list can be omitted (and the template in
1253 /// question must be a concept).
1255 /// If an unrecoverable parse error occurs and no annotation token can be
1256 /// formed, this function returns true.
1258 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
1260 SourceLocation TemplateKWLoc,
1261 UnqualifiedId &TemplateName,
1262 bool AllowTypeAnnotation,
1263 bool TypeConstraint) {
1264 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
1265 assert(Template && (Tok.is(tok::less) || TypeConstraint) &&
1266 "Parser isn't at the beginning of a template-id");
1267 assert(!(TypeConstraint && AllowTypeAnnotation) && "type-constraint can't be "
1268 "a type annotation");
1269 assert((!TypeConstraint || TNK == TNK_Concept_template) && "type-constraint "
1270 "must accompany a concept name");
1272 // Consume the template-name.
1273 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
1275 // Parse the enclosed template argument list.
1276 SourceLocation LAngleLoc, RAngleLoc;
1277 TemplateArgList TemplateArgs;
1278 if (!TypeConstraint || Tok.is(tok::less)) {
1279 bool Invalid = ParseTemplateIdAfterTemplateName(false, LAngleLoc,
1284 // If we failed to parse the template ID but skipped ahead to a >, we're not
1285 // going to be able to form a token annotation. Eat the '>' if present.
1286 TryConsumeToken(tok::greater);
1287 // FIXME: Annotate the token stream so we don't produce the same errors
1288 // again if we're doing this annotation as part of a tentative parse.
1293 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1295 // Build the annotation token.
1296 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
1297 TypeResult Type = Actions.ActOnTemplateIdType(
1298 getCurScope(), SS, TemplateKWLoc, Template, TemplateName.Identifier,
1299 TemplateNameLoc, LAngleLoc, TemplateArgsPtr, RAngleLoc);
1300 if (Type.isInvalid()) {
1301 // If we failed to parse the template ID but skipped ahead to a >, we're
1302 // not going to be able to form a token annotation. Eat the '>' if
1304 TryConsumeToken(tok::greater);
1305 // FIXME: Annotate the token stream so we don't produce the same errors
1306 // again if we're doing this annotation as part of a tentative parse.
1310 Tok.setKind(tok::annot_typename);
1311 setTypeAnnotation(Tok, Type.get());
1312 if (SS.isNotEmpty())
1313 Tok.setLocation(SS.getBeginLoc());
1314 else if (TemplateKWLoc.isValid())
1315 Tok.setLocation(TemplateKWLoc);
1317 Tok.setLocation(TemplateNameLoc);
1319 // Build a template-id annotation token that can be processed
1321 Tok.setKind(tok::annot_template_id);
1323 IdentifierInfo *TemplateII =
1324 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1325 ? TemplateName.Identifier
1328 OverloadedOperatorKind OpKind =
1329 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1331 : TemplateName.OperatorFunctionId.Operator;
1333 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
1334 SS, TemplateKWLoc, TemplateNameLoc, TemplateII, OpKind, Template, TNK,
1335 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
1337 Tok.setAnnotationValue(TemplateId);
1338 if (TemplateKWLoc.isValid())
1339 Tok.setLocation(TemplateKWLoc);
1341 Tok.setLocation(TemplateNameLoc);
1344 // Common fields for the annotation token
1345 Tok.setAnnotationEndLoc(RAngleLoc);
1347 // In case the tokens were cached, have Preprocessor replace them with the
1348 // annotation token.
1349 PP.AnnotateCachedTokens(Tok);
1353 /// Replaces a template-id annotation token with a type
1354 /// annotation token.
1356 /// If there was a failure when forming the type from the template-id,
1357 /// a type annotation token will still be created, but will have a
1358 /// NULL type pointer to signify an error.
1360 /// \param IsClassName Is this template-id appearing in a context where we
1361 /// know it names a class, such as in an elaborated-type-specifier or
1362 /// base-specifier? ('typename' and 'template' are unneeded and disallowed
1363 /// in those contexts.)
1364 void Parser::AnnotateTemplateIdTokenAsType(bool IsClassName) {
1365 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1367 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1368 assert((TemplateId->Kind == TNK_Type_template ||
1369 TemplateId->Kind == TNK_Dependent_template_name ||
1370 TemplateId->Kind == TNK_Undeclared_template) &&
1371 "Only works for type and dependent templates");
1373 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1374 TemplateId->NumArgs);
1377 = Actions.ActOnTemplateIdType(getCurScope(),
1379 TemplateId->TemplateKWLoc,
1380 TemplateId->Template,
1382 TemplateId->TemplateNameLoc,
1383 TemplateId->LAngleLoc,
1385 TemplateId->RAngleLoc,
1386 /*IsCtorOrDtorName*/false,
1388 // Create the new "type" annotation token.
1389 Tok.setKind(tok::annot_typename);
1390 setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
1391 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1392 Tok.setLocation(TemplateId->SS.getBeginLoc());
1393 // End location stays the same
1395 // Replace the template-id annotation token, and possible the scope-specifier
1396 // that precedes it, with the typename annotation token.
1397 PP.AnnotateCachedTokens(Tok);
1400 /// Determine whether the given token can end a template argument.
1401 static bool isEndOfTemplateArgument(Token Tok) {
1402 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
1405 /// Parse a C++ template template argument.
1406 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1407 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1408 !Tok.is(tok::annot_cxxscope))
1409 return ParsedTemplateArgument();
1411 // C++0x [temp.arg.template]p1:
1412 // A template-argument for a template template-parameter shall be the name
1413 // of a class template or an alias template, expressed as id-expression.
1415 // We parse an id-expression that refers to a class template or alias
1416 // template. The grammar we parse is:
1418 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1420 // followed by a token that terminates a template argument, such as ',',
1421 // '>', or (in some cases) '>>'.
1422 CXXScopeSpec SS; // nested-name-specifier, if present
1423 ParseOptionalCXXScopeSpecifier(SS, nullptr,
1424 /*EnteringContext=*/false);
1426 ParsedTemplateArgument Result;
1427 SourceLocation EllipsisLoc;
1428 if (SS.isSet() && Tok.is(tok::kw_template)) {
1429 // Parse the optional 'template' keyword following the
1430 // nested-name-specifier.
1431 SourceLocation TemplateKWLoc = ConsumeToken();
1433 if (Tok.is(tok::identifier)) {
1434 // We appear to have a dependent template name.
1436 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1437 ConsumeToken(); // the identifier
1439 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1441 // If the next token signals the end of a template argument,
1442 // then we have a dependent template name that could be a template
1443 // template argument.
1444 TemplateTy Template;
1445 if (isEndOfTemplateArgument(Tok) &&
1446 Actions.ActOnDependentTemplateName(
1447 getCurScope(), SS, TemplateKWLoc, Name,
1448 /*ObjectType=*/nullptr,
1449 /*EnteringContext=*/false, Template))
1450 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1452 } else if (Tok.is(tok::identifier)) {
1453 // We may have a (non-dependent) template name.
1454 TemplateTy Template;
1456 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1457 ConsumeToken(); // the identifier
1459 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1461 if (isEndOfTemplateArgument(Tok)) {
1462 bool MemberOfUnknownSpecialization;
1463 TemplateNameKind TNK = Actions.isTemplateName(
1465 /*hasTemplateKeyword=*/false, Name,
1466 /*ObjectType=*/nullptr,
1467 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
1468 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1469 // We have an id-expression that refers to a class template or
1470 // (C++0x) alias template.
1471 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1476 // If this is a pack expansion, build it as such.
1477 if (EllipsisLoc.isValid() && !Result.isInvalid())
1478 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1483 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1485 /// template-argument: [C++ 14.2]
1486 /// constant-expression
1489 ParsedTemplateArgument Parser::ParseTemplateArgument() {
1490 // C++ [temp.arg]p2:
1491 // In a template-argument, an ambiguity between a type-id and an
1492 // expression is resolved to a type-id, regardless of the form of
1493 // the corresponding template-parameter.
1495 // Therefore, we initially try to parse a type-id - and isCXXTypeId might look
1496 // up and annotate an identifier as an id-expression during disambiguation,
1497 // so enter the appropriate context for a constant expression template
1498 // argument before trying to disambiguate.
1500 EnterExpressionEvaluationContext EnterConstantEvaluated(
1501 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated,
1502 /*LambdaContextDecl=*/nullptr,
1503 /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
1504 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1505 TypeResult TypeArg = ParseTypeName(
1506 /*Range=*/nullptr, DeclaratorContext::TemplateArgContext);
1507 return Actions.ActOnTemplateTypeArgument(TypeArg);
1510 // Try to parse a template template argument.
1512 TentativeParsingAction TPA(*this);
1514 ParsedTemplateArgument TemplateTemplateArgument
1515 = ParseTemplateTemplateArgument();
1516 if (!TemplateTemplateArgument.isInvalid()) {
1518 return TemplateTemplateArgument;
1521 // Revert this tentative parse to parse a non-type template argument.
1525 // Parse a non-type template argument.
1526 SourceLocation Loc = Tok.getLocation();
1527 ExprResult ExprArg = ParseConstantExpressionInExprEvalContext(MaybeTypeCast);
1528 if (ExprArg.isInvalid() || !ExprArg.get()) {
1529 return ParsedTemplateArgument();
1532 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1533 ExprArg.get(), Loc);
1536 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1537 /// (C++ [temp.names]). Returns true if there was an error.
1539 /// template-argument-list: [C++ 14.2]
1540 /// template-argument
1541 /// template-argument-list ',' template-argument
1543 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1545 ColonProtectionRAIIObject ColonProtection(*this, false);
1548 ParsedTemplateArgument Arg = ParseTemplateArgument();
1549 SourceLocation EllipsisLoc;
1550 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1551 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1553 if (Arg.isInvalid()) {
1554 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
1558 // Save this template argument.
1559 TemplateArgs.push_back(Arg);
1561 // If the next token is a comma, consume it and keep reading
1563 } while (TryConsumeToken(tok::comma));
1568 /// Parse a C++ explicit template instantiation
1569 /// (C++ [temp.explicit]).
1571 /// explicit-instantiation:
1572 /// 'extern' [opt] 'template' declaration
1574 /// Note that the 'extern' is a GNU extension and C++11 feature.
1575 Decl *Parser::ParseExplicitInstantiation(DeclaratorContext Context,
1576 SourceLocation ExternLoc,
1577 SourceLocation TemplateLoc,
1578 SourceLocation &DeclEnd,
1579 ParsedAttributes &AccessAttrs,
1580 AccessSpecifier AS) {
1581 // This isn't really required here.
1582 ParsingDeclRAIIObject
1583 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1585 return ParseSingleDeclarationAfterTemplate(
1586 Context, ParsedTemplateInfo(ExternLoc, TemplateLoc),
1587 ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
1590 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1592 return getTemplateParamsRange(TemplateParams->data(),
1593 TemplateParams->size());
1595 SourceRange R(TemplateLoc);
1596 if (ExternLoc.isValid())
1597 R.setBegin(ExternLoc);
1601 void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1602 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1605 /// Late parse a C++ function template in Microsoft mode.
1606 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1610 // Get the FunctionDecl.
1611 FunctionDecl *FunD = LPT.D->getAsFunction();
1612 // Track template parameter depth.
1613 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1615 // To restore the context after late parsing.
1616 Sema::ContextRAII GlobalSavedContext(
1617 Actions, Actions.Context.getTranslationUnitDecl());
1619 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1621 // Get the list of DeclContexts to reenter. For inline methods, we only want
1622 // to push the DeclContext of the outermost class. This matches the way the
1623 // parser normally parses bodies of inline methods when the outermost class is
1625 struct ContainingDC {
1626 ContainingDC(DeclContext *DC, bool ShouldPush) : Pair(DC, ShouldPush) {}
1627 llvm::PointerIntPair<DeclContext *, 1, bool> Pair;
1628 DeclContext *getDC() { return Pair.getPointer(); }
1629 bool shouldPushDC() { return Pair.getInt(); }
1631 SmallVector<ContainingDC, 4> DeclContextsToReenter;
1632 DeclContext *DD = FunD;
1633 DeclContext *NextContaining = Actions.getContainingDC(DD);
1634 while (DD && !DD->isTranslationUnit()) {
1635 bool ShouldPush = DD == NextContaining;
1636 DeclContextsToReenter.push_back({DD, ShouldPush});
1638 NextContaining = Actions.getContainingDC(DD);
1639 DD = DD->getLexicalParent();
1642 // Reenter template scopes from outermost to innermost.
1643 for (ContainingDC CDC : reverse(DeclContextsToReenter)) {
1644 TemplateParamScopeStack.push_back(
1645 new ParseScope(this, Scope::TemplateParamScope));
1646 unsigned NumParamLists = Actions.ActOnReenterTemplateScope(
1647 getCurScope(), cast<Decl>(CDC.getDC()));
1648 CurTemplateDepthTracker.addDepth(NumParamLists);
1649 if (CDC.shouldPushDC()) {
1650 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1651 Actions.PushDeclContext(Actions.getCurScope(), CDC.getDC());
1655 assert(!LPT.Toks.empty() && "Empty body!");
1657 // Append the current token at the end of the new token stream so that it
1658 // doesn't get lost.
1659 LPT.Toks.push_back(Tok);
1660 PP.EnterTokenStream(LPT.Toks, true, /*IsReinject*/true);
1662 // Consume the previously pushed token.
1663 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1664 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1665 "Inline method not starting with '{', ':' or 'try'");
1667 // Parse the method body. Function body parsing code is similar enough
1668 // to be re-used for method bodies as well.
1669 ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
1670 Scope::CompoundStmtScope);
1672 // Recreate the containing function DeclContext.
1673 Sema::ContextRAII FunctionSavedContext(Actions,
1674 Actions.getContainingDC(FunD));
1676 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1678 if (Tok.is(tok::kw_try)) {
1679 ParseFunctionTryBlock(LPT.D, FnScope);
1681 if (Tok.is(tok::colon))
1682 ParseConstructorInitializer(LPT.D);
1684 Actions.ActOnDefaultCtorInitializers(LPT.D);
1686 if (Tok.is(tok::l_brace)) {
1687 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1688 cast<FunctionTemplateDecl>(LPT.D)
1689 ->getTemplateParameters()
1690 ->getDepth() == TemplateParameterDepth - 1) &&
1691 "TemplateParameterDepth should be greater than the depth of "
1692 "current template being instantiated!");
1693 ParseFunctionStatementBody(LPT.D, FnScope);
1694 Actions.UnmarkAsLateParsedTemplate(FunD);
1696 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1701 SmallVectorImpl<ParseScope *>::reverse_iterator I =
1702 TemplateParamScopeStack.rbegin();
1703 for (; I != TemplateParamScopeStack.rend(); ++I)
1707 /// Lex a delayed template function for late parsing.
1708 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1709 tok::TokenKind kind = Tok.getKind();
1710 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1711 // Consume everything up to (and including) the matching right brace.
1712 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1715 // If we're in a function-try-block, we need to store all the catch blocks.
1716 if (kind == tok::kw_try) {
1717 while (Tok.is(tok::kw_catch)) {
1718 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1719 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1724 /// We've parsed something that could plausibly be intended to be a template
1725 /// name (\p LHS) followed by a '<' token, and the following code can't possibly
1726 /// be an expression. Determine if this is likely to be a template-id and if so,
1728 bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
1729 TentativeParsingAction TPA(*this);
1730 // FIXME: We could look at the token sequence in a lot more detail here.
1731 if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater,
1732 StopAtSemi | StopBeforeMatch)) {
1735 SourceLocation Greater;
1736 ParseGreaterThanInTemplateList(Greater, true, false);
1737 Actions.diagnoseExprIntendedAsTemplateName(getCurScope(), LHS,
1742 // There's no matching '>' token, this probably isn't supposed to be
1743 // interpreted as a template-id. Parse it as an (ill-formed) comparison.
1748 void Parser::checkPotentialAngleBracket(ExprResult &PotentialTemplateName) {
1749 assert(Tok.is(tok::less) && "not at a potential angle bracket");
1751 bool DependentTemplateName = false;
1752 if (!Actions.mightBeIntendedToBeTemplateName(PotentialTemplateName,
1753 DependentTemplateName))
1756 // OK, this might be a name that the user intended to be parsed as a
1757 // template-name, followed by a '<' token. Check for some easy cases.
1759 // If we have potential_template<>, then it's supposed to be a template-name.
1760 if (NextToken().is(tok::greater) ||
1761 (getLangOpts().CPlusPlus11 &&
1762 NextToken().isOneOf(tok::greatergreater, tok::greatergreatergreater))) {
1763 SourceLocation Less = ConsumeToken();
1764 SourceLocation Greater;
1765 ParseGreaterThanInTemplateList(Greater, true, false);
1766 Actions.diagnoseExprIntendedAsTemplateName(
1767 getCurScope(), PotentialTemplateName, Less, Greater);
1768 // FIXME: Perform error recovery.
1769 PotentialTemplateName = ExprError();
1773 // If we have 'potential_template<type-id', assume it's supposed to be a
1774 // template-name if there's a matching '>' later on.
1776 // FIXME: Avoid the tentative parse when NextToken() can't begin a type.
1777 TentativeParsingAction TPA(*this);
1778 SourceLocation Less = ConsumeToken();
1779 if (isTypeIdUnambiguously() &&
1780 diagnoseUnknownTemplateId(PotentialTemplateName, Less)) {
1782 // FIXME: Perform error recovery.
1783 PotentialTemplateName = ExprError();
1789 // Otherwise, remember that we saw this in case we see a potentially-matching
1790 // '>' token later on.
1791 AngleBracketTracker::Priority Priority =
1792 (DependentTemplateName ? AngleBracketTracker::DependentName
1793 : AngleBracketTracker::PotentialTypo) |
1794 (Tok.hasLeadingSpace() ? AngleBracketTracker::SpaceBeforeLess
1795 : AngleBracketTracker::NoSpaceBeforeLess);
1796 AngleBrackets.add(*this, PotentialTemplateName.get(), Tok.getLocation(),
1800 bool Parser::checkPotentialAngleBracketDelimiter(
1801 const AngleBracketTracker::Loc &LAngle, const Token &OpToken) {
1802 // If a comma in an expression context is followed by a type that can be a
1803 // template argument and cannot be an expression, then this is ill-formed,
1804 // but might be intended to be part of a template-id.
1805 if (OpToken.is(tok::comma) && isTypeIdUnambiguously() &&
1806 diagnoseUnknownTemplateId(LAngle.TemplateName, LAngle.LessLoc)) {
1807 AngleBrackets.clear(*this);
1811 // If a context that looks like a template-id is followed by '()', then
1812 // this is ill-formed, but might be intended to be a template-id
1813 // followed by '()'.
1814 if (OpToken.is(tok::greater) && Tok.is(tok::l_paren) &&
1815 NextToken().is(tok::r_paren)) {
1816 Actions.diagnoseExprIntendedAsTemplateName(
1817 getCurScope(), LAngle.TemplateName, LAngle.LessLoc,
1818 OpToken.getLocation());
1819 AngleBrackets.clear(*this);
1823 // After a '>' (etc), we're no longer potentially in a construct that's
1824 // intended to be treated as a template-id.
1825 if (OpToken.is(tok::greater) ||
1826 (getLangOpts().CPlusPlus11 &&
1827 OpToken.isOneOf(tok::greatergreater, tok::greatergreatergreater)))
1828 AngleBrackets.clear(*this);