blob: 84b7df7295f669e36b4e759870225dec4c63defe [file] [log] [blame]
Douglas Gregoradcac882008-12-01 23:54: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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "RAIIObjectsForParser.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/DeclTemplate.h"
Chris Lattner500d3292009-01-29 05:15:15 +000018#include "clang/Parse/ParseDiagnostic.h"
John McCall19510852010-08-20 18:27:03 +000019#include "clang/Sema/DeclSpec.h"
20#include "clang/Sema/ParsedTemplate.h"
21#include "clang/Sema/Scope.h"
Douglas Gregoradcac882008-12-01 23:54:00 +000022using namespace clang;
23
Douglas Gregor4d9a16f2009-05-12 23:25:50 +000024/// \brief Parse a template declaration, explicit instantiation, or
25/// explicit specialization.
John McCalld226f652010-08-21 09:40:31 +000026Decl *
Douglas Gregor4d9a16f2009-05-12 23:25:50 +000027Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
28 SourceLocation &DeclEnd,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +000029 AccessSpecifier AS,
30 AttributeList *AccessAttrs) {
Fariborz Jahanian9735c5e2011-08-22 17:59:19 +000031 ObjCDeclContextSwitch ObjCDC(*this);
32
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000033 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +000034 return ParseExplicitInstantiation(Context,
35 SourceLocation(), ConsumeToken(),
36 DeclEnd, AS);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000037 }
Erik Verbruggen5f1c8222011-10-13 09:41:32 +000038 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
39 AccessAttrs);
Douglas Gregor4d9a16f2009-05-12 23:25:50 +000040}
41
Douglas Gregorc3058332009-08-24 23:03:25 +000042
Douglas Gregorc3058332009-08-24 23:03:25 +000043
Douglas Gregorcc636682009-02-17 23:15:12 +000044/// \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.
Douglas Gregoradcac882008-12-01 23:54:00 +000053///
54/// template-declaration: [C++ temp]
55/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
Douglas Gregorcc636682009-02-17 23:15:12 +000056///
57/// explicit-specialization: [ C++ temp.expl.spec]
58/// 'template' '<' '>' declaration
John McCalld226f652010-08-21 09:40:31 +000059Decl *
Anders Carlsson5aeccdb2009-03-26 00:52:18 +000060Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
Chris Lattner97144fc2009-04-02 04:16:50 +000061 SourceLocation &DeclEnd,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +000062 AccessSpecifier AS,
63 AttributeList *AccessAttrs) {
Mike Stump1eb44332009-09-09 15:08:12 +000064 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
65 "Token does not start a template declaration.");
66
Douglas Gregor26236e82008-12-02 00:41:28 +000067 // Enter template-parameter scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +000068 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Douglas Gregor26236e82008-12-02 00:41:28 +000069
John McCallc9068d72010-07-16 08:13:16 +000070 // Tell the action that names should be checked in the context of
71 // the declaration to come.
John McCall92576642012-05-07 06:16:41 +000072 ParsingDeclRAIIObject
73 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
John McCallc9068d72010-07-16 08:13:16 +000074
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +000075 // 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
Douglas Gregorcc636682009-02-17 23:15:12 +000084 // lists to easily differentiate between the case above and:
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +000085 //
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).
Douglas Gregor0f499d92009-08-20 18:46:05 +000096 bool isSpecialization = true;
Douglas Gregorc78c06d2009-10-30 22:09:44 +000097 bool LastParamListWasEmpty = false;
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +000098 TemplateParameterLists ParamLists;
Richard Smith098b8142013-04-29 11:55:38 +000099 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
100
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000101 do {
102 // Consume the 'export', if any.
103 SourceLocation ExportLoc;
104 if (Tok.is(tok::kw_export)) {
105 ExportLoc = ConsumeToken();
106 }
107
108 // Consume the 'template', which should be here.
109 SourceLocation TemplateLoc;
110 if (Tok.is(tok::kw_template)) {
111 TemplateLoc = ConsumeToken();
112 } else {
113 Diag(Tok.getLocation(), diag::err_expected_template);
John McCalld226f652010-08-21 09:40:31 +0000114 return 0;
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000115 }
Mike Stump1eb44332009-09-09 15:08:12 +0000116
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000117 // Parse the '<' template-parameter-list '>'
118 SourceLocation LAngleLoc, RAngleLoc;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000119 SmallVector<Decl*, 4> TemplateParams;
Richard Smith098b8142013-04-29 11:55:38 +0000120 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
121 TemplateParams, LAngleLoc, RAngleLoc)) {
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000122 // Skip until the semi-colon or a }.
123 SkipUntil(tok::r_brace, true, true);
124 if (Tok.is(tok::semi))
125 ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000126 return 0;
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000127 }
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000128
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000129 ParamLists.push_back(
Richard Smith098b8142013-04-29 11:55:38 +0000130 Actions.ActOnTemplateParameterList(CurTemplateDepthTracker.getDepth(),
131 ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000132 TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +0000133 TemplateParams.data(),
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000134 TemplateParams.size(), RAngleLoc));
Douglas Gregorc3058332009-08-24 23:03:25 +0000135
136 if (!TemplateParams.empty()) {
137 isSpecialization = false;
Richard Smith098b8142013-04-29 11:55:38 +0000138 ++CurTemplateDepthTracker;
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000139 } else {
140 LastParamListWasEmpty = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000141 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000142 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
143
144 // Parse the actual template declaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000145 return ParseSingleDeclarationAfterTemplate(Context,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000146 ParsedTemplateInfo(&ParamLists,
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000147 isSpecialization,
148 LastParamListWasEmpty),
John McCallc9068d72010-07-16 08:13:16 +0000149 ParsingTemplateParams,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +0000150 DeclEnd, AS, AccessAttrs);
Douglas Gregor1426e532009-05-12 21:31:51 +0000151}
Chris Lattner682bf922009-03-29 16:50:03 +0000152
Douglas Gregor1426e532009-05-12 21:31:51 +0000153/// \brief Parse a single declaration that declares a template,
154/// template specialization, or explicit instantiation of a template.
155///
Douglas Gregor1426e532009-05-12 21:31:51 +0000156/// \param DeclEnd will receive the source location of the last token
157/// within this declaration.
158///
159/// \param AS the access specifier associated with this
160/// declaration. Will be AS_none for namespace-scope declarations.
161///
162/// \returns the new declaration.
John McCalld226f652010-08-21 09:40:31 +0000163Decl *
Douglas Gregor1426e532009-05-12 21:31:51 +0000164Parser::ParseSingleDeclarationAfterTemplate(
165 unsigned Context,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000166 const ParsedTemplateInfo &TemplateInfo,
John McCallc9068d72010-07-16 08:13:16 +0000167 ParsingDeclRAIIObject &DiagsFromTParams,
Douglas Gregor1426e532009-05-12 21:31:51 +0000168 SourceLocation &DeclEnd,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +0000169 AccessSpecifier AS,
170 AttributeList *AccessAttrs) {
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000171 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
172 "Template information required");
173
Douglas Gregor37b372b2009-08-20 22:52:58 +0000174 if (Context == Declarator::MemberContext) {
175 // We are parsing a member template.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +0000176 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
177 &DiagsFromTParams);
John McCalld226f652010-08-21 09:40:31 +0000178 return 0;
Douglas Gregor37b372b2009-08-20 22:52:58 +0000179 }
Mike Stump1eb44332009-09-09 15:08:12 +0000180
John McCall0b7e6782011-03-24 11:26:52 +0000181 ParsedAttributesWithRange prefixAttrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +0000182 MaybeParseCXX11Attributes(prefixAttrs);
John McCall78b81052010-11-10 02:40:36 +0000183
184 if (Tok.is(tok::kw_using))
185 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
John McCall7f040a92010-12-24 02:08:15 +0000186 prefixAttrs);
John McCall78b81052010-11-10 02:40:36 +0000187
John McCall92576642012-05-07 06:16:41 +0000188 // Parse the declaration specifiers, stealing any diagnostics from
189 // the template parameters.
John McCall0b7e6782011-03-24 11:26:52 +0000190 ParsingDeclSpec DS(*this, &DiagsFromTParams);
Sean Huntbbd37c62009-11-21 08:43:09 +0000191
Douglas Gregor0efc2c12010-01-13 17:31:36 +0000192 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
193 getDeclSpecContextFromDeclaratorContext(Context));
Douglas Gregor1426e532009-05-12 21:31:51 +0000194
195 if (Tok.is(tok::semi)) {
Richard Smith68ea3ae2013-02-22 09:06:26 +0000196 ProhibitAttributes(prefixAttrs);
Douglas Gregor1426e532009-05-12 21:31:51 +0000197 DeclEnd = ConsumeToken();
Richard Smithc7f81162013-03-18 22:52:47 +0000198 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
199 getCurScope(), AS, DS,
200 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
201 : MultiTemplateParamsArg(),
202 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation);
John McCall54abf7d2009-11-04 02:18:39 +0000203 DS.complete(Decl);
204 return Decl;
Douglas Gregor1426e532009-05-12 21:31:51 +0000205 }
206
Richard Smith68ea3ae2013-02-22 09:06:26 +0000207 // Move the attributes from the prefix into the DS.
208 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
209 ProhibitAttributes(prefixAttrs);
210 else
211 DS.takeAttributesFrom(prefixAttrs);
212
Douglas Gregor1426e532009-05-12 21:31:51 +0000213 // Parse the declarator.
John McCall54abf7d2009-11-04 02:18:39 +0000214 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
Douglas Gregor1426e532009-05-12 21:31:51 +0000215 ParseDeclarator(DeclaratorInfo);
216 // Error parsing the declarator?
217 if (!DeclaratorInfo.hasName()) {
218 // If so, skip until the semi-colon or a }.
219 SkipUntil(tok::r_brace, true, true);
220 if (Tok.is(tok::semi))
221 ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000222 return 0;
Douglas Gregor1426e532009-05-12 21:31:51 +0000223 }
Mike Stump1eb44332009-09-09 15:08:12 +0000224
DeLesley Hutchins161db022012-11-02 21:44:32 +0000225 LateParsedAttrList LateParsedAttrs(true);
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000226 if (DeclaratorInfo.isFunctionDeclarator())
227 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
228
Douglas Gregor1426e532009-05-12 21:31:51 +0000229 if (DeclaratorInfo.isFunctionDeclarator() &&
Chris Lattner004659a2010-07-11 22:42:07 +0000230 isStartOfFunctionDefinition(DeclaratorInfo)) {
Douglas Gregor1426e532009-05-12 21:31:51 +0000231 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Smith6e1fd332011-11-29 09:09:06 +0000232 // Recover by ignoring the 'typedef'. This was probably supposed to be
233 // the 'typename' keyword, which we should have already suggested adding
234 // if it's appropriate.
235 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
236 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith874d2532011-11-29 05:27:40 +0000237 DS.ClearStorageClassSpecs();
Douglas Gregor1426e532009-05-12 21:31:51 +0000238 }
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000239 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
240 &LateParsedAttrs);
Douglas Gregor1426e532009-05-12 21:31:51 +0000241 }
242
Richard Smithd3e723e2013-01-15 06:49:38 +0000243 // Parse this declaration.
244 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
245 TemplateInfo);
246
247 if (Tok.is(tok::comma)) {
248 Diag(Tok, diag::err_multiple_template_declarators)
249 << (int)TemplateInfo.Kind;
250 SkipUntil(tok::semi, true, false);
251 return ThisDecl;
252 }
253
254 // Eat the semi colon after the declaration.
255 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
256 if (LateParsedAttrs.size() > 0)
257 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
258 DeclaratorInfo.complete(ThisDecl);
259 return ThisDecl;
Douglas Gregoradcac882008-12-01 23:54:00 +0000260}
261
262/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000263/// angle brackets. Depth is the depth of this template-parameter-list, which
264/// is the number of template headers directly enclosing this template header.
265/// TemplateParams is the current list of template parameters we're building.
266/// The template parameter we parse will be added to this list. LAngleLoc and
Mike Stump1eb44332009-09-09 15:08:12 +0000267/// RAngleLoc will receive the positions of the '<' and '>', respectively,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000268/// that enclose this template parameter list.
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000269///
270/// \returns true if an error occurred, false otherwise.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000271bool Parser::ParseTemplateParameters(unsigned Depth,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000272 SmallVectorImpl<Decl*> &TemplateParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000273 SourceLocation &LAngleLoc,
274 SourceLocation &RAngleLoc) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000275 // Get the template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +0000276 if (!Tok.is(tok::less)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000277 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000278 return true;
Douglas Gregoradcac882008-12-01 23:54:00 +0000279 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000280 LAngleLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Douglas Gregoradcac882008-12-01 23:54:00 +0000282 // Try to parse the template parameter list.
David Blaikieeb52f86a2012-04-09 16:37:11 +0000283 bool Failed = false;
284 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
285 Failed = ParseTemplateParameterList(Depth, TemplateParams);
286
287 if (Tok.is(tok::greatergreater)) {
Richard Smith19a27022012-06-18 06:11:04 +0000288 // No diagnostic required here: a template-parameter-list can only be
289 // followed by a declaration or, for a template template parameter, the
290 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
291 // This matters for elegant diagnosis of:
292 // template<template<typename>> struct S;
David Blaikieeb52f86a2012-04-09 16:37:11 +0000293 Tok.setKind(tok::greater);
294 RAngleLoc = Tok.getLocation();
295 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
296 } else if (Tok.is(tok::greater))
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000297 RAngleLoc = ConsumeToken();
David Blaikieeb52f86a2012-04-09 16:37:11 +0000298 else if (Failed) {
299 Diag(Tok.getLocation(), diag::err_expected_greater);
300 return true;
Douglas Gregoradcac882008-12-01 23:54:00 +0000301 }
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000302 return false;
Douglas Gregoradcac882008-12-01 23:54:00 +0000303}
304
305/// ParseTemplateParameterList - Parse a template parameter list. If
306/// the parsing fails badly (i.e., closing bracket was left out), this
307/// will try to put the token stream in a reasonable position (closing
Mike Stump1eb44332009-09-09 15:08:12 +0000308/// a statement, etc.) and return false.
Douglas Gregoradcac882008-12-01 23:54:00 +0000309///
310/// template-parameter-list: [C++ temp]
311/// template-parameter
312/// template-parameter-list ',' template-parameter
Mike Stump1eb44332009-09-09 15:08:12 +0000313bool
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000314Parser::ParseTemplateParameterList(unsigned Depth,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000315 SmallVectorImpl<Decl*> &TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000316 while (1) {
John McCalld226f652010-08-21 09:40:31 +0000317 if (Decl *TmpParam
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000318 = ParseTemplateParameter(Depth, TemplateParams.size())) {
319 TemplateParams.push_back(TmpParam);
320 } else {
Douglas Gregoradcac882008-12-01 23:54:00 +0000321 // If we failed to parse a template parameter, skip until we find
322 // a comma or closing brace.
David Blaikie9df1b962012-04-06 05:26:43 +0000323 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000324 }
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Nico Weber001397e2012-12-14 02:40:09 +0000326 // Did we find a comma or the end of the template parameter list?
Mike Stump1eb44332009-09-09 15:08:12 +0000327 if (Tok.is(tok::comma)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000328 ConsumeToken();
David Blaikie9df1b962012-04-06 05:26:43 +0000329 } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000330 // Don't consume this... that's done by template parser.
331 break;
332 } else {
333 // Somebody probably forgot to close the template. Skip ahead and
334 // try to get out of the expression. This error is currently
335 // subsumed by whatever goes on in ParseTemplateParameter.
Douglas Gregor99ea7342010-10-15 01:15:58 +0000336 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
David Blaikieeb52f86a2012-04-09 16:37:11 +0000337 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000338 return false;
339 }
340 }
341 return true;
342}
343
Douglas Gregor98440b42009-11-21 02:07:55 +0000344/// \brief Determine whether the parser is at the start of a template
345/// type parameter.
346bool Parser::isStartOfTemplateTypeParameter() {
Douglas Gregor7b6d25b2010-06-04 07:30:15 +0000347 if (Tok.is(tok::kw_class)) {
348 // "class" may be the start of an elaborated-type-specifier or a
349 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
350 switch (NextToken().getKind()) {
351 case tok::equal:
352 case tok::comma:
353 case tok::greater:
354 case tok::greatergreater:
355 case tok::ellipsis:
356 return true;
357
358 case tok::identifier:
359 // This may be either a type-parameter or an elaborated-type-specifier.
360 // We have to look further.
361 break;
362
363 default:
364 return false;
365 }
366
367 switch (GetLookAheadToken(2).getKind()) {
368 case tok::equal:
369 case tok::comma:
370 case tok::greater:
371 case tok::greatergreater:
372 return true;
373
374 default:
375 return false;
376 }
377 }
Douglas Gregor98440b42009-11-21 02:07:55 +0000378
379 if (Tok.isNot(tok::kw_typename))
380 return false;
381
382 // C++ [temp.param]p2:
383 // There is no semantic difference between class and typename in a
384 // template-parameter. typename followed by an unqualified-id
385 // names a template type parameter. typename followed by a
386 // qualified-id denotes the type in a non-type
387 // parameter-declaration.
388 Token Next = NextToken();
389
390 // If we have an identifier, skip over it.
391 if (Next.getKind() == tok::identifier)
392 Next = GetLookAheadToken(2);
393
394 switch (Next.getKind()) {
395 case tok::equal:
396 case tok::comma:
397 case tok::greater:
398 case tok::greatergreater:
399 case tok::ellipsis:
400 return true;
401
402 default:
403 return false;
404 }
405}
406
Douglas Gregoradcac882008-12-01 23:54:00 +0000407/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
408///
409/// template-parameter: [C++ temp.param]
410/// type-parameter
411/// parameter-declaration
412///
413/// type-parameter: (see below)
Douglas Gregor61c4d282011-01-05 15:48:55 +0000414/// 'class' ...[opt] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000415/// 'class' identifier[opt] '=' type-id
Douglas Gregor61c4d282011-01-05 15:48:55 +0000416/// 'typename' ...[opt] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000417/// 'typename' identifier[opt] '=' type-id
Douglas Gregor61c4d282011-01-05 15:48:55 +0000418/// 'template' '<' template-parameter-list '>'
419/// 'class' ...[opt] identifier[opt]
420/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
421/// = id-expression
John McCalld226f652010-08-21 09:40:31 +0000422Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor98440b42009-11-21 02:07:55 +0000423 if (isStartOfTemplateTypeParameter())
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000424 return ParseTypeParameter(Depth, Position);
Mike Stump1eb44332009-09-09 15:08:12 +0000425
426 if (Tok.is(tok::kw_template))
Chris Lattner532e19b2009-01-04 23:51:17 +0000427 return ParseTemplateTemplateParameter(Depth, Position);
428
429 // If it's none of the above, then it must be a parameter declaration.
430 // NOTE: This will pick up errors in the closure of the template parameter
431 // list (e.g., template < ; Check here to implement >> style closures.
432 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000433}
434
435/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
436/// Other kinds of template parameters are parsed in
437/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
438///
439/// type-parameter: [C++ temp.param]
Anders Carlssonce5635a2009-06-12 23:09:56 +0000440/// 'class' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000441/// 'class' identifier[opt] '=' type-id
Anders Carlssonce5635a2009-06-12 23:09:56 +0000442/// 'typename' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000443/// 'typename' identifier[opt] '=' type-id
John McCalld226f652010-08-21 09:40:31 +0000444Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000445 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
Mike Stump1eb44332009-09-09 15:08:12 +0000446 "A type-parameter starts with 'class' or 'typename'");
Douglas Gregor26236e82008-12-02 00:41:28 +0000447
448 // Consume the 'class' or 'typename' keyword.
449 bool TypenameKeyword = Tok.is(tok::kw_typename);
450 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000451
Anders Carlsson941df7d2009-06-12 19:58:00 +0000452 // Grab the ellipsis (if given).
453 bool Ellipsis = false;
454 SourceLocation EllipsisLoc;
Anders Carlssonce5635a2009-06-12 23:09:56 +0000455 if (Tok.is(tok::ellipsis)) {
Anders Carlsson941df7d2009-06-12 19:58:00 +0000456 Ellipsis = true;
457 EllipsisLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Richard Smithe5acd132011-10-14 20:31:37 +0000459 Diag(EllipsisLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +0000460 getLangOpts().CPlusPlus11
Richard Smithe5acd132011-10-14 20:31:37 +0000461 ? diag::warn_cxx98_compat_variadic_templates
462 : diag::ext_variadic_templates);
Anders Carlsson941df7d2009-06-12 19:58:00 +0000463 }
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Douglas Gregoradcac882008-12-01 23:54:00 +0000465 // Grab the template parameter name (if given)
Douglas Gregor26236e82008-12-02 00:41:28 +0000466 SourceLocation NameLoc;
467 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000468 if (Tok.is(tok::identifier)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000469 ParamName = Tok.getIdentifierInfo();
470 NameLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000471 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
David Blaikie9df1b962012-04-06 05:26:43 +0000472 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000473 // Unnamed template parameter. Don't have to do anything here, just
474 // don't consume this token.
475 } else {
476 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000477 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000478 }
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000480 // Grab a default argument (if available).
481 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
482 // we introduce the type parameter into the local scope.
483 SourceLocation EqualLoc;
John McCallb3d87482010-08-24 05:47:05 +0000484 ParsedType DefaultArg;
Mike Stump1eb44332009-09-09 15:08:12 +0000485 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000486 EqualLoc = ConsumeToken();
Richard Smithd37b3602012-02-10 11:05:11 +0000487 DefaultArg = ParseTypeName(/*Range=*/0,
488 Declarator::TemplateTypeArgContext).get();
Douglas Gregoradcac882008-12-01 23:54:00 +0000489 }
Richard Smithd37b3602012-02-10 11:05:11 +0000490
Douglas Gregor23c94db2010-07-02 17:43:08 +0000491 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000492 EllipsisLoc, KeyLoc, ParamName, NameLoc,
493 Depth, Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000494}
495
496/// ParseTemplateTemplateParameter - Handle the parsing of template
Mike Stump1eb44332009-09-09 15:08:12 +0000497/// template parameters.
Douglas Gregoradcac882008-12-01 23:54:00 +0000498///
499/// type-parameter: [C++ temp.param]
Douglas Gregor61c4d282011-01-05 15:48:55 +0000500/// 'template' '<' template-parameter-list '>' 'class'
501/// ...[opt] identifier[opt]
502/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
503/// = id-expression
John McCalld226f652010-08-21 09:40:31 +0000504Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000505Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000506 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
507
508 // Handle the template <...> part.
509 SourceLocation TemplateLoc = ConsumeToken();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000510 SmallVector<Decl*,8> TemplateParams;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000511 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor68c69932009-02-10 19:52:54 +0000512 {
513 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000514 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000515 RAngleLoc)) {
John McCalld226f652010-08-21 09:40:31 +0000516 return 0;
Douglas Gregor68c69932009-02-10 19:52:54 +0000517 }
Douglas Gregoradcac882008-12-01 23:54:00 +0000518 }
519
520 // Generate a meaningful error if the user forgot to put class before the
David Blaikie9df1b962012-04-06 05:26:43 +0000521 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
522 // or greater appear immediately or after 'typename' or 'struct'. In the
523 // latter case, replace the keyword with 'class'.
524 if (!Tok.is(tok::kw_class)) {
525 bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
526 const Token& Next = Replace ? NextToken() : Tok;
527 if (Next.is(tok::identifier) || Next.is(tok::comma) ||
528 Next.is(tok::greater) || Next.is(tok::greatergreater) ||
529 Next.is(tok::ellipsis))
530 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
531 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
532 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
533 else
534 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
535
536 if (Replace)
537 ConsumeToken();
538 } else
David Blaikie460ef132012-04-02 19:15:28 +0000539 ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000540
Douglas Gregor61c4d282011-01-05 15:48:55 +0000541 // Parse the ellipsis, if given.
542 SourceLocation EllipsisLoc;
543 if (Tok.is(tok::ellipsis)) {
544 EllipsisLoc = ConsumeToken();
545
Richard Smithe5acd132011-10-14 20:31:37 +0000546 Diag(EllipsisLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +0000547 getLangOpts().CPlusPlus11
Richard Smithe5acd132011-10-14 20:31:37 +0000548 ? diag::warn_cxx98_compat_variadic_templates
549 : diag::ext_variadic_templates);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000550 }
551
Douglas Gregoradcac882008-12-01 23:54:00 +0000552 // Get the identifier, if given.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000553 SourceLocation NameLoc;
554 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000555 if (Tok.is(tok::identifier)) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000556 ParamName = Tok.getIdentifierInfo();
557 NameLoc = ConsumeToken();
David Blaikie9df1b962012-04-06 05:26:43 +0000558 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
559 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000560 // Unnamed template parameter. Don't have to do anything here, just
561 // don't consume this token.
562 } else {
563 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000564 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000565 }
566
Richard Trieu90ab75b2011-09-09 03:18:59 +0000567 TemplateParameterList *ParamList =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000568 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
569 TemplateLoc, LAngleLoc,
Douglas Gregor369ea272010-10-21 17:26:49 +0000570 TemplateParams.data(),
Douglas Gregorddc29e12009-02-06 22:42:48 +0000571 TemplateParams.size(),
572 RAngleLoc);
573
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000574 // Grab a default argument (if available).
575 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
576 // we introduce the template parameter into the local scope.
577 SourceLocation EqualLoc;
578 ParsedTemplateArgument DefaultArg;
Douglas Gregord684b002009-02-10 19:49:53 +0000579 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000580 EqualLoc = ConsumeToken();
581 DefaultArg = ParseTemplateTemplateArgument();
582 if (DefaultArg.isInvalid()) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000583 Diag(Tok.getLocation(),
584 diag::err_default_template_template_parameter_not_template);
David Blaikieeb52f86a2012-04-09 16:37:11 +0000585 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000586 }
Douglas Gregord684b002009-02-10 19:49:53 +0000587 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000588
Douglas Gregor23c94db2010-07-02 17:43:08 +0000589 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000590 ParamList, EllipsisLoc,
591 ParamName, NameLoc, Depth,
592 Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000593}
594
595/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
Mike Stump1eb44332009-09-09 15:08:12 +0000596/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000597///
Douglas Gregoradcac882008-12-01 23:54:00 +0000598/// template-parameter:
599/// ...
600/// parameter-declaration
John McCalld226f652010-08-21 09:40:31 +0000601Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000602Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000603 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor26236e82008-12-02 00:41:28 +0000604 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregoradcac882008-12-01 23:54:00 +0000605 // declarators (parts of declarators?) are accepted for parameters.
John McCall0b7e6782011-03-24 11:26:52 +0000606 DeclSpec DS(AttrFactory);
Douglas Gregor26236e82008-12-02 00:41:28 +0000607 ParseDeclarationSpecifiers(DS);
Douglas Gregoradcac882008-12-01 23:54:00 +0000608
609 // Parse this as a typename.
Douglas Gregor26236e82008-12-02 00:41:28 +0000610 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
611 ParseDeclarator(ParamDecl);
John McCallb3d87482010-08-24 05:47:05 +0000612 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
David Blaikieb031eab2012-04-06 23:33:59 +0000613 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
John McCalld226f652010-08-21 09:40:31 +0000614 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000615 }
616
Douglas Gregord684b002009-02-10 19:49:53 +0000617 // If there is a default value, parse it.
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000618 // 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;
John McCall60d7b3a2010-08-24 06:29:42 +0000621 ExprResult DefaultArg;
Chris Lattner7452c6f2009-01-05 01:24:05 +0000622 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000623 EqualLoc = ConsumeToken();
Douglas Gregord684b002009-02-10 19:49:53 +0000624
625 // C++ [temp.param]p15:
626 // When parsing a default template-argument for a non-type
627 // template-parameter, the first non-nested > is taken as the
628 // end of the template-parameter-list rather than a greater-than
629 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +0000630 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Eli Friedman9b94cd12012-04-26 22:43:24 +0000631 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
Douglas Gregord684b002009-02-10 19:49:53 +0000632
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000633 DefaultArg = ParseAssignmentExpression();
Douglas Gregord684b002009-02-10 19:49:53 +0000634 if (DefaultArg.isInvalid())
635 SkipUntil(tok::comma, tok::greater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000636 }
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000638 // Create the parameter.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000639 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000640 Depth, Position, EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000641 DefaultArg.take());
Douglas Gregoradcac882008-12-01 23:54:00 +0000642}
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000643
Nico Weberb707a472012-12-14 18:22:38 +0000644/// \brief Parses a '>' at the end of a template list.
Douglas Gregorcc636682009-02-17 23:15:12 +0000645///
Nico Weberb707a472012-12-14 18:22:38 +0000646/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
647/// to determine if these tokens were supposed to be a '>' followed by
648/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
Douglas Gregorcc636682009-02-17 23:15:12 +0000649///
Nico Weberb707a472012-12-14 18:22:38 +0000650/// \param RAngleLoc the location of the consumed '>'.
Douglas Gregorcc636682009-02-17 23:15:12 +0000651///
Nico Weberb707a472012-12-14 18:22:38 +0000652/// \param ConsumeLastToken if true, the '>' is not consumed.
653bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
654 bool ConsumeLastToken) {
Richard Smith19a27022012-06-18 06:11:04 +0000655 // What will be left once we've consumed the '>'.
656 tok::TokenKind RemainingToken;
657 const char *ReplacementStr = "> >";
658
659 switch (Tok.getKind()) {
660 default:
Eli Friedman64a4eb22009-12-27 22:31:18 +0000661 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregorcc636682009-02-17 23:15:12 +0000662 return true;
Richard Smith19a27022012-06-18 06:11:04 +0000663
664 case tok::greater:
665 // Determine the location of the '>' token. Only consume this token
666 // if the caller asked us to.
667 RAngleLoc = Tok.getLocation();
668 if (ConsumeLastToken)
669 ConsumeToken();
670 return false;
671
672 case tok::greatergreater:
673 RemainingToken = tok::greater;
674 break;
675
676 case tok::greatergreatergreater:
677 RemainingToken = tok::greatergreater;
678 break;
679
680 case tok::greaterequal:
681 RemainingToken = tok::equal;
682 ReplacementStr = "> =";
683 break;
684
685 case tok::greatergreaterequal:
686 RemainingToken = tok::greaterequal;
687 break;
Eli Friedman64a4eb22009-12-27 22:31:18 +0000688 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000689
Richard Smith19a27022012-06-18 06:11:04 +0000690 // This template-id is terminated by a token which starts with a '>'. Outside
691 // C++11, this is now error recovery, and in C++11, this is error recovery if
692 // the token isn't '>>'.
693
Douglas Gregorcc636682009-02-17 23:15:12 +0000694 RAngleLoc = Tok.getLocation();
695
Richard Smith19a27022012-06-18 06:11:04 +0000696 // The source range of the '>>' or '>=' at the start of the token.
697 CharSourceRange ReplacementRange =
698 CharSourceRange::getCharRange(RAngleLoc,
699 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
700 getLangOpts()));
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000701
Richard Smith19a27022012-06-18 06:11:04 +0000702 // A hint to put a space between the '>>'s. In order to make the hint as
703 // clear as possible, we include the characters either side of the space in
704 // the replacement, rather than just inserting a space at SecondCharLoc.
705 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
706 ReplacementStr);
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000707
Richard Smith19a27022012-06-18 06:11:04 +0000708 // A hint to put another space after the token, if it would otherwise be
709 // lexed differently.
710 FixItHint Hint2;
711 Token Next = NextToken();
712 if ((RemainingToken == tok::greater ||
713 RemainingToken == tok::greatergreater) &&
714 (Next.is(tok::greater) || Next.is(tok::greatergreater) ||
715 Next.is(tok::greatergreatergreater) || Next.is(tok::equal) ||
716 Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) ||
717 Next.is(tok::equalequal)) &&
718 areTokensAdjacent(Tok, Next))
719 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
720
721 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
Richard Smith80ad52f2013-01-02 11:42:31 +0000722 if (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater))
Richard Smith19a27022012-06-18 06:11:04 +0000723 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
724 else if (Tok.is(tok::greaterequal))
725 DiagId = diag::err_right_angle_bracket_equal_needs_space;
726 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
727
728 // Strip the initial '>' from the token.
729 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
730 areTokensAdjacent(Tok, Next)) {
731 // Join two adjacent '=' tokens into one, for cases like:
732 // void (*p)() = f<int>;
733 // return f<int>==p;
Douglas Gregorcc636682009-02-17 23:15:12 +0000734 ConsumeToken();
Richard Smith19a27022012-06-18 06:11:04 +0000735 Tok.setKind(tok::equalequal);
736 Tok.setLength(Tok.getLength() + 1);
737 } else {
738 Tok.setKind(RemainingToken);
739 Tok.setLength(Tok.getLength() - 1);
740 }
741 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
742 PP.getSourceManager(),
743 getLangOpts()));
744
745 if (!ConsumeLastToken) {
746 // Since we're not supposed to consume the '>' token, we need to push
747 // this token and revert the current token back to the '>'.
748 PP.EnterToken(Tok);
749 Tok.setKind(tok::greater);
750 Tok.setLength(1);
751 Tok.setLocation(RAngleLoc);
752 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000753 return false;
754}
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Nico Weberb707a472012-12-14 18:22:38 +0000756
757/// \brief Parses a template-id that after the template name has
758/// already been parsed.
759///
760/// This routine takes care of parsing the enclosed template argument
761/// list ('<' template-parameter-list [opt] '>') and placing the
762/// results into a form that can be transferred to semantic analysis.
763///
764/// \param Template the template declaration produced by isTemplateName
765///
766/// \param TemplateNameLoc the source location of the template name
767///
768/// \param SS if non-NULL, the nested-name-specifier preceding the
769/// template name.
770///
771/// \param ConsumeLastToken if true, then we will consume the last
772/// token that forms the template-id. Otherwise, we will leave the
773/// last token in the stream (e.g., so that it can be replaced with an
774/// annotation token).
775bool
776Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
777 SourceLocation TemplateNameLoc,
778 const CXXScopeSpec &SS,
779 bool ConsumeLastToken,
780 SourceLocation &LAngleLoc,
781 TemplateArgList &TemplateArgs,
782 SourceLocation &RAngleLoc) {
783 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
784
785 // Consume the '<'.
786 LAngleLoc = ConsumeToken();
787
788 // Parse the optional template-argument-list.
789 bool Invalid = false;
790 {
791 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
792 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
793 Invalid = ParseTemplateArgumentList(TemplateArgs);
794
795 if (Invalid) {
796 // Try to find the closing '>'.
797 SkipUntil(tok::greater, true, !ConsumeLastToken);
798
799 return true;
800 }
801 }
802
803 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken);
804}
805
Douglas Gregor39a8de12009-02-25 19:37:18 +0000806/// \brief Replace the tokens that form a simple-template-id with an
807/// annotation token containing the complete template-id.
808///
809/// The first token in the stream must be the name of a template that
810/// is followed by a '<'. This routine will parse the complete
811/// simple-template-id and replace the tokens with a single annotation
812/// token with one of two different kinds: if the template-id names a
813/// type (and \p AllowTypeAnnotation is true), the annotation token is
814/// a type annotation that includes the optional nested-name-specifier
815/// (\p SS). Otherwise, the annotation token is a template-id
816/// annotation that does not include the optional
817/// nested-name-specifier.
818///
819/// \param Template the declaration of the template named by the first
820/// token (an identifier), as returned from \c Action::isTemplateName().
821///
NAKAMURA Takumi384d3fc2012-11-14 02:21:42 +0000822/// \param TNK the kind of template that \p Template
Douglas Gregor39a8de12009-02-25 19:37:18 +0000823/// refers to, as returned from \c Action::isTemplateName().
824///
825/// \param SS if non-NULL, the nested-name-specifier that precedes
826/// this template name.
827///
828/// \param TemplateKWLoc if valid, specifies that this template-id
829/// annotation was preceded by the 'template' keyword and gives the
830/// location of that keyword. If invalid (the default), then this
831/// template-id was not preceded by a 'template' keyword.
832///
833/// \param AllowTypeAnnotation if true (the default), then a
834/// simple-template-id that refers to a class template, template
835/// template parameter, or other template that produces a type will be
836/// replaced with a type annotation token. Otherwise, the
837/// simple-template-id is always replaced with a template-id
838/// annotation token.
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000839///
840/// If an unrecoverable parse error occurs and no annotation token can be
841/// formed, this function returns true.
842///
843bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Douglas Gregor059101f2011-03-02 00:47:37 +0000844 CXXScopeSpec &SS,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000845 SourceLocation TemplateKWLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000846 UnqualifiedId &TemplateName,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000847 bool AllowTypeAnnotation) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000848 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000849 assert(Template && Tok.is(tok::less) &&
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000850 "Parser isn't at the beginning of a template-id");
851
852 // Consume the template-name.
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000853 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000854
Douglas Gregorcc636682009-02-17 23:15:12 +0000855 // Parse the enclosed template argument list.
856 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000857 TemplateArgList TemplateArgs;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000858 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
859 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000860 SS, false, LAngleLoc,
861 TemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +0000862 RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000864 if (Invalid) {
865 // If we failed to parse the template ID but skipped ahead to a >, we're not
866 // going to be able to form a token annotation. Eat the '>' if present.
867 if (Tok.is(tok::greater))
868 ConsumeToken();
869 return true;
870 }
Douglas Gregorc15cb382009-02-09 23:23:08 +0000871
Benjamin Kramer5354e772012-08-23 23:38:35 +0000872 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Douglas Gregorf02da892009-02-09 21:04:56 +0000873
Douglas Gregor55f6b142009-02-09 18:46:07 +0000874 // Build the annotation token.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000875 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
John McCallf312b1e2010-08-26 23:41:50 +0000876 TypeResult Type
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000877 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +0000878 Template, TemplateNameLoc,
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000879 LAngleLoc, TemplateArgsPtr, RAngleLoc);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000880 if (Type.isInvalid()) {
881 // If we failed to parse the template ID but skipped ahead to a >, we're not
882 // going to be able to form a token annotation. Eat the '>' if present.
883 if (Tok.is(tok::greater))
884 ConsumeToken();
885 return true;
886 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000887
888 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000889 setTypeAnnotation(Tok, Type.get());
Douglas Gregor059101f2011-03-02 00:47:37 +0000890 if (SS.isNotEmpty())
891 Tok.setLocation(SS.getBeginLoc());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000892 else if (TemplateKWLoc.isValid())
893 Tok.setLocation(TemplateKWLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000894 else
Douglas Gregor39a8de12009-02-25 19:37:18 +0000895 Tok.setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +0000896 } else {
Douglas Gregorc45c2322009-03-31 00:43:58 +0000897 // Build a template-id annotation token that can be processed
898 // later.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000899 Tok.setKind(tok::annot_template_id);
Mike Stump1eb44332009-09-09 15:08:12 +0000900 TemplateIdAnnotation *TemplateId
Benjamin Kramer13bb7012012-04-14 12:14:03 +0000901 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000902 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000903 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
904 TemplateId->Name = TemplateName.Identifier;
905 TemplateId->Operator = OO_None;
906 } else {
907 TemplateId->Name = 0;
908 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
909 }
Douglas Gregor059101f2011-03-02 00:47:37 +0000910 TemplateId->SS = SS;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000911 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall2b5289b2010-08-23 07:28:44 +0000912 TemplateId->Template = Template;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000913 TemplateId->Kind = TNK;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000914 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000915 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregor314b97f2009-11-10 19:49:08 +0000916 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
917 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
Douglas Gregorc34348a2011-02-24 17:54:50 +0000918 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000919 Tok.setAnnotationValue(TemplateId);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000920 if (TemplateKWLoc.isValid())
921 Tok.setLocation(TemplateKWLoc);
922 else
923 Tok.setLocation(TemplateNameLoc);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000924 }
925
926 // Common fields for the annotation token
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000927 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000928
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000929 // In case the tokens were cached, have Preprocessor replace them with the
930 // annotation token.
931 PP.AnnotateCachedTokens(Tok);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000932 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000933}
934
Douglas Gregor39a8de12009-02-25 19:37:18 +0000935/// \brief Replaces a template-id annotation token with a type
936/// annotation token.
937///
Douglas Gregor31a19b62009-04-01 21:51:26 +0000938/// If there was a failure when forming the type from the template-id,
939/// a type annotation token will still be created, but will have a
940/// NULL type pointer to signify an error.
Douglas Gregor059101f2011-03-02 00:47:37 +0000941void Parser::AnnotateTemplateIdTokenAsType() {
Douglas Gregor39a8de12009-02-25 19:37:18 +0000942 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
943
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +0000944 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000945 assert((TemplateId->Kind == TNK_Type_template ||
946 TemplateId->Kind == TNK_Dependent_template_name) &&
947 "Only works for type and dependent templates");
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Benjamin Kramer5354e772012-08-23 23:38:35 +0000949 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor39a8de12009-02-25 19:37:18 +0000950 TemplateId->NumArgs);
951
John McCallf312b1e2010-08-26 23:41:50 +0000952 TypeResult Type
Douglas Gregor059101f2011-03-02 00:47:37 +0000953 = Actions.ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000954 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +0000955 TemplateId->Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000956 TemplateId->TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000957 TemplateId->LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000958 TemplateArgsPtr,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000959 TemplateId->RAngleLoc);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000960 // Create the new "type" annotation token.
961 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000962 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
Douglas Gregor059101f2011-03-02 00:47:37 +0000963 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
964 Tok.setLocation(TemplateId->SS.getBeginLoc());
Sebastian Redl39d67112010-02-08 19:35:18 +0000965 // End location stays the same
Douglas Gregor39a8de12009-02-25 19:37:18 +0000966
Douglas Gregor86235412009-11-04 18:18:19 +0000967 // Replace the template-id annotation token, and possible the scope-specifier
968 // that precedes it, with the typename annotation token.
969 PP.AnnotateCachedTokens(Tok);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000970}
971
Douglas Gregor314b97f2009-11-10 19:49:08 +0000972/// \brief Determine whether the given token can end a template argument.
Benjamin Kramer3a4a2b32009-11-10 21:29:56 +0000973static bool isEndOfTemplateArgument(Token Tok) {
Douglas Gregor314b97f2009-11-10 19:49:08 +0000974 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
975 Tok.is(tok::greatergreater);
976}
977
Douglas Gregor788cd062009-11-11 01:00:40 +0000978/// \brief Parse a C++ template template argument.
979ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
980 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
981 !Tok.is(tok::annot_cxxscope))
982 return ParsedTemplateArgument();
983
984 // C++0x [temp.arg.template]p1:
985 // A template-argument for a template template-parameter shall be the name
Richard Smith3e4c6c42011-05-05 21:57:07 +0000986 // of a class template or an alias template, expressed as id-expression.
Douglas Gregor788cd062009-11-11 01:00:40 +0000987 //
Richard Smith3e4c6c42011-05-05 21:57:07 +0000988 // We parse an id-expression that refers to a class template or alias
989 // template. The grammar we parse is:
Douglas Gregor788cd062009-11-11 01:00:40 +0000990 //
Douglas Gregorec5e6962011-01-05 17:33:50 +0000991 // nested-name-specifier[opt] template[opt] identifier ...[opt]
Douglas Gregor788cd062009-11-11 01:00:40 +0000992 //
993 // followed by a token that terminates a template argument, such as ',',
994 // '>', or (in some cases) '>>'.
Douglas Gregor788cd062009-11-11 01:00:40 +0000995 CXXScopeSpec SS; // nested-name-specifier, if present
John McCallb3d87482010-08-24 05:47:05 +0000996 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000997 /*EnteringContext=*/false);
998
Douglas Gregorec5e6962011-01-05 17:33:50 +0000999 ParsedTemplateArgument Result;
1000 SourceLocation EllipsisLoc;
Douglas Gregor788cd062009-11-11 01:00:40 +00001001 if (SS.isSet() && Tok.is(tok::kw_template)) {
1002 // Parse the optional 'template' keyword following the
1003 // nested-name-specifier.
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001004 SourceLocation TemplateKWLoc = ConsumeToken();
Douglas Gregor788cd062009-11-11 01:00:40 +00001005
1006 if (Tok.is(tok::identifier)) {
1007 // We appear to have a dependent template name.
1008 UnqualifiedId Name;
1009 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1010 ConsumeToken(); // the identifier
1011
Douglas Gregorec5e6962011-01-05 17:33:50 +00001012 // Parse the ellipsis.
1013 if (Tok.is(tok::ellipsis))
1014 EllipsisLoc = ConsumeToken();
1015
Douglas Gregor788cd062009-11-11 01:00:40 +00001016 // If the next token signals the end of a template argument,
1017 // then we have a dependent template name that could be a template
1018 // template argument.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001019 TemplateTy Template;
1020 if (isEndOfTemplateArgument(Tok) &&
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001021 Actions.ActOnDependentTemplateName(getCurScope(),
1022 SS, TemplateKWLoc, Name,
John McCallb3d87482010-08-24 05:47:05 +00001023 /*ObjectType=*/ ParsedType(),
Douglas Gregord6ab2322010-06-16 23:00:59 +00001024 /*EnteringContext=*/false,
1025 Template))
Douglas Gregorec5e6962011-01-05 17:33:50 +00001026 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregord6ab2322010-06-16 23:00:59 +00001027 }
Douglas Gregor788cd062009-11-11 01:00:40 +00001028 } else if (Tok.is(tok::identifier)) {
1029 // We may have a (non-dependent) template name.
1030 TemplateTy Template;
1031 UnqualifiedId Name;
1032 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1033 ConsumeToken(); // the identifier
1034
Douglas Gregorec5e6962011-01-05 17:33:50 +00001035 // Parse the ellipsis.
1036 if (Tok.is(tok::ellipsis))
1037 EllipsisLoc = ConsumeToken();
1038
Douglas Gregor788cd062009-11-11 01:00:40 +00001039 if (isEndOfTemplateArgument(Tok)) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001040 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001041 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1042 /*hasTemplateKeyword=*/false,
1043 Name,
John McCallb3d87482010-08-24 05:47:05 +00001044 /*ObjectType=*/ ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001045 /*EnteringContext=*/false,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001046 Template,
1047 MemberOfUnknownSpecialization);
Douglas Gregor788cd062009-11-11 01:00:40 +00001048 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1049 // We have an id-expression that refers to a class template or
Richard Smith3e4c6c42011-05-05 21:57:07 +00001050 // (C++0x) alias template.
Douglas Gregorec5e6962011-01-05 17:33:50 +00001051 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregor788cd062009-11-11 01:00:40 +00001052 }
1053 }
1054 }
1055
Douglas Gregorec5e6962011-01-05 17:33:50 +00001056 // If this is a pack expansion, build it as such.
1057 if (EllipsisLoc.isValid() && !Result.isInvalid())
1058 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1059
1060 return Result;
Douglas Gregor788cd062009-11-11 01:00:40 +00001061}
1062
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001063/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1064///
1065/// template-argument: [C++ 14.2]
Douglas Gregorac7610d2009-06-22 20:57:11 +00001066/// constant-expression
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001067/// type-id
1068/// id-expression
Douglas Gregor314b97f2009-11-10 19:49:08 +00001069ParsedTemplateArgument Parser::ParseTemplateArgument() {
Douglas Gregor55f6b142009-02-09 18:46:07 +00001070 // C++ [temp.arg]p2:
1071 // In a template-argument, an ambiguity between a type-id and an
1072 // expression is resolved to a type-id, regardless of the form of
1073 // the corresponding template-parameter.
1074 //
Douglas Gregor314b97f2009-11-10 19:49:08 +00001075 // Therefore, we initially try to parse a type-id.
Douglas Gregor8b642592009-02-10 00:53:15 +00001076 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor314b97f2009-11-10 19:49:08 +00001077 SourceLocation Loc = Tok.getLocation();
Douglas Gregor683a81f2011-01-31 16:09:46 +00001078 TypeResult TypeArg = ParseTypeName(/*Range=*/0,
1079 Declarator::TemplateTypeArgContext);
Douglas Gregor809070a2009-02-18 17:45:20 +00001080 if (TypeArg.isInvalid())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001081 return ParsedTemplateArgument();
1082
John McCallb3d87482010-08-24 05:47:05 +00001083 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1084 TypeArg.get().getAsOpaquePtr(),
Douglas Gregor314b97f2009-11-10 19:49:08 +00001085 Loc);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001086 }
Douglas Gregor788cd062009-11-11 01:00:40 +00001087
1088 // Try to parse a template template argument.
Douglas Gregoreaf75f42009-11-12 00:03:40 +00001089 {
1090 TentativeParsingAction TPA(*this);
1091
1092 ParsedTemplateArgument TemplateTemplateArgument
1093 = ParseTemplateTemplateArgument();
1094 if (!TemplateTemplateArgument.isInvalid()) {
1095 TPA.Commit();
1096 return TemplateTemplateArgument;
1097 }
1098
1099 // Revert this tentative parse to parse a non-type template argument.
1100 TPA.Revert();
1101 }
Douglas Gregor314b97f2009-11-10 19:49:08 +00001102
1103 // Parse a non-type template argument.
1104 SourceLocation Loc = Tok.getLocation();
Kaelyn Uhraine43fe992012-02-22 01:03:07 +00001105 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001106 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001107 return ParsedTemplateArgument();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001108
Douglas Gregor314b97f2009-11-10 19:49:08 +00001109 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1110 ExprArg.release(), Loc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001111}
1112
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001113/// \brief Determine whether the current tokens can only be parsed as a
1114/// template argument list (starting with the '<') and never as a '<'
1115/// expression.
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001116bool Parser::IsTemplateArgumentList(unsigned Skip) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001117 struct AlwaysRevertAction : TentativeParsingAction {
1118 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1119 ~AlwaysRevertAction() { Revert(); }
1120 } Tentative(*this);
1121
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001122 while (Skip) {
1123 ConsumeToken();
1124 --Skip;
1125 }
1126
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001127 // '<'
1128 if (!Tok.is(tok::less))
1129 return false;
1130 ConsumeToken();
1131
1132 // An empty template argument list.
1133 if (Tok.is(tok::greater))
1134 return true;
1135
1136 // See whether we have declaration specifiers, which indicate a type.
1137 while (isCXXDeclarationSpecifier() == TPResult::True())
1138 ConsumeToken();
1139
1140 // If we have a '>' or a ',' then this is a template argument list.
1141 return Tok.is(tok::greater) || Tok.is(tok::comma);
1142}
1143
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001144/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1145/// (C++ [temp.names]). Returns true if there was an error.
1146///
1147/// template-argument-list: [C++ 14.2]
1148/// template-argument
1149/// template-argument-list ',' template-argument
Mike Stump1eb44332009-09-09 15:08:12 +00001150bool
Douglas Gregor314b97f2009-11-10 19:49:08 +00001151Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
Douglas Gregor79bef7a2013-05-03 23:44:54 +00001152 // Template argument lists are constant-evaluation contexts.
1153 EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated);
1154
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001155 while (true) {
Douglas Gregor314b97f2009-11-10 19:49:08 +00001156 ParsedTemplateArgument Arg = ParseTemplateArgument();
Douglas Gregor7536dd52010-12-20 02:24:11 +00001157 if (Tok.is(tok::ellipsis)) {
1158 SourceLocation EllipsisLoc = ConsumeToken();
1159 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1160 }
1161
Douglas Gregor314b97f2009-11-10 19:49:08 +00001162 if (Arg.isInvalid()) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001163 SkipUntil(tok::comma, tok::greater, true, true);
1164 return true;
1165 }
Douglas Gregor5908e9f2009-02-09 19:34:22 +00001166
Douglas Gregor314b97f2009-11-10 19:49:08 +00001167 // Save this template argument.
1168 TemplateArgs.push_back(Arg);
1169
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001170 // If the next token is a comma, consume it and keep reading
1171 // arguments.
1172 if (Tok.isNot(tok::comma)) break;
1173
1174 // Consume the comma.
1175 ConsumeToken();
1176 }
1177
Eli Friedman64a4eb22009-12-27 22:31:18 +00001178 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001179}
1180
Mike Stump1eb44332009-09-09 15:08:12 +00001181/// \brief Parse a C++ explicit template instantiation
Douglas Gregor1426e532009-05-12 21:31:51 +00001182/// (C++ [temp.explicit]).
1183///
1184/// explicit-instantiation:
Douglas Gregor45f96552009-09-04 06:33:52 +00001185/// 'extern' [opt] 'template' declaration
1186///
Richard Smithc7f81162013-03-18 22:52:47 +00001187/// Note that the 'extern' is a GNU extension and C++11 feature.
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001188Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1189 SourceLocation ExternLoc,
John McCalld226f652010-08-21 09:40:31 +00001190 SourceLocation TemplateLoc,
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001191 SourceLocation &DeclEnd,
1192 AccessSpecifier AS) {
John McCallc9068d72010-07-16 08:13:16 +00001193 // This isn't really required here.
John McCall92576642012-05-07 06:16:41 +00001194 ParsingDeclRAIIObject
1195 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
John McCallc9068d72010-07-16 08:13:16 +00001196
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001197 return ParseSingleDeclarationAfterTemplate(Context,
Douglas Gregor45f96552009-09-04 06:33:52 +00001198 ParsedTemplateInfo(ExternLoc,
1199 TemplateLoc),
John McCallc9068d72010-07-16 08:13:16 +00001200 ParsingTemplateParams,
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001201 DeclEnd, AS);
Douglas Gregor1426e532009-05-12 21:31:51 +00001202}
John McCall78b81052010-11-10 02:40:36 +00001203
1204SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1205 if (TemplateParams)
1206 return getTemplateParamsRange(TemplateParams->data(),
1207 TemplateParams->size());
1208
1209 SourceRange R(TemplateLoc);
1210 if (ExternLoc.isValid())
1211 R.setBegin(ExternLoc);
1212 return R;
1213}
Francois Pichet8387e2a2011-04-22 22:18:13 +00001214
Francois Pichet4a47e8d2011-04-23 11:52:20 +00001215void Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001216 ((Parser*)P)->LateTemplateParser(FD);
1217}
1218
1219
Francois Pichet4a47e8d2011-04-23 11:52:20 +00001220void Parser::LateTemplateParser(const FunctionDecl *FD) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001221 LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD];
1222 if (LPT) {
1223 ParseLateTemplatedFuncDef(*LPT);
1224 return;
1225 }
1226
1227 llvm_unreachable("Late templated function without associated lexed tokens");
1228}
David Blaikie219c2e22012-04-02 20:59:49 +00001229
1230/// \brief Late parse a C++ function template in Microsoft mode.
1231void Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) {
1232 if(!LMT.D)
1233 return;
1234
1235 // Get the FunctionDecl.
Richard Smith098b8142013-04-29 11:55:38 +00001236 FunctionTemplateDecl *FunTmplD = dyn_cast<FunctionTemplateDecl>(LMT.D);
1237 FunctionDecl *FunD =
1238 FunTmplD ? FunTmplD->getTemplatedDecl() : cast<FunctionDecl>(LMT.D);
1239 // Track template parameter depth.
1240 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
David Blaikie219c2e22012-04-02 20:59:49 +00001241
Francois Pichetd77177a2012-02-22 08:25:53 +00001242 // To restore the context after late parsing.
David Blaikie219c2e22012-04-02 20:59:49 +00001243 Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
1244
1245 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
David Blaikie219c2e22012-04-02 20:59:49 +00001246
Richard Smithfed844d2013-04-29 08:53:40 +00001247 // Get the list of DeclContexts to reenter.
1248 SmallVector<DeclContext*, 4> DeclContextsToReenter;
Richard Smith098b8142013-04-29 11:55:38 +00001249 DeclContext *DD = FunD->getLexicalParent();
Richard Smithfed844d2013-04-29 08:53:40 +00001250 while (DD && !DD->isTranslationUnit()) {
1251 DeclContextsToReenter.push_back(DD);
1252 DD = DD->getLexicalParent();
David Blaikie219c2e22012-04-02 20:59:49 +00001253 }
1254
Richard Smithfed844d2013-04-29 08:53:40 +00001255 // Reenter template scopes from outermost to innermost.
1256 SmallVector<DeclContext*, 4>::reverse_iterator II =
1257 DeclContextsToReenter.rbegin();
1258 for (; II != DeclContextsToReenter.rend(); ++II) {
1259 if (ClassTemplatePartialSpecializationDecl *MD =
1260 dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) {
1261 TemplateParamScopeStack.push_back(
1262 new ParseScope(this, Scope::TemplateParamScope));
1263 Actions.ActOnReenterTemplateScope(getCurScope(), MD);
Richard Smith098b8142013-04-29 11:55:38 +00001264 ++CurTemplateDepthTracker;
Richard Smithfed844d2013-04-29 08:53:40 +00001265 } else if (CXXRecordDecl *MD = dyn_cast_or_null<CXXRecordDecl>(*II)) {
1266 bool ManageScope = MD->getDescribedClassTemplate() != 0;
1267 TemplateParamScopeStack.push_back(
1268 new ParseScope(this, Scope::TemplateParamScope, ManageScope));
1269 Actions.ActOnReenterTemplateScope(getCurScope(),
1270 MD->getDescribedClassTemplate());
Richard Smith098b8142013-04-29 11:55:38 +00001271 ++CurTemplateDepthTracker;
Richard Smithfed844d2013-04-29 08:53:40 +00001272 }
1273 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1274 Actions.PushDeclContext(Actions.getCurScope(), *II);
1275 }
1276 TemplateParamScopeStack.push_back(
1277 new ParseScope(this, Scope::TemplateParamScope));
1278
Richard Smith098b8142013-04-29 11:55:38 +00001279 DeclaratorDecl *Declarator = dyn_cast<DeclaratorDecl>(FunD);
1280 if (Declarator && Declarator->getNumTemplateParameterLists() != 0) {
Richard Smithfed844d2013-04-29 08:53:40 +00001281 Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
Richard Smith098b8142013-04-29 11:55:38 +00001282 ++CurTemplateDepthTracker;
1283 }
Richard Smithfed844d2013-04-29 08:53:40 +00001284 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
Richard Smith098b8142013-04-29 11:55:38 +00001285 ++CurTemplateDepthTracker;
Richard Smithfed844d2013-04-29 08:53:40 +00001286
David Blaikie219c2e22012-04-02 20:59:49 +00001287 assert(!LMT.Toks.empty() && "Empty body!");
1288
1289 // Append the current token at the end of the new token stream so that it
1290 // doesn't get lost.
1291 LMT.Toks.push_back(Tok);
1292 PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false);
1293
1294 // Consume the previously pushed token.
Argyrios Kyrtzidisab2d09b2013-03-27 23:58:17 +00001295 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
David Blaikie219c2e22012-04-02 20:59:49 +00001296 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1297 && "Inline method not starting with '{', ':' or 'try'");
1298
1299 // Parse the method body. Function body parsing code is similar enough
1300 // to be re-used for method bodies as well.
1301 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1302
1303 // Recreate the containing function DeclContext.
Richard Smith098b8142013-04-29 11:55:38 +00001304 Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FunD));
David Blaikie219c2e22012-04-02 20:59:49 +00001305
Richard Smith098b8142013-04-29 11:55:38 +00001306 Actions.ActOnStartOfFunctionDef(getCurScope(), FunD);
David Blaikie219c2e22012-04-02 20:59:49 +00001307
1308 if (Tok.is(tok::kw_try)) {
1309 ParseFunctionTryBlock(LMT.D, FnScope);
1310 } else {
1311 if (Tok.is(tok::colon))
1312 ParseConstructorInitializer(LMT.D);
1313 else
1314 Actions.ActOnDefaultCtorInitializers(LMT.D);
1315
1316 if (Tok.is(tok::l_brace)) {
Richard Smith098b8142013-04-29 11:55:38 +00001317 assert((!FunTmplD || FunTmplD->getTemplateParameters()->getDepth() <
1318 TemplateParameterDepth) &&
1319 "TemplateParameterDepth should be greater than the depth of "
1320 "current template being instantiated!");
David Blaikie219c2e22012-04-02 20:59:49 +00001321 ParseFunctionStatementBody(LMT.D, FnScope);
Richard Smith098b8142013-04-29 11:55:38 +00001322 Actions.MarkAsLateParsedTemplate(FunD, false);
David Blaikie219c2e22012-04-02 20:59:49 +00001323 } else
1324 Actions.ActOnFinishFunctionBody(LMT.D, 0);
1325 }
1326
1327 // Exit scopes.
Francois Pichetfdde4702011-09-22 22:14:56 +00001328 FnScope.Exit();
David Blaikie219c2e22012-04-02 20:59:49 +00001329 SmallVector<ParseScope*, 4>::reverse_iterator I =
1330 TemplateParamScopeStack.rbegin();
1331 for (; I != TemplateParamScopeStack.rend(); ++I)
1332 delete *I;
1333
1334 DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D);
1335 if (grp)
1336 Actions.getASTConsumer().HandleTopLevelDecl(grp.get());
Francois Pichet8387e2a2011-04-22 22:18:13 +00001337}
1338
1339/// \brief Lex a delayed template function for late parsing.
1340void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1341 tok::TokenKind kind = Tok.getKind();
Sebastian Redla891a322011-09-30 08:32:17 +00001342 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1343 // Consume everything up to (and including) the matching right brace.
1344 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001345 }
Francois Pichet8387e2a2011-04-22 22:18:13 +00001346
1347 // If we're in a function-try-block, we need to store all the catch blocks.
1348 if (kind == tok::kw_try) {
1349 while (Tok.is(tok::kw_catch)) {
1350 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1351 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1352 }
1353 }
1354}