blob: b485f1e97771a0411522df7738236ea10476da5d [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)) {
Fariborz Jahanian9735c5e2011-08-22 17:59:19 +000034 return ParseExplicitInstantiation(SourceLocation(), ConsumeToken(),
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000035 DeclEnd);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000036 }
Erik Verbruggen5f1c8222011-10-13 09:41:32 +000037 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
38 AccessAttrs);
Douglas Gregor4d9a16f2009-05-12 23:25:50 +000039}
40
Douglas Gregorc3058332009-08-24 23:03:25 +000041/// \brief RAII class that manages the template parameter depth.
42namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000043 class TemplateParameterDepthCounter {
Douglas Gregorc3058332009-08-24 23:03:25 +000044 unsigned &Depth;
45 unsigned AddedLevels;
46
47 public:
Mike Stump1eb44332009-09-09 15:08:12 +000048 explicit TemplateParameterDepthCounter(unsigned &Depth)
Douglas Gregorc3058332009-08-24 23:03:25 +000049 : Depth(Depth), AddedLevels(0) { }
Mike Stump1eb44332009-09-09 15:08:12 +000050
Douglas Gregorc3058332009-08-24 23:03:25 +000051 ~TemplateParameterDepthCounter() {
52 Depth -= AddedLevels;
53 }
Mike Stump1eb44332009-09-09 15:08:12 +000054
55 void operator++() {
Douglas Gregorc3058332009-08-24 23:03:25 +000056 ++Depth;
57 ++AddedLevels;
58 }
Mike Stump1eb44332009-09-09 15:08:12 +000059
Douglas Gregorc3058332009-08-24 23:03:25 +000060 operator unsigned() const { return Depth; }
61 };
62}
63
Douglas Gregorcc636682009-02-17 23:15:12 +000064/// \brief Parse a template declaration or an explicit specialization.
65///
66/// Template declarations include one or more template parameter lists
67/// and either the function or class template declaration. Explicit
68/// specializations contain one or more 'template < >' prefixes
69/// followed by a (possibly templated) declaration. Since the
70/// syntactic form of both features is nearly identical, we parse all
71/// of the template headers together and let semantic analysis sort
72/// the declarations from the explicit specializations.
Douglas Gregoradcac882008-12-01 23:54:00 +000073///
74/// template-declaration: [C++ temp]
75/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
Douglas Gregorcc636682009-02-17 23:15:12 +000076///
77/// explicit-specialization: [ C++ temp.expl.spec]
78/// 'template' '<' '>' declaration
John McCalld226f652010-08-21 09:40:31 +000079Decl *
Anders Carlsson5aeccdb2009-03-26 00:52:18 +000080Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
Chris Lattner97144fc2009-04-02 04:16:50 +000081 SourceLocation &DeclEnd,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +000082 AccessSpecifier AS,
83 AttributeList *AccessAttrs) {
Mike Stump1eb44332009-09-09 15:08:12 +000084 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
85 "Token does not start a template declaration.");
86
Douglas Gregor26236e82008-12-02 00:41:28 +000087 // Enter template-parameter scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +000088 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Douglas Gregor26236e82008-12-02 00:41:28 +000089
John McCallc9068d72010-07-16 08:13:16 +000090 // Tell the action that names should be checked in the context of
91 // the declaration to come.
92 ParsingDeclRAIIObject ParsingTemplateParams(*this);
93
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +000094 // Parse multiple levels of template headers within this template
95 // parameter scope, e.g.,
96 //
97 // template<typename T>
98 // template<typename U>
99 // class A<T>::B { ... };
100 //
101 // We parse multiple levels non-recursively so that we can build a
102 // single data structure containing all of the template parameter
Douglas Gregorcc636682009-02-17 23:15:12 +0000103 // lists to easily differentiate between the case above and:
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000104 //
105 // template<typename T>
106 // class A {
107 // template<typename U> class B;
108 // };
109 //
110 // In the first case, the action for declaring A<T>::B receives
111 // both template parameter lists. In the second case, the action for
112 // defining A<T>::B receives just the inner template parameter list
113 // (and retrieves the outer template parameter list from its
114 // context).
Douglas Gregor0f499d92009-08-20 18:46:05 +0000115 bool isSpecialization = true;
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000116 bool LastParamListWasEmpty = false;
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000117 TemplateParameterLists ParamLists;
Douglas Gregorc3058332009-08-24 23:03:25 +0000118 TemplateParameterDepthCounter Depth(TemplateParameterDepth);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000119 do {
120 // Consume the 'export', if any.
121 SourceLocation ExportLoc;
122 if (Tok.is(tok::kw_export)) {
123 ExportLoc = ConsumeToken();
124 }
125
126 // Consume the 'template', which should be here.
127 SourceLocation TemplateLoc;
128 if (Tok.is(tok::kw_template)) {
129 TemplateLoc = ConsumeToken();
130 } else {
131 Diag(Tok.getLocation(), diag::err_expected_template);
John McCalld226f652010-08-21 09:40:31 +0000132 return 0;
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000133 }
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000135 // Parse the '<' template-parameter-list '>'
136 SourceLocation LAngleLoc, RAngleLoc;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000137 SmallVector<Decl*, 4> TemplateParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000138 if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000139 RAngleLoc)) {
140 // Skip until the semi-colon or a }.
141 SkipUntil(tok::r_brace, true, true);
142 if (Tok.is(tok::semi))
143 ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000144 return 0;
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000145 }
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000146
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000147 ParamLists.push_back(
Mike Stump1eb44332009-09-09 15:08:12 +0000148 Actions.ActOnTemplateParameterList(Depth, ExportLoc,
149 TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +0000150 TemplateParams.data(),
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000151 TemplateParams.size(), RAngleLoc));
Douglas Gregorc3058332009-08-24 23:03:25 +0000152
153 if (!TemplateParams.empty()) {
154 isSpecialization = false;
155 ++Depth;
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000156 } else {
157 LastParamListWasEmpty = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000158 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000159 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
160
161 // Parse the actual template declaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000162 return ParseSingleDeclarationAfterTemplate(Context,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000163 ParsedTemplateInfo(&ParamLists,
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000164 isSpecialization,
165 LastParamListWasEmpty),
John McCallc9068d72010-07-16 08:13:16 +0000166 ParsingTemplateParams,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +0000167 DeclEnd, AS, AccessAttrs);
Douglas Gregor1426e532009-05-12 21:31:51 +0000168}
Chris Lattner682bf922009-03-29 16:50:03 +0000169
Douglas Gregor1426e532009-05-12 21:31:51 +0000170/// \brief Parse a single declaration that declares a template,
171/// template specialization, or explicit instantiation of a template.
172///
173/// \param TemplateParams if non-NULL, the template parameter lists
174/// that preceded this declaration. In this case, the declaration is a
175/// template declaration, out-of-line definition of a template, or an
176/// explicit template specialization. When NULL, the declaration is an
177/// explicit template instantiation.
178///
179/// \param TemplateLoc when TemplateParams is NULL, the location of
180/// the 'template' keyword that indicates that we have an explicit
181/// template instantiation.
182///
183/// \param DeclEnd will receive the source location of the last token
184/// within this declaration.
185///
186/// \param AS the access specifier associated with this
187/// declaration. Will be AS_none for namespace-scope declarations.
188///
189/// \returns the new declaration.
John McCalld226f652010-08-21 09:40:31 +0000190Decl *
Douglas Gregor1426e532009-05-12 21:31:51 +0000191Parser::ParseSingleDeclarationAfterTemplate(
192 unsigned Context,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000193 const ParsedTemplateInfo &TemplateInfo,
John McCallc9068d72010-07-16 08:13:16 +0000194 ParsingDeclRAIIObject &DiagsFromTParams,
Douglas Gregor1426e532009-05-12 21:31:51 +0000195 SourceLocation &DeclEnd,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +0000196 AccessSpecifier AS,
197 AttributeList *AccessAttrs) {
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000198 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
199 "Template information required");
200
Douglas Gregor37b372b2009-08-20 22:52:58 +0000201 if (Context == Declarator::MemberContext) {
202 // We are parsing a member template.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +0000203 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
204 &DiagsFromTParams);
John McCalld226f652010-08-21 09:40:31 +0000205 return 0;
Douglas Gregor37b372b2009-08-20 22:52:58 +0000206 }
Mike Stump1eb44332009-09-09 15:08:12 +0000207
John McCall0b7e6782011-03-24 11:26:52 +0000208 ParsedAttributesWithRange prefixAttrs(AttrFactory);
John McCall7f040a92010-12-24 02:08:15 +0000209 MaybeParseCXX0XAttributes(prefixAttrs);
John McCall78b81052010-11-10 02:40:36 +0000210
211 if (Tok.is(tok::kw_using))
212 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
John McCall7f040a92010-12-24 02:08:15 +0000213 prefixAttrs);
John McCall78b81052010-11-10 02:40:36 +0000214
John McCallc9068d72010-07-16 08:13:16 +0000215 // Parse the declaration specifiers, stealing the accumulated
216 // diagnostics from the template parameters.
John McCall0b7e6782011-03-24 11:26:52 +0000217 ParsingDeclSpec DS(*this, &DiagsFromTParams);
Sean Huntbbd37c62009-11-21 08:43:09 +0000218
John McCall7f040a92010-12-24 02:08:15 +0000219 DS.takeAttributesFrom(prefixAttrs);
Sean Huntbbd37c62009-11-21 08:43:09 +0000220
Douglas Gregor0efc2c12010-01-13 17:31:36 +0000221 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
222 getDeclSpecContextFromDeclaratorContext(Context));
Douglas Gregor1426e532009-05-12 21:31:51 +0000223
224 if (Tok.is(tok::semi)) {
225 DeclEnd = ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000226 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
John McCall54abf7d2009-11-04 02:18:39 +0000227 DS.complete(Decl);
228 return Decl;
Douglas Gregor1426e532009-05-12 21:31:51 +0000229 }
230
231 // Parse the declarator.
John McCall54abf7d2009-11-04 02:18:39 +0000232 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
Douglas Gregor1426e532009-05-12 21:31:51 +0000233 ParseDeclarator(DeclaratorInfo);
234 // Error parsing the declarator?
235 if (!DeclaratorInfo.hasName()) {
236 // If so, skip until the semi-colon or a }.
237 SkipUntil(tok::r_brace, true, true);
238 if (Tok.is(tok::semi))
239 ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000240 return 0;
Douglas Gregor1426e532009-05-12 21:31:51 +0000241 }
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Douglas Gregor1426e532009-05-12 21:31:51 +0000243 // If we have a declaration or declarator list, handle it.
244 if (isDeclarationAfterDeclarator()) {
245 // Parse this declaration.
John McCalld226f652010-08-21 09:40:31 +0000246 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
247 TemplateInfo);
Douglas Gregor1426e532009-05-12 21:31:51 +0000248
249 if (Tok.is(tok::comma)) {
250 Diag(Tok, diag::err_multiple_template_declarators)
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000251 << (int)TemplateInfo.Kind;
Douglas Gregor1426e532009-05-12 21:31:51 +0000252 SkipUntil(tok::semi, true, false);
253 return ThisDecl;
254 }
255
256 // Eat the semi colon after the declaration.
John McCall5c15fe12009-07-31 02:20:35 +0000257 ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
John McCalleee1d542011-02-14 07:13:47 +0000258 DeclaratorInfo.complete(ThisDecl);
Douglas Gregor1426e532009-05-12 21:31:51 +0000259 return ThisDecl;
260 }
261
262 if (DeclaratorInfo.isFunctionDeclarator() &&
Chris Lattner004659a2010-07-11 22:42:07 +0000263 isStartOfFunctionDefinition(DeclaratorInfo)) {
Douglas Gregor1426e532009-05-12 21:31:51 +0000264 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
265 Diag(Tok, diag::err_function_declared_typedef);
266
267 if (Tok.is(tok::l_brace)) {
268 // This recovery skips the entire function body. It would be nice
269 // to simply call ParseFunctionDefinition() below, however Sema
270 // assumes the declarator represents a function, not a typedef.
271 ConsumeBrace();
272 SkipUntil(tok::r_brace, true);
273 } else {
274 SkipUntil(tok::semi);
275 }
John McCalld226f652010-08-21 09:40:31 +0000276 return 0;
Douglas Gregor1426e532009-05-12 21:31:51 +0000277 }
Douglas Gregor52591bf2009-06-24 00:54:41 +0000278 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo);
Douglas Gregor1426e532009-05-12 21:31:51 +0000279 }
280
281 if (DeclaratorInfo.isFunctionDeclarator())
282 Diag(Tok, diag::err_expected_fn_body);
283 else
284 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
285 SkipUntil(tok::semi);
John McCalld226f652010-08-21 09:40:31 +0000286 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000287}
288
289/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000290/// angle brackets. Depth is the depth of this template-parameter-list, which
291/// is the number of template headers directly enclosing this template header.
292/// TemplateParams is the current list of template parameters we're building.
293/// The template parameter we parse will be added to this list. LAngleLoc and
Mike Stump1eb44332009-09-09 15:08:12 +0000294/// RAngleLoc will receive the positions of the '<' and '>', respectively,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000295/// that enclose this template parameter list.
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000296///
297/// \returns true if an error occurred, false otherwise.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000298bool Parser::ParseTemplateParameters(unsigned Depth,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000299 SmallVectorImpl<Decl*> &TemplateParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000300 SourceLocation &LAngleLoc,
301 SourceLocation &RAngleLoc) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000302 // Get the template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +0000303 if (!Tok.is(tok::less)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000304 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000305 return true;
Douglas Gregoradcac882008-12-01 23:54:00 +0000306 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000307 LAngleLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Douglas Gregoradcac882008-12-01 23:54:00 +0000309 // Try to parse the template parameter list.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000310 if (Tok.is(tok::greater))
311 RAngleLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000312 else if (ParseTemplateParameterList(Depth, TemplateParams)) {
313 if (!Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000314 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000315 return true;
Douglas Gregoradcac882008-12-01 23:54:00 +0000316 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000317 RAngleLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000318 }
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000319 return false;
Douglas Gregoradcac882008-12-01 23:54:00 +0000320}
321
322/// ParseTemplateParameterList - Parse a template parameter list. If
323/// the parsing fails badly (i.e., closing bracket was left out), this
324/// will try to put the token stream in a reasonable position (closing
Mike Stump1eb44332009-09-09 15:08:12 +0000325/// a statement, etc.) and return false.
Douglas Gregoradcac882008-12-01 23:54:00 +0000326///
327/// template-parameter-list: [C++ temp]
328/// template-parameter
329/// template-parameter-list ',' template-parameter
Mike Stump1eb44332009-09-09 15:08:12 +0000330bool
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000331Parser::ParseTemplateParameterList(unsigned Depth,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000332 SmallVectorImpl<Decl*> &TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000333 while (1) {
John McCalld226f652010-08-21 09:40:31 +0000334 if (Decl *TmpParam
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000335 = ParseTemplateParameter(Depth, TemplateParams.size())) {
336 TemplateParams.push_back(TmpParam);
337 } else {
Douglas Gregoradcac882008-12-01 23:54:00 +0000338 // If we failed to parse a template parameter, skip until we find
339 // a comma or closing brace.
340 SkipUntil(tok::comma, tok::greater, true, true);
341 }
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Douglas Gregoradcac882008-12-01 23:54:00 +0000343 // Did we find a comma or the end of the template parmeter list?
Mike Stump1eb44332009-09-09 15:08:12 +0000344 if (Tok.is(tok::comma)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000345 ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000346 } else if (Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000347 // Don't consume this... that's done by template parser.
348 break;
349 } else {
350 // Somebody probably forgot to close the template. Skip ahead and
351 // try to get out of the expression. This error is currently
352 // subsumed by whatever goes on in ParseTemplateParameter.
353 // TODO: This could match >>, and it would be nice to avoid those
354 // silly errors with template <vec<T>>.
Douglas Gregor99ea7342010-10-15 01:15:58 +0000355 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Douglas Gregoradcac882008-12-01 23:54:00 +0000356 SkipUntil(tok::greater, true, true);
357 return false;
358 }
359 }
360 return true;
361}
362
Douglas Gregor98440b42009-11-21 02:07:55 +0000363/// \brief Determine whether the parser is at the start of a template
364/// type parameter.
365bool Parser::isStartOfTemplateTypeParameter() {
Douglas Gregor7b6d25b2010-06-04 07:30:15 +0000366 if (Tok.is(tok::kw_class)) {
367 // "class" may be the start of an elaborated-type-specifier or a
368 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
369 switch (NextToken().getKind()) {
370 case tok::equal:
371 case tok::comma:
372 case tok::greater:
373 case tok::greatergreater:
374 case tok::ellipsis:
375 return true;
376
377 case tok::identifier:
378 // This may be either a type-parameter or an elaborated-type-specifier.
379 // We have to look further.
380 break;
381
382 default:
383 return false;
384 }
385
386 switch (GetLookAheadToken(2).getKind()) {
387 case tok::equal:
388 case tok::comma:
389 case tok::greater:
390 case tok::greatergreater:
391 return true;
392
393 default:
394 return false;
395 }
396 }
Douglas Gregor98440b42009-11-21 02:07:55 +0000397
398 if (Tok.isNot(tok::kw_typename))
399 return false;
400
401 // C++ [temp.param]p2:
402 // There is no semantic difference between class and typename in a
403 // template-parameter. typename followed by an unqualified-id
404 // names a template type parameter. typename followed by a
405 // qualified-id denotes the type in a non-type
406 // parameter-declaration.
407 Token Next = NextToken();
408
409 // If we have an identifier, skip over it.
410 if (Next.getKind() == tok::identifier)
411 Next = GetLookAheadToken(2);
412
413 switch (Next.getKind()) {
414 case tok::equal:
415 case tok::comma:
416 case tok::greater:
417 case tok::greatergreater:
418 case tok::ellipsis:
419 return true;
420
421 default:
422 return false;
423 }
424}
425
Douglas Gregoradcac882008-12-01 23:54:00 +0000426/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
427///
428/// template-parameter: [C++ temp.param]
429/// type-parameter
430/// parameter-declaration
431///
432/// type-parameter: (see below)
Douglas Gregor61c4d282011-01-05 15:48:55 +0000433/// 'class' ...[opt] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000434/// 'class' identifier[opt] '=' type-id
Douglas Gregor61c4d282011-01-05 15:48:55 +0000435/// 'typename' ...[opt] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000436/// 'typename' identifier[opt] '=' type-id
Douglas Gregor61c4d282011-01-05 15:48:55 +0000437/// 'template' '<' template-parameter-list '>'
438/// 'class' ...[opt] identifier[opt]
439/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
440/// = id-expression
John McCalld226f652010-08-21 09:40:31 +0000441Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor98440b42009-11-21 02:07:55 +0000442 if (isStartOfTemplateTypeParameter())
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000443 return ParseTypeParameter(Depth, Position);
Mike Stump1eb44332009-09-09 15:08:12 +0000444
445 if (Tok.is(tok::kw_template))
Chris Lattner532e19b2009-01-04 23:51:17 +0000446 return ParseTemplateTemplateParameter(Depth, Position);
447
448 // If it's none of the above, then it must be a parameter declaration.
449 // NOTE: This will pick up errors in the closure of the template parameter
450 // list (e.g., template < ; Check here to implement >> style closures.
451 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000452}
453
454/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
455/// Other kinds of template parameters are parsed in
456/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
457///
458/// type-parameter: [C++ temp.param]
Anders Carlssonce5635a2009-06-12 23:09:56 +0000459/// 'class' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000460/// 'class' identifier[opt] '=' type-id
Anders Carlssonce5635a2009-06-12 23:09:56 +0000461/// 'typename' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000462/// 'typename' identifier[opt] '=' type-id
John McCalld226f652010-08-21 09:40:31 +0000463Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000464 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
Mike Stump1eb44332009-09-09 15:08:12 +0000465 "A type-parameter starts with 'class' or 'typename'");
Douglas Gregor26236e82008-12-02 00:41:28 +0000466
467 // Consume the 'class' or 'typename' keyword.
468 bool TypenameKeyword = Tok.is(tok::kw_typename);
469 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000470
Anders Carlsson941df7d2009-06-12 19:58:00 +0000471 // Grab the ellipsis (if given).
472 bool Ellipsis = false;
473 SourceLocation EllipsisLoc;
Anders Carlssonce5635a2009-06-12 23:09:56 +0000474 if (Tok.is(tok::ellipsis)) {
Anders Carlsson941df7d2009-06-12 19:58:00 +0000475 Ellipsis = true;
476 EllipsisLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Richard Smithe5acd132011-10-14 20:31:37 +0000478 Diag(EllipsisLoc,
479 getLang().CPlusPlus0x
480 ? diag::warn_cxx98_compat_variadic_templates
481 : diag::ext_variadic_templates);
Anders Carlsson941df7d2009-06-12 19:58:00 +0000482 }
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Douglas Gregoradcac882008-12-01 23:54:00 +0000484 // Grab the template parameter name (if given)
Douglas Gregor26236e82008-12-02 00:41:28 +0000485 SourceLocation NameLoc;
486 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000487 if (Tok.is(tok::identifier)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000488 ParamName = Tok.getIdentifierInfo();
489 NameLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000490 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
491 Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000492 // Unnamed template parameter. Don't have to do anything here, just
493 // don't consume this token.
494 } else {
495 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000496 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000497 }
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000499 // Grab a default argument (if available).
500 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
501 // we introduce the type parameter into the local scope.
502 SourceLocation EqualLoc;
John McCallb3d87482010-08-24 05:47:05 +0000503 ParsedType DefaultArg;
Mike Stump1eb44332009-09-09 15:08:12 +0000504 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000505 EqualLoc = ConsumeToken();
506 DefaultArg = ParseTypeName().get();
Douglas Gregoradcac882008-12-01 23:54:00 +0000507 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000508
Douglas Gregor23c94db2010-07-02 17:43:08 +0000509 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000510 EllipsisLoc, KeyLoc, ParamName, NameLoc,
511 Depth, Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000512}
513
514/// ParseTemplateTemplateParameter - Handle the parsing of template
Mike Stump1eb44332009-09-09 15:08:12 +0000515/// template parameters.
Douglas Gregoradcac882008-12-01 23:54:00 +0000516///
517/// type-parameter: [C++ temp.param]
Douglas Gregor61c4d282011-01-05 15:48:55 +0000518/// 'template' '<' template-parameter-list '>' 'class'
519/// ...[opt] identifier[opt]
520/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
521/// = id-expression
John McCalld226f652010-08-21 09:40:31 +0000522Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000523Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000524 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
525
526 // Handle the template <...> part.
527 SourceLocation TemplateLoc = ConsumeToken();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000528 SmallVector<Decl*,8> TemplateParams;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000529 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor68c69932009-02-10 19:52:54 +0000530 {
531 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000532 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000533 RAngleLoc)) {
John McCalld226f652010-08-21 09:40:31 +0000534 return 0;
Douglas Gregor68c69932009-02-10 19:52:54 +0000535 }
Douglas Gregoradcac882008-12-01 23:54:00 +0000536 }
537
538 // Generate a meaningful error if the user forgot to put class before the
539 // identifier, comma, or greater.
Mike Stump1eb44332009-09-09 15:08:12 +0000540 if (!Tok.is(tok::kw_class)) {
541 Diag(Tok.getLocation(), diag::err_expected_class_before)
Douglas Gregoradcac882008-12-01 23:54:00 +0000542 << PP.getSpelling(Tok);
John McCalld226f652010-08-21 09:40:31 +0000543 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000544 }
Jeffrey Yasskindec09842011-01-18 02:00:16 +0000545 ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000546
Douglas Gregor61c4d282011-01-05 15:48:55 +0000547 // Parse the ellipsis, if given.
548 SourceLocation EllipsisLoc;
549 if (Tok.is(tok::ellipsis)) {
550 EllipsisLoc = ConsumeToken();
551
Richard Smithe5acd132011-10-14 20:31:37 +0000552 Diag(EllipsisLoc,
553 getLang().CPlusPlus0x
554 ? diag::warn_cxx98_compat_variadic_templates
555 : diag::ext_variadic_templates);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000556 }
557
Douglas Gregoradcac882008-12-01 23:54:00 +0000558 // Get the identifier, if given.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000559 SourceLocation NameLoc;
560 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000561 if (Tok.is(tok::identifier)) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000562 ParamName = Tok.getIdentifierInfo();
563 NameLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000564 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000565 // Unnamed template parameter. Don't have to do anything here, just
566 // don't consume this token.
567 } else {
568 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000569 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000570 }
571
Richard Trieu90ab75b2011-09-09 03:18:59 +0000572 TemplateParameterList *ParamList =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000573 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
574 TemplateLoc, LAngleLoc,
Douglas Gregor369ea272010-10-21 17:26:49 +0000575 TemplateParams.data(),
Douglas Gregorddc29e12009-02-06 22:42:48 +0000576 TemplateParams.size(),
577 RAngleLoc);
578
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000579 // Grab a default argument (if available).
580 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
581 // we introduce the template parameter into the local scope.
582 SourceLocation EqualLoc;
583 ParsedTemplateArgument DefaultArg;
Douglas Gregord684b002009-02-10 19:49:53 +0000584 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000585 EqualLoc = ConsumeToken();
586 DefaultArg = ParseTemplateTemplateArgument();
587 if (DefaultArg.isInvalid()) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000588 Diag(Tok.getLocation(),
589 diag::err_default_template_template_parameter_not_template);
Nuno Lopes68f7a242009-12-10 00:07:02 +0000590 static const tok::TokenKind EndToks[] = {
Douglas Gregor788cd062009-11-11 01:00:40 +0000591 tok::comma, tok::greater, tok::greatergreater
592 };
593 SkipUntil(EndToks, 3, true, true);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000594 }
Douglas Gregord684b002009-02-10 19:49:53 +0000595 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000596
Douglas Gregor23c94db2010-07-02 17:43:08 +0000597 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000598 ParamList, EllipsisLoc,
599 ParamName, NameLoc, Depth,
600 Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000601}
602
603/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
Mike Stump1eb44332009-09-09 15:08:12 +0000604/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000605///
Douglas Gregoradcac882008-12-01 23:54:00 +0000606/// template-parameter:
607/// ...
608/// parameter-declaration
John McCalld226f652010-08-21 09:40:31 +0000609Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000610Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000611 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor26236e82008-12-02 00:41:28 +0000612 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregoradcac882008-12-01 23:54:00 +0000613 // declarators (parts of declarators?) are accepted for parameters.
John McCall0b7e6782011-03-24 11:26:52 +0000614 DeclSpec DS(AttrFactory);
Douglas Gregor26236e82008-12-02 00:41:28 +0000615 ParseDeclarationSpecifiers(DS);
Douglas Gregoradcac882008-12-01 23:54:00 +0000616
617 // Parse this as a typename.
Douglas Gregor26236e82008-12-02 00:41:28 +0000618 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
619 ParseDeclarator(ParamDecl);
John McCallb3d87482010-08-24 05:47:05 +0000620 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000621 // This probably shouldn't happen - and it's more of a Sema thing, but
622 // basically we didn't parse the type name because we couldn't associate
623 // it with an AST node. we should just skip to the comma or greater.
624 // TODO: This is currently a placeholder for some kind of Sema Error.
625 Diag(Tok.getLocation(), diag::err_parse_error);
626 SkipUntil(tok::comma, tok::greater, true, true);
John McCalld226f652010-08-21 09:40:31 +0000627 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000628 }
629
Douglas Gregord684b002009-02-10 19:49:53 +0000630 // If there is a default value, parse it.
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000631 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
632 // we introduce the template parameter into the local scope.
633 SourceLocation EqualLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000634 ExprResult DefaultArg;
Chris Lattner7452c6f2009-01-05 01:24:05 +0000635 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000636 EqualLoc = ConsumeToken();
Douglas Gregord684b002009-02-10 19:49:53 +0000637
638 // C++ [temp.param]p15:
639 // When parsing a default template-argument for a non-type
640 // template-parameter, the first non-nested > is taken as the
641 // end of the template-parameter-list rather than a greater-than
642 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +0000643 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000644
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000645 DefaultArg = ParseAssignmentExpression();
Douglas Gregord684b002009-02-10 19:49:53 +0000646 if (DefaultArg.isInvalid())
647 SkipUntil(tok::comma, tok::greater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000648 }
Mike Stump1eb44332009-09-09 15:08:12 +0000649
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000650 // Create the parameter.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000651 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000652 Depth, Position, EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000653 DefaultArg.take());
Douglas Gregoradcac882008-12-01 23:54:00 +0000654}
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000655
Douglas Gregorcc636682009-02-17 23:15:12 +0000656/// \brief Parses a template-id that after the template name has
657/// already been parsed.
658///
659/// This routine takes care of parsing the enclosed template argument
660/// list ('<' template-parameter-list [opt] '>') and placing the
661/// results into a form that can be transferred to semantic analysis.
662///
663/// \param Template the template declaration produced by isTemplateName
664///
665/// \param TemplateNameLoc the source location of the template name
666///
667/// \param SS if non-NULL, the nested-name-specifier preceding the
668/// template name.
669///
670/// \param ConsumeLastToken if true, then we will consume the last
671/// token that forms the template-id. Otherwise, we will leave the
672/// last token in the stream (e.g., so that it can be replaced with an
673/// annotation token).
Mike Stump1eb44332009-09-09 15:08:12 +0000674bool
Douglas Gregor7532dc62009-03-30 22:58:21 +0000675Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
Mike Stump1eb44332009-09-09 15:08:12 +0000676 SourceLocation TemplateNameLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +0000677 const CXXScopeSpec &SS,
Douglas Gregorcc636682009-02-17 23:15:12 +0000678 bool ConsumeLastToken,
679 SourceLocation &LAngleLoc,
680 TemplateArgList &TemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +0000681 SourceLocation &RAngleLoc) {
682 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
683
684 // Consume the '<'.
685 LAngleLoc = ConsumeToken();
686
687 // Parse the optional template-argument-list.
688 bool Invalid = false;
689 {
690 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Douglas Gregor4f3018e2011-01-11 00:45:18 +0000691 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
Douglas Gregor314b97f2009-11-10 19:49:08 +0000692 Invalid = ParseTemplateArgumentList(TemplateArgs);
Douglas Gregorcc636682009-02-17 23:15:12 +0000693
694 if (Invalid) {
695 // Try to find the closing '>'.
696 SkipUntil(tok::greater, true, !ConsumeLastToken);
697
698 return true;
699 }
700 }
701
Eli Friedman64a4eb22009-12-27 22:31:18 +0000702 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) {
703 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregorcc636682009-02-17 23:15:12 +0000704 return true;
Eli Friedman64a4eb22009-12-27 22:31:18 +0000705 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000706
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000707 // Determine the location of the '>' or '>>'. Only consume this
708 // token if the caller asked us to.
Douglas Gregorcc636682009-02-17 23:15:12 +0000709 RAngleLoc = Tok.getLocation();
710
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000711 if (Tok.is(tok::greatergreater)) {
Richard Smith7fe62082011-10-15 05:09:34 +0000712 const char *ReplaceStr = "> >";
713 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
714 ReplaceStr = "> > ";
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000715
Richard Smith7fe62082011-10-15 05:09:34 +0000716 Diag(Tok.getLocation(), getLang().CPlusPlus0x ?
717 diag::warn_cxx98_compat_two_right_angle_brackets :
718 diag::err_two_right_angle_brackets_need_space)
719 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()),
720 ReplaceStr);
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000721
722 Tok.setKind(tok::greater);
723 if (!ConsumeLastToken) {
724 // Since we're not supposed to consume the '>>' token, we need
725 // to insert a second '>' token after the first.
726 PP.EnterToken(Tok);
727 }
728 } else if (ConsumeLastToken)
Douglas Gregorcc636682009-02-17 23:15:12 +0000729 ConsumeToken();
730
731 return false;
732}
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Douglas Gregor39a8de12009-02-25 19:37:18 +0000734/// \brief Replace the tokens that form a simple-template-id with an
735/// annotation token containing the complete template-id.
736///
737/// The first token in the stream must be the name of a template that
738/// is followed by a '<'. This routine will parse the complete
739/// simple-template-id and replace the tokens with a single annotation
740/// token with one of two different kinds: if the template-id names a
741/// type (and \p AllowTypeAnnotation is true), the annotation token is
742/// a type annotation that includes the optional nested-name-specifier
743/// (\p SS). Otherwise, the annotation token is a template-id
744/// annotation that does not include the optional
745/// nested-name-specifier.
746///
747/// \param Template the declaration of the template named by the first
748/// token (an identifier), as returned from \c Action::isTemplateName().
749///
750/// \param TemplateNameKind the kind of template that \p Template
751/// refers to, as returned from \c Action::isTemplateName().
752///
753/// \param SS if non-NULL, the nested-name-specifier that precedes
754/// this template name.
755///
756/// \param TemplateKWLoc if valid, specifies that this template-id
757/// annotation was preceded by the 'template' keyword and gives the
758/// location of that keyword. If invalid (the default), then this
759/// template-id was not preceded by a 'template' keyword.
760///
761/// \param AllowTypeAnnotation if true (the default), then a
762/// simple-template-id that refers to a class template, template
763/// template parameter, or other template that produces a type will be
764/// replaced with a type annotation token. Otherwise, the
765/// simple-template-id is always replaced with a template-id
766/// annotation token.
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000767///
768/// If an unrecoverable parse error occurs and no annotation token can be
769/// formed, this function returns true.
770///
771bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Douglas Gregor059101f2011-03-02 00:47:37 +0000772 CXXScopeSpec &SS,
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000773 UnqualifiedId &TemplateName,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000774 SourceLocation TemplateKWLoc,
775 bool AllowTypeAnnotation) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000776 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000777 assert(Template && Tok.is(tok::less) &&
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000778 "Parser isn't at the beginning of a template-id");
779
780 // Consume the template-name.
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000781 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000782
Douglas Gregorcc636682009-02-17 23:15:12 +0000783 // Parse the enclosed template argument list.
784 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000785 TemplateArgList TemplateArgs;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000786 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
787 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000788 SS, false, LAngleLoc,
789 TemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +0000790 RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000791
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000792 if (Invalid) {
793 // If we failed to parse the template ID but skipped ahead to a >, we're not
794 // going to be able to form a token annotation. Eat the '>' if present.
795 if (Tok.is(tok::greater))
796 ConsumeToken();
797 return true;
798 }
Douglas Gregorc15cb382009-02-09 23:23:08 +0000799
Jay Foadbeaaccd2009-05-21 09:52:38 +0000800 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
Douglas Gregorcc636682009-02-17 23:15:12 +0000801 TemplateArgs.size());
Douglas Gregorf02da892009-02-09 21:04:56 +0000802
Douglas Gregor55f6b142009-02-09 18:46:07 +0000803 // Build the annotation token.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000804 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
John McCallf312b1e2010-08-26 23:41:50 +0000805 TypeResult Type
Douglas Gregor059101f2011-03-02 00:47:37 +0000806 = Actions.ActOnTemplateIdType(SS,
807 Template, TemplateNameLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000808 LAngleLoc, TemplateArgsPtr,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000809 RAngleLoc);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000810 if (Type.isInvalid()) {
811 // If we failed to parse the template ID but skipped ahead to a >, we're not
812 // going to be able to form a token annotation. Eat the '>' if present.
813 if (Tok.is(tok::greater))
814 ConsumeToken();
815 return true;
816 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000817
818 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000819 setTypeAnnotation(Tok, Type.get());
Douglas Gregor059101f2011-03-02 00:47:37 +0000820 if (SS.isNotEmpty())
821 Tok.setLocation(SS.getBeginLoc());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000822 else if (TemplateKWLoc.isValid())
823 Tok.setLocation(TemplateKWLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000824 else
Douglas Gregor39a8de12009-02-25 19:37:18 +0000825 Tok.setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +0000826 } else {
Douglas Gregorc45c2322009-03-31 00:43:58 +0000827 // Build a template-id annotation token that can be processed
828 // later.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000829 Tok.setKind(tok::annot_template_id);
Mike Stump1eb44332009-09-09 15:08:12 +0000830 TemplateIdAnnotation *TemplateId
Douglas Gregor39a8de12009-02-25 19:37:18 +0000831 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
Douglas Gregor55f6b142009-02-09 18:46:07 +0000832 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000833 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
834 TemplateId->Name = TemplateName.Identifier;
835 TemplateId->Operator = OO_None;
836 } else {
837 TemplateId->Name = 0;
838 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
839 }
Douglas Gregor059101f2011-03-02 00:47:37 +0000840 TemplateId->SS = SS;
John McCall2b5289b2010-08-23 07:28:44 +0000841 TemplateId->Template = Template;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000842 TemplateId->Kind = TNK;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000843 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000844 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregor314b97f2009-11-10 19:49:08 +0000845 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
846 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
Douglas Gregorc34348a2011-02-24 17:54:50 +0000847 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000848 Tok.setAnnotationValue(TemplateId);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000849 if (TemplateKWLoc.isValid())
850 Tok.setLocation(TemplateKWLoc);
851 else
852 Tok.setLocation(TemplateNameLoc);
853
854 TemplateArgsPtr.release();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000855 }
856
857 // Common fields for the annotation token
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000858 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000859
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000860 // In case the tokens were cached, have Preprocessor replace them with the
861 // annotation token.
862 PP.AnnotateCachedTokens(Tok);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000863 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000864}
865
Douglas Gregor39a8de12009-02-25 19:37:18 +0000866/// \brief Replaces a template-id annotation token with a type
867/// annotation token.
868///
Douglas Gregor31a19b62009-04-01 21:51:26 +0000869/// If there was a failure when forming the type from the template-id,
870/// a type annotation token will still be created, but will have a
871/// NULL type pointer to signify an error.
Douglas Gregor059101f2011-03-02 00:47:37 +0000872void Parser::AnnotateTemplateIdTokenAsType() {
Douglas Gregor39a8de12009-02-25 19:37:18 +0000873 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
874
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +0000875 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000876 assert((TemplateId->Kind == TNK_Type_template ||
877 TemplateId->Kind == TNK_Dependent_template_name) &&
878 "Only works for type and dependent templates");
Mike Stump1eb44332009-09-09 15:08:12 +0000879
880 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000881 TemplateId->getTemplateArgs(),
Douglas Gregor39a8de12009-02-25 19:37:18 +0000882 TemplateId->NumArgs);
883
John McCallf312b1e2010-08-26 23:41:50 +0000884 TypeResult Type
Douglas Gregor059101f2011-03-02 00:47:37 +0000885 = Actions.ActOnTemplateIdType(TemplateId->SS,
886 TemplateId->Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000887 TemplateId->TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000888 TemplateId->LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000889 TemplateArgsPtr,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000890 TemplateId->RAngleLoc);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000891 // Create the new "type" annotation token.
892 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000893 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
Douglas Gregor059101f2011-03-02 00:47:37 +0000894 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
895 Tok.setLocation(TemplateId->SS.getBeginLoc());
Sebastian Redl39d67112010-02-08 19:35:18 +0000896 // End location stays the same
Douglas Gregor39a8de12009-02-25 19:37:18 +0000897
Douglas Gregor86235412009-11-04 18:18:19 +0000898 // Replace the template-id annotation token, and possible the scope-specifier
899 // that precedes it, with the typename annotation token.
900 PP.AnnotateCachedTokens(Tok);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000901}
902
Douglas Gregor314b97f2009-11-10 19:49:08 +0000903/// \brief Determine whether the given token can end a template argument.
Benjamin Kramer3a4a2b32009-11-10 21:29:56 +0000904static bool isEndOfTemplateArgument(Token Tok) {
Douglas Gregor314b97f2009-11-10 19:49:08 +0000905 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
906 Tok.is(tok::greatergreater);
907}
908
Douglas Gregor788cd062009-11-11 01:00:40 +0000909/// \brief Parse a C++ template template argument.
910ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
911 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
912 !Tok.is(tok::annot_cxxscope))
913 return ParsedTemplateArgument();
914
915 // C++0x [temp.arg.template]p1:
916 // A template-argument for a template template-parameter shall be the name
Richard Smith3e4c6c42011-05-05 21:57:07 +0000917 // of a class template or an alias template, expressed as id-expression.
Douglas Gregor788cd062009-11-11 01:00:40 +0000918 //
Richard Smith3e4c6c42011-05-05 21:57:07 +0000919 // We parse an id-expression that refers to a class template or alias
920 // template. The grammar we parse is:
Douglas Gregor788cd062009-11-11 01:00:40 +0000921 //
Douglas Gregorec5e6962011-01-05 17:33:50 +0000922 // nested-name-specifier[opt] template[opt] identifier ...[opt]
Douglas Gregor788cd062009-11-11 01:00:40 +0000923 //
924 // followed by a token that terminates a template argument, such as ',',
925 // '>', or (in some cases) '>>'.
Douglas Gregor788cd062009-11-11 01:00:40 +0000926 CXXScopeSpec SS; // nested-name-specifier, if present
John McCallb3d87482010-08-24 05:47:05 +0000927 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000928 /*EnteringContext=*/false);
929
Douglas Gregorec5e6962011-01-05 17:33:50 +0000930 ParsedTemplateArgument Result;
931 SourceLocation EllipsisLoc;
Douglas Gregor788cd062009-11-11 01:00:40 +0000932 if (SS.isSet() && Tok.is(tok::kw_template)) {
933 // Parse the optional 'template' keyword following the
934 // nested-name-specifier.
935 SourceLocation TemplateLoc = ConsumeToken();
936
937 if (Tok.is(tok::identifier)) {
938 // We appear to have a dependent template name.
939 UnqualifiedId Name;
940 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
941 ConsumeToken(); // the identifier
942
Douglas Gregorec5e6962011-01-05 17:33:50 +0000943 // Parse the ellipsis.
944 if (Tok.is(tok::ellipsis))
945 EllipsisLoc = ConsumeToken();
946
Douglas Gregor788cd062009-11-11 01:00:40 +0000947 // If the next token signals the end of a template argument,
948 // then we have a dependent template name that could be a template
949 // template argument.
Douglas Gregord6ab2322010-06-16 23:00:59 +0000950 TemplateTy Template;
951 if (isEndOfTemplateArgument(Tok) &&
John McCallb3d87482010-08-24 05:47:05 +0000952 Actions.ActOnDependentTemplateName(getCurScope(), TemplateLoc,
953 SS, Name,
954 /*ObjectType=*/ ParsedType(),
Douglas Gregord6ab2322010-06-16 23:00:59 +0000955 /*EnteringContext=*/false,
956 Template))
Douglas Gregorec5e6962011-01-05 17:33:50 +0000957 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregord6ab2322010-06-16 23:00:59 +0000958 }
Douglas Gregor788cd062009-11-11 01:00:40 +0000959 } else if (Tok.is(tok::identifier)) {
960 // We may have a (non-dependent) template name.
961 TemplateTy Template;
962 UnqualifiedId Name;
963 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
964 ConsumeToken(); // the identifier
965
Douglas Gregorec5e6962011-01-05 17:33:50 +0000966 // Parse the ellipsis.
967 if (Tok.is(tok::ellipsis))
968 EllipsisLoc = ConsumeToken();
969
Douglas Gregor788cd062009-11-11 01:00:40 +0000970 if (isEndOfTemplateArgument(Tok)) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000971 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +0000972 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
973 /*hasTemplateKeyword=*/false,
974 Name,
John McCallb3d87482010-08-24 05:47:05 +0000975 /*ObjectType=*/ ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000976 /*EnteringContext=*/false,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000977 Template,
978 MemberOfUnknownSpecialization);
Douglas Gregor788cd062009-11-11 01:00:40 +0000979 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
980 // We have an id-expression that refers to a class template or
Richard Smith3e4c6c42011-05-05 21:57:07 +0000981 // (C++0x) alias template.
Douglas Gregorec5e6962011-01-05 17:33:50 +0000982 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregor788cd062009-11-11 01:00:40 +0000983 }
984 }
985 }
986
Douglas Gregorec5e6962011-01-05 17:33:50 +0000987 // If this is a pack expansion, build it as such.
988 if (EllipsisLoc.isValid() && !Result.isInvalid())
989 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
990
991 return Result;
Douglas Gregor788cd062009-11-11 01:00:40 +0000992}
993
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000994/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
995///
996/// template-argument: [C++ 14.2]
Douglas Gregorac7610d2009-06-22 20:57:11 +0000997/// constant-expression
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000998/// type-id
999/// id-expression
Douglas Gregor314b97f2009-11-10 19:49:08 +00001000ParsedTemplateArgument Parser::ParseTemplateArgument() {
Douglas Gregor55f6b142009-02-09 18:46:07 +00001001 // C++ [temp.arg]p2:
1002 // In a template-argument, an ambiguity between a type-id and an
1003 // expression is resolved to a type-id, regardless of the form of
1004 // the corresponding template-parameter.
1005 //
Douglas Gregor314b97f2009-11-10 19:49:08 +00001006 // Therefore, we initially try to parse a type-id.
Douglas Gregor8b642592009-02-10 00:53:15 +00001007 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor314b97f2009-11-10 19:49:08 +00001008 SourceLocation Loc = Tok.getLocation();
Douglas Gregor683a81f2011-01-31 16:09:46 +00001009 TypeResult TypeArg = ParseTypeName(/*Range=*/0,
1010 Declarator::TemplateTypeArgContext);
Douglas Gregor809070a2009-02-18 17:45:20 +00001011 if (TypeArg.isInvalid())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001012 return ParsedTemplateArgument();
1013
John McCallb3d87482010-08-24 05:47:05 +00001014 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1015 TypeArg.get().getAsOpaquePtr(),
Douglas Gregor314b97f2009-11-10 19:49:08 +00001016 Loc);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001017 }
Douglas Gregor788cd062009-11-11 01:00:40 +00001018
1019 // Try to parse a template template argument.
Douglas Gregoreaf75f42009-11-12 00:03:40 +00001020 {
1021 TentativeParsingAction TPA(*this);
1022
1023 ParsedTemplateArgument TemplateTemplateArgument
1024 = ParseTemplateTemplateArgument();
1025 if (!TemplateTemplateArgument.isInvalid()) {
1026 TPA.Commit();
1027 return TemplateTemplateArgument;
1028 }
1029
1030 // Revert this tentative parse to parse a non-type template argument.
1031 TPA.Revert();
1032 }
Douglas Gregor314b97f2009-11-10 19:49:08 +00001033
1034 // Parse a non-type template argument.
1035 SourceLocation Loc = Tok.getLocation();
John McCall60d7b3a2010-08-24 06:29:42 +00001036 ExprResult ExprArg = ParseConstantExpression();
Douglas Gregorc15cb382009-02-09 23:23:08 +00001037 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001038 return ParsedTemplateArgument();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001039
Douglas Gregor314b97f2009-11-10 19:49:08 +00001040 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1041 ExprArg.release(), Loc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001042}
1043
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001044/// \brief Determine whether the current tokens can only be parsed as a
1045/// template argument list (starting with the '<') and never as a '<'
1046/// expression.
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001047bool Parser::IsTemplateArgumentList(unsigned Skip) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001048 struct AlwaysRevertAction : TentativeParsingAction {
1049 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1050 ~AlwaysRevertAction() { Revert(); }
1051 } Tentative(*this);
1052
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001053 while (Skip) {
1054 ConsumeToken();
1055 --Skip;
1056 }
1057
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001058 // '<'
1059 if (!Tok.is(tok::less))
1060 return false;
1061 ConsumeToken();
1062
1063 // An empty template argument list.
1064 if (Tok.is(tok::greater))
1065 return true;
1066
1067 // See whether we have declaration specifiers, which indicate a type.
1068 while (isCXXDeclarationSpecifier() == TPResult::True())
1069 ConsumeToken();
1070
1071 // If we have a '>' or a ',' then this is a template argument list.
1072 return Tok.is(tok::greater) || Tok.is(tok::comma);
1073}
1074
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001075/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1076/// (C++ [temp.names]). Returns true if there was an error.
1077///
1078/// template-argument-list: [C++ 14.2]
1079/// template-argument
1080/// template-argument-list ',' template-argument
Mike Stump1eb44332009-09-09 15:08:12 +00001081bool
Douglas Gregor314b97f2009-11-10 19:49:08 +00001082Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001083 while (true) {
Douglas Gregor314b97f2009-11-10 19:49:08 +00001084 ParsedTemplateArgument Arg = ParseTemplateArgument();
Douglas Gregor7536dd52010-12-20 02:24:11 +00001085 if (Tok.is(tok::ellipsis)) {
1086 SourceLocation EllipsisLoc = ConsumeToken();
1087 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1088 }
1089
Douglas Gregor314b97f2009-11-10 19:49:08 +00001090 if (Arg.isInvalid()) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001091 SkipUntil(tok::comma, tok::greater, true, true);
1092 return true;
1093 }
Douglas Gregor5908e9f2009-02-09 19:34:22 +00001094
Douglas Gregor314b97f2009-11-10 19:49:08 +00001095 // Save this template argument.
1096 TemplateArgs.push_back(Arg);
1097
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001098 // If the next token is a comma, consume it and keep reading
1099 // arguments.
1100 if (Tok.isNot(tok::comma)) break;
1101
1102 // Consume the comma.
1103 ConsumeToken();
1104 }
1105
Eli Friedman64a4eb22009-12-27 22:31:18 +00001106 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001107}
1108
Mike Stump1eb44332009-09-09 15:08:12 +00001109/// \brief Parse a C++ explicit template instantiation
Douglas Gregor1426e532009-05-12 21:31:51 +00001110/// (C++ [temp.explicit]).
1111///
1112/// explicit-instantiation:
Douglas Gregor45f96552009-09-04 06:33:52 +00001113/// 'extern' [opt] 'template' declaration
1114///
1115/// Note that the 'extern' is a GNU extension and C++0x feature.
John McCalld226f652010-08-21 09:40:31 +00001116Decl *Parser::ParseExplicitInstantiation(SourceLocation ExternLoc,
1117 SourceLocation TemplateLoc,
1118 SourceLocation &DeclEnd) {
John McCallc9068d72010-07-16 08:13:16 +00001119 // This isn't really required here.
1120 ParsingDeclRAIIObject ParsingTemplateParams(*this);
1121
Mike Stump1eb44332009-09-09 15:08:12 +00001122 return ParseSingleDeclarationAfterTemplate(Declarator::FileContext,
Douglas Gregor45f96552009-09-04 06:33:52 +00001123 ParsedTemplateInfo(ExternLoc,
1124 TemplateLoc),
John McCallc9068d72010-07-16 08:13:16 +00001125 ParsingTemplateParams,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +00001126 DeclEnd, AS_none);
Douglas Gregor1426e532009-05-12 21:31:51 +00001127}
John McCall78b81052010-11-10 02:40:36 +00001128
1129SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1130 if (TemplateParams)
1131 return getTemplateParamsRange(TemplateParams->data(),
1132 TemplateParams->size());
1133
1134 SourceRange R(TemplateLoc);
1135 if (ExternLoc.isValid())
1136 R.setBegin(ExternLoc);
1137 return R;
1138}
Francois Pichet8387e2a2011-04-22 22:18:13 +00001139
Francois Pichet4a47e8d2011-04-23 11:52:20 +00001140void Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001141 ((Parser*)P)->LateTemplateParser(FD);
1142}
1143
1144
Francois Pichet4a47e8d2011-04-23 11:52:20 +00001145void Parser::LateTemplateParser(const FunctionDecl *FD) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001146 LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD];
1147 if (LPT) {
1148 ParseLateTemplatedFuncDef(*LPT);
1149 return;
1150 }
1151
1152 llvm_unreachable("Late templated function without associated lexed tokens");
1153}
1154
1155/// \brief Late parse a C++ function template in Microsoft mode.
1156void Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) {
1157 if(!LMT.D)
1158 return;
1159
1160 // If this is a member template, introduce the template parameter scope.
1161 ParseScope TemplateScope(this, Scope::TemplateParamScope);
1162
1163 // Get the FunctionDecl.
1164 FunctionDecl *FD = 0;
1165 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(LMT.D))
1166 FD = FunTmpl->getTemplatedDecl();
1167 else
1168 FD = cast<FunctionDecl>(LMT.D);
1169
1170 // Reinject the template parameters.
Francois Pichetfdde4702011-09-22 22:14:56 +00001171 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
Francois Pichet8387e2a2011-04-22 22:18:13 +00001172 DeclaratorDecl* Declarator = dyn_cast<DeclaratorDecl>(FD);
1173 if (Declarator && Declarator->getNumTemplateParameterLists() != 0) {
1174 Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
1175 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1176 } else {
1177 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1178
Francois Pichetfdde4702011-09-22 22:14:56 +00001179 // Get the list of DeclContext to reenter.
1180 SmallVector<DeclContext*, 4> DeclContextToReenter;
Francois Pichet8387e2a2011-04-22 22:18:13 +00001181 DeclContext *DD = FD->getLexicalParent();
1182 while (DD && DD->isRecord()) {
Francois Pichetfdde4702011-09-22 22:14:56 +00001183 DeclContextToReenter.push_back(DD);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001184 DD = DD->getLexicalParent();
1185 }
Francois Pichetfdde4702011-09-22 22:14:56 +00001186
Francois Pichet901a9a42011-09-23 16:02:49 +00001187 // Reenter template scopes from outmost to innermost.
Francois Pichetfdde4702011-09-22 22:14:56 +00001188 SmallVector<DeclContext*, 4>::reverse_iterator II =
1189 DeclContextToReenter.rbegin();
1190 for (; II != DeclContextToReenter.rend(); ++II) {
1191 if (ClassTemplatePartialSpecializationDecl* MD =
1192 dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) {
Sebastian Redla891a322011-09-30 08:32:17 +00001193 TemplateParamScopeStack.push_back(new ParseScope(this,
1194 Scope::TemplateParamScope));
Francois Pichetfdde4702011-09-22 22:14:56 +00001195 Actions.ActOnReenterTemplateScope(getCurScope(), MD);
1196 } else if (CXXRecordDecl* MD = dyn_cast_or_null<CXXRecordDecl>(*II)) {
Sebastian Redla891a322011-09-30 08:32:17 +00001197 TemplateParamScopeStack.push_back(new ParseScope(this,
1198 Scope::TemplateParamScope,
1199 MD->getDescribedClassTemplate() != 0 ));
Francois Pichetfdde4702011-09-22 22:14:56 +00001200 Actions.ActOnReenterTemplateScope(getCurScope(),
1201 MD->getDescribedClassTemplate());
1202 }
1203 }
Francois Pichet8387e2a2011-04-22 22:18:13 +00001204 }
1205 assert(!LMT.Toks.empty() && "Empty body!");
1206
1207 // Append the current token at the end of the new token stream so that it
1208 // doesn't get lost.
1209 LMT.Toks.push_back(Tok);
1210 PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false);
1211
1212 // Consume the previously pushed token.
1213 ConsumeAnyToken();
1214 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1215 && "Inline method not starting with '{', ':' or 'try'");
1216
1217 // Parse the method body. Function body parsing code is similar enough
1218 // to be re-used for method bodies as well.
1219 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1220
1221 // Recreate the DeclContext.
1222 Sema::ContextRAII SavedContext(Actions, Actions.getContainingDC(FD));
1223
1224 if (FunctionTemplateDecl *FunctionTemplate
1225 = dyn_cast_or_null<FunctionTemplateDecl>(LMT.D))
1226 Actions.ActOnStartOfFunctionDef(getCurScope(),
1227 FunctionTemplate->getTemplatedDecl());
1228 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(LMT.D))
1229 Actions.ActOnStartOfFunctionDef(getCurScope(), Function);
1230
1231
1232 if (Tok.is(tok::kw_try)) {
1233 ParseFunctionTryBlock(LMT.D, FnScope);
Francois Pichetfdde4702011-09-22 22:14:56 +00001234 } else {
1235 if (Tok.is(tok::colon))
1236 ParseConstructorInitializer(LMT.D);
1237 else
1238 Actions.ActOnDefaultCtorInitializers(LMT.D);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001239
Francois Pichetfdde4702011-09-22 22:14:56 +00001240 if (Tok.is(tok::l_brace)) {
1241 ParseFunctionStatementBody(LMT.D, FnScope);
1242 Actions.MarkAsLateParsedTemplate(FD, false);
1243 } else
Francois Pichet8387e2a2011-04-22 22:18:13 +00001244 Actions.ActOnFinishFunctionBody(LMT.D, 0);
Francois Pichetfdde4702011-09-22 22:14:56 +00001245 }
Francois Pichet8387e2a2011-04-22 22:18:13 +00001246
Francois Pichetfdde4702011-09-22 22:14:56 +00001247 // Exit scopes.
1248 FnScope.Exit();
1249 SmallVector<ParseScope*, 4>::reverse_iterator I =
1250 TemplateParamScopeStack.rbegin();
1251 for (; I != TemplateParamScopeStack.rend(); ++I)
1252 delete *I;
Francois Pichet8387e2a2011-04-22 22:18:13 +00001253
1254 DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D);
1255 if (grp)
1256 Actions.getASTConsumer().HandleTopLevelDecl(grp.get());
1257}
1258
1259/// \brief Lex a delayed template function for late parsing.
1260void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1261 tok::TokenKind kind = Tok.getKind();
Sebastian Redla891a322011-09-30 08:32:17 +00001262 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1263 // Consume everything up to (and including) the matching right brace.
1264 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001265 }
Francois Pichet8387e2a2011-04-22 22:18:13 +00001266
1267 // If we're in a function-try-block, we need to store all the catch blocks.
1268 if (kind == tok::kw_try) {
1269 while (Tok.is(tok::kw_catch)) {
1270 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1271 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1272 }
1273 }
1274}