blob: 91a9d723a6c82e2a3981fd80504ee53773cc1d47 [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"
Francois Pichet8387e2a2011-04-22 22:18:13 +000020#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/ASTConsumer.h"
Douglas Gregoradcac882008-12-01 23:54:00 +000022using namespace clang;
23
Douglas Gregor4d9a16f2009-05-12 23:25:50 +000024/// \brief Parse a template declaration, explicit instantiation, or
25/// explicit specialization.
John McCalld226f652010-08-21 09:40:31 +000026Decl *
Douglas Gregor4d9a16f2009-05-12 23:25:50 +000027Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
28 SourceLocation &DeclEnd,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +000029 AccessSpecifier AS,
30 AttributeList *AccessAttrs) {
Fariborz Jahanian9735c5e2011-08-22 17:59:19 +000031 ObjCDeclContextSwitch ObjCDC(*this);
32
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000033 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +000034 return ParseExplicitInstantiation(Context,
35 SourceLocation(), ConsumeToken(),
36 DeclEnd, AS);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000037 }
Erik Verbruggen5f1c8222011-10-13 09:41:32 +000038 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
39 AccessAttrs);
Douglas Gregor4d9a16f2009-05-12 23:25:50 +000040}
41
Douglas Gregorc3058332009-08-24 23:03:25 +000042/// \brief RAII class that manages the template parameter depth.
43namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000044 class TemplateParameterDepthCounter {
Douglas Gregorc3058332009-08-24 23:03:25 +000045 unsigned &Depth;
46 unsigned AddedLevels;
47
48 public:
Mike Stump1eb44332009-09-09 15:08:12 +000049 explicit TemplateParameterDepthCounter(unsigned &Depth)
Douglas Gregorc3058332009-08-24 23:03:25 +000050 : Depth(Depth), AddedLevels(0) { }
Mike Stump1eb44332009-09-09 15:08:12 +000051
Douglas Gregorc3058332009-08-24 23:03:25 +000052 ~TemplateParameterDepthCounter() {
53 Depth -= AddedLevels;
54 }
Mike Stump1eb44332009-09-09 15:08:12 +000055
56 void operator++() {
Douglas Gregorc3058332009-08-24 23:03:25 +000057 ++Depth;
58 ++AddedLevels;
59 }
Mike Stump1eb44332009-09-09 15:08:12 +000060
Douglas Gregorc3058332009-08-24 23:03:25 +000061 operator unsigned() const { return Depth; }
62 };
63}
64
Douglas Gregorcc636682009-02-17 23:15:12 +000065/// \brief Parse a template declaration or an explicit specialization.
66///
67/// Template declarations include one or more template parameter lists
68/// and either the function or class template declaration. Explicit
69/// specializations contain one or more 'template < >' prefixes
70/// followed by a (possibly templated) declaration. Since the
71/// syntactic form of both features is nearly identical, we parse all
72/// of the template headers together and let semantic analysis sort
73/// the declarations from the explicit specializations.
Douglas Gregoradcac882008-12-01 23:54:00 +000074///
75/// template-declaration: [C++ temp]
76/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
Douglas Gregorcc636682009-02-17 23:15:12 +000077///
78/// explicit-specialization: [ C++ temp.expl.spec]
79/// 'template' '<' '>' declaration
John McCalld226f652010-08-21 09:40:31 +000080Decl *
Anders Carlsson5aeccdb2009-03-26 00:52:18 +000081Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
Chris Lattner97144fc2009-04-02 04:16:50 +000082 SourceLocation &DeclEnd,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +000083 AccessSpecifier AS,
84 AttributeList *AccessAttrs) {
Mike Stump1eb44332009-09-09 15:08:12 +000085 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
86 "Token does not start a template declaration.");
87
Douglas Gregor26236e82008-12-02 00:41:28 +000088 // Enter template-parameter scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +000089 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Douglas Gregor26236e82008-12-02 00:41:28 +000090
John McCallc9068d72010-07-16 08:13:16 +000091 // Tell the action that names should be checked in the context of
92 // the declaration to come.
93 ParsingDeclRAIIObject ParsingTemplateParams(*this);
94
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +000095 // Parse multiple levels of template headers within this template
96 // parameter scope, e.g.,
97 //
98 // template<typename T>
99 // template<typename U>
100 // class A<T>::B { ... };
101 //
102 // We parse multiple levels non-recursively so that we can build a
103 // single data structure containing all of the template parameter
Douglas Gregorcc636682009-02-17 23:15:12 +0000104 // lists to easily differentiate between the case above and:
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000105 //
106 // template<typename T>
107 // class A {
108 // template<typename U> class B;
109 // };
110 //
111 // In the first case, the action for declaring A<T>::B receives
112 // both template parameter lists. In the second case, the action for
113 // defining A<T>::B receives just the inner template parameter list
114 // (and retrieves the outer template parameter list from its
115 // context).
Douglas Gregor0f499d92009-08-20 18:46:05 +0000116 bool isSpecialization = true;
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000117 bool LastParamListWasEmpty = false;
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000118 TemplateParameterLists ParamLists;
Douglas Gregorc3058332009-08-24 23:03:25 +0000119 TemplateParameterDepthCounter Depth(TemplateParameterDepth);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000120 do {
121 // Consume the 'export', if any.
122 SourceLocation ExportLoc;
123 if (Tok.is(tok::kw_export)) {
124 ExportLoc = ConsumeToken();
125 }
126
127 // Consume the 'template', which should be here.
128 SourceLocation TemplateLoc;
129 if (Tok.is(tok::kw_template)) {
130 TemplateLoc = ConsumeToken();
131 } else {
132 Diag(Tok.getLocation(), diag::err_expected_template);
John McCalld226f652010-08-21 09:40:31 +0000133 return 0;
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000134 }
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000136 // Parse the '<' template-parameter-list '>'
137 SourceLocation LAngleLoc, RAngleLoc;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000138 SmallVector<Decl*, 4> TemplateParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000139 if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000140 RAngleLoc)) {
141 // Skip until the semi-colon or a }.
142 SkipUntil(tok::r_brace, true, true);
143 if (Tok.is(tok::semi))
144 ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000145 return 0;
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000146 }
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000147
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000148 ParamLists.push_back(
Mike Stump1eb44332009-09-09 15:08:12 +0000149 Actions.ActOnTemplateParameterList(Depth, ExportLoc,
150 TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +0000151 TemplateParams.data(),
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000152 TemplateParams.size(), RAngleLoc));
Douglas Gregorc3058332009-08-24 23:03:25 +0000153
154 if (!TemplateParams.empty()) {
155 isSpecialization = false;
156 ++Depth;
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000157 } else {
158 LastParamListWasEmpty = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000159 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000160 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
161
162 // Parse the actual template declaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000163 return ParseSingleDeclarationAfterTemplate(Context,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000164 ParsedTemplateInfo(&ParamLists,
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000165 isSpecialization,
166 LastParamListWasEmpty),
John McCallc9068d72010-07-16 08:13:16 +0000167 ParsingTemplateParams,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +0000168 DeclEnd, AS, AccessAttrs);
Douglas Gregor1426e532009-05-12 21:31:51 +0000169}
Chris Lattner682bf922009-03-29 16:50:03 +0000170
Douglas Gregor1426e532009-05-12 21:31:51 +0000171/// \brief Parse a single declaration that declares a template,
172/// template specialization, or explicit instantiation of a template.
173///
174/// \param TemplateParams if non-NULL, the template parameter lists
175/// that preceded this declaration. In this case, the declaration is a
176/// template declaration, out-of-line definition of a template, or an
177/// explicit template specialization. When NULL, the declaration is an
178/// explicit template instantiation.
179///
180/// \param TemplateLoc when TemplateParams is NULL, the location of
181/// the 'template' keyword that indicates that we have an explicit
182/// template instantiation.
183///
184/// \param DeclEnd will receive the source location of the last token
185/// within this declaration.
186///
187/// \param AS the access specifier associated with this
188/// declaration. Will be AS_none for namespace-scope declarations.
189///
190/// \returns the new declaration.
John McCalld226f652010-08-21 09:40:31 +0000191Decl *
Douglas Gregor1426e532009-05-12 21:31:51 +0000192Parser::ParseSingleDeclarationAfterTemplate(
193 unsigned Context,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000194 const ParsedTemplateInfo &TemplateInfo,
John McCallc9068d72010-07-16 08:13:16 +0000195 ParsingDeclRAIIObject &DiagsFromTParams,
Douglas Gregor1426e532009-05-12 21:31:51 +0000196 SourceLocation &DeclEnd,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +0000197 AccessSpecifier AS,
198 AttributeList *AccessAttrs) {
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000199 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
200 "Template information required");
201
Douglas Gregor37b372b2009-08-20 22:52:58 +0000202 if (Context == Declarator::MemberContext) {
203 // We are parsing a member template.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +0000204 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
205 &DiagsFromTParams);
John McCalld226f652010-08-21 09:40:31 +0000206 return 0;
Douglas Gregor37b372b2009-08-20 22:52:58 +0000207 }
Mike Stump1eb44332009-09-09 15:08:12 +0000208
John McCall0b7e6782011-03-24 11:26:52 +0000209 ParsedAttributesWithRange prefixAttrs(AttrFactory);
John McCall7f040a92010-12-24 02:08:15 +0000210 MaybeParseCXX0XAttributes(prefixAttrs);
John McCall78b81052010-11-10 02:40:36 +0000211
212 if (Tok.is(tok::kw_using))
213 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
John McCall7f040a92010-12-24 02:08:15 +0000214 prefixAttrs);
John McCall78b81052010-11-10 02:40:36 +0000215
John McCallc9068d72010-07-16 08:13:16 +0000216 // Parse the declaration specifiers, stealing the accumulated
217 // diagnostics from the template parameters.
John McCall0b7e6782011-03-24 11:26:52 +0000218 ParsingDeclSpec DS(*this, &DiagsFromTParams);
Sean Huntbbd37c62009-11-21 08:43:09 +0000219
John McCall7f040a92010-12-24 02:08:15 +0000220 DS.takeAttributesFrom(prefixAttrs);
Sean Huntbbd37c62009-11-21 08:43:09 +0000221
Douglas Gregor0efc2c12010-01-13 17:31:36 +0000222 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
223 getDeclSpecContextFromDeclaratorContext(Context));
Douglas Gregor1426e532009-05-12 21:31:51 +0000224
225 if (Tok.is(tok::semi)) {
226 DeclEnd = ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000227 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
John McCall54abf7d2009-11-04 02:18:39 +0000228 DS.complete(Decl);
229 return Decl;
Douglas Gregor1426e532009-05-12 21:31:51 +0000230 }
231
232 // Parse the declarator.
John McCall54abf7d2009-11-04 02:18:39 +0000233 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
Douglas Gregor1426e532009-05-12 21:31:51 +0000234 ParseDeclarator(DeclaratorInfo);
235 // Error parsing the declarator?
236 if (!DeclaratorInfo.hasName()) {
237 // If so, skip until the semi-colon or a }.
238 SkipUntil(tok::r_brace, true, true);
239 if (Tok.is(tok::semi))
240 ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000241 return 0;
Douglas Gregor1426e532009-05-12 21:31:51 +0000242 }
Mike Stump1eb44332009-09-09 15:08:12 +0000243
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000244 LateParsedAttrList LateParsedAttrs;
245 if (DeclaratorInfo.isFunctionDeclarator())
246 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
247
Douglas Gregor1426e532009-05-12 21:31:51 +0000248 // If we have a declaration or declarator list, handle it.
249 if (isDeclarationAfterDeclarator()) {
250 // Parse this declaration.
John McCalld226f652010-08-21 09:40:31 +0000251 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
252 TemplateInfo);
Douglas Gregor1426e532009-05-12 21:31:51 +0000253
254 if (Tok.is(tok::comma)) {
255 Diag(Tok, diag::err_multiple_template_declarators)
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000256 << (int)TemplateInfo.Kind;
Douglas Gregor1426e532009-05-12 21:31:51 +0000257 SkipUntil(tok::semi, true, false);
258 return ThisDecl;
259 }
260
261 // Eat the semi colon after the declaration.
John McCall5c15fe12009-07-31 02:20:35 +0000262 ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000263 if (LateParsedAttrs.size() > 0)
264 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
John McCalleee1d542011-02-14 07:13:47 +0000265 DeclaratorInfo.complete(ThisDecl);
Douglas Gregor1426e532009-05-12 21:31:51 +0000266 return ThisDecl;
267 }
268
269 if (DeclaratorInfo.isFunctionDeclarator() &&
Chris Lattner004659a2010-07-11 22:42:07 +0000270 isStartOfFunctionDefinition(DeclaratorInfo)) {
Douglas Gregor1426e532009-05-12 21:31:51 +0000271 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Smith6e1fd332011-11-29 09:09:06 +0000272 // Recover by ignoring the 'typedef'. This was probably supposed to be
273 // the 'typename' keyword, which we should have already suggested adding
274 // if it's appropriate.
275 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
276 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith874d2532011-11-29 05:27:40 +0000277 DS.ClearStorageClassSpecs();
Douglas Gregor1426e532009-05-12 21:31:51 +0000278 }
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000279 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
280 &LateParsedAttrs);
Douglas Gregor1426e532009-05-12 21:31:51 +0000281 }
282
283 if (DeclaratorInfo.isFunctionDeclarator())
284 Diag(Tok, diag::err_expected_fn_body);
285 else
286 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
287 SkipUntil(tok::semi);
John McCalld226f652010-08-21 09:40:31 +0000288 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000289}
290
291/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000292/// angle brackets. Depth is the depth of this template-parameter-list, which
293/// is the number of template headers directly enclosing this template header.
294/// TemplateParams is the current list of template parameters we're building.
295/// The template parameter we parse will be added to this list. LAngleLoc and
Mike Stump1eb44332009-09-09 15:08:12 +0000296/// RAngleLoc will receive the positions of the '<' and '>', respectively,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000297/// that enclose this template parameter list.
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000298///
299/// \returns true if an error occurred, false otherwise.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000300bool Parser::ParseTemplateParameters(unsigned Depth,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000301 SmallVectorImpl<Decl*> &TemplateParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000302 SourceLocation &LAngleLoc,
303 SourceLocation &RAngleLoc) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000304 // Get the template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +0000305 if (!Tok.is(tok::less)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000306 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000307 return true;
Douglas Gregoradcac882008-12-01 23:54:00 +0000308 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000309 LAngleLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Douglas Gregoradcac882008-12-01 23:54:00 +0000311 // Try to parse the template parameter list.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000312 if (Tok.is(tok::greater))
313 RAngleLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000314 else if (ParseTemplateParameterList(Depth, TemplateParams)) {
315 if (!Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000316 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000317 return true;
Douglas Gregoradcac882008-12-01 23:54:00 +0000318 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000319 RAngleLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000320 }
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000321 return false;
Douglas Gregoradcac882008-12-01 23:54:00 +0000322}
323
324/// ParseTemplateParameterList - Parse a template parameter list. If
325/// the parsing fails badly (i.e., closing bracket was left out), this
326/// will try to put the token stream in a reasonable position (closing
Mike Stump1eb44332009-09-09 15:08:12 +0000327/// a statement, etc.) and return false.
Douglas Gregoradcac882008-12-01 23:54:00 +0000328///
329/// template-parameter-list: [C++ temp]
330/// template-parameter
331/// template-parameter-list ',' template-parameter
Mike Stump1eb44332009-09-09 15:08:12 +0000332bool
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000333Parser::ParseTemplateParameterList(unsigned Depth,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000334 SmallVectorImpl<Decl*> &TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000335 while (1) {
John McCalld226f652010-08-21 09:40:31 +0000336 if (Decl *TmpParam
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000337 = ParseTemplateParameter(Depth, TemplateParams.size())) {
338 TemplateParams.push_back(TmpParam);
339 } else {
Douglas Gregoradcac882008-12-01 23:54:00 +0000340 // If we failed to parse a template parameter, skip until we find
341 // a comma or closing brace.
342 SkipUntil(tok::comma, tok::greater, true, true);
343 }
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Douglas Gregoradcac882008-12-01 23:54:00 +0000345 // Did we find a comma or the end of the template parmeter list?
Mike Stump1eb44332009-09-09 15:08:12 +0000346 if (Tok.is(tok::comma)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000347 ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000348 } else if (Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000349 // Don't consume this... that's done by template parser.
350 break;
351 } else {
352 // Somebody probably forgot to close the template. Skip ahead and
353 // try to get out of the expression. This error is currently
354 // subsumed by whatever goes on in ParseTemplateParameter.
355 // TODO: This could match >>, and it would be nice to avoid those
356 // silly errors with template <vec<T>>.
Douglas Gregor99ea7342010-10-15 01:15:58 +0000357 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Douglas Gregoradcac882008-12-01 23:54:00 +0000358 SkipUntil(tok::greater, true, true);
359 return false;
360 }
361 }
362 return true;
363}
364
Douglas Gregor98440b42009-11-21 02:07:55 +0000365/// \brief Determine whether the parser is at the start of a template
366/// type parameter.
367bool Parser::isStartOfTemplateTypeParameter() {
Douglas Gregor7b6d25b2010-06-04 07:30:15 +0000368 if (Tok.is(tok::kw_class)) {
369 // "class" may be the start of an elaborated-type-specifier or a
370 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
371 switch (NextToken().getKind()) {
372 case tok::equal:
373 case tok::comma:
374 case tok::greater:
375 case tok::greatergreater:
376 case tok::ellipsis:
377 return true;
378
379 case tok::identifier:
380 // This may be either a type-parameter or an elaborated-type-specifier.
381 // We have to look further.
382 break;
383
384 default:
385 return false;
386 }
387
388 switch (GetLookAheadToken(2).getKind()) {
389 case tok::equal:
390 case tok::comma:
391 case tok::greater:
392 case tok::greatergreater:
393 return true;
394
395 default:
396 return false;
397 }
398 }
Douglas Gregor98440b42009-11-21 02:07:55 +0000399
400 if (Tok.isNot(tok::kw_typename))
401 return false;
402
403 // C++ [temp.param]p2:
404 // There is no semantic difference between class and typename in a
405 // template-parameter. typename followed by an unqualified-id
406 // names a template type parameter. typename followed by a
407 // qualified-id denotes the type in a non-type
408 // parameter-declaration.
409 Token Next = NextToken();
410
411 // If we have an identifier, skip over it.
412 if (Next.getKind() == tok::identifier)
413 Next = GetLookAheadToken(2);
414
415 switch (Next.getKind()) {
416 case tok::equal:
417 case tok::comma:
418 case tok::greater:
419 case tok::greatergreater:
420 case tok::ellipsis:
421 return true;
422
423 default:
424 return false;
425 }
426}
427
Douglas Gregoradcac882008-12-01 23:54:00 +0000428/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
429///
430/// template-parameter: [C++ temp.param]
431/// type-parameter
432/// parameter-declaration
433///
434/// type-parameter: (see below)
Douglas Gregor61c4d282011-01-05 15:48:55 +0000435/// 'class' ...[opt] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000436/// 'class' identifier[opt] '=' type-id
Douglas Gregor61c4d282011-01-05 15:48:55 +0000437/// 'typename' ...[opt] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000438/// 'typename' identifier[opt] '=' type-id
Douglas Gregor61c4d282011-01-05 15:48:55 +0000439/// 'template' '<' template-parameter-list '>'
440/// 'class' ...[opt] identifier[opt]
441/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
442/// = id-expression
John McCalld226f652010-08-21 09:40:31 +0000443Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor98440b42009-11-21 02:07:55 +0000444 if (isStartOfTemplateTypeParameter())
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000445 return ParseTypeParameter(Depth, Position);
Mike Stump1eb44332009-09-09 15:08:12 +0000446
447 if (Tok.is(tok::kw_template))
Chris Lattner532e19b2009-01-04 23:51:17 +0000448 return ParseTemplateTemplateParameter(Depth, Position);
449
450 // If it's none of the above, then it must be a parameter declaration.
451 // NOTE: This will pick up errors in the closure of the template parameter
452 // list (e.g., template < ; Check here to implement >> style closures.
453 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000454}
455
456/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
457/// Other kinds of template parameters are parsed in
458/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
459///
460/// type-parameter: [C++ temp.param]
Anders Carlssonce5635a2009-06-12 23:09:56 +0000461/// 'class' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000462/// 'class' identifier[opt] '=' type-id
Anders Carlssonce5635a2009-06-12 23:09:56 +0000463/// 'typename' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000464/// 'typename' identifier[opt] '=' type-id
John McCalld226f652010-08-21 09:40:31 +0000465Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000466 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
Mike Stump1eb44332009-09-09 15:08:12 +0000467 "A type-parameter starts with 'class' or 'typename'");
Douglas Gregor26236e82008-12-02 00:41:28 +0000468
469 // Consume the 'class' or 'typename' keyword.
470 bool TypenameKeyword = Tok.is(tok::kw_typename);
471 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000472
Anders Carlsson941df7d2009-06-12 19:58:00 +0000473 // Grab the ellipsis (if given).
474 bool Ellipsis = false;
475 SourceLocation EllipsisLoc;
Anders Carlssonce5635a2009-06-12 23:09:56 +0000476 if (Tok.is(tok::ellipsis)) {
Anders Carlsson941df7d2009-06-12 19:58:00 +0000477 Ellipsis = true;
478 EllipsisLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Richard Smithe5acd132011-10-14 20:31:37 +0000480 Diag(EllipsisLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +0000481 getLangOpts().CPlusPlus0x
Richard Smithe5acd132011-10-14 20:31:37 +0000482 ? diag::warn_cxx98_compat_variadic_templates
483 : diag::ext_variadic_templates);
Anders Carlsson941df7d2009-06-12 19:58:00 +0000484 }
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Douglas Gregoradcac882008-12-01 23:54:00 +0000486 // Grab the template parameter name (if given)
Douglas Gregor26236e82008-12-02 00:41:28 +0000487 SourceLocation NameLoc;
488 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000489 if (Tok.is(tok::identifier)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000490 ParamName = Tok.getIdentifierInfo();
491 NameLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000492 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
493 Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000494 // Unnamed template parameter. Don't have to do anything here, just
495 // don't consume this token.
496 } else {
497 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000498 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000499 }
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000501 // Grab a default argument (if available).
502 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
503 // we introduce the type parameter into the local scope.
504 SourceLocation EqualLoc;
John McCallb3d87482010-08-24 05:47:05 +0000505 ParsedType DefaultArg;
Mike Stump1eb44332009-09-09 15:08:12 +0000506 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000507 EqualLoc = ConsumeToken();
Richard Smithd37b3602012-02-10 11:05:11 +0000508 DefaultArg = ParseTypeName(/*Range=*/0,
509 Declarator::TemplateTypeArgContext).get();
Douglas Gregoradcac882008-12-01 23:54:00 +0000510 }
Richard Smithd37b3602012-02-10 11:05:11 +0000511
Douglas Gregor23c94db2010-07-02 17:43:08 +0000512 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000513 EllipsisLoc, KeyLoc, ParamName, NameLoc,
514 Depth, Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000515}
516
517/// ParseTemplateTemplateParameter - Handle the parsing of template
Mike Stump1eb44332009-09-09 15:08:12 +0000518/// template parameters.
Douglas Gregoradcac882008-12-01 23:54:00 +0000519///
520/// type-parameter: [C++ temp.param]
Douglas Gregor61c4d282011-01-05 15:48:55 +0000521/// 'template' '<' template-parameter-list '>' 'class'
522/// ...[opt] identifier[opt]
523/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
524/// = id-expression
John McCalld226f652010-08-21 09:40:31 +0000525Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000526Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000527 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
528
529 // Handle the template <...> part.
530 SourceLocation TemplateLoc = ConsumeToken();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000531 SmallVector<Decl*,8> TemplateParams;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000532 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor68c69932009-02-10 19:52:54 +0000533 {
534 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000535 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000536 RAngleLoc)) {
John McCalld226f652010-08-21 09:40:31 +0000537 return 0;
Douglas Gregor68c69932009-02-10 19:52:54 +0000538 }
Douglas Gregoradcac882008-12-01 23:54:00 +0000539 }
540
541 // Generate a meaningful error if the user forgot to put class before the
542 // identifier, comma, or greater.
David Blaikie460ef132012-04-02 19:15:28 +0000543 if (Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct)) {
David Blaikiea8235452012-04-05 16:56:02 +0000544 Diag(Tok.getLocation(), diag::err_expected_class_on_template_template_param)
David Blaikie460ef132012-04-02 19:15:28 +0000545 << FixItHint::CreateReplacement(Tok.getLocation(), "class");
546 ConsumeToken();
547 } else if (!Tok.is(tok::kw_class))
David Blaikiea8235452012-04-05 16:56:02 +0000548 Diag(Tok.getLocation(), diag::err_expected_class_on_template_template_param)
549 << FixItHint::CreateInsertion(Tok.getLocation(), "class ");
David Blaikie460ef132012-04-02 19:15:28 +0000550 else
551 ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000552
Douglas Gregor61c4d282011-01-05 15:48:55 +0000553 // Parse the ellipsis, if given.
554 SourceLocation EllipsisLoc;
555 if (Tok.is(tok::ellipsis)) {
556 EllipsisLoc = ConsumeToken();
557
Richard Smithe5acd132011-10-14 20:31:37 +0000558 Diag(EllipsisLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +0000559 getLangOpts().CPlusPlus0x
Richard Smithe5acd132011-10-14 20:31:37 +0000560 ? diag::warn_cxx98_compat_variadic_templates
561 : diag::ext_variadic_templates);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000562 }
563
Douglas Gregoradcac882008-12-01 23:54:00 +0000564 // Get the identifier, if given.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000565 SourceLocation NameLoc;
566 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000567 if (Tok.is(tok::identifier)) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000568 ParamName = Tok.getIdentifierInfo();
569 NameLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000570 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000571 // Unnamed template parameter. Don't have to do anything here, just
572 // don't consume this token.
573 } else {
574 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000575 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000576 }
577
Richard Trieu90ab75b2011-09-09 03:18:59 +0000578 TemplateParameterList *ParamList =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000579 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
580 TemplateLoc, LAngleLoc,
Douglas Gregor369ea272010-10-21 17:26:49 +0000581 TemplateParams.data(),
Douglas Gregorddc29e12009-02-06 22:42:48 +0000582 TemplateParams.size(),
583 RAngleLoc);
584
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000585 // Grab a default argument (if available).
586 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
587 // we introduce the template parameter into the local scope.
588 SourceLocation EqualLoc;
589 ParsedTemplateArgument DefaultArg;
Douglas Gregord684b002009-02-10 19:49:53 +0000590 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000591 EqualLoc = ConsumeToken();
592 DefaultArg = ParseTemplateTemplateArgument();
593 if (DefaultArg.isInvalid()) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000594 Diag(Tok.getLocation(),
595 diag::err_default_template_template_parameter_not_template);
Nuno Lopes68f7a242009-12-10 00:07:02 +0000596 static const tok::TokenKind EndToks[] = {
Douglas Gregor788cd062009-11-11 01:00:40 +0000597 tok::comma, tok::greater, tok::greatergreater
598 };
599 SkipUntil(EndToks, 3, true, true);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000600 }
Douglas Gregord684b002009-02-10 19:49:53 +0000601 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000602
Douglas Gregor23c94db2010-07-02 17:43:08 +0000603 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000604 ParamList, EllipsisLoc,
605 ParamName, NameLoc, Depth,
606 Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000607}
608
609/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
Mike Stump1eb44332009-09-09 15:08:12 +0000610/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000611///
Douglas Gregoradcac882008-12-01 23:54:00 +0000612/// template-parameter:
613/// ...
614/// parameter-declaration
John McCalld226f652010-08-21 09:40:31 +0000615Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000616Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000617 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor26236e82008-12-02 00:41:28 +0000618 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregoradcac882008-12-01 23:54:00 +0000619 // declarators (parts of declarators?) are accepted for parameters.
John McCall0b7e6782011-03-24 11:26:52 +0000620 DeclSpec DS(AttrFactory);
Douglas Gregor26236e82008-12-02 00:41:28 +0000621 ParseDeclarationSpecifiers(DS);
Douglas Gregoradcac882008-12-01 23:54:00 +0000622
623 // Parse this as a typename.
Douglas Gregor26236e82008-12-02 00:41:28 +0000624 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
625 ParseDeclarator(ParamDecl);
John McCallb3d87482010-08-24 05:47:05 +0000626 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000627 // This probably shouldn't happen - and it's more of a Sema thing, but
628 // basically we didn't parse the type name because we couldn't associate
629 // it with an AST node. we should just skip to the comma or greater.
630 // TODO: This is currently a placeholder for some kind of Sema Error.
631 Diag(Tok.getLocation(), diag::err_parse_error);
632 SkipUntil(tok::comma, tok::greater, true, true);
John McCalld226f652010-08-21 09:40:31 +0000633 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000634 }
635
Douglas Gregord684b002009-02-10 19:49:53 +0000636 // If there is a default value, parse it.
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000637 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
638 // we introduce the template parameter into the local scope.
639 SourceLocation EqualLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000640 ExprResult DefaultArg;
Chris Lattner7452c6f2009-01-05 01:24:05 +0000641 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000642 EqualLoc = ConsumeToken();
Douglas Gregord684b002009-02-10 19:49:53 +0000643
644 // C++ [temp.param]p15:
645 // When parsing a default template-argument for a non-type
646 // template-parameter, the first non-nested > is taken as the
647 // end of the template-parameter-list rather than a greater-than
648 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +0000649 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000650
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000651 DefaultArg = ParseAssignmentExpression();
Douglas Gregord684b002009-02-10 19:49:53 +0000652 if (DefaultArg.isInvalid())
653 SkipUntil(tok::comma, tok::greater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000654 }
Mike Stump1eb44332009-09-09 15:08:12 +0000655
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000656 // Create the parameter.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000657 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000658 Depth, Position, EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000659 DefaultArg.take());
Douglas Gregoradcac882008-12-01 23:54:00 +0000660}
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000661
Douglas Gregorcc636682009-02-17 23:15:12 +0000662/// \brief Parses a template-id that after the template name has
663/// already been parsed.
664///
665/// This routine takes care of parsing the enclosed template argument
666/// list ('<' template-parameter-list [opt] '>') and placing the
667/// results into a form that can be transferred to semantic analysis.
668///
669/// \param Template the template declaration produced by isTemplateName
670///
671/// \param TemplateNameLoc the source location of the template name
672///
673/// \param SS if non-NULL, the nested-name-specifier preceding the
674/// template name.
675///
676/// \param ConsumeLastToken if true, then we will consume the last
677/// token that forms the template-id. Otherwise, we will leave the
678/// last token in the stream (e.g., so that it can be replaced with an
679/// annotation token).
Mike Stump1eb44332009-09-09 15:08:12 +0000680bool
Douglas Gregor7532dc62009-03-30 22:58:21 +0000681Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
Mike Stump1eb44332009-09-09 15:08:12 +0000682 SourceLocation TemplateNameLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +0000683 const CXXScopeSpec &SS,
Douglas Gregorcc636682009-02-17 23:15:12 +0000684 bool ConsumeLastToken,
685 SourceLocation &LAngleLoc,
686 TemplateArgList &TemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +0000687 SourceLocation &RAngleLoc) {
688 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
689
690 // Consume the '<'.
691 LAngleLoc = ConsumeToken();
692
693 // Parse the optional template-argument-list.
694 bool Invalid = false;
695 {
696 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Douglas Gregor4f3018e2011-01-11 00:45:18 +0000697 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
Douglas Gregor314b97f2009-11-10 19:49:08 +0000698 Invalid = ParseTemplateArgumentList(TemplateArgs);
Douglas Gregorcc636682009-02-17 23:15:12 +0000699
700 if (Invalid) {
701 // Try to find the closing '>'.
702 SkipUntil(tok::greater, true, !ConsumeLastToken);
703
704 return true;
705 }
706 }
707
Eli Friedman64a4eb22009-12-27 22:31:18 +0000708 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) {
709 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregorcc636682009-02-17 23:15:12 +0000710 return true;
Eli Friedman64a4eb22009-12-27 22:31:18 +0000711 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000712
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000713 // Determine the location of the '>' or '>>'. Only consume this
714 // token if the caller asked us to.
Douglas Gregorcc636682009-02-17 23:15:12 +0000715 RAngleLoc = Tok.getLocation();
716
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000717 if (Tok.is(tok::greatergreater)) {
Richard Smith7fe62082011-10-15 05:09:34 +0000718 const char *ReplaceStr = "> >";
719 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
720 ReplaceStr = "> > ";
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000721
David Blaikie4e4d0842012-03-11 07:00:24 +0000722 Diag(Tok.getLocation(), getLangOpts().CPlusPlus0x ?
Richard Smith7fe62082011-10-15 05:09:34 +0000723 diag::warn_cxx98_compat_two_right_angle_brackets :
724 diag::err_two_right_angle_brackets_need_space)
725 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()),
726 ReplaceStr);
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000727
728 Tok.setKind(tok::greater);
729 if (!ConsumeLastToken) {
730 // Since we're not supposed to consume the '>>' token, we need
731 // to insert a second '>' token after the first.
732 PP.EnterToken(Tok);
733 }
734 } else if (ConsumeLastToken)
Douglas Gregorcc636682009-02-17 23:15:12 +0000735 ConsumeToken();
736
737 return false;
738}
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Douglas Gregor39a8de12009-02-25 19:37:18 +0000740/// \brief Replace the tokens that form a simple-template-id with an
741/// annotation token containing the complete template-id.
742///
743/// The first token in the stream must be the name of a template that
744/// is followed by a '<'. This routine will parse the complete
745/// simple-template-id and replace the tokens with a single annotation
746/// token with one of two different kinds: if the template-id names a
747/// type (and \p AllowTypeAnnotation is true), the annotation token is
748/// a type annotation that includes the optional nested-name-specifier
749/// (\p SS). Otherwise, the annotation token is a template-id
750/// annotation that does not include the optional
751/// nested-name-specifier.
752///
753/// \param Template the declaration of the template named by the first
754/// token (an identifier), as returned from \c Action::isTemplateName().
755///
756/// \param TemplateNameKind the kind of template that \p Template
757/// refers to, as returned from \c Action::isTemplateName().
758///
759/// \param SS if non-NULL, the nested-name-specifier that precedes
760/// this template name.
761///
762/// \param TemplateKWLoc if valid, specifies that this template-id
763/// annotation was preceded by the 'template' keyword and gives the
764/// location of that keyword. If invalid (the default), then this
765/// template-id was not preceded by a 'template' keyword.
766///
767/// \param AllowTypeAnnotation if true (the default), then a
768/// simple-template-id that refers to a class template, template
769/// template parameter, or other template that produces a type will be
770/// replaced with a type annotation token. Otherwise, the
771/// simple-template-id is always replaced with a template-id
772/// annotation token.
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000773///
774/// If an unrecoverable parse error occurs and no annotation token can be
775/// formed, this function returns true.
776///
777bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Douglas Gregor059101f2011-03-02 00:47:37 +0000778 CXXScopeSpec &SS,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000779 SourceLocation TemplateKWLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000780 UnqualifiedId &TemplateName,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000781 bool AllowTypeAnnotation) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000782 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000783 assert(Template && Tok.is(tok::less) &&
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000784 "Parser isn't at the beginning of a template-id");
785
786 // Consume the template-name.
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000787 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000788
Douglas Gregorcc636682009-02-17 23:15:12 +0000789 // Parse the enclosed template argument list.
790 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000791 TemplateArgList TemplateArgs;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000792 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
793 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000794 SS, false, LAngleLoc,
795 TemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +0000796 RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000798 if (Invalid) {
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 Gregorc15cb382009-02-09 23:23:08 +0000805
Jay Foadbeaaccd2009-05-21 09:52:38 +0000806 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
Douglas Gregorcc636682009-02-17 23:15:12 +0000807 TemplateArgs.size());
Douglas Gregorf02da892009-02-09 21:04:56 +0000808
Douglas Gregor55f6b142009-02-09 18:46:07 +0000809 // Build the annotation token.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000810 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
John McCallf312b1e2010-08-26 23:41:50 +0000811 TypeResult Type
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000812 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +0000813 Template, TemplateNameLoc,
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000814 LAngleLoc, TemplateArgsPtr, RAngleLoc);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000815 if (Type.isInvalid()) {
816 // If we failed to parse the template ID but skipped ahead to a >, we're not
817 // going to be able to form a token annotation. Eat the '>' if present.
818 if (Tok.is(tok::greater))
819 ConsumeToken();
820 return true;
821 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000822
823 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000824 setTypeAnnotation(Tok, Type.get());
Douglas Gregor059101f2011-03-02 00:47:37 +0000825 if (SS.isNotEmpty())
826 Tok.setLocation(SS.getBeginLoc());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000827 else if (TemplateKWLoc.isValid())
828 Tok.setLocation(TemplateKWLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000829 else
Douglas Gregor39a8de12009-02-25 19:37:18 +0000830 Tok.setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +0000831 } else {
Douglas Gregorc45c2322009-03-31 00:43:58 +0000832 // Build a template-id annotation token that can be processed
833 // later.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000834 Tok.setKind(tok::annot_template_id);
Mike Stump1eb44332009-09-09 15:08:12 +0000835 TemplateIdAnnotation *TemplateId
Douglas Gregor39a8de12009-02-25 19:37:18 +0000836 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
Douglas Gregor55f6b142009-02-09 18:46:07 +0000837 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000838 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
839 TemplateId->Name = TemplateName.Identifier;
840 TemplateId->Operator = OO_None;
841 } else {
842 TemplateId->Name = 0;
843 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
844 }
Douglas Gregor059101f2011-03-02 00:47:37 +0000845 TemplateId->SS = SS;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000846 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall2b5289b2010-08-23 07:28:44 +0000847 TemplateId->Template = Template;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000848 TemplateId->Kind = TNK;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000849 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000850 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregor314b97f2009-11-10 19:49:08 +0000851 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
852 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
Douglas Gregorc34348a2011-02-24 17:54:50 +0000853 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000854 Tok.setAnnotationValue(TemplateId);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000855 if (TemplateKWLoc.isValid())
856 Tok.setLocation(TemplateKWLoc);
857 else
858 Tok.setLocation(TemplateNameLoc);
859
860 TemplateArgsPtr.release();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000861 }
862
863 // Common fields for the annotation token
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000864 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000865
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000866 // In case the tokens were cached, have Preprocessor replace them with the
867 // annotation token.
868 PP.AnnotateCachedTokens(Tok);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000869 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000870}
871
Douglas Gregor39a8de12009-02-25 19:37:18 +0000872/// \brief Replaces a template-id annotation token with a type
873/// annotation token.
874///
Douglas Gregor31a19b62009-04-01 21:51:26 +0000875/// If there was a failure when forming the type from the template-id,
876/// a type annotation token will still be created, but will have a
877/// NULL type pointer to signify an error.
Douglas Gregor059101f2011-03-02 00:47:37 +0000878void Parser::AnnotateTemplateIdTokenAsType() {
Douglas Gregor39a8de12009-02-25 19:37:18 +0000879 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
880
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +0000881 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000882 assert((TemplateId->Kind == TNK_Type_template ||
883 TemplateId->Kind == TNK_Dependent_template_name) &&
884 "Only works for type and dependent templates");
Mike Stump1eb44332009-09-09 15:08:12 +0000885
886 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000887 TemplateId->getTemplateArgs(),
Douglas Gregor39a8de12009-02-25 19:37:18 +0000888 TemplateId->NumArgs);
889
John McCallf312b1e2010-08-26 23:41:50 +0000890 TypeResult Type
Douglas Gregor059101f2011-03-02 00:47:37 +0000891 = Actions.ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000892 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +0000893 TemplateId->Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000894 TemplateId->TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000895 TemplateId->LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000896 TemplateArgsPtr,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000897 TemplateId->RAngleLoc);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000898 // Create the new "type" annotation token.
899 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000900 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
Douglas Gregor059101f2011-03-02 00:47:37 +0000901 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
902 Tok.setLocation(TemplateId->SS.getBeginLoc());
Sebastian Redl39d67112010-02-08 19:35:18 +0000903 // End location stays the same
Douglas Gregor39a8de12009-02-25 19:37:18 +0000904
Douglas Gregor86235412009-11-04 18:18:19 +0000905 // Replace the template-id annotation token, and possible the scope-specifier
906 // that precedes it, with the typename annotation token.
907 PP.AnnotateCachedTokens(Tok);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000908}
909
Douglas Gregor314b97f2009-11-10 19:49:08 +0000910/// \brief Determine whether the given token can end a template argument.
Benjamin Kramer3a4a2b32009-11-10 21:29:56 +0000911static bool isEndOfTemplateArgument(Token Tok) {
Douglas Gregor314b97f2009-11-10 19:49:08 +0000912 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
913 Tok.is(tok::greatergreater);
914}
915
Douglas Gregor788cd062009-11-11 01:00:40 +0000916/// \brief Parse a C++ template template argument.
917ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
918 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
919 !Tok.is(tok::annot_cxxscope))
920 return ParsedTemplateArgument();
921
922 // C++0x [temp.arg.template]p1:
923 // A template-argument for a template template-parameter shall be the name
Richard Smith3e4c6c42011-05-05 21:57:07 +0000924 // of a class template or an alias template, expressed as id-expression.
Douglas Gregor788cd062009-11-11 01:00:40 +0000925 //
Richard Smith3e4c6c42011-05-05 21:57:07 +0000926 // We parse an id-expression that refers to a class template or alias
927 // template. The grammar we parse is:
Douglas Gregor788cd062009-11-11 01:00:40 +0000928 //
Douglas Gregorec5e6962011-01-05 17:33:50 +0000929 // nested-name-specifier[opt] template[opt] identifier ...[opt]
Douglas Gregor788cd062009-11-11 01:00:40 +0000930 //
931 // followed by a token that terminates a template argument, such as ',',
932 // '>', or (in some cases) '>>'.
Douglas Gregor788cd062009-11-11 01:00:40 +0000933 CXXScopeSpec SS; // nested-name-specifier, if present
John McCallb3d87482010-08-24 05:47:05 +0000934 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000935 /*EnteringContext=*/false);
936
Douglas Gregorec5e6962011-01-05 17:33:50 +0000937 ParsedTemplateArgument Result;
938 SourceLocation EllipsisLoc;
Douglas Gregor788cd062009-11-11 01:00:40 +0000939 if (SS.isSet() && Tok.is(tok::kw_template)) {
940 // Parse the optional 'template' keyword following the
941 // nested-name-specifier.
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000942 SourceLocation TemplateKWLoc = ConsumeToken();
Douglas Gregor788cd062009-11-11 01:00:40 +0000943
944 if (Tok.is(tok::identifier)) {
945 // We appear to have a dependent template name.
946 UnqualifiedId Name;
947 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
948 ConsumeToken(); // the identifier
949
Douglas Gregorec5e6962011-01-05 17:33:50 +0000950 // Parse the ellipsis.
951 if (Tok.is(tok::ellipsis))
952 EllipsisLoc = ConsumeToken();
953
Douglas Gregor788cd062009-11-11 01:00:40 +0000954 // If the next token signals the end of a template argument,
955 // then we have a dependent template name that could be a template
956 // template argument.
Douglas Gregord6ab2322010-06-16 23:00:59 +0000957 TemplateTy Template;
958 if (isEndOfTemplateArgument(Tok) &&
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000959 Actions.ActOnDependentTemplateName(getCurScope(),
960 SS, TemplateKWLoc, Name,
John McCallb3d87482010-08-24 05:47:05 +0000961 /*ObjectType=*/ ParsedType(),
Douglas Gregord6ab2322010-06-16 23:00:59 +0000962 /*EnteringContext=*/false,
963 Template))
Douglas Gregorec5e6962011-01-05 17:33:50 +0000964 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregord6ab2322010-06-16 23:00:59 +0000965 }
Douglas Gregor788cd062009-11-11 01:00:40 +0000966 } else if (Tok.is(tok::identifier)) {
967 // We may have a (non-dependent) template name.
968 TemplateTy Template;
969 UnqualifiedId Name;
970 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
971 ConsumeToken(); // the identifier
972
Douglas Gregorec5e6962011-01-05 17:33:50 +0000973 // Parse the ellipsis.
974 if (Tok.is(tok::ellipsis))
975 EllipsisLoc = ConsumeToken();
976
Douglas Gregor788cd062009-11-11 01:00:40 +0000977 if (isEndOfTemplateArgument(Tok)) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000978 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +0000979 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
980 /*hasTemplateKeyword=*/false,
981 Name,
John McCallb3d87482010-08-24 05:47:05 +0000982 /*ObjectType=*/ ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000983 /*EnteringContext=*/false,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000984 Template,
985 MemberOfUnknownSpecialization);
Douglas Gregor788cd062009-11-11 01:00:40 +0000986 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
987 // We have an id-expression that refers to a class template or
Richard Smith3e4c6c42011-05-05 21:57:07 +0000988 // (C++0x) alias template.
Douglas Gregorec5e6962011-01-05 17:33:50 +0000989 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregor788cd062009-11-11 01:00:40 +0000990 }
991 }
992 }
993
Douglas Gregorec5e6962011-01-05 17:33:50 +0000994 // If this is a pack expansion, build it as such.
995 if (EllipsisLoc.isValid() && !Result.isInvalid())
996 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
997
998 return Result;
Douglas Gregor788cd062009-11-11 01:00:40 +0000999}
1000
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001001/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1002///
1003/// template-argument: [C++ 14.2]
Douglas Gregorac7610d2009-06-22 20:57:11 +00001004/// constant-expression
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001005/// type-id
1006/// id-expression
Douglas Gregor314b97f2009-11-10 19:49:08 +00001007ParsedTemplateArgument Parser::ParseTemplateArgument() {
Douglas Gregor55f6b142009-02-09 18:46:07 +00001008 // C++ [temp.arg]p2:
1009 // In a template-argument, an ambiguity between a type-id and an
1010 // expression is resolved to a type-id, regardless of the form of
1011 // the corresponding template-parameter.
1012 //
Douglas Gregor314b97f2009-11-10 19:49:08 +00001013 // Therefore, we initially try to parse a type-id.
Douglas Gregor8b642592009-02-10 00:53:15 +00001014 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor314b97f2009-11-10 19:49:08 +00001015 SourceLocation Loc = Tok.getLocation();
Douglas Gregor683a81f2011-01-31 16:09:46 +00001016 TypeResult TypeArg = ParseTypeName(/*Range=*/0,
1017 Declarator::TemplateTypeArgContext);
Douglas Gregor809070a2009-02-18 17:45:20 +00001018 if (TypeArg.isInvalid())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001019 return ParsedTemplateArgument();
1020
John McCallb3d87482010-08-24 05:47:05 +00001021 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1022 TypeArg.get().getAsOpaquePtr(),
Douglas Gregor314b97f2009-11-10 19:49:08 +00001023 Loc);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001024 }
Douglas Gregor788cd062009-11-11 01:00:40 +00001025
1026 // Try to parse a template template argument.
Douglas Gregoreaf75f42009-11-12 00:03:40 +00001027 {
1028 TentativeParsingAction TPA(*this);
1029
1030 ParsedTemplateArgument TemplateTemplateArgument
1031 = ParseTemplateTemplateArgument();
1032 if (!TemplateTemplateArgument.isInvalid()) {
1033 TPA.Commit();
1034 return TemplateTemplateArgument;
1035 }
1036
1037 // Revert this tentative parse to parse a non-type template argument.
1038 TPA.Revert();
1039 }
Douglas Gregor314b97f2009-11-10 19:49:08 +00001040
1041 // Parse a non-type template argument.
1042 SourceLocation Loc = Tok.getLocation();
Kaelyn Uhraine43fe992012-02-22 01:03:07 +00001043 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001044 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001045 return ParsedTemplateArgument();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001046
Douglas Gregor314b97f2009-11-10 19:49:08 +00001047 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1048 ExprArg.release(), Loc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001049}
1050
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001051/// \brief Determine whether the current tokens can only be parsed as a
1052/// template argument list (starting with the '<') and never as a '<'
1053/// expression.
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001054bool Parser::IsTemplateArgumentList(unsigned Skip) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001055 struct AlwaysRevertAction : TentativeParsingAction {
1056 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1057 ~AlwaysRevertAction() { Revert(); }
1058 } Tentative(*this);
1059
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001060 while (Skip) {
1061 ConsumeToken();
1062 --Skip;
1063 }
1064
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001065 // '<'
1066 if (!Tok.is(tok::less))
1067 return false;
1068 ConsumeToken();
1069
1070 // An empty template argument list.
1071 if (Tok.is(tok::greater))
1072 return true;
1073
1074 // See whether we have declaration specifiers, which indicate a type.
1075 while (isCXXDeclarationSpecifier() == TPResult::True())
1076 ConsumeToken();
1077
1078 // If we have a '>' or a ',' then this is a template argument list.
1079 return Tok.is(tok::greater) || Tok.is(tok::comma);
1080}
1081
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001082/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1083/// (C++ [temp.names]). Returns true if there was an error.
1084///
1085/// template-argument-list: [C++ 14.2]
1086/// template-argument
1087/// template-argument-list ',' template-argument
Mike Stump1eb44332009-09-09 15:08:12 +00001088bool
Douglas Gregor314b97f2009-11-10 19:49:08 +00001089Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001090 while (true) {
Douglas Gregor314b97f2009-11-10 19:49:08 +00001091 ParsedTemplateArgument Arg = ParseTemplateArgument();
Douglas Gregor7536dd52010-12-20 02:24:11 +00001092 if (Tok.is(tok::ellipsis)) {
1093 SourceLocation EllipsisLoc = ConsumeToken();
1094 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1095 }
1096
Douglas Gregor314b97f2009-11-10 19:49:08 +00001097 if (Arg.isInvalid()) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001098 SkipUntil(tok::comma, tok::greater, true, true);
1099 return true;
1100 }
Douglas Gregor5908e9f2009-02-09 19:34:22 +00001101
Douglas Gregor314b97f2009-11-10 19:49:08 +00001102 // Save this template argument.
1103 TemplateArgs.push_back(Arg);
1104
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001105 // If the next token is a comma, consume it and keep reading
1106 // arguments.
1107 if (Tok.isNot(tok::comma)) break;
1108
1109 // Consume the comma.
1110 ConsumeToken();
1111 }
1112
Eli Friedman64a4eb22009-12-27 22:31:18 +00001113 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001114}
1115
Mike Stump1eb44332009-09-09 15:08:12 +00001116/// \brief Parse a C++ explicit template instantiation
Douglas Gregor1426e532009-05-12 21:31:51 +00001117/// (C++ [temp.explicit]).
1118///
1119/// explicit-instantiation:
Douglas Gregor45f96552009-09-04 06:33:52 +00001120/// 'extern' [opt] 'template' declaration
1121///
1122/// Note that the 'extern' is a GNU extension and C++0x feature.
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001123Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1124 SourceLocation ExternLoc,
John McCalld226f652010-08-21 09:40:31 +00001125 SourceLocation TemplateLoc,
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001126 SourceLocation &DeclEnd,
1127 AccessSpecifier AS) {
John McCallc9068d72010-07-16 08:13:16 +00001128 // This isn't really required here.
1129 ParsingDeclRAIIObject ParsingTemplateParams(*this);
1130
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001131 return ParseSingleDeclarationAfterTemplate(Context,
Douglas Gregor45f96552009-09-04 06:33:52 +00001132 ParsedTemplateInfo(ExternLoc,
1133 TemplateLoc),
John McCallc9068d72010-07-16 08:13:16 +00001134 ParsingTemplateParams,
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001135 DeclEnd, AS);
Douglas Gregor1426e532009-05-12 21:31:51 +00001136}
John McCall78b81052010-11-10 02:40:36 +00001137
1138SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1139 if (TemplateParams)
1140 return getTemplateParamsRange(TemplateParams->data(),
1141 TemplateParams->size());
1142
1143 SourceRange R(TemplateLoc);
1144 if (ExternLoc.isValid())
1145 R.setBegin(ExternLoc);
1146 return R;
1147}
Francois Pichet8387e2a2011-04-22 22:18:13 +00001148
Francois Pichet4a47e8d2011-04-23 11:52:20 +00001149void Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001150 ((Parser*)P)->LateTemplateParser(FD);
1151}
1152
1153
Francois Pichet4a47e8d2011-04-23 11:52:20 +00001154void Parser::LateTemplateParser(const FunctionDecl *FD) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001155 LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD];
1156 if (LPT) {
1157 ParseLateTemplatedFuncDef(*LPT);
1158 return;
1159 }
1160
1161 llvm_unreachable("Late templated function without associated lexed tokens");
1162}
David Blaikie219c2e22012-04-02 20:59:49 +00001163
1164/// \brief Late parse a C++ function template in Microsoft mode.
1165void Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) {
1166 if(!LMT.D)
1167 return;
1168
1169 // Get the FunctionDecl.
1170 FunctionDecl *FD = 0;
1171 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(LMT.D))
1172 FD = FunTmpl->getTemplatedDecl();
1173 else
1174 FD = cast<FunctionDecl>(LMT.D);
1175
Francois Pichetd77177a2012-02-22 08:25:53 +00001176 // To restore the context after late parsing.
David Blaikie219c2e22012-04-02 20:59:49 +00001177 Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
1178
1179 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1180 DeclaratorDecl* Declarator = dyn_cast<DeclaratorDecl>(FD);
1181 if (Declarator && Declarator->getNumTemplateParameterLists() != 0) {
1182 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::TemplateParamScope));
1183 Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
1184 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1185 } else {
1186 // Get the list of DeclContext to reenter.
1187 SmallVector<DeclContext*, 4> DeclContextToReenter;
1188 DeclContext *DD = FD->getLexicalParent();
1189 while (DD && !DD->isTranslationUnit()) {
1190 DeclContextToReenter.push_back(DD);
1191 DD = DD->getLexicalParent();
1192 }
1193
1194 // Reenter template scopes from outmost to innermost.
1195 SmallVector<DeclContext*, 4>::reverse_iterator II =
1196 DeclContextToReenter.rbegin();
1197 for (; II != DeclContextToReenter.rend(); ++II) {
1198 if (ClassTemplatePartialSpecializationDecl* MD =
1199 dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) {
1200 TemplateParamScopeStack.push_back(new ParseScope(this,
1201 Scope::TemplateParamScope));
1202 Actions.ActOnReenterTemplateScope(getCurScope(), MD);
1203 } else if (CXXRecordDecl* MD = dyn_cast_or_null<CXXRecordDecl>(*II)) {
1204 TemplateParamScopeStack.push_back(new ParseScope(this,
1205 Scope::TemplateParamScope,
1206 MD->getDescribedClassTemplate() != 0 ));
1207 Actions.ActOnReenterTemplateScope(getCurScope(),
1208 MD->getDescribedClassTemplate());
1209 }
1210 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1211 Actions.PushDeclContext(Actions.getCurScope(), *II);
1212 }
1213 TemplateParamScopeStack.push_back(new ParseScope(this,
1214 Scope::TemplateParamScope));
1215 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1216 }
1217
1218 assert(!LMT.Toks.empty() && "Empty body!");
1219
1220 // Append the current token at the end of the new token stream so that it
1221 // doesn't get lost.
1222 LMT.Toks.push_back(Tok);
1223 PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false);
1224
1225 // Consume the previously pushed token.
1226 ConsumeAnyToken();
1227 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1228 && "Inline method not starting with '{', ':' or 'try'");
1229
1230 // Parse the method body. Function body parsing code is similar enough
1231 // to be re-used for method bodies as well.
1232 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1233
1234 // Recreate the containing function DeclContext.
1235 Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FD));
1236
1237 if (FunctionTemplateDecl *FunctionTemplate
1238 = dyn_cast_or_null<FunctionTemplateDecl>(LMT.D))
1239 Actions.ActOnStartOfFunctionDef(getCurScope(),
1240 FunctionTemplate->getTemplatedDecl());
1241 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(LMT.D))
1242 Actions.ActOnStartOfFunctionDef(getCurScope(), Function);
1243
1244
1245 if (Tok.is(tok::kw_try)) {
1246 ParseFunctionTryBlock(LMT.D, FnScope);
1247 } else {
1248 if (Tok.is(tok::colon))
1249 ParseConstructorInitializer(LMT.D);
1250 else
1251 Actions.ActOnDefaultCtorInitializers(LMT.D);
1252
1253 if (Tok.is(tok::l_brace)) {
1254 ParseFunctionStatementBody(LMT.D, FnScope);
1255 Actions.MarkAsLateParsedTemplate(FD, false);
1256 } else
1257 Actions.ActOnFinishFunctionBody(LMT.D, 0);
1258 }
1259
1260 // Exit scopes.
Francois Pichetfdde4702011-09-22 22:14:56 +00001261 FnScope.Exit();
David Blaikie219c2e22012-04-02 20:59:49 +00001262 SmallVector<ParseScope*, 4>::reverse_iterator I =
1263 TemplateParamScopeStack.rbegin();
1264 for (; I != TemplateParamScopeStack.rend(); ++I)
1265 delete *I;
1266
1267 DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D);
1268 if (grp)
1269 Actions.getASTConsumer().HandleTopLevelDecl(grp.get());
Francois Pichet8387e2a2011-04-22 22:18:13 +00001270}
1271
1272/// \brief Lex a delayed template function for late parsing.
1273void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1274 tok::TokenKind kind = Tok.getKind();
Sebastian Redla891a322011-09-30 08:32:17 +00001275 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1276 // Consume everything up to (and including) the matching right brace.
1277 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001278 }
Francois Pichet8387e2a2011-04-22 22:18:13 +00001279
1280 // If we're in a function-try-block, we need to store all the catch blocks.
1281 if (kind == tok::kw_try) {
1282 while (Tok.is(tok::kw_catch)) {
1283 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1284 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1285 }
1286 }
1287}