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/AST/ASTContext.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/Parse/ParseDiagnostic.h"
17 #include "clang/Parse/Parser.h"
18 #include "clang/Parse/RAIIObjectsForParser.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(DeclaratorContext 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(DeclaratorContext 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<NamedDecl*, 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(
172 DeclaratorContext Context,
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 == DeclaratorContext::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 auto usingDeclPtr = ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
202 if (!usingDeclPtr || !usingDeclPtr.get().isSingleDecl())
204 return usingDeclPtr.get().getSingleDecl();
207 // Parse the declaration specifiers, stealing any diagnostics from
208 // the template parameters.
209 ParsingDeclSpec DS(*this, &DiagsFromTParams);
211 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
212 getDeclSpecContextFromDeclaratorContext(Context));
214 if (Tok.is(tok::semi)) {
215 ProhibitAttributes(prefixAttrs);
216 DeclEnd = ConsumeToken();
217 RecordDecl *AnonRecord = nullptr;
218 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
219 getCurScope(), AS, DS,
220 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
221 : MultiTemplateParamsArg(),
222 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
224 assert(!AnonRecord &&
225 "Anonymous unions/structs should not be valid with template");
230 // Move the attributes from the prefix into the DS.
231 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
232 ProhibitAttributes(prefixAttrs);
234 DS.takeAttributesFrom(prefixAttrs);
236 // Parse the declarator.
237 ParsingDeclarator DeclaratorInfo(*this, DS, (DeclaratorContext)Context);
238 ParseDeclarator(DeclaratorInfo);
239 // Error parsing the declarator?
240 if (!DeclaratorInfo.hasName()) {
241 // If so, skip until the semi-colon or a }.
242 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
243 if (Tok.is(tok::semi))
248 LateParsedAttrList LateParsedAttrs(true);
249 if (DeclaratorInfo.isFunctionDeclarator())
250 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
252 if (DeclaratorInfo.isFunctionDeclarator() &&
253 isStartOfFunctionDefinition(DeclaratorInfo)) {
255 // Function definitions are only allowed at file scope and in C++ classes.
256 // The C++ inline method definition case is handled elsewhere, so we only
257 // need to handle the file scope definition case.
258 if (Context != DeclaratorContext::FileContext) {
259 Diag(Tok, diag::err_function_definition_not_allowed);
264 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
265 // Recover by ignoring the 'typedef'. This was probably supposed to be
266 // the 'typename' keyword, which we should have already suggested adding
267 // if it's appropriate.
268 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
269 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
270 DS.ClearStorageClassSpecs();
273 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
274 if (DeclaratorInfo.getName().getKind() !=
275 UnqualifiedIdKind::IK_TemplateId) {
276 // If the declarator-id is not a template-id, issue a diagnostic and
277 // recover by ignoring the 'template' keyword.
278 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
279 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
282 SourceLocation LAngleLoc
283 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
284 Diag(DeclaratorInfo.getIdentifierLoc(),
285 diag::err_explicit_instantiation_with_definition)
286 << SourceRange(TemplateInfo.TemplateLoc)
287 << FixItHint::CreateInsertion(LAngleLoc, "<>");
289 // Recover as if it were an explicit specialization.
290 TemplateParameterLists FakedParamLists;
291 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
292 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
293 LAngleLoc, nullptr));
295 return ParseFunctionDefinition(
296 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
297 /*isSpecialization=*/true,
298 /*LastParamListWasEmpty=*/true),
302 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
306 // Parse this declaration.
307 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
310 if (Tok.is(tok::comma)) {
311 Diag(Tok, diag::err_multiple_template_declarators)
312 << (int)TemplateInfo.Kind;
313 SkipUntil(tok::semi);
317 // Eat the semi colon after the declaration.
318 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
319 if (LateParsedAttrs.size() > 0)
320 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
321 DeclaratorInfo.complete(ThisDecl);
325 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
326 /// angle brackets. Depth is the depth of this template-parameter-list, which
327 /// is the number of template headers directly enclosing this template header.
328 /// TemplateParams is the current list of template parameters we're building.
329 /// The template parameter we parse will be added to this list. LAngleLoc and
330 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
331 /// that enclose this template parameter list.
333 /// \returns true if an error occurred, false otherwise.
334 bool Parser::ParseTemplateParameters(
335 unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams,
336 SourceLocation &LAngleLoc, SourceLocation &RAngleLoc) {
337 // Get the template parameter list.
338 if (!TryConsumeToken(tok::less, LAngleLoc)) {
339 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
343 // Try to parse the template parameter list.
345 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
346 Failed = ParseTemplateParameterList(Depth, TemplateParams);
348 if (Tok.is(tok::greatergreater)) {
349 // No diagnostic required here: a template-parameter-list can only be
350 // followed by a declaration or, for a template template parameter, the
351 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
352 // This matters for elegant diagnosis of:
353 // template<template<typename>> struct S;
354 Tok.setKind(tok::greater);
355 RAngleLoc = Tok.getLocation();
356 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
357 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
358 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
364 /// ParseTemplateParameterList - Parse a template parameter list. If
365 /// the parsing fails badly (i.e., closing bracket was left out), this
366 /// will try to put the token stream in a reasonable position (closing
367 /// a statement, etc.) and return false.
369 /// template-parameter-list: [C++ temp]
370 /// template-parameter
371 /// template-parameter-list ',' template-parameter
373 Parser::ParseTemplateParameterList(const unsigned Depth,
374 SmallVectorImpl<NamedDecl*> &TemplateParams) {
377 if (NamedDecl *TmpParam
378 = ParseTemplateParameter(Depth, TemplateParams.size())) {
379 TemplateParams.push_back(TmpParam);
381 // If we failed to parse a template parameter, skip until we find
382 // a comma or closing brace.
383 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
384 StopAtSemi | StopBeforeMatch);
387 // Did we find a comma or the end of the template parameter list?
388 if (Tok.is(tok::comma)) {
390 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
391 // Don't consume this... that's done by template parser.
394 // Somebody probably forgot to close the template. Skip ahead and
395 // try to get out of the expression. This error is currently
396 // subsumed by whatever goes on in ParseTemplateParameter.
397 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
398 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
399 StopAtSemi | StopBeforeMatch);
406 /// \brief Determine whether the parser is at the start of a template
408 bool Parser::isStartOfTemplateTypeParameter() {
409 if (Tok.is(tok::kw_class)) {
410 // "class" may be the start of an elaborated-type-specifier or a
411 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
412 switch (NextToken().getKind()) {
416 case tok::greatergreater:
420 case tok::identifier:
421 // This may be either a type-parameter or an elaborated-type-specifier.
422 // We have to look further.
429 switch (GetLookAheadToken(2).getKind()) {
433 case tok::greatergreater:
441 if (Tok.isNot(tok::kw_typename))
444 // C++ [temp.param]p2:
445 // There is no semantic difference between class and typename in a
446 // template-parameter. typename followed by an unqualified-id
447 // names a template type parameter. typename followed by a
448 // qualified-id denotes the type in a non-type
449 // parameter-declaration.
450 Token Next = NextToken();
452 // If we have an identifier, skip over it.
453 if (Next.getKind() == tok::identifier)
454 Next = GetLookAheadToken(2);
456 switch (Next.getKind()) {
460 case tok::greatergreater:
469 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
471 /// template-parameter: [C++ temp.param]
473 /// parameter-declaration
475 /// type-parameter: (see below)
476 /// 'class' ...[opt] identifier[opt]
477 /// 'class' identifier[opt] '=' type-id
478 /// 'typename' ...[opt] identifier[opt]
479 /// 'typename' identifier[opt] '=' type-id
480 /// 'template' '<' template-parameter-list '>'
481 /// 'class' ...[opt] identifier[opt]
482 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
484 NamedDecl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
485 if (isStartOfTemplateTypeParameter())
486 return ParseTypeParameter(Depth, Position);
488 if (Tok.is(tok::kw_template))
489 return ParseTemplateTemplateParameter(Depth, Position);
491 // If it's none of the above, then it must be a parameter declaration.
492 // NOTE: This will pick up errors in the closure of the template parameter
493 // list (e.g., template < ; Check here to implement >> style closures.
494 return ParseNonTypeTemplateParameter(Depth, Position);
497 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
498 /// Other kinds of template parameters are parsed in
499 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
501 /// type-parameter: [C++ temp.param]
502 /// 'class' ...[opt][C++0x] identifier[opt]
503 /// 'class' identifier[opt] '=' type-id
504 /// 'typename' ...[opt][C++0x] identifier[opt]
505 /// 'typename' identifier[opt] '=' type-id
506 NamedDecl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
507 assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
508 "A type-parameter starts with 'class' or 'typename'");
510 // Consume the 'class' or 'typename' keyword.
511 bool TypenameKeyword = Tok.is(tok::kw_typename);
512 SourceLocation KeyLoc = ConsumeToken();
514 // Grab the ellipsis (if given).
515 SourceLocation EllipsisLoc;
516 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
518 getLangOpts().CPlusPlus11
519 ? diag::warn_cxx98_compat_variadic_templates
520 : diag::ext_variadic_templates);
523 // Grab the template parameter name (if given)
524 SourceLocation NameLoc;
525 IdentifierInfo *ParamName = nullptr;
526 if (Tok.is(tok::identifier)) {
527 ParamName = Tok.getIdentifierInfo();
528 NameLoc = ConsumeToken();
529 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
530 tok::greatergreater)) {
531 // Unnamed template parameter. Don't have to do anything here, just
532 // don't consume this token.
534 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
538 // Recover from misplaced ellipsis.
539 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
540 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
541 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
543 // Grab a default argument (if available).
544 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
545 // we introduce the type parameter into the local scope.
546 SourceLocation EqualLoc;
547 ParsedType DefaultArg;
548 if (TryConsumeToken(tok::equal, EqualLoc))
549 DefaultArg = ParseTypeName(/*Range=*/nullptr,
550 DeclaratorContext::TemplateTypeArgContext).get();
552 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
553 KeyLoc, ParamName, NameLoc, Depth, Position,
554 EqualLoc, DefaultArg);
557 /// ParseTemplateTemplateParameter - Handle the parsing of template
558 /// template parameters.
560 /// type-parameter: [C++ temp.param]
561 /// 'template' '<' template-parameter-list '>' type-parameter-key
562 /// ...[opt] identifier[opt]
563 /// 'template' '<' template-parameter-list '>' type-parameter-key
564 /// identifier[opt] = id-expression
565 /// type-parameter-key:
567 /// 'typename' [C++1z]
569 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
570 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
572 // Handle the template <...> part.
573 SourceLocation TemplateLoc = ConsumeToken();
574 SmallVector<NamedDecl*,8> TemplateParams;
575 SourceLocation LAngleLoc, RAngleLoc;
577 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
578 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
584 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
585 // Generate a meaningful error if the user forgot to put class before the
586 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
587 // or greater appear immediately or after 'struct'. In the latter case,
588 // replace the keyword with 'class'.
589 if (!TryConsumeToken(tok::kw_class)) {
590 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
591 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
592 if (Tok.is(tok::kw_typename)) {
593 Diag(Tok.getLocation(),
594 getLangOpts().CPlusPlus17
595 ? diag::warn_cxx14_compat_template_template_param_typename
596 : diag::ext_template_template_param_typename)
597 << (!getLangOpts().CPlusPlus17
598 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
600 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
601 tok::greatergreater, tok::ellipsis)) {
602 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
603 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
604 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
606 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
612 // Parse the ellipsis, if given.
613 SourceLocation EllipsisLoc;
614 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
616 getLangOpts().CPlusPlus11
617 ? diag::warn_cxx98_compat_variadic_templates
618 : diag::ext_variadic_templates);
620 // Get the identifier, if given.
621 SourceLocation NameLoc;
622 IdentifierInfo *ParamName = nullptr;
623 if (Tok.is(tok::identifier)) {
624 ParamName = Tok.getIdentifierInfo();
625 NameLoc = ConsumeToken();
626 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
627 tok::greatergreater)) {
628 // Unnamed template parameter. Don't have to do anything here, just
629 // don't consume this token.
631 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
635 // Recover from misplaced ellipsis.
636 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
637 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
638 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
640 TemplateParameterList *ParamList =
641 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
642 TemplateLoc, LAngleLoc,
646 // Grab a default argument (if available).
647 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
648 // we introduce the template parameter into the local scope.
649 SourceLocation EqualLoc;
650 ParsedTemplateArgument DefaultArg;
651 if (TryConsumeToken(tok::equal, EqualLoc)) {
652 DefaultArg = ParseTemplateTemplateArgument();
653 if (DefaultArg.isInvalid()) {
654 Diag(Tok.getLocation(),
655 diag::err_default_template_template_parameter_not_template);
656 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
657 StopAtSemi | StopBeforeMatch);
661 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
662 ParamList, EllipsisLoc,
663 ParamName, NameLoc, Depth,
664 Position, EqualLoc, DefaultArg);
667 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
668 /// template parameters (e.g., in "template<int Size> class array;").
670 /// template-parameter:
672 /// parameter-declaration
674 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
675 // Parse the declaration-specifiers (i.e., the type).
676 // FIXME: The type should probably be restricted in some way... Not all
677 // declarators (parts of declarators?) are accepted for parameters.
678 DeclSpec DS(AttrFactory);
679 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none,
680 DeclSpecContext::DSC_template_param);
682 // Parse this as a typename.
683 Declarator ParamDecl(DS, DeclaratorContext::TemplateParamContext);
684 ParseDeclarator(ParamDecl);
685 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
686 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
690 // Recover from misplaced ellipsis.
691 SourceLocation EllipsisLoc;
692 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
693 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
695 // If there is a default value, parse it.
696 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
697 // we introduce the template parameter into the local scope.
698 SourceLocation EqualLoc;
699 ExprResult DefaultArg;
700 if (TryConsumeToken(tok::equal, EqualLoc)) {
701 // C++ [temp.param]p15:
702 // When parsing a default template-argument for a non-type
703 // template-parameter, the first non-nested > is taken as the
704 // end of the template-parameter-list rather than a greater-than
706 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
707 EnterExpressionEvaluationContext ConstantEvaluated(
708 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
710 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
711 if (DefaultArg.isInvalid())
712 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
715 // Create the parameter.
716 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
717 Depth, Position, EqualLoc,
721 void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
722 SourceLocation CorrectLoc,
723 bool AlreadyHasEllipsis,
724 bool IdentifierHasName) {
726 if (!AlreadyHasEllipsis)
727 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
728 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
729 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
730 << !IdentifierHasName;
733 void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
735 assert(EllipsisLoc.isValid());
736 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
737 if (!AlreadyHasEllipsis)
738 D.setEllipsisLoc(EllipsisLoc);
739 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
740 AlreadyHasEllipsis, D.hasName());
743 /// \brief Parses a '>' at the end of a template list.
745 /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
746 /// to determine if these tokens were supposed to be a '>' followed by
747 /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
749 /// \param RAngleLoc the location of the consumed '>'.
751 /// \param ConsumeLastToken if true, the '>' is consumed.
753 /// \param ObjCGenericList if true, this is the '>' closing an Objective-C
754 /// type parameter or type argument list, rather than a C++ template parameter
755 /// or argument list.
757 /// \returns true, if current token does not start with '>', false otherwise.
758 bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
759 bool ConsumeLastToken,
760 bool ObjCGenericList) {
761 // What will be left once we've consumed the '>'.
762 tok::TokenKind RemainingToken;
763 const char *ReplacementStr = "> >";
765 switch (Tok.getKind()) {
767 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
771 // Determine the location of the '>' token. Only consume this token
772 // if the caller asked us to.
773 RAngleLoc = Tok.getLocation();
774 if (ConsumeLastToken)
778 case tok::greatergreater:
779 RemainingToken = tok::greater;
782 case tok::greatergreatergreater:
783 RemainingToken = tok::greatergreater;
786 case tok::greaterequal:
787 RemainingToken = tok::equal;
788 ReplacementStr = "> =";
791 case tok::greatergreaterequal:
792 RemainingToken = tok::greaterequal;
796 // This template-id is terminated by a token which starts with a '>'. Outside
797 // C++11, this is now error recovery, and in C++11, this is error recovery if
798 // the token isn't '>>' or '>>>'.
799 // '>>>' is for CUDA, where this sequence of characters is parsed into
800 // tok::greatergreatergreater, rather than two separate tokens.
802 // We always allow this for Objective-C type parameter and type argument
804 RAngleLoc = Tok.getLocation();
805 Token Next = NextToken();
806 if (!ObjCGenericList) {
807 // The source range of the '>>' or '>=' at the start of the token.
808 CharSourceRange ReplacementRange =
809 CharSourceRange::getCharRange(RAngleLoc,
810 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
813 // A hint to put a space between the '>>'s. In order to make the hint as
814 // clear as possible, we include the characters either side of the space in
815 // the replacement, rather than just inserting a space at SecondCharLoc.
816 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
819 // A hint to put another space after the token, if it would otherwise be
820 // lexed differently.
822 if ((RemainingToken == tok::greater ||
823 RemainingToken == tok::greatergreater) &&
824 (Next.isOneOf(tok::greater, tok::greatergreater,
825 tok::greatergreatergreater, tok::equal,
826 tok::greaterequal, tok::greatergreaterequal,
828 areTokensAdjacent(Tok, Next))
829 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
831 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
832 if (getLangOpts().CPlusPlus11 &&
833 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
834 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
835 else if (Tok.is(tok::greaterequal))
836 DiagId = diag::err_right_angle_bracket_equal_needs_space;
837 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
840 // Strip the initial '>' from the token.
842 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
843 areTokensAdjacent(Tok, Next)) {
844 // Join two adjacent '=' tokens into one, for cases like:
845 // void (*p)() = f<int>;
848 Tok.setKind(tok::equalequal);
849 Tok.setLength(Tok.getLength() + 1);
851 Tok.setKind(RemainingToken);
852 Tok.setLength(Tok.getLength() - 1);
854 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
855 PP.getSourceManager(),
858 // The advance from '>>' to '>' in a ObjectiveC template argument list needs
859 // to be properly reflected in the token cache to allow correct interaction
860 // between annotation and backtracking.
861 if (ObjCGenericList && PrevTok.getKind() == tok::greatergreater &&
862 RemainingToken == tok::greater && PP.IsPreviousCachedToken(PrevTok)) {
863 PrevTok.setKind(RemainingToken);
864 PrevTok.setLength(1);
865 // Break tok::greatergreater into two tok::greater but only add the second
866 // one in case the client asks to consume the last token.
867 if (ConsumeLastToken)
868 PP.ReplacePreviousCachedToken({PrevTok, Tok});
870 PP.ReplacePreviousCachedToken({PrevTok});
873 if (!ConsumeLastToken) {
874 // Since we're not supposed to consume the '>' token, we need to push
875 // this token and revert the current token back to the '>'.
877 Tok.setKind(tok::greater);
879 Tok.setLocation(RAngleLoc);
885 /// \brief Parses a template-id that after the template name has
886 /// already been parsed.
888 /// This routine takes care of parsing the enclosed template argument
889 /// list ('<' template-parameter-list [opt] '>') and placing the
890 /// results into a form that can be transferred to semantic analysis.
892 /// \param ConsumeLastToken if true, then we will consume the last
893 /// token that forms the template-id. Otherwise, we will leave the
894 /// last token in the stream (e.g., so that it can be replaced with an
895 /// annotation token).
897 Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
898 SourceLocation &LAngleLoc,
899 TemplateArgList &TemplateArgs,
900 SourceLocation &RAngleLoc) {
901 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
904 LAngleLoc = ConsumeToken();
906 // Parse the optional template-argument-list.
907 bool Invalid = false;
909 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
910 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
911 Invalid = ParseTemplateArgumentList(TemplateArgs);
914 // Try to find the closing '>'.
915 if (ConsumeLastToken)
916 SkipUntil(tok::greater, StopAtSemi);
918 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
923 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
924 /*ObjCGenericList=*/false);
927 /// \brief Replace the tokens that form a simple-template-id with an
928 /// annotation token containing the complete template-id.
930 /// The first token in the stream must be the name of a template that
931 /// is followed by a '<'. This routine will parse the complete
932 /// simple-template-id and replace the tokens with a single annotation
933 /// token with one of two different kinds: if the template-id names a
934 /// type (and \p AllowTypeAnnotation is true), the annotation token is
935 /// a type annotation that includes the optional nested-name-specifier
936 /// (\p SS). Otherwise, the annotation token is a template-id
937 /// annotation that does not include the optional
938 /// nested-name-specifier.
940 /// \param Template the declaration of the template named by the first
941 /// token (an identifier), as returned from \c Action::isTemplateName().
943 /// \param TNK the kind of template that \p Template
944 /// refers to, as returned from \c Action::isTemplateName().
946 /// \param SS if non-NULL, the nested-name-specifier that precedes
947 /// this template name.
949 /// \param TemplateKWLoc if valid, specifies that this template-id
950 /// annotation was preceded by the 'template' keyword and gives the
951 /// location of that keyword. If invalid (the default), then this
952 /// template-id was not preceded by a 'template' keyword.
954 /// \param AllowTypeAnnotation if true (the default), then a
955 /// simple-template-id that refers to a class template, template
956 /// template parameter, or other template that produces a type will be
957 /// replaced with a type annotation token. Otherwise, the
958 /// simple-template-id is always replaced with a template-id
959 /// annotation token.
961 /// If an unrecoverable parse error occurs and no annotation token can be
962 /// formed, this function returns true.
964 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
966 SourceLocation TemplateKWLoc,
967 UnqualifiedId &TemplateName,
968 bool AllowTypeAnnotation) {
969 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
970 assert(Template && Tok.is(tok::less) &&
971 "Parser isn't at the beginning of a template-id");
973 // Consume the template-name.
974 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
976 // Parse the enclosed template argument list.
977 SourceLocation LAngleLoc, RAngleLoc;
978 TemplateArgList TemplateArgs;
979 bool Invalid = ParseTemplateIdAfterTemplateName(false, LAngleLoc,
984 // If we failed to parse the template ID but skipped ahead to a >, we're not
985 // going to be able to form a token annotation. Eat the '>' if present.
986 TryConsumeToken(tok::greater);
990 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
992 // Build the annotation token.
993 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
994 TypeResult Type = Actions.ActOnTemplateIdType(
995 SS, TemplateKWLoc, Template, TemplateName.Identifier,
996 TemplateNameLoc, LAngleLoc, TemplateArgsPtr, RAngleLoc);
997 if (Type.isInvalid()) {
998 // If we failed to parse the template ID but skipped ahead to a >, we're
999 // not going to be able to form a token annotation. Eat the '>' if
1001 TryConsumeToken(tok::greater);
1005 Tok.setKind(tok::annot_typename);
1006 setTypeAnnotation(Tok, Type.get());
1007 if (SS.isNotEmpty())
1008 Tok.setLocation(SS.getBeginLoc());
1009 else if (TemplateKWLoc.isValid())
1010 Tok.setLocation(TemplateKWLoc);
1012 Tok.setLocation(TemplateNameLoc);
1014 // Build a template-id annotation token that can be processed
1016 Tok.setKind(tok::annot_template_id);
1018 IdentifierInfo *TemplateII =
1019 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1020 ? TemplateName.Identifier
1023 OverloadedOperatorKind OpKind =
1024 TemplateName.getKind() == UnqualifiedIdKind::IK_Identifier
1026 : TemplateName.OperatorFunctionId.Operator;
1028 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
1029 SS, TemplateKWLoc, TemplateNameLoc, TemplateII, OpKind, Template, TNK,
1030 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
1032 Tok.setAnnotationValue(TemplateId);
1033 if (TemplateKWLoc.isValid())
1034 Tok.setLocation(TemplateKWLoc);
1036 Tok.setLocation(TemplateNameLoc);
1039 // Common fields for the annotation token
1040 Tok.setAnnotationEndLoc(RAngleLoc);
1042 // In case the tokens were cached, have Preprocessor replace them with the
1043 // annotation token.
1044 PP.AnnotateCachedTokens(Tok);
1048 /// \brief Replaces a template-id annotation token with a type
1049 /// annotation token.
1051 /// If there was a failure when forming the type from the template-id,
1052 /// a type annotation token will still be created, but will have a
1053 /// NULL type pointer to signify an error.
1055 /// \param IsClassName Is this template-id appearing in a context where we
1056 /// know it names a class, such as in an elaborated-type-specifier or
1057 /// base-specifier? ('typename' and 'template' are unneeded and disallowed
1058 /// in those contexts.)
1059 void Parser::AnnotateTemplateIdTokenAsType(bool IsClassName) {
1060 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1062 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1063 assert((TemplateId->Kind == TNK_Type_template ||
1064 TemplateId->Kind == TNK_Dependent_template_name) &&
1065 "Only works for type and dependent templates");
1067 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1068 TemplateId->NumArgs);
1071 = Actions.ActOnTemplateIdType(TemplateId->SS,
1072 TemplateId->TemplateKWLoc,
1073 TemplateId->Template,
1075 TemplateId->TemplateNameLoc,
1076 TemplateId->LAngleLoc,
1078 TemplateId->RAngleLoc,
1079 /*IsCtorOrDtorName*/false,
1081 // Create the new "type" annotation token.
1082 Tok.setKind(tok::annot_typename);
1083 setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
1084 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1085 Tok.setLocation(TemplateId->SS.getBeginLoc());
1086 // End location stays the same
1088 // Replace the template-id annotation token, and possible the scope-specifier
1089 // that precedes it, with the typename annotation token.
1090 PP.AnnotateCachedTokens(Tok);
1093 /// \brief Determine whether the given token can end a template argument.
1094 static bool isEndOfTemplateArgument(Token Tok) {
1095 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
1098 /// \brief Parse a C++ template template argument.
1099 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1100 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1101 !Tok.is(tok::annot_cxxscope))
1102 return ParsedTemplateArgument();
1104 // C++0x [temp.arg.template]p1:
1105 // A template-argument for a template template-parameter shall be the name
1106 // of a class template or an alias template, expressed as id-expression.
1108 // We parse an id-expression that refers to a class template or alias
1109 // template. The grammar we parse is:
1111 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1113 // followed by a token that terminates a template argument, such as ',',
1114 // '>', or (in some cases) '>>'.
1115 CXXScopeSpec SS; // nested-name-specifier, if present
1116 ParseOptionalCXXScopeSpecifier(SS, nullptr,
1117 /*EnteringContext=*/false);
1119 ParsedTemplateArgument Result;
1120 SourceLocation EllipsisLoc;
1121 if (SS.isSet() && Tok.is(tok::kw_template)) {
1122 // Parse the optional 'template' keyword following the
1123 // nested-name-specifier.
1124 SourceLocation TemplateKWLoc = ConsumeToken();
1126 if (Tok.is(tok::identifier)) {
1127 // We appear to have a dependent template name.
1129 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1130 ConsumeToken(); // the identifier
1132 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1134 // If the next token signals the end of a template argument,
1135 // then we have a dependent template name that could be a template
1136 // template argument.
1137 TemplateTy Template;
1138 if (isEndOfTemplateArgument(Tok) &&
1139 Actions.ActOnDependentTemplateName(
1140 getCurScope(), SS, TemplateKWLoc, Name,
1141 /*ObjectType=*/nullptr,
1142 /*EnteringContext=*/false, Template))
1143 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1145 } else if (Tok.is(tok::identifier)) {
1146 // We may have a (non-dependent) template name.
1147 TemplateTy Template;
1149 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1150 ConsumeToken(); // the identifier
1152 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1154 if (isEndOfTemplateArgument(Tok)) {
1155 bool MemberOfUnknownSpecialization;
1156 TemplateNameKind TNK = Actions.isTemplateName(
1158 /*hasTemplateKeyword=*/false, Name,
1159 /*ObjectType=*/nullptr,
1160 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
1161 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1162 // We have an id-expression that refers to a class template or
1163 // (C++0x) alias template.
1164 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1169 // If this is a pack expansion, build it as such.
1170 if (EllipsisLoc.isValid() && !Result.isInvalid())
1171 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1176 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1178 /// template-argument: [C++ 14.2]
1179 /// constant-expression
1182 ParsedTemplateArgument Parser::ParseTemplateArgument() {
1183 // C++ [temp.arg]p2:
1184 // In a template-argument, an ambiguity between a type-id and an
1185 // expression is resolved to a type-id, regardless of the form of
1186 // the corresponding template-parameter.
1188 // Therefore, we initially try to parse a type-id - and isCXXTypeId might look
1189 // up and annotate an identifier as an id-expression during disambiguation,
1190 // so enter the appropriate context for a constant expression template
1191 // argument before trying to disambiguate.
1193 EnterExpressionEvaluationContext EnterConstantEvaluated(
1194 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1195 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1196 SourceLocation Loc = Tok.getLocation();
1197 TypeResult TypeArg = ParseTypeName(
1198 /*Range=*/nullptr, DeclaratorContext::TemplateTypeArgContext);
1199 if (TypeArg.isInvalid())
1200 return ParsedTemplateArgument();
1202 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1203 TypeArg.get().getAsOpaquePtr(),
1207 // Try to parse a template template argument.
1209 TentativeParsingAction TPA(*this);
1211 ParsedTemplateArgument TemplateTemplateArgument
1212 = ParseTemplateTemplateArgument();
1213 if (!TemplateTemplateArgument.isInvalid()) {
1215 return TemplateTemplateArgument;
1218 // Revert this tentative parse to parse a non-type template argument.
1222 // Parse a non-type template argument.
1223 SourceLocation Loc = Tok.getLocation();
1224 ExprResult ExprArg = ParseConstantExpressionInExprEvalContext(MaybeTypeCast);
1225 if (ExprArg.isInvalid() || !ExprArg.get())
1226 return ParsedTemplateArgument();
1228 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1229 ExprArg.get(), Loc);
1232 /// \brief Determine whether the current tokens can only be parsed as a
1233 /// template argument list (starting with the '<') and never as a '<'
1235 bool Parser::IsTemplateArgumentList(unsigned Skip) {
1236 struct AlwaysRevertAction : TentativeParsingAction {
1237 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1238 ~AlwaysRevertAction() { Revert(); }
1247 if (!TryConsumeToken(tok::less))
1250 // An empty template argument list.
1251 if (Tok.is(tok::greater))
1254 // See whether we have declaration specifiers, which indicate a type.
1255 while (isCXXDeclarationSpecifier() == TPResult::True)
1258 // If we have a '>' or a ',' then this is a template argument list.
1259 return Tok.isOneOf(tok::greater, tok::comma);
1262 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1263 /// (C++ [temp.names]). Returns true if there was an error.
1265 /// template-argument-list: [C++ 14.2]
1266 /// template-argument
1267 /// template-argument-list ',' template-argument
1269 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
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(DeclaratorContext 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 |
1386 Scope::CompoundStmtScope);
1388 // Recreate the containing function DeclContext.
1389 Sema::ContextRAII FunctionSavedContext(Actions,
1390 Actions.getContainingDC(FunD));
1392 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1394 if (Tok.is(tok::kw_try)) {
1395 ParseFunctionTryBlock(LPT.D, FnScope);
1397 if (Tok.is(tok::colon))
1398 ParseConstructorInitializer(LPT.D);
1400 Actions.ActOnDefaultCtorInitializers(LPT.D);
1402 if (Tok.is(tok::l_brace)) {
1403 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1404 cast<FunctionTemplateDecl>(LPT.D)
1405 ->getTemplateParameters()
1406 ->getDepth() == TemplateParameterDepth - 1) &&
1407 "TemplateParameterDepth should be greater than the depth of "
1408 "current template being instantiated!");
1409 ParseFunctionStatementBody(LPT.D, FnScope);
1410 Actions.UnmarkAsLateParsedTemplate(FunD);
1412 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
1417 SmallVectorImpl<ParseScope *>::reverse_iterator I =
1418 TemplateParamScopeStack.rbegin();
1419 for (; I != TemplateParamScopeStack.rend(); ++I)
1423 /// \brief Lex a delayed template function for late parsing.
1424 void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1425 tok::TokenKind kind = Tok.getKind();
1426 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1427 // Consume everything up to (and including) the matching right brace.
1428 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1431 // If we're in a function-try-block, we need to store all the catch blocks.
1432 if (kind == tok::kw_try) {
1433 while (Tok.is(tok::kw_catch)) {
1434 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1435 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);