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.data(),
130 TemplateParams.size(), RAngleLoc));
132 if (!TemplateParams.empty()) {
133 isSpecialization = false;
134 ++CurTemplateDepthTracker;
136 if (TryConsumeToken(tok::kw_requires)) {
138 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
139 if (!ER.isUsable()) {
140 // Skip until the semi-colon or a '}'.
141 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
142 TryConsumeToken(tok::semi);
147 LastParamListWasEmpty = true;
149 } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
151 // Parse the actual template declaration.
152 return ParseSingleDeclarationAfterTemplate(Context,
153 ParsedTemplateInfo(&ParamLists,
155 LastParamListWasEmpty),
156 ParsingTemplateParams,
157 DeclEnd, AS, AccessAttrs);
160 /// \brief Parse a single declaration that declares a template,
161 /// template specialization, or explicit instantiation of a template.
163 /// \param DeclEnd will receive the source location of the last token
164 /// within this declaration.
166 /// \param AS the access specifier associated with this
167 /// declaration. Will be AS_none for namespace-scope declarations.
169 /// \returns the new declaration.
171 Parser::ParseSingleDeclarationAfterTemplate(
173 const ParsedTemplateInfo &TemplateInfo,
174 ParsingDeclRAIIObject &DiagsFromTParams,
175 SourceLocation &DeclEnd,
177 AttributeList *AccessAttrs) {
178 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
179 "Template information required");
181 if (Tok.is(tok::kw_static_assert)) {
182 // A static_assert declaration may not be templated.
183 Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
184 << TemplateInfo.getSourceRange();
185 // Parse the static_assert declaration to improve error recovery.
186 return ParseStaticAssertDeclaration(DeclEnd);
189 if (Context == Declarator::MemberContext) {
190 // We are parsing a member template.
191 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
196 ParsedAttributesWithRange prefixAttrs(AttrFactory);
197 MaybeParseCXX11Attributes(prefixAttrs);
199 if (Tok.is(tok::kw_using))
200 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
203 // Parse the declaration specifiers, stealing any diagnostics from
204 // the template parameters.
205 ParsingDeclSpec DS(*this, &DiagsFromTParams);
207 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
208 getDeclSpecContextFromDeclaratorContext(Context));
210 if (Tok.is(tok::semi)) {
211 ProhibitAttributes(prefixAttrs);
212 DeclEnd = ConsumeToken();
213 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
214 getCurScope(), AS, DS,
215 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
216 : MultiTemplateParamsArg(),
217 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation);
222 // Move the attributes from the prefix into the DS.
223 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
224 ProhibitAttributes(prefixAttrs);
226 DS.takeAttributesFrom(prefixAttrs);
228 // Parse the declarator.
229 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
230 ParseDeclarator(DeclaratorInfo);
231 // Error parsing the declarator?
232 if (!DeclaratorInfo.hasName()) {
233 // If so, skip until the semi-colon or a }.
234 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
235 if (Tok.is(tok::semi))
240 LateParsedAttrList LateParsedAttrs(true);
241 if (DeclaratorInfo.isFunctionDeclarator())
242 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
244 if (DeclaratorInfo.isFunctionDeclarator() &&
245 isStartOfFunctionDefinition(DeclaratorInfo)) {
247 // Function definitions are only allowed at file scope and in C++ classes.
248 // The C++ inline method definition case is handled elsewhere, so we only
249 // need to handle the file scope definition case.
250 if (Context != Declarator::FileContext) {
251 Diag(Tok, diag::err_function_definition_not_allowed);
256 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
257 // Recover by ignoring the 'typedef'. This was probably supposed to be
258 // the 'typename' keyword, which we should have already suggested adding
259 // if it's appropriate.
260 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
261 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
262 DS.ClearStorageClassSpecs();
265 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
266 if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
267 // If the declarator-id is not a template-id, issue a diagnostic and
268 // recover by ignoring the 'template' keyword.
269 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
270 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
273 SourceLocation LAngleLoc
274 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
275 Diag(DeclaratorInfo.getIdentifierLoc(),
276 diag::err_explicit_instantiation_with_definition)
277 << SourceRange(TemplateInfo.TemplateLoc)
278 << FixItHint::CreateInsertion(LAngleLoc, "<>");
280 // Recover as if it were an explicit specialization.
281 TemplateParameterLists FakedParamLists;
282 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
283 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr,
286 return ParseFunctionDefinition(
287 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
288 /*isSpecialization=*/true,
289 /*LastParamListWasEmpty=*/true),
293 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
297 // Parse this declaration.
298 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
301 if (Tok.is(tok::comma)) {
302 Diag(Tok, diag::err_multiple_template_declarators)
303 << (int)TemplateInfo.Kind;
304 SkipUntil(tok::semi);
308 // Eat the semi colon after the declaration.
309 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
310 if (LateParsedAttrs.size() > 0)
311 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
312 DeclaratorInfo.complete(ThisDecl);
316 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
317 /// angle brackets. Depth is the depth of this template-parameter-list, which
318 /// is the number of template headers directly enclosing this template header.
319 /// TemplateParams is the current list of template parameters we're building.
320 /// The template parameter we parse will be added to this list. LAngleLoc and
321 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
322 /// that enclose this template parameter list.
324 /// \returns true if an error occurred, false otherwise.
325 bool Parser::ParseTemplateParameters(unsigned Depth,
326 SmallVectorImpl<Decl*> &TemplateParams,
327 SourceLocation &LAngleLoc,
328 SourceLocation &RAngleLoc) {
329 // Get the template parameter list.
330 if (!TryConsumeToken(tok::less, LAngleLoc)) {
331 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
335 // Try to parse the template parameter list.
337 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
338 Failed = ParseTemplateParameterList(Depth, TemplateParams);
340 if (Tok.is(tok::greatergreater)) {
341 // No diagnostic required here: a template-parameter-list can only be
342 // followed by a declaration or, for a template template parameter, the
343 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
344 // This matters for elegant diagnosis of:
345 // template<template<typename>> struct S;
346 Tok.setKind(tok::greater);
347 RAngleLoc = Tok.getLocation();
348 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
349 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
350 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
356 /// ParseTemplateParameterList - Parse a template parameter list. If
357 /// the parsing fails badly (i.e., closing bracket was left out), this
358 /// will try to put the token stream in a reasonable position (closing
359 /// a statement, etc.) and return false.
361 /// template-parameter-list: [C++ temp]
362 /// template-parameter
363 /// template-parameter-list ',' template-parameter
365 Parser::ParseTemplateParameterList(unsigned Depth,
366 SmallVectorImpl<Decl*> &TemplateParams) {
369 = ParseTemplateParameter(Depth, TemplateParams.size())) {
370 TemplateParams.push_back(TmpParam);
372 // If we failed to parse a template parameter, skip until we find
373 // a comma or closing brace.
374 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
375 StopAtSemi | StopBeforeMatch);
378 // Did we find a comma or the end of the template parameter list?
379 if (Tok.is(tok::comma)) {
381 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
382 // Don't consume this... that's done by template parser.
385 // Somebody probably forgot to close the template. Skip ahead and
386 // try to get out of the expression. This error is currently
387 // subsumed by whatever goes on in ParseTemplateParameter.
388 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
389 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
390 StopAtSemi | StopBeforeMatch);
397 /// \brief Determine whether the parser is at the start of a template
399 bool Parser::isStartOfTemplateTypeParameter() {
400 if (Tok.is(tok::kw_class)) {
401 // "class" may be the start of an elaborated-type-specifier or a
402 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
403 switch (NextToken().getKind()) {
407 case tok::greatergreater:
411 case tok::identifier:
412 // This may be either a type-parameter or an elaborated-type-specifier.
413 // We have to look further.
420 switch (GetLookAheadToken(2).getKind()) {
424 case tok::greatergreater:
432 if (Tok.isNot(tok::kw_typename))
435 // C++ [temp.param]p2:
436 // There is no semantic difference between class and typename in a
437 // template-parameter. typename followed by an unqualified-id
438 // names a template type parameter. typename followed by a
439 // qualified-id denotes the type in a non-type
440 // parameter-declaration.
441 Token Next = NextToken();
443 // If we have an identifier, skip over it.
444 if (Next.getKind() == tok::identifier)
445 Next = GetLookAheadToken(2);
447 switch (Next.getKind()) {
451 case tok::greatergreater:
460 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
462 /// template-parameter: [C++ temp.param]
464 /// parameter-declaration
466 /// type-parameter: (see below)
467 /// 'class' ...[opt] identifier[opt]
468 /// 'class' identifier[opt] '=' type-id
469 /// 'typename' ...[opt] identifier[opt]
470 /// 'typename' identifier[opt] '=' type-id
471 /// 'template' '<' template-parameter-list '>'
472 /// 'class' ...[opt] identifier[opt]
473 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
475 Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
476 if (isStartOfTemplateTypeParameter())
477 return ParseTypeParameter(Depth, Position);
479 if (Tok.is(tok::kw_template))
480 return ParseTemplateTemplateParameter(Depth, Position);
482 // If it's none of the above, then it must be a parameter declaration.
483 // NOTE: This will pick up errors in the closure of the template parameter
484 // list (e.g., template < ; Check here to implement >> style closures.
485 return ParseNonTypeTemplateParameter(Depth, Position);
488 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
489 /// Other kinds of template parameters are parsed in
490 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
492 /// type-parameter: [C++ temp.param]
493 /// 'class' ...[opt][C++0x] identifier[opt]
494 /// 'class' identifier[opt] '=' type-id
495 /// 'typename' ...[opt][C++0x] identifier[opt]
496 /// 'typename' identifier[opt] '=' type-id
497 Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
498 assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
499 "A type-parameter starts with 'class' or 'typename'");
501 // Consume the 'class' or 'typename' keyword.
502 bool TypenameKeyword = Tok.is(tok::kw_typename);
503 SourceLocation KeyLoc = ConsumeToken();
505 // Grab the ellipsis (if given).
506 SourceLocation EllipsisLoc;
507 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
509 getLangOpts().CPlusPlus11
510 ? diag::warn_cxx98_compat_variadic_templates
511 : diag::ext_variadic_templates);
514 // Grab the template parameter name (if given)
515 SourceLocation NameLoc;
516 IdentifierInfo *ParamName = nullptr;
517 if (Tok.is(tok::identifier)) {
518 ParamName = Tok.getIdentifierInfo();
519 NameLoc = ConsumeToken();
520 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
521 tok::greatergreater)) {
522 // Unnamed template parameter. Don't have to do anything here, just
523 // don't consume this token.
525 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
529 // Recover from misplaced ellipsis.
530 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
531 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
532 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
534 // Grab a default argument (if available).
535 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
536 // we introduce the type parameter into the local scope.
537 SourceLocation EqualLoc;
538 ParsedType DefaultArg;
539 if (TryConsumeToken(tok::equal, EqualLoc))
540 DefaultArg = ParseTypeName(/*Range=*/nullptr,
541 Declarator::TemplateTypeArgContext).get();
543 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
544 KeyLoc, ParamName, NameLoc, Depth, Position,
545 EqualLoc, DefaultArg);
548 /// ParseTemplateTemplateParameter - Handle the parsing of template
549 /// template parameters.
551 /// type-parameter: [C++ temp.param]
552 /// 'template' '<' template-parameter-list '>' type-parameter-key
553 /// ...[opt] identifier[opt]
554 /// 'template' '<' template-parameter-list '>' type-parameter-key
555 /// identifier[opt] = id-expression
556 /// type-parameter-key:
558 /// 'typename' [C++1z]
560 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
561 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
563 // Handle the template <...> part.
564 SourceLocation TemplateLoc = ConsumeToken();
565 SmallVector<Decl*,8> TemplateParams;
566 SourceLocation LAngleLoc, RAngleLoc;
568 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
569 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
575 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
576 // Generate a meaningful error if the user forgot to put class before the
577 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
578 // or greater appear immediately or after 'struct'. In the latter case,
579 // replace the keyword with 'class'.
580 if (!TryConsumeToken(tok::kw_class)) {
581 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
582 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
583 if (Tok.is(tok::kw_typename)) {
584 Diag(Tok.getLocation(),
585 getLangOpts().CPlusPlus1z
586 ? diag::warn_cxx14_compat_template_template_param_typename
587 : diag::ext_template_template_param_typename)
588 << (!getLangOpts().CPlusPlus1z
589 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
591 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
592 tok::greatergreater, tok::ellipsis)) {
593 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
594 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
595 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
597 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
603 // Parse the ellipsis, if given.
604 SourceLocation EllipsisLoc;
605 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
607 getLangOpts().CPlusPlus11
608 ? diag::warn_cxx98_compat_variadic_templates
609 : diag::ext_variadic_templates);
611 // Get the identifier, if given.
612 SourceLocation NameLoc;
613 IdentifierInfo *ParamName = nullptr;
614 if (Tok.is(tok::identifier)) {
615 ParamName = Tok.getIdentifierInfo();
616 NameLoc = ConsumeToken();
617 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
618 tok::greatergreater)) {
619 // Unnamed template parameter. Don't have to do anything here, just
620 // don't consume this token.
622 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
626 // Recover from misplaced ellipsis.
627 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
628 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
629 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
631 TemplateParameterList *ParamList =
632 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
633 TemplateLoc, LAngleLoc,
634 TemplateParams.data(),
635 TemplateParams.size(),
638 // Grab a default argument (if available).
639 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
640 // we introduce the template parameter into the local scope.
641 SourceLocation EqualLoc;
642 ParsedTemplateArgument DefaultArg;
643 if (TryConsumeToken(tok::equal, EqualLoc)) {
644 DefaultArg = ParseTemplateTemplateArgument();
645 if (DefaultArg.isInvalid()) {
646 Diag(Tok.getLocation(),
647 diag::err_default_template_template_parameter_not_template);
648 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
649 StopAtSemi | StopBeforeMatch);
653 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
654 ParamList, EllipsisLoc,
655 ParamName, NameLoc, Depth,
656 Position, EqualLoc, DefaultArg);
659 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
660 /// template parameters (e.g., in "template<int Size> class array;").
662 /// template-parameter:
664 /// parameter-declaration
666 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
667 // Parse the declaration-specifiers (i.e., the type).
668 // FIXME: The type should probably be restricted in some way... Not all
669 // declarators (parts of declarators?) are accepted for parameters.
670 DeclSpec DS(AttrFactory);
671 ParseDeclarationSpecifiers(DS);
673 // Parse this as a typename.
674 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
675 ParseDeclarator(ParamDecl);
676 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
677 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
681 // Recover from misplaced ellipsis.
682 SourceLocation EllipsisLoc;
683 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
684 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
686 // If there is a default value, parse it.
687 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
688 // we introduce the template parameter into the local scope.
689 SourceLocation EqualLoc;
690 ExprResult DefaultArg;
691 if (TryConsumeToken(tok::equal, EqualLoc)) {
692 // C++ [temp.param]p15:
693 // When parsing a default template-argument for a non-type
694 // template-parameter, the first non-nested > is taken as the
695 // end of the template-parameter-list rather than a greater-than
697 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
698 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
700 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
701 if (DefaultArg.isInvalid())
702 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
705 // Create the parameter.
706 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
707 Depth, Position, EqualLoc,
711 void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
712 SourceLocation CorrectLoc,
713 bool AlreadyHasEllipsis,
714 bool IdentifierHasName) {
716 if (!AlreadyHasEllipsis)
717 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
718 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
719 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
720 << !IdentifierHasName;
723 void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
725 assert(EllipsisLoc.isValid());
726 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
727 if (!AlreadyHasEllipsis)
728 D.setEllipsisLoc(EllipsisLoc);
729 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
730 AlreadyHasEllipsis, D.hasName());
733 /// \brief Parses a '>' at the end of a template list.
735 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
736 /// to determine if these tokens were supposed to be a '>' followed by
737 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
739 /// \param RAngleLoc the location of the consumed '>'.
741 /// \param ConsumeLastToken if true, the '>' is not consumed.
743 /// \returns true, if current token does not start with '>', false otherwise.
744 bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
745 bool ConsumeLastToken) {
746 // What will be left once we've consumed the '>'.
747 tok::TokenKind RemainingToken;
748 const char *ReplacementStr = "> >";
750 switch (Tok.getKind()) {
752 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
756 // Determine the location of the '>' token. Only consume this token
757 // if the caller asked us to.
758 RAngleLoc = Tok.getLocation();
759 if (ConsumeLastToken)
763 case tok::greatergreater:
764 RemainingToken = tok::greater;
767 case tok::greatergreatergreater:
768 RemainingToken = tok::greatergreater;
771 case tok::greaterequal:
772 RemainingToken = tok::equal;
773 ReplacementStr = "> =";
776 case tok::greatergreaterequal:
777 RemainingToken = tok::greaterequal;
781 // This template-id is terminated by a token which starts with a '>'. Outside
782 // C++11, this is now error recovery, and in C++11, this is error recovery if
783 // the token isn't '>>' or '>>>'.
784 // '>>>' is for CUDA, where this sequence of characters is parsed into
785 // tok::greatergreatergreater, rather than two separate tokens.
787 RAngleLoc = Tok.getLocation();
789 // The source range of the '>>' or '>=' at the start of the token.
790 CharSourceRange ReplacementRange =
791 CharSourceRange::getCharRange(RAngleLoc,
792 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
795 // A hint to put a space between the '>>'s. In order to make the hint as
796 // clear as possible, we include the characters either side of the space in
797 // the replacement, rather than just inserting a space at SecondCharLoc.
798 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
801 // A hint to put another space after the token, if it would otherwise be
802 // lexed differently.
804 Token Next = NextToken();
805 if ((RemainingToken == tok::greater ||
806 RemainingToken == tok::greatergreater) &&
807 Next.isOneOf(tok::greater, tok::greatergreater,
808 tok::greatergreatergreater, tok::equal, tok::greaterequal,
809 tok::greatergreaterequal, tok::equalequal) &&
810 areTokensAdjacent(Tok, Next))
811 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
813 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
814 if (getLangOpts().CPlusPlus11 &&
815 Tok.isOneOf(tok::greatergreater, tok::greatergreatergreater))
816 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
817 else if (Tok.is(tok::greaterequal))
818 DiagId = diag::err_right_angle_bracket_equal_needs_space;
819 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
821 // Strip the initial '>' from the token.
822 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
823 areTokensAdjacent(Tok, Next)) {
824 // Join two adjacent '=' tokens into one, for cases like:
825 // void (*p)() = f<int>;
828 Tok.setKind(tok::equalequal);
829 Tok.setLength(Tok.getLength() + 1);
831 Tok.setKind(RemainingToken);
832 Tok.setLength(Tok.getLength() - 1);
834 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
835 PP.getSourceManager(),
838 if (!ConsumeLastToken) {
839 // Since we're not supposed to consume the '>' token, we need to push
840 // this token and revert the current token back to the '>'.
842 Tok.setKind(tok::greater);
844 Tok.setLocation(RAngleLoc);
850 /// \brief Parses a template-id that after the template name has
851 /// already been parsed.
853 /// This routine takes care of parsing the enclosed template argument
854 /// list ('<' template-parameter-list [opt] '>') and placing the
855 /// results into a form that can be transferred to semantic analysis.
857 /// \param Template the template declaration produced by isTemplateName
859 /// \param TemplateNameLoc the source location of the template name
861 /// \param SS if non-NULL, the nested-name-specifier preceding the
864 /// \param ConsumeLastToken if true, then we will consume the last
865 /// token that forms the template-id. Otherwise, we will leave the
866 /// last token in the stream (e.g., so that it can be replaced with an
867 /// annotation token).
869 Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
870 SourceLocation TemplateNameLoc,
871 const CXXScopeSpec &SS,
872 bool ConsumeLastToken,
873 SourceLocation &LAngleLoc,
874 TemplateArgList &TemplateArgs,
875 SourceLocation &RAngleLoc) {
876 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
879 LAngleLoc = ConsumeToken();
881 // Parse the optional template-argument-list.
882 bool Invalid = false;
884 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
885 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
886 Invalid = ParseTemplateArgumentList(TemplateArgs);
889 // Try to find the closing '>'.
890 if (ConsumeLastToken)
891 SkipUntil(tok::greater, StopAtSemi);
893 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
898 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken);
901 /// \brief Replace the tokens that form a simple-template-id with an
902 /// annotation token containing the complete template-id.
904 /// The first token in the stream must be the name of a template that
905 /// is followed by a '<'. This routine will parse the complete
906 /// simple-template-id and replace the tokens with a single annotation
907 /// token with one of two different kinds: if the template-id names a
908 /// type (and \p AllowTypeAnnotation is true), the annotation token is
909 /// a type annotation that includes the optional nested-name-specifier
910 /// (\p SS). Otherwise, the annotation token is a template-id
911 /// annotation that does not include the optional
912 /// nested-name-specifier.
914 /// \param Template the declaration of the template named by the first
915 /// token (an identifier), as returned from \c Action::isTemplateName().
917 /// \param TNK the kind of template that \p Template
918 /// refers to, as returned from \c Action::isTemplateName().
920 /// \param SS if non-NULL, the nested-name-specifier that precedes
921 /// this template name.
923 /// \param TemplateKWLoc if valid, specifies that this template-id
924 /// annotation was preceded by the 'template' keyword and gives the
925 /// location of that keyword. If invalid (the default), then this
926 /// template-id was not preceded by a 'template' keyword.
928 /// \param AllowTypeAnnotation if true (the default), then a
929 /// simple-template-id that refers to a class template, template
930 /// template parameter, or other template that produces a type will be
931 /// replaced with a type annotation token. Otherwise, the
932 /// simple-template-id is always replaced with a template-id
933 /// annotation token.
935 /// If an unrecoverable parse error occurs and no annotation token can be
936 /// formed, this function returns true.
938 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
940 SourceLocation TemplateKWLoc,
941 UnqualifiedId &TemplateName,
942 bool AllowTypeAnnotation) {
943 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
944 assert(Template && Tok.is(tok::less) &&
945 "Parser isn't at the beginning of a template-id");
947 // Consume the template-name.
948 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
950 // Parse the enclosed template argument list.
951 SourceLocation LAngleLoc, RAngleLoc;
952 TemplateArgList TemplateArgs;
953 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
955 SS, false, LAngleLoc,
960 // If we failed to parse the template ID but skipped ahead to a >, we're not
961 // going to be able to form a token annotation. Eat the '>' if present.
962 TryConsumeToken(tok::greater);
966 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
968 // Build the annotation token.
969 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
971 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
972 Template, TemplateNameLoc,
973 LAngleLoc, TemplateArgsPtr, RAngleLoc);
974 if (Type.isInvalid()) {
975 // If we failed to parse the template ID but skipped ahead to a >, we're not
976 // going to be able to form a token annotation. Eat the '>' if present.
977 TryConsumeToken(tok::greater);
981 Tok.setKind(tok::annot_typename);
982 setTypeAnnotation(Tok, Type.get());
984 Tok.setLocation(SS.getBeginLoc());
985 else if (TemplateKWLoc.isValid())
986 Tok.setLocation(TemplateKWLoc);
988 Tok.setLocation(TemplateNameLoc);
990 // Build a template-id annotation token that can be processed
992 Tok.setKind(tok::annot_template_id);
993 TemplateIdAnnotation *TemplateId
994 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
995 TemplateId->TemplateNameLoc = TemplateNameLoc;
996 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
997 TemplateId->Name = TemplateName.Identifier;
998 TemplateId->Operator = OO_None;
1000 TemplateId->Name = nullptr;
1001 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
1003 TemplateId->SS = SS;
1004 TemplateId->TemplateKWLoc = TemplateKWLoc;
1005 TemplateId->Template = Template;
1006 TemplateId->Kind = TNK;
1007 TemplateId->LAngleLoc = LAngleLoc;
1008 TemplateId->RAngleLoc = RAngleLoc;
1009 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1010 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
1011 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
1012 Tok.setAnnotationValue(TemplateId);
1013 if (TemplateKWLoc.isValid())
1014 Tok.setLocation(TemplateKWLoc);
1016 Tok.setLocation(TemplateNameLoc);
1019 // Common fields for the annotation token
1020 Tok.setAnnotationEndLoc(RAngleLoc);
1022 // In case the tokens were cached, have Preprocessor replace them with the
1023 // annotation token.
1024 PP.AnnotateCachedTokens(Tok);
1028 /// \brief Replaces a template-id annotation token with a type
1029 /// annotation token.
1031 /// If there was a failure when forming the type from the template-id,
1032 /// a type annotation token will still be created, but will have a
1033 /// NULL type pointer to signify an error.
1034 void Parser::AnnotateTemplateIdTokenAsType() {
1035 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1037 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1038 assert((TemplateId->Kind == TNK_Type_template ||
1039 TemplateId->Kind == TNK_Dependent_template_name) &&
1040 "Only works for type and dependent templates");
1042 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1043 TemplateId->NumArgs);
1046 = Actions.ActOnTemplateIdType(TemplateId->SS,
1047 TemplateId->TemplateKWLoc,
1048 TemplateId->Template,
1049 TemplateId->TemplateNameLoc,
1050 TemplateId->LAngleLoc,
1052 TemplateId->RAngleLoc);
1053 // Create the new "type" annotation token.
1054 Tok.setKind(tok::annot_typename);
1055 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
1056 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1057 Tok.setLocation(TemplateId->SS.getBeginLoc());
1058 // End location stays the same
1060 // Replace the template-id annotation token, and possible the scope-specifier
1061 // that precedes it, with the typename annotation token.
1062 PP.AnnotateCachedTokens(Tok);
1065 /// \brief Determine whether the given token can end a template argument.
1066 static bool isEndOfTemplateArgument(Token Tok) {
1067 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
1070 /// \brief Parse a C++ template template argument.
1071 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1072 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1073 !Tok.is(tok::annot_cxxscope))
1074 return ParsedTemplateArgument();
1076 // C++0x [temp.arg.template]p1:
1077 // A template-argument for a template template-parameter shall be the name
1078 // of a class template or an alias template, expressed as id-expression.
1080 // We parse an id-expression that refers to a class template or alias
1081 // template. The grammar we parse is:
1083 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1085 // followed by a token that terminates a template argument, such as ',',
1086 // '>', or (in some cases) '>>'.
1087 CXXScopeSpec SS; // nested-name-specifier, if present
1088 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1089 /*EnteringContext=*/false);
1091 ParsedTemplateArgument Result;
1092 SourceLocation EllipsisLoc;
1093 if (SS.isSet() && Tok.is(tok::kw_template)) {
1094 // Parse the optional 'template' keyword following the
1095 // nested-name-specifier.
1096 SourceLocation TemplateKWLoc = ConsumeToken();
1098 if (Tok.is(tok::identifier)) {
1099 // We appear to have a dependent template name.
1101 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1102 ConsumeToken(); // the identifier
1104 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1106 // If the next token signals the end of a template argument,
1107 // then we have a dependent template name that could be a template
1108 // template argument.
1109 TemplateTy Template;
1110 if (isEndOfTemplateArgument(Tok) &&
1111 Actions.ActOnDependentTemplateName(getCurScope(),
1112 SS, TemplateKWLoc, Name,
1113 /*ObjectType=*/ ParsedType(),
1114 /*EnteringContext=*/false,
1116 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1118 } else if (Tok.is(tok::identifier)) {
1119 // We may have a (non-dependent) template name.
1120 TemplateTy Template;
1122 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1123 ConsumeToken(); // the identifier
1125 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1127 if (isEndOfTemplateArgument(Tok)) {
1128 bool MemberOfUnknownSpecialization;
1129 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1130 /*hasTemplateKeyword=*/false,
1132 /*ObjectType=*/ ParsedType(),
1133 /*EnteringContext=*/false,
1135 MemberOfUnknownSpecialization);
1136 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1137 // We have an id-expression that refers to a class template or
1138 // (C++0x) alias template.
1139 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1144 // If this is a pack expansion, build it as such.
1145 if (EllipsisLoc.isValid() && !Result.isInvalid())
1146 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1151 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1153 /// template-argument: [C++ 14.2]
1154 /// constant-expression
1157 ParsedTemplateArgument Parser::ParseTemplateArgument() {
1158 // C++ [temp.arg]p2:
1159 // In a template-argument, an ambiguity between a type-id and an
1160 // expression is resolved to a type-id, regardless of the form of
1161 // the corresponding template-parameter.
1163 // Therefore, we initially try to parse a type-id.
1164 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1165 SourceLocation Loc = Tok.getLocation();
1166 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
1167 Declarator::TemplateTypeArgContext);
1168 if (TypeArg.isInvalid())
1169 return ParsedTemplateArgument();
1171 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1172 TypeArg.get().getAsOpaquePtr(),
1176 // Try to parse a template template argument.
1178 TentativeParsingAction TPA(*this);
1180 ParsedTemplateArgument TemplateTemplateArgument
1181 = ParseTemplateTemplateArgument();
1182 if (!TemplateTemplateArgument.isInvalid()) {
1184 return TemplateTemplateArgument;
1187 // Revert this tentative parse to parse a non-type template argument.
1191 // Parse a non-type template argument.
1192 SourceLocation Loc = Tok.getLocation();
1193 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1194 if (ExprArg.isInvalid() || !ExprArg.get())
1195 return ParsedTemplateArgument();
1197 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1198 ExprArg.get(), Loc);
1201 /// \brief Determine whether the current tokens can only be parsed as a
1202 /// template argument list (starting with the '<') and never as a '<'
1204 bool Parser::IsTemplateArgumentList(unsigned Skip) {
1205 struct AlwaysRevertAction : TentativeParsingAction {
1206 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1207 ~AlwaysRevertAction() { Revert(); }
1216 if (!TryConsumeToken(tok::less))
1219 // An empty template argument list.
1220 if (Tok.is(tok::greater))
1223 // See whether we have declaration specifiers, which indicate a type.
1224 while (isCXXDeclarationSpecifier() == TPResult::True)
1227 // If we have a '>' or a ',' then this is a template argument list.
1228 return Tok.isOneOf(tok::greater, tok::comma);
1231 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1232 /// (C++ [temp.names]). Returns true if there was an error.
1234 /// template-argument-list: [C++ 14.2]
1235 /// template-argument
1236 /// template-argument-list ',' template-argument
1238 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1239 // Template argument lists are constant-evaluation contexts.
1240 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
1241 ColonProtectionRAIIObject ColonProtection(*this, false);
1244 ParsedTemplateArgument Arg = ParseTemplateArgument();
1245 SourceLocation EllipsisLoc;
1246 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1247 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1249 if (Arg.isInvalid()) {
1250 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
1254 // Save this template argument.
1255 TemplateArgs.push_back(Arg);
1257 // If the next token is a comma, consume it and keep reading
1259 } while (TryConsumeToken(tok::comma));
1264 /// \brief Parse a C++ explicit template instantiation
1265 /// (C++ [temp.explicit]).
1267 /// explicit-instantiation:
1268 /// 'extern' [opt] 'template' declaration
1270 /// Note that the 'extern' is a GNU extension and C++11 feature.
1271 Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1272 SourceLocation ExternLoc,
1273 SourceLocation TemplateLoc,
1274 SourceLocation &DeclEnd,
1275 AccessSpecifier AS) {
1276 // This isn't really required here.
1277 ParsingDeclRAIIObject
1278 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1280 return ParseSingleDeclarationAfterTemplate(Context,
1281 ParsedTemplateInfo(ExternLoc,
1283 ParsingTemplateParams,
1287 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1289 return getTemplateParamsRange(TemplateParams->data(),
1290 TemplateParams->size());
1292 SourceRange R(TemplateLoc);
1293 if (ExternLoc.isValid())
1294 R.setBegin(ExternLoc);
1298 void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1299 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1302 /// \brief Late parse a C++ function template in Microsoft mode.
1303 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1307 // Get the FunctionDecl.
1308 FunctionDecl *FunD = LPT.D->getAsFunction();
1309 // Track template parameter depth.
1310 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1312 // To restore the context after late parsing.
1313 Sema::ContextRAII GlobalSavedContext(
1314 Actions, Actions.Context.getTranslationUnitDecl());
1316 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1318 // Get the list of DeclContexts to reenter.
1319 SmallVector<DeclContext*, 4> DeclContextsToReenter;
1320 DeclContext *DD = FunD;
1321 while (DD && !DD->isTranslationUnit()) {
1322 DeclContextsToReenter.push_back(DD);
1323 DD = DD->getLexicalParent();
1326 // Reenter template scopes from outermost to innermost.
1327 SmallVectorImpl<DeclContext *>::reverse_iterator II =
1328 DeclContextsToReenter.rbegin();
1329 for (; II != DeclContextsToReenter.rend(); ++II) {
1330 TemplateParamScopeStack.push_back(new ParseScope(this,
1331 Scope::TemplateParamScope));
1332 unsigned NumParamLists =
1333 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1334 CurTemplateDepthTracker.addDepth(NumParamLists);
1336 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1337 Actions.PushDeclContext(Actions.getCurScope(), *II);
1341 assert(!LPT.Toks.empty() && "Empty body!");
1343 // Append the current token at the end of the new token stream so that it
1344 // doesn't get lost.
1345 LPT.Toks.push_back(Tok);
1346 PP.EnterTokenStream(LPT.Toks.data(), LPT.Toks.size(), true, false);
1348 // Consume the previously pushed token.
1349 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1350 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1351 "Inline method not starting with '{', ':' or 'try'");
1353 // Parse the method body. Function body parsing code is similar enough
1354 // to be re-used for method bodies as well.
1355 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1357 // Recreate the containing function DeclContext.
1358 Sema::ContextRAII FunctionSavedContext(Actions,
1359 Actions.getContainingDC(FunD));
1361 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1363 if (Tok.is(tok::kw_try)) {
1364 ParseFunctionTryBlock(LPT.D, FnScope);
1366 if (Tok.is(tok::colon))
1367 ParseConstructorInitializer(LPT.D);
1369 Actions.ActOnDefaultCtorInitializers(LPT.D);
1371 if (Tok.is(tok::l_brace)) {
1372 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1373 cast<FunctionTemplateDecl>(LPT.D)
1374 ->getTemplateParameters()
1375 ->getDepth() == TemplateParameterDepth - 1) &&
1376 "TemplateParameterDepth should be greater than the depth of "
1377 "current template being instantiated!");
1378 ParseFunctionStatementBody(LPT.D, FnScope);
1379 Actions.UnmarkAsLateParsedTemplate(FunD);
1381 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1386 SmallVectorImpl<ParseScope *>::reverse_iterator I =
1387 TemplateParamScopeStack.rbegin();
1388 for (; I != TemplateParamScopeStack.rend(); ++I)
1392 /// \brief Lex a delayed template function for late parsing.
1393 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1394 tok::TokenKind kind = Tok.getKind();
1395 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1396 // Consume everything up to (and including) the matching right brace.
1397 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1400 // If we're in a function-try-block, we need to store all the catch blocks.
1401 if (kind == tok::kw_try) {
1402 while (Tok.is(tok::kw_catch)) {
1403 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1404 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);