blob: e6ce30a6595de4197962ff619957e313e22cb8b4 [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.
Bruno Cardoso Lopes428a5aa2016-01-31 00:47:51 +0000834 Token PrevTok = Tok;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000835 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
836 areTokensAdjacent(Tok, Next)) {
837 // Join two adjacent '=' tokens into one, for cases like:
838 // void (*p)() = f<int>;
839 // return f<int>==p;
840 ConsumeToken();
841 Tok.setKind(tok::equalequal);
842 Tok.setLength(Tok.getLength() + 1);
843 } else {
844 Tok.setKind(RemainingToken);
845 Tok.setLength(Tok.getLength() - 1);
846 }
847 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
848 PP.getSourceManager(),
849 getLangOpts()));
850
Bruno Cardoso Lopes428a5aa2016-01-31 00:47:51 +0000851 // The advance from '>>' to '>' in a ObjectiveC template argument list needs
852 // to be properly reflected in the token cache to allow correct interaction
853 // between annotation and backtracking.
854 if (ObjCGenericList && PrevTok.getKind() == tok::greatergreater &&
855 RemainingToken == tok::greater && PP.IsPreviousCachedToken(PrevTok)) {
856 PrevTok.setKind(RemainingToken);
857 PrevTok.setLength(1);
Bruno Cardoso Lopesfb9b6cd2016-02-05 19:36:39 +0000858 // Break tok::greatergreater into two tok::greater but only add the second
859 // one in case the client asks to consume the last token.
860 if (ConsumeLastToken)
861 PP.ReplacePreviousCachedToken({PrevTok, Tok});
862 else
863 PP.ReplacePreviousCachedToken({PrevTok});
Bruno Cardoso Lopes428a5aa2016-01-31 00:47:51 +0000864 }
865
Faisal Vali6a79ca12013-06-08 19:39:00 +0000866 if (!ConsumeLastToken) {
867 // Since we're not supposed to consume the '>' token, we need to push
868 // this token and revert the current token back to the '>'.
869 PP.EnterToken(Tok);
870 Tok.setKind(tok::greater);
871 Tok.setLength(1);
872 Tok.setLocation(RAngleLoc);
873 }
874 return false;
875}
876
877
878/// \brief Parses a template-id that after the template name has
879/// already been parsed.
880///
881/// This routine takes care of parsing the enclosed template argument
882/// list ('<' template-parameter-list [opt] '>') and placing the
883/// results into a form that can be transferred to semantic analysis.
884///
885/// \param Template the template declaration produced by isTemplateName
886///
887/// \param TemplateNameLoc the source location of the template name
888///
889/// \param SS if non-NULL, the nested-name-specifier preceding the
890/// template name.
891///
892/// \param ConsumeLastToken if true, then we will consume the last
893/// token that forms the template-id. Otherwise, we will leave the
894/// last token in the stream (e.g., so that it can be replaced with an
895/// annotation token).
896bool
897Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
898 SourceLocation TemplateNameLoc,
899 const CXXScopeSpec &SS,
900 bool ConsumeLastToken,
901 SourceLocation &LAngleLoc,
902 TemplateArgList &TemplateArgs,
903 SourceLocation &RAngleLoc) {
904 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
905
906 // Consume the '<'.
907 LAngleLoc = ConsumeToken();
908
909 // Parse the optional template-argument-list.
910 bool Invalid = false;
911 {
912 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
913 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
914 Invalid = ParseTemplateArgumentList(TemplateArgs);
915
916 if (Invalid) {
917 // Try to find the closing '>'.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000918 if (ConsumeLastToken)
919 SkipUntil(tok::greater, StopAtSemi);
920 else
921 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000922 return true;
923 }
924 }
925
Douglas Gregor85f3f952015-07-07 03:57:15 +0000926 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
927 /*ObjCGenericList=*/false);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000928}
929
930/// \brief Replace the tokens that form a simple-template-id with an
931/// annotation token containing the complete template-id.
932///
933/// The first token in the stream must be the name of a template that
934/// is followed by a '<'. This routine will parse the complete
935/// simple-template-id and replace the tokens with a single annotation
936/// token with one of two different kinds: if the template-id names a
937/// type (and \p AllowTypeAnnotation is true), the annotation token is
938/// a type annotation that includes the optional nested-name-specifier
939/// (\p SS). Otherwise, the annotation token is a template-id
940/// annotation that does not include the optional
941/// nested-name-specifier.
942///
943/// \param Template the declaration of the template named by the first
944/// token (an identifier), as returned from \c Action::isTemplateName().
945///
946/// \param TNK the kind of template that \p Template
947/// refers to, as returned from \c Action::isTemplateName().
948///
949/// \param SS if non-NULL, the nested-name-specifier that precedes
950/// this template name.
951///
952/// \param TemplateKWLoc if valid, specifies that this template-id
953/// annotation was preceded by the 'template' keyword and gives the
954/// location of that keyword. If invalid (the default), then this
955/// template-id was not preceded by a 'template' keyword.
956///
957/// \param AllowTypeAnnotation if true (the default), then a
958/// simple-template-id that refers to a class template, template
959/// template parameter, or other template that produces a type will be
960/// replaced with a type annotation token. Otherwise, the
961/// simple-template-id is always replaced with a template-id
962/// annotation token.
963///
964/// If an unrecoverable parse error occurs and no annotation token can be
965/// formed, this function returns true.
966///
967bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
968 CXXScopeSpec &SS,
969 SourceLocation TemplateKWLoc,
970 UnqualifiedId &TemplateName,
971 bool AllowTypeAnnotation) {
972 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
973 assert(Template && Tok.is(tok::less) &&
974 "Parser isn't at the beginning of a template-id");
975
976 // Consume the template-name.
977 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
978
979 // Parse the enclosed template argument list.
980 SourceLocation LAngleLoc, RAngleLoc;
981 TemplateArgList TemplateArgs;
982 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
983 TemplateNameLoc,
984 SS, false, LAngleLoc,
985 TemplateArgs,
986 RAngleLoc);
987
988 if (Invalid) {
989 // If we failed to parse the template ID but skipped ahead to a >, we're not
990 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000991 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000992 return true;
993 }
994
995 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
996
997 // Build the annotation token.
998 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
999 TypeResult Type
1000 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
1001 Template, TemplateNameLoc,
1002 LAngleLoc, TemplateArgsPtr, RAngleLoc);
1003 if (Type.isInvalid()) {
1004 // If we failed to parse the template ID but skipped ahead to a >, we're not
1005 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001006 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001007 return true;
1008 }
1009
1010 Tok.setKind(tok::annot_typename);
1011 setTypeAnnotation(Tok, Type.get());
1012 if (SS.isNotEmpty())
1013 Tok.setLocation(SS.getBeginLoc());
1014 else if (TemplateKWLoc.isValid())
1015 Tok.setLocation(TemplateKWLoc);
1016 else
1017 Tok.setLocation(TemplateNameLoc);
1018 } else {
1019 // Build a template-id annotation token that can be processed
1020 // later.
1021 Tok.setKind(tok::annot_template_id);
1022 TemplateIdAnnotation *TemplateId
1023 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
1024 TemplateId->TemplateNameLoc = TemplateNameLoc;
1025 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
1026 TemplateId->Name = TemplateName.Identifier;
1027 TemplateId->Operator = OO_None;
1028 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001029 TemplateId->Name = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001030 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
1031 }
1032 TemplateId->SS = SS;
1033 TemplateId->TemplateKWLoc = TemplateKWLoc;
1034 TemplateId->Template = Template;
1035 TemplateId->Kind = TNK;
1036 TemplateId->LAngleLoc = LAngleLoc;
1037 TemplateId->RAngleLoc = RAngleLoc;
1038 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1039 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
1040 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
1041 Tok.setAnnotationValue(TemplateId);
1042 if (TemplateKWLoc.isValid())
1043 Tok.setLocation(TemplateKWLoc);
1044 else
1045 Tok.setLocation(TemplateNameLoc);
1046 }
1047
1048 // Common fields for the annotation token
1049 Tok.setAnnotationEndLoc(RAngleLoc);
1050
1051 // In case the tokens were cached, have Preprocessor replace them with the
1052 // annotation token.
1053 PP.AnnotateCachedTokens(Tok);
1054 return false;
1055}
1056
1057/// \brief Replaces a template-id annotation token with a type
1058/// annotation token.
1059///
1060/// If there was a failure when forming the type from the template-id,
1061/// a type annotation token will still be created, but will have a
1062/// NULL type pointer to signify an error.
1063void Parser::AnnotateTemplateIdTokenAsType() {
1064 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1065
1066 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1067 assert((TemplateId->Kind == TNK_Type_template ||
1068 TemplateId->Kind == TNK_Dependent_template_name) &&
1069 "Only works for type and dependent templates");
1070
1071 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1072 TemplateId->NumArgs);
1073
1074 TypeResult Type
1075 = Actions.ActOnTemplateIdType(TemplateId->SS,
1076 TemplateId->TemplateKWLoc,
1077 TemplateId->Template,
1078 TemplateId->TemplateNameLoc,
1079 TemplateId->LAngleLoc,
1080 TemplateArgsPtr,
1081 TemplateId->RAngleLoc);
1082 // Create the new "type" annotation token.
1083 Tok.setKind(tok::annot_typename);
David Blaikieefdccaa2016-01-15 23:43:34 +00001084 setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001085 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1086 Tok.setLocation(TemplateId->SS.getBeginLoc());
1087 // End location stays the same
1088
1089 // Replace the template-id annotation token, and possible the scope-specifier
1090 // that precedes it, with the typename annotation token.
1091 PP.AnnotateCachedTokens(Tok);
1092}
1093
1094/// \brief Determine whether the given token can end a template argument.
1095static bool isEndOfTemplateArgument(Token Tok) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001096 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001097}
1098
1099/// \brief Parse a C++ template template argument.
1100ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1101 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1102 !Tok.is(tok::annot_cxxscope))
1103 return ParsedTemplateArgument();
1104
1105 // C++0x [temp.arg.template]p1:
1106 // A template-argument for a template template-parameter shall be the name
1107 // of a class template or an alias template, expressed as id-expression.
1108 //
1109 // We parse an id-expression that refers to a class template or alias
1110 // template. The grammar we parse is:
1111 //
1112 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1113 //
1114 // followed by a token that terminates a template argument, such as ',',
1115 // '>', or (in some cases) '>>'.
1116 CXXScopeSpec SS; // nested-name-specifier, if present
David Blaikieefdccaa2016-01-15 23:43:34 +00001117 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001118 /*EnteringContext=*/false);
David Blaikieefdccaa2016-01-15 23:43:34 +00001119
Faisal Vali6a79ca12013-06-08 19:39:00 +00001120 ParsedTemplateArgument Result;
1121 SourceLocation EllipsisLoc;
1122 if (SS.isSet() && Tok.is(tok::kw_template)) {
1123 // Parse the optional 'template' keyword following the
1124 // nested-name-specifier.
1125 SourceLocation TemplateKWLoc = ConsumeToken();
1126
1127 if (Tok.is(tok::identifier)) {
1128 // We appear to have a dependent template name.
1129 UnqualifiedId Name;
1130 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1131 ConsumeToken(); // the identifier
Alp Toker094e5212014-01-05 03:27:11 +00001132
1133 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1134
Faisal Vali6a79ca12013-06-08 19:39:00 +00001135 // If the next token signals the end of a template argument,
1136 // then we have a dependent template name that could be a template
1137 // template argument.
1138 TemplateTy Template;
1139 if (isEndOfTemplateArgument(Tok) &&
David Blaikieefdccaa2016-01-15 23:43:34 +00001140 Actions.ActOnDependentTemplateName(
1141 getCurScope(), SS, TemplateKWLoc, Name,
1142 /*ObjectType=*/nullptr,
1143 /*EnteringContext=*/false, Template))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001144 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1145 }
1146 } else if (Tok.is(tok::identifier)) {
1147 // We may have a (non-dependent) template name.
1148 TemplateTy Template;
1149 UnqualifiedId Name;
1150 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1151 ConsumeToken(); // the identifier
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001152
1153 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001154
1155 if (isEndOfTemplateArgument(Tok)) {
1156 bool MemberOfUnknownSpecialization;
David Blaikieefdccaa2016-01-15 23:43:34 +00001157 TemplateNameKind TNK = Actions.isTemplateName(
1158 getCurScope(), SS,
1159 /*hasTemplateKeyword=*/false, Name,
1160 /*ObjectType=*/nullptr,
1161 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001162 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1163 // We have an id-expression that refers to a class template or
1164 // (C++0x) alias template.
1165 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1166 }
1167 }
1168 }
1169
1170 // If this is a pack expansion, build it as such.
1171 if (EllipsisLoc.isValid() && !Result.isInvalid())
1172 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1173
1174 return Result;
1175}
1176
1177/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1178///
1179/// template-argument: [C++ 14.2]
1180/// constant-expression
1181/// type-id
1182/// id-expression
1183ParsedTemplateArgument Parser::ParseTemplateArgument() {
1184 // C++ [temp.arg]p2:
1185 // In a template-argument, an ambiguity between a type-id and an
1186 // expression is resolved to a type-id, regardless of the form of
1187 // the corresponding template-parameter.
1188 //
1189 // Therefore, we initially try to parse a type-id.
1190 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1191 SourceLocation Loc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00001192 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001193 Declarator::TemplateTypeArgContext);
1194 if (TypeArg.isInvalid())
1195 return ParsedTemplateArgument();
1196
1197 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1198 TypeArg.get().getAsOpaquePtr(),
1199 Loc);
1200 }
1201
1202 // Try to parse a template template argument.
1203 {
1204 TentativeParsingAction TPA(*this);
1205
1206 ParsedTemplateArgument TemplateTemplateArgument
1207 = ParseTemplateTemplateArgument();
1208 if (!TemplateTemplateArgument.isInvalid()) {
1209 TPA.Commit();
1210 return TemplateTemplateArgument;
1211 }
1212
1213 // Revert this tentative parse to parse a non-type template argument.
1214 TPA.Revert();
1215 }
1216
1217 // Parse a non-type template argument.
1218 SourceLocation Loc = Tok.getLocation();
1219 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1220 if (ExprArg.isInvalid() || !ExprArg.get())
1221 return ParsedTemplateArgument();
1222
1223 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001224 ExprArg.get(), Loc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001225}
1226
1227/// \brief Determine whether the current tokens can only be parsed as a
1228/// template argument list (starting with the '<') and never as a '<'
1229/// expression.
1230bool Parser::IsTemplateArgumentList(unsigned Skip) {
1231 struct AlwaysRevertAction : TentativeParsingAction {
1232 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1233 ~AlwaysRevertAction() { Revert(); }
1234 } Tentative(*this);
1235
1236 while (Skip) {
1237 ConsumeToken();
1238 --Skip;
1239 }
1240
1241 // '<'
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001242 if (!TryConsumeToken(tok::less))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001243 return false;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001244
1245 // An empty template argument list.
1246 if (Tok.is(tok::greater))
1247 return true;
1248
1249 // See whether we have declaration specifiers, which indicate a type.
Richard Smithee390432014-05-16 01:56:53 +00001250 while (isCXXDeclarationSpecifier() == TPResult::True)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001251 ConsumeToken();
1252
1253 // If we have a '>' or a ',' then this is a template argument list.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001254 return Tok.isOneOf(tok::greater, tok::comma);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001255}
1256
1257/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1258/// (C++ [temp.names]). Returns true if there was an error.
1259///
1260/// template-argument-list: [C++ 14.2]
1261/// template-argument
1262/// template-argument-list ',' template-argument
1263bool
1264Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1265 // Template argument lists are constant-evaluation contexts.
1266 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +00001267 ColonProtectionRAIIObject ColonProtection(*this, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001268
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001269 do {
Faisal Vali6a79ca12013-06-08 19:39:00 +00001270 ParsedTemplateArgument Arg = ParseTemplateArgument();
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001271 SourceLocation EllipsisLoc;
1272 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001273 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001274
1275 if (Arg.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001276 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001277 return true;
1278 }
1279
1280 // Save this template argument.
1281 TemplateArgs.push_back(Arg);
1282
1283 // If the next token is a comma, consume it and keep reading
1284 // arguments.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001285 } while (TryConsumeToken(tok::comma));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001286
1287 return false;
1288}
1289
1290/// \brief Parse a C++ explicit template instantiation
1291/// (C++ [temp.explicit]).
1292///
1293/// explicit-instantiation:
1294/// 'extern' [opt] 'template' declaration
1295///
1296/// Note that the 'extern' is a GNU extension and C++11 feature.
1297Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1298 SourceLocation ExternLoc,
1299 SourceLocation TemplateLoc,
1300 SourceLocation &DeclEnd,
1301 AccessSpecifier AS) {
1302 // This isn't really required here.
1303 ParsingDeclRAIIObject
1304 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1305
1306 return ParseSingleDeclarationAfterTemplate(Context,
1307 ParsedTemplateInfo(ExternLoc,
1308 TemplateLoc),
1309 ParsingTemplateParams,
1310 DeclEnd, AS);
1311}
1312
1313SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1314 if (TemplateParams)
1315 return getTemplateParamsRange(TemplateParams->data(),
1316 TemplateParams->size());
1317
1318 SourceRange R(TemplateLoc);
1319 if (ExternLoc.isValid())
1320 R.setBegin(ExternLoc);
1321 return R;
1322}
1323
Richard Smithe40f2ba2013-08-07 21:41:30 +00001324void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1325 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001326}
1327
1328/// \brief Late parse a C++ function template in Microsoft mode.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001329void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
David Majnemerf0a84f22013-08-16 08:29:13 +00001330 if (!LPT.D)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001331 return;
1332
1333 // Get the FunctionDecl.
Alp Tokera2794f92014-01-22 07:29:52 +00001334 FunctionDecl *FunD = LPT.D->getAsFunction();
Faisal Vali6a79ca12013-06-08 19:39:00 +00001335 // Track template parameter depth.
1336 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1337
1338 // To restore the context after late parsing.
Richard Smithb0b68012015-05-11 23:09:06 +00001339 Sema::ContextRAII GlobalSavedContext(
1340 Actions, Actions.Context.getTranslationUnitDecl());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001341
1342 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1343
1344 // Get the list of DeclContexts to reenter.
1345 SmallVector<DeclContext*, 4> DeclContextsToReenter;
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001346 DeclContext *DD = FunD;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001347 while (DD && !DD->isTranslationUnit()) {
1348 DeclContextsToReenter.push_back(DD);
1349 DD = DD->getLexicalParent();
1350 }
1351
1352 // Reenter template scopes from outermost to innermost.
Craig Topper61ac9062013-07-08 03:55:09 +00001353 SmallVectorImpl<DeclContext *>::reverse_iterator II =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001354 DeclContextsToReenter.rbegin();
1355 for (; II != DeclContextsToReenter.rend(); ++II) {
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001356 TemplateParamScopeStack.push_back(new ParseScope(this,
1357 Scope::TemplateParamScope));
1358 unsigned NumParamLists =
1359 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1360 CurTemplateDepthTracker.addDepth(NumParamLists);
1361 if (*II != FunD) {
1362 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1363 Actions.PushDeclContext(Actions.getCurScope(), *II);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001364 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001365 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001366
Richard Smithe40f2ba2013-08-07 21:41:30 +00001367 assert(!LPT.Toks.empty() && "Empty body!");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001368
1369 // Append the current token at the end of the new token stream so that it
1370 // doesn't get lost.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001371 LPT.Toks.push_back(Tok);
1372 PP.EnterTokenStream(LPT.Toks.data(), LPT.Toks.size(), true, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001373
1374 // Consume the previously pushed token.
1375 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001376 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1377 "Inline method not starting with '{', ':' or 'try'");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001378
1379 // Parse the method body. Function body parsing code is similar enough
1380 // to be re-used for method bodies as well.
1381 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1382
1383 // Recreate the containing function DeclContext.
Nico Weber55048cf2014-08-15 22:15:00 +00001384 Sema::ContextRAII FunctionSavedContext(Actions,
1385 Actions.getContainingDC(FunD));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001386
1387 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1388
1389 if (Tok.is(tok::kw_try)) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00001390 ParseFunctionTryBlock(LPT.D, FnScope);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001391 } else {
1392 if (Tok.is(tok::colon))
Richard Smithe40f2ba2013-08-07 21:41:30 +00001393 ParseConstructorInitializer(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001394 else
Richard Smithe40f2ba2013-08-07 21:41:30 +00001395 Actions.ActOnDefaultCtorInitializers(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001396
1397 if (Tok.is(tok::l_brace)) {
Alp Tokera2794f92014-01-22 07:29:52 +00001398 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1399 cast<FunctionTemplateDecl>(LPT.D)
1400 ->getTemplateParameters()
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001401 ->getDepth() == TemplateParameterDepth - 1) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +00001402 "TemplateParameterDepth should be greater than the depth of "
1403 "current template being instantiated!");
Richard Smithe40f2ba2013-08-07 21:41:30 +00001404 ParseFunctionStatementBody(LPT.D, FnScope);
1405 Actions.UnmarkAsLateParsedTemplate(FunD);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001406 } else
Craig Topper161e4db2014-05-21 06:02:52 +00001407 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001408 }
1409
1410 // Exit scopes.
1411 FnScope.Exit();
Craig Topper61ac9062013-07-08 03:55:09 +00001412 SmallVectorImpl<ParseScope *>::reverse_iterator I =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001413 TemplateParamScopeStack.rbegin();
1414 for (; I != TemplateParamScopeStack.rend(); ++I)
1415 delete *I;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001416}
1417
1418/// \brief Lex a delayed template function for late parsing.
1419void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1420 tok::TokenKind kind = Tok.getKind();
1421 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1422 // Consume everything up to (and including) the matching right brace.
1423 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1424 }
1425
1426 // If we're in a function-try-block, we need to store all the catch blocks.
1427 if (kind == tok::kw_try) {
1428 while (Tok.is(tok::kw_catch)) {
1429 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1430 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1431 }
1432 }
1433}