1 //===--- ParseTemplate.cpp - Template Parsing -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements parsing of C++ templates.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Parse/Parser.h"
15 #include "RAIIObjectsForParser.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/Parse/ParseDiagnostic.h"
20 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/ParsedTemplate.h"
22 #include "clang/Sema/Scope.h"
23 using namespace clang;
25 /// \brief Parse a template declaration, explicit instantiation, or
26 /// explicit specialization.
28 Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
29 SourceLocation &DeclEnd,
31 AttributeList *AccessAttrs) {
32 ObjCDeclContextSwitch ObjCDC(*this);
34 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
35 return ParseExplicitInstantiation(Context,
36 SourceLocation(), ConsumeToken(),
39 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
45 /// \brief Parse a template declaration or an explicit specialization.
47 /// Template declarations include one or more template parameter lists
48 /// and either the function or class template declaration. Explicit
49 /// specializations contain one or more 'template < >' prefixes
50 /// followed by a (possibly templated) declaration. Since the
51 /// syntactic form of both features is nearly identical, we parse all
52 /// of the template headers together and let semantic analysis sort
53 /// the declarations from the explicit specializations.
55 /// template-declaration: [C++ temp]
56 /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
58 /// explicit-specialization: [ C++ temp.expl.spec]
59 /// 'template' '<' '>' declaration
61 Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
62 SourceLocation &DeclEnd,
64 AttributeList *AccessAttrs) {
65 assert(Tok.isOneOf(tok::kw_export, tok::kw_template) &&
66 "Token does not start a template declaration.");
68 // Enter template-parameter scope.
69 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
71 // Tell the action that names should be checked in the context of
72 // the declaration to come.
74 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
76 // Parse multiple levels of template headers within this template
77 // parameter scope, e.g.,
79 // template<typename T>
80 // template<typename U>
81 // class A<T>::B { ... };
83 // We parse multiple levels non-recursively so that we can build a
84 // single data structure containing all of the template parameter
85 // lists to easily differentiate between the case above and:
87 // template<typename T>
89 // template<typename U> class B;
92 // In the first case, the action for declaring A<T>::B receives
93 // both template parameter lists. In the second case, the action for
94 // defining A<T>::B receives just the inner template parameter list
95 // (and retrieves the outer template parameter list from its
97 bool isSpecialization = true;
98 bool LastParamListWasEmpty = false;
99 TemplateParameterLists ParamLists;
100 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
103 // Consume the 'export', if any.
104 SourceLocation ExportLoc;
105 TryConsumeToken(tok::kw_export, ExportLoc);
107 // Consume the 'template', which should be here.
108 SourceLocation TemplateLoc;
109 if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
110 Diag(Tok.getLocation(), diag::err_expected_template);
114 // Parse the '<' template-parameter-list '>'
115 SourceLocation LAngleLoc, RAngleLoc;
116 SmallVector<Decl*, 4> TemplateParams;
117 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
118 TemplateParams, LAngleLoc, RAngleLoc)) {
119 // Skip until the semi-colon or a '}'.
120 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
121 TryConsumeToken(tok::semi);
125 ExprResult OptionalRequiresClauseConstraintER;
126 if (!TemplateParams.empty()) {
127 isSpecialization = false;
128 ++CurTemplateDepthTracker;
130 if (TryConsumeToken(tok::kw_requires)) {
131 OptionalRequiresClauseConstraintER =
132 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
133 if (!OptionalRequiresClauseConstraintER.isUsable()) {
134 // Skip until the semi-colon or a '}'.
135 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
136 TryConsumeToken(tok::semi);
141 LastParamListWasEmpty = true;
144 ParamLists.push_back(Actions.ActOnTemplateParameterList(
145 CurTemplateDepthTracker.getDepth(), ExportLoc, TemplateLoc, LAngleLoc,
146 TemplateParams, RAngleLoc, OptionalRequiresClauseConstraintER.get()));
147 } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
149 unsigned NewFlags = getCurScope()->getFlags() & ~Scope::TemplateParamScope;
150 ParseScopeFlags TemplateScopeFlags(this, NewFlags, isSpecialization);
152 // Parse the actual template declaration.
153 return ParseSingleDeclarationAfterTemplate(Context,
154 ParsedTemplateInfo(&ParamLists,
156 LastParamListWasEmpty),
157 ParsingTemplateParams,
158 DeclEnd, AS, AccessAttrs);
161 /// \brief Parse a single declaration that declares a template,
162 /// template specialization, or explicit instantiation of a template.
164 /// \param DeclEnd will receive the source location of the last token
165 /// within this declaration.
167 /// \param AS the access specifier associated with this
168 /// declaration. Will be AS_none for namespace-scope declarations.
170 /// \returns the new declaration.
172 Parser::ParseSingleDeclarationAfterTemplate(
174 const ParsedTemplateInfo &TemplateInfo,
175 ParsingDeclRAIIObject &DiagsFromTParams,
176 SourceLocation &DeclEnd,
178 AttributeList *AccessAttrs) {
179 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
180 "Template information required");
182 if (Tok.is(tok::kw_static_assert)) {
183 // A static_assert declaration may not be templated.
184 Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
185 << TemplateInfo.getSourceRange();
186 // Parse the static_assert declaration to improve error recovery.
187 return ParseStaticAssertDeclaration(DeclEnd);
190 if (Context == Declarator::MemberContext) {
191 // We are parsing a member template.
192 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
197 ParsedAttributesWithRange prefixAttrs(AttrFactory);
198 MaybeParseCXX11Attributes(prefixAttrs);
200 if (Tok.is(tok::kw_using))
201 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
204 // Parse the declaration specifiers, stealing any diagnostics from
205 // the template parameters.
206 ParsingDeclSpec DS(*this, &DiagsFromTParams);
208 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
209 getDeclSpecContextFromDeclaratorContext(Context));
211 if (Tok.is(tok::semi)) {
212 ProhibitAttributes(prefixAttrs);
213 DeclEnd = ConsumeToken();
214 RecordDecl *AnonRecord = nullptr;
215 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
216 getCurScope(), AS, DS,
217 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
218 : MultiTemplateParamsArg(),
219 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
221 assert(!AnonRecord &&
222 "Anonymous unions/structs should not be valid with template");
227 // Move the attributes from the prefix into the DS.
228 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
229 ProhibitAttributes(prefixAttrs);
231 DS.takeAttributesFrom(prefixAttrs);
233 // Parse the declarator.
234 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
235 ParseDeclarator(DeclaratorInfo);
236 // Error parsing the declarator?
237 if (!DeclaratorInfo.hasName()) {
238 // If so, skip until the semi-colon or a }.
239 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
240 if (Tok.is(tok::semi))
245 LateParsedAttrList LateParsedAttrs(true);
246 if (DeclaratorInfo.isFunctionDeclarator())
247 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
249 if (DeclaratorInfo.isFunctionDeclarator() &&
250 isStartOfFunctionDefinition(DeclaratorInfo)) {
252 // Function definitions are only allowed at file scope and in C++ classes.
253 // The C++ inline method definition case is handled elsewhere, so we only
254 // need to handle the file scope definition case.
255 if (Context != Declarator::FileContext) {
256 Diag(Tok, diag::err_function_definition_not_allowed);
261 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
262 // Recover by ignoring the 'typedef'. This was probably supposed to be
263 // the 'typename' keyword, which we should have already suggested adding
264 // if it's appropriate.
265 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
266 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
267 DS.ClearStorageClassSpecs();
270 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
271 if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
272 // If the declarator-id is not a template-id, issue a diagnostic and
273 // recover by ignoring the 'template' keyword.
274 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
275 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
278 SourceLocation LAngleLoc
279 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
280 Diag(DeclaratorInfo.getIdentifierLoc(),
281 diag::err_explicit_instantiation_with_definition)
282 << SourceRange(TemplateInfo.TemplateLoc)
283 << FixItHint::CreateInsertion(LAngleLoc, "<>");
285 // Recover as if it were an explicit specialization.
286 TemplateParameterLists FakedParamLists;
287 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
288 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
289 LAngleLoc, nullptr));
291 return ParseFunctionDefinition(
292 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
293 /*isSpecialization=*/true,
294 /*LastParamListWasEmpty=*/true),
298 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
302 // Parse this declaration.
303 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
306 if (Tok.is(tok::comma)) {
307 Diag(Tok, diag::err_multiple_template_declarators)
308 << (int)TemplateInfo.Kind;
309 SkipUntil(tok::semi);
313 // Eat the semi colon after the declaration.
314 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
315 if (LateParsedAttrs.size() > 0)
316 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
317 DeclaratorInfo.complete(ThisDecl);
321 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
322 /// angle brackets. Depth is the depth of this template-parameter-list, which
323 /// is the number of template headers directly enclosing this template header.
324 /// TemplateParams is the current list of template parameters we're building.
325 /// The template parameter we parse will be added to this list. LAngleLoc and
326 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
327 /// that enclose this template parameter list.
329 /// \returns true if an error occurred, false otherwise.
330 bool Parser::ParseTemplateParameters(unsigned Depth,
331 SmallVectorImpl<Decl*> &TemplateParams,
332 SourceLocation &LAngleLoc,
333 SourceLocation &RAngleLoc) {
334 // Get the template parameter list.
335 if (!TryConsumeToken(tok::less, LAngleLoc)) {
336 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
340 // Try to parse the template parameter list.
342 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
343 Failed = ParseTemplateParameterList(Depth, TemplateParams);
345 if (Tok.is(tok::greatergreater)) {
346 // No diagnostic required here: a template-parameter-list can only be
347 // followed by a declaration or, for a template template parameter, the
348 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
349 // This matters for elegant diagnosis of:
350 // template<template<typename>> struct S;
351 Tok.setKind(tok::greater);
352 RAngleLoc = Tok.getLocation();
353 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
354 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
355 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
361 /// ParseTemplateParameterList - Parse a template parameter list. If
362 /// the parsing fails badly (i.e., closing bracket was left out), this
363 /// will try to put the token stream in a reasonable position (closing
364 /// a statement, etc.) and return false.
366 /// template-parameter-list: [C++ temp]
367 /// template-parameter
368 /// template-parameter-list ',' template-parameter
370 Parser::ParseTemplateParameterList(unsigned Depth,
371 SmallVectorImpl<Decl*> &TemplateParams) {
374 = ParseTemplateParameter(Depth, TemplateParams.size())) {
375 TemplateParams.push_back(TmpParam);
377 // If we failed to parse a template parameter, skip until we find
378 // a comma or closing brace.
379 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
380 StopAtSemi | StopBeforeMatch);
383 // Did we find a comma or the end of the template parameter list?
384 if (Tok.is(tok::comma)) {
386 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
387 // Don't consume this... that's done by template parser.
390 // Somebody probably forgot to close the template. Skip ahead and
391 // try to get out of the expression. This error is currently
392 // subsumed by whatever goes on in ParseTemplateParameter.
393 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
394 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
395 StopAtSemi | StopBeforeMatch);
402 /// \brief Determine whether the parser is at the start of a template
404 bool Parser::isStartOfTemplateTypeParameter() {
405 if (Tok.is(tok::kw_class)) {
406 // "class" may be the start of an elaborated-type-specifier or a
407 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
408 switch (NextToken().getKind()) {
412 case tok::greatergreater:
416 case tok::identifier:
417 // This may be either a type-parameter or an elaborated-type-specifier.
418 // We have to look further.
425 switch (GetLookAheadToken(2).getKind()) {
429 case tok::greatergreater:
437 if (Tok.isNot(tok::kw_typename))
440 // C++ [temp.param]p2:
441 // There is no semantic difference between class and typename in a
442 // template-parameter. typename followed by an unqualified-id
443 // names a template type parameter. typename followed by a
444 // qualified-id denotes the type in a non-type
445 // parameter-declaration.
446 Token Next = NextToken();
448 // If we have an identifier, skip over it.
449 if (Next.getKind() == tok::identifier)
450 Next = GetLookAheadToken(2);
452 switch (Next.getKind()) {
456 case tok::greatergreater:
465 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
467 /// template-parameter: [C++ temp.param]
469 /// parameter-declaration
471 /// type-parameter: (see below)
472 /// 'class' ...[opt] identifier[opt]
473 /// 'class' identifier[opt] '=' type-id
474 /// 'typename' ...[opt] identifier[opt]
475 /// 'typename' identifier[opt] '=' type-id
476 /// 'template' '<' template-parameter-list '>'
477 /// 'class' ...[opt] identifier[opt]
478 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
480 Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
481 if (isStartOfTemplateTypeParameter())
482 return ParseTypeParameter(Depth, Position);
484 if (Tok.is(tok::kw_template))
485 return ParseTemplateTemplateParameter(Depth, Position);
487 // If it's none of the above, then it must be a parameter declaration.
488 // NOTE: This will pick up errors in the closure of the template parameter
489 // list (e.g., template < ; Check here to implement >> style closures.
490 return ParseNonTypeTemplateParameter(Depth, Position);
493 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
494 /// Other kinds of template parameters are parsed in
495 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
497 /// type-parameter: [C++ temp.param]
498 /// 'class' ...[opt][C++0x] identifier[opt]
499 /// 'class' identifier[opt] '=' type-id
500 /// 'typename' ...[opt][C++0x] identifier[opt]
501 /// 'typename' identifier[opt] '=' type-id
502 Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
503 assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
504 "A type-parameter starts with 'class' or 'typename'");
506 // Consume the 'class' or 'typename' keyword.
507 bool TypenameKeyword = Tok.is(tok::kw_typename);
508 SourceLocation KeyLoc = ConsumeToken();
510 // Grab the ellipsis (if given).
511 SourceLocation EllipsisLoc;
512 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
514 getLangOpts().CPlusPlus11
515 ? diag::warn_cxx98_compat_variadic_templates
516 : diag::ext_variadic_templates);
519 // Grab the template parameter name (if given)
520 SourceLocation NameLoc;
521 IdentifierInfo *ParamName = nullptr;
522 if (Tok.is(tok::identifier)) {
523 ParamName = Tok.getIdentifierInfo();
524 NameLoc = ConsumeToken();
525 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
526 tok::greatergreater)) {
527 // Unnamed template parameter. Don't have to do anything here, just
528 // don't consume this token.
530 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
534 // Recover from misplaced ellipsis.
535 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
536 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
537 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
539 // Grab a default argument (if available).
540 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
541 // we introduce the type parameter into the local scope.
542 SourceLocation EqualLoc;
543 ParsedType DefaultArg;
544 if (TryConsumeToken(tok::equal, EqualLoc))
545 DefaultArg = ParseTypeName(/*Range=*/nullptr,
546 Declarator::TemplateTypeArgContext).get();
548 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
549 KeyLoc, ParamName, NameLoc, Depth, Position,
550 EqualLoc, DefaultArg);
553 /// ParseTemplateTemplateParameter - Handle the parsing of template
554 /// template parameters.
556 /// type-parameter: [C++ temp.param]
557 /// 'template' '<' template-parameter-list '>' type-parameter-key
558 /// ...[opt] identifier[opt]
559 /// 'template' '<' template-parameter-list '>' type-parameter-key
560 /// identifier[opt] = id-expression
561 /// type-parameter-key:
563 /// 'typename' [C++1z]
565 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
566 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
568 // Handle the template <...> part.
569 SourceLocation TemplateLoc = ConsumeToken();
570 SmallVector<Decl*,8> TemplateParams;
571 SourceLocation LAngleLoc, RAngleLoc;
573 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
574 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
580 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
581 // Generate a meaningful error if the user forgot to put class before the
582 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
583 // or greater appear immediately or after 'struct'. In the latter case,
584 // replace the keyword with 'class'.
585 if (!TryConsumeToken(tok::kw_class)) {
586 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
587 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
588 if (Tok.is(tok::kw_typename)) {
589 Diag(Tok.getLocation(),
590 getLangOpts().CPlusPlus1z
591 ? diag::warn_cxx14_compat_template_template_param_typename
592 : diag::ext_template_template_param_typename)
593 << (!getLangOpts().CPlusPlus1z
594 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
596 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
597 tok::greatergreater, tok::ellipsis)) {
598 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
599 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
600 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
602 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
608 // Parse the ellipsis, if given.
609 SourceLocation EllipsisLoc;
610 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
612 getLangOpts().CPlusPlus11
613 ? diag::warn_cxx98_compat_variadic_templates
614 : diag::ext_variadic_templates);
616 // Get the identifier, if given.
617 SourceLocation NameLoc;
618 IdentifierInfo *ParamName = nullptr;
619 if (Tok.is(tok::identifier)) {
620 ParamName = Tok.getIdentifierInfo();
621 NameLoc = ConsumeToken();
622 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
623 tok::greatergreater)) {
624 // Unnamed template parameter. Don't have to do anything here, just
625 // don't consume this token.
627 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
631 // Recover from misplaced ellipsis.
632 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
633 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
634 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
636 TemplateParameterList *ParamList =
637 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
638 TemplateLoc, LAngleLoc,
642 // Grab a default argument (if available).
643 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
644 // we introduce the template parameter into the local scope.
645 SourceLocation EqualLoc;
646 ParsedTemplateArgument DefaultArg;
647 if (TryConsumeToken(tok::equal, EqualLoc)) {
648 DefaultArg = ParseTemplateTemplateArgument();
649 if (DefaultArg.isInvalid()) {
650 Diag(Tok.getLocation(),
651 diag::err_default_template_template_parameter_not_template);
652 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
653 StopAtSemi | StopBeforeMatch);
657 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
658 ParamList, EllipsisLoc,
659 ParamName, NameLoc, Depth,
660 Position, EqualLoc, DefaultArg);
663 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
664 /// template parameters (e.g., in "template<int Size> class array;").
666 /// template-parameter:
668 /// parameter-declaration
670 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
671 // Parse the declaration-specifiers (i.e., the type).
672 // FIXME: The type should probably be restricted in some way... Not all
673 // declarators (parts of declarators?) are accepted for parameters.
674 DeclSpec DS(AttrFactory);
675 ParseDeclarationSpecifiers(DS);
677 // Parse this as a typename.
678 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
679 ParseDeclarator(ParamDecl);
680 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
681 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
685 // Recover from misplaced ellipsis.
686 SourceLocation EllipsisLoc;
687 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
688 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
690 // If there is a default value, parse it.
691 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
692 // we introduce the template parameter into the local scope.
693 SourceLocation EqualLoc;
694 ExprResult DefaultArg;
695 if (TryConsumeToken(tok::equal, EqualLoc)) {
696 // C++ [temp.param]p15:
697 // When parsing a default template-argument for a non-type
698 // template-parameter, the first non-nested > is taken as the
699 // end of the template-parameter-list rather than a greater-than
701 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
702 EnterExpressionEvaluationContext ConstantEvaluated(Actions,
703 Sema::ConstantEvaluated);
705 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
706 if (DefaultArg.isInvalid())
707 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
710 // Create the parameter.
711 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
712 Depth, Position, EqualLoc,
716 void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
717 SourceLocation CorrectLoc,
718 bool AlreadyHasEllipsis,
719 bool IdentifierHasName) {
721 if (!AlreadyHasEllipsis)
722 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
723 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
724 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
725 << !IdentifierHasName;
728 void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
730 assert(EllipsisLoc.isValid());
731 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
732 if (!AlreadyHasEllipsis)
733 D.setEllipsisLoc(EllipsisLoc);
734 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
735 AlreadyHasEllipsis, D.hasName());
738 /// \brief Parses a '>' at the end of a template list.
740 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
741 /// to determine if these tokens were supposed to be a '>' followed by
742 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
744 /// \param RAngleLoc the location of the consumed '>'.
746 /// \param ConsumeLastToken if true, the '>' is consumed.
748 /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
749 /// type parameter or type argument list, rather than a C++ template parameter
750 /// or argument list.
752 /// \returns true, if current token does not start with '>', false otherwise.
753 bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
754 bool ConsumeLastToken,
755 bool ObjCGenericList) {
756 // What will be left once we've consumed the '>'.
757 tok::TokenKind RemainingToken;
758 const char *ReplacementStr = "> >";
760 switch (Tok.getKind()) {
762 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
766 // Determine the location of the '>' token. Only consume this token
767 // if the caller asked us to.
768 RAngleLoc = Tok.getLocation();
769 if (ConsumeLastToken)
773 case tok::greatergreater:
774 RemainingToken = tok::greater;
777 case tok::greatergreatergreater:
778 RemainingToken = tok::greatergreater;
781 case tok::greaterequal:
782 RemainingToken = tok::equal;
783 ReplacementStr = "> =";
786 case tok::greatergreaterequal:
787 RemainingToken = tok::greaterequal;
791 // This template-id is terminated by a token which starts with a '>'. Outside
792 // C++11, this is now error recovery, and in C++11, this is error recovery if
793 // the token isn't '>>' or '>>>'.
794 // '>>>' is for CUDA, where this sequence of characters is parsed into
795 // tok::greatergreatergreater, rather than two separate tokens.
797 // We always allow this for Objective-C type parameter and type argument
799 RAngleLoc = Tok.getLocation();
800 Token Next = NextToken();
801 if (!ObjCGenericList) {
802 // The source range of the '>>' or '>=' at the start of the token.
803 CharSourceRange ReplacementRange =
804 CharSourceRange::getCharRange(RAngleLoc,
805 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
808 // A hint to put a space between the '>>'s. In order to make the hint as
809 // clear as possible, we include the characters either side of the space in
810 // the replacement, rather than just inserting a space at SecondCharLoc.
811 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
814 // A hint to put another space after the token, if it would otherwise be
815 // lexed differently.
817 if ((RemainingToken == tok::greater ||
818 RemainingToken == tok::greatergreater) &&
819 (Next.isOneOf(tok::greater, tok::greatergreater,
820 tok::greatergreatergreater, tok::equal,
821 tok::greaterequal, tok::greatergreaterequal,
823 areTokensAdjacent(Tok, Next))
824 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
826 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
827 if (getLangOpts().CPlusPlus11 &&
828 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
829 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
830 else if (Tok.is(tok::greaterequal))
831 DiagId = diag::err_right_angle_bracket_equal_needs_space;
832 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
835 // Strip the initial '>' from the token.
837 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
838 areTokensAdjacent(Tok, Next)) {
839 // Join two adjacent '=' tokens into one, for cases like:
840 // void (*p)() = f<int>;
843 Tok.setKind(tok::equalequal);
844 Tok.setLength(Tok.getLength() + 1);
846 Tok.setKind(RemainingToken);
847 Tok.setLength(Tok.getLength() - 1);
849 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
850 PP.getSourceManager(),
853 // The advance from '>>' to '>' in a ObjectiveC template argument list needs
854 // to be properly reflected in the token cache to allow correct interaction
855 // between annotation and backtracking.
856 if (ObjCGenericList && PrevTok.getKind() == tok::greatergreater &&
857 RemainingToken == tok::greater && PP.IsPreviousCachedToken(PrevTok)) {
858 PrevTok.setKind(RemainingToken);
859 PrevTok.setLength(1);
860 // Break tok::greatergreater into two tok::greater but only add the second
861 // one in case the client asks to consume the last token.
862 if (ConsumeLastToken)
863 PP.ReplacePreviousCachedToken({PrevTok, Tok});
865 PP.ReplacePreviousCachedToken({PrevTok});
868 if (!ConsumeLastToken) {
869 // Since we're not supposed to consume the '>' token, we need to push
870 // this token and revert the current token back to the '>'.
872 Tok.setKind(tok::greater);
874 Tok.setLocation(RAngleLoc);
880 /// \brief Parses a template-id that after the template name has
881 /// already been parsed.
883 /// This routine takes care of parsing the enclosed template argument
884 /// list ('<' template-parameter-list [opt] '>') and placing the
885 /// results into a form that can be transferred to semantic analysis.
887 /// \param Template the template declaration produced by isTemplateName
889 /// \param TemplateNameLoc the source location of the template name
891 /// \param SS if non-NULL, the nested-name-specifier preceding the
894 /// \param ConsumeLastToken if true, then we will consume the last
895 /// token that forms the template-id. Otherwise, we will leave the
896 /// last token in the stream (e.g., so that it can be replaced with an
897 /// annotation token).
899 Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
900 SourceLocation TemplateNameLoc,
901 const CXXScopeSpec &SS,
902 bool ConsumeLastToken,
903 SourceLocation &LAngleLoc,
904 TemplateArgList &TemplateArgs,
905 SourceLocation &RAngleLoc) {
906 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
909 LAngleLoc = ConsumeToken();
911 // Parse the optional template-argument-list.
912 bool Invalid = false;
914 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
915 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
916 Invalid = ParseTemplateArgumentList(TemplateArgs);
919 // Try to find the closing '>'.
920 if (ConsumeLastToken)
921 SkipUntil(tok::greater, StopAtSemi);
923 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
928 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
929 /*ObjCGenericList=*/false);
932 /// \brief Replace the tokens that form a simple-template-id with an
933 /// annotation token containing the complete template-id.
935 /// The first token in the stream must be the name of a template that
936 /// is followed by a '<'. This routine will parse the complete
937 /// simple-template-id and replace the tokens with a single annotation
938 /// token with one of two different kinds: if the template-id names a
939 /// type (and \p AllowTypeAnnotation is true), the annotation token is
940 /// a type annotation that includes the optional nested-name-specifier
941 /// (\p SS). Otherwise, the annotation token is a template-id
942 /// annotation that does not include the optional
943 /// nested-name-specifier.
945 /// \param Template the declaration of the template named by the first
946 /// token (an identifier), as returned from \c Action::isTemplateName().
948 /// \param TNK the kind of template that \p Template
949 /// refers to, as returned from \c Action::isTemplateName().
951 /// \param SS if non-NULL, the nested-name-specifier that precedes
952 /// this template name.
954 /// \param TemplateKWLoc if valid, specifies that this template-id
955 /// annotation was preceded by the 'template' keyword and gives the
956 /// location of that keyword. If invalid (the default), then this
957 /// template-id was not preceded by a 'template' keyword.
959 /// \param AllowTypeAnnotation if true (the default), then a
960 /// simple-template-id that refers to a class template, template
961 /// template parameter, or other template that produces a type will be
962 /// replaced with a type annotation token. Otherwise, the
963 /// simple-template-id is always replaced with a template-id
964 /// annotation token.
966 /// If an unrecoverable parse error occurs and no annotation token can be
967 /// formed, this function returns true.
969 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
971 SourceLocation TemplateKWLoc,
972 UnqualifiedId &TemplateName,
973 bool AllowTypeAnnotation) {
974 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
975 assert(Template && Tok.is(tok::less) &&
976 "Parser isn't at the beginning of a template-id");
978 // Consume the template-name.
979 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
981 // Parse the enclosed template argument list.
982 SourceLocation LAngleLoc, RAngleLoc;
983 TemplateArgList TemplateArgs;
984 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
986 SS, false, LAngleLoc,
991 // If we failed to parse the template ID but skipped ahead to a >, we're not
992 // going to be able to form a token annotation. Eat the '>' if present.
993 TryConsumeToken(tok::greater);
997 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
999 // Build the annotation token.
1000 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
1002 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
1003 Template, TemplateNameLoc,
1004 LAngleLoc, TemplateArgsPtr, RAngleLoc);
1005 if (Type.isInvalid()) {
1006 // If we failed to parse the template ID but skipped ahead to a >, we're not
1007 // going to be able to form a token annotation. Eat the '>' if present.
1008 TryConsumeToken(tok::greater);
1012 Tok.setKind(tok::annot_typename);
1013 setTypeAnnotation(Tok, Type.get());
1014 if (SS.isNotEmpty())
1015 Tok.setLocation(SS.getBeginLoc());
1016 else if (TemplateKWLoc.isValid())
1017 Tok.setLocation(TemplateKWLoc);
1019 Tok.setLocation(TemplateNameLoc);
1021 // Build a template-id annotation token that can be processed
1023 Tok.setKind(tok::annot_template_id);
1024 TemplateIdAnnotation *TemplateId
1025 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
1026 TemplateId->TemplateNameLoc = TemplateNameLoc;
1027 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
1028 TemplateId->Name = TemplateName.Identifier;
1029 TemplateId->Operator = OO_None;
1031 TemplateId->Name = nullptr;
1032 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
1034 TemplateId->SS = SS;
1035 TemplateId->TemplateKWLoc = TemplateKWLoc;
1036 TemplateId->Template = Template;
1037 TemplateId->Kind = TNK;
1038 TemplateId->LAngleLoc = LAngleLoc;
1039 TemplateId->RAngleLoc = RAngleLoc;
1040 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1041 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
1042 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
1043 Tok.setAnnotationValue(TemplateId);
1044 if (TemplateKWLoc.isValid())
1045 Tok.setLocation(TemplateKWLoc);
1047 Tok.setLocation(TemplateNameLoc);
1050 // Common fields for the annotation token
1051 Tok.setAnnotationEndLoc(RAngleLoc);
1053 // In case the tokens were cached, have Preprocessor replace them with the
1054 // annotation token.
1055 PP.AnnotateCachedTokens(Tok);
1059 /// \brief Replaces a template-id annotation token with a type
1060 /// annotation token.
1062 /// If there was a failure when forming the type from the template-id,
1063 /// a type annotation token will still be created, but will have a
1064 /// NULL type pointer to signify an error.
1065 void Parser::AnnotateTemplateIdTokenAsType() {
1066 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1068 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1069 assert((TemplateId->Kind == TNK_Type_template ||
1070 TemplateId->Kind == TNK_Dependent_template_name) &&
1071 "Only works for type and dependent templates");
1073 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1074 TemplateId->NumArgs);
1077 = Actions.ActOnTemplateIdType(TemplateId->SS,
1078 TemplateId->TemplateKWLoc,
1079 TemplateId->Template,
1080 TemplateId->TemplateNameLoc,
1081 TemplateId->LAngleLoc,
1083 TemplateId->RAngleLoc);
1084 // Create the new "type" annotation token.
1085 Tok.setKind(tok::annot_typename);
1086 setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
1087 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1088 Tok.setLocation(TemplateId->SS.getBeginLoc());
1089 // End location stays the same
1091 // Replace the template-id annotation token, and possible the scope-specifier
1092 // that precedes it, with the typename annotation token.
1093 PP.AnnotateCachedTokens(Tok);
1096 /// \brief Determine whether the given token can end a template argument.
1097 static bool isEndOfTemplateArgument(Token Tok) {
1098 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
1101 /// \brief Parse a C++ template template argument.
1102 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1103 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1104 !Tok.is(tok::annot_cxxscope))
1105 return ParsedTemplateArgument();
1107 // C++0x [temp.arg.template]p1:
1108 // A template-argument for a template template-parameter shall be the name
1109 // of a class template or an alias template, expressed as id-expression.
1111 // We parse an id-expression that refers to a class template or alias
1112 // template. The grammar we parse is:
1114 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1116 // followed by a token that terminates a template argument, such as ',',
1117 // '>', or (in some cases) '>>'.
1118 CXXScopeSpec SS; // nested-name-specifier, if present
1119 ParseOptionalCXXScopeSpecifier(SS, nullptr,
1120 /*EnteringContext=*/false);
1122 ParsedTemplateArgument Result;
1123 SourceLocation EllipsisLoc;
1124 if (SS.isSet() && Tok.is(tok::kw_template)) {
1125 // Parse the optional 'template' keyword following the
1126 // nested-name-specifier.
1127 SourceLocation TemplateKWLoc = ConsumeToken();
1129 if (Tok.is(tok::identifier)) {
1130 // We appear to have a dependent template name.
1132 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1133 ConsumeToken(); // the identifier
1135 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1137 // If the next token signals the end of a template argument,
1138 // then we have a dependent template name that could be a template
1139 // template argument.
1140 TemplateTy Template;
1141 if (isEndOfTemplateArgument(Tok) &&
1142 Actions.ActOnDependentTemplateName(
1143 getCurScope(), SS, TemplateKWLoc, Name,
1144 /*ObjectType=*/nullptr,
1145 /*EnteringContext=*/false, Template))
1146 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1148 } else if (Tok.is(tok::identifier)) {
1149 // We may have a (non-dependent) template name.
1150 TemplateTy Template;
1152 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1153 ConsumeToken(); // the identifier
1155 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1157 if (isEndOfTemplateArgument(Tok)) {
1158 bool MemberOfUnknownSpecialization;
1159 TemplateNameKind TNK = Actions.isTemplateName(
1161 /*hasTemplateKeyword=*/false, Name,
1162 /*ObjectType=*/nullptr,
1163 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
1164 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1165 // We have an id-expression that refers to a class template or
1166 // (C++0x) alias template.
1167 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1172 // If this is a pack expansion, build it as such.
1173 if (EllipsisLoc.isValid() && !Result.isInvalid())
1174 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1179 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1181 /// template-argument: [C++ 14.2]
1182 /// constant-expression
1185 ParsedTemplateArgument Parser::ParseTemplateArgument() {
1186 // C++ [temp.arg]p2:
1187 // In a template-argument, an ambiguity between a type-id and an
1188 // expression is resolved to a type-id, regardless of the form of
1189 // the corresponding template-parameter.
1191 // Therefore, we initially try to parse a type-id.
1192 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1193 SourceLocation Loc = Tok.getLocation();
1194 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
1195 Declarator::TemplateTypeArgContext);
1196 if (TypeArg.isInvalid())
1197 return ParsedTemplateArgument();
1199 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1200 TypeArg.get().getAsOpaquePtr(),
1204 // Try to parse a template template argument.
1206 TentativeParsingAction TPA(*this);
1208 ParsedTemplateArgument TemplateTemplateArgument
1209 = ParseTemplateTemplateArgument();
1210 if (!TemplateTemplateArgument.isInvalid()) {
1212 return TemplateTemplateArgument;
1215 // Revert this tentative parse to parse a non-type template argument.
1219 // Parse a non-type template argument.
1220 SourceLocation Loc = Tok.getLocation();
1221 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1222 if (ExprArg.isInvalid() || !ExprArg.get())
1223 return ParsedTemplateArgument();
1225 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1226 ExprArg.get(), Loc);
1229 /// \brief Determine whether the current tokens can only be parsed as a
1230 /// template argument list (starting with the '<') and never as a '<'
1232 bool Parser::IsTemplateArgumentList(unsigned Skip) {
1233 struct AlwaysRevertAction : TentativeParsingAction {
1234 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1235 ~AlwaysRevertAction() { Revert(); }
1244 if (!TryConsumeToken(tok::less))
1247 // An empty template argument list.
1248 if (Tok.is(tok::greater))
1251 // See whether we have declaration specifiers, which indicate a type.
1252 while (isCXXDeclarationSpecifier() == TPResult::True)
1255 // If we have a '>' or a ',' then this is a template argument list.
1256 return Tok.isOneOf(tok::greater, tok::comma);
1259 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1260 /// (C++ [temp.names]). Returns true if there was an error.
1262 /// template-argument-list: [C++ 14.2]
1263 /// template-argument
1264 /// template-argument-list ',' template-argument
1266 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1267 // Template argument lists are constant-evaluation contexts.
1268 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
1269 ColonProtectionRAIIObject ColonProtection(*this, false);
1272 ParsedTemplateArgument Arg = ParseTemplateArgument();
1273 SourceLocation EllipsisLoc;
1274 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
1275 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1277 if (Arg.isInvalid()) {
1278 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
1282 // Save this template argument.
1283 TemplateArgs.push_back(Arg);
1285 // If the next token is a comma, consume it and keep reading
1287 } while (TryConsumeToken(tok::comma));
1292 /// \brief Parse a C++ explicit template instantiation
1293 /// (C++ [temp.explicit]).
1295 /// explicit-instantiation:
1296 /// 'extern' [opt] 'template' declaration
1298 /// Note that the 'extern' is a GNU extension and C++11 feature.
1299 Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1300 SourceLocation ExternLoc,
1301 SourceLocation TemplateLoc,
1302 SourceLocation &DeclEnd,
1303 AccessSpecifier AS) {
1304 // This isn't really required here.
1305 ParsingDeclRAIIObject
1306 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1308 return ParseSingleDeclarationAfterTemplate(Context,
1309 ParsedTemplateInfo(ExternLoc,
1311 ParsingTemplateParams,
1315 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1317 return getTemplateParamsRange(TemplateParams->data(),
1318 TemplateParams->size());
1320 SourceRange R(TemplateLoc);
1321 if (ExternLoc.isValid())
1322 R.setBegin(ExternLoc);
1326 void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1327 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
1330 /// \brief Late parse a C++ function template in Microsoft mode.
1331 void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1335 // Get the FunctionDecl.
1336 FunctionDecl *FunD = LPT.D->getAsFunction();
1337 // Track template parameter depth.
1338 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1340 // To restore the context after late parsing.
1341 Sema::ContextRAII GlobalSavedContext(
1342 Actions, Actions.Context.getTranslationUnitDecl());
1344 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1346 // Get the list of DeclContexts to reenter.
1347 SmallVector<DeclContext*, 4> DeclContextsToReenter;
1348 DeclContext *DD = FunD;
1349 while (DD && !DD->isTranslationUnit()) {
1350 DeclContextsToReenter.push_back(DD);
1351 DD = DD->getLexicalParent();
1354 // Reenter template scopes from outermost to innermost.
1355 SmallVectorImpl<DeclContext *>::reverse_iterator II =
1356 DeclContextsToReenter.rbegin();
1357 for (; II != DeclContextsToReenter.rend(); ++II) {
1358 TemplateParamScopeStack.push_back(new ParseScope(this,
1359 Scope::TemplateParamScope));
1360 unsigned NumParamLists =
1361 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1362 CurTemplateDepthTracker.addDepth(NumParamLists);
1364 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1365 Actions.PushDeclContext(Actions.getCurScope(), *II);
1369 assert(!LPT.Toks.empty() && "Empty body!");
1371 // Append the current token at the end of the new token stream so that it
1372 // doesn't get lost.
1373 LPT.Toks.push_back(Tok);
1374 PP.EnterTokenStream(LPT.Toks, true);
1376 // Consume the previously pushed token.
1377 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1378 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1379 "Inline method not starting with '{', ':' or 'try'");
1381 // Parse the method body. Function body parsing code is similar enough
1382 // to be re-used for method bodies as well.
1383 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1385 // Recreate the containing function DeclContext.
1386 Sema::ContextRAII FunctionSavedContext(Actions,
1387 Actions.getContainingDC(FunD));
1389 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1391 if (Tok.is(tok::kw_try)) {
1392 ParseFunctionTryBlock(LPT.D, FnScope);
1394 if (Tok.is(tok::colon))
1395 ParseConstructorInitializer(LPT.D);
1397 Actions.ActOnDefaultCtorInitializers(LPT.D);
1399 if (Tok.is(tok::l_brace)) {
1400 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1401 cast<FunctionTemplateDecl>(LPT.D)
1402 ->getTemplateParameters()
1403 ->getDepth() == TemplateParameterDepth - 1) &&
1404 "TemplateParameterDepth should be greater than the depth of "
1405 "current template being instantiated!");
1406 ParseFunctionStatementBody(LPT.D, FnScope);
1407 Actions.UnmarkAsLateParsedTemplate(FunD);
1409 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1414 SmallVectorImpl<ParseScope *>::reverse_iterator I =
1415 TemplateParamScopeStack.rbegin();
1416 for (; I != TemplateParamScopeStack.rend(); ++I)
1420 /// \brief Lex a delayed template function for late parsing.
1421 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1422 tok::TokenKind kind = Tok.getKind();
1423 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1424 // Consume everything up to (and including) the matching right brace.
1425 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1428 // If we're in a function-try-block, we need to store all the catch blocks.
1429 if (kind == tok::kw_try) {
1430 while (Tok.is(tok::kw_catch)) {
1431 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1432 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);