blob: 6cf7b6d3dc55430b0872b72720c10af887de80f9 [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
Hubert Tongf608c052016-04-29 18:05:37 +0000125 ExprResult OptionalRequiresClauseConstraintER;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000126 if (!TemplateParams.empty()) {
127 isSpecialization = false;
128 ++CurTemplateDepthTracker;
Hubert Tongec3cb572015-06-25 00:23:39 +0000129
130 if (TryConsumeToken(tok::kw_requires)) {
Hubert Tongf608c052016-04-29 18:05:37 +0000131 OptionalRequiresClauseConstraintER =
Hubert Tongec3cb572015-06-25 00:23:39 +0000132 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
Hubert Tongf608c052016-04-29 18:05:37 +0000133 if (!OptionalRequiresClauseConstraintER.isUsable()) {
Hubert Tongec3cb572015-06-25 00:23:39 +0000134 // Skip until the semi-colon or a '}'.
135 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
136 TryConsumeToken(tok::semi);
137 return nullptr;
138 }
139 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000140 } else {
141 LastParamListWasEmpty = true;
142 }
Hubert Tongf608c052016-04-29 18:05:37 +0000143
144 ParamLists.push_back(Actions.ActOnTemplateParameterList(
145 CurTemplateDepthTracker.getDepth(), ExportLoc, TemplateLoc, LAngleLoc,
146 TemplateParams, RAngleLoc, OptionalRequiresClauseConstraintER.get()));
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000147 } while (Tok.isOneOf(tok::kw_export, tok::kw_template));
Faisal Vali6a79ca12013-06-08 19:39:00 +0000148
Akira Hatanaka10aced82016-04-29 02:24:14 +0000149 unsigned NewFlags = getCurScope()->getFlags() & ~Scope::TemplateParamScope;
150 ParseScopeFlags TemplateScopeFlags(this, NewFlags, isSpecialization);
151
Faisal Vali6a79ca12013-06-08 19:39:00 +0000152 // Parse the actual template declaration.
153 return ParseSingleDeclarationAfterTemplate(Context,
154 ParsedTemplateInfo(&ParamLists,
155 isSpecialization,
156 LastParamListWasEmpty),
157 ParsingTemplateParams,
158 DeclEnd, AS, AccessAttrs);
159}
160
161/// \brief Parse a single declaration that declares a template,
162/// template specialization, or explicit instantiation of a template.
163///
164/// \param DeclEnd will receive the source location of the last token
165/// within this declaration.
166///
167/// \param AS the access specifier associated with this
168/// declaration. Will be AS_none for namespace-scope declarations.
169///
170/// \returns the new declaration.
171Decl *
172Parser::ParseSingleDeclarationAfterTemplate(
173 unsigned Context,
174 const ParsedTemplateInfo &TemplateInfo,
175 ParsingDeclRAIIObject &DiagsFromTParams,
176 SourceLocation &DeclEnd,
177 AccessSpecifier AS,
178 AttributeList *AccessAttrs) {
179 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
180 "Template information required");
181
Aaron Ballmane7c544d2014-08-04 20:28:35 +0000182 if (Tok.is(tok::kw_static_assert)) {
183 // A static_assert declaration may not be templated.
184 Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
185 << TemplateInfo.getSourceRange();
186 // Parse the static_assert declaration to improve error recovery.
187 return ParseStaticAssertDeclaration(DeclEnd);
188 }
189
Faisal Vali6a79ca12013-06-08 19:39:00 +0000190 if (Context == Declarator::MemberContext) {
191 // We are parsing a member template.
192 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
193 &DiagsFromTParams);
Craig Topper161e4db2014-05-21 06:02:52 +0000194 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000195 }
196
197 ParsedAttributesWithRange prefixAttrs(AttrFactory);
198 MaybeParseCXX11Attributes(prefixAttrs);
199
200 if (Tok.is(tok::kw_using))
201 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
202 prefixAttrs);
203
204 // Parse the declaration specifiers, stealing any diagnostics from
205 // the template parameters.
206 ParsingDeclSpec DS(*this, &DiagsFromTParams);
207
208 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
209 getDeclSpecContextFromDeclaratorContext(Context));
210
211 if (Tok.is(tok::semi)) {
212 ProhibitAttributes(prefixAttrs);
213 DeclEnd = ConsumeToken();
Nico Weber7b837f52016-01-28 19:25:00 +0000214 RecordDecl *AnonRecord = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000215 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
216 getCurScope(), AS, DS,
217 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
218 : MultiTemplateParamsArg(),
Nico Weber7b837f52016-01-28 19:25:00 +0000219 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
220 AnonRecord);
221 assert(!AnonRecord &&
222 "Anonymous unions/structs should not be valid with template");
Faisal Vali6a79ca12013-06-08 19:39:00 +0000223 DS.complete(Decl);
224 return Decl;
225 }
226
227 // Move the attributes from the prefix into the DS.
228 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
229 ProhibitAttributes(prefixAttrs);
230 else
231 DS.takeAttributesFrom(prefixAttrs);
232
233 // Parse the declarator.
234 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
235 ParseDeclarator(DeclaratorInfo);
236 // Error parsing the declarator?
237 if (!DeclaratorInfo.hasName()) {
238 // If so, skip until the semi-colon or a }.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000239 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000240 if (Tok.is(tok::semi))
241 ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000242 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000243 }
244
245 LateParsedAttrList LateParsedAttrs(true);
246 if (DeclaratorInfo.isFunctionDeclarator())
247 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
248
249 if (DeclaratorInfo.isFunctionDeclarator() &&
250 isStartOfFunctionDefinition(DeclaratorInfo)) {
Reid Klecknerd61a3112014-12-15 23:16:32 +0000251
252 // Function definitions are only allowed at file scope and in C++ classes.
253 // The C++ inline method definition case is handled elsewhere, so we only
254 // need to handle the file scope definition case.
255 if (Context != Declarator::FileContext) {
256 Diag(Tok, diag::err_function_definition_not_allowed);
257 SkipMalformedDecl();
258 return nullptr;
259 }
260
Faisal Vali6a79ca12013-06-08 19:39:00 +0000261 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
262 // Recover by ignoring the 'typedef'. This was probably supposed to be
263 // the 'typename' keyword, which we should have already suggested adding
264 // if it's appropriate.
265 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
266 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
267 DS.ClearStorageClassSpecs();
268 }
Larisse Voufo725de3e2013-06-21 00:08:46 +0000269
270 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
271 if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
272 // If the declarator-id is not a template-id, issue a diagnostic and
273 // recover by ignoring the 'template' keyword.
274 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000275 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
276 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000277 } else {
278 SourceLocation LAngleLoc
279 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000280 Diag(DeclaratorInfo.getIdentifierLoc(),
Larisse Voufo725de3e2013-06-21 00:08:46 +0000281 diag::err_explicit_instantiation_with_definition)
Larisse Voufo39a1e502013-08-06 01:03:05 +0000282 << SourceRange(TemplateInfo.TemplateLoc)
283 << FixItHint::CreateInsertion(LAngleLoc, "<>");
Larisse Voufo725de3e2013-06-21 00:08:46 +0000284
Larisse Voufo39a1e502013-08-06 01:03:05 +0000285 // Recover as if it were an explicit specialization.
Larisse Voufob9bbaba2013-06-22 13:56:11 +0000286 TemplateParameterLists FakedParamLists;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000287 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +0000288 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
Hubert Tongf608c052016-04-29 18:05:37 +0000289 LAngleLoc, nullptr));
Larisse Voufo725de3e2013-06-21 00:08:46 +0000290
Larisse Voufo39a1e502013-08-06 01:03:05 +0000291 return ParseFunctionDefinition(
292 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
293 /*isSpecialization=*/true,
294 /*LastParamListWasEmpty=*/true),
295 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000296 }
297 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000298 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
Larisse Voufo39a1e502013-08-06 01:03:05 +0000299 &LateParsedAttrs);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000300 }
301
302 // Parse this declaration.
303 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
304 TemplateInfo);
305
306 if (Tok.is(tok::comma)) {
307 Diag(Tok, diag::err_multiple_template_declarators)
308 << (int)TemplateInfo.Kind;
Alexey Bataevee6507d2013-11-18 08:17:37 +0000309 SkipUntil(tok::semi);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000310 return ThisDecl;
311 }
312
313 // Eat the semi colon after the declaration.
314 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
315 if (LateParsedAttrs.size() > 0)
316 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
317 DeclaratorInfo.complete(ThisDecl);
318 return ThisDecl;
319}
320
321/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
322/// angle brackets. Depth is the depth of this template-parameter-list, which
323/// is the number of template headers directly enclosing this template header.
324/// TemplateParams is the current list of template parameters we're building.
325/// The template parameter we parse will be added to this list. LAngleLoc and
326/// RAngleLoc will receive the positions of the '<' and '>', respectively,
327/// that enclose this template parameter list.
328///
329/// \returns true if an error occurred, false otherwise.
330bool Parser::ParseTemplateParameters(unsigned Depth,
331 SmallVectorImpl<Decl*> &TemplateParams,
332 SourceLocation &LAngleLoc,
333 SourceLocation &RAngleLoc) {
334 // Get the template parameter list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000335 if (!TryConsumeToken(tok::less, LAngleLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000336 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
337 return true;
338 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000339
340 // Try to parse the template parameter list.
341 bool Failed = false;
342 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
343 Failed = ParseTemplateParameterList(Depth, TemplateParams);
344
345 if (Tok.is(tok::greatergreater)) {
346 // No diagnostic required here: a template-parameter-list can only be
347 // followed by a declaration or, for a template template parameter, the
348 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
349 // This matters for elegant diagnosis of:
350 // template<template<typename>> struct S;
351 Tok.setKind(tok::greater);
352 RAngleLoc = Tok.getLocation();
353 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
Alp Toker383d2c42014-01-01 03:08:43 +0000354 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
355 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000356 return true;
357 }
358 return false;
359}
360
361/// ParseTemplateParameterList - Parse a template parameter list. If
362/// the parsing fails badly (i.e., closing bracket was left out), this
363/// will try to put the token stream in a reasonable position (closing
364/// a statement, etc.) and return false.
365///
366/// template-parameter-list: [C++ temp]
367/// template-parameter
368/// template-parameter-list ',' template-parameter
369bool
370Parser::ParseTemplateParameterList(unsigned Depth,
371 SmallVectorImpl<Decl*> &TemplateParams) {
372 while (1) {
373 if (Decl *TmpParam
374 = ParseTemplateParameter(Depth, TemplateParams.size())) {
375 TemplateParams.push_back(TmpParam);
376 } else {
377 // If we failed to parse a template parameter, skip until we find
378 // a comma or closing brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000379 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
380 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000381 }
382
383 // Did we find a comma or the end of the template parameter list?
384 if (Tok.is(tok::comma)) {
385 ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000386 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000387 // Don't consume this... that's done by template parser.
388 break;
389 } else {
390 // Somebody probably forgot to close the template. Skip ahead and
391 // try to get out of the expression. This error is currently
392 // subsumed by whatever goes on in ParseTemplateParameter.
393 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000394 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
395 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000396 return false;
397 }
398 }
399 return true;
400}
401
402/// \brief Determine whether the parser is at the start of a template
403/// type parameter.
404bool Parser::isStartOfTemplateTypeParameter() {
405 if (Tok.is(tok::kw_class)) {
406 // "class" may be the start of an elaborated-type-specifier or a
407 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
408 switch (NextToken().getKind()) {
409 case tok::equal:
410 case tok::comma:
411 case tok::greater:
412 case tok::greatergreater:
413 case tok::ellipsis:
414 return true;
415
416 case tok::identifier:
417 // This may be either a type-parameter or an elaborated-type-specifier.
418 // We have to look further.
419 break;
420
421 default:
422 return false;
423 }
424
425 switch (GetLookAheadToken(2).getKind()) {
426 case tok::equal:
427 case tok::comma:
428 case tok::greater:
429 case tok::greatergreater:
430 return true;
431
432 default:
433 return false;
434 }
435 }
436
437 if (Tok.isNot(tok::kw_typename))
438 return false;
439
440 // C++ [temp.param]p2:
441 // There is no semantic difference between class and typename in a
442 // template-parameter. typename followed by an unqualified-id
443 // names a template type parameter. typename followed by a
444 // qualified-id denotes the type in a non-type
445 // parameter-declaration.
446 Token Next = NextToken();
447
448 // If we have an identifier, skip over it.
449 if (Next.getKind() == tok::identifier)
450 Next = GetLookAheadToken(2);
451
452 switch (Next.getKind()) {
453 case tok::equal:
454 case tok::comma:
455 case tok::greater:
456 case tok::greatergreater:
457 case tok::ellipsis:
458 return true;
459
460 default:
461 return false;
462 }
463}
464
465/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
466///
467/// template-parameter: [C++ temp.param]
468/// type-parameter
469/// parameter-declaration
470///
471/// type-parameter: (see below)
472/// 'class' ...[opt] identifier[opt]
473/// 'class' identifier[opt] '=' type-id
474/// 'typename' ...[opt] identifier[opt]
475/// 'typename' identifier[opt] '=' type-id
476/// 'template' '<' template-parameter-list '>'
477/// 'class' ...[opt] identifier[opt]
478/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
479/// = id-expression
480Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
481 if (isStartOfTemplateTypeParameter())
482 return ParseTypeParameter(Depth, Position);
483
484 if (Tok.is(tok::kw_template))
485 return ParseTemplateTemplateParameter(Depth, Position);
486
487 // If it's none of the above, then it must be a parameter declaration.
488 // NOTE: This will pick up errors in the closure of the template parameter
489 // list (e.g., template < ; Check here to implement >> style closures.
490 return ParseNonTypeTemplateParameter(Depth, Position);
491}
492
493/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
494/// Other kinds of template parameters are parsed in
495/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
496///
497/// type-parameter: [C++ temp.param]
498/// 'class' ...[opt][C++0x] identifier[opt]
499/// 'class' identifier[opt] '=' type-id
500/// 'typename' ...[opt][C++0x] identifier[opt]
501/// 'typename' identifier[opt] '=' type-id
502Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000503 assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +0000504 "A type-parameter starts with 'class' or 'typename'");
505
506 // Consume the 'class' or 'typename' keyword.
507 bool TypenameKeyword = Tok.is(tok::kw_typename);
508 SourceLocation KeyLoc = ConsumeToken();
509
510 // Grab the ellipsis (if given).
Faisal Vali6a79ca12013-06-08 19:39:00 +0000511 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000512 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000513 Diag(EllipsisLoc,
514 getLangOpts().CPlusPlus11
515 ? diag::warn_cxx98_compat_variadic_templates
516 : diag::ext_variadic_templates);
517 }
518
519 // Grab the template parameter name (if given)
520 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000521 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000522 if (Tok.is(tok::identifier)) {
523 ParamName = Tok.getIdentifierInfo();
524 NameLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000525 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
526 tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000527 // Unnamed template parameter. Don't have to do anything here, just
528 // don't consume this token.
529 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000530 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000531 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000532 }
533
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000534 // Recover from misplaced ellipsis.
535 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
536 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
537 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
538
Faisal Vali6a79ca12013-06-08 19:39:00 +0000539 // Grab a default argument (if available).
540 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
541 // we introduce the type parameter into the local scope.
542 SourceLocation EqualLoc;
543 ParsedType DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000544 if (TryConsumeToken(tok::equal, EqualLoc))
Craig Topper161e4db2014-05-21 06:02:52 +0000545 DefaultArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000546 Declarator::TemplateTypeArgContext).get();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000547
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000548 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
549 KeyLoc, ParamName, NameLoc, Depth, Position,
550 EqualLoc, DefaultArg);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000551}
552
553/// ParseTemplateTemplateParameter - Handle the parsing of template
554/// template parameters.
555///
556/// type-parameter: [C++ temp.param]
Richard Smith78e1ca62014-06-16 15:51:22 +0000557/// 'template' '<' template-parameter-list '>' type-parameter-key
Faisal Vali6a79ca12013-06-08 19:39:00 +0000558/// ...[opt] identifier[opt]
Richard Smith78e1ca62014-06-16 15:51:22 +0000559/// 'template' '<' template-parameter-list '>' type-parameter-key
560/// identifier[opt] = id-expression
561/// type-parameter-key:
562/// 'class'
563/// 'typename' [C++1z]
Faisal Vali6a79ca12013-06-08 19:39:00 +0000564Decl *
565Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
566 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
567
568 // Handle the template <...> part.
569 SourceLocation TemplateLoc = ConsumeToken();
570 SmallVector<Decl*,8> TemplateParams;
571 SourceLocation LAngleLoc, RAngleLoc;
572 {
573 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
574 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
575 RAngleLoc)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000576 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000577 }
578 }
579
Richard Smith78e1ca62014-06-16 15:51:22 +0000580 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000581 // Generate a meaningful error if the user forgot to put class before the
582 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
Richard Smith78e1ca62014-06-16 15:51:22 +0000583 // or greater appear immediately or after 'struct'. In the latter case,
584 // replace the keyword with 'class'.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000585 if (!TryConsumeToken(tok::kw_class)) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000586 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
Richard Smith78e1ca62014-06-16 15:51:22 +0000587 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
588 if (Tok.is(tok::kw_typename)) {
589 Diag(Tok.getLocation(),
590 getLangOpts().CPlusPlus1z
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000591 ? diag::warn_cxx14_compat_template_template_param_typename
Richard Smith78e1ca62014-06-16 15:51:22 +0000592 : diag::ext_template_template_param_typename)
593 << (!getLangOpts().CPlusPlus1z
594 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
595 : FixItHint());
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000596 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
597 tok::greatergreater, tok::ellipsis)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000598 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
599 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
600 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
Richard Smith78e1ca62014-06-16 15:51:22 +0000601 } else
Faisal Vali6a79ca12013-06-08 19:39:00 +0000602 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
603
604 if (Replace)
605 ConsumeToken();
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000606 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000607
608 // Parse the ellipsis, if given.
609 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000610 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000611 Diag(EllipsisLoc,
612 getLangOpts().CPlusPlus11
613 ? diag::warn_cxx98_compat_variadic_templates
614 : diag::ext_variadic_templates);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000615
616 // Get the identifier, if given.
617 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000618 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000619 if (Tok.is(tok::identifier)) {
620 ParamName = Tok.getIdentifierInfo();
621 NameLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000622 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
623 tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000624 // Unnamed template parameter. Don't have to do anything here, just
625 // don't consume this token.
626 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000627 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000628 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000629 }
630
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000631 // Recover from misplaced ellipsis.
632 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
633 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
634 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
635
Faisal Vali6a79ca12013-06-08 19:39:00 +0000636 TemplateParameterList *ParamList =
637 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
638 TemplateLoc, LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000639 TemplateParams,
Hubert Tongf608c052016-04-29 18:05:37 +0000640 RAngleLoc, nullptr);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000641
642 // Grab a default argument (if available).
643 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
644 // we introduce the template parameter into the local scope.
645 SourceLocation EqualLoc;
646 ParsedTemplateArgument DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000647 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000648 DefaultArg = ParseTemplateTemplateArgument();
649 if (DefaultArg.isInvalid()) {
650 Diag(Tok.getLocation(),
651 diag::err_default_template_template_parameter_not_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000652 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
653 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000654 }
655 }
656
657 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
658 ParamList, EllipsisLoc,
659 ParamName, NameLoc, Depth,
660 Position, EqualLoc, DefaultArg);
661}
662
663/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
664/// template parameters (e.g., in "template<int Size> class array;").
665///
666/// template-parameter:
667/// ...
668/// parameter-declaration
669Decl *
670Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
671 // Parse the declaration-specifiers (i.e., the type).
672 // FIXME: The type should probably be restricted in some way... Not all
673 // declarators (parts of declarators?) are accepted for parameters.
674 DeclSpec DS(AttrFactory);
675 ParseDeclarationSpecifiers(DS);
676
677 // Parse this as a typename.
678 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
679 ParseDeclarator(ParamDecl);
680 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
681 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
Craig Topper161e4db2014-05-21 06:02:52 +0000682 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000683 }
684
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000685 // Recover from misplaced ellipsis.
686 SourceLocation EllipsisLoc;
687 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
688 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
689
Faisal Vali6a79ca12013-06-08 19:39:00 +0000690 // If there is a default value, parse it.
691 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
692 // we introduce the template parameter into the local scope.
693 SourceLocation EqualLoc;
694 ExprResult DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000695 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000696 // C++ [temp.param]p15:
697 // When parsing a default template-argument for a non-type
698 // template-parameter, the first non-nested > is taken as the
699 // end of the template-parameter-list rather than a greater-than
700 // operator.
701 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Faisal Vali48401eb2015-11-19 19:20:17 +0000702 EnterExpressionEvaluationContext ConstantEvaluated(Actions,
703 Sema::ConstantEvaluated);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000704
Kaelyn Takata999dd852014-12-02 23:32:20 +0000705 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000706 if (DefaultArg.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +0000707 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000708 }
709
710 // Create the parameter.
711 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
712 Depth, Position, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000713 DefaultArg.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000714}
715
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000716void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
717 SourceLocation CorrectLoc,
718 bool AlreadyHasEllipsis,
719 bool IdentifierHasName) {
720 FixItHint Insertion;
721 if (!AlreadyHasEllipsis)
722 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
723 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
724 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
725 << !IdentifierHasName;
726}
727
728void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
729 Declarator &D) {
730 assert(EllipsisLoc.isValid());
731 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
732 if (!AlreadyHasEllipsis)
733 D.setEllipsisLoc(EllipsisLoc);
734 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
735 AlreadyHasEllipsis, D.hasName());
736}
737
Faisal Vali6a79ca12013-06-08 19:39:00 +0000738/// \brief Parses a '>' at the end of a template list.
739///
740/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
741/// to determine if these tokens were supposed to be a '>' followed by
742/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
743///
744/// \param RAngleLoc the location of the consumed '>'.
745///
Douglas Gregor85f3f952015-07-07 03:57:15 +0000746/// \param ConsumeLastToken if true, the '>' is consumed.
747///
748/// \param ObjCGenericList if true, this is the '>' closing an Objective-C
749/// type parameter or type argument list, rather than a C++ template parameter
750/// or argument list.
Serge Pavlovb716b3c2013-08-10 05:54:47 +0000751///
752/// \returns true, if current token does not start with '>', false otherwise.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000753bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000754 bool ConsumeLastToken,
755 bool ObjCGenericList) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000756 // What will be left once we've consumed the '>'.
757 tok::TokenKind RemainingToken;
758 const char *ReplacementStr = "> >";
759
760 switch (Tok.getKind()) {
761 default:
Alp Toker383d2c42014-01-01 03:08:43 +0000762 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000763 return true;
764
765 case tok::greater:
766 // Determine the location of the '>' token. Only consume this token
767 // if the caller asked us to.
768 RAngleLoc = Tok.getLocation();
769 if (ConsumeLastToken)
770 ConsumeToken();
771 return false;
772
773 case tok::greatergreater:
774 RemainingToken = tok::greater;
775 break;
776
777 case tok::greatergreatergreater:
778 RemainingToken = tok::greatergreater;
779 break;
780
781 case tok::greaterequal:
782 RemainingToken = tok::equal;
783 ReplacementStr = "> =";
784 break;
785
786 case tok::greatergreaterequal:
787 RemainingToken = tok::greaterequal;
788 break;
789 }
790
791 // This template-id is terminated by a token which starts with a '>'. Outside
792 // C++11, this is now error recovery, and in C++11, this is error recovery if
Eli Bendersky36a61932014-06-20 13:09:59 +0000793 // the token isn't '>>' or '>>>'.
794 // '>>>' is for CUDA, where this sequence of characters is parsed into
795 // tok::greatergreatergreater, rather than two separate tokens.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000796 //
797 // We always allow this for Objective-C type parameter and type argument
798 // lists.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000799 RAngleLoc = Tok.getLocation();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000800 Token Next = NextToken();
Douglas Gregor85f3f952015-07-07 03:57:15 +0000801 if (!ObjCGenericList) {
802 // The source range of the '>>' or '>=' at the start of the token.
803 CharSourceRange ReplacementRange =
804 CharSourceRange::getCharRange(RAngleLoc,
805 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
806 getLangOpts()));
Faisal Vali6a79ca12013-06-08 19:39:00 +0000807
Douglas Gregor85f3f952015-07-07 03:57:15 +0000808 // A hint to put a space between the '>>'s. In order to make the hint as
809 // clear as possible, we include the characters either side of the space in
810 // the replacement, rather than just inserting a space at SecondCharLoc.
811 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
812 ReplacementStr);
813
814 // A hint to put another space after the token, if it would otherwise be
815 // lexed differently.
816 FixItHint Hint2;
817 if ((RemainingToken == tok::greater ||
818 RemainingToken == tok::greatergreater) &&
819 (Next.isOneOf(tok::greater, tok::greatergreater,
820 tok::greatergreatergreater, tok::equal,
821 tok::greaterequal, tok::greatergreaterequal,
822 tok::equalequal)) &&
823 areTokensAdjacent(Tok, Next))
824 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
825
826 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
827 if (getLangOpts().CPlusPlus11 &&
828 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
829 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
830 else if (Tok.is(tok::greaterequal))
831 DiagId = diag::err_right_angle_bracket_equal_needs_space;
832 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
833 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000834
835 // Strip the initial '>' from the token.
Bruno Cardoso Lopes428a5aa2016-01-31 00:47:51 +0000836 Token PrevTok = Tok;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000837 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
838 areTokensAdjacent(Tok, Next)) {
839 // Join two adjacent '=' tokens into one, for cases like:
840 // void (*p)() = f<int>;
841 // return f<int>==p;
842 ConsumeToken();
843 Tok.setKind(tok::equalequal);
844 Tok.setLength(Tok.getLength() + 1);
845 } else {
846 Tok.setKind(RemainingToken);
847 Tok.setLength(Tok.getLength() - 1);
848 }
849 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
850 PP.getSourceManager(),
851 getLangOpts()));
852
Bruno Cardoso Lopes428a5aa2016-01-31 00:47:51 +0000853 // The advance from '>>' to '>' in a ObjectiveC template argument list needs
854 // to be properly reflected in the token cache to allow correct interaction
855 // between annotation and backtracking.
856 if (ObjCGenericList && PrevTok.getKind() == tok::greatergreater &&
857 RemainingToken == tok::greater && PP.IsPreviousCachedToken(PrevTok)) {
858 PrevTok.setKind(RemainingToken);
859 PrevTok.setLength(1);
Bruno Cardoso Lopesfb9b6cd2016-02-05 19:36:39 +0000860 // Break tok::greatergreater into two tok::greater but only add the second
861 // one in case the client asks to consume the last token.
862 if (ConsumeLastToken)
863 PP.ReplacePreviousCachedToken({PrevTok, Tok});
864 else
865 PP.ReplacePreviousCachedToken({PrevTok});
Bruno Cardoso Lopes428a5aa2016-01-31 00:47:51 +0000866 }
867
Faisal Vali6a79ca12013-06-08 19:39:00 +0000868 if (!ConsumeLastToken) {
869 // Since we're not supposed to consume the '>' token, we need to push
870 // this token and revert the current token back to the '>'.
871 PP.EnterToken(Tok);
872 Tok.setKind(tok::greater);
873 Tok.setLength(1);
874 Tok.setLocation(RAngleLoc);
875 }
876 return false;
877}
878
879
880/// \brief Parses a template-id that after the template name has
881/// already been parsed.
882///
883/// This routine takes care of parsing the enclosed template argument
884/// list ('<' template-parameter-list [opt] '>') and placing the
885/// results into a form that can be transferred to semantic analysis.
886///
887/// \param Template the template declaration produced by isTemplateName
888///
889/// \param TemplateNameLoc the source location of the template name
890///
891/// \param SS if non-NULL, the nested-name-specifier preceding the
892/// template name.
893///
894/// \param ConsumeLastToken if true, then we will consume the last
895/// token that forms the template-id. Otherwise, we will leave the
896/// last token in the stream (e.g., so that it can be replaced with an
897/// annotation token).
898bool
899Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
900 SourceLocation TemplateNameLoc,
901 const CXXScopeSpec &SS,
902 bool ConsumeLastToken,
903 SourceLocation &LAngleLoc,
904 TemplateArgList &TemplateArgs,
905 SourceLocation &RAngleLoc) {
906 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
907
908 // Consume the '<'.
909 LAngleLoc = ConsumeToken();
910
911 // Parse the optional template-argument-list.
912 bool Invalid = false;
913 {
914 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
915 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
916 Invalid = ParseTemplateArgumentList(TemplateArgs);
917
918 if (Invalid) {
919 // Try to find the closing '>'.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000920 if (ConsumeLastToken)
921 SkipUntil(tok::greater, StopAtSemi);
922 else
923 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000924 return true;
925 }
926 }
927
Douglas Gregor85f3f952015-07-07 03:57:15 +0000928 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
929 /*ObjCGenericList=*/false);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000930}
931
932/// \brief Replace the tokens that form a simple-template-id with an
933/// annotation token containing the complete template-id.
934///
935/// The first token in the stream must be the name of a template that
936/// is followed by a '<'. This routine will parse the complete
937/// simple-template-id and replace the tokens with a single annotation
938/// token with one of two different kinds: if the template-id names a
939/// type (and \p AllowTypeAnnotation is true), the annotation token is
940/// a type annotation that includes the optional nested-name-specifier
941/// (\p SS). Otherwise, the annotation token is a template-id
942/// annotation that does not include the optional
943/// nested-name-specifier.
944///
945/// \param Template the declaration of the template named by the first
946/// token (an identifier), as returned from \c Action::isTemplateName().
947///
948/// \param TNK the kind of template that \p Template
949/// refers to, as returned from \c Action::isTemplateName().
950///
951/// \param SS if non-NULL, the nested-name-specifier that precedes
952/// this template name.
953///
954/// \param TemplateKWLoc if valid, specifies that this template-id
955/// annotation was preceded by the 'template' keyword and gives the
956/// location of that keyword. If invalid (the default), then this
957/// template-id was not preceded by a 'template' keyword.
958///
959/// \param AllowTypeAnnotation if true (the default), then a
960/// simple-template-id that refers to a class template, template
961/// template parameter, or other template that produces a type will be
962/// replaced with a type annotation token. Otherwise, the
963/// simple-template-id is always replaced with a template-id
964/// annotation token.
965///
966/// If an unrecoverable parse error occurs and no annotation token can be
967/// formed, this function returns true.
968///
969bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
970 CXXScopeSpec &SS,
971 SourceLocation TemplateKWLoc,
972 UnqualifiedId &TemplateName,
973 bool AllowTypeAnnotation) {
974 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
975 assert(Template && Tok.is(tok::less) &&
976 "Parser isn't at the beginning of a template-id");
977
978 // Consume the template-name.
979 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
980
981 // Parse the enclosed template argument list.
982 SourceLocation LAngleLoc, RAngleLoc;
983 TemplateArgList TemplateArgs;
984 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
985 TemplateNameLoc,
986 SS, false, LAngleLoc,
987 TemplateArgs,
988 RAngleLoc);
989
990 if (Invalid) {
991 // If we failed to parse the template ID but skipped ahead to a >, we're not
992 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000993 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000994 return true;
995 }
996
997 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
998
999 // Build the annotation token.
1000 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
1001 TypeResult Type
1002 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
1003 Template, TemplateNameLoc,
1004 LAngleLoc, TemplateArgsPtr, RAngleLoc);
1005 if (Type.isInvalid()) {
1006 // If we failed to parse the template ID but skipped ahead to a >, we're not
1007 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001008 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001009 return true;
1010 }
1011
1012 Tok.setKind(tok::annot_typename);
1013 setTypeAnnotation(Tok, Type.get());
1014 if (SS.isNotEmpty())
1015 Tok.setLocation(SS.getBeginLoc());
1016 else if (TemplateKWLoc.isValid())
1017 Tok.setLocation(TemplateKWLoc);
1018 else
1019 Tok.setLocation(TemplateNameLoc);
1020 } else {
1021 // Build a template-id annotation token that can be processed
1022 // later.
1023 Tok.setKind(tok::annot_template_id);
1024 TemplateIdAnnotation *TemplateId
1025 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
1026 TemplateId->TemplateNameLoc = TemplateNameLoc;
1027 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
1028 TemplateId->Name = TemplateName.Identifier;
1029 TemplateId->Operator = OO_None;
1030 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001031 TemplateId->Name = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001032 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
1033 }
1034 TemplateId->SS = SS;
1035 TemplateId->TemplateKWLoc = TemplateKWLoc;
1036 TemplateId->Template = Template;
1037 TemplateId->Kind = TNK;
1038 TemplateId->LAngleLoc = LAngleLoc;
1039 TemplateId->RAngleLoc = RAngleLoc;
1040 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1041 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
1042 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
1043 Tok.setAnnotationValue(TemplateId);
1044 if (TemplateKWLoc.isValid())
1045 Tok.setLocation(TemplateKWLoc);
1046 else
1047 Tok.setLocation(TemplateNameLoc);
1048 }
1049
1050 // Common fields for the annotation token
1051 Tok.setAnnotationEndLoc(RAngleLoc);
1052
1053 // In case the tokens were cached, have Preprocessor replace them with the
1054 // annotation token.
1055 PP.AnnotateCachedTokens(Tok);
1056 return false;
1057}
1058
1059/// \brief Replaces a template-id annotation token with a type
1060/// annotation token.
1061///
1062/// If there was a failure when forming the type from the template-id,
1063/// a type annotation token will still be created, but will have a
1064/// NULL type pointer to signify an error.
1065void Parser::AnnotateTemplateIdTokenAsType() {
1066 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1067
1068 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1069 assert((TemplateId->Kind == TNK_Type_template ||
1070 TemplateId->Kind == TNK_Dependent_template_name) &&
1071 "Only works for type and dependent templates");
1072
1073 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1074 TemplateId->NumArgs);
1075
1076 TypeResult Type
1077 = Actions.ActOnTemplateIdType(TemplateId->SS,
1078 TemplateId->TemplateKWLoc,
1079 TemplateId->Template,
1080 TemplateId->TemplateNameLoc,
1081 TemplateId->LAngleLoc,
1082 TemplateArgsPtr,
1083 TemplateId->RAngleLoc);
1084 // Create the new "type" annotation token.
1085 Tok.setKind(tok::annot_typename);
David Blaikieefdccaa2016-01-15 23:43:34 +00001086 setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001087 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1088 Tok.setLocation(TemplateId->SS.getBeginLoc());
1089 // End location stays the same
1090
1091 // Replace the template-id annotation token, and possible the scope-specifier
1092 // that precedes it, with the typename annotation token.
1093 PP.AnnotateCachedTokens(Tok);
1094}
1095
1096/// \brief Determine whether the given token can end a template argument.
1097static bool isEndOfTemplateArgument(Token Tok) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001098 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001099}
1100
1101/// \brief Parse a C++ template template argument.
1102ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1103 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1104 !Tok.is(tok::annot_cxxscope))
1105 return ParsedTemplateArgument();
1106
1107 // C++0x [temp.arg.template]p1:
1108 // A template-argument for a template template-parameter shall be the name
1109 // of a class template or an alias template, expressed as id-expression.
1110 //
1111 // We parse an id-expression that refers to a class template or alias
1112 // template. The grammar we parse is:
1113 //
1114 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1115 //
1116 // followed by a token that terminates a template argument, such as ',',
1117 // '>', or (in some cases) '>>'.
1118 CXXScopeSpec SS; // nested-name-specifier, if present
David Blaikieefdccaa2016-01-15 23:43:34 +00001119 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001120 /*EnteringContext=*/false);
David Blaikieefdccaa2016-01-15 23:43:34 +00001121
Faisal Vali6a79ca12013-06-08 19:39:00 +00001122 ParsedTemplateArgument Result;
1123 SourceLocation EllipsisLoc;
1124 if (SS.isSet() && Tok.is(tok::kw_template)) {
1125 // Parse the optional 'template' keyword following the
1126 // nested-name-specifier.
1127 SourceLocation TemplateKWLoc = ConsumeToken();
1128
1129 if (Tok.is(tok::identifier)) {
1130 // We appear to have a dependent template name.
1131 UnqualifiedId Name;
1132 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1133 ConsumeToken(); // the identifier
Alp Toker094e5212014-01-05 03:27:11 +00001134
1135 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1136
Faisal Vali6a79ca12013-06-08 19:39:00 +00001137 // If the next token signals the end of a template argument,
1138 // then we have a dependent template name that could be a template
1139 // template argument.
1140 TemplateTy Template;
1141 if (isEndOfTemplateArgument(Tok) &&
David Blaikieefdccaa2016-01-15 23:43:34 +00001142 Actions.ActOnDependentTemplateName(
1143 getCurScope(), SS, TemplateKWLoc, Name,
1144 /*ObjectType=*/nullptr,
1145 /*EnteringContext=*/false, Template))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001146 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1147 }
1148 } else if (Tok.is(tok::identifier)) {
1149 // We may have a (non-dependent) template name.
1150 TemplateTy Template;
1151 UnqualifiedId Name;
1152 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1153 ConsumeToken(); // the identifier
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001154
1155 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001156
1157 if (isEndOfTemplateArgument(Tok)) {
1158 bool MemberOfUnknownSpecialization;
David Blaikieefdccaa2016-01-15 23:43:34 +00001159 TemplateNameKind TNK = Actions.isTemplateName(
1160 getCurScope(), SS,
1161 /*hasTemplateKeyword=*/false, Name,
1162 /*ObjectType=*/nullptr,
1163 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001164 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1165 // We have an id-expression that refers to a class template or
1166 // (C++0x) alias template.
1167 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1168 }
1169 }
1170 }
1171
1172 // If this is a pack expansion, build it as such.
1173 if (EllipsisLoc.isValid() && !Result.isInvalid())
1174 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1175
1176 return Result;
1177}
1178
1179/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1180///
1181/// template-argument: [C++ 14.2]
1182/// constant-expression
1183/// type-id
1184/// id-expression
1185ParsedTemplateArgument Parser::ParseTemplateArgument() {
1186 // C++ [temp.arg]p2:
1187 // In a template-argument, an ambiguity between a type-id and an
1188 // expression is resolved to a type-id, regardless of the form of
1189 // the corresponding template-parameter.
1190 //
1191 // Therefore, we initially try to parse a type-id.
1192 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1193 SourceLocation Loc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00001194 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001195 Declarator::TemplateTypeArgContext);
1196 if (TypeArg.isInvalid())
1197 return ParsedTemplateArgument();
1198
1199 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1200 TypeArg.get().getAsOpaquePtr(),
1201 Loc);
1202 }
1203
1204 // Try to parse a template template argument.
1205 {
1206 TentativeParsingAction TPA(*this);
1207
1208 ParsedTemplateArgument TemplateTemplateArgument
1209 = ParseTemplateTemplateArgument();
1210 if (!TemplateTemplateArgument.isInvalid()) {
1211 TPA.Commit();
1212 return TemplateTemplateArgument;
1213 }
1214
1215 // Revert this tentative parse to parse a non-type template argument.
1216 TPA.Revert();
1217 }
1218
1219 // Parse a non-type template argument.
1220 SourceLocation Loc = Tok.getLocation();
1221 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1222 if (ExprArg.isInvalid() || !ExprArg.get())
1223 return ParsedTemplateArgument();
1224
1225 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001226 ExprArg.get(), Loc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001227}
1228
1229/// \brief Determine whether the current tokens can only be parsed as a
1230/// template argument list (starting with the '<') and never as a '<'
1231/// expression.
1232bool Parser::IsTemplateArgumentList(unsigned Skip) {
1233 struct AlwaysRevertAction : TentativeParsingAction {
1234 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1235 ~AlwaysRevertAction() { Revert(); }
1236 } Tentative(*this);
1237
1238 while (Skip) {
1239 ConsumeToken();
1240 --Skip;
1241 }
1242
1243 // '<'
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001244 if (!TryConsumeToken(tok::less))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001245 return false;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001246
1247 // An empty template argument list.
1248 if (Tok.is(tok::greater))
1249 return true;
1250
1251 // See whether we have declaration specifiers, which indicate a type.
Richard Smithee390432014-05-16 01:56:53 +00001252 while (isCXXDeclarationSpecifier() == TPResult::True)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001253 ConsumeToken();
1254
1255 // If we have a '>' or a ',' then this is a template argument list.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001256 return Tok.isOneOf(tok::greater, tok::comma);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001257}
1258
1259/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1260/// (C++ [temp.names]). Returns true if there was an error.
1261///
1262/// template-argument-list: [C++ 14.2]
1263/// template-argument
1264/// template-argument-list ',' template-argument
1265bool
1266Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1267 // Template argument lists are constant-evaluation contexts.
1268 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +00001269 ColonProtectionRAIIObject ColonProtection(*this, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001270
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001271 do {
Faisal Vali6a79ca12013-06-08 19:39:00 +00001272 ParsedTemplateArgument Arg = ParseTemplateArgument();
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001273 SourceLocation EllipsisLoc;
1274 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001275 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001276
1277 if (Arg.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001278 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001279 return true;
1280 }
1281
1282 // Save this template argument.
1283 TemplateArgs.push_back(Arg);
1284
1285 // If the next token is a comma, consume it and keep reading
1286 // arguments.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001287 } while (TryConsumeToken(tok::comma));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001288
1289 return false;
1290}
1291
1292/// \brief Parse a C++ explicit template instantiation
1293/// (C++ [temp.explicit]).
1294///
1295/// explicit-instantiation:
1296/// 'extern' [opt] 'template' declaration
1297///
1298/// Note that the 'extern' is a GNU extension and C++11 feature.
1299Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1300 SourceLocation ExternLoc,
1301 SourceLocation TemplateLoc,
1302 SourceLocation &DeclEnd,
1303 AccessSpecifier AS) {
1304 // This isn't really required here.
1305 ParsingDeclRAIIObject
1306 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1307
1308 return ParseSingleDeclarationAfterTemplate(Context,
1309 ParsedTemplateInfo(ExternLoc,
1310 TemplateLoc),
1311 ParsingTemplateParams,
1312 DeclEnd, AS);
1313}
1314
1315SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1316 if (TemplateParams)
1317 return getTemplateParamsRange(TemplateParams->data(),
1318 TemplateParams->size());
1319
1320 SourceRange R(TemplateLoc);
1321 if (ExternLoc.isValid())
1322 R.setBegin(ExternLoc);
1323 return R;
1324}
1325
Richard Smithe40f2ba2013-08-07 21:41:30 +00001326void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1327 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001328}
1329
1330/// \brief Late parse a C++ function template in Microsoft mode.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001331void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
David Majnemerf0a84f22013-08-16 08:29:13 +00001332 if (!LPT.D)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001333 return;
1334
1335 // Get the FunctionDecl.
Alp Tokera2794f92014-01-22 07:29:52 +00001336 FunctionDecl *FunD = LPT.D->getAsFunction();
Faisal Vali6a79ca12013-06-08 19:39:00 +00001337 // Track template parameter depth.
1338 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1339
1340 // To restore the context after late parsing.
Richard Smithb0b68012015-05-11 23:09:06 +00001341 Sema::ContextRAII GlobalSavedContext(
1342 Actions, Actions.Context.getTranslationUnitDecl());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001343
1344 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1345
1346 // Get the list of DeclContexts to reenter.
1347 SmallVector<DeclContext*, 4> DeclContextsToReenter;
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001348 DeclContext *DD = FunD;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001349 while (DD && !DD->isTranslationUnit()) {
1350 DeclContextsToReenter.push_back(DD);
1351 DD = DD->getLexicalParent();
1352 }
1353
1354 // Reenter template scopes from outermost to innermost.
Craig Topper61ac9062013-07-08 03:55:09 +00001355 SmallVectorImpl<DeclContext *>::reverse_iterator II =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001356 DeclContextsToReenter.rbegin();
1357 for (; II != DeclContextsToReenter.rend(); ++II) {
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001358 TemplateParamScopeStack.push_back(new ParseScope(this,
1359 Scope::TemplateParamScope));
1360 unsigned NumParamLists =
1361 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1362 CurTemplateDepthTracker.addDepth(NumParamLists);
1363 if (*II != FunD) {
1364 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1365 Actions.PushDeclContext(Actions.getCurScope(), *II);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001366 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001367 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001368
Richard Smithe40f2ba2013-08-07 21:41:30 +00001369 assert(!LPT.Toks.empty() && "Empty body!");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001370
1371 // Append the current token at the end of the new token stream so that it
1372 // doesn't get lost.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001373 LPT.Toks.push_back(Tok);
David Blaikie2eabcc92016-02-09 18:52:09 +00001374 PP.EnterTokenStream(LPT.Toks, true);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001375
1376 // Consume the previously pushed token.
1377 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001378 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1379 "Inline method not starting with '{', ':' or 'try'");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001380
1381 // Parse the method body. Function body parsing code is similar enough
1382 // to be re-used for method bodies as well.
1383 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1384
1385 // Recreate the containing function DeclContext.
Nico Weber55048cf2014-08-15 22:15:00 +00001386 Sema::ContextRAII FunctionSavedContext(Actions,
1387 Actions.getContainingDC(FunD));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001388
1389 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1390
1391 if (Tok.is(tok::kw_try)) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00001392 ParseFunctionTryBlock(LPT.D, FnScope);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001393 } else {
1394 if (Tok.is(tok::colon))
Richard Smithe40f2ba2013-08-07 21:41:30 +00001395 ParseConstructorInitializer(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001396 else
Richard Smithe40f2ba2013-08-07 21:41:30 +00001397 Actions.ActOnDefaultCtorInitializers(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001398
1399 if (Tok.is(tok::l_brace)) {
Alp Tokera2794f92014-01-22 07:29:52 +00001400 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1401 cast<FunctionTemplateDecl>(LPT.D)
1402 ->getTemplateParameters()
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001403 ->getDepth() == TemplateParameterDepth - 1) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +00001404 "TemplateParameterDepth should be greater than the depth of "
1405 "current template being instantiated!");
Richard Smithe40f2ba2013-08-07 21:41:30 +00001406 ParseFunctionStatementBody(LPT.D, FnScope);
1407 Actions.UnmarkAsLateParsedTemplate(FunD);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001408 } else
Craig Topper161e4db2014-05-21 06:02:52 +00001409 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001410 }
1411
1412 // Exit scopes.
1413 FnScope.Exit();
Craig Topper61ac9062013-07-08 03:55:09 +00001414 SmallVectorImpl<ParseScope *>::reverse_iterator I =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001415 TemplateParamScopeStack.rbegin();
1416 for (; I != TemplateParamScopeStack.rend(); ++I)
1417 delete *I;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001418}
1419
1420/// \brief Lex a delayed template function for late parsing.
1421void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1422 tok::TokenKind kind = Tok.getKind();
1423 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1424 // Consume everything up to (and including) the matching right brace.
1425 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1426 }
1427
1428 // If we're in a function-try-block, we need to store all the catch blocks.
1429 if (kind == tok::kw_try) {
1430 while (Tok.is(tok::kw_catch)) {
1431 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1432 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1433 }
1434 }
1435}