blob: 098ac6836fd74a04324a741e04f82a90f680ad1c [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();
212 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
213 getCurScope(), AS, DS,
214 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
215 : MultiTemplateParamsArg(),
216 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation);
217 DS.complete(Decl);
218 return Decl;
219 }
220
221 // Move the attributes from the prefix into the DS.
222 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
223 ProhibitAttributes(prefixAttrs);
224 else
225 DS.takeAttributesFrom(prefixAttrs);
226
227 // Parse the declarator.
228 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
229 ParseDeclarator(DeclaratorInfo);
230 // Error parsing the declarator?
231 if (!DeclaratorInfo.hasName()) {
232 // If so, skip until the semi-colon or a }.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000233 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000234 if (Tok.is(tok::semi))
235 ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000236 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000237 }
238
239 LateParsedAttrList LateParsedAttrs(true);
240 if (DeclaratorInfo.isFunctionDeclarator())
241 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
242
243 if (DeclaratorInfo.isFunctionDeclarator() &&
244 isStartOfFunctionDefinition(DeclaratorInfo)) {
Reid Klecknerd61a3112014-12-15 23:16:32 +0000245
246 // Function definitions are only allowed at file scope and in C++ classes.
247 // The C++ inline method definition case is handled elsewhere, so we only
248 // need to handle the file scope definition case.
249 if (Context != Declarator::FileContext) {
250 Diag(Tok, diag::err_function_definition_not_allowed);
251 SkipMalformedDecl();
252 return nullptr;
253 }
254
Faisal Vali6a79ca12013-06-08 19:39:00 +0000255 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
256 // Recover by ignoring the 'typedef'. This was probably supposed to be
257 // the 'typename' keyword, which we should have already suggested adding
258 // if it's appropriate.
259 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
260 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
261 DS.ClearStorageClassSpecs();
262 }
Larisse Voufo725de3e2013-06-21 00:08:46 +0000263
264 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
265 if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
266 // If the declarator-id is not a template-id, issue a diagnostic and
267 // recover by ignoring the 'template' keyword.
268 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000269 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
270 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000271 } else {
272 SourceLocation LAngleLoc
273 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000274 Diag(DeclaratorInfo.getIdentifierLoc(),
Larisse Voufo725de3e2013-06-21 00:08:46 +0000275 diag::err_explicit_instantiation_with_definition)
Larisse Voufo39a1e502013-08-06 01:03:05 +0000276 << SourceRange(TemplateInfo.TemplateLoc)
277 << FixItHint::CreateInsertion(LAngleLoc, "<>");
Larisse Voufo725de3e2013-06-21 00:08:46 +0000278
Larisse Voufo39a1e502013-08-06 01:03:05 +0000279 // Recover as if it were an explicit specialization.
Larisse Voufob9bbaba2013-06-22 13:56:11 +0000280 TemplateParameterLists FakedParamLists;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000281 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +0000282 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
283 LAngleLoc));
Larisse Voufo725de3e2013-06-21 00:08:46 +0000284
Larisse Voufo39a1e502013-08-06 01:03:05 +0000285 return ParseFunctionDefinition(
286 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
287 /*isSpecialization=*/true,
288 /*LastParamListWasEmpty=*/true),
289 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000290 }
291 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000292 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
Larisse Voufo39a1e502013-08-06 01:03:05 +0000293 &LateParsedAttrs);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000294 }
295
296 // Parse this declaration.
297 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
298 TemplateInfo);
299
300 if (Tok.is(tok::comma)) {
301 Diag(Tok, diag::err_multiple_template_declarators)
302 << (int)TemplateInfo.Kind;
Alexey Bataevee6507d2013-11-18 08:17:37 +0000303 SkipUntil(tok::semi);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000304 return ThisDecl;
305 }
306
307 // Eat the semi colon after the declaration.
308 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
309 if (LateParsedAttrs.size() > 0)
310 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
311 DeclaratorInfo.complete(ThisDecl);
312 return ThisDecl;
313}
314
315/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
316/// angle brackets. Depth is the depth of this template-parameter-list, which
317/// is the number of template headers directly enclosing this template header.
318/// TemplateParams is the current list of template parameters we're building.
319/// The template parameter we parse will be added to this list. LAngleLoc and
320/// RAngleLoc will receive the positions of the '<' and '>', respectively,
321/// that enclose this template parameter list.
322///
323/// \returns true if an error occurred, false otherwise.
324bool Parser::ParseTemplateParameters(unsigned Depth,
325 SmallVectorImpl<Decl*> &TemplateParams,
326 SourceLocation &LAngleLoc,
327 SourceLocation &RAngleLoc) {
328 // Get the template parameter list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000329 if (!TryConsumeToken(tok::less, LAngleLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000330 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
331 return true;
332 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000333
334 // Try to parse the template parameter list.
335 bool Failed = false;
336 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
337 Failed = ParseTemplateParameterList(Depth, TemplateParams);
338
339 if (Tok.is(tok::greatergreater)) {
340 // No diagnostic required here: a template-parameter-list can only be
341 // followed by a declaration or, for a template template parameter, the
342 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
343 // This matters for elegant diagnosis of:
344 // template<template<typename>> struct S;
345 Tok.setKind(tok::greater);
346 RAngleLoc = Tok.getLocation();
347 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
Alp Toker383d2c42014-01-01 03:08:43 +0000348 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
349 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000350 return true;
351 }
352 return false;
353}
354
355/// ParseTemplateParameterList - Parse a template parameter list. If
356/// the parsing fails badly (i.e., closing bracket was left out), this
357/// will try to put the token stream in a reasonable position (closing
358/// a statement, etc.) and return false.
359///
360/// template-parameter-list: [C++ temp]
361/// template-parameter
362/// template-parameter-list ',' template-parameter
363bool
364Parser::ParseTemplateParameterList(unsigned Depth,
365 SmallVectorImpl<Decl*> &TemplateParams) {
366 while (1) {
367 if (Decl *TmpParam
368 = ParseTemplateParameter(Depth, TemplateParams.size())) {
369 TemplateParams.push_back(TmpParam);
370 } else {
371 // If we failed to parse a template parameter, skip until we find
372 // a comma or closing brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000373 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
374 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000375 }
376
377 // Did we find a comma or the end of the template parameter list?
378 if (Tok.is(tok::comma)) {
379 ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000380 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000381 // Don't consume this... that's done by template parser.
382 break;
383 } else {
384 // Somebody probably forgot to close the template. Skip ahead and
385 // try to get out of the expression. This error is currently
386 // subsumed by whatever goes on in ParseTemplateParameter.
387 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000388 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
389 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000390 return false;
391 }
392 }
393 return true;
394}
395
396/// \brief Determine whether the parser is at the start of a template
397/// type parameter.
398bool Parser::isStartOfTemplateTypeParameter() {
399 if (Tok.is(tok::kw_class)) {
400 // "class" may be the start of an elaborated-type-specifier or a
401 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
402 switch (NextToken().getKind()) {
403 case tok::equal:
404 case tok::comma:
405 case tok::greater:
406 case tok::greatergreater:
407 case tok::ellipsis:
408 return true;
409
410 case tok::identifier:
411 // This may be either a type-parameter or an elaborated-type-specifier.
412 // We have to look further.
413 break;
414
415 default:
416 return false;
417 }
418
419 switch (GetLookAheadToken(2).getKind()) {
420 case tok::equal:
421 case tok::comma:
422 case tok::greater:
423 case tok::greatergreater:
424 return true;
425
426 default:
427 return false;
428 }
429 }
430
431 if (Tok.isNot(tok::kw_typename))
432 return false;
433
434 // C++ [temp.param]p2:
435 // There is no semantic difference between class and typename in a
436 // template-parameter. typename followed by an unqualified-id
437 // names a template type parameter. typename followed by a
438 // qualified-id denotes the type in a non-type
439 // parameter-declaration.
440 Token Next = NextToken();
441
442 // If we have an identifier, skip over it.
443 if (Next.getKind() == tok::identifier)
444 Next = GetLookAheadToken(2);
445
446 switch (Next.getKind()) {
447 case tok::equal:
448 case tok::comma:
449 case tok::greater:
450 case tok::greatergreater:
451 case tok::ellipsis:
452 return true;
453
454 default:
455 return false;
456 }
457}
458
459/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
460///
461/// template-parameter: [C++ temp.param]
462/// type-parameter
463/// parameter-declaration
464///
465/// type-parameter: (see below)
466/// 'class' ...[opt] identifier[opt]
467/// 'class' identifier[opt] '=' type-id
468/// 'typename' ...[opt] identifier[opt]
469/// 'typename' identifier[opt] '=' type-id
470/// 'template' '<' template-parameter-list '>'
471/// 'class' ...[opt] identifier[opt]
472/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
473/// = id-expression
474Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
475 if (isStartOfTemplateTypeParameter())
476 return ParseTypeParameter(Depth, Position);
477
478 if (Tok.is(tok::kw_template))
479 return ParseTemplateTemplateParameter(Depth, Position);
480
481 // If it's none of the above, then it must be a parameter declaration.
482 // NOTE: This will pick up errors in the closure of the template parameter
483 // list (e.g., template < ; Check here to implement >> style closures.
484 return ParseNonTypeTemplateParameter(Depth, Position);
485}
486
487/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
488/// Other kinds of template parameters are parsed in
489/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
490///
491/// type-parameter: [C++ temp.param]
492/// 'class' ...[opt][C++0x] identifier[opt]
493/// 'class' identifier[opt] '=' type-id
494/// 'typename' ...[opt][C++0x] identifier[opt]
495/// 'typename' identifier[opt] '=' type-id
496Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000497 assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +0000498 "A type-parameter starts with 'class' or 'typename'");
499
500 // Consume the 'class' or 'typename' keyword.
501 bool TypenameKeyword = Tok.is(tok::kw_typename);
502 SourceLocation KeyLoc = ConsumeToken();
503
504 // Grab the ellipsis (if given).
Faisal Vali6a79ca12013-06-08 19:39:00 +0000505 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000506 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000507 Diag(EllipsisLoc,
508 getLangOpts().CPlusPlus11
509 ? diag::warn_cxx98_compat_variadic_templates
510 : diag::ext_variadic_templates);
511 }
512
513 // Grab the template parameter name (if given)
514 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000515 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000516 if (Tok.is(tok::identifier)) {
517 ParamName = Tok.getIdentifierInfo();
518 NameLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000519 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
520 tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000521 // Unnamed template parameter. Don't have to do anything here, just
522 // don't consume this token.
523 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000524 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000525 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000526 }
527
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000528 // Recover from misplaced ellipsis.
529 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
530 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
531 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
532
Faisal Vali6a79ca12013-06-08 19:39:00 +0000533 // Grab a default argument (if available).
534 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
535 // we introduce the type parameter into the local scope.
536 SourceLocation EqualLoc;
537 ParsedType DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000538 if (TryConsumeToken(tok::equal, EqualLoc))
Craig Topper161e4db2014-05-21 06:02:52 +0000539 DefaultArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000540 Declarator::TemplateTypeArgContext).get();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000541
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000542 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
543 KeyLoc, ParamName, NameLoc, Depth, Position,
544 EqualLoc, DefaultArg);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000545}
546
547/// ParseTemplateTemplateParameter - Handle the parsing of template
548/// template parameters.
549///
550/// type-parameter: [C++ temp.param]
Richard Smith78e1ca62014-06-16 15:51:22 +0000551/// 'template' '<' template-parameter-list '>' type-parameter-key
Faisal Vali6a79ca12013-06-08 19:39:00 +0000552/// ...[opt] identifier[opt]
Richard Smith78e1ca62014-06-16 15:51:22 +0000553/// 'template' '<' template-parameter-list '>' type-parameter-key
554/// identifier[opt] = id-expression
555/// type-parameter-key:
556/// 'class'
557/// 'typename' [C++1z]
Faisal Vali6a79ca12013-06-08 19:39:00 +0000558Decl *
559Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
560 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
561
562 // Handle the template <...> part.
563 SourceLocation TemplateLoc = ConsumeToken();
564 SmallVector<Decl*,8> TemplateParams;
565 SourceLocation LAngleLoc, RAngleLoc;
566 {
567 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
568 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
569 RAngleLoc)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000570 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000571 }
572 }
573
Richard Smith78e1ca62014-06-16 15:51:22 +0000574 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000575 // Generate a meaningful error if the user forgot to put class before the
576 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
Richard Smith78e1ca62014-06-16 15:51:22 +0000577 // or greater appear immediately or after 'struct'. In the latter case,
578 // replace the keyword with 'class'.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000579 if (!TryConsumeToken(tok::kw_class)) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000580 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
Richard Smith78e1ca62014-06-16 15:51:22 +0000581 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
582 if (Tok.is(tok::kw_typename)) {
583 Diag(Tok.getLocation(),
584 getLangOpts().CPlusPlus1z
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000585 ? diag::warn_cxx14_compat_template_template_param_typename
Richard Smith78e1ca62014-06-16 15:51:22 +0000586 : diag::ext_template_template_param_typename)
587 << (!getLangOpts().CPlusPlus1z
588 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
589 : FixItHint());
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000590 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
591 tok::greatergreater, tok::ellipsis)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000592 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
593 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
594 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
Richard Smith78e1ca62014-06-16 15:51:22 +0000595 } else
Faisal Vali6a79ca12013-06-08 19:39:00 +0000596 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
597
598 if (Replace)
599 ConsumeToken();
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000600 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000601
602 // Parse the ellipsis, if given.
603 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000604 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000605 Diag(EllipsisLoc,
606 getLangOpts().CPlusPlus11
607 ? diag::warn_cxx98_compat_variadic_templates
608 : diag::ext_variadic_templates);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000609
610 // Get the identifier, if given.
611 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000612 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000613 if (Tok.is(tok::identifier)) {
614 ParamName = Tok.getIdentifierInfo();
615 NameLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000616 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
617 tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000618 // Unnamed template parameter. Don't have to do anything here, just
619 // don't consume this token.
620 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000621 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000622 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000623 }
624
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000625 // Recover from misplaced ellipsis.
626 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
627 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
628 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
629
Faisal Vali6a79ca12013-06-08 19:39:00 +0000630 TemplateParameterList *ParamList =
631 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
632 TemplateLoc, LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000633 TemplateParams,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000634 RAngleLoc);
635
636 // Grab a default argument (if available).
637 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
638 // we introduce the template parameter into the local scope.
639 SourceLocation EqualLoc;
640 ParsedTemplateArgument DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000641 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000642 DefaultArg = ParseTemplateTemplateArgument();
643 if (DefaultArg.isInvalid()) {
644 Diag(Tok.getLocation(),
645 diag::err_default_template_template_parameter_not_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000646 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
647 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000648 }
649 }
650
651 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
652 ParamList, EllipsisLoc,
653 ParamName, NameLoc, Depth,
654 Position, EqualLoc, DefaultArg);
655}
656
657/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
658/// template parameters (e.g., in "template<int Size> class array;").
659///
660/// template-parameter:
661/// ...
662/// parameter-declaration
663Decl *
664Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
665 // Parse the declaration-specifiers (i.e., the type).
666 // FIXME: The type should probably be restricted in some way... Not all
667 // declarators (parts of declarators?) are accepted for parameters.
668 DeclSpec DS(AttrFactory);
669 ParseDeclarationSpecifiers(DS);
670
671 // Parse this as a typename.
672 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
673 ParseDeclarator(ParamDecl);
674 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
675 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
Craig Topper161e4db2014-05-21 06:02:52 +0000676 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000677 }
678
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000679 // Recover from misplaced ellipsis.
680 SourceLocation EllipsisLoc;
681 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
682 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
683
Faisal Vali6a79ca12013-06-08 19:39:00 +0000684 // If there is a default value, parse it.
685 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
686 // we introduce the template parameter into the local scope.
687 SourceLocation EqualLoc;
688 ExprResult DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000689 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000690 // C++ [temp.param]p15:
691 // When parsing a default template-argument for a non-type
692 // template-parameter, the first non-nested > is taken as the
693 // end of the template-parameter-list rather than a greater-than
694 // operator.
695 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Faisal Vali48401eb2015-11-19 19:20:17 +0000696 EnterExpressionEvaluationContext ConstantEvaluated(Actions,
697 Sema::ConstantEvaluated);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000698
Kaelyn Takata999dd852014-12-02 23:32:20 +0000699 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000700 if (DefaultArg.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +0000701 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000702 }
703
704 // Create the parameter.
705 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
706 Depth, Position, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000707 DefaultArg.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000708}
709
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000710void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
711 SourceLocation CorrectLoc,
712 bool AlreadyHasEllipsis,
713 bool IdentifierHasName) {
714 FixItHint Insertion;
715 if (!AlreadyHasEllipsis)
716 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
717 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
718 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
719 << !IdentifierHasName;
720}
721
722void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
723 Declarator &D) {
724 assert(EllipsisLoc.isValid());
725 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
726 if (!AlreadyHasEllipsis)
727 D.setEllipsisLoc(EllipsisLoc);
728 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
729 AlreadyHasEllipsis, D.hasName());
730}
731
Faisal Vali6a79ca12013-06-08 19:39:00 +0000732/// \brief Parses a '>' at the end of a template list.
733///
734/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
735/// to determine if these tokens were supposed to be a '>' followed by
736/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
737///
738/// \param RAngleLoc the location of the consumed '>'.
739///
Douglas Gregor85f3f952015-07-07 03:57:15 +0000740/// \param ConsumeLastToken if true, the '>' is consumed.
741///
742/// \param ObjCGenericList if true, this is the '>' closing an Objective-C
743/// type parameter or type argument list, rather than a C++ template parameter
744/// or argument list.
Serge Pavlovb716b3c2013-08-10 05:54:47 +0000745///
746/// \returns true, if current token does not start with '>', false otherwise.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000747bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000748 bool ConsumeLastToken,
749 bool ObjCGenericList) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000750 // What will be left once we've consumed the '>'.
751 tok::TokenKind RemainingToken;
752 const char *ReplacementStr = "> >";
753
754 switch (Tok.getKind()) {
755 default:
Alp Toker383d2c42014-01-01 03:08:43 +0000756 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000757 return true;
758
759 case tok::greater:
760 // Determine the location of the '>' token. Only consume this token
761 // if the caller asked us to.
762 RAngleLoc = Tok.getLocation();
763 if (ConsumeLastToken)
764 ConsumeToken();
765 return false;
766
767 case tok::greatergreater:
768 RemainingToken = tok::greater;
769 break;
770
771 case tok::greatergreatergreater:
772 RemainingToken = tok::greatergreater;
773 break;
774
775 case tok::greaterequal:
776 RemainingToken = tok::equal;
777 ReplacementStr = "> =";
778 break;
779
780 case tok::greatergreaterequal:
781 RemainingToken = tok::greaterequal;
782 break;
783 }
784
785 // This template-id is terminated by a token which starts with a '>'. Outside
786 // C++11, this is now error recovery, and in C++11, this is error recovery if
Eli Bendersky36a61932014-06-20 13:09:59 +0000787 // the token isn't '>>' or '>>>'.
788 // '>>>' is for CUDA, where this sequence of characters is parsed into
789 // tok::greatergreatergreater, rather than two separate tokens.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000790 //
791 // We always allow this for Objective-C type parameter and type argument
792 // lists.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000793 RAngleLoc = Tok.getLocation();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000794 Token Next = NextToken();
Douglas Gregor85f3f952015-07-07 03:57:15 +0000795 if (!ObjCGenericList) {
796 // The source range of the '>>' or '>=' at the start of the token.
797 CharSourceRange ReplacementRange =
798 CharSourceRange::getCharRange(RAngleLoc,
799 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
800 getLangOpts()));
Faisal Vali6a79ca12013-06-08 19:39:00 +0000801
Douglas Gregor85f3f952015-07-07 03:57:15 +0000802 // A hint to put a space between the '>>'s. In order to make the hint as
803 // clear as possible, we include the characters either side of the space in
804 // the replacement, rather than just inserting a space at SecondCharLoc.
805 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
806 ReplacementStr);
807
808 // A hint to put another space after the token, if it would otherwise be
809 // lexed differently.
810 FixItHint Hint2;
811 if ((RemainingToken == tok::greater ||
812 RemainingToken == tok::greatergreater) &&
813 (Next.isOneOf(tok::greater, tok::greatergreater,
814 tok::greatergreatergreater, tok::equal,
815 tok::greaterequal, tok::greatergreaterequal,
816 tok::equalequal)) &&
817 areTokensAdjacent(Tok, Next))
818 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
819
820 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
821 if (getLangOpts().CPlusPlus11 &&
822 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
823 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
824 else if (Tok.is(tok::greaterequal))
825 DiagId = diag::err_right_angle_bracket_equal_needs_space;
826 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
827 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000828
829 // Strip the initial '>' from the token.
830 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
831 areTokensAdjacent(Tok, Next)) {
832 // Join two adjacent '=' tokens into one, for cases like:
833 // void (*p)() = f<int>;
834 // return f<int>==p;
835 ConsumeToken();
836 Tok.setKind(tok::equalequal);
837 Tok.setLength(Tok.getLength() + 1);
838 } else {
839 Tok.setKind(RemainingToken);
840 Tok.setLength(Tok.getLength() - 1);
841 }
842 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
843 PP.getSourceManager(),
844 getLangOpts()));
845
846 if (!ConsumeLastToken) {
847 // Since we're not supposed to consume the '>' token, we need to push
848 // this token and revert the current token back to the '>'.
849 PP.EnterToken(Tok);
850 Tok.setKind(tok::greater);
851 Tok.setLength(1);
852 Tok.setLocation(RAngleLoc);
853 }
854 return false;
855}
856
857
858/// \brief Parses a template-id that after the template name has
859/// already been parsed.
860///
861/// This routine takes care of parsing the enclosed template argument
862/// list ('<' template-parameter-list [opt] '>') and placing the
863/// results into a form that can be transferred to semantic analysis.
864///
865/// \param Template the template declaration produced by isTemplateName
866///
867/// \param TemplateNameLoc the source location of the template name
868///
869/// \param SS if non-NULL, the nested-name-specifier preceding the
870/// template name.
871///
872/// \param ConsumeLastToken if true, then we will consume the last
873/// token that forms the template-id. Otherwise, we will leave the
874/// last token in the stream (e.g., so that it can be replaced with an
875/// annotation token).
876bool
877Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
878 SourceLocation TemplateNameLoc,
879 const CXXScopeSpec &SS,
880 bool ConsumeLastToken,
881 SourceLocation &LAngleLoc,
882 TemplateArgList &TemplateArgs,
883 SourceLocation &RAngleLoc) {
884 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
885
886 // Consume the '<'.
887 LAngleLoc = ConsumeToken();
888
889 // Parse the optional template-argument-list.
890 bool Invalid = false;
891 {
892 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
893 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
894 Invalid = ParseTemplateArgumentList(TemplateArgs);
895
896 if (Invalid) {
897 // Try to find the closing '>'.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000898 if (ConsumeLastToken)
899 SkipUntil(tok::greater, StopAtSemi);
900 else
901 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000902 return true;
903 }
904 }
905
Douglas Gregor85f3f952015-07-07 03:57:15 +0000906 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
907 /*ObjCGenericList=*/false);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000908}
909
910/// \brief Replace the tokens that form a simple-template-id with an
911/// annotation token containing the complete template-id.
912///
913/// The first token in the stream must be the name of a template that
914/// is followed by a '<'. This routine will parse the complete
915/// simple-template-id and replace the tokens with a single annotation
916/// token with one of two different kinds: if the template-id names a
917/// type (and \p AllowTypeAnnotation is true), the annotation token is
918/// a type annotation that includes the optional nested-name-specifier
919/// (\p SS). Otherwise, the annotation token is a template-id
920/// annotation that does not include the optional
921/// nested-name-specifier.
922///
923/// \param Template the declaration of the template named by the first
924/// token (an identifier), as returned from \c Action::isTemplateName().
925///
926/// \param TNK the kind of template that \p Template
927/// refers to, as returned from \c Action::isTemplateName().
928///
929/// \param SS if non-NULL, the nested-name-specifier that precedes
930/// this template name.
931///
932/// \param TemplateKWLoc if valid, specifies that this template-id
933/// annotation was preceded by the 'template' keyword and gives the
934/// location of that keyword. If invalid (the default), then this
935/// template-id was not preceded by a 'template' keyword.
936///
937/// \param AllowTypeAnnotation if true (the default), then a
938/// simple-template-id that refers to a class template, template
939/// template parameter, or other template that produces a type will be
940/// replaced with a type annotation token. Otherwise, the
941/// simple-template-id is always replaced with a template-id
942/// annotation token.
943///
944/// If an unrecoverable parse error occurs and no annotation token can be
945/// formed, this function returns true.
946///
947bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
948 CXXScopeSpec &SS,
949 SourceLocation TemplateKWLoc,
950 UnqualifiedId &TemplateName,
951 bool AllowTypeAnnotation) {
952 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
953 assert(Template && Tok.is(tok::less) &&
954 "Parser isn't at the beginning of a template-id");
955
956 // Consume the template-name.
957 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
958
959 // Parse the enclosed template argument list.
960 SourceLocation LAngleLoc, RAngleLoc;
961 TemplateArgList TemplateArgs;
962 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
963 TemplateNameLoc,
964 SS, false, LAngleLoc,
965 TemplateArgs,
966 RAngleLoc);
967
968 if (Invalid) {
969 // If we failed to parse the template ID but skipped ahead to a >, we're not
970 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000971 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000972 return true;
973 }
974
975 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
976
977 // Build the annotation token.
978 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
979 TypeResult Type
980 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
981 Template, TemplateNameLoc,
982 LAngleLoc, TemplateArgsPtr, RAngleLoc);
983 if (Type.isInvalid()) {
984 // If we failed to parse the template ID but skipped ahead to a >, we're not
985 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000986 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000987 return true;
988 }
989
990 Tok.setKind(tok::annot_typename);
991 setTypeAnnotation(Tok, Type.get());
992 if (SS.isNotEmpty())
993 Tok.setLocation(SS.getBeginLoc());
994 else if (TemplateKWLoc.isValid())
995 Tok.setLocation(TemplateKWLoc);
996 else
997 Tok.setLocation(TemplateNameLoc);
998 } else {
999 // Build a template-id annotation token that can be processed
1000 // later.
1001 Tok.setKind(tok::annot_template_id);
1002 TemplateIdAnnotation *TemplateId
1003 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
1004 TemplateId->TemplateNameLoc = TemplateNameLoc;
1005 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
1006 TemplateId->Name = TemplateName.Identifier;
1007 TemplateId->Operator = OO_None;
1008 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001009 TemplateId->Name = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001010 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
1011 }
1012 TemplateId->SS = SS;
1013 TemplateId->TemplateKWLoc = TemplateKWLoc;
1014 TemplateId->Template = Template;
1015 TemplateId->Kind = TNK;
1016 TemplateId->LAngleLoc = LAngleLoc;
1017 TemplateId->RAngleLoc = RAngleLoc;
1018 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1019 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
1020 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
1021 Tok.setAnnotationValue(TemplateId);
1022 if (TemplateKWLoc.isValid())
1023 Tok.setLocation(TemplateKWLoc);
1024 else
1025 Tok.setLocation(TemplateNameLoc);
1026 }
1027
1028 // Common fields for the annotation token
1029 Tok.setAnnotationEndLoc(RAngleLoc);
1030
1031 // In case the tokens were cached, have Preprocessor replace them with the
1032 // annotation token.
1033 PP.AnnotateCachedTokens(Tok);
1034 return false;
1035}
1036
1037/// \brief Replaces a template-id annotation token with a type
1038/// annotation token.
1039///
1040/// If there was a failure when forming the type from the template-id,
1041/// a type annotation token will still be created, but will have a
1042/// NULL type pointer to signify an error.
1043void Parser::AnnotateTemplateIdTokenAsType() {
1044 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1045
1046 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1047 assert((TemplateId->Kind == TNK_Type_template ||
1048 TemplateId->Kind == TNK_Dependent_template_name) &&
1049 "Only works for type and dependent templates");
1050
1051 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1052 TemplateId->NumArgs);
1053
1054 TypeResult Type
1055 = Actions.ActOnTemplateIdType(TemplateId->SS,
1056 TemplateId->TemplateKWLoc,
1057 TemplateId->Template,
1058 TemplateId->TemplateNameLoc,
1059 TemplateId->LAngleLoc,
1060 TemplateArgsPtr,
1061 TemplateId->RAngleLoc);
1062 // Create the new "type" annotation token.
1063 Tok.setKind(tok::annot_typename);
David Blaikieefdccaa2016-01-15 23:43:34 +00001064 setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001065 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1066 Tok.setLocation(TemplateId->SS.getBeginLoc());
1067 // End location stays the same
1068
1069 // Replace the template-id annotation token, and possible the scope-specifier
1070 // that precedes it, with the typename annotation token.
1071 PP.AnnotateCachedTokens(Tok);
1072}
1073
1074/// \brief Determine whether the given token can end a template argument.
1075static bool isEndOfTemplateArgument(Token Tok) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001076 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001077}
1078
1079/// \brief Parse a C++ template template argument.
1080ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1081 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1082 !Tok.is(tok::annot_cxxscope))
1083 return ParsedTemplateArgument();
1084
1085 // C++0x [temp.arg.template]p1:
1086 // A template-argument for a template template-parameter shall be the name
1087 // of a class template or an alias template, expressed as id-expression.
1088 //
1089 // We parse an id-expression that refers to a class template or alias
1090 // template. The grammar we parse is:
1091 //
1092 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1093 //
1094 // followed by a token that terminates a template argument, such as ',',
1095 // '>', or (in some cases) '>>'.
1096 CXXScopeSpec SS; // nested-name-specifier, if present
David Blaikieefdccaa2016-01-15 23:43:34 +00001097 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001098 /*EnteringContext=*/false);
David Blaikieefdccaa2016-01-15 23:43:34 +00001099
Faisal Vali6a79ca12013-06-08 19:39:00 +00001100 ParsedTemplateArgument Result;
1101 SourceLocation EllipsisLoc;
1102 if (SS.isSet() && Tok.is(tok::kw_template)) {
1103 // Parse the optional 'template' keyword following the
1104 // nested-name-specifier.
1105 SourceLocation TemplateKWLoc = ConsumeToken();
1106
1107 if (Tok.is(tok::identifier)) {
1108 // We appear to have a dependent template name.
1109 UnqualifiedId Name;
1110 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1111 ConsumeToken(); // the identifier
Alp Toker094e5212014-01-05 03:27:11 +00001112
1113 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1114
Faisal Vali6a79ca12013-06-08 19:39:00 +00001115 // If the next token signals the end of a template argument,
1116 // then we have a dependent template name that could be a template
1117 // template argument.
1118 TemplateTy Template;
1119 if (isEndOfTemplateArgument(Tok) &&
David Blaikieefdccaa2016-01-15 23:43:34 +00001120 Actions.ActOnDependentTemplateName(
1121 getCurScope(), SS, TemplateKWLoc, Name,
1122 /*ObjectType=*/nullptr,
1123 /*EnteringContext=*/false, Template))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001124 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1125 }
1126 } else if (Tok.is(tok::identifier)) {
1127 // We may have a (non-dependent) template name.
1128 TemplateTy Template;
1129 UnqualifiedId Name;
1130 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1131 ConsumeToken(); // the identifier
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001132
1133 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001134
1135 if (isEndOfTemplateArgument(Tok)) {
1136 bool MemberOfUnknownSpecialization;
David Blaikieefdccaa2016-01-15 23:43:34 +00001137 TemplateNameKind TNK = Actions.isTemplateName(
1138 getCurScope(), SS,
1139 /*hasTemplateKeyword=*/false, Name,
1140 /*ObjectType=*/nullptr,
1141 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001142 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1143 // We have an id-expression that refers to a class template or
1144 // (C++0x) alias template.
1145 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1146 }
1147 }
1148 }
1149
1150 // If this is a pack expansion, build it as such.
1151 if (EllipsisLoc.isValid() && !Result.isInvalid())
1152 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1153
1154 return Result;
1155}
1156
1157/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1158///
1159/// template-argument: [C++ 14.2]
1160/// constant-expression
1161/// type-id
1162/// id-expression
1163ParsedTemplateArgument Parser::ParseTemplateArgument() {
1164 // C++ [temp.arg]p2:
1165 // In a template-argument, an ambiguity between a type-id and an
1166 // expression is resolved to a type-id, regardless of the form of
1167 // the corresponding template-parameter.
1168 //
1169 // Therefore, we initially try to parse a type-id.
1170 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1171 SourceLocation Loc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00001172 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001173 Declarator::TemplateTypeArgContext);
1174 if (TypeArg.isInvalid())
1175 return ParsedTemplateArgument();
1176
1177 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1178 TypeArg.get().getAsOpaquePtr(),
1179 Loc);
1180 }
1181
1182 // Try to parse a template template argument.
1183 {
1184 TentativeParsingAction TPA(*this);
1185
1186 ParsedTemplateArgument TemplateTemplateArgument
1187 = ParseTemplateTemplateArgument();
1188 if (!TemplateTemplateArgument.isInvalid()) {
1189 TPA.Commit();
1190 return TemplateTemplateArgument;
1191 }
1192
1193 // Revert this tentative parse to parse a non-type template argument.
1194 TPA.Revert();
1195 }
1196
1197 // Parse a non-type template argument.
1198 SourceLocation Loc = Tok.getLocation();
1199 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1200 if (ExprArg.isInvalid() || !ExprArg.get())
1201 return ParsedTemplateArgument();
1202
1203 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001204 ExprArg.get(), Loc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001205}
1206
1207/// \brief Determine whether the current tokens can only be parsed as a
1208/// template argument list (starting with the '<') and never as a '<'
1209/// expression.
1210bool Parser::IsTemplateArgumentList(unsigned Skip) {
1211 struct AlwaysRevertAction : TentativeParsingAction {
1212 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1213 ~AlwaysRevertAction() { Revert(); }
1214 } Tentative(*this);
1215
1216 while (Skip) {
1217 ConsumeToken();
1218 --Skip;
1219 }
1220
1221 // '<'
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001222 if (!TryConsumeToken(tok::less))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001223 return false;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001224
1225 // An empty template argument list.
1226 if (Tok.is(tok::greater))
1227 return true;
1228
1229 // See whether we have declaration specifiers, which indicate a type.
Richard Smithee390432014-05-16 01:56:53 +00001230 while (isCXXDeclarationSpecifier() == TPResult::True)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001231 ConsumeToken();
1232
1233 // If we have a '>' or a ',' then this is a template argument list.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001234 return Tok.isOneOf(tok::greater, tok::comma);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001235}
1236
1237/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1238/// (C++ [temp.names]). Returns true if there was an error.
1239///
1240/// template-argument-list: [C++ 14.2]
1241/// template-argument
1242/// template-argument-list ',' template-argument
1243bool
1244Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1245 // Template argument lists are constant-evaluation contexts.
1246 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +00001247 ColonProtectionRAIIObject ColonProtection(*this, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001248
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001249 do {
Faisal Vali6a79ca12013-06-08 19:39:00 +00001250 ParsedTemplateArgument Arg = ParseTemplateArgument();
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001251 SourceLocation EllipsisLoc;
1252 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001253 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001254
1255 if (Arg.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001256 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001257 return true;
1258 }
1259
1260 // Save this template argument.
1261 TemplateArgs.push_back(Arg);
1262
1263 // If the next token is a comma, consume it and keep reading
1264 // arguments.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001265 } while (TryConsumeToken(tok::comma));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001266
1267 return false;
1268}
1269
1270/// \brief Parse a C++ explicit template instantiation
1271/// (C++ [temp.explicit]).
1272///
1273/// explicit-instantiation:
1274/// 'extern' [opt] 'template' declaration
1275///
1276/// Note that the 'extern' is a GNU extension and C++11 feature.
1277Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1278 SourceLocation ExternLoc,
1279 SourceLocation TemplateLoc,
1280 SourceLocation &DeclEnd,
1281 AccessSpecifier AS) {
1282 // This isn't really required here.
1283 ParsingDeclRAIIObject
1284 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1285
1286 return ParseSingleDeclarationAfterTemplate(Context,
1287 ParsedTemplateInfo(ExternLoc,
1288 TemplateLoc),
1289 ParsingTemplateParams,
1290 DeclEnd, AS);
1291}
1292
1293SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1294 if (TemplateParams)
1295 return getTemplateParamsRange(TemplateParams->data(),
1296 TemplateParams->size());
1297
1298 SourceRange R(TemplateLoc);
1299 if (ExternLoc.isValid())
1300 R.setBegin(ExternLoc);
1301 return R;
1302}
1303
Richard Smithe40f2ba2013-08-07 21:41:30 +00001304void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1305 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001306}
1307
1308/// \brief Late parse a C++ function template in Microsoft mode.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001309void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
David Majnemerf0a84f22013-08-16 08:29:13 +00001310 if (!LPT.D)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001311 return;
1312
1313 // Get the FunctionDecl.
Alp Tokera2794f92014-01-22 07:29:52 +00001314 FunctionDecl *FunD = LPT.D->getAsFunction();
Faisal Vali6a79ca12013-06-08 19:39:00 +00001315 // Track template parameter depth.
1316 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1317
1318 // To restore the context after late parsing.
Richard Smithb0b68012015-05-11 23:09:06 +00001319 Sema::ContextRAII GlobalSavedContext(
1320 Actions, Actions.Context.getTranslationUnitDecl());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001321
1322 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1323
1324 // Get the list of DeclContexts to reenter.
1325 SmallVector<DeclContext*, 4> DeclContextsToReenter;
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001326 DeclContext *DD = FunD;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001327 while (DD && !DD->isTranslationUnit()) {
1328 DeclContextsToReenter.push_back(DD);
1329 DD = DD->getLexicalParent();
1330 }
1331
1332 // Reenter template scopes from outermost to innermost.
Craig Topper61ac9062013-07-08 03:55:09 +00001333 SmallVectorImpl<DeclContext *>::reverse_iterator II =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001334 DeclContextsToReenter.rbegin();
1335 for (; II != DeclContextsToReenter.rend(); ++II) {
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001336 TemplateParamScopeStack.push_back(new ParseScope(this,
1337 Scope::TemplateParamScope));
1338 unsigned NumParamLists =
1339 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1340 CurTemplateDepthTracker.addDepth(NumParamLists);
1341 if (*II != FunD) {
1342 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1343 Actions.PushDeclContext(Actions.getCurScope(), *II);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001344 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001345 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001346
Richard Smithe40f2ba2013-08-07 21:41:30 +00001347 assert(!LPT.Toks.empty() && "Empty body!");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001348
1349 // Append the current token at the end of the new token stream so that it
1350 // doesn't get lost.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001351 LPT.Toks.push_back(Tok);
1352 PP.EnterTokenStream(LPT.Toks.data(), LPT.Toks.size(), true, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001353
1354 // Consume the previously pushed token.
1355 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001356 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1357 "Inline method not starting with '{', ':' or 'try'");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001358
1359 // Parse the method body. Function body parsing code is similar enough
1360 // to be re-used for method bodies as well.
1361 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1362
1363 // Recreate the containing function DeclContext.
Nico Weber55048cf2014-08-15 22:15:00 +00001364 Sema::ContextRAII FunctionSavedContext(Actions,
1365 Actions.getContainingDC(FunD));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001366
1367 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1368
1369 if (Tok.is(tok::kw_try)) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00001370 ParseFunctionTryBlock(LPT.D, FnScope);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001371 } else {
1372 if (Tok.is(tok::colon))
Richard Smithe40f2ba2013-08-07 21:41:30 +00001373 ParseConstructorInitializer(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001374 else
Richard Smithe40f2ba2013-08-07 21:41:30 +00001375 Actions.ActOnDefaultCtorInitializers(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001376
1377 if (Tok.is(tok::l_brace)) {
Alp Tokera2794f92014-01-22 07:29:52 +00001378 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1379 cast<FunctionTemplateDecl>(LPT.D)
1380 ->getTemplateParameters()
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001381 ->getDepth() == TemplateParameterDepth - 1) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +00001382 "TemplateParameterDepth should be greater than the depth of "
1383 "current template being instantiated!");
Richard Smithe40f2ba2013-08-07 21:41:30 +00001384 ParseFunctionStatementBody(LPT.D, FnScope);
1385 Actions.UnmarkAsLateParsedTemplate(FunD);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001386 } else
Craig Topper161e4db2014-05-21 06:02:52 +00001387 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001388 }
1389
1390 // Exit scopes.
1391 FnScope.Exit();
Craig Topper61ac9062013-07-08 03:55:09 +00001392 SmallVectorImpl<ParseScope *>::reverse_iterator I =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001393 TemplateParamScopeStack.rbegin();
1394 for (; I != TemplateParamScopeStack.rend(); ++I)
1395 delete *I;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001396}
1397
1398/// \brief Lex a delayed template function for late parsing.
1399void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1400 tok::TokenKind kind = Tok.getKind();
1401 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1402 // Consume everything up to (and including) the matching right brace.
1403 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1404 }
1405
1406 // If we're in a function-try-block, we need to store all the catch blocks.
1407 if (kind == tok::kw_try) {
1408 while (Tok.is(tok::kw_catch)) {
1409 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1410 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1411 }
1412 }
1413}