blob: d8fbe0c264395be23e2947e18ed33e541f3ab17f [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;
Stephen Hines651f13c2014-04-23 16:59:28 -0700104 TryConsumeToken(tok::kw_export, ExportLoc);
Faisal Vali65efd102013-06-08 19:39:00 +0000105
106 // Consume the 'template', which should be here.
107 SourceLocation TemplateLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -0700108 if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
Faisal Vali65efd102013-06-08 19:39:00 +0000109 Diag(Tok.getLocation(), diag::err_expected_template);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700110 return nullptr;
Faisal Vali65efd102013-06-08 19:39:00 +0000111 }
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 Bataev8fe24752013-11-18 08:17:37 +0000119 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Stephen Hines651f13c2014-04-23 16:59:28 -0700120 TryConsumeToken(tok::semi);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700121 return nullptr;
Faisal Vali65efd102013-06-08 19:39:00 +0000122 }
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);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700173 return nullptr;
Faisal Vali65efd102013-06-08 19:39:00 +0000174 }
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 Bataev8fe24752013-11-18 08:17:37 +0000214 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Faisal Vali65efd102013-06-08 19:39:00 +0000215 if (Tok.is(tok::semi))
216 ConsumeToken();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700217 return nullptr;
Faisal Vali65efd102013-06-08 19:39:00 +0000218 }
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 Voufo7c64ef02013-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 Voufoef4579c2013-08-06 01:03:05 +0000240 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
241 &LateParsedAttrs);
Larisse Voufo7c64ef02013-06-21 00:08:46 +0000242 } else {
243 SourceLocation LAngleLoc
244 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
Larisse Voufoef4579c2013-08-06 01:03:05 +0000245 Diag(DeclaratorInfo.getIdentifierLoc(),
Larisse Voufo7c64ef02013-06-21 00:08:46 +0000246 diag::err_explicit_instantiation_with_definition)
Larisse Voufoef4579c2013-08-06 01:03:05 +0000247 << SourceRange(TemplateInfo.TemplateLoc)
248 << FixItHint::CreateInsertion(LAngleLoc, "<>");
Larisse Voufo7c64ef02013-06-21 00:08:46 +0000249
Larisse Voufoef4579c2013-08-06 01:03:05 +0000250 // Recover as if it were an explicit specialization.
Larisse Voufo49854292013-06-22 13:56:11 +0000251 TemplateParameterLists FakedParamLists;
Larisse Voufoef4579c2013-08-06 01:03:05 +0000252 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700253 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr,
254 0, LAngleLoc));
Larisse Voufo7c64ef02013-06-21 00:08:46 +0000255
Larisse Voufoef4579c2013-08-06 01:03:05 +0000256 return ParseFunctionDefinition(
257 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
258 /*isSpecialization=*/true,
259 /*LastParamListWasEmpty=*/true),
260 &LateParsedAttrs);
Larisse Voufo7c64ef02013-06-21 00:08:46 +0000261 }
262 }
Faisal Vali65efd102013-06-08 19:39:00 +0000263 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
Larisse Voufoef4579c2013-08-06 01:03:05 +0000264 &LateParsedAttrs);
Faisal Vali65efd102013-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 Bataev8fe24752013-11-18 08:17:37 +0000274 SkipUntil(tok::semi);
Faisal Vali65efd102013-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.
Stephen Hines651f13c2014-04-23 16:59:28 -0700300 if (!TryConsumeToken(tok::less, LAngleLoc)) {
Faisal Vali65efd102013-06-08 19:39:00 +0000301 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
302 return true;
303 }
Faisal Vali65efd102013-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));
Stephen Hines651f13c2014-04-23 16:59:28 -0700319 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
320 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali65efd102013-06-08 19:39:00 +0000321 return true;
322 }
323 return false;
324}
325
326/// ParseTemplateParameterList - Parse a template parameter list. If
327/// the parsing fails badly (i.e., closing bracket was left out), this
328/// will try to put the token stream in a reasonable position (closing
329/// a statement, etc.) and return false.
330///
331/// template-parameter-list: [C++ temp]
332/// template-parameter
333/// template-parameter-list ',' template-parameter
334bool
335Parser::ParseTemplateParameterList(unsigned Depth,
336 SmallVectorImpl<Decl*> &TemplateParams) {
337 while (1) {
338 if (Decl *TmpParam
339 = ParseTemplateParameter(Depth, TemplateParams.size())) {
340 TemplateParams.push_back(TmpParam);
341 } else {
342 // If we failed to parse a template parameter, skip until we find
343 // a comma or closing brace.
Alexey Bataev8fe24752013-11-18 08:17:37 +0000344 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
345 StopAtSemi | StopBeforeMatch);
Faisal Vali65efd102013-06-08 19:39:00 +0000346 }
347
348 // Did we find a comma or the end of the template parameter list?
349 if (Tok.is(tok::comma)) {
350 ConsumeToken();
351 } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
352 // Don't consume this... that's done by template parser.
353 break;
354 } else {
355 // Somebody probably forgot to close the template. Skip ahead and
356 // try to get out of the expression. This error is currently
357 // subsumed by whatever goes on in ParseTemplateParameter.
358 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Alexey Bataev8fe24752013-11-18 08:17:37 +0000359 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
360 StopAtSemi | StopBeforeMatch);
Faisal Vali65efd102013-06-08 19:39:00 +0000361 return false;
362 }
363 }
364 return true;
365}
366
367/// \brief Determine whether the parser is at the start of a template
368/// type parameter.
369bool Parser::isStartOfTemplateTypeParameter() {
370 if (Tok.is(tok::kw_class)) {
371 // "class" may be the start of an elaborated-type-specifier or a
372 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
373 switch (NextToken().getKind()) {
374 case tok::equal:
375 case tok::comma:
376 case tok::greater:
377 case tok::greatergreater:
378 case tok::ellipsis:
379 return true;
380
381 case tok::identifier:
382 // This may be either a type-parameter or an elaborated-type-specifier.
383 // We have to look further.
384 break;
385
386 default:
387 return false;
388 }
389
390 switch (GetLookAheadToken(2).getKind()) {
391 case tok::equal:
392 case tok::comma:
393 case tok::greater:
394 case tok::greatergreater:
395 return true;
396
397 default:
398 return false;
399 }
400 }
401
402 if (Tok.isNot(tok::kw_typename))
403 return false;
404
405 // C++ [temp.param]p2:
406 // There is no semantic difference between class and typename in a
407 // template-parameter. typename followed by an unqualified-id
408 // names a template type parameter. typename followed by a
409 // qualified-id denotes the type in a non-type
410 // parameter-declaration.
411 Token Next = NextToken();
412
413 // If we have an identifier, skip over it.
414 if (Next.getKind() == tok::identifier)
415 Next = GetLookAheadToken(2);
416
417 switch (Next.getKind()) {
418 case tok::equal:
419 case tok::comma:
420 case tok::greater:
421 case tok::greatergreater:
422 case tok::ellipsis:
423 return true;
424
425 default:
426 return false;
427 }
428}
429
430/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
431///
432/// template-parameter: [C++ temp.param]
433/// type-parameter
434/// parameter-declaration
435///
436/// type-parameter: (see below)
437/// 'class' ...[opt] identifier[opt]
438/// 'class' identifier[opt] '=' type-id
439/// 'typename' ...[opt] identifier[opt]
440/// 'typename' identifier[opt] '=' type-id
441/// 'template' '<' template-parameter-list '>'
442/// 'class' ...[opt] identifier[opt]
443/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
444/// = id-expression
445Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
446 if (isStartOfTemplateTypeParameter())
447 return ParseTypeParameter(Depth, Position);
448
449 if (Tok.is(tok::kw_template))
450 return ParseTemplateTemplateParameter(Depth, Position);
451
452 // If it's none of the above, then it must be a parameter declaration.
453 // NOTE: This will pick up errors in the closure of the template parameter
454 // list (e.g., template < ; Check here to implement >> style closures.
455 return ParseNonTypeTemplateParameter(Depth, Position);
456}
457
458/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
459/// Other kinds of template parameters are parsed in
460/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
461///
462/// type-parameter: [C++ temp.param]
463/// 'class' ...[opt][C++0x] identifier[opt]
464/// 'class' identifier[opt] '=' type-id
465/// 'typename' ...[opt][C++0x] identifier[opt]
466/// 'typename' identifier[opt] '=' type-id
467Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
468 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
469 "A type-parameter starts with 'class' or 'typename'");
470
471 // Consume the 'class' or 'typename' keyword.
472 bool TypenameKeyword = Tok.is(tok::kw_typename);
473 SourceLocation KeyLoc = ConsumeToken();
474
475 // Grab the ellipsis (if given).
476 bool Ellipsis = false;
477 SourceLocation EllipsisLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -0700478 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
Faisal Vali65efd102013-06-08 19:39:00 +0000479 Ellipsis = true;
Faisal Vali65efd102013-06-08 19:39:00 +0000480 Diag(EllipsisLoc,
481 getLangOpts().CPlusPlus11
482 ? diag::warn_cxx98_compat_variadic_templates
483 : diag::ext_variadic_templates);
484 }
485
486 // Grab the template parameter name (if given)
487 SourceLocation NameLoc;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700488 IdentifierInfo *ParamName = nullptr;
Faisal Vali65efd102013-06-08 19:39:00 +0000489 if (Tok.is(tok::identifier)) {
490 ParamName = Tok.getIdentifierInfo();
491 NameLoc = ConsumeToken();
492 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
493 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
494 // Unnamed template parameter. Don't have to do anything here, just
495 // don't consume this token.
496 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -0700497 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700498 return nullptr;
Faisal Vali65efd102013-06-08 19:39:00 +0000499 }
500
501 // Grab a default argument (if available).
502 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
503 // we introduce the type parameter into the local scope.
504 SourceLocation EqualLoc;
505 ParsedType DefaultArg;
Stephen Hines651f13c2014-04-23 16:59:28 -0700506 if (TryConsumeToken(tok::equal, EqualLoc))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700507 DefaultArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali65efd102013-06-08 19:39:00 +0000508 Declarator::TemplateTypeArgContext).get();
Faisal Vali65efd102013-06-08 19:39:00 +0000509
510 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
511 EllipsisLoc, KeyLoc, ParamName, NameLoc,
512 Depth, Position, EqualLoc, DefaultArg);
513}
514
515/// ParseTemplateTemplateParameter - Handle the parsing of template
516/// template parameters.
517///
518/// type-parameter: [C++ temp.param]
519/// 'template' '<' template-parameter-list '>' 'class'
520/// ...[opt] identifier[opt]
521/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
522/// = id-expression
523Decl *
524Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
525 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
526
527 // Handle the template <...> part.
528 SourceLocation TemplateLoc = ConsumeToken();
529 SmallVector<Decl*,8> TemplateParams;
530 SourceLocation LAngleLoc, RAngleLoc;
531 {
532 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
533 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
534 RAngleLoc)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700535 return nullptr;
Faisal Vali65efd102013-06-08 19:39:00 +0000536 }
537 }
538
539 // Generate a meaningful error if the user forgot to put class before the
540 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
541 // or greater appear immediately or after 'typename' or 'struct'. In the
542 // latter case, replace the keyword with 'class'.
Stephen Hines651f13c2014-04-23 16:59:28 -0700543 if (!TryConsumeToken(tok::kw_class)) {
Faisal Vali65efd102013-06-08 19:39:00 +0000544 bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
545 const Token& Next = Replace ? NextToken() : Tok;
546 if (Next.is(tok::identifier) || Next.is(tok::comma) ||
547 Next.is(tok::greater) || Next.is(tok::greatergreater) ||
548 Next.is(tok::ellipsis))
549 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
550 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
551 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
552 else
553 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
554
555 if (Replace)
556 ConsumeToken();
Stephen Hines651f13c2014-04-23 16:59:28 -0700557 }
Faisal Vali65efd102013-06-08 19:39:00 +0000558
559 // Parse the ellipsis, if given.
560 SourceLocation EllipsisLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -0700561 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali65efd102013-06-08 19:39:00 +0000562 Diag(EllipsisLoc,
563 getLangOpts().CPlusPlus11
564 ? diag::warn_cxx98_compat_variadic_templates
565 : diag::ext_variadic_templates);
Faisal Vali65efd102013-06-08 19:39:00 +0000566
567 // Get the identifier, if given.
568 SourceLocation NameLoc;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700569 IdentifierInfo *ParamName = nullptr;
Faisal Vali65efd102013-06-08 19:39:00 +0000570 if (Tok.is(tok::identifier)) {
571 ParamName = Tok.getIdentifierInfo();
572 NameLoc = ConsumeToken();
573 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
574 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
575 // Unnamed template parameter. Don't have to do anything here, just
576 // don't consume this token.
577 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -0700578 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700579 return nullptr;
Faisal Vali65efd102013-06-08 19:39:00 +0000580 }
581
582 TemplateParameterList *ParamList =
583 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
584 TemplateLoc, LAngleLoc,
585 TemplateParams.data(),
586 TemplateParams.size(),
587 RAngleLoc);
588
589 // Grab a default argument (if available).
590 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
591 // we introduce the template parameter into the local scope.
592 SourceLocation EqualLoc;
593 ParsedTemplateArgument DefaultArg;
Stephen Hines651f13c2014-04-23 16:59:28 -0700594 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali65efd102013-06-08 19:39:00 +0000595 DefaultArg = ParseTemplateTemplateArgument();
596 if (DefaultArg.isInvalid()) {
597 Diag(Tok.getLocation(),
598 diag::err_default_template_template_parameter_not_template);
Alexey Bataev8fe24752013-11-18 08:17:37 +0000599 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
600 StopAtSemi | StopBeforeMatch);
Faisal Vali65efd102013-06-08 19:39:00 +0000601 }
602 }
603
604 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
605 ParamList, EllipsisLoc,
606 ParamName, NameLoc, Depth,
607 Position, EqualLoc, DefaultArg);
608}
609
610/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
611/// template parameters (e.g., in "template<int Size> class array;").
612///
613/// template-parameter:
614/// ...
615/// parameter-declaration
616Decl *
617Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
618 // Parse the declaration-specifiers (i.e., the type).
619 // FIXME: The type should probably be restricted in some way... Not all
620 // declarators (parts of declarators?) are accepted for parameters.
621 DeclSpec DS(AttrFactory);
622 ParseDeclarationSpecifiers(DS);
623
624 // Parse this as a typename.
625 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
626 ParseDeclarator(ParamDecl);
627 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
628 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700629 return nullptr;
Faisal Vali65efd102013-06-08 19:39:00 +0000630 }
631
632 // If there is a default value, parse it.
633 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
634 // we introduce the template parameter into the local scope.
635 SourceLocation EqualLoc;
636 ExprResult DefaultArg;
Stephen Hines651f13c2014-04-23 16:59:28 -0700637 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali65efd102013-06-08 19:39:00 +0000638 // C++ [temp.param]p15:
639 // When parsing a default template-argument for a non-type
640 // template-parameter, the first non-nested > is taken as the
641 // end of the template-parameter-list rather than a greater-than
642 // operator.
643 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
644 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
645
646 DefaultArg = ParseAssignmentExpression();
647 if (DefaultArg.isInvalid())
Alexey Bataev8fe24752013-11-18 08:17:37 +0000648 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali65efd102013-06-08 19:39:00 +0000649 }
650
651 // Create the parameter.
652 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
653 Depth, Position, EqualLoc,
654 DefaultArg.take());
655}
656
657/// \brief Parses a '>' at the end of a template list.
658///
659/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
660/// to determine if these tokens were supposed to be a '>' followed by
661/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
662///
663/// \param RAngleLoc the location of the consumed '>'.
664///
665/// \param ConsumeLastToken if true, the '>' is not consumed.
Serge Pavlov62f675c2013-08-10 05:54:47 +0000666///
667/// \returns true, if current token does not start with '>', false otherwise.
Faisal Vali65efd102013-06-08 19:39:00 +0000668bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
669 bool ConsumeLastToken) {
670 // What will be left once we've consumed the '>'.
671 tok::TokenKind RemainingToken;
672 const char *ReplacementStr = "> >";
673
674 switch (Tok.getKind()) {
675 default:
Stephen Hines651f13c2014-04-23 16:59:28 -0700676 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali65efd102013-06-08 19:39:00 +0000677 return true;
678
679 case tok::greater:
680 // Determine the location of the '>' token. Only consume this token
681 // if the caller asked us to.
682 RAngleLoc = Tok.getLocation();
683 if (ConsumeLastToken)
684 ConsumeToken();
685 return false;
686
687 case tok::greatergreater:
688 RemainingToken = tok::greater;
689 break;
690
691 case tok::greatergreatergreater:
692 RemainingToken = tok::greatergreater;
693 break;
694
695 case tok::greaterequal:
696 RemainingToken = tok::equal;
697 ReplacementStr = "> =";
698 break;
699
700 case tok::greatergreaterequal:
701 RemainingToken = tok::greaterequal;
702 break;
703 }
704
705 // This template-id is terminated by a token which starts with a '>'. Outside
706 // C++11, this is now error recovery, and in C++11, this is error recovery if
707 // the token isn't '>>'.
708
709 RAngleLoc = Tok.getLocation();
710
711 // The source range of the '>>' or '>=' at the start of the token.
712 CharSourceRange ReplacementRange =
713 CharSourceRange::getCharRange(RAngleLoc,
714 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
715 getLangOpts()));
716
717 // A hint to put a space between the '>>'s. In order to make the hint as
718 // clear as possible, we include the characters either side of the space in
719 // the replacement, rather than just inserting a space at SecondCharLoc.
720 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
721 ReplacementStr);
722
723 // A hint to put another space after the token, if it would otherwise be
724 // lexed differently.
725 FixItHint Hint2;
726 Token Next = NextToken();
727 if ((RemainingToken == tok::greater ||
728 RemainingToken == tok::greatergreater) &&
729 (Next.is(tok::greater) || Next.is(tok::greatergreater) ||
730 Next.is(tok::greatergreatergreater) || Next.is(tok::equal) ||
731 Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) ||
732 Next.is(tok::equalequal)) &&
733 areTokensAdjacent(Tok, Next))
734 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
735
736 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
737 if (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater))
738 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
739 else if (Tok.is(tok::greaterequal))
740 DiagId = diag::err_right_angle_bracket_equal_needs_space;
741 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
742
743 // Strip the initial '>' from the token.
744 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
745 areTokensAdjacent(Tok, Next)) {
746 // Join two adjacent '=' tokens into one, for cases like:
747 // void (*p)() = f<int>;
748 // return f<int>==p;
749 ConsumeToken();
750 Tok.setKind(tok::equalequal);
751 Tok.setLength(Tok.getLength() + 1);
752 } else {
753 Tok.setKind(RemainingToken);
754 Tok.setLength(Tok.getLength() - 1);
755 }
756 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
757 PP.getSourceManager(),
758 getLangOpts()));
759
760 if (!ConsumeLastToken) {
761 // Since we're not supposed to consume the '>' token, we need to push
762 // this token and revert the current token back to the '>'.
763 PP.EnterToken(Tok);
764 Tok.setKind(tok::greater);
765 Tok.setLength(1);
766 Tok.setLocation(RAngleLoc);
767 }
768 return false;
769}
770
771
772/// \brief Parses a template-id that after the template name has
773/// already been parsed.
774///
775/// This routine takes care of parsing the enclosed template argument
776/// list ('<' template-parameter-list [opt] '>') and placing the
777/// results into a form that can be transferred to semantic analysis.
778///
779/// \param Template the template declaration produced by isTemplateName
780///
781/// \param TemplateNameLoc the source location of the template name
782///
783/// \param SS if non-NULL, the nested-name-specifier preceding the
784/// template name.
785///
786/// \param ConsumeLastToken if true, then we will consume the last
787/// token that forms the template-id. Otherwise, we will leave the
788/// last token in the stream (e.g., so that it can be replaced with an
789/// annotation token).
790bool
791Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
792 SourceLocation TemplateNameLoc,
793 const CXXScopeSpec &SS,
794 bool ConsumeLastToken,
795 SourceLocation &LAngleLoc,
796 TemplateArgList &TemplateArgs,
797 SourceLocation &RAngleLoc) {
798 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
799
800 // Consume the '<'.
801 LAngleLoc = ConsumeToken();
802
803 // Parse the optional template-argument-list.
804 bool Invalid = false;
805 {
806 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
807 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
808 Invalid = ParseTemplateArgumentList(TemplateArgs);
809
810 if (Invalid) {
811 // Try to find the closing '>'.
Alexey Bataev8fe24752013-11-18 08:17:37 +0000812 if (ConsumeLastToken)
813 SkipUntil(tok::greater, StopAtSemi);
814 else
815 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali65efd102013-06-08 19:39:00 +0000816 return true;
817 }
818 }
819
820 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken);
821}
822
823/// \brief Replace the tokens that form a simple-template-id with an
824/// annotation token containing the complete template-id.
825///
826/// The first token in the stream must be the name of a template that
827/// is followed by a '<'. This routine will parse the complete
828/// simple-template-id and replace the tokens with a single annotation
829/// token with one of two different kinds: if the template-id names a
830/// type (and \p AllowTypeAnnotation is true), the annotation token is
831/// a type annotation that includes the optional nested-name-specifier
832/// (\p SS). Otherwise, the annotation token is a template-id
833/// annotation that does not include the optional
834/// nested-name-specifier.
835///
836/// \param Template the declaration of the template named by the first
837/// token (an identifier), as returned from \c Action::isTemplateName().
838///
839/// \param TNK the kind of template that \p Template
840/// refers to, as returned from \c Action::isTemplateName().
841///
842/// \param SS if non-NULL, the nested-name-specifier that precedes
843/// this template name.
844///
845/// \param TemplateKWLoc if valid, specifies that this template-id
846/// annotation was preceded by the 'template' keyword and gives the
847/// location of that keyword. If invalid (the default), then this
848/// template-id was not preceded by a 'template' keyword.
849///
850/// \param AllowTypeAnnotation if true (the default), then a
851/// simple-template-id that refers to a class template, template
852/// template parameter, or other template that produces a type will be
853/// replaced with a type annotation token. Otherwise, the
854/// simple-template-id is always replaced with a template-id
855/// annotation token.
856///
857/// If an unrecoverable parse error occurs and no annotation token can be
858/// formed, this function returns true.
859///
860bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
861 CXXScopeSpec &SS,
862 SourceLocation TemplateKWLoc,
863 UnqualifiedId &TemplateName,
864 bool AllowTypeAnnotation) {
865 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
866 assert(Template && Tok.is(tok::less) &&
867 "Parser isn't at the beginning of a template-id");
868
869 // Consume the template-name.
870 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
871
872 // Parse the enclosed template argument list.
873 SourceLocation LAngleLoc, RAngleLoc;
874 TemplateArgList TemplateArgs;
875 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
876 TemplateNameLoc,
877 SS, false, LAngleLoc,
878 TemplateArgs,
879 RAngleLoc);
880
881 if (Invalid) {
882 // If we failed to parse the template ID but skipped ahead to a >, we're not
883 // going to be able to form a token annotation. Eat the '>' if present.
Stephen Hines651f13c2014-04-23 16:59:28 -0700884 TryConsumeToken(tok::greater);
Faisal Vali65efd102013-06-08 19:39:00 +0000885 return true;
886 }
887
888 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
889
890 // Build the annotation token.
891 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
892 TypeResult Type
893 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
894 Template, TemplateNameLoc,
895 LAngleLoc, TemplateArgsPtr, RAngleLoc);
896 if (Type.isInvalid()) {
897 // If we failed to parse the template ID but skipped ahead to a >, we're not
898 // going to be able to form a token annotation. Eat the '>' if present.
Stephen Hines651f13c2014-04-23 16:59:28 -0700899 TryConsumeToken(tok::greater);
Faisal Vali65efd102013-06-08 19:39:00 +0000900 return true;
901 }
902
903 Tok.setKind(tok::annot_typename);
904 setTypeAnnotation(Tok, Type.get());
905 if (SS.isNotEmpty())
906 Tok.setLocation(SS.getBeginLoc());
907 else if (TemplateKWLoc.isValid())
908 Tok.setLocation(TemplateKWLoc);
909 else
910 Tok.setLocation(TemplateNameLoc);
911 } else {
912 // Build a template-id annotation token that can be processed
913 // later.
914 Tok.setKind(tok::annot_template_id);
915 TemplateIdAnnotation *TemplateId
916 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
917 TemplateId->TemplateNameLoc = TemplateNameLoc;
918 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
919 TemplateId->Name = TemplateName.Identifier;
920 TemplateId->Operator = OO_None;
921 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700922 TemplateId->Name = nullptr;
Faisal Vali65efd102013-06-08 19:39:00 +0000923 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
924 }
925 TemplateId->SS = SS;
926 TemplateId->TemplateKWLoc = TemplateKWLoc;
927 TemplateId->Template = Template;
928 TemplateId->Kind = TNK;
929 TemplateId->LAngleLoc = LAngleLoc;
930 TemplateId->RAngleLoc = RAngleLoc;
931 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
932 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
933 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
934 Tok.setAnnotationValue(TemplateId);
935 if (TemplateKWLoc.isValid())
936 Tok.setLocation(TemplateKWLoc);
937 else
938 Tok.setLocation(TemplateNameLoc);
939 }
940
941 // Common fields for the annotation token
942 Tok.setAnnotationEndLoc(RAngleLoc);
943
944 // In case the tokens were cached, have Preprocessor replace them with the
945 // annotation token.
946 PP.AnnotateCachedTokens(Tok);
947 return false;
948}
949
950/// \brief Replaces a template-id annotation token with a type
951/// annotation token.
952///
953/// If there was a failure when forming the type from the template-id,
954/// a type annotation token will still be created, but will have a
955/// NULL type pointer to signify an error.
956void Parser::AnnotateTemplateIdTokenAsType() {
957 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
958
959 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
960 assert((TemplateId->Kind == TNK_Type_template ||
961 TemplateId->Kind == TNK_Dependent_template_name) &&
962 "Only works for type and dependent templates");
963
964 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
965 TemplateId->NumArgs);
966
967 TypeResult Type
968 = Actions.ActOnTemplateIdType(TemplateId->SS,
969 TemplateId->TemplateKWLoc,
970 TemplateId->Template,
971 TemplateId->TemplateNameLoc,
972 TemplateId->LAngleLoc,
973 TemplateArgsPtr,
974 TemplateId->RAngleLoc);
975 // Create the new "type" annotation token.
976 Tok.setKind(tok::annot_typename);
977 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
978 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
979 Tok.setLocation(TemplateId->SS.getBeginLoc());
980 // End location stays the same
981
982 // Replace the template-id annotation token, and possible the scope-specifier
983 // that precedes it, with the typename annotation token.
984 PP.AnnotateCachedTokens(Tok);
985}
986
987/// \brief Determine whether the given token can end a template argument.
988static bool isEndOfTemplateArgument(Token Tok) {
989 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
990 Tok.is(tok::greatergreater);
991}
992
993/// \brief Parse a C++ template template argument.
994ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
995 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
996 !Tok.is(tok::annot_cxxscope))
997 return ParsedTemplateArgument();
998
999 // C++0x [temp.arg.template]p1:
1000 // A template-argument for a template template-parameter shall be the name
1001 // of a class template or an alias template, expressed as id-expression.
1002 //
1003 // We parse an id-expression that refers to a class template or alias
1004 // template. The grammar we parse is:
1005 //
1006 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1007 //
1008 // followed by a token that terminates a template argument, such as ',',
1009 // '>', or (in some cases) '>>'.
1010 CXXScopeSpec SS; // nested-name-specifier, if present
1011 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1012 /*EnteringContext=*/false);
1013
1014 ParsedTemplateArgument Result;
1015 SourceLocation EllipsisLoc;
1016 if (SS.isSet() && Tok.is(tok::kw_template)) {
1017 // Parse the optional 'template' keyword following the
1018 // nested-name-specifier.
1019 SourceLocation TemplateKWLoc = ConsumeToken();
1020
1021 if (Tok.is(tok::identifier)) {
1022 // We appear to have a dependent template name.
1023 UnqualifiedId Name;
1024 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1025 ConsumeToken(); // the identifier
Stephen Hines651f13c2014-04-23 16:59:28 -07001026
1027 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1028
Faisal Vali65efd102013-06-08 19:39:00 +00001029 // If the next token signals the end of a template argument,
1030 // then we have a dependent template name that could be a template
1031 // template argument.
1032 TemplateTy Template;
1033 if (isEndOfTemplateArgument(Tok) &&
1034 Actions.ActOnDependentTemplateName(getCurScope(),
1035 SS, TemplateKWLoc, Name,
1036 /*ObjectType=*/ ParsedType(),
1037 /*EnteringContext=*/false,
1038 Template))
1039 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1040 }
1041 } else if (Tok.is(tok::identifier)) {
1042 // We may have a (non-dependent) template name.
1043 TemplateTy Template;
1044 UnqualifiedId Name;
1045 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1046 ConsumeToken(); // the identifier
Stephen Hines651f13c2014-04-23 16:59:28 -07001047
1048 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Faisal Vali65efd102013-06-08 19:39:00 +00001049
1050 if (isEndOfTemplateArgument(Tok)) {
1051 bool MemberOfUnknownSpecialization;
1052 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1053 /*hasTemplateKeyword=*/false,
1054 Name,
1055 /*ObjectType=*/ ParsedType(),
1056 /*EnteringContext=*/false,
1057 Template,
1058 MemberOfUnknownSpecialization);
1059 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1060 // We have an id-expression that refers to a class template or
1061 // (C++0x) alias template.
1062 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1063 }
1064 }
1065 }
1066
1067 // If this is a pack expansion, build it as such.
1068 if (EllipsisLoc.isValid() && !Result.isInvalid())
1069 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1070
1071 return Result;
1072}
1073
1074/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1075///
1076/// template-argument: [C++ 14.2]
1077/// constant-expression
1078/// type-id
1079/// id-expression
1080ParsedTemplateArgument Parser::ParseTemplateArgument() {
1081 // C++ [temp.arg]p2:
1082 // In a template-argument, an ambiguity between a type-id and an
1083 // expression is resolved to a type-id, regardless of the form of
1084 // the corresponding template-parameter.
1085 //
1086 // Therefore, we initially try to parse a type-id.
1087 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1088 SourceLocation Loc = Tok.getLocation();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001089 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali65efd102013-06-08 19:39:00 +00001090 Declarator::TemplateTypeArgContext);
1091 if (TypeArg.isInvalid())
1092 return ParsedTemplateArgument();
1093
1094 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1095 TypeArg.get().getAsOpaquePtr(),
1096 Loc);
1097 }
1098
1099 // Try to parse a template template argument.
1100 {
1101 TentativeParsingAction TPA(*this);
1102
1103 ParsedTemplateArgument TemplateTemplateArgument
1104 = ParseTemplateTemplateArgument();
1105 if (!TemplateTemplateArgument.isInvalid()) {
1106 TPA.Commit();
1107 return TemplateTemplateArgument;
1108 }
1109
1110 // Revert this tentative parse to parse a non-type template argument.
1111 TPA.Revert();
1112 }
1113
1114 // Parse a non-type template argument.
1115 SourceLocation Loc = Tok.getLocation();
1116 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1117 if (ExprArg.isInvalid() || !ExprArg.get())
1118 return ParsedTemplateArgument();
1119
1120 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1121 ExprArg.release(), Loc);
1122}
1123
1124/// \brief Determine whether the current tokens can only be parsed as a
1125/// template argument list (starting with the '<') and never as a '<'
1126/// expression.
1127bool Parser::IsTemplateArgumentList(unsigned Skip) {
1128 struct AlwaysRevertAction : TentativeParsingAction {
1129 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1130 ~AlwaysRevertAction() { Revert(); }
1131 } Tentative(*this);
1132
1133 while (Skip) {
1134 ConsumeToken();
1135 --Skip;
1136 }
1137
1138 // '<'
Stephen Hines651f13c2014-04-23 16:59:28 -07001139 if (!TryConsumeToken(tok::less))
Faisal Vali65efd102013-06-08 19:39:00 +00001140 return false;
Faisal Vali65efd102013-06-08 19:39:00 +00001141
1142 // An empty template argument list.
1143 if (Tok.is(tok::greater))
1144 return true;
1145
1146 // See whether we have declaration specifiers, which indicate a type.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001147 while (isCXXDeclarationSpecifier() == TPResult::True)
Faisal Vali65efd102013-06-08 19:39:00 +00001148 ConsumeToken();
1149
1150 // If we have a '>' or a ',' then this is a template argument list.
1151 return Tok.is(tok::greater) || Tok.is(tok::comma);
1152}
1153
1154/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1155/// (C++ [temp.names]). Returns true if there was an error.
1156///
1157/// template-argument-list: [C++ 14.2]
1158/// template-argument
1159/// template-argument-list ',' template-argument
1160bool
1161Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1162 // Template argument lists are constant-evaluation contexts.
1163 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001164 ColonProtectionRAIIObject ColonProtection(*this, false);
Faisal Vali65efd102013-06-08 19:39:00 +00001165
Stephen Hines651f13c2014-04-23 16:59:28 -07001166 do {
Faisal Vali65efd102013-06-08 19:39:00 +00001167 ParsedTemplateArgument Arg = ParseTemplateArgument();
Stephen Hines651f13c2014-04-23 16:59:28 -07001168 SourceLocation EllipsisLoc;
1169 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali65efd102013-06-08 19:39:00 +00001170 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
Faisal Vali65efd102013-06-08 19:39:00 +00001171
1172 if (Arg.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00001173 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali65efd102013-06-08 19:39:00 +00001174 return true;
1175 }
1176
1177 // Save this template argument.
1178 TemplateArgs.push_back(Arg);
1179
1180 // If the next token is a comma, consume it and keep reading
1181 // arguments.
Stephen Hines651f13c2014-04-23 16:59:28 -07001182 } while (TryConsumeToken(tok::comma));
Faisal Vali65efd102013-06-08 19:39:00 +00001183
1184 return false;
1185}
1186
1187/// \brief Parse a C++ explicit template instantiation
1188/// (C++ [temp.explicit]).
1189///
1190/// explicit-instantiation:
1191/// 'extern' [opt] 'template' declaration
1192///
1193/// Note that the 'extern' is a GNU extension and C++11 feature.
1194Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1195 SourceLocation ExternLoc,
1196 SourceLocation TemplateLoc,
1197 SourceLocation &DeclEnd,
1198 AccessSpecifier AS) {
1199 // This isn't really required here.
1200 ParsingDeclRAIIObject
1201 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1202
1203 return ParseSingleDeclarationAfterTemplate(Context,
1204 ParsedTemplateInfo(ExternLoc,
1205 TemplateLoc),
1206 ParsingTemplateParams,
1207 DeclEnd, AS);
1208}
1209
1210SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1211 if (TemplateParams)
1212 return getTemplateParamsRange(TemplateParams->data(),
1213 TemplateParams->size());
1214
1215 SourceRange R(TemplateLoc);
1216 if (ExternLoc.isValid())
1217 R.setBegin(ExternLoc);
1218 return R;
1219}
1220
Richard Smithac32d902013-08-07 21:41:30 +00001221void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1222 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
Faisal Vali65efd102013-06-08 19:39:00 +00001223}
1224
1225/// \brief Late parse a C++ function template in Microsoft mode.
Richard Smithac32d902013-08-07 21:41:30 +00001226void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
David Majnemer360d23e2013-08-16 08:29:13 +00001227 if (!LPT.D)
Faisal Vali65efd102013-06-08 19:39:00 +00001228 return;
1229
1230 // Get the FunctionDecl.
Stephen Hines651f13c2014-04-23 16:59:28 -07001231 FunctionDecl *FunD = LPT.D->getAsFunction();
Faisal Vali65efd102013-06-08 19:39:00 +00001232 // Track template parameter depth.
1233 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1234
1235 // To restore the context after late parsing.
1236 Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
1237
1238 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1239
1240 // Get the list of DeclContexts to reenter.
1241 SmallVector<DeclContext*, 4> DeclContextsToReenter;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001242 DeclContext *DD = FunD;
Faisal Vali65efd102013-06-08 19:39:00 +00001243 while (DD && !DD->isTranslationUnit()) {
1244 DeclContextsToReenter.push_back(DD);
1245 DD = DD->getLexicalParent();
1246 }
1247
1248 // Reenter template scopes from outermost to innermost.
Craig Topper163fbf82013-07-08 03:55:09 +00001249 SmallVectorImpl<DeclContext *>::reverse_iterator II =
Faisal Vali65efd102013-06-08 19:39:00 +00001250 DeclContextsToReenter.rbegin();
1251 for (; II != DeclContextsToReenter.rend(); ++II) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001252 TemplateParamScopeStack.push_back(new ParseScope(this,
1253 Scope::TemplateParamScope));
1254 unsigned NumParamLists =
1255 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1256 CurTemplateDepthTracker.addDepth(NumParamLists);
1257 if (*II != FunD) {
1258 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1259 Actions.PushDeclContext(Actions.getCurScope(), *II);
Faisal Vali65efd102013-06-08 19:39:00 +00001260 }
Faisal Vali65efd102013-06-08 19:39:00 +00001261 }
Faisal Vali65efd102013-06-08 19:39:00 +00001262
Richard Smithac32d902013-08-07 21:41:30 +00001263 assert(!LPT.Toks.empty() && "Empty body!");
Faisal Vali65efd102013-06-08 19:39:00 +00001264
1265 // Append the current token at the end of the new token stream so that it
1266 // doesn't get lost.
Richard Smithac32d902013-08-07 21:41:30 +00001267 LPT.Toks.push_back(Tok);
1268 PP.EnterTokenStream(LPT.Toks.data(), LPT.Toks.size(), true, false);
Faisal Vali65efd102013-06-08 19:39:00 +00001269
1270 // Consume the previously pushed token.
1271 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1272 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1273 && "Inline method not starting with '{', ':' or 'try'");
1274
1275 // Parse the method body. Function body parsing code is similar enough
1276 // to be re-used for method bodies as well.
1277 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1278
1279 // Recreate the containing function DeclContext.
1280 Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FunD));
1281
1282 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1283
1284 if (Tok.is(tok::kw_try)) {
Richard Smithac32d902013-08-07 21:41:30 +00001285 ParseFunctionTryBlock(LPT.D, FnScope);
Faisal Vali65efd102013-06-08 19:39:00 +00001286 } else {
1287 if (Tok.is(tok::colon))
Richard Smithac32d902013-08-07 21:41:30 +00001288 ParseConstructorInitializer(LPT.D);
Faisal Vali65efd102013-06-08 19:39:00 +00001289 else
Richard Smithac32d902013-08-07 21:41:30 +00001290 Actions.ActOnDefaultCtorInitializers(LPT.D);
Faisal Vali65efd102013-06-08 19:39:00 +00001291
1292 if (Tok.is(tok::l_brace)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001293 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1294 cast<FunctionTemplateDecl>(LPT.D)
1295 ->getTemplateParameters()
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001296 ->getDepth() == TemplateParameterDepth - 1) &&
Faisal Vali65efd102013-06-08 19:39:00 +00001297 "TemplateParameterDepth should be greater than the depth of "
1298 "current template being instantiated!");
Richard Smithac32d902013-08-07 21:41:30 +00001299 ParseFunctionStatementBody(LPT.D, FnScope);
1300 Actions.UnmarkAsLateParsedTemplate(FunD);
Faisal Vali65efd102013-06-08 19:39:00 +00001301 } else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001302 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
Faisal Vali65efd102013-06-08 19:39:00 +00001303 }
1304
1305 // Exit scopes.
1306 FnScope.Exit();
Craig Topper163fbf82013-07-08 03:55:09 +00001307 SmallVectorImpl<ParseScope *>::reverse_iterator I =
Faisal Vali65efd102013-06-08 19:39:00 +00001308 TemplateParamScopeStack.rbegin();
1309 for (; I != TemplateParamScopeStack.rend(); ++I)
1310 delete *I;
Faisal Vali65efd102013-06-08 19:39:00 +00001311}
1312
1313/// \brief Lex a delayed template function for late parsing.
1314void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1315 tok::TokenKind kind = Tok.getKind();
1316 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1317 // Consume everything up to (and including) the matching right brace.
1318 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1319 }
1320
1321 // If we're in a function-try-block, we need to store all the catch blocks.
1322 if (kind == tok::kw_try) {
1323 while (Tok.is(tok::kw_catch)) {
1324 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1325 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1326 }
1327 }
1328}