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 "clang/Parse/ParseDiagnostic.h"
16 #include "clang/Sema/DeclSpec.h"
17 #include "clang/Sema/ParsedTemplate.h"
18 #include "clang/Sema/Scope.h"
19 #include "RAIIObjectsForParser.h"
20 using namespace clang;
22 /// \brief Parse a template declaration, explicit instantiation, or
23 /// explicit specialization.
25 Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
26 SourceLocation &DeclEnd,
28 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less))
29 return ParseExplicitInstantiation(SourceLocation(), ConsumeToken(),
32 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS);
35 /// \brief RAII class that manages the template parameter depth.
37 class TemplateParameterDepthCounter {
42 explicit TemplateParameterDepthCounter(unsigned &Depth)
43 : Depth(Depth), AddedLevels(0) { }
45 ~TemplateParameterDepthCounter() {
54 operator unsigned() const { return Depth; }
58 /// \brief Parse a template declaration or an explicit specialization.
60 /// Template declarations include one or more template parameter lists
61 /// and either the function or class template declaration. Explicit
62 /// specializations contain one or more 'template < >' prefixes
63 /// followed by a (possibly templated) declaration. Since the
64 /// syntactic form of both features is nearly identical, we parse all
65 /// of the template headers together and let semantic analysis sort
66 /// the declarations from the explicit specializations.
68 /// template-declaration: [C++ temp]
69 /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
71 /// explicit-specialization: [ C++ temp.expl.spec]
72 /// 'template' '<' '>' declaration
74 Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
75 SourceLocation &DeclEnd,
77 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
78 "Token does not start a template declaration.");
80 // Enter template-parameter scope.
81 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
83 // Tell the action that names should be checked in the context of
84 // the declaration to come.
85 ParsingDeclRAIIObject ParsingTemplateParams(*this);
87 // Parse multiple levels of template headers within this template
88 // parameter scope, e.g.,
90 // template<typename T>
91 // template<typename U>
92 // class A<T>::B { ... };
94 // We parse multiple levels non-recursively so that we can build a
95 // single data structure containing all of the template parameter
96 // lists to easily differentiate between the case above and:
98 // template<typename T>
100 // template<typename U> class B;
103 // In the first case, the action for declaring A<T>::B receives
104 // both template parameter lists. In the second case, the action for
105 // defining A<T>::B receives just the inner template parameter list
106 // (and retrieves the outer template parameter list from its
108 bool isSpecialization = true;
109 bool LastParamListWasEmpty = false;
110 TemplateParameterLists ParamLists;
111 TemplateParameterDepthCounter Depth(TemplateParameterDepth);
113 // Consume the 'export', if any.
114 SourceLocation ExportLoc;
115 if (Tok.is(tok::kw_export)) {
116 ExportLoc = ConsumeToken();
119 // Consume the 'template', which should be here.
120 SourceLocation TemplateLoc;
121 if (Tok.is(tok::kw_template)) {
122 TemplateLoc = ConsumeToken();
124 Diag(Tok.getLocation(), diag::err_expected_template);
128 // Parse the '<' template-parameter-list '>'
129 SourceLocation LAngleLoc, RAngleLoc;
130 llvm::SmallVector<Decl*, 4> TemplateParams;
131 if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc,
133 // Skip until the semi-colon or a }.
134 SkipUntil(tok::r_brace, true, true);
135 if (Tok.is(tok::semi))
140 ParamLists.push_back(
141 Actions.ActOnTemplateParameterList(Depth, ExportLoc,
142 TemplateLoc, LAngleLoc,
143 TemplateParams.data(),
144 TemplateParams.size(), RAngleLoc));
146 if (!TemplateParams.empty()) {
147 isSpecialization = false;
150 LastParamListWasEmpty = true;
152 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
154 // Parse the actual template declaration.
155 return ParseSingleDeclarationAfterTemplate(Context,
156 ParsedTemplateInfo(&ParamLists,
158 LastParamListWasEmpty),
159 ParsingTemplateParams,
163 /// \brief Parse a single declaration that declares a template,
164 /// template specialization, or explicit instantiation of a template.
166 /// \param TemplateParams if non-NULL, the template parameter lists
167 /// that preceded this declaration. In this case, the declaration is a
168 /// template declaration, out-of-line definition of a template, or an
169 /// explicit template specialization. When NULL, the declaration is an
170 /// explicit template instantiation.
172 /// \param TemplateLoc when TemplateParams is NULL, the location of
173 /// the 'template' keyword that indicates that we have an explicit
174 /// template instantiation.
176 /// \param DeclEnd will receive the source location of the last token
177 /// within this declaration.
179 /// \param AS the access specifier associated with this
180 /// declaration. Will be AS_none for namespace-scope declarations.
182 /// \returns the new declaration.
184 Parser::ParseSingleDeclarationAfterTemplate(
186 const ParsedTemplateInfo &TemplateInfo,
187 ParsingDeclRAIIObject &DiagsFromTParams,
188 SourceLocation &DeclEnd,
189 AccessSpecifier AS) {
190 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
191 "Template information required");
193 if (Context == Declarator::MemberContext) {
194 // We are parsing a member template.
195 ParseCXXClassMemberDeclaration(AS, TemplateInfo, &DiagsFromTParams);
199 // Parse the declaration specifiers, stealing the accumulated
200 // diagnostics from the template parameters.
201 ParsingDeclSpec DS(DiagsFromTParams);
203 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
204 DS.AddAttributes(ParseCXX0XAttributes().AttrList);
206 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
207 getDeclSpecContextFromDeclaratorContext(Context));
209 if (Tok.is(tok::semi)) {
210 DeclEnd = ConsumeToken();
211 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
216 // Parse the declarator.
217 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
218 ParseDeclarator(DeclaratorInfo);
219 // Error parsing the declarator?
220 if (!DeclaratorInfo.hasName()) {
221 // If so, skip until the semi-colon or a }.
222 SkipUntil(tok::r_brace, true, true);
223 if (Tok.is(tok::semi))
228 // If we have a declaration or declarator list, handle it.
229 if (isDeclarationAfterDeclarator()) {
230 // Parse this declaration.
231 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
234 if (Tok.is(tok::comma)) {
235 Diag(Tok, diag::err_multiple_template_declarators)
236 << (int)TemplateInfo.Kind;
237 SkipUntil(tok::semi, true, false);
241 // Eat the semi colon after the declaration.
242 ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
243 DS.complete(ThisDecl);
247 if (DeclaratorInfo.isFunctionDeclarator() &&
248 isStartOfFunctionDefinition(DeclaratorInfo)) {
249 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
250 Diag(Tok, diag::err_function_declared_typedef);
252 if (Tok.is(tok::l_brace)) {
253 // This recovery skips the entire function body. It would be nice
254 // to simply call ParseFunctionDefinition() below, however Sema
255 // assumes the declarator represents a function, not a typedef.
257 SkipUntil(tok::r_brace, true);
259 SkipUntil(tok::semi);
263 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo);
266 if (DeclaratorInfo.isFunctionDeclarator())
267 Diag(Tok, diag::err_expected_fn_body);
269 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
270 SkipUntil(tok::semi);
274 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
275 /// angle brackets. Depth is the depth of this template-parameter-list, which
276 /// is the number of template headers directly enclosing this template header.
277 /// TemplateParams is the current list of template parameters we're building.
278 /// The template parameter we parse will be added to this list. LAngleLoc and
279 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
280 /// that enclose this template parameter list.
282 /// \returns true if an error occurred, false otherwise.
283 bool Parser::ParseTemplateParameters(unsigned Depth,
284 llvm::SmallVectorImpl<Decl*> &TemplateParams,
285 SourceLocation &LAngleLoc,
286 SourceLocation &RAngleLoc) {
287 // Get the template parameter list.
288 if (!Tok.is(tok::less)) {
289 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
292 LAngleLoc = ConsumeToken();
294 // Try to parse the template parameter list.
295 if (Tok.is(tok::greater))
296 RAngleLoc = ConsumeToken();
297 else if (ParseTemplateParameterList(Depth, TemplateParams)) {
298 if (!Tok.is(tok::greater)) {
299 Diag(Tok.getLocation(), diag::err_expected_greater);
302 RAngleLoc = ConsumeToken();
307 /// ParseTemplateParameterList - Parse a template parameter list. If
308 /// the parsing fails badly (i.e., closing bracket was left out), this
309 /// will try to put the token stream in a reasonable position (closing
310 /// a statement, etc.) and return false.
312 /// template-parameter-list: [C++ temp]
313 /// template-parameter
314 /// template-parameter-list ',' template-parameter
316 Parser::ParseTemplateParameterList(unsigned Depth,
317 llvm::SmallVectorImpl<Decl*> &TemplateParams) {
320 = ParseTemplateParameter(Depth, TemplateParams.size())) {
321 TemplateParams.push_back(TmpParam);
323 // If we failed to parse a template parameter, skip until we find
324 // a comma or closing brace.
325 SkipUntil(tok::comma, tok::greater, true, true);
328 // Did we find a comma or the end of the template parmeter list?
329 if (Tok.is(tok::comma)) {
331 } else if (Tok.is(tok::greater)) {
332 // Don't consume this... that's done by template parser.
335 // Somebody probably forgot to close the template. Skip ahead and
336 // try to get out of the expression. This error is currently
337 // subsumed by whatever goes on in ParseTemplateParameter.
338 // TODO: This could match >>, and it would be nice to avoid those
339 // silly errors with template <vec<T>>.
340 // Diag(Tok.getLocation(), diag::err_expected_comma_greater);
341 SkipUntil(tok::greater, true, true);
348 /// \brief Determine whether the parser is at the start of a template
350 bool Parser::isStartOfTemplateTypeParameter() {
351 if (Tok.is(tok::kw_class)) {
352 // "class" may be the start of an elaborated-type-specifier or a
353 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
354 switch (NextToken().getKind()) {
358 case tok::greatergreater:
362 case tok::identifier:
363 // This may be either a type-parameter or an elaborated-type-specifier.
364 // We have to look further.
371 switch (GetLookAheadToken(2).getKind()) {
375 case tok::greatergreater:
383 if (Tok.isNot(tok::kw_typename))
386 // C++ [temp.param]p2:
387 // There is no semantic difference between class and typename in a
388 // template-parameter. typename followed by an unqualified-id
389 // names a template type parameter. typename followed by a
390 // qualified-id denotes the type in a non-type
391 // parameter-declaration.
392 Token Next = NextToken();
394 // If we have an identifier, skip over it.
395 if (Next.getKind() == tok::identifier)
396 Next = GetLookAheadToken(2);
398 switch (Next.getKind()) {
402 case tok::greatergreater:
411 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
413 /// template-parameter: [C++ temp.param]
415 /// parameter-declaration
417 /// type-parameter: (see below)
418 /// 'class' ...[opt][C++0x] identifier[opt]
419 /// 'class' identifier[opt] '=' type-id
420 /// 'typename' ...[opt][C++0x] identifier[opt]
421 /// 'typename' identifier[opt] '=' type-id
422 /// 'template' ...[opt][C++0x] '<' template-parameter-list '>' 'class' identifier[opt]
423 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
424 Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
425 if (isStartOfTemplateTypeParameter())
426 return ParseTypeParameter(Depth, Position);
428 if (Tok.is(tok::kw_template))
429 return ParseTemplateTemplateParameter(Depth, Position);
431 // If it's none of the above, then it must be a parameter declaration.
432 // NOTE: This will pick up errors in the closure of the template parameter
433 // list (e.g., template < ; Check here to implement >> style closures.
434 return ParseNonTypeTemplateParameter(Depth, Position);
437 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
438 /// Other kinds of template parameters are parsed in
439 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
441 /// type-parameter: [C++ temp.param]
442 /// 'class' ...[opt][C++0x] identifier[opt]
443 /// 'class' identifier[opt] '=' type-id
444 /// 'typename' ...[opt][C++0x] identifier[opt]
445 /// 'typename' identifier[opt] '=' type-id
446 Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
447 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
448 "A type-parameter starts with 'class' or 'typename'");
450 // Consume the 'class' or 'typename' keyword.
451 bool TypenameKeyword = Tok.is(tok::kw_typename);
452 SourceLocation KeyLoc = ConsumeToken();
454 // Grab the ellipsis (if given).
455 bool Ellipsis = false;
456 SourceLocation EllipsisLoc;
457 if (Tok.is(tok::ellipsis)) {
459 EllipsisLoc = ConsumeToken();
461 if (!getLang().CPlusPlus0x)
462 Diag(EllipsisLoc, diag::err_variadic_templates);
465 // Grab the template parameter name (if given)
466 SourceLocation NameLoc;
467 IdentifierInfo* ParamName = 0;
468 if (Tok.is(tok::identifier)) {
469 ParamName = Tok.getIdentifierInfo();
470 NameLoc = ConsumeToken();
471 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
472 Tok.is(tok::greater)) {
473 // Unnamed template parameter. Don't have to do anything here, just
474 // don't consume this token.
476 Diag(Tok.getLocation(), diag::err_expected_ident);
480 // Grab a default argument (if available).
481 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
482 // we introduce the type parameter into the local scope.
483 SourceLocation EqualLoc;
484 ParsedType DefaultArg;
485 if (Tok.is(tok::equal)) {
486 EqualLoc = ConsumeToken();
487 DefaultArg = ParseTypeName().get();
490 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
491 EllipsisLoc, KeyLoc, ParamName, NameLoc,
492 Depth, Position, EqualLoc, DefaultArg);
495 /// ParseTemplateTemplateParameter - Handle the parsing of template
496 /// template parameters.
498 /// type-parameter: [C++ temp.param]
499 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
500 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
502 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
503 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
505 // Handle the template <...> part.
506 SourceLocation TemplateLoc = ConsumeToken();
507 llvm::SmallVector<Decl*,8> TemplateParams;
508 SourceLocation LAngleLoc, RAngleLoc;
510 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
511 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
517 // Generate a meaningful error if the user forgot to put class before the
518 // identifier, comma, or greater.
519 if (!Tok.is(tok::kw_class)) {
520 Diag(Tok.getLocation(), diag::err_expected_class_before)
521 << PP.getSpelling(Tok);
524 SourceLocation ClassLoc = ConsumeToken();
526 // Get the identifier, if given.
527 SourceLocation NameLoc;
528 IdentifierInfo* ParamName = 0;
529 if (Tok.is(tok::identifier)) {
530 ParamName = Tok.getIdentifierInfo();
531 NameLoc = ConsumeToken();
532 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
533 // Unnamed template parameter. Don't have to do anything here, just
534 // don't consume this token.
536 Diag(Tok.getLocation(), diag::err_expected_ident);
540 TemplateParamsTy *ParamList =
541 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
542 TemplateLoc, LAngleLoc,
544 TemplateParams.size(),
547 // Grab a default argument (if available).
548 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
549 // we introduce the template parameter into the local scope.
550 SourceLocation EqualLoc;
551 ParsedTemplateArgument DefaultArg;
552 if (Tok.is(tok::equal)) {
553 EqualLoc = ConsumeToken();
554 DefaultArg = ParseTemplateTemplateArgument();
555 if (DefaultArg.isInvalid()) {
556 Diag(Tok.getLocation(),
557 diag::err_default_template_template_parameter_not_template);
558 static const tok::TokenKind EndToks[] = {
559 tok::comma, tok::greater, tok::greatergreater
561 SkipUntil(EndToks, 3, true, true);
565 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
566 ParamList, ParamName,
567 NameLoc, Depth, Position,
568 EqualLoc, DefaultArg);
571 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
572 /// template parameters (e.g., in "template<int Size> class array;").
574 /// template-parameter:
576 /// parameter-declaration
578 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
579 SourceLocation StartLoc = Tok.getLocation();
581 // Parse the declaration-specifiers (i.e., the type).
582 // FIXME: The type should probably be restricted in some way... Not all
583 // declarators (parts of declarators?) are accepted for parameters.
585 ParseDeclarationSpecifiers(DS);
587 // Parse this as a typename.
588 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
589 ParseDeclarator(ParamDecl);
590 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
591 // This probably shouldn't happen - and it's more of a Sema thing, but
592 // basically we didn't parse the type name because we couldn't associate
593 // it with an AST node. we should just skip to the comma or greater.
594 // TODO: This is currently a placeholder for some kind of Sema Error.
595 Diag(Tok.getLocation(), diag::err_parse_error);
596 SkipUntil(tok::comma, tok::greater, true, true);
600 // If there is a default value, parse it.
601 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
602 // we introduce the template parameter into the local scope.
603 SourceLocation EqualLoc;
604 ExprResult DefaultArg;
605 if (Tok.is(tok::equal)) {
606 EqualLoc = ConsumeToken();
608 // C++ [temp.param]p15:
609 // When parsing a default template-argument for a non-type
610 // template-parameter, the first non-nested > is taken as the
611 // end of the template-parameter-list rather than a greater-than
613 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
615 DefaultArg = ParseAssignmentExpression();
616 if (DefaultArg.isInvalid())
617 SkipUntil(tok::comma, tok::greater, true, true);
620 // Create the parameter.
621 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
622 Depth, Position, EqualLoc,
626 /// \brief Parses a template-id that after the template name has
627 /// already been parsed.
629 /// This routine takes care of parsing the enclosed template argument
630 /// list ('<' template-parameter-list [opt] '>') and placing the
631 /// results into a form that can be transferred to semantic analysis.
633 /// \param Template the template declaration produced by isTemplateName
635 /// \param TemplateNameLoc the source location of the template name
637 /// \param SS if non-NULL, the nested-name-specifier preceding the
640 /// \param ConsumeLastToken if true, then we will consume the last
641 /// token that forms the template-id. Otherwise, we will leave the
642 /// last token in the stream (e.g., so that it can be replaced with an
643 /// annotation token).
645 Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
646 SourceLocation TemplateNameLoc,
647 const CXXScopeSpec *SS,
648 bool ConsumeLastToken,
649 SourceLocation &LAngleLoc,
650 TemplateArgList &TemplateArgs,
651 SourceLocation &RAngleLoc) {
652 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
655 LAngleLoc = ConsumeToken();
657 // Parse the optional template-argument-list.
658 bool Invalid = false;
660 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
661 if (Tok.isNot(tok::greater))
662 Invalid = ParseTemplateArgumentList(TemplateArgs);
665 // Try to find the closing '>'.
666 SkipUntil(tok::greater, true, !ConsumeLastToken);
672 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) {
673 Diag(Tok.getLocation(), diag::err_expected_greater);
677 // Determine the location of the '>' or '>>'. Only consume this
678 // token if the caller asked us to.
679 RAngleLoc = Tok.getLocation();
681 if (Tok.is(tok::greatergreater)) {
682 if (!getLang().CPlusPlus0x) {
683 const char *ReplaceStr = "> >";
684 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
687 Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space)
688 << FixItHint::CreateReplacement(
689 SourceRange(Tok.getLocation()), ReplaceStr);
692 Tok.setKind(tok::greater);
693 if (!ConsumeLastToken) {
694 // Since we're not supposed to consume the '>>' token, we need
695 // to insert a second '>' token after the first.
698 } else if (ConsumeLastToken)
704 /// \brief Replace the tokens that form a simple-template-id with an
705 /// annotation token containing the complete template-id.
707 /// The first token in the stream must be the name of a template that
708 /// is followed by a '<'. This routine will parse the complete
709 /// simple-template-id and replace the tokens with a single annotation
710 /// token with one of two different kinds: if the template-id names a
711 /// type (and \p AllowTypeAnnotation is true), the annotation token is
712 /// a type annotation that includes the optional nested-name-specifier
713 /// (\p SS). Otherwise, the annotation token is a template-id
714 /// annotation that does not include the optional
715 /// nested-name-specifier.
717 /// \param Template the declaration of the template named by the first
718 /// token (an identifier), as returned from \c Action::isTemplateName().
720 /// \param TemplateNameKind the kind of template that \p Template
721 /// refers to, as returned from \c Action::isTemplateName().
723 /// \param SS if non-NULL, the nested-name-specifier that precedes
724 /// this template name.
726 /// \param TemplateKWLoc if valid, specifies that this template-id
727 /// annotation was preceded by the 'template' keyword and gives the
728 /// location of that keyword. If invalid (the default), then this
729 /// template-id was not preceded by a 'template' keyword.
731 /// \param AllowTypeAnnotation if true (the default), then a
732 /// simple-template-id that refers to a class template, template
733 /// template parameter, or other template that produces a type will be
734 /// replaced with a type annotation token. Otherwise, the
735 /// simple-template-id is always replaced with a template-id
736 /// annotation token.
738 /// If an unrecoverable parse error occurs and no annotation token can be
739 /// formed, this function returns true.
741 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
742 const CXXScopeSpec *SS,
743 UnqualifiedId &TemplateName,
744 SourceLocation TemplateKWLoc,
745 bool AllowTypeAnnotation) {
746 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
747 assert(Template && Tok.is(tok::less) &&
748 "Parser isn't at the beginning of a template-id");
750 // Consume the template-name.
751 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
753 // Parse the enclosed template argument list.
754 SourceLocation LAngleLoc, RAngleLoc;
755 TemplateArgList TemplateArgs;
756 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
758 SS, false, LAngleLoc,
763 // If we failed to parse the template ID but skipped ahead to a >, we're not
764 // going to be able to form a token annotation. Eat the '>' if present.
765 if (Tok.is(tok::greater))
770 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
771 TemplateArgs.size());
773 // Build the annotation token.
774 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
776 = Actions.ActOnTemplateIdType(Template, TemplateNameLoc,
777 LAngleLoc, TemplateArgsPtr,
779 if (Type.isInvalid()) {
780 // If we failed to parse the template ID but skipped ahead to a >, we're not
781 // going to be able to form a token annotation. Eat the '>' if present.
782 if (Tok.is(tok::greater))
787 Tok.setKind(tok::annot_typename);
788 setTypeAnnotation(Tok, Type.get());
789 if (SS && SS->isNotEmpty())
790 Tok.setLocation(SS->getBeginLoc());
791 else if (TemplateKWLoc.isValid())
792 Tok.setLocation(TemplateKWLoc);
794 Tok.setLocation(TemplateNameLoc);
796 // Build a template-id annotation token that can be processed
798 Tok.setKind(tok::annot_template_id);
799 TemplateIdAnnotation *TemplateId
800 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
801 TemplateId->TemplateNameLoc = TemplateNameLoc;
802 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
803 TemplateId->Name = TemplateName.Identifier;
804 TemplateId->Operator = OO_None;
806 TemplateId->Name = 0;
807 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
809 TemplateId->Template = Template;
810 TemplateId->Kind = TNK;
811 TemplateId->LAngleLoc = LAngleLoc;
812 TemplateId->RAngleLoc = RAngleLoc;
813 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
814 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
815 Args[Arg] = TemplateArgs[Arg];
816 Tok.setAnnotationValue(TemplateId);
817 if (TemplateKWLoc.isValid())
818 Tok.setLocation(TemplateKWLoc);
820 Tok.setLocation(TemplateNameLoc);
822 TemplateArgsPtr.release();
825 // Common fields for the annotation token
826 Tok.setAnnotationEndLoc(RAngleLoc);
828 // In case the tokens were cached, have Preprocessor replace them with the
830 PP.AnnotateCachedTokens(Tok);
834 /// \brief Replaces a template-id annotation token with a type
835 /// annotation token.
837 /// If there was a failure when forming the type from the template-id,
838 /// a type annotation token will still be created, but will have a
839 /// NULL type pointer to signify an error.
840 void Parser::AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS) {
841 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
843 TemplateIdAnnotation *TemplateId
844 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
845 assert((TemplateId->Kind == TNK_Type_template ||
846 TemplateId->Kind == TNK_Dependent_template_name) &&
847 "Only works for type and dependent templates");
849 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
850 TemplateId->getTemplateArgs(),
851 TemplateId->NumArgs);
854 = Actions.ActOnTemplateIdType(TemplateId->Template,
855 TemplateId->TemplateNameLoc,
856 TemplateId->LAngleLoc,
858 TemplateId->RAngleLoc);
859 // Create the new "type" annotation token.
860 Tok.setKind(tok::annot_typename);
861 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
862 if (SS && SS->isNotEmpty()) // it was a C++ qualified type name.
863 Tok.setLocation(SS->getBeginLoc());
864 // End location stays the same
866 // Replace the template-id annotation token, and possible the scope-specifier
867 // that precedes it, with the typename annotation token.
868 PP.AnnotateCachedTokens(Tok);
869 TemplateId->Destroy();
872 /// \brief Determine whether the given token can end a template argument.
873 static bool isEndOfTemplateArgument(Token Tok) {
874 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
875 Tok.is(tok::greatergreater);
878 /// \brief Parse a C++ template template argument.
879 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
880 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
881 !Tok.is(tok::annot_cxxscope))
882 return ParsedTemplateArgument();
884 // C++0x [temp.arg.template]p1:
885 // A template-argument for a template template-parameter shall be the name
886 // of a class template or a template alias, expressed as id-expression.
888 // We parse an id-expression that refers to a class template or template
889 // alias. The grammar we parse is:
891 // nested-name-specifier[opt] template[opt] identifier
893 // followed by a token that terminates a template argument, such as ',',
894 // '>', or (in some cases) '>>'.
895 CXXScopeSpec SS; // nested-name-specifier, if present
896 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
897 /*EnteringContext=*/false);
899 if (SS.isSet() && Tok.is(tok::kw_template)) {
900 // Parse the optional 'template' keyword following the
901 // nested-name-specifier.
902 SourceLocation TemplateLoc = ConsumeToken();
904 if (Tok.is(tok::identifier)) {
905 // We appear to have a dependent template name.
907 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
908 ConsumeToken(); // the identifier
910 // If the next token signals the end of a template argument,
911 // then we have a dependent template name that could be a template
912 // template argument.
914 if (isEndOfTemplateArgument(Tok) &&
915 Actions.ActOnDependentTemplateName(getCurScope(), TemplateLoc,
917 /*ObjectType=*/ ParsedType(),
918 /*EnteringContext=*/false,
920 return ParsedTemplateArgument(SS, Template, Name.StartLocation);
922 } else if (Tok.is(tok::identifier)) {
923 // We may have a (non-dependent) template name.
926 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
927 ConsumeToken(); // the identifier
929 if (isEndOfTemplateArgument(Tok)) {
930 bool MemberOfUnknownSpecialization;
931 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
932 /*hasTemplateKeyword=*/false,
934 /*ObjectType=*/ ParsedType(),
935 /*EnteringContext=*/false,
937 MemberOfUnknownSpecialization);
938 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
939 // We have an id-expression that refers to a class template or
940 // (C++0x) template alias.
941 return ParsedTemplateArgument(SS, Template, Name.StartLocation);
946 // We don't have a template template argument.
947 return ParsedTemplateArgument();
950 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
952 /// template-argument: [C++ 14.2]
953 /// constant-expression
956 ParsedTemplateArgument Parser::ParseTemplateArgument() {
958 // In a template-argument, an ambiguity between a type-id and an
959 // expression is resolved to a type-id, regardless of the form of
960 // the corresponding template-parameter.
962 // Therefore, we initially try to parse a type-id.
963 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
964 SourceLocation Loc = Tok.getLocation();
965 TypeResult TypeArg = ParseTypeName();
966 if (TypeArg.isInvalid())
967 return ParsedTemplateArgument();
969 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
970 TypeArg.get().getAsOpaquePtr(),
974 // Try to parse a template template argument.
976 TentativeParsingAction TPA(*this);
978 ParsedTemplateArgument TemplateTemplateArgument
979 = ParseTemplateTemplateArgument();
980 if (!TemplateTemplateArgument.isInvalid()) {
982 return TemplateTemplateArgument;
985 // Revert this tentative parse to parse a non-type template argument.
989 // Parse a non-type template argument.
990 SourceLocation Loc = Tok.getLocation();
991 ExprResult ExprArg = ParseConstantExpression();
992 if (ExprArg.isInvalid() || !ExprArg.get())
993 return ParsedTemplateArgument();
995 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
996 ExprArg.release(), Loc);
999 /// \brief Determine whether the current tokens can only be parsed as a
1000 /// template argument list (starting with the '<') and never as a '<'
1002 bool Parser::IsTemplateArgumentList(unsigned Skip) {
1003 struct AlwaysRevertAction : TentativeParsingAction {
1004 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1005 ~AlwaysRevertAction() { Revert(); }
1014 if (!Tok.is(tok::less))
1018 // An empty template argument list.
1019 if (Tok.is(tok::greater))
1022 // See whether we have declaration specifiers, which indicate a type.
1023 while (isCXXDeclarationSpecifier() == TPResult::True())
1026 // If we have a '>' or a ',' then this is a template argument list.
1027 return Tok.is(tok::greater) || Tok.is(tok::comma);
1030 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1031 /// (C++ [temp.names]). Returns true if there was an error.
1033 /// template-argument-list: [C++ 14.2]
1034 /// template-argument
1035 /// template-argument-list ',' template-argument
1037 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1039 ParsedTemplateArgument Arg = ParseTemplateArgument();
1040 if (Arg.isInvalid()) {
1041 SkipUntil(tok::comma, tok::greater, true, true);
1045 // Save this template argument.
1046 TemplateArgs.push_back(Arg);
1048 // If the next token is a comma, consume it and keep reading
1050 if (Tok.isNot(tok::comma)) break;
1052 // Consume the comma.
1059 /// \brief Parse a C++ explicit template instantiation
1060 /// (C++ [temp.explicit]).
1062 /// explicit-instantiation:
1063 /// 'extern' [opt] 'template' declaration
1065 /// Note that the 'extern' is a GNU extension and C++0x feature.
1066 Decl *Parser::ParseExplicitInstantiation(SourceLocation ExternLoc,
1067 SourceLocation TemplateLoc,
1068 SourceLocation &DeclEnd) {
1069 // This isn't really required here.
1070 ParsingDeclRAIIObject ParsingTemplateParams(*this);
1072 return ParseSingleDeclarationAfterTemplate(Declarator::FileContext,
1073 ParsedTemplateInfo(ExternLoc,
1075 ParsingTemplateParams,