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 (Context == Declarator::MemberContext) {
170 // We are parsing a member template.
171 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
176 ParsedAttributesWithRange prefixAttrs(AttrFactory);
177 MaybeParseCXX11Attributes(prefixAttrs);
179 if (Tok.is(tok::kw_using))
180 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
183 // Parse the declaration specifiers, stealing any diagnostics from
184 // the template parameters.
185 ParsingDeclSpec DS(*this, &DiagsFromTParams);
187 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
188 getDeclSpecContextFromDeclaratorContext(Context));
190 if (Tok.is(tok::semi)) {
191 ProhibitAttributes(prefixAttrs);
192 DeclEnd = ConsumeToken();
193 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
194 getCurScope(), AS, DS,
195 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
196 : MultiTemplateParamsArg(),
197 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation);
202 // Move the attributes from the prefix into the DS.
203 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
204 ProhibitAttributes(prefixAttrs);
206 DS.takeAttributesFrom(prefixAttrs);
208 // Parse the declarator.
209 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
210 ParseDeclarator(DeclaratorInfo);
211 // Error parsing the declarator?
212 if (!DeclaratorInfo.hasName()) {
213 // If so, skip until the semi-colon or a }.
214 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
215 if (Tok.is(tok::semi))
220 LateParsedAttrList LateParsedAttrs(true);
221 if (DeclaratorInfo.isFunctionDeclarator())
222 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
224 if (DeclaratorInfo.isFunctionDeclarator() &&
225 isStartOfFunctionDefinition(DeclaratorInfo)) {
226 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
227 // Recover by ignoring the 'typedef'. This was probably supposed to be
228 // the 'typename' keyword, which we should have already suggested adding
229 // if it's appropriate.
230 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
231 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
232 DS.ClearStorageClassSpecs();
235 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
236 if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
237 // If the declarator-id is not a template-id, issue a diagnostic and
238 // recover by ignoring the 'template' keyword.
239 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
240 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
243 SourceLocation LAngleLoc
244 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
245 Diag(DeclaratorInfo.getIdentifierLoc(),
246 diag::err_explicit_instantiation_with_definition)
247 << SourceRange(TemplateInfo.TemplateLoc)
248 << FixItHint::CreateInsertion(LAngleLoc, "<>");
250 // Recover as if it were an explicit specialization.
251 TemplateParameterLists FakedParamLists;
252 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
253 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr,
256 return ParseFunctionDefinition(
257 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
258 /*isSpecialization=*/true,
259 /*LastParamListWasEmpty=*/true),
263 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
267 // Parse this declaration.
268 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
271 if (Tok.is(tok::comma)) {
272 Diag(Tok, diag::err_multiple_template_declarators)
273 << (int)TemplateInfo.Kind;
274 SkipUntil(tok::semi);
278 // Eat the semi colon after the declaration.
279 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
280 if (LateParsedAttrs.size() > 0)
281 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
282 DeclaratorInfo.complete(ThisDecl);
286 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
287 /// angle brackets. Depth is the depth of this template-parameter-list, which
288 /// is the number of template headers directly enclosing this template header.
289 /// TemplateParams is the current list of template parameters we're building.
290 /// The template parameter we parse will be added to this list. LAngleLoc and
291 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
292 /// that enclose this template parameter list.
294 /// \returns true if an error occurred, false otherwise.
295 bool Parser::ParseTemplateParameters(unsigned Depth,
296 SmallVectorImpl<Decl*> &TemplateParams,
297 SourceLocation &LAngleLoc,
298 SourceLocation &RAngleLoc) {
299 // Get the template parameter list.
300 if (!TryConsumeToken(tok::less, LAngleLoc)) {
301 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
305 // Try to parse the template parameter list.
307 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
308 Failed = ParseTemplateParameterList(Depth, TemplateParams);
310 if (Tok.is(tok::greatergreater)) {
311 // No diagnostic required here: a template-parameter-list can only be
312 // followed by a declaration or, for a template template parameter, the
313 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
314 // This matters for elegant diagnosis of:
315 // template<template<typename>> struct S;
316 Tok.setKind(tok::greater);
317 RAngleLoc = Tok.getLocation();
318 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
319 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
320 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
326 /// ParseTemplateParameterList - Parse a template parameter list. If
327 /// the parsing fails badly (i.e., closing bracket was left out), this
328 /// will try to put the token stream in a reasonable position (closing
329 /// a statement, etc.) and return false.
331 /// template-parameter-list: [C++ temp]
332 /// template-parameter
333 /// template-parameter-list ',' template-parameter
335 Parser::ParseTemplateParameterList(unsigned Depth,
336 SmallVectorImpl<Decl*> &TemplateParams) {
339 = ParseTemplateParameter(Depth, TemplateParams.size())) {
340 TemplateParams.push_back(TmpParam);
342 // If we failed to parse a template parameter, skip until we find
343 // a comma or closing brace.
344 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
345 StopAtSemi | StopBeforeMatch);
348 // Did we find a comma or the end of the template parameter list?
349 if (Tok.is(tok::comma)) {
351 } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
352 // Don't consume this... that's done by template parser.
355 // Somebody probably forgot to close the template. Skip ahead and
356 // try to get out of the expression. This error is currently
357 // subsumed by whatever goes on in ParseTemplateParameter.
358 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
359 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
360 StopAtSemi | StopBeforeMatch);
367 /// \brief Determine whether the parser is at the start of a template
369 bool Parser::isStartOfTemplateTypeParameter() {
370 if (Tok.is(tok::kw_class)) {
371 // "class" may be the start of an elaborated-type-specifier or a
372 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
373 switch (NextToken().getKind()) {
377 case tok::greatergreater:
381 case tok::identifier:
382 // This may be either a type-parameter or an elaborated-type-specifier.
383 // We have to look further.
390 switch (GetLookAheadToken(2).getKind()) {
394 case tok::greatergreater:
402 if (Tok.isNot(tok::kw_typename))
405 // C++ [temp.param]p2:
406 // There is no semantic difference between class and typename in a
407 // template-parameter. typename followed by an unqualified-id
408 // names a template type parameter. typename followed by a
409 // qualified-id denotes the type in a non-type
410 // parameter-declaration.
411 Token Next = NextToken();
413 // If we have an identifier, skip over it.
414 if (Next.getKind() == tok::identifier)
415 Next = GetLookAheadToken(2);
417 switch (Next.getKind()) {
421 case tok::greatergreater:
430 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
432 /// template-parameter: [C++ temp.param]
434 /// parameter-declaration
436 /// type-parameter: (see below)
437 /// 'class' ...[opt] identifier[opt]
438 /// 'class' identifier[opt] '=' type-id
439 /// 'typename' ...[opt] identifier[opt]
440 /// 'typename' identifier[opt] '=' type-id
441 /// 'template' '<' template-parameter-list '>'
442 /// 'class' ...[opt] identifier[opt]
443 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
445 Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
446 if (isStartOfTemplateTypeParameter())
447 return ParseTypeParameter(Depth, Position);
449 if (Tok.is(tok::kw_template))
450 return ParseTemplateTemplateParameter(Depth, Position);
452 // If it's none of the above, then it must be a parameter declaration.
453 // NOTE: This will pick up errors in the closure of the template parameter
454 // list (e.g., template < ; Check here to implement >> style closures.
455 return ParseNonTypeTemplateParameter(Depth, Position);
458 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
459 /// Other kinds of template parameters are parsed in
460 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
462 /// type-parameter: [C++ temp.param]
463 /// 'class' ...[opt][C++0x] identifier[opt]
464 /// 'class' identifier[opt] '=' type-id
465 /// 'typename' ...[opt][C++0x] identifier[opt]
466 /// 'typename' identifier[opt] '=' type-id
467 Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
468 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
469 "A type-parameter starts with 'class' or 'typename'");
471 // Consume the 'class' or 'typename' keyword.
472 bool TypenameKeyword = Tok.is(tok::kw_typename);
473 SourceLocation KeyLoc = ConsumeToken();
475 // Grab the ellipsis (if given).
476 SourceLocation EllipsisLoc;
477 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
479 getLangOpts().CPlusPlus11
480 ? diag::warn_cxx98_compat_variadic_templates
481 : diag::ext_variadic_templates);
484 // Grab the template parameter name (if given)
485 SourceLocation NameLoc;
486 IdentifierInfo *ParamName = nullptr;
487 if (Tok.is(tok::identifier)) {
488 ParamName = Tok.getIdentifierInfo();
489 NameLoc = ConsumeToken();
490 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
491 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
492 // Unnamed template parameter. Don't have to do anything here, just
493 // don't consume this token.
495 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
499 // Recover from misplaced ellipsis.
500 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
501 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
502 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
504 // Grab a default argument (if available).
505 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
506 // we introduce the type parameter into the local scope.
507 SourceLocation EqualLoc;
508 ParsedType DefaultArg;
509 if (TryConsumeToken(tok::equal, EqualLoc))
510 DefaultArg = ParseTypeName(/*Range=*/nullptr,
511 Declarator::TemplateTypeArgContext).get();
513 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
514 KeyLoc, ParamName, NameLoc, Depth, Position,
515 EqualLoc, DefaultArg);
518 /// ParseTemplateTemplateParameter - Handle the parsing of template
519 /// template parameters.
521 /// type-parameter: [C++ temp.param]
522 /// 'template' '<' template-parameter-list '>' type-parameter-key
523 /// ...[opt] identifier[opt]
524 /// 'template' '<' template-parameter-list '>' type-parameter-key
525 /// identifier[opt] = id-expression
526 /// type-parameter-key:
528 /// 'typename' [C++1z]
530 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
531 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
533 // Handle the template <...> part.
534 SourceLocation TemplateLoc = ConsumeToken();
535 SmallVector<Decl*,8> TemplateParams;
536 SourceLocation LAngleLoc, RAngleLoc;
538 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
539 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
545 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
546 // Generate a meaningful error if the user forgot to put class before the
547 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
548 // or greater appear immediately or after 'struct'. In the latter case,
549 // replace the keyword with 'class'.
550 if (!TryConsumeToken(tok::kw_class)) {
551 bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
552 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
553 if (Tok.is(tok::kw_typename)) {
554 Diag(Tok.getLocation(),
555 getLangOpts().CPlusPlus1z
556 ? diag::warn_cxx1y_compat_template_template_param_typename
557 : diag::ext_template_template_param_typename)
558 << (!getLangOpts().CPlusPlus1z
559 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
561 } else if (Next.is(tok::identifier) || Next.is(tok::comma) ||
562 Next.is(tok::greater) || Next.is(tok::greatergreater) ||
563 Next.is(tok::ellipsis)) {
564 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
565 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
566 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
568 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
574 // Parse the ellipsis, if given.
575 SourceLocation EllipsisLoc;
576 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
578 getLangOpts().CPlusPlus11
579 ? diag::warn_cxx98_compat_variadic_templates
580 : diag::ext_variadic_templates);
582 // Get the identifier, if given.
583 SourceLocation NameLoc;
584 IdentifierInfo *ParamName = nullptr;
585 if (Tok.is(tok::identifier)) {
586 ParamName = Tok.getIdentifierInfo();
587 NameLoc = ConsumeToken();
588 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
589 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
590 // Unnamed template parameter. Don't have to do anything here, just
591 // don't consume this token.
593 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
597 // Recover from misplaced ellipsis.
598 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
599 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
600 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
602 TemplateParameterList *ParamList =
603 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
604 TemplateLoc, LAngleLoc,
605 TemplateParams.data(),
606 TemplateParams.size(),
609 // Grab a default argument (if available).
610 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
611 // we introduce the template parameter into the local scope.
612 SourceLocation EqualLoc;
613 ParsedTemplateArgument DefaultArg;
614 if (TryConsumeToken(tok::equal, EqualLoc)) {
615 DefaultArg = ParseTemplateTemplateArgument();
616 if (DefaultArg.isInvalid()) {
617 Diag(Tok.getLocation(),
618 diag::err_default_template_template_parameter_not_template);
619 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
620 StopAtSemi | StopBeforeMatch);
624 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
625 ParamList, EllipsisLoc,
626 ParamName, NameLoc, Depth,
627 Position, EqualLoc, DefaultArg);
630 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
631 /// template parameters (e.g., in "template<int Size> class array;").
633 /// template-parameter:
635 /// parameter-declaration
637 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
638 // Parse the declaration-specifiers (i.e., the type).
639 // FIXME: The type should probably be restricted in some way... Not all
640 // declarators (parts of declarators?) are accepted for parameters.
641 DeclSpec DS(AttrFactory);
642 ParseDeclarationSpecifiers(DS);
644 // Parse this as a typename.
645 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
646 ParseDeclarator(ParamDecl);
647 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
648 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
652 // Recover from misplaced ellipsis.
653 SourceLocation EllipsisLoc;
654 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
655 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
657 // If there is a default value, parse it.
658 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
659 // we introduce the template parameter into the local scope.
660 SourceLocation EqualLoc;
661 ExprResult DefaultArg;
662 if (TryConsumeToken(tok::equal, EqualLoc)) {
663 // C++ [temp.param]p15:
664 // When parsing a default template-argument for a non-type
665 // template-parameter, the first non-nested > is taken as the
666 // end of the template-parameter-list rather than a greater-than
668 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
669 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
671 DefaultArg = ParseAssignmentExpression();
672 if (DefaultArg.isInvalid())
673 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
676 // Create the parameter.
677 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
678 Depth, Position, EqualLoc,
682 void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
683 SourceLocation CorrectLoc,
684 bool AlreadyHasEllipsis,
685 bool IdentifierHasName) {
687 if (!AlreadyHasEllipsis)
688 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
689 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
690 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
691 << !IdentifierHasName;
694 void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
696 assert(EllipsisLoc.isValid());
697 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
698 if (!AlreadyHasEllipsis)
699 D.setEllipsisLoc(EllipsisLoc);
700 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
701 AlreadyHasEllipsis, D.hasName());
704 /// \brief Parses a '>' at the end of a template list.
706 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
707 /// to determine if these tokens were supposed to be a '>' followed by
708 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
710 /// \param RAngleLoc the location of the consumed '>'.
712 /// \param ConsumeLastToken if true, the '>' is not consumed.
714 /// \returns true, if current token does not start with '>', false otherwise.
715 bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
716 bool ConsumeLastToken) {
717 // What will be left once we've consumed the '>'.
718 tok::TokenKind RemainingToken;
719 const char *ReplacementStr = "> >";
721 switch (Tok.getKind()) {
723 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
727 // Determine the location of the '>' token. Only consume this token
728 // if the caller asked us to.
729 RAngleLoc = Tok.getLocation();
730 if (ConsumeLastToken)
734 case tok::greatergreater:
735 RemainingToken = tok::greater;
738 case tok::greatergreatergreater:
739 RemainingToken = tok::greatergreater;
742 case tok::greaterequal:
743 RemainingToken = tok::equal;
744 ReplacementStr = "> =";
747 case tok::greatergreaterequal:
748 RemainingToken = tok::greaterequal;
752 // This template-id is terminated by a token which starts with a '>'. Outside
753 // C++11, this is now error recovery, and in C++11, this is error recovery if
754 // the token isn't '>>' or '>>>'.
755 // '>>>' is for CUDA, where this sequence of characters is parsed into
756 // tok::greatergreatergreater, rather than two separate tokens.
758 RAngleLoc = Tok.getLocation();
760 // The source range of the '>>' or '>=' at the start of the token.
761 CharSourceRange ReplacementRange =
762 CharSourceRange::getCharRange(RAngleLoc,
763 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
766 // A hint to put a space between the '>>'s. In order to make the hint as
767 // clear as possible, we include the characters either side of the space in
768 // the replacement, rather than just inserting a space at SecondCharLoc.
769 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
772 // A hint to put another space after the token, if it would otherwise be
773 // lexed differently.
775 Token Next = NextToken();
776 if ((RemainingToken == tok::greater ||
777 RemainingToken == tok::greatergreater) &&
778 (Next.is(tok::greater) || Next.is(tok::greatergreater) ||
779 Next.is(tok::greatergreatergreater) || Next.is(tok::equal) ||
780 Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) ||
781 Next.is(tok::equalequal)) &&
782 areTokensAdjacent(Tok, Next))
783 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
785 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
786 if (getLangOpts().CPlusPlus11 &&
787 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
788 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
789 else if (Tok.is(tok::greaterequal))
790 DiagId = diag::err_right_angle_bracket_equal_needs_space;
791 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
793 // Strip the initial '>' from the token.
794 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
795 areTokensAdjacent(Tok, Next)) {
796 // Join two adjacent '=' tokens into one, for cases like:
797 // void (*p)() = f<int>;
800 Tok.setKind(tok::equalequal);
801 Tok.setLength(Tok.getLength() + 1);
803 Tok.setKind(RemainingToken);
804 Tok.setLength(Tok.getLength() - 1);
806 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
807 PP.getSourceManager(),
810 if (!ConsumeLastToken) {
811 // Since we're not supposed to consume the '>' token, we need to push
812 // this token and revert the current token back to the '>'.
814 Tok.setKind(tok::greater);
816 Tok.setLocation(RAngleLoc);
822 /// \brief Parses a template-id that after the template name has
823 /// already been parsed.
825 /// This routine takes care of parsing the enclosed template argument
826 /// list ('<' template-parameter-list [opt] '>') and placing the
827 /// results into a form that can be transferred to semantic analysis.
829 /// \param Template the template declaration produced by isTemplateName
831 /// \param TemplateNameLoc the source location of the template name
833 /// \param SS if non-NULL, the nested-name-specifier preceding the
836 /// \param ConsumeLastToken if true, then we will consume the last
837 /// token that forms the template-id. Otherwise, we will leave the
838 /// last token in the stream (e.g., so that it can be replaced with an
839 /// annotation token).
841 Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
842 SourceLocation TemplateNameLoc,
843 const CXXScopeSpec &SS,
844 bool ConsumeLastToken,
845 SourceLocation &LAngleLoc,
846 TemplateArgList &TemplateArgs,
847 SourceLocation &RAngleLoc) {
848 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
851 LAngleLoc = ConsumeToken();
853 // Parse the optional template-argument-list.
854 bool Invalid = false;
856 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
857 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
858 Invalid = ParseTemplateArgumentList(TemplateArgs);
861 // Try to find the closing '>'.
862 if (ConsumeLastToken)
863 SkipUntil(tok::greater, StopAtSemi);
865 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
870 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken);
873 /// \brief Replace the tokens that form a simple-template-id with an
874 /// annotation token containing the complete template-id.
876 /// The first token in the stream must be the name of a template that
877 /// is followed by a '<'. This routine will parse the complete
878 /// simple-template-id and replace the tokens with a single annotation
879 /// token with one of two different kinds: if the template-id names a
880 /// type (and \p AllowTypeAnnotation is true), the annotation token is
881 /// a type annotation that includes the optional nested-name-specifier
882 /// (\p SS). Otherwise, the annotation token is a template-id
883 /// annotation that does not include the optional
884 /// nested-name-specifier.
886 /// \param Template the declaration of the template named by the first
887 /// token (an identifier), as returned from \c Action::isTemplateName().
889 /// \param TNK the kind of template that \p Template
890 /// refers to, as returned from \c Action::isTemplateName().
892 /// \param SS if non-NULL, the nested-name-specifier that precedes
893 /// this template name.
895 /// \param TemplateKWLoc if valid, specifies that this template-id
896 /// annotation was preceded by the 'template' keyword and gives the
897 /// location of that keyword. If invalid (the default), then this
898 /// template-id was not preceded by a 'template' keyword.
900 /// \param AllowTypeAnnotation if true (the default), then a
901 /// simple-template-id that refers to a class template, template
902 /// template parameter, or other template that produces a type will be
903 /// replaced with a type annotation token. Otherwise, the
904 /// simple-template-id is always replaced with a template-id
905 /// annotation token.
907 /// If an unrecoverable parse error occurs and no annotation token can be
908 /// formed, this function returns true.
910 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
912 SourceLocation TemplateKWLoc,
913 UnqualifiedId &TemplateName,
914 bool AllowTypeAnnotation) {
915 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
916 assert(Template && Tok.is(tok::less) &&
917 "Parser isn't at the beginning of a template-id");
919 // Consume the template-name.
920 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
922 // Parse the enclosed template argument list.
923 SourceLocation LAngleLoc, RAngleLoc;
924 TemplateArgList TemplateArgs;
925 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
927 SS, false, LAngleLoc,
932 // If we failed to parse the template ID but skipped ahead to a >, we're not
933 // going to be able to form a token annotation. Eat the '>' if present.
934 TryConsumeToken(tok::greater);
938 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
940 // Build the annotation token.
941 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
943 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
944 Template, TemplateNameLoc,
945 LAngleLoc, TemplateArgsPtr, RAngleLoc);
946 if (Type.isInvalid()) {
947 // If we failed to parse the template ID but skipped ahead to a >, we're not
948 // going to be able to form a token annotation. Eat the '>' if present.
949 TryConsumeToken(tok::greater);
953 Tok.setKind(tok::annot_typename);
954 setTypeAnnotation(Tok, Type.get());
956 Tok.setLocation(SS.getBeginLoc());
957 else if (TemplateKWLoc.isValid())
958 Tok.setLocation(TemplateKWLoc);
960 Tok.setLocation(TemplateNameLoc);
962 // Build a template-id annotation token that can be processed
964 Tok.setKind(tok::annot_template_id);
965 TemplateIdAnnotation *TemplateId
966 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
967 TemplateId->TemplateNameLoc = TemplateNameLoc;
968 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
969 TemplateId->Name = TemplateName.Identifier;
970 TemplateId->Operator = OO_None;
972 TemplateId->Name = nullptr;
973 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
976 TemplateId->TemplateKWLoc = TemplateKWLoc;
977 TemplateId->Template = Template;
978 TemplateId->Kind = TNK;
979 TemplateId->LAngleLoc = LAngleLoc;
980 TemplateId->RAngleLoc = RAngleLoc;
981 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
982 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
983 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
984 Tok.setAnnotationValue(TemplateId);
985 if (TemplateKWLoc.isValid())
986 Tok.setLocation(TemplateKWLoc);
988 Tok.setLocation(TemplateNameLoc);
991 // Common fields for the annotation token
992 Tok.setAnnotationEndLoc(RAngleLoc);
994 // In case the tokens were cached, have Preprocessor replace them with the
996 PP.AnnotateCachedTokens(Tok);
1000 /// \brief Replaces a template-id annotation token with a type
1001 /// annotation token.
1003 /// If there was a failure when forming the type from the template-id,
1004 /// a type annotation token will still be created, but will have a
1005 /// NULL type pointer to signify an error.
1006 void Parser::AnnotateTemplateIdTokenAsType() {
1007 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1009 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1010 assert((TemplateId->Kind == TNK_Type_template ||
1011 TemplateId->Kind == TNK_Dependent_template_name) &&
1012 "Only works for type and dependent templates");
1014 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1015 TemplateId->NumArgs);
1018 = Actions.ActOnTemplateIdType(TemplateId->SS,
1019 TemplateId->TemplateKWLoc,
1020 TemplateId->Template,
1021 TemplateId->TemplateNameLoc,
1022 TemplateId->LAngleLoc,
1024 TemplateId->RAngleLoc);
1025 // Create the new "type" annotation token.
1026 Tok.setKind(tok::annot_typename);
1027 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
1028 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1029 Tok.setLocation(TemplateId->SS.getBeginLoc());
1030 // End location stays the same
1032 // Replace the template-id annotation token, and possible the scope-specifier
1033 // that precedes it, with the typename annotation token.
1034 PP.AnnotateCachedTokens(Tok);
1037 /// \brief Determine whether the given token can end a template argument.
1038 static bool isEndOfTemplateArgument(Token Tok) {
1039 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
1040 Tok.is(tok::greatergreater);
1043 /// \brief Parse a C++ template template argument.
1044 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1045 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1046 !Tok.is(tok::annot_cxxscope))
1047 return ParsedTemplateArgument();
1049 // C++0x [temp.arg.template]p1:
1050 // A template-argument for a template template-parameter shall be the name
1051 // of a class template or an alias template, expressed as id-expression.
1053 // We parse an id-expression that refers to a class template or alias
1054 // template. The grammar we parse is:
1056 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1058 // followed by a token that terminates a template argument, such as ',',
1059 // '>', or (in some cases) '>>'.
1060 CXXScopeSpec SS; // nested-name-specifier, if present
1061 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1062 /*EnteringContext=*/false);
1064 ParsedTemplateArgument Result;
1065 SourceLocation EllipsisLoc;
1066 if (SS.isSet() && Tok.is(tok::kw_template)) {
1067 // Parse the optional 'template' keyword following the
1068 // nested-name-specifier.
1069 SourceLocation TemplateKWLoc = ConsumeToken();
1071 if (Tok.is(tok::identifier)) {
1072 // We appear to have a dependent template name.
1074 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1075 ConsumeToken(); // the identifier
1077 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1079 // If the next token signals the end of a template argument,
1080 // then we have a dependent template name that could be a template
1081 // template argument.
1082 TemplateTy Template;
1083 if (isEndOfTemplateArgument(Tok) &&
1084 Actions.ActOnDependentTemplateName(getCurScope(),
1085 SS, TemplateKWLoc, Name,
1086 /*ObjectType=*/ ParsedType(),
1087 /*EnteringContext=*/false,
1089 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1091 } else if (Tok.is(tok::identifier)) {
1092 // We may have a (non-dependent) template name.
1093 TemplateTy Template;
1095 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1096 ConsumeToken(); // the identifier
1098 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1100 if (isEndOfTemplateArgument(Tok)) {
1101 bool MemberOfUnknownSpecialization;
1102 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1103 /*hasTemplateKeyword=*/false,
1105 /*ObjectType=*/ ParsedType(),
1106 /*EnteringContext=*/false,
1108 MemberOfUnknownSpecialization);
1109 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1110 // We have an id-expression that refers to a class template or
1111 // (C++0x) alias template.
1112 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1117 // If this is a pack expansion, build it as such.
1118 if (EllipsisLoc.isValid() && !Result.isInvalid())
1119 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1124 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1126 /// template-argument: [C++ 14.2]
1127 /// constant-expression
1130 ParsedTemplateArgument Parser::ParseTemplateArgument() {
1131 // C++ [temp.arg]p2:
1132 // In a template-argument, an ambiguity between a type-id and an
1133 // expression is resolved to a type-id, regardless of the form of
1134 // the corresponding template-parameter.
1136 // Therefore, we initially try to parse a type-id.
1137 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1138 SourceLocation Loc = Tok.getLocation();
1139 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
1140 Declarator::TemplateTypeArgContext);
1141 if (TypeArg.isInvalid())
1142 return ParsedTemplateArgument();
1144 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1145 TypeArg.get().getAsOpaquePtr(),
1149 // Try to parse a template template argument.
1151 TentativeParsingAction TPA(*this);
1153 ParsedTemplateArgument TemplateTemplateArgument
1154 = ParseTemplateTemplateArgument();
1155 if (!TemplateTemplateArgument.isInvalid()) {
1157 return TemplateTemplateArgument;
1160 // Revert this tentative parse to parse a non-type template argument.
1164 // Parse a non-type template argument.
1165 SourceLocation Loc = Tok.getLocation();
1166 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1167 if (ExprArg.isInvalid() || !ExprArg.get())
1168 return ParsedTemplateArgument();
1170 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1171 ExprArg.get(), Loc);
1174 /// \brief Determine whether the current tokens can only be parsed as a
1175 /// template argument list (starting with the '<') and never as a '<'
1177 bool Parser::IsTemplateArgumentList(unsigned Skip) {
1178 struct AlwaysRevertAction : TentativeParsingAction {
1179 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1180 ~AlwaysRevertAction() { Revert(); }
1189 if (!TryConsumeToken(tok::less))
1192 // An empty template argument list.
1193 if (Tok.is(tok::greater))
1196 // See whether we have declaration specifiers, which indicate a type.
1197 while (isCXXDeclarationSpecifier() == TPResult::True)
1200 // If we have a '>' or a ',' then this is a template argument list.
1201 return Tok.is(tok::greater) || Tok.is(tok::comma);
1204 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1205 /// (C++ [temp.names]). Returns true if there was an error.
1207 /// template-argument-list: [C++ 14.2]
1208 /// template-argument
1209 /// template-argument-list ',' template-argument
1211 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1212 // Template argument lists are constant-evaluation contexts.
1213 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
1214 ColonProtectionRAIIObject ColonProtection(*this, false);
1217 ParsedTemplateArgument Arg = ParseTemplateArgument();
1218 SourceLocation EllipsisLoc;
1219 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1220 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1222 if (Arg.isInvalid()) {
1223 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
1227 // Save this template argument.
1228 TemplateArgs.push_back(Arg);
1230 // If the next token is a comma, consume it and keep reading
1232 } while (TryConsumeToken(tok::comma));
1237 /// \brief Parse a C++ explicit template instantiation
1238 /// (C++ [temp.explicit]).
1240 /// explicit-instantiation:
1241 /// 'extern' [opt] 'template' declaration
1243 /// Note that the 'extern' is a GNU extension and C++11 feature.
1244 Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1245 SourceLocation ExternLoc,
1246 SourceLocation TemplateLoc,
1247 SourceLocation &DeclEnd,
1248 AccessSpecifier AS) {
1249 // This isn't really required here.
1250 ParsingDeclRAIIObject
1251 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1253 return ParseSingleDeclarationAfterTemplate(Context,
1254 ParsedTemplateInfo(ExternLoc,
1256 ParsingTemplateParams,
1260 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1262 return getTemplateParamsRange(TemplateParams->data(),
1263 TemplateParams->size());
1265 SourceRange R(TemplateLoc);
1266 if (ExternLoc.isValid())
1267 R.setBegin(ExternLoc);
1271 void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1272 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1275 /// \brief Late parse a C++ function template in Microsoft mode.
1276 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1280 // Get the FunctionDecl.
1281 FunctionDecl *FunD = LPT.D->getAsFunction();
1282 // Track template parameter depth.
1283 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1285 // To restore the context after late parsing.
1286 Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
1288 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1290 // Get the list of DeclContexts to reenter.
1291 SmallVector<DeclContext*, 4> DeclContextsToReenter;
1292 DeclContext *DD = FunD;
1293 while (DD && !DD->isTranslationUnit()) {
1294 DeclContextsToReenter.push_back(DD);
1295 DD = DD->getLexicalParent();
1298 // Reenter template scopes from outermost to innermost.
1299 SmallVectorImpl<DeclContext *>::reverse_iterator II =
1300 DeclContextsToReenter.rbegin();
1301 for (; II != DeclContextsToReenter.rend(); ++II) {
1302 TemplateParamScopeStack.push_back(new ParseScope(this,
1303 Scope::TemplateParamScope));
1304 unsigned NumParamLists =
1305 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1306 CurTemplateDepthTracker.addDepth(NumParamLists);
1308 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1309 Actions.PushDeclContext(Actions.getCurScope(), *II);
1313 assert(!LPT.Toks.empty() && "Empty body!");
1315 // Append the current token at the end of the new token stream so that it
1316 // doesn't get lost.
1317 LPT.Toks.push_back(Tok);
1318 PP.EnterTokenStream(LPT.Toks.data(), LPT.Toks.size(), true, false);
1320 // Consume the previously pushed token.
1321 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1322 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1323 && "Inline method not starting with '{', ':' or 'try'");
1325 // Parse the method body. Function body parsing code is similar enough
1326 // to be re-used for method bodies as well.
1327 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1329 // Recreate the containing function DeclContext.
1330 Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FunD));
1332 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1334 if (Tok.is(tok::kw_try)) {
1335 ParseFunctionTryBlock(LPT.D, FnScope);
1337 if (Tok.is(tok::colon))
1338 ParseConstructorInitializer(LPT.D);
1340 Actions.ActOnDefaultCtorInitializers(LPT.D);
1342 if (Tok.is(tok::l_brace)) {
1343 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1344 cast<FunctionTemplateDecl>(LPT.D)
1345 ->getTemplateParameters()
1346 ->getDepth() == TemplateParameterDepth - 1) &&
1347 "TemplateParameterDepth should be greater than the depth of "
1348 "current template being instantiated!");
1349 ParseFunctionStatementBody(LPT.D, FnScope);
1350 Actions.UnmarkAsLateParsedTemplate(FunD);
1352 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1357 SmallVectorImpl<ParseScope *>::reverse_iterator I =
1358 TemplateParamScopeStack.rbegin();
1359 for (; I != TemplateParamScopeStack.rend(); ++I)
1363 /// \brief Lex a delayed template function for late parsing.
1364 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1365 tok::TokenKind kind = Tok.getKind();
1366 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1367 // Consume everything up to (and including) the matching right brace.
1368 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1371 // If we're in a function-try-block, we need to store all the catch blocks.
1372 if (kind == tok::kw_try) {
1373 while (Tok.is(tok::kw_catch)) {
1374 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1375 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);