blob: 333d72a754c4fc62aa200e33a728e776bd966479 [file] [log] [blame]
Douglas Gregoradcac882008-12-01 23:54:00 +00001//===--- ParseTemplate.cpp - Template Parsing -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements parsing of C++ templates.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
Chris Lattner500d3292009-01-29 05:15:15 +000015#include "clang/Parse/ParseDiagnostic.h"
John McCall19510852010-08-20 18:27:03 +000016#include "clang/Sema/DeclSpec.h"
17#include "clang/Sema/ParsedTemplate.h"
18#include "clang/Sema/Scope.h"
Chris Lattnerde138eb2009-12-10 00:45:15 +000019#include "RAIIObjectsForParser.h"
Douglas Gregoradcac882008-12-01 23:54:00 +000020using namespace clang;
21
Douglas Gregor4d9a16f2009-05-12 23:25:50 +000022/// \brief Parse a template declaration, explicit instantiation, or
23/// explicit specialization.
John McCalld226f652010-08-21 09:40:31 +000024Decl *
Douglas Gregor4d9a16f2009-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 Stump1eb44332009-09-09 15:08:12 +000029 return ParseExplicitInstantiation(SourceLocation(), ConsumeToken(),
Douglas Gregor45f96552009-09-04 06:33:52 +000030 DeclEnd);
Douglas Gregor4d9a16f2009-05-12 23:25:50 +000031
32 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS);
33}
34
Douglas Gregorc3058332009-08-24 23:03:25 +000035/// \brief RAII class that manages the template parameter depth.
36namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000037 class TemplateParameterDepthCounter {
Douglas Gregorc3058332009-08-24 23:03:25 +000038 unsigned &Depth;
39 unsigned AddedLevels;
40
41 public:
Mike Stump1eb44332009-09-09 15:08:12 +000042 explicit TemplateParameterDepthCounter(unsigned &Depth)
Douglas Gregorc3058332009-08-24 23:03:25 +000043 : Depth(Depth), AddedLevels(0) { }
Mike Stump1eb44332009-09-09 15:08:12 +000044
Douglas Gregorc3058332009-08-24 23:03:25 +000045 ~TemplateParameterDepthCounter() {
46 Depth -= AddedLevels;
47 }
Mike Stump1eb44332009-09-09 15:08:12 +000048
49 void operator++() {
Douglas Gregorc3058332009-08-24 23:03:25 +000050 ++Depth;
51 ++AddedLevels;
52 }
Mike Stump1eb44332009-09-09 15:08:12 +000053
Douglas Gregorc3058332009-08-24 23:03:25 +000054 operator unsigned() const { return Depth; }
55 };
56}
57
Douglas Gregorcc636682009-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 Gregoradcac882008-12-01 23:54:00 +000067///
68/// template-declaration: [C++ temp]
69/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
Douglas Gregorcc636682009-02-17 23:15:12 +000070///
71/// explicit-specialization: [ C++ temp.expl.spec]
72/// 'template' '<' '>' declaration
John McCalld226f652010-08-21 09:40:31 +000073Decl *
Anders Carlsson5aeccdb2009-03-26 00:52:18 +000074Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
Chris Lattner97144fc2009-04-02 04:16:50 +000075 SourceLocation &DeclEnd,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +000076 AccessSpecifier AS) {
Mike Stump1eb44332009-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 Gregor26236e82008-12-02 00:41:28 +000080 // Enter template-parameter scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +000081 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Douglas Gregor26236e82008-12-02 00:41:28 +000082
John McCallc9068d72010-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 Gregorc4b4e7b2008-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 Gregorcc636682009-02-17 23:15:12 +000096 // lists to easily differentiate between the case above and:
Douglas Gregorc4b4e7b2008-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 Gregor0f499d92009-08-20 18:46:05 +0000108 bool isSpecialization = true;
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000109 bool LastParamListWasEmpty = false;
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000110 TemplateParameterLists ParamLists;
Douglas Gregorc3058332009-08-24 23:03:25 +0000111 TemplateParameterDepthCounter Depth(TemplateParameterDepth);
Douglas Gregorc4b4e7b2008-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 McCalld226f652010-08-21 09:40:31 +0000125 return 0;
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000126 }
Mike Stump1eb44332009-09-09 15:08:12 +0000127
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000128 // Parse the '<' template-parameter-list '>'
129 SourceLocation LAngleLoc, RAngleLoc;
John McCall1f588162010-08-23 06:53:58 +0000130 llvm::SmallVector<Decl*, 4> TemplateParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000131 if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc,
Douglas Gregor7cdbc582009-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 McCalld226f652010-08-21 09:40:31 +0000137 return 0;
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000138 }
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000139
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000140 ParamLists.push_back(
Mike Stump1eb44332009-09-09 15:08:12 +0000141 Actions.ActOnTemplateParameterList(Depth, ExportLoc,
142 TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +0000143 TemplateParams.data(),
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000144 TemplateParams.size(), RAngleLoc));
Douglas Gregorc3058332009-08-24 23:03:25 +0000145
146 if (!TemplateParams.empty()) {
147 isSpecialization = false;
148 ++Depth;
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000149 } else {
150 LastParamListWasEmpty = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000151 }
Douglas Gregorc4b4e7b2008-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 Stump1eb44332009-09-09 15:08:12 +0000155 return ParseSingleDeclarationAfterTemplate(Context,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000156 ParsedTemplateInfo(&ParamLists,
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000157 isSpecialization,
158 LastParamListWasEmpty),
John McCallc9068d72010-07-16 08:13:16 +0000159 ParsingTemplateParams,
Douglas Gregor1426e532009-05-12 21:31:51 +0000160 DeclEnd, AS);
161}
Chris Lattner682bf922009-03-29 16:50:03 +0000162
Douglas Gregor1426e532009-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 McCalld226f652010-08-21 09:40:31 +0000183Decl *
Douglas Gregor1426e532009-05-12 21:31:51 +0000184Parser::ParseSingleDeclarationAfterTemplate(
185 unsigned Context,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000186 const ParsedTemplateInfo &TemplateInfo,
John McCallc9068d72010-07-16 08:13:16 +0000187 ParsingDeclRAIIObject &DiagsFromTParams,
Douglas Gregor1426e532009-05-12 21:31:51 +0000188 SourceLocation &DeclEnd,
189 AccessSpecifier AS) {
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000190 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
191 "Template information required");
192
Douglas Gregor37b372b2009-08-20 22:52:58 +0000193 if (Context == Declarator::MemberContext) {
194 // We are parsing a member template.
John McCallc9068d72010-07-16 08:13:16 +0000195 ParseCXXClassMemberDeclaration(AS, TemplateInfo, &DiagsFromTParams);
John McCalld226f652010-08-21 09:40:31 +0000196 return 0;
Douglas Gregor37b372b2009-08-20 22:52:58 +0000197 }
Mike Stump1eb44332009-09-09 15:08:12 +0000198
John McCall78b81052010-11-10 02:40:36 +0000199 CXX0XAttributeList PrefixAttrs;
200 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier())
201 PrefixAttrs = ParseCXX0XAttributes();
202
203 if (Tok.is(tok::kw_using))
204 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
205 PrefixAttrs);
206
John McCallc9068d72010-07-16 08:13:16 +0000207 // Parse the declaration specifiers, stealing the accumulated
208 // diagnostics from the template parameters.
209 ParsingDeclSpec DS(DiagsFromTParams);
Sean Huntbbd37c62009-11-21 08:43:09 +0000210
John McCall78b81052010-11-10 02:40:36 +0000211 if (PrefixAttrs.HasAttr)
212 DS.AddAttributes(PrefixAttrs.AttrList);
Sean Huntbbd37c62009-11-21 08:43:09 +0000213
Douglas Gregor0efc2c12010-01-13 17:31:36 +0000214 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
215 getDeclSpecContextFromDeclaratorContext(Context));
Douglas Gregor1426e532009-05-12 21:31:51 +0000216
217 if (Tok.is(tok::semi)) {
218 DeclEnd = ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000219 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
John McCall54abf7d2009-11-04 02:18:39 +0000220 DS.complete(Decl);
221 return Decl;
Douglas Gregor1426e532009-05-12 21:31:51 +0000222 }
223
224 // Parse the declarator.
John McCall54abf7d2009-11-04 02:18:39 +0000225 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
Douglas Gregor1426e532009-05-12 21:31:51 +0000226 ParseDeclarator(DeclaratorInfo);
227 // Error parsing the declarator?
228 if (!DeclaratorInfo.hasName()) {
229 // If so, skip until the semi-colon or a }.
230 SkipUntil(tok::r_brace, true, true);
231 if (Tok.is(tok::semi))
232 ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000233 return 0;
Douglas Gregor1426e532009-05-12 21:31:51 +0000234 }
Mike Stump1eb44332009-09-09 15:08:12 +0000235
Douglas Gregor1426e532009-05-12 21:31:51 +0000236 // If we have a declaration or declarator list, handle it.
237 if (isDeclarationAfterDeclarator()) {
238 // Parse this declaration.
John McCalld226f652010-08-21 09:40:31 +0000239 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
240 TemplateInfo);
Douglas Gregor1426e532009-05-12 21:31:51 +0000241
242 if (Tok.is(tok::comma)) {
243 Diag(Tok, diag::err_multiple_template_declarators)
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000244 << (int)TemplateInfo.Kind;
Douglas Gregor1426e532009-05-12 21:31:51 +0000245 SkipUntil(tok::semi, true, false);
246 return ThisDecl;
247 }
248
249 // Eat the semi colon after the declaration.
John McCall5c15fe12009-07-31 02:20:35 +0000250 ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
John McCall54abf7d2009-11-04 02:18:39 +0000251 DS.complete(ThisDecl);
Douglas Gregor1426e532009-05-12 21:31:51 +0000252 return ThisDecl;
253 }
254
255 if (DeclaratorInfo.isFunctionDeclarator() &&
Chris Lattner004659a2010-07-11 22:42:07 +0000256 isStartOfFunctionDefinition(DeclaratorInfo)) {
Douglas Gregor1426e532009-05-12 21:31:51 +0000257 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
258 Diag(Tok, diag::err_function_declared_typedef);
259
260 if (Tok.is(tok::l_brace)) {
261 // This recovery skips the entire function body. It would be nice
262 // to simply call ParseFunctionDefinition() below, however Sema
263 // assumes the declarator represents a function, not a typedef.
264 ConsumeBrace();
265 SkipUntil(tok::r_brace, true);
266 } else {
267 SkipUntil(tok::semi);
268 }
John McCalld226f652010-08-21 09:40:31 +0000269 return 0;
Douglas Gregor1426e532009-05-12 21:31:51 +0000270 }
Douglas Gregor52591bf2009-06-24 00:54:41 +0000271 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo);
Douglas Gregor1426e532009-05-12 21:31:51 +0000272 }
273
274 if (DeclaratorInfo.isFunctionDeclarator())
275 Diag(Tok, diag::err_expected_fn_body);
276 else
277 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
278 SkipUntil(tok::semi);
John McCalld226f652010-08-21 09:40:31 +0000279 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000280}
281
282/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000283/// angle brackets. Depth is the depth of this template-parameter-list, which
284/// is the number of template headers directly enclosing this template header.
285/// TemplateParams is the current list of template parameters we're building.
286/// The template parameter we parse will be added to this list. LAngleLoc and
Mike Stump1eb44332009-09-09 15:08:12 +0000287/// RAngleLoc will receive the positions of the '<' and '>', respectively,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000288/// that enclose this template parameter list.
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000289///
290/// \returns true if an error occurred, false otherwise.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000291bool Parser::ParseTemplateParameters(unsigned Depth,
John McCall1f588162010-08-23 06:53:58 +0000292 llvm::SmallVectorImpl<Decl*> &TemplateParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000293 SourceLocation &LAngleLoc,
294 SourceLocation &RAngleLoc) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000295 // Get the template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +0000296 if (!Tok.is(tok::less)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000297 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000298 return true;
Douglas Gregoradcac882008-12-01 23:54:00 +0000299 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000300 LAngleLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000301
Douglas Gregoradcac882008-12-01 23:54:00 +0000302 // Try to parse the template parameter list.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000303 if (Tok.is(tok::greater))
304 RAngleLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000305 else if (ParseTemplateParameterList(Depth, TemplateParams)) {
306 if (!Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000307 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000308 return true;
Douglas Gregoradcac882008-12-01 23:54:00 +0000309 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000310 RAngleLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000311 }
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000312 return false;
Douglas Gregoradcac882008-12-01 23:54:00 +0000313}
314
315/// ParseTemplateParameterList - Parse a template parameter list. If
316/// the parsing fails badly (i.e., closing bracket was left out), this
317/// will try to put the token stream in a reasonable position (closing
Mike Stump1eb44332009-09-09 15:08:12 +0000318/// a statement, etc.) and return false.
Douglas Gregoradcac882008-12-01 23:54:00 +0000319///
320/// template-parameter-list: [C++ temp]
321/// template-parameter
322/// template-parameter-list ',' template-parameter
Mike Stump1eb44332009-09-09 15:08:12 +0000323bool
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000324Parser::ParseTemplateParameterList(unsigned Depth,
John McCall1f588162010-08-23 06:53:58 +0000325 llvm::SmallVectorImpl<Decl*> &TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000326 while (1) {
John McCalld226f652010-08-21 09:40:31 +0000327 if (Decl *TmpParam
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000328 = ParseTemplateParameter(Depth, TemplateParams.size())) {
329 TemplateParams.push_back(TmpParam);
330 } else {
Douglas Gregoradcac882008-12-01 23:54:00 +0000331 // If we failed to parse a template parameter, skip until we find
332 // a comma or closing brace.
333 SkipUntil(tok::comma, tok::greater, true, true);
334 }
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Douglas Gregoradcac882008-12-01 23:54:00 +0000336 // Did we find a comma or the end of the template parmeter list?
Mike Stump1eb44332009-09-09 15:08:12 +0000337 if (Tok.is(tok::comma)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000338 ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000339 } else if (Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000340 // Don't consume this... that's done by template parser.
341 break;
342 } else {
343 // Somebody probably forgot to close the template. Skip ahead and
344 // try to get out of the expression. This error is currently
345 // subsumed by whatever goes on in ParseTemplateParameter.
346 // TODO: This could match >>, and it would be nice to avoid those
347 // silly errors with template <vec<T>>.
Douglas Gregor99ea7342010-10-15 01:15:58 +0000348 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Douglas Gregoradcac882008-12-01 23:54:00 +0000349 SkipUntil(tok::greater, true, true);
350 return false;
351 }
352 }
353 return true;
354}
355
Douglas Gregor98440b42009-11-21 02:07:55 +0000356/// \brief Determine whether the parser is at the start of a template
357/// type parameter.
358bool Parser::isStartOfTemplateTypeParameter() {
Douglas Gregor7b6d25b2010-06-04 07:30:15 +0000359 if (Tok.is(tok::kw_class)) {
360 // "class" may be the start of an elaborated-type-specifier or a
361 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
362 switch (NextToken().getKind()) {
363 case tok::equal:
364 case tok::comma:
365 case tok::greater:
366 case tok::greatergreater:
367 case tok::ellipsis:
368 return true;
369
370 case tok::identifier:
371 // This may be either a type-parameter or an elaborated-type-specifier.
372 // We have to look further.
373 break;
374
375 default:
376 return false;
377 }
378
379 switch (GetLookAheadToken(2).getKind()) {
380 case tok::equal:
381 case tok::comma:
382 case tok::greater:
383 case tok::greatergreater:
384 return true;
385
386 default:
387 return false;
388 }
389 }
Douglas Gregor98440b42009-11-21 02:07:55 +0000390
391 if (Tok.isNot(tok::kw_typename))
392 return false;
393
394 // C++ [temp.param]p2:
395 // There is no semantic difference between class and typename in a
396 // template-parameter. typename followed by an unqualified-id
397 // names a template type parameter. typename followed by a
398 // qualified-id denotes the type in a non-type
399 // parameter-declaration.
400 Token Next = NextToken();
401
402 // If we have an identifier, skip over it.
403 if (Next.getKind() == tok::identifier)
404 Next = GetLookAheadToken(2);
405
406 switch (Next.getKind()) {
407 case tok::equal:
408 case tok::comma:
409 case tok::greater:
410 case tok::greatergreater:
411 case tok::ellipsis:
412 return true;
413
414 default:
415 return false;
416 }
417}
418
Douglas Gregoradcac882008-12-01 23:54:00 +0000419/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
420///
421/// template-parameter: [C++ temp.param]
422/// type-parameter
423/// parameter-declaration
424///
425/// type-parameter: (see below)
Anders Carlssonce5635a2009-06-12 23:09:56 +0000426/// 'class' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000427/// 'class' identifier[opt] '=' type-id
Anders Carlssonce5635a2009-06-12 23:09:56 +0000428/// 'typename' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000429/// 'typename' identifier[opt] '=' type-id
Anders Carlssonce5635a2009-06-12 23:09:56 +0000430/// 'template' ...[opt][C++0x] '<' template-parameter-list '>' 'class' identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000431/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
John McCalld226f652010-08-21 09:40:31 +0000432Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor98440b42009-11-21 02:07:55 +0000433 if (isStartOfTemplateTypeParameter())
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000434 return ParseTypeParameter(Depth, Position);
Mike Stump1eb44332009-09-09 15:08:12 +0000435
436 if (Tok.is(tok::kw_template))
Chris Lattner532e19b2009-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 Gregoradcac882008-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 Carlssonce5635a2009-06-12 23:09:56 +0000450/// 'class' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000451/// 'class' identifier[opt] '=' type-id
Anders Carlssonce5635a2009-06-12 23:09:56 +0000452/// 'typename' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000453/// 'typename' identifier[opt] '=' type-id
John McCalld226f652010-08-21 09:40:31 +0000454Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000455 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
Mike Stump1eb44332009-09-09 15:08:12 +0000456 "A type-parameter starts with 'class' or 'typename'");
Douglas Gregor26236e82008-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 Gregoradcac882008-12-01 23:54:00 +0000461
Anders Carlsson941df7d2009-06-12 19:58:00 +0000462 // Grab the ellipsis (if given).
463 bool Ellipsis = false;
464 SourceLocation EllipsisLoc;
Anders Carlssonce5635a2009-06-12 23:09:56 +0000465 if (Tok.is(tok::ellipsis)) {
Anders Carlsson941df7d2009-06-12 19:58:00 +0000466 Ellipsis = true;
467 EllipsisLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000468
469 if (!getLang().CPlusPlus0x)
Anders Carlssonce5635a2009-06-12 23:09:56 +0000470 Diag(EllipsisLoc, diag::err_variadic_templates);
Anders Carlsson941df7d2009-06-12 19:58:00 +0000471 }
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Douglas Gregoradcac882008-12-01 23:54:00 +0000473 // Grab the template parameter name (if given)
Douglas Gregor26236e82008-12-02 00:41:28 +0000474 SourceLocation NameLoc;
475 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000476 if (Tok.is(tok::identifier)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000477 ParamName = Tok.getIdentifierInfo();
478 NameLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000479 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
480 Tok.is(tok::greater)) {
Douglas Gregoradcac882008-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 McCalld226f652010-08-21 09:40:31 +0000485 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000486 }
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Douglas Gregorbb3310a2010-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 McCallb3d87482010-08-24 05:47:05 +0000492 ParsedType DefaultArg;
Mike Stump1eb44332009-09-09 15:08:12 +0000493 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000494 EqualLoc = ConsumeToken();
495 DefaultArg = ParseTypeName().get();
Douglas Gregoradcac882008-12-01 23:54:00 +0000496 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000497
Douglas Gregor23c94db2010-07-02 17:43:08 +0000498 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000499 EllipsisLoc, KeyLoc, ParamName, NameLoc,
500 Depth, Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000501}
502
503/// ParseTemplateTemplateParameter - Handle the parsing of template
Mike Stump1eb44332009-09-09 15:08:12 +0000504/// template parameters.
Douglas Gregoradcac882008-12-01 23:54:00 +0000505///
506/// type-parameter: [C++ temp.param]
507/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
508/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
John McCalld226f652010-08-21 09:40:31 +0000509Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000510Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000511 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
512
513 // Handle the template <...> part.
514 SourceLocation TemplateLoc = ConsumeToken();
John McCall1f588162010-08-23 06:53:58 +0000515 llvm::SmallVector<Decl*,8> TemplateParams;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000516 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor68c69932009-02-10 19:52:54 +0000517 {
518 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000519 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000520 RAngleLoc)) {
John McCalld226f652010-08-21 09:40:31 +0000521 return 0;
Douglas Gregor68c69932009-02-10 19:52:54 +0000522 }
Douglas Gregoradcac882008-12-01 23:54:00 +0000523 }
524
525 // Generate a meaningful error if the user forgot to put class before the
526 // identifier, comma, or greater.
Mike Stump1eb44332009-09-09 15:08:12 +0000527 if (!Tok.is(tok::kw_class)) {
528 Diag(Tok.getLocation(), diag::err_expected_class_before)
Douglas Gregoradcac882008-12-01 23:54:00 +0000529 << PP.getSpelling(Tok);
John McCalld226f652010-08-21 09:40:31 +0000530 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000531 }
532 SourceLocation ClassLoc = ConsumeToken();
533
534 // Get the identifier, if given.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000535 SourceLocation NameLoc;
536 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000537 if (Tok.is(tok::identifier)) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000538 ParamName = Tok.getIdentifierInfo();
539 NameLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000540 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000541 // Unnamed template parameter. Don't have to do anything here, just
542 // don't consume this token.
543 } else {
544 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000545 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000546 }
547
Mike Stump1eb44332009-09-09 15:08:12 +0000548 TemplateParamsTy *ParamList =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000549 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
550 TemplateLoc, LAngleLoc,
Douglas Gregor369ea272010-10-21 17:26:49 +0000551 TemplateParams.data(),
Douglas Gregorddc29e12009-02-06 22:42:48 +0000552 TemplateParams.size(),
553 RAngleLoc);
554
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000555 // Grab a default argument (if available).
556 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
557 // we introduce the template parameter into the local scope.
558 SourceLocation EqualLoc;
559 ParsedTemplateArgument DefaultArg;
Douglas Gregord684b002009-02-10 19:49:53 +0000560 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000561 EqualLoc = ConsumeToken();
562 DefaultArg = ParseTemplateTemplateArgument();
563 if (DefaultArg.isInvalid()) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000564 Diag(Tok.getLocation(),
565 diag::err_default_template_template_parameter_not_template);
Nuno Lopes68f7a242009-12-10 00:07:02 +0000566 static const tok::TokenKind EndToks[] = {
Douglas Gregor788cd062009-11-11 01:00:40 +0000567 tok::comma, tok::greater, tok::greatergreater
568 };
569 SkipUntil(EndToks, 3, true, true);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000570 }
Douglas Gregord684b002009-02-10 19:49:53 +0000571 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000572
Douglas Gregor23c94db2010-07-02 17:43:08 +0000573 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000574 ParamList, ParamName,
575 NameLoc, Depth, Position,
576 EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000577}
578
579/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
Mike Stump1eb44332009-09-09 15:08:12 +0000580/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000581///
Douglas Gregoradcac882008-12-01 23:54:00 +0000582/// template-parameter:
583/// ...
584/// parameter-declaration
John McCalld226f652010-08-21 09:40:31 +0000585Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000586Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000587 SourceLocation StartLoc = Tok.getLocation();
Douglas Gregoradcac882008-12-01 23:54:00 +0000588
589 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor26236e82008-12-02 00:41:28 +0000590 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregoradcac882008-12-01 23:54:00 +0000591 // declarators (parts of declarators?) are accepted for parameters.
Douglas Gregor26236e82008-12-02 00:41:28 +0000592 DeclSpec DS;
593 ParseDeclarationSpecifiers(DS);
Douglas Gregoradcac882008-12-01 23:54:00 +0000594
595 // Parse this as a typename.
Douglas Gregor26236e82008-12-02 00:41:28 +0000596 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
597 ParseDeclarator(ParamDecl);
John McCallb3d87482010-08-24 05:47:05 +0000598 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000599 // This probably shouldn't happen - and it's more of a Sema thing, but
600 // basically we didn't parse the type name because we couldn't associate
601 // it with an AST node. we should just skip to the comma or greater.
602 // TODO: This is currently a placeholder for some kind of Sema Error.
603 Diag(Tok.getLocation(), diag::err_parse_error);
604 SkipUntil(tok::comma, tok::greater, true, true);
John McCalld226f652010-08-21 09:40:31 +0000605 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000606 }
607
Douglas Gregord684b002009-02-10 19:49:53 +0000608 // If there is a default value, parse it.
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000609 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
610 // we introduce the template parameter into the local scope.
611 SourceLocation EqualLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000612 ExprResult DefaultArg;
Chris Lattner7452c6f2009-01-05 01:24:05 +0000613 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000614 EqualLoc = ConsumeToken();
Douglas Gregord684b002009-02-10 19:49:53 +0000615
616 // C++ [temp.param]p15:
617 // When parsing a default template-argument for a non-type
618 // template-parameter, the first non-nested > is taken as the
619 // end of the template-parameter-list rather than a greater-than
620 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +0000621 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000622
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000623 DefaultArg = ParseAssignmentExpression();
Douglas Gregord684b002009-02-10 19:49:53 +0000624 if (DefaultArg.isInvalid())
625 SkipUntil(tok::comma, tok::greater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000626 }
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000628 // Create the parameter.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000629 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000630 Depth, Position, EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000631 DefaultArg.take());
Douglas Gregoradcac882008-12-01 23:54:00 +0000632}
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000633
Douglas Gregorcc636682009-02-17 23:15:12 +0000634/// \brief Parses a template-id that after the template name has
635/// already been parsed.
636///
637/// This routine takes care of parsing the enclosed template argument
638/// list ('<' template-parameter-list [opt] '>') and placing the
639/// results into a form that can be transferred to semantic analysis.
640///
641/// \param Template the template declaration produced by isTemplateName
642///
643/// \param TemplateNameLoc the source location of the template name
644///
645/// \param SS if non-NULL, the nested-name-specifier preceding the
646/// template name.
647///
648/// \param ConsumeLastToken if true, then we will consume the last
649/// token that forms the template-id. Otherwise, we will leave the
650/// last token in the stream (e.g., so that it can be replaced with an
651/// annotation token).
Mike Stump1eb44332009-09-09 15:08:12 +0000652bool
Douglas Gregor7532dc62009-03-30 22:58:21 +0000653Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
Mike Stump1eb44332009-09-09 15:08:12 +0000654 SourceLocation TemplateNameLoc,
Douglas Gregorcc636682009-02-17 23:15:12 +0000655 const CXXScopeSpec *SS,
656 bool ConsumeLastToken,
657 SourceLocation &LAngleLoc,
658 TemplateArgList &TemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +0000659 SourceLocation &RAngleLoc) {
660 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
661
662 // Consume the '<'.
663 LAngleLoc = ConsumeToken();
664
665 // Parse the optional template-argument-list.
666 bool Invalid = false;
667 {
668 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
669 if (Tok.isNot(tok::greater))
Douglas Gregor314b97f2009-11-10 19:49:08 +0000670 Invalid = ParseTemplateArgumentList(TemplateArgs);
Douglas Gregorcc636682009-02-17 23:15:12 +0000671
672 if (Invalid) {
673 // Try to find the closing '>'.
674 SkipUntil(tok::greater, true, !ConsumeLastToken);
675
676 return true;
677 }
678 }
679
Eli Friedman64a4eb22009-12-27 22:31:18 +0000680 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) {
681 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregorcc636682009-02-17 23:15:12 +0000682 return true;
Eli Friedman64a4eb22009-12-27 22:31:18 +0000683 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000684
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000685 // Determine the location of the '>' or '>>'. Only consume this
686 // token if the caller asked us to.
Douglas Gregorcc636682009-02-17 23:15:12 +0000687 RAngleLoc = Tok.getLocation();
688
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000689 if (Tok.is(tok::greatergreater)) {
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000690 if (!getLang().CPlusPlus0x) {
691 const char *ReplaceStr = "> >";
692 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
693 ReplaceStr = "> > ";
694
695 Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space)
Douglas Gregor849b2432010-03-31 17:46:05 +0000696 << FixItHint::CreateReplacement(
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000697 SourceRange(Tok.getLocation()), ReplaceStr);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000698 }
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000699
700 Tok.setKind(tok::greater);
701 if (!ConsumeLastToken) {
702 // Since we're not supposed to consume the '>>' token, we need
703 // to insert a second '>' token after the first.
704 PP.EnterToken(Tok);
705 }
706 } else if (ConsumeLastToken)
Douglas Gregorcc636682009-02-17 23:15:12 +0000707 ConsumeToken();
708
709 return false;
710}
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Douglas Gregor39a8de12009-02-25 19:37:18 +0000712/// \brief Replace the tokens that form a simple-template-id with an
713/// annotation token containing the complete template-id.
714///
715/// The first token in the stream must be the name of a template that
716/// is followed by a '<'. This routine will parse the complete
717/// simple-template-id and replace the tokens with a single annotation
718/// token with one of two different kinds: if the template-id names a
719/// type (and \p AllowTypeAnnotation is true), the annotation token is
720/// a type annotation that includes the optional nested-name-specifier
721/// (\p SS). Otherwise, the annotation token is a template-id
722/// annotation that does not include the optional
723/// nested-name-specifier.
724///
725/// \param Template the declaration of the template named by the first
726/// token (an identifier), as returned from \c Action::isTemplateName().
727///
728/// \param TemplateNameKind the kind of template that \p Template
729/// refers to, as returned from \c Action::isTemplateName().
730///
731/// \param SS if non-NULL, the nested-name-specifier that precedes
732/// this template name.
733///
734/// \param TemplateKWLoc if valid, specifies that this template-id
735/// annotation was preceded by the 'template' keyword and gives the
736/// location of that keyword. If invalid (the default), then this
737/// template-id was not preceded by a 'template' keyword.
738///
739/// \param AllowTypeAnnotation if true (the default), then a
740/// simple-template-id that refers to a class template, template
741/// template parameter, or other template that produces a type will be
742/// replaced with a type annotation token. Otherwise, the
743/// simple-template-id is always replaced with a template-id
744/// annotation token.
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000745///
746/// If an unrecoverable parse error occurs and no annotation token can be
747/// formed, this function returns true.
748///
749bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Mike Stump1eb44332009-09-09 15:08:12 +0000750 const CXXScopeSpec *SS,
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000751 UnqualifiedId &TemplateName,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000752 SourceLocation TemplateKWLoc,
753 bool AllowTypeAnnotation) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000754 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000755 assert(Template && Tok.is(tok::less) &&
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000756 "Parser isn't at the beginning of a template-id");
757
758 // Consume the template-name.
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000759 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000760
Douglas Gregorcc636682009-02-17 23:15:12 +0000761 // Parse the enclosed template argument list.
762 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000763 TemplateArgList TemplateArgs;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000764 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
765 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000766 SS, false, LAngleLoc,
767 TemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +0000768 RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000770 if (Invalid) {
771 // If we failed to parse the template ID but skipped ahead to a >, we're not
772 // going to be able to form a token annotation. Eat the '>' if present.
773 if (Tok.is(tok::greater))
774 ConsumeToken();
775 return true;
776 }
Douglas Gregorc15cb382009-02-09 23:23:08 +0000777
Jay Foadbeaaccd2009-05-21 09:52:38 +0000778 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
Douglas Gregorcc636682009-02-17 23:15:12 +0000779 TemplateArgs.size());
Douglas Gregorf02da892009-02-09 21:04:56 +0000780
Douglas Gregor55f6b142009-02-09 18:46:07 +0000781 // Build the annotation token.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000782 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
John McCallf312b1e2010-08-26 23:41:50 +0000783 TypeResult Type
Douglas Gregor7532dc62009-03-30 22:58:21 +0000784 = Actions.ActOnTemplateIdType(Template, TemplateNameLoc,
785 LAngleLoc, TemplateArgsPtr,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000786 RAngleLoc);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000787 if (Type.isInvalid()) {
788 // If we failed to parse the template ID but skipped ahead to a >, we're not
789 // going to be able to form a token annotation. Eat the '>' if present.
790 if (Tok.is(tok::greater))
791 ConsumeToken();
792 return true;
793 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000794
795 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000796 setTypeAnnotation(Tok, Type.get());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000797 if (SS && SS->isNotEmpty())
798 Tok.setLocation(SS->getBeginLoc());
799 else if (TemplateKWLoc.isValid())
800 Tok.setLocation(TemplateKWLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000801 else
Douglas Gregor39a8de12009-02-25 19:37:18 +0000802 Tok.setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +0000803 } else {
Douglas Gregorc45c2322009-03-31 00:43:58 +0000804 // Build a template-id annotation token that can be processed
805 // later.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000806 Tok.setKind(tok::annot_template_id);
Mike Stump1eb44332009-09-09 15:08:12 +0000807 TemplateIdAnnotation *TemplateId
Douglas Gregor39a8de12009-02-25 19:37:18 +0000808 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
Douglas Gregor55f6b142009-02-09 18:46:07 +0000809 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000810 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
811 TemplateId->Name = TemplateName.Identifier;
812 TemplateId->Operator = OO_None;
813 } else {
814 TemplateId->Name = 0;
815 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
816 }
John McCall2b5289b2010-08-23 07:28:44 +0000817 TemplateId->Template = Template;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000818 TemplateId->Kind = TNK;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000819 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000820 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregor314b97f2009-11-10 19:49:08 +0000821 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
822 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
Douglas Gregor55f6b142009-02-09 18:46:07 +0000823 Args[Arg] = TemplateArgs[Arg];
824 Tok.setAnnotationValue(TemplateId);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000825 if (TemplateKWLoc.isValid())
826 Tok.setLocation(TemplateKWLoc);
827 else
828 Tok.setLocation(TemplateNameLoc);
829
830 TemplateArgsPtr.release();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000831 }
832
833 // Common fields for the annotation token
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000834 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000835
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000836 // In case the tokens were cached, have Preprocessor replace them with the
837 // annotation token.
838 PP.AnnotateCachedTokens(Tok);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000839 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000840}
841
Douglas Gregor39a8de12009-02-25 19:37:18 +0000842/// \brief Replaces a template-id annotation token with a type
843/// annotation token.
844///
Douglas Gregor31a19b62009-04-01 21:51:26 +0000845/// If there was a failure when forming the type from the template-id,
846/// a type annotation token will still be created, but will have a
847/// NULL type pointer to signify an error.
848void Parser::AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS) {
Douglas Gregor39a8de12009-02-25 19:37:18 +0000849 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
850
Mike Stump1eb44332009-09-09 15:08:12 +0000851 TemplateIdAnnotation *TemplateId
Douglas Gregor39a8de12009-02-25 19:37:18 +0000852 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
Douglas Gregorc45c2322009-03-31 00:43:58 +0000853 assert((TemplateId->Kind == TNK_Type_template ||
854 TemplateId->Kind == TNK_Dependent_template_name) &&
855 "Only works for type and dependent templates");
Mike Stump1eb44332009-09-09 15:08:12 +0000856
857 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000858 TemplateId->getTemplateArgs(),
Douglas Gregor39a8de12009-02-25 19:37:18 +0000859 TemplateId->NumArgs);
860
John McCallf312b1e2010-08-26 23:41:50 +0000861 TypeResult Type
John McCall2b5289b2010-08-23 07:28:44 +0000862 = Actions.ActOnTemplateIdType(TemplateId->Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000863 TemplateId->TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000864 TemplateId->LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000865 TemplateArgsPtr,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000866 TemplateId->RAngleLoc);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000867 // Create the new "type" annotation token.
868 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000869 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000870 if (SS && SS->isNotEmpty()) // it was a C++ qualified type name.
871 Tok.setLocation(SS->getBeginLoc());
Sebastian Redl39d67112010-02-08 19:35:18 +0000872 // End location stays the same
Douglas Gregor39a8de12009-02-25 19:37:18 +0000873
Douglas Gregor86235412009-11-04 18:18:19 +0000874 // Replace the template-id annotation token, and possible the scope-specifier
875 // that precedes it, with the typename annotation token.
876 PP.AnnotateCachedTokens(Tok);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000877 TemplateId->Destroy();
Douglas Gregor39a8de12009-02-25 19:37:18 +0000878}
879
Douglas Gregor314b97f2009-11-10 19:49:08 +0000880/// \brief Determine whether the given token can end a template argument.
Benjamin Kramer3a4a2b32009-11-10 21:29:56 +0000881static bool isEndOfTemplateArgument(Token Tok) {
Douglas Gregor314b97f2009-11-10 19:49:08 +0000882 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
883 Tok.is(tok::greatergreater);
884}
885
Douglas Gregor788cd062009-11-11 01:00:40 +0000886/// \brief Parse a C++ template template argument.
887ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
888 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
889 !Tok.is(tok::annot_cxxscope))
890 return ParsedTemplateArgument();
891
892 // C++0x [temp.arg.template]p1:
893 // A template-argument for a template template-parameter shall be the name
894 // of a class template or a template alias, expressed as id-expression.
895 //
Douglas Gregoreaf75f42009-11-12 00:03:40 +0000896 // We parse an id-expression that refers to a class template or template
897 // alias. The grammar we parse is:
Douglas Gregor788cd062009-11-11 01:00:40 +0000898 //
899 // nested-name-specifier[opt] template[opt] identifier
900 //
901 // followed by a token that terminates a template argument, such as ',',
902 // '>', or (in some cases) '>>'.
Douglas Gregor788cd062009-11-11 01:00:40 +0000903 CXXScopeSpec SS; // nested-name-specifier, if present
John McCallb3d87482010-08-24 05:47:05 +0000904 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000905 /*EnteringContext=*/false);
906
907 if (SS.isSet() && Tok.is(tok::kw_template)) {
908 // Parse the optional 'template' keyword following the
909 // nested-name-specifier.
910 SourceLocation TemplateLoc = ConsumeToken();
911
912 if (Tok.is(tok::identifier)) {
913 // We appear to have a dependent template name.
914 UnqualifiedId Name;
915 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
916 ConsumeToken(); // the identifier
917
918 // If the next token signals the end of a template argument,
919 // then we have a dependent template name that could be a template
920 // template argument.
Douglas Gregord6ab2322010-06-16 23:00:59 +0000921 TemplateTy Template;
922 if (isEndOfTemplateArgument(Tok) &&
John McCallb3d87482010-08-24 05:47:05 +0000923 Actions.ActOnDependentTemplateName(getCurScope(), TemplateLoc,
924 SS, Name,
925 /*ObjectType=*/ ParsedType(),
Douglas Gregord6ab2322010-06-16 23:00:59 +0000926 /*EnteringContext=*/false,
927 Template))
928 return ParsedTemplateArgument(SS, Template, Name.StartLocation);
929 }
Douglas Gregor788cd062009-11-11 01:00:40 +0000930 } else if (Tok.is(tok::identifier)) {
931 // We may have a (non-dependent) template name.
932 TemplateTy Template;
933 UnqualifiedId Name;
934 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
935 ConsumeToken(); // the identifier
936
937 if (isEndOfTemplateArgument(Tok)) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000938 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +0000939 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
940 /*hasTemplateKeyword=*/false,
941 Name,
John McCallb3d87482010-08-24 05:47:05 +0000942 /*ObjectType=*/ ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000943 /*EnteringContext=*/false,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000944 Template,
945 MemberOfUnknownSpecialization);
Douglas Gregor788cd062009-11-11 01:00:40 +0000946 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
947 // We have an id-expression that refers to a class template or
948 // (C++0x) template alias.
Douglas Gregor788cd062009-11-11 01:00:40 +0000949 return ParsedTemplateArgument(SS, Template, Name.StartLocation);
950 }
951 }
952 }
953
Douglas Gregoreaf75f42009-11-12 00:03:40 +0000954 // We don't have a template template argument.
Douglas Gregor788cd062009-11-11 01:00:40 +0000955 return ParsedTemplateArgument();
956}
957
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000958/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
959///
960/// template-argument: [C++ 14.2]
Douglas Gregorac7610d2009-06-22 20:57:11 +0000961/// constant-expression
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000962/// type-id
963/// id-expression
Douglas Gregor314b97f2009-11-10 19:49:08 +0000964ParsedTemplateArgument Parser::ParseTemplateArgument() {
Douglas Gregor55f6b142009-02-09 18:46:07 +0000965 // C++ [temp.arg]p2:
966 // In a template-argument, an ambiguity between a type-id and an
967 // expression is resolved to a type-id, regardless of the form of
968 // the corresponding template-parameter.
969 //
Douglas Gregor314b97f2009-11-10 19:49:08 +0000970 // Therefore, we initially try to parse a type-id.
Douglas Gregor8b642592009-02-10 00:53:15 +0000971 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor314b97f2009-11-10 19:49:08 +0000972 SourceLocation Loc = Tok.getLocation();
Douglas Gregor809070a2009-02-18 17:45:20 +0000973 TypeResult TypeArg = ParseTypeName();
974 if (TypeArg.isInvalid())
Douglas Gregor314b97f2009-11-10 19:49:08 +0000975 return ParsedTemplateArgument();
976
John McCallb3d87482010-08-24 05:47:05 +0000977 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
978 TypeArg.get().getAsOpaquePtr(),
Douglas Gregor314b97f2009-11-10 19:49:08 +0000979 Loc);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000980 }
Douglas Gregor788cd062009-11-11 01:00:40 +0000981
982 // Try to parse a template template argument.
Douglas Gregoreaf75f42009-11-12 00:03:40 +0000983 {
984 TentativeParsingAction TPA(*this);
985
986 ParsedTemplateArgument TemplateTemplateArgument
987 = ParseTemplateTemplateArgument();
988 if (!TemplateTemplateArgument.isInvalid()) {
989 TPA.Commit();
990 return TemplateTemplateArgument;
991 }
992
993 // Revert this tentative parse to parse a non-type template argument.
994 TPA.Revert();
995 }
Douglas Gregor314b97f2009-11-10 19:49:08 +0000996
997 // Parse a non-type template argument.
998 SourceLocation Loc = Tok.getLocation();
John McCall60d7b3a2010-08-24 06:29:42 +0000999 ExprResult ExprArg = ParseConstantExpression();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001000 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001001 return ParsedTemplateArgument();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001002
Douglas Gregor314b97f2009-11-10 19:49:08 +00001003 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1004 ExprArg.release(), Loc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001005}
1006
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001007/// \brief Determine whether the current tokens can only be parsed as a
1008/// template argument list (starting with the '<') and never as a '<'
1009/// expression.
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001010bool Parser::IsTemplateArgumentList(unsigned Skip) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001011 struct AlwaysRevertAction : TentativeParsingAction {
1012 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1013 ~AlwaysRevertAction() { Revert(); }
1014 } Tentative(*this);
1015
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001016 while (Skip) {
1017 ConsumeToken();
1018 --Skip;
1019 }
1020
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001021 // '<'
1022 if (!Tok.is(tok::less))
1023 return false;
1024 ConsumeToken();
1025
1026 // An empty template argument list.
1027 if (Tok.is(tok::greater))
1028 return true;
1029
1030 // See whether we have declaration specifiers, which indicate a type.
1031 while (isCXXDeclarationSpecifier() == TPResult::True())
1032 ConsumeToken();
1033
1034 // If we have a '>' or a ',' then this is a template argument list.
1035 return Tok.is(tok::greater) || Tok.is(tok::comma);
1036}
1037
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001038/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1039/// (C++ [temp.names]). Returns true if there was an error.
1040///
1041/// template-argument-list: [C++ 14.2]
1042/// template-argument
1043/// template-argument-list ',' template-argument
Mike Stump1eb44332009-09-09 15:08:12 +00001044bool
Douglas Gregor314b97f2009-11-10 19:49:08 +00001045Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001046 while (true) {
Douglas Gregor314b97f2009-11-10 19:49:08 +00001047 ParsedTemplateArgument Arg = ParseTemplateArgument();
1048 if (Arg.isInvalid()) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001049 SkipUntil(tok::comma, tok::greater, true, true);
1050 return true;
1051 }
Douglas Gregor5908e9f2009-02-09 19:34:22 +00001052
Douglas Gregor314b97f2009-11-10 19:49:08 +00001053 // Save this template argument.
1054 TemplateArgs.push_back(Arg);
1055
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001056 // If the next token is a comma, consume it and keep reading
1057 // arguments.
1058 if (Tok.isNot(tok::comma)) break;
1059
1060 // Consume the comma.
1061 ConsumeToken();
1062 }
1063
Eli Friedman64a4eb22009-12-27 22:31:18 +00001064 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001065}
1066
Mike Stump1eb44332009-09-09 15:08:12 +00001067/// \brief Parse a C++ explicit template instantiation
Douglas Gregor1426e532009-05-12 21:31:51 +00001068/// (C++ [temp.explicit]).
1069///
1070/// explicit-instantiation:
Douglas Gregor45f96552009-09-04 06:33:52 +00001071/// 'extern' [opt] 'template' declaration
1072///
1073/// Note that the 'extern' is a GNU extension and C++0x feature.
John McCalld226f652010-08-21 09:40:31 +00001074Decl *Parser::ParseExplicitInstantiation(SourceLocation ExternLoc,
1075 SourceLocation TemplateLoc,
1076 SourceLocation &DeclEnd) {
John McCallc9068d72010-07-16 08:13:16 +00001077 // This isn't really required here.
1078 ParsingDeclRAIIObject ParsingTemplateParams(*this);
1079
Mike Stump1eb44332009-09-09 15:08:12 +00001080 return ParseSingleDeclarationAfterTemplate(Declarator::FileContext,
Douglas Gregor45f96552009-09-04 06:33:52 +00001081 ParsedTemplateInfo(ExternLoc,
1082 TemplateLoc),
John McCallc9068d72010-07-16 08:13:16 +00001083 ParsingTemplateParams,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00001084 DeclEnd, AS_none);
Douglas Gregor1426e532009-05-12 21:31:51 +00001085}
John McCall78b81052010-11-10 02:40:36 +00001086
1087SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1088 if (TemplateParams)
1089 return getTemplateParamsRange(TemplateParams->data(),
1090 TemplateParams->size());
1091
1092 SourceRange R(TemplateLoc);
1093 if (ExternLoc.isValid())
1094 R.setBegin(ExternLoc);
1095 return R;
1096}