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/DeclTemplate.h"
18 #include "clang/Parse/ParseDiagnostic.h"
19 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/ParsedTemplate.h"
21 #include "clang/Sema/Scope.h"
22 using namespace clang;
24 /// \brief Parse a template declaration, explicit instantiation, or
25 /// explicit specialization.
27 Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
28 SourceLocation &DeclEnd,
30 AttributeList *AccessAttrs) {
31 ObjCDeclContextSwitch ObjCDC(*this);
33 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
34 return ParseExplicitInstantiation(Context,
35 SourceLocation(), ConsumeToken(),
38 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
44 /// \brief Parse a template declaration or an explicit specialization.
46 /// Template declarations include one or more template parameter lists
47 /// and either the function or class template declaration. Explicit
48 /// specializations contain one or more 'template < >' prefixes
49 /// followed by a (possibly templated) declaration. Since the
50 /// syntactic form of both features is nearly identical, we parse all
51 /// of the template headers together and let semantic analysis sort
52 /// the declarations from the explicit specializations.
54 /// template-declaration: [C++ temp]
55 /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
57 /// explicit-specialization: [ C++ temp.expl.spec]
58 /// 'template' '<' '>' declaration
60 Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
61 SourceLocation &DeclEnd,
63 AttributeList *AccessAttrs) {
64 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
65 "Token does not start a template declaration.");
67 // Enter template-parameter scope.
68 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
70 // Tell the action that names should be checked in the context of
71 // the declaration to come.
73 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
75 // Parse multiple levels of template headers within this template
76 // parameter scope, e.g.,
78 // template<typename T>
79 // template<typename U>
80 // class A<T>::B { ... };
82 // We parse multiple levels non-recursively so that we can build a
83 // single data structure containing all of the template parameter
84 // lists to easily differentiate between the case above and:
86 // template<typename T>
88 // template<typename U> class B;
91 // In the first case, the action for declaring A<T>::B receives
92 // both template parameter lists. In the second case, the action for
93 // defining A<T>::B receives just the inner template parameter list
94 // (and retrieves the outer template parameter list from its
96 bool isSpecialization = true;
97 bool LastParamListWasEmpty = false;
98 TemplateParameterLists ParamLists;
99 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
102 // Consume the 'export', if any.
103 SourceLocation ExportLoc;
104 TryConsumeToken(tok::kw_export, ExportLoc);
106 // Consume the 'template', which should be here.
107 SourceLocation TemplateLoc;
108 if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
109 Diag(Tok.getLocation(), diag::err_expected_template);
113 // Parse the '<' template-parameter-list '>'
114 SourceLocation LAngleLoc, RAngleLoc;
115 SmallVector<Decl*, 4> TemplateParams;
116 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
117 TemplateParams, LAngleLoc, RAngleLoc)) {
118 // Skip until the semi-colon or a }.
119 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
120 TryConsumeToken(tok::semi);
124 ParamLists.push_back(
125 Actions.ActOnTemplateParameterList(CurTemplateDepthTracker.getDepth(),
127 TemplateLoc, LAngleLoc,
128 TemplateParams.data(),
129 TemplateParams.size(), RAngleLoc));
131 if (!TemplateParams.empty()) {
132 isSpecialization = false;
133 ++CurTemplateDepthTracker;
135 LastParamListWasEmpty = true;
137 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
139 // Parse the actual template declaration.
140 return ParseSingleDeclarationAfterTemplate(Context,
141 ParsedTemplateInfo(&ParamLists,
143 LastParamListWasEmpty),
144 ParsingTemplateParams,
145 DeclEnd, AS, AccessAttrs);
148 /// \brief Parse a single declaration that declares a template,
149 /// template specialization, or explicit instantiation of a template.
151 /// \param DeclEnd will receive the source location of the last token
152 /// within this declaration.
154 /// \param AS the access specifier associated with this
155 /// declaration. Will be AS_none for namespace-scope declarations.
157 /// \returns the new declaration.
159 Parser::ParseSingleDeclarationAfterTemplate(
161 const ParsedTemplateInfo &TemplateInfo,
162 ParsingDeclRAIIObject &DiagsFromTParams,
163 SourceLocation &DeclEnd,
165 AttributeList *AccessAttrs) {
166 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
167 "Template information required");
169 if (Tok.is(tok::kw_static_assert)) {
170 // A static_assert declaration may not be templated.
171 Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
172 << TemplateInfo.getSourceRange();
173 // Parse the static_assert declaration to improve error recovery.
174 return ParseStaticAssertDeclaration(DeclEnd);
177 if (Context == Declarator::MemberContext) {
178 // We are parsing a member template.
179 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
184 ParsedAttributesWithRange prefixAttrs(AttrFactory);
185 MaybeParseCXX11Attributes(prefixAttrs);
187 if (Tok.is(tok::kw_using))
188 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
191 // Parse the declaration specifiers, stealing any diagnostics from
192 // the template parameters.
193 ParsingDeclSpec DS(*this, &DiagsFromTParams);
195 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
196 getDeclSpecContextFromDeclaratorContext(Context));
198 if (Tok.is(tok::semi)) {
199 ProhibitAttributes(prefixAttrs);
200 DeclEnd = ConsumeToken();
201 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
202 getCurScope(), AS, DS,
203 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
204 : MultiTemplateParamsArg(),
205 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation);
210 // Move the attributes from the prefix into the DS.
211 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
212 ProhibitAttributes(prefixAttrs);
214 DS.takeAttributesFrom(prefixAttrs);
216 // Parse the declarator.
217 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
218 ParseDeclarator(DeclaratorInfo);
219 // Error parsing the declarator?
220 if (!DeclaratorInfo.hasName()) {
221 // If so, skip until the semi-colon or a }.
222 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
223 if (Tok.is(tok::semi))
228 LateParsedAttrList LateParsedAttrs(true);
229 if (DeclaratorInfo.isFunctionDeclarator())
230 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
232 if (DeclaratorInfo.isFunctionDeclarator() &&
233 isStartOfFunctionDefinition(DeclaratorInfo)) {
235 // Function definitions are only allowed at file scope and in C++ classes.
236 // The C++ inline method definition case is handled elsewhere, so we only
237 // need to handle the file scope definition case.
238 if (Context != Declarator::FileContext) {
239 Diag(Tok, diag::err_function_definition_not_allowed);
244 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
245 // Recover by ignoring the 'typedef'. This was probably supposed to be
246 // the 'typename' keyword, which we should have already suggested adding
247 // if it's appropriate.
248 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
249 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
250 DS.ClearStorageClassSpecs();
253 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
254 if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
255 // If the declarator-id is not a template-id, issue a diagnostic and
256 // recover by ignoring the 'template' keyword.
257 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
258 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
261 SourceLocation LAngleLoc
262 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
263 Diag(DeclaratorInfo.getIdentifierLoc(),
264 diag::err_explicit_instantiation_with_definition)
265 << SourceRange(TemplateInfo.TemplateLoc)
266 << FixItHint::CreateInsertion(LAngleLoc, "<>");
268 // Recover as if it were an explicit specialization.
269 TemplateParameterLists FakedParamLists;
270 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
271 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr,
274 return ParseFunctionDefinition(
275 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
276 /*isSpecialization=*/true,
277 /*LastParamListWasEmpty=*/true),
281 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
285 // Parse this declaration.
286 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
289 if (Tok.is(tok::comma)) {
290 Diag(Tok, diag::err_multiple_template_declarators)
291 << (int)TemplateInfo.Kind;
292 SkipUntil(tok::semi);
296 // Eat the semi colon after the declaration.
297 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
298 if (LateParsedAttrs.size() > 0)
299 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
300 DeclaratorInfo.complete(ThisDecl);
304 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
305 /// angle brackets. Depth is the depth of this template-parameter-list, which
306 /// is the number of template headers directly enclosing this template header.
307 /// TemplateParams is the current list of template parameters we're building.
308 /// The template parameter we parse will be added to this list. LAngleLoc and
309 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
310 /// that enclose this template parameter list.
312 /// \returns true if an error occurred, false otherwise.
313 bool Parser::ParseTemplateParameters(unsigned Depth,
314 SmallVectorImpl<Decl*> &TemplateParams,
315 SourceLocation &LAngleLoc,
316 SourceLocation &RAngleLoc) {
317 // Get the template parameter list.
318 if (!TryConsumeToken(tok::less, LAngleLoc)) {
319 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
323 // Try to parse the template parameter list.
325 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
326 Failed = ParseTemplateParameterList(Depth, TemplateParams);
328 if (Tok.is(tok::greatergreater)) {
329 // No diagnostic required here: a template-parameter-list can only be
330 // followed by a declaration or, for a template template parameter, the
331 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
332 // This matters for elegant diagnosis of:
333 // template<template<typename>> struct S;
334 Tok.setKind(tok::greater);
335 RAngleLoc = Tok.getLocation();
336 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
337 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
338 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
344 /// ParseTemplateParameterList - Parse a template parameter list. If
345 /// the parsing fails badly (i.e., closing bracket was left out), this
346 /// will try to put the token stream in a reasonable position (closing
347 /// a statement, etc.) and return false.
349 /// template-parameter-list: [C++ temp]
350 /// template-parameter
351 /// template-parameter-list ',' template-parameter
353 Parser::ParseTemplateParameterList(unsigned Depth,
354 SmallVectorImpl<Decl*> &TemplateParams) {
357 = ParseTemplateParameter(Depth, TemplateParams.size())) {
358 TemplateParams.push_back(TmpParam);
360 // If we failed to parse a template parameter, skip until we find
361 // a comma or closing brace.
362 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
363 StopAtSemi | StopBeforeMatch);
366 // Did we find a comma or the end of the template parameter list?
367 if (Tok.is(tok::comma)) {
369 } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
370 // Don't consume this... that's done by template parser.
373 // Somebody probably forgot to close the template. Skip ahead and
374 // try to get out of the expression. This error is currently
375 // subsumed by whatever goes on in ParseTemplateParameter.
376 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
377 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
378 StopAtSemi | StopBeforeMatch);
385 /// \brief Determine whether the parser is at the start of a template
387 bool Parser::isStartOfTemplateTypeParameter() {
388 if (Tok.is(tok::kw_class)) {
389 // "class" may be the start of an elaborated-type-specifier or a
390 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
391 switch (NextToken().getKind()) {
395 case tok::greatergreater:
399 case tok::identifier:
400 // This may be either a type-parameter or an elaborated-type-specifier.
401 // We have to look further.
408 switch (GetLookAheadToken(2).getKind()) {
412 case tok::greatergreater:
420 if (Tok.isNot(tok::kw_typename))
423 // C++ [temp.param]p2:
424 // There is no semantic difference between class and typename in a
425 // template-parameter. typename followed by an unqualified-id
426 // names a template type parameter. typename followed by a
427 // qualified-id denotes the type in a non-type
428 // parameter-declaration.
429 Token Next = NextToken();
431 // If we have an identifier, skip over it.
432 if (Next.getKind() == tok::identifier)
433 Next = GetLookAheadToken(2);
435 switch (Next.getKind()) {
439 case tok::greatergreater:
448 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
450 /// template-parameter: [C++ temp.param]
452 /// parameter-declaration
454 /// type-parameter: (see below)
455 /// 'class' ...[opt] identifier[opt]
456 /// 'class' identifier[opt] '=' type-id
457 /// 'typename' ...[opt] identifier[opt]
458 /// 'typename' identifier[opt] '=' type-id
459 /// 'template' '<' template-parameter-list '>'
460 /// 'class' ...[opt] identifier[opt]
461 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
463 Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
464 if (isStartOfTemplateTypeParameter())
465 return ParseTypeParameter(Depth, Position);
467 if (Tok.is(tok::kw_template))
468 return ParseTemplateTemplateParameter(Depth, Position);
470 // If it's none of the above, then it must be a parameter declaration.
471 // NOTE: This will pick up errors in the closure of the template parameter
472 // list (e.g., template < ; Check here to implement >> style closures.
473 return ParseNonTypeTemplateParameter(Depth, Position);
476 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
477 /// Other kinds of template parameters are parsed in
478 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
480 /// type-parameter: [C++ temp.param]
481 /// 'class' ...[opt][C++0x] identifier[opt]
482 /// 'class' identifier[opt] '=' type-id
483 /// 'typename' ...[opt][C++0x] identifier[opt]
484 /// 'typename' identifier[opt] '=' type-id
485 Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
486 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
487 "A type-parameter starts with 'class' or 'typename'");
489 // Consume the 'class' or 'typename' keyword.
490 bool TypenameKeyword = Tok.is(tok::kw_typename);
491 SourceLocation KeyLoc = ConsumeToken();
493 // Grab the ellipsis (if given).
494 SourceLocation EllipsisLoc;
495 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
497 getLangOpts().CPlusPlus11
498 ? diag::warn_cxx98_compat_variadic_templates
499 : diag::ext_variadic_templates);
502 // Grab the template parameter name (if given)
503 SourceLocation NameLoc;
504 IdentifierInfo *ParamName = nullptr;
505 if (Tok.is(tok::identifier)) {
506 ParamName = Tok.getIdentifierInfo();
507 NameLoc = ConsumeToken();
508 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
509 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
510 // Unnamed template parameter. Don't have to do anything here, just
511 // don't consume this token.
513 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
517 // Recover from misplaced ellipsis.
518 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
519 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
520 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
522 // Grab a default argument (if available).
523 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
524 // we introduce the type parameter into the local scope.
525 SourceLocation EqualLoc;
526 ParsedType DefaultArg;
527 if (TryConsumeToken(tok::equal, EqualLoc))
528 DefaultArg = ParseTypeName(/*Range=*/nullptr,
529 Declarator::TemplateTypeArgContext).get();
531 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
532 KeyLoc, ParamName, NameLoc, Depth, Position,
533 EqualLoc, DefaultArg);
536 /// ParseTemplateTemplateParameter - Handle the parsing of template
537 /// template parameters.
539 /// type-parameter: [C++ temp.param]
540 /// 'template' '<' template-parameter-list '>' type-parameter-key
541 /// ...[opt] identifier[opt]
542 /// 'template' '<' template-parameter-list '>' type-parameter-key
543 /// identifier[opt] = id-expression
544 /// type-parameter-key:
546 /// 'typename' [C++1z]
548 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
549 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
551 // Handle the template <...> part.
552 SourceLocation TemplateLoc = ConsumeToken();
553 SmallVector<Decl*,8> TemplateParams;
554 SourceLocation LAngleLoc, RAngleLoc;
556 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
557 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
563 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
564 // Generate a meaningful error if the user forgot to put class before the
565 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
566 // or greater appear immediately or after 'struct'. In the latter case,
567 // replace the keyword with 'class'.
568 if (!TryConsumeToken(tok::kw_class)) {
569 bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
570 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
571 if (Tok.is(tok::kw_typename)) {
572 Diag(Tok.getLocation(),
573 getLangOpts().CPlusPlus1z
574 ? diag::warn_cxx14_compat_template_template_param_typename
575 : diag::ext_template_template_param_typename)
576 << (!getLangOpts().CPlusPlus1z
577 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
579 } else if (Next.is(tok::identifier) || Next.is(tok::comma) ||
580 Next.is(tok::greater) || Next.is(tok::greatergreater) ||
581 Next.is(tok::ellipsis)) {
582 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
583 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
584 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
586 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
592 // Parse the ellipsis, if given.
593 SourceLocation EllipsisLoc;
594 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
596 getLangOpts().CPlusPlus11
597 ? diag::warn_cxx98_compat_variadic_templates
598 : diag::ext_variadic_templates);
600 // Get the identifier, if given.
601 SourceLocation NameLoc;
602 IdentifierInfo *ParamName = nullptr;
603 if (Tok.is(tok::identifier)) {
604 ParamName = Tok.getIdentifierInfo();
605 NameLoc = ConsumeToken();
606 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
607 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
608 // Unnamed template parameter. Don't have to do anything here, just
609 // don't consume this token.
611 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
615 // Recover from misplaced ellipsis.
616 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
617 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
618 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
620 TemplateParameterList *ParamList =
621 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
622 TemplateLoc, LAngleLoc,
623 TemplateParams.data(),
624 TemplateParams.size(),
627 // Grab a default argument (if available).
628 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
629 // we introduce the template parameter into the local scope.
630 SourceLocation EqualLoc;
631 ParsedTemplateArgument DefaultArg;
632 if (TryConsumeToken(tok::equal, EqualLoc)) {
633 DefaultArg = ParseTemplateTemplateArgument();
634 if (DefaultArg.isInvalid()) {
635 Diag(Tok.getLocation(),
636 diag::err_default_template_template_parameter_not_template);
637 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
638 StopAtSemi | StopBeforeMatch);
642 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
643 ParamList, EllipsisLoc,
644 ParamName, NameLoc, Depth,
645 Position, EqualLoc, DefaultArg);
648 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
649 /// template parameters (e.g., in "template<int Size> class array;").
651 /// template-parameter:
653 /// parameter-declaration
655 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
656 // Parse the declaration-specifiers (i.e., the type).
657 // FIXME: The type should probably be restricted in some way... Not all
658 // declarators (parts of declarators?) are accepted for parameters.
659 DeclSpec DS(AttrFactory);
660 ParseDeclarationSpecifiers(DS);
662 // Parse this as a typename.
663 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
664 ParseDeclarator(ParamDecl);
665 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
666 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
670 // Recover from misplaced ellipsis.
671 SourceLocation EllipsisLoc;
672 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
673 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
675 // If there is a default value, parse it.
676 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
677 // we introduce the template parameter into the local scope.
678 SourceLocation EqualLoc;
679 ExprResult DefaultArg;
680 if (TryConsumeToken(tok::equal, EqualLoc)) {
681 // C++ [temp.param]p15:
682 // When parsing a default template-argument for a non-type
683 // template-parameter, the first non-nested > is taken as the
684 // end of the template-parameter-list rather than a greater-than
686 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
687 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
689 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
690 if (DefaultArg.isInvalid())
691 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
694 // Create the parameter.
695 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
696 Depth, Position, EqualLoc,
700 void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
701 SourceLocation CorrectLoc,
702 bool AlreadyHasEllipsis,
703 bool IdentifierHasName) {
705 if (!AlreadyHasEllipsis)
706 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
707 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
708 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
709 << !IdentifierHasName;
712 void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
714 assert(EllipsisLoc.isValid());
715 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
716 if (!AlreadyHasEllipsis)
717 D.setEllipsisLoc(EllipsisLoc);
718 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
719 AlreadyHasEllipsis, D.hasName());
722 /// \brief Parses a '>' at the end of a template list.
724 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
725 /// to determine if these tokens were supposed to be a '>' followed by
726 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
728 /// \param RAngleLoc the location of the consumed '>'.
730 /// \param ConsumeLastToken if true, the '>' is not consumed.
732 /// \returns true, if current token does not start with '>', false otherwise.
733 bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
734 bool ConsumeLastToken) {
735 // What will be left once we've consumed the '>'.
736 tok::TokenKind RemainingToken;
737 const char *ReplacementStr = "> >";
739 switch (Tok.getKind()) {
741 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
745 // Determine the location of the '>' token. Only consume this token
746 // if the caller asked us to.
747 RAngleLoc = Tok.getLocation();
748 if (ConsumeLastToken)
752 case tok::greatergreater:
753 RemainingToken = tok::greater;
756 case tok::greatergreatergreater:
757 RemainingToken = tok::greatergreater;
760 case tok::greaterequal:
761 RemainingToken = tok::equal;
762 ReplacementStr = "> =";
765 case tok::greatergreaterequal:
766 RemainingToken = tok::greaterequal;
770 // This template-id is terminated by a token which starts with a '>'. Outside
771 // C++11, this is now error recovery, and in C++11, this is error recovery if
772 // the token isn't '>>' or '>>>'.
773 // '>>>' is for CUDA, where this sequence of characters is parsed into
774 // tok::greatergreatergreater, rather than two separate tokens.
776 RAngleLoc = Tok.getLocation();
778 // The source range of the '>>' or '>=' at the start of the token.
779 CharSourceRange ReplacementRange =
780 CharSourceRange::getCharRange(RAngleLoc,
781 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
784 // A hint to put a space between the '>>'s. In order to make the hint as
785 // clear as possible, we include the characters either side of the space in
786 // the replacement, rather than just inserting a space at SecondCharLoc.
787 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
790 // A hint to put another space after the token, if it would otherwise be
791 // lexed differently.
793 Token Next = NextToken();
794 if ((RemainingToken == tok::greater ||
795 RemainingToken == tok::greatergreater) &&
796 (Next.is(tok::greater) || Next.is(tok::greatergreater) ||
797 Next.is(tok::greatergreatergreater) || Next.is(tok::equal) ||
798 Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) ||
799 Next.is(tok::equalequal)) &&
800 areTokensAdjacent(Tok, Next))
801 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
803 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
804 if (getLangOpts().CPlusPlus11 &&
805 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
806 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
807 else if (Tok.is(tok::greaterequal))
808 DiagId = diag::err_right_angle_bracket_equal_needs_space;
809 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
811 // Strip the initial '>' from the token.
812 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
813 areTokensAdjacent(Tok, Next)) {
814 // Join two adjacent '=' tokens into one, for cases like:
815 // void (*p)() = f<int>;
818 Tok.setKind(tok::equalequal);
819 Tok.setLength(Tok.getLength() + 1);
821 Tok.setKind(RemainingToken);
822 Tok.setLength(Tok.getLength() - 1);
824 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
825 PP.getSourceManager(),
828 if (!ConsumeLastToken) {
829 // Since we're not supposed to consume the '>' token, we need to push
830 // this token and revert the current token back to the '>'.
832 Tok.setKind(tok::greater);
834 Tok.setLocation(RAngleLoc);
840 /// \brief Parses a template-id that after the template name has
841 /// already been parsed.
843 /// This routine takes care of parsing the enclosed template argument
844 /// list ('<' template-parameter-list [opt] '>') and placing the
845 /// results into a form that can be transferred to semantic analysis.
847 /// \param Template the template declaration produced by isTemplateName
849 /// \param TemplateNameLoc the source location of the template name
851 /// \param SS if non-NULL, the nested-name-specifier preceding the
854 /// \param ConsumeLastToken if true, then we will consume the last
855 /// token that forms the template-id. Otherwise, we will leave the
856 /// last token in the stream (e.g., so that it can be replaced with an
857 /// annotation token).
859 Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
860 SourceLocation TemplateNameLoc,
861 const CXXScopeSpec &SS,
862 bool ConsumeLastToken,
863 SourceLocation &LAngleLoc,
864 TemplateArgList &TemplateArgs,
865 SourceLocation &RAngleLoc) {
866 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
869 LAngleLoc = ConsumeToken();
871 // Parse the optional template-argument-list.
872 bool Invalid = false;
874 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
875 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
876 Invalid = ParseTemplateArgumentList(TemplateArgs);
879 // Try to find the closing '>'.
880 if (ConsumeLastToken)
881 SkipUntil(tok::greater, StopAtSemi);
883 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
888 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken);
891 /// \brief Replace the tokens that form a simple-template-id with an
892 /// annotation token containing the complete template-id.
894 /// The first token in the stream must be the name of a template that
895 /// is followed by a '<'. This routine will parse the complete
896 /// simple-template-id and replace the tokens with a single annotation
897 /// token with one of two different kinds: if the template-id names a
898 /// type (and \p AllowTypeAnnotation is true), the annotation token is
899 /// a type annotation that includes the optional nested-name-specifier
900 /// (\p SS). Otherwise, the annotation token is a template-id
901 /// annotation that does not include the optional
902 /// nested-name-specifier.
904 /// \param Template the declaration of the template named by the first
905 /// token (an identifier), as returned from \c Action::isTemplateName().
907 /// \param TNK the kind of template that \p Template
908 /// refers to, as returned from \c Action::isTemplateName().
910 /// \param SS if non-NULL, the nested-name-specifier that precedes
911 /// this template name.
913 /// \param TemplateKWLoc if valid, specifies that this template-id
914 /// annotation was preceded by the 'template' keyword and gives the
915 /// location of that keyword. If invalid (the default), then this
916 /// template-id was not preceded by a 'template' keyword.
918 /// \param AllowTypeAnnotation if true (the default), then a
919 /// simple-template-id that refers to a class template, template
920 /// template parameter, or other template that produces a type will be
921 /// replaced with a type annotation token. Otherwise, the
922 /// simple-template-id is always replaced with a template-id
923 /// annotation token.
925 /// If an unrecoverable parse error occurs and no annotation token can be
926 /// formed, this function returns true.
928 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
930 SourceLocation TemplateKWLoc,
931 UnqualifiedId &TemplateName,
932 bool AllowTypeAnnotation) {
933 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
934 assert(Template && Tok.is(tok::less) &&
935 "Parser isn't at the beginning of a template-id");
937 // Consume the template-name.
938 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
940 // Parse the enclosed template argument list.
941 SourceLocation LAngleLoc, RAngleLoc;
942 TemplateArgList TemplateArgs;
943 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
945 SS, false, LAngleLoc,
950 // If we failed to parse the template ID but skipped ahead to a >, we're not
951 // going to be able to form a token annotation. Eat the '>' if present.
952 TryConsumeToken(tok::greater);
956 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
958 // Build the annotation token.
959 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
961 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
962 Template, TemplateNameLoc,
963 LAngleLoc, TemplateArgsPtr, RAngleLoc);
964 if (Type.isInvalid()) {
965 // If we failed to parse the template ID but skipped ahead to a >, we're not
966 // going to be able to form a token annotation. Eat the '>' if present.
967 TryConsumeToken(tok::greater);
971 Tok.setKind(tok::annot_typename);
972 setTypeAnnotation(Tok, Type.get());
974 Tok.setLocation(SS.getBeginLoc());
975 else if (TemplateKWLoc.isValid())
976 Tok.setLocation(TemplateKWLoc);
978 Tok.setLocation(TemplateNameLoc);
980 // Build a template-id annotation token that can be processed
982 Tok.setKind(tok::annot_template_id);
983 TemplateIdAnnotation *TemplateId
984 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
985 TemplateId->TemplateNameLoc = TemplateNameLoc;
986 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
987 TemplateId->Name = TemplateName.Identifier;
988 TemplateId->Operator = OO_None;
990 TemplateId->Name = nullptr;
991 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
994 TemplateId->TemplateKWLoc = TemplateKWLoc;
995 TemplateId->Template = Template;
996 TemplateId->Kind = TNK;
997 TemplateId->LAngleLoc = LAngleLoc;
998 TemplateId->RAngleLoc = RAngleLoc;
999 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1000 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
1001 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
1002 Tok.setAnnotationValue(TemplateId);
1003 if (TemplateKWLoc.isValid())
1004 Tok.setLocation(TemplateKWLoc);
1006 Tok.setLocation(TemplateNameLoc);
1009 // Common fields for the annotation token
1010 Tok.setAnnotationEndLoc(RAngleLoc);
1012 // In case the tokens were cached, have Preprocessor replace them with the
1013 // annotation token.
1014 PP.AnnotateCachedTokens(Tok);
1018 /// \brief Replaces a template-id annotation token with a type
1019 /// annotation token.
1021 /// If there was a failure when forming the type from the template-id,
1022 /// a type annotation token will still be created, but will have a
1023 /// NULL type pointer to signify an error.
1024 void Parser::AnnotateTemplateIdTokenAsType() {
1025 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1027 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1028 assert((TemplateId->Kind == TNK_Type_template ||
1029 TemplateId->Kind == TNK_Dependent_template_name) &&
1030 "Only works for type and dependent templates");
1032 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1033 TemplateId->NumArgs);
1036 = Actions.ActOnTemplateIdType(TemplateId->SS,
1037 TemplateId->TemplateKWLoc,
1038 TemplateId->Template,
1039 TemplateId->TemplateNameLoc,
1040 TemplateId->LAngleLoc,
1042 TemplateId->RAngleLoc);
1043 // Create the new "type" annotation token.
1044 Tok.setKind(tok::annot_typename);
1045 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
1046 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1047 Tok.setLocation(TemplateId->SS.getBeginLoc());
1048 // End location stays the same
1050 // Replace the template-id annotation token, and possible the scope-specifier
1051 // that precedes it, with the typename annotation token.
1052 PP.AnnotateCachedTokens(Tok);
1055 /// \brief Determine whether the given token can end a template argument.
1056 static bool isEndOfTemplateArgument(Token Tok) {
1057 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
1058 Tok.is(tok::greatergreater);
1061 /// \brief Parse a C++ template template argument.
1062 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1063 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1064 !Tok.is(tok::annot_cxxscope))
1065 return ParsedTemplateArgument();
1067 // C++0x [temp.arg.template]p1:
1068 // A template-argument for a template template-parameter shall be the name
1069 // of a class template or an alias template, expressed as id-expression.
1071 // We parse an id-expression that refers to a class template or alias
1072 // template. The grammar we parse is:
1074 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1076 // followed by a token that terminates a template argument, such as ',',
1077 // '>', or (in some cases) '>>'.
1078 CXXScopeSpec SS; // nested-name-specifier, if present
1079 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1080 /*EnteringContext=*/false);
1082 ParsedTemplateArgument Result;
1083 SourceLocation EllipsisLoc;
1084 if (SS.isSet() && Tok.is(tok::kw_template)) {
1085 // Parse the optional 'template' keyword following the
1086 // nested-name-specifier.
1087 SourceLocation TemplateKWLoc = ConsumeToken();
1089 if (Tok.is(tok::identifier)) {
1090 // We appear to have a dependent template name.
1092 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1093 ConsumeToken(); // the identifier
1095 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1097 // If the next token signals the end of a template argument,
1098 // then we have a dependent template name that could be a template
1099 // template argument.
1100 TemplateTy Template;
1101 if (isEndOfTemplateArgument(Tok) &&
1102 Actions.ActOnDependentTemplateName(getCurScope(),
1103 SS, TemplateKWLoc, Name,
1104 /*ObjectType=*/ ParsedType(),
1105 /*EnteringContext=*/false,
1107 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1109 } else if (Tok.is(tok::identifier)) {
1110 // We may have a (non-dependent) template name.
1111 TemplateTy Template;
1113 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1114 ConsumeToken(); // the identifier
1116 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1118 if (isEndOfTemplateArgument(Tok)) {
1119 bool MemberOfUnknownSpecialization;
1120 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1121 /*hasTemplateKeyword=*/false,
1123 /*ObjectType=*/ ParsedType(),
1124 /*EnteringContext=*/false,
1126 MemberOfUnknownSpecialization);
1127 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1128 // We have an id-expression that refers to a class template or
1129 // (C++0x) alias template.
1130 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1135 // If this is a pack expansion, build it as such.
1136 if (EllipsisLoc.isValid() && !Result.isInvalid())
1137 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1142 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1144 /// template-argument: [C++ 14.2]
1145 /// constant-expression
1148 ParsedTemplateArgument Parser::ParseTemplateArgument() {
1149 // C++ [temp.arg]p2:
1150 // In a template-argument, an ambiguity between a type-id and an
1151 // expression is resolved to a type-id, regardless of the form of
1152 // the corresponding template-parameter.
1154 // Therefore, we initially try to parse a type-id.
1155 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1156 SourceLocation Loc = Tok.getLocation();
1157 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
1158 Declarator::TemplateTypeArgContext);
1159 if (TypeArg.isInvalid())
1160 return ParsedTemplateArgument();
1162 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1163 TypeArg.get().getAsOpaquePtr(),
1167 // Try to parse a template template argument.
1169 TentativeParsingAction TPA(*this);
1171 ParsedTemplateArgument TemplateTemplateArgument
1172 = ParseTemplateTemplateArgument();
1173 if (!TemplateTemplateArgument.isInvalid()) {
1175 return TemplateTemplateArgument;
1178 // Revert this tentative parse to parse a non-type template argument.
1182 // Parse a non-type template argument.
1183 SourceLocation Loc = Tok.getLocation();
1184 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1185 if (ExprArg.isInvalid() || !ExprArg.get())
1186 return ParsedTemplateArgument();
1188 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1189 ExprArg.get(), Loc);
1192 /// \brief Determine whether the current tokens can only be parsed as a
1193 /// template argument list (starting with the '<') and never as a '<'
1195 bool Parser::IsTemplateArgumentList(unsigned Skip) {
1196 struct AlwaysRevertAction : TentativeParsingAction {
1197 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1198 ~AlwaysRevertAction() { Revert(); }
1207 if (!TryConsumeToken(tok::less))
1210 // An empty template argument list.
1211 if (Tok.is(tok::greater))
1214 // See whether we have declaration specifiers, which indicate a type.
1215 while (isCXXDeclarationSpecifier() == TPResult::True)
1218 // If we have a '>' or a ',' then this is a template argument list.
1219 return Tok.is(tok::greater) || Tok.is(tok::comma);
1222 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1223 /// (C++ [temp.names]). Returns true if there was an error.
1225 /// template-argument-list: [C++ 14.2]
1226 /// template-argument
1227 /// template-argument-list ',' template-argument
1229 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1230 // Template argument lists are constant-evaluation contexts.
1231 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
1232 ColonProtectionRAIIObject ColonProtection(*this, false);
1235 ParsedTemplateArgument Arg = ParseTemplateArgument();
1236 SourceLocation EllipsisLoc;
1237 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1238 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1240 if (Arg.isInvalid()) {
1241 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
1245 // Save this template argument.
1246 TemplateArgs.push_back(Arg);
1248 // If the next token is a comma, consume it and keep reading
1250 } while (TryConsumeToken(tok::comma));
1255 /// \brief Parse a C++ explicit template instantiation
1256 /// (C++ [temp.explicit]).
1258 /// explicit-instantiation:
1259 /// 'extern' [opt] 'template' declaration
1261 /// Note that the 'extern' is a GNU extension and C++11 feature.
1262 Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1263 SourceLocation ExternLoc,
1264 SourceLocation TemplateLoc,
1265 SourceLocation &DeclEnd,
1266 AccessSpecifier AS) {
1267 // This isn't really required here.
1268 ParsingDeclRAIIObject
1269 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1271 return ParseSingleDeclarationAfterTemplate(Context,
1272 ParsedTemplateInfo(ExternLoc,
1274 ParsingTemplateParams,
1278 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1280 return getTemplateParamsRange(TemplateParams->data(),
1281 TemplateParams->size());
1283 SourceRange R(TemplateLoc);
1284 if (ExternLoc.isValid())
1285 R.setBegin(ExternLoc);
1289 void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1290 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1293 /// \brief Late parse a C++ function template in Microsoft mode.
1294 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1298 // Get the FunctionDecl.
1299 FunctionDecl *FunD = LPT.D->getAsFunction();
1300 // Track template parameter depth.
1301 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1303 // To restore the context after late parsing.
1304 Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
1306 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1308 // Get the list of DeclContexts to reenter.
1309 SmallVector<DeclContext*, 4> DeclContextsToReenter;
1310 DeclContext *DD = FunD;
1311 while (DD && !DD->isTranslationUnit()) {
1312 DeclContextsToReenter.push_back(DD);
1313 DD = DD->getLexicalParent();
1316 // Reenter template scopes from outermost to innermost.
1317 SmallVectorImpl<DeclContext *>::reverse_iterator II =
1318 DeclContextsToReenter.rbegin();
1319 for (; II != DeclContextsToReenter.rend(); ++II) {
1320 TemplateParamScopeStack.push_back(new ParseScope(this,
1321 Scope::TemplateParamScope));
1322 unsigned NumParamLists =
1323 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1324 CurTemplateDepthTracker.addDepth(NumParamLists);
1326 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1327 Actions.PushDeclContext(Actions.getCurScope(), *II);
1331 assert(!LPT.Toks.empty() && "Empty body!");
1333 // Append the current token at the end of the new token stream so that it
1334 // doesn't get lost.
1335 LPT.Toks.push_back(Tok);
1336 PP.EnterTokenStream(LPT.Toks.data(), LPT.Toks.size(), true, false);
1338 // Consume the previously pushed token.
1339 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1340 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1341 && "Inline method not starting with '{', ':' or 'try'");
1343 // Parse the method body. Function body parsing code is similar enough
1344 // to be re-used for method bodies as well.
1345 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1347 // Recreate the containing function DeclContext.
1348 Sema::ContextRAII FunctionSavedContext(Actions,
1349 Actions.getContainingDC(FunD));
1351 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1353 if (Tok.is(tok::kw_try)) {
1354 ParseFunctionTryBlock(LPT.D, FnScope);
1356 if (Tok.is(tok::colon))
1357 ParseConstructorInitializer(LPT.D);
1359 Actions.ActOnDefaultCtorInitializers(LPT.D);
1361 if (Tok.is(tok::l_brace)) {
1362 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1363 cast<FunctionTemplateDecl>(LPT.D)
1364 ->getTemplateParameters()
1365 ->getDepth() == TemplateParameterDepth - 1) &&
1366 "TemplateParameterDepth should be greater than the depth of "
1367 "current template being instantiated!");
1368 ParseFunctionStatementBody(LPT.D, FnScope);
1369 Actions.UnmarkAsLateParsedTemplate(FunD);
1371 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1376 SmallVectorImpl<ParseScope *>::reverse_iterator I =
1377 TemplateParamScopeStack.rbegin();
1378 for (; I != TemplateParamScopeStack.rend(); ++I)
1382 /// \brief Lex a delayed template function for late parsing.
1383 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1384 tok::TokenKind kind = Tok.getKind();
1385 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1386 // Consume everything up to (and including) the matching right brace.
1387 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1390 // If we're in a function-try-block, we need to store all the catch blocks.
1391 if (kind == tok::kw_try) {
1392 while (Tok.is(tok::kw_catch)) {
1393 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1394 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);