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/Parse/ParseDiagnostic.h"
16 #include "clang/Parse/Parser.h"
17 #include "clang/Parse/RAIIObjectsForParser.h"
18 #include "clang/Sema/DeclSpec.h"
19 #include "clang/Sema/ParsedTemplate.h"
20 #include "clang/Sema/Scope.h"
21 #include "llvm/Support/TimeProfiler.h"
22 using namespace clang;
24 /// Parse a template declaration, explicit instantiation, or
25 /// explicit specialization.
26 Decl *Parser::ParseDeclarationStartingWithTemplate(
27 DeclaratorContext Context, SourceLocation &DeclEnd,
28 ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
29 ObjCDeclContextSwitch ObjCDC(*this);
31 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
32 return ParseExplicitInstantiation(Context, SourceLocation(), ConsumeToken(),
33 DeclEnd, AccessAttrs, AS);
35 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AccessAttrs,
39 /// Parse a template declaration or an explicit specialization.
41 /// Template declarations include one or more template parameter lists
42 /// and either the function or class template declaration. Explicit
43 /// specializations contain one or more 'template < >' prefixes
44 /// followed by a (possibly templated) declaration. Since the
45 /// syntactic form of both features is nearly identical, we parse all
46 /// of the template headers together and let semantic analysis sort
47 /// the declarations from the explicit specializations.
49 /// template-declaration: [C++ temp]
50 /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
52 /// template-declaration: [C++2a]
53 /// template-head declaration
54 /// template-head concept-definition
56 /// TODO: requires-clause
57 /// template-head: [C++2a]
58 /// 'template' '<' template-parameter-list '>'
59 /// requires-clause[opt]
61 /// explicit-specialization: [ C++ temp.expl.spec]
62 /// 'template' '<' '>' declaration
63 Decl *Parser::ParseTemplateDeclarationOrSpecialization(
64 DeclaratorContext Context, SourceLocation &DeclEnd,
65 ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
66 assert(Tok.isOneOf(tok::kw_export, tok::kw_template) &&
67 "Token does not start a template declaration.");
69 // Enter template-parameter scope.
70 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
72 // Tell the action that names should be checked in the context of
73 // the declaration to come.
75 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
77 // Parse multiple levels of template headers within this template
78 // parameter scope, e.g.,
80 // template<typename T>
81 // template<typename U>
82 // class A<T>::B { ... };
84 // We parse multiple levels non-recursively so that we can build a
85 // single data structure containing all of the template parameter
86 // lists to easily differentiate between the case above and:
88 // template<typename T>
90 // template<typename U> class B;
93 // In the first case, the action for declaring A<T>::B receives
94 // both template parameter lists. In the second case, the action for
95 // defining A<T>::B receives just the inner template parameter list
96 // (and retrieves the outer template parameter list from its
98 bool isSpecialization = true;
99 bool LastParamListWasEmpty = false;
100 TemplateParameterLists ParamLists;
101 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
104 // Consume the 'export', if any.
105 SourceLocation ExportLoc;
106 TryConsumeToken(tok::kw_export, ExportLoc);
108 // Consume the 'template', which should be here.
109 SourceLocation TemplateLoc;
110 if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
111 Diag(Tok.getLocation(), diag::err_expected_template);
115 // Parse the '<' template-parameter-list '>'
116 SourceLocation LAngleLoc, RAngleLoc;
117 SmallVector<NamedDecl*, 4> TemplateParams;
118 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
119 TemplateParams, LAngleLoc, RAngleLoc)) {
120 // Skip until the semi-colon or a '}'.
121 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
122 TryConsumeToken(tok::semi);
126 ExprResult OptionalRequiresClauseConstraintER;
127 if (!TemplateParams.empty()) {
128 isSpecialization = false;
129 ++CurTemplateDepthTracker;
131 if (TryConsumeToken(tok::kw_requires)) {
132 OptionalRequiresClauseConstraintER =
133 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
134 if (!OptionalRequiresClauseConstraintER.isUsable()) {
135 // Skip until the semi-colon or a '}'.
136 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
137 TryConsumeToken(tok::semi);
142 LastParamListWasEmpty = true;
145 ParamLists.push_back(Actions.ActOnTemplateParameterList(
146 CurTemplateDepthTracker.getDepth(), ExportLoc, TemplateLoc, LAngleLoc,
147 TemplateParams, RAngleLoc, OptionalRequiresClauseConstraintER.get()));
148 } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
150 unsigned NewFlags = getCurScope()->getFlags() & ~Scope::TemplateParamScope;
151 ParseScopeFlags TemplateScopeFlags(this, NewFlags, isSpecialization);
153 // Parse the actual template declaration.
154 if (Tok.is(tok::kw_concept))
155 return ParseConceptDefinition(
156 ParsedTemplateInfo(&ParamLists, isSpecialization,
157 LastParamListWasEmpty),
160 return ParseSingleDeclarationAfterTemplate(
162 ParsedTemplateInfo(&ParamLists, isSpecialization, LastParamListWasEmpty),
163 ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
166 /// Parse a single declaration that declares a template,
167 /// template specialization, or explicit instantiation of a template.
169 /// \param DeclEnd will receive the source location of the last token
170 /// within this declaration.
172 /// \param AS the access specifier associated with this
173 /// declaration. Will be AS_none for namespace-scope declarations.
175 /// \returns the new declaration.
176 Decl *Parser::ParseSingleDeclarationAfterTemplate(
177 DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo,
178 ParsingDeclRAIIObject &DiagsFromTParams, SourceLocation &DeclEnd,
179 ParsedAttributes &AccessAttrs, AccessSpecifier AS) {
180 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
181 "Template information required");
183 if (Tok.is(tok::kw_static_assert)) {
184 // A static_assert declaration may not be templated.
185 Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
186 << TemplateInfo.getSourceRange();
187 // Parse the static_assert declaration to improve error recovery.
188 return ParseStaticAssertDeclaration(DeclEnd);
191 if (Context == DeclaratorContext::MemberContext) {
192 // We are parsing a member template.
193 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
198 ParsedAttributesWithRange prefixAttrs(AttrFactory);
199 MaybeParseCXX11Attributes(prefixAttrs);
201 if (Tok.is(tok::kw_using)) {
202 auto usingDeclPtr = ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
204 if (!usingDeclPtr || !usingDeclPtr.get().isSingleDecl())
206 return usingDeclPtr.get().getSingleDecl();
209 // Parse the declaration specifiers, stealing any diagnostics from
210 // the template parameters.
211 ParsingDeclSpec DS(*this, &DiagsFromTParams);
213 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
214 getDeclSpecContextFromDeclaratorContext(Context));
216 if (Tok.is(tok::semi)) {
217 ProhibitAttributes(prefixAttrs);
218 DeclEnd = ConsumeToken();
219 RecordDecl *AnonRecord = nullptr;
220 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
221 getCurScope(), AS, DS,
222 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
223 : MultiTemplateParamsArg(),
224 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
226 assert(!AnonRecord &&
227 "Anonymous unions/structs should not be valid with template");
232 // Move the attributes from the prefix into the DS.
233 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
234 ProhibitAttributes(prefixAttrs);
236 DS.takeAttributesFrom(prefixAttrs);
238 // Parse the declarator.
239 ParsingDeclarator DeclaratorInfo(*this, DS, (DeclaratorContext)Context);
240 ParseDeclarator(DeclaratorInfo);
241 // Error parsing the declarator?
242 if (!DeclaratorInfo.hasName()) {
243 // If so, skip until the semi-colon or a }.
244 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
245 if (Tok.is(tok::semi))
250 llvm::TimeTraceScope TimeScope("ParseTemplate", [&]() {
251 return DeclaratorInfo.getIdentifier() != nullptr
252 ? DeclaratorInfo.getIdentifier()->getName()
256 LateParsedAttrList LateParsedAttrs(true);
257 if (DeclaratorInfo.isFunctionDeclarator())
258 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
260 if (DeclaratorInfo.isFunctionDeclarator() &&
261 isStartOfFunctionDefinition(DeclaratorInfo)) {
263 // Function definitions are only allowed at file scope and in C++ classes.
264 // The C++ inline method definition case is handled elsewhere, so we only
265 // need to handle the file scope definition case.
266 if (Context != DeclaratorContext::FileContext) {
267 Diag(Tok, diag::err_function_definition_not_allowed);
272 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
273 // Recover by ignoring the 'typedef'. This was probably supposed to be
274 // the 'typename' keyword, which we should have already suggested adding
275 // if it's appropriate.
276 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
277 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
278 DS.ClearStorageClassSpecs();
281 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
282 if (DeclaratorInfo.getName().getKind() !=
283 UnqualifiedIdKind::IK_TemplateId) {
284 // If the declarator-id is not a template-id, issue a diagnostic and
285 // recover by ignoring the 'template' keyword.
286 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
287 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
290 SourceLocation LAngleLoc
291 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
292 Diag(DeclaratorInfo.getIdentifierLoc(),
293 diag::err_explicit_instantiation_with_definition)
294 << SourceRange(TemplateInfo.TemplateLoc)
295 << FixItHint::CreateInsertion(LAngleLoc, "<>");
297 // Recover as if it were an explicit specialization.
298 TemplateParameterLists FakedParamLists;
299 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
300 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
301 LAngleLoc, nullptr));
303 return ParseFunctionDefinition(
304 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
305 /*isSpecialization=*/true,
306 /*lastParameterListWasEmpty=*/true),
310 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
314 // Parse this declaration.
315 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
318 if (Tok.is(tok::comma)) {
319 Diag(Tok, diag::err_multiple_template_declarators)
320 << (int)TemplateInfo.Kind;
321 SkipUntil(tok::semi);
325 // Eat the semi colon after the declaration.
326 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
327 if (LateParsedAttrs.size() > 0)
328 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
329 DeclaratorInfo.complete(ThisDecl);
333 /// \brief Parse a single declaration that declares a concept.
335 /// \param DeclEnd will receive the source location of the last token
336 /// within this declaration.
338 /// \returns the new declaration.
340 Parser::ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo,
341 SourceLocation &DeclEnd) {
342 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
343 "Template information required");
344 assert(Tok.is(tok::kw_concept) &&
345 "ParseConceptDefinition must be called when at a 'concept' keyword");
347 ConsumeToken(); // Consume 'concept'
349 SourceLocation BoolKWLoc;
350 if (TryConsumeToken(tok::kw_bool, BoolKWLoc))
351 Diag(Tok.getLocation(), diag::ext_concept_legacy_bool_keyword) <<
352 FixItHint::CreateRemoval(SourceLocation(BoolKWLoc));
354 DiagnoseAndSkipCXX11Attributes();
357 if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
358 /*EnteringContext=*/false, /*MayBePseudoDestructor=*/nullptr,
359 /*IsTypename=*/false, /*LastII=*/nullptr, /*OnlyNamespace=*/true) ||
361 SkipUntil(tok::semi);
366 Diag(SS.getBeginLoc(),
367 diag::err_concept_definition_not_identifier);
369 UnqualifiedId Result;
370 if (ParseUnqualifiedId(SS, /*EnteringContext=*/false,
371 /*AllowDestructorName=*/false,
372 /*AllowConstructorName=*/false,
373 /*AllowDeductionGuide=*/false,
374 /*ObjectType=*/ParsedType(), /*TemplateKWLoc=*/nullptr,
376 SkipUntil(tok::semi);
380 if (Result.getKind() != UnqualifiedIdKind::IK_Identifier) {
381 Diag(Result.getBeginLoc(), diag::err_concept_definition_not_identifier);
382 SkipUntil(tok::semi);
386 IdentifierInfo *Id = Result.Identifier;
387 SourceLocation IdLoc = Result.getBeginLoc();
389 DiagnoseAndSkipCXX11Attributes();
391 if (!TryConsumeToken(tok::equal)) {
392 Diag(Tok.getLocation(), diag::err_expected) << tok::equal;
393 SkipUntil(tok::semi);
397 ExprResult ConstraintExprResult =
398 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
399 if (ConstraintExprResult.isInvalid()) {
400 SkipUntil(tok::semi);
404 DeclEnd = Tok.getLocation();
405 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
406 Expr *ConstraintExpr = ConstraintExprResult.get();
407 return Actions.ActOnConceptDefinition(getCurScope(),
408 *TemplateInfo.TemplateParams,
409 Id, IdLoc, ConstraintExpr);
412 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
413 /// angle brackets. Depth is the depth of this template-parameter-list, which
414 /// is the number of template headers directly enclosing this template header.
415 /// TemplateParams is the current list of template parameters we're building.
416 /// The template parameter we parse will be added to this list. LAngleLoc and
417 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
418 /// that enclose this template parameter list.
420 /// \returns true if an error occurred, false otherwise.
421 bool Parser::ParseTemplateParameters(
422 unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams,
423 SourceLocation &LAngleLoc, SourceLocation &RAngleLoc) {
424 // Get the template parameter list.
425 if (!TryConsumeToken(tok::less, LAngleLoc)) {
426 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
430 // Try to parse the template parameter list.
432 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
433 Failed = ParseTemplateParameterList(Depth, TemplateParams);
435 if (Tok.is(tok::greatergreater)) {
436 // No diagnostic required here: a template-parameter-list can only be
437 // followed by a declaration or, for a template template parameter, the
438 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
439 // This matters for elegant diagnosis of:
440 // template<template<typename>> struct S;
441 Tok.setKind(tok::greater);
442 RAngleLoc = Tok.getLocation();
443 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
444 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
445 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
451 /// ParseTemplateParameterList - Parse a template parameter list. If
452 /// the parsing fails badly (i.e., closing bracket was left out), this
453 /// will try to put the token stream in a reasonable position (closing
454 /// a statement, etc.) and return false.
456 /// template-parameter-list: [C++ temp]
457 /// template-parameter
458 /// template-parameter-list ',' template-parameter
460 Parser::ParseTemplateParameterList(const unsigned Depth,
461 SmallVectorImpl<NamedDecl*> &TemplateParams) {
464 if (NamedDecl *TmpParam
465 = ParseTemplateParameter(Depth, TemplateParams.size())) {
466 TemplateParams.push_back(TmpParam);
468 // If we failed to parse a template parameter, skip until we find
469 // a comma or closing brace.
470 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
471 StopAtSemi | StopBeforeMatch);
474 // Did we find a comma or the end of the template parameter list?
475 if (Tok.is(tok::comma)) {
477 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
478 // Don't consume this... that's done by template parser.
481 // Somebody probably forgot to close the template. Skip ahead and
482 // try to get out of the expression. This error is currently
483 // subsumed by whatever goes on in ParseTemplateParameter.
484 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
485 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
486 StopAtSemi | StopBeforeMatch);
493 /// Determine whether the parser is at the start of a template
495 bool Parser::isStartOfTemplateTypeParameter() {
496 if (Tok.is(tok::kw_class)) {
497 // "class" may be the start of an elaborated-type-specifier or a
498 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
499 switch (NextToken().getKind()) {
503 case tok::greatergreater:
507 case tok::identifier:
508 // This may be either a type-parameter or an elaborated-type-specifier.
509 // We have to look further.
516 switch (GetLookAheadToken(2).getKind()) {
520 case tok::greatergreater:
528 // 'typedef' is a reasonably-common typo/thinko for 'typename', and is
529 // ill-formed otherwise.
530 if (Tok.isNot(tok::kw_typename) && Tok.isNot(tok::kw_typedef))
533 // C++ [temp.param]p2:
534 // There is no semantic difference between class and typename in a
535 // template-parameter. typename followed by an unqualified-id
536 // names a template type parameter. typename followed by a
537 // qualified-id denotes the type in a non-type
538 // parameter-declaration.
539 Token Next = NextToken();
541 // If we have an identifier, skip over it.
542 if (Next.getKind() == tok::identifier)
543 Next = GetLookAheadToken(2);
545 switch (Next.getKind()) {
549 case tok::greatergreater:
553 case tok::kw_typename:
554 case tok::kw_typedef:
556 // These indicate that a comma was missed after a type parameter, not that
557 // we have found a non-type parameter.
565 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
567 /// template-parameter: [C++ temp.param]
569 /// parameter-declaration
571 /// type-parameter: (see below)
572 /// 'class' ...[opt] identifier[opt]
573 /// 'class' identifier[opt] '=' type-id
574 /// 'typename' ...[opt] identifier[opt]
575 /// 'typename' identifier[opt] '=' type-id
576 /// 'template' '<' template-parameter-list '>'
577 /// 'class' ...[opt] identifier[opt]
578 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
580 NamedDecl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
581 if (isStartOfTemplateTypeParameter()) {
582 // Is there just a typo in the input code? ('typedef' instead of 'typename')
583 if (Tok.is(tok::kw_typedef)) {
584 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
586 Diag(Tok.getLocation(), diag::note_meant_to_use_typename)
587 << FixItHint::CreateReplacement(CharSourceRange::getCharRange(
588 Tok.getLocation(), Tok.getEndLoc()),
591 Tok.setKind(tok::kw_typename);
594 return ParseTypeParameter(Depth, Position);
597 if (Tok.is(tok::kw_template))
598 return ParseTemplateTemplateParameter(Depth, Position);
600 // If it's none of the above, then it must be a parameter declaration.
601 // NOTE: This will pick up errors in the closure of the template parameter
602 // list (e.g., template < ; Check here to implement >> style closures.
603 return ParseNonTypeTemplateParameter(Depth, Position);
606 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
607 /// Other kinds of template parameters are parsed in
608 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
610 /// type-parameter: [C++ temp.param]
611 /// 'class' ...[opt][C++0x] identifier[opt]
612 /// 'class' identifier[opt] '=' type-id
613 /// 'typename' ...[opt][C++0x] identifier[opt]
614 /// 'typename' identifier[opt] '=' type-id
615 NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
616 assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
617 "A type-parameter starts with 'class' or 'typename'");
619 // Consume the 'class' or 'typename' keyword.
620 bool TypenameKeyword = Tok.is(tok::kw_typename);
621 SourceLocation KeyLoc = ConsumeToken();
623 // Grab the ellipsis (if given).
624 SourceLocation EllipsisLoc;
625 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
627 getLangOpts().CPlusPlus11
628 ? diag::warn_cxx98_compat_variadic_templates
629 : diag::ext_variadic_templates);
632 // Grab the template parameter name (if given)
633 SourceLocation NameLoc = Tok.getLocation();
634 IdentifierInfo *ParamName = nullptr;
635 if (Tok.is(tok::identifier)) {
636 ParamName = Tok.getIdentifierInfo();
638 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
639 tok::greatergreater)) {
640 // Unnamed template parameter. Don't have to do anything here, just
641 // don't consume this token.
643 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
647 // Recover from misplaced ellipsis.
648 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
649 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
650 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
652 // Grab a default argument (if available).
653 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
654 // we introduce the type parameter into the local scope.
655 SourceLocation EqualLoc;
656 ParsedType DefaultArg;
657 if (TryConsumeToken(tok::equal, EqualLoc))
658 DefaultArg = ParseTypeName(/*Range=*/nullptr,
659 DeclaratorContext::TemplateTypeArgContext).get();
661 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
662 KeyLoc, ParamName, NameLoc, Depth, Position,
663 EqualLoc, DefaultArg);
666 /// ParseTemplateTemplateParameter - Handle the parsing of template
667 /// template parameters.
669 /// type-parameter: [C++ temp.param]
670 /// 'template' '<' template-parameter-list '>' type-parameter-key
671 /// ...[opt] identifier[opt]
672 /// 'template' '<' template-parameter-list '>' type-parameter-key
673 /// identifier[opt] = id-expression
674 /// type-parameter-key:
676 /// 'typename' [C++1z]
678 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
679 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
681 // Handle the template <...> part.
682 SourceLocation TemplateLoc = ConsumeToken();
683 SmallVector<NamedDecl*,8> TemplateParams;
684 SourceLocation LAngleLoc, RAngleLoc;
686 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
687 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
693 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
694 // Generate a meaningful error if the user forgot to put class before the
695 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
696 // or greater appear immediately or after 'struct'. In the latter case,
697 // replace the keyword with 'class'.
698 if (!TryConsumeToken(tok::kw_class)) {
699 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
700 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
701 if (Tok.is(tok::kw_typename)) {
702 Diag(Tok.getLocation(),
703 getLangOpts().CPlusPlus17
704 ? diag::warn_cxx14_compat_template_template_param_typename
705 : diag::ext_template_template_param_typename)
706 << (!getLangOpts().CPlusPlus17
707 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
709 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
710 tok::greatergreater, tok::ellipsis)) {
711 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
712 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
713 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
715 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
721 // Parse the ellipsis, if given.
722 SourceLocation EllipsisLoc;
723 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
725 getLangOpts().CPlusPlus11
726 ? diag::warn_cxx98_compat_variadic_templates
727 : diag::ext_variadic_templates);
729 // Get the identifier, if given.
730 SourceLocation NameLoc = Tok.getLocation();
731 IdentifierInfo *ParamName = nullptr;
732 if (Tok.is(tok::identifier)) {
733 ParamName = Tok.getIdentifierInfo();
735 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
736 tok::greatergreater)) {
737 // Unnamed template parameter. Don't have to do anything here, just
738 // don't consume this token.
740 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
744 // Recover from misplaced ellipsis.
745 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
746 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
747 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
749 TemplateParameterList *ParamList =
750 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
751 TemplateLoc, LAngleLoc,
755 // Grab a default argument (if available).
756 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
757 // we introduce the template parameter into the local scope.
758 SourceLocation EqualLoc;
759 ParsedTemplateArgument DefaultArg;
760 if (TryConsumeToken(tok::equal, EqualLoc)) {
761 DefaultArg = ParseTemplateTemplateArgument();
762 if (DefaultArg.isInvalid()) {
763 Diag(Tok.getLocation(),
764 diag::err_default_template_template_parameter_not_template);
765 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
766 StopAtSemi | StopBeforeMatch);
770 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
771 ParamList, EllipsisLoc,
772 ParamName, NameLoc, Depth,
773 Position, EqualLoc, DefaultArg);
776 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
777 /// template parameters (e.g., in "template<int Size> class array;").
779 /// template-parameter:
781 /// parameter-declaration
783 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
784 // Parse the declaration-specifiers (i.e., the type).
785 // FIXME: The type should probably be restricted in some way... Not all
786 // declarators (parts of declarators?) are accepted for parameters.
787 DeclSpec DS(AttrFactory);
788 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
789 DeclSpecContext::DSC_template_param);
791 // Parse this as a typename.
792 Declarator ParamDecl(DS, DeclaratorContext::TemplateParamContext);
793 ParseDeclarator(ParamDecl);
794 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
795 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
799 // Recover from misplaced ellipsis.
800 SourceLocation EllipsisLoc;
801 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
802 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
804 // If there is a default value, parse it.
805 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
806 // we introduce the template parameter into the local scope.
807 SourceLocation EqualLoc;
808 ExprResult DefaultArg;
809 if (TryConsumeToken(tok::equal, EqualLoc)) {
810 // C++ [temp.param]p15:
811 // When parsing a default template-argument for a non-type
812 // template-parameter, the first non-nested > is taken as the
813 // end of the template-parameter-list rather than a greater-than
815 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
816 EnterExpressionEvaluationContext ConstantEvaluated(
817 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
819 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
820 if (DefaultArg.isInvalid())
821 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
824 // Create the parameter.
825 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
826 Depth, Position, EqualLoc,
830 void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
831 SourceLocation CorrectLoc,
832 bool AlreadyHasEllipsis,
833 bool IdentifierHasName) {
835 if (!AlreadyHasEllipsis)
836 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
837 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
838 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
839 << !IdentifierHasName;
842 void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
844 assert(EllipsisLoc.isValid());
845 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
846 if (!AlreadyHasEllipsis)
847 D.setEllipsisLoc(EllipsisLoc);
848 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
849 AlreadyHasEllipsis, D.hasName());
852 /// Parses a '>' at the end of a template list.
854 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
855 /// to determine if these tokens were supposed to be a '>' followed by
856 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
858 /// \param RAngleLoc the location of the consumed '>'.
860 /// \param ConsumeLastToken if true, the '>' is consumed.
862 /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
863 /// type parameter or type argument list, rather than a C++ template parameter
864 /// or argument list.
866 /// \returns true, if current token does not start with '>', false otherwise.
867 bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
868 bool ConsumeLastToken,
869 bool ObjCGenericList) {
870 // What will be left once we've consumed the '>'.
871 tok::TokenKind RemainingToken;
872 const char *ReplacementStr = "> >";
873 bool MergeWithNextToken = false;
875 switch (Tok.getKind()) {
877 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
881 // Determine the location of the '>' token. Only consume this token
882 // if the caller asked us to.
883 RAngleLoc = Tok.getLocation();
884 if (ConsumeLastToken)
888 case tok::greatergreater:
889 RemainingToken = tok::greater;
892 case tok::greatergreatergreater:
893 RemainingToken = tok::greatergreater;
896 case tok::greaterequal:
897 RemainingToken = tok::equal;
898 ReplacementStr = "> =";
900 // Join two adjacent '=' tokens into one, for cases like:
901 // void (*p)() = f<int>;
903 if (NextToken().is(tok::equal) &&
904 areTokensAdjacent(Tok, NextToken())) {
905 RemainingToken = tok::equalequal;
906 MergeWithNextToken = true;
910 case tok::greatergreaterequal:
911 RemainingToken = tok::greaterequal;
915 // This template-id is terminated by a token that starts with a '>'.
916 // Outside C++11 and Objective-C, this is now error recovery.
918 // C++11 allows this when the token is '>>', and in CUDA + C++11 mode, we
919 // extend that treatment to also apply to the '>>>' token.
921 // Objective-C allows this in its type parameter / argument lists.
923 SourceLocation TokBeforeGreaterLoc = PrevTokLocation;
924 SourceLocation TokLoc = Tok.getLocation();
925 Token Next = NextToken();
927 // Whether splitting the current token after the '>' would undesirably result
928 // in the remaining token pasting with the token after it. This excludes the
929 // MergeWithNextToken cases, which we've already handled.
930 bool PreventMergeWithNextToken =
931 (RemainingToken == tok::greater ||
932 RemainingToken == tok::greatergreater) &&
933 (Next.isOneOf(tok::greater, tok::greatergreater,
934 tok::greatergreatergreater, tok::equal, tok::greaterequal,
935 tok::greatergreaterequal, tok::equalequal)) &&
936 areTokensAdjacent(Tok, Next);
938 // Diagnose this situation as appropriate.
939 if (!ObjCGenericList) {
940 // The source range of the replaced token(s).
941 CharSourceRange ReplacementRange = CharSourceRange::getCharRange(
942 TokLoc, Lexer::AdvanceToTokenCharacter(TokLoc, 2, PP.getSourceManager(),
945 // A hint to put a space between the '>>'s. In order to make the hint as
946 // clear as possible, we include the characters either side of the space in
947 // the replacement, rather than just inserting a space at SecondCharLoc.
948 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
951 // A hint to put another space after the token, if it would otherwise be
952 // lexed differently.
954 if (PreventMergeWithNextToken)
955 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
957 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
958 if (getLangOpts().CPlusPlus11 &&
959 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
960 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
961 else if (Tok.is(tok::greaterequal))
962 DiagId = diag::err_right_angle_bracket_equal_needs_space;
963 Diag(TokLoc, DiagId) << Hint1 << Hint2;
966 // Find the "length" of the resulting '>' token. This is not always 1, as it
967 // can contain escaped newlines.
968 unsigned GreaterLength = Lexer::getTokenPrefixLength(
969 TokLoc, 1, PP.getSourceManager(), getLangOpts());
971 // Annotate the source buffer to indicate that we split the token after the
972 // '>'. This allows us to properly find the end of, and extract the spelling
973 // of, the '>' token later.
974 RAngleLoc = PP.SplitToken(TokLoc, GreaterLength);
976 // Strip the initial '>' from the token.
977 bool CachingTokens = PP.IsPreviousCachedToken(Tok);
980 Greater.setLocation(RAngleLoc);
981 Greater.setKind(tok::greater);
982 Greater.setLength(GreaterLength);
984 unsigned OldLength = Tok.getLength();
985 if (MergeWithNextToken) {
987 OldLength += Tok.getLength();
990 Tok.setKind(RemainingToken);
991 Tok.setLength(OldLength - GreaterLength);
993 // Split the second token if lexing it normally would lex a different token
994 // (eg, the fifth token in 'A<B>>>' should re-lex as '>', not '>>').
995 SourceLocation AfterGreaterLoc = TokLoc.getLocWithOffset(GreaterLength);
996 if (PreventMergeWithNextToken)
997 AfterGreaterLoc = PP.SplitToken(AfterGreaterLoc, Tok.getLength());
998 Tok.setLocation(AfterGreaterLoc);
1000 // Update the token cache to match what we just did if necessary.
1001 if (CachingTokens) {
1002 // If the previous cached token is being merged, delete it.
1003 if (MergeWithNextToken)
1004 PP.ReplacePreviousCachedToken({});
1006 if (ConsumeLastToken)
1007 PP.ReplacePreviousCachedToken({Greater, Tok});
1009 PP.ReplacePreviousCachedToken({Greater});
1012 if (ConsumeLastToken) {
1013 PrevTokLocation = RAngleLoc;
1015 PrevTokLocation = TokBeforeGreaterLoc;
1016 PP.EnterToken(Tok, /*IsReinject=*/true);
1024 /// Parses a template-id that after the template name has
1025 /// already been parsed.
1027 /// This routine takes care of parsing the enclosed template argument
1028 /// list ('<' template-parameter-list [opt] '>') and placing the
1029 /// results into a form that can be transferred to semantic analysis.
1031 /// \param ConsumeLastToken if true, then we will consume the last
1032 /// token that forms the template-id. Otherwise, we will leave the
1033 /// last token in the stream (e.g., so that it can be replaced with an
1034 /// annotation token).
1036 Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
1037 SourceLocation &LAngleLoc,
1038 TemplateArgList &TemplateArgs,
1039 SourceLocation &RAngleLoc) {
1040 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
1043 LAngleLoc = ConsumeToken();
1045 // Parse the optional template-argument-list.
1046 bool Invalid = false;
1048 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
1049 if (!Tok.isOneOf(tok::greater, tok::greatergreater,
1050 tok::greatergreatergreater, tok::greaterequal,
1051 tok::greatergreaterequal))
1052 Invalid = ParseTemplateArgumentList(TemplateArgs);
1055 // Try to find the closing '>'.
1056 if (ConsumeLastToken)
1057 SkipUntil(tok::greater, StopAtSemi);
1059 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
1064 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
1065 /*ObjCGenericList=*/false);
1068 /// Replace the tokens that form a simple-template-id with an
1069 /// annotation token containing the complete template-id.
1071 /// The first token in the stream must be the name of a template that
1072 /// is followed by a '<'. This routine will parse the complete
1073 /// simple-template-id and replace the tokens with a single annotation
1074 /// token with one of two different kinds: if the template-id names a
1075 /// type (and \p AllowTypeAnnotation is true), the annotation token is
1076 /// a type annotation that includes the optional nested-name-specifier
1077 /// (\p SS). Otherwise, the annotation token is a template-id
1078 /// annotation that does not include the optional
1079 /// nested-name-specifier.
1081 /// \param Template the declaration of the template named by the first
1082 /// token (an identifier), as returned from \c Action::isTemplateName().
1084 /// \param TNK the kind of template that \p Template
1085 /// refers to, as returned from \c Action::isTemplateName().
1087 /// \param SS if non-NULL, the nested-name-specifier that precedes
1088 /// this template name.
1090 /// \param TemplateKWLoc if valid, specifies that this template-id
1091 /// annotation was preceded by the 'template' keyword and gives the
1092 /// location of that keyword. If invalid (the default), then this
1093 /// template-id was not preceded by a 'template' keyword.
1095 /// \param AllowTypeAnnotation if true (the default), then a
1096 /// simple-template-id that refers to a class template, template
1097 /// template parameter, or other template that produces a type will be
1098 /// replaced with a type annotation token. Otherwise, the
1099 /// simple-template-id is always replaced with a template-id
1100 /// annotation token.
1102 /// If an unrecoverable parse error occurs and no annotation token can be
1103 /// formed, this function returns true.
1105 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
1107 SourceLocation TemplateKWLoc,
1108 UnqualifiedId &TemplateName,
1109 bool AllowTypeAnnotation) {
1110 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
1111 assert(Template && Tok.is(tok::less) &&
1112 "Parser isn't at the beginning of a template-id");
1114 // Consume the template-name.
1115 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
1117 // Parse the enclosed template argument list.
1118 SourceLocation LAngleLoc, RAngleLoc;
1119 TemplateArgList TemplateArgs;
1120 bool Invalid = ParseTemplateIdAfterTemplateName(false, LAngleLoc,
1125 // If we failed to parse the template ID but skipped ahead to a >, we're not
1126 // going to be able to form a token annotation. Eat the '>' if present.
1127 TryConsumeToken(tok::greater);
1128 // FIXME: Annotate the token stream so we don't produce the same errors
1129 // again if we're doing this annotation as part of a tentative parse.
1133 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1135 // Build the annotation token.
1136 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
1137 TypeResult Type = Actions.ActOnTemplateIdType(
1138 getCurScope(), SS, TemplateKWLoc, Template, TemplateName.Identifier,
1139 TemplateNameLoc, LAngleLoc, TemplateArgsPtr, RAngleLoc);
1140 if (Type.isInvalid()) {
1141 // If we failed to parse the template ID but skipped ahead to a >, we're
1142 // not going to be able to form a token annotation. Eat the '>' if
1144 TryConsumeToken(tok::greater);
1145 // FIXME: Annotate the token stream so we don't produce the same errors
1146 // again if we're doing this annotation as part of a tentative parse.
1150 Tok.setKind(tok::annot_typename);
1151 setTypeAnnotation(Tok, Type.get());
1152 if (SS.isNotEmpty())
1153 Tok.setLocation(SS.getBeginLoc());
1154 else if (TemplateKWLoc.isValid())
1155 Tok.setLocation(TemplateKWLoc);
1157 Tok.setLocation(TemplateNameLoc);
1159 // Build a template-id annotation token that can be processed
1161 Tok.setKind(tok::annot_template_id);
1163 IdentifierInfo *TemplateII =
1164 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1165 ? TemplateName.Identifier
1168 OverloadedOperatorKind OpKind =
1169 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1171 : TemplateName.OperatorFunctionId.Operator;
1173 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
1174 SS, TemplateKWLoc, TemplateNameLoc, TemplateII, OpKind, Template, TNK,
1175 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
1177 Tok.setAnnotationValue(TemplateId);
1178 if (TemplateKWLoc.isValid())
1179 Tok.setLocation(TemplateKWLoc);
1181 Tok.setLocation(TemplateNameLoc);
1184 // Common fields for the annotation token
1185 Tok.setAnnotationEndLoc(RAngleLoc);
1187 // In case the tokens were cached, have Preprocessor replace them with the
1188 // annotation token.
1189 PP.AnnotateCachedTokens(Tok);
1193 /// Replaces a template-id annotation token with a type
1194 /// annotation token.
1196 /// If there was a failure when forming the type from the template-id,
1197 /// a type annotation token will still be created, but will have a
1198 /// NULL type pointer to signify an error.
1200 /// \param IsClassName Is this template-id appearing in a context where we
1201 /// know it names a class, such as in an elaborated-type-specifier or
1202 /// base-specifier? ('typename' and 'template' are unneeded and disallowed
1203 /// in those contexts.)
1204 void Parser::AnnotateTemplateIdTokenAsType(bool IsClassName) {
1205 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1207 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1208 assert((TemplateId->Kind == TNK_Type_template ||
1209 TemplateId->Kind == TNK_Dependent_template_name ||
1210 TemplateId->Kind == TNK_Undeclared_template) &&
1211 "Only works for type and dependent templates");
1213 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1214 TemplateId->NumArgs);
1217 = Actions.ActOnTemplateIdType(getCurScope(),
1219 TemplateId->TemplateKWLoc,
1220 TemplateId->Template,
1222 TemplateId->TemplateNameLoc,
1223 TemplateId->LAngleLoc,
1225 TemplateId->RAngleLoc,
1226 /*IsCtorOrDtorName*/false,
1228 // Create the new "type" annotation token.
1229 Tok.setKind(tok::annot_typename);
1230 setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
1231 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1232 Tok.setLocation(TemplateId->SS.getBeginLoc());
1233 // End location stays the same
1235 // Replace the template-id annotation token, and possible the scope-specifier
1236 // that precedes it, with the typename annotation token.
1237 PP.AnnotateCachedTokens(Tok);
1240 /// Determine whether the given token can end a template argument.
1241 static bool isEndOfTemplateArgument(Token Tok) {
1242 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
1245 /// Parse a C++ template template argument.
1246 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1247 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1248 !Tok.is(tok::annot_cxxscope))
1249 return ParsedTemplateArgument();
1251 // C++0x [temp.arg.template]p1:
1252 // A template-argument for a template template-parameter shall be the name
1253 // of a class template or an alias template, expressed as id-expression.
1255 // We parse an id-expression that refers to a class template or alias
1256 // template. The grammar we parse is:
1258 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1260 // followed by a token that terminates a template argument, such as ',',
1261 // '>', or (in some cases) '>>'.
1262 CXXScopeSpec SS; // nested-name-specifier, if present
1263 ParseOptionalCXXScopeSpecifier(SS, nullptr,
1264 /*EnteringContext=*/false);
1266 ParsedTemplateArgument Result;
1267 SourceLocation EllipsisLoc;
1268 if (SS.isSet() && Tok.is(tok::kw_template)) {
1269 // Parse the optional 'template' keyword following the
1270 // nested-name-specifier.
1271 SourceLocation TemplateKWLoc = ConsumeToken();
1273 if (Tok.is(tok::identifier)) {
1274 // We appear to have a dependent template name.
1276 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1277 ConsumeToken(); // the identifier
1279 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1281 // If the next token signals the end of a template argument,
1282 // then we have a dependent template name that could be a template
1283 // template argument.
1284 TemplateTy Template;
1285 if (isEndOfTemplateArgument(Tok) &&
1286 Actions.ActOnDependentTemplateName(
1287 getCurScope(), SS, TemplateKWLoc, Name,
1288 /*ObjectType=*/nullptr,
1289 /*EnteringContext=*/false, Template))
1290 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1292 } else if (Tok.is(tok::identifier)) {
1293 // We may have a (non-dependent) template name.
1294 TemplateTy Template;
1296 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1297 ConsumeToken(); // the identifier
1299 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1301 if (isEndOfTemplateArgument(Tok)) {
1302 bool MemberOfUnknownSpecialization;
1303 TemplateNameKind TNK = Actions.isTemplateName(
1305 /*hasTemplateKeyword=*/false, Name,
1306 /*ObjectType=*/nullptr,
1307 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
1308 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1309 // We have an id-expression that refers to a class template or
1310 // (C++0x) alias template.
1311 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1316 // If this is a pack expansion, build it as such.
1317 if (EllipsisLoc.isValid() && !Result.isInvalid())
1318 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1323 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1325 /// template-argument: [C++ 14.2]
1326 /// constant-expression
1329 ParsedTemplateArgument Parser::ParseTemplateArgument() {
1330 // C++ [temp.arg]p2:
1331 // In a template-argument, an ambiguity between a type-id and an
1332 // expression is resolved to a type-id, regardless of the form of
1333 // the corresponding template-parameter.
1335 // Therefore, we initially try to parse a type-id - and isCXXTypeId might look
1336 // up and annotate an identifier as an id-expression during disambiguation,
1337 // so enter the appropriate context for a constant expression template
1338 // argument before trying to disambiguate.
1340 EnterExpressionEvaluationContext EnterConstantEvaluated(
1341 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated,
1342 /*LambdaContextDecl=*/nullptr,
1343 /*ExprContext=*/Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
1344 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1345 TypeResult TypeArg = ParseTypeName(
1346 /*Range=*/nullptr, DeclaratorContext::TemplateArgContext);
1347 return Actions.ActOnTemplateTypeArgument(TypeArg);
1350 // Try to parse a template template argument.
1352 TentativeParsingAction TPA(*this);
1354 ParsedTemplateArgument TemplateTemplateArgument
1355 = ParseTemplateTemplateArgument();
1356 if (!TemplateTemplateArgument.isInvalid()) {
1358 return TemplateTemplateArgument;
1361 // Revert this tentative parse to parse a non-type template argument.
1365 // Parse a non-type template argument.
1366 SourceLocation Loc = Tok.getLocation();
1367 ExprResult ExprArg = ParseConstantExpressionInExprEvalContext(MaybeTypeCast);
1368 if (ExprArg.isInvalid() || !ExprArg.get())
1369 return ParsedTemplateArgument();
1371 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1372 ExprArg.get(), Loc);
1375 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1376 /// (C++ [temp.names]). Returns true if there was an error.
1378 /// template-argument-list: [C++ 14.2]
1379 /// template-argument
1380 /// template-argument-list ',' template-argument
1382 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1384 ColonProtectionRAIIObject ColonProtection(*this, false);
1387 ParsedTemplateArgument Arg = ParseTemplateArgument();
1388 SourceLocation EllipsisLoc;
1389 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1390 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1392 if (Arg.isInvalid()) {
1393 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
1397 // Save this template argument.
1398 TemplateArgs.push_back(Arg);
1400 // If the next token is a comma, consume it and keep reading
1402 } while (TryConsumeToken(tok::comma));
1407 /// Parse a C++ explicit template instantiation
1408 /// (C++ [temp.explicit]).
1410 /// explicit-instantiation:
1411 /// 'extern' [opt] 'template' declaration
1413 /// Note that the 'extern' is a GNU extension and C++11 feature.
1414 Decl *Parser::ParseExplicitInstantiation(DeclaratorContext Context,
1415 SourceLocation ExternLoc,
1416 SourceLocation TemplateLoc,
1417 SourceLocation &DeclEnd,
1418 ParsedAttributes &AccessAttrs,
1419 AccessSpecifier AS) {
1420 // This isn't really required here.
1421 ParsingDeclRAIIObject
1422 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1424 return ParseSingleDeclarationAfterTemplate(
1425 Context, ParsedTemplateInfo(ExternLoc, TemplateLoc),
1426 ParsingTemplateParams, DeclEnd, AccessAttrs, AS);
1429 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1431 return getTemplateParamsRange(TemplateParams->data(),
1432 TemplateParams->size());
1434 SourceRange R(TemplateLoc);
1435 if (ExternLoc.isValid())
1436 R.setBegin(ExternLoc);
1440 void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1441 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1444 /// Late parse a C++ function template in Microsoft mode.
1445 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1449 // Get the FunctionDecl.
1450 FunctionDecl *FunD = LPT.D->getAsFunction();
1451 // Track template parameter depth.
1452 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1454 // To restore the context after late parsing.
1455 Sema::ContextRAII GlobalSavedContext(
1456 Actions, Actions.Context.getTranslationUnitDecl());
1458 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1460 // Get the list of DeclContexts to reenter. For inline methods, we only want
1461 // to push the DeclContext of the outermost class. This matches the way the
1462 // parser normally parses bodies of inline methods when the outermost class is
1464 struct ContainingDC {
1465 ContainingDC(DeclContext *DC, bool ShouldPush) : Pair(DC, ShouldPush) {}
1466 llvm::PointerIntPair<DeclContext *, 1, bool> Pair;
1467 DeclContext *getDC() { return Pair.getPointer(); }
1468 bool shouldPushDC() { return Pair.getInt(); }
1470 SmallVector<ContainingDC, 4> DeclContextsToReenter;
1471 DeclContext *DD = FunD;
1472 DeclContext *NextContaining = Actions.getContainingDC(DD);
1473 while (DD && !DD->isTranslationUnit()) {
1474 bool ShouldPush = DD == NextContaining;
1475 DeclContextsToReenter.push_back({DD, ShouldPush});
1477 NextContaining = Actions.getContainingDC(DD);
1478 DD = DD->getLexicalParent();
1481 // Reenter template scopes from outermost to innermost.
1482 for (ContainingDC CDC : reverse(DeclContextsToReenter)) {
1483 TemplateParamScopeStack.push_back(
1484 new ParseScope(this, Scope::TemplateParamScope));
1485 unsigned NumParamLists = Actions.ActOnReenterTemplateScope(
1486 getCurScope(), cast<Decl>(CDC.getDC()));
1487 CurTemplateDepthTracker.addDepth(NumParamLists);
1488 if (CDC.shouldPushDC()) {
1489 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1490 Actions.PushDeclContext(Actions.getCurScope(), CDC.getDC());
1494 assert(!LPT.Toks.empty() && "Empty body!");
1496 // Append the current token at the end of the new token stream so that it
1497 // doesn't get lost.
1498 LPT.Toks.push_back(Tok);
1499 PP.EnterTokenStream(LPT.Toks, true, /*IsReinject*/true);
1501 // Consume the previously pushed token.
1502 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1503 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1504 "Inline method not starting with '{', ':' or 'try'");
1506 // Parse the method body. Function body parsing code is similar enough
1507 // to be re-used for method bodies as well.
1508 ParseScope FnScope(this, Scope::FnScope | Scope::DeclScope |
1509 Scope::CompoundStmtScope);
1511 // Recreate the containing function DeclContext.
1512 Sema::ContextRAII FunctionSavedContext(Actions,
1513 Actions.getContainingDC(FunD));
1515 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1517 if (Tok.is(tok::kw_try)) {
1518 ParseFunctionTryBlock(LPT.D, FnScope);
1520 if (Tok.is(tok::colon))
1521 ParseConstructorInitializer(LPT.D);
1523 Actions.ActOnDefaultCtorInitializers(LPT.D);
1525 if (Tok.is(tok::l_brace)) {
1526 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1527 cast<FunctionTemplateDecl>(LPT.D)
1528 ->getTemplateParameters()
1529 ->getDepth() == TemplateParameterDepth - 1) &&
1530 "TemplateParameterDepth should be greater than the depth of "
1531 "current template being instantiated!");
1532 ParseFunctionStatementBody(LPT.D, FnScope);
1533 Actions.UnmarkAsLateParsedTemplate(FunD);
1535 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1540 SmallVectorImpl<ParseScope *>::reverse_iterator I =
1541 TemplateParamScopeStack.rbegin();
1542 for (; I != TemplateParamScopeStack.rend(); ++I)
1546 /// Lex a delayed template function for late parsing.
1547 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1548 tok::TokenKind kind = Tok.getKind();
1549 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1550 // Consume everything up to (and including) the matching right brace.
1551 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1554 // If we're in a function-try-block, we need to store all the catch blocks.
1555 if (kind == tok::kw_try) {
1556 while (Tok.is(tok::kw_catch)) {
1557 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1558 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1563 /// We've parsed something that could plausibly be intended to be a template
1564 /// name (\p LHS) followed by a '<' token, and the following code can't possibly
1565 /// be an expression. Determine if this is likely to be a template-id and if so,
1567 bool Parser::diagnoseUnknownTemplateId(ExprResult LHS, SourceLocation Less) {
1568 TentativeParsingAction TPA(*this);
1569 // FIXME: We could look at the token sequence in a lot more detail here.
1570 if (SkipUntil(tok::greater, tok::greatergreater, tok::greatergreatergreater,
1571 StopAtSemi | StopBeforeMatch)) {
1574 SourceLocation Greater;
1575 ParseGreaterThanInTemplateList(Greater, true, false);
1576 Actions.diagnoseExprIntendedAsTemplateName(getCurScope(), LHS,
1581 // There's no matching '>' token, this probably isn't supposed to be
1582 // interpreted as a template-id. Parse it as an (ill-formed) comparison.
1587 void Parser::checkPotentialAngleBracket(ExprResult &PotentialTemplateName) {
1588 assert(Tok.is(tok::less) && "not at a potential angle bracket");
1590 bool DependentTemplateName = false;
1591 if (!Actions.mightBeIntendedToBeTemplateName(PotentialTemplateName,
1592 DependentTemplateName))
1595 // OK, this might be a name that the user intended to be parsed as a
1596 // template-name, followed by a '<' token. Check for some easy cases.
1598 // If we have potential_template<>, then it's supposed to be a template-name.
1599 if (NextToken().is(tok::greater) ||
1600 (getLangOpts().CPlusPlus11 &&
1601 NextToken().isOneOf(tok::greatergreater, tok::greatergreatergreater))) {
1602 SourceLocation Less = ConsumeToken();
1603 SourceLocation Greater;
1604 ParseGreaterThanInTemplateList(Greater, true, false);
1605 Actions.diagnoseExprIntendedAsTemplateName(
1606 getCurScope(), PotentialTemplateName, Less, Greater);
1607 // FIXME: Perform error recovery.
1608 PotentialTemplateName = ExprError();
1612 // If we have 'potential_template<type-id', assume it's supposed to be a
1613 // template-name if there's a matching '>' later on.
1615 // FIXME: Avoid the tentative parse when NextToken() can't begin a type.
1616 TentativeParsingAction TPA(*this);
1617 SourceLocation Less = ConsumeToken();
1618 if (isTypeIdUnambiguously() &&
1619 diagnoseUnknownTemplateId(PotentialTemplateName, Less)) {
1621 // FIXME: Perform error recovery.
1622 PotentialTemplateName = ExprError();
1628 // Otherwise, remember that we saw this in case we see a potentially-matching
1629 // '>' token later on.
1630 AngleBracketTracker::Priority Priority =
1631 (DependentTemplateName ? AngleBracketTracker::DependentName
1632 : AngleBracketTracker::PotentialTypo) |
1633 (Tok.hasLeadingSpace() ? AngleBracketTracker::SpaceBeforeLess
1634 : AngleBracketTracker::NoSpaceBeforeLess);
1635 AngleBrackets.add(*this, PotentialTemplateName.get(), Tok.getLocation(),
1639 bool Parser::checkPotentialAngleBracketDelimiter(
1640 const AngleBracketTracker::Loc &LAngle, const Token &OpToken) {
1641 // If a comma in an expression context is followed by a type that can be a
1642 // template argument and cannot be an expression, then this is ill-formed,
1643 // but might be intended to be part of a template-id.
1644 if (OpToken.is(tok::comma) && isTypeIdUnambiguously() &&
1645 diagnoseUnknownTemplateId(LAngle.TemplateName, LAngle.LessLoc)) {
1646 AngleBrackets.clear(*this);
1650 // If a context that looks like a template-id is followed by '()', then
1651 // this is ill-formed, but might be intended to be a template-id
1652 // followed by '()'.
1653 if (OpToken.is(tok::greater) && Tok.is(tok::l_paren) &&
1654 NextToken().is(tok::r_paren)) {
1655 Actions.diagnoseExprIntendedAsTemplateName(
1656 getCurScope(), LAngle.TemplateName, LAngle.LessLoc,
1657 OpToken.getLocation());
1658 AngleBrackets.clear(*this);
1662 // After a '>' (etc), we're no longer potentially in a construct that's
1663 // intended to be treated as a template-id.
1664 if (OpToken.is(tok::greater) ||
1665 (getLangOpts().CPlusPlus11 &&
1666 OpToken.isOneOf(tok::greatergreater, tok::greatergreatergreater)))
1667 AngleBrackets.clear(*this);