blob: 5ab5cec0289b8b9ff0adc178025b6a533ffa0bbf [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 Voufoef4579c2013-08-06 01:03:05 +0000245 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
246 &LateParsedAttrs);
Larisse Voufo7c64ef02013-06-21 00:08:46 +0000247 } else {
248 SourceLocation LAngleLoc
249 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
Larisse Voufoef4579c2013-08-06 01:03:05 +0000250 Diag(DeclaratorInfo.getIdentifierLoc(),
Larisse Voufo7c64ef02013-06-21 00:08:46 +0000251 diag::err_explicit_instantiation_with_definition)
Larisse Voufoef4579c2013-08-06 01:03:05 +0000252 << SourceRange(TemplateInfo.TemplateLoc)
253 << FixItHint::CreateInsertion(LAngleLoc, "<>");
Larisse Voufo7c64ef02013-06-21 00:08:46 +0000254
Larisse Voufoef4579c2013-08-06 01:03:05 +0000255 // Recover as if it were an explicit specialization.
Larisse Voufo49854292013-06-22 13:56:11 +0000256 TemplateParameterLists FakedParamLists;
Larisse Voufoef4579c2013-08-06 01:03:05 +0000257 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
258 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, 0, 0,
259 LAngleLoc));
Larisse Voufo7c64ef02013-06-21 00:08:46 +0000260
Larisse Voufoef4579c2013-08-06 01:03:05 +0000261 return ParseFunctionDefinition(
262 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
263 /*isSpecialization=*/true,
264 /*LastParamListWasEmpty=*/true),
265 &LateParsedAttrs);
Larisse Voufo7c64ef02013-06-21 00:08:46 +0000266 }
267 }
Faisal Vali65efd102013-06-08 19:39:00 +0000268 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
Larisse Voufoef4579c2013-08-06 01:03:05 +0000269 &LateParsedAttrs);
Faisal Vali65efd102013-06-08 19:39:00 +0000270 }
271
272 // Parse this declaration.
273 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
274 TemplateInfo);
275
276 if (Tok.is(tok::comma)) {
277 Diag(Tok, diag::err_multiple_template_declarators)
278 << (int)TemplateInfo.Kind;
279 SkipUntil(tok::semi, true, false);
280 return ThisDecl;
281 }
282
283 // Eat the semi colon after the declaration.
284 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
285 if (LateParsedAttrs.size() > 0)
286 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
287 DeclaratorInfo.complete(ThisDecl);
288 return ThisDecl;
289}
290
291/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
292/// angle brackets. Depth is the depth of this template-parameter-list, which
293/// is the number of template headers directly enclosing this template header.
294/// TemplateParams is the current list of template parameters we're building.
295/// The template parameter we parse will be added to this list. LAngleLoc and
296/// RAngleLoc will receive the positions of the '<' and '>', respectively,
297/// that enclose this template parameter list.
298///
299/// \returns true if an error occurred, false otherwise.
300bool Parser::ParseTemplateParameters(unsigned Depth,
301 SmallVectorImpl<Decl*> &TemplateParams,
302 SourceLocation &LAngleLoc,
303 SourceLocation &RAngleLoc) {
304 // Get the template parameter list.
305 if (!Tok.is(tok::less)) {
306 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
307 return true;
308 }
309 LAngleLoc = ConsumeToken();
310
311 // Try to parse the template parameter list.
312 bool Failed = false;
313 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
314 Failed = ParseTemplateParameterList(Depth, TemplateParams);
315
316 if (Tok.is(tok::greatergreater)) {
317 // No diagnostic required here: a template-parameter-list can only be
318 // followed by a declaration or, for a template template parameter, the
319 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
320 // This matters for elegant diagnosis of:
321 // template<template<typename>> struct S;
322 Tok.setKind(tok::greater);
323 RAngleLoc = Tok.getLocation();
324 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
325 } else if (Tok.is(tok::greater))
326 RAngleLoc = ConsumeToken();
327 else if (Failed) {
328 Diag(Tok.getLocation(), diag::err_expected_greater);
329 return true;
330 }
331 return false;
332}
333
334/// ParseTemplateParameterList - Parse a template parameter list. If
335/// the parsing fails badly (i.e., closing bracket was left out), this
336/// will try to put the token stream in a reasonable position (closing
337/// a statement, etc.) and return false.
338///
339/// template-parameter-list: [C++ temp]
340/// template-parameter
341/// template-parameter-list ',' template-parameter
342bool
343Parser::ParseTemplateParameterList(unsigned Depth,
344 SmallVectorImpl<Decl*> &TemplateParams) {
345 while (1) {
346 if (Decl *TmpParam
347 = ParseTemplateParameter(Depth, TemplateParams.size())) {
348 TemplateParams.push_back(TmpParam);
349 } else {
350 // If we failed to parse a template parameter, skip until we find
351 // a comma or closing brace.
352 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
353 }
354
355 // Did we find a comma or the end of the template parameter list?
356 if (Tok.is(tok::comma)) {
357 ConsumeToken();
358 } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
359 // Don't consume this... that's done by template parser.
360 break;
361 } else {
362 // Somebody probably forgot to close the template. Skip ahead and
363 // try to get out of the expression. This error is currently
364 // subsumed by whatever goes on in ParseTemplateParameter.
365 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
366 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
367 return false;
368 }
369 }
370 return true;
371}
372
373/// \brief Determine whether the parser is at the start of a template
374/// type parameter.
375bool Parser::isStartOfTemplateTypeParameter() {
376 if (Tok.is(tok::kw_class)) {
377 // "class" may be the start of an elaborated-type-specifier or a
378 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
379 switch (NextToken().getKind()) {
380 case tok::equal:
381 case tok::comma:
382 case tok::greater:
383 case tok::greatergreater:
384 case tok::ellipsis:
385 return true;
386
387 case tok::identifier:
388 // This may be either a type-parameter or an elaborated-type-specifier.
389 // We have to look further.
390 break;
391
392 default:
393 return false;
394 }
395
396 switch (GetLookAheadToken(2).getKind()) {
397 case tok::equal:
398 case tok::comma:
399 case tok::greater:
400 case tok::greatergreater:
401 return true;
402
403 default:
404 return false;
405 }
406 }
407
408 if (Tok.isNot(tok::kw_typename))
409 return false;
410
411 // C++ [temp.param]p2:
412 // There is no semantic difference between class and typename in a
413 // template-parameter. typename followed by an unqualified-id
414 // names a template type parameter. typename followed by a
415 // qualified-id denotes the type in a non-type
416 // parameter-declaration.
417 Token Next = NextToken();
418
419 // If we have an identifier, skip over it.
420 if (Next.getKind() == tok::identifier)
421 Next = GetLookAheadToken(2);
422
423 switch (Next.getKind()) {
424 case tok::equal:
425 case tok::comma:
426 case tok::greater:
427 case tok::greatergreater:
428 case tok::ellipsis:
429 return true;
430
431 default:
432 return false;
433 }
434}
435
436/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
437///
438/// template-parameter: [C++ temp.param]
439/// type-parameter
440/// parameter-declaration
441///
442/// type-parameter: (see below)
443/// 'class' ...[opt] identifier[opt]
444/// 'class' identifier[opt] '=' type-id
445/// 'typename' ...[opt] identifier[opt]
446/// 'typename' identifier[opt] '=' type-id
447/// 'template' '<' template-parameter-list '>'
448/// 'class' ...[opt] identifier[opt]
449/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
450/// = id-expression
451Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
452 if (isStartOfTemplateTypeParameter())
453 return ParseTypeParameter(Depth, Position);
454
455 if (Tok.is(tok::kw_template))
456 return ParseTemplateTemplateParameter(Depth, Position);
457
458 // If it's none of the above, then it must be a parameter declaration.
459 // NOTE: This will pick up errors in the closure of the template parameter
460 // list (e.g., template < ; Check here to implement >> style closures.
461 return ParseNonTypeTemplateParameter(Depth, Position);
462}
463
464/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
465/// Other kinds of template parameters are parsed in
466/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
467///
468/// type-parameter: [C++ temp.param]
469/// 'class' ...[opt][C++0x] identifier[opt]
470/// 'class' identifier[opt] '=' type-id
471/// 'typename' ...[opt][C++0x] identifier[opt]
472/// 'typename' identifier[opt] '=' type-id
473Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
474 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
475 "A type-parameter starts with 'class' or 'typename'");
476
477 // Consume the 'class' or 'typename' keyword.
478 bool TypenameKeyword = Tok.is(tok::kw_typename);
479 SourceLocation KeyLoc = ConsumeToken();
480
481 // Grab the ellipsis (if given).
482 bool Ellipsis = false;
483 SourceLocation EllipsisLoc;
484 if (Tok.is(tok::ellipsis)) {
485 Ellipsis = true;
486 EllipsisLoc = ConsumeToken();
487
488 Diag(EllipsisLoc,
489 getLangOpts().CPlusPlus11
490 ? diag::warn_cxx98_compat_variadic_templates
491 : diag::ext_variadic_templates);
492 }
493
494 // Grab the template parameter name (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) ||
501 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
502 // Unnamed template parameter. Don't have to do anything here, just
503 // don't consume this token.
504 } else {
505 Diag(Tok.getLocation(), diag::err_expected_ident);
506 return 0;
507 }
508
509 // Grab a default argument (if available).
510 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
511 // we introduce the type parameter into the local scope.
512 SourceLocation EqualLoc;
513 ParsedType DefaultArg;
514 if (Tok.is(tok::equal)) {
515 EqualLoc = ConsumeToken();
516 DefaultArg = ParseTypeName(/*Range=*/0,
517 Declarator::TemplateTypeArgContext).get();
518 }
519
520 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
521 EllipsisLoc, KeyLoc, ParamName, NameLoc,
522 Depth, Position, EqualLoc, DefaultArg);
523}
524
525/// ParseTemplateTemplateParameter - Handle the parsing of template
526/// template parameters.
527///
528/// type-parameter: [C++ temp.param]
529/// 'template' '<' template-parameter-list '>' 'class'
530/// ...[opt] identifier[opt]
531/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
532/// = id-expression
533Decl *
534Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
535 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
536
537 // Handle the template <...> part.
538 SourceLocation TemplateLoc = ConsumeToken();
539 SmallVector<Decl*,8> TemplateParams;
540 SourceLocation LAngleLoc, RAngleLoc;
541 {
542 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
543 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
544 RAngleLoc)) {
545 return 0;
546 }
547 }
548
549 // Generate a meaningful error if the user forgot to put class before the
550 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
551 // or greater appear immediately or after 'typename' or 'struct'. In the
552 // latter case, replace the keyword with 'class'.
553 if (!Tok.is(tok::kw_class)) {
554 bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
555 const Token& Next = Replace ? NextToken() : Tok;
556 if (Next.is(tok::identifier) || Next.is(tok::comma) ||
557 Next.is(tok::greater) || Next.is(tok::greatergreater) ||
558 Next.is(tok::ellipsis))
559 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
560 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
561 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
562 else
563 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
564
565 if (Replace)
566 ConsumeToken();
567 } else
568 ConsumeToken();
569
570 // Parse the ellipsis, if given.
571 SourceLocation EllipsisLoc;
572 if (Tok.is(tok::ellipsis)) {
573 EllipsisLoc = ConsumeToken();
574
575 Diag(EllipsisLoc,
576 getLangOpts().CPlusPlus11
577 ? diag::warn_cxx98_compat_variadic_templates
578 : diag::ext_variadic_templates);
579 }
580
581 // Get the identifier, if given.
582 SourceLocation NameLoc;
583 IdentifierInfo* ParamName = 0;
584 if (Tok.is(tok::identifier)) {
585 ParamName = Tok.getIdentifierInfo();
586 NameLoc = ConsumeToken();
587 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
588 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
589 // Unnamed template parameter. Don't have to do anything here, just
590 // don't consume this token.
591 } else {
592 Diag(Tok.getLocation(), diag::err_expected_ident);
593 return 0;
594 }
595
596 TemplateParameterList *ParamList =
597 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
598 TemplateLoc, LAngleLoc,
599 TemplateParams.data(),
600 TemplateParams.size(),
601 RAngleLoc);
602
603 // Grab a default argument (if available).
604 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
605 // we introduce the template parameter into the local scope.
606 SourceLocation EqualLoc;
607 ParsedTemplateArgument DefaultArg;
608 if (Tok.is(tok::equal)) {
609 EqualLoc = ConsumeToken();
610 DefaultArg = ParseTemplateTemplateArgument();
611 if (DefaultArg.isInvalid()) {
612 Diag(Tok.getLocation(),
613 diag::err_default_template_template_parameter_not_template);
614 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
615 }
616 }
617
618 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
619 ParamList, EllipsisLoc,
620 ParamName, NameLoc, Depth,
621 Position, EqualLoc, DefaultArg);
622}
623
624/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
625/// template parameters (e.g., in "template<int Size> class array;").
626///
627/// template-parameter:
628/// ...
629/// parameter-declaration
630Decl *
631Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
632 // Parse the declaration-specifiers (i.e., the type).
633 // FIXME: The type should probably be restricted in some way... Not all
634 // declarators (parts of declarators?) are accepted for parameters.
635 DeclSpec DS(AttrFactory);
636 ParseDeclarationSpecifiers(DS);
637
638 // Parse this as a typename.
639 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
640 ParseDeclarator(ParamDecl);
641 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
642 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
643 return 0;
644 }
645
646 // If there is a default value, parse it.
647 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
648 // we introduce the template parameter into the local scope.
649 SourceLocation EqualLoc;
650 ExprResult DefaultArg;
651 if (Tok.is(tok::equal)) {
652 EqualLoc = ConsumeToken();
653
654 // C++ [temp.param]p15:
655 // When parsing a default template-argument for a non-type
656 // template-parameter, the first non-nested > is taken as the
657 // end of the template-parameter-list rather than a greater-than
658 // operator.
659 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
660 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
661
662 DefaultArg = ParseAssignmentExpression();
663 if (DefaultArg.isInvalid())
664 SkipUntil(tok::comma, tok::greater, true, true);
665 }
666
667 // Create the parameter.
668 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
669 Depth, Position, EqualLoc,
670 DefaultArg.take());
671}
672
673/// \brief Parses a '>' at the end of a template list.
674///
675/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
676/// to determine if these tokens were supposed to be a '>' followed by
677/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
678///
679/// \param RAngleLoc the location of the consumed '>'.
680///
681/// \param ConsumeLastToken if true, the '>' is not consumed.
Serge Pavlov62f675c2013-08-10 05:54:47 +0000682///
683/// \returns true, if current token does not start with '>', false otherwise.
Faisal Vali65efd102013-06-08 19:39:00 +0000684bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
685 bool ConsumeLastToken) {
686 // What will be left once we've consumed the '>'.
687 tok::TokenKind RemainingToken;
688 const char *ReplacementStr = "> >";
689
690 switch (Tok.getKind()) {
691 default:
692 Diag(Tok.getLocation(), diag::err_expected_greater);
693 return true;
694
695 case tok::greater:
696 // Determine the location of the '>' token. Only consume this token
697 // if the caller asked us to.
698 RAngleLoc = Tok.getLocation();
699 if (ConsumeLastToken)
700 ConsumeToken();
701 return false;
702
703 case tok::greatergreater:
704 RemainingToken = tok::greater;
705 break;
706
707 case tok::greatergreatergreater:
708 RemainingToken = tok::greatergreater;
709 break;
710
711 case tok::greaterequal:
712 RemainingToken = tok::equal;
713 ReplacementStr = "> =";
714 break;
715
716 case tok::greatergreaterequal:
717 RemainingToken = tok::greaterequal;
718 break;
719 }
720
721 // This template-id is terminated by a token which starts with a '>'. Outside
722 // C++11, this is now error recovery, and in C++11, this is error recovery if
723 // the token isn't '>>'.
724
725 RAngleLoc = Tok.getLocation();
726
727 // The source range of the '>>' or '>=' at the start of the token.
728 CharSourceRange ReplacementRange =
729 CharSourceRange::getCharRange(RAngleLoc,
730 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
731 getLangOpts()));
732
733 // A hint to put a space between the '>>'s. In order to make the hint as
734 // clear as possible, we include the characters either side of the space in
735 // the replacement, rather than just inserting a space at SecondCharLoc.
736 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
737 ReplacementStr);
738
739 // A hint to put another space after the token, if it would otherwise be
740 // lexed differently.
741 FixItHint Hint2;
742 Token Next = NextToken();
743 if ((RemainingToken == tok::greater ||
744 RemainingToken == tok::greatergreater) &&
745 (Next.is(tok::greater) || Next.is(tok::greatergreater) ||
746 Next.is(tok::greatergreatergreater) || Next.is(tok::equal) ||
747 Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) ||
748 Next.is(tok::equalequal)) &&
749 areTokensAdjacent(Tok, Next))
750 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
751
752 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
753 if (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater))
754 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
755 else if (Tok.is(tok::greaterequal))
756 DiagId = diag::err_right_angle_bracket_equal_needs_space;
757 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
758
759 // Strip the initial '>' from the token.
760 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
761 areTokensAdjacent(Tok, Next)) {
762 // Join two adjacent '=' tokens into one, for cases like:
763 // void (*p)() = f<int>;
764 // return f<int>==p;
765 ConsumeToken();
766 Tok.setKind(tok::equalequal);
767 Tok.setLength(Tok.getLength() + 1);
768 } else {
769 Tok.setKind(RemainingToken);
770 Tok.setLength(Tok.getLength() - 1);
771 }
772 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
773 PP.getSourceManager(),
774 getLangOpts()));
775
776 if (!ConsumeLastToken) {
777 // Since we're not supposed to consume the '>' token, we need to push
778 // this token and revert the current token back to the '>'.
779 PP.EnterToken(Tok);
780 Tok.setKind(tok::greater);
781 Tok.setLength(1);
782 Tok.setLocation(RAngleLoc);
783 }
784 return false;
785}
786
787
788/// \brief Parses a template-id that after the template name has
789/// already been parsed.
790///
791/// This routine takes care of parsing the enclosed template argument
792/// list ('<' template-parameter-list [opt] '>') and placing the
793/// results into a form that can be transferred to semantic analysis.
794///
795/// \param Template the template declaration produced by isTemplateName
796///
797/// \param TemplateNameLoc the source location of the template name
798///
799/// \param SS if non-NULL, the nested-name-specifier preceding the
800/// template name.
801///
802/// \param ConsumeLastToken if true, then we will consume the last
803/// token that forms the template-id. Otherwise, we will leave the
804/// last token in the stream (e.g., so that it can be replaced with an
805/// annotation token).
806bool
807Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
808 SourceLocation TemplateNameLoc,
809 const CXXScopeSpec &SS,
810 bool ConsumeLastToken,
811 SourceLocation &LAngleLoc,
812 TemplateArgList &TemplateArgs,
813 SourceLocation &RAngleLoc) {
814 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
815
816 // Consume the '<'.
817 LAngleLoc = ConsumeToken();
818
819 // Parse the optional template-argument-list.
820 bool Invalid = false;
821 {
822 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
823 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
824 Invalid = ParseTemplateArgumentList(TemplateArgs);
825
826 if (Invalid) {
827 // Try to find the closing '>'.
828 SkipUntil(tok::greater, true, !ConsumeLastToken);
829
830 return true;
831 }
832 }
833
834 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken);
835}
836
837/// \brief Replace the tokens that form a simple-template-id with an
838/// annotation token containing the complete template-id.
839///
840/// The first token in the stream must be the name of a template that
841/// is followed by a '<'. This routine will parse the complete
842/// simple-template-id and replace the tokens with a single annotation
843/// token with one of two different kinds: if the template-id names a
844/// type (and \p AllowTypeAnnotation is true), the annotation token is
845/// a type annotation that includes the optional nested-name-specifier
846/// (\p SS). Otherwise, the annotation token is a template-id
847/// annotation that does not include the optional
848/// nested-name-specifier.
849///
850/// \param Template the declaration of the template named by the first
851/// token (an identifier), as returned from \c Action::isTemplateName().
852///
853/// \param TNK the kind of template that \p Template
854/// refers to, as returned from \c Action::isTemplateName().
855///
856/// \param SS if non-NULL, the nested-name-specifier that precedes
857/// this template name.
858///
859/// \param TemplateKWLoc if valid, specifies that this template-id
860/// annotation was preceded by the 'template' keyword and gives the
861/// location of that keyword. If invalid (the default), then this
862/// template-id was not preceded by a 'template' keyword.
863///
864/// \param AllowTypeAnnotation if true (the default), then a
865/// simple-template-id that refers to a class template, template
866/// template parameter, or other template that produces a type will be
867/// replaced with a type annotation token. Otherwise, the
868/// simple-template-id is always replaced with a template-id
869/// annotation token.
870///
871/// If an unrecoverable parse error occurs and no annotation token can be
872/// formed, this function returns true.
873///
874bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
875 CXXScopeSpec &SS,
876 SourceLocation TemplateKWLoc,
877 UnqualifiedId &TemplateName,
878 bool AllowTypeAnnotation) {
879 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
880 assert(Template && Tok.is(tok::less) &&
881 "Parser isn't at the beginning of a template-id");
882
883 // Consume the template-name.
884 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
885
886 // Parse the enclosed template argument list.
887 SourceLocation LAngleLoc, RAngleLoc;
888 TemplateArgList TemplateArgs;
889 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
890 TemplateNameLoc,
891 SS, false, LAngleLoc,
892 TemplateArgs,
893 RAngleLoc);
894
895 if (Invalid) {
896 // If we failed to parse the template ID but skipped ahead to a >, we're not
897 // going to be able to form a token annotation. Eat the '>' if present.
898 if (Tok.is(tok::greater))
899 ConsumeToken();
900 return true;
901 }
902
903 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
904
905 // Build the annotation token.
906 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
907 TypeResult Type
908 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
909 Template, TemplateNameLoc,
910 LAngleLoc, TemplateArgsPtr, RAngleLoc);
911 if (Type.isInvalid()) {
912 // If we failed to parse the template ID but skipped ahead to a >, we're not
913 // going to be able to form a token annotation. Eat the '>' if present.
914 if (Tok.is(tok::greater))
915 ConsumeToken();
916 return true;
917 }
918
919 Tok.setKind(tok::annot_typename);
920 setTypeAnnotation(Tok, Type.get());
921 if (SS.isNotEmpty())
922 Tok.setLocation(SS.getBeginLoc());
923 else if (TemplateKWLoc.isValid())
924 Tok.setLocation(TemplateKWLoc);
925 else
926 Tok.setLocation(TemplateNameLoc);
927 } else {
928 // Build a template-id annotation token that can be processed
929 // later.
930 Tok.setKind(tok::annot_template_id);
931 TemplateIdAnnotation *TemplateId
932 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
933 TemplateId->TemplateNameLoc = TemplateNameLoc;
934 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
935 TemplateId->Name = TemplateName.Identifier;
936 TemplateId->Operator = OO_None;
937 } else {
938 TemplateId->Name = 0;
939 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
940 }
941 TemplateId->SS = SS;
942 TemplateId->TemplateKWLoc = TemplateKWLoc;
943 TemplateId->Template = Template;
944 TemplateId->Kind = TNK;
945 TemplateId->LAngleLoc = LAngleLoc;
946 TemplateId->RAngleLoc = RAngleLoc;
947 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
948 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
949 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
950 Tok.setAnnotationValue(TemplateId);
951 if (TemplateKWLoc.isValid())
952 Tok.setLocation(TemplateKWLoc);
953 else
954 Tok.setLocation(TemplateNameLoc);
955 }
956
957 // Common fields for the annotation token
958 Tok.setAnnotationEndLoc(RAngleLoc);
959
960 // In case the tokens were cached, have Preprocessor replace them with the
961 // annotation token.
962 PP.AnnotateCachedTokens(Tok);
963 return false;
964}
965
966/// \brief Replaces a template-id annotation token with a type
967/// annotation token.
968///
969/// If there was a failure when forming the type from the template-id,
970/// a type annotation token will still be created, but will have a
971/// NULL type pointer to signify an error.
972void Parser::AnnotateTemplateIdTokenAsType() {
973 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
974
975 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
976 assert((TemplateId->Kind == TNK_Type_template ||
977 TemplateId->Kind == TNK_Dependent_template_name) &&
978 "Only works for type and dependent templates");
979
980 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
981 TemplateId->NumArgs);
982
983 TypeResult Type
984 = Actions.ActOnTemplateIdType(TemplateId->SS,
985 TemplateId->TemplateKWLoc,
986 TemplateId->Template,
987 TemplateId->TemplateNameLoc,
988 TemplateId->LAngleLoc,
989 TemplateArgsPtr,
990 TemplateId->RAngleLoc);
991 // Create the new "type" annotation token.
992 Tok.setKind(tok::annot_typename);
993 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
994 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
995 Tok.setLocation(TemplateId->SS.getBeginLoc());
996 // End location stays the same
997
998 // Replace the template-id annotation token, and possible the scope-specifier
999 // that precedes it, with the typename annotation token.
1000 PP.AnnotateCachedTokens(Tok);
1001}
1002
1003/// \brief Determine whether the given token can end a template argument.
1004static bool isEndOfTemplateArgument(Token Tok) {
1005 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
1006 Tok.is(tok::greatergreater);
1007}
1008
1009/// \brief Parse a C++ template template argument.
1010ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1011 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1012 !Tok.is(tok::annot_cxxscope))
1013 return ParsedTemplateArgument();
1014
1015 // C++0x [temp.arg.template]p1:
1016 // A template-argument for a template template-parameter shall be the name
1017 // of a class template or an alias template, expressed as id-expression.
1018 //
1019 // We parse an id-expression that refers to a class template or alias
1020 // template. The grammar we parse is:
1021 //
1022 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1023 //
1024 // followed by a token that terminates a template argument, such as ',',
1025 // '>', or (in some cases) '>>'.
1026 CXXScopeSpec SS; // nested-name-specifier, if present
1027 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1028 /*EnteringContext=*/false);
1029
1030 ParsedTemplateArgument Result;
1031 SourceLocation EllipsisLoc;
1032 if (SS.isSet() && Tok.is(tok::kw_template)) {
1033 // Parse the optional 'template' keyword following the
1034 // nested-name-specifier.
1035 SourceLocation TemplateKWLoc = ConsumeToken();
1036
1037 if (Tok.is(tok::identifier)) {
1038 // We appear to have a dependent template name.
1039 UnqualifiedId Name;
1040 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1041 ConsumeToken(); // the identifier
1042
1043 // Parse the ellipsis.
1044 if (Tok.is(tok::ellipsis))
1045 EllipsisLoc = ConsumeToken();
1046
1047 // If the next token signals the end of a template argument,
1048 // then we have a dependent template name that could be a template
1049 // template argument.
1050 TemplateTy Template;
1051 if (isEndOfTemplateArgument(Tok) &&
1052 Actions.ActOnDependentTemplateName(getCurScope(),
1053 SS, TemplateKWLoc, Name,
1054 /*ObjectType=*/ ParsedType(),
1055 /*EnteringContext=*/false,
1056 Template))
1057 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1058 }
1059 } else if (Tok.is(tok::identifier)) {
1060 // We may have a (non-dependent) template name.
1061 TemplateTy Template;
1062 UnqualifiedId Name;
1063 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1064 ConsumeToken(); // the identifier
1065
1066 // Parse the ellipsis.
1067 if (Tok.is(tok::ellipsis))
1068 EllipsisLoc = ConsumeToken();
1069
1070 if (isEndOfTemplateArgument(Tok)) {
1071 bool MemberOfUnknownSpecialization;
1072 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1073 /*hasTemplateKeyword=*/false,
1074 Name,
1075 /*ObjectType=*/ ParsedType(),
1076 /*EnteringContext=*/false,
1077 Template,
1078 MemberOfUnknownSpecialization);
1079 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1080 // We have an id-expression that refers to a class template or
1081 // (C++0x) alias template.
1082 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1083 }
1084 }
1085 }
1086
1087 // If this is a pack expansion, build it as such.
1088 if (EllipsisLoc.isValid() && !Result.isInvalid())
1089 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1090
1091 return Result;
1092}
1093
1094/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1095///
1096/// template-argument: [C++ 14.2]
1097/// constant-expression
1098/// type-id
1099/// id-expression
1100ParsedTemplateArgument Parser::ParseTemplateArgument() {
1101 // C++ [temp.arg]p2:
1102 // In a template-argument, an ambiguity between a type-id and an
1103 // expression is resolved to a type-id, regardless of the form of
1104 // the corresponding template-parameter.
1105 //
1106 // Therefore, we initially try to parse a type-id.
1107 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1108 SourceLocation Loc = Tok.getLocation();
1109 TypeResult TypeArg = ParseTypeName(/*Range=*/0,
1110 Declarator::TemplateTypeArgContext);
1111 if (TypeArg.isInvalid())
1112 return ParsedTemplateArgument();
1113
1114 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1115 TypeArg.get().getAsOpaquePtr(),
1116 Loc);
1117 }
1118
1119 // Try to parse a template template argument.
1120 {
1121 TentativeParsingAction TPA(*this);
1122
1123 ParsedTemplateArgument TemplateTemplateArgument
1124 = ParseTemplateTemplateArgument();
1125 if (!TemplateTemplateArgument.isInvalid()) {
1126 TPA.Commit();
1127 return TemplateTemplateArgument;
1128 }
1129
1130 // Revert this tentative parse to parse a non-type template argument.
1131 TPA.Revert();
1132 }
1133
1134 // Parse a non-type template argument.
1135 SourceLocation Loc = Tok.getLocation();
1136 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1137 if (ExprArg.isInvalid() || !ExprArg.get())
1138 return ParsedTemplateArgument();
1139
1140 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1141 ExprArg.release(), Loc);
1142}
1143
1144/// \brief Determine whether the current tokens can only be parsed as a
1145/// template argument list (starting with the '<') and never as a '<'
1146/// expression.
1147bool Parser::IsTemplateArgumentList(unsigned Skip) {
1148 struct AlwaysRevertAction : TentativeParsingAction {
1149 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1150 ~AlwaysRevertAction() { Revert(); }
1151 } Tentative(*this);
1152
1153 while (Skip) {
1154 ConsumeToken();
1155 --Skip;
1156 }
1157
1158 // '<'
1159 if (!Tok.is(tok::less))
1160 return false;
1161 ConsumeToken();
1162
1163 // An empty template argument list.
1164 if (Tok.is(tok::greater))
1165 return true;
1166
1167 // See whether we have declaration specifiers, which indicate a type.
1168 while (isCXXDeclarationSpecifier() == TPResult::True())
1169 ConsumeToken();
1170
1171 // If we have a '>' or a ',' then this is a template argument list.
1172 return Tok.is(tok::greater) || Tok.is(tok::comma);
1173}
1174
1175/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1176/// (C++ [temp.names]). Returns true if there was an error.
1177///
1178/// template-argument-list: [C++ 14.2]
1179/// template-argument
1180/// template-argument-list ',' template-argument
1181bool
1182Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1183 // Template argument lists are constant-evaluation contexts.
1184 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
1185
1186 while (true) {
1187 ParsedTemplateArgument Arg = ParseTemplateArgument();
1188 if (Tok.is(tok::ellipsis)) {
1189 SourceLocation EllipsisLoc = ConsumeToken();
1190 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1191 }
1192
1193 if (Arg.isInvalid()) {
1194 SkipUntil(tok::comma, tok::greater, true, true);
1195 return true;
1196 }
1197
1198 // Save this template argument.
1199 TemplateArgs.push_back(Arg);
1200
1201 // If the next token is a comma, consume it and keep reading
1202 // arguments.
1203 if (Tok.isNot(tok::comma)) break;
1204
1205 // Consume the comma.
1206 ConsumeToken();
1207 }
1208
1209 return false;
1210}
1211
1212/// \brief Parse a C++ explicit template instantiation
1213/// (C++ [temp.explicit]).
1214///
1215/// explicit-instantiation:
1216/// 'extern' [opt] 'template' declaration
1217///
1218/// Note that the 'extern' is a GNU extension and C++11 feature.
1219Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1220 SourceLocation ExternLoc,
1221 SourceLocation TemplateLoc,
1222 SourceLocation &DeclEnd,
1223 AccessSpecifier AS) {
1224 // This isn't really required here.
1225 ParsingDeclRAIIObject
1226 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1227
1228 return ParseSingleDeclarationAfterTemplate(Context,
1229 ParsedTemplateInfo(ExternLoc,
1230 TemplateLoc),
1231 ParsingTemplateParams,
1232 DeclEnd, AS);
1233}
1234
1235SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1236 if (TemplateParams)
1237 return getTemplateParamsRange(TemplateParams->data(),
1238 TemplateParams->size());
1239
1240 SourceRange R(TemplateLoc);
1241 if (ExternLoc.isValid())
1242 R.setBegin(ExternLoc);
1243 return R;
1244}
1245
Richard Smithac32d902013-08-07 21:41:30 +00001246void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1247 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
Faisal Vali65efd102013-06-08 19:39:00 +00001248}
1249
1250/// \brief Late parse a C++ function template in Microsoft mode.
Richard Smithac32d902013-08-07 21:41:30 +00001251void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
1252 if(!LPT.D)
Faisal Vali65efd102013-06-08 19:39:00 +00001253 return;
1254
1255 // Get the FunctionDecl.
Richard Smithac32d902013-08-07 21:41:30 +00001256 FunctionTemplateDecl *FunTmplD = dyn_cast<FunctionTemplateDecl>(LPT.D);
Faisal Vali65efd102013-06-08 19:39:00 +00001257 FunctionDecl *FunD =
Richard Smithac32d902013-08-07 21:41:30 +00001258 FunTmplD ? FunTmplD->getTemplatedDecl() : cast<FunctionDecl>(LPT.D);
Faisal Vali65efd102013-06-08 19:39:00 +00001259 // Track template parameter depth.
1260 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1261
1262 // To restore the context after late parsing.
1263 Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
1264
1265 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1266
1267 // Get the list of DeclContexts to reenter.
1268 SmallVector<DeclContext*, 4> DeclContextsToReenter;
1269 DeclContext *DD = FunD->getLexicalParent();
1270 while (DD && !DD->isTranslationUnit()) {
1271 DeclContextsToReenter.push_back(DD);
1272 DD = DD->getLexicalParent();
1273 }
1274
1275 // Reenter template scopes from outermost to innermost.
Craig Topper163fbf82013-07-08 03:55:09 +00001276 SmallVectorImpl<DeclContext *>::reverse_iterator II =
Faisal Vali65efd102013-06-08 19:39:00 +00001277 DeclContextsToReenter.rbegin();
1278 for (; II != DeclContextsToReenter.rend(); ++II) {
1279 if (ClassTemplatePartialSpecializationDecl *MD =
1280 dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) {
1281 TemplateParamScopeStack.push_back(
1282 new ParseScope(this, Scope::TemplateParamScope));
1283 Actions.ActOnReenterTemplateScope(getCurScope(), MD);
1284 ++CurTemplateDepthTracker;
1285 } else if (CXXRecordDecl *MD = dyn_cast_or_null<CXXRecordDecl>(*II)) {
Faisal Vali688f9862013-06-08 19:47:52 +00001286 bool IsClassTemplate = MD->getDescribedClassTemplate() != 0;
Faisal Vali65efd102013-06-08 19:39:00 +00001287 TemplateParamScopeStack.push_back(
Faisal Vali688f9862013-06-08 19:47:52 +00001288 new ParseScope(this, Scope::TemplateParamScope,
1289 /*ManageScope*/IsClassTemplate));
Faisal Vali65efd102013-06-08 19:39:00 +00001290 Actions.ActOnReenterTemplateScope(getCurScope(),
1291 MD->getDescribedClassTemplate());
Faisal Vali688f9862013-06-08 19:47:52 +00001292 if (IsClassTemplate)
1293 ++CurTemplateDepthTracker;
Faisal Vali65efd102013-06-08 19:39:00 +00001294 }
1295 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1296 Actions.PushDeclContext(Actions.getCurScope(), *II);
1297 }
1298 TemplateParamScopeStack.push_back(
1299 new ParseScope(this, Scope::TemplateParamScope));
1300
1301 DeclaratorDecl *Declarator = dyn_cast<DeclaratorDecl>(FunD);
1302 if (Declarator && Declarator->getNumTemplateParameterLists() != 0) {
1303 Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
1304 ++CurTemplateDepthTracker;
1305 }
Richard Smithac32d902013-08-07 21:41:30 +00001306 Actions.ActOnReenterTemplateScope(getCurScope(), LPT.D);
Faisal Vali65efd102013-06-08 19:39:00 +00001307 ++CurTemplateDepthTracker;
1308
Richard Smithac32d902013-08-07 21:41:30 +00001309 assert(!LPT.Toks.empty() && "Empty body!");
Faisal Vali65efd102013-06-08 19:39:00 +00001310
1311 // Append the current token at the end of the new token stream so that it
1312 // doesn't get lost.
Richard Smithac32d902013-08-07 21:41:30 +00001313 LPT.Toks.push_back(Tok);
1314 PP.EnterTokenStream(LPT.Toks.data(), LPT.Toks.size(), true, false);
Faisal Vali65efd102013-06-08 19:39:00 +00001315
1316 // Consume the previously pushed token.
1317 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1318 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1319 && "Inline method not starting with '{', ':' or 'try'");
1320
1321 // Parse the method body. Function body parsing code is similar enough
1322 // to be re-used for method bodies as well.
1323 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1324
1325 // Recreate the containing function DeclContext.
1326 Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FunD));
1327
1328 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1329
1330 if (Tok.is(tok::kw_try)) {
Richard Smithac32d902013-08-07 21:41:30 +00001331 ParseFunctionTryBlock(LPT.D, FnScope);
Faisal Vali65efd102013-06-08 19:39:00 +00001332 } else {
1333 if (Tok.is(tok::colon))
Richard Smithac32d902013-08-07 21:41:30 +00001334 ParseConstructorInitializer(LPT.D);
Faisal Vali65efd102013-06-08 19:39:00 +00001335 else
Richard Smithac32d902013-08-07 21:41:30 +00001336 Actions.ActOnDefaultCtorInitializers(LPT.D);
Faisal Vali65efd102013-06-08 19:39:00 +00001337
1338 if (Tok.is(tok::l_brace)) {
1339 assert((!FunTmplD || FunTmplD->getTemplateParameters()->getDepth() <
1340 TemplateParameterDepth) &&
1341 "TemplateParameterDepth should be greater than the depth of "
1342 "current template being instantiated!");
Richard Smithac32d902013-08-07 21:41:30 +00001343 ParseFunctionStatementBody(LPT.D, FnScope);
1344 Actions.UnmarkAsLateParsedTemplate(FunD);
Faisal Vali65efd102013-06-08 19:39:00 +00001345 } else
Richard Smithac32d902013-08-07 21:41:30 +00001346 Actions.ActOnFinishFunctionBody(LPT.D, 0);
Faisal Vali65efd102013-06-08 19:39:00 +00001347 }
1348
1349 // Exit scopes.
1350 FnScope.Exit();
Craig Topper163fbf82013-07-08 03:55:09 +00001351 SmallVectorImpl<ParseScope *>::reverse_iterator I =
Faisal Vali65efd102013-06-08 19:39:00 +00001352 TemplateParamScopeStack.rbegin();
1353 for (; I != TemplateParamScopeStack.rend(); ++I)
1354 delete *I;
1355
Richard Smithac32d902013-08-07 21:41:30 +00001356 DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LPT.D);
Faisal Vali65efd102013-06-08 19:39:00 +00001357 if (grp)
1358 Actions.getASTConsumer().HandleTopLevelDecl(grp.get());
1359}
1360
1361/// \brief Lex a delayed template function for late parsing.
1362void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1363 tok::TokenKind kind = Tok.getKind();
1364 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1365 // Consume everything up to (and including) the matching right brace.
1366 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1367 }
1368
1369 // If we're in a function-try-block, we need to store all the catch blocks.
1370 if (kind == tok::kw_try) {
1371 while (Tok.is(tok::kw_catch)) {
1372 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1373 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1374 }
1375 }
1376}