blob: f8204d9cda5ec5ecc73dfbcc40daa34dc8f082ac [file] [log] [blame]
Douglas Gregoreb31f392008-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"
Chris Lattner60f36222009-01-29 05:15:15 +000015#include "clang/Parse/ParseDiagnostic.h"
John McCall8b0666c2010-08-20 18:27:03 +000016#include "clang/Sema/DeclSpec.h"
17#include "clang/Sema/ParsedTemplate.h"
18#include "clang/Sema/Scope.h"
Chris Lattnerb2434d52009-12-10 00:45:15 +000019#include "RAIIObjectsForParser.h"
Francois Pichet1c229c02011-04-22 22:18:13 +000020#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/ASTConsumer.h"
Douglas Gregoreb31f392008-12-01 23:54:00 +000022using namespace clang;
23
Douglas Gregor1b57ff32009-05-12 23:25:50 +000024/// \brief Parse a template declaration, explicit instantiation, or
25/// explicit specialization.
John McCall48871652010-08-21 09:40:31 +000026Decl *
Douglas Gregor1b57ff32009-05-12 23:25:50 +000027Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
28 SourceLocation &DeclEnd,
Erik Verbruggenca98f2a2011-10-13 09:41:32 +000029 AccessSpecifier AS,
30 AttributeList *AccessAttrs) {
Fariborz Jahanian4bf82622011-08-22 17:59:19 +000031 ObjCDeclContextSwitch ObjCDC(*this);
32
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000033 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
Argyrios Kyrtzidis26440632011-12-23 02:16:45 +000034 return ParseExplicitInstantiation(Context,
35 SourceLocation(), ConsumeToken(),
36 DeclEnd, AS);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000037 }
Erik Verbruggenca98f2a2011-10-13 09:41:32 +000038 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
39 AccessAttrs);
Douglas Gregor1b57ff32009-05-12 23:25:50 +000040}
41
Douglas Gregora3dff8e2009-08-24 23:03:25 +000042/// \brief RAII class that manages the template parameter depth.
43namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +000044 class TemplateParameterDepthCounter {
Douglas Gregora3dff8e2009-08-24 23:03:25 +000045 unsigned &Depth;
46 unsigned AddedLevels;
47
48 public:
Mike Stump11289f42009-09-09 15:08:12 +000049 explicit TemplateParameterDepthCounter(unsigned &Depth)
Douglas Gregora3dff8e2009-08-24 23:03:25 +000050 : Depth(Depth), AddedLevels(0) { }
Mike Stump11289f42009-09-09 15:08:12 +000051
Douglas Gregora3dff8e2009-08-24 23:03:25 +000052 ~TemplateParameterDepthCounter() {
53 Depth -= AddedLevels;
54 }
Mike Stump11289f42009-09-09 15:08:12 +000055
56 void operator++() {
Douglas Gregora3dff8e2009-08-24 23:03:25 +000057 ++Depth;
58 ++AddedLevels;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Douglas Gregora3dff8e2009-08-24 23:03:25 +000061 operator unsigned() const { return Depth; }
62 };
63}
64
Douglas Gregor67a65642009-02-17 23:15:12 +000065/// \brief Parse a template declaration or an explicit specialization.
66///
67/// Template declarations include one or more template parameter lists
68/// and either the function or class template declaration. Explicit
69/// specializations contain one or more 'template < >' prefixes
70/// followed by a (possibly templated) declaration. Since the
71/// syntactic form of both features is nearly identical, we parse all
72/// of the template headers together and let semantic analysis sort
73/// the declarations from the explicit specializations.
Douglas Gregoreb31f392008-12-01 23:54:00 +000074///
75/// template-declaration: [C++ temp]
76/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
Douglas Gregor67a65642009-02-17 23:15:12 +000077///
78/// explicit-specialization: [ C++ temp.expl.spec]
79/// 'template' '<' '>' declaration
John McCall48871652010-08-21 09:40:31 +000080Decl *
Anders Carlssondfbbdf62009-03-26 00:52:18 +000081Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
Chris Lattner49836b42009-04-02 04:16:50 +000082 SourceLocation &DeclEnd,
Erik Verbruggenca98f2a2011-10-13 09:41:32 +000083 AccessSpecifier AS,
84 AttributeList *AccessAttrs) {
Mike Stump11289f42009-09-09 15:08:12 +000085 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
86 "Token does not start a template declaration.");
87
Douglas Gregorf5586182008-12-02 00:41:28 +000088 // Enter template-parameter scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +000089 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Douglas Gregorf5586182008-12-02 00:41:28 +000090
John McCall796c2a52010-07-16 08:13:16 +000091 // Tell the action that names should be checked in the context of
92 // the declaration to come.
93 ParsingDeclRAIIObject ParsingTemplateParams(*this);
94
Douglas Gregorb9bd8a92008-12-24 02:52:09 +000095 // Parse multiple levels of template headers within this template
96 // parameter scope, e.g.,
97 //
98 // template<typename T>
99 // template<typename U>
100 // class A<T>::B { ... };
101 //
102 // We parse multiple levels non-recursively so that we can build a
103 // single data structure containing all of the template parameter
Douglas Gregor67a65642009-02-17 23:15:12 +0000104 // lists to easily differentiate between the case above and:
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000105 //
106 // template<typename T>
107 // class A {
108 // template<typename U> class B;
109 // };
110 //
111 // In the first case, the action for declaring A<T>::B receives
112 // both template parameter lists. In the second case, the action for
113 // defining A<T>::B receives just the inner template parameter list
114 // (and retrieves the outer template parameter list from its
115 // context).
Douglas Gregor468535e2009-08-20 18:46:05 +0000116 bool isSpecialization = true;
Douglas Gregor1d0015f2009-10-30 22:09:44 +0000117 bool LastParamListWasEmpty = false;
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000118 TemplateParameterLists ParamLists;
Douglas Gregora3dff8e2009-08-24 23:03:25 +0000119 TemplateParameterDepthCounter Depth(TemplateParameterDepth);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000120 do {
121 // Consume the 'export', if any.
122 SourceLocation ExportLoc;
123 if (Tok.is(tok::kw_export)) {
124 ExportLoc = ConsumeToken();
125 }
126
127 // Consume the 'template', which should be here.
128 SourceLocation TemplateLoc;
129 if (Tok.is(tok::kw_template)) {
130 TemplateLoc = ConsumeToken();
131 } else {
132 Diag(Tok.getLocation(), diag::err_expected_template);
John McCall48871652010-08-21 09:40:31 +0000133 return 0;
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000134 }
Mike Stump11289f42009-09-09 15:08:12 +0000135
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000136 // Parse the '<' template-parameter-list '>'
137 SourceLocation LAngleLoc, RAngleLoc;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000138 SmallVector<Decl*, 4> TemplateParams;
Mike Stump11289f42009-09-09 15:08:12 +0000139 if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +0000140 RAngleLoc)) {
141 // Skip until the semi-colon or a }.
142 SkipUntil(tok::r_brace, true, true);
143 if (Tok.is(tok::semi))
144 ConsumeToken();
John McCall48871652010-08-21 09:40:31 +0000145 return 0;
Douglas Gregore93e46c2009-07-22 23:48:44 +0000146 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +0000147
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000148 ParamLists.push_back(
Mike Stump11289f42009-09-09 15:08:12 +0000149 Actions.ActOnTemplateParameterList(Depth, ExportLoc,
150 TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +0000151 TemplateParams.data(),
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000152 TemplateParams.size(), RAngleLoc));
Douglas Gregora3dff8e2009-08-24 23:03:25 +0000153
154 if (!TemplateParams.empty()) {
155 isSpecialization = false;
156 ++Depth;
Douglas Gregor1d0015f2009-10-30 22:09:44 +0000157 } else {
158 LastParamListWasEmpty = true;
Mike Stump11289f42009-09-09 15:08:12 +0000159 }
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000160 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
161
162 // Parse the actual template declaration.
Mike Stump11289f42009-09-09 15:08:12 +0000163 return ParseSingleDeclarationAfterTemplate(Context,
Douglas Gregor1b57ff32009-05-12 23:25:50 +0000164 ParsedTemplateInfo(&ParamLists,
Douglas Gregor1d0015f2009-10-30 22:09:44 +0000165 isSpecialization,
166 LastParamListWasEmpty),
John McCall796c2a52010-07-16 08:13:16 +0000167 ParsingTemplateParams,
Erik Verbruggenca98f2a2011-10-13 09:41:32 +0000168 DeclEnd, AS, AccessAttrs);
Douglas Gregor23996282009-05-12 21:31:51 +0000169}
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000170
Douglas Gregor23996282009-05-12 21:31:51 +0000171/// \brief Parse a single declaration that declares a template,
172/// template specialization, or explicit instantiation of a template.
173///
174/// \param TemplateParams if non-NULL, the template parameter lists
175/// that preceded this declaration. In this case, the declaration is a
176/// template declaration, out-of-line definition of a template, or an
177/// explicit template specialization. When NULL, the declaration is an
178/// explicit template instantiation.
179///
180/// \param TemplateLoc when TemplateParams is NULL, the location of
181/// the 'template' keyword that indicates that we have an explicit
182/// template instantiation.
183///
184/// \param DeclEnd will receive the source location of the last token
185/// within this declaration.
186///
187/// \param AS the access specifier associated with this
188/// declaration. Will be AS_none for namespace-scope declarations.
189///
190/// \returns the new declaration.
John McCall48871652010-08-21 09:40:31 +0000191Decl *
Douglas Gregor23996282009-05-12 21:31:51 +0000192Parser::ParseSingleDeclarationAfterTemplate(
193 unsigned Context,
Douglas Gregor1b57ff32009-05-12 23:25:50 +0000194 const ParsedTemplateInfo &TemplateInfo,
John McCall796c2a52010-07-16 08:13:16 +0000195 ParsingDeclRAIIObject &DiagsFromTParams,
Douglas Gregor23996282009-05-12 21:31:51 +0000196 SourceLocation &DeclEnd,
Erik Verbruggenca98f2a2011-10-13 09:41:32 +0000197 AccessSpecifier AS,
198 AttributeList *AccessAttrs) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +0000199 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
200 "Template information required");
201
Douglas Gregor3447e762009-08-20 22:52:58 +0000202 if (Context == Declarator::MemberContext) {
203 // We are parsing a member template.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +0000204 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
205 &DiagsFromTParams);
John McCall48871652010-08-21 09:40:31 +0000206 return 0;
Douglas Gregor3447e762009-08-20 22:52:58 +0000207 }
Mike Stump11289f42009-09-09 15:08:12 +0000208
John McCall084e83d2011-03-24 11:26:52 +0000209 ParsedAttributesWithRange prefixAttrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +0000210 MaybeParseCXX0XAttributes(prefixAttrs);
John McCall9b72f892010-11-10 02:40:36 +0000211
212 if (Tok.is(tok::kw_using))
213 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000214 prefixAttrs);
John McCall9b72f892010-11-10 02:40:36 +0000215
John McCall796c2a52010-07-16 08:13:16 +0000216 // Parse the declaration specifiers, stealing the accumulated
217 // diagnostics from the template parameters.
John McCall084e83d2011-03-24 11:26:52 +0000218 ParsingDeclSpec DS(*this, &DiagsFromTParams);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000219
John McCall53fa7142010-12-24 02:08:15 +0000220 DS.takeAttributesFrom(prefixAttrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000221
Douglas Gregor9de54ea2010-01-13 17:31:36 +0000222 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
223 getDeclSpecContextFromDeclaratorContext(Context));
Douglas Gregor23996282009-05-12 21:31:51 +0000224
225 if (Tok.is(tok::semi)) {
226 DeclEnd = ConsumeToken();
John McCall48871652010-08-21 09:40:31 +0000227 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
John McCall28a6aea2009-11-04 02:18:39 +0000228 DS.complete(Decl);
229 return Decl;
Douglas Gregor23996282009-05-12 21:31:51 +0000230 }
231
232 // Parse the declarator.
John McCall28a6aea2009-11-04 02:18:39 +0000233 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
Douglas Gregor23996282009-05-12 21:31:51 +0000234 ParseDeclarator(DeclaratorInfo);
235 // Error parsing the declarator?
236 if (!DeclaratorInfo.hasName()) {
237 // If so, skip until the semi-colon or a }.
238 SkipUntil(tok::r_brace, true, true);
239 if (Tok.is(tok::semi))
240 ConsumeToken();
John McCall48871652010-08-21 09:40:31 +0000241 return 0;
Douglas Gregor23996282009-05-12 21:31:51 +0000242 }
Mike Stump11289f42009-09-09 15:08:12 +0000243
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +0000244 LateParsedAttrList LateParsedAttrs;
245 if (DeclaratorInfo.isFunctionDeclarator())
246 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
247
Douglas Gregor23996282009-05-12 21:31:51 +0000248 // If we have a declaration or declarator list, handle it.
249 if (isDeclarationAfterDeclarator()) {
250 // Parse this declaration.
John McCall48871652010-08-21 09:40:31 +0000251 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
252 TemplateInfo);
Douglas Gregor23996282009-05-12 21:31:51 +0000253
254 if (Tok.is(tok::comma)) {
255 Diag(Tok, diag::err_multiple_template_declarators)
Douglas Gregor1b57ff32009-05-12 23:25:50 +0000256 << (int)TemplateInfo.Kind;
Douglas Gregor23996282009-05-12 21:31:51 +0000257 SkipUntil(tok::semi, true, false);
258 return ThisDecl;
259 }
260
261 // Eat the semi colon after the declaration.
John McCallef50e992009-07-31 02:20:35 +0000262 ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +0000263 if (LateParsedAttrs.size() > 0)
264 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
John McCallc1465822011-02-14 07:13:47 +0000265 DeclaratorInfo.complete(ThisDecl);
Douglas Gregor23996282009-05-12 21:31:51 +0000266 return ThisDecl;
267 }
268
269 if (DeclaratorInfo.isFunctionDeclarator() &&
Chris Lattner13901342010-07-11 22:42:07 +0000270 isStartOfFunctionDefinition(DeclaratorInfo)) {
Douglas Gregor23996282009-05-12 21:31:51 +0000271 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Smith53711602011-11-29 09:09:06 +0000272 // Recover by ignoring the 'typedef'. This was probably supposed to be
273 // the 'typename' keyword, which we should have already suggested adding
274 // if it's appropriate.
275 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
276 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith675ea992011-11-29 05:27:40 +0000277 DS.ClearStorageClassSpecs();
Douglas Gregor23996282009-05-12 21:31:51 +0000278 }
DeLesley Hutchins3fc6e4a2012-02-16 16:50:43 +0000279 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
280 &LateParsedAttrs);
Douglas Gregor23996282009-05-12 21:31:51 +0000281 }
282
283 if (DeclaratorInfo.isFunctionDeclarator())
284 Diag(Tok, diag::err_expected_fn_body);
285 else
286 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
287 SkipUntil(tok::semi);
John McCall48871652010-08-21 09:40:31 +0000288 return 0;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000289}
290
291/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000292/// angle brackets. Depth is the depth of this template-parameter-list, which
293/// is the number of template headers directly enclosing this template header.
294/// TemplateParams is the current list of template parameters we're building.
295/// The template parameter we parse will be added to this list. LAngleLoc and
Mike Stump11289f42009-09-09 15:08:12 +0000296/// RAngleLoc will receive the positions of the '<' and '>', respectively,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000297/// that enclose this template parameter list.
Douglas Gregore93e46c2009-07-22 23:48:44 +0000298///
299/// \returns true if an error occurred, false otherwise.
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000300bool Parser::ParseTemplateParameters(unsigned Depth,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000301 SmallVectorImpl<Decl*> &TemplateParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000302 SourceLocation &LAngleLoc,
303 SourceLocation &RAngleLoc) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000304 // Get the template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +0000305 if (!Tok.is(tok::less)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000306 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
Douglas Gregore93e46c2009-07-22 23:48:44 +0000307 return true;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000308 }
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000309 LAngleLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000310
Douglas Gregoreb31f392008-12-01 23:54:00 +0000311 // Try to parse the template parameter list.
David Blaikie80cdddc2012-04-09 16:37:11 +0000312 bool Failed = false;
313 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
314 Failed = ParseTemplateParameterList(Depth, TemplateParams);
315
316 if (Tok.is(tok::greatergreater)) {
317 Tok.setKind(tok::greater);
318 RAngleLoc = Tok.getLocation();
319 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
320 } else if (Tok.is(tok::greater))
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000321 RAngleLoc = ConsumeToken();
David Blaikie80cdddc2012-04-09 16:37:11 +0000322 else if (Failed) {
323 Diag(Tok.getLocation(), diag::err_expected_greater);
324 return true;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000325 }
Douglas Gregore93e46c2009-07-22 23:48:44 +0000326 return false;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000327}
328
329/// ParseTemplateParameterList - Parse a template parameter list. If
330/// the parsing fails badly (i.e., closing bracket was left out), this
331/// will try to put the token stream in a reasonable position (closing
Mike Stump11289f42009-09-09 15:08:12 +0000332/// a statement, etc.) and return false.
Douglas Gregoreb31f392008-12-01 23:54:00 +0000333///
334/// template-parameter-list: [C++ temp]
335/// template-parameter
336/// template-parameter-list ',' template-parameter
Mike Stump11289f42009-09-09 15:08:12 +0000337bool
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000338Parser::ParseTemplateParameterList(unsigned Depth,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000339 SmallVectorImpl<Decl*> &TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +0000340 while (1) {
John McCall48871652010-08-21 09:40:31 +0000341 if (Decl *TmpParam
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000342 = ParseTemplateParameter(Depth, TemplateParams.size())) {
343 TemplateParams.push_back(TmpParam);
344 } else {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000345 // If we failed to parse a template parameter, skip until we find
346 // a comma or closing brace.
David Blaikiecbd81252012-04-06 05:26:43 +0000347 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000348 }
Mike Stump11289f42009-09-09 15:08:12 +0000349
Douglas Gregoreb31f392008-12-01 23:54:00 +0000350 // Did we find a comma or the end of the template parmeter list?
Mike Stump11289f42009-09-09 15:08:12 +0000351 if (Tok.is(tok::comma)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000352 ConsumeToken();
David Blaikiecbd81252012-04-06 05:26:43 +0000353 } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000354 // Don't consume this... that's done by template parser.
355 break;
356 } else {
357 // Somebody probably forgot to close the template. Skip ahead and
358 // try to get out of the expression. This error is currently
359 // subsumed by whatever goes on in ParseTemplateParameter.
Douglas Gregorb0484022010-10-15 01:15:58 +0000360 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
David Blaikie80cdddc2012-04-09 16:37:11 +0000361 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000362 return false;
363 }
364 }
365 return true;
366}
367
Douglas Gregor26aedb72009-11-21 02:07:55 +0000368/// \brief Determine whether the parser is at the start of a template
369/// type parameter.
370bool Parser::isStartOfTemplateTypeParameter() {
Douglas Gregor71b209d2010-06-04 07:30:15 +0000371 if (Tok.is(tok::kw_class)) {
372 // "class" may be the start of an elaborated-type-specifier or a
373 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
374 switch (NextToken().getKind()) {
375 case tok::equal:
376 case tok::comma:
377 case tok::greater:
378 case tok::greatergreater:
379 case tok::ellipsis:
380 return true;
381
382 case tok::identifier:
383 // This may be either a type-parameter or an elaborated-type-specifier.
384 // We have to look further.
385 break;
386
387 default:
388 return false;
389 }
390
391 switch (GetLookAheadToken(2).getKind()) {
392 case tok::equal:
393 case tok::comma:
394 case tok::greater:
395 case tok::greatergreater:
396 return true;
397
398 default:
399 return false;
400 }
401 }
Douglas Gregor26aedb72009-11-21 02:07:55 +0000402
403 if (Tok.isNot(tok::kw_typename))
404 return false;
405
406 // C++ [temp.param]p2:
407 // There is no semantic difference between class and typename in a
408 // template-parameter. typename followed by an unqualified-id
409 // names a template type parameter. typename followed by a
410 // qualified-id denotes the type in a non-type
411 // parameter-declaration.
412 Token Next = NextToken();
413
414 // If we have an identifier, skip over it.
415 if (Next.getKind() == tok::identifier)
416 Next = GetLookAheadToken(2);
417
418 switch (Next.getKind()) {
419 case tok::equal:
420 case tok::comma:
421 case tok::greater:
422 case tok::greatergreater:
423 case tok::ellipsis:
424 return true;
425
426 default:
427 return false;
428 }
429}
430
Douglas Gregoreb31f392008-12-01 23:54:00 +0000431/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
432///
433/// template-parameter: [C++ temp.param]
434/// type-parameter
435/// parameter-declaration
436///
437/// type-parameter: (see below)
Douglas Gregorf5500772011-01-05 15:48:55 +0000438/// 'class' ...[opt] identifier[opt]
Douglas Gregoreb31f392008-12-01 23:54:00 +0000439/// 'class' identifier[opt] '=' type-id
Douglas Gregorf5500772011-01-05 15:48:55 +0000440/// 'typename' ...[opt] identifier[opt]
Douglas Gregoreb31f392008-12-01 23:54:00 +0000441/// 'typename' identifier[opt] '=' type-id
Douglas Gregorf5500772011-01-05 15:48:55 +0000442/// 'template' '<' template-parameter-list '>'
443/// 'class' ...[opt] identifier[opt]
444/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
445/// = id-expression
John McCall48871652010-08-21 09:40:31 +0000446Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26aedb72009-11-21 02:07:55 +0000447 if (isStartOfTemplateTypeParameter())
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000448 return ParseTypeParameter(Depth, Position);
Mike Stump11289f42009-09-09 15:08:12 +0000449
450 if (Tok.is(tok::kw_template))
Chris Lattnera21db612009-01-04 23:51:17 +0000451 return ParseTemplateTemplateParameter(Depth, Position);
452
453 // If it's none of the above, then it must be a parameter declaration.
454 // NOTE: This will pick up errors in the closure of the template parameter
455 // list (e.g., template < ; Check here to implement >> style closures.
456 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000457}
458
459/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
460/// Other kinds of template parameters are parsed in
461/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
462///
463/// type-parameter: [C++ temp.param]
Anders Carlssonf986ba72009-06-12 23:09:56 +0000464/// 'class' ...[opt][C++0x] identifier[opt]
Douglas Gregoreb31f392008-12-01 23:54:00 +0000465/// 'class' identifier[opt] '=' type-id
Anders Carlssonf986ba72009-06-12 23:09:56 +0000466/// 'typename' ...[opt][C++0x] identifier[opt]
Douglas Gregoreb31f392008-12-01 23:54:00 +0000467/// 'typename' identifier[opt] '=' type-id
John McCall48871652010-08-21 09:40:31 +0000468Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Douglas Gregorf5586182008-12-02 00:41:28 +0000469 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
Mike Stump11289f42009-09-09 15:08:12 +0000470 "A type-parameter starts with 'class' or 'typename'");
Douglas Gregorf5586182008-12-02 00:41:28 +0000471
472 // Consume the 'class' or 'typename' keyword.
473 bool TypenameKeyword = Tok.is(tok::kw_typename);
474 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregoreb31f392008-12-01 23:54:00 +0000475
Anders Carlsson01e9e932009-06-12 19:58:00 +0000476 // Grab the ellipsis (if given).
477 bool Ellipsis = false;
478 SourceLocation EllipsisLoc;
Anders Carlssonf986ba72009-06-12 23:09:56 +0000479 if (Tok.is(tok::ellipsis)) {
Anders Carlsson01e9e932009-06-12 19:58:00 +0000480 Ellipsis = true;
481 EllipsisLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000482
Richard Smith96bd62f2011-10-14 20:31:37 +0000483 Diag(EllipsisLoc,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000484 getLangOpts().CPlusPlus0x
Richard Smith96bd62f2011-10-14 20:31:37 +0000485 ? diag::warn_cxx98_compat_variadic_templates
486 : diag::ext_variadic_templates);
Anders Carlsson01e9e932009-06-12 19:58:00 +0000487 }
Mike Stump11289f42009-09-09 15:08:12 +0000488
Douglas Gregoreb31f392008-12-01 23:54:00 +0000489 // Grab the template parameter name (if given)
Douglas Gregorf5586182008-12-02 00:41:28 +0000490 SourceLocation NameLoc;
491 IdentifierInfo* ParamName = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000492 if (Tok.is(tok::identifier)) {
Douglas Gregorf5586182008-12-02 00:41:28 +0000493 ParamName = Tok.getIdentifierInfo();
494 NameLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000495 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
David Blaikiecbd81252012-04-06 05:26:43 +0000496 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000497 // Unnamed template parameter. Don't have to do anything here, just
498 // don't consume this token.
499 } else {
500 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCall48871652010-08-21 09:40:31 +0000501 return 0;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000502 }
Mike Stump11289f42009-09-09 15:08:12 +0000503
Douglas Gregordc13ded2010-07-01 00:00:45 +0000504 // Grab a default argument (if available).
505 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
506 // we introduce the type parameter into the local scope.
507 SourceLocation EqualLoc;
John McCallba7bf592010-08-24 05:47:05 +0000508 ParsedType DefaultArg;
Mike Stump11289f42009-09-09 15:08:12 +0000509 if (Tok.is(tok::equal)) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000510 EqualLoc = ConsumeToken();
Richard Smith63168c72012-02-10 11:05:11 +0000511 DefaultArg = ParseTypeName(/*Range=*/0,
512 Declarator::TemplateTypeArgContext).get();
Douglas Gregoreb31f392008-12-01 23:54:00 +0000513 }
Richard Smith63168c72012-02-10 11:05:11 +0000514
Douglas Gregor0be31a22010-07-02 17:43:08 +0000515 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000516 EllipsisLoc, KeyLoc, ParamName, NameLoc,
517 Depth, Position, EqualLoc, DefaultArg);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000518}
519
520/// ParseTemplateTemplateParameter - Handle the parsing of template
Mike Stump11289f42009-09-09 15:08:12 +0000521/// template parameters.
Douglas Gregoreb31f392008-12-01 23:54:00 +0000522///
523/// type-parameter: [C++ temp.param]
Douglas Gregorf5500772011-01-05 15:48:55 +0000524/// 'template' '<' template-parameter-list '>' 'class'
525/// ...[opt] identifier[opt]
526/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
527/// = id-expression
John McCall48871652010-08-21 09:40:31 +0000528Decl *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000529Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000530 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
531
532 // Handle the template <...> part.
533 SourceLocation TemplateLoc = ConsumeToken();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000534 SmallVector<Decl*,8> TemplateParams;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000535 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor85e8b3e2009-02-10 19:52:54 +0000536 {
537 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Mike Stump11289f42009-09-09 15:08:12 +0000538 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +0000539 RAngleLoc)) {
John McCall48871652010-08-21 09:40:31 +0000540 return 0;
Douglas Gregor85e8b3e2009-02-10 19:52:54 +0000541 }
Douglas Gregoreb31f392008-12-01 23:54:00 +0000542 }
543
544 // Generate a meaningful error if the user forgot to put class before the
David Blaikiecbd81252012-04-06 05:26:43 +0000545 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
546 // or greater appear immediately or after 'typename' or 'struct'. In the
547 // latter case, replace the keyword with 'class'.
548 if (!Tok.is(tok::kw_class)) {
549 bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
550 const Token& Next = Replace ? NextToken() : Tok;
551 if (Next.is(tok::identifier) || Next.is(tok::comma) ||
552 Next.is(tok::greater) || Next.is(tok::greatergreater) ||
553 Next.is(tok::ellipsis))
554 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
555 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
556 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
557 else
558 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
559
560 if (Replace)
561 ConsumeToken();
562 } else
David Blaikief221e512012-04-02 19:15:28 +0000563 ConsumeToken();
Douglas Gregoreb31f392008-12-01 23:54:00 +0000564
Douglas Gregorf5500772011-01-05 15:48:55 +0000565 // Parse the ellipsis, if given.
566 SourceLocation EllipsisLoc;
567 if (Tok.is(tok::ellipsis)) {
568 EllipsisLoc = ConsumeToken();
569
Richard Smith96bd62f2011-10-14 20:31:37 +0000570 Diag(EllipsisLoc,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000571 getLangOpts().CPlusPlus0x
Richard Smith96bd62f2011-10-14 20:31:37 +0000572 ? diag::warn_cxx98_compat_variadic_templates
573 : diag::ext_variadic_templates);
Douglas Gregorf5500772011-01-05 15:48:55 +0000574 }
575
Douglas Gregoreb31f392008-12-01 23:54:00 +0000576 // Get the identifier, if given.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000577 SourceLocation NameLoc;
578 IdentifierInfo* ParamName = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000579 if (Tok.is(tok::identifier)) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000580 ParamName = Tok.getIdentifierInfo();
581 NameLoc = ConsumeToken();
David Blaikiecbd81252012-04-06 05:26:43 +0000582 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
583 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000584 // Unnamed template parameter. Don't have to do anything here, just
585 // don't consume this token.
586 } else {
587 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCall48871652010-08-21 09:40:31 +0000588 return 0;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000589 }
590
Richard Trieu9becef62011-09-09 03:18:59 +0000591 TemplateParameterList *ParamList =
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000592 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
593 TemplateLoc, LAngleLoc,
Douglas Gregora02bb372010-10-21 17:26:49 +0000594 TemplateParams.data(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000595 TemplateParams.size(),
596 RAngleLoc);
597
Douglas Gregordc13ded2010-07-01 00:00:45 +0000598 // Grab a default argument (if available).
599 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
600 // we introduce the template parameter into the local scope.
601 SourceLocation EqualLoc;
602 ParsedTemplateArgument DefaultArg;
Douglas Gregordba32632009-02-10 19:49:53 +0000603 if (Tok.is(tok::equal)) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000604 EqualLoc = ConsumeToken();
605 DefaultArg = ParseTemplateTemplateArgument();
606 if (DefaultArg.isInvalid()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000607 Diag(Tok.getLocation(),
608 diag::err_default_template_template_parameter_not_template);
David Blaikie80cdddc2012-04-09 16:37:11 +0000609 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000610 }
Douglas Gregordba32632009-02-10 19:49:53 +0000611 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000612
Douglas Gregor0be31a22010-07-02 17:43:08 +0000613 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000614 ParamList, EllipsisLoc,
615 ParamName, NameLoc, Depth,
616 Position, EqualLoc, DefaultArg);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000617}
618
619/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
Mike Stump11289f42009-09-09 15:08:12 +0000620/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000621///
Douglas Gregoreb31f392008-12-01 23:54:00 +0000622/// template-parameter:
623/// ...
624/// parameter-declaration
John McCall48871652010-08-21 09:40:31 +0000625Decl *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000626Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000627 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregorf5586182008-12-02 00:41:28 +0000628 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregoreb31f392008-12-01 23:54:00 +0000629 // declarators (parts of declarators?) are accepted for parameters.
John McCall084e83d2011-03-24 11:26:52 +0000630 DeclSpec DS(AttrFactory);
Douglas Gregorf5586182008-12-02 00:41:28 +0000631 ParseDeclarationSpecifiers(DS);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000632
633 // Parse this as a typename.
Douglas Gregorf5586182008-12-02 00:41:28 +0000634 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
635 ParseDeclarator(ParamDecl);
John McCallba7bf592010-08-24 05:47:05 +0000636 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
David Blaikie89f13cb2012-04-06 23:33:59 +0000637 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
John McCall48871652010-08-21 09:40:31 +0000638 return 0;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000639 }
640
Douglas Gregordba32632009-02-10 19:49:53 +0000641 // If there is a default value, parse it.
Douglas Gregordc13ded2010-07-01 00:00:45 +0000642 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
643 // we introduce the template parameter into the local scope.
644 SourceLocation EqualLoc;
John McCalldadc5752010-08-24 06:29:42 +0000645 ExprResult DefaultArg;
Chris Lattnerb5134c02009-01-05 01:24:05 +0000646 if (Tok.is(tok::equal)) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000647 EqualLoc = ConsumeToken();
Douglas Gregordba32632009-02-10 19:49:53 +0000648
649 // C++ [temp.param]p15:
650 // When parsing a default template-argument for a non-type
651 // template-parameter, the first non-nested > is taken as the
652 // end of the template-parameter-list rather than a greater-than
653 // operator.
Mike Stump11289f42009-09-09 15:08:12 +0000654 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000655
Douglas Gregordc13ded2010-07-01 00:00:45 +0000656 DefaultArg = ParseAssignmentExpression();
Douglas Gregordba32632009-02-10 19:49:53 +0000657 if (DefaultArg.isInvalid())
658 SkipUntil(tok::comma, tok::greater, true, true);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000659 }
Mike Stump11289f42009-09-09 15:08:12 +0000660
Douglas Gregordc13ded2010-07-01 00:00:45 +0000661 // Create the parameter.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000662 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000663 Depth, Position, EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000664 DefaultArg.take());
Douglas Gregoreb31f392008-12-01 23:54:00 +0000665}
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000666
Douglas Gregor67a65642009-02-17 23:15:12 +0000667/// \brief Parses a template-id that after the template name has
668/// already been parsed.
669///
670/// This routine takes care of parsing the enclosed template argument
671/// list ('<' template-parameter-list [opt] '>') and placing the
672/// results into a form that can be transferred to semantic analysis.
673///
674/// \param Template the template declaration produced by isTemplateName
675///
676/// \param TemplateNameLoc the source location of the template name
677///
678/// \param SS if non-NULL, the nested-name-specifier preceding the
679/// template name.
680///
681/// \param ConsumeLastToken if true, then we will consume the last
682/// token that forms the template-id. Otherwise, we will leave the
683/// last token in the stream (e.g., so that it can be replaced with an
684/// annotation token).
Mike Stump11289f42009-09-09 15:08:12 +0000685bool
Douglas Gregordc572a32009-03-30 22:58:21 +0000686Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
Mike Stump11289f42009-09-09 15:08:12 +0000687 SourceLocation TemplateNameLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +0000688 const CXXScopeSpec &SS,
Douglas Gregor67a65642009-02-17 23:15:12 +0000689 bool ConsumeLastToken,
690 SourceLocation &LAngleLoc,
691 TemplateArgList &TemplateArgs,
Douglas Gregor67a65642009-02-17 23:15:12 +0000692 SourceLocation &RAngleLoc) {
693 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
694
695 // Consume the '<'.
696 LAngleLoc = ConsumeToken();
697
698 // Parse the optional template-argument-list.
699 bool Invalid = false;
700 {
701 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Douglas Gregor180dda92011-01-11 00:45:18 +0000702 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
Douglas Gregorb53edfb2009-11-10 19:49:08 +0000703 Invalid = ParseTemplateArgumentList(TemplateArgs);
Douglas Gregor67a65642009-02-17 23:15:12 +0000704
705 if (Invalid) {
706 // Try to find the closing '>'.
707 SkipUntil(tok::greater, true, !ConsumeLastToken);
708
709 return true;
710 }
711 }
712
Eli Friedmanaffd5fd2009-12-27 22:31:18 +0000713 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) {
714 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregor67a65642009-02-17 23:15:12 +0000715 return true;
Eli Friedmanaffd5fd2009-12-27 22:31:18 +0000716 }
Douglas Gregor67a65642009-02-17 23:15:12 +0000717
Douglas Gregorcbb45d02009-02-25 23:02:36 +0000718 // Determine the location of the '>' or '>>'. Only consume this
719 // token if the caller asked us to.
Douglas Gregor67a65642009-02-17 23:15:12 +0000720 RAngleLoc = Tok.getLocation();
721
Douglas Gregorcbb45d02009-02-25 23:02:36 +0000722 if (Tok.is(tok::greatergreater)) {
Richard Smith5d164bc2011-10-15 05:09:34 +0000723 const char *ReplaceStr = "> >";
724 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
725 ReplaceStr = "> > ";
Douglas Gregor87f95b02009-02-26 21:00:50 +0000726
David Blaikiebbafb8a2012-03-11 07:00:24 +0000727 Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ?
Richard Smith5d164bc2011-10-15 05:09:34 +0000728 diag::warn_cxx98_compat_two_right_angle_brackets :
729 diag::err_two_right_angle_brackets_need_space)
730 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()),
731 ReplaceStr);
Douglas Gregorcbb45d02009-02-25 23:02:36 +0000732
733 Tok.setKind(tok::greater);
734 if (!ConsumeLastToken) {
735 // Since we're not supposed to consume the '>>' token, we need
736 // to insert a second '>' token after the first.
737 PP.EnterToken(Tok);
738 }
739 } else if (ConsumeLastToken)
Douglas Gregor67a65642009-02-17 23:15:12 +0000740 ConsumeToken();
741
742 return false;
743}
Mike Stump11289f42009-09-09 15:08:12 +0000744
Douglas Gregor7f741122009-02-25 19:37:18 +0000745/// \brief Replace the tokens that form a simple-template-id with an
746/// annotation token containing the complete template-id.
747///
748/// The first token in the stream must be the name of a template that
749/// is followed by a '<'. This routine will parse the complete
750/// simple-template-id and replace the tokens with a single annotation
751/// token with one of two different kinds: if the template-id names a
752/// type (and \p AllowTypeAnnotation is true), the annotation token is
753/// a type annotation that includes the optional nested-name-specifier
754/// (\p SS). Otherwise, the annotation token is a template-id
755/// annotation that does not include the optional
756/// nested-name-specifier.
757///
758/// \param Template the declaration of the template named by the first
759/// token (an identifier), as returned from \c Action::isTemplateName().
760///
761/// \param TemplateNameKind the kind of template that \p Template
762/// refers to, as returned from \c Action::isTemplateName().
763///
764/// \param SS if non-NULL, the nested-name-specifier that precedes
765/// this template name.
766///
767/// \param TemplateKWLoc if valid, specifies that this template-id
768/// annotation was preceded by the 'template' keyword and gives the
769/// location of that keyword. If invalid (the default), then this
770/// template-id was not preceded by a 'template' keyword.
771///
772/// \param AllowTypeAnnotation if true (the default), then a
773/// simple-template-id that refers to a class template, template
774/// template parameter, or other template that produces a type will be
775/// replaced with a type annotation token. Otherwise, the
776/// simple-template-id is always replaced with a template-id
777/// annotation token.
Chris Lattner5558e9f2009-06-26 04:27:47 +0000778///
779/// If an unrecoverable parse error occurs and no annotation token can be
780/// formed, this function returns true.
781///
782bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Douglas Gregore7c20652011-03-02 00:47:37 +0000783 CXXScopeSpec &SS,
Douglas Gregor7f741122009-02-25 19:37:18 +0000784 SourceLocation TemplateKWLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000785 UnqualifiedId &TemplateName,
Douglas Gregor7f741122009-02-25 19:37:18 +0000786 bool AllowTypeAnnotation) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000787 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
Douglas Gregor71395fa2009-11-04 00:56:37 +0000788 assert(Template && Tok.is(tok::less) &&
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000789 "Parser isn't at the beginning of a template-id");
790
791 // Consume the template-name.
Douglas Gregor71395fa2009-11-04 00:56:37 +0000792 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000793
Douglas Gregor67a65642009-02-17 23:15:12 +0000794 // Parse the enclosed template argument list.
795 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor67b556a2009-02-09 19:34:22 +0000796 TemplateArgList TemplateArgs;
Douglas Gregor71395fa2009-11-04 00:56:37 +0000797 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
798 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000799 SS, false, LAngleLoc,
800 TemplateArgs,
Douglas Gregor67a65642009-02-17 23:15:12 +0000801 RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000802
Chris Lattner5558e9f2009-06-26 04:27:47 +0000803 if (Invalid) {
804 // If we failed to parse the template ID but skipped ahead to a >, we're not
805 // going to be able to form a token annotation. Eat the '>' if present.
806 if (Tok.is(tok::greater))
807 ConsumeToken();
808 return true;
809 }
Douglas Gregord32e0282009-02-09 23:23:08 +0000810
Jay Foad7d0479f2009-05-21 09:52:38 +0000811 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
Douglas Gregor67a65642009-02-17 23:15:12 +0000812 TemplateArgs.size());
Douglas Gregor0db4ccd2009-02-09 21:04:56 +0000813
Douglas Gregor8bf42052009-02-09 18:46:07 +0000814 // Build the annotation token.
Douglas Gregorb67535d2009-03-31 00:43:58 +0000815 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
John McCallfaf5fb42010-08-26 23:41:50 +0000816 TypeResult Type
Abramo Bagnara48c05be2012-02-06 14:41:24 +0000817 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +0000818 Template, TemplateNameLoc,
Abramo Bagnara48c05be2012-02-06 14:41:24 +0000819 LAngleLoc, TemplateArgsPtr, RAngleLoc);
Chris Lattner5558e9f2009-06-26 04:27:47 +0000820 if (Type.isInvalid()) {
821 // If we failed to parse the template ID but skipped ahead to a >, we're not
822 // going to be able to form a token annotation. Eat the '>' if present.
823 if (Tok.is(tok::greater))
824 ConsumeToken();
825 return true;
826 }
Douglas Gregor67a65642009-02-17 23:15:12 +0000827
828 Tok.setKind(tok::annot_typename);
John McCallba7bf592010-08-24 05:47:05 +0000829 setTypeAnnotation(Tok, Type.get());
Douglas Gregore7c20652011-03-02 00:47:37 +0000830 if (SS.isNotEmpty())
831 Tok.setLocation(SS.getBeginLoc());
Douglas Gregor7f741122009-02-25 19:37:18 +0000832 else if (TemplateKWLoc.isValid())
833 Tok.setLocation(TemplateKWLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000834 else
Douglas Gregor7f741122009-02-25 19:37:18 +0000835 Tok.setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +0000836 } else {
Douglas Gregorb67535d2009-03-31 00:43:58 +0000837 // Build a template-id annotation token that can be processed
838 // later.
Douglas Gregor7f741122009-02-25 19:37:18 +0000839 Tok.setKind(tok::annot_template_id);
Mike Stump11289f42009-09-09 15:08:12 +0000840 TemplateIdAnnotation *TemplateId
Benjamin Kramer1e6b6062012-04-14 12:14:03 +0000841 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor8bf42052009-02-09 18:46:07 +0000842 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregor71395fa2009-11-04 00:56:37 +0000843 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
844 TemplateId->Name = TemplateName.Identifier;
845 TemplateId->Operator = OO_None;
846 } else {
847 TemplateId->Name = 0;
848 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
849 }
Douglas Gregore7c20652011-03-02 00:47:37 +0000850 TemplateId->SS = SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000851 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall3e56fd42010-08-23 07:28:44 +0000852 TemplateId->Template = Template;
Douglas Gregor7f741122009-02-25 19:37:18 +0000853 TemplateId->Kind = TNK;
Douglas Gregor8bf42052009-02-09 18:46:07 +0000854 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor7f741122009-02-25 19:37:18 +0000855 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregorb53edfb2009-11-10 19:49:08 +0000856 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
857 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
Douglas Gregor869ad452011-02-24 17:54:50 +0000858 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
Douglas Gregor8bf42052009-02-09 18:46:07 +0000859 Tok.setAnnotationValue(TemplateId);
Douglas Gregor7f741122009-02-25 19:37:18 +0000860 if (TemplateKWLoc.isValid())
861 Tok.setLocation(TemplateKWLoc);
862 else
863 Tok.setLocation(TemplateNameLoc);
864
865 TemplateArgsPtr.release();
Douglas Gregor8bf42052009-02-09 18:46:07 +0000866 }
867
868 // Common fields for the annotation token
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000869 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000870
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000871 // In case the tokens were cached, have Preprocessor replace them with the
872 // annotation token.
873 PP.AnnotateCachedTokens(Tok);
Chris Lattner5558e9f2009-06-26 04:27:47 +0000874 return false;
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000875}
876
Douglas Gregor7f741122009-02-25 19:37:18 +0000877/// \brief Replaces a template-id annotation token with a type
878/// annotation token.
879///
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000880/// If there was a failure when forming the type from the template-id,
881/// a type annotation token will still be created, but will have a
882/// NULL type pointer to signify an error.
Douglas Gregore7c20652011-03-02 00:47:37 +0000883void Parser::AnnotateTemplateIdTokenAsType() {
Douglas Gregor7f741122009-02-25 19:37:18 +0000884 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
885
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +0000886 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorb67535d2009-03-31 00:43:58 +0000887 assert((TemplateId->Kind == TNK_Type_template ||
888 TemplateId->Kind == TNK_Dependent_template_name) &&
889 "Only works for type and dependent templates");
Mike Stump11289f42009-09-09 15:08:12 +0000890
891 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
Douglas Gregor7f741122009-02-25 19:37:18 +0000892 TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +0000893 TemplateId->NumArgs);
894
John McCallfaf5fb42010-08-26 23:41:50 +0000895 TypeResult Type
Douglas Gregore7c20652011-03-02 00:47:37 +0000896 = Actions.ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +0000897 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +0000898 TemplateId->Template,
Douglas Gregordc572a32009-03-30 22:58:21 +0000899 TemplateId->TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000900 TemplateId->LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +0000901 TemplateArgsPtr,
Douglas Gregordc572a32009-03-30 22:58:21 +0000902 TemplateId->RAngleLoc);
Douglas Gregor7f741122009-02-25 19:37:18 +0000903 // Create the new "type" annotation token.
904 Tok.setKind(tok::annot_typename);
John McCallba7bf592010-08-24 05:47:05 +0000905 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
Douglas Gregore7c20652011-03-02 00:47:37 +0000906 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
907 Tok.setLocation(TemplateId->SS.getBeginLoc());
Sebastian Redlb0e3e1b2010-02-08 19:35:18 +0000908 // End location stays the same
Douglas Gregor7f741122009-02-25 19:37:18 +0000909
Douglas Gregor35522592009-11-04 18:18:19 +0000910 // Replace the template-id annotation token, and possible the scope-specifier
911 // that precedes it, with the typename annotation token.
912 PP.AnnotateCachedTokens(Tok);
Douglas Gregor7f741122009-02-25 19:37:18 +0000913}
914
Douglas Gregorb53edfb2009-11-10 19:49:08 +0000915/// \brief Determine whether the given token can end a template argument.
Benjamin Kramer2c9a91c2009-11-10 21:29:56 +0000916static bool isEndOfTemplateArgument(Token Tok) {
Douglas Gregorb53edfb2009-11-10 19:49:08 +0000917 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
918 Tok.is(tok::greatergreater);
919}
920
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000921/// \brief Parse a C++ template template argument.
922ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
923 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
924 !Tok.is(tok::annot_cxxscope))
925 return ParsedTemplateArgument();
926
927 // C++0x [temp.arg.template]p1:
928 // A template-argument for a template template-parameter shall be the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000929 // of a class template or an alias template, expressed as id-expression.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000930 //
Richard Smith3f1b5d02011-05-05 21:57:07 +0000931 // We parse an id-expression that refers to a class template or alias
932 // template. The grammar we parse is:
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000933 //
Douglas Gregore9a80352011-01-05 17:33:50 +0000934 // nested-name-specifier[opt] template[opt] identifier ...[opt]
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000935 //
936 // followed by a token that terminates a template argument, such as ',',
937 // '>', or (in some cases) '>>'.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000938 CXXScopeSpec SS; // nested-name-specifier, if present
John McCallba7bf592010-08-24 05:47:05 +0000939 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000940 /*EnteringContext=*/false);
941
Douglas Gregore9a80352011-01-05 17:33:50 +0000942 ParsedTemplateArgument Result;
943 SourceLocation EllipsisLoc;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000944 if (SS.isSet() && Tok.is(tok::kw_template)) {
945 // Parse the optional 'template' keyword following the
946 // nested-name-specifier.
Abramo Bagnara7945c982012-01-27 09:46:47 +0000947 SourceLocation TemplateKWLoc = ConsumeToken();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000948
949 if (Tok.is(tok::identifier)) {
950 // We appear to have a dependent template name.
951 UnqualifiedId Name;
952 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
953 ConsumeToken(); // the identifier
954
Douglas Gregore9a80352011-01-05 17:33:50 +0000955 // Parse the ellipsis.
956 if (Tok.is(tok::ellipsis))
957 EllipsisLoc = ConsumeToken();
958
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000959 // If the next token signals the end of a template argument,
960 // then we have a dependent template name that could be a template
961 // template argument.
Douglas Gregorbb119652010-06-16 23:00:59 +0000962 TemplateTy Template;
963 if (isEndOfTemplateArgument(Tok) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +0000964 Actions.ActOnDependentTemplateName(getCurScope(),
965 SS, TemplateKWLoc, Name,
John McCallba7bf592010-08-24 05:47:05 +0000966 /*ObjectType=*/ ParsedType(),
Douglas Gregorbb119652010-06-16 23:00:59 +0000967 /*EnteringContext=*/false,
968 Template))
Douglas Gregore9a80352011-01-05 17:33:50 +0000969 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregorbb119652010-06-16 23:00:59 +0000970 }
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000971 } else if (Tok.is(tok::identifier)) {
972 // We may have a (non-dependent) template name.
973 TemplateTy Template;
974 UnqualifiedId Name;
975 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
976 ConsumeToken(); // the identifier
977
Douglas Gregore9a80352011-01-05 17:33:50 +0000978 // Parse the ellipsis.
979 if (Tok.is(tok::ellipsis))
980 EllipsisLoc = ConsumeToken();
981
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000982 if (isEndOfTemplateArgument(Tok)) {
Douglas Gregor786123d2010-05-21 23:18:07 +0000983 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000984 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
985 /*hasTemplateKeyword=*/false,
986 Name,
John McCallba7bf592010-08-24 05:47:05 +0000987 /*ObjectType=*/ ParsedType(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000988 /*EnteringContext=*/false,
Douglas Gregor786123d2010-05-21 23:18:07 +0000989 Template,
990 MemberOfUnknownSpecialization);
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000991 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
992 // We have an id-expression that refers to a class template or
Richard Smith3f1b5d02011-05-05 21:57:07 +0000993 // (C++0x) alias template.
Douglas Gregore9a80352011-01-05 17:33:50 +0000994 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000995 }
996 }
997 }
998
Douglas Gregore9a80352011-01-05 17:33:50 +0000999 // If this is a pack expansion, build it as such.
1000 if (EllipsisLoc.isValid() && !Result.isInvalid())
1001 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1002
1003 return Result;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001004}
1005
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001006/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1007///
1008/// template-argument: [C++ 14.2]
Douglas Gregor0b6a6242009-06-22 20:57:11 +00001009/// constant-expression
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001010/// type-id
1011/// id-expression
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001012ParsedTemplateArgument Parser::ParseTemplateArgument() {
Douglas Gregor8bf42052009-02-09 18:46:07 +00001013 // C++ [temp.arg]p2:
1014 // In a template-argument, an ambiguity between a type-id and an
1015 // expression is resolved to a type-id, regardless of the form of
1016 // the corresponding template-parameter.
1017 //
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001018 // Therefore, we initially try to parse a type-id.
Douglas Gregor97f34572009-02-10 00:53:15 +00001019 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001020 SourceLocation Loc = Tok.getLocation();
Douglas Gregor205d5e32011-01-31 16:09:46 +00001021 TypeResult TypeArg = ParseTypeName(/*Range=*/0,
1022 Declarator::TemplateTypeArgContext);
Douglas Gregor220cac52009-02-18 17:45:20 +00001023 if (TypeArg.isInvalid())
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001024 return ParsedTemplateArgument();
1025
John McCallba7bf592010-08-24 05:47:05 +00001026 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1027 TypeArg.get().getAsOpaquePtr(),
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001028 Loc);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001029 }
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001030
1031 // Try to parse a template template argument.
Douglas Gregorc9984092009-11-12 00:03:40 +00001032 {
1033 TentativeParsingAction TPA(*this);
1034
1035 ParsedTemplateArgument TemplateTemplateArgument
1036 = ParseTemplateTemplateArgument();
1037 if (!TemplateTemplateArgument.isInvalid()) {
1038 TPA.Commit();
1039 return TemplateTemplateArgument;
1040 }
1041
1042 // Revert this tentative parse to parse a non-type template argument.
1043 TPA.Revert();
1044 }
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001045
1046 // Parse a non-type template argument.
1047 SourceLocation Loc = Tok.getLocation();
Kaelyn Uhrain01782002012-02-22 01:03:07 +00001048 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
Douglas Gregord32e0282009-02-09 23:23:08 +00001049 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001050 return ParsedTemplateArgument();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001051
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001052 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1053 ExprArg.release(), Loc);
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001054}
1055
Douglas Gregor786123d2010-05-21 23:18:07 +00001056/// \brief Determine whether the current tokens can only be parsed as a
1057/// template argument list (starting with the '<') and never as a '<'
1058/// expression.
Douglas Gregor20c38a72010-05-21 23:43:39 +00001059bool Parser::IsTemplateArgumentList(unsigned Skip) {
Douglas Gregor786123d2010-05-21 23:18:07 +00001060 struct AlwaysRevertAction : TentativeParsingAction {
1061 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1062 ~AlwaysRevertAction() { Revert(); }
1063 } Tentative(*this);
1064
Douglas Gregor20c38a72010-05-21 23:43:39 +00001065 while (Skip) {
1066 ConsumeToken();
1067 --Skip;
1068 }
1069
Douglas Gregor786123d2010-05-21 23:18:07 +00001070 // '<'
1071 if (!Tok.is(tok::less))
1072 return false;
1073 ConsumeToken();
1074
1075 // An empty template argument list.
1076 if (Tok.is(tok::greater))
1077 return true;
1078
1079 // See whether we have declaration specifiers, which indicate a type.
1080 while (isCXXDeclarationSpecifier() == TPResult::True())
1081 ConsumeToken();
1082
1083 // If we have a '>' or a ',' then this is a template argument list.
1084 return Tok.is(tok::greater) || Tok.is(tok::comma);
1085}
1086
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001087/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1088/// (C++ [temp.names]). Returns true if there was an error.
1089///
1090/// template-argument-list: [C++ 14.2]
1091/// template-argument
1092/// template-argument-list ',' template-argument
Mike Stump11289f42009-09-09 15:08:12 +00001093bool
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001094Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001095 while (true) {
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001096 ParsedTemplateArgument Arg = ParseTemplateArgument();
Douglas Gregord2fa7662010-12-20 02:24:11 +00001097 if (Tok.is(tok::ellipsis)) {
1098 SourceLocation EllipsisLoc = ConsumeToken();
1099 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1100 }
1101
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001102 if (Arg.isInvalid()) {
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001103 SkipUntil(tok::comma, tok::greater, true, true);
1104 return true;
1105 }
Douglas Gregor67b556a2009-02-09 19:34:22 +00001106
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001107 // Save this template argument.
1108 TemplateArgs.push_back(Arg);
1109
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001110 // If the next token is a comma, consume it and keep reading
1111 // arguments.
1112 if (Tok.isNot(tok::comma)) break;
1113
1114 // Consume the comma.
1115 ConsumeToken();
1116 }
1117
Eli Friedmanaffd5fd2009-12-27 22:31:18 +00001118 return false;
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001119}
1120
Mike Stump11289f42009-09-09 15:08:12 +00001121/// \brief Parse a C++ explicit template instantiation
Douglas Gregor23996282009-05-12 21:31:51 +00001122/// (C++ [temp.explicit]).
1123///
1124/// explicit-instantiation:
Douglas Gregor43e75172009-09-04 06:33:52 +00001125/// 'extern' [opt] 'template' declaration
1126///
1127/// Note that the 'extern' is a GNU extension and C++0x feature.
Argyrios Kyrtzidis26440632011-12-23 02:16:45 +00001128Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1129 SourceLocation ExternLoc,
John McCall48871652010-08-21 09:40:31 +00001130 SourceLocation TemplateLoc,
Argyrios Kyrtzidis26440632011-12-23 02:16:45 +00001131 SourceLocation &DeclEnd,
1132 AccessSpecifier AS) {
John McCall796c2a52010-07-16 08:13:16 +00001133 // This isn't really required here.
1134 ParsingDeclRAIIObject ParsingTemplateParams(*this);
1135
Argyrios Kyrtzidis26440632011-12-23 02:16:45 +00001136 return ParseSingleDeclarationAfterTemplate(Context,
Douglas Gregor43e75172009-09-04 06:33:52 +00001137 ParsedTemplateInfo(ExternLoc,
1138 TemplateLoc),
John McCall796c2a52010-07-16 08:13:16 +00001139 ParsingTemplateParams,
Argyrios Kyrtzidis26440632011-12-23 02:16:45 +00001140 DeclEnd, AS);
Douglas Gregor23996282009-05-12 21:31:51 +00001141}
John McCall9b72f892010-11-10 02:40:36 +00001142
1143SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1144 if (TemplateParams)
1145 return getTemplateParamsRange(TemplateParams->data(),
1146 TemplateParams->size());
1147
1148 SourceRange R(TemplateLoc);
1149 if (ExternLoc.isValid())
1150 R.setBegin(ExternLoc);
1151 return R;
1152}
Francois Pichet1c229c02011-04-22 22:18:13 +00001153
Francois Picheta7d337d2011-04-23 11:52:20 +00001154void Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) {
Francois Pichet1c229c02011-04-22 22:18:13 +00001155 ((Parser*)P)->LateTemplateParser(FD);
1156}
1157
1158
Francois Picheta7d337d2011-04-23 11:52:20 +00001159void Parser::LateTemplateParser(const FunctionDecl *FD) {
Francois Pichet1c229c02011-04-22 22:18:13 +00001160 LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD];
1161 if (LPT) {
1162 ParseLateTemplatedFuncDef(*LPT);
1163 return;
1164 }
1165
1166 llvm_unreachable("Late templated function without associated lexed tokens");
1167}
David Blaikie9b7efd52012-04-02 20:59:49 +00001168
1169/// \brief Late parse a C++ function template in Microsoft mode.
1170void Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) {
1171 if(!LMT.D)
1172 return;
1173
1174 // Get the FunctionDecl.
1175 FunctionDecl *FD = 0;
1176 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(LMT.D))
1177 FD = FunTmpl->getTemplatedDecl();
1178 else
1179 FD = cast<FunctionDecl>(LMT.D);
1180
Francois Pichete6664762012-02-22 08:25:53 +00001181 // To restore the context after late parsing.
David Blaikie9b7efd52012-04-02 20:59:49 +00001182 Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
1183
1184 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1185 DeclaratorDecl* Declarator = dyn_cast<DeclaratorDecl>(FD);
1186 if (Declarator && Declarator->getNumTemplateParameterLists() != 0) {
1187 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::TemplateParamScope));
1188 Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
1189 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1190 } else {
1191 // Get the list of DeclContext to reenter.
1192 SmallVector<DeclContext*, 4> DeclContextToReenter;
1193 DeclContext *DD = FD->getLexicalParent();
1194 while (DD && !DD->isTranslationUnit()) {
1195 DeclContextToReenter.push_back(DD);
1196 DD = DD->getLexicalParent();
1197 }
1198
1199 // Reenter template scopes from outmost to innermost.
1200 SmallVector<DeclContext*, 4>::reverse_iterator II =
1201 DeclContextToReenter.rbegin();
1202 for (; II != DeclContextToReenter.rend(); ++II) {
1203 if (ClassTemplatePartialSpecializationDecl* MD =
1204 dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) {
1205 TemplateParamScopeStack.push_back(new ParseScope(this,
1206 Scope::TemplateParamScope));
1207 Actions.ActOnReenterTemplateScope(getCurScope(), MD);
1208 } else if (CXXRecordDecl* MD = dyn_cast_or_null<CXXRecordDecl>(*II)) {
1209 TemplateParamScopeStack.push_back(new ParseScope(this,
1210 Scope::TemplateParamScope,
1211 MD->getDescribedClassTemplate() != 0 ));
1212 Actions.ActOnReenterTemplateScope(getCurScope(),
1213 MD->getDescribedClassTemplate());
1214 }
1215 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1216 Actions.PushDeclContext(Actions.getCurScope(), *II);
1217 }
1218 TemplateParamScopeStack.push_back(new ParseScope(this,
1219 Scope::TemplateParamScope));
1220 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1221 }
1222
1223 assert(!LMT.Toks.empty() && "Empty body!");
1224
1225 // Append the current token at the end of the new token stream so that it
1226 // doesn't get lost.
1227 LMT.Toks.push_back(Tok);
1228 PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false);
1229
1230 // Consume the previously pushed token.
1231 ConsumeAnyToken();
1232 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1233 && "Inline method not starting with '{', ':' or 'try'");
1234
1235 // Parse the method body. Function body parsing code is similar enough
1236 // to be re-used for method bodies as well.
1237 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1238
1239 // Recreate the containing function DeclContext.
1240 Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FD));
1241
1242 if (FunctionTemplateDecl *FunctionTemplate
1243 = dyn_cast_or_null<FunctionTemplateDecl>(LMT.D))
1244 Actions.ActOnStartOfFunctionDef(getCurScope(),
1245 FunctionTemplate->getTemplatedDecl());
1246 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(LMT.D))
1247 Actions.ActOnStartOfFunctionDef(getCurScope(), Function);
1248
1249
1250 if (Tok.is(tok::kw_try)) {
1251 ParseFunctionTryBlock(LMT.D, FnScope);
1252 } else {
1253 if (Tok.is(tok::colon))
1254 ParseConstructorInitializer(LMT.D);
1255 else
1256 Actions.ActOnDefaultCtorInitializers(LMT.D);
1257
1258 if (Tok.is(tok::l_brace)) {
1259 ParseFunctionStatementBody(LMT.D, FnScope);
1260 Actions.MarkAsLateParsedTemplate(FD, false);
1261 } else
1262 Actions.ActOnFinishFunctionBody(LMT.D, 0);
1263 }
1264
1265 // Exit scopes.
Francois Pichet81345182011-09-22 22:14:56 +00001266 FnScope.Exit();
David Blaikie9b7efd52012-04-02 20:59:49 +00001267 SmallVector<ParseScope*, 4>::reverse_iterator I =
1268 TemplateParamScopeStack.rbegin();
1269 for (; I != TemplateParamScopeStack.rend(); ++I)
1270 delete *I;
1271
1272 DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D);
1273 if (grp)
1274 Actions.getASTConsumer().HandleTopLevelDecl(grp.get());
Francois Pichet1c229c02011-04-22 22:18:13 +00001275}
1276
1277/// \brief Lex a delayed template function for late parsing.
1278void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1279 tok::TokenKind kind = Tok.getKind();
Sebastian Redl0d164012011-09-30 08:32:17 +00001280 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1281 // Consume everything up to (and including) the matching right brace.
1282 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Francois Pichet1c229c02011-04-22 22:18:13 +00001283 }
Francois Pichet1c229c02011-04-22 22:18:13 +00001284
1285 // If we're in a function-try-block, we need to store all the catch blocks.
1286 if (kind == tok::kw_try) {
1287 while (Tok.is(tok::kw_catch)) {
1288 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1289 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1290 }
1291 }
1292}