When throwing an elidable object, first try to treat the subexpression
[clang.git] / lib / Parse / ParseTemplate.cpp
blobd150260709ea40f5d39eb6d362c9d637677c7d6b
1 //===--- ParseTemplate.cpp - Template Parsing -----------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
24 Decl *
25 Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
26 SourceLocation &DeclEnd,
27 AccessSpecifier AS) {
28 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less))
29 return ParseExplicitInstantiation(SourceLocation(), ConsumeToken(),
30 DeclEnd);
32 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS);
35 /// \brief RAII class that manages the template parameter depth.
36 namespace {
37 class TemplateParameterDepthCounter {
38 unsigned &Depth;
39 unsigned AddedLevels;
41 public:
42 explicit TemplateParameterDepthCounter(unsigned &Depth)
43 : Depth(Depth), AddedLevels(0) { }
45 ~TemplateParameterDepthCounter() {
46 Depth -= AddedLevels;
49 void operator++() {
50 ++Depth;
51 ++AddedLevels;
54 operator unsigned() const { return Depth; }
58 /// \brief Parse a template declaration or an explicit specialization.
59 ///
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.
67 ///
68 /// template-declaration: [C++ temp]
69 /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
70 ///
71 /// explicit-specialization: [ C++ temp.expl.spec]
72 /// 'template' '<' '>' declaration
73 Decl *
74 Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
75 SourceLocation &DeclEnd,
76 AccessSpecifier AS) {
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>
99 // class A {
100 // template<typename U> class B;
101 // };
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
107 // context).
108 bool isSpecialization = true;
109 bool LastParamListWasEmpty = false;
110 TemplateParameterLists ParamLists;
111 TemplateParameterDepthCounter Depth(TemplateParameterDepth);
112 do {
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();
123 } else {
124 Diag(Tok.getLocation(), diag::err_expected_template);
125 return 0;
128 // Parse the '<' template-parameter-list '>'
129 SourceLocation LAngleLoc, RAngleLoc;
130 llvm::SmallVector<Decl*, 4> TemplateParams;
131 if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc,
132 RAngleLoc)) {
133 // Skip until the semi-colon or a }.
134 SkipUntil(tok::r_brace, true, true);
135 if (Tok.is(tok::semi))
136 ConsumeToken();
137 return 0;
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;
148 ++Depth;
149 } else {
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,
157 isSpecialization,
158 LastParamListWasEmpty),
159 ParsingTemplateParams,
160 DeclEnd, AS);
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.
183 Decl *
184 Parser::ParseSingleDeclarationAfterTemplate(
185 unsigned Context,
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);
196 return 0;
199 ParsedAttributesWithRange prefixAttrs;
200 MaybeParseCXX0XAttributes(prefixAttrs);
202 if (Tok.is(tok::kw_using))
203 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
204 prefixAttrs);
206 // Parse the declaration specifiers, stealing the accumulated
207 // diagnostics from the template parameters.
208 ParsingDeclSpec DS(DiagsFromTParams);
210 DS.takeAttributesFrom(prefixAttrs);
212 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
213 getDeclSpecContextFromDeclaratorContext(Context));
215 if (Tok.is(tok::semi)) {
216 DeclEnd = ConsumeToken();
217 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
218 DS.complete(Decl);
219 return Decl;
222 // Parse the declarator.
223 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
224 ParseDeclarator(DeclaratorInfo);
225 // Error parsing the declarator?
226 if (!DeclaratorInfo.hasName()) {
227 // If so, skip until the semi-colon or a }.
228 SkipUntil(tok::r_brace, true, true);
229 if (Tok.is(tok::semi))
230 ConsumeToken();
231 return 0;
234 // If we have a declaration or declarator list, handle it.
235 if (isDeclarationAfterDeclarator()) {
236 // Parse this declaration.
237 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
238 TemplateInfo);
240 if (Tok.is(tok::comma)) {
241 Diag(Tok, diag::err_multiple_template_declarators)
242 << (int)TemplateInfo.Kind;
243 SkipUntil(tok::semi, true, false);
244 return ThisDecl;
247 // Eat the semi colon after the declaration.
248 ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
249 DS.complete(ThisDecl);
250 return ThisDecl;
253 if (DeclaratorInfo.isFunctionDeclarator() &&
254 isStartOfFunctionDefinition(DeclaratorInfo)) {
255 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
256 Diag(Tok, diag::err_function_declared_typedef);
258 if (Tok.is(tok::l_brace)) {
259 // This recovery skips the entire function body. It would be nice
260 // to simply call ParseFunctionDefinition() below, however Sema
261 // assumes the declarator represents a function, not a typedef.
262 ConsumeBrace();
263 SkipUntil(tok::r_brace, true);
264 } else {
265 SkipUntil(tok::semi);
267 return 0;
269 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo);
272 if (DeclaratorInfo.isFunctionDeclarator())
273 Diag(Tok, diag::err_expected_fn_body);
274 else
275 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
276 SkipUntil(tok::semi);
277 return 0;
280 /// ParseTemplateParameters - Parses a template-parameter-list enclosed in
281 /// angle brackets. Depth is the depth of this template-parameter-list, which
282 /// is the number of template headers directly enclosing this template header.
283 /// TemplateParams is the current list of template parameters we're building.
284 /// The template parameter we parse will be added to this list. LAngleLoc and
285 /// RAngleLoc will receive the positions of the '<' and '>', respectively,
286 /// that enclose this template parameter list.
288 /// \returns true if an error occurred, false otherwise.
289 bool Parser::ParseTemplateParameters(unsigned Depth,
290 llvm::SmallVectorImpl<Decl*> &TemplateParams,
291 SourceLocation &LAngleLoc,
292 SourceLocation &RAngleLoc) {
293 // Get the template parameter list.
294 if (!Tok.is(tok::less)) {
295 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
296 return true;
298 LAngleLoc = ConsumeToken();
300 // Try to parse the template parameter list.
301 if (Tok.is(tok::greater))
302 RAngleLoc = ConsumeToken();
303 else if (ParseTemplateParameterList(Depth, TemplateParams)) {
304 if (!Tok.is(tok::greater)) {
305 Diag(Tok.getLocation(), diag::err_expected_greater);
306 return true;
308 RAngleLoc = ConsumeToken();
310 return false;
313 /// ParseTemplateParameterList - Parse a template parameter list. If
314 /// the parsing fails badly (i.e., closing bracket was left out), this
315 /// will try to put the token stream in a reasonable position (closing
316 /// a statement, etc.) and return false.
318 /// template-parameter-list: [C++ temp]
319 /// template-parameter
320 /// template-parameter-list ',' template-parameter
321 bool
322 Parser::ParseTemplateParameterList(unsigned Depth,
323 llvm::SmallVectorImpl<Decl*> &TemplateParams) {
324 while (1) {
325 if (Decl *TmpParam
326 = ParseTemplateParameter(Depth, TemplateParams.size())) {
327 TemplateParams.push_back(TmpParam);
328 } else {
329 // If we failed to parse a template parameter, skip until we find
330 // a comma or closing brace.
331 SkipUntil(tok::comma, tok::greater, true, true);
334 // Did we find a comma or the end of the template parmeter list?
335 if (Tok.is(tok::comma)) {
336 ConsumeToken();
337 } else if (Tok.is(tok::greater)) {
338 // Don't consume this... that's done by template parser.
339 break;
340 } else {
341 // Somebody probably forgot to close the template. Skip ahead and
342 // try to get out of the expression. This error is currently
343 // subsumed by whatever goes on in ParseTemplateParameter.
344 // TODO: This could match >>, and it would be nice to avoid those
345 // silly errors with template <vec<T>>.
346 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
347 SkipUntil(tok::greater, true, true);
348 return false;
351 return true;
354 /// \brief Determine whether the parser is at the start of a template
355 /// type parameter.
356 bool Parser::isStartOfTemplateTypeParameter() {
357 if (Tok.is(tok::kw_class)) {
358 // "class" may be the start of an elaborated-type-specifier or a
359 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
360 switch (NextToken().getKind()) {
361 case tok::equal:
362 case tok::comma:
363 case tok::greater:
364 case tok::greatergreater:
365 case tok::ellipsis:
366 return true;
368 case tok::identifier:
369 // This may be either a type-parameter or an elaborated-type-specifier.
370 // We have to look further.
371 break;
373 default:
374 return false;
377 switch (GetLookAheadToken(2).getKind()) {
378 case tok::equal:
379 case tok::comma:
380 case tok::greater:
381 case tok::greatergreater:
382 return true;
384 default:
385 return false;
389 if (Tok.isNot(tok::kw_typename))
390 return false;
392 // C++ [temp.param]p2:
393 // There is no semantic difference between class and typename in a
394 // template-parameter. typename followed by an unqualified-id
395 // names a template type parameter. typename followed by a
396 // qualified-id denotes the type in a non-type
397 // parameter-declaration.
398 Token Next = NextToken();
400 // If we have an identifier, skip over it.
401 if (Next.getKind() == tok::identifier)
402 Next = GetLookAheadToken(2);
404 switch (Next.getKind()) {
405 case tok::equal:
406 case tok::comma:
407 case tok::greater:
408 case tok::greatergreater:
409 case tok::ellipsis:
410 return true;
412 default:
413 return false;
417 /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
419 /// template-parameter: [C++ temp.param]
420 /// type-parameter
421 /// parameter-declaration
423 /// type-parameter: (see below)
424 /// 'class' ...[opt] identifier[opt]
425 /// 'class' identifier[opt] '=' type-id
426 /// 'typename' ...[opt] identifier[opt]
427 /// 'typename' identifier[opt] '=' type-id
428 /// 'template' '<' template-parameter-list '>'
429 /// 'class' ...[opt] identifier[opt]
430 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
431 /// = id-expression
432 Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
433 if (isStartOfTemplateTypeParameter())
434 return ParseTypeParameter(Depth, Position);
436 if (Tok.is(tok::kw_template))
437 return ParseTemplateTemplateParameter(Depth, Position);
439 // If it's none of the above, then it must be a parameter declaration.
440 // NOTE: This will pick up errors in the closure of the template parameter
441 // list (e.g., template < ; Check here to implement >> style closures.
442 return ParseNonTypeTemplateParameter(Depth, Position);
445 /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
446 /// Other kinds of template parameters are parsed in
447 /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
449 /// type-parameter: [C++ temp.param]
450 /// 'class' ...[opt][C++0x] identifier[opt]
451 /// 'class' identifier[opt] '=' type-id
452 /// 'typename' ...[opt][C++0x] identifier[opt]
453 /// 'typename' identifier[opt] '=' type-id
454 Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
455 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
456 "A type-parameter starts with 'class' or 'typename'");
458 // Consume the 'class' or 'typename' keyword.
459 bool TypenameKeyword = Tok.is(tok::kw_typename);
460 SourceLocation KeyLoc = ConsumeToken();
462 // Grab the ellipsis (if given).
463 bool Ellipsis = false;
464 SourceLocation EllipsisLoc;
465 if (Tok.is(tok::ellipsis)) {
466 Ellipsis = true;
467 EllipsisLoc = ConsumeToken();
469 if (!getLang().CPlusPlus0x)
470 Diag(EllipsisLoc, diag::ext_variadic_templates);
473 // Grab the template parameter name (if given)
474 SourceLocation NameLoc;
475 IdentifierInfo* ParamName = 0;
476 if (Tok.is(tok::identifier)) {
477 ParamName = Tok.getIdentifierInfo();
478 NameLoc = ConsumeToken();
479 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
480 Tok.is(tok::greater)) {
481 // Unnamed template parameter. Don't have to do anything here, just
482 // don't consume this token.
483 } else {
484 Diag(Tok.getLocation(), diag::err_expected_ident);
485 return 0;
488 // Grab a default argument (if available).
489 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
490 // we introduce the type parameter into the local scope.
491 SourceLocation EqualLoc;
492 ParsedType DefaultArg;
493 if (Tok.is(tok::equal)) {
494 EqualLoc = ConsumeToken();
495 DefaultArg = ParseTypeName().get();
498 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
499 EllipsisLoc, KeyLoc, ParamName, NameLoc,
500 Depth, Position, EqualLoc, DefaultArg);
503 /// ParseTemplateTemplateParameter - Handle the parsing of template
504 /// template parameters.
506 /// type-parameter: [C++ temp.param]
507 /// 'template' '<' template-parameter-list '>' 'class'
508 /// ...[opt] identifier[opt]
509 /// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
510 /// = id-expression
511 Decl *
512 Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
513 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
515 // Handle the template <...> part.
516 SourceLocation TemplateLoc = ConsumeToken();
517 llvm::SmallVector<Decl*,8> TemplateParams;
518 SourceLocation LAngleLoc, RAngleLoc;
520 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
521 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
522 RAngleLoc)) {
523 return 0;
527 // Generate a meaningful error if the user forgot to put class before the
528 // identifier, comma, or greater.
529 if (!Tok.is(tok::kw_class)) {
530 Diag(Tok.getLocation(), diag::err_expected_class_before)
531 << PP.getSpelling(Tok);
532 return 0;
534 ConsumeToken();
536 // Parse the ellipsis, if given.
537 SourceLocation EllipsisLoc;
538 if (Tok.is(tok::ellipsis)) {
539 EllipsisLoc = ConsumeToken();
541 if (!getLang().CPlusPlus0x)
542 Diag(EllipsisLoc, diag::ext_variadic_templates);
545 // Get the identifier, if given.
546 SourceLocation NameLoc;
547 IdentifierInfo* ParamName = 0;
548 if (Tok.is(tok::identifier)) {
549 ParamName = Tok.getIdentifierInfo();
550 NameLoc = ConsumeToken();
551 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
552 // Unnamed template parameter. Don't have to do anything here, just
553 // don't consume this token.
554 } else {
555 Diag(Tok.getLocation(), diag::err_expected_ident);
556 return 0;
559 TemplateParamsTy *ParamList =
560 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
561 TemplateLoc, LAngleLoc,
562 TemplateParams.data(),
563 TemplateParams.size(),
564 RAngleLoc);
566 // Grab a default argument (if available).
567 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
568 // we introduce the template parameter into the local scope.
569 SourceLocation EqualLoc;
570 ParsedTemplateArgument DefaultArg;
571 if (Tok.is(tok::equal)) {
572 EqualLoc = ConsumeToken();
573 DefaultArg = ParseTemplateTemplateArgument();
574 if (DefaultArg.isInvalid()) {
575 Diag(Tok.getLocation(),
576 diag::err_default_template_template_parameter_not_template);
577 static const tok::TokenKind EndToks[] = {
578 tok::comma, tok::greater, tok::greatergreater
580 SkipUntil(EndToks, 3, true, true);
584 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
585 ParamList, EllipsisLoc,
586 ParamName, NameLoc, Depth,
587 Position, EqualLoc, DefaultArg);
590 /// ParseNonTypeTemplateParameter - Handle the parsing of non-type
591 /// template parameters (e.g., in "template<int Size> class array;").
593 /// template-parameter:
594 /// ...
595 /// parameter-declaration
596 Decl *
597 Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
598 // Parse the declaration-specifiers (i.e., the type).
599 // FIXME: The type should probably be restricted in some way... Not all
600 // declarators (parts of declarators?) are accepted for parameters.
601 DeclSpec DS;
602 ParseDeclarationSpecifiers(DS);
604 // Parse this as a typename.
605 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
606 ParseDeclarator(ParamDecl);
607 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
608 // This probably shouldn't happen - and it's more of a Sema thing, but
609 // basically we didn't parse the type name because we couldn't associate
610 // it with an AST node. we should just skip to the comma or greater.
611 // TODO: This is currently a placeholder for some kind of Sema Error.
612 Diag(Tok.getLocation(), diag::err_parse_error);
613 SkipUntil(tok::comma, tok::greater, true, true);
614 return 0;
617 // If there is a default value, parse it.
618 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
619 // we introduce the template parameter into the local scope.
620 SourceLocation EqualLoc;
621 ExprResult DefaultArg;
622 if (Tok.is(tok::equal)) {
623 EqualLoc = ConsumeToken();
625 // C++ [temp.param]p15:
626 // When parsing a default template-argument for a non-type
627 // template-parameter, the first non-nested > is taken as the
628 // end of the template-parameter-list rather than a greater-than
629 // operator.
630 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
632 DefaultArg = ParseAssignmentExpression();
633 if (DefaultArg.isInvalid())
634 SkipUntil(tok::comma, tok::greater, true, true);
637 // Create the parameter.
638 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
639 Depth, Position, EqualLoc,
640 DefaultArg.take());
643 /// \brief Parses a template-id that after the template name has
644 /// already been parsed.
646 /// This routine takes care of parsing the enclosed template argument
647 /// list ('<' template-parameter-list [opt] '>') and placing the
648 /// results into a form that can be transferred to semantic analysis.
650 /// \param Template the template declaration produced by isTemplateName
652 /// \param TemplateNameLoc the source location of the template name
654 /// \param SS if non-NULL, the nested-name-specifier preceding the
655 /// template name.
657 /// \param ConsumeLastToken if true, then we will consume the last
658 /// token that forms the template-id. Otherwise, we will leave the
659 /// last token in the stream (e.g., so that it can be replaced with an
660 /// annotation token).
661 bool
662 Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
663 SourceLocation TemplateNameLoc,
664 const CXXScopeSpec *SS,
665 bool ConsumeLastToken,
666 SourceLocation &LAngleLoc,
667 TemplateArgList &TemplateArgs,
668 SourceLocation &RAngleLoc) {
669 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
671 // Consume the '<'.
672 LAngleLoc = ConsumeToken();
674 // Parse the optional template-argument-list.
675 bool Invalid = false;
677 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
678 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
679 Invalid = ParseTemplateArgumentList(TemplateArgs);
681 if (Invalid) {
682 // Try to find the closing '>'.
683 SkipUntil(tok::greater, true, !ConsumeLastToken);
685 return true;
689 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) {
690 Diag(Tok.getLocation(), diag::err_expected_greater);
691 return true;
694 // Determine the location of the '>' or '>>'. Only consume this
695 // token if the caller asked us to.
696 RAngleLoc = Tok.getLocation();
698 if (Tok.is(tok::greatergreater)) {
699 if (!getLang().CPlusPlus0x) {
700 const char *ReplaceStr = "> >";
701 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
702 ReplaceStr = "> > ";
704 Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space)
705 << FixItHint::CreateReplacement(
706 SourceRange(Tok.getLocation()), ReplaceStr);
709 Tok.setKind(tok::greater);
710 if (!ConsumeLastToken) {
711 // Since we're not supposed to consume the '>>' token, we need
712 // to insert a second '>' token after the first.
713 PP.EnterToken(Tok);
715 } else if (ConsumeLastToken)
716 ConsumeToken();
718 return false;
721 /// \brief Replace the tokens that form a simple-template-id with an
722 /// annotation token containing the complete template-id.
724 /// The first token in the stream must be the name of a template that
725 /// is followed by a '<'. This routine will parse the complete
726 /// simple-template-id and replace the tokens with a single annotation
727 /// token with one of two different kinds: if the template-id names a
728 /// type (and \p AllowTypeAnnotation is true), the annotation token is
729 /// a type annotation that includes the optional nested-name-specifier
730 /// (\p SS). Otherwise, the annotation token is a template-id
731 /// annotation that does not include the optional
732 /// nested-name-specifier.
734 /// \param Template the declaration of the template named by the first
735 /// token (an identifier), as returned from \c Action::isTemplateName().
737 /// \param TemplateNameKind the kind of template that \p Template
738 /// refers to, as returned from \c Action::isTemplateName().
740 /// \param SS if non-NULL, the nested-name-specifier that precedes
741 /// this template name.
743 /// \param TemplateKWLoc if valid, specifies that this template-id
744 /// annotation was preceded by the 'template' keyword and gives the
745 /// location of that keyword. If invalid (the default), then this
746 /// template-id was not preceded by a 'template' keyword.
748 /// \param AllowTypeAnnotation if true (the default), then a
749 /// simple-template-id that refers to a class template, template
750 /// template parameter, or other template that produces a type will be
751 /// replaced with a type annotation token. Otherwise, the
752 /// simple-template-id is always replaced with a template-id
753 /// annotation token.
755 /// If an unrecoverable parse error occurs and no annotation token can be
756 /// formed, this function returns true.
758 bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
759 const CXXScopeSpec *SS,
760 UnqualifiedId &TemplateName,
761 SourceLocation TemplateKWLoc,
762 bool AllowTypeAnnotation) {
763 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
764 assert(Template && Tok.is(tok::less) &&
765 "Parser isn't at the beginning of a template-id");
767 // Consume the template-name.
768 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
770 // Parse the enclosed template argument list.
771 SourceLocation LAngleLoc, RAngleLoc;
772 TemplateArgList TemplateArgs;
773 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
774 TemplateNameLoc,
775 SS, false, LAngleLoc,
776 TemplateArgs,
777 RAngleLoc);
779 if (Invalid) {
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))
783 ConsumeToken();
784 return true;
787 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
788 TemplateArgs.size());
790 // Build the annotation token.
791 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
792 TypeResult Type
793 = Actions.ActOnTemplateIdType(Template, TemplateNameLoc,
794 LAngleLoc, TemplateArgsPtr,
795 RAngleLoc);
796 if (Type.isInvalid()) {
797 // If we failed to parse the template ID but skipped ahead to a >, we're not
798 // going to be able to form a token annotation. Eat the '>' if present.
799 if (Tok.is(tok::greater))
800 ConsumeToken();
801 return true;
804 Tok.setKind(tok::annot_typename);
805 setTypeAnnotation(Tok, Type.get());
806 if (SS && SS->isNotEmpty())
807 Tok.setLocation(SS->getBeginLoc());
808 else if (TemplateKWLoc.isValid())
809 Tok.setLocation(TemplateKWLoc);
810 else
811 Tok.setLocation(TemplateNameLoc);
812 } else {
813 // Build a template-id annotation token that can be processed
814 // later.
815 Tok.setKind(tok::annot_template_id);
816 TemplateIdAnnotation *TemplateId
817 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
818 TemplateId->TemplateNameLoc = TemplateNameLoc;
819 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
820 TemplateId->Name = TemplateName.Identifier;
821 TemplateId->Operator = OO_None;
822 } else {
823 TemplateId->Name = 0;
824 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
826 TemplateId->Template = Template;
827 TemplateId->Kind = TNK;
828 TemplateId->LAngleLoc = LAngleLoc;
829 TemplateId->RAngleLoc = RAngleLoc;
830 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
831 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
832 Args[Arg] = TemplateArgs[Arg];
833 Tok.setAnnotationValue(TemplateId);
834 if (TemplateKWLoc.isValid())
835 Tok.setLocation(TemplateKWLoc);
836 else
837 Tok.setLocation(TemplateNameLoc);
839 TemplateArgsPtr.release();
842 // Common fields for the annotation token
843 Tok.setAnnotationEndLoc(RAngleLoc);
845 // In case the tokens were cached, have Preprocessor replace them with the
846 // annotation token.
847 PP.AnnotateCachedTokens(Tok);
848 return false;
851 /// \brief Replaces a template-id annotation token with a type
852 /// annotation token.
854 /// If there was a failure when forming the type from the template-id,
855 /// a type annotation token will still be created, but will have a
856 /// NULL type pointer to signify an error.
857 void Parser::AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS) {
858 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
860 TemplateIdAnnotation *TemplateId
861 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
862 assert((TemplateId->Kind == TNK_Type_template ||
863 TemplateId->Kind == TNK_Dependent_template_name) &&
864 "Only works for type and dependent templates");
866 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
867 TemplateId->getTemplateArgs(),
868 TemplateId->NumArgs);
870 TypeResult Type
871 = Actions.ActOnTemplateIdType(TemplateId->Template,
872 TemplateId->TemplateNameLoc,
873 TemplateId->LAngleLoc,
874 TemplateArgsPtr,
875 TemplateId->RAngleLoc);
876 // Create the new "type" annotation token.
877 Tok.setKind(tok::annot_typename);
878 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
879 if (SS && SS->isNotEmpty()) // it was a C++ qualified type name.
880 Tok.setLocation(SS->getBeginLoc());
881 // End location stays the same
883 // Replace the template-id annotation token, and possible the scope-specifier
884 // that precedes it, with the typename annotation token.
885 PP.AnnotateCachedTokens(Tok);
886 TemplateId->Destroy();
889 /// \brief Determine whether the given token can end a template argument.
890 static bool isEndOfTemplateArgument(Token Tok) {
891 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
892 Tok.is(tok::greatergreater);
895 /// \brief Parse a C++ template template argument.
896 ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
897 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
898 !Tok.is(tok::annot_cxxscope))
899 return ParsedTemplateArgument();
901 // C++0x [temp.arg.template]p1:
902 // A template-argument for a template template-parameter shall be the name
903 // of a class template or a template alias, expressed as id-expression.
905 // We parse an id-expression that refers to a class template or template
906 // alias. The grammar we parse is:
908 // nested-name-specifier[opt] template[opt] identifier ...[opt]
910 // followed by a token that terminates a template argument, such as ',',
911 // '>', or (in some cases) '>>'.
912 CXXScopeSpec SS; // nested-name-specifier, if present
913 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
914 /*EnteringContext=*/false);
916 ParsedTemplateArgument Result;
917 SourceLocation EllipsisLoc;
918 if (SS.isSet() && Tok.is(tok::kw_template)) {
919 // Parse the optional 'template' keyword following the
920 // nested-name-specifier.
921 SourceLocation TemplateLoc = ConsumeToken();
923 if (Tok.is(tok::identifier)) {
924 // We appear to have a dependent template name.
925 UnqualifiedId Name;
926 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
927 ConsumeToken(); // the identifier
929 // Parse the ellipsis.
930 if (Tok.is(tok::ellipsis))
931 EllipsisLoc = ConsumeToken();
933 // If the next token signals the end of a template argument,
934 // then we have a dependent template name that could be a template
935 // template argument.
936 TemplateTy Template;
937 if (isEndOfTemplateArgument(Tok) &&
938 Actions.ActOnDependentTemplateName(getCurScope(), TemplateLoc,
939 SS, Name,
940 /*ObjectType=*/ ParsedType(),
941 /*EnteringContext=*/false,
942 Template))
943 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
945 } else if (Tok.is(tok::identifier)) {
946 // We may have a (non-dependent) template name.
947 TemplateTy Template;
948 UnqualifiedId Name;
949 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
950 ConsumeToken(); // the identifier
952 // Parse the ellipsis.
953 if (Tok.is(tok::ellipsis))
954 EllipsisLoc = ConsumeToken();
956 if (isEndOfTemplateArgument(Tok)) {
957 bool MemberOfUnknownSpecialization;
958 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
959 /*hasTemplateKeyword=*/false,
960 Name,
961 /*ObjectType=*/ ParsedType(),
962 /*EnteringContext=*/false,
963 Template,
964 MemberOfUnknownSpecialization);
965 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
966 // We have an id-expression that refers to a class template or
967 // (C++0x) template alias.
968 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
973 // If this is a pack expansion, build it as such.
974 if (EllipsisLoc.isValid() && !Result.isInvalid())
975 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
977 return Result;
980 /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
982 /// template-argument: [C++ 14.2]
983 /// constant-expression
984 /// type-id
985 /// id-expression
986 ParsedTemplateArgument Parser::ParseTemplateArgument() {
987 // C++ [temp.arg]p2:
988 // In a template-argument, an ambiguity between a type-id and an
989 // expression is resolved to a type-id, regardless of the form of
990 // the corresponding template-parameter.
992 // Therefore, we initially try to parse a type-id.
993 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
994 SourceLocation Loc = Tok.getLocation();
995 TypeResult TypeArg = ParseTypeName();
996 if (TypeArg.isInvalid())
997 return ParsedTemplateArgument();
999 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1000 TypeArg.get().getAsOpaquePtr(),
1001 Loc);
1004 // Try to parse a template template argument.
1006 TentativeParsingAction TPA(*this);
1008 ParsedTemplateArgument TemplateTemplateArgument
1009 = ParseTemplateTemplateArgument();
1010 if (!TemplateTemplateArgument.isInvalid()) {
1011 TPA.Commit();
1012 return TemplateTemplateArgument;
1015 // Revert this tentative parse to parse a non-type template argument.
1016 TPA.Revert();
1019 // Parse a non-type template argument.
1020 SourceLocation Loc = Tok.getLocation();
1021 ExprResult ExprArg = ParseConstantExpression();
1022 if (ExprArg.isInvalid() || !ExprArg.get())
1023 return ParsedTemplateArgument();
1025 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1026 ExprArg.release(), Loc);
1029 /// \brief Determine whether the current tokens can only be parsed as a
1030 /// template argument list (starting with the '<') and never as a '<'
1031 /// expression.
1032 bool Parser::IsTemplateArgumentList(unsigned Skip) {
1033 struct AlwaysRevertAction : TentativeParsingAction {
1034 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1035 ~AlwaysRevertAction() { Revert(); }
1036 } Tentative(*this);
1038 while (Skip) {
1039 ConsumeToken();
1040 --Skip;
1043 // '<'
1044 if (!Tok.is(tok::less))
1045 return false;
1046 ConsumeToken();
1048 // An empty template argument list.
1049 if (Tok.is(tok::greater))
1050 return true;
1052 // See whether we have declaration specifiers, which indicate a type.
1053 while (isCXXDeclarationSpecifier() == TPResult::True())
1054 ConsumeToken();
1056 // If we have a '>' or a ',' then this is a template argument list.
1057 return Tok.is(tok::greater) || Tok.is(tok::comma);
1060 /// ParseTemplateArgumentList - Parse a C++ template-argument-list
1061 /// (C++ [temp.names]). Returns true if there was an error.
1063 /// template-argument-list: [C++ 14.2]
1064 /// template-argument
1065 /// template-argument-list ',' template-argument
1066 bool
1067 Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1068 while (true) {
1069 ParsedTemplateArgument Arg = ParseTemplateArgument();
1070 if (Tok.is(tok::ellipsis)) {
1071 SourceLocation EllipsisLoc = ConsumeToken();
1072 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1075 if (Arg.isInvalid()) {
1076 SkipUntil(tok::comma, tok::greater, true, true);
1077 return true;
1080 // Save this template argument.
1081 TemplateArgs.push_back(Arg);
1083 // If the next token is a comma, consume it and keep reading
1084 // arguments.
1085 if (Tok.isNot(tok::comma)) break;
1087 // Consume the comma.
1088 ConsumeToken();
1091 return false;
1094 /// \brief Parse a C++ explicit template instantiation
1095 /// (C++ [temp.explicit]).
1097 /// explicit-instantiation:
1098 /// 'extern' [opt] 'template' declaration
1100 /// Note that the 'extern' is a GNU extension and C++0x feature.
1101 Decl *Parser::ParseExplicitInstantiation(SourceLocation ExternLoc,
1102 SourceLocation TemplateLoc,
1103 SourceLocation &DeclEnd) {
1104 // This isn't really required here.
1105 ParsingDeclRAIIObject ParsingTemplateParams(*this);
1107 return ParseSingleDeclarationAfterTemplate(Declarator::FileContext,
1108 ParsedTemplateInfo(ExternLoc,
1109 TemplateLoc),
1110 ParsingTemplateParams,
1111 DeclEnd, AS_none);
1114 SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1115 if (TemplateParams)
1116 return getTemplateParamsRange(TemplateParams->data(),
1117 TemplateParams->size());
1119 SourceRange R(TemplateLoc);
1120 if (ExternLoc.isValid())
1121 R.setBegin(ExternLoc);
1122 return R;