blob: f73b1b41bd361d16e470accada11198e9a857966 [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
Aaron Ballmane7c544d2014-08-04 20:28:35 +0000169 if (Tok.is(tok::kw_static_assert)) {
170 // A static_assert declaration may not be templated.
171 Diag(Tok.getLocation(), diag::err_templated_invalid_declaration)
172 << TemplateInfo.getSourceRange();
173 // Parse the static_assert declaration to improve error recovery.
174 return ParseStaticAssertDeclaration(DeclEnd);
175 }
176
Faisal Vali6a79ca12013-06-08 19:39:00 +0000177 if (Context == Declarator::MemberContext) {
178 // We are parsing a member template.
179 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
180 &DiagsFromTParams);
Craig Topper161e4db2014-05-21 06:02:52 +0000181 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000182 }
183
184 ParsedAttributesWithRange prefixAttrs(AttrFactory);
185 MaybeParseCXX11Attributes(prefixAttrs);
186
187 if (Tok.is(tok::kw_using))
188 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
189 prefixAttrs);
190
191 // Parse the declaration specifiers, stealing any diagnostics from
192 // the template parameters.
193 ParsingDeclSpec DS(*this, &DiagsFromTParams);
194
195 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
196 getDeclSpecContextFromDeclaratorContext(Context));
197
198 if (Tok.is(tok::semi)) {
199 ProhibitAttributes(prefixAttrs);
200 DeclEnd = ConsumeToken();
201 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
202 getCurScope(), AS, DS,
203 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
204 : MultiTemplateParamsArg(),
205 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation);
206 DS.complete(Decl);
207 return Decl;
208 }
209
210 // Move the attributes from the prefix into the DS.
211 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
212 ProhibitAttributes(prefixAttrs);
213 else
214 DS.takeAttributesFrom(prefixAttrs);
215
216 // Parse the declarator.
217 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
218 ParseDeclarator(DeclaratorInfo);
219 // Error parsing the declarator?
220 if (!DeclaratorInfo.hasName()) {
221 // If so, skip until the semi-colon or a }.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000222 SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000223 if (Tok.is(tok::semi))
224 ConsumeToken();
Craig Topper161e4db2014-05-21 06:02:52 +0000225 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000226 }
227
228 LateParsedAttrList LateParsedAttrs(true);
229 if (DeclaratorInfo.isFunctionDeclarator())
230 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
231
232 if (DeclaratorInfo.isFunctionDeclarator() &&
233 isStartOfFunctionDefinition(DeclaratorInfo)) {
234 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
235 // Recover by ignoring the 'typedef'. This was probably supposed to be
236 // the 'typename' keyword, which we should have already suggested adding
237 // if it's appropriate.
238 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
239 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
240 DS.ClearStorageClassSpecs();
241 }
Larisse Voufo725de3e2013-06-21 00:08:46 +0000242
243 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) {
244 if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) {
245 // If the declarator-id is not a template-id, issue a diagnostic and
246 // recover by ignoring the 'template' keyword.
247 Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000248 return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(),
249 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000250 } else {
251 SourceLocation LAngleLoc
252 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000253 Diag(DeclaratorInfo.getIdentifierLoc(),
Larisse Voufo725de3e2013-06-21 00:08:46 +0000254 diag::err_explicit_instantiation_with_definition)
Larisse Voufo39a1e502013-08-06 01:03:05 +0000255 << SourceRange(TemplateInfo.TemplateLoc)
256 << FixItHint::CreateInsertion(LAngleLoc, "<>");
Larisse Voufo725de3e2013-06-21 00:08:46 +0000257
Larisse Voufo39a1e502013-08-06 01:03:05 +0000258 // Recover as if it were an explicit specialization.
Larisse Voufob9bbaba2013-06-22 13:56:11 +0000259 TemplateParameterLists FakedParamLists;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000260 FakedParamLists.push_back(Actions.ActOnTemplateParameterList(
Craig Topper161e4db2014-05-21 06:02:52 +0000261 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr,
262 0, LAngleLoc));
Larisse Voufo725de3e2013-06-21 00:08:46 +0000263
Larisse Voufo39a1e502013-08-06 01:03:05 +0000264 return ParseFunctionDefinition(
265 DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists,
266 /*isSpecialization=*/true,
267 /*LastParamListWasEmpty=*/true),
268 &LateParsedAttrs);
Larisse Voufo725de3e2013-06-21 00:08:46 +0000269 }
270 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000271 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
Larisse Voufo39a1e502013-08-06 01:03:05 +0000272 &LateParsedAttrs);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000273 }
274
275 // Parse this declaration.
276 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
277 TemplateInfo);
278
279 if (Tok.is(tok::comma)) {
280 Diag(Tok, diag::err_multiple_template_declarators)
281 << (int)TemplateInfo.Kind;
Alexey Bataevee6507d2013-11-18 08:17:37 +0000282 SkipUntil(tok::semi);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000283 return ThisDecl;
284 }
285
286 // Eat the semi colon after the declaration.
287 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
288 if (LateParsedAttrs.size() > 0)
289 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
290 DeclaratorInfo.complete(ThisDecl);
291 return ThisDecl;
292}
293
294/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
295/// angle brackets. Depth is the depth of this template-parameter-list, which
296/// is the number of template headers directly enclosing this template header.
297/// TemplateParams is the current list of template parameters we're building.
298/// The template parameter we parse will be added to this list. LAngleLoc and
299/// RAngleLoc will receive the positions of the '<' and '>', respectively,
300/// that enclose this template parameter list.
301///
302/// \returns true if an error occurred, false otherwise.
303bool Parser::ParseTemplateParameters(unsigned Depth,
304 SmallVectorImpl<Decl*> &TemplateParams,
305 SourceLocation &LAngleLoc,
306 SourceLocation &RAngleLoc) {
307 // Get the template parameter list.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000308 if (!TryConsumeToken(tok::less, LAngleLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000309 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
310 return true;
311 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000312
313 // Try to parse the template parameter list.
314 bool Failed = false;
315 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
316 Failed = ParseTemplateParameterList(Depth, TemplateParams);
317
318 if (Tok.is(tok::greatergreater)) {
319 // No diagnostic required here: a template-parameter-list can only be
320 // followed by a declaration or, for a template template parameter, the
321 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
322 // This matters for elegant diagnosis of:
323 // template<template<typename>> struct S;
324 Tok.setKind(tok::greater);
325 RAngleLoc = Tok.getLocation();
326 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
Alp Toker383d2c42014-01-01 03:08:43 +0000327 } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) {
328 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000329 return true;
330 }
331 return false;
332}
333
334/// ParseTemplateParameterList - Parse a template parameter list. If
335/// the parsing fails badly (i.e., closing bracket was left out), this
336/// will try to put the token stream in a reasonable position (closing
337/// a statement, etc.) and return false.
338///
339/// template-parameter-list: [C++ temp]
340/// template-parameter
341/// template-parameter-list ',' template-parameter
342bool
343Parser::ParseTemplateParameterList(unsigned Depth,
344 SmallVectorImpl<Decl*> &TemplateParams) {
345 while (1) {
346 if (Decl *TmpParam
347 = ParseTemplateParameter(Depth, TemplateParams.size())) {
348 TemplateParams.push_back(TmpParam);
349 } else {
350 // If we failed to parse a template parameter, skip until we find
351 // a comma or closing brace.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000352 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
353 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000354 }
355
356 // Did we find a comma or the end of the template parameter list?
357 if (Tok.is(tok::comma)) {
358 ConsumeToken();
359 } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
360 // Don't consume this... that's done by template parser.
361 break;
362 } else {
363 // Somebody probably forgot to close the template. Skip ahead and
364 // try to get out of the expression. This error is currently
365 // subsumed by whatever goes on in ParseTemplateParameter.
366 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000367 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
368 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000369 return false;
370 }
371 }
372 return true;
373}
374
375/// \brief Determine whether the parser is at the start of a template
376/// type parameter.
377bool Parser::isStartOfTemplateTypeParameter() {
378 if (Tok.is(tok::kw_class)) {
379 // "class" may be the start of an elaborated-type-specifier or a
380 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
381 switch (NextToken().getKind()) {
382 case tok::equal:
383 case tok::comma:
384 case tok::greater:
385 case tok::greatergreater:
386 case tok::ellipsis:
387 return true;
388
389 case tok::identifier:
390 // This may be either a type-parameter or an elaborated-type-specifier.
391 // We have to look further.
392 break;
393
394 default:
395 return false;
396 }
397
398 switch (GetLookAheadToken(2).getKind()) {
399 case tok::equal:
400 case tok::comma:
401 case tok::greater:
402 case tok::greatergreater:
403 return true;
404
405 default:
406 return false;
407 }
408 }
409
410 if (Tok.isNot(tok::kw_typename))
411 return false;
412
413 // C++ [temp.param]p2:
414 // There is no semantic difference between class and typename in a
415 // template-parameter. typename followed by an unqualified-id
416 // names a template type parameter. typename followed by a
417 // qualified-id denotes the type in a non-type
418 // parameter-declaration.
419 Token Next = NextToken();
420
421 // If we have an identifier, skip over it.
422 if (Next.getKind() == tok::identifier)
423 Next = GetLookAheadToken(2);
424
425 switch (Next.getKind()) {
426 case tok::equal:
427 case tok::comma:
428 case tok::greater:
429 case tok::greatergreater:
430 case tok::ellipsis:
431 return true;
432
433 default:
434 return false;
435 }
436}
437
438/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
439///
440/// template-parameter: [C++ temp.param]
441/// type-parameter
442/// parameter-declaration
443///
444/// type-parameter: (see below)
445/// 'class' ...[opt] identifier[opt]
446/// 'class' identifier[opt] '=' type-id
447/// 'typename' ...[opt] identifier[opt]
448/// 'typename' identifier[opt] '=' type-id
449/// 'template' '<' template-parameter-list '>'
450/// 'class' ...[opt] identifier[opt]
451/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
452/// = id-expression
453Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
454 if (isStartOfTemplateTypeParameter())
455 return ParseTypeParameter(Depth, Position);
456
457 if (Tok.is(tok::kw_template))
458 return ParseTemplateTemplateParameter(Depth, Position);
459
460 // If it's none of the above, then it must be a parameter declaration.
461 // NOTE: This will pick up errors in the closure of the template parameter
462 // list (e.g., template < ; Check here to implement >> style closures.
463 return ParseNonTypeTemplateParameter(Depth, Position);
464}
465
466/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
467/// Other kinds of template parameters are parsed in
468/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
469///
470/// type-parameter: [C++ temp.param]
471/// 'class' ...[opt][C++0x] identifier[opt]
472/// 'class' identifier[opt] '=' type-id
473/// 'typename' ...[opt][C++0x] identifier[opt]
474/// 'typename' identifier[opt] '=' type-id
475Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
476 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
477 "A type-parameter starts with 'class' or 'typename'");
478
479 // Consume the 'class' or 'typename' keyword.
480 bool TypenameKeyword = Tok.is(tok::kw_typename);
481 SourceLocation KeyLoc = ConsumeToken();
482
483 // Grab the ellipsis (if given).
Faisal Vali6a79ca12013-06-08 19:39:00 +0000484 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000485 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000486 Diag(EllipsisLoc,
487 getLangOpts().CPlusPlus11
488 ? diag::warn_cxx98_compat_variadic_templates
489 : diag::ext_variadic_templates);
490 }
491
492 // Grab the template parameter name (if given)
493 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000494 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000495 if (Tok.is(tok::identifier)) {
496 ParamName = Tok.getIdentifierInfo();
497 NameLoc = ConsumeToken();
498 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
499 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
500 // Unnamed template parameter. Don't have to do anything here, just
501 // don't consume this token.
502 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000503 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000504 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000505 }
506
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000507 // Recover from misplaced ellipsis.
508 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
509 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
510 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
511
Faisal Vali6a79ca12013-06-08 19:39:00 +0000512 // Grab a default argument (if available).
513 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
514 // we introduce the type parameter into the local scope.
515 SourceLocation EqualLoc;
516 ParsedType DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000517 if (TryConsumeToken(tok::equal, EqualLoc))
Craig Topper161e4db2014-05-21 06:02:52 +0000518 DefaultArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +0000519 Declarator::TemplateTypeArgContext).get();
Faisal Vali6a79ca12013-06-08 19:39:00 +0000520
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000521 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc,
522 KeyLoc, ParamName, NameLoc, Depth, Position,
523 EqualLoc, DefaultArg);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000524}
525
526/// ParseTemplateTemplateParameter - Handle the parsing of template
527/// template parameters.
528///
529/// type-parameter: [C++ temp.param]
Richard Smith78e1ca62014-06-16 15:51:22 +0000530/// 'template' '<' template-parameter-list '>' type-parameter-key
Faisal Vali6a79ca12013-06-08 19:39:00 +0000531/// ...[opt] identifier[opt]
Richard Smith78e1ca62014-06-16 15:51:22 +0000532/// 'template' '<' template-parameter-list '>' type-parameter-key
533/// identifier[opt] = id-expression
534/// type-parameter-key:
535/// 'class'
536/// 'typename' [C++1z]
Faisal Vali6a79ca12013-06-08 19:39:00 +0000537Decl *
538Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
539 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
540
541 // Handle the template <...> part.
542 SourceLocation TemplateLoc = ConsumeToken();
543 SmallVector<Decl*,8> TemplateParams;
544 SourceLocation LAngleLoc, RAngleLoc;
545 {
546 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
547 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
548 RAngleLoc)) {
Craig Topper161e4db2014-05-21 06:02:52 +0000549 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000550 }
551 }
552
Richard Smith78e1ca62014-06-16 15:51:22 +0000553 // Provide an ExtWarn if the C++1z feature of using 'typename' here is used.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000554 // Generate a meaningful error if the user forgot to put class before the
555 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
Richard Smith78e1ca62014-06-16 15:51:22 +0000556 // or greater appear immediately or after 'struct'. In the latter case,
557 // replace the keyword with 'class'.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000558 if (!TryConsumeToken(tok::kw_class)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000559 bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
Richard Smith78e1ca62014-06-16 15:51:22 +0000560 const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok;
561 if (Tok.is(tok::kw_typename)) {
562 Diag(Tok.getLocation(),
563 getLangOpts().CPlusPlus1z
564 ? diag::warn_cxx1y_compat_template_template_param_typename
565 : diag::ext_template_template_param_typename)
566 << (!getLangOpts().CPlusPlus1z
567 ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
568 : FixItHint());
569 } else if (Next.is(tok::identifier) || Next.is(tok::comma) ||
570 Next.is(tok::greater) || Next.is(tok::greatergreater) ||
571 Next.is(tok::ellipsis)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000572 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
573 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
574 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
Richard Smith78e1ca62014-06-16 15:51:22 +0000575 } else
Faisal Vali6a79ca12013-06-08 19:39:00 +0000576 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
577
578 if (Replace)
579 ConsumeToken();
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000580 }
Faisal Vali6a79ca12013-06-08 19:39:00 +0000581
582 // Parse the ellipsis, if given.
583 SourceLocation EllipsisLoc;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000584 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000585 Diag(EllipsisLoc,
586 getLangOpts().CPlusPlus11
587 ? diag::warn_cxx98_compat_variadic_templates
588 : diag::ext_variadic_templates);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000589
590 // Get the identifier, if given.
591 SourceLocation NameLoc;
Craig Topper161e4db2014-05-21 06:02:52 +0000592 IdentifierInfo *ParamName = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000593 if (Tok.is(tok::identifier)) {
594 ParamName = Tok.getIdentifierInfo();
595 NameLoc = ConsumeToken();
596 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
597 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
598 // Unnamed template parameter. Don't have to do anything here, just
599 // don't consume this token.
600 } else {
Alp Tokerec543272013-12-24 09:48:30 +0000601 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Craig Topper161e4db2014-05-21 06:02:52 +0000602 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000603 }
604
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000605 // Recover from misplaced ellipsis.
606 bool AlreadyHasEllipsis = EllipsisLoc.isValid();
607 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
608 DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true);
609
Faisal Vali6a79ca12013-06-08 19:39:00 +0000610 TemplateParameterList *ParamList =
611 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
612 TemplateLoc, LAngleLoc,
613 TemplateParams.data(),
614 TemplateParams.size(),
615 RAngleLoc);
616
617 // Grab a default argument (if available).
618 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
619 // we introduce the template parameter into the local scope.
620 SourceLocation EqualLoc;
621 ParsedTemplateArgument DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000622 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000623 DefaultArg = ParseTemplateTemplateArgument();
624 if (DefaultArg.isInvalid()) {
625 Diag(Tok.getLocation(),
626 diag::err_default_template_template_parameter_not_template);
Alexey Bataevee6507d2013-11-18 08:17:37 +0000627 SkipUntil(tok::comma, tok::greater, tok::greatergreater,
628 StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000629 }
630 }
631
632 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
633 ParamList, EllipsisLoc,
634 ParamName, NameLoc, Depth,
635 Position, EqualLoc, DefaultArg);
636}
637
638/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
639/// template parameters (e.g., in "template<int Size> class array;").
640///
641/// template-parameter:
642/// ...
643/// parameter-declaration
644Decl *
645Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
646 // Parse the declaration-specifiers (i.e., the type).
647 // FIXME: The type should probably be restricted in some way... Not all
648 // declarators (parts of declarators?) are accepted for parameters.
649 DeclSpec DS(AttrFactory);
650 ParseDeclarationSpecifiers(DS);
651
652 // Parse this as a typename.
653 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
654 ParseDeclarator(ParamDecl);
655 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
656 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
Craig Topper161e4db2014-05-21 06:02:52 +0000657 return nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000658 }
659
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000660 // Recover from misplaced ellipsis.
661 SourceLocation EllipsisLoc;
662 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
663 DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl);
664
Faisal Vali6a79ca12013-06-08 19:39:00 +0000665 // If there is a default value, parse it.
666 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
667 // we introduce the template parameter into the local scope.
668 SourceLocation EqualLoc;
669 ExprResult DefaultArg;
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000670 if (TryConsumeToken(tok::equal, EqualLoc)) {
Faisal Vali6a79ca12013-06-08 19:39:00 +0000671 // C++ [temp.param]p15:
672 // When parsing a default template-argument for a non-type
673 // template-parameter, the first non-nested > is taken as the
674 // end of the template-parameter-list rather than a greater-than
675 // operator.
676 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
677 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
678
679 DefaultArg = ParseAssignmentExpression();
680 if (DefaultArg.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +0000681 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000682 }
683
684 // Create the parameter.
685 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
686 Depth, Position, EqualLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000687 DefaultArg.get());
Faisal Vali6a79ca12013-06-08 19:39:00 +0000688}
689
Nikola Smiljanic69fdc9f2014-06-06 02:58:59 +0000690void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc,
691 SourceLocation CorrectLoc,
692 bool AlreadyHasEllipsis,
693 bool IdentifierHasName) {
694 FixItHint Insertion;
695 if (!AlreadyHasEllipsis)
696 Insertion = FixItHint::CreateInsertion(CorrectLoc, "...");
697 Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration)
698 << FixItHint::CreateRemoval(EllipsisLoc) << Insertion
699 << !IdentifierHasName;
700}
701
702void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc,
703 Declarator &D) {
704 assert(EllipsisLoc.isValid());
705 bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid();
706 if (!AlreadyHasEllipsis)
707 D.setEllipsisLoc(EllipsisLoc);
708 DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(),
709 AlreadyHasEllipsis, D.hasName());
710}
711
Faisal Vali6a79ca12013-06-08 19:39:00 +0000712/// \brief Parses a '>' at the end of a template list.
713///
714/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
715/// to determine if these tokens were supposed to be a '>' followed by
716/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
717///
718/// \param RAngleLoc the location of the consumed '>'.
719///
720/// \param ConsumeLastToken if true, the '>' is not consumed.
Serge Pavlovb716b3c2013-08-10 05:54:47 +0000721///
722/// \returns true, if current token does not start with '>', false otherwise.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000723bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
724 bool ConsumeLastToken) {
725 // What will be left once we've consumed the '>'.
726 tok::TokenKind RemainingToken;
727 const char *ReplacementStr = "> >";
728
729 switch (Tok.getKind()) {
730 default:
Alp Toker383d2c42014-01-01 03:08:43 +0000731 Diag(Tok.getLocation(), diag::err_expected) << tok::greater;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000732 return true;
733
734 case tok::greater:
735 // Determine the location of the '>' token. Only consume this token
736 // if the caller asked us to.
737 RAngleLoc = Tok.getLocation();
738 if (ConsumeLastToken)
739 ConsumeToken();
740 return false;
741
742 case tok::greatergreater:
743 RemainingToken = tok::greater;
744 break;
745
746 case tok::greatergreatergreater:
747 RemainingToken = tok::greatergreater;
748 break;
749
750 case tok::greaterequal:
751 RemainingToken = tok::equal;
752 ReplacementStr = "> =";
753 break;
754
755 case tok::greatergreaterequal:
756 RemainingToken = tok::greaterequal;
757 break;
758 }
759
760 // This template-id is terminated by a token which starts with a '>'. Outside
761 // C++11, this is now error recovery, and in C++11, this is error recovery if
Eli Bendersky36a61932014-06-20 13:09:59 +0000762 // the token isn't '>>' or '>>>'.
763 // '>>>' is for CUDA, where this sequence of characters is parsed into
764 // tok::greatergreatergreater, rather than two separate tokens.
Faisal Vali6a79ca12013-06-08 19:39:00 +0000765
766 RAngleLoc = Tok.getLocation();
767
768 // The source range of the '>>' or '>=' at the start of the token.
769 CharSourceRange ReplacementRange =
770 CharSourceRange::getCharRange(RAngleLoc,
771 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
772 getLangOpts()));
773
774 // A hint to put a space between the '>>'s. In order to make the hint as
775 // clear as possible, we include the characters either side of the space in
776 // the replacement, rather than just inserting a space at SecondCharLoc.
777 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
778 ReplacementStr);
779
780 // A hint to put another space after the token, if it would otherwise be
781 // lexed differently.
782 FixItHint Hint2;
783 Token Next = NextToken();
784 if ((RemainingToken == tok::greater ||
785 RemainingToken == tok::greatergreater) &&
786 (Next.is(tok::greater) || Next.is(tok::greatergreater) ||
787 Next.is(tok::greatergreatergreater) || Next.is(tok::equal) ||
788 Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) ||
789 Next.is(tok::equalequal)) &&
790 areTokensAdjacent(Tok, Next))
791 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
792
793 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
Eli Bendersky36a61932014-06-20 13:09:59 +0000794 if (getLangOpts().CPlusPlus11 &&
795 (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater)))
Faisal Vali6a79ca12013-06-08 19:39:00 +0000796 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
797 else if (Tok.is(tok::greaterequal))
798 DiagId = diag::err_right_angle_bracket_equal_needs_space;
799 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
800
801 // Strip the initial '>' from the token.
802 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
803 areTokensAdjacent(Tok, Next)) {
804 // Join two adjacent '=' tokens into one, for cases like:
805 // void (*p)() = f<int>;
806 // return f<int>==p;
807 ConsumeToken();
808 Tok.setKind(tok::equalequal);
809 Tok.setLength(Tok.getLength() + 1);
810 } else {
811 Tok.setKind(RemainingToken);
812 Tok.setLength(Tok.getLength() - 1);
813 }
814 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
815 PP.getSourceManager(),
816 getLangOpts()));
817
818 if (!ConsumeLastToken) {
819 // Since we're not supposed to consume the '>' token, we need to push
820 // this token and revert the current token back to the '>'.
821 PP.EnterToken(Tok);
822 Tok.setKind(tok::greater);
823 Tok.setLength(1);
824 Tok.setLocation(RAngleLoc);
825 }
826 return false;
827}
828
829
830/// \brief Parses a template-id that after the template name has
831/// already been parsed.
832///
833/// This routine takes care of parsing the enclosed template argument
834/// list ('<' template-parameter-list [opt] '>') and placing the
835/// results into a form that can be transferred to semantic analysis.
836///
837/// \param Template the template declaration produced by isTemplateName
838///
839/// \param TemplateNameLoc the source location of the template name
840///
841/// \param SS if non-NULL, the nested-name-specifier preceding the
842/// template name.
843///
844/// \param ConsumeLastToken if true, then we will consume the last
845/// token that forms the template-id. Otherwise, we will leave the
846/// last token in the stream (e.g., so that it can be replaced with an
847/// annotation token).
848bool
849Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
850 SourceLocation TemplateNameLoc,
851 const CXXScopeSpec &SS,
852 bool ConsumeLastToken,
853 SourceLocation &LAngleLoc,
854 TemplateArgList &TemplateArgs,
855 SourceLocation &RAngleLoc) {
856 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
857
858 // Consume the '<'.
859 LAngleLoc = ConsumeToken();
860
861 // Parse the optional template-argument-list.
862 bool Invalid = false;
863 {
864 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
865 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
866 Invalid = ParseTemplateArgumentList(TemplateArgs);
867
868 if (Invalid) {
869 // Try to find the closing '>'.
Alexey Bataevee6507d2013-11-18 08:17:37 +0000870 if (ConsumeLastToken)
871 SkipUntil(tok::greater, StopAtSemi);
872 else
873 SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000874 return true;
875 }
876 }
877
878 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken);
879}
880
881/// \brief Replace the tokens that form a simple-template-id with an
882/// annotation token containing the complete template-id.
883///
884/// The first token in the stream must be the name of a template that
885/// is followed by a '<'. This routine will parse the complete
886/// simple-template-id and replace the tokens with a single annotation
887/// token with one of two different kinds: if the template-id names a
888/// type (and \p AllowTypeAnnotation is true), the annotation token is
889/// a type annotation that includes the optional nested-name-specifier
890/// (\p SS). Otherwise, the annotation token is a template-id
891/// annotation that does not include the optional
892/// nested-name-specifier.
893///
894/// \param Template the declaration of the template named by the first
895/// token (an identifier), as returned from \c Action::isTemplateName().
896///
897/// \param TNK the kind of template that \p Template
898/// refers to, as returned from \c Action::isTemplateName().
899///
900/// \param SS if non-NULL, the nested-name-specifier that precedes
901/// this template name.
902///
903/// \param TemplateKWLoc if valid, specifies that this template-id
904/// annotation was preceded by the 'template' keyword and gives the
905/// location of that keyword. If invalid (the default), then this
906/// template-id was not preceded by a 'template' keyword.
907///
908/// \param AllowTypeAnnotation if true (the default), then a
909/// simple-template-id that refers to a class template, template
910/// template parameter, or other template that produces a type will be
911/// replaced with a type annotation token. Otherwise, the
912/// simple-template-id is always replaced with a template-id
913/// annotation token.
914///
915/// If an unrecoverable parse error occurs and no annotation token can be
916/// formed, this function returns true.
917///
918bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
919 CXXScopeSpec &SS,
920 SourceLocation TemplateKWLoc,
921 UnqualifiedId &TemplateName,
922 bool AllowTypeAnnotation) {
923 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
924 assert(Template && Tok.is(tok::less) &&
925 "Parser isn't at the beginning of a template-id");
926
927 // Consume the template-name.
928 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
929
930 // Parse the enclosed template argument list.
931 SourceLocation LAngleLoc, RAngleLoc;
932 TemplateArgList TemplateArgs;
933 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
934 TemplateNameLoc,
935 SS, false, LAngleLoc,
936 TemplateArgs,
937 RAngleLoc);
938
939 if (Invalid) {
940 // If we failed to parse the template ID but skipped ahead to a >, we're not
941 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000942 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000943 return true;
944 }
945
946 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
947
948 // Build the annotation token.
949 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
950 TypeResult Type
951 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
952 Template, TemplateNameLoc,
953 LAngleLoc, TemplateArgsPtr, RAngleLoc);
954 if (Type.isInvalid()) {
955 // If we failed to parse the template ID but skipped ahead to a >, we're not
956 // going to be able to form a token annotation. Eat the '>' if present.
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000957 TryConsumeToken(tok::greater);
Faisal Vali6a79ca12013-06-08 19:39:00 +0000958 return true;
959 }
960
961 Tok.setKind(tok::annot_typename);
962 setTypeAnnotation(Tok, Type.get());
963 if (SS.isNotEmpty())
964 Tok.setLocation(SS.getBeginLoc());
965 else if (TemplateKWLoc.isValid())
966 Tok.setLocation(TemplateKWLoc);
967 else
968 Tok.setLocation(TemplateNameLoc);
969 } else {
970 // Build a template-id annotation token that can be processed
971 // later.
972 Tok.setKind(tok::annot_template_id);
973 TemplateIdAnnotation *TemplateId
974 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
975 TemplateId->TemplateNameLoc = TemplateNameLoc;
976 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
977 TemplateId->Name = TemplateName.Identifier;
978 TemplateId->Operator = OO_None;
979 } else {
Craig Topper161e4db2014-05-21 06:02:52 +0000980 TemplateId->Name = nullptr;
Faisal Vali6a79ca12013-06-08 19:39:00 +0000981 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
982 }
983 TemplateId->SS = SS;
984 TemplateId->TemplateKWLoc = TemplateKWLoc;
985 TemplateId->Template = Template;
986 TemplateId->Kind = TNK;
987 TemplateId->LAngleLoc = LAngleLoc;
988 TemplateId->RAngleLoc = RAngleLoc;
989 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
990 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
991 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
992 Tok.setAnnotationValue(TemplateId);
993 if (TemplateKWLoc.isValid())
994 Tok.setLocation(TemplateKWLoc);
995 else
996 Tok.setLocation(TemplateNameLoc);
997 }
998
999 // Common fields for the annotation token
1000 Tok.setAnnotationEndLoc(RAngleLoc);
1001
1002 // In case the tokens were cached, have Preprocessor replace them with the
1003 // annotation token.
1004 PP.AnnotateCachedTokens(Tok);
1005 return false;
1006}
1007
1008/// \brief Replaces a template-id annotation token with a type
1009/// annotation token.
1010///
1011/// If there was a failure when forming the type from the template-id,
1012/// a type annotation token will still be created, but will have a
1013/// NULL type pointer to signify an error.
1014void Parser::AnnotateTemplateIdTokenAsType() {
1015 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
1016
1017 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1018 assert((TemplateId->Kind == TNK_Type_template ||
1019 TemplateId->Kind == TNK_Dependent_template_name) &&
1020 "Only works for type and dependent templates");
1021
1022 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1023 TemplateId->NumArgs);
1024
1025 TypeResult Type
1026 = Actions.ActOnTemplateIdType(TemplateId->SS,
1027 TemplateId->TemplateKWLoc,
1028 TemplateId->Template,
1029 TemplateId->TemplateNameLoc,
1030 TemplateId->LAngleLoc,
1031 TemplateArgsPtr,
1032 TemplateId->RAngleLoc);
1033 // Create the new "type" annotation token.
1034 Tok.setKind(tok::annot_typename);
1035 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
1036 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
1037 Tok.setLocation(TemplateId->SS.getBeginLoc());
1038 // End location stays the same
1039
1040 // Replace the template-id annotation token, and possible the scope-specifier
1041 // that precedes it, with the typename annotation token.
1042 PP.AnnotateCachedTokens(Tok);
1043}
1044
1045/// \brief Determine whether the given token can end a template argument.
1046static bool isEndOfTemplateArgument(Token Tok) {
1047 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
1048 Tok.is(tok::greatergreater);
1049}
1050
1051/// \brief Parse a C++ template template argument.
1052ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1053 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1054 !Tok.is(tok::annot_cxxscope))
1055 return ParsedTemplateArgument();
1056
1057 // C++0x [temp.arg.template]p1:
1058 // A template-argument for a template template-parameter shall be the name
1059 // of a class template or an alias template, expressed as id-expression.
1060 //
1061 // We parse an id-expression that refers to a class template or alias
1062 // template. The grammar we parse is:
1063 //
1064 // nested-name-specifier[opt] template[opt] identifier ...[opt]
1065 //
1066 // followed by a token that terminates a template argument, such as ',',
1067 // '>', or (in some cases) '>>'.
1068 CXXScopeSpec SS; // nested-name-specifier, if present
1069 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1070 /*EnteringContext=*/false);
1071
1072 ParsedTemplateArgument Result;
1073 SourceLocation EllipsisLoc;
1074 if (SS.isSet() && Tok.is(tok::kw_template)) {
1075 // Parse the optional 'template' keyword following the
1076 // nested-name-specifier.
1077 SourceLocation TemplateKWLoc = ConsumeToken();
1078
1079 if (Tok.is(tok::identifier)) {
1080 // We appear to have a dependent template name.
1081 UnqualifiedId Name;
1082 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1083 ConsumeToken(); // the identifier
Alp Toker094e5212014-01-05 03:27:11 +00001084
1085 TryConsumeToken(tok::ellipsis, EllipsisLoc);
1086
Faisal Vali6a79ca12013-06-08 19:39:00 +00001087 // If the next token signals the end of a template argument,
1088 // then we have a dependent template name that could be a template
1089 // template argument.
1090 TemplateTy Template;
1091 if (isEndOfTemplateArgument(Tok) &&
1092 Actions.ActOnDependentTemplateName(getCurScope(),
1093 SS, TemplateKWLoc, Name,
1094 /*ObjectType=*/ ParsedType(),
1095 /*EnteringContext=*/false,
1096 Template))
1097 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1098 }
1099 } else if (Tok.is(tok::identifier)) {
1100 // We may have a (non-dependent) template name.
1101 TemplateTy Template;
1102 UnqualifiedId Name;
1103 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1104 ConsumeToken(); // the identifier
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001105
1106 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001107
1108 if (isEndOfTemplateArgument(Tok)) {
1109 bool MemberOfUnknownSpecialization;
1110 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1111 /*hasTemplateKeyword=*/false,
1112 Name,
1113 /*ObjectType=*/ ParsedType(),
1114 /*EnteringContext=*/false,
1115 Template,
1116 MemberOfUnknownSpecialization);
1117 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1118 // We have an id-expression that refers to a class template or
1119 // (C++0x) alias template.
1120 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
1121 }
1122 }
1123 }
1124
1125 // If this is a pack expansion, build it as such.
1126 if (EllipsisLoc.isValid() && !Result.isInvalid())
1127 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1128
1129 return Result;
1130}
1131
1132/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1133///
1134/// template-argument: [C++ 14.2]
1135/// constant-expression
1136/// type-id
1137/// id-expression
1138ParsedTemplateArgument Parser::ParseTemplateArgument() {
1139 // C++ [temp.arg]p2:
1140 // In a template-argument, an ambiguity between a type-id and an
1141 // expression is resolved to a type-id, regardless of the form of
1142 // the corresponding template-parameter.
1143 //
1144 // Therefore, we initially try to parse a type-id.
1145 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
1146 SourceLocation Loc = Tok.getLocation();
Craig Topper161e4db2014-05-21 06:02:52 +00001147 TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr,
Faisal Vali6a79ca12013-06-08 19:39:00 +00001148 Declarator::TemplateTypeArgContext);
1149 if (TypeArg.isInvalid())
1150 return ParsedTemplateArgument();
1151
1152 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1153 TypeArg.get().getAsOpaquePtr(),
1154 Loc);
1155 }
1156
1157 // Try to parse a template template argument.
1158 {
1159 TentativeParsingAction TPA(*this);
1160
1161 ParsedTemplateArgument TemplateTemplateArgument
1162 = ParseTemplateTemplateArgument();
1163 if (!TemplateTemplateArgument.isInvalid()) {
1164 TPA.Commit();
1165 return TemplateTemplateArgument;
1166 }
1167
1168 // Revert this tentative parse to parse a non-type template argument.
1169 TPA.Revert();
1170 }
1171
1172 // Parse a non-type template argument.
1173 SourceLocation Loc = Tok.getLocation();
1174 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
1175 if (ExprArg.isInvalid() || !ExprArg.get())
1176 return ParsedTemplateArgument();
1177
1178 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001179 ExprArg.get(), Loc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001180}
1181
1182/// \brief Determine whether the current tokens can only be parsed as a
1183/// template argument list (starting with the '<') and never as a '<'
1184/// expression.
1185bool Parser::IsTemplateArgumentList(unsigned Skip) {
1186 struct AlwaysRevertAction : TentativeParsingAction {
1187 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1188 ~AlwaysRevertAction() { Revert(); }
1189 } Tentative(*this);
1190
1191 while (Skip) {
1192 ConsumeToken();
1193 --Skip;
1194 }
1195
1196 // '<'
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001197 if (!TryConsumeToken(tok::less))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001198 return false;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001199
1200 // An empty template argument list.
1201 if (Tok.is(tok::greater))
1202 return true;
1203
1204 // See whether we have declaration specifiers, which indicate a type.
Richard Smithee390432014-05-16 01:56:53 +00001205 while (isCXXDeclarationSpecifier() == TPResult::True)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001206 ConsumeToken();
1207
1208 // If we have a '>' or a ',' then this is a template argument list.
1209 return Tok.is(tok::greater) || Tok.is(tok::comma);
1210}
1211
1212/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1213/// (C++ [temp.names]). Returns true if there was an error.
1214///
1215/// template-argument-list: [C++ 14.2]
1216/// template-argument
1217/// template-argument-list ',' template-argument
1218bool
1219Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
1220 // Template argument lists are constant-evaluation contexts.
1221 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +00001222 ColonProtectionRAIIObject ColonProtection(*this, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001223
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001224 do {
Faisal Vali6a79ca12013-06-08 19:39:00 +00001225 ParsedTemplateArgument Arg = ParseTemplateArgument();
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001226 SourceLocation EllipsisLoc;
1227 if (TryConsumeToken(tok::ellipsis, EllipsisLoc))
Faisal Vali6a79ca12013-06-08 19:39:00 +00001228 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001229
1230 if (Arg.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001231 SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001232 return true;
1233 }
1234
1235 // Save this template argument.
1236 TemplateArgs.push_back(Arg);
1237
1238 // If the next token is a comma, consume it and keep reading
1239 // arguments.
Alp Tokera3ebe6e2013-12-17 14:12:37 +00001240 } while (TryConsumeToken(tok::comma));
Faisal Vali6a79ca12013-06-08 19:39:00 +00001241
1242 return false;
1243}
1244
1245/// \brief Parse a C++ explicit template instantiation
1246/// (C++ [temp.explicit]).
1247///
1248/// explicit-instantiation:
1249/// 'extern' [opt] 'template' declaration
1250///
1251/// Note that the 'extern' is a GNU extension and C++11 feature.
1252Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1253 SourceLocation ExternLoc,
1254 SourceLocation TemplateLoc,
1255 SourceLocation &DeclEnd,
1256 AccessSpecifier AS) {
1257 // This isn't really required here.
1258 ParsingDeclRAIIObject
1259 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
1260
1261 return ParseSingleDeclarationAfterTemplate(Context,
1262 ParsedTemplateInfo(ExternLoc,
1263 TemplateLoc),
1264 ParsingTemplateParams,
1265 DeclEnd, AS);
1266}
1267
1268SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1269 if (TemplateParams)
1270 return getTemplateParamsRange(TemplateParams->data(),
1271 TemplateParams->size());
1272
1273 SourceRange R(TemplateLoc);
1274 if (ExternLoc.isValid())
1275 R.setBegin(ExternLoc);
1276 return R;
1277}
1278
Richard Smithe40f2ba2013-08-07 21:41:30 +00001279void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) {
1280 ((Parser *)P)->ParseLateTemplatedFuncDef(LPT);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001281}
1282
1283/// \brief Late parse a C++ function template in Microsoft mode.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001284void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) {
David Majnemerf0a84f22013-08-16 08:29:13 +00001285 if (!LPT.D)
Faisal Vali6a79ca12013-06-08 19:39:00 +00001286 return;
1287
1288 // Get the FunctionDecl.
Alp Tokera2794f92014-01-22 07:29:52 +00001289 FunctionDecl *FunD = LPT.D->getAsFunction();
Faisal Vali6a79ca12013-06-08 19:39:00 +00001290 // Track template parameter depth.
1291 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1292
1293 // To restore the context after late parsing.
1294 Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
1295
1296 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1297
1298 // Get the list of DeclContexts to reenter.
1299 SmallVector<DeclContext*, 4> DeclContextsToReenter;
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001300 DeclContext *DD = FunD;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001301 while (DD && !DD->isTranslationUnit()) {
1302 DeclContextsToReenter.push_back(DD);
1303 DD = DD->getLexicalParent();
1304 }
1305
1306 // Reenter template scopes from outermost to innermost.
Craig Topper61ac9062013-07-08 03:55:09 +00001307 SmallVectorImpl<DeclContext *>::reverse_iterator II =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001308 DeclContextsToReenter.rbegin();
1309 for (; II != DeclContextsToReenter.rend(); ++II) {
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001310 TemplateParamScopeStack.push_back(new ParseScope(this,
1311 Scope::TemplateParamScope));
1312 unsigned NumParamLists =
1313 Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II));
1314 CurTemplateDepthTracker.addDepth(NumParamLists);
1315 if (*II != FunD) {
1316 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1317 Actions.PushDeclContext(Actions.getCurScope(), *II);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001318 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001319 }
Faisal Vali6a79ca12013-06-08 19:39:00 +00001320
Richard Smithe40f2ba2013-08-07 21:41:30 +00001321 assert(!LPT.Toks.empty() && "Empty body!");
Faisal Vali6a79ca12013-06-08 19:39:00 +00001322
1323 // Append the current token at the end of the new token stream so that it
1324 // doesn't get lost.
Richard Smithe40f2ba2013-08-07 21:41:30 +00001325 LPT.Toks.push_back(Tok);
1326 PP.EnterTokenStream(LPT.Toks.data(), LPT.Toks.size(), true, false);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001327
1328 // Consume the previously pushed token.
1329 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1330 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1331 && "Inline method not starting with '{', ':' or 'try'");
1332
1333 // Parse the method body. Function body parsing code is similar enough
1334 // to be re-used for method bodies as well.
1335 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1336
1337 // Recreate the containing function DeclContext.
1338 Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FunD));
1339
1340 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
1341
1342 if (Tok.is(tok::kw_try)) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00001343 ParseFunctionTryBlock(LPT.D, FnScope);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001344 } else {
1345 if (Tok.is(tok::colon))
Richard Smithe40f2ba2013-08-07 21:41:30 +00001346 ParseConstructorInitializer(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001347 else
Richard Smithe40f2ba2013-08-07 21:41:30 +00001348 Actions.ActOnDefaultCtorInitializers(LPT.D);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001349
1350 if (Tok.is(tok::l_brace)) {
Alp Tokera2794f92014-01-22 07:29:52 +00001351 assert((!isa<FunctionTemplateDecl>(LPT.D) ||
1352 cast<FunctionTemplateDecl>(LPT.D)
1353 ->getTemplateParameters()
Hans Wennborgb6d4e8c2014-05-02 02:01:07 +00001354 ->getDepth() == TemplateParameterDepth - 1) &&
Faisal Vali6a79ca12013-06-08 19:39:00 +00001355 "TemplateParameterDepth should be greater than the depth of "
1356 "current template being instantiated!");
Richard Smithe40f2ba2013-08-07 21:41:30 +00001357 ParseFunctionStatementBody(LPT.D, FnScope);
1358 Actions.UnmarkAsLateParsedTemplate(FunD);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001359 } else
Craig Topper161e4db2014-05-21 06:02:52 +00001360 Actions.ActOnFinishFunctionBody(LPT.D, nullptr);
Faisal Vali6a79ca12013-06-08 19:39:00 +00001361 }
1362
1363 // Exit scopes.
1364 FnScope.Exit();
Craig Topper61ac9062013-07-08 03:55:09 +00001365 SmallVectorImpl<ParseScope *>::reverse_iterator I =
Faisal Vali6a79ca12013-06-08 19:39:00 +00001366 TemplateParamScopeStack.rbegin();
1367 for (; I != TemplateParamScopeStack.rend(); ++I)
1368 delete *I;
Faisal Vali6a79ca12013-06-08 19:39:00 +00001369}
1370
1371/// \brief Lex a delayed template function for late parsing.
1372void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1373 tok::TokenKind kind = Tok.getKind();
1374 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1375 // Consume everything up to (and including) the matching right brace.
1376 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1377 }
1378
1379 // If we're in a function-try-block, we need to store all the catch blocks.
1380 if (kind == tok::kw_try) {
1381 while (Tok.is(tok::kw_catch)) {
1382 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1383 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1384 }
1385 }
1386}