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 "RAIIObjectsForParser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/Parse/ParseDiagnostic.h"
18 #include "clang/Parse/Parser.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.isOneOf(tok::kw_export, 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 ExprResult OptionalRequiresClauseConstraintER;
125 if (!TemplateParams.empty()) {
126 isSpecialization = false;
127 ++CurTemplateDepthTracker;
129 if (TryConsumeToken(tok::kw_requires)) {
130 OptionalRequiresClauseConstraintER =
131 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
132 if (!OptionalRequiresClauseConstraintER.isUsable()) {
133 // Skip until the semi-colon or a '}'.
134 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
135 TryConsumeToken(tok::semi);
140 LastParamListWasEmpty = true;
143 ParamLists.push_back(Actions.ActOnTemplateParameterList(
144 CurTemplateDepthTracker.getDepth(), ExportLoc, TemplateLoc, LAngleLoc,
145 TemplateParams, RAngleLoc, OptionalRequiresClauseConstraintER.get()));
146 } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
148 unsigned NewFlags = getCurScope()->getFlags() & ~Scope::TemplateParamScope;
149 ParseScopeFlags TemplateScopeFlags(this, NewFlags, isSpecialization);
151 // Parse the actual template declaration.
152 return ParseSingleDeclarationAfterTemplate(Context,
153 ParsedTemplateInfo(&ParamLists,
155 LastParamListWasEmpty),
156 ParsingTemplateParams,
157 DeclEnd, AS, AccessAttrs);
160 /// \brief Parse a single declaration that declares a template,
161 /// template specialization, or explicit instantiation of a template.
163 /// \param DeclEnd will receive the source location of the last token
164 /// within this declaration.
166 /// \param AS the access specifier associated with this
167 /// declaration. Will be AS_none for namespace-scope declarations.
169 /// \returns the new declaration.
171 Parser::ParseSingleDeclarationAfterTemplate(
173 const ParsedTemplateInfo &TemplateInfo,
174 ParsingDeclRAIIObject &DiagsFromTParams,
175 SourceLocation &DeclEnd,
177 AttributeList *AccessAttrs) {
178 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
179 "Template information required");
181 if (Tok.is(tok::kw_static_assert)) {
182 // A static_assert declaration may not be templated.
183 Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
184 << TemplateInfo.getSourceRange();
185 // Parse the static_assert declaration to improve error recovery.
186 return ParseStaticAssertDeclaration(DeclEnd);
189 if (Context == Declarator::MemberContext) {
190 // We are parsing a member template.
191 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
196 ParsedAttributesWithRange prefixAttrs(AttrFactory);
197 MaybeParseCXX11Attributes(prefixAttrs);
199 if (Tok.is(tok::kw_using)) {
200 // FIXME: We should return the DeclGroup to the caller.
201 ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
206 // Parse the declaration specifiers, stealing any diagnostics from
207 // the template parameters.
208 ParsingDeclSpec DS(*this, &DiagsFromTParams);
210 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
211 getDeclSpecContextFromDeclaratorContext(Context));
213 if (Tok.is(tok::semi)) {
214 ProhibitAttributes(prefixAttrs);
215 DeclEnd = ConsumeToken();
216 RecordDecl *AnonRecord = nullptr;
217 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
218 getCurScope(), AS, DS,
219 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
220 : MultiTemplateParamsArg(),
221 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
223 assert(!AnonRecord &&
224 "Anonymous unions/structs should not be valid with template");
229 // Move the attributes from the prefix into the DS.
230 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
231 ProhibitAttributes(prefixAttrs);
233 DS.takeAttributesFrom(prefixAttrs);
235 // Parse the declarator.
236 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
237 ParseDeclarator(DeclaratorInfo);
238 // Error parsing the declarator?
239 if (!DeclaratorInfo.hasName()) {
240 // If so, skip until the semi-colon or a }.
241 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
242 if (Tok.is(tok::semi))
247 LateParsedAttrList LateParsedAttrs(true);
248 if (DeclaratorInfo.isFunctionDeclarator())
249 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
251 if (DeclaratorInfo.isFunctionDeclarator() &&
252 isStartOfFunctionDefinition(DeclaratorInfo)) {
254 // Function definitions are only allowed at file scope and in C++ classes.
255 // The C++ inline method definition case is handled elsewhere, so we only
256 // need to handle the file scope definition case.
257 if (Context != Declarator::FileContext) {
258 Diag(Tok, diag::err_function_definition_not_allowed);
263 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
264 // Recover by ignoring the 'typedef'. This was probably supposed to be
265 // the 'typename' keyword, which we should have already suggested adding
266 // if it's appropriate.
267 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
268 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
269 DS.ClearStorageClassSpecs();
272 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
273 if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
274 // If the declarator-id is not a template-id, issue a diagnostic and
275 // recover by ignoring the 'template' keyword.
276 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
277 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
280 SourceLocation LAngleLoc
281 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
282 Diag(DeclaratorInfo.getIdentifierLoc(),
283 diag::err_explicit_instantiation_with_definition)
284 << SourceRange(TemplateInfo.TemplateLoc)
285 << FixItHint::CreateInsertion(LAngleLoc, "<>");
287 // Recover as if it were an explicit specialization.
288 TemplateParameterLists FakedParamLists;
289 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
290 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
291 LAngleLoc, nullptr));
293 return ParseFunctionDefinition(
294 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
295 /*isSpecialization=*/true,
296 /*LastParamListWasEmpty=*/true),
300 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
304 // Parse this declaration.
305 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
308 if (Tok.is(tok::comma)) {
309 Diag(Tok, diag::err_multiple_template_declarators)
310 << (int)TemplateInfo.Kind;
311 SkipUntil(tok::semi);
315 // Eat the semi colon after the declaration.
316 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
317 if (LateParsedAttrs.size() > 0)
318 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
319 DeclaratorInfo.complete(ThisDecl);
323 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
324 /// angle brackets. Depth is the depth of this template-parameter-list, which
325 /// is the number of template headers directly enclosing this template header.
326 /// TemplateParams is the current list of template parameters we're building.
327 /// The template parameter we parse will be added to this list. LAngleLoc and
328 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
329 /// that enclose this template parameter list.
331 /// \returns true if an error occurred, false otherwise.
332 bool Parser::ParseTemplateParameters(unsigned Depth,
333 SmallVectorImpl<Decl*> &TemplateParams,
334 SourceLocation &LAngleLoc,
335 SourceLocation &RAngleLoc) {
336 // Get the template parameter list.
337 if (!TryConsumeToken(tok::less, LAngleLoc)) {
338 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
342 // Try to parse the template parameter list.
344 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
345 Failed = ParseTemplateParameterList(Depth, TemplateParams);
347 if (Tok.is(tok::greatergreater)) {
348 // No diagnostic required here: a template-parameter-list can only be
349 // followed by a declaration or, for a template template parameter, the
350 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
351 // This matters for elegant diagnosis of:
352 // template<template<typename>> struct S;
353 Tok.setKind(tok::greater);
354 RAngleLoc = Tok.getLocation();
355 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
356 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
357 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
363 /// ParseTemplateParameterList - Parse a template parameter list. If
364 /// the parsing fails badly (i.e., closing bracket was left out), this
365 /// will try to put the token stream in a reasonable position (closing
366 /// a statement, etc.) and return false.
368 /// template-parameter-list: [C++ temp]
369 /// template-parameter
370 /// template-parameter-list ',' template-parameter
372 Parser::ParseTemplateParameterList(unsigned Depth,
373 SmallVectorImpl<Decl*> &TemplateParams) {
376 = ParseTemplateParameter(Depth, TemplateParams.size())) {
377 TemplateParams.push_back(TmpParam);
379 // If we failed to parse a template parameter, skip until we find
380 // a comma or closing brace.
381 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
382 StopAtSemi | StopBeforeMatch);
385 // Did we find a comma or the end of the template parameter list?
386 if (Tok.is(tok::comma)) {
388 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
389 // Don't consume this... that's done by template parser.
392 // Somebody probably forgot to close the template. Skip ahead and
393 // try to get out of the expression. This error is currently
394 // subsumed by whatever goes on in ParseTemplateParameter.
395 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
396 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
397 StopAtSemi | StopBeforeMatch);
404 /// \brief Determine whether the parser is at the start of a template
406 bool Parser::isStartOfTemplateTypeParameter() {
407 if (Tok.is(tok::kw_class)) {
408 // "class" may be the start of an elaborated-type-specifier or a
409 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
410 switch (NextToken().getKind()) {
414 case tok::greatergreater:
418 case tok::identifier:
419 // This may be either a type-parameter or an elaborated-type-specifier.
420 // We have to look further.
427 switch (GetLookAheadToken(2).getKind()) {
431 case tok::greatergreater:
439 if (Tok.isNot(tok::kw_typename))
442 // C++ [temp.param]p2:
443 // There is no semantic difference between class and typename in a
444 // template-parameter. typename followed by an unqualified-id
445 // names a template type parameter. typename followed by a
446 // qualified-id denotes the type in a non-type
447 // parameter-declaration.
448 Token Next = NextToken();
450 // If we have an identifier, skip over it.
451 if (Next.getKind() == tok::identifier)
452 Next = GetLookAheadToken(2);
454 switch (Next.getKind()) {
458 case tok::greatergreater:
467 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
469 /// template-parameter: [C++ temp.param]
471 /// parameter-declaration
473 /// type-parameter: (see below)
474 /// 'class' ...[opt] identifier[opt]
475 /// 'class' identifier[opt] '=' type-id
476 /// 'typename' ...[opt] identifier[opt]
477 /// 'typename' identifier[opt] '=' type-id
478 /// 'template' '<' template-parameter-list '>'
479 /// 'class' ...[opt] identifier[opt]
480 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
482 Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
483 if (isStartOfTemplateTypeParameter())
484 return ParseTypeParameter(Depth, Position);
486 if (Tok.is(tok::kw_template))
487 return ParseTemplateTemplateParameter(Depth, Position);
489 // If it's none of the above, then it must be a parameter declaration.
490 // NOTE: This will pick up errors in the closure of the template parameter
491 // list (e.g., template < ; Check here to implement >> style closures.
492 return ParseNonTypeTemplateParameter(Depth, Position);
495 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
496 /// Other kinds of template parameters are parsed in
497 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
499 /// type-parameter: [C++ temp.param]
500 /// 'class' ...[opt][C++0x] identifier[opt]
501 /// 'class' identifier[opt] '=' type-id
502 /// 'typename' ...[opt][C++0x] identifier[opt]
503 /// 'typename' identifier[opt] '=' type-id
504 Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
505 assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
506 "A type-parameter starts with 'class' or 'typename'");
508 // Consume the 'class' or 'typename' keyword.
509 bool TypenameKeyword = Tok.is(tok::kw_typename);
510 SourceLocation KeyLoc = ConsumeToken();
512 // Grab the ellipsis (if given).
513 SourceLocation EllipsisLoc;
514 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
516 getLangOpts().CPlusPlus11
517 ? diag::warn_cxx98_compat_variadic_templates
518 : diag::ext_variadic_templates);
521 // Grab the template parameter name (if given)
522 SourceLocation NameLoc;
523 IdentifierInfo *ParamName = nullptr;
524 if (Tok.is(tok::identifier)) {
525 ParamName = Tok.getIdentifierInfo();
526 NameLoc = ConsumeToken();
527 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
528 tok::greatergreater)) {
529 // Unnamed template parameter. Don't have to do anything here, just
530 // don't consume this token.
532 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
536 // Recover from misplaced ellipsis.
537 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
538 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
539 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
541 // Grab a default argument (if available).
542 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
543 // we introduce the type parameter into the local scope.
544 SourceLocation EqualLoc;
545 ParsedType DefaultArg;
546 if (TryConsumeToken(tok::equal, EqualLoc))
547 DefaultArg = ParseTypeName(/*Range=*/nullptr,
548 Declarator::TemplateTypeArgContext).get();
550 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
551 KeyLoc, ParamName, NameLoc, Depth, Position,
552 EqualLoc, DefaultArg);
555 /// ParseTemplateTemplateParameter - Handle the parsing of template
556 /// template parameters.
558 /// type-parameter: [C++ temp.param]
559 /// 'template' '<' template-parameter-list '>' type-parameter-key
560 /// ...[opt] identifier[opt]
561 /// 'template' '<' template-parameter-list '>' type-parameter-key
562 /// identifier[opt] = id-expression
563 /// type-parameter-key:
565 /// 'typename' [C++1z]
567 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
568 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
570 // Handle the template <...> part.
571 SourceLocation TemplateLoc = ConsumeToken();
572 SmallVector<Decl*,8> TemplateParams;
573 SourceLocation LAngleLoc, RAngleLoc;
575 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
576 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
582 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
583 // Generate a meaningful error if the user forgot to put class before the
584 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
585 // or greater appear immediately or after 'struct'. In the latter case,
586 // replace the keyword with 'class'.
587 if (!TryConsumeToken(tok::kw_class)) {
588 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
589 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
590 if (Tok.is(tok::kw_typename)) {
591 Diag(Tok.getLocation(),
592 getLangOpts().CPlusPlus1z
593 ? diag::warn_cxx14_compat_template_template_param_typename
594 : diag::ext_template_template_param_typename)
595 << (!getLangOpts().CPlusPlus1z
596 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
598 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
599 tok::greatergreater, tok::ellipsis)) {
600 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
601 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
602 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
604 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
610 // Parse the ellipsis, if given.
611 SourceLocation EllipsisLoc;
612 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
614 getLangOpts().CPlusPlus11
615 ? diag::warn_cxx98_compat_variadic_templates
616 : diag::ext_variadic_templates);
618 // Get the identifier, if given.
619 SourceLocation NameLoc;
620 IdentifierInfo *ParamName = nullptr;
621 if (Tok.is(tok::identifier)) {
622 ParamName = Tok.getIdentifierInfo();
623 NameLoc = ConsumeToken();
624 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
625 tok::greatergreater)) {
626 // Unnamed template parameter. Don't have to do anything here, just
627 // don't consume this token.
629 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
633 // Recover from misplaced ellipsis.
634 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
635 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
636 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
638 TemplateParameterList *ParamList =
639 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
640 TemplateLoc, LAngleLoc,
644 // Grab a default argument (if available).
645 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
646 // we introduce the template parameter into the local scope.
647 SourceLocation EqualLoc;
648 ParsedTemplateArgument DefaultArg;
649 if (TryConsumeToken(tok::equal, EqualLoc)) {
650 DefaultArg = ParseTemplateTemplateArgument();
651 if (DefaultArg.isInvalid()) {
652 Diag(Tok.getLocation(),
653 diag::err_default_template_template_parameter_not_template);
654 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
655 StopAtSemi | StopBeforeMatch);
659 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
660 ParamList, EllipsisLoc,
661 ParamName, NameLoc, Depth,
662 Position, EqualLoc, DefaultArg);
665 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
666 /// template parameters (e.g., in "template<int Size> class array;").
668 /// template-parameter:
670 /// parameter-declaration
672 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
673 // Parse the declaration-specifiers (i.e., the type).
674 // FIXME: The type should probably be restricted in some way... Not all
675 // declarators (parts of declarators?) are accepted for parameters.
676 DeclSpec DS(AttrFactory);
677 ParseDeclarationSpecifiers(DS);
679 // Parse this as a typename.
680 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
681 ParseDeclarator(ParamDecl);
682 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
683 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
687 // Recover from misplaced ellipsis.
688 SourceLocation EllipsisLoc;
689 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
690 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
692 // If there is a default value, parse it.
693 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
694 // we introduce the template parameter into the local scope.
695 SourceLocation EqualLoc;
696 ExprResult DefaultArg;
697 if (TryConsumeToken(tok::equal, EqualLoc)) {
698 // C++ [temp.param]p15:
699 // When parsing a default template-argument for a non-type
700 // template-parameter, the first non-nested > is taken as the
701 // end of the template-parameter-list rather than a greater-than
703 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
704 EnterExpressionEvaluationContext ConstantEvaluated(Actions,
705 Sema::ConstantEvaluated);
707 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
708 if (DefaultArg.isInvalid())
709 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
712 // Create the parameter.
713 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
714 Depth, Position, EqualLoc,
718 void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
719 SourceLocation CorrectLoc,
720 bool AlreadyHasEllipsis,
721 bool IdentifierHasName) {
723 if (!AlreadyHasEllipsis)
724 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
725 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
726 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
727 << !IdentifierHasName;
730 void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
732 assert(EllipsisLoc.isValid());
733 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
734 if (!AlreadyHasEllipsis)
735 D.setEllipsisLoc(EllipsisLoc);
736 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
737 AlreadyHasEllipsis, D.hasName());
740 /// \brief Parses a '>' at the end of a template list.
742 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
743 /// to determine if these tokens were supposed to be a '>' followed by
744 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
746 /// \param RAngleLoc the location of the consumed '>'.
748 /// \param ConsumeLastToken if true, the '>' is consumed.
750 /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
751 /// type parameter or type argument list, rather than a C++ template parameter
752 /// or argument list.
754 /// \returns true, if current token does not start with '>', false otherwise.
755 bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
756 bool ConsumeLastToken,
757 bool ObjCGenericList) {
758 // What will be left once we've consumed the '>'.
759 tok::TokenKind RemainingToken;
760 const char *ReplacementStr = "> >";
762 switch (Tok.getKind()) {
764 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
768 // Determine the location of the '>' token. Only consume this token
769 // if the caller asked us to.
770 RAngleLoc = Tok.getLocation();
771 if (ConsumeLastToken)
775 case tok::greatergreater:
776 RemainingToken = tok::greater;
779 case tok::greatergreatergreater:
780 RemainingToken = tok::greatergreater;
783 case tok::greaterequal:
784 RemainingToken = tok::equal;
785 ReplacementStr = "> =";
788 case tok::greatergreaterequal:
789 RemainingToken = tok::greaterequal;
793 // This template-id is terminated by a token which starts with a '>'. Outside
794 // C++11, this is now error recovery, and in C++11, this is error recovery if
795 // the token isn't '>>' or '>>>'.
796 // '>>>' is for CUDA, where this sequence of characters is parsed into
797 // tok::greatergreatergreater, rather than two separate tokens.
799 // We always allow this for Objective-C type parameter and type argument
801 RAngleLoc = Tok.getLocation();
802 Token Next = NextToken();
803 if (!ObjCGenericList) {
804 // The source range of the '>>' or '>=' at the start of the token.
805 CharSourceRange ReplacementRange =
806 CharSourceRange::getCharRange(RAngleLoc,
807 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
810 // A hint to put a space between the '>>'s. In order to make the hint as
811 // clear as possible, we include the characters either side of the space in
812 // the replacement, rather than just inserting a space at SecondCharLoc.
813 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
816 // A hint to put another space after the token, if it would otherwise be
817 // lexed differently.
819 if ((RemainingToken == tok::greater ||
820 RemainingToken == tok::greatergreater) &&
821 (Next.isOneOf(tok::greater, tok::greatergreater,
822 tok::greatergreatergreater, tok::equal,
823 tok::greaterequal, tok::greatergreaterequal,
825 areTokensAdjacent(Tok, Next))
826 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
828 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
829 if (getLangOpts().CPlusPlus11 &&
830 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
831 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
832 else if (Tok.is(tok::greaterequal))
833 DiagId = diag::err_right_angle_bracket_equal_needs_space;
834 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
837 // Strip the initial '>' from the token.
839 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
840 areTokensAdjacent(Tok, Next)) {
841 // Join two adjacent '=' tokens into one, for cases like:
842 // void (*p)() = f<int>;
845 Tok.setKind(tok::equalequal);
846 Tok.setLength(Tok.getLength() + 1);
848 Tok.setKind(RemainingToken);
849 Tok.setLength(Tok.getLength() - 1);
851 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
852 PP.getSourceManager(),
855 // The advance from '>>' to '>' in a ObjectiveC template argument list needs
856 // to be properly reflected in the token cache to allow correct interaction
857 // between annotation and backtracking.
858 if (ObjCGenericList && PrevTok.getKind() == tok::greatergreater &&
859 RemainingToken == tok::greater && PP.IsPreviousCachedToken(PrevTok)) {
860 PrevTok.setKind(RemainingToken);
861 PrevTok.setLength(1);
862 // Break tok::greatergreater into two tok::greater but only add the second
863 // one in case the client asks to consume the last token.
864 if (ConsumeLastToken)
865 PP.ReplacePreviousCachedToken({PrevTok, Tok});
867 PP.ReplacePreviousCachedToken({PrevTok});
870 if (!ConsumeLastToken) {
871 // Since we're not supposed to consume the '>' token, we need to push
872 // this token and revert the current token back to the '>'.
874 Tok.setKind(tok::greater);
876 Tok.setLocation(RAngleLoc);
882 /// \brief Parses a template-id that after the template name has
883 /// already been parsed.
885 /// This routine takes care of parsing the enclosed template argument
886 /// list ('<' template-parameter-list [opt] '>') and placing the
887 /// results into a form that can be transferred to semantic analysis.
889 /// \param Template the template declaration produced by isTemplateName
891 /// \param TemplateNameLoc the source location of the template name
893 /// \param SS if non-NULL, the nested-name-specifier preceding the
896 /// \param ConsumeLastToken if true, then we will consume the last
897 /// token that forms the template-id. Otherwise, we will leave the
898 /// last token in the stream (e.g., so that it can be replaced with an
899 /// annotation token).
901 Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
902 SourceLocation TemplateNameLoc,
903 const CXXScopeSpec &SS,
904 bool ConsumeLastToken,
905 SourceLocation &LAngleLoc,
906 TemplateArgList &TemplateArgs,
907 SourceLocation &RAngleLoc) {
908 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
911 LAngleLoc = ConsumeToken();
913 // Parse the optional template-argument-list.
914 bool Invalid = false;
916 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
917 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
918 Invalid = ParseTemplateArgumentList(TemplateArgs);
921 // Try to find the closing '>'.
922 if (ConsumeLastToken)
923 SkipUntil(tok::greater, StopAtSemi);
925 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
930 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
931 /*ObjCGenericList=*/false);
934 /// \brief Replace the tokens that form a simple-template-id with an
935 /// annotation token containing the complete template-id.
937 /// The first token in the stream must be the name of a template that
938 /// is followed by a '<'. This routine will parse the complete
939 /// simple-template-id and replace the tokens with a single annotation
940 /// token with one of two different kinds: if the template-id names a
941 /// type (and \p AllowTypeAnnotation is true), the annotation token is
942 /// a type annotation that includes the optional nested-name-specifier
943 /// (\p SS). Otherwise, the annotation token is a template-id
944 /// annotation that does not include the optional
945 /// nested-name-specifier.
947 /// \param Template the declaration of the template named by the first
948 /// token (an identifier), as returned from \c Action::isTemplateName().
950 /// \param TNK the kind of template that \p Template
951 /// refers to, as returned from \c Action::isTemplateName().
953 /// \param SS if non-NULL, the nested-name-specifier that precedes
954 /// this template name.
956 /// \param TemplateKWLoc if valid, specifies that this template-id
957 /// annotation was preceded by the 'template' keyword and gives the
958 /// location of that keyword. If invalid (the default), then this
959 /// template-id was not preceded by a 'template' keyword.
961 /// \param AllowTypeAnnotation if true (the default), then a
962 /// simple-template-id that refers to a class template, template
963 /// template parameter, or other template that produces a type will be
964 /// replaced with a type annotation token. Otherwise, the
965 /// simple-template-id is always replaced with a template-id
966 /// annotation token.
968 /// If an unrecoverable parse error occurs and no annotation token can be
969 /// formed, this function returns true.
971 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
973 SourceLocation TemplateKWLoc,
974 UnqualifiedId &TemplateName,
975 bool AllowTypeAnnotation) {
976 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
977 assert(Template && Tok.is(tok::less) &&
978 "Parser isn't at the beginning of a template-id");
980 // Consume the template-name.
981 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
983 // Parse the enclosed template argument list.
984 SourceLocation LAngleLoc, RAngleLoc;
985 TemplateArgList TemplateArgs;
986 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
988 SS, false, LAngleLoc,
993 // If we failed to parse the template ID but skipped ahead to a >, we're not
994 // going to be able to form a token annotation. Eat the '>' if present.
995 TryConsumeToken(tok::greater);
999 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
1001 // Build the annotation token.
1002 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
1004 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
1005 Template, TemplateNameLoc,
1006 LAngleLoc, TemplateArgsPtr, RAngleLoc);
1007 if (Type.isInvalid()) {
1008 // If we failed to parse the template ID but skipped ahead to a >, we're not
1009 // going to be able to form a token annotation. Eat the '>' if present.
1010 TryConsumeToken(tok::greater);
1014 Tok.setKind(tok::annot_typename);
1015 setTypeAnnotation(Tok, Type.get());
1016 if (SS.isNotEmpty())
1017 Tok.setLocation(SS.getBeginLoc());
1018 else if (TemplateKWLoc.isValid())
1019 Tok.setLocation(TemplateKWLoc);
1021 Tok.setLocation(TemplateNameLoc);
1023 // Build a template-id annotation token that can be processed
1025 Tok.setKind(tok::annot_template_id);
1026 TemplateIdAnnotation *TemplateId
1027 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
1028 TemplateId->TemplateNameLoc = TemplateNameLoc;
1029 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
1030 TemplateId->Name = TemplateName.Identifier;
1031 TemplateId->Operator = OO_None;
1033 TemplateId->Name = nullptr;
1034 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
1036 TemplateId->SS = SS;
1037 TemplateId->TemplateKWLoc = TemplateKWLoc;
1038 TemplateId->Template = Template;
1039 TemplateId->Kind = TNK;
1040 TemplateId->LAngleLoc = LAngleLoc;
1041 TemplateId->RAngleLoc = RAngleLoc;
1042 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1043 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
1044 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
1045 Tok.setAnnotationValue(TemplateId);
1046 if (TemplateKWLoc.isValid())
1047 Tok.setLocation(TemplateKWLoc);
1049 Tok.setLocation(TemplateNameLoc);
1052 // Common fields for the annotation token
1053 Tok.setAnnotationEndLoc(RAngleLoc);
1055 // In case the tokens were cached, have Preprocessor replace them with the
1056 // annotation token.
1057 PP.AnnotateCachedTokens(Tok);
1061 /// \brief Replaces a template-id annotation token with a type
1062 /// annotation token.
1064 /// If there was a failure when forming the type from the template-id,
1065 /// a type annotation token will still be created, but will have a
1066 /// NULL type pointer to signify an error.
1067 void Parser::AnnotateTemplateIdTokenAsType() {
1068 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1070 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1071 assert((TemplateId->Kind == TNK_Type_template ||
1072 TemplateId->Kind == TNK_Dependent_template_name) &&
1073 "Only works for type and dependent templates");
1075 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1076 TemplateId->NumArgs);
1079 = Actions.ActOnTemplateIdType(TemplateId->SS,
1080 TemplateId->TemplateKWLoc,
1081 TemplateId->Template,
1082 TemplateId->TemplateNameLoc,
1083 TemplateId->LAngleLoc,
1085 TemplateId->RAngleLoc);
1086 // Create the new "type" annotation token.
1087 Tok.setKind(tok::annot_typename);
1088 setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
1089 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1090 Tok.setLocation(TemplateId->SS.getBeginLoc());
1091 // End location stays the same
1093 // Replace the template-id annotation token, and possible the scope-specifier
1094 // that precedes it, with the typename annotation token.
1095 PP.AnnotateCachedTokens(Tok);
1098 /// \brief Determine whether the given token can end a template argument.
1099 static bool isEndOfTemplateArgument(Token Tok) {
1100 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
1103 /// \brief Parse a C++ template template argument.
1104 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1105 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1106 !Tok.is(tok::annot_cxxscope))
1107 return ParsedTemplateArgument();
1109 // C++0x [temp.arg.template]p1:
1110 // A template-argument for a template template-parameter shall be the name
1111 // of a class template or an alias template, expressed as id-expression.
1113 // We parse an id-expression that refers to a class template or alias
1114 // template. The grammar we parse is:
1116 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1118 // followed by a token that terminates a template argument, such as ',',
1119 // '>', or (in some cases) '>>'.
1120 CXXScopeSpec SS; // nested-name-specifier, if present
1121 ParseOptionalCXXScopeSpecifier(SS, nullptr,
1122 /*EnteringContext=*/false);
1124 ParsedTemplateArgument Result;
1125 SourceLocation EllipsisLoc;
1126 if (SS.isSet() && Tok.is(tok::kw_template)) {
1127 // Parse the optional 'template' keyword following the
1128 // nested-name-specifier.
1129 SourceLocation TemplateKWLoc = ConsumeToken();
1131 if (Tok.is(tok::identifier)) {
1132 // We appear to have a dependent template name.
1134 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1135 ConsumeToken(); // the identifier
1137 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1139 // If the next token signals the end of a template argument,
1140 // then we have a dependent template name that could be a template
1141 // template argument.
1142 TemplateTy Template;
1143 if (isEndOfTemplateArgument(Tok) &&
1144 Actions.ActOnDependentTemplateName(
1145 getCurScope(), SS, TemplateKWLoc, Name,
1146 /*ObjectType=*/nullptr,
1147 /*EnteringContext=*/false, Template))
1148 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1150 } else if (Tok.is(tok::identifier)) {
1151 // We may have a (non-dependent) template name.
1152 TemplateTy Template;
1154 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1155 ConsumeToken(); // the identifier
1157 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1159 if (isEndOfTemplateArgument(Tok)) {
1160 bool MemberOfUnknownSpecialization;
1161 TemplateNameKind TNK = Actions.isTemplateName(
1163 /*hasTemplateKeyword=*/false, Name,
1164 /*ObjectType=*/nullptr,
1165 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
1166 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1167 // We have an id-expression that refers to a class template or
1168 // (C++0x) alias template.
1169 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1174 // If this is a pack expansion, build it as such.
1175 if (EllipsisLoc.isValid() && !Result.isInvalid())
1176 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1181 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1183 /// template-argument: [C++ 14.2]
1184 /// constant-expression
1187 ParsedTemplateArgument Parser::ParseTemplateArgument() {
1188 // C++ [temp.arg]p2:
1189 // In a template-argument, an ambiguity between a type-id and an
1190 // expression is resolved to a type-id, regardless of the form of
1191 // the corresponding template-parameter.
1193 // Therefore, we initially try to parse a type-id.
1194 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1195 SourceLocation Loc = Tok.getLocation();
1196 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
1197 Declarator::TemplateTypeArgContext);
1198 if (TypeArg.isInvalid())
1199 return ParsedTemplateArgument();
1201 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1202 TypeArg.get().getAsOpaquePtr(),
1206 // Try to parse a template template argument.
1208 TentativeParsingAction TPA(*this);
1210 ParsedTemplateArgument TemplateTemplateArgument
1211 = ParseTemplateTemplateArgument();
1212 if (!TemplateTemplateArgument.isInvalid()) {
1214 return TemplateTemplateArgument;
1217 // Revert this tentative parse to parse a non-type template argument.
1221 // Parse a non-type template argument.
1222 SourceLocation Loc = Tok.getLocation();
1223 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1224 if (ExprArg.isInvalid() || !ExprArg.get())
1225 return ParsedTemplateArgument();
1227 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1228 ExprArg.get(), Loc);
1231 /// \brief Determine whether the current tokens can only be parsed as a
1232 /// template argument list (starting with the '<') and never as a '<'
1234 bool Parser::IsTemplateArgumentList(unsigned Skip) {
1235 struct AlwaysRevertAction : TentativeParsingAction {
1236 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1237 ~AlwaysRevertAction() { Revert(); }
1246 if (!TryConsumeToken(tok::less))
1249 // An empty template argument list.
1250 if (Tok.is(tok::greater))
1253 // See whether we have declaration specifiers, which indicate a type.
1254 while (isCXXDeclarationSpecifier() == TPResult::True)
1257 // If we have a '>' or a ',' then this is a template argument list.
1258 return Tok.isOneOf(tok::greater, tok::comma);
1261 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1262 /// (C++ [temp.names]). Returns true if there was an error.
1264 /// template-argument-list: [C++ 14.2]
1265 /// template-argument
1266 /// template-argument-list ',' template-argument
1268 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1269 // Template argument lists are constant-evaluation contexts.
1270 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
1271 ColonProtectionRAIIObject ColonProtection(*this, false);
1274 ParsedTemplateArgument Arg = ParseTemplateArgument();
1275 SourceLocation EllipsisLoc;
1276 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1277 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1279 if (Arg.isInvalid()) {
1280 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
1284 // Save this template argument.
1285 TemplateArgs.push_back(Arg);
1287 // If the next token is a comma, consume it and keep reading
1289 } while (TryConsumeToken(tok::comma));
1294 /// \brief Parse a C++ explicit template instantiation
1295 /// (C++ [temp.explicit]).
1297 /// explicit-instantiation:
1298 /// 'extern' [opt] 'template' declaration
1300 /// Note that the 'extern' is a GNU extension and C++11 feature.
1301 Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1302 SourceLocation ExternLoc,
1303 SourceLocation TemplateLoc,
1304 SourceLocation &DeclEnd,
1305 AccessSpecifier AS) {
1306 // This isn't really required here.
1307 ParsingDeclRAIIObject
1308 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1310 return ParseSingleDeclarationAfterTemplate(Context,
1311 ParsedTemplateInfo(ExternLoc,
1313 ParsingTemplateParams,
1317 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1319 return getTemplateParamsRange(TemplateParams->data(),
1320 TemplateParams->size());
1322 SourceRange R(TemplateLoc);
1323 if (ExternLoc.isValid())
1324 R.setBegin(ExternLoc);
1328 void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1329 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1332 /// \brief Late parse a C++ function template in Microsoft mode.
1333 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1337 // Get the FunctionDecl.
1338 FunctionDecl *FunD = LPT.D->getAsFunction();
1339 // Track template parameter depth.
1340 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1342 // To restore the context after late parsing.
1343 Sema::ContextRAII GlobalSavedContext(
1344 Actions, Actions.Context.getTranslationUnitDecl());
1346 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1348 // Get the list of DeclContexts to reenter.
1349 SmallVector<DeclContext*, 4> DeclContextsToReenter;
1350 DeclContext *DD = FunD;
1351 while (DD && !DD->isTranslationUnit()) {
1352 DeclContextsToReenter.push_back(DD);
1353 DD = DD->getLexicalParent();
1356 // Reenter template scopes from outermost to innermost.
1357 SmallVectorImpl<DeclContext *>::reverse_iterator II =
1358 DeclContextsToReenter.rbegin();
1359 for (; II != DeclContextsToReenter.rend(); ++II) {
1360 TemplateParamScopeStack.push_back(new ParseScope(this,
1361 Scope::TemplateParamScope));
1362 unsigned NumParamLists =
1363 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1364 CurTemplateDepthTracker.addDepth(NumParamLists);
1366 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1367 Actions.PushDeclContext(Actions.getCurScope(), *II);
1371 assert(!LPT.Toks.empty() && "Empty body!");
1373 // Append the current token at the end of the new token stream so that it
1374 // doesn't get lost.
1375 LPT.Toks.push_back(Tok);
1376 PP.EnterTokenStream(LPT.Toks, true);
1378 // Consume the previously pushed token.
1379 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1380 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1381 "Inline method not starting with '{', ':' or 'try'");
1383 // Parse the method body. Function body parsing code is similar enough
1384 // to be re-used for method bodies as well.
1385 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1387 // Recreate the containing function DeclContext.
1388 Sema::ContextRAII FunctionSavedContext(Actions,
1389 Actions.getContainingDC(FunD));
1391 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1393 if (Tok.is(tok::kw_try)) {
1394 ParseFunctionTryBlock(LPT.D, FnScope);
1396 if (Tok.is(tok::colon))
1397 ParseConstructorInitializer(LPT.D);
1399 Actions.ActOnDefaultCtorInitializers(LPT.D);
1401 if (Tok.is(tok::l_brace)) {
1402 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1403 cast<FunctionTemplateDecl>(LPT.D)
1404 ->getTemplateParameters()
1405 ->getDepth() == TemplateParameterDepth - 1) &&
1406 "TemplateParameterDepth should be greater than the depth of "
1407 "current template being instantiated!");
1408 ParseFunctionStatementBody(LPT.D, FnScope);
1409 Actions.UnmarkAsLateParsedTemplate(FunD);
1411 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1416 SmallVectorImpl<ParseScope *>::reverse_iterator I =
1417 TemplateParamScopeStack.rbegin();
1418 for (; I != TemplateParamScopeStack.rend(); ++I)
1422 /// \brief Lex a delayed template function for late parsing.
1423 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1424 tok::TokenKind kind = Tok.getKind();
1425 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1426 // Consume everything up to (and including) the matching right brace.
1427 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1430 // If we're in a function-try-block, we need to store all the catch blocks.
1431 if (kind == tok::kw_try) {
1432 while (Tok.is(tok::kw_catch)) {
1433 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1434 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);