blob: 973eeb29d7b3eeb64c3d9476203f8d94b60eb573 [file] [log] [blame]
Faisal Vali65efd102013-06-08 19:39:00 +00001//===--- 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.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
15#include "RAIIObjectsForParser.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/Parse/ParseDiagnostic.h"
19#include "clang/Sema/DeclSpec.h"
20#include "clang/Sema/ParsedTemplate.h"
21#include "clang/Sema/Scope.h"
22using namespace clang;
23
24/// \brief Parse a template declaration, explicit instantiation, or
25/// explicit specialization.
26Decl *
27Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
28 SourceLocation &DeclEnd,
29 AccessSpecifier AS,
30 AttributeList *AccessAttrs) {
31 ObjCDeclContextSwitch ObjCDC(*this);
32
33 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
34 return ParseExplicitInstantiation(Context,
35 SourceLocation(), ConsumeToken(),
36 DeclEnd, AS);
37 }
38 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
39 AccessAttrs);
40}
41
42
43
44/// \brief Parse a template declaration or an explicit specialization.
45///
46/// Template declarations include one or more template parameter lists
47/// and either the function or class template declaration. Explicit
48/// specializations contain one or more 'template < >' prefixes
49/// followed by a (possibly templated) declaration. Since the
50/// syntactic form of both features is nearly identical, we parse all
51/// of the template headers together and let semantic analysis sort
52/// the declarations from the explicit specializations.
53///
54/// template-declaration: [C++ temp]
55/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
56///
57/// explicit-specialization: [ C++ temp.expl.spec]
58/// 'template' '<' '>' declaration
59Decl *
60Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
61 SourceLocation &DeclEnd,
62 AccessSpecifier AS,
63 AttributeList *AccessAttrs) {
64 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
65 "Token does not start a template declaration.");
66
67 // Enter template-parameter scope.
68 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
69
70 // Tell the action that names should be checked in the context of
71 // the declaration to come.
72 ParsingDeclRAIIObject
73 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
74
75 // Parse multiple levels of template headers within this template
76 // parameter scope, e.g.,
77 //
78 // template<typename T>
79 // template<typename U>
80 // class A<T>::B { ... };
81 //
82 // We parse multiple levels non-recursively so that we can build a
83 // single data structure containing all of the template parameter
84 // lists to easily differentiate between the case above and:
85 //
86 // template<typename T>
87 // class A {
88 // template<typename U> class B;
89 // };
90 //
91 // In the first case, the action for declaring A<T>::B receives
92 // both template parameter lists. In the second case, the action for
93 // defining A<T>::B receives just the inner template parameter list
94 // (and retrieves the outer template parameter list from its
95 // context).
96 bool isSpecialization = true;
97 bool LastParamListWasEmpty = false;
98 TemplateParameterLists ParamLists;
99 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
100
101 do {
102 // Consume the 'export', if any.
103 SourceLocation ExportLoc;
104 if (Tok.is(tok::kw_export)) {
105 ExportLoc = ConsumeToken();
106 }
107
108 // Consume the 'template', which should be here.
109 SourceLocation TemplateLoc;
110 if (Tok.is(tok::kw_template)) {
111 TemplateLoc = ConsumeToken();
112 } else {
113 Diag(Tok.getLocation(), diag::err_expected_template);
114 return 0;
115 }
116
117 // Parse the '<' template-parameter-list '>'
118 SourceLocation LAngleLoc, RAngleLoc;
119 SmallVector<Decl*, 4> TemplateParams;
120 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
121 TemplateParams, LAngleLoc, RAngleLoc)) {
122 // Skip until the semi-colon or a }.
123 SkipUntil(tok::r_brace, true, true);
124 if (Tok.is(tok::semi))
125 ConsumeToken();
126 return 0;
127 }
128
129 ParamLists.push_back(
130 Actions.ActOnTemplateParameterList(CurTemplateDepthTracker.getDepth(),
131 ExportLoc,
132 TemplateLoc, LAngleLoc,
133 TemplateParams.data(),
134 TemplateParams.size(), RAngleLoc));
135
136 if (!TemplateParams.empty()) {
137 isSpecialization = false;
138 ++CurTemplateDepthTracker;
139 } else {
140 LastParamListWasEmpty = true;
141 }
142 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
143
144 // Parse the actual template declaration.
145 return ParseSingleDeclarationAfterTemplate(Context,
146 ParsedTemplateInfo(&ParamLists,
147 isSpecialization,
148 LastParamListWasEmpty),
149 ParsingTemplateParams,
150 DeclEnd, AS, AccessAttrs);
151}
152
153/// \brief Parse a single declaration that declares a template,
154/// template specialization, or explicit instantiation of a template.
155///
156/// \param DeclEnd will receive the source location of the last token
157/// within this declaration.
158///
159/// \param AS the access specifier associated with this
160/// declaration. Will be AS_none for namespace-scope declarations.
161///
162/// \returns the new declaration.
163Decl *
164Parser::ParseSingleDeclarationAfterTemplate(
165 unsigned Context,
166 const ParsedTemplateInfo &TemplateInfo,
167 ParsingDeclRAIIObject &DiagsFromTParams,
168 SourceLocation &DeclEnd,
169 AccessSpecifier AS,
170 AttributeList *AccessAttrs) {
171 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
172 "Template information required");
173
174 if (Context == Declarator::MemberContext) {
175 // We are parsing a member template.
176 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
177 &DiagsFromTParams);
178 return 0;
179 }
180
181 ParsedAttributesWithRange prefixAttrs(AttrFactory);
182 MaybeParseCXX11Attributes(prefixAttrs);
183
184 if (Tok.is(tok::kw_using))
185 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
186 prefixAttrs);
187
188 // Parse the declaration specifiers, stealing any diagnostics from
189 // the template parameters.
190 ParsingDeclSpec DS(*this, &DiagsFromTParams);
191
192 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
193 getDeclSpecContextFromDeclaratorContext(Context));
194
195 if (Tok.is(tok::semi)) {
196 ProhibitAttributes(prefixAttrs);
197 DeclEnd = ConsumeToken();
198 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
199 getCurScope(), AS, DS,
200 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
201 : MultiTemplateParamsArg(),
202 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation);
203 DS.complete(Decl);
204 return Decl;
205 }
206
207 // Move the attributes from the prefix into the DS.
208 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
209 ProhibitAttributes(prefixAttrs);
210 else
211 DS.takeAttributesFrom(prefixAttrs);
212
213 // Parse the declarator.
214 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
215 ParseDeclarator(DeclaratorInfo);
216 // Error parsing the declarator?
217 if (!DeclaratorInfo.hasName()) {
218 // If so, skip until the semi-colon or a }.
219 SkipUntil(tok::r_brace, true, true);
220 if (Tok.is(tok::semi))
221 ConsumeToken();
222 return 0;
223 }
224
225 LateParsedAttrList LateParsedAttrs(true);
226 if (DeclaratorInfo.isFunctionDeclarator())
227 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
228
229 if (DeclaratorInfo.isFunctionDeclarator() &&
230 isStartOfFunctionDefinition(DeclaratorInfo)) {
231 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
232 // Recover by ignoring the 'typedef'. This was probably supposed to be
233 // the 'typename' keyword, which we should have already suggested adding
234 // if it's appropriate.
235 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
236 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
237 DS.ClearStorageClassSpecs();
238 }
Larisse Voufo7c64ef02013-06-21 00:08:46 +0000239
240 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
241 if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
242 // If the declarator-id is not a template-id, issue a diagnostic and
243 // recover by ignoring the 'template' keyword.
244 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
Larisse Voufo49854292013-06-22 13:56:11 +0000245 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
246 &LateParsedAttrs);
Larisse Voufo7c64ef02013-06-21 00:08:46 +0000247 } else {
248 SourceLocation LAngleLoc
249 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
250 Diag(DeclaratorInfo.getIdentifierLoc(),
251 diag::err_explicit_instantiation_with_definition)
252 << SourceRange(TemplateInfo.TemplateLoc)
253 << FixItHint::CreateInsertion(LAngleLoc, "<>");
254
255 // Recover as if it were an explicit specialization.
Larisse Voufo49854292013-06-22 13:56:11 +0000256 TemplateParameterLists FakedParamLists;
257 FakedParamLists.push_back(
258 Actions.ActOnTemplateParameterList(0, SourceLocation(),
259 TemplateInfo.TemplateLoc,
260 LAngleLoc, 0, 0, LAngleLoc));
Larisse Voufo7c64ef02013-06-21 00:08:46 +0000261
262 return ParseFunctionDefinition(DeclaratorInfo,
Larisse Voufo49854292013-06-22 13:56:11 +0000263 ParsedTemplateInfo(&FakedParamLists,
Larisse Voufo7c64ef02013-06-21 00:08:46 +0000264 /*isSpecialization=*/true,
265 /*LastParamListWasEmpty=*/true),
266 &LateParsedAttrs);
267 }
268 }
Faisal Vali65efd102013-06-08 19:39:00 +0000269 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
Larisse Voufo49854292013-06-22 13:56:11 +0000270 &LateParsedAttrs);
Faisal Vali65efd102013-06-08 19:39:00 +0000271 }
272
273 // Parse this declaration.
274 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
275 TemplateInfo);
276
277 if (Tok.is(tok::comma)) {
278 Diag(Tok, diag::err_multiple_template_declarators)
279 << (int)TemplateInfo.Kind;
280 SkipUntil(tok::semi, true, false);
281 return ThisDecl;
282 }
283
284 // Eat the semi colon after the declaration.
285 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
286 if (LateParsedAttrs.size() > 0)
287 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
288 DeclaratorInfo.complete(ThisDecl);
289 return ThisDecl;
290}
291
292/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
293/// angle brackets. Depth is the depth of this template-parameter-list, which
294/// is the number of template headers directly enclosing this template header.
295/// TemplateParams is the current list of template parameters we're building.
296/// The template parameter we parse will be added to this list. LAngleLoc and
297/// RAngleLoc will receive the positions of the '<' and '>', respectively,
298/// that enclose this template parameter list.
299///
300/// \returns true if an error occurred, false otherwise.
301bool Parser::ParseTemplateParameters(unsigned Depth,
302 SmallVectorImpl<Decl*> &TemplateParams,
303 SourceLocation &LAngleLoc,
304 SourceLocation &RAngleLoc) {
305 // Get the template parameter list.
306 if (!Tok.is(tok::less)) {
307 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
308 return true;
309 }
310 LAngleLoc = ConsumeToken();
311
312 // Try to parse the template parameter list.
313 bool Failed = false;
314 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
315 Failed = ParseTemplateParameterList(Depth, TemplateParams);
316
317 if (Tok.is(tok::greatergreater)) {
318 // No diagnostic required here: a template-parameter-list can only be
319 // followed by a declaration or, for a template template parameter, the
320 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
321 // This matters for elegant diagnosis of:
322 // template<template<typename>> struct S;
323 Tok.setKind(tok::greater);
324 RAngleLoc = Tok.getLocation();
325 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
326 } else if (Tok.is(tok::greater))
327 RAngleLoc = ConsumeToken();
328 else if (Failed) {
329 Diag(Tok.getLocation(), diag::err_expected_greater);
330 return true;
331 }
332 return false;
333}
334
335/// ParseTemplateParameterList - Parse a template parameter list. If
336/// the parsing fails badly (i.e., closing bracket was left out), this
337/// will try to put the token stream in a reasonable position (closing
338/// a statement, etc.) and return false.
339///
340/// template-parameter-list: [C++ temp]
341/// template-parameter
342/// template-parameter-list ',' template-parameter
343bool
344Parser::ParseTemplateParameterList(unsigned Depth,
345 SmallVectorImpl<Decl*> &TemplateParams) {
346 while (1) {
347 if (Decl *TmpParam
348 = ParseTemplateParameter(Depth, TemplateParams.size())) {
349 TemplateParams.push_back(TmpParam);
350 } else {
351 // If we failed to parse a template parameter, skip until we find
352 // a comma or closing brace.
353 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
354 }
355
356 // Did we find a comma or the end of the template parameter list?
357 if (Tok.is(tok::comma)) {
358 ConsumeToken();
359 } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
360 // Don't consume this... that's done by template parser.
361 break;
362 } else {
363 // Somebody probably forgot to close the template. Skip ahead and
364 // try to get out of the expression. This error is currently
365 // subsumed by whatever goes on in ParseTemplateParameter.
366 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
367 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
368 return false;
369 }
370 }
371 return true;
372}
373
374/// \brief Determine whether the parser is at the start of a template
375/// type parameter.
376bool Parser::isStartOfTemplateTypeParameter() {
377 if (Tok.is(tok::kw_class)) {
378 // "class" may be the start of an elaborated-type-specifier or a
379 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
380 switch (NextToken().getKind()) {
381 case tok::equal:
382 case tok::comma:
383 case tok::greater:
384 case tok::greatergreater:
385 case tok::ellipsis:
386 return true;
387
388 case tok::identifier:
389 // This may be either a type-parameter or an elaborated-type-specifier.
390 // We have to look further.
391 break;
392
393 default:
394 return false;
395 }
396
397 switch (GetLookAheadToken(2).getKind()) {
398 case tok::equal:
399 case tok::comma:
400 case tok::greater:
401 case tok::greatergreater:
402 return true;
403
404 default:
405 return false;
406 }
407 }
408
409 if (Tok.isNot(tok::kw_typename))
410 return false;
411
412 // C++ [temp.param]p2:
413 // There is no semantic difference between class and typename in a
414 // template-parameter. typename followed by an unqualified-id
415 // names a template type parameter. typename followed by a
416 // qualified-id denotes the type in a non-type
417 // parameter-declaration.
418 Token Next = NextToken();
419
420 // If we have an identifier, skip over it.
421 if (Next.getKind() == tok::identifier)
422 Next = GetLookAheadToken(2);
423
424 switch (Next.getKind()) {
425 case tok::equal:
426 case tok::comma:
427 case tok::greater:
428 case tok::greatergreater:
429 case tok::ellipsis:
430 return true;
431
432 default:
433 return false;
434 }
435}
436
437/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
438///
439/// template-parameter: [C++ temp.param]
440/// type-parameter
441/// parameter-declaration
442///
443/// type-parameter: (see below)
444/// 'class' ...[opt] identifier[opt]
445/// 'class' identifier[opt] '=' type-id
446/// 'typename' ...[opt] identifier[opt]
447/// 'typename' identifier[opt] '=' type-id
448/// 'template' '<' template-parameter-list '>'
449/// 'class' ...[opt] identifier[opt]
450/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
451/// = id-expression
452Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
453 if (isStartOfTemplateTypeParameter())
454 return ParseTypeParameter(Depth, Position);
455
456 if (Tok.is(tok::kw_template))
457 return ParseTemplateTemplateParameter(Depth, Position);
458
459 // If it's none of the above, then it must be a parameter declaration.
460 // NOTE: This will pick up errors in the closure of the template parameter
461 // list (e.g., template < ; Check here to implement >> style closures.
462 return ParseNonTypeTemplateParameter(Depth, Position);
463}
464
465/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
466/// Other kinds of template parameters are parsed in
467/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
468///
469/// type-parameter: [C++ temp.param]
470/// 'class' ...[opt][C++0x] identifier[opt]
471/// 'class' identifier[opt] '=' type-id
472/// 'typename' ...[opt][C++0x] identifier[opt]
473/// 'typename' identifier[opt] '=' type-id
474Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
475 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
476 "A type-parameter starts with 'class' or 'typename'");
477
478 // Consume the 'class' or 'typename' keyword.
479 bool TypenameKeyword = Tok.is(tok::kw_typename);
480 SourceLocation KeyLoc = ConsumeToken();
481
482 // Grab the ellipsis (if given).
483 bool Ellipsis = false;
484 SourceLocation EllipsisLoc;
485 if (Tok.is(tok::ellipsis)) {
486 Ellipsis = true;
487 EllipsisLoc = ConsumeToken();
488
489 Diag(EllipsisLoc,
490 getLangOpts().CPlusPlus11
491 ? diag::warn_cxx98_compat_variadic_templates
492 : diag::ext_variadic_templates);
493 }
494
495 // Grab the template parameter name (if given)
496 SourceLocation NameLoc;
497 IdentifierInfo* ParamName = 0;
498 if (Tok.is(tok::identifier)) {
499 ParamName = Tok.getIdentifierInfo();
500 NameLoc = ConsumeToken();
501 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
502 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
503 // Unnamed template parameter. Don't have to do anything here, just
504 // don't consume this token.
505 } else {
506 Diag(Tok.getLocation(), diag::err_expected_ident);
507 return 0;
508 }
509
510 // Grab a default argument (if available).
511 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
512 // we introduce the type parameter into the local scope.
513 SourceLocation EqualLoc;
514 ParsedType DefaultArg;
515 if (Tok.is(tok::equal)) {
516 EqualLoc = ConsumeToken();
517 DefaultArg = ParseTypeName(/*Range=*/0,
518 Declarator::TemplateTypeArgContext).get();
519 }
520
521 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
522 EllipsisLoc, KeyLoc, ParamName, NameLoc,
523 Depth, Position, EqualLoc, DefaultArg);
524}
525
526/// ParseTemplateTemplateParameter - Handle the parsing of template
527/// template parameters.
528///
529/// type-parameter: [C++ temp.param]
530/// 'template' '<' template-parameter-list '>' 'class'
531/// ...[opt] identifier[opt]
532/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
533/// = id-expression
534Decl *
535Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
536 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
537
538 // Handle the template <...> part.
539 SourceLocation TemplateLoc = ConsumeToken();
540 SmallVector<Decl*,8> TemplateParams;
541 SourceLocation LAngleLoc, RAngleLoc;
542 {
543 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
544 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
545 RAngleLoc)) {
546 return 0;
547 }
548 }
549
550 // Generate a meaningful error if the user forgot to put class before the
551 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
552 // or greater appear immediately or after 'typename' or 'struct'. In the
553 // latter case, replace the keyword with 'class'.
554 if (!Tok.is(tok::kw_class)) {
555 bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
556 const Token& Next = Replace ? NextToken() : Tok;
557 if (Next.is(tok::identifier) || Next.is(tok::comma) ||
558 Next.is(tok::greater) || Next.is(tok::greatergreater) ||
559 Next.is(tok::ellipsis))
560 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
561 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
562 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
563 else
564 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
565
566 if (Replace)
567 ConsumeToken();
568 } else
569 ConsumeToken();
570
571 // Parse the ellipsis, if given.
572 SourceLocation EllipsisLoc;
573 if (Tok.is(tok::ellipsis)) {
574 EllipsisLoc = ConsumeToken();
575
576 Diag(EllipsisLoc,
577 getLangOpts().CPlusPlus11
578 ? diag::warn_cxx98_compat_variadic_templates
579 : diag::ext_variadic_templates);
580 }
581
582 // Get the identifier, if given.
583 SourceLocation NameLoc;
584 IdentifierInfo* ParamName = 0;
585 if (Tok.is(tok::identifier)) {
586 ParamName = Tok.getIdentifierInfo();
587 NameLoc = ConsumeToken();
588 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
589 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
590 // Unnamed template parameter. Don't have to do anything here, just
591 // don't consume this token.
592 } else {
593 Diag(Tok.getLocation(), diag::err_expected_ident);
594 return 0;
595 }
596
597 TemplateParameterList *ParamList =
598 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
599 TemplateLoc, LAngleLoc,
600 TemplateParams.data(),
601 TemplateParams.size(),
602 RAngleLoc);
603
604 // Grab a default argument (if available).
605 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
606 // we introduce the template parameter into the local scope.
607 SourceLocation EqualLoc;
608 ParsedTemplateArgument DefaultArg;
609 if (Tok.is(tok::equal)) {
610 EqualLoc = ConsumeToken();
611 DefaultArg = ParseTemplateTemplateArgument();
612 if (DefaultArg.isInvalid()) {
613 Diag(Tok.getLocation(),
614 diag::err_default_template_template_parameter_not_template);
615 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
616 }
617 }
618
619 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
620 ParamList, EllipsisLoc,
621 ParamName, NameLoc, Depth,
622 Position, EqualLoc, DefaultArg);
623}
624
625/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
626/// template parameters (e.g., in "template<int Size> class array;").
627///
628/// template-parameter:
629/// ...
630/// parameter-declaration
631Decl *
632Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
633 // Parse the declaration-specifiers (i.e., the type).
634 // FIXME: The type should probably be restricted in some way... Not all
635 // declarators (parts of declarators?) are accepted for parameters.
636 DeclSpec DS(AttrFactory);
637 ParseDeclarationSpecifiers(DS);
638
639 // Parse this as a typename.
640 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
641 ParseDeclarator(ParamDecl);
642 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
643 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
644 return 0;
645 }
646
647 // If there is a default value, parse it.
648 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
649 // we introduce the template parameter into the local scope.
650 SourceLocation EqualLoc;
651 ExprResult DefaultArg;
652 if (Tok.is(tok::equal)) {
653 EqualLoc = ConsumeToken();
654
655 // C++ [temp.param]p15:
656 // When parsing a default template-argument for a non-type
657 // template-parameter, the first non-nested > is taken as the
658 // end of the template-parameter-list rather than a greater-than
659 // operator.
660 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
661 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
662
663 DefaultArg = ParseAssignmentExpression();
664 if (DefaultArg.isInvalid())
665 SkipUntil(tok::comma, tok::greater, true, true);
666 }
667
668 // Create the parameter.
669 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
670 Depth, Position, EqualLoc,
671 DefaultArg.take());
672}
673
674/// \brief Parses a '>' at the end of a template list.
675///
676/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
677/// to determine if these tokens were supposed to be a '>' followed by
678/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
679///
680/// \param RAngleLoc the location of the consumed '>'.
681///
682/// \param ConsumeLastToken if true, the '>' is not consumed.
683bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
684 bool ConsumeLastToken) {
685 // What will be left once we've consumed the '>'.
686 tok::TokenKind RemainingToken;
687 const char *ReplacementStr = "> >";
688
689 switch (Tok.getKind()) {
690 default:
691 Diag(Tok.getLocation(), diag::err_expected_greater);
692 return true;
693
694 case tok::greater:
695 // Determine the location of the '>' token. Only consume this token
696 // if the caller asked us to.
697 RAngleLoc = Tok.getLocation();
698 if (ConsumeLastToken)
699 ConsumeToken();
700 return false;
701
702 case tok::greatergreater:
703 RemainingToken = tok::greater;
704 break;
705
706 case tok::greatergreatergreater:
707 RemainingToken = tok::greatergreater;
708 break;
709
710 case tok::greaterequal:
711 RemainingToken = tok::equal;
712 ReplacementStr = "> =";
713 break;
714
715 case tok::greatergreaterequal:
716 RemainingToken = tok::greaterequal;
717 break;
718 }
719
720 // This template-id is terminated by a token which starts with a '>'. Outside
721 // C++11, this is now error recovery, and in C++11, this is error recovery if
722 // the token isn't '>>'.
723
724 RAngleLoc = Tok.getLocation();
725
726 // The source range of the '>>' or '>=' at the start of the token.
727 CharSourceRange ReplacementRange =
728 CharSourceRange::getCharRange(RAngleLoc,
729 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
730 getLangOpts()));
731
732 // A hint to put a space between the '>>'s. In order to make the hint as
733 // clear as possible, we include the characters either side of the space in
734 // the replacement, rather than just inserting a space at SecondCharLoc.
735 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
736 ReplacementStr);
737
738 // A hint to put another space after the token, if it would otherwise be
739 // lexed differently.
740 FixItHint Hint2;
741 Token Next = NextToken();
742 if ((RemainingToken == tok::greater ||
743 RemainingToken == tok::greatergreater) &&
744 (Next.is(tok::greater) || Next.is(tok::greatergreater) ||
745 Next.is(tok::greatergreatergreater) || Next.is(tok::equal) ||
746 Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) ||
747 Next.is(tok::equalequal)) &&
748 areTokensAdjacent(Tok, Next))
749 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
750
751 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
752 if (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater))
753 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
754 else if (Tok.is(tok::greaterequal))
755 DiagId = diag::err_right_angle_bracket_equal_needs_space;
756 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
757
758 // Strip the initial '>' from the token.
759 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
760 areTokensAdjacent(Tok, Next)) {
761 // Join two adjacent '=' tokens into one, for cases like:
762 // void (*p)() = f<int>;
763 // return f<int>==p;
764 ConsumeToken();
765 Tok.setKind(tok::equalequal);
766 Tok.setLength(Tok.getLength() + 1);
767 } else {
768 Tok.setKind(RemainingToken);
769 Tok.setLength(Tok.getLength() - 1);
770 }
771 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
772 PP.getSourceManager(),
773 getLangOpts()));
774
775 if (!ConsumeLastToken) {
776 // Since we're not supposed to consume the '>' token, we need to push
777 // this token and revert the current token back to the '>'.
778 PP.EnterToken(Tok);
779 Tok.setKind(tok::greater);
780 Tok.setLength(1);
781 Tok.setLocation(RAngleLoc);
782 }
783 return false;
784}
785
786
787/// \brief Parses a template-id that after the template name has
788/// already been parsed.
789///
790/// This routine takes care of parsing the enclosed template argument
791/// list ('<' template-parameter-list [opt] '>') and placing the
792/// results into a form that can be transferred to semantic analysis.
793///
794/// \param Template the template declaration produced by isTemplateName
795///
796/// \param TemplateNameLoc the source location of the template name
797///
798/// \param SS if non-NULL, the nested-name-specifier preceding the
799/// template name.
800///
801/// \param ConsumeLastToken if true, then we will consume the last
802/// token that forms the template-id. Otherwise, we will leave the
803/// last token in the stream (e.g., so that it can be replaced with an
804/// annotation token).
805bool
806Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
807 SourceLocation TemplateNameLoc,
808 const CXXScopeSpec &SS,
809 bool ConsumeLastToken,
810 SourceLocation &LAngleLoc,
811 TemplateArgList &TemplateArgs,
812 SourceLocation &RAngleLoc) {
813 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
814
815 // Consume the '<'.
816 LAngleLoc = ConsumeToken();
817
818 // Parse the optional template-argument-list.
819 bool Invalid = false;
820 {
821 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
822 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
823 Invalid = ParseTemplateArgumentList(TemplateArgs);
824
825 if (Invalid) {
826 // Try to find the closing '>'.
827 SkipUntil(tok::greater, true, !ConsumeLastToken);
828
829 return true;
830 }
831 }
832
833 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken);
834}
835
836/// \brief Replace the tokens that form a simple-template-id with an
837/// annotation token containing the complete template-id.
838///
839/// The first token in the stream must be the name of a template that
840/// is followed by a '<'. This routine will parse the complete
841/// simple-template-id and replace the tokens with a single annotation
842/// token with one of two different kinds: if the template-id names a
843/// type (and \p AllowTypeAnnotation is true), the annotation token is
844/// a type annotation that includes the optional nested-name-specifier
845/// (\p SS). Otherwise, the annotation token is a template-id
846/// annotation that does not include the optional
847/// nested-name-specifier.
848///
849/// \param Template the declaration of the template named by the first
850/// token (an identifier), as returned from \c Action::isTemplateName().
851///
852/// \param TNK the kind of template that \p Template
853/// refers to, as returned from \c Action::isTemplateName().
854///
855/// \param SS if non-NULL, the nested-name-specifier that precedes
856/// this template name.
857///
858/// \param TemplateKWLoc if valid, specifies that this template-id
859/// annotation was preceded by the 'template' keyword and gives the
860/// location of that keyword. If invalid (the default), then this
861/// template-id was not preceded by a 'template' keyword.
862///
863/// \param AllowTypeAnnotation if true (the default), then a
864/// simple-template-id that refers to a class template, template
865/// template parameter, or other template that produces a type will be
866/// replaced with a type annotation token. Otherwise, the
867/// simple-template-id is always replaced with a template-id
868/// annotation token.
869///
870/// If an unrecoverable parse error occurs and no annotation token can be
871/// formed, this function returns true.
872///
873bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
874 CXXScopeSpec &SS,
875 SourceLocation TemplateKWLoc,
876 UnqualifiedId &TemplateName,
877 bool AllowTypeAnnotation) {
878 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
879 assert(Template && Tok.is(tok::less) &&
880 "Parser isn't at the beginning of a template-id");
881
882 // Consume the template-name.
883 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
884
885 // Parse the enclosed template argument list.
886 SourceLocation LAngleLoc, RAngleLoc;
887 TemplateArgList TemplateArgs;
888 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
889 TemplateNameLoc,
890 SS, false, LAngleLoc,
891 TemplateArgs,
892 RAngleLoc);
893
894 if (Invalid) {
895 // If we failed to parse the template ID but skipped ahead to a >, we're not
896 // going to be able to form a token annotation. Eat the '>' if present.
897 if (Tok.is(tok::greater))
898 ConsumeToken();
899 return true;
900 }
901
902 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
903
904 // Build the annotation token.
905 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
906 TypeResult Type
907 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
908 Template, TemplateNameLoc,
909 LAngleLoc, TemplateArgsPtr, RAngleLoc);
910 if (Type.isInvalid()) {
911 // If we failed to parse the template ID but skipped ahead to a >, we're not
912 // going to be able to form a token annotation. Eat the '>' if present.
913 if (Tok.is(tok::greater))
914 ConsumeToken();
915 return true;
916 }
917
918 Tok.setKind(tok::annot_typename);
919 setTypeAnnotation(Tok, Type.get());
920 if (SS.isNotEmpty())
921 Tok.setLocation(SS.getBeginLoc());
922 else if (TemplateKWLoc.isValid())
923 Tok.setLocation(TemplateKWLoc);
924 else
925 Tok.setLocation(TemplateNameLoc);
926 } else {
927 // Build a template-id annotation token that can be processed
928 // later.
929 Tok.setKind(tok::annot_template_id);
930 TemplateIdAnnotation *TemplateId
931 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
932 TemplateId->TemplateNameLoc = TemplateNameLoc;
933 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
934 TemplateId->Name = TemplateName.Identifier;
935 TemplateId->Operator = OO_None;
936 } else {
937 TemplateId->Name = 0;
938 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
939 }
940 TemplateId->SS = SS;
941 TemplateId->TemplateKWLoc = TemplateKWLoc;
942 TemplateId->Template = Template;
943 TemplateId->Kind = TNK;
944 TemplateId->LAngleLoc = LAngleLoc;
945 TemplateId->RAngleLoc = RAngleLoc;
946 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
947 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
948 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
949 Tok.setAnnotationValue(TemplateId);
950 if (TemplateKWLoc.isValid())
951 Tok.setLocation(TemplateKWLoc);
952 else
953 Tok.setLocation(TemplateNameLoc);
954 }
955
956 // Common fields for the annotation token
957 Tok.setAnnotationEndLoc(RAngleLoc);
958
959 // In case the tokens were cached, have Preprocessor replace them with the
960 // annotation token.
961 PP.AnnotateCachedTokens(Tok);
962 return false;
963}
964
965/// \brief Replaces a template-id annotation token with a type
966/// annotation token.
967///
968/// If there was a failure when forming the type from the template-id,
969/// a type annotation token will still be created, but will have a
970/// NULL type pointer to signify an error.
971void Parser::AnnotateTemplateIdTokenAsType() {
972 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
973
974 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
975 assert((TemplateId->Kind == TNK_Type_template ||
976 TemplateId->Kind == TNK_Dependent_template_name) &&
977 "Only works for type and dependent templates");
978
979 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
980 TemplateId->NumArgs);
981
982 TypeResult Type
983 = Actions.ActOnTemplateIdType(TemplateId->SS,
984 TemplateId->TemplateKWLoc,
985 TemplateId->Template,
986 TemplateId->TemplateNameLoc,
987 TemplateId->LAngleLoc,
988 TemplateArgsPtr,
989 TemplateId->RAngleLoc);
990 // Create the new "type" annotation token.
991 Tok.setKind(tok::annot_typename);
992 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
993 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
994 Tok.setLocation(TemplateId->SS.getBeginLoc());
995 // End location stays the same
996
997 // Replace the template-id annotation token, and possible the scope-specifier
998 // that precedes it, with the typename annotation token.
999 PP.AnnotateCachedTokens(Tok);
1000}
1001
1002/// \brief Determine whether the given token can end a template argument.
1003static bool isEndOfTemplateArgument(Token Tok) {
1004 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
1005 Tok.is(tok::greatergreater);
1006}
1007
1008/// \brief Parse a C++ template template argument.
1009ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1010 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1011 !Tok.is(tok::annot_cxxscope))
1012 return ParsedTemplateArgument();
1013
1014 // C++0x [temp.arg.template]p1:
1015 // A template-argument for a template template-parameter shall be the name
1016 // of a class template or an alias template, expressed as id-expression.
1017 //
1018 // We parse an id-expression that refers to a class template or alias
1019 // template. The grammar we parse is:
1020 //
1021 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1022 //
1023 // followed by a token that terminates a template argument, such as ',',
1024 // '>', or (in some cases) '>>'.
1025 CXXScopeSpec SS; // nested-name-specifier, if present
1026 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1027 /*EnteringContext=*/false);
1028
1029 ParsedTemplateArgument Result;
1030 SourceLocation EllipsisLoc;
1031 if (SS.isSet() && Tok.is(tok::kw_template)) {
1032 // Parse the optional 'template' keyword following the
1033 // nested-name-specifier.
1034 SourceLocation TemplateKWLoc = ConsumeToken();
1035
1036 if (Tok.is(tok::identifier)) {
1037 // We appear to have a dependent template name.
1038 UnqualifiedId Name;
1039 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1040 ConsumeToken(); // the identifier
1041
1042 // Parse the ellipsis.
1043 if (Tok.is(tok::ellipsis))
1044 EllipsisLoc = ConsumeToken();
1045
1046 // If the next token signals the end of a template argument,
1047 // then we have a dependent template name that could be a template
1048 // template argument.
1049 TemplateTy Template;
1050 if (isEndOfTemplateArgument(Tok) &&
1051 Actions.ActOnDependentTemplateName(getCurScope(),
1052 SS, TemplateKWLoc, Name,
1053 /*ObjectType=*/ ParsedType(),
1054 /*EnteringContext=*/false,
1055 Template))
1056 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1057 }
1058 } else if (Tok.is(tok::identifier)) {
1059 // We may have a (non-dependent) template name.
1060 TemplateTy Template;
1061 UnqualifiedId Name;
1062 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1063 ConsumeToken(); // the identifier
1064
1065 // Parse the ellipsis.
1066 if (Tok.is(tok::ellipsis))
1067 EllipsisLoc = ConsumeToken();
1068
1069 if (isEndOfTemplateArgument(Tok)) {
1070 bool MemberOfUnknownSpecialization;
1071 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1072 /*hasTemplateKeyword=*/false,
1073 Name,
1074 /*ObjectType=*/ ParsedType(),
1075 /*EnteringContext=*/false,
1076 Template,
1077 MemberOfUnknownSpecialization);
1078 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1079 // We have an id-expression that refers to a class template or
1080 // (C++0x) alias template.
1081 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1082 }
1083 }
1084 }
1085
1086 // If this is a pack expansion, build it as such.
1087 if (EllipsisLoc.isValid() && !Result.isInvalid())
1088 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1089
1090 return Result;
1091}
1092
1093/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1094///
1095/// template-argument: [C++ 14.2]
1096/// constant-expression
1097/// type-id
1098/// id-expression
1099ParsedTemplateArgument Parser::ParseTemplateArgument() {
1100 // C++ [temp.arg]p2:
1101 // In a template-argument, an ambiguity between a type-id and an
1102 // expression is resolved to a type-id, regardless of the form of
1103 // the corresponding template-parameter.
1104 //
1105 // Therefore, we initially try to parse a type-id.
1106 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1107 SourceLocation Loc = Tok.getLocation();
1108 TypeResult TypeArg = ParseTypeName(/*Range=*/0,
1109 Declarator::TemplateTypeArgContext);
1110 if (TypeArg.isInvalid())
1111 return ParsedTemplateArgument();
1112
1113 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1114 TypeArg.get().getAsOpaquePtr(),
1115 Loc);
1116 }
1117
1118 // Try to parse a template template argument.
1119 {
1120 TentativeParsingAction TPA(*this);
1121
1122 ParsedTemplateArgument TemplateTemplateArgument
1123 = ParseTemplateTemplateArgument();
1124 if (!TemplateTemplateArgument.isInvalid()) {
1125 TPA.Commit();
1126 return TemplateTemplateArgument;
1127 }
1128
1129 // Revert this tentative parse to parse a non-type template argument.
1130 TPA.Revert();
1131 }
1132
1133 // Parse a non-type template argument.
1134 SourceLocation Loc = Tok.getLocation();
1135 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1136 if (ExprArg.isInvalid() || !ExprArg.get())
1137 return ParsedTemplateArgument();
1138
1139 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1140 ExprArg.release(), Loc);
1141}
1142
1143/// \brief Determine whether the current tokens can only be parsed as a
1144/// template argument list (starting with the '<') and never as a '<'
1145/// expression.
1146bool Parser::IsTemplateArgumentList(unsigned Skip) {
1147 struct AlwaysRevertAction : TentativeParsingAction {
1148 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1149 ~AlwaysRevertAction() { Revert(); }
1150 } Tentative(*this);
1151
1152 while (Skip) {
1153 ConsumeToken();
1154 --Skip;
1155 }
1156
1157 // '<'
1158 if (!Tok.is(tok::less))
1159 return false;
1160 ConsumeToken();
1161
1162 // An empty template argument list.
1163 if (Tok.is(tok::greater))
1164 return true;
1165
1166 // See whether we have declaration specifiers, which indicate a type.
1167 while (isCXXDeclarationSpecifier() == TPResult::True())
1168 ConsumeToken();
1169
1170 // If we have a '>' or a ',' then this is a template argument list.
1171 return Tok.is(tok::greater) || Tok.is(tok::comma);
1172}
1173
1174/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1175/// (C++ [temp.names]). Returns true if there was an error.
1176///
1177/// template-argument-list: [C++ 14.2]
1178/// template-argument
1179/// template-argument-list ',' template-argument
1180bool
1181Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1182 // Template argument lists are constant-evaluation contexts.
1183 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
1184
1185 while (true) {
1186 ParsedTemplateArgument Arg = ParseTemplateArgument();
1187 if (Tok.is(tok::ellipsis)) {
1188 SourceLocation EllipsisLoc = ConsumeToken();
1189 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1190 }
1191
1192 if (Arg.isInvalid()) {
1193 SkipUntil(tok::comma, tok::greater, true, true);
1194 return true;
1195 }
1196
1197 // Save this template argument.
1198 TemplateArgs.push_back(Arg);
1199
1200 // If the next token is a comma, consume it and keep reading
1201 // arguments.
1202 if (Tok.isNot(tok::comma)) break;
1203
1204 // Consume the comma.
1205 ConsumeToken();
1206 }
1207
1208 return false;
1209}
1210
1211/// \brief Parse a C++ explicit template instantiation
1212/// (C++ [temp.explicit]).
1213///
1214/// explicit-instantiation:
1215/// 'extern' [opt] 'template' declaration
1216///
1217/// Note that the 'extern' is a GNU extension and C++11 feature.
1218Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1219 SourceLocation ExternLoc,
1220 SourceLocation TemplateLoc,
1221 SourceLocation &DeclEnd,
1222 AccessSpecifier AS) {
1223 // This isn't really required here.
1224 ParsingDeclRAIIObject
1225 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1226
1227 return ParseSingleDeclarationAfterTemplate(Context,
1228 ParsedTemplateInfo(ExternLoc,
1229 TemplateLoc),
1230 ParsingTemplateParams,
1231 DeclEnd, AS);
1232}
1233
1234SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1235 if (TemplateParams)
1236 return getTemplateParamsRange(TemplateParams->data(),
1237 TemplateParams->size());
1238
1239 SourceRange R(TemplateLoc);
1240 if (ExternLoc.isValid())
1241 R.setBegin(ExternLoc);
1242 return R;
1243}
1244
1245void Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) {
1246 ((Parser*)P)->LateTemplateParser(FD);
1247}
1248
1249
1250void Parser::LateTemplateParser(const FunctionDecl *FD) {
1251 LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD];
1252 if (LPT) {
1253 ParseLateTemplatedFuncDef(*LPT);
1254 return;
1255 }
1256
1257 llvm_unreachable("Late templated function without associated lexed tokens");
1258}
1259
1260/// \brief Late parse a C++ function template in Microsoft mode.
1261void Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) {
1262 if(!LMT.D)
1263 return;
1264
1265 // Get the FunctionDecl.
1266 FunctionTemplateDecl *FunTmplD = dyn_cast<FunctionTemplateDecl>(LMT.D);
1267 FunctionDecl *FunD =
1268 FunTmplD ? FunTmplD->getTemplatedDecl() : cast<FunctionDecl>(LMT.D);
1269 // Track template parameter depth.
1270 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1271
1272 // To restore the context after late parsing.
1273 Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
1274
1275 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1276
1277 // Get the list of DeclContexts to reenter.
1278 SmallVector<DeclContext*, 4> DeclContextsToReenter;
1279 DeclContext *DD = FunD->getLexicalParent();
1280 while (DD && !DD->isTranslationUnit()) {
1281 DeclContextsToReenter.push_back(DD);
1282 DD = DD->getLexicalParent();
1283 }
1284
1285 // Reenter template scopes from outermost to innermost.
1286 SmallVector<DeclContext*, 4>::reverse_iterator II =
1287 DeclContextsToReenter.rbegin();
1288 for (; II != DeclContextsToReenter.rend(); ++II) {
1289 if (ClassTemplatePartialSpecializationDecl *MD =
1290 dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) {
1291 TemplateParamScopeStack.push_back(
1292 new ParseScope(this, Scope::TemplateParamScope));
1293 Actions.ActOnReenterTemplateScope(getCurScope(), MD);
1294 ++CurTemplateDepthTracker;
1295 } else if (CXXRecordDecl *MD = dyn_cast_or_null<CXXRecordDecl>(*II)) {
Faisal Vali688f9862013-06-08 19:47:52 +00001296 bool IsClassTemplate = MD->getDescribedClassTemplate() != 0;
Faisal Vali65efd102013-06-08 19:39:00 +00001297 TemplateParamScopeStack.push_back(
Faisal Vali688f9862013-06-08 19:47:52 +00001298 new ParseScope(this, Scope::TemplateParamScope,
1299 /*ManageScope*/IsClassTemplate));
Faisal Vali65efd102013-06-08 19:39:00 +00001300 Actions.ActOnReenterTemplateScope(getCurScope(),
1301 MD->getDescribedClassTemplate());
Faisal Vali688f9862013-06-08 19:47:52 +00001302 if (IsClassTemplate)
1303 ++CurTemplateDepthTracker;
Faisal Vali65efd102013-06-08 19:39:00 +00001304 }
1305 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1306 Actions.PushDeclContext(Actions.getCurScope(), *II);
1307 }
1308 TemplateParamScopeStack.push_back(
1309 new ParseScope(this, Scope::TemplateParamScope));
1310
1311 DeclaratorDecl *Declarator = dyn_cast<DeclaratorDecl>(FunD);
1312 if (Declarator && Declarator->getNumTemplateParameterLists() != 0) {
1313 Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
1314 ++CurTemplateDepthTracker;
1315 }
1316 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1317 ++CurTemplateDepthTracker;
1318
1319 assert(!LMT.Toks.empty() && "Empty body!");
1320
1321 // Append the current token at the end of the new token stream so that it
1322 // doesn't get lost.
1323 LMT.Toks.push_back(Tok);
1324 PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false);
1325
1326 // Consume the previously pushed token.
1327 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1328 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1329 && "Inline method not starting with '{', ':' or 'try'");
1330
1331 // Parse the method body. Function body parsing code is similar enough
1332 // to be re-used for method bodies as well.
1333 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1334
1335 // Recreate the containing function DeclContext.
1336 Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FunD));
1337
1338 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1339
1340 if (Tok.is(tok::kw_try)) {
1341 ParseFunctionTryBlock(LMT.D, FnScope);
1342 } else {
1343 if (Tok.is(tok::colon))
1344 ParseConstructorInitializer(LMT.D);
1345 else
1346 Actions.ActOnDefaultCtorInitializers(LMT.D);
1347
1348 if (Tok.is(tok::l_brace)) {
1349 assert((!FunTmplD || FunTmplD->getTemplateParameters()->getDepth() <
1350 TemplateParameterDepth) &&
1351 "TemplateParameterDepth should be greater than the depth of "
1352 "current template being instantiated!");
1353 ParseFunctionStatementBody(LMT.D, FnScope);
1354 Actions.MarkAsLateParsedTemplate(FunD, false);
1355 } else
1356 Actions.ActOnFinishFunctionBody(LMT.D, 0);
1357 }
1358
1359 // Exit scopes.
1360 FnScope.Exit();
1361 SmallVector<ParseScope*, 4>::reverse_iterator I =
1362 TemplateParamScopeStack.rbegin();
1363 for (; I != TemplateParamScopeStack.rend(); ++I)
1364 delete *I;
1365
1366 DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D);
1367 if (grp)
1368 Actions.getASTConsumer().HandleTopLevelDecl(grp.get());
1369}
1370
1371/// \brief Lex a delayed template function for late parsing.
1372void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1373 tok::TokenKind kind = Tok.getKind();
1374 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1375 // Consume everything up to (and including) the matching right brace.
1376 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1377 }
1378
1379 // If we're in a function-try-block, we need to store all the catch blocks.
1380 if (kind == tok::kw_try) {
1381 while (Tok.is(tok::kw_catch)) {
1382 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1383 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1384 }
1385 }
1386}