blob: 04050c0edb1c25d0ee76bf7e02d14467813e81f5 [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
Douglas Gregor1426e532009-05-12 21:31:51 +0000244 // If we have a declaration or declarator list, handle it.
245 if (isDeclarationAfterDeclarator()) {
246 // Parse this declaration.
John McCalld226f652010-08-21 09:40:31 +0000247 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
248 TemplateInfo);
Douglas Gregor1426e532009-05-12 21:31:51 +0000249
250 if (Tok.is(tok::comma)) {
251 Diag(Tok, diag::err_multiple_template_declarators)
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000252 << (int)TemplateInfo.Kind;
Douglas Gregor1426e532009-05-12 21:31:51 +0000253 SkipUntil(tok::semi, true, false);
254 return ThisDecl;
255 }
256
257 // Eat the semi colon after the declaration.
John McCall5c15fe12009-07-31 02:20:35 +0000258 ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
John McCalleee1d542011-02-14 07:13:47 +0000259 DeclaratorInfo.complete(ThisDecl);
Douglas Gregor1426e532009-05-12 21:31:51 +0000260 return ThisDecl;
261 }
262
263 if (DeclaratorInfo.isFunctionDeclarator() &&
Chris Lattner004659a2010-07-11 22:42:07 +0000264 isStartOfFunctionDefinition(DeclaratorInfo)) {
Douglas Gregor1426e532009-05-12 21:31:51 +0000265 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Smith6e1fd332011-11-29 09:09:06 +0000266 // Recover by ignoring the 'typedef'. This was probably supposed to be
267 // the 'typename' keyword, which we should have already suggested adding
268 // if it's appropriate.
269 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
270 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith874d2532011-11-29 05:27:40 +0000271 DS.ClearStorageClassSpecs();
Douglas Gregor1426e532009-05-12 21:31:51 +0000272 }
Douglas Gregor52591bf2009-06-24 00:54:41 +0000273 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo);
Douglas Gregor1426e532009-05-12 21:31:51 +0000274 }
275
276 if (DeclaratorInfo.isFunctionDeclarator())
277 Diag(Tok, diag::err_expected_fn_body);
278 else
279 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
280 SkipUntil(tok::semi);
John McCalld226f652010-08-21 09:40:31 +0000281 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000282}
283
284/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000285/// angle brackets. Depth is the depth of this template-parameter-list, which
286/// is the number of template headers directly enclosing this template header.
287/// TemplateParams is the current list of template parameters we're building.
288/// The template parameter we parse will be added to this list. LAngleLoc and
Mike Stump1eb44332009-09-09 15:08:12 +0000289/// RAngleLoc will receive the positions of the '<' and '>', respectively,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000290/// that enclose this template parameter list.
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000291///
292/// \returns true if an error occurred, false otherwise.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000293bool Parser::ParseTemplateParameters(unsigned Depth,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000294 SmallVectorImpl<Decl*> &TemplateParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000295 SourceLocation &LAngleLoc,
296 SourceLocation &RAngleLoc) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000297 // Get the template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +0000298 if (!Tok.is(tok::less)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000299 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000300 return true;
Douglas Gregoradcac882008-12-01 23:54:00 +0000301 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000302 LAngleLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000303
Douglas Gregoradcac882008-12-01 23:54:00 +0000304 // Try to parse the template parameter list.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000305 if (Tok.is(tok::greater))
306 RAngleLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000307 else if (ParseTemplateParameterList(Depth, TemplateParams)) {
308 if (!Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000309 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000310 return true;
Douglas Gregoradcac882008-12-01 23:54:00 +0000311 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000312 RAngleLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000313 }
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000314 return false;
Douglas Gregoradcac882008-12-01 23:54:00 +0000315}
316
317/// ParseTemplateParameterList - Parse a template parameter list. If
318/// the parsing fails badly (i.e., closing bracket was left out), this
319/// will try to put the token stream in a reasonable position (closing
Mike Stump1eb44332009-09-09 15:08:12 +0000320/// a statement, etc.) and return false.
Douglas Gregoradcac882008-12-01 23:54:00 +0000321///
322/// template-parameter-list: [C++ temp]
323/// template-parameter
324/// template-parameter-list ',' template-parameter
Mike Stump1eb44332009-09-09 15:08:12 +0000325bool
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000326Parser::ParseTemplateParameterList(unsigned Depth,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000327 SmallVectorImpl<Decl*> &TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000328 while (1) {
John McCalld226f652010-08-21 09:40:31 +0000329 if (Decl *TmpParam
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000330 = ParseTemplateParameter(Depth, TemplateParams.size())) {
331 TemplateParams.push_back(TmpParam);
332 } else {
Douglas Gregoradcac882008-12-01 23:54:00 +0000333 // If we failed to parse a template parameter, skip until we find
334 // a comma or closing brace.
335 SkipUntil(tok::comma, tok::greater, true, true);
336 }
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Douglas Gregoradcac882008-12-01 23:54:00 +0000338 // Did we find a comma or the end of the template parmeter list?
Mike Stump1eb44332009-09-09 15:08:12 +0000339 if (Tok.is(tok::comma)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000340 ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000341 } else if (Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000342 // Don't consume this... that's done by template parser.
343 break;
344 } else {
345 // Somebody probably forgot to close the template. Skip ahead and
346 // try to get out of the expression. This error is currently
347 // subsumed by whatever goes on in ParseTemplateParameter.
348 // TODO: This could match >>, and it would be nice to avoid those
349 // silly errors with template <vec<T>>.
Douglas Gregor99ea7342010-10-15 01:15:58 +0000350 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Douglas Gregoradcac882008-12-01 23:54:00 +0000351 SkipUntil(tok::greater, true, true);
352 return false;
353 }
354 }
355 return true;
356}
357
Douglas Gregor98440b42009-11-21 02:07:55 +0000358/// \brief Determine whether the parser is at the start of a template
359/// type parameter.
360bool Parser::isStartOfTemplateTypeParameter() {
Douglas Gregor7b6d25b2010-06-04 07:30:15 +0000361 if (Tok.is(tok::kw_class)) {
362 // "class" may be the start of an elaborated-type-specifier or a
363 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
364 switch (NextToken().getKind()) {
365 case tok::equal:
366 case tok::comma:
367 case tok::greater:
368 case tok::greatergreater:
369 case tok::ellipsis:
370 return true;
371
372 case tok::identifier:
373 // This may be either a type-parameter or an elaborated-type-specifier.
374 // We have to look further.
375 break;
376
377 default:
378 return false;
379 }
380
381 switch (GetLookAheadToken(2).getKind()) {
382 case tok::equal:
383 case tok::comma:
384 case tok::greater:
385 case tok::greatergreater:
386 return true;
387
388 default:
389 return false;
390 }
391 }
Douglas Gregor98440b42009-11-21 02:07:55 +0000392
393 if (Tok.isNot(tok::kw_typename))
394 return false;
395
396 // C++ [temp.param]p2:
397 // There is no semantic difference between class and typename in a
398 // template-parameter. typename followed by an unqualified-id
399 // names a template type parameter. typename followed by a
400 // qualified-id denotes the type in a non-type
401 // parameter-declaration.
402 Token Next = NextToken();
403
404 // If we have an identifier, skip over it.
405 if (Next.getKind() == tok::identifier)
406 Next = GetLookAheadToken(2);
407
408 switch (Next.getKind()) {
409 case tok::equal:
410 case tok::comma:
411 case tok::greater:
412 case tok::greatergreater:
413 case tok::ellipsis:
414 return true;
415
416 default:
417 return false;
418 }
419}
420
Douglas Gregoradcac882008-12-01 23:54:00 +0000421/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
422///
423/// template-parameter: [C++ temp.param]
424/// type-parameter
425/// parameter-declaration
426///
427/// type-parameter: (see below)
Douglas Gregor61c4d282011-01-05 15:48:55 +0000428/// 'class' ...[opt] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000429/// 'class' identifier[opt] '=' type-id
Douglas Gregor61c4d282011-01-05 15:48:55 +0000430/// 'typename' ...[opt] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000431/// 'typename' identifier[opt] '=' type-id
Douglas Gregor61c4d282011-01-05 15:48:55 +0000432/// 'template' '<' template-parameter-list '>'
433/// 'class' ...[opt] identifier[opt]
434/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
435/// = id-expression
John McCalld226f652010-08-21 09:40:31 +0000436Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor98440b42009-11-21 02:07:55 +0000437 if (isStartOfTemplateTypeParameter())
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000438 return ParseTypeParameter(Depth, Position);
Mike Stump1eb44332009-09-09 15:08:12 +0000439
440 if (Tok.is(tok::kw_template))
Chris Lattner532e19b2009-01-04 23:51:17 +0000441 return ParseTemplateTemplateParameter(Depth, Position);
442
443 // If it's none of the above, then it must be a parameter declaration.
444 // NOTE: This will pick up errors in the closure of the template parameter
445 // list (e.g., template < ; Check here to implement >> style closures.
446 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000447}
448
449/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
450/// Other kinds of template parameters are parsed in
451/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
452///
453/// type-parameter: [C++ temp.param]
Anders Carlssonce5635a2009-06-12 23:09:56 +0000454/// 'class' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000455/// 'class' identifier[opt] '=' type-id
Anders Carlssonce5635a2009-06-12 23:09:56 +0000456/// 'typename' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000457/// 'typename' identifier[opt] '=' type-id
John McCalld226f652010-08-21 09:40:31 +0000458Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000459 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
Mike Stump1eb44332009-09-09 15:08:12 +0000460 "A type-parameter starts with 'class' or 'typename'");
Douglas Gregor26236e82008-12-02 00:41:28 +0000461
462 // Consume the 'class' or 'typename' keyword.
463 bool TypenameKeyword = Tok.is(tok::kw_typename);
464 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000465
Anders Carlsson941df7d2009-06-12 19:58:00 +0000466 // Grab the ellipsis (if given).
467 bool Ellipsis = false;
468 SourceLocation EllipsisLoc;
Anders Carlssonce5635a2009-06-12 23:09:56 +0000469 if (Tok.is(tok::ellipsis)) {
Anders Carlsson941df7d2009-06-12 19:58:00 +0000470 Ellipsis = true;
471 EllipsisLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Richard Smithe5acd132011-10-14 20:31:37 +0000473 Diag(EllipsisLoc,
474 getLang().CPlusPlus0x
475 ? diag::warn_cxx98_compat_variadic_templates
476 : diag::ext_variadic_templates);
Anders Carlsson941df7d2009-06-12 19:58:00 +0000477 }
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Douglas Gregoradcac882008-12-01 23:54:00 +0000479 // Grab the template parameter name (if given)
Douglas Gregor26236e82008-12-02 00:41:28 +0000480 SourceLocation NameLoc;
481 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000482 if (Tok.is(tok::identifier)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000483 ParamName = Tok.getIdentifierInfo();
484 NameLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000485 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
486 Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000487 // Unnamed template parameter. Don't have to do anything here, just
488 // don't consume this token.
489 } else {
490 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000491 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000492 }
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000494 // Grab a default argument (if available).
495 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
496 // we introduce the type parameter into the local scope.
497 SourceLocation EqualLoc;
John McCallb3d87482010-08-24 05:47:05 +0000498 ParsedType DefaultArg;
Mike Stump1eb44332009-09-09 15:08:12 +0000499 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000500 EqualLoc = ConsumeToken();
501 DefaultArg = ParseTypeName().get();
Douglas Gregoradcac882008-12-01 23:54:00 +0000502 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000503
Douglas Gregor23c94db2010-07-02 17:43:08 +0000504 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000505 EllipsisLoc, KeyLoc, ParamName, NameLoc,
506 Depth, Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000507}
508
509/// ParseTemplateTemplateParameter - Handle the parsing of template
Mike Stump1eb44332009-09-09 15:08:12 +0000510/// template parameters.
Douglas Gregoradcac882008-12-01 23:54:00 +0000511///
512/// type-parameter: [C++ temp.param]
Douglas Gregor61c4d282011-01-05 15:48:55 +0000513/// 'template' '<' template-parameter-list '>' 'class'
514/// ...[opt] identifier[opt]
515/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
516/// = id-expression
John McCalld226f652010-08-21 09:40:31 +0000517Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000518Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000519 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
520
521 // Handle the template <...> part.
522 SourceLocation TemplateLoc = ConsumeToken();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000523 SmallVector<Decl*,8> TemplateParams;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000524 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor68c69932009-02-10 19:52:54 +0000525 {
526 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000527 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000528 RAngleLoc)) {
John McCalld226f652010-08-21 09:40:31 +0000529 return 0;
Douglas Gregor68c69932009-02-10 19:52:54 +0000530 }
Douglas Gregoradcac882008-12-01 23:54:00 +0000531 }
532
533 // Generate a meaningful error if the user forgot to put class before the
534 // identifier, comma, or greater.
Mike Stump1eb44332009-09-09 15:08:12 +0000535 if (!Tok.is(tok::kw_class)) {
536 Diag(Tok.getLocation(), diag::err_expected_class_before)
Douglas Gregoradcac882008-12-01 23:54:00 +0000537 << PP.getSpelling(Tok);
John McCalld226f652010-08-21 09:40:31 +0000538 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000539 }
Jeffrey Yasskindec09842011-01-18 02:00:16 +0000540 ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000541
Douglas Gregor61c4d282011-01-05 15:48:55 +0000542 // Parse the ellipsis, if given.
543 SourceLocation EllipsisLoc;
544 if (Tok.is(tok::ellipsis)) {
545 EllipsisLoc = ConsumeToken();
546
Richard Smithe5acd132011-10-14 20:31:37 +0000547 Diag(EllipsisLoc,
548 getLang().CPlusPlus0x
549 ? diag::warn_cxx98_compat_variadic_templates
550 : diag::ext_variadic_templates);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000551 }
552
Douglas Gregoradcac882008-12-01 23:54:00 +0000553 // Get the identifier, if given.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000554 SourceLocation NameLoc;
555 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000556 if (Tok.is(tok::identifier)) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000557 ParamName = Tok.getIdentifierInfo();
558 NameLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000559 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000560 // Unnamed template parameter. Don't have to do anything here, just
561 // don't consume this token.
562 } else {
563 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000564 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000565 }
566
Richard Trieu90ab75b2011-09-09 03:18:59 +0000567 TemplateParameterList *ParamList =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000568 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
569 TemplateLoc, LAngleLoc,
Douglas Gregor369ea272010-10-21 17:26:49 +0000570 TemplateParams.data(),
Douglas Gregorddc29e12009-02-06 22:42:48 +0000571 TemplateParams.size(),
572 RAngleLoc);
573
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000574 // Grab a default argument (if available).
575 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
576 // we introduce the template parameter into the local scope.
577 SourceLocation EqualLoc;
578 ParsedTemplateArgument DefaultArg;
Douglas Gregord684b002009-02-10 19:49:53 +0000579 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000580 EqualLoc = ConsumeToken();
581 DefaultArg = ParseTemplateTemplateArgument();
582 if (DefaultArg.isInvalid()) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000583 Diag(Tok.getLocation(),
584 diag::err_default_template_template_parameter_not_template);
Nuno Lopes68f7a242009-12-10 00:07:02 +0000585 static const tok::TokenKind EndToks[] = {
Douglas Gregor788cd062009-11-11 01:00:40 +0000586 tok::comma, tok::greater, tok::greatergreater
587 };
588 SkipUntil(EndToks, 3, true, true);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000589 }
Douglas Gregord684b002009-02-10 19:49:53 +0000590 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000591
Douglas Gregor23c94db2010-07-02 17:43:08 +0000592 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000593 ParamList, EllipsisLoc,
594 ParamName, NameLoc, Depth,
595 Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000596}
597
598/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
Mike Stump1eb44332009-09-09 15:08:12 +0000599/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000600///
Douglas Gregoradcac882008-12-01 23:54:00 +0000601/// template-parameter:
602/// ...
603/// parameter-declaration
John McCalld226f652010-08-21 09:40:31 +0000604Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000605Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000606 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor26236e82008-12-02 00:41:28 +0000607 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregoradcac882008-12-01 23:54:00 +0000608 // declarators (parts of declarators?) are accepted for parameters.
John McCall0b7e6782011-03-24 11:26:52 +0000609 DeclSpec DS(AttrFactory);
Douglas Gregor26236e82008-12-02 00:41:28 +0000610 ParseDeclarationSpecifiers(DS);
Douglas Gregoradcac882008-12-01 23:54:00 +0000611
612 // Parse this as a typename.
Douglas Gregor26236e82008-12-02 00:41:28 +0000613 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
614 ParseDeclarator(ParamDecl);
John McCallb3d87482010-08-24 05:47:05 +0000615 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000616 // This probably shouldn't happen - and it's more of a Sema thing, but
617 // basically we didn't parse the type name because we couldn't associate
618 // it with an AST node. we should just skip to the comma or greater.
619 // TODO: This is currently a placeholder for some kind of Sema Error.
620 Diag(Tok.getLocation(), diag::err_parse_error);
621 SkipUntil(tok::comma, tok::greater, true, true);
John McCalld226f652010-08-21 09:40:31 +0000622 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000623 }
624
Douglas Gregord684b002009-02-10 19:49:53 +0000625 // If there is a default value, parse it.
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000626 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
627 // we introduce the template parameter into the local scope.
628 SourceLocation EqualLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000629 ExprResult DefaultArg;
Chris Lattner7452c6f2009-01-05 01:24:05 +0000630 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000631 EqualLoc = ConsumeToken();
Douglas Gregord684b002009-02-10 19:49:53 +0000632
633 // C++ [temp.param]p15:
634 // When parsing a default template-argument for a non-type
635 // template-parameter, the first non-nested > is taken as the
636 // end of the template-parameter-list rather than a greater-than
637 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +0000638 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000639
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000640 DefaultArg = ParseAssignmentExpression();
Douglas Gregord684b002009-02-10 19:49:53 +0000641 if (DefaultArg.isInvalid())
642 SkipUntil(tok::comma, tok::greater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000643 }
Mike Stump1eb44332009-09-09 15:08:12 +0000644
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000645 // Create the parameter.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000646 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000647 Depth, Position, EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000648 DefaultArg.take());
Douglas Gregoradcac882008-12-01 23:54:00 +0000649}
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000650
Douglas Gregorcc636682009-02-17 23:15:12 +0000651/// \brief Parses a template-id that after the template name has
652/// already been parsed.
653///
654/// This routine takes care of parsing the enclosed template argument
655/// list ('<' template-parameter-list [opt] '>') and placing the
656/// results into a form that can be transferred to semantic analysis.
657///
658/// \param Template the template declaration produced by isTemplateName
659///
660/// \param TemplateNameLoc the source location of the template name
661///
662/// \param SS if non-NULL, the nested-name-specifier preceding the
663/// template name.
664///
665/// \param ConsumeLastToken if true, then we will consume the last
666/// token that forms the template-id. Otherwise, we will leave the
667/// last token in the stream (e.g., so that it can be replaced with an
668/// annotation token).
Mike Stump1eb44332009-09-09 15:08:12 +0000669bool
Douglas Gregor7532dc62009-03-30 22:58:21 +0000670Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
Mike Stump1eb44332009-09-09 15:08:12 +0000671 SourceLocation TemplateNameLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +0000672 const CXXScopeSpec &SS,
Douglas Gregorcc636682009-02-17 23:15:12 +0000673 bool ConsumeLastToken,
674 SourceLocation &LAngleLoc,
675 TemplateArgList &TemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +0000676 SourceLocation &RAngleLoc) {
677 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
678
679 // Consume the '<'.
680 LAngleLoc = ConsumeToken();
681
682 // Parse the optional template-argument-list.
683 bool Invalid = false;
684 {
685 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Douglas Gregor4f3018e2011-01-11 00:45:18 +0000686 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
Douglas Gregor314b97f2009-11-10 19:49:08 +0000687 Invalid = ParseTemplateArgumentList(TemplateArgs);
Douglas Gregorcc636682009-02-17 23:15:12 +0000688
689 if (Invalid) {
690 // Try to find the closing '>'.
691 SkipUntil(tok::greater, true, !ConsumeLastToken);
692
693 return true;
694 }
695 }
696
Eli Friedman64a4eb22009-12-27 22:31:18 +0000697 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) {
698 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregorcc636682009-02-17 23:15:12 +0000699 return true;
Eli Friedman64a4eb22009-12-27 22:31:18 +0000700 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000701
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000702 // Determine the location of the '>' or '>>'. Only consume this
703 // token if the caller asked us to.
Douglas Gregorcc636682009-02-17 23:15:12 +0000704 RAngleLoc = Tok.getLocation();
705
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000706 if (Tok.is(tok::greatergreater)) {
Richard Smith7fe62082011-10-15 05:09:34 +0000707 const char *ReplaceStr = "> >";
708 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
709 ReplaceStr = "> > ";
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000710
Richard Smith7fe62082011-10-15 05:09:34 +0000711 Diag(Tok.getLocation(), getLang().CPlusPlus0x ?
712 diag::warn_cxx98_compat_two_right_angle_brackets :
713 diag::err_two_right_angle_brackets_need_space)
714 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()),
715 ReplaceStr);
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000716
717 Tok.setKind(tok::greater);
718 if (!ConsumeLastToken) {
719 // Since we're not supposed to consume the '>>' token, we need
720 // to insert a second '>' token after the first.
721 PP.EnterToken(Tok);
722 }
723 } else if (ConsumeLastToken)
Douglas Gregorcc636682009-02-17 23:15:12 +0000724 ConsumeToken();
725
726 return false;
727}
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Douglas Gregor39a8de12009-02-25 19:37:18 +0000729/// \brief Replace the tokens that form a simple-template-id with an
730/// annotation token containing the complete template-id.
731///
732/// The first token in the stream must be the name of a template that
733/// is followed by a '<'. This routine will parse the complete
734/// simple-template-id and replace the tokens with a single annotation
735/// token with one of two different kinds: if the template-id names a
736/// type (and \p AllowTypeAnnotation is true), the annotation token is
737/// a type annotation that includes the optional nested-name-specifier
738/// (\p SS). Otherwise, the annotation token is a template-id
739/// annotation that does not include the optional
740/// nested-name-specifier.
741///
742/// \param Template the declaration of the template named by the first
743/// token (an identifier), as returned from \c Action::isTemplateName().
744///
745/// \param TemplateNameKind the kind of template that \p Template
746/// refers to, as returned from \c Action::isTemplateName().
747///
748/// \param SS if non-NULL, the nested-name-specifier that precedes
749/// this template name.
750///
751/// \param TemplateKWLoc if valid, specifies that this template-id
752/// annotation was preceded by the 'template' keyword and gives the
753/// location of that keyword. If invalid (the default), then this
754/// template-id was not preceded by a 'template' keyword.
755///
756/// \param AllowTypeAnnotation if true (the default), then a
757/// simple-template-id that refers to a class template, template
758/// template parameter, or other template that produces a type will be
759/// replaced with a type annotation token. Otherwise, the
760/// simple-template-id is always replaced with a template-id
761/// annotation token.
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000762///
763/// If an unrecoverable parse error occurs and no annotation token can be
764/// formed, this function returns true.
765///
766bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Douglas Gregor059101f2011-03-02 00:47:37 +0000767 CXXScopeSpec &SS,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000768 SourceLocation TemplateKWLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000769 UnqualifiedId &TemplateName,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000770 bool AllowTypeAnnotation) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000771 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000772 assert(Template && Tok.is(tok::less) &&
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000773 "Parser isn't at the beginning of a template-id");
774
775 // Consume the template-name.
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000776 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000777
Douglas Gregorcc636682009-02-17 23:15:12 +0000778 // Parse the enclosed template argument list.
779 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000780 TemplateArgList TemplateArgs;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000781 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
782 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000783 SS, false, LAngleLoc,
784 TemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +0000785 RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000787 if (Invalid) {
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 Gregorc15cb382009-02-09 23:23:08 +0000794
Jay Foadbeaaccd2009-05-21 09:52:38 +0000795 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
Douglas Gregorcc636682009-02-17 23:15:12 +0000796 TemplateArgs.size());
Douglas Gregorf02da892009-02-09 21:04:56 +0000797
Douglas Gregor55f6b142009-02-09 18:46:07 +0000798 // Build the annotation token.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000799 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
John McCallf312b1e2010-08-26 23:41:50 +0000800 TypeResult Type
Douglas Gregor059101f2011-03-02 00:47:37 +0000801 = Actions.ActOnTemplateIdType(SS,
802 Template, TemplateNameLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000803 LAngleLoc, TemplateArgsPtr,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000804 RAngleLoc);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000805 if (Type.isInvalid()) {
806 // If we failed to parse the template ID but skipped ahead to a >, we're not
807 // going to be able to form a token annotation. Eat the '>' if present.
808 if (Tok.is(tok::greater))
809 ConsumeToken();
810 return true;
811 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000812
813 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000814 setTypeAnnotation(Tok, Type.get());
Douglas Gregor059101f2011-03-02 00:47:37 +0000815 if (SS.isNotEmpty())
816 Tok.setLocation(SS.getBeginLoc());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000817 else if (TemplateKWLoc.isValid())
818 Tok.setLocation(TemplateKWLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000819 else
Douglas Gregor39a8de12009-02-25 19:37:18 +0000820 Tok.setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +0000821 } else {
Douglas Gregorc45c2322009-03-31 00:43:58 +0000822 // Build a template-id annotation token that can be processed
823 // later.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000824 Tok.setKind(tok::annot_template_id);
Mike Stump1eb44332009-09-09 15:08:12 +0000825 TemplateIdAnnotation *TemplateId
Douglas Gregor39a8de12009-02-25 19:37:18 +0000826 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
Douglas Gregor55f6b142009-02-09 18:46:07 +0000827 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000828 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
829 TemplateId->Name = TemplateName.Identifier;
830 TemplateId->Operator = OO_None;
831 } else {
832 TemplateId->Name = 0;
833 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
834 }
Douglas Gregor059101f2011-03-02 00:47:37 +0000835 TemplateId->SS = SS;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000836 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall2b5289b2010-08-23 07:28:44 +0000837 TemplateId->Template = Template;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000838 TemplateId->Kind = TNK;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000839 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000840 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregor314b97f2009-11-10 19:49:08 +0000841 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
842 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
Douglas Gregorc34348a2011-02-24 17:54:50 +0000843 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000844 Tok.setAnnotationValue(TemplateId);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000845 if (TemplateKWLoc.isValid())
846 Tok.setLocation(TemplateKWLoc);
847 else
848 Tok.setLocation(TemplateNameLoc);
849
850 TemplateArgsPtr.release();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000851 }
852
853 // Common fields for the annotation token
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000854 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000855
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000856 // In case the tokens were cached, have Preprocessor replace them with the
857 // annotation token.
858 PP.AnnotateCachedTokens(Tok);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000859 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000860}
861
Douglas Gregor39a8de12009-02-25 19:37:18 +0000862/// \brief Replaces a template-id annotation token with a type
863/// annotation token.
864///
Douglas Gregor31a19b62009-04-01 21:51:26 +0000865/// If there was a failure when forming the type from the template-id,
866/// a type annotation token will still be created, but will have a
867/// NULL type pointer to signify an error.
Douglas Gregor059101f2011-03-02 00:47:37 +0000868void Parser::AnnotateTemplateIdTokenAsType() {
Douglas Gregor39a8de12009-02-25 19:37:18 +0000869 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
870
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +0000871 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000872 assert((TemplateId->Kind == TNK_Type_template ||
873 TemplateId->Kind == TNK_Dependent_template_name) &&
874 "Only works for type and dependent templates");
Mike Stump1eb44332009-09-09 15:08:12 +0000875
876 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000877 TemplateId->getTemplateArgs(),
Douglas Gregor39a8de12009-02-25 19:37:18 +0000878 TemplateId->NumArgs);
879
John McCallf312b1e2010-08-26 23:41:50 +0000880 TypeResult Type
Douglas Gregor059101f2011-03-02 00:47:37 +0000881 = Actions.ActOnTemplateIdType(TemplateId->SS,
882 TemplateId->Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000883 TemplateId->TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000884 TemplateId->LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000885 TemplateArgsPtr,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000886 TemplateId->RAngleLoc);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000887 // Create the new "type" annotation token.
888 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000889 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
Douglas Gregor059101f2011-03-02 00:47:37 +0000890 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
891 Tok.setLocation(TemplateId->SS.getBeginLoc());
Sebastian Redl39d67112010-02-08 19:35:18 +0000892 // End location stays the same
Douglas Gregor39a8de12009-02-25 19:37:18 +0000893
Douglas Gregor86235412009-11-04 18:18:19 +0000894 // Replace the template-id annotation token, and possible the scope-specifier
895 // that precedes it, with the typename annotation token.
896 PP.AnnotateCachedTokens(Tok);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000897}
898
Douglas Gregor314b97f2009-11-10 19:49:08 +0000899/// \brief Determine whether the given token can end a template argument.
Benjamin Kramer3a4a2b32009-11-10 21:29:56 +0000900static bool isEndOfTemplateArgument(Token Tok) {
Douglas Gregor314b97f2009-11-10 19:49:08 +0000901 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
902 Tok.is(tok::greatergreater);
903}
904
Douglas Gregor788cd062009-11-11 01:00:40 +0000905/// \brief Parse a C++ template template argument.
906ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
907 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
908 !Tok.is(tok::annot_cxxscope))
909 return ParsedTemplateArgument();
910
911 // C++0x [temp.arg.template]p1:
912 // A template-argument for a template template-parameter shall be the name
Richard Smith3e4c6c42011-05-05 21:57:07 +0000913 // of a class template or an alias template, expressed as id-expression.
Douglas Gregor788cd062009-11-11 01:00:40 +0000914 //
Richard Smith3e4c6c42011-05-05 21:57:07 +0000915 // We parse an id-expression that refers to a class template or alias
916 // template. The grammar we parse is:
Douglas Gregor788cd062009-11-11 01:00:40 +0000917 //
Douglas Gregorec5e6962011-01-05 17:33:50 +0000918 // nested-name-specifier[opt] template[opt] identifier ...[opt]
Douglas Gregor788cd062009-11-11 01:00:40 +0000919 //
920 // followed by a token that terminates a template argument, such as ',',
921 // '>', or (in some cases) '>>'.
Douglas Gregor788cd062009-11-11 01:00:40 +0000922 CXXScopeSpec SS; // nested-name-specifier, if present
John McCallb3d87482010-08-24 05:47:05 +0000923 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000924 /*EnteringContext=*/false);
925
Douglas Gregorec5e6962011-01-05 17:33:50 +0000926 ParsedTemplateArgument Result;
927 SourceLocation EllipsisLoc;
Douglas Gregor788cd062009-11-11 01:00:40 +0000928 if (SS.isSet() && Tok.is(tok::kw_template)) {
929 // Parse the optional 'template' keyword following the
930 // nested-name-specifier.
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000931 SourceLocation TemplateKWLoc = ConsumeToken();
Douglas Gregor788cd062009-11-11 01:00:40 +0000932
933 if (Tok.is(tok::identifier)) {
934 // We appear to have a dependent template name.
935 UnqualifiedId Name;
936 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
937 ConsumeToken(); // the identifier
938
Douglas Gregorec5e6962011-01-05 17:33:50 +0000939 // Parse the ellipsis.
940 if (Tok.is(tok::ellipsis))
941 EllipsisLoc = ConsumeToken();
942
Douglas Gregor788cd062009-11-11 01:00:40 +0000943 // If the next token signals the end of a template argument,
944 // then we have a dependent template name that could be a template
945 // template argument.
Douglas Gregord6ab2322010-06-16 23:00:59 +0000946 TemplateTy Template;
947 if (isEndOfTemplateArgument(Tok) &&
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000948 Actions.ActOnDependentTemplateName(getCurScope(),
949 SS, TemplateKWLoc, Name,
John McCallb3d87482010-08-24 05:47:05 +0000950 /*ObjectType=*/ ParsedType(),
Douglas Gregord6ab2322010-06-16 23:00:59 +0000951 /*EnteringContext=*/false,
952 Template))
Douglas Gregorec5e6962011-01-05 17:33:50 +0000953 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregord6ab2322010-06-16 23:00:59 +0000954 }
Douglas Gregor788cd062009-11-11 01:00:40 +0000955 } else if (Tok.is(tok::identifier)) {
956 // We may have a (non-dependent) template name.
957 TemplateTy Template;
958 UnqualifiedId Name;
959 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
960 ConsumeToken(); // the identifier
961
Douglas Gregorec5e6962011-01-05 17:33:50 +0000962 // Parse the ellipsis.
963 if (Tok.is(tok::ellipsis))
964 EllipsisLoc = ConsumeToken();
965
Douglas Gregor788cd062009-11-11 01:00:40 +0000966 if (isEndOfTemplateArgument(Tok)) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000967 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +0000968 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
969 /*hasTemplateKeyword=*/false,
970 Name,
John McCallb3d87482010-08-24 05:47:05 +0000971 /*ObjectType=*/ ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000972 /*EnteringContext=*/false,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000973 Template,
974 MemberOfUnknownSpecialization);
Douglas Gregor788cd062009-11-11 01:00:40 +0000975 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
976 // We have an id-expression that refers to a class template or
Richard Smith3e4c6c42011-05-05 21:57:07 +0000977 // (C++0x) alias template.
Douglas Gregorec5e6962011-01-05 17:33:50 +0000978 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregor788cd062009-11-11 01:00:40 +0000979 }
980 }
981 }
982
Douglas Gregorec5e6962011-01-05 17:33:50 +0000983 // If this is a pack expansion, build it as such.
984 if (EllipsisLoc.isValid() && !Result.isInvalid())
985 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
986
987 return Result;
Douglas Gregor788cd062009-11-11 01:00:40 +0000988}
989
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000990/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
991///
992/// template-argument: [C++ 14.2]
Douglas Gregorac7610d2009-06-22 20:57:11 +0000993/// constant-expression
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000994/// type-id
995/// id-expression
Douglas Gregor314b97f2009-11-10 19:49:08 +0000996ParsedTemplateArgument Parser::ParseTemplateArgument() {
Douglas Gregor55f6b142009-02-09 18:46:07 +0000997 // C++ [temp.arg]p2:
998 // In a template-argument, an ambiguity between a type-id and an
999 // expression is resolved to a type-id, regardless of the form of
1000 // the corresponding template-parameter.
1001 //
Douglas Gregor314b97f2009-11-10 19:49:08 +00001002 // Therefore, we initially try to parse a type-id.
Douglas Gregor8b642592009-02-10 00:53:15 +00001003 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor314b97f2009-11-10 19:49:08 +00001004 SourceLocation Loc = Tok.getLocation();
Douglas Gregor683a81f2011-01-31 16:09:46 +00001005 TypeResult TypeArg = ParseTypeName(/*Range=*/0,
1006 Declarator::TemplateTypeArgContext);
Douglas Gregor809070a2009-02-18 17:45:20 +00001007 if (TypeArg.isInvalid())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001008 return ParsedTemplateArgument();
1009
John McCallb3d87482010-08-24 05:47:05 +00001010 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1011 TypeArg.get().getAsOpaquePtr(),
Douglas Gregor314b97f2009-11-10 19:49:08 +00001012 Loc);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001013 }
Douglas Gregor788cd062009-11-11 01:00:40 +00001014
1015 // Try to parse a template template argument.
Douglas Gregoreaf75f42009-11-12 00:03:40 +00001016 {
1017 TentativeParsingAction TPA(*this);
1018
1019 ParsedTemplateArgument TemplateTemplateArgument
1020 = ParseTemplateTemplateArgument();
1021 if (!TemplateTemplateArgument.isInvalid()) {
1022 TPA.Commit();
1023 return TemplateTemplateArgument;
1024 }
1025
1026 // Revert this tentative parse to parse a non-type template argument.
1027 TPA.Revert();
1028 }
Douglas Gregor314b97f2009-11-10 19:49:08 +00001029
1030 // Parse a non-type template argument.
1031 SourceLocation Loc = Tok.getLocation();
John McCall60d7b3a2010-08-24 06:29:42 +00001032 ExprResult ExprArg = ParseConstantExpression();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001033 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001034 return ParsedTemplateArgument();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001035
Douglas Gregor314b97f2009-11-10 19:49:08 +00001036 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1037 ExprArg.release(), Loc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001038}
1039
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001040/// \brief Determine whether the current tokens can only be parsed as a
1041/// template argument list (starting with the '<') and never as a '<'
1042/// expression.
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001043bool Parser::IsTemplateArgumentList(unsigned Skip) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001044 struct AlwaysRevertAction : TentativeParsingAction {
1045 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1046 ~AlwaysRevertAction() { Revert(); }
1047 } Tentative(*this);
1048
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001049 while (Skip) {
1050 ConsumeToken();
1051 --Skip;
1052 }
1053
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001054 // '<'
1055 if (!Tok.is(tok::less))
1056 return false;
1057 ConsumeToken();
1058
1059 // An empty template argument list.
1060 if (Tok.is(tok::greater))
1061 return true;
1062
1063 // See whether we have declaration specifiers, which indicate a type.
1064 while (isCXXDeclarationSpecifier() == TPResult::True())
1065 ConsumeToken();
1066
1067 // If we have a '>' or a ',' then this is a template argument list.
1068 return Tok.is(tok::greater) || Tok.is(tok::comma);
1069}
1070
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001071/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1072/// (C++ [temp.names]). Returns true if there was an error.
1073///
1074/// template-argument-list: [C++ 14.2]
1075/// template-argument
1076/// template-argument-list ',' template-argument
Mike Stump1eb44332009-09-09 15:08:12 +00001077bool
Douglas Gregor314b97f2009-11-10 19:49:08 +00001078Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001079 while (true) {
Douglas Gregor314b97f2009-11-10 19:49:08 +00001080 ParsedTemplateArgument Arg = ParseTemplateArgument();
Douglas Gregor7536dd52010-12-20 02:24:11 +00001081 if (Tok.is(tok::ellipsis)) {
1082 SourceLocation EllipsisLoc = ConsumeToken();
1083 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1084 }
1085
Douglas Gregor314b97f2009-11-10 19:49:08 +00001086 if (Arg.isInvalid()) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001087 SkipUntil(tok::comma, tok::greater, true, true);
1088 return true;
1089 }
Douglas Gregor5908e9f2009-02-09 19:34:22 +00001090
Douglas Gregor314b97f2009-11-10 19:49:08 +00001091 // Save this template argument.
1092 TemplateArgs.push_back(Arg);
1093
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001094 // If the next token is a comma, consume it and keep reading
1095 // arguments.
1096 if (Tok.isNot(tok::comma)) break;
1097
1098 // Consume the comma.
1099 ConsumeToken();
1100 }
1101
Eli Friedman64a4eb22009-12-27 22:31:18 +00001102 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001103}
1104
Mike Stump1eb44332009-09-09 15:08:12 +00001105/// \brief Parse a C++ explicit template instantiation
Douglas Gregor1426e532009-05-12 21:31:51 +00001106/// (C++ [temp.explicit]).
1107///
1108/// explicit-instantiation:
Douglas Gregor45f96552009-09-04 06:33:52 +00001109/// 'extern' [opt] 'template' declaration
1110///
1111/// Note that the 'extern' is a GNU extension and C++0x feature.
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001112Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1113 SourceLocation ExternLoc,
John McCalld226f652010-08-21 09:40:31 +00001114 SourceLocation TemplateLoc,
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001115 SourceLocation &DeclEnd,
1116 AccessSpecifier AS) {
John McCallc9068d72010-07-16 08:13:16 +00001117 // This isn't really required here.
1118 ParsingDeclRAIIObject ParsingTemplateParams(*this);
1119
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001120 return ParseSingleDeclarationAfterTemplate(Context,
Douglas Gregor45f96552009-09-04 06:33:52 +00001121 ParsedTemplateInfo(ExternLoc,
1122 TemplateLoc),
John McCallc9068d72010-07-16 08:13:16 +00001123 ParsingTemplateParams,
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001124 DeclEnd, AS);
Douglas Gregor1426e532009-05-12 21:31:51 +00001125}
John McCall78b81052010-11-10 02:40:36 +00001126
1127SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1128 if (TemplateParams)
1129 return getTemplateParamsRange(TemplateParams->data(),
1130 TemplateParams->size());
1131
1132 SourceRange R(TemplateLoc);
1133 if (ExternLoc.isValid())
1134 R.setBegin(ExternLoc);
1135 return R;
1136}
Francois Pichet8387e2a2011-04-22 22:18:13 +00001137
Francois Pichet4a47e8d2011-04-23 11:52:20 +00001138void Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001139 ((Parser*)P)->LateTemplateParser(FD);
1140}
1141
1142
Francois Pichet4a47e8d2011-04-23 11:52:20 +00001143void Parser::LateTemplateParser(const FunctionDecl *FD) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001144 LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD];
1145 if (LPT) {
1146 ParseLateTemplatedFuncDef(*LPT);
1147 return;
1148 }
1149
1150 llvm_unreachable("Late templated function without associated lexed tokens");
1151}
1152
1153/// \brief Late parse a C++ function template in Microsoft mode.
1154void Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) {
1155 if(!LMT.D)
1156 return;
1157
1158 // If this is a member template, introduce the template parameter scope.
1159 ParseScope TemplateScope(this, Scope::TemplateParamScope);
1160
1161 // Get the FunctionDecl.
1162 FunctionDecl *FD = 0;
1163 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(LMT.D))
1164 FD = FunTmpl->getTemplatedDecl();
1165 else
1166 FD = cast<FunctionDecl>(LMT.D);
1167
1168 // Reinject the template parameters.
Francois Pichetfdde4702011-09-22 22:14:56 +00001169 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
Francois Pichet8387e2a2011-04-22 22:18:13 +00001170 DeclaratorDecl* Declarator = dyn_cast<DeclaratorDecl>(FD);
1171 if (Declarator && Declarator->getNumTemplateParameterLists() != 0) {
1172 Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
1173 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1174 } else {
1175 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1176
Francois Pichetfdde4702011-09-22 22:14:56 +00001177 // Get the list of DeclContext to reenter.
1178 SmallVector<DeclContext*, 4> DeclContextToReenter;
Francois Pichet8387e2a2011-04-22 22:18:13 +00001179 DeclContext *DD = FD->getLexicalParent();
1180 while (DD && DD->isRecord()) {
Francois Pichetfdde4702011-09-22 22:14:56 +00001181 DeclContextToReenter.push_back(DD);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001182 DD = DD->getLexicalParent();
1183 }
Francois Pichetfdde4702011-09-22 22:14:56 +00001184
Francois Pichet901a9a42011-09-23 16:02:49 +00001185 // Reenter template scopes from outmost to innermost.
Francois Pichetfdde4702011-09-22 22:14:56 +00001186 SmallVector<DeclContext*, 4>::reverse_iterator II =
1187 DeclContextToReenter.rbegin();
1188 for (; II != DeclContextToReenter.rend(); ++II) {
1189 if (ClassTemplatePartialSpecializationDecl* MD =
1190 dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) {
Sebastian Redla891a322011-09-30 08:32:17 +00001191 TemplateParamScopeStack.push_back(new ParseScope(this,
1192 Scope::TemplateParamScope));
Francois Pichetfdde4702011-09-22 22:14:56 +00001193 Actions.ActOnReenterTemplateScope(getCurScope(), MD);
1194 } else if (CXXRecordDecl* MD = dyn_cast_or_null<CXXRecordDecl>(*II)) {
Sebastian Redla891a322011-09-30 08:32:17 +00001195 TemplateParamScopeStack.push_back(new ParseScope(this,
1196 Scope::TemplateParamScope,
1197 MD->getDescribedClassTemplate() != 0 ));
Francois Pichetfdde4702011-09-22 22:14:56 +00001198 Actions.ActOnReenterTemplateScope(getCurScope(),
1199 MD->getDescribedClassTemplate());
1200 }
1201 }
Francois Pichet8387e2a2011-04-22 22:18:13 +00001202 }
1203 assert(!LMT.Toks.empty() && "Empty body!");
1204
1205 // Append the current token at the end of the new token stream so that it
1206 // doesn't get lost.
1207 LMT.Toks.push_back(Tok);
1208 PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false);
1209
1210 // Consume the previously pushed token.
1211 ConsumeAnyToken();
1212 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1213 && "Inline method not starting with '{', ':' or 'try'");
1214
1215 // Parse the method body. Function body parsing code is similar enough
1216 // to be re-used for method bodies as well.
1217 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1218
1219 // Recreate the DeclContext.
1220 Sema::ContextRAII SavedContext(Actions, Actions.getContainingDC(FD));
1221
1222 if (FunctionTemplateDecl *FunctionTemplate
1223 = dyn_cast_or_null<FunctionTemplateDecl>(LMT.D))
1224 Actions.ActOnStartOfFunctionDef(getCurScope(),
1225 FunctionTemplate->getTemplatedDecl());
1226 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(LMT.D))
1227 Actions.ActOnStartOfFunctionDef(getCurScope(), Function);
1228
1229
1230 if (Tok.is(tok::kw_try)) {
1231 ParseFunctionTryBlock(LMT.D, FnScope);
Francois Pichetfdde4702011-09-22 22:14:56 +00001232 } else {
1233 if (Tok.is(tok::colon))
1234 ParseConstructorInitializer(LMT.D);
1235 else
1236 Actions.ActOnDefaultCtorInitializers(LMT.D);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001237
Francois Pichetfdde4702011-09-22 22:14:56 +00001238 if (Tok.is(tok::l_brace)) {
1239 ParseFunctionStatementBody(LMT.D, FnScope);
1240 Actions.MarkAsLateParsedTemplate(FD, false);
1241 } else
Francois Pichet8387e2a2011-04-22 22:18:13 +00001242 Actions.ActOnFinishFunctionBody(LMT.D, 0);
Francois Pichetfdde4702011-09-22 22:14:56 +00001243 }
Francois Pichet8387e2a2011-04-22 22:18:13 +00001244
Francois Pichetfdde4702011-09-22 22:14:56 +00001245 // Exit scopes.
1246 FnScope.Exit();
1247 SmallVector<ParseScope*, 4>::reverse_iterator I =
1248 TemplateParamScopeStack.rbegin();
1249 for (; I != TemplateParamScopeStack.rend(); ++I)
1250 delete *I;
Francois Pichet8387e2a2011-04-22 22:18:13 +00001251
1252 DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D);
1253 if (grp)
1254 Actions.getASTConsumer().HandleTopLevelDecl(grp.get());
1255}
1256
1257/// \brief Lex a delayed template function for late parsing.
1258void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1259 tok::TokenKind kind = Tok.getKind();
Sebastian Redla891a322011-09-30 08:32:17 +00001260 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1261 // Consume everything up to (and including) the matching right brace.
1262 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001263 }
Francois Pichet8387e2a2011-04-22 22:18:13 +00001264
1265 // If we're in a function-try-block, we need to store all the catch blocks.
1266 if (kind == tok::kw_try) {
1267 while (Tok.is(tok::kw_catch)) {
1268 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1269 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1270 }
1271 }
1272}