blob: 5ffd535337007e47f2141acd7b121b451b7a0d8f [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,
29 AccessSpecifier AS) {
Fariborz Jahanian9735c5e2011-08-22 17:59:19 +000030 ObjCDeclContextSwitch ObjCDC(*this);
31
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000032 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
Fariborz Jahanian9735c5e2011-08-22 17:59:19 +000033 return ParseExplicitInstantiation(SourceLocation(), ConsumeToken(),
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000034 DeclEnd);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000035 }
Fariborz Jahanian9735c5e2011-08-22 17:59:19 +000036 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS);
Douglas Gregor4d9a16f2009-05-12 23:25:50 +000037}
38
Douglas Gregorc3058332009-08-24 23:03:25 +000039/// \brief RAII class that manages the template parameter depth.
40namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000041 class TemplateParameterDepthCounter {
Douglas Gregorc3058332009-08-24 23:03:25 +000042 unsigned &Depth;
43 unsigned AddedLevels;
44
45 public:
Mike Stump1eb44332009-09-09 15:08:12 +000046 explicit TemplateParameterDepthCounter(unsigned &Depth)
Douglas Gregorc3058332009-08-24 23:03:25 +000047 : Depth(Depth), AddedLevels(0) { }
Mike Stump1eb44332009-09-09 15:08:12 +000048
Douglas Gregorc3058332009-08-24 23:03:25 +000049 ~TemplateParameterDepthCounter() {
50 Depth -= AddedLevels;
51 }
Mike Stump1eb44332009-09-09 15:08:12 +000052
53 void operator++() {
Douglas Gregorc3058332009-08-24 23:03:25 +000054 ++Depth;
55 ++AddedLevels;
56 }
Mike Stump1eb44332009-09-09 15:08:12 +000057
Douglas Gregorc3058332009-08-24 23:03:25 +000058 operator unsigned() const { return Depth; }
59 };
60}
61
Douglas Gregorcc636682009-02-17 23:15:12 +000062/// \brief Parse a template declaration or an explicit specialization.
63///
64/// Template declarations include one or more template parameter lists
65/// and either the function or class template declaration. Explicit
66/// specializations contain one or more 'template < >' prefixes
67/// followed by a (possibly templated) declaration. Since the
68/// syntactic form of both features is nearly identical, we parse all
69/// of the template headers together and let semantic analysis sort
70/// the declarations from the explicit specializations.
Douglas Gregoradcac882008-12-01 23:54:00 +000071///
72/// template-declaration: [C++ temp]
73/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
Douglas Gregorcc636682009-02-17 23:15:12 +000074///
75/// explicit-specialization: [ C++ temp.expl.spec]
76/// 'template' '<' '>' declaration
John McCalld226f652010-08-21 09:40:31 +000077Decl *
Anders Carlsson5aeccdb2009-03-26 00:52:18 +000078Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
Chris Lattner97144fc2009-04-02 04:16:50 +000079 SourceLocation &DeclEnd,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +000080 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +000081 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
82 "Token does not start a template declaration.");
83
Douglas Gregor26236e82008-12-02 00:41:28 +000084 // Enter template-parameter scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +000085 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Douglas Gregor26236e82008-12-02 00:41:28 +000086
John McCallc9068d72010-07-16 08:13:16 +000087 // Tell the action that names should be checked in the context of
88 // the declaration to come.
89 ParsingDeclRAIIObject ParsingTemplateParams(*this);
90
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +000091 // Parse multiple levels of template headers within this template
92 // parameter scope, e.g.,
93 //
94 // template<typename T>
95 // template<typename U>
96 // class A<T>::B { ... };
97 //
98 // We parse multiple levels non-recursively so that we can build a
99 // single data structure containing all of the template parameter
Douglas Gregorcc636682009-02-17 23:15:12 +0000100 // lists to easily differentiate between the case above and:
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000101 //
102 // template<typename T>
103 // class A {
104 // template<typename U> class B;
105 // };
106 //
107 // In the first case, the action for declaring A<T>::B receives
108 // both template parameter lists. In the second case, the action for
109 // defining A<T>::B receives just the inner template parameter list
110 // (and retrieves the outer template parameter list from its
111 // context).
Douglas Gregor0f499d92009-08-20 18:46:05 +0000112 bool isSpecialization = true;
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000113 bool LastParamListWasEmpty = false;
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000114 TemplateParameterLists ParamLists;
Douglas Gregorc3058332009-08-24 23:03:25 +0000115 TemplateParameterDepthCounter Depth(TemplateParameterDepth);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000116 do {
117 // Consume the 'export', if any.
118 SourceLocation ExportLoc;
119 if (Tok.is(tok::kw_export)) {
120 ExportLoc = ConsumeToken();
121 }
122
123 // Consume the 'template', which should be here.
124 SourceLocation TemplateLoc;
125 if (Tok.is(tok::kw_template)) {
126 TemplateLoc = ConsumeToken();
127 } else {
128 Diag(Tok.getLocation(), diag::err_expected_template);
John McCalld226f652010-08-21 09:40:31 +0000129 return 0;
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000130 }
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000132 // Parse the '<' template-parameter-list '>'
133 SourceLocation LAngleLoc, RAngleLoc;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000134 SmallVector<Decl*, 4> TemplateParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000135 if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000136 RAngleLoc)) {
137 // Skip until the semi-colon or a }.
138 SkipUntil(tok::r_brace, true, true);
139 if (Tok.is(tok::semi))
140 ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000141 return 0;
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000142 }
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000143
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000144 ParamLists.push_back(
Mike Stump1eb44332009-09-09 15:08:12 +0000145 Actions.ActOnTemplateParameterList(Depth, ExportLoc,
146 TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +0000147 TemplateParams.data(),
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000148 TemplateParams.size(), RAngleLoc));
Douglas Gregorc3058332009-08-24 23:03:25 +0000149
150 if (!TemplateParams.empty()) {
151 isSpecialization = false;
152 ++Depth;
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000153 } else {
154 LastParamListWasEmpty = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000155 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000156 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
157
158 // Parse the actual template declaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000159 return ParseSingleDeclarationAfterTemplate(Context,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000160 ParsedTemplateInfo(&ParamLists,
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000161 isSpecialization,
162 LastParamListWasEmpty),
John McCallc9068d72010-07-16 08:13:16 +0000163 ParsingTemplateParams,
Douglas Gregor1426e532009-05-12 21:31:51 +0000164 DeclEnd, AS);
165}
Chris Lattner682bf922009-03-29 16:50:03 +0000166
Douglas Gregor1426e532009-05-12 21:31:51 +0000167/// \brief Parse a single declaration that declares a template,
168/// template specialization, or explicit instantiation of a template.
169///
170/// \param TemplateParams if non-NULL, the template parameter lists
171/// that preceded this declaration. In this case, the declaration is a
172/// template declaration, out-of-line definition of a template, or an
173/// explicit template specialization. When NULL, the declaration is an
174/// explicit template instantiation.
175///
176/// \param TemplateLoc when TemplateParams is NULL, the location of
177/// the 'template' keyword that indicates that we have an explicit
178/// template instantiation.
179///
180/// \param DeclEnd will receive the source location of the last token
181/// within this declaration.
182///
183/// \param AS the access specifier associated with this
184/// declaration. Will be AS_none for namespace-scope declarations.
185///
186/// \returns the new declaration.
John McCalld226f652010-08-21 09:40:31 +0000187Decl *
Douglas Gregor1426e532009-05-12 21:31:51 +0000188Parser::ParseSingleDeclarationAfterTemplate(
189 unsigned Context,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000190 const ParsedTemplateInfo &TemplateInfo,
John McCallc9068d72010-07-16 08:13:16 +0000191 ParsingDeclRAIIObject &DiagsFromTParams,
Douglas Gregor1426e532009-05-12 21:31:51 +0000192 SourceLocation &DeclEnd,
193 AccessSpecifier AS) {
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000194 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
195 "Template information required");
196
Douglas Gregor37b372b2009-08-20 22:52:58 +0000197 if (Context == Declarator::MemberContext) {
198 // We are parsing a member template.
John McCallc9068d72010-07-16 08:13:16 +0000199 ParseCXXClassMemberDeclaration(AS, TemplateInfo, &DiagsFromTParams);
John McCalld226f652010-08-21 09:40:31 +0000200 return 0;
Douglas Gregor37b372b2009-08-20 22:52:58 +0000201 }
Mike Stump1eb44332009-09-09 15:08:12 +0000202
John McCall0b7e6782011-03-24 11:26:52 +0000203 ParsedAttributesWithRange prefixAttrs(AttrFactory);
John McCall7f040a92010-12-24 02:08:15 +0000204 MaybeParseCXX0XAttributes(prefixAttrs);
John McCall78b81052010-11-10 02:40:36 +0000205
206 if (Tok.is(tok::kw_using))
207 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
John McCall7f040a92010-12-24 02:08:15 +0000208 prefixAttrs);
John McCall78b81052010-11-10 02:40:36 +0000209
John McCallc9068d72010-07-16 08:13:16 +0000210 // Parse the declaration specifiers, stealing the accumulated
211 // diagnostics from the template parameters.
John McCall0b7e6782011-03-24 11:26:52 +0000212 ParsingDeclSpec DS(*this, &DiagsFromTParams);
Sean Huntbbd37c62009-11-21 08:43:09 +0000213
John McCall7f040a92010-12-24 02:08:15 +0000214 DS.takeAttributesFrom(prefixAttrs);
Sean Huntbbd37c62009-11-21 08:43:09 +0000215
Douglas Gregor0efc2c12010-01-13 17:31:36 +0000216 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
217 getDeclSpecContextFromDeclaratorContext(Context));
Douglas Gregor1426e532009-05-12 21:31:51 +0000218
219 if (Tok.is(tok::semi)) {
220 DeclEnd = ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000221 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
John McCall54abf7d2009-11-04 02:18:39 +0000222 DS.complete(Decl);
223 return Decl;
Douglas Gregor1426e532009-05-12 21:31:51 +0000224 }
225
226 // Parse the declarator.
John McCall54abf7d2009-11-04 02:18:39 +0000227 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
Douglas Gregor1426e532009-05-12 21:31:51 +0000228 ParseDeclarator(DeclaratorInfo);
229 // Error parsing the declarator?
230 if (!DeclaratorInfo.hasName()) {
231 // If so, skip until the semi-colon or a }.
232 SkipUntil(tok::r_brace, true, true);
233 if (Tok.is(tok::semi))
234 ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000235 return 0;
Douglas Gregor1426e532009-05-12 21:31:51 +0000236 }
Mike Stump1eb44332009-09-09 15:08:12 +0000237
Douglas Gregor1426e532009-05-12 21:31:51 +0000238 // If we have a declaration or declarator list, handle it.
239 if (isDeclarationAfterDeclarator()) {
240 // Parse this declaration.
John McCalld226f652010-08-21 09:40:31 +0000241 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
242 TemplateInfo);
Douglas Gregor1426e532009-05-12 21:31:51 +0000243
244 if (Tok.is(tok::comma)) {
245 Diag(Tok, diag::err_multiple_template_declarators)
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000246 << (int)TemplateInfo.Kind;
Douglas Gregor1426e532009-05-12 21:31:51 +0000247 SkipUntil(tok::semi, true, false);
248 return ThisDecl;
249 }
250
251 // Eat the semi colon after the declaration.
John McCall5c15fe12009-07-31 02:20:35 +0000252 ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
John McCalleee1d542011-02-14 07:13:47 +0000253 DeclaratorInfo.complete(ThisDecl);
Douglas Gregor1426e532009-05-12 21:31:51 +0000254 return ThisDecl;
255 }
256
257 if (DeclaratorInfo.isFunctionDeclarator() &&
Chris Lattner004659a2010-07-11 22:42:07 +0000258 isStartOfFunctionDefinition(DeclaratorInfo)) {
Douglas Gregor1426e532009-05-12 21:31:51 +0000259 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
260 Diag(Tok, diag::err_function_declared_typedef);
261
262 if (Tok.is(tok::l_brace)) {
263 // This recovery skips the entire function body. It would be nice
264 // to simply call ParseFunctionDefinition() below, however Sema
265 // assumes the declarator represents a function, not a typedef.
266 ConsumeBrace();
267 SkipUntil(tok::r_brace, true);
268 } else {
269 SkipUntil(tok::semi);
270 }
John McCalld226f652010-08-21 09:40:31 +0000271 return 0;
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
473 if (!getLang().CPlusPlus0x)
Douglas Gregor5ce5f522011-01-19 21:59:15 +0000474 Diag(EllipsisLoc, diag::ext_variadic_templates);
Anders Carlsson941df7d2009-06-12 19:58:00 +0000475 }
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Douglas Gregoradcac882008-12-01 23:54:00 +0000477 // Grab the template parameter name (if given)
Douglas Gregor26236e82008-12-02 00:41:28 +0000478 SourceLocation NameLoc;
479 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000480 if (Tok.is(tok::identifier)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000481 ParamName = Tok.getIdentifierInfo();
482 NameLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000483 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
484 Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000485 // Unnamed template parameter. Don't have to do anything here, just
486 // don't consume this token.
487 } else {
488 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000489 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000490 }
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000492 // Grab a default argument (if available).
493 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
494 // we introduce the type parameter into the local scope.
495 SourceLocation EqualLoc;
John McCallb3d87482010-08-24 05:47:05 +0000496 ParsedType DefaultArg;
Mike Stump1eb44332009-09-09 15:08:12 +0000497 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000498 EqualLoc = ConsumeToken();
499 DefaultArg = ParseTypeName().get();
Douglas Gregoradcac882008-12-01 23:54:00 +0000500 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000501
Douglas Gregor23c94db2010-07-02 17:43:08 +0000502 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000503 EllipsisLoc, KeyLoc, ParamName, NameLoc,
504 Depth, Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000505}
506
507/// ParseTemplateTemplateParameter - Handle the parsing of template
Mike Stump1eb44332009-09-09 15:08:12 +0000508/// template parameters.
Douglas Gregoradcac882008-12-01 23:54:00 +0000509///
510/// type-parameter: [C++ temp.param]
Douglas Gregor61c4d282011-01-05 15:48:55 +0000511/// 'template' '<' template-parameter-list '>' 'class'
512/// ...[opt] identifier[opt]
513/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
514/// = id-expression
John McCalld226f652010-08-21 09:40:31 +0000515Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000516Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000517 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
518
519 // Handle the template <...> part.
520 SourceLocation TemplateLoc = ConsumeToken();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000521 SmallVector<Decl*,8> TemplateParams;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000522 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor68c69932009-02-10 19:52:54 +0000523 {
524 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000525 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000526 RAngleLoc)) {
John McCalld226f652010-08-21 09:40:31 +0000527 return 0;
Douglas Gregor68c69932009-02-10 19:52:54 +0000528 }
Douglas Gregoradcac882008-12-01 23:54:00 +0000529 }
530
531 // Generate a meaningful error if the user forgot to put class before the
532 // identifier, comma, or greater.
Mike Stump1eb44332009-09-09 15:08:12 +0000533 if (!Tok.is(tok::kw_class)) {
534 Diag(Tok.getLocation(), diag::err_expected_class_before)
Douglas Gregoradcac882008-12-01 23:54:00 +0000535 << PP.getSpelling(Tok);
John McCalld226f652010-08-21 09:40:31 +0000536 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000537 }
Jeffrey Yasskindec09842011-01-18 02:00:16 +0000538 ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000539
Douglas Gregor61c4d282011-01-05 15:48:55 +0000540 // Parse the ellipsis, if given.
541 SourceLocation EllipsisLoc;
542 if (Tok.is(tok::ellipsis)) {
543 EllipsisLoc = ConsumeToken();
544
545 if (!getLang().CPlusPlus0x)
Douglas Gregor5ce5f522011-01-19 21:59:15 +0000546 Diag(EllipsisLoc, diag::ext_variadic_templates);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000547 }
548
Douglas Gregoradcac882008-12-01 23:54:00 +0000549 // Get the identifier, if given.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000550 SourceLocation NameLoc;
551 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000552 if (Tok.is(tok::identifier)) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000553 ParamName = Tok.getIdentifierInfo();
554 NameLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000555 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000556 // Unnamed template parameter. Don't have to do anything here, just
557 // don't consume this token.
558 } else {
559 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000560 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000561 }
562
Richard Trieu90ab75b2011-09-09 03:18:59 +0000563 TemplateParameterList *ParamList =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000564 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
565 TemplateLoc, LAngleLoc,
Douglas Gregor369ea272010-10-21 17:26:49 +0000566 TemplateParams.data(),
Douglas Gregorddc29e12009-02-06 22:42:48 +0000567 TemplateParams.size(),
568 RAngleLoc);
569
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000570 // Grab a default argument (if available).
571 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
572 // we introduce the template parameter into the local scope.
573 SourceLocation EqualLoc;
574 ParsedTemplateArgument DefaultArg;
Douglas Gregord684b002009-02-10 19:49:53 +0000575 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000576 EqualLoc = ConsumeToken();
577 DefaultArg = ParseTemplateTemplateArgument();
578 if (DefaultArg.isInvalid()) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000579 Diag(Tok.getLocation(),
580 diag::err_default_template_template_parameter_not_template);
Nuno Lopes68f7a242009-12-10 00:07:02 +0000581 static const tok::TokenKind EndToks[] = {
Douglas Gregor788cd062009-11-11 01:00:40 +0000582 tok::comma, tok::greater, tok::greatergreater
583 };
584 SkipUntil(EndToks, 3, true, true);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000585 }
Douglas Gregord684b002009-02-10 19:49:53 +0000586 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000587
Douglas Gregor23c94db2010-07-02 17:43:08 +0000588 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000589 ParamList, EllipsisLoc,
590 ParamName, NameLoc, Depth,
591 Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000592}
593
594/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
Mike Stump1eb44332009-09-09 15:08:12 +0000595/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000596///
Douglas Gregoradcac882008-12-01 23:54:00 +0000597/// template-parameter:
598/// ...
599/// parameter-declaration
John McCalld226f652010-08-21 09:40:31 +0000600Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000601Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000602 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor26236e82008-12-02 00:41:28 +0000603 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregoradcac882008-12-01 23:54:00 +0000604 // declarators (parts of declarators?) are accepted for parameters.
John McCall0b7e6782011-03-24 11:26:52 +0000605 DeclSpec DS(AttrFactory);
Douglas Gregor26236e82008-12-02 00:41:28 +0000606 ParseDeclarationSpecifiers(DS);
Douglas Gregoradcac882008-12-01 23:54:00 +0000607
608 // Parse this as a typename.
Douglas Gregor26236e82008-12-02 00:41:28 +0000609 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
610 ParseDeclarator(ParamDecl);
John McCallb3d87482010-08-24 05:47:05 +0000611 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000612 // This probably shouldn't happen - and it's more of a Sema thing, but
613 // basically we didn't parse the type name because we couldn't associate
614 // it with an AST node. we should just skip to the comma or greater.
615 // TODO: This is currently a placeholder for some kind of Sema Error.
616 Diag(Tok.getLocation(), diag::err_parse_error);
617 SkipUntil(tok::comma, tok::greater, true, true);
John McCalld226f652010-08-21 09:40:31 +0000618 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000619 }
620
Douglas Gregord684b002009-02-10 19:49:53 +0000621 // If there is a default value, parse it.
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000622 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
623 // we introduce the template parameter into the local scope.
624 SourceLocation EqualLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000625 ExprResult DefaultArg;
Chris Lattner7452c6f2009-01-05 01:24:05 +0000626 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000627 EqualLoc = ConsumeToken();
Douglas Gregord684b002009-02-10 19:49:53 +0000628
629 // C++ [temp.param]p15:
630 // When parsing a default template-argument for a non-type
631 // template-parameter, the first non-nested > is taken as the
632 // end of the template-parameter-list rather than a greater-than
633 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +0000634 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000635
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000636 DefaultArg = ParseAssignmentExpression();
Douglas Gregord684b002009-02-10 19:49:53 +0000637 if (DefaultArg.isInvalid())
638 SkipUntil(tok::comma, tok::greater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000639 }
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000641 // Create the parameter.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000642 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000643 Depth, Position, EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000644 DefaultArg.take());
Douglas Gregoradcac882008-12-01 23:54:00 +0000645}
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000646
Douglas Gregorcc636682009-02-17 23:15:12 +0000647/// \brief Parses a template-id that after the template name has
648/// already been parsed.
649///
650/// This routine takes care of parsing the enclosed template argument
651/// list ('<' template-parameter-list [opt] '>') and placing the
652/// results into a form that can be transferred to semantic analysis.
653///
654/// \param Template the template declaration produced by isTemplateName
655///
656/// \param TemplateNameLoc the source location of the template name
657///
658/// \param SS if non-NULL, the nested-name-specifier preceding the
659/// template name.
660///
661/// \param ConsumeLastToken if true, then we will consume the last
662/// token that forms the template-id. Otherwise, we will leave the
663/// last token in the stream (e.g., so that it can be replaced with an
664/// annotation token).
Mike Stump1eb44332009-09-09 15:08:12 +0000665bool
Douglas Gregor7532dc62009-03-30 22:58:21 +0000666Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
Mike Stump1eb44332009-09-09 15:08:12 +0000667 SourceLocation TemplateNameLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +0000668 const CXXScopeSpec &SS,
Douglas Gregorcc636682009-02-17 23:15:12 +0000669 bool ConsumeLastToken,
670 SourceLocation &LAngleLoc,
671 TemplateArgList &TemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +0000672 SourceLocation &RAngleLoc) {
673 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
674
675 // Consume the '<'.
676 LAngleLoc = ConsumeToken();
677
678 // Parse the optional template-argument-list.
679 bool Invalid = false;
680 {
681 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Douglas Gregor4f3018e2011-01-11 00:45:18 +0000682 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
Douglas Gregor314b97f2009-11-10 19:49:08 +0000683 Invalid = ParseTemplateArgumentList(TemplateArgs);
Douglas Gregorcc636682009-02-17 23:15:12 +0000684
685 if (Invalid) {
686 // Try to find the closing '>'.
687 SkipUntil(tok::greater, true, !ConsumeLastToken);
688
689 return true;
690 }
691 }
692
Eli Friedman64a4eb22009-12-27 22:31:18 +0000693 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) {
694 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregorcc636682009-02-17 23:15:12 +0000695 return true;
Eli Friedman64a4eb22009-12-27 22:31:18 +0000696 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000697
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000698 // Determine the location of the '>' or '>>'. Only consume this
699 // token if the caller asked us to.
Douglas Gregorcc636682009-02-17 23:15:12 +0000700 RAngleLoc = Tok.getLocation();
701
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000702 if (Tok.is(tok::greatergreater)) {
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000703 if (!getLang().CPlusPlus0x) {
704 const char *ReplaceStr = "> >";
705 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
706 ReplaceStr = "> > ";
707
708 Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space)
Douglas Gregor849b2432010-03-31 17:46:05 +0000709 << FixItHint::CreateReplacement(
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000710 SourceRange(Tok.getLocation()), ReplaceStr);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000711 }
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000712
713 Tok.setKind(tok::greater);
714 if (!ConsumeLastToken) {
715 // Since we're not supposed to consume the '>>' token, we need
716 // to insert a second '>' token after the first.
717 PP.EnterToken(Tok);
718 }
719 } else if (ConsumeLastToken)
Douglas Gregorcc636682009-02-17 23:15:12 +0000720 ConsumeToken();
721
722 return false;
723}
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Douglas Gregor39a8de12009-02-25 19:37:18 +0000725/// \brief Replace the tokens that form a simple-template-id with an
726/// annotation token containing the complete template-id.
727///
728/// The first token in the stream must be the name of a template that
729/// is followed by a '<'. This routine will parse the complete
730/// simple-template-id and replace the tokens with a single annotation
731/// token with one of two different kinds: if the template-id names a
732/// type (and \p AllowTypeAnnotation is true), the annotation token is
733/// a type annotation that includes the optional nested-name-specifier
734/// (\p SS). Otherwise, the annotation token is a template-id
735/// annotation that does not include the optional
736/// nested-name-specifier.
737///
738/// \param Template the declaration of the template named by the first
739/// token (an identifier), as returned from \c Action::isTemplateName().
740///
741/// \param TemplateNameKind the kind of template that \p Template
742/// refers to, as returned from \c Action::isTemplateName().
743///
744/// \param SS if non-NULL, the nested-name-specifier that precedes
745/// this template name.
746///
747/// \param TemplateKWLoc if valid, specifies that this template-id
748/// annotation was preceded by the 'template' keyword and gives the
749/// location of that keyword. If invalid (the default), then this
750/// template-id was not preceded by a 'template' keyword.
751///
752/// \param AllowTypeAnnotation if true (the default), then a
753/// simple-template-id that refers to a class template, template
754/// template parameter, or other template that produces a type will be
755/// replaced with a type annotation token. Otherwise, the
756/// simple-template-id is always replaced with a template-id
757/// annotation token.
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000758///
759/// If an unrecoverable parse error occurs and no annotation token can be
760/// formed, this function returns true.
761///
762bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Douglas Gregor059101f2011-03-02 00:47:37 +0000763 CXXScopeSpec &SS,
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000764 UnqualifiedId &TemplateName,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000765 SourceLocation TemplateKWLoc,
766 bool AllowTypeAnnotation) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000767 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000768 assert(Template && Tok.is(tok::less) &&
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000769 "Parser isn't at the beginning of a template-id");
770
771 // Consume the template-name.
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000772 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000773
Douglas Gregorcc636682009-02-17 23:15:12 +0000774 // Parse the enclosed template argument list.
775 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000776 TemplateArgList TemplateArgs;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000777 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
778 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000779 SS, false, LAngleLoc,
780 TemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +0000781 RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000783 if (Invalid) {
784 // If we failed to parse the template ID but skipped ahead to a >, we're not
785 // going to be able to form a token annotation. Eat the '>' if present.
786 if (Tok.is(tok::greater))
787 ConsumeToken();
788 return true;
789 }
Douglas Gregorc15cb382009-02-09 23:23:08 +0000790
Jay Foadbeaaccd2009-05-21 09:52:38 +0000791 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
Douglas Gregorcc636682009-02-17 23:15:12 +0000792 TemplateArgs.size());
Douglas Gregorf02da892009-02-09 21:04:56 +0000793
Douglas Gregor55f6b142009-02-09 18:46:07 +0000794 // Build the annotation token.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000795 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
John McCallf312b1e2010-08-26 23:41:50 +0000796 TypeResult Type
Douglas Gregor059101f2011-03-02 00:47:37 +0000797 = Actions.ActOnTemplateIdType(SS,
798 Template, TemplateNameLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000799 LAngleLoc, TemplateArgsPtr,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000800 RAngleLoc);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000801 if (Type.isInvalid()) {
802 // If we failed to parse the template ID but skipped ahead to a >, we're not
803 // going to be able to form a token annotation. Eat the '>' if present.
804 if (Tok.is(tok::greater))
805 ConsumeToken();
806 return true;
807 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000808
809 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000810 setTypeAnnotation(Tok, Type.get());
Douglas Gregor059101f2011-03-02 00:47:37 +0000811 if (SS.isNotEmpty())
812 Tok.setLocation(SS.getBeginLoc());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000813 else if (TemplateKWLoc.isValid())
814 Tok.setLocation(TemplateKWLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000815 else
Douglas Gregor39a8de12009-02-25 19:37:18 +0000816 Tok.setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +0000817 } else {
Douglas Gregorc45c2322009-03-31 00:43:58 +0000818 // Build a template-id annotation token that can be processed
819 // later.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000820 Tok.setKind(tok::annot_template_id);
Mike Stump1eb44332009-09-09 15:08:12 +0000821 TemplateIdAnnotation *TemplateId
Douglas Gregor39a8de12009-02-25 19:37:18 +0000822 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
Douglas Gregor55f6b142009-02-09 18:46:07 +0000823 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000824 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
825 TemplateId->Name = TemplateName.Identifier;
826 TemplateId->Operator = OO_None;
827 } else {
828 TemplateId->Name = 0;
829 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
830 }
Douglas Gregor059101f2011-03-02 00:47:37 +0000831 TemplateId->SS = SS;
John McCall2b5289b2010-08-23 07:28:44 +0000832 TemplateId->Template = Template;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000833 TemplateId->Kind = TNK;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000834 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000835 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregor314b97f2009-11-10 19:49:08 +0000836 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
837 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
Douglas Gregorc34348a2011-02-24 17:54:50 +0000838 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000839 Tok.setAnnotationValue(TemplateId);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000840 if (TemplateKWLoc.isValid())
841 Tok.setLocation(TemplateKWLoc);
842 else
843 Tok.setLocation(TemplateNameLoc);
844
845 TemplateArgsPtr.release();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000846 }
847
848 // Common fields for the annotation token
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000849 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000850
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000851 // In case the tokens were cached, have Preprocessor replace them with the
852 // annotation token.
853 PP.AnnotateCachedTokens(Tok);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000854 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000855}
856
Douglas Gregor39a8de12009-02-25 19:37:18 +0000857/// \brief Replaces a template-id annotation token with a type
858/// annotation token.
859///
Douglas Gregor31a19b62009-04-01 21:51:26 +0000860/// If there was a failure when forming the type from the template-id,
861/// a type annotation token will still be created, but will have a
862/// NULL type pointer to signify an error.
Douglas Gregor059101f2011-03-02 00:47:37 +0000863void Parser::AnnotateTemplateIdTokenAsType() {
Douglas Gregor39a8de12009-02-25 19:37:18 +0000864 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
865
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +0000866 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000867 assert((TemplateId->Kind == TNK_Type_template ||
868 TemplateId->Kind == TNK_Dependent_template_name) &&
869 "Only works for type and dependent templates");
Mike Stump1eb44332009-09-09 15:08:12 +0000870
871 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000872 TemplateId->getTemplateArgs(),
Douglas Gregor39a8de12009-02-25 19:37:18 +0000873 TemplateId->NumArgs);
874
John McCallf312b1e2010-08-26 23:41:50 +0000875 TypeResult Type
Douglas Gregor059101f2011-03-02 00:47:37 +0000876 = Actions.ActOnTemplateIdType(TemplateId->SS,
877 TemplateId->Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000878 TemplateId->TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000879 TemplateId->LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000880 TemplateArgsPtr,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000881 TemplateId->RAngleLoc);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000882 // Create the new "type" annotation token.
883 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000884 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
Douglas Gregor059101f2011-03-02 00:47:37 +0000885 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
886 Tok.setLocation(TemplateId->SS.getBeginLoc());
Sebastian Redl39d67112010-02-08 19:35:18 +0000887 // End location stays the same
Douglas Gregor39a8de12009-02-25 19:37:18 +0000888
Douglas Gregor86235412009-11-04 18:18:19 +0000889 // Replace the template-id annotation token, and possible the scope-specifier
890 // that precedes it, with the typename annotation token.
891 PP.AnnotateCachedTokens(Tok);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000892}
893
Douglas Gregor314b97f2009-11-10 19:49:08 +0000894/// \brief Determine whether the given token can end a template argument.
Benjamin Kramer3a4a2b32009-11-10 21:29:56 +0000895static bool isEndOfTemplateArgument(Token Tok) {
Douglas Gregor314b97f2009-11-10 19:49:08 +0000896 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
897 Tok.is(tok::greatergreater);
898}
899
Douglas Gregor788cd062009-11-11 01:00:40 +0000900/// \brief Parse a C++ template template argument.
901ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
902 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
903 !Tok.is(tok::annot_cxxscope))
904 return ParsedTemplateArgument();
905
906 // C++0x [temp.arg.template]p1:
907 // A template-argument for a template template-parameter shall be the name
Richard Smith3e4c6c42011-05-05 21:57:07 +0000908 // of a class template or an alias template, expressed as id-expression.
Douglas Gregor788cd062009-11-11 01:00:40 +0000909 //
Richard Smith3e4c6c42011-05-05 21:57:07 +0000910 // We parse an id-expression that refers to a class template or alias
911 // template. The grammar we parse is:
Douglas Gregor788cd062009-11-11 01:00:40 +0000912 //
Douglas Gregorec5e6962011-01-05 17:33:50 +0000913 // nested-name-specifier[opt] template[opt] identifier ...[opt]
Douglas Gregor788cd062009-11-11 01:00:40 +0000914 //
915 // followed by a token that terminates a template argument, such as ',',
916 // '>', or (in some cases) '>>'.
Douglas Gregor788cd062009-11-11 01:00:40 +0000917 CXXScopeSpec SS; // nested-name-specifier, if present
John McCallb3d87482010-08-24 05:47:05 +0000918 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000919 /*EnteringContext=*/false);
920
Douglas Gregorec5e6962011-01-05 17:33:50 +0000921 ParsedTemplateArgument Result;
922 SourceLocation EllipsisLoc;
Douglas Gregor788cd062009-11-11 01:00:40 +0000923 if (SS.isSet() && Tok.is(tok::kw_template)) {
924 // Parse the optional 'template' keyword following the
925 // nested-name-specifier.
926 SourceLocation TemplateLoc = ConsumeToken();
927
928 if (Tok.is(tok::identifier)) {
929 // We appear to have a dependent template name.
930 UnqualifiedId Name;
931 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
932 ConsumeToken(); // the identifier
933
Douglas Gregorec5e6962011-01-05 17:33:50 +0000934 // Parse the ellipsis.
935 if (Tok.is(tok::ellipsis))
936 EllipsisLoc = ConsumeToken();
937
Douglas Gregor788cd062009-11-11 01:00:40 +0000938 // If the next token signals the end of a template argument,
939 // then we have a dependent template name that could be a template
940 // template argument.
Douglas Gregord6ab2322010-06-16 23:00:59 +0000941 TemplateTy Template;
942 if (isEndOfTemplateArgument(Tok) &&
John McCallb3d87482010-08-24 05:47:05 +0000943 Actions.ActOnDependentTemplateName(getCurScope(), TemplateLoc,
944 SS, Name,
945 /*ObjectType=*/ ParsedType(),
Douglas Gregord6ab2322010-06-16 23:00:59 +0000946 /*EnteringContext=*/false,
947 Template))
Douglas Gregorec5e6962011-01-05 17:33:50 +0000948 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregord6ab2322010-06-16 23:00:59 +0000949 }
Douglas Gregor788cd062009-11-11 01:00:40 +0000950 } else if (Tok.is(tok::identifier)) {
951 // We may have a (non-dependent) template name.
952 TemplateTy Template;
953 UnqualifiedId Name;
954 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
955 ConsumeToken(); // the identifier
956
Douglas Gregorec5e6962011-01-05 17:33:50 +0000957 // Parse the ellipsis.
958 if (Tok.is(tok::ellipsis))
959 EllipsisLoc = ConsumeToken();
960
Douglas Gregor788cd062009-11-11 01:00:40 +0000961 if (isEndOfTemplateArgument(Tok)) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000962 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +0000963 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
964 /*hasTemplateKeyword=*/false,
965 Name,
John McCallb3d87482010-08-24 05:47:05 +0000966 /*ObjectType=*/ ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000967 /*EnteringContext=*/false,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000968 Template,
969 MemberOfUnknownSpecialization);
Douglas Gregor788cd062009-11-11 01:00:40 +0000970 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
971 // We have an id-expression that refers to a class template or
Richard Smith3e4c6c42011-05-05 21:57:07 +0000972 // (C++0x) alias template.
Douglas Gregorec5e6962011-01-05 17:33:50 +0000973 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregor788cd062009-11-11 01:00:40 +0000974 }
975 }
976 }
977
Douglas Gregorec5e6962011-01-05 17:33:50 +0000978 // If this is a pack expansion, build it as such.
979 if (EllipsisLoc.isValid() && !Result.isInvalid())
980 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
981
982 return Result;
Douglas Gregor788cd062009-11-11 01:00:40 +0000983}
984
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000985/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
986///
987/// template-argument: [C++ 14.2]
Douglas Gregorac7610d2009-06-22 20:57:11 +0000988/// constant-expression
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000989/// type-id
990/// id-expression
Douglas Gregor314b97f2009-11-10 19:49:08 +0000991ParsedTemplateArgument Parser::ParseTemplateArgument() {
Douglas Gregor55f6b142009-02-09 18:46:07 +0000992 // C++ [temp.arg]p2:
993 // In a template-argument, an ambiguity between a type-id and an
994 // expression is resolved to a type-id, regardless of the form of
995 // the corresponding template-parameter.
996 //
Douglas Gregor314b97f2009-11-10 19:49:08 +0000997 // Therefore, we initially try to parse a type-id.
Douglas Gregor8b642592009-02-10 00:53:15 +0000998 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor314b97f2009-11-10 19:49:08 +0000999 SourceLocation Loc = Tok.getLocation();
Douglas Gregor683a81f2011-01-31 16:09:46 +00001000 TypeResult TypeArg = ParseTypeName(/*Range=*/0,
1001 Declarator::TemplateTypeArgContext);
Douglas Gregor809070a2009-02-18 17:45:20 +00001002 if (TypeArg.isInvalid())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001003 return ParsedTemplateArgument();
1004
John McCallb3d87482010-08-24 05:47:05 +00001005 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1006 TypeArg.get().getAsOpaquePtr(),
Douglas Gregor314b97f2009-11-10 19:49:08 +00001007 Loc);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001008 }
Douglas Gregor788cd062009-11-11 01:00:40 +00001009
1010 // Try to parse a template template argument.
Douglas Gregoreaf75f42009-11-12 00:03:40 +00001011 {
1012 TentativeParsingAction TPA(*this);
1013
1014 ParsedTemplateArgument TemplateTemplateArgument
1015 = ParseTemplateTemplateArgument();
1016 if (!TemplateTemplateArgument.isInvalid()) {
1017 TPA.Commit();
1018 return TemplateTemplateArgument;
1019 }
1020
1021 // Revert this tentative parse to parse a non-type template argument.
1022 TPA.Revert();
1023 }
Douglas Gregor314b97f2009-11-10 19:49:08 +00001024
1025 // Parse a non-type template argument.
1026 SourceLocation Loc = Tok.getLocation();
John McCall60d7b3a2010-08-24 06:29:42 +00001027 ExprResult ExprArg = ParseConstantExpression();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001028 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001029 return ParsedTemplateArgument();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001030
Douglas Gregor314b97f2009-11-10 19:49:08 +00001031 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1032 ExprArg.release(), Loc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001033}
1034
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001035/// \brief Determine whether the current tokens can only be parsed as a
1036/// template argument list (starting with the '<') and never as a '<'
1037/// expression.
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001038bool Parser::IsTemplateArgumentList(unsigned Skip) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001039 struct AlwaysRevertAction : TentativeParsingAction {
1040 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1041 ~AlwaysRevertAction() { Revert(); }
1042 } Tentative(*this);
1043
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001044 while (Skip) {
1045 ConsumeToken();
1046 --Skip;
1047 }
1048
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001049 // '<'
1050 if (!Tok.is(tok::less))
1051 return false;
1052 ConsumeToken();
1053
1054 // An empty template argument list.
1055 if (Tok.is(tok::greater))
1056 return true;
1057
1058 // See whether we have declaration specifiers, which indicate a type.
1059 while (isCXXDeclarationSpecifier() == TPResult::True())
1060 ConsumeToken();
1061
1062 // If we have a '>' or a ',' then this is a template argument list.
1063 return Tok.is(tok::greater) || Tok.is(tok::comma);
1064}
1065
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001066/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1067/// (C++ [temp.names]). Returns true if there was an error.
1068///
1069/// template-argument-list: [C++ 14.2]
1070/// template-argument
1071/// template-argument-list ',' template-argument
Mike Stump1eb44332009-09-09 15:08:12 +00001072bool
Douglas Gregor314b97f2009-11-10 19:49:08 +00001073Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001074 while (true) {
Douglas Gregor314b97f2009-11-10 19:49:08 +00001075 ParsedTemplateArgument Arg = ParseTemplateArgument();
Douglas Gregor7536dd52010-12-20 02:24:11 +00001076 if (Tok.is(tok::ellipsis)) {
1077 SourceLocation EllipsisLoc = ConsumeToken();
1078 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1079 }
1080
Douglas Gregor314b97f2009-11-10 19:49:08 +00001081 if (Arg.isInvalid()) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001082 SkipUntil(tok::comma, tok::greater, true, true);
1083 return true;
1084 }
Douglas Gregor5908e9f2009-02-09 19:34:22 +00001085
Douglas Gregor314b97f2009-11-10 19:49:08 +00001086 // Save this template argument.
1087 TemplateArgs.push_back(Arg);
1088
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001089 // If the next token is a comma, consume it and keep reading
1090 // arguments.
1091 if (Tok.isNot(tok::comma)) break;
1092
1093 // Consume the comma.
1094 ConsumeToken();
1095 }
1096
Eli Friedman64a4eb22009-12-27 22:31:18 +00001097 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001098}
1099
Mike Stump1eb44332009-09-09 15:08:12 +00001100/// \brief Parse a C++ explicit template instantiation
Douglas Gregor1426e532009-05-12 21:31:51 +00001101/// (C++ [temp.explicit]).
1102///
1103/// explicit-instantiation:
Douglas Gregor45f96552009-09-04 06:33:52 +00001104/// 'extern' [opt] 'template' declaration
1105///
1106/// Note that the 'extern' is a GNU extension and C++0x feature.
John McCalld226f652010-08-21 09:40:31 +00001107Decl *Parser::ParseExplicitInstantiation(SourceLocation ExternLoc,
1108 SourceLocation TemplateLoc,
1109 SourceLocation &DeclEnd) {
John McCallc9068d72010-07-16 08:13:16 +00001110 // This isn't really required here.
1111 ParsingDeclRAIIObject ParsingTemplateParams(*this);
1112
Mike Stump1eb44332009-09-09 15:08:12 +00001113 return ParseSingleDeclarationAfterTemplate(Declarator::FileContext,
Douglas Gregor45f96552009-09-04 06:33:52 +00001114 ParsedTemplateInfo(ExternLoc,
1115 TemplateLoc),
John McCallc9068d72010-07-16 08:13:16 +00001116 ParsingTemplateParams,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00001117 DeclEnd, AS_none);
Douglas Gregor1426e532009-05-12 21:31:51 +00001118}
John McCall78b81052010-11-10 02:40:36 +00001119
1120SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1121 if (TemplateParams)
1122 return getTemplateParamsRange(TemplateParams->data(),
1123 TemplateParams->size());
1124
1125 SourceRange R(TemplateLoc);
1126 if (ExternLoc.isValid())
1127 R.setBegin(ExternLoc);
1128 return R;
1129}
Francois Pichet8387e2a2011-04-22 22:18:13 +00001130
Francois Pichet4a47e8d2011-04-23 11:52:20 +00001131void Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001132 ((Parser*)P)->LateTemplateParser(FD);
1133}
1134
1135
Francois Pichet4a47e8d2011-04-23 11:52:20 +00001136void Parser::LateTemplateParser(const FunctionDecl *FD) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001137 LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD];
1138 if (LPT) {
1139 ParseLateTemplatedFuncDef(*LPT);
1140 return;
1141 }
1142
1143 llvm_unreachable("Late templated function without associated lexed tokens");
1144}
1145
1146/// \brief Late parse a C++ function template in Microsoft mode.
1147void Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) {
1148 if(!LMT.D)
1149 return;
1150
1151 // If this is a member template, introduce the template parameter scope.
1152 ParseScope TemplateScope(this, Scope::TemplateParamScope);
1153
1154 // Get the FunctionDecl.
1155 FunctionDecl *FD = 0;
1156 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(LMT.D))
1157 FD = FunTmpl->getTemplatedDecl();
1158 else
1159 FD = cast<FunctionDecl>(LMT.D);
1160
1161 // Reinject the template parameters.
Francois Pichetfdde4702011-09-22 22:14:56 +00001162 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
Francois Pichet8387e2a2011-04-22 22:18:13 +00001163 DeclaratorDecl* Declarator = dyn_cast<DeclaratorDecl>(FD);
1164 if (Declarator && Declarator->getNumTemplateParameterLists() != 0) {
1165 Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
1166 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1167 } else {
1168 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1169
Francois Pichetfdde4702011-09-22 22:14:56 +00001170 // Get the list of DeclContext to reenter.
1171 SmallVector<DeclContext*, 4> DeclContextToReenter;
Francois Pichet8387e2a2011-04-22 22:18:13 +00001172 DeclContext *DD = FD->getLexicalParent();
1173 while (DD && DD->isRecord()) {
Francois Pichetfdde4702011-09-22 22:14:56 +00001174 DeclContextToReenter.push_back(DD);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001175 DD = DD->getLexicalParent();
1176 }
Francois Pichetfdde4702011-09-22 22:14:56 +00001177
Francois Pichet901a9a42011-09-23 16:02:49 +00001178 // Reenter template scopes from outmost to innermost.
Francois Pichetfdde4702011-09-22 22:14:56 +00001179 SmallVector<DeclContext*, 4>::reverse_iterator II =
1180 DeclContextToReenter.rbegin();
1181 for (; II != DeclContextToReenter.rend(); ++II) {
1182 if (ClassTemplatePartialSpecializationDecl* MD =
1183 dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) {
1184 TemplateParamScopeStack.push_back(new ParseScope(this,
1185 Scope::TemplateParamScope));
1186 Actions.ActOnReenterTemplateScope(getCurScope(), MD);
1187 } else if (CXXRecordDecl* MD = dyn_cast_or_null<CXXRecordDecl>(*II)) {
1188 TemplateParamScopeStack.push_back(new ParseScope(this,
1189 Scope::TemplateParamScope,
1190 MD->getDescribedClassTemplate() != 0 ));
1191 Actions.ActOnReenterTemplateScope(getCurScope(),
1192 MD->getDescribedClassTemplate());
1193 }
1194 }
Francois Pichet8387e2a2011-04-22 22:18:13 +00001195 }
1196 assert(!LMT.Toks.empty() && "Empty body!");
1197
1198 // Append the current token at the end of the new token stream so that it
1199 // doesn't get lost.
1200 LMT.Toks.push_back(Tok);
1201 PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false);
1202
1203 // Consume the previously pushed token.
1204 ConsumeAnyToken();
1205 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1206 && "Inline method not starting with '{', ':' or 'try'");
1207
1208 // Parse the method body. Function body parsing code is similar enough
1209 // to be re-used for method bodies as well.
1210 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1211
1212 // Recreate the DeclContext.
1213 Sema::ContextRAII SavedContext(Actions, Actions.getContainingDC(FD));
1214
1215 if (FunctionTemplateDecl *FunctionTemplate
1216 = dyn_cast_or_null<FunctionTemplateDecl>(LMT.D))
1217 Actions.ActOnStartOfFunctionDef(getCurScope(),
1218 FunctionTemplate->getTemplatedDecl());
1219 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(LMT.D))
1220 Actions.ActOnStartOfFunctionDef(getCurScope(), Function);
1221
1222
1223 if (Tok.is(tok::kw_try)) {
1224 ParseFunctionTryBlock(LMT.D, FnScope);
Francois Pichetfdde4702011-09-22 22:14:56 +00001225 } else {
1226 if (Tok.is(tok::colon))
1227 ParseConstructorInitializer(LMT.D);
1228 else
1229 Actions.ActOnDefaultCtorInitializers(LMT.D);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001230
Francois Pichetfdde4702011-09-22 22:14:56 +00001231 if (Tok.is(tok::l_brace)) {
1232 ParseFunctionStatementBody(LMT.D, FnScope);
1233 Actions.MarkAsLateParsedTemplate(FD, false);
1234 } else
Francois Pichet8387e2a2011-04-22 22:18:13 +00001235 Actions.ActOnFinishFunctionBody(LMT.D, 0);
Francois Pichetfdde4702011-09-22 22:14:56 +00001236 }
Francois Pichet8387e2a2011-04-22 22:18:13 +00001237
Francois Pichetfdde4702011-09-22 22:14:56 +00001238 // Exit scopes.
1239 FnScope.Exit();
1240 SmallVector<ParseScope*, 4>::reverse_iterator I =
1241 TemplateParamScopeStack.rbegin();
1242 for (; I != TemplateParamScopeStack.rend(); ++I)
1243 delete *I;
Francois Pichet8387e2a2011-04-22 22:18:13 +00001244
1245 DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D);
1246 if (grp)
1247 Actions.getASTConsumer().HandleTopLevelDecl(grp.get());
1248}
1249
1250/// \brief Lex a delayed template function for late parsing.
1251void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1252 tok::TokenKind kind = Tok.getKind();
1253 // We may have a constructor initializer or function-try-block here.
1254 if (kind == tok::colon || kind == tok::kw_try)
Sebastian Redl6df65482011-09-24 17:48:25 +00001255 ConsumeAndStoreTryAndInitializers(Toks);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001256 else {
1257 Toks.push_back(Tok);
1258 ConsumeBrace();
1259 }
1260 // Consume everything up to (and including) the matching right brace.
1261 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1262
1263 // If we're in a function-try-block, we need to store all the catch blocks.
1264 if (kind == tok::kw_try) {
1265 while (Tok.is(tok::kw_catch)) {
1266 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1267 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1268 }
1269 }
1270}