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