blob: f1467fe553a0810f5bea610116ae7b3f974fb53e [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) {
65 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
66 "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 }
138 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
139
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();
370 } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
371 // 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) {
487 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
488 "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();
509 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
510 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
511 // 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)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000570 bool Replace = Tok.is(tok::kw_typename) || Tok.is(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());
580 } else if (Next.is(tok::identifier) || Next.is(tok::comma) ||
581 Next.is(tok::greater) || Next.is(tok::greatergreater) ||
582 Next.is(tok::ellipsis)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000583 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
584 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
585 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
Richard Smith78e1ca62014-06-16 15:51:22 +0000586 } else
Faisal Vali6a79ca12013-06-08 19:39:00 +0000587 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
588
589 if (Replace)
590 ConsumeToken();
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000591 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000592
593 // Parse the ellipsis, if given.
594 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000595 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000596 Diag(EllipsisLoc,
597 getLangOpts().CPlusPlus11
598 ? diag::warn_cxx98_compat_variadic_templates
599 : diag::ext_variadic_templates);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000600
601 // Get the identifier, if given.
602 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000603 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000604 if (Tok.is(tok::identifier)) {
605 ParamName = Tok.getIdentifierInfo();
606 NameLoc = ConsumeToken();
607 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
608 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
609 // Unnamed template parameter. Don't have to do anything here, just
610 // don't consume this token.
611 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000612 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000613 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000614 }
615
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000616 // Recover from misplaced ellipsis.
617 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
618 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
619 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
620
Faisal Vali6a79ca12013-06-08 19:39:00 +0000621 TemplateParameterList *ParamList =
622 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
623 TemplateLoc, LAngleLoc,
624 TemplateParams.data(),
625 TemplateParams.size(),
626 RAngleLoc);
627
628 // Grab a default argument (if available).
629 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
630 // we introduce the template parameter into the local scope.
631 SourceLocation EqualLoc;
632 ParsedTemplateArgument DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000633 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000634 DefaultArg = ParseTemplateTemplateArgument();
635 if (DefaultArg.isInvalid()) {
636 Diag(Tok.getLocation(),
637 diag::err_default_template_template_parameter_not_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000638 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
639 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000640 }
641 }
642
643 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
644 ParamList, EllipsisLoc,
645 ParamName, NameLoc, Depth,
646 Position, EqualLoc, DefaultArg);
647}
648
649/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
650/// template parameters (e.g., in "template<int Size> class array;").
651///
652/// template-parameter:
653/// ...
654/// parameter-declaration
655Decl *
656Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
657 // Parse the declaration-specifiers (i.e., the type).
658 // FIXME: The type should probably be restricted in some way... Not all
659 // declarators (parts of declarators?) are accepted for parameters.
660 DeclSpec DS(AttrFactory);
661 ParseDeclarationSpecifiers(DS);
662
663 // Parse this as a typename.
664 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
665 ParseDeclarator(ParamDecl);
666 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
667 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
Craig Topper161e4db2014-05-21 06:02:52 +0000668 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000669 }
670
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000671 // Recover from misplaced ellipsis.
672 SourceLocation EllipsisLoc;
673 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
674 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
675
Faisal Vali6a79ca12013-06-08 19:39:00 +0000676 // If there is a default value, parse it.
677 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
678 // we introduce the template parameter into the local scope.
679 SourceLocation EqualLoc;
680 ExprResult DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000681 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000682 // C++ [temp.param]p15:
683 // When parsing a default template-argument for a non-type
684 // template-parameter, the first non-nested > is taken as the
685 // end of the template-parameter-list rather than a greater-than
686 // operator.
687 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
688 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
689
Kaelyn Takata999dd852014-12-02 23:32:20 +0000690 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000691 if (DefaultArg.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +0000692 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000693 }
694
695 // Create the parameter.
696 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
697 Depth, Position, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000698 DefaultArg.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000699}
700
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000701void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
702 SourceLocation CorrectLoc,
703 bool AlreadyHasEllipsis,
704 bool IdentifierHasName) {
705 FixItHint Insertion;
706 if (!AlreadyHasEllipsis)
707 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
708 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
709 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
710 << !IdentifierHasName;
711}
712
713void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
714 Declarator &D) {
715 assert(EllipsisLoc.isValid());
716 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
717 if (!AlreadyHasEllipsis)
718 D.setEllipsisLoc(EllipsisLoc);
719 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
720 AlreadyHasEllipsis, D.hasName());
721}
722
Faisal Vali6a79ca12013-06-08 19:39:00 +0000723/// \brief Parses a '>' at the end of a template list.
724///
725/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
726/// to determine if these tokens were supposed to be a '>' followed by
727/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
728///
729/// \param RAngleLoc the location of the consumed '>'.
730///
731/// \param ConsumeLastToken if true, the '>' is not consumed.
Serge Pavlovb716b3c2013-08-10 05:54:47 +0000732///
733/// \returns true, if current token does not start with '>', false otherwise.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000734bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
735 bool ConsumeLastToken) {
736 // What will be left once we've consumed the '>'.
737 tok::TokenKind RemainingToken;
738 const char *ReplacementStr = "> >";
739
740 switch (Tok.getKind()) {
741 default:
Alp Toker383d2c42014-01-01 03:08:43 +0000742 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000743 return true;
744
745 case tok::greater:
746 // Determine the location of the '>' token. Only consume this token
747 // if the caller asked us to.
748 RAngleLoc = Tok.getLocation();
749 if (ConsumeLastToken)
750 ConsumeToken();
751 return false;
752
753 case tok::greatergreater:
754 RemainingToken = tok::greater;
755 break;
756
757 case tok::greatergreatergreater:
758 RemainingToken = tok::greatergreater;
759 break;
760
761 case tok::greaterequal:
762 RemainingToken = tok::equal;
763 ReplacementStr = "> =";
764 break;
765
766 case tok::greatergreaterequal:
767 RemainingToken = tok::greaterequal;
768 break;
769 }
770
771 // This template-id is terminated by a token which starts with a '>'. Outside
772 // C++11, this is now error recovery, and in C++11, this is error recovery if
Eli Bendersky36a61932014-06-20 13:09:59 +0000773 // the token isn't '>>' or '>>>'.
774 // '>>>' is for CUDA, where this sequence of characters is parsed into
775 // tok::greatergreatergreater, rather than two separate tokens.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000776
777 RAngleLoc = Tok.getLocation();
778
779 // The source range of the '>>' or '>=' at the start of the token.
780 CharSourceRange ReplacementRange =
781 CharSourceRange::getCharRange(RAngleLoc,
782 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
783 getLangOpts()));
784
785 // A hint to put a space between the '>>'s. In order to make the hint as
786 // clear as possible, we include the characters either side of the space in
787 // the replacement, rather than just inserting a space at SecondCharLoc.
788 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
789 ReplacementStr);
790
791 // A hint to put another space after the token, if it would otherwise be
792 // lexed differently.
793 FixItHint Hint2;
794 Token Next = NextToken();
795 if ((RemainingToken == tok::greater ||
796 RemainingToken == tok::greatergreater) &&
797 (Next.is(tok::greater) || Next.is(tok::greatergreater) ||
798 Next.is(tok::greatergreatergreater) || Next.is(tok::equal) ||
799 Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) ||
800 Next.is(tok::equalequal)) &&
801 areTokensAdjacent(Tok, Next))
802 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
803
804 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
Eli Bendersky36a61932014-06-20 13:09:59 +0000805 if (getLangOpts().CPlusPlus11 &&
806 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000807 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
808 else if (Tok.is(tok::greaterequal))
809 DiagId = diag::err_right_angle_bracket_equal_needs_space;
810 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
811
812 // Strip the initial '>' from the token.
813 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
814 areTokensAdjacent(Tok, Next)) {
815 // Join two adjacent '=' tokens into one, for cases like:
816 // void (*p)() = f<int>;
817 // return f<int>==p;
818 ConsumeToken();
819 Tok.setKind(tok::equalequal);
820 Tok.setLength(Tok.getLength() + 1);
821 } else {
822 Tok.setKind(RemainingToken);
823 Tok.setLength(Tok.getLength() - 1);
824 }
825 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
826 PP.getSourceManager(),
827 getLangOpts()));
828
829 if (!ConsumeLastToken) {
830 // Since we're not supposed to consume the '>' token, we need to push
831 // this token and revert the current token back to the '>'.
832 PP.EnterToken(Tok);
833 Tok.setKind(tok::greater);
834 Tok.setLength(1);
835 Tok.setLocation(RAngleLoc);
836 }
837 return false;
838}
839
840
841/// \brief Parses a template-id that after the template name has
842/// already been parsed.
843///
844/// This routine takes care of parsing the enclosed template argument
845/// list ('<' template-parameter-list [opt] '>') and placing the
846/// results into a form that can be transferred to semantic analysis.
847///
848/// \param Template the template declaration produced by isTemplateName
849///
850/// \param TemplateNameLoc the source location of the template name
851///
852/// \param SS if non-NULL, the nested-name-specifier preceding the
853/// template name.
854///
855/// \param ConsumeLastToken if true, then we will consume the last
856/// token that forms the template-id. Otherwise, we will leave the
857/// last token in the stream (e.g., so that it can be replaced with an
858/// annotation token).
859bool
860Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
861 SourceLocation TemplateNameLoc,
862 const CXXScopeSpec &SS,
863 bool ConsumeLastToken,
864 SourceLocation &LAngleLoc,
865 TemplateArgList &TemplateArgs,
866 SourceLocation &RAngleLoc) {
867 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
868
869 // Consume the '<'.
870 LAngleLoc = ConsumeToken();
871
872 // Parse the optional template-argument-list.
873 bool Invalid = false;
874 {
875 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
876 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
877 Invalid = ParseTemplateArgumentList(TemplateArgs);
878
879 if (Invalid) {
880 // Try to find the closing '>'.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000881 if (ConsumeLastToken)
882 SkipUntil(tok::greater, StopAtSemi);
883 else
884 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000885 return true;
886 }
887 }
888
889 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken);
890}
891
892/// \brief Replace the tokens that form a simple-template-id with an
893/// annotation token containing the complete template-id.
894///
895/// The first token in the stream must be the name of a template that
896/// is followed by a '<'. This routine will parse the complete
897/// simple-template-id and replace the tokens with a single annotation
898/// token with one of two different kinds: if the template-id names a
899/// type (and \p AllowTypeAnnotation is true), the annotation token is
900/// a type annotation that includes the optional nested-name-specifier
901/// (\p SS). Otherwise, the annotation token is a template-id
902/// annotation that does not include the optional
903/// nested-name-specifier.
904///
905/// \param Template the declaration of the template named by the first
906/// token (an identifier), as returned from \c Action::isTemplateName().
907///
908/// \param TNK the kind of template that \p Template
909/// refers to, as returned from \c Action::isTemplateName().
910///
911/// \param SS if non-NULL, the nested-name-specifier that precedes
912/// this template name.
913///
914/// \param TemplateKWLoc if valid, specifies that this template-id
915/// annotation was preceded by the 'template' keyword and gives the
916/// location of that keyword. If invalid (the default), then this
917/// template-id was not preceded by a 'template' keyword.
918///
919/// \param AllowTypeAnnotation if true (the default), then a
920/// simple-template-id that refers to a class template, template
921/// template parameter, or other template that produces a type will be
922/// replaced with a type annotation token. Otherwise, the
923/// simple-template-id is always replaced with a template-id
924/// annotation token.
925///
926/// If an unrecoverable parse error occurs and no annotation token can be
927/// formed, this function returns true.
928///
929bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
930 CXXScopeSpec &SS,
931 SourceLocation TemplateKWLoc,
932 UnqualifiedId &TemplateName,
933 bool AllowTypeAnnotation) {
934 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
935 assert(Template && Tok.is(tok::less) &&
936 "Parser isn't at the beginning of a template-id");
937
938 // Consume the template-name.
939 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
940
941 // Parse the enclosed template argument list.
942 SourceLocation LAngleLoc, RAngleLoc;
943 TemplateArgList TemplateArgs;
944 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
945 TemplateNameLoc,
946 SS, false, LAngleLoc,
947 TemplateArgs,
948 RAngleLoc);
949
950 if (Invalid) {
951 // If we failed to parse the template ID but skipped ahead to a >, we're not
952 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000953 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000954 return true;
955 }
956
957 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
958
959 // Build the annotation token.
960 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
961 TypeResult Type
962 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
963 Template, TemplateNameLoc,
964 LAngleLoc, TemplateArgsPtr, RAngleLoc);
965 if (Type.isInvalid()) {
966 // If we failed to parse the template ID but skipped ahead to a >, we're not
967 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000968 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000969 return true;
970 }
971
972 Tok.setKind(tok::annot_typename);
973 setTypeAnnotation(Tok, Type.get());
974 if (SS.isNotEmpty())
975 Tok.setLocation(SS.getBeginLoc());
976 else if (TemplateKWLoc.isValid())
977 Tok.setLocation(TemplateKWLoc);
978 else
979 Tok.setLocation(TemplateNameLoc);
980 } else {
981 // Build a template-id annotation token that can be processed
982 // later.
983 Tok.setKind(tok::annot_template_id);
984 TemplateIdAnnotation *TemplateId
985 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
986 TemplateId->TemplateNameLoc = TemplateNameLoc;
987 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
988 TemplateId->Name = TemplateName.Identifier;
989 TemplateId->Operator = OO_None;
990 } else {
Craig Topper161e4db2014-05-21 06:02:52 +0000991 TemplateId->Name = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000992 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
993 }
994 TemplateId->SS = SS;
995 TemplateId->TemplateKWLoc = TemplateKWLoc;
996 TemplateId->Template = Template;
997 TemplateId->Kind = TNK;
998 TemplateId->LAngleLoc = LAngleLoc;
999 TemplateId->RAngleLoc = RAngleLoc;
1000 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1001 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
1002 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
1003 Tok.setAnnotationValue(TemplateId);
1004 if (TemplateKWLoc.isValid())
1005 Tok.setLocation(TemplateKWLoc);
1006 else
1007 Tok.setLocation(TemplateNameLoc);
1008 }
1009
1010 // Common fields for the annotation token
1011 Tok.setAnnotationEndLoc(RAngleLoc);
1012
1013 // In case the tokens were cached, have Preprocessor replace them with the
1014 // annotation token.
1015 PP.AnnotateCachedTokens(Tok);
1016 return false;
1017}
1018
1019/// \brief Replaces a template-id annotation token with a type
1020/// annotation token.
1021///
1022/// If there was a failure when forming the type from the template-id,
1023/// a type annotation token will still be created, but will have a
1024/// NULL type pointer to signify an error.
1025void Parser::AnnotateTemplateIdTokenAsType() {
1026 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1027
1028 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1029 assert((TemplateId->Kind == TNK_Type_template ||
1030 TemplateId->Kind == TNK_Dependent_template_name) &&
1031 "Only works for type and dependent templates");
1032
1033 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1034 TemplateId->NumArgs);
1035
1036 TypeResult Type
1037 = Actions.ActOnTemplateIdType(TemplateId->SS,
1038 TemplateId->TemplateKWLoc,
1039 TemplateId->Template,
1040 TemplateId->TemplateNameLoc,
1041 TemplateId->LAngleLoc,
1042 TemplateArgsPtr,
1043 TemplateId->RAngleLoc);
1044 // Create the new "type" annotation token.
1045 Tok.setKind(tok::annot_typename);
1046 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
1047 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1048 Tok.setLocation(TemplateId->SS.getBeginLoc());
1049 // End location stays the same
1050
1051 // Replace the template-id annotation token, and possible the scope-specifier
1052 // that precedes it, with the typename annotation token.
1053 PP.AnnotateCachedTokens(Tok);
1054}
1055
1056/// \brief Determine whether the given token can end a template argument.
1057static bool isEndOfTemplateArgument(Token Tok) {
1058 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
1059 Tok.is(tok::greatergreater);
1060}
1061
1062/// \brief Parse a C++ template template argument.
1063ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1064 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1065 !Tok.is(tok::annot_cxxscope))
1066 return ParsedTemplateArgument();
1067
1068 // C++0x [temp.arg.template]p1:
1069 // A template-argument for a template template-parameter shall be the name
1070 // of a class template or an alias template, expressed as id-expression.
1071 //
1072 // We parse an id-expression that refers to a class template or alias
1073 // template. The grammar we parse is:
1074 //
1075 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1076 //
1077 // followed by a token that terminates a template argument, such as ',',
1078 // '>', or (in some cases) '>>'.
1079 CXXScopeSpec SS; // nested-name-specifier, if present
1080 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1081 /*EnteringContext=*/false);
1082
1083 ParsedTemplateArgument Result;
1084 SourceLocation EllipsisLoc;
1085 if (SS.isSet() && Tok.is(tok::kw_template)) {
1086 // Parse the optional 'template' keyword following the
1087 // nested-name-specifier.
1088 SourceLocation TemplateKWLoc = ConsumeToken();
1089
1090 if (Tok.is(tok::identifier)) {
1091 // We appear to have a dependent template name.
1092 UnqualifiedId Name;
1093 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1094 ConsumeToken(); // the identifier
Alp Toker094e5212014-01-05 03:27:11 +00001095
1096 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1097
Faisal Vali6a79ca12013-06-08 19:39:00 +00001098 // If the next token signals the end of a template argument,
1099 // then we have a dependent template name that could be a template
1100 // template argument.
1101 TemplateTy Template;
1102 if (isEndOfTemplateArgument(Tok) &&
1103 Actions.ActOnDependentTemplateName(getCurScope(),
1104 SS, TemplateKWLoc, Name,
1105 /*ObjectType=*/ ParsedType(),
1106 /*EnteringContext=*/false,
1107 Template))
1108 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1109 }
1110 } else if (Tok.is(tok::identifier)) {
1111 // We may have a (non-dependent) template name.
1112 TemplateTy Template;
1113 UnqualifiedId Name;
1114 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1115 ConsumeToken(); // the identifier
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001116
1117 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001118
1119 if (isEndOfTemplateArgument(Tok)) {
1120 bool MemberOfUnknownSpecialization;
1121 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1122 /*hasTemplateKeyword=*/false,
1123 Name,
1124 /*ObjectType=*/ ParsedType(),
1125 /*EnteringContext=*/false,
1126 Template,
1127 MemberOfUnknownSpecialization);
1128 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1129 // We have an id-expression that refers to a class template or
1130 // (C++0x) alias template.
1131 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1132 }
1133 }
1134 }
1135
1136 // If this is a pack expansion, build it as such.
1137 if (EllipsisLoc.isValid() && !Result.isInvalid())
1138 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1139
1140 return Result;
1141}
1142
1143/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1144///
1145/// template-argument: [C++ 14.2]
1146/// constant-expression
1147/// type-id
1148/// id-expression
1149ParsedTemplateArgument Parser::ParseTemplateArgument() {
1150 // C++ [temp.arg]p2:
1151 // In a template-argument, an ambiguity between a type-id and an
1152 // expression is resolved to a type-id, regardless of the form of
1153 // the corresponding template-parameter.
1154 //
1155 // Therefore, we initially try to parse a type-id.
1156 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1157 SourceLocation Loc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00001158 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001159 Declarator::TemplateTypeArgContext);
1160 if (TypeArg.isInvalid())
1161 return ParsedTemplateArgument();
1162
1163 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1164 TypeArg.get().getAsOpaquePtr(),
1165 Loc);
1166 }
1167
1168 // Try to parse a template template argument.
1169 {
1170 TentativeParsingAction TPA(*this);
1171
1172 ParsedTemplateArgument TemplateTemplateArgument
1173 = ParseTemplateTemplateArgument();
1174 if (!TemplateTemplateArgument.isInvalid()) {
1175 TPA.Commit();
1176 return TemplateTemplateArgument;
1177 }
1178
1179 // Revert this tentative parse to parse a non-type template argument.
1180 TPA.Revert();
1181 }
1182
1183 // Parse a non-type template argument.
1184 SourceLocation Loc = Tok.getLocation();
1185 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1186 if (ExprArg.isInvalid() || !ExprArg.get())
1187 return ParsedTemplateArgument();
1188
1189 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001190 ExprArg.get(), Loc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001191}
1192
1193/// \brief Determine whether the current tokens can only be parsed as a
1194/// template argument list (starting with the '<') and never as a '<'
1195/// expression.
1196bool Parser::IsTemplateArgumentList(unsigned Skip) {
1197 struct AlwaysRevertAction : TentativeParsingAction {
1198 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1199 ~AlwaysRevertAction() { Revert(); }
1200 } Tentative(*this);
1201
1202 while (Skip) {
1203 ConsumeToken();
1204 --Skip;
1205 }
1206
1207 // '<'
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001208 if (!TryConsumeToken(tok::less))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001209 return false;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001210
1211 // An empty template argument list.
1212 if (Tok.is(tok::greater))
1213 return true;
1214
1215 // See whether we have declaration specifiers, which indicate a type.
Richard Smithee390432014-05-16 01:56:53 +00001216 while (isCXXDeclarationSpecifier() == TPResult::True)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001217 ConsumeToken();
1218
1219 // If we have a '>' or a ',' then this is a template argument list.
1220 return Tok.is(tok::greater) || Tok.is(tok::comma);
1221}
1222
1223/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1224/// (C++ [temp.names]). Returns true if there was an error.
1225///
1226/// template-argument-list: [C++ 14.2]
1227/// template-argument
1228/// template-argument-list ',' template-argument
1229bool
1230Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1231 // Template argument lists are constant-evaluation contexts.
1232 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +00001233 ColonProtectionRAIIObject ColonProtection(*this, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001234
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001235 do {
Faisal Vali6a79ca12013-06-08 19:39:00 +00001236 ParsedTemplateArgument Arg = ParseTemplateArgument();
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001237 SourceLocation EllipsisLoc;
1238 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001239 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001240
1241 if (Arg.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001242 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001243 return true;
1244 }
1245
1246 // Save this template argument.
1247 TemplateArgs.push_back(Arg);
1248
1249 // If the next token is a comma, consume it and keep reading
1250 // arguments.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001251 } while (TryConsumeToken(tok::comma));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001252
1253 return false;
1254}
1255
1256/// \brief Parse a C++ explicit template instantiation
1257/// (C++ [temp.explicit]).
1258///
1259/// explicit-instantiation:
1260/// 'extern' [opt] 'template' declaration
1261///
1262/// Note that the 'extern' is a GNU extension and C++11 feature.
1263Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1264 SourceLocation ExternLoc,
1265 SourceLocation TemplateLoc,
1266 SourceLocation &DeclEnd,
1267 AccessSpecifier AS) {
1268 // This isn't really required here.
1269 ParsingDeclRAIIObject
1270 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1271
1272 return ParseSingleDeclarationAfterTemplate(Context,
1273 ParsedTemplateInfo(ExternLoc,
1274 TemplateLoc),
1275 ParsingTemplateParams,
1276 DeclEnd, AS);
1277}
1278
1279SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1280 if (TemplateParams)
1281 return getTemplateParamsRange(TemplateParams->data(),
1282 TemplateParams->size());
1283
1284 SourceRange R(TemplateLoc);
1285 if (ExternLoc.isValid())
1286 R.setBegin(ExternLoc);
1287 return R;
1288}
1289
Richard Smithe40f2ba2013-08-07 21:41:30 +00001290void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1291 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001292}
1293
1294/// \brief Late parse a C++ function template in Microsoft mode.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001295void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
David Majnemerf0a84f22013-08-16 08:29:13 +00001296 if (!LPT.D)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001297 return;
1298
1299 // Get the FunctionDecl.
Alp Tokera2794f92014-01-22 07:29:52 +00001300 FunctionDecl *FunD = LPT.D->getAsFunction();
Faisal Vali6a79ca12013-06-08 19:39:00 +00001301 // Track template parameter depth.
1302 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1303
1304 // To restore the context after late parsing.
Richard Smithb0b68012015-05-11 23:09:06 +00001305 Sema::ContextRAII GlobalSavedContext(
1306 Actions, Actions.Context.getTranslationUnitDecl());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001307
1308 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1309
1310 // Get the list of DeclContexts to reenter.
1311 SmallVector<DeclContext*, 4> DeclContextsToReenter;
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001312 DeclContext *DD = FunD;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001313 while (DD && !DD->isTranslationUnit()) {
1314 DeclContextsToReenter.push_back(DD);
1315 DD = DD->getLexicalParent();
1316 }
1317
1318 // Reenter template scopes from outermost to innermost.
Craig Topper61ac9062013-07-08 03:55:09 +00001319 SmallVectorImpl<DeclContext *>::reverse_iterator II =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001320 DeclContextsToReenter.rbegin();
1321 for (; II != DeclContextsToReenter.rend(); ++II) {
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001322 TemplateParamScopeStack.push_back(new ParseScope(this,
1323 Scope::TemplateParamScope));
1324 unsigned NumParamLists =
1325 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1326 CurTemplateDepthTracker.addDepth(NumParamLists);
1327 if (*II != FunD) {
1328 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1329 Actions.PushDeclContext(Actions.getCurScope(), *II);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001330 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001331 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001332
Richard Smithe40f2ba2013-08-07 21:41:30 +00001333 assert(!LPT.Toks.empty() && "Empty body!");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001334
1335 // Append the current token at the end of the new token stream so that it
1336 // doesn't get lost.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001337 LPT.Toks.push_back(Tok);
1338 PP.EnterTokenStream(LPT.Toks.data(), LPT.Toks.size(), true, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001339
1340 // Consume the previously pushed token.
1341 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1342 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1343 && "Inline method not starting with '{', ':' or 'try'");
1344
1345 // Parse the method body. Function body parsing code is similar enough
1346 // to be re-used for method bodies as well.
1347 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1348
1349 // Recreate the containing function DeclContext.
Nico Weber55048cf2014-08-15 22:15:00 +00001350 Sema::ContextRAII FunctionSavedContext(Actions,
1351 Actions.getContainingDC(FunD));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001352
1353 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1354
1355 if (Tok.is(tok::kw_try)) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00001356 ParseFunctionTryBlock(LPT.D, FnScope);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001357 } else {
1358 if (Tok.is(tok::colon))
Richard Smithe40f2ba2013-08-07 21:41:30 +00001359 ParseConstructorInitializer(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001360 else
Richard Smithe40f2ba2013-08-07 21:41:30 +00001361 Actions.ActOnDefaultCtorInitializers(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001362
1363 if (Tok.is(tok::l_brace)) {
Alp Tokera2794f92014-01-22 07:29:52 +00001364 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1365 cast<FunctionTemplateDecl>(LPT.D)
1366 ->getTemplateParameters()
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001367 ->getDepth() == TemplateParameterDepth - 1) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +00001368 "TemplateParameterDepth should be greater than the depth of "
1369 "current template being instantiated!");
Richard Smithe40f2ba2013-08-07 21:41:30 +00001370 ParseFunctionStatementBody(LPT.D, FnScope);
1371 Actions.UnmarkAsLateParsedTemplate(FunD);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001372 } else
Craig Topper161e4db2014-05-21 06:02:52 +00001373 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001374 }
1375
1376 // Exit scopes.
1377 FnScope.Exit();
Craig Topper61ac9062013-07-08 03:55:09 +00001378 SmallVectorImpl<ParseScope *>::reverse_iterator I =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001379 TemplateParamScopeStack.rbegin();
1380 for (; I != TemplateParamScopeStack.rend(); ++I)
1381 delete *I;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001382}
1383
1384/// \brief Lex a delayed template function for late parsing.
1385void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1386 tok::TokenKind kind = Tok.getKind();
1387 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1388 // Consume everything up to (and including) the matching right brace.
1389 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1390 }
1391
1392 // If we're in a function-try-block, we need to store all the catch blocks.
1393 if (kind == tok::kw_try) {
1394 while (Tok.is(tok::kw_catch)) {
1395 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1396 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1397 }
1398 }
1399}