blob: 93f5c9ba43d7a94defb6cce50ac343804e3cd70c [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"
Douglas Gregoreb31f392008-12-01 23:54:00 +000020using namespace clang;
21
Douglas Gregor1b57ff32009-05-12 23:25:50 +000022/// \brief Parse a template declaration, explicit instantiation, or
23/// explicit specialization.
John McCall48871652010-08-21 09:40:31 +000024Decl *
Douglas Gregor1b57ff32009-05-12 23:25:50 +000025Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
26 SourceLocation &DeclEnd,
27 AccessSpecifier AS) {
28 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less))
Mike Stump11289f42009-09-09 15:08:12 +000029 return ParseExplicitInstantiation(SourceLocation(), ConsumeToken(),
Douglas Gregor43e75172009-09-04 06:33:52 +000030 DeclEnd);
Douglas Gregor1b57ff32009-05-12 23:25:50 +000031
32 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS);
33}
34
Douglas Gregora3dff8e2009-08-24 23:03:25 +000035/// \brief RAII class that manages the template parameter depth.
36namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +000037 class TemplateParameterDepthCounter {
Douglas Gregora3dff8e2009-08-24 23:03:25 +000038 unsigned &Depth;
39 unsigned AddedLevels;
40
41 public:
Mike Stump11289f42009-09-09 15:08:12 +000042 explicit TemplateParameterDepthCounter(unsigned &Depth)
Douglas Gregora3dff8e2009-08-24 23:03:25 +000043 : Depth(Depth), AddedLevels(0) { }
Mike Stump11289f42009-09-09 15:08:12 +000044
Douglas Gregora3dff8e2009-08-24 23:03:25 +000045 ~TemplateParameterDepthCounter() {
46 Depth -= AddedLevels;
47 }
Mike Stump11289f42009-09-09 15:08:12 +000048
49 void operator++() {
Douglas Gregora3dff8e2009-08-24 23:03:25 +000050 ++Depth;
51 ++AddedLevels;
52 }
Mike Stump11289f42009-09-09 15:08:12 +000053
Douglas Gregora3dff8e2009-08-24 23:03:25 +000054 operator unsigned() const { return Depth; }
55 };
56}
57
Douglas Gregor67a65642009-02-17 23:15:12 +000058/// \brief Parse a template declaration or an explicit specialization.
59///
60/// Template declarations include one or more template parameter lists
61/// and either the function or class template declaration. Explicit
62/// specializations contain one or more 'template < >' prefixes
63/// followed by a (possibly templated) declaration. Since the
64/// syntactic form of both features is nearly identical, we parse all
65/// of the template headers together and let semantic analysis sort
66/// the declarations from the explicit specializations.
Douglas Gregoreb31f392008-12-01 23:54:00 +000067///
68/// template-declaration: [C++ temp]
69/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
Douglas Gregor67a65642009-02-17 23:15:12 +000070///
71/// explicit-specialization: [ C++ temp.expl.spec]
72/// 'template' '<' '>' declaration
John McCall48871652010-08-21 09:40:31 +000073Decl *
Anders Carlssondfbbdf62009-03-26 00:52:18 +000074Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
Chris Lattner49836b42009-04-02 04:16:50 +000075 SourceLocation &DeclEnd,
Anders Carlssondfbbdf62009-03-26 00:52:18 +000076 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +000077 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
78 "Token does not start a template declaration.");
79
Douglas Gregorf5586182008-12-02 00:41:28 +000080 // Enter template-parameter scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +000081 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Douglas Gregorf5586182008-12-02 00:41:28 +000082
John McCall796c2a52010-07-16 08:13:16 +000083 // Tell the action that names should be checked in the context of
84 // the declaration to come.
85 ParsingDeclRAIIObject ParsingTemplateParams(*this);
86
Douglas Gregorb9bd8a92008-12-24 02:52:09 +000087 // Parse multiple levels of template headers within this template
88 // parameter scope, e.g.,
89 //
90 // template<typename T>
91 // template<typename U>
92 // class A<T>::B { ... };
93 //
94 // We parse multiple levels non-recursively so that we can build a
95 // single data structure containing all of the template parameter
Douglas Gregor67a65642009-02-17 23:15:12 +000096 // lists to easily differentiate between the case above and:
Douglas Gregorb9bd8a92008-12-24 02:52:09 +000097 //
98 // template<typename T>
99 // class A {
100 // template<typename U> class B;
101 // };
102 //
103 // In the first case, the action for declaring A<T>::B receives
104 // both template parameter lists. In the second case, the action for
105 // defining A<T>::B receives just the inner template parameter list
106 // (and retrieves the outer template parameter list from its
107 // context).
Douglas Gregor468535e2009-08-20 18:46:05 +0000108 bool isSpecialization = true;
Douglas Gregor1d0015f2009-10-30 22:09:44 +0000109 bool LastParamListWasEmpty = false;
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000110 TemplateParameterLists ParamLists;
Douglas Gregora3dff8e2009-08-24 23:03:25 +0000111 TemplateParameterDepthCounter Depth(TemplateParameterDepth);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000112 do {
113 // Consume the 'export', if any.
114 SourceLocation ExportLoc;
115 if (Tok.is(tok::kw_export)) {
116 ExportLoc = ConsumeToken();
117 }
118
119 // Consume the 'template', which should be here.
120 SourceLocation TemplateLoc;
121 if (Tok.is(tok::kw_template)) {
122 TemplateLoc = ConsumeToken();
123 } else {
124 Diag(Tok.getLocation(), diag::err_expected_template);
John McCall48871652010-08-21 09:40:31 +0000125 return 0;
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000126 }
Mike Stump11289f42009-09-09 15:08:12 +0000127
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000128 // Parse the '<' template-parameter-list '>'
129 SourceLocation LAngleLoc, RAngleLoc;
John McCall572ccbc2010-08-23 06:53:58 +0000130 llvm::SmallVector<Decl*, 4> TemplateParams;
Mike Stump11289f42009-09-09 15:08:12 +0000131 if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +0000132 RAngleLoc)) {
133 // Skip until the semi-colon or a }.
134 SkipUntil(tok::r_brace, true, true);
135 if (Tok.is(tok::semi))
136 ConsumeToken();
John McCall48871652010-08-21 09:40:31 +0000137 return 0;
Douglas Gregore93e46c2009-07-22 23:48:44 +0000138 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +0000139
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000140 ParamLists.push_back(
Mike Stump11289f42009-09-09 15:08:12 +0000141 Actions.ActOnTemplateParameterList(Depth, ExportLoc,
142 TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +0000143 TemplateParams.data(),
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000144 TemplateParams.size(), RAngleLoc));
Douglas Gregora3dff8e2009-08-24 23:03:25 +0000145
146 if (!TemplateParams.empty()) {
147 isSpecialization = false;
148 ++Depth;
Douglas Gregor1d0015f2009-10-30 22:09:44 +0000149 } else {
150 LastParamListWasEmpty = true;
Mike Stump11289f42009-09-09 15:08:12 +0000151 }
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000152 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
153
154 // Parse the actual template declaration.
Mike Stump11289f42009-09-09 15:08:12 +0000155 return ParseSingleDeclarationAfterTemplate(Context,
Douglas Gregor1b57ff32009-05-12 23:25:50 +0000156 ParsedTemplateInfo(&ParamLists,
Douglas Gregor1d0015f2009-10-30 22:09:44 +0000157 isSpecialization,
158 LastParamListWasEmpty),
John McCall796c2a52010-07-16 08:13:16 +0000159 ParsingTemplateParams,
Douglas Gregor23996282009-05-12 21:31:51 +0000160 DeclEnd, AS);
161}
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000162
Douglas Gregor23996282009-05-12 21:31:51 +0000163/// \brief Parse a single declaration that declares a template,
164/// template specialization, or explicit instantiation of a template.
165///
166/// \param TemplateParams if non-NULL, the template parameter lists
167/// that preceded this declaration. In this case, the declaration is a
168/// template declaration, out-of-line definition of a template, or an
169/// explicit template specialization. When NULL, the declaration is an
170/// explicit template instantiation.
171///
172/// \param TemplateLoc when TemplateParams is NULL, the location of
173/// the 'template' keyword that indicates that we have an explicit
174/// template instantiation.
175///
176/// \param DeclEnd will receive the source location of the last token
177/// within this declaration.
178///
179/// \param AS the access specifier associated with this
180/// declaration. Will be AS_none for namespace-scope declarations.
181///
182/// \returns the new declaration.
John McCall48871652010-08-21 09:40:31 +0000183Decl *
Douglas Gregor23996282009-05-12 21:31:51 +0000184Parser::ParseSingleDeclarationAfterTemplate(
185 unsigned Context,
Douglas Gregor1b57ff32009-05-12 23:25:50 +0000186 const ParsedTemplateInfo &TemplateInfo,
John McCall796c2a52010-07-16 08:13:16 +0000187 ParsingDeclRAIIObject &DiagsFromTParams,
Douglas Gregor23996282009-05-12 21:31:51 +0000188 SourceLocation &DeclEnd,
189 AccessSpecifier AS) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +0000190 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
191 "Template information required");
192
Douglas Gregor3447e762009-08-20 22:52:58 +0000193 if (Context == Declarator::MemberContext) {
194 // We are parsing a member template.
John McCall796c2a52010-07-16 08:13:16 +0000195 ParseCXXClassMemberDeclaration(AS, TemplateInfo, &DiagsFromTParams);
John McCall48871652010-08-21 09:40:31 +0000196 return 0;
Douglas Gregor3447e762009-08-20 22:52:58 +0000197 }
Mike Stump11289f42009-09-09 15:08:12 +0000198
John McCall53fa7142010-12-24 02:08:15 +0000199 ParsedAttributesWithRange prefixAttrs;
200 MaybeParseCXX0XAttributes(prefixAttrs);
John McCall9b72f892010-11-10 02:40:36 +0000201
202 if (Tok.is(tok::kw_using))
203 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000204 prefixAttrs);
John McCall9b72f892010-11-10 02:40:36 +0000205
John McCall796c2a52010-07-16 08:13:16 +0000206 // Parse the declaration specifiers, stealing the accumulated
207 // diagnostics from the template parameters.
208 ParsingDeclSpec DS(DiagsFromTParams);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000209
John McCall53fa7142010-12-24 02:08:15 +0000210 DS.takeAttributesFrom(prefixAttrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000211
Douglas Gregor9de54ea2010-01-13 17:31:36 +0000212 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
213 getDeclSpecContextFromDeclaratorContext(Context));
Douglas Gregor23996282009-05-12 21:31:51 +0000214
215 if (Tok.is(tok::semi)) {
216 DeclEnd = ConsumeToken();
John McCall48871652010-08-21 09:40:31 +0000217 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
John McCall28a6aea2009-11-04 02:18:39 +0000218 DS.complete(Decl);
219 return Decl;
Douglas Gregor23996282009-05-12 21:31:51 +0000220 }
221
222 // Parse the declarator.
John McCall28a6aea2009-11-04 02:18:39 +0000223 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
Douglas Gregor23996282009-05-12 21:31:51 +0000224 ParseDeclarator(DeclaratorInfo);
225 // Error parsing the declarator?
226 if (!DeclaratorInfo.hasName()) {
227 // If so, skip until the semi-colon or a }.
228 SkipUntil(tok::r_brace, true, true);
229 if (Tok.is(tok::semi))
230 ConsumeToken();
John McCall48871652010-08-21 09:40:31 +0000231 return 0;
Douglas Gregor23996282009-05-12 21:31:51 +0000232 }
Mike Stump11289f42009-09-09 15:08:12 +0000233
Douglas Gregor23996282009-05-12 21:31:51 +0000234 // If we have a declaration or declarator list, handle it.
235 if (isDeclarationAfterDeclarator()) {
236 // Parse this declaration.
John McCall48871652010-08-21 09:40:31 +0000237 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
238 TemplateInfo);
Douglas Gregor23996282009-05-12 21:31:51 +0000239
240 if (Tok.is(tok::comma)) {
241 Diag(Tok, diag::err_multiple_template_declarators)
Douglas Gregor1b57ff32009-05-12 23:25:50 +0000242 << (int)TemplateInfo.Kind;
Douglas Gregor23996282009-05-12 21:31:51 +0000243 SkipUntil(tok::semi, true, false);
244 return ThisDecl;
245 }
246
247 // Eat the semi colon after the declaration.
John McCallef50e992009-07-31 02:20:35 +0000248 ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
John McCall28a6aea2009-11-04 02:18:39 +0000249 DS.complete(ThisDecl);
Douglas Gregor23996282009-05-12 21:31:51 +0000250 return ThisDecl;
251 }
252
253 if (DeclaratorInfo.isFunctionDeclarator() &&
Chris Lattner13901342010-07-11 22:42:07 +0000254 isStartOfFunctionDefinition(DeclaratorInfo)) {
Douglas Gregor23996282009-05-12 21:31:51 +0000255 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
256 Diag(Tok, diag::err_function_declared_typedef);
257
258 if (Tok.is(tok::l_brace)) {
259 // This recovery skips the entire function body. It would be nice
260 // to simply call ParseFunctionDefinition() below, however Sema
261 // assumes the declarator represents a function, not a typedef.
262 ConsumeBrace();
263 SkipUntil(tok::r_brace, true);
264 } else {
265 SkipUntil(tok::semi);
266 }
John McCall48871652010-08-21 09:40:31 +0000267 return 0;
Douglas Gregor23996282009-05-12 21:31:51 +0000268 }
Douglas Gregor17a7c122009-06-24 00:54:41 +0000269 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo);
Douglas Gregor23996282009-05-12 21:31:51 +0000270 }
271
272 if (DeclaratorInfo.isFunctionDeclarator())
273 Diag(Tok, diag::err_expected_fn_body);
274 else
275 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
276 SkipUntil(tok::semi);
John McCall48871652010-08-21 09:40:31 +0000277 return 0;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000278}
279
280/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000281/// angle brackets. Depth is the depth of this template-parameter-list, which
282/// is the number of template headers directly enclosing this template header.
283/// TemplateParams is the current list of template parameters we're building.
284/// The template parameter we parse will be added to this list. LAngleLoc and
Mike Stump11289f42009-09-09 15:08:12 +0000285/// RAngleLoc will receive the positions of the '<' and '>', respectively,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000286/// that enclose this template parameter list.
Douglas Gregore93e46c2009-07-22 23:48:44 +0000287///
288/// \returns true if an error occurred, false otherwise.
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000289bool Parser::ParseTemplateParameters(unsigned Depth,
John McCall572ccbc2010-08-23 06:53:58 +0000290 llvm::SmallVectorImpl<Decl*> &TemplateParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000291 SourceLocation &LAngleLoc,
292 SourceLocation &RAngleLoc) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000293 // Get the template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +0000294 if (!Tok.is(tok::less)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000295 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
Douglas Gregore93e46c2009-07-22 23:48:44 +0000296 return true;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000297 }
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000298 LAngleLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000299
Douglas Gregoreb31f392008-12-01 23:54:00 +0000300 // Try to parse the template parameter list.
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000301 if (Tok.is(tok::greater))
302 RAngleLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000303 else if (ParseTemplateParameterList(Depth, TemplateParams)) {
304 if (!Tok.is(tok::greater)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000305 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregore93e46c2009-07-22 23:48:44 +0000306 return true;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000307 }
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000308 RAngleLoc = ConsumeToken();
Douglas Gregoreb31f392008-12-01 23:54:00 +0000309 }
Douglas Gregore93e46c2009-07-22 23:48:44 +0000310 return false;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000311}
312
313/// ParseTemplateParameterList - Parse a template parameter list. If
314/// the parsing fails badly (i.e., closing bracket was left out), this
315/// will try to put the token stream in a reasonable position (closing
Mike Stump11289f42009-09-09 15:08:12 +0000316/// a statement, etc.) and return false.
Douglas Gregoreb31f392008-12-01 23:54:00 +0000317///
318/// template-parameter-list: [C++ temp]
319/// template-parameter
320/// template-parameter-list ',' template-parameter
Mike Stump11289f42009-09-09 15:08:12 +0000321bool
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000322Parser::ParseTemplateParameterList(unsigned Depth,
John McCall572ccbc2010-08-23 06:53:58 +0000323 llvm::SmallVectorImpl<Decl*> &TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +0000324 while (1) {
John McCall48871652010-08-21 09:40:31 +0000325 if (Decl *TmpParam
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000326 = ParseTemplateParameter(Depth, TemplateParams.size())) {
327 TemplateParams.push_back(TmpParam);
328 } else {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000329 // If we failed to parse a template parameter, skip until we find
330 // a comma or closing brace.
331 SkipUntil(tok::comma, tok::greater, true, true);
332 }
Mike Stump11289f42009-09-09 15:08:12 +0000333
Douglas Gregoreb31f392008-12-01 23:54:00 +0000334 // Did we find a comma or the end of the template parmeter list?
Mike Stump11289f42009-09-09 15:08:12 +0000335 if (Tok.is(tok::comma)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000336 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000337 } else if (Tok.is(tok::greater)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000338 // Don't consume this... that's done by template parser.
339 break;
340 } else {
341 // Somebody probably forgot to close the template. Skip ahead and
342 // try to get out of the expression. This error is currently
343 // subsumed by whatever goes on in ParseTemplateParameter.
344 // TODO: This could match >>, and it would be nice to avoid those
345 // silly errors with template <vec<T>>.
Douglas Gregorb0484022010-10-15 01:15:58 +0000346 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000347 SkipUntil(tok::greater, true, true);
348 return false;
349 }
350 }
351 return true;
352}
353
Douglas Gregor26aedb72009-11-21 02:07:55 +0000354/// \brief Determine whether the parser is at the start of a template
355/// type parameter.
356bool Parser::isStartOfTemplateTypeParameter() {
Douglas Gregor71b209d2010-06-04 07:30:15 +0000357 if (Tok.is(tok::kw_class)) {
358 // "class" may be the start of an elaborated-type-specifier or a
359 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
360 switch (NextToken().getKind()) {
361 case tok::equal:
362 case tok::comma:
363 case tok::greater:
364 case tok::greatergreater:
365 case tok::ellipsis:
366 return true;
367
368 case tok::identifier:
369 // This may be either a type-parameter or an elaborated-type-specifier.
370 // We have to look further.
371 break;
372
373 default:
374 return false;
375 }
376
377 switch (GetLookAheadToken(2).getKind()) {
378 case tok::equal:
379 case tok::comma:
380 case tok::greater:
381 case tok::greatergreater:
382 return true;
383
384 default:
385 return false;
386 }
387 }
Douglas Gregor26aedb72009-11-21 02:07:55 +0000388
389 if (Tok.isNot(tok::kw_typename))
390 return false;
391
392 // C++ [temp.param]p2:
393 // There is no semantic difference between class and typename in a
394 // template-parameter. typename followed by an unqualified-id
395 // names a template type parameter. typename followed by a
396 // qualified-id denotes the type in a non-type
397 // parameter-declaration.
398 Token Next = NextToken();
399
400 // If we have an identifier, skip over it.
401 if (Next.getKind() == tok::identifier)
402 Next = GetLookAheadToken(2);
403
404 switch (Next.getKind()) {
405 case tok::equal:
406 case tok::comma:
407 case tok::greater:
408 case tok::greatergreater:
409 case tok::ellipsis:
410 return true;
411
412 default:
413 return false;
414 }
415}
416
Douglas Gregoreb31f392008-12-01 23:54:00 +0000417/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
418///
419/// template-parameter: [C++ temp.param]
420/// type-parameter
421/// parameter-declaration
422///
423/// type-parameter: (see below)
Douglas Gregorf5500772011-01-05 15:48:55 +0000424/// 'class' ...[opt] identifier[opt]
Douglas Gregoreb31f392008-12-01 23:54:00 +0000425/// 'class' identifier[opt] '=' type-id
Douglas Gregorf5500772011-01-05 15:48:55 +0000426/// 'typename' ...[opt] identifier[opt]
Douglas Gregoreb31f392008-12-01 23:54:00 +0000427/// 'typename' identifier[opt] '=' type-id
Douglas Gregorf5500772011-01-05 15:48:55 +0000428/// 'template' '<' template-parameter-list '>'
429/// 'class' ...[opt] identifier[opt]
430/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
431/// = id-expression
John McCall48871652010-08-21 09:40:31 +0000432Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26aedb72009-11-21 02:07:55 +0000433 if (isStartOfTemplateTypeParameter())
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000434 return ParseTypeParameter(Depth, Position);
Mike Stump11289f42009-09-09 15:08:12 +0000435
436 if (Tok.is(tok::kw_template))
Chris Lattnera21db612009-01-04 23:51:17 +0000437 return ParseTemplateTemplateParameter(Depth, Position);
438
439 // If it's none of the above, then it must be a parameter declaration.
440 // NOTE: This will pick up errors in the closure of the template parameter
441 // list (e.g., template < ; Check here to implement >> style closures.
442 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000443}
444
445/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
446/// Other kinds of template parameters are parsed in
447/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
448///
449/// type-parameter: [C++ temp.param]
Anders Carlssonf986ba72009-06-12 23:09:56 +0000450/// 'class' ...[opt][C++0x] identifier[opt]
Douglas Gregoreb31f392008-12-01 23:54:00 +0000451/// 'class' identifier[opt] '=' type-id
Anders Carlssonf986ba72009-06-12 23:09:56 +0000452/// 'typename' ...[opt][C++0x] identifier[opt]
Douglas Gregoreb31f392008-12-01 23:54:00 +0000453/// 'typename' identifier[opt] '=' type-id
John McCall48871652010-08-21 09:40:31 +0000454Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Douglas Gregorf5586182008-12-02 00:41:28 +0000455 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
Mike Stump11289f42009-09-09 15:08:12 +0000456 "A type-parameter starts with 'class' or 'typename'");
Douglas Gregorf5586182008-12-02 00:41:28 +0000457
458 // Consume the 'class' or 'typename' keyword.
459 bool TypenameKeyword = Tok.is(tok::kw_typename);
460 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregoreb31f392008-12-01 23:54:00 +0000461
Anders Carlsson01e9e932009-06-12 19:58:00 +0000462 // Grab the ellipsis (if given).
463 bool Ellipsis = false;
464 SourceLocation EllipsisLoc;
Anders Carlssonf986ba72009-06-12 23:09:56 +0000465 if (Tok.is(tok::ellipsis)) {
Anders Carlsson01e9e932009-06-12 19:58:00 +0000466 Ellipsis = true;
467 EllipsisLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000468
469 if (!getLang().CPlusPlus0x)
Anders Carlssonf986ba72009-06-12 23:09:56 +0000470 Diag(EllipsisLoc, diag::err_variadic_templates);
Anders Carlsson01e9e932009-06-12 19:58:00 +0000471 }
Mike Stump11289f42009-09-09 15:08:12 +0000472
Douglas Gregoreb31f392008-12-01 23:54:00 +0000473 // Grab the template parameter name (if given)
Douglas Gregorf5586182008-12-02 00:41:28 +0000474 SourceLocation NameLoc;
475 IdentifierInfo* ParamName = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000476 if (Tok.is(tok::identifier)) {
Douglas Gregorf5586182008-12-02 00:41:28 +0000477 ParamName = Tok.getIdentifierInfo();
478 NameLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000479 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
480 Tok.is(tok::greater)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000481 // Unnamed template parameter. Don't have to do anything here, just
482 // don't consume this token.
483 } else {
484 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCall48871652010-08-21 09:40:31 +0000485 return 0;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000486 }
Mike Stump11289f42009-09-09 15:08:12 +0000487
Douglas Gregordc13ded2010-07-01 00:00:45 +0000488 // Grab a default argument (if available).
489 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
490 // we introduce the type parameter into the local scope.
491 SourceLocation EqualLoc;
John McCallba7bf592010-08-24 05:47:05 +0000492 ParsedType DefaultArg;
Mike Stump11289f42009-09-09 15:08:12 +0000493 if (Tok.is(tok::equal)) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000494 EqualLoc = ConsumeToken();
495 DefaultArg = ParseTypeName().get();
Douglas Gregoreb31f392008-12-01 23:54:00 +0000496 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000497
Douglas Gregor0be31a22010-07-02 17:43:08 +0000498 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000499 EllipsisLoc, KeyLoc, ParamName, NameLoc,
500 Depth, Position, EqualLoc, DefaultArg);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000501}
502
503/// ParseTemplateTemplateParameter - Handle the parsing of template
Mike Stump11289f42009-09-09 15:08:12 +0000504/// template parameters.
Douglas Gregoreb31f392008-12-01 23:54:00 +0000505///
506/// type-parameter: [C++ temp.param]
Douglas Gregorf5500772011-01-05 15:48:55 +0000507/// 'template' '<' template-parameter-list '>' 'class'
508/// ...[opt] identifier[opt]
509/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
510/// = id-expression
John McCall48871652010-08-21 09:40:31 +0000511Decl *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000512Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000513 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
514
515 // Handle the template <...> part.
516 SourceLocation TemplateLoc = ConsumeToken();
John McCall572ccbc2010-08-23 06:53:58 +0000517 llvm::SmallVector<Decl*,8> TemplateParams;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000518 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor85e8b3e2009-02-10 19:52:54 +0000519 {
520 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Mike Stump11289f42009-09-09 15:08:12 +0000521 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +0000522 RAngleLoc)) {
John McCall48871652010-08-21 09:40:31 +0000523 return 0;
Douglas Gregor85e8b3e2009-02-10 19:52:54 +0000524 }
Douglas Gregoreb31f392008-12-01 23:54:00 +0000525 }
526
527 // Generate a meaningful error if the user forgot to put class before the
528 // identifier, comma, or greater.
Mike Stump11289f42009-09-09 15:08:12 +0000529 if (!Tok.is(tok::kw_class)) {
530 Diag(Tok.getLocation(), diag::err_expected_class_before)
Douglas Gregoreb31f392008-12-01 23:54:00 +0000531 << PP.getSpelling(Tok);
John McCall48871652010-08-21 09:40:31 +0000532 return 0;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000533 }
534 SourceLocation ClassLoc = ConsumeToken();
535
Douglas Gregorf5500772011-01-05 15:48:55 +0000536 // Parse the ellipsis, if given.
537 SourceLocation EllipsisLoc;
538 if (Tok.is(tok::ellipsis)) {
539 EllipsisLoc = ConsumeToken();
540
541 if (!getLang().CPlusPlus0x)
542 Diag(EllipsisLoc, diag::err_variadic_templates);
543 }
544
Douglas Gregoreb31f392008-12-01 23:54:00 +0000545 // Get the identifier, if given.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000546 SourceLocation NameLoc;
547 IdentifierInfo* ParamName = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000548 if (Tok.is(tok::identifier)) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000549 ParamName = Tok.getIdentifierInfo();
550 NameLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000551 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000552 // Unnamed template parameter. Don't have to do anything here, just
553 // don't consume this token.
554 } else {
555 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCall48871652010-08-21 09:40:31 +0000556 return 0;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000557 }
558
Mike Stump11289f42009-09-09 15:08:12 +0000559 TemplateParamsTy *ParamList =
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000560 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
561 TemplateLoc, LAngleLoc,
Douglas Gregora02bb372010-10-21 17:26:49 +0000562 TemplateParams.data(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000563 TemplateParams.size(),
564 RAngleLoc);
565
Douglas Gregordc13ded2010-07-01 00:00:45 +0000566 // Grab a default argument (if available).
567 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
568 // we introduce the template parameter into the local scope.
569 SourceLocation EqualLoc;
570 ParsedTemplateArgument DefaultArg;
Douglas Gregordba32632009-02-10 19:49:53 +0000571 if (Tok.is(tok::equal)) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000572 EqualLoc = ConsumeToken();
573 DefaultArg = ParseTemplateTemplateArgument();
574 if (DefaultArg.isInvalid()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000575 Diag(Tok.getLocation(),
576 diag::err_default_template_template_parameter_not_template);
Nuno Lopes221c1fd2009-12-10 00:07:02 +0000577 static const tok::TokenKind EndToks[] = {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000578 tok::comma, tok::greater, tok::greatergreater
579 };
580 SkipUntil(EndToks, 3, true, true);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000581 }
Douglas Gregordba32632009-02-10 19:49:53 +0000582 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000583
Douglas Gregor0be31a22010-07-02 17:43:08 +0000584 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000585 ParamList, EllipsisLoc,
586 ParamName, NameLoc, Depth,
587 Position, EqualLoc, DefaultArg);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000588}
589
590/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
Mike Stump11289f42009-09-09 15:08:12 +0000591/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000592///
Douglas Gregoreb31f392008-12-01 23:54:00 +0000593/// template-parameter:
594/// ...
595/// parameter-declaration
John McCall48871652010-08-21 09:40:31 +0000596Decl *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000597Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregorf5586182008-12-02 00:41:28 +0000598 SourceLocation StartLoc = Tok.getLocation();
Douglas Gregoreb31f392008-12-01 23:54:00 +0000599
600 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregorf5586182008-12-02 00:41:28 +0000601 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregoreb31f392008-12-01 23:54:00 +0000602 // declarators (parts of declarators?) are accepted for parameters.
Douglas Gregorf5586182008-12-02 00:41:28 +0000603 DeclSpec DS;
604 ParseDeclarationSpecifiers(DS);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000605
606 // Parse this as a typename.
Douglas Gregorf5586182008-12-02 00:41:28 +0000607 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
608 ParseDeclarator(ParamDecl);
John McCallba7bf592010-08-24 05:47:05 +0000609 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000610 // This probably shouldn't happen - and it's more of a Sema thing, but
611 // basically we didn't parse the type name because we couldn't associate
612 // it with an AST node. we should just skip to the comma or greater.
613 // TODO: This is currently a placeholder for some kind of Sema Error.
614 Diag(Tok.getLocation(), diag::err_parse_error);
615 SkipUntil(tok::comma, tok::greater, true, true);
John McCall48871652010-08-21 09:40:31 +0000616 return 0;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000617 }
618
Douglas Gregordba32632009-02-10 19:49:53 +0000619 // If there is a default value, parse it.
Douglas Gregordc13ded2010-07-01 00:00:45 +0000620 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
621 // we introduce the template parameter into the local scope.
622 SourceLocation EqualLoc;
John McCalldadc5752010-08-24 06:29:42 +0000623 ExprResult DefaultArg;
Chris Lattnerb5134c02009-01-05 01:24:05 +0000624 if (Tok.is(tok::equal)) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000625 EqualLoc = ConsumeToken();
Douglas Gregordba32632009-02-10 19:49:53 +0000626
627 // C++ [temp.param]p15:
628 // When parsing a default template-argument for a non-type
629 // template-parameter, the first non-nested > is taken as the
630 // end of the template-parameter-list rather than a greater-than
631 // operator.
Mike Stump11289f42009-09-09 15:08:12 +0000632 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000633
Douglas Gregordc13ded2010-07-01 00:00:45 +0000634 DefaultArg = ParseAssignmentExpression();
Douglas Gregordba32632009-02-10 19:49:53 +0000635 if (DefaultArg.isInvalid())
636 SkipUntil(tok::comma, tok::greater, true, true);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000637 }
Mike Stump11289f42009-09-09 15:08:12 +0000638
Douglas Gregordc13ded2010-07-01 00:00:45 +0000639 // Create the parameter.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000640 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000641 Depth, Position, EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000642 DefaultArg.take());
Douglas Gregoreb31f392008-12-01 23:54:00 +0000643}
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000644
Douglas Gregor67a65642009-02-17 23:15:12 +0000645/// \brief Parses a template-id that after the template name has
646/// already been parsed.
647///
648/// This routine takes care of parsing the enclosed template argument
649/// list ('<' template-parameter-list [opt] '>') and placing the
650/// results into a form that can be transferred to semantic analysis.
651///
652/// \param Template the template declaration produced by isTemplateName
653///
654/// \param TemplateNameLoc the source location of the template name
655///
656/// \param SS if non-NULL, the nested-name-specifier preceding the
657/// template name.
658///
659/// \param ConsumeLastToken if true, then we will consume the last
660/// token that forms the template-id. Otherwise, we will leave the
661/// last token in the stream (e.g., so that it can be replaced with an
662/// annotation token).
Mike Stump11289f42009-09-09 15:08:12 +0000663bool
Douglas Gregordc572a32009-03-30 22:58:21 +0000664Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
Mike Stump11289f42009-09-09 15:08:12 +0000665 SourceLocation TemplateNameLoc,
Douglas Gregor67a65642009-02-17 23:15:12 +0000666 const CXXScopeSpec *SS,
667 bool ConsumeLastToken,
668 SourceLocation &LAngleLoc,
669 TemplateArgList &TemplateArgs,
Douglas Gregor67a65642009-02-17 23:15:12 +0000670 SourceLocation &RAngleLoc) {
671 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
672
673 // Consume the '<'.
674 LAngleLoc = ConsumeToken();
675
676 // Parse the optional template-argument-list.
677 bool Invalid = false;
678 {
679 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Douglas Gregor180dda92011-01-11 00:45:18 +0000680 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
Douglas Gregorb53edfb2009-11-10 19:49:08 +0000681 Invalid = ParseTemplateArgumentList(TemplateArgs);
Douglas Gregor67a65642009-02-17 23:15:12 +0000682
683 if (Invalid) {
684 // Try to find the closing '>'.
685 SkipUntil(tok::greater, true, !ConsumeLastToken);
686
687 return true;
688 }
689 }
690
Eli Friedmanaffd5fd2009-12-27 22:31:18 +0000691 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) {
692 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregor67a65642009-02-17 23:15:12 +0000693 return true;
Eli Friedmanaffd5fd2009-12-27 22:31:18 +0000694 }
Douglas Gregor67a65642009-02-17 23:15:12 +0000695
Douglas Gregorcbb45d02009-02-25 23:02:36 +0000696 // Determine the location of the '>' or '>>'. Only consume this
697 // token if the caller asked us to.
Douglas Gregor67a65642009-02-17 23:15:12 +0000698 RAngleLoc = Tok.getLocation();
699
Douglas Gregorcbb45d02009-02-25 23:02:36 +0000700 if (Tok.is(tok::greatergreater)) {
Douglas Gregor87f95b02009-02-26 21:00:50 +0000701 if (!getLang().CPlusPlus0x) {
702 const char *ReplaceStr = "> >";
703 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
704 ReplaceStr = "> > ";
705
706 Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space)
Douglas Gregora771f462010-03-31 17:46:05 +0000707 << FixItHint::CreateReplacement(
Douglas Gregor96977da2009-02-27 17:53:17 +0000708 SourceRange(Tok.getLocation()), ReplaceStr);
Douglas Gregor87f95b02009-02-26 21:00:50 +0000709 }
Douglas Gregorcbb45d02009-02-25 23:02:36 +0000710
711 Tok.setKind(tok::greater);
712 if (!ConsumeLastToken) {
713 // Since we're not supposed to consume the '>>' token, we need
714 // to insert a second '>' token after the first.
715 PP.EnterToken(Tok);
716 }
717 } else if (ConsumeLastToken)
Douglas Gregor67a65642009-02-17 23:15:12 +0000718 ConsumeToken();
719
720 return false;
721}
Mike Stump11289f42009-09-09 15:08:12 +0000722
Douglas Gregor7f741122009-02-25 19:37:18 +0000723/// \brief Replace the tokens that form a simple-template-id with an
724/// annotation token containing the complete template-id.
725///
726/// The first token in the stream must be the name of a template that
727/// is followed by a '<'. This routine will parse the complete
728/// simple-template-id and replace the tokens with a single annotation
729/// token with one of two different kinds: if the template-id names a
730/// type (and \p AllowTypeAnnotation is true), the annotation token is
731/// a type annotation that includes the optional nested-name-specifier
732/// (\p SS). Otherwise, the annotation token is a template-id
733/// annotation that does not include the optional
734/// nested-name-specifier.
735///
736/// \param Template the declaration of the template named by the first
737/// token (an identifier), as returned from \c Action::isTemplateName().
738///
739/// \param TemplateNameKind the kind of template that \p Template
740/// refers to, as returned from \c Action::isTemplateName().
741///
742/// \param SS if non-NULL, the nested-name-specifier that precedes
743/// this template name.
744///
745/// \param TemplateKWLoc if valid, specifies that this template-id
746/// annotation was preceded by the 'template' keyword and gives the
747/// location of that keyword. If invalid (the default), then this
748/// template-id was not preceded by a 'template' keyword.
749///
750/// \param AllowTypeAnnotation if true (the default), then a
751/// simple-template-id that refers to a class template, template
752/// template parameter, or other template that produces a type will be
753/// replaced with a type annotation token. Otherwise, the
754/// simple-template-id is always replaced with a template-id
755/// annotation token.
Chris Lattner5558e9f2009-06-26 04:27:47 +0000756///
757/// If an unrecoverable parse error occurs and no annotation token can be
758/// formed, this function returns true.
759///
760bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Mike Stump11289f42009-09-09 15:08:12 +0000761 const CXXScopeSpec *SS,
Douglas Gregor71395fa2009-11-04 00:56:37 +0000762 UnqualifiedId &TemplateName,
Douglas Gregor7f741122009-02-25 19:37:18 +0000763 SourceLocation TemplateKWLoc,
764 bool AllowTypeAnnotation) {
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000765 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
Douglas Gregor71395fa2009-11-04 00:56:37 +0000766 assert(Template && Tok.is(tok::less) &&
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000767 "Parser isn't at the beginning of a template-id");
768
769 // Consume the template-name.
Douglas Gregor71395fa2009-11-04 00:56:37 +0000770 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000771
Douglas Gregor67a65642009-02-17 23:15:12 +0000772 // Parse the enclosed template argument list.
773 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor67b556a2009-02-09 19:34:22 +0000774 TemplateArgList TemplateArgs;
Douglas Gregor71395fa2009-11-04 00:56:37 +0000775 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
776 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000777 SS, false, LAngleLoc,
778 TemplateArgs,
Douglas Gregor67a65642009-02-17 23:15:12 +0000779 RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000780
Chris Lattner5558e9f2009-06-26 04:27:47 +0000781 if (Invalid) {
782 // If we failed to parse the template ID but skipped ahead to a >, we're not
783 // going to be able to form a token annotation. Eat the '>' if present.
784 if (Tok.is(tok::greater))
785 ConsumeToken();
786 return true;
787 }
Douglas Gregord32e0282009-02-09 23:23:08 +0000788
Jay Foad7d0479f2009-05-21 09:52:38 +0000789 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
Douglas Gregor67a65642009-02-17 23:15:12 +0000790 TemplateArgs.size());
Douglas Gregor0db4ccd2009-02-09 21:04:56 +0000791
Douglas Gregor8bf42052009-02-09 18:46:07 +0000792 // Build the annotation token.
Douglas Gregorb67535d2009-03-31 00:43:58 +0000793 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
John McCallfaf5fb42010-08-26 23:41:50 +0000794 TypeResult Type
Douglas Gregordc572a32009-03-30 22:58:21 +0000795 = Actions.ActOnTemplateIdType(Template, TemplateNameLoc,
796 LAngleLoc, TemplateArgsPtr,
Douglas Gregordc572a32009-03-30 22:58:21 +0000797 RAngleLoc);
Chris Lattner5558e9f2009-06-26 04:27:47 +0000798 if (Type.isInvalid()) {
799 // If we failed to parse the template ID but skipped ahead to a >, we're not
800 // going to be able to form a token annotation. Eat the '>' if present.
801 if (Tok.is(tok::greater))
802 ConsumeToken();
803 return true;
804 }
Douglas Gregor67a65642009-02-17 23:15:12 +0000805
806 Tok.setKind(tok::annot_typename);
John McCallba7bf592010-08-24 05:47:05 +0000807 setTypeAnnotation(Tok, Type.get());
Douglas Gregor7f741122009-02-25 19:37:18 +0000808 if (SS && SS->isNotEmpty())
809 Tok.setLocation(SS->getBeginLoc());
810 else if (TemplateKWLoc.isValid())
811 Tok.setLocation(TemplateKWLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000812 else
Douglas Gregor7f741122009-02-25 19:37:18 +0000813 Tok.setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +0000814 } else {
Douglas Gregorb67535d2009-03-31 00:43:58 +0000815 // Build a template-id annotation token that can be processed
816 // later.
Douglas Gregor7f741122009-02-25 19:37:18 +0000817 Tok.setKind(tok::annot_template_id);
Mike Stump11289f42009-09-09 15:08:12 +0000818 TemplateIdAnnotation *TemplateId
Douglas Gregor7f741122009-02-25 19:37:18 +0000819 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
Douglas Gregor8bf42052009-02-09 18:46:07 +0000820 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregor71395fa2009-11-04 00:56:37 +0000821 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
822 TemplateId->Name = TemplateName.Identifier;
823 TemplateId->Operator = OO_None;
824 } else {
825 TemplateId->Name = 0;
826 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
827 }
John McCall3e56fd42010-08-23 07:28:44 +0000828 TemplateId->Template = Template;
Douglas Gregor7f741122009-02-25 19:37:18 +0000829 TemplateId->Kind = TNK;
Douglas Gregor8bf42052009-02-09 18:46:07 +0000830 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor7f741122009-02-25 19:37:18 +0000831 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregorb53edfb2009-11-10 19:49:08 +0000832 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
833 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
Douglas Gregor8bf42052009-02-09 18:46:07 +0000834 Args[Arg] = TemplateArgs[Arg];
835 Tok.setAnnotationValue(TemplateId);
Douglas Gregor7f741122009-02-25 19:37:18 +0000836 if (TemplateKWLoc.isValid())
837 Tok.setLocation(TemplateKWLoc);
838 else
839 Tok.setLocation(TemplateNameLoc);
840
841 TemplateArgsPtr.release();
Douglas Gregor8bf42052009-02-09 18:46:07 +0000842 }
843
844 // Common fields for the annotation token
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000845 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000846
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000847 // In case the tokens were cached, have Preprocessor replace them with the
848 // annotation token.
849 PP.AnnotateCachedTokens(Tok);
Chris Lattner5558e9f2009-06-26 04:27:47 +0000850 return false;
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000851}
852
Douglas Gregor7f741122009-02-25 19:37:18 +0000853/// \brief Replaces a template-id annotation token with a type
854/// annotation token.
855///
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000856/// If there was a failure when forming the type from the template-id,
857/// a type annotation token will still be created, but will have a
858/// NULL type pointer to signify an error.
859void Parser::AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS) {
Douglas Gregor7f741122009-02-25 19:37:18 +0000860 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
861
Mike Stump11289f42009-09-09 15:08:12 +0000862 TemplateIdAnnotation *TemplateId
Douglas Gregor7f741122009-02-25 19:37:18 +0000863 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
Douglas Gregorb67535d2009-03-31 00:43:58 +0000864 assert((TemplateId->Kind == TNK_Type_template ||
865 TemplateId->Kind == TNK_Dependent_template_name) &&
866 "Only works for type and dependent templates");
Mike Stump11289f42009-09-09 15:08:12 +0000867
868 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
Douglas Gregor7f741122009-02-25 19:37:18 +0000869 TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +0000870 TemplateId->NumArgs);
871
John McCallfaf5fb42010-08-26 23:41:50 +0000872 TypeResult Type
John McCall3e56fd42010-08-23 07:28:44 +0000873 = Actions.ActOnTemplateIdType(TemplateId->Template,
Douglas Gregordc572a32009-03-30 22:58:21 +0000874 TemplateId->TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000875 TemplateId->LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +0000876 TemplateArgsPtr,
Douglas Gregordc572a32009-03-30 22:58:21 +0000877 TemplateId->RAngleLoc);
Douglas Gregor7f741122009-02-25 19:37:18 +0000878 // Create the new "type" annotation token.
879 Tok.setKind(tok::annot_typename);
John McCallba7bf592010-08-24 05:47:05 +0000880 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
Douglas Gregor7f741122009-02-25 19:37:18 +0000881 if (SS && SS->isNotEmpty()) // it was a C++ qualified type name.
882 Tok.setLocation(SS->getBeginLoc());
Sebastian Redlb0e3e1b2010-02-08 19:35:18 +0000883 // End location stays the same
Douglas Gregor7f741122009-02-25 19:37:18 +0000884
Douglas Gregor35522592009-11-04 18:18:19 +0000885 // Replace the template-id annotation token, and possible the scope-specifier
886 // that precedes it, with the typename annotation token.
887 PP.AnnotateCachedTokens(Tok);
Douglas Gregor7f741122009-02-25 19:37:18 +0000888 TemplateId->Destroy();
Douglas Gregor7f741122009-02-25 19:37:18 +0000889}
890
Douglas Gregorb53edfb2009-11-10 19:49:08 +0000891/// \brief Determine whether the given token can end a template argument.
Benjamin Kramer2c9a91c2009-11-10 21:29:56 +0000892static bool isEndOfTemplateArgument(Token Tok) {
Douglas Gregorb53edfb2009-11-10 19:49:08 +0000893 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
894 Tok.is(tok::greatergreater);
895}
896
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000897/// \brief Parse a C++ template template argument.
898ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
899 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
900 !Tok.is(tok::annot_cxxscope))
901 return ParsedTemplateArgument();
902
903 // C++0x [temp.arg.template]p1:
904 // A template-argument for a template template-parameter shall be the name
905 // of a class template or a template alias, expressed as id-expression.
906 //
Douglas Gregorc9984092009-11-12 00:03:40 +0000907 // We parse an id-expression that refers to a class template or template
908 // alias. The grammar we parse is:
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000909 //
Douglas Gregore9a80352011-01-05 17:33:50 +0000910 // nested-name-specifier[opt] template[opt] identifier ...[opt]
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000911 //
912 // followed by a token that terminates a template argument, such as ',',
913 // '>', or (in some cases) '>>'.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000914 CXXScopeSpec SS; // nested-name-specifier, if present
John McCallba7bf592010-08-24 05:47:05 +0000915 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000916 /*EnteringContext=*/false);
917
Douglas Gregore9a80352011-01-05 17:33:50 +0000918 ParsedTemplateArgument Result;
919 SourceLocation EllipsisLoc;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000920 if (SS.isSet() && Tok.is(tok::kw_template)) {
921 // Parse the optional 'template' keyword following the
922 // nested-name-specifier.
923 SourceLocation TemplateLoc = ConsumeToken();
924
925 if (Tok.is(tok::identifier)) {
926 // We appear to have a dependent template name.
927 UnqualifiedId Name;
928 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
929 ConsumeToken(); // the identifier
930
Douglas Gregore9a80352011-01-05 17:33:50 +0000931 // Parse the ellipsis.
932 if (Tok.is(tok::ellipsis))
933 EllipsisLoc = ConsumeToken();
934
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000935 // If the next token signals the end of a template argument,
936 // then we have a dependent template name that could be a template
937 // template argument.
Douglas Gregorbb119652010-06-16 23:00:59 +0000938 TemplateTy Template;
939 if (isEndOfTemplateArgument(Tok) &&
John McCallba7bf592010-08-24 05:47:05 +0000940 Actions.ActOnDependentTemplateName(getCurScope(), TemplateLoc,
941 SS, Name,
942 /*ObjectType=*/ ParsedType(),
Douglas Gregorbb119652010-06-16 23:00:59 +0000943 /*EnteringContext=*/false,
944 Template))
Douglas Gregore9a80352011-01-05 17:33:50 +0000945 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregorbb119652010-06-16 23:00:59 +0000946 }
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000947 } else if (Tok.is(tok::identifier)) {
948 // We may have a (non-dependent) template name.
949 TemplateTy Template;
950 UnqualifiedId Name;
951 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
952 ConsumeToken(); // the identifier
953
Douglas Gregore9a80352011-01-05 17:33:50 +0000954 // Parse the ellipsis.
955 if (Tok.is(tok::ellipsis))
956 EllipsisLoc = ConsumeToken();
957
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000958 if (isEndOfTemplateArgument(Tok)) {
Douglas Gregor786123d2010-05-21 23:18:07 +0000959 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000960 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
961 /*hasTemplateKeyword=*/false,
962 Name,
John McCallba7bf592010-08-24 05:47:05 +0000963 /*ObjectType=*/ ParsedType(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000964 /*EnteringContext=*/false,
Douglas Gregor786123d2010-05-21 23:18:07 +0000965 Template,
966 MemberOfUnknownSpecialization);
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000967 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
968 // We have an id-expression that refers to a class template or
969 // (C++0x) template alias.
Douglas Gregore9a80352011-01-05 17:33:50 +0000970 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000971 }
972 }
973 }
974
Douglas Gregore9a80352011-01-05 17:33:50 +0000975 // If this is a pack expansion, build it as such.
976 if (EllipsisLoc.isValid() && !Result.isInvalid())
977 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
978
979 return Result;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000980}
981
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000982/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
983///
984/// template-argument: [C++ 14.2]
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000985/// constant-expression
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000986/// type-id
987/// id-expression
Douglas Gregorb53edfb2009-11-10 19:49:08 +0000988ParsedTemplateArgument Parser::ParseTemplateArgument() {
Douglas Gregor8bf42052009-02-09 18:46:07 +0000989 // C++ [temp.arg]p2:
990 // In a template-argument, an ambiguity between a type-id and an
991 // expression is resolved to a type-id, regardless of the form of
992 // the corresponding template-parameter.
993 //
Douglas Gregorb53edfb2009-11-10 19:49:08 +0000994 // Therefore, we initially try to parse a type-id.
Douglas Gregor97f34572009-02-10 00:53:15 +0000995 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregorb53edfb2009-11-10 19:49:08 +0000996 SourceLocation Loc = Tok.getLocation();
Douglas Gregor220cac52009-02-18 17:45:20 +0000997 TypeResult TypeArg = ParseTypeName();
998 if (TypeArg.isInvalid())
Douglas Gregorb53edfb2009-11-10 19:49:08 +0000999 return ParsedTemplateArgument();
1000
John McCallba7bf592010-08-24 05:47:05 +00001001 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1002 TypeArg.get().getAsOpaquePtr(),
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001003 Loc);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001004 }
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001005
1006 // Try to parse a template template argument.
Douglas Gregorc9984092009-11-12 00:03:40 +00001007 {
1008 TentativeParsingAction TPA(*this);
1009
1010 ParsedTemplateArgument TemplateTemplateArgument
1011 = ParseTemplateTemplateArgument();
1012 if (!TemplateTemplateArgument.isInvalid()) {
1013 TPA.Commit();
1014 return TemplateTemplateArgument;
1015 }
1016
1017 // Revert this tentative parse to parse a non-type template argument.
1018 TPA.Revert();
1019 }
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001020
1021 // Parse a non-type template argument.
1022 SourceLocation Loc = Tok.getLocation();
John McCalldadc5752010-08-24 06:29:42 +00001023 ExprResult ExprArg = ParseConstantExpression();
Douglas Gregord32e0282009-02-09 23:23:08 +00001024 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001025 return ParsedTemplateArgument();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001026
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001027 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1028 ExprArg.release(), Loc);
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001029}
1030
Douglas Gregor786123d2010-05-21 23:18:07 +00001031/// \brief Determine whether the current tokens can only be parsed as a
1032/// template argument list (starting with the '<') and never as a '<'
1033/// expression.
Douglas Gregor20c38a72010-05-21 23:43:39 +00001034bool Parser::IsTemplateArgumentList(unsigned Skip) {
Douglas Gregor786123d2010-05-21 23:18:07 +00001035 struct AlwaysRevertAction : TentativeParsingAction {
1036 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1037 ~AlwaysRevertAction() { Revert(); }
1038 } Tentative(*this);
1039
Douglas Gregor20c38a72010-05-21 23:43:39 +00001040 while (Skip) {
1041 ConsumeToken();
1042 --Skip;
1043 }
1044
Douglas Gregor786123d2010-05-21 23:18:07 +00001045 // '<'
1046 if (!Tok.is(tok::less))
1047 return false;
1048 ConsumeToken();
1049
1050 // An empty template argument list.
1051 if (Tok.is(tok::greater))
1052 return true;
1053
1054 // See whether we have declaration specifiers, which indicate a type.
1055 while (isCXXDeclarationSpecifier() == TPResult::True())
1056 ConsumeToken();
1057
1058 // If we have a '>' or a ',' then this is a template argument list.
1059 return Tok.is(tok::greater) || Tok.is(tok::comma);
1060}
1061
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001062/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1063/// (C++ [temp.names]). Returns true if there was an error.
1064///
1065/// template-argument-list: [C++ 14.2]
1066/// template-argument
1067/// template-argument-list ',' template-argument
Mike Stump11289f42009-09-09 15:08:12 +00001068bool
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001069Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001070 while (true) {
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001071 ParsedTemplateArgument Arg = ParseTemplateArgument();
Douglas Gregord2fa7662010-12-20 02:24:11 +00001072 if (Tok.is(tok::ellipsis)) {
1073 SourceLocation EllipsisLoc = ConsumeToken();
1074 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1075 }
1076
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001077 if (Arg.isInvalid()) {
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001078 SkipUntil(tok::comma, tok::greater, true, true);
1079 return true;
1080 }
Douglas Gregor67b556a2009-02-09 19:34:22 +00001081
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001082 // Save this template argument.
1083 TemplateArgs.push_back(Arg);
1084
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001085 // If the next token is a comma, consume it and keep reading
1086 // arguments.
1087 if (Tok.isNot(tok::comma)) break;
1088
1089 // Consume the comma.
1090 ConsumeToken();
1091 }
1092
Eli Friedmanaffd5fd2009-12-27 22:31:18 +00001093 return false;
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001094}
1095
Mike Stump11289f42009-09-09 15:08:12 +00001096/// \brief Parse a C++ explicit template instantiation
Douglas Gregor23996282009-05-12 21:31:51 +00001097/// (C++ [temp.explicit]).
1098///
1099/// explicit-instantiation:
Douglas Gregor43e75172009-09-04 06:33:52 +00001100/// 'extern' [opt] 'template' declaration
1101///
1102/// Note that the 'extern' is a GNU extension and C++0x feature.
John McCall48871652010-08-21 09:40:31 +00001103Decl *Parser::ParseExplicitInstantiation(SourceLocation ExternLoc,
1104 SourceLocation TemplateLoc,
1105 SourceLocation &DeclEnd) {
John McCall796c2a52010-07-16 08:13:16 +00001106 // This isn't really required here.
1107 ParsingDeclRAIIObject ParsingTemplateParams(*this);
1108
Mike Stump11289f42009-09-09 15:08:12 +00001109 return ParseSingleDeclarationAfterTemplate(Declarator::FileContext,
Douglas Gregor43e75172009-09-04 06:33:52 +00001110 ParsedTemplateInfo(ExternLoc,
1111 TemplateLoc),
John McCall796c2a52010-07-16 08:13:16 +00001112 ParsingTemplateParams,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001113 DeclEnd, AS_none);
Douglas Gregor23996282009-05-12 21:31:51 +00001114}
John McCall9b72f892010-11-10 02:40:36 +00001115
1116SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1117 if (TemplateParams)
1118 return getTemplateParamsRange(TemplateParams->data(),
1119 TemplateParams->size());
1120
1121 SourceRange R(TemplateLoc);
1122 if (ExternLoc.isValid())
1123 R.setBegin(ExternLoc);
1124 return R;
1125}