blob: 28ae113a511ff812da4e9f0fd983a3a6333d0c1b [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
Richard Smithb0b68012015-05-11 23:09:06 +000014#include "clang/AST/ASTContext.h"
Faisal Vali6a79ca12013-06-08 19:39:00 +000015#include "clang/AST/DeclTemplate.h"
16#include "clang/Parse/ParseDiagnostic.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000017#include "clang/Parse/Parser.h"
Vassil Vassilev11ad3392017-03-23 15:11:07 +000018#include "clang/Parse/RAIIObjectsForParser.h"
Faisal Vali6a79ca12013-06-08 19:39:00 +000019#include "clang/Sema/DeclSpec.h"
20#include "clang/Sema/ParsedTemplate.h"
21#include "clang/Sema/Scope.h"
22using namespace clang;
23
24/// \brief Parse a template declaration, explicit instantiation, or
25/// explicit specialization.
26Decl *
27Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
28 SourceLocation &DeclEnd,
29 AccessSpecifier AS,
30 AttributeList *AccessAttrs) {
31 ObjCDeclContextSwitch ObjCDC(*this);
32
33 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
34 return ParseExplicitInstantiation(Context,
35 SourceLocation(), ConsumeToken(),
36 DeclEnd, AS);
37 }
38 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
39 AccessAttrs);
40}
41
42
43
44/// \brief Parse a template declaration or an explicit specialization.
45///
46/// Template declarations include one or more template parameter lists
47/// and either the function or class template declaration. Explicit
48/// specializations contain one or more 'template < >' prefixes
49/// followed by a (possibly templated) declaration. Since the
50/// syntactic form of both features is nearly identical, we parse all
51/// of the template headers together and let semantic analysis sort
52/// the declarations from the explicit specializations.
53///
54/// template-declaration: [C++ temp]
55/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
56///
57/// explicit-specialization: [ C++ temp.expl.spec]
58/// 'template' '<' '>' declaration
59Decl *
60Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
61 SourceLocation &DeclEnd,
62 AccessSpecifier AS,
63 AttributeList *AccessAttrs) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +000064 assert(Tok.isOneOf(tok::kw_export, tok::kw_template) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +000065 "Token does not start a template declaration.");
66
67 // Enter template-parameter scope.
68 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
69
70 // Tell the action that names should be checked in the context of
71 // the declaration to come.
72 ParsingDeclRAIIObject
73 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
74
75 // Parse multiple levels of template headers within this template
76 // parameter scope, e.g.,
77 //
78 // template<typename T>
79 // template<typename U>
80 // class A<T>::B { ... };
81 //
82 // We parse multiple levels non-recursively so that we can build a
83 // single data structure containing all of the template parameter
84 // lists to easily differentiate between the case above and:
85 //
86 // template<typename T>
87 // class A {
88 // template<typename U> class B;
89 // };
90 //
91 // In the first case, the action for declaring A<T>::B receives
92 // both template parameter lists. In the second case, the action for
93 // defining A<T>::B receives just the inner template parameter list
94 // (and retrieves the outer template parameter list from its
95 // context).
96 bool isSpecialization = true;
97 bool LastParamListWasEmpty = false;
98 TemplateParameterLists ParamLists;
99 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
100
101 do {
102 // Consume the 'export', if any.
103 SourceLocation ExportLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000104 TryConsumeToken(tok::kw_export, ExportLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000105
106 // Consume the 'template', which should be here.
107 SourceLocation TemplateLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000108 if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000109 Diag(Tok.getLocation(), diag::err_expected_template);
Craig Topper161e4db2014-05-21 06:02:52 +0000110 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000111 }
112
113 // Parse the '<' template-parameter-list '>'
114 SourceLocation LAngleLoc, RAngleLoc;
115 SmallVector<Decl*, 4> TemplateParams;
116 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
117 TemplateParams, LAngleLoc, RAngleLoc)) {
Hubert Tongec3cb572015-06-25 00:23:39 +0000118 // Skip until the semi-colon or a '}'.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000119 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000120 TryConsumeToken(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000121 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000122 }
123
Hubert Tongf608c052016-04-29 18:05:37 +0000124 ExprResult OptionalRequiresClauseConstraintER;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000125 if (!TemplateParams.empty()) {
126 isSpecialization = false;
127 ++CurTemplateDepthTracker;
Hubert Tongec3cb572015-06-25 00:23:39 +0000128
129 if (TryConsumeToken(tok::kw_requires)) {
Hubert Tongf608c052016-04-29 18:05:37 +0000130 OptionalRequiresClauseConstraintER =
Hubert Tongec3cb572015-06-25 00:23:39 +0000131 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
Hubert Tongf608c052016-04-29 18:05:37 +0000132 if (!OptionalRequiresClauseConstraintER.isUsable()) {
Hubert Tongec3cb572015-06-25 00:23:39 +0000133 // Skip until the semi-colon or a '}'.
134 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
135 TryConsumeToken(tok::semi);
136 return nullptr;
137 }
138 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000139 } else {
140 LastParamListWasEmpty = true;
141 }
Hubert Tongf608c052016-04-29 18:05:37 +0000142
143 ParamLists.push_back(Actions.ActOnTemplateParameterList(
144 CurTemplateDepthTracker.getDepth(), ExportLoc, TemplateLoc, LAngleLoc,
145 TemplateParams, RAngleLoc, OptionalRequiresClauseConstraintER.get()));
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000146 } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
Faisal Vali6a79ca12013-06-08 19:39:00 +0000147
Akira Hatanaka10aced82016-04-29 02:24:14 +0000148 unsigned NewFlags = getCurScope()->getFlags() & ~Scope::TemplateParamScope;
149 ParseScopeFlags TemplateScopeFlags(this, NewFlags, isSpecialization);
150
Faisal Vali6a79ca12013-06-08 19:39:00 +0000151 // Parse the actual template declaration.
152 return ParseSingleDeclarationAfterTemplate(Context,
153 ParsedTemplateInfo(&ParamLists,
154 isSpecialization,
155 LastParamListWasEmpty),
156 ParsingTemplateParams,
157 DeclEnd, AS, AccessAttrs);
158}
159
160/// \brief Parse a single declaration that declares a template,
161/// template specialization, or explicit instantiation of a template.
162///
163/// \param DeclEnd will receive the source location of the last token
164/// within this declaration.
165///
166/// \param AS the access specifier associated with this
167/// declaration. Will be AS_none for namespace-scope declarations.
168///
169/// \returns the new declaration.
170Decl *
171Parser::ParseSingleDeclarationAfterTemplate(
172 unsigned Context,
173 const ParsedTemplateInfo &TemplateInfo,
174 ParsingDeclRAIIObject &DiagsFromTParams,
175 SourceLocation &DeclEnd,
176 AccessSpecifier AS,
177 AttributeList *AccessAttrs) {
178 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
179 "Template information required");
180
Aaron Ballmane7c544d2014-08-04 20:28:35 +0000181 if (Tok.is(tok::kw_static_assert)) {
182 // A static_assert declaration may not be templated.
183 Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
184 << TemplateInfo.getSourceRange();
185 // Parse the static_assert declaration to improve error recovery.
186 return ParseStaticAssertDeclaration(DeclEnd);
187 }
188
Faisal Vali6a79ca12013-06-08 19:39:00 +0000189 if (Context == Declarator::MemberContext) {
190 // We are parsing a member template.
191 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
192 &DiagsFromTParams);
Craig Topper161e4db2014-05-21 06:02:52 +0000193 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000194 }
195
196 ParsedAttributesWithRange prefixAttrs(AttrFactory);
197 MaybeParseCXX11Attributes(prefixAttrs);
198
Richard Smith6f1daa42016-12-16 00:58:48 +0000199 if (Tok.is(tok::kw_using)) {
200 // FIXME: We should return the DeclGroup to the caller.
201 ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
202 prefixAttrs);
203 return nullptr;
204 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000205
206 // Parse the declaration specifiers, stealing any diagnostics from
207 // the template parameters.
208 ParsingDeclSpec DS(*this, &DiagsFromTParams);
209
210 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
211 getDeclSpecContextFromDeclaratorContext(Context));
212
213 if (Tok.is(tok::semi)) {
214 ProhibitAttributes(prefixAttrs);
215 DeclEnd = ConsumeToken();
Nico Weber7b837f52016-01-28 19:25:00 +0000216 RecordDecl *AnonRecord = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000217 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
218 getCurScope(), AS, DS,
219 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
220 : MultiTemplateParamsArg(),
Nico Weber7b837f52016-01-28 19:25:00 +0000221 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
222 AnonRecord);
223 assert(!AnonRecord &&
224 "Anonymous unions/structs should not be valid with template");
Faisal Vali6a79ca12013-06-08 19:39:00 +0000225 DS.complete(Decl);
226 return Decl;
227 }
228
229 // Move the attributes from the prefix into the DS.
230 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
231 ProhibitAttributes(prefixAttrs);
232 else
233 DS.takeAttributesFrom(prefixAttrs);
234
235 // Parse the declarator.
236 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
237 ParseDeclarator(DeclaratorInfo);
238 // Error parsing the declarator?
239 if (!DeclaratorInfo.hasName()) {
240 // If so, skip until the semi-colon or a }.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000241 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000242 if (Tok.is(tok::semi))
243 ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000244 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000245 }
246
247 LateParsedAttrList LateParsedAttrs(true);
248 if (DeclaratorInfo.isFunctionDeclarator())
249 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
250
251 if (DeclaratorInfo.isFunctionDeclarator() &&
252 isStartOfFunctionDefinition(DeclaratorInfo)) {
Reid Klecknerd61a3112014-12-15 23:16:32 +0000253
254 // Function definitions are only allowed at file scope and in C++ classes.
255 // The C++ inline method definition case is handled elsewhere, so we only
256 // need to handle the file scope definition case.
257 if (Context != Declarator::FileContext) {
258 Diag(Tok, diag::err_function_definition_not_allowed);
259 SkipMalformedDecl();
260 return nullptr;
261 }
262
Faisal Vali6a79ca12013-06-08 19:39:00 +0000263 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
264 // Recover by ignoring the 'typedef'. This was probably supposed to be
265 // the 'typename' keyword, which we should have already suggested adding
266 // if it's appropriate.
267 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
268 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
269 DS.ClearStorageClassSpecs();
270 }
Larisse Voufo725de3e2013-06-21 00:08:46 +0000271
272 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
273 if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
274 // If the declarator-id is not a template-id, issue a diagnostic and
275 // recover by ignoring the 'template' keyword.
276 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000277 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
278 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000279 } else {
280 SourceLocation LAngleLoc
281 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000282 Diag(DeclaratorInfo.getIdentifierLoc(),
Larisse Voufo725de3e2013-06-21 00:08:46 +0000283 diag::err_explicit_instantiation_with_definition)
Larisse Voufo39a1e502013-08-06 01:03:05 +0000284 << SourceRange(TemplateInfo.TemplateLoc)
285 << FixItHint::CreateInsertion(LAngleLoc, "<>");
Larisse Voufo725de3e2013-06-21 00:08:46 +0000286
Larisse Voufo39a1e502013-08-06 01:03:05 +0000287 // Recover as if it were an explicit specialization.
Larisse Voufob9bbaba2013-06-22 13:56:11 +0000288 TemplateParameterLists FakedParamLists;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000289 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +0000290 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +0000291 LAngleLoc, nullptr));
Larisse Voufo725de3e2013-06-21 00:08:46 +0000292
Larisse Voufo39a1e502013-08-06 01:03:05 +0000293 return ParseFunctionDefinition(
294 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
295 /*isSpecialization=*/true,
296 /*LastParamListWasEmpty=*/true),
297 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000298 }
299 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000300 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
Larisse Voufo39a1e502013-08-06 01:03:05 +0000301 &LateParsedAttrs);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000302 }
303
304 // Parse this declaration.
305 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
306 TemplateInfo);
307
308 if (Tok.is(tok::comma)) {
309 Diag(Tok, diag::err_multiple_template_declarators)
310 << (int)TemplateInfo.Kind;
Alexey Bataevee6507d2013-11-18 08:17:37 +0000311 SkipUntil(tok::semi);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000312 return ThisDecl;
313 }
314
315 // Eat the semi colon after the declaration.
316 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
317 if (LateParsedAttrs.size() > 0)
318 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
319 DeclaratorInfo.complete(ThisDecl);
320 return ThisDecl;
321}
322
323/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
324/// angle brackets. Depth is the depth of this template-parameter-list, which
325/// is the number of template headers directly enclosing this template header.
326/// TemplateParams is the current list of template parameters we're building.
327/// The template parameter we parse will be added to this list. LAngleLoc and
328/// RAngleLoc will receive the positions of the '<' and '>', respectively,
329/// that enclose this template parameter list.
330///
331/// \returns true if an error occurred, false otherwise.
332bool Parser::ParseTemplateParameters(unsigned Depth,
333 SmallVectorImpl<Decl*> &TemplateParams,
334 SourceLocation &LAngleLoc,
335 SourceLocation &RAngleLoc) {
336 // Get the template parameter list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000337 if (!TryConsumeToken(tok::less, LAngleLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000338 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
339 return true;
340 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000341
342 // Try to parse the template parameter list.
343 bool Failed = false;
344 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
345 Failed = ParseTemplateParameterList(Depth, TemplateParams);
346
347 if (Tok.is(tok::greatergreater)) {
348 // No diagnostic required here: a template-parameter-list can only be
349 // followed by a declaration or, for a template template parameter, the
350 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
351 // This matters for elegant diagnosis of:
352 // template<template<typename>> struct S;
353 Tok.setKind(tok::greater);
354 RAngleLoc = Tok.getLocation();
355 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
Alp Toker383d2c42014-01-01 03:08:43 +0000356 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
357 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000358 return true;
359 }
360 return false;
361}
362
363/// ParseTemplateParameterList - Parse a template parameter list. If
364/// the parsing fails badly (i.e., closing bracket was left out), this
365/// will try to put the token stream in a reasonable position (closing
366/// a statement, etc.) and return false.
367///
368/// template-parameter-list: [C++ temp]
369/// template-parameter
370/// template-parameter-list ',' template-parameter
371bool
372Parser::ParseTemplateParameterList(unsigned Depth,
373 SmallVectorImpl<Decl*> &TemplateParams) {
374 while (1) {
375 if (Decl *TmpParam
376 = ParseTemplateParameter(Depth, TemplateParams.size())) {
377 TemplateParams.push_back(TmpParam);
378 } else {
379 // If we failed to parse a template parameter, skip until we find
380 // a comma or closing brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000381 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
382 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000383 }
384
385 // Did we find a comma or the end of the template parameter list?
386 if (Tok.is(tok::comma)) {
387 ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000388 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000389 // Don't consume this... that's done by template parser.
390 break;
391 } else {
392 // Somebody probably forgot to close the template. Skip ahead and
393 // try to get out of the expression. This error is currently
394 // subsumed by whatever goes on in ParseTemplateParameter.
395 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000396 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
397 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000398 return false;
399 }
400 }
401 return true;
402}
403
404/// \brief Determine whether the parser is at the start of a template
405/// type parameter.
406bool Parser::isStartOfTemplateTypeParameter() {
407 if (Tok.is(tok::kw_class)) {
408 // "class" may be the start of an elaborated-type-specifier or a
409 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
410 switch (NextToken().getKind()) {
411 case tok::equal:
412 case tok::comma:
413 case tok::greater:
414 case tok::greatergreater:
415 case tok::ellipsis:
416 return true;
417
418 case tok::identifier:
419 // This may be either a type-parameter or an elaborated-type-specifier.
420 // We have to look further.
421 break;
422
423 default:
424 return false;
425 }
426
427 switch (GetLookAheadToken(2).getKind()) {
428 case tok::equal:
429 case tok::comma:
430 case tok::greater:
431 case tok::greatergreater:
432 return true;
433
434 default:
435 return false;
436 }
437 }
438
439 if (Tok.isNot(tok::kw_typename))
440 return false;
441
442 // C++ [temp.param]p2:
443 // There is no semantic difference between class and typename in a
444 // template-parameter. typename followed by an unqualified-id
445 // names a template type parameter. typename followed by a
446 // qualified-id denotes the type in a non-type
447 // parameter-declaration.
448 Token Next = NextToken();
449
450 // If we have an identifier, skip over it.
451 if (Next.getKind() == tok::identifier)
452 Next = GetLookAheadToken(2);
453
454 switch (Next.getKind()) {
455 case tok::equal:
456 case tok::comma:
457 case tok::greater:
458 case tok::greatergreater:
459 case tok::ellipsis:
460 return true;
461
462 default:
463 return false;
464 }
465}
466
467/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
468///
469/// template-parameter: [C++ temp.param]
470/// type-parameter
471/// parameter-declaration
472///
473/// type-parameter: (see below)
474/// 'class' ...[opt] identifier[opt]
475/// 'class' identifier[opt] '=' type-id
476/// 'typename' ...[opt] identifier[opt]
477/// 'typename' identifier[opt] '=' type-id
478/// 'template' '<' template-parameter-list '>'
479/// 'class' ...[opt] identifier[opt]
480/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
481/// = id-expression
482Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
483 if (isStartOfTemplateTypeParameter())
484 return ParseTypeParameter(Depth, Position);
485
486 if (Tok.is(tok::kw_template))
487 return ParseTemplateTemplateParameter(Depth, Position);
488
489 // If it's none of the above, then it must be a parameter declaration.
490 // NOTE: This will pick up errors in the closure of the template parameter
491 // list (e.g., template < ; Check here to implement >> style closures.
492 return ParseNonTypeTemplateParameter(Depth, Position);
493}
494
495/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
496/// Other kinds of template parameters are parsed in
497/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
498///
499/// type-parameter: [C++ temp.param]
500/// 'class' ...[opt][C++0x] identifier[opt]
501/// 'class' identifier[opt] '=' type-id
502/// 'typename' ...[opt][C++0x] identifier[opt]
503/// 'typename' identifier[opt] '=' type-id
504Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000505 assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +0000506 "A type-parameter starts with 'class' or 'typename'");
507
508 // Consume the 'class' or 'typename' keyword.
509 bool TypenameKeyword = Tok.is(tok::kw_typename);
510 SourceLocation KeyLoc = ConsumeToken();
511
512 // Grab the ellipsis (if given).
Faisal Vali6a79ca12013-06-08 19:39:00 +0000513 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000514 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000515 Diag(EllipsisLoc,
516 getLangOpts().CPlusPlus11
517 ? diag::warn_cxx98_compat_variadic_templates
518 : diag::ext_variadic_templates);
519 }
520
521 // Grab the template parameter name (if given)
522 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000523 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000524 if (Tok.is(tok::identifier)) {
525 ParamName = Tok.getIdentifierInfo();
526 NameLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000527 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
528 tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000529 // Unnamed template parameter. Don't have to do anything here, just
530 // don't consume this token.
531 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000532 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000533 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000534 }
535
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000536 // Recover from misplaced ellipsis.
537 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
538 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
539 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
540
Faisal Vali6a79ca12013-06-08 19:39:00 +0000541 // Grab a default argument (if available).
542 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
543 // we introduce the type parameter into the local scope.
544 SourceLocation EqualLoc;
545 ParsedType DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000546 if (TryConsumeToken(tok::equal, EqualLoc))
Craig Topper161e4db2014-05-21 06:02:52 +0000547 DefaultArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000548 Declarator::TemplateTypeArgContext).get();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000549
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000550 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
551 KeyLoc, ParamName, NameLoc, Depth, Position,
552 EqualLoc, DefaultArg);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000553}
554
555/// ParseTemplateTemplateParameter - Handle the parsing of template
556/// template parameters.
557///
558/// type-parameter: [C++ temp.param]
Richard Smith78e1ca62014-06-16 15:51:22 +0000559/// 'template' '<' template-parameter-list '>' type-parameter-key
Faisal Vali6a79ca12013-06-08 19:39:00 +0000560/// ...[opt] identifier[opt]
Richard Smith78e1ca62014-06-16 15:51:22 +0000561/// 'template' '<' template-parameter-list '>' type-parameter-key
562/// identifier[opt] = id-expression
563/// type-parameter-key:
564/// 'class'
565/// 'typename' [C++1z]
Faisal Vali6a79ca12013-06-08 19:39:00 +0000566Decl *
567Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
568 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
569
570 // Handle the template <...> part.
571 SourceLocation TemplateLoc = ConsumeToken();
572 SmallVector<Decl*,8> TemplateParams;
573 SourceLocation LAngleLoc, RAngleLoc;
574 {
575 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
576 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
577 RAngleLoc)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000578 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000579 }
580 }
581
Richard Smith78e1ca62014-06-16 15:51:22 +0000582 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000583 // Generate a meaningful error if the user forgot to put class before the
584 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
Richard Smith78e1ca62014-06-16 15:51:22 +0000585 // or greater appear immediately or after 'struct'. In the latter case,
586 // replace the keyword with 'class'.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000587 if (!TryConsumeToken(tok::kw_class)) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000588 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
Richard Smith78e1ca62014-06-16 15:51:22 +0000589 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
590 if (Tok.is(tok::kw_typename)) {
591 Diag(Tok.getLocation(),
592 getLangOpts().CPlusPlus1z
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000593 ? diag::warn_cxx14_compat_template_template_param_typename
Richard Smith78e1ca62014-06-16 15:51:22 +0000594 : diag::ext_template_template_param_typename)
595 << (!getLangOpts().CPlusPlus1z
596 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
597 : FixItHint());
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000598 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
599 tok::greatergreater, tok::ellipsis)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000600 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
601 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
602 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
Richard Smith78e1ca62014-06-16 15:51:22 +0000603 } else
Faisal Vali6a79ca12013-06-08 19:39:00 +0000604 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
605
606 if (Replace)
607 ConsumeToken();
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000608 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000609
610 // Parse the ellipsis, if given.
611 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000612 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000613 Diag(EllipsisLoc,
614 getLangOpts().CPlusPlus11
615 ? diag::warn_cxx98_compat_variadic_templates
616 : diag::ext_variadic_templates);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000617
618 // Get the identifier, if given.
619 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000620 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000621 if (Tok.is(tok::identifier)) {
622 ParamName = Tok.getIdentifierInfo();
623 NameLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000624 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
625 tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000626 // Unnamed template parameter. Don't have to do anything here, just
627 // don't consume this token.
628 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000629 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000630 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000631 }
632
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000633 // Recover from misplaced ellipsis.
634 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
635 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
636 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
637
Faisal Vali6a79ca12013-06-08 19:39:00 +0000638 TemplateParameterList *ParamList =
639 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
640 TemplateLoc, LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000641 TemplateParams,
Hubert Tongf608c052016-04-29 18:05:37 +0000642 RAngleLoc, nullptr);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000643
644 // Grab a default argument (if available).
645 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
646 // we introduce the template parameter into the local scope.
647 SourceLocation EqualLoc;
648 ParsedTemplateArgument DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000649 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000650 DefaultArg = ParseTemplateTemplateArgument();
651 if (DefaultArg.isInvalid()) {
652 Diag(Tok.getLocation(),
653 diag::err_default_template_template_parameter_not_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000654 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
655 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000656 }
657 }
658
659 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
660 ParamList, EllipsisLoc,
661 ParamName, NameLoc, Depth,
662 Position, EqualLoc, DefaultArg);
663}
664
665/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
666/// template parameters (e.g., in "template<int Size> class array;").
667///
668/// template-parameter:
669/// ...
670/// parameter-declaration
671Decl *
672Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
673 // Parse the declaration-specifiers (i.e., the type).
674 // FIXME: The type should probably be restricted in some way... Not all
675 // declarators (parts of declarators?) are accepted for parameters.
676 DeclSpec DS(AttrFactory);
677 ParseDeclarationSpecifiers(DS);
678
679 // Parse this as a typename.
680 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
681 ParseDeclarator(ParamDecl);
682 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
683 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
Craig Topper161e4db2014-05-21 06:02:52 +0000684 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000685 }
686
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000687 // Recover from misplaced ellipsis.
688 SourceLocation EllipsisLoc;
689 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
690 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
691
Faisal Vali6a79ca12013-06-08 19:39:00 +0000692 // If there is a default value, parse it.
693 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
694 // we introduce the template parameter into the local scope.
695 SourceLocation EqualLoc;
696 ExprResult DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000697 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000698 // C++ [temp.param]p15:
699 // When parsing a default template-argument for a non-type
700 // template-parameter, the first non-nested > is taken as the
701 // end of the template-parameter-list rather than a greater-than
702 // operator.
703 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Faisal Valid143a0c2017-04-01 21:30:49 +0000704 EnterExpressionEvaluationContext ConstantEvaluated(
705 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000706
Kaelyn Takata999dd852014-12-02 23:32:20 +0000707 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000708 if (DefaultArg.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +0000709 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000710 }
711
712 // Create the parameter.
713 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
714 Depth, Position, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000715 DefaultArg.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000716}
717
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000718void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
719 SourceLocation CorrectLoc,
720 bool AlreadyHasEllipsis,
721 bool IdentifierHasName) {
722 FixItHint Insertion;
723 if (!AlreadyHasEllipsis)
724 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
725 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
726 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
727 << !IdentifierHasName;
728}
729
730void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
731 Declarator &D) {
732 assert(EllipsisLoc.isValid());
733 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
734 if (!AlreadyHasEllipsis)
735 D.setEllipsisLoc(EllipsisLoc);
736 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
737 AlreadyHasEllipsis, D.hasName());
738}
739
Faisal Vali6a79ca12013-06-08 19:39:00 +0000740/// \brief Parses a '>' at the end of a template list.
741///
742/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
743/// to determine if these tokens were supposed to be a '>' followed by
744/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
745///
746/// \param RAngleLoc the location of the consumed '>'.
747///
Douglas Gregor85f3f952015-07-07 03:57:15 +0000748/// \param ConsumeLastToken if true, the '>' is consumed.
749///
750/// \param ObjCGenericList if true, this is the '>' closing an Objective-C
751/// type parameter or type argument list, rather than a C++ template parameter
752/// or argument list.
Serge Pavlovb716b3c2013-08-10 05:54:47 +0000753///
754/// \returns true, if current token does not start with '>', false otherwise.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000755bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000756 bool ConsumeLastToken,
757 bool ObjCGenericList) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000758 // What will be left once we've consumed the '>'.
759 tok::TokenKind RemainingToken;
760 const char *ReplacementStr = "> >";
761
762 switch (Tok.getKind()) {
763 default:
Alp Toker383d2c42014-01-01 03:08:43 +0000764 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000765 return true;
766
767 case tok::greater:
768 // Determine the location of the '>' token. Only consume this token
769 // if the caller asked us to.
770 RAngleLoc = Tok.getLocation();
771 if (ConsumeLastToken)
772 ConsumeToken();
773 return false;
774
775 case tok::greatergreater:
776 RemainingToken = tok::greater;
777 break;
778
779 case tok::greatergreatergreater:
780 RemainingToken = tok::greatergreater;
781 break;
782
783 case tok::greaterequal:
784 RemainingToken = tok::equal;
785 ReplacementStr = "> =";
786 break;
787
788 case tok::greatergreaterequal:
789 RemainingToken = tok::greaterequal;
790 break;
791 }
792
793 // This template-id is terminated by a token which starts with a '>'. Outside
794 // C++11, this is now error recovery, and in C++11, this is error recovery if
Eli Bendersky36a61932014-06-20 13:09:59 +0000795 // the token isn't '>>' or '>>>'.
796 // '>>>' is for CUDA, where this sequence of characters is parsed into
797 // tok::greatergreatergreater, rather than two separate tokens.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000798 //
799 // We always allow this for Objective-C type parameter and type argument
800 // lists.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000801 RAngleLoc = Tok.getLocation();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000802 Token Next = NextToken();
Douglas Gregor85f3f952015-07-07 03:57:15 +0000803 if (!ObjCGenericList) {
804 // The source range of the '>>' or '>=' at the start of the token.
805 CharSourceRange ReplacementRange =
806 CharSourceRange::getCharRange(RAngleLoc,
807 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
808 getLangOpts()));
Faisal Vali6a79ca12013-06-08 19:39:00 +0000809
Douglas Gregor85f3f952015-07-07 03:57:15 +0000810 // A hint to put a space between the '>>'s. In order to make the hint as
811 // clear as possible, we include the characters either side of the space in
812 // the replacement, rather than just inserting a space at SecondCharLoc.
813 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
814 ReplacementStr);
815
816 // A hint to put another space after the token, if it would otherwise be
817 // lexed differently.
818 FixItHint Hint2;
819 if ((RemainingToken == tok::greater ||
820 RemainingToken == tok::greatergreater) &&
821 (Next.isOneOf(tok::greater, tok::greatergreater,
822 tok::greatergreatergreater, tok::equal,
823 tok::greaterequal, tok::greatergreaterequal,
824 tok::equalequal)) &&
825 areTokensAdjacent(Tok, Next))
826 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
827
828 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
829 if (getLangOpts().CPlusPlus11 &&
830 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
831 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
832 else if (Tok.is(tok::greaterequal))
833 DiagId = diag::err_right_angle_bracket_equal_needs_space;
834 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
835 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000836
837 // Strip the initial '>' from the token.
Bruno Cardoso Lopes428a5aa2016-01-31 00:47:51 +0000838 Token PrevTok = Tok;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000839 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
840 areTokensAdjacent(Tok, Next)) {
841 // Join two adjacent '=' tokens into one, for cases like:
842 // void (*p)() = f<int>;
843 // return f<int>==p;
844 ConsumeToken();
845 Tok.setKind(tok::equalequal);
846 Tok.setLength(Tok.getLength() + 1);
847 } else {
848 Tok.setKind(RemainingToken);
849 Tok.setLength(Tok.getLength() - 1);
850 }
851 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
852 PP.getSourceManager(),
853 getLangOpts()));
854
Bruno Cardoso Lopes428a5aa2016-01-31 00:47:51 +0000855 // The advance from '>>' to '>' in a ObjectiveC template argument list needs
856 // to be properly reflected in the token cache to allow correct interaction
857 // between annotation and backtracking.
858 if (ObjCGenericList && PrevTok.getKind() == tok::greatergreater &&
859 RemainingToken == tok::greater && PP.IsPreviousCachedToken(PrevTok)) {
860 PrevTok.setKind(RemainingToken);
861 PrevTok.setLength(1);
Bruno Cardoso Lopesfb9b6cd2016-02-05 19:36:39 +0000862 // Break tok::greatergreater into two tok::greater but only add the second
863 // one in case the client asks to consume the last token.
864 if (ConsumeLastToken)
865 PP.ReplacePreviousCachedToken({PrevTok, Tok});
866 else
867 PP.ReplacePreviousCachedToken({PrevTok});
Bruno Cardoso Lopes428a5aa2016-01-31 00:47:51 +0000868 }
869
Faisal Vali6a79ca12013-06-08 19:39:00 +0000870 if (!ConsumeLastToken) {
871 // Since we're not supposed to consume the '>' token, we need to push
872 // this token and revert the current token back to the '>'.
873 PP.EnterToken(Tok);
874 Tok.setKind(tok::greater);
875 Tok.setLength(1);
876 Tok.setLocation(RAngleLoc);
877 }
878 return false;
879}
880
881
882/// \brief Parses a template-id that after the template name has
883/// already been parsed.
884///
885/// This routine takes care of parsing the enclosed template argument
886/// list ('<' template-parameter-list [opt] '>') and placing the
887/// results into a form that can be transferred to semantic analysis.
888///
Faisal Vali6a79ca12013-06-08 19:39:00 +0000889/// \param ConsumeLastToken if true, then we will consume the last
890/// token that forms the template-id. Otherwise, we will leave the
891/// last token in the stream (e.g., so that it can be replaced with an
892/// annotation token).
893bool
Richard Smith9a420f92017-05-10 21:47:30 +0000894Parser::ParseTemplateIdAfterTemplateName(bool ConsumeLastToken,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000895 SourceLocation &LAngleLoc,
896 TemplateArgList &TemplateArgs,
897 SourceLocation &RAngleLoc) {
898 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
899
900 // Consume the '<'.
901 LAngleLoc = ConsumeToken();
902
903 // Parse the optional template-argument-list.
904 bool Invalid = false;
905 {
906 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
907 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
908 Invalid = ParseTemplateArgumentList(TemplateArgs);
909
910 if (Invalid) {
911 // Try to find the closing '>'.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000912 if (ConsumeLastToken)
913 SkipUntil(tok::greater, StopAtSemi);
914 else
915 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000916 return true;
917 }
918 }
919
Douglas Gregor85f3f952015-07-07 03:57:15 +0000920 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
921 /*ObjCGenericList=*/false);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000922}
923
924/// \brief Replace the tokens that form a simple-template-id with an
925/// annotation token containing the complete template-id.
926///
927/// The first token in the stream must be the name of a template that
928/// is followed by a '<'. This routine will parse the complete
929/// simple-template-id and replace the tokens with a single annotation
930/// token with one of two different kinds: if the template-id names a
931/// type (and \p AllowTypeAnnotation is true), the annotation token is
932/// a type annotation that includes the optional nested-name-specifier
933/// (\p SS). Otherwise, the annotation token is a template-id
934/// annotation that does not include the optional
935/// nested-name-specifier.
936///
937/// \param Template the declaration of the template named by the first
938/// token (an identifier), as returned from \c Action::isTemplateName().
939///
940/// \param TNK the kind of template that \p Template
941/// refers to, as returned from \c Action::isTemplateName().
942///
943/// \param SS if non-NULL, the nested-name-specifier that precedes
944/// this template name.
945///
946/// \param TemplateKWLoc if valid, specifies that this template-id
947/// annotation was preceded by the 'template' keyword and gives the
948/// location of that keyword. If invalid (the default), then this
949/// template-id was not preceded by a 'template' keyword.
950///
951/// \param AllowTypeAnnotation if true (the default), then a
952/// simple-template-id that refers to a class template, template
953/// template parameter, or other template that produces a type will be
954/// replaced with a type annotation token. Otherwise, the
955/// simple-template-id is always replaced with a template-id
956/// annotation token.
957///
958/// If an unrecoverable parse error occurs and no annotation token can be
959/// formed, this function returns true.
960///
961bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
962 CXXScopeSpec &SS,
963 SourceLocation TemplateKWLoc,
964 UnqualifiedId &TemplateName,
965 bool AllowTypeAnnotation) {
966 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
967 assert(Template && Tok.is(tok::less) &&
968 "Parser isn't at the beginning of a template-id");
969
970 // Consume the template-name.
971 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
972
973 // Parse the enclosed template argument list.
974 SourceLocation LAngleLoc, RAngleLoc;
975 TemplateArgList TemplateArgs;
Richard Smith9a420f92017-05-10 21:47:30 +0000976 bool Invalid = ParseTemplateIdAfterTemplateName(false, LAngleLoc,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000977 TemplateArgs,
978 RAngleLoc);
979
980 if (Invalid) {
981 // If we failed to parse the template ID but skipped ahead to a >, we're not
982 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000983 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000984 return true;
985 }
986
987 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
988
989 // Build the annotation token.
990 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
Richard Smith74f02342017-01-19 21:00:13 +0000991 TypeResult Type = Actions.ActOnTemplateIdType(
992 SS, TemplateKWLoc, Template, TemplateName.Identifier,
993 TemplateNameLoc, LAngleLoc, TemplateArgsPtr, RAngleLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000994 if (Type.isInvalid()) {
Richard Smith74f02342017-01-19 21:00:13 +0000995 // If we failed to parse the template ID but skipped ahead to a >, we're
996 // not going to be able to form a token annotation. Eat the '>' if
997 // present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000998 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000999 return true;
1000 }
1001
1002 Tok.setKind(tok::annot_typename);
1003 setTypeAnnotation(Tok, Type.get());
1004 if (SS.isNotEmpty())
1005 Tok.setLocation(SS.getBeginLoc());
1006 else if (TemplateKWLoc.isValid())
1007 Tok.setLocation(TemplateKWLoc);
1008 else
1009 Tok.setLocation(TemplateNameLoc);
1010 } else {
1011 // Build a template-id annotation token that can be processed
1012 // later.
1013 Tok.setKind(tok::annot_template_id);
1014 TemplateIdAnnotation *TemplateId
1015 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
1016 TemplateId->TemplateNameLoc = TemplateNameLoc;
1017 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
1018 TemplateId->Name = TemplateName.Identifier;
1019 TemplateId->Operator = OO_None;
1020 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001021 TemplateId->Name = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001022 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
1023 }
1024 TemplateId->SS = SS;
1025 TemplateId->TemplateKWLoc = TemplateKWLoc;
1026 TemplateId->Template = Template;
1027 TemplateId->Kind = TNK;
1028 TemplateId->LAngleLoc = LAngleLoc;
1029 TemplateId->RAngleLoc = RAngleLoc;
1030 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1031 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
1032 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
1033 Tok.setAnnotationValue(TemplateId);
1034 if (TemplateKWLoc.isValid())
1035 Tok.setLocation(TemplateKWLoc);
1036 else
1037 Tok.setLocation(TemplateNameLoc);
1038 }
1039
1040 // Common fields for the annotation token
1041 Tok.setAnnotationEndLoc(RAngleLoc);
1042
1043 // In case the tokens were cached, have Preprocessor replace them with the
1044 // annotation token.
1045 PP.AnnotateCachedTokens(Tok);
1046 return false;
1047}
1048
1049/// \brief Replaces a template-id annotation token with a type
1050/// annotation token.
1051///
1052/// If there was a failure when forming the type from the template-id,
1053/// a type annotation token will still be created, but will have a
1054/// NULL type pointer to signify an error.
Richard Smith62559bd2017-02-01 21:36:38 +00001055///
1056/// \param IsClassName Is this template-id appearing in a context where we
1057/// know it names a class, such as in an elaborated-type-specifier or
1058/// base-specifier? ('typename' and 'template' are unneeded and disallowed
1059/// in those contexts.)
1060void Parser::AnnotateTemplateIdTokenAsType(bool IsClassName) {
Faisal Vali6a79ca12013-06-08 19:39:00 +00001061 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1062
1063 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1064 assert((TemplateId->Kind == TNK_Type_template ||
1065 TemplateId->Kind == TNK_Dependent_template_name) &&
1066 "Only works for type and dependent templates");
1067
1068 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1069 TemplateId->NumArgs);
1070
1071 TypeResult Type
1072 = Actions.ActOnTemplateIdType(TemplateId->SS,
1073 TemplateId->TemplateKWLoc,
1074 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00001075 TemplateId->Name,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001076 TemplateId->TemplateNameLoc,
1077 TemplateId->LAngleLoc,
1078 TemplateArgsPtr,
Richard Smith62559bd2017-02-01 21:36:38 +00001079 TemplateId->RAngleLoc,
1080 /*IsCtorOrDtorName*/false,
1081 IsClassName);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001082 // Create the new "type" annotation token.
1083 Tok.setKind(tok::annot_typename);
David Blaikieefdccaa2016-01-15 23:43:34 +00001084 setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001085 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1086 Tok.setLocation(TemplateId->SS.getBeginLoc());
1087 // End location stays the same
1088
1089 // Replace the template-id annotation token, and possible the scope-specifier
1090 // that precedes it, with the typename annotation token.
1091 PP.AnnotateCachedTokens(Tok);
1092}
1093
1094/// \brief Determine whether the given token can end a template argument.
1095static bool isEndOfTemplateArgument(Token Tok) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001096 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001097}
1098
1099/// \brief Parse a C++ template template argument.
1100ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1101 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1102 !Tok.is(tok::annot_cxxscope))
1103 return ParsedTemplateArgument();
1104
1105 // C++0x [temp.arg.template]p1:
1106 // A template-argument for a template template-parameter shall be the name
1107 // of a class template or an alias template, expressed as id-expression.
1108 //
1109 // We parse an id-expression that refers to a class template or alias
1110 // template. The grammar we parse is:
1111 //
1112 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1113 //
1114 // followed by a token that terminates a template argument, such as ',',
1115 // '>', or (in some cases) '>>'.
1116 CXXScopeSpec SS; // nested-name-specifier, if present
David Blaikieefdccaa2016-01-15 23:43:34 +00001117 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001118 /*EnteringContext=*/false);
David Blaikieefdccaa2016-01-15 23:43:34 +00001119
Faisal Vali6a79ca12013-06-08 19:39:00 +00001120 ParsedTemplateArgument Result;
1121 SourceLocation EllipsisLoc;
1122 if (SS.isSet() && Tok.is(tok::kw_template)) {
1123 // Parse the optional 'template' keyword following the
1124 // nested-name-specifier.
1125 SourceLocation TemplateKWLoc = ConsumeToken();
1126
1127 if (Tok.is(tok::identifier)) {
1128 // We appear to have a dependent template name.
1129 UnqualifiedId Name;
1130 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1131 ConsumeToken(); // the identifier
Alp Toker094e5212014-01-05 03:27:11 +00001132
1133 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1134
Faisal Vali6a79ca12013-06-08 19:39:00 +00001135 // If the next token signals the end of a template argument,
1136 // then we have a dependent template name that could be a template
1137 // template argument.
1138 TemplateTy Template;
1139 if (isEndOfTemplateArgument(Tok) &&
David Blaikieefdccaa2016-01-15 23:43:34 +00001140 Actions.ActOnDependentTemplateName(
1141 getCurScope(), SS, TemplateKWLoc, Name,
1142 /*ObjectType=*/nullptr,
1143 /*EnteringContext=*/false, Template))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001144 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1145 }
1146 } else if (Tok.is(tok::identifier)) {
1147 // We may have a (non-dependent) template name.
1148 TemplateTy Template;
1149 UnqualifiedId Name;
1150 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1151 ConsumeToken(); // the identifier
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001152
1153 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001154
1155 if (isEndOfTemplateArgument(Tok)) {
1156 bool MemberOfUnknownSpecialization;
David Blaikieefdccaa2016-01-15 23:43:34 +00001157 TemplateNameKind TNK = Actions.isTemplateName(
1158 getCurScope(), SS,
1159 /*hasTemplateKeyword=*/false, Name,
1160 /*ObjectType=*/nullptr,
1161 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001162 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1163 // We have an id-expression that refers to a class template or
1164 // (C++0x) alias template.
1165 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1166 }
1167 }
1168 }
1169
1170 // If this is a pack expansion, build it as such.
1171 if (EllipsisLoc.isValid() && !Result.isInvalid())
1172 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1173
1174 return Result;
1175}
1176
1177/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1178///
1179/// template-argument: [C++ 14.2]
1180/// constant-expression
1181/// type-id
1182/// id-expression
1183ParsedTemplateArgument Parser::ParseTemplateArgument() {
1184 // C++ [temp.arg]p2:
1185 // In a template-argument, an ambiguity between a type-id and an
1186 // expression is resolved to a type-id, regardless of the form of
1187 // the corresponding template-parameter.
1188 //
1189 // Therefore, we initially try to parse a type-id.
1190 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1191 SourceLocation Loc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00001192 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001193 Declarator::TemplateTypeArgContext);
1194 if (TypeArg.isInvalid())
1195 return ParsedTemplateArgument();
1196
1197 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1198 TypeArg.get().getAsOpaquePtr(),
1199 Loc);
1200 }
1201
1202 // Try to parse a template template argument.
1203 {
1204 TentativeParsingAction TPA(*this);
1205
1206 ParsedTemplateArgument TemplateTemplateArgument
1207 = ParseTemplateTemplateArgument();
1208 if (!TemplateTemplateArgument.isInvalid()) {
1209 TPA.Commit();
1210 return TemplateTemplateArgument;
1211 }
1212
1213 // Revert this tentative parse to parse a non-type template argument.
1214 TPA.Revert();
1215 }
1216
1217 // Parse a non-type template argument.
1218 SourceLocation Loc = Tok.getLocation();
1219 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1220 if (ExprArg.isInvalid() || !ExprArg.get())
1221 return ParsedTemplateArgument();
1222
1223 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001224 ExprArg.get(), Loc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001225}
1226
1227/// \brief Determine whether the current tokens can only be parsed as a
1228/// template argument list (starting with the '<') and never as a '<'
1229/// expression.
1230bool Parser::IsTemplateArgumentList(unsigned Skip) {
1231 struct AlwaysRevertAction : TentativeParsingAction {
1232 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1233 ~AlwaysRevertAction() { Revert(); }
1234 } Tentative(*this);
1235
1236 while (Skip) {
Richard Smithaf3b3252017-05-18 19:21:48 +00001237 ConsumeAnyToken();
Faisal Vali6a79ca12013-06-08 19:39:00 +00001238 --Skip;
1239 }
1240
1241 // '<'
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001242 if (!TryConsumeToken(tok::less))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001243 return false;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001244
1245 // An empty template argument list.
1246 if (Tok.is(tok::greater))
1247 return true;
1248
1249 // See whether we have declaration specifiers, which indicate a type.
Richard Smithee390432014-05-16 01:56:53 +00001250 while (isCXXDeclarationSpecifier() == TPResult::True)
Richard Smithaf3b3252017-05-18 19:21:48 +00001251 ConsumeAnyToken();
Faisal Vali6a79ca12013-06-08 19:39:00 +00001252
1253 // If we have a '>' or a ',' then this is a template argument list.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001254 return Tok.isOneOf(tok::greater, tok::comma);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001255}
1256
1257/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1258/// (C++ [temp.names]). Returns true if there was an error.
1259///
1260/// template-argument-list: [C++ 14.2]
1261/// template-argument
1262/// template-argument-list ',' template-argument
1263bool
1264Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1265 // Template argument lists are constant-evaluation contexts.
Faisal Valid143a0c2017-04-01 21:30:49 +00001266 EnterExpressionEvaluationContext EvalContext(
1267 Actions, Sema::ExpressionEvaluationContext::ConstantEvaluated);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +00001268 ColonProtectionRAIIObject ColonProtection(*this, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001269
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001270 do {
Faisal Vali6a79ca12013-06-08 19:39:00 +00001271 ParsedTemplateArgument Arg = ParseTemplateArgument();
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001272 SourceLocation EllipsisLoc;
1273 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001274 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001275
1276 if (Arg.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001277 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001278 return true;
1279 }
1280
1281 // Save this template argument.
1282 TemplateArgs.push_back(Arg);
1283
1284 // If the next token is a comma, consume it and keep reading
1285 // arguments.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001286 } while (TryConsumeToken(tok::comma));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001287
1288 return false;
1289}
1290
1291/// \brief Parse a C++ explicit template instantiation
1292/// (C++ [temp.explicit]).
1293///
1294/// explicit-instantiation:
1295/// 'extern' [opt] 'template' declaration
1296///
1297/// Note that the 'extern' is a GNU extension and C++11 feature.
1298Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1299 SourceLocation ExternLoc,
1300 SourceLocation TemplateLoc,
1301 SourceLocation &DeclEnd,
1302 AccessSpecifier AS) {
1303 // This isn't really required here.
1304 ParsingDeclRAIIObject
1305 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1306
1307 return ParseSingleDeclarationAfterTemplate(Context,
1308 ParsedTemplateInfo(ExternLoc,
1309 TemplateLoc),
1310 ParsingTemplateParams,
1311 DeclEnd, AS);
1312}
1313
1314SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1315 if (TemplateParams)
1316 return getTemplateParamsRange(TemplateParams->data(),
1317 TemplateParams->size());
1318
1319 SourceRange R(TemplateLoc);
1320 if (ExternLoc.isValid())
1321 R.setBegin(ExternLoc);
1322 return R;
1323}
1324
Richard Smithe40f2ba2013-08-07 21:41:30 +00001325void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1326 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001327}
1328
1329/// \brief Late parse a C++ function template in Microsoft mode.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001330void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
David Majnemerf0a84f22013-08-16 08:29:13 +00001331 if (!LPT.D)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001332 return;
1333
1334 // Get the FunctionDecl.
Alp Tokera2794f92014-01-22 07:29:52 +00001335 FunctionDecl *FunD = LPT.D->getAsFunction();
Faisal Vali6a79ca12013-06-08 19:39:00 +00001336 // Track template parameter depth.
1337 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1338
1339 // To restore the context after late parsing.
Richard Smithb0b68012015-05-11 23:09:06 +00001340 Sema::ContextRAII GlobalSavedContext(
1341 Actions, Actions.Context.getTranslationUnitDecl());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001342
1343 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1344
1345 // Get the list of DeclContexts to reenter.
1346 SmallVector<DeclContext*, 4> DeclContextsToReenter;
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001347 DeclContext *DD = FunD;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001348 while (DD && !DD->isTranslationUnit()) {
1349 DeclContextsToReenter.push_back(DD);
1350 DD = DD->getLexicalParent();
1351 }
1352
1353 // Reenter template scopes from outermost to innermost.
Craig Topper61ac9062013-07-08 03:55:09 +00001354 SmallVectorImpl<DeclContext *>::reverse_iterator II =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001355 DeclContextsToReenter.rbegin();
1356 for (; II != DeclContextsToReenter.rend(); ++II) {
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001357 TemplateParamScopeStack.push_back(new ParseScope(this,
1358 Scope::TemplateParamScope));
1359 unsigned NumParamLists =
1360 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1361 CurTemplateDepthTracker.addDepth(NumParamLists);
1362 if (*II != FunD) {
1363 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1364 Actions.PushDeclContext(Actions.getCurScope(), *II);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001365 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001366 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001367
Richard Smithe40f2ba2013-08-07 21:41:30 +00001368 assert(!LPT.Toks.empty() && "Empty body!");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001369
1370 // Append the current token at the end of the new token stream so that it
1371 // doesn't get lost.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001372 LPT.Toks.push_back(Tok);
David Blaikie2eabcc92016-02-09 18:52:09 +00001373 PP.EnterTokenStream(LPT.Toks, true);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001374
1375 // Consume the previously pushed token.
1376 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001377 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1378 "Inline method not starting with '{', ':' or 'try'");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001379
1380 // Parse the method body. Function body parsing code is similar enough
1381 // to be re-used for method bodies as well.
1382 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1383
1384 // Recreate the containing function DeclContext.
Nico Weber55048cf2014-08-15 22:15:00 +00001385 Sema::ContextRAII FunctionSavedContext(Actions,
1386 Actions.getContainingDC(FunD));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001387
1388 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1389
1390 if (Tok.is(tok::kw_try)) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00001391 ParseFunctionTryBlock(LPT.D, FnScope);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001392 } else {
1393 if (Tok.is(tok::colon))
Richard Smithe40f2ba2013-08-07 21:41:30 +00001394 ParseConstructorInitializer(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001395 else
Richard Smithe40f2ba2013-08-07 21:41:30 +00001396 Actions.ActOnDefaultCtorInitializers(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001397
1398 if (Tok.is(tok::l_brace)) {
Alp Tokera2794f92014-01-22 07:29:52 +00001399 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1400 cast<FunctionTemplateDecl>(LPT.D)
1401 ->getTemplateParameters()
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001402 ->getDepth() == TemplateParameterDepth - 1) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +00001403 "TemplateParameterDepth should be greater than the depth of "
1404 "current template being instantiated!");
Richard Smithe40f2ba2013-08-07 21:41:30 +00001405 ParseFunctionStatementBody(LPT.D, FnScope);
1406 Actions.UnmarkAsLateParsedTemplate(FunD);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001407 } else
Craig Topper161e4db2014-05-21 06:02:52 +00001408 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001409 }
1410
1411 // Exit scopes.
1412 FnScope.Exit();
Craig Topper61ac9062013-07-08 03:55:09 +00001413 SmallVectorImpl<ParseScope *>::reverse_iterator I =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001414 TemplateParamScopeStack.rbegin();
1415 for (; I != TemplateParamScopeStack.rend(); ++I)
1416 delete *I;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001417}
1418
1419/// \brief Lex a delayed template function for late parsing.
1420void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1421 tok::TokenKind kind = Tok.getKind();
1422 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1423 // Consume everything up to (and including) the matching right brace.
1424 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1425 }
1426
1427 // If we're in a function-try-block, we need to store all the catch blocks.
1428 if (kind == tok::kw_try) {
1429 while (Tok.is(tok::kw_catch)) {
1430 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1431 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1432 }
1433 }
1434}