1 //===--- ParseTemplate.cpp - Template Parsing -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements parsing of C++ templates.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/Parse/ParseDiagnostic.h"
20 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/ParsedTemplate.h"
22 #include "clang/Sema/Scope.h"
23 using namespace clang;
25 /// \brief Parse a template declaration, explicit instantiation, or
26 /// explicit specialization.
28 Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
29 SourceLocation &DeclEnd,
31 AttributeList *AccessAttrs) {
32 ObjCDeclContextSwitch ObjCDC(*this);
34 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
35 return ParseExplicitInstantiation(Context,
36 SourceLocation(), ConsumeToken(),
39 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
45 /// \brief Parse a template declaration or an explicit specialization.
47 /// Template declarations include one or more template parameter lists
48 /// and either the function or class template declaration. Explicit
49 /// specializations contain one or more 'template < >' prefixes
50 /// followed by a (possibly templated) declaration. Since the
51 /// syntactic form of both features is nearly identical, we parse all
52 /// of the template headers together and let semantic analysis sort
53 /// the declarations from the explicit specializations.
55 /// template-declaration: [C++ temp]
56 /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
58 /// explicit-specialization: [ C++ temp.expl.spec]
59 /// 'template' '<' '>' declaration
61 Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
62 SourceLocation &DeclEnd,
64 AttributeList *AccessAttrs) {
65 assert(Tok.isOneOf(tok::kw_export, tok::kw_template) &&
66 "Token does not start a template declaration.");
68 // Enter template-parameter scope.
69 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
71 // Tell the action that names should be checked in the context of
72 // the declaration to come.
74 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
76 // Parse multiple levels of template headers within this template
77 // parameter scope, e.g.,
79 // template<typename T>
80 // template<typename U>
81 // class A<T>::B { ... };
83 // We parse multiple levels non-recursively so that we can build a
84 // single data structure containing all of the template parameter
85 // lists to easily differentiate between the case above and:
87 // template<typename T>
89 // template<typename U> class B;
92 // In the first case, the action for declaring A<T>::B receives
93 // both template parameter lists. In the second case, the action for
94 // defining A<T>::B receives just the inner template parameter list
95 // (and retrieves the outer template parameter list from its
97 bool isSpecialization = true;
98 bool LastParamListWasEmpty = false;
99 TemplateParameterLists ParamLists;
100 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
103 // Consume the 'export', if any.
104 SourceLocation ExportLoc;
105 TryConsumeToken(tok::kw_export, ExportLoc);
107 // Consume the 'template', which should be here.
108 SourceLocation TemplateLoc;
109 if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
110 Diag(Tok.getLocation(), diag::err_expected_template);
114 // Parse the '<' template-parameter-list '>'
115 SourceLocation LAngleLoc, RAngleLoc;
116 SmallVector<Decl*, 4> TemplateParams;
117 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
118 TemplateParams, LAngleLoc, RAngleLoc)) {
119 // Skip until the semi-colon or a '}'.
120 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
121 TryConsumeToken(tok::semi);
125 ParamLists.push_back(
126 Actions.ActOnTemplateParameterList(CurTemplateDepthTracker.getDepth(),
128 TemplateLoc, LAngleLoc,
129 TemplateParams, RAngleLoc));
131 if (!TemplateParams.empty()) {
132 isSpecialization = false;
133 ++CurTemplateDepthTracker;
135 if (TryConsumeToken(tok::kw_requires)) {
137 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
138 if (!ER.isUsable()) {
139 // Skip until the semi-colon or a '}'.
140 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
141 TryConsumeToken(tok::semi);
146 LastParamListWasEmpty = true;
148 } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
150 // Parse the actual template declaration.
151 return ParseSingleDeclarationAfterTemplate(Context,
152 ParsedTemplateInfo(&ParamLists,
154 LastParamListWasEmpty),
155 ParsingTemplateParams,
156 DeclEnd, AS, AccessAttrs);
159 /// \brief Parse a single declaration that declares a template,
160 /// template specialization, or explicit instantiation of a template.
162 /// \param DeclEnd will receive the source location of the last token
163 /// within this declaration.
165 /// \param AS the access specifier associated with this
166 /// declaration. Will be AS_none for namespace-scope declarations.
168 /// \returns the new declaration.
170 Parser::ParseSingleDeclarationAfterTemplate(
172 const ParsedTemplateInfo &TemplateInfo,
173 ParsingDeclRAIIObject &DiagsFromTParams,
174 SourceLocation &DeclEnd,
176 AttributeList *AccessAttrs) {
177 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
178 "Template information required");
180 if (Tok.is(tok::kw_static_assert)) {
181 // A static_assert declaration may not be templated.
182 Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
183 << TemplateInfo.getSourceRange();
184 // Parse the static_assert declaration to improve error recovery.
185 return ParseStaticAssertDeclaration(DeclEnd);
188 if (Context == Declarator::MemberContext) {
189 // We are parsing a member template.
190 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
195 ParsedAttributesWithRange prefixAttrs(AttrFactory);
196 MaybeParseCXX11Attributes(prefixAttrs);
198 if (Tok.is(tok::kw_using))
199 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
202 // Parse the declaration specifiers, stealing any diagnostics from
203 // the template parameters.
204 ParsingDeclSpec DS(*this, &DiagsFromTParams);
206 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
207 getDeclSpecContextFromDeclaratorContext(Context));
209 if (Tok.is(tok::semi)) {
210 ProhibitAttributes(prefixAttrs);
211 DeclEnd = ConsumeToken();
212 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
213 getCurScope(), AS, DS,
214 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
215 : MultiTemplateParamsArg(),
216 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation);
221 // Move the attributes from the prefix into the DS.
222 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
223 ProhibitAttributes(prefixAttrs);
225 DS.takeAttributesFrom(prefixAttrs);
227 // Parse the declarator.
228 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
229 ParseDeclarator(DeclaratorInfo);
230 // Error parsing the declarator?
231 if (!DeclaratorInfo.hasName()) {
232 // If so, skip until the semi-colon or a }.
233 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
234 if (Tok.is(tok::semi))
239 LateParsedAttrList LateParsedAttrs(true);
240 if (DeclaratorInfo.isFunctionDeclarator())
241 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
243 if (DeclaratorInfo.isFunctionDeclarator() &&
244 isStartOfFunctionDefinition(DeclaratorInfo)) {
246 // Function definitions are only allowed at file scope and in C++ classes.
247 // The C++ inline method definition case is handled elsewhere, so we only
248 // need to handle the file scope definition case.
249 if (Context != Declarator::FileContext) {
250 Diag(Tok, diag::err_function_definition_not_allowed);
255 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
256 // Recover by ignoring the 'typedef'. This was probably supposed to be
257 // the 'typename' keyword, which we should have already suggested adding
258 // if it's appropriate.
259 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
260 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
261 DS.ClearStorageClassSpecs();
264 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
265 if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
266 // If the declarator-id is not a template-id, issue a diagnostic and
267 // recover by ignoring the 'template' keyword.
268 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
269 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
272 SourceLocation LAngleLoc
273 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
274 Diag(DeclaratorInfo.getIdentifierLoc(),
275 diag::err_explicit_instantiation_with_definition)
276 << SourceRange(TemplateInfo.TemplateLoc)
277 << FixItHint::CreateInsertion(LAngleLoc, "<>");
279 // Recover as if it were an explicit specialization.
280 TemplateParameterLists FakedParamLists;
281 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
282 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
285 return ParseFunctionDefinition(
286 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
287 /*isSpecialization=*/true,
288 /*LastParamListWasEmpty=*/true),
292 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
296 // Parse this declaration.
297 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
300 if (Tok.is(tok::comma)) {
301 Diag(Tok, diag::err_multiple_template_declarators)
302 << (int)TemplateInfo.Kind;
303 SkipUntil(tok::semi);
307 // Eat the semi colon after the declaration.
308 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
309 if (LateParsedAttrs.size() > 0)
310 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
311 DeclaratorInfo.complete(ThisDecl);
315 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
316 /// angle brackets. Depth is the depth of this template-parameter-list, which
317 /// is the number of template headers directly enclosing this template header.
318 /// TemplateParams is the current list of template parameters we're building.
319 /// The template parameter we parse will be added to this list. LAngleLoc and
320 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
321 /// that enclose this template parameter list.
323 /// \returns true if an error occurred, false otherwise.
324 bool Parser::ParseTemplateParameters(unsigned Depth,
325 SmallVectorImpl<Decl*> &TemplateParams,
326 SourceLocation &LAngleLoc,
327 SourceLocation &RAngleLoc) {
328 // Get the template parameter list.
329 if (!TryConsumeToken(tok::less, LAngleLoc)) {
330 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
334 // Try to parse the template parameter list.
336 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
337 Failed = ParseTemplateParameterList(Depth, TemplateParams);
339 if (Tok.is(tok::greatergreater)) {
340 // No diagnostic required here: a template-parameter-list can only be
341 // followed by a declaration or, for a template template parameter, the
342 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
343 // This matters for elegant diagnosis of:
344 // template<template<typename>> struct S;
345 Tok.setKind(tok::greater);
346 RAngleLoc = Tok.getLocation();
347 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
348 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
349 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
355 /// ParseTemplateParameterList - Parse a template parameter list. If
356 /// the parsing fails badly (i.e., closing bracket was left out), this
357 /// will try to put the token stream in a reasonable position (closing
358 /// a statement, etc.) and return false.
360 /// template-parameter-list: [C++ temp]
361 /// template-parameter
362 /// template-parameter-list ',' template-parameter
364 Parser::ParseTemplateParameterList(unsigned Depth,
365 SmallVectorImpl<Decl*> &TemplateParams) {
368 = ParseTemplateParameter(Depth, TemplateParams.size())) {
369 TemplateParams.push_back(TmpParam);
371 // If we failed to parse a template parameter, skip until we find
372 // a comma or closing brace.
373 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
374 StopAtSemi | StopBeforeMatch);
377 // Did we find a comma or the end of the template parameter list?
378 if (Tok.is(tok::comma)) {
380 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
381 // Don't consume this... that's done by template parser.
384 // Somebody probably forgot to close the template. Skip ahead and
385 // try to get out of the expression. This error is currently
386 // subsumed by whatever goes on in ParseTemplateParameter.
387 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
388 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
389 StopAtSemi | StopBeforeMatch);
396 /// \brief Determine whether the parser is at the start of a template
398 bool Parser::isStartOfTemplateTypeParameter() {
399 if (Tok.is(tok::kw_class)) {
400 // "class" may be the start of an elaborated-type-specifier or a
401 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
402 switch (NextToken().getKind()) {
406 case tok::greatergreater:
410 case tok::identifier:
411 // This may be either a type-parameter or an elaborated-type-specifier.
412 // We have to look further.
419 switch (GetLookAheadToken(2).getKind()) {
423 case tok::greatergreater:
431 if (Tok.isNot(tok::kw_typename))
434 // C++ [temp.param]p2:
435 // There is no semantic difference between class and typename in a
436 // template-parameter. typename followed by an unqualified-id
437 // names a template type parameter. typename followed by a
438 // qualified-id denotes the type in a non-type
439 // parameter-declaration.
440 Token Next = NextToken();
442 // If we have an identifier, skip over it.
443 if (Next.getKind() == tok::identifier)
444 Next = GetLookAheadToken(2);
446 switch (Next.getKind()) {
450 case tok::greatergreater:
459 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
461 /// template-parameter: [C++ temp.param]
463 /// parameter-declaration
465 /// type-parameter: (see below)
466 /// 'class' ...[opt] identifier[opt]
467 /// 'class' identifier[opt] '=' type-id
468 /// 'typename' ...[opt] identifier[opt]
469 /// 'typename' identifier[opt] '=' type-id
470 /// 'template' '<' template-parameter-list '>'
471 /// 'class' ...[opt] identifier[opt]
472 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
474 Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
475 if (isStartOfTemplateTypeParameter())
476 return ParseTypeParameter(Depth, Position);
478 if (Tok.is(tok::kw_template))
479 return ParseTemplateTemplateParameter(Depth, Position);
481 // If it's none of the above, then it must be a parameter declaration.
482 // NOTE: This will pick up errors in the closure of the template parameter
483 // list (e.g., template < ; Check here to implement >> style closures.
484 return ParseNonTypeTemplateParameter(Depth, Position);
487 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
488 /// Other kinds of template parameters are parsed in
489 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
491 /// type-parameter: [C++ temp.param]
492 /// 'class' ...[opt][C++0x] identifier[opt]
493 /// 'class' identifier[opt] '=' type-id
494 /// 'typename' ...[opt][C++0x] identifier[opt]
495 /// 'typename' identifier[opt] '=' type-id
496 Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
497 assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
498 "A type-parameter starts with 'class' or 'typename'");
500 // Consume the 'class' or 'typename' keyword.
501 bool TypenameKeyword = Tok.is(tok::kw_typename);
502 SourceLocation KeyLoc = ConsumeToken();
504 // Grab the ellipsis (if given).
505 SourceLocation EllipsisLoc;
506 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
508 getLangOpts().CPlusPlus11
509 ? diag::warn_cxx98_compat_variadic_templates
510 : diag::ext_variadic_templates);
513 // Grab the template parameter name (if given)
514 SourceLocation NameLoc;
515 IdentifierInfo *ParamName = nullptr;
516 if (Tok.is(tok::identifier)) {
517 ParamName = Tok.getIdentifierInfo();
518 NameLoc = ConsumeToken();
519 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
520 tok::greatergreater)) {
521 // Unnamed template parameter. Don't have to do anything here, just
522 // don't consume this token.
524 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
528 // Recover from misplaced ellipsis.
529 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
530 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
531 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
533 // Grab a default argument (if available).
534 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
535 // we introduce the type parameter into the local scope.
536 SourceLocation EqualLoc;
537 ParsedType DefaultArg;
538 if (TryConsumeToken(tok::equal, EqualLoc))
539 DefaultArg = ParseTypeName(/*Range=*/nullptr,
540 Declarator::TemplateTypeArgContext).get();
542 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
543 KeyLoc, ParamName, NameLoc, Depth, Position,
544 EqualLoc, DefaultArg);
547 /// ParseTemplateTemplateParameter - Handle the parsing of template
548 /// template parameters.
550 /// type-parameter: [C++ temp.param]
551 /// 'template' '<' template-parameter-list '>' type-parameter-key
552 /// ...[opt] identifier[opt]
553 /// 'template' '<' template-parameter-list '>' type-parameter-key
554 /// identifier[opt] = id-expression
555 /// type-parameter-key:
557 /// 'typename' [C++1z]
559 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
560 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
562 // Handle the template <...> part.
563 SourceLocation TemplateLoc = ConsumeToken();
564 SmallVector<Decl*,8> TemplateParams;
565 SourceLocation LAngleLoc, RAngleLoc;
567 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
568 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
574 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
575 // Generate a meaningful error if the user forgot to put class before the
576 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
577 // or greater appear immediately or after 'struct'. In the latter case,
578 // replace the keyword with 'class'.
579 if (!TryConsumeToken(tok::kw_class)) {
580 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
581 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
582 if (Tok.is(tok::kw_typename)) {
583 Diag(Tok.getLocation(),
584 getLangOpts().CPlusPlus1z
585 ? diag::warn_cxx14_compat_template_template_param_typename
586 : diag::ext_template_template_param_typename)
587 << (!getLangOpts().CPlusPlus1z
588 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
590 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
591 tok::greatergreater, tok::ellipsis)) {
592 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
593 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
594 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
596 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
602 // Parse the ellipsis, if given.
603 SourceLocation EllipsisLoc;
604 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
606 getLangOpts().CPlusPlus11
607 ? diag::warn_cxx98_compat_variadic_templates
608 : diag::ext_variadic_templates);
610 // Get the identifier, if given.
611 SourceLocation NameLoc;
612 IdentifierInfo *ParamName = nullptr;
613 if (Tok.is(tok::identifier)) {
614 ParamName = Tok.getIdentifierInfo();
615 NameLoc = ConsumeToken();
616 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
617 tok::greatergreater)) {
618 // Unnamed template parameter. Don't have to do anything here, just
619 // don't consume this token.
621 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
625 // Recover from misplaced ellipsis.
626 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
627 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
628 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
630 TemplateParameterList *ParamList =
631 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
632 TemplateLoc, LAngleLoc,
636 // Grab a default argument (if available).
637 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
638 // we introduce the template parameter into the local scope.
639 SourceLocation EqualLoc;
640 ParsedTemplateArgument DefaultArg;
641 if (TryConsumeToken(tok::equal, EqualLoc)) {
642 DefaultArg = ParseTemplateTemplateArgument();
643 if (DefaultArg.isInvalid()) {
644 Diag(Tok.getLocation(),
645 diag::err_default_template_template_parameter_not_template);
646 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
647 StopAtSemi | StopBeforeMatch);
651 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
652 ParamList, EllipsisLoc,
653 ParamName, NameLoc, Depth,
654 Position, EqualLoc, DefaultArg);
657 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
658 /// template parameters (e.g., in "template<int Size> class array;").
660 /// template-parameter:
662 /// parameter-declaration
664 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
665 // Parse the declaration-specifiers (i.e., the type).
666 // FIXME: The type should probably be restricted in some way... Not all
667 // declarators (parts of declarators?) are accepted for parameters.
668 DeclSpec DS(AttrFactory);
669 ParseDeclarationSpecifiers(DS);
671 // Parse this as a typename.
672 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
673 ParseDeclarator(ParamDecl);
674 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
675 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
679 // Recover from misplaced ellipsis.
680 SourceLocation EllipsisLoc;
681 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
682 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
684 // If there is a default value, parse it.
685 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
686 // we introduce the template parameter into the local scope.
687 SourceLocation EqualLoc;
688 ExprResult DefaultArg;
689 if (TryConsumeToken(tok::equal, EqualLoc)) {
690 // C++ [temp.param]p15:
691 // When parsing a default template-argument for a non-type
692 // template-parameter, the first non-nested > is taken as the
693 // end of the template-parameter-list rather than a greater-than
695 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
696 EnterExpressionEvaluationContext ConstantEvaluated(Actions,
697 Sema::ConstantEvaluated);
699 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
700 if (DefaultArg.isInvalid())
701 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
704 // Create the parameter.
705 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
706 Depth, Position, EqualLoc,
710 void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
711 SourceLocation CorrectLoc,
712 bool AlreadyHasEllipsis,
713 bool IdentifierHasName) {
715 if (!AlreadyHasEllipsis)
716 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
717 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
718 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
719 << !IdentifierHasName;
722 void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
724 assert(EllipsisLoc.isValid());
725 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
726 if (!AlreadyHasEllipsis)
727 D.setEllipsisLoc(EllipsisLoc);
728 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
729 AlreadyHasEllipsis, D.hasName());
732 /// \brief Parses a '>' at the end of a template list.
734 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
735 /// to determine if these tokens were supposed to be a '>' followed by
736 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
738 /// \param RAngleLoc the location of the consumed '>'.
740 /// \param ConsumeLastToken if true, the '>' is consumed.
742 /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
743 /// type parameter or type argument list, rather than a C++ template parameter
744 /// or argument list.
746 /// \returns true, if current token does not start with '>', false otherwise.
747 bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
748 bool ConsumeLastToken,
749 bool ObjCGenericList) {
750 // What will be left once we've consumed the '>'.
751 tok::TokenKind RemainingToken;
752 const char *ReplacementStr = "> >";
754 switch (Tok.getKind()) {
756 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
760 // Determine the location of the '>' token. Only consume this token
761 // if the caller asked us to.
762 RAngleLoc = Tok.getLocation();
763 if (ConsumeLastToken)
767 case tok::greatergreater:
768 RemainingToken = tok::greater;
771 case tok::greatergreatergreater:
772 RemainingToken = tok::greatergreater;
775 case tok::greaterequal:
776 RemainingToken = tok::equal;
777 ReplacementStr = "> =";
780 case tok::greatergreaterequal:
781 RemainingToken = tok::greaterequal;
785 // This template-id is terminated by a token which starts with a '>'. Outside
786 // C++11, this is now error recovery, and in C++11, this is error recovery if
787 // the token isn't '>>' or '>>>'.
788 // '>>>' is for CUDA, where this sequence of characters is parsed into
789 // tok::greatergreatergreater, rather than two separate tokens.
791 // We always allow this for Objective-C type parameter and type argument
793 RAngleLoc = Tok.getLocation();
794 Token Next = NextToken();
795 if (!ObjCGenericList) {
796 // The source range of the '>>' or '>=' at the start of the token.
797 CharSourceRange ReplacementRange =
798 CharSourceRange::getCharRange(RAngleLoc,
799 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
802 // A hint to put a space between the '>>'s. In order to make the hint as
803 // clear as possible, we include the characters either side of the space in
804 // the replacement, rather than just inserting a space at SecondCharLoc.
805 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
808 // A hint to put another space after the token, if it would otherwise be
809 // lexed differently.
811 if ((RemainingToken == tok::greater ||
812 RemainingToken == tok::greatergreater) &&
813 (Next.isOneOf(tok::greater, tok::greatergreater,
814 tok::greatergreatergreater, tok::equal,
815 tok::greaterequal, tok::greatergreaterequal,
817 areTokensAdjacent(Tok, Next))
818 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
820 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
821 if (getLangOpts().CPlusPlus11 &&
822 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
823 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
824 else if (Tok.is(tok::greaterequal))
825 DiagId = diag::err_right_angle_bracket_equal_needs_space;
826 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
829 // Strip the initial '>' from the token.
830 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
831 areTokensAdjacent(Tok, Next)) {
832 // Join two adjacent '=' tokens into one, for cases like:
833 // void (*p)() = f<int>;
836 Tok.setKind(tok::equalequal);
837 Tok.setLength(Tok.getLength() + 1);
839 Tok.setKind(RemainingToken);
840 Tok.setLength(Tok.getLength() - 1);
842 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
843 PP.getSourceManager(),
846 if (!ConsumeLastToken) {
847 // Since we're not supposed to consume the '>' token, we need to push
848 // this token and revert the current token back to the '>'.
850 Tok.setKind(tok::greater);
852 Tok.setLocation(RAngleLoc);
858 /// \brief Parses a template-id that after the template name has
859 /// already been parsed.
861 /// This routine takes care of parsing the enclosed template argument
862 /// list ('<' template-parameter-list [opt] '>') and placing the
863 /// results into a form that can be transferred to semantic analysis.
865 /// \param Template the template declaration produced by isTemplateName
867 /// \param TemplateNameLoc the source location of the template name
869 /// \param SS if non-NULL, the nested-name-specifier preceding the
872 /// \param ConsumeLastToken if true, then we will consume the last
873 /// token that forms the template-id. Otherwise, we will leave the
874 /// last token in the stream (e.g., so that it can be replaced with an
875 /// annotation token).
877 Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
878 SourceLocation TemplateNameLoc,
879 const CXXScopeSpec &SS,
880 bool ConsumeLastToken,
881 SourceLocation &LAngleLoc,
882 TemplateArgList &TemplateArgs,
883 SourceLocation &RAngleLoc) {
884 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
887 LAngleLoc = ConsumeToken();
889 // Parse the optional template-argument-list.
890 bool Invalid = false;
892 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
893 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
894 Invalid = ParseTemplateArgumentList(TemplateArgs);
897 // Try to find the closing '>'.
898 if (ConsumeLastToken)
899 SkipUntil(tok::greater, StopAtSemi);
901 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
906 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
907 /*ObjCGenericList=*/false);
910 /// \brief Replace the tokens that form a simple-template-id with an
911 /// annotation token containing the complete template-id.
913 /// The first token in the stream must be the name of a template that
914 /// is followed by a '<'. This routine will parse the complete
915 /// simple-template-id and replace the tokens with a single annotation
916 /// token with one of two different kinds: if the template-id names a
917 /// type (and \p AllowTypeAnnotation is true), the annotation token is
918 /// a type annotation that includes the optional nested-name-specifier
919 /// (\p SS). Otherwise, the annotation token is a template-id
920 /// annotation that does not include the optional
921 /// nested-name-specifier.
923 /// \param Template the declaration of the template named by the first
924 /// token (an identifier), as returned from \c Action::isTemplateName().
926 /// \param TNK the kind of template that \p Template
927 /// refers to, as returned from \c Action::isTemplateName().
929 /// \param SS if non-NULL, the nested-name-specifier that precedes
930 /// this template name.
932 /// \param TemplateKWLoc if valid, specifies that this template-id
933 /// annotation was preceded by the 'template' keyword and gives the
934 /// location of that keyword. If invalid (the default), then this
935 /// template-id was not preceded by a 'template' keyword.
937 /// \param AllowTypeAnnotation if true (the default), then a
938 /// simple-template-id that refers to a class template, template
939 /// template parameter, or other template that produces a type will be
940 /// replaced with a type annotation token. Otherwise, the
941 /// simple-template-id is always replaced with a template-id
942 /// annotation token.
944 /// If an unrecoverable parse error occurs and no annotation token can be
945 /// formed, this function returns true.
947 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
949 SourceLocation TemplateKWLoc,
950 UnqualifiedId &TemplateName,
951 bool AllowTypeAnnotation) {
952 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
953 assert(Template && Tok.is(tok::less) &&
954 "Parser isn't at the beginning of a template-id");
956 // Consume the template-name.
957 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
959 // Parse the enclosed template argument list.
960 SourceLocation LAngleLoc, RAngleLoc;
961 TemplateArgList TemplateArgs;
962 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
964 SS, false, LAngleLoc,
969 // If we failed to parse the template ID but skipped ahead to a >, we're not
970 // going to be able to form a token annotation. Eat the '>' if present.
971 TryConsumeToken(tok::greater);
975 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
977 // Build the annotation token.
978 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
980 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
981 Template, TemplateNameLoc,
982 LAngleLoc, TemplateArgsPtr, RAngleLoc);
983 if (Type.isInvalid()) {
984 // If we failed to parse the template ID but skipped ahead to a >, we're not
985 // going to be able to form a token annotation. Eat the '>' if present.
986 TryConsumeToken(tok::greater);
990 Tok.setKind(tok::annot_typename);
991 setTypeAnnotation(Tok, Type.get());
993 Tok.setLocation(SS.getBeginLoc());
994 else if (TemplateKWLoc.isValid())
995 Tok.setLocation(TemplateKWLoc);
997 Tok.setLocation(TemplateNameLoc);
999 // Build a template-id annotation token that can be processed
1001 Tok.setKind(tok::annot_template_id);
1002 TemplateIdAnnotation *TemplateId
1003 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
1004 TemplateId->TemplateNameLoc = TemplateNameLoc;
1005 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
1006 TemplateId->Name = TemplateName.Identifier;
1007 TemplateId->Operator = OO_None;
1009 TemplateId->Name = nullptr;
1010 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
1012 TemplateId->SS = SS;
1013 TemplateId->TemplateKWLoc = TemplateKWLoc;
1014 TemplateId->Template = Template;
1015 TemplateId->Kind = TNK;
1016 TemplateId->LAngleLoc = LAngleLoc;
1017 TemplateId->RAngleLoc = RAngleLoc;
1018 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1019 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
1020 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
1021 Tok.setAnnotationValue(TemplateId);
1022 if (TemplateKWLoc.isValid())
1023 Tok.setLocation(TemplateKWLoc);
1025 Tok.setLocation(TemplateNameLoc);
1028 // Common fields for the annotation token
1029 Tok.setAnnotationEndLoc(RAngleLoc);
1031 // In case the tokens were cached, have Preprocessor replace them with the
1032 // annotation token.
1033 PP.AnnotateCachedTokens(Tok);
1037 /// \brief Replaces a template-id annotation token with a type
1038 /// annotation token.
1040 /// If there was a failure when forming the type from the template-id,
1041 /// a type annotation token will still be created, but will have a
1042 /// NULL type pointer to signify an error.
1043 void Parser::AnnotateTemplateIdTokenAsType() {
1044 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1046 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1047 assert((TemplateId->Kind == TNK_Type_template ||
1048 TemplateId->Kind == TNK_Dependent_template_name) &&
1049 "Only works for type and dependent templates");
1051 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1052 TemplateId->NumArgs);
1055 = Actions.ActOnTemplateIdType(TemplateId->SS,
1056 TemplateId->TemplateKWLoc,
1057 TemplateId->Template,
1058 TemplateId->TemplateNameLoc,
1059 TemplateId->LAngleLoc,
1061 TemplateId->RAngleLoc);
1062 // Create the new "type" annotation token.
1063 Tok.setKind(tok::annot_typename);
1064 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
1065 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1066 Tok.setLocation(TemplateId->SS.getBeginLoc());
1067 // End location stays the same
1069 // Replace the template-id annotation token, and possible the scope-specifier
1070 // that precedes it, with the typename annotation token.
1071 PP.AnnotateCachedTokens(Tok);
1074 /// \brief Determine whether the given token can end a template argument.
1075 static bool isEndOfTemplateArgument(Token Tok) {
1076 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
1079 /// \brief Parse a C++ template template argument.
1080 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1081 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1082 !Tok.is(tok::annot_cxxscope))
1083 return ParsedTemplateArgument();
1085 // C++0x [temp.arg.template]p1:
1086 // A template-argument for a template template-parameter shall be the name
1087 // of a class template or an alias template, expressed as id-expression.
1089 // We parse an id-expression that refers to a class template or alias
1090 // template. The grammar we parse is:
1092 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1094 // followed by a token that terminates a template argument, such as ',',
1095 // '>', or (in some cases) '>>'.
1096 CXXScopeSpec SS; // nested-name-specifier, if present
1097 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1098 /*EnteringContext=*/false);
1100 ParsedTemplateArgument Result;
1101 SourceLocation EllipsisLoc;
1102 if (SS.isSet() && Tok.is(tok::kw_template)) {
1103 // Parse the optional 'template' keyword following the
1104 // nested-name-specifier.
1105 SourceLocation TemplateKWLoc = ConsumeToken();
1107 if (Tok.is(tok::identifier)) {
1108 // We appear to have a dependent template name.
1110 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1111 ConsumeToken(); // the identifier
1113 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1115 // If the next token signals the end of a template argument,
1116 // then we have a dependent template name that could be a template
1117 // template argument.
1118 TemplateTy Template;
1119 if (isEndOfTemplateArgument(Tok) &&
1120 Actions.ActOnDependentTemplateName(getCurScope(),
1121 SS, TemplateKWLoc, Name,
1122 /*ObjectType=*/ ParsedType(),
1123 /*EnteringContext=*/false,
1125 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1127 } else if (Tok.is(tok::identifier)) {
1128 // We may have a (non-dependent) template name.
1129 TemplateTy Template;
1131 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1132 ConsumeToken(); // the identifier
1134 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1136 if (isEndOfTemplateArgument(Tok)) {
1137 bool MemberOfUnknownSpecialization;
1138 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1139 /*hasTemplateKeyword=*/false,
1141 /*ObjectType=*/ ParsedType(),
1142 /*EnteringContext=*/false,
1144 MemberOfUnknownSpecialization);
1145 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1146 // We have an id-expression that refers to a class template or
1147 // (C++0x) alias template.
1148 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1153 // If this is a pack expansion, build it as such.
1154 if (EllipsisLoc.isValid() && !Result.isInvalid())
1155 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1160 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1162 /// template-argument: [C++ 14.2]
1163 /// constant-expression
1166 ParsedTemplateArgument Parser::ParseTemplateArgument() {
1167 // C++ [temp.arg]p2:
1168 // In a template-argument, an ambiguity between a type-id and an
1169 // expression is resolved to a type-id, regardless of the form of
1170 // the corresponding template-parameter.
1172 // Therefore, we initially try to parse a type-id.
1173 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1174 SourceLocation Loc = Tok.getLocation();
1175 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
1176 Declarator::TemplateTypeArgContext);
1177 if (TypeArg.isInvalid())
1178 return ParsedTemplateArgument();
1180 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1181 TypeArg.get().getAsOpaquePtr(),
1185 // Try to parse a template template argument.
1187 TentativeParsingAction TPA(*this);
1189 ParsedTemplateArgument TemplateTemplateArgument
1190 = ParseTemplateTemplateArgument();
1191 if (!TemplateTemplateArgument.isInvalid()) {
1193 return TemplateTemplateArgument;
1196 // Revert this tentative parse to parse a non-type template argument.
1200 // Parse a non-type template argument.
1201 SourceLocation Loc = Tok.getLocation();
1202 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1203 if (ExprArg.isInvalid() || !ExprArg.get())
1204 return ParsedTemplateArgument();
1206 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1207 ExprArg.get(), Loc);
1210 /// \brief Determine whether the current tokens can only be parsed as a
1211 /// template argument list (starting with the '<') and never as a '<'
1213 bool Parser::IsTemplateArgumentList(unsigned Skip) {
1214 struct AlwaysRevertAction : TentativeParsingAction {
1215 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1216 ~AlwaysRevertAction() { Revert(); }
1225 if (!TryConsumeToken(tok::less))
1228 // An empty template argument list.
1229 if (Tok.is(tok::greater))
1232 // See whether we have declaration specifiers, which indicate a type.
1233 while (isCXXDeclarationSpecifier() == TPResult::True)
1236 // If we have a '>' or a ',' then this is a template argument list.
1237 return Tok.isOneOf(tok::greater, tok::comma);
1240 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1241 /// (C++ [temp.names]). Returns true if there was an error.
1243 /// template-argument-list: [C++ 14.2]
1244 /// template-argument
1245 /// template-argument-list ',' template-argument
1247 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1248 // Template argument lists are constant-evaluation contexts.
1249 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
1250 ColonProtectionRAIIObject ColonProtection(*this, false);
1253 ParsedTemplateArgument Arg = ParseTemplateArgument();
1254 SourceLocation EllipsisLoc;
1255 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1256 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1258 if (Arg.isInvalid()) {
1259 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
1263 // Save this template argument.
1264 TemplateArgs.push_back(Arg);
1266 // If the next token is a comma, consume it and keep reading
1268 } while (TryConsumeToken(tok::comma));
1273 /// \brief Parse a C++ explicit template instantiation
1274 /// (C++ [temp.explicit]).
1276 /// explicit-instantiation:
1277 /// 'extern' [opt] 'template' declaration
1279 /// Note that the 'extern' is a GNU extension and C++11 feature.
1280 Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1281 SourceLocation ExternLoc,
1282 SourceLocation TemplateLoc,
1283 SourceLocation &DeclEnd,
1284 AccessSpecifier AS) {
1285 // This isn't really required here.
1286 ParsingDeclRAIIObject
1287 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1289 return ParseSingleDeclarationAfterTemplate(Context,
1290 ParsedTemplateInfo(ExternLoc,
1292 ParsingTemplateParams,
1296 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1298 return getTemplateParamsRange(TemplateParams->data(),
1299 TemplateParams->size());
1301 SourceRange R(TemplateLoc);
1302 if (ExternLoc.isValid())
1303 R.setBegin(ExternLoc);
1307 void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1308 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1311 /// \brief Late parse a C++ function template in Microsoft mode.
1312 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1316 // Get the FunctionDecl.
1317 FunctionDecl *FunD = LPT.D->getAsFunction();
1318 // Track template parameter depth.
1319 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1321 // To restore the context after late parsing.
1322 Sema::ContextRAII GlobalSavedContext(
1323 Actions, Actions.Context.getTranslationUnitDecl());
1325 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1327 // Get the list of DeclContexts to reenter.
1328 SmallVector<DeclContext*, 4> DeclContextsToReenter;
1329 DeclContext *DD = FunD;
1330 while (DD && !DD->isTranslationUnit()) {
1331 DeclContextsToReenter.push_back(DD);
1332 DD = DD->getLexicalParent();
1335 // Reenter template scopes from outermost to innermost.
1336 SmallVectorImpl<DeclContext *>::reverse_iterator II =
1337 DeclContextsToReenter.rbegin();
1338 for (; II != DeclContextsToReenter.rend(); ++II) {
1339 TemplateParamScopeStack.push_back(new ParseScope(this,
1340 Scope::TemplateParamScope));
1341 unsigned NumParamLists =
1342 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1343 CurTemplateDepthTracker.addDepth(NumParamLists);
1345 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1346 Actions.PushDeclContext(Actions.getCurScope(), *II);
1350 assert(!LPT.Toks.empty() && "Empty body!");
1352 // Append the current token at the end of the new token stream so that it
1353 // doesn't get lost.
1354 LPT.Toks.push_back(Tok);
1355 PP.EnterTokenStream(LPT.Toks.data(), LPT.Toks.size(), true, false);
1357 // Consume the previously pushed token.
1358 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1359 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1360 "Inline method not starting with '{', ':' or 'try'");
1362 // Parse the method body. Function body parsing code is similar enough
1363 // to be re-used for method bodies as well.
1364 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1366 // Recreate the containing function DeclContext.
1367 Sema::ContextRAII FunctionSavedContext(Actions,
1368 Actions.getContainingDC(FunD));
1370 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1372 if (Tok.is(tok::kw_try)) {
1373 ParseFunctionTryBlock(LPT.D, FnScope);
1375 if (Tok.is(tok::colon))
1376 ParseConstructorInitializer(LPT.D);
1378 Actions.ActOnDefaultCtorInitializers(LPT.D);
1380 if (Tok.is(tok::l_brace)) {
1381 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1382 cast<FunctionTemplateDecl>(LPT.D)
1383 ->getTemplateParameters()
1384 ->getDepth() == TemplateParameterDepth - 1) &&
1385 "TemplateParameterDepth should be greater than the depth of "
1386 "current template being instantiated!");
1387 ParseFunctionStatementBody(LPT.D, FnScope);
1388 Actions.UnmarkAsLateParsedTemplate(FunD);
1390 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1395 SmallVectorImpl<ParseScope *>::reverse_iterator I =
1396 TemplateParamScopeStack.rbegin();
1397 for (; I != TemplateParamScopeStack.rend(); ++I)
1401 /// \brief Lex a delayed template function for late parsing.
1402 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1403 tok::TokenKind kind = Tok.getKind();
1404 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1405 // Consume everything up to (and including) the matching right brace.
1406 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1409 // If we're in a function-try-block, we need to store all the catch blocks.
1410 if (kind == tok::kw_try) {
1411 while (Tok.is(tok::kw_catch)) {
1412 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1413 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);