blob: 61da159ae02179d5600984d5b32d884435e6dd11 [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
Akira Hatanaka10aced82016-04-29 02:24:14 +0000150 unsigned NewFlags = getCurScope()->getFlags() & ~Scope::TemplateParamScope;
151 ParseScopeFlags TemplateScopeFlags(this, NewFlags, isSpecialization);
152
Faisal Vali6a79ca12013-06-08 19:39:00 +0000153 // Parse the actual template declaration.
154 return ParseSingleDeclarationAfterTemplate(Context,
155 ParsedTemplateInfo(&ParamLists,
156 isSpecialization,
157 LastParamListWasEmpty),
158 ParsingTemplateParams,
159 DeclEnd, AS, AccessAttrs);
160}
161
162/// \brief Parse a single declaration that declares a template,
163/// template specialization, or explicit instantiation of a template.
164///
165/// \param DeclEnd will receive the source location of the last token
166/// within this declaration.
167///
168/// \param AS the access specifier associated with this
169/// declaration. Will be AS_none for namespace-scope declarations.
170///
171/// \returns the new declaration.
172Decl *
173Parser::ParseSingleDeclarationAfterTemplate(
174 unsigned Context,
175 const ParsedTemplateInfo &TemplateInfo,
176 ParsingDeclRAIIObject &DiagsFromTParams,
177 SourceLocation &DeclEnd,
178 AccessSpecifier AS,
179 AttributeList *AccessAttrs) {
180 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
181 "Template information required");
182
Aaron Ballmane7c544d2014-08-04 20:28:35 +0000183 if (Tok.is(tok::kw_static_assert)) {
184 // A static_assert declaration may not be templated.
185 Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
186 << TemplateInfo.getSourceRange();
187 // Parse the static_assert declaration to improve error recovery.
188 return ParseStaticAssertDeclaration(DeclEnd);
189 }
190
Faisal Vali6a79ca12013-06-08 19:39:00 +0000191 if (Context == Declarator::MemberContext) {
192 // We are parsing a member template.
193 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
194 &DiagsFromTParams);
Craig Topper161e4db2014-05-21 06:02:52 +0000195 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000196 }
197
198 ParsedAttributesWithRange prefixAttrs(AttrFactory);
199 MaybeParseCXX11Attributes(prefixAttrs);
200
201 if (Tok.is(tok::kw_using))
202 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
203 prefixAttrs);
204
205 // Parse the declaration specifiers, stealing any diagnostics from
206 // the template parameters.
207 ParsingDeclSpec DS(*this, &DiagsFromTParams);
208
209 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
210 getDeclSpecContextFromDeclaratorContext(Context));
211
212 if (Tok.is(tok::semi)) {
213 ProhibitAttributes(prefixAttrs);
214 DeclEnd = ConsumeToken();
Nico Weber7b837f52016-01-28 19:25:00 +0000215 RecordDecl *AnonRecord = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000216 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
217 getCurScope(), AS, DS,
218 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
219 : MultiTemplateParamsArg(),
Nico Weber7b837f52016-01-28 19:25:00 +0000220 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation,
221 AnonRecord);
222 assert(!AnonRecord &&
223 "Anonymous unions/structs should not be valid with template");
Faisal Vali6a79ca12013-06-08 19:39:00 +0000224 DS.complete(Decl);
225 return Decl;
226 }
227
228 // Move the attributes from the prefix into the DS.
229 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
230 ProhibitAttributes(prefixAttrs);
231 else
232 DS.takeAttributesFrom(prefixAttrs);
233
234 // Parse the declarator.
235 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
236 ParseDeclarator(DeclaratorInfo);
237 // Error parsing the declarator?
238 if (!DeclaratorInfo.hasName()) {
239 // If so, skip until the semi-colon or a }.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000240 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000241 if (Tok.is(tok::semi))
242 ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000243 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000244 }
245
246 LateParsedAttrList LateParsedAttrs(true);
247 if (DeclaratorInfo.isFunctionDeclarator())
248 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
249
250 if (DeclaratorInfo.isFunctionDeclarator() &&
251 isStartOfFunctionDefinition(DeclaratorInfo)) {
Reid Klecknerd61a3112014-12-15 23:16:32 +0000252
253 // Function definitions are only allowed at file scope and in C++ classes.
254 // The C++ inline method definition case is handled elsewhere, so we only
255 // need to handle the file scope definition case.
256 if (Context != Declarator::FileContext) {
257 Diag(Tok, diag::err_function_definition_not_allowed);
258 SkipMalformedDecl();
259 return nullptr;
260 }
261
Faisal Vali6a79ca12013-06-08 19:39:00 +0000262 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
263 // Recover by ignoring the 'typedef'. This was probably supposed to be
264 // the 'typename' keyword, which we should have already suggested adding
265 // if it's appropriate.
266 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
267 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
268 DS.ClearStorageClassSpecs();
269 }
Larisse Voufo725de3e2013-06-21 00:08:46 +0000270
271 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
272 if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
273 // If the declarator-id is not a template-id, issue a diagnostic and
274 // recover by ignoring the 'template' keyword.
275 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000276 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
277 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000278 } else {
279 SourceLocation LAngleLoc
280 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000281 Diag(DeclaratorInfo.getIdentifierLoc(),
Larisse Voufo725de3e2013-06-21 00:08:46 +0000282 diag::err_explicit_instantiation_with_definition)
Larisse Voufo39a1e502013-08-06 01:03:05 +0000283 << SourceRange(TemplateInfo.TemplateLoc)
284 << FixItHint::CreateInsertion(LAngleLoc, "<>");
Larisse Voufo725de3e2013-06-21 00:08:46 +0000285
Larisse Voufo39a1e502013-08-06 01:03:05 +0000286 // Recover as if it were an explicit specialization.
Larisse Voufob9bbaba2013-06-22 13:56:11 +0000287 TemplateParameterLists FakedParamLists;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000288 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper96225a52015-12-24 23:58:25 +0000289 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, None,
290 LAngleLoc));
Larisse Voufo725de3e2013-06-21 00:08:46 +0000291
Larisse Voufo39a1e502013-08-06 01:03:05 +0000292 return ParseFunctionDefinition(
293 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
294 /*isSpecialization=*/true,
295 /*LastParamListWasEmpty=*/true),
296 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000297 }
298 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000299 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
Larisse Voufo39a1e502013-08-06 01:03:05 +0000300 &LateParsedAttrs);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000301 }
302
303 // Parse this declaration.
304 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
305 TemplateInfo);
306
307 if (Tok.is(tok::comma)) {
308 Diag(Tok, diag::err_multiple_template_declarators)
309 << (int)TemplateInfo.Kind;
Alexey Bataevee6507d2013-11-18 08:17:37 +0000310 SkipUntil(tok::semi);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000311 return ThisDecl;
312 }
313
314 // Eat the semi colon after the declaration.
315 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
316 if (LateParsedAttrs.size() > 0)
317 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
318 DeclaratorInfo.complete(ThisDecl);
319 return ThisDecl;
320}
321
322/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
323/// angle brackets. Depth is the depth of this template-parameter-list, which
324/// is the number of template headers directly enclosing this template header.
325/// TemplateParams is the current list of template parameters we're building.
326/// The template parameter we parse will be added to this list. LAngleLoc and
327/// RAngleLoc will receive the positions of the '<' and '>', respectively,
328/// that enclose this template parameter list.
329///
330/// \returns true if an error occurred, false otherwise.
331bool Parser::ParseTemplateParameters(unsigned Depth,
332 SmallVectorImpl<Decl*> &TemplateParams,
333 SourceLocation &LAngleLoc,
334 SourceLocation &RAngleLoc) {
335 // Get the template parameter list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000336 if (!TryConsumeToken(tok::less, LAngleLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000337 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
338 return true;
339 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000340
341 // Try to parse the template parameter list.
342 bool Failed = false;
343 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
344 Failed = ParseTemplateParameterList(Depth, TemplateParams);
345
346 if (Tok.is(tok::greatergreater)) {
347 // No diagnostic required here: a template-parameter-list can only be
348 // followed by a declaration or, for a template template parameter, the
349 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
350 // This matters for elegant diagnosis of:
351 // template<template<typename>> struct S;
352 Tok.setKind(tok::greater);
353 RAngleLoc = Tok.getLocation();
354 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
Alp Toker383d2c42014-01-01 03:08:43 +0000355 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
356 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000357 return true;
358 }
359 return false;
360}
361
362/// ParseTemplateParameterList - Parse a template parameter list. If
363/// the parsing fails badly (i.e., closing bracket was left out), this
364/// will try to put the token stream in a reasonable position (closing
365/// a statement, etc.) and return false.
366///
367/// template-parameter-list: [C++ temp]
368/// template-parameter
369/// template-parameter-list ',' template-parameter
370bool
371Parser::ParseTemplateParameterList(unsigned Depth,
372 SmallVectorImpl<Decl*> &TemplateParams) {
373 while (1) {
374 if (Decl *TmpParam
375 = ParseTemplateParameter(Depth, TemplateParams.size())) {
376 TemplateParams.push_back(TmpParam);
377 } else {
378 // If we failed to parse a template parameter, skip until we find
379 // a comma or closing brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000380 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
381 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000382 }
383
384 // Did we find a comma or the end of the template parameter list?
385 if (Tok.is(tok::comma)) {
386 ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000387 } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000388 // Don't consume this... that's done by template parser.
389 break;
390 } else {
391 // Somebody probably forgot to close the template. Skip ahead and
392 // try to get out of the expression. This error is currently
393 // subsumed by whatever goes on in ParseTemplateParameter.
394 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000395 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
396 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000397 return false;
398 }
399 }
400 return true;
401}
402
403/// \brief Determine whether the parser is at the start of a template
404/// type parameter.
405bool Parser::isStartOfTemplateTypeParameter() {
406 if (Tok.is(tok::kw_class)) {
407 // "class" may be the start of an elaborated-type-specifier or a
408 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
409 switch (NextToken().getKind()) {
410 case tok::equal:
411 case tok::comma:
412 case tok::greater:
413 case tok::greatergreater:
414 case tok::ellipsis:
415 return true;
416
417 case tok::identifier:
418 // This may be either a type-parameter or an elaborated-type-specifier.
419 // We have to look further.
420 break;
421
422 default:
423 return false;
424 }
425
426 switch (GetLookAheadToken(2).getKind()) {
427 case tok::equal:
428 case tok::comma:
429 case tok::greater:
430 case tok::greatergreater:
431 return true;
432
433 default:
434 return false;
435 }
436 }
437
438 if (Tok.isNot(tok::kw_typename))
439 return false;
440
441 // C++ [temp.param]p2:
442 // There is no semantic difference between class and typename in a
443 // template-parameter. typename followed by an unqualified-id
444 // names a template type parameter. typename followed by a
445 // qualified-id denotes the type in a non-type
446 // parameter-declaration.
447 Token Next = NextToken();
448
449 // If we have an identifier, skip over it.
450 if (Next.getKind() == tok::identifier)
451 Next = GetLookAheadToken(2);
452
453 switch (Next.getKind()) {
454 case tok::equal:
455 case tok::comma:
456 case tok::greater:
457 case tok::greatergreater:
458 case tok::ellipsis:
459 return true;
460
461 default:
462 return false;
463 }
464}
465
466/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
467///
468/// template-parameter: [C++ temp.param]
469/// type-parameter
470/// parameter-declaration
471///
472/// type-parameter: (see below)
473/// 'class' ...[opt] identifier[opt]
474/// 'class' identifier[opt] '=' type-id
475/// 'typename' ...[opt] identifier[opt]
476/// 'typename' identifier[opt] '=' type-id
477/// 'template' '<' template-parameter-list '>'
478/// 'class' ...[opt] identifier[opt]
479/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
480/// = id-expression
481Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
482 if (isStartOfTemplateTypeParameter())
483 return ParseTypeParameter(Depth, Position);
484
485 if (Tok.is(tok::kw_template))
486 return ParseTemplateTemplateParameter(Depth, Position);
487
488 // If it's none of the above, then it must be a parameter declaration.
489 // NOTE: This will pick up errors in the closure of the template parameter
490 // list (e.g., template < ; Check here to implement >> style closures.
491 return ParseNonTypeTemplateParameter(Depth, Position);
492}
493
494/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
495/// Other kinds of template parameters are parsed in
496/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
497///
498/// type-parameter: [C++ temp.param]
499/// 'class' ...[opt][C++0x] identifier[opt]
500/// 'class' identifier[opt] '=' type-id
501/// 'typename' ...[opt][C++0x] identifier[opt]
502/// 'typename' identifier[opt] '=' type-id
503Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000504 assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +0000505 "A type-parameter starts with 'class' or 'typename'");
506
507 // Consume the 'class' or 'typename' keyword.
508 bool TypenameKeyword = Tok.is(tok::kw_typename);
509 SourceLocation KeyLoc = ConsumeToken();
510
511 // Grab the ellipsis (if given).
Faisal Vali6a79ca12013-06-08 19:39:00 +0000512 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000513 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000514 Diag(EllipsisLoc,
515 getLangOpts().CPlusPlus11
516 ? diag::warn_cxx98_compat_variadic_templates
517 : diag::ext_variadic_templates);
518 }
519
520 // Grab the template parameter name (if given)
521 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000522 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000523 if (Tok.is(tok::identifier)) {
524 ParamName = Tok.getIdentifierInfo();
525 NameLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000526 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
527 tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000528 // Unnamed template parameter. Don't have to do anything here, just
529 // don't consume this token.
530 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000531 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000532 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000533 }
534
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000535 // Recover from misplaced ellipsis.
536 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
537 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
538 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
539
Faisal Vali6a79ca12013-06-08 19:39:00 +0000540 // Grab a default argument (if available).
541 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
542 // we introduce the type parameter into the local scope.
543 SourceLocation EqualLoc;
544 ParsedType DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000545 if (TryConsumeToken(tok::equal, EqualLoc))
Craig Topper161e4db2014-05-21 06:02:52 +0000546 DefaultArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000547 Declarator::TemplateTypeArgContext).get();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000548
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000549 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
550 KeyLoc, ParamName, NameLoc, Depth, Position,
551 EqualLoc, DefaultArg);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000552}
553
554/// ParseTemplateTemplateParameter - Handle the parsing of template
555/// template parameters.
556///
557/// type-parameter: [C++ temp.param]
Richard Smith78e1ca62014-06-16 15:51:22 +0000558/// 'template' '<' template-parameter-list '>' type-parameter-key
Faisal Vali6a79ca12013-06-08 19:39:00 +0000559/// ...[opt] identifier[opt]
Richard Smith78e1ca62014-06-16 15:51:22 +0000560/// 'template' '<' template-parameter-list '>' type-parameter-key
561/// identifier[opt] = id-expression
562/// type-parameter-key:
563/// 'class'
564/// 'typename' [C++1z]
Faisal Vali6a79ca12013-06-08 19:39:00 +0000565Decl *
566Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
567 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
568
569 // Handle the template <...> part.
570 SourceLocation TemplateLoc = ConsumeToken();
571 SmallVector<Decl*,8> TemplateParams;
572 SourceLocation LAngleLoc, RAngleLoc;
573 {
574 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
575 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
576 RAngleLoc)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000577 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000578 }
579 }
580
Richard Smith78e1ca62014-06-16 15:51:22 +0000581 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000582 // Generate a meaningful error if the user forgot to put class before the
583 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
Richard Smith78e1ca62014-06-16 15:51:22 +0000584 // or greater appear immediately or after 'struct'. In the latter case,
585 // replace the keyword with 'class'.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000586 if (!TryConsumeToken(tok::kw_class)) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000587 bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct);
Richard Smith78e1ca62014-06-16 15:51:22 +0000588 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
589 if (Tok.is(tok::kw_typename)) {
590 Diag(Tok.getLocation(),
591 getLangOpts().CPlusPlus1z
Aaron Ballmandd69ef32014-08-19 15:55:55 +0000592 ? diag::warn_cxx14_compat_template_template_param_typename
Richard Smith78e1ca62014-06-16 15:51:22 +0000593 : diag::ext_template_template_param_typename)
594 << (!getLangOpts().CPlusPlus1z
595 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
596 : FixItHint());
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000597 } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater,
598 tok::greatergreater, tok::ellipsis)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000599 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
600 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
601 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
Richard Smith78e1ca62014-06-16 15:51:22 +0000602 } else
Faisal Vali6a79ca12013-06-08 19:39:00 +0000603 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
604
605 if (Replace)
606 ConsumeToken();
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000607 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000608
609 // Parse the ellipsis, if given.
610 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000611 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000612 Diag(EllipsisLoc,
613 getLangOpts().CPlusPlus11
614 ? diag::warn_cxx98_compat_variadic_templates
615 : diag::ext_variadic_templates);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000616
617 // Get the identifier, if given.
618 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000619 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000620 if (Tok.is(tok::identifier)) {
621 ParamName = Tok.getIdentifierInfo();
622 NameLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000623 } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater,
624 tok::greatergreater)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000625 // Unnamed template parameter. Don't have to do anything here, just
626 // don't consume this token.
627 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000628 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000629 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000630 }
631
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000632 // Recover from misplaced ellipsis.
633 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
634 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
635 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
636
Faisal Vali6a79ca12013-06-08 19:39:00 +0000637 TemplateParameterList *ParamList =
638 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
639 TemplateLoc, LAngleLoc,
Craig Topper96225a52015-12-24 23:58:25 +0000640 TemplateParams,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000641 RAngleLoc);
642
643 // Grab a default argument (if available).
644 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
645 // we introduce the template parameter into the local scope.
646 SourceLocation EqualLoc;
647 ParsedTemplateArgument DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000648 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000649 DefaultArg = ParseTemplateTemplateArgument();
650 if (DefaultArg.isInvalid()) {
651 Diag(Tok.getLocation(),
652 diag::err_default_template_template_parameter_not_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000653 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
654 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000655 }
656 }
657
658 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
659 ParamList, EllipsisLoc,
660 ParamName, NameLoc, Depth,
661 Position, EqualLoc, DefaultArg);
662}
663
664/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
665/// template parameters (e.g., in "template<int Size> class array;").
666///
667/// template-parameter:
668/// ...
669/// parameter-declaration
670Decl *
671Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
672 // Parse the declaration-specifiers (i.e., the type).
673 // FIXME: The type should probably be restricted in some way... Not all
674 // declarators (parts of declarators?) are accepted for parameters.
675 DeclSpec DS(AttrFactory);
676 ParseDeclarationSpecifiers(DS);
677
678 // Parse this as a typename.
679 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
680 ParseDeclarator(ParamDecl);
681 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
682 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
Craig Topper161e4db2014-05-21 06:02:52 +0000683 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000684 }
685
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000686 // Recover from misplaced ellipsis.
687 SourceLocation EllipsisLoc;
688 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
689 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
690
Faisal Vali6a79ca12013-06-08 19:39:00 +0000691 // If there is a default value, parse it.
692 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
693 // we introduce the template parameter into the local scope.
694 SourceLocation EqualLoc;
695 ExprResult DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000696 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000697 // C++ [temp.param]p15:
698 // When parsing a default template-argument for a non-type
699 // template-parameter, the first non-nested > is taken as the
700 // end of the template-parameter-list rather than a greater-than
701 // operator.
702 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Faisal Vali48401eb2015-11-19 19:20:17 +0000703 EnterExpressionEvaluationContext ConstantEvaluated(Actions,
704 Sema::ConstantEvaluated);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000705
Kaelyn Takata999dd852014-12-02 23:32:20 +0000706 DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000707 if (DefaultArg.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +0000708 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000709 }
710
711 // Create the parameter.
712 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
713 Depth, Position, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000714 DefaultArg.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000715}
716
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000717void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
718 SourceLocation CorrectLoc,
719 bool AlreadyHasEllipsis,
720 bool IdentifierHasName) {
721 FixItHint Insertion;
722 if (!AlreadyHasEllipsis)
723 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
724 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
725 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
726 << !IdentifierHasName;
727}
728
729void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
730 Declarator &D) {
731 assert(EllipsisLoc.isValid());
732 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
733 if (!AlreadyHasEllipsis)
734 D.setEllipsisLoc(EllipsisLoc);
735 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
736 AlreadyHasEllipsis, D.hasName());
737}
738
Faisal Vali6a79ca12013-06-08 19:39:00 +0000739/// \brief Parses a '>' at the end of a template list.
740///
741/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
742/// to determine if these tokens were supposed to be a '>' followed by
743/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
744///
745/// \param RAngleLoc the location of the consumed '>'.
746///
Douglas Gregor85f3f952015-07-07 03:57:15 +0000747/// \param ConsumeLastToken if true, the '>' is consumed.
748///
749/// \param ObjCGenericList if true, this is the '>' closing an Objective-C
750/// type parameter or type argument list, rather than a C++ template parameter
751/// or argument list.
Serge Pavlovb716b3c2013-08-10 05:54:47 +0000752///
753/// \returns true, if current token does not start with '>', false otherwise.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000754bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000755 bool ConsumeLastToken,
756 bool ObjCGenericList) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000757 // What will be left once we've consumed the '>'.
758 tok::TokenKind RemainingToken;
759 const char *ReplacementStr = "> >";
760
761 switch (Tok.getKind()) {
762 default:
Alp Toker383d2c42014-01-01 03:08:43 +0000763 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000764 return true;
765
766 case tok::greater:
767 // Determine the location of the '>' token. Only consume this token
768 // if the caller asked us to.
769 RAngleLoc = Tok.getLocation();
770 if (ConsumeLastToken)
771 ConsumeToken();
772 return false;
773
774 case tok::greatergreater:
775 RemainingToken = tok::greater;
776 break;
777
778 case tok::greatergreatergreater:
779 RemainingToken = tok::greatergreater;
780 break;
781
782 case tok::greaterequal:
783 RemainingToken = tok::equal;
784 ReplacementStr = "> =";
785 break;
786
787 case tok::greatergreaterequal:
788 RemainingToken = tok::greaterequal;
789 break;
790 }
791
792 // This template-id is terminated by a token which starts with a '>'. Outside
793 // C++11, this is now error recovery, and in C++11, this is error recovery if
Eli Bendersky36a61932014-06-20 13:09:59 +0000794 // the token isn't '>>' or '>>>'.
795 // '>>>' is for CUDA, where this sequence of characters is parsed into
796 // tok::greatergreatergreater, rather than two separate tokens.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000797 //
798 // We always allow this for Objective-C type parameter and type argument
799 // lists.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000800 RAngleLoc = Tok.getLocation();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000801 Token Next = NextToken();
Douglas Gregor85f3f952015-07-07 03:57:15 +0000802 if (!ObjCGenericList) {
803 // The source range of the '>>' or '>=' at the start of the token.
804 CharSourceRange ReplacementRange =
805 CharSourceRange::getCharRange(RAngleLoc,
806 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
807 getLangOpts()));
Faisal Vali6a79ca12013-06-08 19:39:00 +0000808
Douglas Gregor85f3f952015-07-07 03:57:15 +0000809 // A hint to put a space between the '>>'s. In order to make the hint as
810 // clear as possible, we include the characters either side of the space in
811 // the replacement, rather than just inserting a space at SecondCharLoc.
812 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
813 ReplacementStr);
814
815 // A hint to put another space after the token, if it would otherwise be
816 // lexed differently.
817 FixItHint Hint2;
818 if ((RemainingToken == tok::greater ||
819 RemainingToken == tok::greatergreater) &&
820 (Next.isOneOf(tok::greater, tok::greatergreater,
821 tok::greatergreatergreater, tok::equal,
822 tok::greaterequal, tok::greatergreaterequal,
823 tok::equalequal)) &&
824 areTokensAdjacent(Tok, Next))
825 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
826
827 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
828 if (getLangOpts().CPlusPlus11 &&
829 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
830 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
831 else if (Tok.is(tok::greaterequal))
832 DiagId = diag::err_right_angle_bracket_equal_needs_space;
833 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
834 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000835
836 // Strip the initial '>' from the token.
Bruno Cardoso Lopes428a5aa2016-01-31 00:47:51 +0000837 Token PrevTok = Tok;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000838 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
839 areTokensAdjacent(Tok, Next)) {
840 // Join two adjacent '=' tokens into one, for cases like:
841 // void (*p)() = f<int>;
842 // return f<int>==p;
843 ConsumeToken();
844 Tok.setKind(tok::equalequal);
845 Tok.setLength(Tok.getLength() + 1);
846 } else {
847 Tok.setKind(RemainingToken);
848 Tok.setLength(Tok.getLength() - 1);
849 }
850 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
851 PP.getSourceManager(),
852 getLangOpts()));
853
Bruno Cardoso Lopes428a5aa2016-01-31 00:47:51 +0000854 // The advance from '>>' to '>' in a ObjectiveC template argument list needs
855 // to be properly reflected in the token cache to allow correct interaction
856 // between annotation and backtracking.
857 if (ObjCGenericList && PrevTok.getKind() == tok::greatergreater &&
858 RemainingToken == tok::greater && PP.IsPreviousCachedToken(PrevTok)) {
859 PrevTok.setKind(RemainingToken);
860 PrevTok.setLength(1);
Bruno Cardoso Lopesfb9b6cd2016-02-05 19:36:39 +0000861 // Break tok::greatergreater into two tok::greater but only add the second
862 // one in case the client asks to consume the last token.
863 if (ConsumeLastToken)
864 PP.ReplacePreviousCachedToken({PrevTok, Tok});
865 else
866 PP.ReplacePreviousCachedToken({PrevTok});
Bruno Cardoso Lopes428a5aa2016-01-31 00:47:51 +0000867 }
868
Faisal Vali6a79ca12013-06-08 19:39:00 +0000869 if (!ConsumeLastToken) {
870 // Since we're not supposed to consume the '>' token, we need to push
871 // this token and revert the current token back to the '>'.
872 PP.EnterToken(Tok);
873 Tok.setKind(tok::greater);
874 Tok.setLength(1);
875 Tok.setLocation(RAngleLoc);
876 }
877 return false;
878}
879
880
881/// \brief Parses a template-id that after the template name has
882/// already been parsed.
883///
884/// This routine takes care of parsing the enclosed template argument
885/// list ('<' template-parameter-list [opt] '>') and placing the
886/// results into a form that can be transferred to semantic analysis.
887///
888/// \param Template the template declaration produced by isTemplateName
889///
890/// \param TemplateNameLoc the source location of the template name
891///
892/// \param SS if non-NULL, the nested-name-specifier preceding the
893/// template name.
894///
895/// \param ConsumeLastToken if true, then we will consume the last
896/// token that forms the template-id. Otherwise, we will leave the
897/// last token in the stream (e.g., so that it can be replaced with an
898/// annotation token).
899bool
900Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
901 SourceLocation TemplateNameLoc,
902 const CXXScopeSpec &SS,
903 bool ConsumeLastToken,
904 SourceLocation &LAngleLoc,
905 TemplateArgList &TemplateArgs,
906 SourceLocation &RAngleLoc) {
907 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
908
909 // Consume the '<'.
910 LAngleLoc = ConsumeToken();
911
912 // Parse the optional template-argument-list.
913 bool Invalid = false;
914 {
915 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
916 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
917 Invalid = ParseTemplateArgumentList(TemplateArgs);
918
919 if (Invalid) {
920 // Try to find the closing '>'.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000921 if (ConsumeLastToken)
922 SkipUntil(tok::greater, StopAtSemi);
923 else
924 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000925 return true;
926 }
927 }
928
Douglas Gregor85f3f952015-07-07 03:57:15 +0000929 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken,
930 /*ObjCGenericList=*/false);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000931}
932
933/// \brief Replace the tokens that form a simple-template-id with an
934/// annotation token containing the complete template-id.
935///
936/// The first token in the stream must be the name of a template that
937/// is followed by a '<'. This routine will parse the complete
938/// simple-template-id and replace the tokens with a single annotation
939/// token with one of two different kinds: if the template-id names a
940/// type (and \p AllowTypeAnnotation is true), the annotation token is
941/// a type annotation that includes the optional nested-name-specifier
942/// (\p SS). Otherwise, the annotation token is a template-id
943/// annotation that does not include the optional
944/// nested-name-specifier.
945///
946/// \param Template the declaration of the template named by the first
947/// token (an identifier), as returned from \c Action::isTemplateName().
948///
949/// \param TNK the kind of template that \p Template
950/// refers to, as returned from \c Action::isTemplateName().
951///
952/// \param SS if non-NULL, the nested-name-specifier that precedes
953/// this template name.
954///
955/// \param TemplateKWLoc if valid, specifies that this template-id
956/// annotation was preceded by the 'template' keyword and gives the
957/// location of that keyword. If invalid (the default), then this
958/// template-id was not preceded by a 'template' keyword.
959///
960/// \param AllowTypeAnnotation if true (the default), then a
961/// simple-template-id that refers to a class template, template
962/// template parameter, or other template that produces a type will be
963/// replaced with a type annotation token. Otherwise, the
964/// simple-template-id is always replaced with a template-id
965/// annotation token.
966///
967/// If an unrecoverable parse error occurs and no annotation token can be
968/// formed, this function returns true.
969///
970bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
971 CXXScopeSpec &SS,
972 SourceLocation TemplateKWLoc,
973 UnqualifiedId &TemplateName,
974 bool AllowTypeAnnotation) {
975 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
976 assert(Template && Tok.is(tok::less) &&
977 "Parser isn't at the beginning of a template-id");
978
979 // Consume the template-name.
980 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
981
982 // Parse the enclosed template argument list.
983 SourceLocation LAngleLoc, RAngleLoc;
984 TemplateArgList TemplateArgs;
985 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
986 TemplateNameLoc,
987 SS, false, LAngleLoc,
988 TemplateArgs,
989 RAngleLoc);
990
991 if (Invalid) {
992 // If we failed to parse the template ID but skipped ahead to a >, we're not
993 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000994 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000995 return true;
996 }
997
998 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
999
1000 // Build the annotation token.
1001 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
1002 TypeResult Type
1003 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
1004 Template, TemplateNameLoc,
1005 LAngleLoc, TemplateArgsPtr, RAngleLoc);
1006 if (Type.isInvalid()) {
1007 // If we failed to parse the template ID but skipped ahead to a >, we're not
1008 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001009 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001010 return true;
1011 }
1012
1013 Tok.setKind(tok::annot_typename);
1014 setTypeAnnotation(Tok, Type.get());
1015 if (SS.isNotEmpty())
1016 Tok.setLocation(SS.getBeginLoc());
1017 else if (TemplateKWLoc.isValid())
1018 Tok.setLocation(TemplateKWLoc);
1019 else
1020 Tok.setLocation(TemplateNameLoc);
1021 } else {
1022 // Build a template-id annotation token that can be processed
1023 // later.
1024 Tok.setKind(tok::annot_template_id);
1025 TemplateIdAnnotation *TemplateId
1026 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
1027 TemplateId->TemplateNameLoc = TemplateNameLoc;
1028 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
1029 TemplateId->Name = TemplateName.Identifier;
1030 TemplateId->Operator = OO_None;
1031 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001032 TemplateId->Name = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001033 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
1034 }
1035 TemplateId->SS = SS;
1036 TemplateId->TemplateKWLoc = TemplateKWLoc;
1037 TemplateId->Template = Template;
1038 TemplateId->Kind = TNK;
1039 TemplateId->LAngleLoc = LAngleLoc;
1040 TemplateId->RAngleLoc = RAngleLoc;
1041 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
1042 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
1043 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
1044 Tok.setAnnotationValue(TemplateId);
1045 if (TemplateKWLoc.isValid())
1046 Tok.setLocation(TemplateKWLoc);
1047 else
1048 Tok.setLocation(TemplateNameLoc);
1049 }
1050
1051 // Common fields for the annotation token
1052 Tok.setAnnotationEndLoc(RAngleLoc);
1053
1054 // In case the tokens were cached, have Preprocessor replace them with the
1055 // annotation token.
1056 PP.AnnotateCachedTokens(Tok);
1057 return false;
1058}
1059
1060/// \brief Replaces a template-id annotation token with a type
1061/// annotation token.
1062///
1063/// If there was a failure when forming the type from the template-id,
1064/// a type annotation token will still be created, but will have a
1065/// NULL type pointer to signify an error.
1066void Parser::AnnotateTemplateIdTokenAsType() {
1067 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1068
1069 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1070 assert((TemplateId->Kind == TNK_Type_template ||
1071 TemplateId->Kind == TNK_Dependent_template_name) &&
1072 "Only works for type and dependent templates");
1073
1074 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1075 TemplateId->NumArgs);
1076
1077 TypeResult Type
1078 = Actions.ActOnTemplateIdType(TemplateId->SS,
1079 TemplateId->TemplateKWLoc,
1080 TemplateId->Template,
1081 TemplateId->TemplateNameLoc,
1082 TemplateId->LAngleLoc,
1083 TemplateArgsPtr,
1084 TemplateId->RAngleLoc);
1085 // Create the new "type" annotation token.
1086 Tok.setKind(tok::annot_typename);
David Blaikieefdccaa2016-01-15 23:43:34 +00001087 setTypeAnnotation(Tok, Type.isInvalid() ? nullptr : Type.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001088 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1089 Tok.setLocation(TemplateId->SS.getBeginLoc());
1090 // End location stays the same
1091
1092 // Replace the template-id annotation token, and possible the scope-specifier
1093 // that precedes it, with the typename annotation token.
1094 PP.AnnotateCachedTokens(Tok);
1095}
1096
1097/// \brief Determine whether the given token can end a template argument.
1098static bool isEndOfTemplateArgument(Token Tok) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001099 return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001100}
1101
1102/// \brief Parse a C++ template template argument.
1103ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1104 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1105 !Tok.is(tok::annot_cxxscope))
1106 return ParsedTemplateArgument();
1107
1108 // C++0x [temp.arg.template]p1:
1109 // A template-argument for a template template-parameter shall be the name
1110 // of a class template or an alias template, expressed as id-expression.
1111 //
1112 // We parse an id-expression that refers to a class template or alias
1113 // template. The grammar we parse is:
1114 //
1115 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1116 //
1117 // followed by a token that terminates a template argument, such as ',',
1118 // '>', or (in some cases) '>>'.
1119 CXXScopeSpec SS; // nested-name-specifier, if present
David Blaikieefdccaa2016-01-15 23:43:34 +00001120 ParseOptionalCXXScopeSpecifier(SS, nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001121 /*EnteringContext=*/false);
David Blaikieefdccaa2016-01-15 23:43:34 +00001122
Faisal Vali6a79ca12013-06-08 19:39:00 +00001123 ParsedTemplateArgument Result;
1124 SourceLocation EllipsisLoc;
1125 if (SS.isSet() && Tok.is(tok::kw_template)) {
1126 // Parse the optional 'template' keyword following the
1127 // nested-name-specifier.
1128 SourceLocation TemplateKWLoc = ConsumeToken();
1129
1130 if (Tok.is(tok::identifier)) {
1131 // We appear to have a dependent template name.
1132 UnqualifiedId Name;
1133 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1134 ConsumeToken(); // the identifier
Alp Toker094e5212014-01-05 03:27:11 +00001135
1136 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1137
Faisal Vali6a79ca12013-06-08 19:39:00 +00001138 // If the next token signals the end of a template argument,
1139 // then we have a dependent template name that could be a template
1140 // template argument.
1141 TemplateTy Template;
1142 if (isEndOfTemplateArgument(Tok) &&
David Blaikieefdccaa2016-01-15 23:43:34 +00001143 Actions.ActOnDependentTemplateName(
1144 getCurScope(), SS, TemplateKWLoc, Name,
1145 /*ObjectType=*/nullptr,
1146 /*EnteringContext=*/false, Template))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001147 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1148 }
1149 } else if (Tok.is(tok::identifier)) {
1150 // We may have a (non-dependent) template name.
1151 TemplateTy Template;
1152 UnqualifiedId Name;
1153 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1154 ConsumeToken(); // the identifier
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001155
1156 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001157
1158 if (isEndOfTemplateArgument(Tok)) {
1159 bool MemberOfUnknownSpecialization;
David Blaikieefdccaa2016-01-15 23:43:34 +00001160 TemplateNameKind TNK = Actions.isTemplateName(
1161 getCurScope(), SS,
1162 /*hasTemplateKeyword=*/false, Name,
1163 /*ObjectType=*/nullptr,
1164 /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001165 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1166 // We have an id-expression that refers to a class template or
1167 // (C++0x) alias template.
1168 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1169 }
1170 }
1171 }
1172
1173 // If this is a pack expansion, build it as such.
1174 if (EllipsisLoc.isValid() && !Result.isInvalid())
1175 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1176
1177 return Result;
1178}
1179
1180/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1181///
1182/// template-argument: [C++ 14.2]
1183/// constant-expression
1184/// type-id
1185/// id-expression
1186ParsedTemplateArgument Parser::ParseTemplateArgument() {
1187 // C++ [temp.arg]p2:
1188 // In a template-argument, an ambiguity between a type-id and an
1189 // expression is resolved to a type-id, regardless of the form of
1190 // the corresponding template-parameter.
1191 //
1192 // Therefore, we initially try to parse a type-id.
1193 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1194 SourceLocation Loc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00001195 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001196 Declarator::TemplateTypeArgContext);
1197 if (TypeArg.isInvalid())
1198 return ParsedTemplateArgument();
1199
1200 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1201 TypeArg.get().getAsOpaquePtr(),
1202 Loc);
1203 }
1204
1205 // Try to parse a template template argument.
1206 {
1207 TentativeParsingAction TPA(*this);
1208
1209 ParsedTemplateArgument TemplateTemplateArgument
1210 = ParseTemplateTemplateArgument();
1211 if (!TemplateTemplateArgument.isInvalid()) {
1212 TPA.Commit();
1213 return TemplateTemplateArgument;
1214 }
1215
1216 // Revert this tentative parse to parse a non-type template argument.
1217 TPA.Revert();
1218 }
1219
1220 // Parse a non-type template argument.
1221 SourceLocation Loc = Tok.getLocation();
1222 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1223 if (ExprArg.isInvalid() || !ExprArg.get())
1224 return ParsedTemplateArgument();
1225
1226 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001227 ExprArg.get(), Loc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001228}
1229
1230/// \brief Determine whether the current tokens can only be parsed as a
1231/// template argument list (starting with the '<') and never as a '<'
1232/// expression.
1233bool Parser::IsTemplateArgumentList(unsigned Skip) {
1234 struct AlwaysRevertAction : TentativeParsingAction {
1235 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1236 ~AlwaysRevertAction() { Revert(); }
1237 } Tentative(*this);
1238
1239 while (Skip) {
1240 ConsumeToken();
1241 --Skip;
1242 }
1243
1244 // '<'
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001245 if (!TryConsumeToken(tok::less))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001246 return false;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001247
1248 // An empty template argument list.
1249 if (Tok.is(tok::greater))
1250 return true;
1251
1252 // See whether we have declaration specifiers, which indicate a type.
Richard Smithee390432014-05-16 01:56:53 +00001253 while (isCXXDeclarationSpecifier() == TPResult::True)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001254 ConsumeToken();
1255
1256 // If we have a '>' or a ',' then this is a template argument list.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001257 return Tok.isOneOf(tok::greater, tok::comma);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001258}
1259
1260/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1261/// (C++ [temp.names]). Returns true if there was an error.
1262///
1263/// template-argument-list: [C++ 14.2]
1264/// template-argument
1265/// template-argument-list ',' template-argument
1266bool
1267Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1268 // Template argument lists are constant-evaluation contexts.
1269 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +00001270 ColonProtectionRAIIObject ColonProtection(*this, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001271
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001272 do {
Faisal Vali6a79ca12013-06-08 19:39:00 +00001273 ParsedTemplateArgument Arg = ParseTemplateArgument();
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001274 SourceLocation EllipsisLoc;
1275 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001276 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001277
1278 if (Arg.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001279 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001280 return true;
1281 }
1282
1283 // Save this template argument.
1284 TemplateArgs.push_back(Arg);
1285
1286 // If the next token is a comma, consume it and keep reading
1287 // arguments.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001288 } while (TryConsumeToken(tok::comma));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001289
1290 return false;
1291}
1292
1293/// \brief Parse a C++ explicit template instantiation
1294/// (C++ [temp.explicit]).
1295///
1296/// explicit-instantiation:
1297/// 'extern' [opt] 'template' declaration
1298///
1299/// Note that the 'extern' is a GNU extension and C++11 feature.
1300Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1301 SourceLocation ExternLoc,
1302 SourceLocation TemplateLoc,
1303 SourceLocation &DeclEnd,
1304 AccessSpecifier AS) {
1305 // This isn't really required here.
1306 ParsingDeclRAIIObject
1307 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1308
1309 return ParseSingleDeclarationAfterTemplate(Context,
1310 ParsedTemplateInfo(ExternLoc,
1311 TemplateLoc),
1312 ParsingTemplateParams,
1313 DeclEnd, AS);
1314}
1315
1316SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1317 if (TemplateParams)
1318 return getTemplateParamsRange(TemplateParams->data(),
1319 TemplateParams->size());
1320
1321 SourceRange R(TemplateLoc);
1322 if (ExternLoc.isValid())
1323 R.setBegin(ExternLoc);
1324 return R;
1325}
1326
Richard Smithe40f2ba2013-08-07 21:41:30 +00001327void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1328 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001329}
1330
1331/// \brief Late parse a C++ function template in Microsoft mode.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001332void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
David Majnemerf0a84f22013-08-16 08:29:13 +00001333 if (!LPT.D)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001334 return;
1335
1336 // Get the FunctionDecl.
Alp Tokera2794f92014-01-22 07:29:52 +00001337 FunctionDecl *FunD = LPT.D->getAsFunction();
Faisal Vali6a79ca12013-06-08 19:39:00 +00001338 // Track template parameter depth.
1339 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1340
1341 // To restore the context after late parsing.
Richard Smithb0b68012015-05-11 23:09:06 +00001342 Sema::ContextRAII GlobalSavedContext(
1343 Actions, Actions.Context.getTranslationUnitDecl());
Faisal Vali6a79ca12013-06-08 19:39:00 +00001344
1345 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1346
1347 // Get the list of DeclContexts to reenter.
1348 SmallVector<DeclContext*, 4> DeclContextsToReenter;
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001349 DeclContext *DD = FunD;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001350 while (DD && !DD->isTranslationUnit()) {
1351 DeclContextsToReenter.push_back(DD);
1352 DD = DD->getLexicalParent();
1353 }
1354
1355 // Reenter template scopes from outermost to innermost.
Craig Topper61ac9062013-07-08 03:55:09 +00001356 SmallVectorImpl<DeclContext *>::reverse_iterator II =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001357 DeclContextsToReenter.rbegin();
1358 for (; II != DeclContextsToReenter.rend(); ++II) {
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001359 TemplateParamScopeStack.push_back(new ParseScope(this,
1360 Scope::TemplateParamScope));
1361 unsigned NumParamLists =
1362 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1363 CurTemplateDepthTracker.addDepth(NumParamLists);
1364 if (*II != FunD) {
1365 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1366 Actions.PushDeclContext(Actions.getCurScope(), *II);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001367 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001368 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001369
Richard Smithe40f2ba2013-08-07 21:41:30 +00001370 assert(!LPT.Toks.empty() && "Empty body!");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001371
1372 // Append the current token at the end of the new token stream so that it
1373 // doesn't get lost.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001374 LPT.Toks.push_back(Tok);
David Blaikie2eabcc92016-02-09 18:52:09 +00001375 PP.EnterTokenStream(LPT.Toks, true);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001376
1377 // Consume the previously pushed token.
1378 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001379 assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) &&
1380 "Inline method not starting with '{', ':' or 'try'");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001381
1382 // Parse the method body. Function body parsing code is similar enough
1383 // to be re-used for method bodies as well.
1384 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1385
1386 // Recreate the containing function DeclContext.
Nico Weber55048cf2014-08-15 22:15:00 +00001387 Sema::ContextRAII FunctionSavedContext(Actions,
1388 Actions.getContainingDC(FunD));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001389
1390 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1391
1392 if (Tok.is(tok::kw_try)) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00001393 ParseFunctionTryBlock(LPT.D, FnScope);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001394 } else {
1395 if (Tok.is(tok::colon))
Richard Smithe40f2ba2013-08-07 21:41:30 +00001396 ParseConstructorInitializer(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001397 else
Richard Smithe40f2ba2013-08-07 21:41:30 +00001398 Actions.ActOnDefaultCtorInitializers(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001399
1400 if (Tok.is(tok::l_brace)) {
Alp Tokera2794f92014-01-22 07:29:52 +00001401 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1402 cast<FunctionTemplateDecl>(LPT.D)
1403 ->getTemplateParameters()
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001404 ->getDepth() == TemplateParameterDepth - 1) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +00001405 "TemplateParameterDepth should be greater than the depth of "
1406 "current template being instantiated!");
Richard Smithe40f2ba2013-08-07 21:41:30 +00001407 ParseFunctionStatementBody(LPT.D, FnScope);
1408 Actions.UnmarkAsLateParsedTemplate(FunD);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001409 } else
Craig Topper161e4db2014-05-21 06:02:52 +00001410 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001411 }
1412
1413 // Exit scopes.
1414 FnScope.Exit();
Craig Topper61ac9062013-07-08 03:55:09 +00001415 SmallVectorImpl<ParseScope *>::reverse_iterator I =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001416 TemplateParamScopeStack.rbegin();
1417 for (; I != TemplateParamScopeStack.rend(); ++I)
1418 delete *I;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001419}
1420
1421/// \brief Lex a delayed template function for late parsing.
1422void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1423 tok::TokenKind kind = Tok.getKind();
1424 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1425 // Consume everything up to (and including) the matching right brace.
1426 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1427 }
1428
1429 // If we're in a function-try-block, we need to store all the catch blocks.
1430 if (kind == tok::kw_try) {
1431 while (Tok.is(tok::kw_catch)) {
1432 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1433 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1434 }
1435 }
1436}