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/Parse/DeclSpec.h"
17 #include "clang/Parse/Scope.h"
18 #include "clang/Parse/Template.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 // Parse multiple levels of template headers within this template
84 // parameter scope, e.g.,
86 // template<typename T>
87 // template<typename U>
88 // class A<T>::B { ... };
90 // We parse multiple levels non-recursively so that we can build a
91 // single data structure containing all of the template parameter
92 // lists to easily differentiate between the case above and:
94 // template<typename T>
96 // template<typename U> class B;
99 // In the first case, the action for declaring A<T>::B receives
100 // both template parameter lists. In the second case, the action for
101 // defining A<T>::B receives just the inner template parameter list
102 // (and retrieves the outer template parameter list from its
104 bool isSpecialization = true;
105 bool LastParamListWasEmpty = false;
106 TemplateParameterLists ParamLists;
107 TemplateParameterDepthCounter Depth(TemplateParameterDepth);
109 // Consume the 'export', if any.
110 SourceLocation ExportLoc;
111 if (Tok.is(tok::kw_export)) {
112 ExportLoc = ConsumeToken();
115 // Consume the 'template', which should be here.
116 SourceLocation TemplateLoc;
117 if (Tok.is(tok::kw_template)) {
118 TemplateLoc = ConsumeToken();
120 Diag(Tok.getLocation(), diag::err_expected_template);
124 // Parse the '<' template-parameter-list '>'
125 SourceLocation LAngleLoc, RAngleLoc;
126 TemplateParameterList TemplateParams;
127 if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc,
129 // Skip until the semi-colon or a }.
130 SkipUntil(tok::r_brace, true, true);
131 if (Tok.is(tok::semi))
136 ParamLists.push_back(
137 Actions.ActOnTemplateParameterList(Depth, ExportLoc,
138 TemplateLoc, LAngleLoc,
139 TemplateParams.data(),
140 TemplateParams.size(), RAngleLoc));
142 if (!TemplateParams.empty()) {
143 isSpecialization = false;
146 LastParamListWasEmpty = true;
148 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
150 // Parse the actual template declaration.
151 return ParseSingleDeclarationAfterTemplate(Context,
152 ParsedTemplateInfo(&ParamLists,
154 LastParamListWasEmpty),
158 /// \brief Parse a single declaration that declares a template,
159 /// template specialization, or explicit instantiation of a template.
161 /// \param TemplateParams if non-NULL, the template parameter lists
162 /// that preceded this declaration. In this case, the declaration is a
163 /// template declaration, out-of-line definition of a template, or an
164 /// explicit template specialization. When NULL, the declaration is an
165 /// explicit template instantiation.
167 /// \param TemplateLoc when TemplateParams is NULL, the location of
168 /// the 'template' keyword that indicates that we have an explicit
169 /// template instantiation.
171 /// \param DeclEnd will receive the source location of the last token
172 /// within this declaration.
174 /// \param AS the access specifier associated with this
175 /// declaration. Will be AS_none for namespace-scope declarations.
177 /// \returns the new declaration.
179 Parser::ParseSingleDeclarationAfterTemplate(
181 const ParsedTemplateInfo &TemplateInfo,
182 SourceLocation &DeclEnd,
183 AccessSpecifier AS) {
184 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
185 "Template information required");
187 if (Context == Declarator::MemberContext) {
188 // We are parsing a member template.
189 ParseCXXClassMemberDeclaration(AS, TemplateInfo);
190 return DeclPtrTy::make((void*)0);
193 // Parse the declaration specifiers.
194 ParsingDeclSpec DS(*this);
196 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
197 DS.AddAttributes(ParseCXX0XAttributes().AttrList);
199 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
200 getDeclSpecContextFromDeclaratorContext(Context));
202 if (Tok.is(tok::semi)) {
203 DeclEnd = ConsumeToken();
204 DeclPtrTy Decl = Actions.ParsedFreeStandingDeclSpec(CurScope, AS, DS);
209 // Parse the declarator.
210 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
211 ParseDeclarator(DeclaratorInfo);
212 // Error parsing the declarator?
213 if (!DeclaratorInfo.hasName()) {
214 // If so, skip until the semi-colon or a }.
215 SkipUntil(tok::r_brace, true, true);
216 if (Tok.is(tok::semi))
221 // If we have a declaration or declarator list, handle it.
222 if (isDeclarationAfterDeclarator()) {
223 // Parse this declaration.
224 DeclPtrTy ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
227 if (Tok.is(tok::comma)) {
228 Diag(Tok, diag::err_multiple_template_declarators)
229 << (int)TemplateInfo.Kind;
230 SkipUntil(tok::semi, true, false);
234 // Eat the semi colon after the declaration.
235 ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
236 DS.complete(ThisDecl);
240 if (DeclaratorInfo.isFunctionDeclarator() &&
241 isStartOfFunctionDefinition()) {
242 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
243 Diag(Tok, diag::err_function_declared_typedef);
245 if (Tok.is(tok::l_brace)) {
246 // This recovery skips the entire function body. It would be nice
247 // to simply call ParseFunctionDefinition() below, however Sema
248 // assumes the declarator represents a function, not a typedef.
250 SkipUntil(tok::r_brace, true);
252 SkipUntil(tok::semi);
256 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo);
259 if (DeclaratorInfo.isFunctionDeclarator())
260 Diag(Tok, diag::err_expected_fn_body);
262 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
263 SkipUntil(tok::semi);
267 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
268 /// angle brackets. Depth is the depth of this template-parameter-list, which
269 /// is the number of template headers directly enclosing this template header.
270 /// TemplateParams is the current list of template parameters we're building.
271 /// The template parameter we parse will be added to this list. LAngleLoc and
272 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
273 /// that enclose this template parameter list.
275 /// \returns true if an error occurred, false otherwise.
276 bool Parser::ParseTemplateParameters(unsigned Depth,
277 TemplateParameterList &TemplateParams,
278 SourceLocation &LAngleLoc,
279 SourceLocation &RAngleLoc) {
280 // Get the template parameter list.
281 if (!Tok.is(tok::less)) {
282 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
285 LAngleLoc = ConsumeToken();
287 // Try to parse the template parameter list.
288 if (Tok.is(tok::greater))
289 RAngleLoc = ConsumeToken();
290 else if (ParseTemplateParameterList(Depth, TemplateParams)) {
291 if (!Tok.is(tok::greater)) {
292 Diag(Tok.getLocation(), diag::err_expected_greater);
295 RAngleLoc = ConsumeToken();
300 /// ParseTemplateParameterList - Parse a template parameter list. If
301 /// the parsing fails badly (i.e., closing bracket was left out), this
302 /// will try to put the token stream in a reasonable position (closing
303 /// a statement, etc.) and return false.
305 /// template-parameter-list: [C++ temp]
306 /// template-parameter
307 /// template-parameter-list ',' template-parameter
309 Parser::ParseTemplateParameterList(unsigned Depth,
310 TemplateParameterList &TemplateParams) {
312 if (DeclPtrTy TmpParam
313 = ParseTemplateParameter(Depth, TemplateParams.size())) {
314 TemplateParams.push_back(TmpParam);
316 // If we failed to parse a template parameter, skip until we find
317 // a comma or closing brace.
318 SkipUntil(tok::comma, tok::greater, true, true);
321 // Did we find a comma or the end of the template parmeter list?
322 if (Tok.is(tok::comma)) {
324 } else if (Tok.is(tok::greater)) {
325 // Don't consume this... that's done by template parser.
328 // Somebody probably forgot to close the template. Skip ahead and
329 // try to get out of the expression. This error is currently
330 // subsumed by whatever goes on in ParseTemplateParameter.
331 // TODO: This could match >>, and it would be nice to avoid those
332 // silly errors with template <vec<T>>.
333 // Diag(Tok.getLocation(), diag::err_expected_comma_greater);
334 SkipUntil(tok::greater, true, true);
341 /// \brief Determine whether the parser is at the start of a template
343 bool Parser::isStartOfTemplateTypeParameter() {
344 if (Tok.is(tok::kw_class))
347 if (Tok.isNot(tok::kw_typename))
350 // C++ [temp.param]p2:
351 // There is no semantic difference between class and typename in a
352 // template-parameter. typename followed by an unqualified-id
353 // names a template type parameter. typename followed by a
354 // qualified-id denotes the type in a non-type
355 // parameter-declaration.
356 Token Next = NextToken();
358 // If we have an identifier, skip over it.
359 if (Next.getKind() == tok::identifier)
360 Next = GetLookAheadToken(2);
362 switch (Next.getKind()) {
366 case tok::greatergreater:
375 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
377 /// template-parameter: [C++ temp.param]
379 /// parameter-declaration
381 /// type-parameter: (see below)
382 /// 'class' ...[opt][C++0x] identifier[opt]
383 /// 'class' identifier[opt] '=' type-id
384 /// 'typename' ...[opt][C++0x] identifier[opt]
385 /// 'typename' identifier[opt] '=' type-id
386 /// 'template' ...[opt][C++0x] '<' template-parameter-list '>' 'class' identifier[opt]
387 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
389 Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
390 if (isStartOfTemplateTypeParameter())
391 return ParseTypeParameter(Depth, Position);
393 if (Tok.is(tok::kw_template))
394 return ParseTemplateTemplateParameter(Depth, Position);
396 // If it's none of the above, then it must be a parameter declaration.
397 // NOTE: This will pick up errors in the closure of the template parameter
398 // list (e.g., template < ; Check here to implement >> style closures.
399 return ParseNonTypeTemplateParameter(Depth, Position);
402 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
403 /// Other kinds of template parameters are parsed in
404 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
406 /// type-parameter: [C++ temp.param]
407 /// 'class' ...[opt][C++0x] identifier[opt]
408 /// 'class' identifier[opt] '=' type-id
409 /// 'typename' ...[opt][C++0x] identifier[opt]
410 /// 'typename' identifier[opt] '=' type-id
411 Parser::DeclPtrTy Parser::ParseTypeParameter(unsigned Depth, unsigned Position){
412 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
413 "A type-parameter starts with 'class' or 'typename'");
415 // Consume the 'class' or 'typename' keyword.
416 bool TypenameKeyword = Tok.is(tok::kw_typename);
417 SourceLocation KeyLoc = ConsumeToken();
419 // Grab the ellipsis (if given).
420 bool Ellipsis = false;
421 SourceLocation EllipsisLoc;
422 if (Tok.is(tok::ellipsis)) {
424 EllipsisLoc = ConsumeToken();
426 if (!getLang().CPlusPlus0x)
427 Diag(EllipsisLoc, diag::err_variadic_templates);
430 // Grab the template parameter name (if given)
431 SourceLocation NameLoc;
432 IdentifierInfo* ParamName = 0;
433 if (Tok.is(tok::identifier)) {
434 ParamName = Tok.getIdentifierInfo();
435 NameLoc = ConsumeToken();
436 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
437 Tok.is(tok::greater)) {
438 // Unnamed template parameter. Don't have to do anything here, just
439 // don't consume this token.
441 Diag(Tok.getLocation(), diag::err_expected_ident);
445 DeclPtrTy TypeParam = Actions.ActOnTypeParameter(CurScope, TypenameKeyword,
446 Ellipsis, EllipsisLoc,
447 KeyLoc, ParamName, NameLoc,
450 // Grab a default type id (if given).
451 if (Tok.is(tok::equal)) {
452 SourceLocation EqualLoc = ConsumeToken();
453 SourceLocation DefaultLoc = Tok.getLocation();
454 TypeResult DefaultType = ParseTypeName();
455 if (!DefaultType.isInvalid())
456 Actions.ActOnTypeParameterDefault(TypeParam, EqualLoc, DefaultLoc,
463 /// ParseTemplateTemplateParameter - Handle the parsing of template
464 /// template parameters.
466 /// type-parameter: [C++ temp.param]
467 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
468 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
470 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
471 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
473 // Handle the template <...> part.
474 SourceLocation TemplateLoc = ConsumeToken();
475 TemplateParameterList TemplateParams;
476 SourceLocation LAngleLoc, RAngleLoc;
478 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
479 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
485 // Generate a meaningful error if the user forgot to put class before the
486 // identifier, comma, or greater.
487 if (!Tok.is(tok::kw_class)) {
488 Diag(Tok.getLocation(), diag::err_expected_class_before)
489 << PP.getSpelling(Tok);
492 SourceLocation ClassLoc = ConsumeToken();
494 // Get the identifier, if given.
495 SourceLocation NameLoc;
496 IdentifierInfo* ParamName = 0;
497 if (Tok.is(tok::identifier)) {
498 ParamName = Tok.getIdentifierInfo();
499 NameLoc = ConsumeToken();
500 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
501 // Unnamed template parameter. Don't have to do anything here, just
502 // don't consume this token.
504 Diag(Tok.getLocation(), diag::err_expected_ident);
508 TemplateParamsTy *ParamList =
509 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
510 TemplateLoc, LAngleLoc,
512 TemplateParams.size(),
515 Parser::DeclPtrTy Param
516 = Actions.ActOnTemplateTemplateParameter(CurScope, TemplateLoc,
517 ParamList, ParamName,
518 NameLoc, Depth, Position);
520 // Get the a default value, if given.
521 if (Tok.is(tok::equal)) {
522 SourceLocation EqualLoc = ConsumeToken();
523 ParsedTemplateArgument Default = ParseTemplateTemplateArgument();
524 if (Default.isInvalid()) {
525 Diag(Tok.getLocation(),
526 diag::err_default_template_template_parameter_not_template);
527 static const tok::TokenKind EndToks[] = {
528 tok::comma, tok::greater, tok::greatergreater
530 SkipUntil(EndToks, 3, true, true);
533 Actions.ActOnTemplateTemplateParameterDefault(Param, EqualLoc, Default);
539 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
540 /// template parameters (e.g., in "template<int Size> class array;").
542 /// template-parameter:
544 /// parameter-declaration
546 /// NOTE: It would be ideal to simply call out to ParseParameterDeclaration(),
547 /// but that didn't work out to well. Instead, this tries to recrate the basic
548 /// parsing of parameter declarations, but tries to constrain it for template
550 /// FIXME: We need to make a ParseParameterDeclaration that works for
551 /// non-type template parameters and normal function parameters.
553 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
554 SourceLocation StartLoc = Tok.getLocation();
556 // Parse the declaration-specifiers (i.e., the type).
557 // FIXME: The type should probably be restricted in some way... Not all
558 // declarators (parts of declarators?) are accepted for parameters.
560 ParseDeclarationSpecifiers(DS);
562 // Parse this as a typename.
563 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
564 ParseDeclarator(ParamDecl);
565 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified && !DS.getTypeRep()) {
566 // This probably shouldn't happen - and it's more of a Sema thing, but
567 // basically we didn't parse the type name because we couldn't associate
568 // it with an AST node. we should just skip to the comma or greater.
569 // TODO: This is currently a placeholder for some kind of Sema Error.
570 Diag(Tok.getLocation(), diag::err_parse_error);
571 SkipUntil(tok::comma, tok::greater, true, true);
575 // Create the parameter.
576 DeclPtrTy Param = Actions.ActOnNonTypeTemplateParameter(CurScope, ParamDecl,
579 // If there is a default value, parse it.
580 if (Tok.is(tok::equal)) {
581 SourceLocation EqualLoc = ConsumeToken();
583 // C++ [temp.param]p15:
584 // When parsing a default template-argument for a non-type
585 // template-parameter, the first non-nested > is taken as the
586 // end of the template-parameter-list rather than a greater-than
588 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
590 OwningExprResult DefaultArg = ParseAssignmentExpression();
591 if (DefaultArg.isInvalid())
592 SkipUntil(tok::comma, tok::greater, true, true);
594 Actions.ActOnNonTypeTemplateParameterDefault(Param, EqualLoc,
601 /// \brief Parses a template-id that after the template name has
602 /// already been parsed.
604 /// This routine takes care of parsing the enclosed template argument
605 /// list ('<' template-parameter-list [opt] '>') and placing the
606 /// results into a form that can be transferred to semantic analysis.
608 /// \param Template the template declaration produced by isTemplateName
610 /// \param TemplateNameLoc the source location of the template name
612 /// \param SS if non-NULL, the nested-name-specifier preceding the
615 /// \param ConsumeLastToken if true, then we will consume the last
616 /// token that forms the template-id. Otherwise, we will leave the
617 /// last token in the stream (e.g., so that it can be replaced with an
618 /// annotation token).
620 Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
621 SourceLocation TemplateNameLoc,
622 const CXXScopeSpec *SS,
623 bool ConsumeLastToken,
624 SourceLocation &LAngleLoc,
625 TemplateArgList &TemplateArgs,
626 SourceLocation &RAngleLoc) {
627 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
630 LAngleLoc = ConsumeToken();
632 // Parse the optional template-argument-list.
633 bool Invalid = false;
635 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
636 if (Tok.isNot(tok::greater))
637 Invalid = ParseTemplateArgumentList(TemplateArgs);
640 // Try to find the closing '>'.
641 SkipUntil(tok::greater, true, !ConsumeLastToken);
647 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) {
648 Diag(Tok.getLocation(), diag::err_expected_greater);
652 // Determine the location of the '>' or '>>'. Only consume this
653 // token if the caller asked us to.
654 RAngleLoc = Tok.getLocation();
656 if (Tok.is(tok::greatergreater)) {
657 if (!getLang().CPlusPlus0x) {
658 const char *ReplaceStr = "> >";
659 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
662 Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space)
663 << FixItHint::CreateReplacement(
664 SourceRange(Tok.getLocation()), ReplaceStr);
667 Tok.setKind(tok::greater);
668 if (!ConsumeLastToken) {
669 // Since we're not supposed to consume the '>>' token, we need
670 // to insert a second '>' token after the first.
673 } else if (ConsumeLastToken)
679 /// \brief Replace the tokens that form a simple-template-id with an
680 /// annotation token containing the complete template-id.
682 /// The first token in the stream must be the name of a template that
683 /// is followed by a '<'. This routine will parse the complete
684 /// simple-template-id and replace the tokens with a single annotation
685 /// token with one of two different kinds: if the template-id names a
686 /// type (and \p AllowTypeAnnotation is true), the annotation token is
687 /// a type annotation that includes the optional nested-name-specifier
688 /// (\p SS). Otherwise, the annotation token is a template-id
689 /// annotation that does not include the optional
690 /// nested-name-specifier.
692 /// \param Template the declaration of the template named by the first
693 /// token (an identifier), as returned from \c Action::isTemplateName().
695 /// \param TemplateNameKind the kind of template that \p Template
696 /// refers to, as returned from \c Action::isTemplateName().
698 /// \param SS if non-NULL, the nested-name-specifier that precedes
699 /// this template name.
701 /// \param TemplateKWLoc if valid, specifies that this template-id
702 /// annotation was preceded by the 'template' keyword and gives the
703 /// location of that keyword. If invalid (the default), then this
704 /// template-id was not preceded by a 'template' keyword.
706 /// \param AllowTypeAnnotation if true (the default), then a
707 /// simple-template-id that refers to a class template, template
708 /// template parameter, or other template that produces a type will be
709 /// replaced with a type annotation token. Otherwise, the
710 /// simple-template-id is always replaced with a template-id
711 /// annotation token.
713 /// If an unrecoverable parse error occurs and no annotation token can be
714 /// formed, this function returns true.
716 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
717 const CXXScopeSpec *SS,
718 UnqualifiedId &TemplateName,
719 SourceLocation TemplateKWLoc,
720 bool AllowTypeAnnotation) {
721 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
722 assert(Template && Tok.is(tok::less) &&
723 "Parser isn't at the beginning of a template-id");
725 // Consume the template-name.
726 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
728 // Parse the enclosed template argument list.
729 SourceLocation LAngleLoc, RAngleLoc;
730 TemplateArgList TemplateArgs;
731 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
733 SS, false, LAngleLoc,
738 // If we failed to parse the template ID but skipped ahead to a >, we're not
739 // going to be able to form a token annotation. Eat the '>' if present.
740 if (Tok.is(tok::greater))
745 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
746 TemplateArgs.size());
748 // Build the annotation token.
749 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
750 Action::TypeResult Type
751 = Actions.ActOnTemplateIdType(Template, TemplateNameLoc,
752 LAngleLoc, TemplateArgsPtr,
754 if (Type.isInvalid()) {
755 // If we failed to parse the template ID but skipped ahead to a >, we're not
756 // going to be able to form a token annotation. Eat the '>' if present.
757 if (Tok.is(tok::greater))
762 Tok.setKind(tok::annot_typename);
763 Tok.setAnnotationValue(Type.get());
764 if (SS && SS->isNotEmpty())
765 Tok.setLocation(SS->getBeginLoc());
766 else if (TemplateKWLoc.isValid())
767 Tok.setLocation(TemplateKWLoc);
769 Tok.setLocation(TemplateNameLoc);
771 // Build a template-id annotation token that can be processed
773 Tok.setKind(tok::annot_template_id);
774 TemplateIdAnnotation *TemplateId
775 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
776 TemplateId->TemplateNameLoc = TemplateNameLoc;
777 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
778 TemplateId->Name = TemplateName.Identifier;
779 TemplateId->Operator = OO_None;
781 TemplateId->Name = 0;
782 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
784 TemplateId->Template = Template.getAs<void*>();
785 TemplateId->Kind = TNK;
786 TemplateId->LAngleLoc = LAngleLoc;
787 TemplateId->RAngleLoc = RAngleLoc;
788 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
789 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
790 Args[Arg] = TemplateArgs[Arg];
791 Tok.setAnnotationValue(TemplateId);
792 if (TemplateKWLoc.isValid())
793 Tok.setLocation(TemplateKWLoc);
795 Tok.setLocation(TemplateNameLoc);
797 TemplateArgsPtr.release();
800 // Common fields for the annotation token
801 Tok.setAnnotationEndLoc(RAngleLoc);
803 // In case the tokens were cached, have Preprocessor replace them with the
805 PP.AnnotateCachedTokens(Tok);
809 /// \brief Replaces a template-id annotation token with a type
810 /// annotation token.
812 /// If there was a failure when forming the type from the template-id,
813 /// a type annotation token will still be created, but will have a
814 /// NULL type pointer to signify an error.
815 void Parser::AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS) {
816 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
818 TemplateIdAnnotation *TemplateId
819 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
820 assert((TemplateId->Kind == TNK_Type_template ||
821 TemplateId->Kind == TNK_Dependent_template_name) &&
822 "Only works for type and dependent templates");
824 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
825 TemplateId->getTemplateArgs(),
826 TemplateId->NumArgs);
828 Action::TypeResult Type
829 = Actions.ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
830 TemplateId->TemplateNameLoc,
831 TemplateId->LAngleLoc,
833 TemplateId->RAngleLoc);
834 // Create the new "type" annotation token.
835 Tok.setKind(tok::annot_typename);
836 Tok.setAnnotationValue(Type.isInvalid()? 0 : Type.get());
837 if (SS && SS->isNotEmpty()) // it was a C++ qualified type name.
838 Tok.setLocation(SS->getBeginLoc());
839 // End location stays the same
841 // Replace the template-id annotation token, and possible the scope-specifier
842 // that precedes it, with the typename annotation token.
843 PP.AnnotateCachedTokens(Tok);
844 TemplateId->Destroy();
847 /// \brief Determine whether the given token can end a template argument.
848 static bool isEndOfTemplateArgument(Token Tok) {
849 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
850 Tok.is(tok::greatergreater);
853 /// \brief Parse a C++ template template argument.
854 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
855 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
856 !Tok.is(tok::annot_cxxscope))
857 return ParsedTemplateArgument();
859 // C++0x [temp.arg.template]p1:
860 // A template-argument for a template template-parameter shall be the name
861 // of a class template or a template alias, expressed as id-expression.
863 // We parse an id-expression that refers to a class template or template
864 // alias. The grammar we parse is:
866 // nested-name-specifier[opt] template[opt] identifier
868 // followed by a token that terminates a template argument, such as ',',
869 // '>', or (in some cases) '>>'.
870 CXXScopeSpec SS; // nested-name-specifier, if present
871 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0,
872 /*EnteringContext=*/false);
874 if (SS.isSet() && Tok.is(tok::kw_template)) {
875 // Parse the optional 'template' keyword following the
876 // nested-name-specifier.
877 SourceLocation TemplateLoc = ConsumeToken();
879 if (Tok.is(tok::identifier)) {
880 // We appear to have a dependent template name.
882 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
883 ConsumeToken(); // the identifier
885 // If the next token signals the end of a template argument,
886 // then we have a dependent template name that could be a template
887 // template argument.
888 if (isEndOfTemplateArgument(Tok)) {
890 = Actions.ActOnDependentTemplateName(TemplateLoc, SS, Name,
892 /*EnteringContext=*/false);
894 return ParsedTemplateArgument(SS, Template, Name.StartLocation);
897 } else if (Tok.is(tok::identifier)) {
898 // We may have a (non-dependent) template name.
901 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
902 ConsumeToken(); // the identifier
904 if (isEndOfTemplateArgument(Tok)) {
905 bool MemberOfUnknownSpecialization;
906 TemplateNameKind TNK = Actions.isTemplateName(CurScope, SS, Name,
908 /*EnteringContext=*/false,
910 MemberOfUnknownSpecialization);
911 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
912 // We have an id-expression that refers to a class template or
913 // (C++0x) template alias.
914 return ParsedTemplateArgument(SS, Template, Name.StartLocation);
919 // We don't have a template template argument.
920 return ParsedTemplateArgument();
923 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
925 /// template-argument: [C++ 14.2]
926 /// constant-expression
929 ParsedTemplateArgument Parser::ParseTemplateArgument() {
931 // In a template-argument, an ambiguity between a type-id and an
932 // expression is resolved to a type-id, regardless of the form of
933 // the corresponding template-parameter.
935 // Therefore, we initially try to parse a type-id.
936 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
937 SourceLocation Loc = Tok.getLocation();
938 TypeResult TypeArg = ParseTypeName();
939 if (TypeArg.isInvalid())
940 return ParsedTemplateArgument();
942 return ParsedTemplateArgument(ParsedTemplateArgument::Type, TypeArg.get(),
946 // Try to parse a template template argument.
948 TentativeParsingAction TPA(*this);
950 ParsedTemplateArgument TemplateTemplateArgument
951 = ParseTemplateTemplateArgument();
952 if (!TemplateTemplateArgument.isInvalid()) {
954 return TemplateTemplateArgument;
957 // Revert this tentative parse to parse a non-type template argument.
961 // Parse a non-type template argument.
962 SourceLocation Loc = Tok.getLocation();
963 OwningExprResult ExprArg = ParseConstantExpression();
964 if (ExprArg.isInvalid() || !ExprArg.get())
965 return ParsedTemplateArgument();
967 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
968 ExprArg.release(), Loc);
971 /// \brief Determine whether the current tokens can only be parsed as a
972 /// template argument list (starting with the '<') and never as a '<'
974 bool Parser::IsTemplateArgumentList(unsigned Skip) {
975 struct AlwaysRevertAction : TentativeParsingAction {
976 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
977 ~AlwaysRevertAction() { Revert(); }
986 if (!Tok.is(tok::less))
990 // An empty template argument list.
991 if (Tok.is(tok::greater))
994 // See whether we have declaration specifiers, which indicate a type.
995 while (isCXXDeclarationSpecifier() == TPResult::True())
998 // If we have a '>' or a ',' then this is a template argument list.
999 return Tok.is(tok::greater) || Tok.is(tok::comma);
1002 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1003 /// (C++ [temp.names]). Returns true if there was an error.
1005 /// template-argument-list: [C++ 14.2]
1006 /// template-argument
1007 /// template-argument-list ',' template-argument
1009 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1011 ParsedTemplateArgument Arg = ParseTemplateArgument();
1012 if (Arg.isInvalid()) {
1013 SkipUntil(tok::comma, tok::greater, true, true);
1017 // Save this template argument.
1018 TemplateArgs.push_back(Arg);
1020 // If the next token is a comma, consume it and keep reading
1022 if (Tok.isNot(tok::comma)) break;
1024 // Consume the comma.
1031 /// \brief Parse a C++ explicit template instantiation
1032 /// (C++ [temp.explicit]).
1034 /// explicit-instantiation:
1035 /// 'extern' [opt] 'template' declaration
1037 /// Note that the 'extern' is a GNU extension and C++0x feature.
1039 Parser::ParseExplicitInstantiation(SourceLocation ExternLoc,
1040 SourceLocation TemplateLoc,
1041 SourceLocation &DeclEnd) {
1042 return ParseSingleDeclarationAfterTemplate(Declarator::FileContext,
1043 ParsedTemplateInfo(ExternLoc,