blob: fffc40ee4e1f092f69338c43d6567782ffebab7c [file] [log] [blame]
Faisal Vali6a79ca12013-06-08 19:39:00 +00001//===--- ParseTemplate.cpp - Template Parsing -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements parsing of C++ templates.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
15#include "RAIIObjectsForParser.h"
16#include "clang/AST/ASTConsumer.h"
Richard Smithb0b68012015-05-11 23:09:06 +000017#include "clang/AST/ASTContext.h"
Faisal Vali6a79ca12013-06-08 19:39:00 +000018#include "clang/AST/DeclTemplate.h"
19#include "clang/Parse/ParseDiagnostic.h"
20#include "clang/Sema/DeclSpec.h"
21#include "clang/Sema/ParsedTemplate.h"
22#include "clang/Sema/Scope.h"
23using namespace clang;
24
25/// \brief Parse a template declaration, explicit instantiation, or
26/// explicit specialization.
27Decl *
28Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
29 SourceLocation &DeclEnd,
30 AccessSpecifier AS,
31 AttributeList *AccessAttrs) {
32 ObjCDeclContextSwitch ObjCDC(*this);
33
34 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
35 return ParseExplicitInstantiation(Context,
36 SourceLocation(), ConsumeToken(),
37 DeclEnd, AS);
38 }
39 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
40 AccessAttrs);
41}
42
43
44
45/// \brief Parse a template declaration or an explicit specialization.
46///
47/// Template declarations include one or more template parameter lists
48/// and either the function or class template declaration. Explicit
49/// specializations contain one or more 'template < >' prefixes
50/// followed by a (possibly templated) declaration. Since the
51/// syntactic form of both features is nearly identical, we parse all
52/// of the template headers together and let semantic analysis sort
53/// the declarations from the explicit specializations.
54///
55/// template-declaration: [C++ temp]
56/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
57///
58/// explicit-specialization: [ C++ temp.expl.spec]
59/// 'template' '<' '>' declaration
60Decl *
61Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
62 SourceLocation &DeclEnd,
63 AccessSpecifier AS,
64 AttributeList *AccessAttrs) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +000065 assert(Tok.isOneOf(tok::kw_export, tok::kw_template) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +000066 "Token does not start a template declaration.");
67
68 // Enter template-parameter scope.
69 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
70
71 // Tell the action that names should be checked in the context of
72 // the declaration to come.
73 ParsingDeclRAIIObject
74 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
75
76 // Parse multiple levels of template headers within this template
77 // parameter scope, e.g.,
78 //
79 // template<typename T>
80 // template<typename U>
81 // class A<T>::B { ... };
82 //
83 // We parse multiple levels non-recursively so that we can build a
84 // single data structure containing all of the template parameter
85 // lists to easily differentiate between the case above and:
86 //
87 // template<typename T>
88 // class A {
89 // template<typename U> class B;
90 // };
91 //
92 // In the first case, the action for declaring A<T>::B receives
93 // both template parameter lists. In the second case, the action for
94 // defining A<T>::B receives just the inner template parameter list
95 // (and retrieves the outer template parameter list from its
96 // context).
97 bool isSpecialization = true;
98 bool LastParamListWasEmpty = false;
99 TemplateParameterLists ParamLists;
100 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
101
102 do {
103 // Consume the 'export', if any.
104 SourceLocation ExportLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000105 TryConsumeToken(tok::kw_export, ExportLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000106
107 // Consume the 'template', which should be here.
108 SourceLocation TemplateLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000109 if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000110 Diag(Tok.getLocation(), diag::err_expected_template);
Craig Topper161e4db2014-05-21 06:02:52 +0000111 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000112 }
113
114 // Parse the '<' template-parameter-list '>'
115 SourceLocation LAngleLoc, RAngleLoc;
116 SmallVector<Decl*, 4> TemplateParams;
117 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
118 TemplateParams, LAngleLoc, RAngleLoc)) {
Hubert Tongec3cb572015-06-25 00:23:39 +0000119 // 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,
Craig Topper96225a52015-12-24 23:58:25 +0000129 TemplateParams, RAngleLoc));
Faisal Vali6a79ca12013-06-08 19:39:00 +0000130
131 if (!TemplateParams.empty()) {
132 isSpecialization = false;
133 ++CurTemplateDepthTracker;
Hubert Tongec3cb572015-06-25 00:23:39 +0000134
135 if (TryConsumeToken(tok::kw_requires)) {
136 ExprResult ER =
137 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
138 if (!ER.isUsable()) {
139 // Skip until the semi-colon or a '}'.
140 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
141 TryConsumeToken(tok::semi);
142 return nullptr;
143 }
144 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000145 } else {
146 LastParamListWasEmpty = true;
147 }
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000148 } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
Faisal Vali6a79ca12013-06-08 19:39:00 +0000149
150 // Parse the actual template declaration.
151 return ParseSingleDeclarationAfterTemplate(Context,
152 ParsedTemplateInfo(&ParamLists,
153 isSpecialization,
154 LastParamListWasEmpty),
155 ParsingTemplateParams,
156 DeclEnd, AS, AccessAttrs);
157}
158
159/// \brief Parse a single declaration that declares a template,
160/// template specialization, or explicit instantiation of a template.
161///
162/// \param DeclEnd will receive the source location of the last token
163/// within this declaration.
164///
165/// \param AS the access specifier associated with this
166/// declaration. Will be AS_none for namespace-scope declarations.
167///
168/// \returns the new declaration.
169Decl *
170Parser::ParseSingleDeclarationAfterTemplate(
171 unsigned Context,
172 const ParsedTemplateInfo &TemplateInfo,
173 ParsingDeclRAIIObject &DiagsFromTParams,
174 SourceLocation &DeclEnd,
175 AccessSpecifier AS,
176 AttributeList *AccessAttrs) {
177 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
178 "Template information required");
179
Aaron Ballmane7c544d2014-08-04 20:28:35 +0000180 if (Tok.is(tok::kw_static_assert)) {
181 // A static_assert declaration may not be templated.
182 Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
183 << TemplateInfo.getSourceRange();
184 // Parse the static_assert declaration to improve error recovery.
185 return ParseStaticAssertDeclaration(DeclEnd);
186 }
187
Faisal Vali6a79ca12013-06-08 19:39:00 +0000188 if (Context == Declarator::MemberContext) {
189 // We are parsing a member template.
190 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
191 &DiagsFromTParams);
Craig Topper161e4db2014-05-21 06:02:52 +0000192 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000193 }
194
195 ParsedAttributesWithRange prefixAttrs(AttrFactory);
196 MaybeParseCXX11Attributes(prefixAttrs);
197
198 if (Tok.is(tok::kw_using))
199 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
200 prefixAttrs);
201
202 // Parse the declaration specifiers, stealing any diagnostics from
203 // the template parameters.
204 ParsingDeclSpec DS(*this, &DiagsFromTParams);
205
206 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
207 getDeclSpecContextFromDeclaratorContext(Context));
208
209 if (Tok.is(tok::semi)) {
210 ProhibitAttributes(prefixAttrs);
211 DeclEnd = ConsumeToken();
Nico Weber7b837f52016-01-28 19:25:00 +0000212 RecordDecl *AnonRecord = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000213 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
214 getCurScope(), AS, DS,
215 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
216 : MultiTemplateParamsArg(),
Nico Weber7b837f52016-01-28 19:25:00 +0000217 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
218 AnonRecord);
219 assert(!AnonRecord &&
220 "Anonymous unions/structs should not be valid with template");
Faisal Vali6a79ca12013-06-08 19:39:00 +0000221 DS.complete(Decl);
222 return Decl;
223 }
224
225 // Move the attributes from the prefix into the DS.
226 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
227 ProhibitAttributes(prefixAttrs);
228 else
229 DS.takeAttributesFrom(prefixAttrs);
230
231 // Parse the declarator.
232 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
233 ParseDeclarator(DeclaratorInfo);
234 // Error parsing the declarator?
235 if (!DeclaratorInfo.hasName()) {
236 // If so, skip until the semi-colon or a }.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000237 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000238 if (Tok.is(tok::semi))
239 ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000240 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000241 }
242
243 LateParsedAttrList LateParsedAttrs(true);
244 if (DeclaratorInfo.isFunctionDeclarator())
245 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
246
247 if (DeclaratorInfo.isFunctionDeclarator() &&
248 isStartOfFunctionDefinition(DeclaratorInfo)) {
Reid Klecknerd61a3112014-12-15 23:16:32 +0000249
250 // Function definitions are only allowed at file scope and in C++ classes.
251 // The C++ inline method definition case is handled elsewhere, so we only
252 // need to handle the file scope definition case.
253 if (Context != Declarator::FileContext) {
254 Diag(Tok, diag::err_function_definition_not_allowed);
255 SkipMalformedDecl();
256 return nullptr;
257 }
258
Faisal Vali6a79ca12013-06-08 19:39:00 +0000259 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
260 // Recover by ignoring the 'typedef'. This was probably supposed to be
261 // the 'typename' keyword, which we should have already suggested adding
262 // if it's appropriate.
263 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
264 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
265 DS.ClearStorageClassSpecs();
266 }
Larisse Voufo725de3e2013-06-21 00:08:46 +0000267
268 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
269 if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
270 // If the declarator-id is not a template-id, issue a diagnostic and
271 // recover by ignoring the 'template' keyword.
272 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000273 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
274 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000275 } else {
276 SourceLocation LAngleLoc
277 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000278 Diag(DeclaratorInfo.getIdentifierLoc(),
Larisse Voufo725de3e2013-06-21 00:08:46 +0000279 diag::err_explicit_instantiation_with_definition)
Larisse Voufo39a1e502013-08-06 01:03:05 +0000280 << SourceRange(TemplateInfo.TemplateLoc)
281 << FixItHint::CreateInsertion(LAngleLoc, "<>");
Larisse Voufo725de3e2013-06-21 00:08:46 +0000282
Larisse Voufo39a1e502013-08-06 01:03:05 +0000283 // Recover as if it were an explicit specialization.
Larisse Voufob9bbaba2013-06-22 13:56:11 +0000284 TemplateParameterLists FakedParamLists;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000285 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +0000286 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
287 LAngleLoc));
Larisse Voufo725de3e2013-06-21 00:08:46 +0000288
Larisse Voufo39a1e502013-08-06 01:03:05 +0000289 return ParseFunctionDefinition(
290 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
291 /*isSpecialization=*/true,
292 /*LastParamListWasEmpty=*/true),
293 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000294 }
295 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000296 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
Larisse Voufo39a1e502013-08-06 01:03:05 +0000297 &LateParsedAttrs);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000298 }
299
300 // Parse this declaration.
301 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
302 TemplateInfo);
303
304 if (Tok.is(tok::comma)) {
305 Diag(Tok, diag::err_multiple_template_declarators)
306 << (int)TemplateInfo.Kind;
Alexey Bataevee6507d2013-11-18 08:17:37 +0000307 SkipUntil(tok::semi);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000308 return ThisDecl;
309 }
310
311 // Eat the semi colon after the declaration.
312 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
313 if (LateParsedAttrs.size() > 0)
314 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
315 DeclaratorInfo.complete(ThisDecl);
316 return ThisDecl;
317}
318
319/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
320/// angle brackets. Depth is the depth of this template-parameter-list, which
321/// is the number of template headers directly enclosing this template header.
322/// TemplateParams is the current list of template parameters we're building.
323/// The template parameter we parse will be added to this list. LAngleLoc and
324/// RAngleLoc will receive the positions of the '<' and '>', respectively,
325/// that enclose this template parameter list.
326///
327/// \returns true if an error occurred, false otherwise.
328bool Parser::ParseTemplateParameters(unsigned Depth,
329 SmallVectorImpl<Decl*> &TemplateParams,
330 SourceLocation &LAngleLoc,
331 SourceLocation &RAngleLoc) {
332 // Get the template parameter list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000333 if (!TryConsumeToken(tok::less, LAngleLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000334 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
335 return true;
336 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000337
338 // Try to parse the template parameter list.
339 bool Failed = false;
340 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
341 Failed = ParseTemplateParameterList(Depth, TemplateParams);
342
343 if (Tok.is(tok::greatergreater)) {
344 // No diagnostic required here: a template-parameter-list can only be
345 // followed by a declaration or, for a template template parameter, the
346 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
347 // This matters for elegant diagnosis of:
348 // template<template<typename>> struct S;
349 Tok.setKind(tok::greater);
350 RAngleLoc = Tok.getLocation();
351 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
Alp Toker383d2c42014-01-01 03:08:43 +0000352 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
353 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000354 return true;
355 }
356 return false;
357}
358
359/// ParseTemplateParameterList - Parse a template parameter list. If
360/// the parsing fails badly (i.e., closing bracket was left out), this
361/// will try to put the token stream in a reasonable position (closing
362/// a statement, etc.) and return false.
363///
364/// template-parameter-list: [C++ temp]
365/// template-parameter
366/// template-parameter-list ',' template-parameter
367bool
368Parser::ParseTemplateParameterList(unsigned Depth,
369 SmallVectorImpl<Decl*> &TemplateParams) {
370 while (1) {
371 if (Decl *TmpParam
372 = ParseTemplateParameter(Depth, TemplateParams.size())) {
373 TemplateParams.push_back(TmpParam);
374 } else {
375 // If we failed to parse a template parameter, skip until we find
376 // a comma or closing brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000377 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
378 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000379 }
380
381 // Did we find a comma or the end of the template parameter list?
382 if (Tok.is(tok::comma)) {
383 ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000384 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000385 // Don't consume this... that's done by template parser.
386 break;
387 } else {
388 // Somebody probably forgot to close the template. Skip ahead and
389 // try to get out of the expression. This error is currently
390 // subsumed by whatever goes on in ParseTemplateParameter.
391 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000392 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
393 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000394 return false;
395 }
396 }
397 return true;
398}
399
400/// \brief Determine whether the parser is at the start of a template
401/// type parameter.
402bool Parser::isStartOfTemplateTypeParameter() {
403 if (Tok.is(tok::kw_class)) {
404 // "class" may be the start of an elaborated-type-specifier or a
405 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
406 switch (NextToken().getKind()) {
407 case tok::equal:
408 case tok::comma:
409 case tok::greater:
410 case tok::greatergreater:
411 case tok::ellipsis:
412 return true;
413
414 case tok::identifier:
415 // This may be either a type-parameter or an elaborated-type-specifier.
416 // We have to look further.
417 break;
418
419 default:
420 return false;
421 }
422
423 switch (GetLookAheadToken(2).getKind()) {
424 case tok::equal:
425 case tok::comma:
426 case tok::greater:
427 case tok::greatergreater:
428 return true;
429
430 default:
431 return false;
432 }
433 }
434
435 if (Tok.isNot(tok::kw_typename))
436 return false;
437
438 // C++ [temp.param]p2:
439 // There is no semantic difference between class and typename in a
440 // template-parameter. typename followed by an unqualified-id
441 // names a template type parameter. typename followed by a
442 // qualified-id denotes the type in a non-type
443 // parameter-declaration.
444 Token Next = NextToken();
445
446 // If we have an identifier, skip over it.
447 if (Next.getKind() == tok::identifier)
448 Next = GetLookAheadToken(2);
449
450 switch (Next.getKind()) {
451 case tok::equal:
452 case tok::comma:
453 case tok::greater:
454 case tok::greatergreater:
455 case tok::ellipsis:
456 return true;
457
458 default:
459 return false;
460 }
461}
462
463/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
464///
465/// template-parameter: [C++ temp.param]
466/// type-parameter
467/// parameter-declaration
468///
469/// type-parameter: (see below)
470/// 'class' ...[opt] identifier[opt]
471/// 'class' identifier[opt] '=' type-id
472/// 'typename' ...[opt] identifier[opt]
473/// 'typename' identifier[opt] '=' type-id
474/// 'template' '<' template-parameter-list '>'
475/// 'class' ...[opt] identifier[opt]
476/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
477/// = id-expression
478Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
479 if (isStartOfTemplateTypeParameter())
480 return ParseTypeParameter(Depth, Position);
481
482 if (Tok.is(tok::kw_template))
483 return ParseTemplateTemplateParameter(Depth, Position);
484
485 // If it's none of the above, then it must be a parameter declaration.
486 // NOTE: This will pick up errors in the closure of the template parameter
487 // list (e.g., template < ; Check here to implement >> style closures.
488 return ParseNonTypeTemplateParameter(Depth, Position);
489}
490
491/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
492/// Other kinds of template parameters are parsed in
493/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
494///
495/// type-parameter: [C++ temp.param]
496/// 'class' ...[opt][C++0x] identifier[opt]
497/// 'class' identifier[opt] '=' type-id
498/// 'typename' ...[opt][C++0x] identifier[opt]
499/// 'typename' identifier[opt] '=' type-id
500Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000501 assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +0000502 "A type-parameter starts with 'class' or 'typename'");
503
504 // Consume the 'class' or 'typename' keyword.
505 bool TypenameKeyword = Tok.is(tok::kw_typename);
506 SourceLocation KeyLoc = ConsumeToken();
507
508 // Grab the ellipsis (if given).
Faisal Vali6a79ca12013-06-08 19:39:00 +0000509 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000510 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000511 Diag(EllipsisLoc,
512 getLangOpts().CPlusPlus11
513 ? diag::warn_cxx98_compat_variadic_templates
514 : diag::ext_variadic_templates);
515 }
516
517 // Grab the template parameter name (if given)
518 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000519 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000520 if (Tok.is(tok::identifier)) {
521 ParamName = Tok.getIdentifierInfo();
522 NameLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000523 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
524 tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000525 // Unnamed template parameter. Don't have to do anything here, just
526 // don't consume this token.
527 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000528 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000529 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000530 }
531
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000532 // Recover from misplaced ellipsis.
533 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
534 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
535 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
536
Faisal Vali6a79ca12013-06-08 19:39:00 +0000537 // Grab a default argument (if available).
538 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
539 // we introduce the type parameter into the local scope.
540 SourceLocation EqualLoc;
541 ParsedType DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000542 if (TryConsumeToken(tok::equal, EqualLoc))
Craig Topper161e4db2014-05-21 06:02:52 +0000543 DefaultArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000544 Declarator::TemplateTypeArgContext).get();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000545
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000546 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
547 KeyLoc, ParamName, NameLoc, Depth, Position,
548 EqualLoc, DefaultArg);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000549}
550
551/// ParseTemplateTemplateParameter - Handle the parsing of template
552/// template parameters.
553///
554/// type-parameter: [C++ temp.param]
Richard Smith78e1ca62014-06-16 15:51:22 +0000555/// 'template' '<' template-parameter-list '>' type-parameter-key
Faisal Vali6a79ca12013-06-08 19:39:00 +0000556/// ...[opt] identifier[opt]
Richard Smith78e1ca62014-06-16 15:51:22 +0000557/// 'template' '<' template-parameter-list '>' type-parameter-key
558/// identifier[opt] = id-expression
559/// type-parameter-key:
560/// 'class'
561/// 'typename' [C++1z]
Faisal Vali6a79ca12013-06-08 19:39:00 +0000562Decl *
563Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
564 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
565
566 // Handle the template <...> part.
567 SourceLocation TemplateLoc = ConsumeToken();
568 SmallVector<Decl*,8> TemplateParams;
569 SourceLocation LAngleLoc, RAngleLoc;
570 {
571 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
572 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
573 RAngleLoc)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000574 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000575 }
576 }
577
Richard Smith78e1ca62014-06-16 15:51:22 +0000578 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000579 // Generate a meaningful error if the user forgot to put class before the
580 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
Richard Smith78e1ca62014-06-16 15:51:22 +0000581 // or greater appear immediately or after 'struct'. In the latter case,
582 // replace the keyword with 'class'.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000583 if (!TryConsumeToken(tok::kw_class)) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000584 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
Richard Smith78e1ca62014-06-16 15:51:22 +0000585 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
586 if (Tok.is(tok::kw_typename)) {
587 Diag(Tok.getLocation(),
588 getLangOpts().CPlusPlus1z
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000589 ? diag::warn_cxx14_compat_template_template_param_typename
Richard Smith78e1ca62014-06-16 15:51:22 +0000590 : diag::ext_template_template_param_typename)
591 << (!getLangOpts().CPlusPlus1z
592 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
593 : FixItHint());
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000594 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
595 tok::greatergreater, tok::ellipsis)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000596 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
597 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
598 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
Richard Smith78e1ca62014-06-16 15:51:22 +0000599 } else
Faisal Vali6a79ca12013-06-08 19:39:00 +0000600 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
601
602 if (Replace)
603 ConsumeToken();
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000604 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000605
606 // Parse the ellipsis, if given.
607 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000608 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000609 Diag(EllipsisLoc,
610 getLangOpts().CPlusPlus11
611 ? diag::warn_cxx98_compat_variadic_templates
612 : diag::ext_variadic_templates);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000613
614 // Get the identifier, if given.
615 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000616 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000617 if (Tok.is(tok::identifier)) {
618 ParamName = Tok.getIdentifierInfo();
619 NameLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000620 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
621 tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000622 // Unnamed template parameter. Don't have to do anything here, just
623 // don't consume this token.
624 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000625 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000626 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000627 }
628
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000629 // Recover from misplaced ellipsis.
630 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
631 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
632 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
633
Faisal Vali6a79ca12013-06-08 19:39:00 +0000634 TemplateParameterList *ParamList =
635 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
636 TemplateLoc, LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000637 TemplateParams,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000638 RAngleLoc);
639
640 // Grab a default argument (if available).
641 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
642 // we introduce the template parameter into the local scope.
643 SourceLocation EqualLoc;
644 ParsedTemplateArgument DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000645 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000646 DefaultArg = ParseTemplateTemplateArgument();
647 if (DefaultArg.isInvalid()) {
648 Diag(Tok.getLocation(),
649 diag::err_default_template_template_parameter_not_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000650 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
651 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000652 }
653 }
654
655 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
656 ParamList, EllipsisLoc,
657 ParamName, NameLoc, Depth,
658 Position, EqualLoc, DefaultArg);
659}
660
661/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
662/// template parameters (e.g., in "template<int Size> class array;").
663///
664/// template-parameter:
665/// ...
666/// parameter-declaration
667Decl *
668Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
669 // Parse the declaration-specifiers (i.e., the type).
670 // FIXME: The type should probably be restricted in some way... Not all
671 // declarators (parts of declarators?) are accepted for parameters.
672 DeclSpec DS(AttrFactory);
673 ParseDeclarationSpecifiers(DS);
674
675 // Parse this as a typename.
676 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
677 ParseDeclarator(ParamDecl);
678 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
679 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
Craig Topper161e4db2014-05-21 06:02:52 +0000680 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000681 }
682
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000683 // Recover from misplaced ellipsis.
684 SourceLocation EllipsisLoc;
685 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
686 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
687
Faisal Vali6a79ca12013-06-08 19:39:00 +0000688 // If there is a default value, parse it.
689 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
690 // we introduce the template parameter into the local scope.
691 SourceLocation EqualLoc;
692 ExprResult DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000693 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000694 // C++ [temp.param]p15:
695 // When parsing a default template-argument for a non-type
696 // template-parameter, the first non-nested > is taken as the
697 // end of the template-parameter-list rather than a greater-than
698 // operator.
699 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Faisal Vali48401eb2015-11-19 19:20:17 +0000700 EnterExpressionEvaluationContext ConstantEvaluated(Actions,
701 Sema::ConstantEvaluated);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000702
Kaelyn Takata999dd852014-12-02 23:32:20 +0000703 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000704 if (DefaultArg.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +0000705 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000706 }
707
708 // Create the parameter.
709 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
710 Depth, Position, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000711 DefaultArg.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000712}
713
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000714void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
715 SourceLocation CorrectLoc,
716 bool AlreadyHasEllipsis,
717 bool IdentifierHasName) {
718 FixItHint Insertion;
719 if (!AlreadyHasEllipsis)
720 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
721 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
722 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
723 << !IdentifierHasName;
724}
725
726void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
727 Declarator &D) {
728 assert(EllipsisLoc.isValid());
729 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
730 if (!AlreadyHasEllipsis)
731 D.setEllipsisLoc(EllipsisLoc);
732 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
733 AlreadyHasEllipsis, D.hasName());
734}
735
Faisal Vali6a79ca12013-06-08 19:39:00 +0000736/// \brief Parses a '>' at the end of a template list.
737///
738/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
739/// to determine if these tokens were supposed to be a '>' followed by
740/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
741///
742/// \param RAngleLoc the location of the consumed '>'.
743///
Douglas Gregor85f3f952015-07-07 03:57:15 +0000744/// \param ConsumeLastToken if true, the '>' is consumed.
745///
746/// \param ObjCGenericList if true, this is the '>' closing an Objective-C
747/// type parameter or type argument list, rather than a C++ template parameter
748/// or argument list.
Serge Pavlovb716b3c2013-08-10 05:54:47 +0000749///
750/// \returns true, if current token does not start with '>', false otherwise.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000751bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000752 bool ConsumeLastToken,
753 bool ObjCGenericList) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000754 // What will be left once we've consumed the '>'.
755 tok::TokenKind RemainingToken;
756 const char *ReplacementStr = "> >";
757
758 switch (Tok.getKind()) {
759 default:
Alp Toker383d2c42014-01-01 03:08:43 +0000760 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000761 return true;
762
763 case tok::greater:
764 // Determine the location of the '>' token. Only consume this token
765 // if the caller asked us to.
766 RAngleLoc = Tok.getLocation();
767 if (ConsumeLastToken)
768 ConsumeToken();
769 return false;
770
771 case tok::greatergreater:
772 RemainingToken = tok::greater;
773 break;
774
775 case tok::greatergreatergreater:
776 RemainingToken = tok::greatergreater;
777 break;
778
779 case tok::greaterequal:
780 RemainingToken = tok::equal;
781 ReplacementStr = "> =";
782 break;
783
784 case tok::greatergreaterequal:
785 RemainingToken = tok::greaterequal;
786 break;
787 }
788
789 // This template-id is terminated by a token which starts with a '>'. Outside
790 // C++11, this is now error recovery, and in C++11, this is error recovery if
Eli Bendersky36a61932014-06-20 13:09:59 +0000791 // the token isn't '>>' or '>>>'.
792 // '>>>' is for CUDA, where this sequence of characters is parsed into
793 // tok::greatergreatergreater, rather than two separate tokens.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000794 //
795 // We always allow this for Objective-C type parameter and type argument
796 // lists.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000797 RAngleLoc = Tok.getLocation();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000798 Token Next = NextToken();
Douglas Gregor85f3f952015-07-07 03:57:15 +0000799 if (!ObjCGenericList) {
800 // The source range of the '>>' or '>=' at the start of the token.
801 CharSourceRange ReplacementRange =
802 CharSourceRange::getCharRange(RAngleLoc,
803 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
804 getLangOpts()));
Faisal Vali6a79ca12013-06-08 19:39:00 +0000805
Douglas Gregor85f3f952015-07-07 03:57:15 +0000806 // A hint to put a space between the '>>'s. In order to make the hint as
807 // clear as possible, we include the characters either side of the space in
808 // the replacement, rather than just inserting a space at SecondCharLoc.
809 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
810 ReplacementStr);
811
812 // A hint to put another space after the token, if it would otherwise be
813 // lexed differently.
814 FixItHint Hint2;
815 if ((RemainingToken == tok::greater ||
816 RemainingToken == tok::greatergreater) &&
817 (Next.isOneOf(tok::greater, tok::greatergreater,
818 tok::greatergreatergreater, tok::equal,
819 tok::greaterequal, tok::greatergreaterequal,
820 tok::equalequal)) &&
821 areTokensAdjacent(Tok, Next))
822 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
823
824 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
825 if (getLangOpts().CPlusPlus11 &&
826 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
827 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
828 else if (Tok.is(tok::greaterequal))
829 DiagId = diag::err_right_angle_bracket_equal_needs_space;
830 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
831 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000832
833 // Strip the initial '>' from the token.
834 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
835 areTokensAdjacent(Tok, Next)) {
836 // Join two adjacent '=' tokens into one, for cases like:
837 // void (*p)() = f<int>;
838 // return f<int>==p;
839 ConsumeToken();
840 Tok.setKind(tok::equalequal);
841 Tok.setLength(Tok.getLength() + 1);
842 } else {
843 Tok.setKind(RemainingToken);
844 Tok.setLength(Tok.getLength() - 1);
845 }
846 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
847 PP.getSourceManager(),
848 getLangOpts()));
849
850 if (!ConsumeLastToken) {
851 // Since we're not supposed to consume the '>' token, we need to push
852 // this token and revert the current token back to the '>'.
853 PP.EnterToken(Tok);
854 Tok.setKind(tok::greater);
855 Tok.setLength(1);
856 Tok.setLocation(RAngleLoc);
857 }
858 return false;
859}
860
861
862/// \brief Parses a template-id that after the template name has
863/// already been parsed.
864///
865/// This routine takes care of parsing the enclosed template argument
866/// list ('<' template-parameter-list [opt] '>') and placing the
867/// results into a form that can be transferred to semantic analysis.
868///
869/// \param Template the template declaration produced by isTemplateName
870///
871/// \param TemplateNameLoc the source location of the template name
872///
873/// \param SS if non-NULL, the nested-name-specifier preceding the
874/// template name.
875///
876/// \param ConsumeLastToken if true, then we will consume the last
877/// token that forms the template-id. Otherwise, we will leave the
878/// last token in the stream (e.g., so that it can be replaced with an
879/// annotation token).
880bool
881Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
882 SourceLocation TemplateNameLoc,
883 const CXXScopeSpec &SS,
884 bool ConsumeLastToken,
885 SourceLocation &LAngleLoc,
886 TemplateArgList &TemplateArgs,
887 SourceLocation &RAngleLoc) {
888 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
889
890 // Consume the '<'.
891 LAngleLoc = ConsumeToken();
892
893 // Parse the optional template-argument-list.
894 bool Invalid = false;
895 {
896 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
897 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
898 Invalid = ParseTemplateArgumentList(TemplateArgs);
899
900 if (Invalid) {
901 // Try to find the closing '>'.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000902 if (ConsumeLastToken)
903 SkipUntil(tok::greater, StopAtSemi);
904 else
905 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000906 return true;
907 }
908 }
909
Douglas Gregor85f3f952015-07-07 03:57:15 +0000910 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
911 /*ObjCGenericList=*/false);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000912}
913
914/// \brief Replace the tokens that form a simple-template-id with an
915/// annotation token containing the complete template-id.
916///
917/// The first token in the stream must be the name of a template that
918/// is followed by a '<'. This routine will parse the complete
919/// simple-template-id and replace the tokens with a single annotation
920/// token with one of two different kinds: if the template-id names a
921/// type (and \p AllowTypeAnnotation is true), the annotation token is
922/// a type annotation that includes the optional nested-name-specifier
923/// (\p SS). Otherwise, the annotation token is a template-id
924/// annotation that does not include the optional
925/// nested-name-specifier.
926///
927/// \param Template the declaration of the template named by the first
928/// token (an identifier), as returned from \c Action::isTemplateName().
929///
930/// \param TNK the kind of template that \p Template
931/// refers to, as returned from \c Action::isTemplateName().
932///
933/// \param SS if non-NULL, the nested-name-specifier that precedes
934/// this template name.
935///
936/// \param TemplateKWLoc if valid, specifies that this template-id
937/// annotation was preceded by the 'template' keyword and gives the
938/// location of that keyword. If invalid (the default), then this
939/// template-id was not preceded by a 'template' keyword.
940///
941/// \param AllowTypeAnnotation if true (the default), then a
942/// simple-template-id that refers to a class template, template
943/// template parameter, or other template that produces a type will be
944/// replaced with a type annotation token. Otherwise, the
945/// simple-template-id is always replaced with a template-id
946/// annotation token.
947///
948/// If an unrecoverable parse error occurs and no annotation token can be
949/// formed, this function returns true.
950///
951bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
952 CXXScopeSpec &SS,
953 SourceLocation TemplateKWLoc,
954 UnqualifiedId &TemplateName,
955 bool AllowTypeAnnotation) {
956 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
957 assert(Template && Tok.is(tok::less) &&
958 "Parser isn't at the beginning of a template-id");
959
960 // Consume the template-name.
961 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
962
963 // Parse the enclosed template argument list.
964 SourceLocation LAngleLoc, RAngleLoc;
965 TemplateArgList TemplateArgs;
966 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
967 TemplateNameLoc,
968 SS, false, LAngleLoc,
969 TemplateArgs,
970 RAngleLoc);
971
972 if (Invalid) {
973 // If we failed to parse the template ID but skipped ahead to a >, we're not
974 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000975 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000976 return true;
977 }
978
979 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
980
981 // Build the annotation token.
982 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
983 TypeResult Type
984 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
985 Template, TemplateNameLoc,
986 LAngleLoc, TemplateArgsPtr, RAngleLoc);
987 if (Type.isInvalid()) {
988 // If we failed to parse the template ID but skipped ahead to a >, we're not
989 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000990 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000991 return true;
992 }
993
994 Tok.setKind(tok::annot_typename);
995 setTypeAnnotation(Tok, Type.get());
996 if (SS.isNotEmpty())
997 Tok.setLocation(SS.getBeginLoc());
998 else if (TemplateKWLoc.isValid())
999 Tok.setLocation(TemplateKWLoc);
1000 else
1001 Tok.setLocation(TemplateNameLoc);
1002 } else {
1003 // Build a template-id annotation token that can be processed
1004 // later.
1005 Tok.setKind(tok::annot_template_id);
1006 TemplateIdAnnotation *TemplateId
1007 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
1008 TemplateId->TemplateNameLoc = TemplateNameLoc;
1009 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
1010 TemplateId->Name = TemplateName.Identifier;
1011 TemplateId->Operator = OO_None;
1012 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001013 TemplateId->Name = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001014 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
1015 }
1016 TemplateId->SS = SS;
1017 TemplateId->TemplateKWLoc = TemplateKWLoc;
1018 TemplateId->Template = Template;
1019 TemplateId->Kind = TNK;
1020 TemplateId->LAngleLoc = LAngleLoc;
1021 TemplateId->RAngleLoc = RAngleLoc;
1022 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1023 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
1024 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
1025 Tok.setAnnotationValue(TemplateId);
1026 if (TemplateKWLoc.isValid())
1027 Tok.setLocation(TemplateKWLoc);
1028 else
1029 Tok.setLocation(TemplateNameLoc);
1030 }
1031
1032 // Common fields for the annotation token
1033 Tok.setAnnotationEndLoc(RAngleLoc);
1034
1035 // In case the tokens were cached, have Preprocessor replace them with the
1036 // annotation token.
1037 PP.AnnotateCachedTokens(Tok);
1038 return false;
1039}
1040
1041/// \brief Replaces a template-id annotation token with a type
1042/// annotation token.
1043///
1044/// If there was a failure when forming the type from the template-id,
1045/// a type annotation token will still be created, but will have a
1046/// NULL type pointer to signify an error.
1047void Parser::AnnotateTemplateIdTokenAsType() {
1048 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1049
1050 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1051 assert((TemplateId->Kind == TNK_Type_template ||
1052 TemplateId->Kind == TNK_Dependent_template_name) &&
1053 "Only works for type and dependent templates");
1054
1055 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1056 TemplateId->NumArgs);
1057
1058 TypeResult Type
1059 = Actions.ActOnTemplateIdType(TemplateId->SS,
1060 TemplateId->TemplateKWLoc,
1061 TemplateId->Template,
1062 TemplateId->TemplateNameLoc,
1063 TemplateId->LAngleLoc,
1064 TemplateArgsPtr,
1065 TemplateId->RAngleLoc);
1066 // Create the new "type" annotation token.
1067 Tok.setKind(tok::annot_typename);
David Blaikieefdccaa2016-01-15 23:43:34 +00001068 setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001069 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1070 Tok.setLocation(TemplateId->SS.getBeginLoc());
1071 // End location stays the same
1072
1073 // Replace the template-id annotation token, and possible the scope-specifier
1074 // that precedes it, with the typename annotation token.
1075 PP.AnnotateCachedTokens(Tok);
1076}
1077
1078/// \brief Determine whether the given token can end a template argument.
1079static bool isEndOfTemplateArgument(Token Tok) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001080 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001081}
1082
1083/// \brief Parse a C++ template template argument.
1084ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1085 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1086 !Tok.is(tok::annot_cxxscope))
1087 return ParsedTemplateArgument();
1088
1089 // C++0x [temp.arg.template]p1:
1090 // A template-argument for a template template-parameter shall be the name
1091 // of a class template or an alias template, expressed as id-expression.
1092 //
1093 // We parse an id-expression that refers to a class template or alias
1094 // template. The grammar we parse is:
1095 //
1096 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1097 //
1098 // followed by a token that terminates a template argument, such as ',',
1099 // '>', or (in some cases) '>>'.
1100 CXXScopeSpec SS; // nested-name-specifier, if present
David Blaikieefdccaa2016-01-15 23:43:34 +00001101 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001102 /*EnteringContext=*/false);
David Blaikieefdccaa2016-01-15 23:43:34 +00001103
Faisal Vali6a79ca12013-06-08 19:39:00 +00001104 ParsedTemplateArgument Result;
1105 SourceLocation EllipsisLoc;
1106 if (SS.isSet() && Tok.is(tok::kw_template)) {
1107 // Parse the optional 'template' keyword following the
1108 // nested-name-specifier.
1109 SourceLocation TemplateKWLoc = ConsumeToken();
1110
1111 if (Tok.is(tok::identifier)) {
1112 // We appear to have a dependent template name.
1113 UnqualifiedId Name;
1114 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1115 ConsumeToken(); // the identifier
Alp Toker094e5212014-01-05 03:27:11 +00001116
1117 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1118
Faisal Vali6a79ca12013-06-08 19:39:00 +00001119 // If the next token signals the end of a template argument,
1120 // then we have a dependent template name that could be a template
1121 // template argument.
1122 TemplateTy Template;
1123 if (isEndOfTemplateArgument(Tok) &&
David Blaikieefdccaa2016-01-15 23:43:34 +00001124 Actions.ActOnDependentTemplateName(
1125 getCurScope(), SS, TemplateKWLoc, Name,
1126 /*ObjectType=*/nullptr,
1127 /*EnteringContext=*/false, Template))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001128 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1129 }
1130 } else if (Tok.is(tok::identifier)) {
1131 // We may have a (non-dependent) template name.
1132 TemplateTy Template;
1133 UnqualifiedId Name;
1134 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1135 ConsumeToken(); // the identifier
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001136
1137 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001138
1139 if (isEndOfTemplateArgument(Tok)) {
1140 bool MemberOfUnknownSpecialization;
David Blaikieefdccaa2016-01-15 23:43:34 +00001141 TemplateNameKind TNK = Actions.isTemplateName(
1142 getCurScope(), SS,
1143 /*hasTemplateKeyword=*/false, Name,
1144 /*ObjectType=*/nullptr,
1145 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001146 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1147 // We have an id-expression that refers to a class template or
1148 // (C++0x) alias template.
1149 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1150 }
1151 }
1152 }
1153
1154 // If this is a pack expansion, build it as such.
1155 if (EllipsisLoc.isValid() && !Result.isInvalid())
1156 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1157
1158 return Result;
1159}
1160
1161/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1162///
1163/// template-argument: [C++ 14.2]
1164/// constant-expression
1165/// type-id
1166/// id-expression
1167ParsedTemplateArgument Parser::ParseTemplateArgument() {
1168 // C++ [temp.arg]p2:
1169 // In a template-argument, an ambiguity between a type-id and an
1170 // expression is resolved to a type-id, regardless of the form of
1171 // the corresponding template-parameter.
1172 //
1173 // Therefore, we initially try to parse a type-id.
1174 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1175 SourceLocation Loc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00001176 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001177 Declarator::TemplateTypeArgContext);
1178 if (TypeArg.isInvalid())
1179 return ParsedTemplateArgument();
1180
1181 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1182 TypeArg.get().getAsOpaquePtr(),
1183 Loc);
1184 }
1185
1186 // Try to parse a template template argument.
1187 {
1188 TentativeParsingAction TPA(*this);
1189
1190 ParsedTemplateArgument TemplateTemplateArgument
1191 = ParseTemplateTemplateArgument();
1192 if (!TemplateTemplateArgument.isInvalid()) {
1193 TPA.Commit();
1194 return TemplateTemplateArgument;
1195 }
1196
1197 // Revert this tentative parse to parse a non-type template argument.
1198 TPA.Revert();
1199 }
1200
1201 // Parse a non-type template argument.
1202 SourceLocation Loc = Tok.getLocation();
1203 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1204 if (ExprArg.isInvalid() || !ExprArg.get())
1205 return ParsedTemplateArgument();
1206
1207 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001208 ExprArg.get(), Loc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001209}
1210
1211/// \brief Determine whether the current tokens can only be parsed as a
1212/// template argument list (starting with the '<') and never as a '<'
1213/// expression.
1214bool Parser::IsTemplateArgumentList(unsigned Skip) {
1215 struct AlwaysRevertAction : TentativeParsingAction {
1216 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1217 ~AlwaysRevertAction() { Revert(); }
1218 } Tentative(*this);
1219
1220 while (Skip) {
1221 ConsumeToken();
1222 --Skip;
1223 }
1224
1225 // '<'
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001226 if (!TryConsumeToken(tok::less))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001227 return false;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001228
1229 // An empty template argument list.
1230 if (Tok.is(tok::greater))
1231 return true;
1232
1233 // See whether we have declaration specifiers, which indicate a type.
Richard Smithee390432014-05-16 01:56:53 +00001234 while (isCXXDeclarationSpecifier() == TPResult::True)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001235 ConsumeToken();
1236
1237 // If we have a '>' or a ',' then this is a template argument list.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001238 return Tok.isOneOf(tok::greater, tok::comma);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001239}
1240
1241/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1242/// (C++ [temp.names]). Returns true if there was an error.
1243///
1244/// template-argument-list: [C++ 14.2]
1245/// template-argument
1246/// template-argument-list ',' template-argument
1247bool
1248Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1249 // Template argument lists are constant-evaluation contexts.
1250 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +00001251 ColonProtectionRAIIObject ColonProtection(*this, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001252
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001253 do {
Faisal Vali6a79ca12013-06-08 19:39:00 +00001254 ParsedTemplateArgument Arg = ParseTemplateArgument();
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001255 SourceLocation EllipsisLoc;
1256 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001257 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001258
1259 if (Arg.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001260 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001261 return true;
1262 }
1263
1264 // Save this template argument.
1265 TemplateArgs.push_back(Arg);
1266
1267 // If the next token is a comma, consume it and keep reading
1268 // arguments.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001269 } while (TryConsumeToken(tok::comma));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001270
1271 return false;
1272}
1273
1274/// \brief Parse a C++ explicit template instantiation
1275/// (C++ [temp.explicit]).
1276///
1277/// explicit-instantiation:
1278/// 'extern' [opt] 'template' declaration
1279///
1280/// Note that the 'extern' is a GNU extension and C++11 feature.
1281Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1282 SourceLocation ExternLoc,
1283 SourceLocation TemplateLoc,
1284 SourceLocation &DeclEnd,
1285 AccessSpecifier AS) {
1286 // This isn't really required here.
1287 ParsingDeclRAIIObject
1288 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1289
1290 return ParseSingleDeclarationAfterTemplate(Context,
1291 ParsedTemplateInfo(ExternLoc,
1292 TemplateLoc),
1293 ParsingTemplateParams,
1294 DeclEnd, AS);
1295}
1296
1297SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1298 if (TemplateParams)
1299 return getTemplateParamsRange(TemplateParams->data(),
1300 TemplateParams->size());
1301
1302 SourceRange R(TemplateLoc);
1303 if (ExternLoc.isValid())
1304 R.setBegin(ExternLoc);
1305 return R;
1306}
1307
Richard Smithe40f2ba2013-08-07 21:41:30 +00001308void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1309 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001310}
1311
1312/// \brief Late parse a C++ function template in Microsoft mode.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001313void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
David Majnemerf0a84f22013-08-16 08:29:13 +00001314 if (!LPT.D)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001315 return;
1316
1317 // Get the FunctionDecl.
Alp Tokera2794f92014-01-22 07:29:52 +00001318 FunctionDecl *FunD = LPT.D->getAsFunction();
Faisal Vali6a79ca12013-06-08 19:39:00 +00001319 // Track template parameter depth.
1320 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1321
1322 // To restore the context after late parsing.
Richard Smithb0b68012015-05-11 23:09:06 +00001323 Sema::ContextRAII GlobalSavedContext(
1324 Actions, Actions.Context.getTranslationUnitDecl());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001325
1326 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1327
1328 // Get the list of DeclContexts to reenter.
1329 SmallVector<DeclContext*, 4> DeclContextsToReenter;
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001330 DeclContext *DD = FunD;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001331 while (DD && !DD->isTranslationUnit()) {
1332 DeclContextsToReenter.push_back(DD);
1333 DD = DD->getLexicalParent();
1334 }
1335
1336 // Reenter template scopes from outermost to innermost.
Craig Topper61ac9062013-07-08 03:55:09 +00001337 SmallVectorImpl<DeclContext *>::reverse_iterator II =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001338 DeclContextsToReenter.rbegin();
1339 for (; II != DeclContextsToReenter.rend(); ++II) {
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001340 TemplateParamScopeStack.push_back(new ParseScope(this,
1341 Scope::TemplateParamScope));
1342 unsigned NumParamLists =
1343 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1344 CurTemplateDepthTracker.addDepth(NumParamLists);
1345 if (*II != FunD) {
1346 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1347 Actions.PushDeclContext(Actions.getCurScope(), *II);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001348 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001349 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001350
Richard Smithe40f2ba2013-08-07 21:41:30 +00001351 assert(!LPT.Toks.empty() && "Empty body!");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001352
1353 // Append the current token at the end of the new token stream so that it
1354 // doesn't get lost.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001355 LPT.Toks.push_back(Tok);
1356 PP.EnterTokenStream(LPT.Toks.data(), LPT.Toks.size(), true, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001357
1358 // Consume the previously pushed token.
1359 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001360 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1361 "Inline method not starting with '{', ':' or 'try'");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001362
1363 // Parse the method body. Function body parsing code is similar enough
1364 // to be re-used for method bodies as well.
1365 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1366
1367 // Recreate the containing function DeclContext.
Nico Weber55048cf2014-08-15 22:15:00 +00001368 Sema::ContextRAII FunctionSavedContext(Actions,
1369 Actions.getContainingDC(FunD));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001370
1371 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1372
1373 if (Tok.is(tok::kw_try)) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00001374 ParseFunctionTryBlock(LPT.D, FnScope);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001375 } else {
1376 if (Tok.is(tok::colon))
Richard Smithe40f2ba2013-08-07 21:41:30 +00001377 ParseConstructorInitializer(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001378 else
Richard Smithe40f2ba2013-08-07 21:41:30 +00001379 Actions.ActOnDefaultCtorInitializers(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001380
1381 if (Tok.is(tok::l_brace)) {
Alp Tokera2794f92014-01-22 07:29:52 +00001382 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1383 cast<FunctionTemplateDecl>(LPT.D)
1384 ->getTemplateParameters()
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001385 ->getDepth() == TemplateParameterDepth - 1) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +00001386 "TemplateParameterDepth should be greater than the depth of "
1387 "current template being instantiated!");
Richard Smithe40f2ba2013-08-07 21:41:30 +00001388 ParseFunctionStatementBody(LPT.D, FnScope);
1389 Actions.UnmarkAsLateParsedTemplate(FunD);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001390 } else
Craig Topper161e4db2014-05-21 06:02:52 +00001391 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001392 }
1393
1394 // Exit scopes.
1395 FnScope.Exit();
Craig Topper61ac9062013-07-08 03:55:09 +00001396 SmallVectorImpl<ParseScope *>::reverse_iterator I =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001397 TemplateParamScopeStack.rbegin();
1398 for (; I != TemplateParamScopeStack.rend(); ++I)
1399 delete *I;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001400}
1401
1402/// \brief Lex a delayed template function for late parsing.
1403void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1404 tok::TokenKind kind = Tok.getKind();
1405 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1406 // Consume everything up to (and including) the matching right brace.
1407 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1408 }
1409
1410 // If we're in a function-try-block, we need to store all the catch blocks.
1411 if (kind == tok::kw_try) {
1412 while (Tok.is(tok::kw_catch)) {
1413 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1414 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1415 }
1416 }
1417}