blob: 4d0ec8f834db1fee6f282e2bf49101cf60510aff [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"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/Parse/ParseDiagnostic.h"
19#include "clang/Sema/DeclSpec.h"
20#include "clang/Sema/ParsedTemplate.h"
21#include "clang/Sema/Scope.h"
22using namespace clang;
23
24/// \brief Parse a template declaration, explicit instantiation, or
25/// explicit specialization.
26Decl *
27Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
28 SourceLocation &DeclEnd,
29 AccessSpecifier AS,
30 AttributeList *AccessAttrs) {
31 ObjCDeclContextSwitch ObjCDC(*this);
32
33 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
34 return ParseExplicitInstantiation(Context,
35 SourceLocation(), ConsumeToken(),
36 DeclEnd, AS);
37 }
38 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
39 AccessAttrs);
40}
41
42
43
44/// \brief Parse a template declaration or an explicit specialization.
45///
46/// Template declarations include one or more template parameter lists
47/// and either the function or class template declaration. Explicit
48/// specializations contain one or more 'template < >' prefixes
49/// followed by a (possibly templated) declaration. Since the
50/// syntactic form of both features is nearly identical, we parse all
51/// of the template headers together and let semantic analysis sort
52/// the declarations from the explicit specializations.
53///
54/// template-declaration: [C++ temp]
55/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
56///
57/// explicit-specialization: [ C++ temp.expl.spec]
58/// 'template' '<' '>' declaration
59Decl *
60Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
61 SourceLocation &DeclEnd,
62 AccessSpecifier AS,
63 AttributeList *AccessAttrs) {
64 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
65 "Token does not start a template declaration.");
66
67 // Enter template-parameter scope.
68 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
69
70 // Tell the action that names should be checked in the context of
71 // the declaration to come.
72 ParsingDeclRAIIObject
73 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
74
75 // Parse multiple levels of template headers within this template
76 // parameter scope, e.g.,
77 //
78 // template<typename T>
79 // template<typename U>
80 // class A<T>::B { ... };
81 //
82 // We parse multiple levels non-recursively so that we can build a
83 // single data structure containing all of the template parameter
84 // lists to easily differentiate between the case above and:
85 //
86 // template<typename T>
87 // class A {
88 // template<typename U> class B;
89 // };
90 //
91 // In the first case, the action for declaring A<T>::B receives
92 // both template parameter lists. In the second case, the action for
93 // defining A<T>::B receives just the inner template parameter list
94 // (and retrieves the outer template parameter list from its
95 // context).
96 bool isSpecialization = true;
97 bool LastParamListWasEmpty = false;
98 TemplateParameterLists ParamLists;
99 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
100
101 do {
102 // Consume the 'export', if any.
103 SourceLocation ExportLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000104 TryConsumeToken(tok::kw_export, ExportLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000105
106 // Consume the 'template', which should be here.
107 SourceLocation TemplateLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000108 if (!TryConsumeToken(tok::kw_template, TemplateLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000109 Diag(Tok.getLocation(), diag::err_expected_template);
Craig Topper161e4db2014-05-21 06:02:52 +0000110 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000111 }
112
113 // Parse the '<' template-parameter-list '>'
114 SourceLocation LAngleLoc, RAngleLoc;
115 SmallVector<Decl*, 4> TemplateParams;
116 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
117 TemplateParams, LAngleLoc, RAngleLoc)) {
118 // Skip until the semi-colon or a }.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000119 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000120 TryConsumeToken(tok::semi);
Craig Topper161e4db2014-05-21 06:02:52 +0000121 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000122 }
123
124 ParamLists.push_back(
125 Actions.ActOnTemplateParameterList(CurTemplateDepthTracker.getDepth(),
126 ExportLoc,
127 TemplateLoc, LAngleLoc,
128 TemplateParams.data(),
129 TemplateParams.size(), RAngleLoc));
130
131 if (!TemplateParams.empty()) {
132 isSpecialization = false;
133 ++CurTemplateDepthTracker;
134 } else {
135 LastParamListWasEmpty = true;
136 }
137 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
138
139 // Parse the actual template declaration.
140 return ParseSingleDeclarationAfterTemplate(Context,
141 ParsedTemplateInfo(&ParamLists,
142 isSpecialization,
143 LastParamListWasEmpty),
144 ParsingTemplateParams,
145 DeclEnd, AS, AccessAttrs);
146}
147
148/// \brief Parse a single declaration that declares a template,
149/// template specialization, or explicit instantiation of a template.
150///
151/// \param DeclEnd will receive the source location of the last token
152/// within this declaration.
153///
154/// \param AS the access specifier associated with this
155/// declaration. Will be AS_none for namespace-scope declarations.
156///
157/// \returns the new declaration.
158Decl *
159Parser::ParseSingleDeclarationAfterTemplate(
160 unsigned Context,
161 const ParsedTemplateInfo &TemplateInfo,
162 ParsingDeclRAIIObject &DiagsFromTParams,
163 SourceLocation &DeclEnd,
164 AccessSpecifier AS,
165 AttributeList *AccessAttrs) {
166 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
167 "Template information required");
168
169 if (Context == Declarator::MemberContext) {
170 // We are parsing a member template.
171 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
172 &DiagsFromTParams);
Craig Topper161e4db2014-05-21 06:02:52 +0000173 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000174 }
175
176 ParsedAttributesWithRange prefixAttrs(AttrFactory);
177 MaybeParseCXX11Attributes(prefixAttrs);
178
179 if (Tok.is(tok::kw_using))
180 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
181 prefixAttrs);
182
183 // Parse the declaration specifiers, stealing any diagnostics from
184 // the template parameters.
185 ParsingDeclSpec DS(*this, &DiagsFromTParams);
186
187 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
188 getDeclSpecContextFromDeclaratorContext(Context));
189
190 if (Tok.is(tok::semi)) {
191 ProhibitAttributes(prefixAttrs);
192 DeclEnd = ConsumeToken();
193 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
194 getCurScope(), AS, DS,
195 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
196 : MultiTemplateParamsArg(),
197 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation);
198 DS.complete(Decl);
199 return Decl;
200 }
201
202 // Move the attributes from the prefix into the DS.
203 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
204 ProhibitAttributes(prefixAttrs);
205 else
206 DS.takeAttributesFrom(prefixAttrs);
207
208 // Parse the declarator.
209 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
210 ParseDeclarator(DeclaratorInfo);
211 // Error parsing the declarator?
212 if (!DeclaratorInfo.hasName()) {
213 // If so, skip until the semi-colon or a }.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000214 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000215 if (Tok.is(tok::semi))
216 ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000217 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000218 }
219
220 LateParsedAttrList LateParsedAttrs(true);
221 if (DeclaratorInfo.isFunctionDeclarator())
222 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
223
224 if (DeclaratorInfo.isFunctionDeclarator() &&
225 isStartOfFunctionDefinition(DeclaratorInfo)) {
226 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
227 // Recover by ignoring the 'typedef'. This was probably supposed to be
228 // the 'typename' keyword, which we should have already suggested adding
229 // if it's appropriate.
230 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
231 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
232 DS.ClearStorageClassSpecs();
233 }
Larisse Voufo725de3e2013-06-21 00:08:46 +0000234
235 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
236 if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
237 // If the declarator-id is not a template-id, issue a diagnostic and
238 // recover by ignoring the 'template' keyword.
239 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000240 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
241 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000242 } else {
243 SourceLocation LAngleLoc
244 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000245 Diag(DeclaratorInfo.getIdentifierLoc(),
Larisse Voufo725de3e2013-06-21 00:08:46 +0000246 diag::err_explicit_instantiation_with_definition)
Larisse Voufo39a1e502013-08-06 01:03:05 +0000247 << SourceRange(TemplateInfo.TemplateLoc)
248 << FixItHint::CreateInsertion(LAngleLoc, "<>");
Larisse Voufo725de3e2013-06-21 00:08:46 +0000249
Larisse Voufo39a1e502013-08-06 01:03:05 +0000250 // Recover as if it were an explicit specialization.
Larisse Voufob9bbaba2013-06-22 13:56:11 +0000251 TemplateParameterLists FakedParamLists;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000252 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper161e4db2014-05-21 06:02:52 +0000253 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr,
254 0, LAngleLoc));
Larisse Voufo725de3e2013-06-21 00:08:46 +0000255
Larisse Voufo39a1e502013-08-06 01:03:05 +0000256 return ParseFunctionDefinition(
257 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
258 /*isSpecialization=*/true,
259 /*LastParamListWasEmpty=*/true),
260 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000261 }
262 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000263 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
Larisse Voufo39a1e502013-08-06 01:03:05 +0000264 &LateParsedAttrs);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000265 }
266
267 // Parse this declaration.
268 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
269 TemplateInfo);
270
271 if (Tok.is(tok::comma)) {
272 Diag(Tok, diag::err_multiple_template_declarators)
273 << (int)TemplateInfo.Kind;
Alexey Bataevee6507d2013-11-18 08:17:37 +0000274 SkipUntil(tok::semi);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000275 return ThisDecl;
276 }
277
278 // Eat the semi colon after the declaration.
279 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
280 if (LateParsedAttrs.size() > 0)
281 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
282 DeclaratorInfo.complete(ThisDecl);
283 return ThisDecl;
284}
285
286/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
287/// angle brackets. Depth is the depth of this template-parameter-list, which
288/// is the number of template headers directly enclosing this template header.
289/// TemplateParams is the current list of template parameters we're building.
290/// The template parameter we parse will be added to this list. LAngleLoc and
291/// RAngleLoc will receive the positions of the '<' and '>', respectively,
292/// that enclose this template parameter list.
293///
294/// \returns true if an error occurred, false otherwise.
295bool Parser::ParseTemplateParameters(unsigned Depth,
296 SmallVectorImpl<Decl*> &TemplateParams,
297 SourceLocation &LAngleLoc,
298 SourceLocation &RAngleLoc) {
299 // Get the template parameter list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000300 if (!TryConsumeToken(tok::less, LAngleLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000301 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
302 return true;
303 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000304
305 // Try to parse the template parameter list.
306 bool Failed = false;
307 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
308 Failed = ParseTemplateParameterList(Depth, TemplateParams);
309
310 if (Tok.is(tok::greatergreater)) {
311 // No diagnostic required here: a template-parameter-list can only be
312 // followed by a declaration or, for a template template parameter, the
313 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
314 // This matters for elegant diagnosis of:
315 // template<template<typename>> struct S;
316 Tok.setKind(tok::greater);
317 RAngleLoc = Tok.getLocation();
318 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
Alp Toker383d2c42014-01-01 03:08:43 +0000319 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
320 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000321 return true;
322 }
323 return false;
324}
325
326/// ParseTemplateParameterList - Parse a template parameter list. If
327/// the parsing fails badly (i.e., closing bracket was left out), this
328/// will try to put the token stream in a reasonable position (closing
329/// a statement, etc.) and return false.
330///
331/// template-parameter-list: [C++ temp]
332/// template-parameter
333/// template-parameter-list ',' template-parameter
334bool
335Parser::ParseTemplateParameterList(unsigned Depth,
336 SmallVectorImpl<Decl*> &TemplateParams) {
337 while (1) {
338 if (Decl *TmpParam
339 = ParseTemplateParameter(Depth, TemplateParams.size())) {
340 TemplateParams.push_back(TmpParam);
341 } else {
342 // If we failed to parse a template parameter, skip until we find
343 // a comma or closing brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000344 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
345 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000346 }
347
348 // Did we find a comma or the end of the template parameter list?
349 if (Tok.is(tok::comma)) {
350 ConsumeToken();
351 } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
352 // Don't consume this... that's done by template parser.
353 break;
354 } else {
355 // Somebody probably forgot to close the template. Skip ahead and
356 // try to get out of the expression. This error is currently
357 // subsumed by whatever goes on in ParseTemplateParameter.
358 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000359 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
360 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000361 return false;
362 }
363 }
364 return true;
365}
366
367/// \brief Determine whether the parser is at the start of a template
368/// type parameter.
369bool Parser::isStartOfTemplateTypeParameter() {
370 if (Tok.is(tok::kw_class)) {
371 // "class" may be the start of an elaborated-type-specifier or a
372 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
373 switch (NextToken().getKind()) {
374 case tok::equal:
375 case tok::comma:
376 case tok::greater:
377 case tok::greatergreater:
378 case tok::ellipsis:
379 return true;
380
381 case tok::identifier:
382 // This may be either a type-parameter or an elaborated-type-specifier.
383 // We have to look further.
384 break;
385
386 default:
387 return false;
388 }
389
390 switch (GetLookAheadToken(2).getKind()) {
391 case tok::equal:
392 case tok::comma:
393 case tok::greater:
394 case tok::greatergreater:
395 return true;
396
397 default:
398 return false;
399 }
400 }
401
402 if (Tok.isNot(tok::kw_typename))
403 return false;
404
405 // C++ [temp.param]p2:
406 // There is no semantic difference between class and typename in a
407 // template-parameter. typename followed by an unqualified-id
408 // names a template type parameter. typename followed by a
409 // qualified-id denotes the type in a non-type
410 // parameter-declaration.
411 Token Next = NextToken();
412
413 // If we have an identifier, skip over it.
414 if (Next.getKind() == tok::identifier)
415 Next = GetLookAheadToken(2);
416
417 switch (Next.getKind()) {
418 case tok::equal:
419 case tok::comma:
420 case tok::greater:
421 case tok::greatergreater:
422 case tok::ellipsis:
423 return true;
424
425 default:
426 return false;
427 }
428}
429
430/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
431///
432/// template-parameter: [C++ temp.param]
433/// type-parameter
434/// parameter-declaration
435///
436/// type-parameter: (see below)
437/// 'class' ...[opt] identifier[opt]
438/// 'class' identifier[opt] '=' type-id
439/// 'typename' ...[opt] identifier[opt]
440/// 'typename' identifier[opt] '=' type-id
441/// 'template' '<' template-parameter-list '>'
442/// 'class' ...[opt] identifier[opt]
443/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
444/// = id-expression
445Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
446 if (isStartOfTemplateTypeParameter())
447 return ParseTypeParameter(Depth, Position);
448
449 if (Tok.is(tok::kw_template))
450 return ParseTemplateTemplateParameter(Depth, Position);
451
452 // If it's none of the above, then it must be a parameter declaration.
453 // NOTE: This will pick up errors in the closure of the template parameter
454 // list (e.g., template < ; Check here to implement >> style closures.
455 return ParseNonTypeTemplateParameter(Depth, Position);
456}
457
458/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
459/// Other kinds of template parameters are parsed in
460/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
461///
462/// type-parameter: [C++ temp.param]
463/// 'class' ...[opt][C++0x] identifier[opt]
464/// 'class' identifier[opt] '=' type-id
465/// 'typename' ...[opt][C++0x] identifier[opt]
466/// 'typename' identifier[opt] '=' type-id
467Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
468 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
469 "A type-parameter starts with 'class' or 'typename'");
470
471 // Consume the 'class' or 'typename' keyword.
472 bool TypenameKeyword = Tok.is(tok::kw_typename);
473 SourceLocation KeyLoc = ConsumeToken();
474
475 // Grab the ellipsis (if given).
476 bool Ellipsis = false;
477 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000478 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000479 Ellipsis = true;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000480 Diag(EllipsisLoc,
481 getLangOpts().CPlusPlus11
482 ? diag::warn_cxx98_compat_variadic_templates
483 : diag::ext_variadic_templates);
484 }
485
486 // Grab the template parameter name (if given)
487 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000488 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000489 if (Tok.is(tok::identifier)) {
490 ParamName = Tok.getIdentifierInfo();
491 NameLoc = ConsumeToken();
492 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
493 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
494 // Unnamed template parameter. Don't have to do anything here, just
495 // don't consume this token.
496 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000497 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000498 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000499 }
500
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000501 // Recover from misplaced ellipsis.
502 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
503 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
504 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
505
Faisal Vali6a79ca12013-06-08 19:39:00 +0000506 // Grab a default argument (if available).
507 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
508 // we introduce the type parameter into the local scope.
509 SourceLocation EqualLoc;
510 ParsedType DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000511 if (TryConsumeToken(tok::equal, EqualLoc))
Craig Topper161e4db2014-05-21 06:02:52 +0000512 DefaultArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000513 Declarator::TemplateTypeArgContext).get();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000514
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000515 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
516 KeyLoc, ParamName, NameLoc, Depth, Position,
517 EqualLoc, DefaultArg);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000518}
519
520/// ParseTemplateTemplateParameter - Handle the parsing of template
521/// template parameters.
522///
523/// type-parameter: [C++ temp.param]
524/// 'template' '<' template-parameter-list '>' 'class'
525/// ...[opt] identifier[opt]
526/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
527/// = id-expression
528Decl *
529Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
530 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
531
532 // Handle the template <...> part.
533 SourceLocation TemplateLoc = ConsumeToken();
534 SmallVector<Decl*,8> TemplateParams;
535 SourceLocation LAngleLoc, RAngleLoc;
536 {
537 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
538 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
539 RAngleLoc)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000540 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000541 }
542 }
543
544 // Generate a meaningful error if the user forgot to put class before the
545 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
546 // or greater appear immediately or after 'typename' or 'struct'. In the
547 // latter case, replace the keyword with 'class'.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000548 if (!TryConsumeToken(tok::kw_class)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000549 bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
550 const Token& Next = Replace ? NextToken() : Tok;
551 if (Next.is(tok::identifier) || Next.is(tok::comma) ||
552 Next.is(tok::greater) || Next.is(tok::greatergreater) ||
553 Next.is(tok::ellipsis))
554 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
555 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
556 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
557 else
558 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
559
560 if (Replace)
561 ConsumeToken();
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000562 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000563
564 // Parse the ellipsis, if given.
565 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000566 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000567 Diag(EllipsisLoc,
568 getLangOpts().CPlusPlus11
569 ? diag::warn_cxx98_compat_variadic_templates
570 : diag::ext_variadic_templates);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000571
572 // Get the identifier, if given.
573 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000574 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000575 if (Tok.is(tok::identifier)) {
576 ParamName = Tok.getIdentifierInfo();
577 NameLoc = ConsumeToken();
578 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
579 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
580 // Unnamed template parameter. Don't have to do anything here, just
581 // don't consume this token.
582 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000583 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000584 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000585 }
586
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000587 // Recover from misplaced ellipsis.
588 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
589 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
590 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
591
Faisal Vali6a79ca12013-06-08 19:39:00 +0000592 TemplateParameterList *ParamList =
593 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
594 TemplateLoc, LAngleLoc,
595 TemplateParams.data(),
596 TemplateParams.size(),
597 RAngleLoc);
598
599 // Grab a default argument (if available).
600 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
601 // we introduce the template parameter into the local scope.
602 SourceLocation EqualLoc;
603 ParsedTemplateArgument DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000604 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000605 DefaultArg = ParseTemplateTemplateArgument();
606 if (DefaultArg.isInvalid()) {
607 Diag(Tok.getLocation(),
608 diag::err_default_template_template_parameter_not_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000609 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
610 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000611 }
612 }
613
614 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
615 ParamList, EllipsisLoc,
616 ParamName, NameLoc, Depth,
617 Position, EqualLoc, DefaultArg);
618}
619
620/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
621/// template parameters (e.g., in "template<int Size> class array;").
622///
623/// template-parameter:
624/// ...
625/// parameter-declaration
626Decl *
627Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
628 // Parse the declaration-specifiers (i.e., the type).
629 // FIXME: The type should probably be restricted in some way... Not all
630 // declarators (parts of declarators?) are accepted for parameters.
631 DeclSpec DS(AttrFactory);
632 ParseDeclarationSpecifiers(DS);
633
634 // Parse this as a typename.
635 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
636 ParseDeclarator(ParamDecl);
637 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
638 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
Craig Topper161e4db2014-05-21 06:02:52 +0000639 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000640 }
641
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000642 // Recover from misplaced ellipsis.
643 SourceLocation EllipsisLoc;
644 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
645 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
646
Faisal Vali6a79ca12013-06-08 19:39:00 +0000647 // If there is a default value, parse it.
648 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
649 // we introduce the template parameter into the local scope.
650 SourceLocation EqualLoc;
651 ExprResult DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000652 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000653 // C++ [temp.param]p15:
654 // When parsing a default template-argument for a non-type
655 // template-parameter, the first non-nested > is taken as the
656 // end of the template-parameter-list rather than a greater-than
657 // operator.
658 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
659 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
660
661 DefaultArg = ParseAssignmentExpression();
662 if (DefaultArg.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +0000663 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000664 }
665
666 // Create the parameter.
667 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
668 Depth, Position, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000669 DefaultArg.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000670}
671
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000672void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
673 SourceLocation CorrectLoc,
674 bool AlreadyHasEllipsis,
675 bool IdentifierHasName) {
676 FixItHint Insertion;
677 if (!AlreadyHasEllipsis)
678 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
679 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
680 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
681 << !IdentifierHasName;
682}
683
684void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
685 Declarator &D) {
686 assert(EllipsisLoc.isValid());
687 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
688 if (!AlreadyHasEllipsis)
689 D.setEllipsisLoc(EllipsisLoc);
690 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
691 AlreadyHasEllipsis, D.hasName());
692}
693
Faisal Vali6a79ca12013-06-08 19:39:00 +0000694/// \brief Parses a '>' at the end of a template list.
695///
696/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
697/// to determine if these tokens were supposed to be a '>' followed by
698/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
699///
700/// \param RAngleLoc the location of the consumed '>'.
701///
702/// \param ConsumeLastToken if true, the '>' is not consumed.
Serge Pavlovb716b3c2013-08-10 05:54:47 +0000703///
704/// \returns true, if current token does not start with '>', false otherwise.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000705bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
706 bool ConsumeLastToken) {
707 // What will be left once we've consumed the '>'.
708 tok::TokenKind RemainingToken;
709 const char *ReplacementStr = "> >";
710
711 switch (Tok.getKind()) {
712 default:
Alp Toker383d2c42014-01-01 03:08:43 +0000713 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000714 return true;
715
716 case tok::greater:
717 // Determine the location of the '>' token. Only consume this token
718 // if the caller asked us to.
719 RAngleLoc = Tok.getLocation();
720 if (ConsumeLastToken)
721 ConsumeToken();
722 return false;
723
724 case tok::greatergreater:
725 RemainingToken = tok::greater;
726 break;
727
728 case tok::greatergreatergreater:
729 RemainingToken = tok::greatergreater;
730 break;
731
732 case tok::greaterequal:
733 RemainingToken = tok::equal;
734 ReplacementStr = "> =";
735 break;
736
737 case tok::greatergreaterequal:
738 RemainingToken = tok::greaterequal;
739 break;
740 }
741
742 // This template-id is terminated by a token which starts with a '>'. Outside
743 // C++11, this is now error recovery, and in C++11, this is error recovery if
744 // the token isn't '>>'.
745
746 RAngleLoc = Tok.getLocation();
747
748 // The source range of the '>>' or '>=' at the start of the token.
749 CharSourceRange ReplacementRange =
750 CharSourceRange::getCharRange(RAngleLoc,
751 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
752 getLangOpts()));
753
754 // A hint to put a space between the '>>'s. In order to make the hint as
755 // clear as possible, we include the characters either side of the space in
756 // the replacement, rather than just inserting a space at SecondCharLoc.
757 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
758 ReplacementStr);
759
760 // A hint to put another space after the token, if it would otherwise be
761 // lexed differently.
762 FixItHint Hint2;
763 Token Next = NextToken();
764 if ((RemainingToken == tok::greater ||
765 RemainingToken == tok::greatergreater) &&
766 (Next.is(tok::greater) || Next.is(tok::greatergreater) ||
767 Next.is(tok::greatergreatergreater) || Next.is(tok::equal) ||
768 Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) ||
769 Next.is(tok::equalequal)) &&
770 areTokensAdjacent(Tok, Next))
771 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
772
773 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
774 if (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater))
775 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
776 else if (Tok.is(tok::greaterequal))
777 DiagId = diag::err_right_angle_bracket_equal_needs_space;
778 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
779
780 // Strip the initial '>' from the token.
781 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
782 areTokensAdjacent(Tok, Next)) {
783 // Join two adjacent '=' tokens into one, for cases like:
784 // void (*p)() = f<int>;
785 // return f<int>==p;
786 ConsumeToken();
787 Tok.setKind(tok::equalequal);
788 Tok.setLength(Tok.getLength() + 1);
789 } else {
790 Tok.setKind(RemainingToken);
791 Tok.setLength(Tok.getLength() - 1);
792 }
793 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
794 PP.getSourceManager(),
795 getLangOpts()));
796
797 if (!ConsumeLastToken) {
798 // Since we're not supposed to consume the '>' token, we need to push
799 // this token and revert the current token back to the '>'.
800 PP.EnterToken(Tok);
801 Tok.setKind(tok::greater);
802 Tok.setLength(1);
803 Tok.setLocation(RAngleLoc);
804 }
805 return false;
806}
807
808
809/// \brief Parses a template-id that after the template name has
810/// already been parsed.
811///
812/// This routine takes care of parsing the enclosed template argument
813/// list ('<' template-parameter-list [opt] '>') and placing the
814/// results into a form that can be transferred to semantic analysis.
815///
816/// \param Template the template declaration produced by isTemplateName
817///
818/// \param TemplateNameLoc the source location of the template name
819///
820/// \param SS if non-NULL, the nested-name-specifier preceding the
821/// template name.
822///
823/// \param ConsumeLastToken if true, then we will consume the last
824/// token that forms the template-id. Otherwise, we will leave the
825/// last token in the stream (e.g., so that it can be replaced with an
826/// annotation token).
827bool
828Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
829 SourceLocation TemplateNameLoc,
830 const CXXScopeSpec &SS,
831 bool ConsumeLastToken,
832 SourceLocation &LAngleLoc,
833 TemplateArgList &TemplateArgs,
834 SourceLocation &RAngleLoc) {
835 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
836
837 // Consume the '<'.
838 LAngleLoc = ConsumeToken();
839
840 // Parse the optional template-argument-list.
841 bool Invalid = false;
842 {
843 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
844 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
845 Invalid = ParseTemplateArgumentList(TemplateArgs);
846
847 if (Invalid) {
848 // Try to find the closing '>'.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000849 if (ConsumeLastToken)
850 SkipUntil(tok::greater, StopAtSemi);
851 else
852 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000853 return true;
854 }
855 }
856
857 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken);
858}
859
860/// \brief Replace the tokens that form a simple-template-id with an
861/// annotation token containing the complete template-id.
862///
863/// The first token in the stream must be the name of a template that
864/// is followed by a '<'. This routine will parse the complete
865/// simple-template-id and replace the tokens with a single annotation
866/// token with one of two different kinds: if the template-id names a
867/// type (and \p AllowTypeAnnotation is true), the annotation token is
868/// a type annotation that includes the optional nested-name-specifier
869/// (\p SS). Otherwise, the annotation token is a template-id
870/// annotation that does not include the optional
871/// nested-name-specifier.
872///
873/// \param Template the declaration of the template named by the first
874/// token (an identifier), as returned from \c Action::isTemplateName().
875///
876/// \param TNK the kind of template that \p Template
877/// refers to, as returned from \c Action::isTemplateName().
878///
879/// \param SS if non-NULL, the nested-name-specifier that precedes
880/// this template name.
881///
882/// \param TemplateKWLoc if valid, specifies that this template-id
883/// annotation was preceded by the 'template' keyword and gives the
884/// location of that keyword. If invalid (the default), then this
885/// template-id was not preceded by a 'template' keyword.
886///
887/// \param AllowTypeAnnotation if true (the default), then a
888/// simple-template-id that refers to a class template, template
889/// template parameter, or other template that produces a type will be
890/// replaced with a type annotation token. Otherwise, the
891/// simple-template-id is always replaced with a template-id
892/// annotation token.
893///
894/// If an unrecoverable parse error occurs and no annotation token can be
895/// formed, this function returns true.
896///
897bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
898 CXXScopeSpec &SS,
899 SourceLocation TemplateKWLoc,
900 UnqualifiedId &TemplateName,
901 bool AllowTypeAnnotation) {
902 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
903 assert(Template && Tok.is(tok::less) &&
904 "Parser isn't at the beginning of a template-id");
905
906 // Consume the template-name.
907 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
908
909 // Parse the enclosed template argument list.
910 SourceLocation LAngleLoc, RAngleLoc;
911 TemplateArgList TemplateArgs;
912 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
913 TemplateNameLoc,
914 SS, false, LAngleLoc,
915 TemplateArgs,
916 RAngleLoc);
917
918 if (Invalid) {
919 // If we failed to parse the template ID but skipped ahead to a >, we're not
920 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000921 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000922 return true;
923 }
924
925 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
926
927 // Build the annotation token.
928 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
929 TypeResult Type
930 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
931 Template, TemplateNameLoc,
932 LAngleLoc, TemplateArgsPtr, RAngleLoc);
933 if (Type.isInvalid()) {
934 // If we failed to parse the template ID but skipped ahead to a >, we're not
935 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000936 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000937 return true;
938 }
939
940 Tok.setKind(tok::annot_typename);
941 setTypeAnnotation(Tok, Type.get());
942 if (SS.isNotEmpty())
943 Tok.setLocation(SS.getBeginLoc());
944 else if (TemplateKWLoc.isValid())
945 Tok.setLocation(TemplateKWLoc);
946 else
947 Tok.setLocation(TemplateNameLoc);
948 } else {
949 // Build a template-id annotation token that can be processed
950 // later.
951 Tok.setKind(tok::annot_template_id);
952 TemplateIdAnnotation *TemplateId
953 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
954 TemplateId->TemplateNameLoc = TemplateNameLoc;
955 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
956 TemplateId->Name = TemplateName.Identifier;
957 TemplateId->Operator = OO_None;
958 } else {
Craig Topper161e4db2014-05-21 06:02:52 +0000959 TemplateId->Name = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000960 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
961 }
962 TemplateId->SS = SS;
963 TemplateId->TemplateKWLoc = TemplateKWLoc;
964 TemplateId->Template = Template;
965 TemplateId->Kind = TNK;
966 TemplateId->LAngleLoc = LAngleLoc;
967 TemplateId->RAngleLoc = RAngleLoc;
968 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
969 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
970 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
971 Tok.setAnnotationValue(TemplateId);
972 if (TemplateKWLoc.isValid())
973 Tok.setLocation(TemplateKWLoc);
974 else
975 Tok.setLocation(TemplateNameLoc);
976 }
977
978 // Common fields for the annotation token
979 Tok.setAnnotationEndLoc(RAngleLoc);
980
981 // In case the tokens were cached, have Preprocessor replace them with the
982 // annotation token.
983 PP.AnnotateCachedTokens(Tok);
984 return false;
985}
986
987/// \brief Replaces a template-id annotation token with a type
988/// annotation token.
989///
990/// If there was a failure when forming the type from the template-id,
991/// a type annotation token will still be created, but will have a
992/// NULL type pointer to signify an error.
993void Parser::AnnotateTemplateIdTokenAsType() {
994 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
995
996 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
997 assert((TemplateId->Kind == TNK_Type_template ||
998 TemplateId->Kind == TNK_Dependent_template_name) &&
999 "Only works for type and dependent templates");
1000
1001 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1002 TemplateId->NumArgs);
1003
1004 TypeResult Type
1005 = Actions.ActOnTemplateIdType(TemplateId->SS,
1006 TemplateId->TemplateKWLoc,
1007 TemplateId->Template,
1008 TemplateId->TemplateNameLoc,
1009 TemplateId->LAngleLoc,
1010 TemplateArgsPtr,
1011 TemplateId->RAngleLoc);
1012 // Create the new "type" annotation token.
1013 Tok.setKind(tok::annot_typename);
1014 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
1015 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1016 Tok.setLocation(TemplateId->SS.getBeginLoc());
1017 // End location stays the same
1018
1019 // Replace the template-id annotation token, and possible the scope-specifier
1020 // that precedes it, with the typename annotation token.
1021 PP.AnnotateCachedTokens(Tok);
1022}
1023
1024/// \brief Determine whether the given token can end a template argument.
1025static bool isEndOfTemplateArgument(Token Tok) {
1026 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
1027 Tok.is(tok::greatergreater);
1028}
1029
1030/// \brief Parse a C++ template template argument.
1031ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1032 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1033 !Tok.is(tok::annot_cxxscope))
1034 return ParsedTemplateArgument();
1035
1036 // C++0x [temp.arg.template]p1:
1037 // A template-argument for a template template-parameter shall be the name
1038 // of a class template or an alias template, expressed as id-expression.
1039 //
1040 // We parse an id-expression that refers to a class template or alias
1041 // template. The grammar we parse is:
1042 //
1043 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1044 //
1045 // followed by a token that terminates a template argument, such as ',',
1046 // '>', or (in some cases) '>>'.
1047 CXXScopeSpec SS; // nested-name-specifier, if present
1048 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1049 /*EnteringContext=*/false);
1050
1051 ParsedTemplateArgument Result;
1052 SourceLocation EllipsisLoc;
1053 if (SS.isSet() && Tok.is(tok::kw_template)) {
1054 // Parse the optional 'template' keyword following the
1055 // nested-name-specifier.
1056 SourceLocation TemplateKWLoc = ConsumeToken();
1057
1058 if (Tok.is(tok::identifier)) {
1059 // We appear to have a dependent template name.
1060 UnqualifiedId Name;
1061 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1062 ConsumeToken(); // the identifier
Alp Toker094e5212014-01-05 03:27:11 +00001063
1064 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1065
Faisal Vali6a79ca12013-06-08 19:39:00 +00001066 // If the next token signals the end of a template argument,
1067 // then we have a dependent template name that could be a template
1068 // template argument.
1069 TemplateTy Template;
1070 if (isEndOfTemplateArgument(Tok) &&
1071 Actions.ActOnDependentTemplateName(getCurScope(),
1072 SS, TemplateKWLoc, Name,
1073 /*ObjectType=*/ ParsedType(),
1074 /*EnteringContext=*/false,
1075 Template))
1076 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1077 }
1078 } else if (Tok.is(tok::identifier)) {
1079 // We may have a (non-dependent) template name.
1080 TemplateTy Template;
1081 UnqualifiedId Name;
1082 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1083 ConsumeToken(); // the identifier
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001084
1085 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001086
1087 if (isEndOfTemplateArgument(Tok)) {
1088 bool MemberOfUnknownSpecialization;
1089 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1090 /*hasTemplateKeyword=*/false,
1091 Name,
1092 /*ObjectType=*/ ParsedType(),
1093 /*EnteringContext=*/false,
1094 Template,
1095 MemberOfUnknownSpecialization);
1096 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1097 // We have an id-expression that refers to a class template or
1098 // (C++0x) alias template.
1099 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1100 }
1101 }
1102 }
1103
1104 // If this is a pack expansion, build it as such.
1105 if (EllipsisLoc.isValid() && !Result.isInvalid())
1106 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1107
1108 return Result;
1109}
1110
1111/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1112///
1113/// template-argument: [C++ 14.2]
1114/// constant-expression
1115/// type-id
1116/// id-expression
1117ParsedTemplateArgument Parser::ParseTemplateArgument() {
1118 // C++ [temp.arg]p2:
1119 // In a template-argument, an ambiguity between a type-id and an
1120 // expression is resolved to a type-id, regardless of the form of
1121 // the corresponding template-parameter.
1122 //
1123 // Therefore, we initially try to parse a type-id.
1124 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1125 SourceLocation Loc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00001126 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001127 Declarator::TemplateTypeArgContext);
1128 if (TypeArg.isInvalid())
1129 return ParsedTemplateArgument();
1130
1131 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1132 TypeArg.get().getAsOpaquePtr(),
1133 Loc);
1134 }
1135
1136 // Try to parse a template template argument.
1137 {
1138 TentativeParsingAction TPA(*this);
1139
1140 ParsedTemplateArgument TemplateTemplateArgument
1141 = ParseTemplateTemplateArgument();
1142 if (!TemplateTemplateArgument.isInvalid()) {
1143 TPA.Commit();
1144 return TemplateTemplateArgument;
1145 }
1146
1147 // Revert this tentative parse to parse a non-type template argument.
1148 TPA.Revert();
1149 }
1150
1151 // Parse a non-type template argument.
1152 SourceLocation Loc = Tok.getLocation();
1153 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1154 if (ExprArg.isInvalid() || !ExprArg.get())
1155 return ParsedTemplateArgument();
1156
1157 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001158 ExprArg.get(), Loc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001159}
1160
1161/// \brief Determine whether the current tokens can only be parsed as a
1162/// template argument list (starting with the '<') and never as a '<'
1163/// expression.
1164bool Parser::IsTemplateArgumentList(unsigned Skip) {
1165 struct AlwaysRevertAction : TentativeParsingAction {
1166 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1167 ~AlwaysRevertAction() { Revert(); }
1168 } Tentative(*this);
1169
1170 while (Skip) {
1171 ConsumeToken();
1172 --Skip;
1173 }
1174
1175 // '<'
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001176 if (!TryConsumeToken(tok::less))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001177 return false;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001178
1179 // An empty template argument list.
1180 if (Tok.is(tok::greater))
1181 return true;
1182
1183 // See whether we have declaration specifiers, which indicate a type.
Richard Smithee390432014-05-16 01:56:53 +00001184 while (isCXXDeclarationSpecifier() == TPResult::True)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001185 ConsumeToken();
1186
1187 // If we have a '>' or a ',' then this is a template argument list.
1188 return Tok.is(tok::greater) || Tok.is(tok::comma);
1189}
1190
1191/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1192/// (C++ [temp.names]). Returns true if there was an error.
1193///
1194/// template-argument-list: [C++ 14.2]
1195/// template-argument
1196/// template-argument-list ',' template-argument
1197bool
1198Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1199 // Template argument lists are constant-evaluation contexts.
1200 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +00001201 ColonProtectionRAIIObject ColonProtection(*this, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001202
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001203 do {
Faisal Vali6a79ca12013-06-08 19:39:00 +00001204 ParsedTemplateArgument Arg = ParseTemplateArgument();
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001205 SourceLocation EllipsisLoc;
1206 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001207 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001208
1209 if (Arg.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001210 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001211 return true;
1212 }
1213
1214 // Save this template argument.
1215 TemplateArgs.push_back(Arg);
1216
1217 // If the next token is a comma, consume it and keep reading
1218 // arguments.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001219 } while (TryConsumeToken(tok::comma));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001220
1221 return false;
1222}
1223
1224/// \brief Parse a C++ explicit template instantiation
1225/// (C++ [temp.explicit]).
1226///
1227/// explicit-instantiation:
1228/// 'extern' [opt] 'template' declaration
1229///
1230/// Note that the 'extern' is a GNU extension and C++11 feature.
1231Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1232 SourceLocation ExternLoc,
1233 SourceLocation TemplateLoc,
1234 SourceLocation &DeclEnd,
1235 AccessSpecifier AS) {
1236 // This isn't really required here.
1237 ParsingDeclRAIIObject
1238 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1239
1240 return ParseSingleDeclarationAfterTemplate(Context,
1241 ParsedTemplateInfo(ExternLoc,
1242 TemplateLoc),
1243 ParsingTemplateParams,
1244 DeclEnd, AS);
1245}
1246
1247SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1248 if (TemplateParams)
1249 return getTemplateParamsRange(TemplateParams->data(),
1250 TemplateParams->size());
1251
1252 SourceRange R(TemplateLoc);
1253 if (ExternLoc.isValid())
1254 R.setBegin(ExternLoc);
1255 return R;
1256}
1257
Richard Smithe40f2ba2013-08-07 21:41:30 +00001258void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1259 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001260}
1261
1262/// \brief Late parse a C++ function template in Microsoft mode.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001263void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
David Majnemerf0a84f22013-08-16 08:29:13 +00001264 if (!LPT.D)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001265 return;
1266
1267 // Get the FunctionDecl.
Alp Tokera2794f92014-01-22 07:29:52 +00001268 FunctionDecl *FunD = LPT.D->getAsFunction();
Faisal Vali6a79ca12013-06-08 19:39:00 +00001269 // Track template parameter depth.
1270 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1271
1272 // To restore the context after late parsing.
1273 Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
1274
1275 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1276
1277 // Get the list of DeclContexts to reenter.
1278 SmallVector<DeclContext*, 4> DeclContextsToReenter;
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001279 DeclContext *DD = FunD;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001280 while (DD && !DD->isTranslationUnit()) {
1281 DeclContextsToReenter.push_back(DD);
1282 DD = DD->getLexicalParent();
1283 }
1284
1285 // Reenter template scopes from outermost to innermost.
Craig Topper61ac9062013-07-08 03:55:09 +00001286 SmallVectorImpl<DeclContext *>::reverse_iterator II =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001287 DeclContextsToReenter.rbegin();
1288 for (; II != DeclContextsToReenter.rend(); ++II) {
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001289 TemplateParamScopeStack.push_back(new ParseScope(this,
1290 Scope::TemplateParamScope));
1291 unsigned NumParamLists =
1292 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1293 CurTemplateDepthTracker.addDepth(NumParamLists);
1294 if (*II != FunD) {
1295 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1296 Actions.PushDeclContext(Actions.getCurScope(), *II);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001297 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001298 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001299
Richard Smithe40f2ba2013-08-07 21:41:30 +00001300 assert(!LPT.Toks.empty() && "Empty body!");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001301
1302 // Append the current token at the end of the new token stream so that it
1303 // doesn't get lost.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001304 LPT.Toks.push_back(Tok);
1305 PP.EnterTokenStream(LPT.Toks.data(), LPT.Toks.size(), true, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001306
1307 // Consume the previously pushed token.
1308 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1309 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1310 && "Inline method not starting with '{', ':' or 'try'");
1311
1312 // Parse the method body. Function body parsing code is similar enough
1313 // to be re-used for method bodies as well.
1314 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1315
1316 // Recreate the containing function DeclContext.
1317 Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FunD));
1318
1319 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1320
1321 if (Tok.is(tok::kw_try)) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00001322 ParseFunctionTryBlock(LPT.D, FnScope);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001323 } else {
1324 if (Tok.is(tok::colon))
Richard Smithe40f2ba2013-08-07 21:41:30 +00001325 ParseConstructorInitializer(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001326 else
Richard Smithe40f2ba2013-08-07 21:41:30 +00001327 Actions.ActOnDefaultCtorInitializers(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001328
1329 if (Tok.is(tok::l_brace)) {
Alp Tokera2794f92014-01-22 07:29:52 +00001330 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1331 cast<FunctionTemplateDecl>(LPT.D)
1332 ->getTemplateParameters()
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001333 ->getDepth() == TemplateParameterDepth - 1) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +00001334 "TemplateParameterDepth should be greater than the depth of "
1335 "current template being instantiated!");
Richard Smithe40f2ba2013-08-07 21:41:30 +00001336 ParseFunctionStatementBody(LPT.D, FnScope);
1337 Actions.UnmarkAsLateParsedTemplate(FunD);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001338 } else
Craig Topper161e4db2014-05-21 06:02:52 +00001339 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001340 }
1341
1342 // Exit scopes.
1343 FnScope.Exit();
Craig Topper61ac9062013-07-08 03:55:09 +00001344 SmallVectorImpl<ParseScope *>::reverse_iterator I =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001345 TemplateParamScopeStack.rbegin();
1346 for (; I != TemplateParamScopeStack.rend(); ++I)
1347 delete *I;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001348}
1349
1350/// \brief Lex a delayed template function for late parsing.
1351void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1352 tok::TokenKind kind = Tok.getKind();
1353 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1354 // Consume everything up to (and including) the matching right brace.
1355 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1356 }
1357
1358 // If we're in a function-try-block, we need to store all the catch blocks.
1359 if (kind == tok::kw_try) {
1360 while (Tok.is(tok::kw_catch)) {
1361 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1362 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1363 }
1364 }
1365}