blob: a8116785fdfd164c408fb81602898142837042d0 [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"
Richard Smithb0b68012015-05-11 23:09:06 +000017#include "clang/AST/ASTContext.h"
Faisal Vali6a79ca12013-06-08 19:39:00 +000018#include "clang/AST/DeclTemplate.h"
19#include "clang/Parse/ParseDiagnostic.h"
20#include "clang/Sema/DeclSpec.h"
21#include "clang/Sema/ParsedTemplate.h"
22#include "clang/Sema/Scope.h"
23using namespace clang;
24
25/// \brief Parse a template declaration, explicit instantiation, or
26/// explicit specialization.
27Decl *
28Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
29 SourceLocation &DeclEnd,
30 AccessSpecifier AS,
31 AttributeList *AccessAttrs) {
32 ObjCDeclContextSwitch ObjCDC(*this);
33
34 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
35 return ParseExplicitInstantiation(Context,
36 SourceLocation(), ConsumeToken(),
37 DeclEnd, AS);
38 }
39 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
40 AccessAttrs);
41}
42
43
44
45/// \brief Parse a template declaration or an explicit specialization.
46///
47/// Template declarations include one or more template parameter lists
48/// and either the function or class template declaration. Explicit
49/// specializations contain one or more 'template < >' prefixes
50/// followed by a (possibly templated) declaration. Since the
51/// syntactic form of both features is nearly identical, we parse all
52/// of the template headers together and let semantic analysis sort
53/// the declarations from the explicit specializations.
54///
55/// template-declaration: [C++ temp]
56/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
57///
58/// explicit-specialization: [ C++ temp.expl.spec]
59/// 'template' '<' '>' declaration
60Decl *
61Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
62 SourceLocation &DeclEnd,
63 AccessSpecifier AS,
64 AttributeList *AccessAttrs) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +000065 assert(Tok.isOneOf(tok::kw_export, tok::kw_template) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +000066 "Token does not start a template declaration.");
67
68 // Enter template-parameter scope.
69 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
70
71 // Tell the action that names should be checked in the context of
72 // the declaration to come.
73 ParsingDeclRAIIObject
74 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
75
76 // Parse multiple levels of template headers within this template
77 // parameter scope, e.g.,
78 //
79 // template<typename T>
80 // template<typename U>
81 // class A<T>::B { ... };
82 //
83 // We parse multiple levels non-recursively so that we can build a
84 // single data structure containing all of the template parameter
85 // lists to easily differentiate between the case above and:
86 //
87 // template<typename T>
88 // class A {
89 // template<typename U> class B;
90 // };
91 //
92 // In the first case, the action for declaring A<T>::B receives
93 // both template parameter lists. In the second case, the action for
94 // defining A<T>::B receives just the inner template parameter list
95 // (and retrieves the outer template parameter list from its
96 // context).
97 bool isSpecialization = true;
98 bool LastParamListWasEmpty = false;
99 TemplateParameterLists ParamLists;
100 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
101
102 do {
103 // Consume the 'export', if any.
104 SourceLocation ExportLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000105 TryConsumeToken(tok::kw_export, ExportLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000106
107 // Consume the 'template', which should be here.
108 SourceLocation TemplateLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000109 if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000110 Diag(Tok.getLocation(), diag::err_expected_template);
Craig Topper161e4db2014-05-21 06:02:52 +0000111 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000112 }
113
114 // Parse the '<' template-parameter-list '>'
115 SourceLocation LAngleLoc, RAngleLoc;
116 SmallVector<Decl*, 4> TemplateParams;
117 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
118 TemplateParams, LAngleLoc, RAngleLoc)) {
119 // Skip until the semi-colon or a }.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000120 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000121 TryConsumeToken(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000122 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000123 }
124
125 ParamLists.push_back(
126 Actions.ActOnTemplateParameterList(CurTemplateDepthTracker.getDepth(),
127 ExportLoc,
128 TemplateLoc, LAngleLoc,
129 TemplateParams.data(),
130 TemplateParams.size(), RAngleLoc));
131
132 if (!TemplateParams.empty()) {
133 isSpecialization = false;
134 ++CurTemplateDepthTracker;
135 } else {
136 LastParamListWasEmpty = true;
137 }
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000138 } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
Faisal Vali6a79ca12013-06-08 19:39:00 +0000139
140 // Parse the actual template declaration.
141 return ParseSingleDeclarationAfterTemplate(Context,
142 ParsedTemplateInfo(&ParamLists,
143 isSpecialization,
144 LastParamListWasEmpty),
145 ParsingTemplateParams,
146 DeclEnd, AS, AccessAttrs);
147}
148
149/// \brief Parse a single declaration that declares a template,
150/// template specialization, or explicit instantiation of a template.
151///
152/// \param DeclEnd will receive the source location of the last token
153/// within this declaration.
154///
155/// \param AS the access specifier associated with this
156/// declaration. Will be AS_none for namespace-scope declarations.
157///
158/// \returns the new declaration.
159Decl *
160Parser::ParseSingleDeclarationAfterTemplate(
161 unsigned Context,
162 const ParsedTemplateInfo &TemplateInfo,
163 ParsingDeclRAIIObject &DiagsFromTParams,
164 SourceLocation &DeclEnd,
165 AccessSpecifier AS,
166 AttributeList *AccessAttrs) {
167 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
168 "Template information required");
169
Aaron Ballmane7c544d2014-08-04 20:28:35 +0000170 if (Tok.is(tok::kw_static_assert)) {
171 // A static_assert declaration may not be templated.
172 Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
173 << TemplateInfo.getSourceRange();
174 // Parse the static_assert declaration to improve error recovery.
175 return ParseStaticAssertDeclaration(DeclEnd);
176 }
177
Faisal Vali6a79ca12013-06-08 19:39:00 +0000178 if (Context == Declarator::MemberContext) {
179 // We are parsing a member template.
180 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
181 &DiagsFromTParams);
Craig Topper161e4db2014-05-21 06:02:52 +0000182 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000183 }
184
185 ParsedAttributesWithRange prefixAttrs(AttrFactory);
186 MaybeParseCXX11Attributes(prefixAttrs);
187
188 if (Tok.is(tok::kw_using))
189 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
190 prefixAttrs);
191
192 // Parse the declaration specifiers, stealing any diagnostics from
193 // the template parameters.
194 ParsingDeclSpec DS(*this, &DiagsFromTParams);
195
196 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
197 getDeclSpecContextFromDeclaratorContext(Context));
198
199 if (Tok.is(tok::semi)) {
200 ProhibitAttributes(prefixAttrs);
201 DeclEnd = ConsumeToken();
202 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
203 getCurScope(), AS, DS,
204 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
205 : MultiTemplateParamsArg(),
206 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation);
207 DS.complete(Decl);
208 return Decl;
209 }
210
211 // Move the attributes from the prefix into the DS.
212 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
213 ProhibitAttributes(prefixAttrs);
214 else
215 DS.takeAttributesFrom(prefixAttrs);
216
217 // Parse the declarator.
218 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
219 ParseDeclarator(DeclaratorInfo);
220 // Error parsing the declarator?
221 if (!DeclaratorInfo.hasName()) {
222 // If so, skip until the semi-colon or a }.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000223 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000224 if (Tok.is(tok::semi))
225 ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000226 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000227 }
228
229 LateParsedAttrList LateParsedAttrs(true);
230 if (DeclaratorInfo.isFunctionDeclarator())
231 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
232
233 if (DeclaratorInfo.isFunctionDeclarator() &&
234 isStartOfFunctionDefinition(DeclaratorInfo)) {
Reid Klecknerd61a3112014-12-15 23:16:32 +0000235
236 // Function definitions are only allowed at file scope and in C++ classes.
237 // The C++ inline method definition case is handled elsewhere, so we only
238 // need to handle the file scope definition case.
239 if (Context != Declarator::FileContext) {
240 Diag(Tok, diag::err_function_definition_not_allowed);
241 SkipMalformedDecl();
242 return nullptr;
243 }
244
Faisal Vali6a79ca12013-06-08 19:39:00 +0000245 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
246 // Recover by ignoring the 'typedef'. This was probably supposed to be
247 // the 'typename' keyword, which we should have already suggested adding
248 // if it's appropriate.
249 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
250 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
251 DS.ClearStorageClassSpecs();
252 }
Larisse Voufo725de3e2013-06-21 00:08:46 +0000253
254 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
255 if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
256 // If the declarator-id is not a template-id, issue a diagnostic and
257 // recover by ignoring the 'template' keyword.
258 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000259 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
260 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000261 } else {
262 SourceLocation LAngleLoc
263 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000264 Diag(DeclaratorInfo.getIdentifierLoc(),
Larisse Voufo725de3e2013-06-21 00:08:46 +0000265 diag::err_explicit_instantiation_with_definition)
Larisse Voufo39a1e502013-08-06 01:03:05 +0000266 << SourceRange(TemplateInfo.TemplateLoc)
267 << FixItHint::CreateInsertion(LAngleLoc, "<>");
Larisse Voufo725de3e2013-06-21 00:08:46 +0000268
Larisse Voufo39a1e502013-08-06 01:03:05 +0000269 // Recover as if it were an explicit specialization.
Larisse Voufob9bbaba2013-06-22 13:56:11 +0000270 TemplateParameterLists FakedParamLists;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000271 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper161e4db2014-05-21 06:02:52 +0000272 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr,
273 0, LAngleLoc));
Larisse Voufo725de3e2013-06-21 00:08:46 +0000274
Larisse Voufo39a1e502013-08-06 01:03:05 +0000275 return ParseFunctionDefinition(
276 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
277 /*isSpecialization=*/true,
278 /*LastParamListWasEmpty=*/true),
279 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000280 }
281 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000282 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
Larisse Voufo39a1e502013-08-06 01:03:05 +0000283 &LateParsedAttrs);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000284 }
285
286 // Parse this declaration.
287 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
288 TemplateInfo);
289
290 if (Tok.is(tok::comma)) {
291 Diag(Tok, diag::err_multiple_template_declarators)
292 << (int)TemplateInfo.Kind;
Alexey Bataevee6507d2013-11-18 08:17:37 +0000293 SkipUntil(tok::semi);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000294 return ThisDecl;
295 }
296
297 // Eat the semi colon after the declaration.
298 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
299 if (LateParsedAttrs.size() > 0)
300 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
301 DeclaratorInfo.complete(ThisDecl);
302 return ThisDecl;
303}
304
305/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
306/// angle brackets. Depth is the depth of this template-parameter-list, which
307/// is the number of template headers directly enclosing this template header.
308/// TemplateParams is the current list of template parameters we're building.
309/// The template parameter we parse will be added to this list. LAngleLoc and
310/// RAngleLoc will receive the positions of the '<' and '>', respectively,
311/// that enclose this template parameter list.
312///
313/// \returns true if an error occurred, false otherwise.
314bool Parser::ParseTemplateParameters(unsigned Depth,
315 SmallVectorImpl<Decl*> &TemplateParams,
316 SourceLocation &LAngleLoc,
317 SourceLocation &RAngleLoc) {
318 // Get the template parameter list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000319 if (!TryConsumeToken(tok::less, LAngleLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000320 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
321 return true;
322 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000323
324 // Try to parse the template parameter list.
325 bool Failed = false;
326 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
327 Failed = ParseTemplateParameterList(Depth, TemplateParams);
328
329 if (Tok.is(tok::greatergreater)) {
330 // No diagnostic required here: a template-parameter-list can only be
331 // followed by a declaration or, for a template template parameter, the
332 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
333 // This matters for elegant diagnosis of:
334 // template<template<typename>> struct S;
335 Tok.setKind(tok::greater);
336 RAngleLoc = Tok.getLocation();
337 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
Alp Toker383d2c42014-01-01 03:08:43 +0000338 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
339 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000340 return true;
341 }
342 return false;
343}
344
345/// ParseTemplateParameterList - Parse a template parameter list. If
346/// the parsing fails badly (i.e., closing bracket was left out), this
347/// will try to put the token stream in a reasonable position (closing
348/// a statement, etc.) and return false.
349///
350/// template-parameter-list: [C++ temp]
351/// template-parameter
352/// template-parameter-list ',' template-parameter
353bool
354Parser::ParseTemplateParameterList(unsigned Depth,
355 SmallVectorImpl<Decl*> &TemplateParams) {
356 while (1) {
357 if (Decl *TmpParam
358 = ParseTemplateParameter(Depth, TemplateParams.size())) {
359 TemplateParams.push_back(TmpParam);
360 } else {
361 // If we failed to parse a template parameter, skip until we find
362 // a comma or closing brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000363 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
364 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000365 }
366
367 // Did we find a comma or the end of the template parameter list?
368 if (Tok.is(tok::comma)) {
369 ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000370 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000371 // Don't consume this... that's done by template parser.
372 break;
373 } else {
374 // Somebody probably forgot to close the template. Skip ahead and
375 // try to get out of the expression. This error is currently
376 // subsumed by whatever goes on in ParseTemplateParameter.
377 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000378 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
379 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000380 return false;
381 }
382 }
383 return true;
384}
385
386/// \brief Determine whether the parser is at the start of a template
387/// type parameter.
388bool Parser::isStartOfTemplateTypeParameter() {
389 if (Tok.is(tok::kw_class)) {
390 // "class" may be the start of an elaborated-type-specifier or a
391 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
392 switch (NextToken().getKind()) {
393 case tok::equal:
394 case tok::comma:
395 case tok::greater:
396 case tok::greatergreater:
397 case tok::ellipsis:
398 return true;
399
400 case tok::identifier:
401 // This may be either a type-parameter or an elaborated-type-specifier.
402 // We have to look further.
403 break;
404
405 default:
406 return false;
407 }
408
409 switch (GetLookAheadToken(2).getKind()) {
410 case tok::equal:
411 case tok::comma:
412 case tok::greater:
413 case tok::greatergreater:
414 return true;
415
416 default:
417 return false;
418 }
419 }
420
421 if (Tok.isNot(tok::kw_typename))
422 return false;
423
424 // C++ [temp.param]p2:
425 // There is no semantic difference between class and typename in a
426 // template-parameter. typename followed by an unqualified-id
427 // names a template type parameter. typename followed by a
428 // qualified-id denotes the type in a non-type
429 // parameter-declaration.
430 Token Next = NextToken();
431
432 // If we have an identifier, skip over it.
433 if (Next.getKind() == tok::identifier)
434 Next = GetLookAheadToken(2);
435
436 switch (Next.getKind()) {
437 case tok::equal:
438 case tok::comma:
439 case tok::greater:
440 case tok::greatergreater:
441 case tok::ellipsis:
442 return true;
443
444 default:
445 return false;
446 }
447}
448
449/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
450///
451/// template-parameter: [C++ temp.param]
452/// type-parameter
453/// parameter-declaration
454///
455/// type-parameter: (see below)
456/// 'class' ...[opt] identifier[opt]
457/// 'class' identifier[opt] '=' type-id
458/// 'typename' ...[opt] identifier[opt]
459/// 'typename' identifier[opt] '=' type-id
460/// 'template' '<' template-parameter-list '>'
461/// 'class' ...[opt] identifier[opt]
462/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
463/// = id-expression
464Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
465 if (isStartOfTemplateTypeParameter())
466 return ParseTypeParameter(Depth, Position);
467
468 if (Tok.is(tok::kw_template))
469 return ParseTemplateTemplateParameter(Depth, Position);
470
471 // If it's none of the above, then it must be a parameter declaration.
472 // NOTE: This will pick up errors in the closure of the template parameter
473 // list (e.g., template < ; Check here to implement >> style closures.
474 return ParseNonTypeTemplateParameter(Depth, Position);
475}
476
477/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
478/// Other kinds of template parameters are parsed in
479/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
480///
481/// type-parameter: [C++ temp.param]
482/// 'class' ...[opt][C++0x] identifier[opt]
483/// 'class' identifier[opt] '=' type-id
484/// 'typename' ...[opt][C++0x] identifier[opt]
485/// 'typename' identifier[opt] '=' type-id
486Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000487 assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +0000488 "A type-parameter starts with 'class' or 'typename'");
489
490 // Consume the 'class' or 'typename' keyword.
491 bool TypenameKeyword = Tok.is(tok::kw_typename);
492 SourceLocation KeyLoc = ConsumeToken();
493
494 // Grab the ellipsis (if given).
Faisal Vali6a79ca12013-06-08 19:39:00 +0000495 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000496 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000497 Diag(EllipsisLoc,
498 getLangOpts().CPlusPlus11
499 ? diag::warn_cxx98_compat_variadic_templates
500 : diag::ext_variadic_templates);
501 }
502
503 // Grab the template parameter name (if given)
504 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000505 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000506 if (Tok.is(tok::identifier)) {
507 ParamName = Tok.getIdentifierInfo();
508 NameLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000509 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
510 tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000511 // Unnamed template parameter. Don't have to do anything here, just
512 // don't consume this token.
513 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000514 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000515 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000516 }
517
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000518 // Recover from misplaced ellipsis.
519 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
520 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
521 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
522
Faisal Vali6a79ca12013-06-08 19:39:00 +0000523 // Grab a default argument (if available).
524 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
525 // we introduce the type parameter into the local scope.
526 SourceLocation EqualLoc;
527 ParsedType DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000528 if (TryConsumeToken(tok::equal, EqualLoc))
Craig Topper161e4db2014-05-21 06:02:52 +0000529 DefaultArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000530 Declarator::TemplateTypeArgContext).get();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000531
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000532 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
533 KeyLoc, ParamName, NameLoc, Depth, Position,
534 EqualLoc, DefaultArg);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000535}
536
537/// ParseTemplateTemplateParameter - Handle the parsing of template
538/// template parameters.
539///
540/// type-parameter: [C++ temp.param]
Richard Smith78e1ca62014-06-16 15:51:22 +0000541/// 'template' '<' template-parameter-list '>' type-parameter-key
Faisal Vali6a79ca12013-06-08 19:39:00 +0000542/// ...[opt] identifier[opt]
Richard Smith78e1ca62014-06-16 15:51:22 +0000543/// 'template' '<' template-parameter-list '>' type-parameter-key
544/// identifier[opt] = id-expression
545/// type-parameter-key:
546/// 'class'
547/// 'typename' [C++1z]
Faisal Vali6a79ca12013-06-08 19:39:00 +0000548Decl *
549Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
550 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
551
552 // Handle the template <...> part.
553 SourceLocation TemplateLoc = ConsumeToken();
554 SmallVector<Decl*,8> TemplateParams;
555 SourceLocation LAngleLoc, RAngleLoc;
556 {
557 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
558 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
559 RAngleLoc)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000560 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000561 }
562 }
563
Richard Smith78e1ca62014-06-16 15:51:22 +0000564 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000565 // Generate a meaningful error if the user forgot to put class before the
566 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
Richard Smith78e1ca62014-06-16 15:51:22 +0000567 // or greater appear immediately or after 'struct'. In the latter case,
568 // replace the keyword with 'class'.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000569 if (!TryConsumeToken(tok::kw_class)) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000570 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
Richard Smith78e1ca62014-06-16 15:51:22 +0000571 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
572 if (Tok.is(tok::kw_typename)) {
573 Diag(Tok.getLocation(),
574 getLangOpts().CPlusPlus1z
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000575 ? diag::warn_cxx14_compat_template_template_param_typename
Richard Smith78e1ca62014-06-16 15:51:22 +0000576 : diag::ext_template_template_param_typename)
577 << (!getLangOpts().CPlusPlus1z
578 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
579 : FixItHint());
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000580 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
581 tok::greatergreater, tok::ellipsis)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000582 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
583 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
584 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
Richard Smith78e1ca62014-06-16 15:51:22 +0000585 } else
Faisal Vali6a79ca12013-06-08 19:39:00 +0000586 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
587
588 if (Replace)
589 ConsumeToken();
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000590 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000591
592 // Parse the ellipsis, if given.
593 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000594 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000595 Diag(EllipsisLoc,
596 getLangOpts().CPlusPlus11
597 ? diag::warn_cxx98_compat_variadic_templates
598 : diag::ext_variadic_templates);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000599
600 // Get the identifier, if given.
601 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000602 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000603 if (Tok.is(tok::identifier)) {
604 ParamName = Tok.getIdentifierInfo();
605 NameLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000606 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
607 tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000608 // Unnamed template parameter. Don't have to do anything here, just
609 // don't consume this token.
610 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000611 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000612 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000613 }
614
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000615 // Recover from misplaced ellipsis.
616 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
617 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
618 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
619
Faisal Vali6a79ca12013-06-08 19:39:00 +0000620 TemplateParameterList *ParamList =
621 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
622 TemplateLoc, LAngleLoc,
623 TemplateParams.data(),
624 TemplateParams.size(),
625 RAngleLoc);
626
627 // Grab a default argument (if available).
628 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
629 // we introduce the template parameter into the local scope.
630 SourceLocation EqualLoc;
631 ParsedTemplateArgument DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000632 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000633 DefaultArg = ParseTemplateTemplateArgument();
634 if (DefaultArg.isInvalid()) {
635 Diag(Tok.getLocation(),
636 diag::err_default_template_template_parameter_not_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000637 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
638 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000639 }
640 }
641
642 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
643 ParamList, EllipsisLoc,
644 ParamName, NameLoc, Depth,
645 Position, EqualLoc, DefaultArg);
646}
647
648/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
649/// template parameters (e.g., in "template<int Size> class array;").
650///
651/// template-parameter:
652/// ...
653/// parameter-declaration
654Decl *
655Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
656 // Parse the declaration-specifiers (i.e., the type).
657 // FIXME: The type should probably be restricted in some way... Not all
658 // declarators (parts of declarators?) are accepted for parameters.
659 DeclSpec DS(AttrFactory);
660 ParseDeclarationSpecifiers(DS);
661
662 // Parse this as a typename.
663 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
664 ParseDeclarator(ParamDecl);
665 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
666 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
Craig Topper161e4db2014-05-21 06:02:52 +0000667 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000668 }
669
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000670 // Recover from misplaced ellipsis.
671 SourceLocation EllipsisLoc;
672 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
673 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
674
Faisal Vali6a79ca12013-06-08 19:39:00 +0000675 // If there is a default value, parse it.
676 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
677 // we introduce the template parameter into the local scope.
678 SourceLocation EqualLoc;
679 ExprResult DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000680 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000681 // C++ [temp.param]p15:
682 // When parsing a default template-argument for a non-type
683 // template-parameter, the first non-nested > is taken as the
684 // end of the template-parameter-list rather than a greater-than
685 // operator.
686 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
687 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
688
Kaelyn Takata999dd852014-12-02 23:32:20 +0000689 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000690 if (DefaultArg.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +0000691 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000692 }
693
694 // Create the parameter.
695 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
696 Depth, Position, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000697 DefaultArg.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000698}
699
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000700void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
701 SourceLocation CorrectLoc,
702 bool AlreadyHasEllipsis,
703 bool IdentifierHasName) {
704 FixItHint Insertion;
705 if (!AlreadyHasEllipsis)
706 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
707 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
708 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
709 << !IdentifierHasName;
710}
711
712void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
713 Declarator &D) {
714 assert(EllipsisLoc.isValid());
715 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
716 if (!AlreadyHasEllipsis)
717 D.setEllipsisLoc(EllipsisLoc);
718 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
719 AlreadyHasEllipsis, D.hasName());
720}
721
Faisal Vali6a79ca12013-06-08 19:39:00 +0000722/// \brief Parses a '>' at the end of a template list.
723///
724/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
725/// to determine if these tokens were supposed to be a '>' followed by
726/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
727///
728/// \param RAngleLoc the location of the consumed '>'.
729///
730/// \param ConsumeLastToken if true, the '>' is not consumed.
Serge Pavlovb716b3c2013-08-10 05:54:47 +0000731///
732/// \returns true, if current token does not start with '>', false otherwise.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000733bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
734 bool ConsumeLastToken) {
735 // What will be left once we've consumed the '>'.
736 tok::TokenKind RemainingToken;
737 const char *ReplacementStr = "> >";
738
739 switch (Tok.getKind()) {
740 default:
Alp Toker383d2c42014-01-01 03:08:43 +0000741 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000742 return true;
743
744 case tok::greater:
745 // Determine the location of the '>' token. Only consume this token
746 // if the caller asked us to.
747 RAngleLoc = Tok.getLocation();
748 if (ConsumeLastToken)
749 ConsumeToken();
750 return false;
751
752 case tok::greatergreater:
753 RemainingToken = tok::greater;
754 break;
755
756 case tok::greatergreatergreater:
757 RemainingToken = tok::greatergreater;
758 break;
759
760 case tok::greaterequal:
761 RemainingToken = tok::equal;
762 ReplacementStr = "> =";
763 break;
764
765 case tok::greatergreaterequal:
766 RemainingToken = tok::greaterequal;
767 break;
768 }
769
770 // This template-id is terminated by a token which starts with a '>'. Outside
771 // C++11, this is now error recovery, and in C++11, this is error recovery if
Eli Bendersky36a61932014-06-20 13:09:59 +0000772 // the token isn't '>>' or '>>>'.
773 // '>>>' is for CUDA, where this sequence of characters is parsed into
774 // tok::greatergreatergreater, rather than two separate tokens.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000775
776 RAngleLoc = Tok.getLocation();
777
778 // The source range of the '>>' or '>=' at the start of the token.
779 CharSourceRange ReplacementRange =
780 CharSourceRange::getCharRange(RAngleLoc,
781 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
782 getLangOpts()));
783
784 // A hint to put a space between the '>>'s. In order to make the hint as
785 // clear as possible, we include the characters either side of the space in
786 // the replacement, rather than just inserting a space at SecondCharLoc.
787 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
788 ReplacementStr);
789
790 // A hint to put another space after the token, if it would otherwise be
791 // lexed differently.
792 FixItHint Hint2;
793 Token Next = NextToken();
794 if ((RemainingToken == tok::greater ||
795 RemainingToken == tok::greatergreater) &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000796 Next.isOneOf(tok::greater, tok::greatergreater,
797 tok::greatergreatergreater, tok::equal, tok::greaterequal,
798 tok::greatergreaterequal, tok::equalequal) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +0000799 areTokensAdjacent(Tok, Next))
800 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
801
802 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
Eli Bendersky36a61932014-06-20 13:09:59 +0000803 if (getLangOpts().CPlusPlus11 &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000804 Tok.isOneOf(tok::greatergreater, tok::greatergreatergreater))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000805 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
806 else if (Tok.is(tok::greaterequal))
807 DiagId = diag::err_right_angle_bracket_equal_needs_space;
808 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
809
810 // Strip the initial '>' from the token.
811 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
812 areTokensAdjacent(Tok, Next)) {
813 // Join two adjacent '=' tokens into one, for cases like:
814 // void (*p)() = f<int>;
815 // return f<int>==p;
816 ConsumeToken();
817 Tok.setKind(tok::equalequal);
818 Tok.setLength(Tok.getLength() + 1);
819 } else {
820 Tok.setKind(RemainingToken);
821 Tok.setLength(Tok.getLength() - 1);
822 }
823 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
824 PP.getSourceManager(),
825 getLangOpts()));
826
827 if (!ConsumeLastToken) {
828 // Since we're not supposed to consume the '>' token, we need to push
829 // this token and revert the current token back to the '>'.
830 PP.EnterToken(Tok);
831 Tok.setKind(tok::greater);
832 Tok.setLength(1);
833 Tok.setLocation(RAngleLoc);
834 }
835 return false;
836}
837
838
839/// \brief Parses a template-id that after the template name has
840/// already been parsed.
841///
842/// This routine takes care of parsing the enclosed template argument
843/// list ('<' template-parameter-list [opt] '>') and placing the
844/// results into a form that can be transferred to semantic analysis.
845///
846/// \param Template the template declaration produced by isTemplateName
847///
848/// \param TemplateNameLoc the source location of the template name
849///
850/// \param SS if non-NULL, the nested-name-specifier preceding the
851/// template name.
852///
853/// \param ConsumeLastToken if true, then we will consume the last
854/// token that forms the template-id. Otherwise, we will leave the
855/// last token in the stream (e.g., so that it can be replaced with an
856/// annotation token).
857bool
858Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
859 SourceLocation TemplateNameLoc,
860 const CXXScopeSpec &SS,
861 bool ConsumeLastToken,
862 SourceLocation &LAngleLoc,
863 TemplateArgList &TemplateArgs,
864 SourceLocation &RAngleLoc) {
865 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
866
867 // Consume the '<'.
868 LAngleLoc = ConsumeToken();
869
870 // Parse the optional template-argument-list.
871 bool Invalid = false;
872 {
873 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
874 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
875 Invalid = ParseTemplateArgumentList(TemplateArgs);
876
877 if (Invalid) {
878 // Try to find the closing '>'.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000879 if (ConsumeLastToken)
880 SkipUntil(tok::greater, StopAtSemi);
881 else
882 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000883 return true;
884 }
885 }
886
887 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken);
888}
889
890/// \brief Replace the tokens that form a simple-template-id with an
891/// annotation token containing the complete template-id.
892///
893/// The first token in the stream must be the name of a template that
894/// is followed by a '<'. This routine will parse the complete
895/// simple-template-id and replace the tokens with a single annotation
896/// token with one of two different kinds: if the template-id names a
897/// type (and \p AllowTypeAnnotation is true), the annotation token is
898/// a type annotation that includes the optional nested-name-specifier
899/// (\p SS). Otherwise, the annotation token is a template-id
900/// annotation that does not include the optional
901/// nested-name-specifier.
902///
903/// \param Template the declaration of the template named by the first
904/// token (an identifier), as returned from \c Action::isTemplateName().
905///
906/// \param TNK the kind of template that \p Template
907/// refers to, as returned from \c Action::isTemplateName().
908///
909/// \param SS if non-NULL, the nested-name-specifier that precedes
910/// this template name.
911///
912/// \param TemplateKWLoc if valid, specifies that this template-id
913/// annotation was preceded by the 'template' keyword and gives the
914/// location of that keyword. If invalid (the default), then this
915/// template-id was not preceded by a 'template' keyword.
916///
917/// \param AllowTypeAnnotation if true (the default), then a
918/// simple-template-id that refers to a class template, template
919/// template parameter, or other template that produces a type will be
920/// replaced with a type annotation token. Otherwise, the
921/// simple-template-id is always replaced with a template-id
922/// annotation token.
923///
924/// If an unrecoverable parse error occurs and no annotation token can be
925/// formed, this function returns true.
926///
927bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
928 CXXScopeSpec &SS,
929 SourceLocation TemplateKWLoc,
930 UnqualifiedId &TemplateName,
931 bool AllowTypeAnnotation) {
932 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
933 assert(Template && Tok.is(tok::less) &&
934 "Parser isn't at the beginning of a template-id");
935
936 // Consume the template-name.
937 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
938
939 // Parse the enclosed template argument list.
940 SourceLocation LAngleLoc, RAngleLoc;
941 TemplateArgList TemplateArgs;
942 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
943 TemplateNameLoc,
944 SS, false, LAngleLoc,
945 TemplateArgs,
946 RAngleLoc);
947
948 if (Invalid) {
949 // If we failed to parse the template ID but skipped ahead to a >, we're not
950 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000951 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000952 return true;
953 }
954
955 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
956
957 // Build the annotation token.
958 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
959 TypeResult Type
960 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
961 Template, TemplateNameLoc,
962 LAngleLoc, TemplateArgsPtr, RAngleLoc);
963 if (Type.isInvalid()) {
964 // If we failed to parse the template ID but skipped ahead to a >, we're not
965 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000966 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000967 return true;
968 }
969
970 Tok.setKind(tok::annot_typename);
971 setTypeAnnotation(Tok, Type.get());
972 if (SS.isNotEmpty())
973 Tok.setLocation(SS.getBeginLoc());
974 else if (TemplateKWLoc.isValid())
975 Tok.setLocation(TemplateKWLoc);
976 else
977 Tok.setLocation(TemplateNameLoc);
978 } else {
979 // Build a template-id annotation token that can be processed
980 // later.
981 Tok.setKind(tok::annot_template_id);
982 TemplateIdAnnotation *TemplateId
983 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
984 TemplateId->TemplateNameLoc = TemplateNameLoc;
985 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
986 TemplateId->Name = TemplateName.Identifier;
987 TemplateId->Operator = OO_None;
988 } else {
Craig Topper161e4db2014-05-21 06:02:52 +0000989 TemplateId->Name = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000990 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
991 }
992 TemplateId->SS = SS;
993 TemplateId->TemplateKWLoc = TemplateKWLoc;
994 TemplateId->Template = Template;
995 TemplateId->Kind = TNK;
996 TemplateId->LAngleLoc = LAngleLoc;
997 TemplateId->RAngleLoc = RAngleLoc;
998 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
999 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
1000 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
1001 Tok.setAnnotationValue(TemplateId);
1002 if (TemplateKWLoc.isValid())
1003 Tok.setLocation(TemplateKWLoc);
1004 else
1005 Tok.setLocation(TemplateNameLoc);
1006 }
1007
1008 // Common fields for the annotation token
1009 Tok.setAnnotationEndLoc(RAngleLoc);
1010
1011 // In case the tokens were cached, have Preprocessor replace them with the
1012 // annotation token.
1013 PP.AnnotateCachedTokens(Tok);
1014 return false;
1015}
1016
1017/// \brief Replaces a template-id annotation token with a type
1018/// annotation token.
1019///
1020/// If there was a failure when forming the type from the template-id,
1021/// a type annotation token will still be created, but will have a
1022/// NULL type pointer to signify an error.
1023void Parser::AnnotateTemplateIdTokenAsType() {
1024 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1025
1026 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1027 assert((TemplateId->Kind == TNK_Type_template ||
1028 TemplateId->Kind == TNK_Dependent_template_name) &&
1029 "Only works for type and dependent templates");
1030
1031 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1032 TemplateId->NumArgs);
1033
1034 TypeResult Type
1035 = Actions.ActOnTemplateIdType(TemplateId->SS,
1036 TemplateId->TemplateKWLoc,
1037 TemplateId->Template,
1038 TemplateId->TemplateNameLoc,
1039 TemplateId->LAngleLoc,
1040 TemplateArgsPtr,
1041 TemplateId->RAngleLoc);
1042 // Create the new "type" annotation token.
1043 Tok.setKind(tok::annot_typename);
1044 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
1045 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1046 Tok.setLocation(TemplateId->SS.getBeginLoc());
1047 // End location stays the same
1048
1049 // Replace the template-id annotation token, and possible the scope-specifier
1050 // that precedes it, with the typename annotation token.
1051 PP.AnnotateCachedTokens(Tok);
1052}
1053
1054/// \brief Determine whether the given token can end a template argument.
1055static bool isEndOfTemplateArgument(Token Tok) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001056 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001057}
1058
1059/// \brief Parse a C++ template template argument.
1060ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1061 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1062 !Tok.is(tok::annot_cxxscope))
1063 return ParsedTemplateArgument();
1064
1065 // C++0x [temp.arg.template]p1:
1066 // A template-argument for a template template-parameter shall be the name
1067 // of a class template or an alias template, expressed as id-expression.
1068 //
1069 // We parse an id-expression that refers to a class template or alias
1070 // template. The grammar we parse is:
1071 //
1072 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1073 //
1074 // followed by a token that terminates a template argument, such as ',',
1075 // '>', or (in some cases) '>>'.
1076 CXXScopeSpec SS; // nested-name-specifier, if present
1077 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1078 /*EnteringContext=*/false);
1079
1080 ParsedTemplateArgument Result;
1081 SourceLocation EllipsisLoc;
1082 if (SS.isSet() && Tok.is(tok::kw_template)) {
1083 // Parse the optional 'template' keyword following the
1084 // nested-name-specifier.
1085 SourceLocation TemplateKWLoc = ConsumeToken();
1086
1087 if (Tok.is(tok::identifier)) {
1088 // We appear to have a dependent template name.
1089 UnqualifiedId Name;
1090 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1091 ConsumeToken(); // the identifier
Alp Toker094e5212014-01-05 03:27:11 +00001092
1093 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1094
Faisal Vali6a79ca12013-06-08 19:39:00 +00001095 // If the next token signals the end of a template argument,
1096 // then we have a dependent template name that could be a template
1097 // template argument.
1098 TemplateTy Template;
1099 if (isEndOfTemplateArgument(Tok) &&
1100 Actions.ActOnDependentTemplateName(getCurScope(),
1101 SS, TemplateKWLoc, Name,
1102 /*ObjectType=*/ ParsedType(),
1103 /*EnteringContext=*/false,
1104 Template))
1105 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1106 }
1107 } else if (Tok.is(tok::identifier)) {
1108 // We may have a (non-dependent) template name.
1109 TemplateTy Template;
1110 UnqualifiedId Name;
1111 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1112 ConsumeToken(); // the identifier
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001113
1114 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001115
1116 if (isEndOfTemplateArgument(Tok)) {
1117 bool MemberOfUnknownSpecialization;
1118 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1119 /*hasTemplateKeyword=*/false,
1120 Name,
1121 /*ObjectType=*/ ParsedType(),
1122 /*EnteringContext=*/false,
1123 Template,
1124 MemberOfUnknownSpecialization);
1125 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1126 // We have an id-expression that refers to a class template or
1127 // (C++0x) alias template.
1128 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1129 }
1130 }
1131 }
1132
1133 // If this is a pack expansion, build it as such.
1134 if (EllipsisLoc.isValid() && !Result.isInvalid())
1135 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1136
1137 return Result;
1138}
1139
1140/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1141///
1142/// template-argument: [C++ 14.2]
1143/// constant-expression
1144/// type-id
1145/// id-expression
1146ParsedTemplateArgument Parser::ParseTemplateArgument() {
1147 // C++ [temp.arg]p2:
1148 // In a template-argument, an ambiguity between a type-id and an
1149 // expression is resolved to a type-id, regardless of the form of
1150 // the corresponding template-parameter.
1151 //
1152 // Therefore, we initially try to parse a type-id.
1153 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1154 SourceLocation Loc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00001155 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001156 Declarator::TemplateTypeArgContext);
1157 if (TypeArg.isInvalid())
1158 return ParsedTemplateArgument();
1159
1160 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1161 TypeArg.get().getAsOpaquePtr(),
1162 Loc);
1163 }
1164
1165 // Try to parse a template template argument.
1166 {
1167 TentativeParsingAction TPA(*this);
1168
1169 ParsedTemplateArgument TemplateTemplateArgument
1170 = ParseTemplateTemplateArgument();
1171 if (!TemplateTemplateArgument.isInvalid()) {
1172 TPA.Commit();
1173 return TemplateTemplateArgument;
1174 }
1175
1176 // Revert this tentative parse to parse a non-type template argument.
1177 TPA.Revert();
1178 }
1179
1180 // Parse a non-type template argument.
1181 SourceLocation Loc = Tok.getLocation();
1182 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1183 if (ExprArg.isInvalid() || !ExprArg.get())
1184 return ParsedTemplateArgument();
1185
1186 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001187 ExprArg.get(), Loc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001188}
1189
1190/// \brief Determine whether the current tokens can only be parsed as a
1191/// template argument list (starting with the '<') and never as a '<'
1192/// expression.
1193bool Parser::IsTemplateArgumentList(unsigned Skip) {
1194 struct AlwaysRevertAction : TentativeParsingAction {
1195 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1196 ~AlwaysRevertAction() { Revert(); }
1197 } Tentative(*this);
1198
1199 while (Skip) {
1200 ConsumeToken();
1201 --Skip;
1202 }
1203
1204 // '<'
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001205 if (!TryConsumeToken(tok::less))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001206 return false;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001207
1208 // An empty template argument list.
1209 if (Tok.is(tok::greater))
1210 return true;
1211
1212 // See whether we have declaration specifiers, which indicate a type.
Richard Smithee390432014-05-16 01:56:53 +00001213 while (isCXXDeclarationSpecifier() == TPResult::True)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001214 ConsumeToken();
1215
1216 // If we have a '>' or a ',' then this is a template argument list.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001217 return Tok.isOneOf(tok::greater, tok::comma);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001218}
1219
1220/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1221/// (C++ [temp.names]). Returns true if there was an error.
1222///
1223/// template-argument-list: [C++ 14.2]
1224/// template-argument
1225/// template-argument-list ',' template-argument
1226bool
1227Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1228 // Template argument lists are constant-evaluation contexts.
1229 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +00001230 ColonProtectionRAIIObject ColonProtection(*this, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001231
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001232 do {
Faisal Vali6a79ca12013-06-08 19:39:00 +00001233 ParsedTemplateArgument Arg = ParseTemplateArgument();
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001234 SourceLocation EllipsisLoc;
1235 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001236 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001237
1238 if (Arg.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001239 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001240 return true;
1241 }
1242
1243 // Save this template argument.
1244 TemplateArgs.push_back(Arg);
1245
1246 // If the next token is a comma, consume it and keep reading
1247 // arguments.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001248 } while (TryConsumeToken(tok::comma));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001249
1250 return false;
1251}
1252
1253/// \brief Parse a C++ explicit template instantiation
1254/// (C++ [temp.explicit]).
1255///
1256/// explicit-instantiation:
1257/// 'extern' [opt] 'template' declaration
1258///
1259/// Note that the 'extern' is a GNU extension and C++11 feature.
1260Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1261 SourceLocation ExternLoc,
1262 SourceLocation TemplateLoc,
1263 SourceLocation &DeclEnd,
1264 AccessSpecifier AS) {
1265 // This isn't really required here.
1266 ParsingDeclRAIIObject
1267 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1268
1269 return ParseSingleDeclarationAfterTemplate(Context,
1270 ParsedTemplateInfo(ExternLoc,
1271 TemplateLoc),
1272 ParsingTemplateParams,
1273 DeclEnd, AS);
1274}
1275
1276SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1277 if (TemplateParams)
1278 return getTemplateParamsRange(TemplateParams->data(),
1279 TemplateParams->size());
1280
1281 SourceRange R(TemplateLoc);
1282 if (ExternLoc.isValid())
1283 R.setBegin(ExternLoc);
1284 return R;
1285}
1286
Richard Smithe40f2ba2013-08-07 21:41:30 +00001287void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1288 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001289}
1290
1291/// \brief Late parse a C++ function template in Microsoft mode.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001292void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
David Majnemerf0a84f22013-08-16 08:29:13 +00001293 if (!LPT.D)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001294 return;
1295
1296 // Get the FunctionDecl.
Alp Tokera2794f92014-01-22 07:29:52 +00001297 FunctionDecl *FunD = LPT.D->getAsFunction();
Faisal Vali6a79ca12013-06-08 19:39:00 +00001298 // Track template parameter depth.
1299 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1300
1301 // To restore the context after late parsing.
Richard Smithb0b68012015-05-11 23:09:06 +00001302 Sema::ContextRAII GlobalSavedContext(
1303 Actions, Actions.Context.getTranslationUnitDecl());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001304
1305 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1306
1307 // Get the list of DeclContexts to reenter.
1308 SmallVector<DeclContext*, 4> DeclContextsToReenter;
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001309 DeclContext *DD = FunD;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001310 while (DD && !DD->isTranslationUnit()) {
1311 DeclContextsToReenter.push_back(DD);
1312 DD = DD->getLexicalParent();
1313 }
1314
1315 // Reenter template scopes from outermost to innermost.
Craig Topper61ac9062013-07-08 03:55:09 +00001316 SmallVectorImpl<DeclContext *>::reverse_iterator II =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001317 DeclContextsToReenter.rbegin();
1318 for (; II != DeclContextsToReenter.rend(); ++II) {
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001319 TemplateParamScopeStack.push_back(new ParseScope(this,
1320 Scope::TemplateParamScope));
1321 unsigned NumParamLists =
1322 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1323 CurTemplateDepthTracker.addDepth(NumParamLists);
1324 if (*II != FunD) {
1325 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1326 Actions.PushDeclContext(Actions.getCurScope(), *II);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001327 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001328 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001329
Richard Smithe40f2ba2013-08-07 21:41:30 +00001330 assert(!LPT.Toks.empty() && "Empty body!");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001331
1332 // Append the current token at the end of the new token stream so that it
1333 // doesn't get lost.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001334 LPT.Toks.push_back(Tok);
1335 PP.EnterTokenStream(LPT.Toks.data(), LPT.Toks.size(), true, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001336
1337 // Consume the previously pushed token.
1338 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001339 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1340 "Inline method not starting with '{', ':' or 'try'");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001341
1342 // Parse the method body. Function body parsing code is similar enough
1343 // to be re-used for method bodies as well.
1344 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1345
1346 // Recreate the containing function DeclContext.
Nico Weber55048cf2014-08-15 22:15:00 +00001347 Sema::ContextRAII FunctionSavedContext(Actions,
1348 Actions.getContainingDC(FunD));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001349
1350 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1351
1352 if (Tok.is(tok::kw_try)) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00001353 ParseFunctionTryBlock(LPT.D, FnScope);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001354 } else {
1355 if (Tok.is(tok::colon))
Richard Smithe40f2ba2013-08-07 21:41:30 +00001356 ParseConstructorInitializer(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001357 else
Richard Smithe40f2ba2013-08-07 21:41:30 +00001358 Actions.ActOnDefaultCtorInitializers(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001359
1360 if (Tok.is(tok::l_brace)) {
Alp Tokera2794f92014-01-22 07:29:52 +00001361 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1362 cast<FunctionTemplateDecl>(LPT.D)
1363 ->getTemplateParameters()
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001364 ->getDepth() == TemplateParameterDepth - 1) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +00001365 "TemplateParameterDepth should be greater than the depth of "
1366 "current template being instantiated!");
Richard Smithe40f2ba2013-08-07 21:41:30 +00001367 ParseFunctionStatementBody(LPT.D, FnScope);
1368 Actions.UnmarkAsLateParsedTemplate(FunD);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001369 } else
Craig Topper161e4db2014-05-21 06:02:52 +00001370 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001371 }
1372
1373 // Exit scopes.
1374 FnScope.Exit();
Craig Topper61ac9062013-07-08 03:55:09 +00001375 SmallVectorImpl<ParseScope *>::reverse_iterator I =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001376 TemplateParamScopeStack.rbegin();
1377 for (; I != TemplateParamScopeStack.rend(); ++I)
1378 delete *I;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001379}
1380
1381/// \brief Lex a delayed template function for late parsing.
1382void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1383 tok::TokenKind kind = Tok.getKind();
1384 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1385 // Consume everything up to (and including) the matching right brace.
1386 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1387 }
1388
1389 // If we're in a function-try-block, we need to store all the catch blocks.
1390 if (kind == tok::kw_try) {
1391 while (Tok.is(tok::kw_catch)) {
1392 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1393 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1394 }
1395 }
1396}