blob: 91cf8e81c2a48bff5ae1418af4aab8ebbf481d78 [file] [log] [blame]
Douglas Gregoreb31f392008-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 Lattner60f36222009-01-29 05:15:15 +000015#include "clang/Parse/ParseDiagnostic.h"
John McCall8b0666c2010-08-20 18:27:03 +000016#include "clang/Sema/DeclSpec.h"
17#include "clang/Sema/ParsedTemplate.h"
18#include "clang/Sema/Scope.h"
Chris Lattnerb2434d52009-12-10 00:45:15 +000019#include "RAIIObjectsForParser.h"
Francois Pichet1c229c02011-04-22 22:18:13 +000020#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/ASTConsumer.h"
Douglas Gregoreb31f392008-12-01 23:54:00 +000022using namespace clang;
23
Douglas Gregor1b57ff32009-05-12 23:25:50 +000024/// \brief Parse a template declaration, explicit instantiation, or
25/// explicit specialization.
John McCall48871652010-08-21 09:40:31 +000026Decl *
Douglas Gregor1b57ff32009-05-12 23:25:50 +000027Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
28 SourceLocation &DeclEnd,
Erik Verbruggenca98f2a2011-10-13 09:41:32 +000029 AccessSpecifier AS,
30 AttributeList *AccessAttrs) {
Fariborz Jahanian4bf82622011-08-22 17:59:19 +000031 ObjCDeclContextSwitch ObjCDC(*this);
32
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000033 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
Fariborz Jahanian4bf82622011-08-22 17:59:19 +000034 return ParseExplicitInstantiation(SourceLocation(), ConsumeToken(),
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000035 DeclEnd);
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +000036 }
Erik Verbruggenca98f2a2011-10-13 09:41:32 +000037 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
38 AccessAttrs);
Douglas Gregor1b57ff32009-05-12 23:25:50 +000039}
40
Douglas Gregora3dff8e2009-08-24 23:03:25 +000041/// \brief RAII class that manages the template parameter depth.
42namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +000043 class TemplateParameterDepthCounter {
Douglas Gregora3dff8e2009-08-24 23:03:25 +000044 unsigned &Depth;
45 unsigned AddedLevels;
46
47 public:
Mike Stump11289f42009-09-09 15:08:12 +000048 explicit TemplateParameterDepthCounter(unsigned &Depth)
Douglas Gregora3dff8e2009-08-24 23:03:25 +000049 : Depth(Depth), AddedLevels(0) { }
Mike Stump11289f42009-09-09 15:08:12 +000050
Douglas Gregora3dff8e2009-08-24 23:03:25 +000051 ~TemplateParameterDepthCounter() {
52 Depth -= AddedLevels;
53 }
Mike Stump11289f42009-09-09 15:08:12 +000054
55 void operator++() {
Douglas Gregora3dff8e2009-08-24 23:03:25 +000056 ++Depth;
57 ++AddedLevels;
58 }
Mike Stump11289f42009-09-09 15:08:12 +000059
Douglas Gregora3dff8e2009-08-24 23:03:25 +000060 operator unsigned() const { return Depth; }
61 };
62}
63
Douglas Gregor67a65642009-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 Gregoreb31f392008-12-01 23:54:00 +000073///
74/// template-declaration: [C++ temp]
75/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
Douglas Gregor67a65642009-02-17 23:15:12 +000076///
77/// explicit-specialization: [ C++ temp.expl.spec]
78/// 'template' '<' '>' declaration
John McCall48871652010-08-21 09:40:31 +000079Decl *
Anders Carlssondfbbdf62009-03-26 00:52:18 +000080Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
Chris Lattner49836b42009-04-02 04:16:50 +000081 SourceLocation &DeclEnd,
Erik Verbruggenca98f2a2011-10-13 09:41:32 +000082 AccessSpecifier AS,
83 AttributeList *AccessAttrs) {
Mike Stump11289f42009-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 Gregorf5586182008-12-02 00:41:28 +000087 // Enter template-parameter scope.
Douglas Gregor7307d6c2008-12-10 06:34:36 +000088 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Douglas Gregorf5586182008-12-02 00:41:28 +000089
John McCall796c2a52010-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 Gregorb9bd8a92008-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 Gregor67a65642009-02-17 23:15:12 +0000103 // lists to easily differentiate between the case above and:
Douglas Gregorb9bd8a92008-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 Gregor468535e2009-08-20 18:46:05 +0000115 bool isSpecialization = true;
Douglas Gregor1d0015f2009-10-30 22:09:44 +0000116 bool LastParamListWasEmpty = false;
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000117 TemplateParameterLists ParamLists;
Douglas Gregora3dff8e2009-08-24 23:03:25 +0000118 TemplateParameterDepthCounter Depth(TemplateParameterDepth);
Douglas Gregorb9bd8a92008-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 McCall48871652010-08-21 09:40:31 +0000132 return 0;
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000133 }
Mike Stump11289f42009-09-09 15:08:12 +0000134
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000135 // Parse the '<' template-parameter-list '>'
136 SourceLocation LAngleLoc, RAngleLoc;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000137 SmallVector<Decl*, 4> TemplateParams;
Mike Stump11289f42009-09-09 15:08:12 +0000138 if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc,
Douglas Gregore93e46c2009-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 McCall48871652010-08-21 09:40:31 +0000144 return 0;
Douglas Gregore93e46c2009-07-22 23:48:44 +0000145 }
Douglas Gregor1b57ff32009-05-12 23:25:50 +0000146
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000147 ParamLists.push_back(
Mike Stump11289f42009-09-09 15:08:12 +0000148 Actions.ActOnTemplateParameterList(Depth, ExportLoc,
149 TemplateLoc, LAngleLoc,
Jay Foad7d0479f2009-05-21 09:52:38 +0000150 TemplateParams.data(),
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000151 TemplateParams.size(), RAngleLoc));
Douglas Gregora3dff8e2009-08-24 23:03:25 +0000152
153 if (!TemplateParams.empty()) {
154 isSpecialization = false;
155 ++Depth;
Douglas Gregor1d0015f2009-10-30 22:09:44 +0000156 } else {
157 LastParamListWasEmpty = true;
Mike Stump11289f42009-09-09 15:08:12 +0000158 }
Douglas Gregorb9bd8a92008-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 Stump11289f42009-09-09 15:08:12 +0000162 return ParseSingleDeclarationAfterTemplate(Context,
Douglas Gregor1b57ff32009-05-12 23:25:50 +0000163 ParsedTemplateInfo(&ParamLists,
Douglas Gregor1d0015f2009-10-30 22:09:44 +0000164 isSpecialization,
165 LastParamListWasEmpty),
John McCall796c2a52010-07-16 08:13:16 +0000166 ParsingTemplateParams,
Erik Verbruggenca98f2a2011-10-13 09:41:32 +0000167 DeclEnd, AS, AccessAttrs);
Douglas Gregor23996282009-05-12 21:31:51 +0000168}
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000169
Douglas Gregor23996282009-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 McCall48871652010-08-21 09:40:31 +0000190Decl *
Douglas Gregor23996282009-05-12 21:31:51 +0000191Parser::ParseSingleDeclarationAfterTemplate(
192 unsigned Context,
Douglas Gregor1b57ff32009-05-12 23:25:50 +0000193 const ParsedTemplateInfo &TemplateInfo,
John McCall796c2a52010-07-16 08:13:16 +0000194 ParsingDeclRAIIObject &DiagsFromTParams,
Douglas Gregor23996282009-05-12 21:31:51 +0000195 SourceLocation &DeclEnd,
Erik Verbruggenca98f2a2011-10-13 09:41:32 +0000196 AccessSpecifier AS,
197 AttributeList *AccessAttrs) {
Douglas Gregor1b57ff32009-05-12 23:25:50 +0000198 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
199 "Template information required");
200
Douglas Gregor3447e762009-08-20 22:52:58 +0000201 if (Context == Declarator::MemberContext) {
202 // We are parsing a member template.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +0000203 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
204 &DiagsFromTParams);
John McCall48871652010-08-21 09:40:31 +0000205 return 0;
Douglas Gregor3447e762009-08-20 22:52:58 +0000206 }
Mike Stump11289f42009-09-09 15:08:12 +0000207
John McCall084e83d2011-03-24 11:26:52 +0000208 ParsedAttributesWithRange prefixAttrs(AttrFactory);
John McCall53fa7142010-12-24 02:08:15 +0000209 MaybeParseCXX0XAttributes(prefixAttrs);
John McCall9b72f892010-11-10 02:40:36 +0000210
211 if (Tok.is(tok::kw_using))
212 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
John McCall53fa7142010-12-24 02:08:15 +0000213 prefixAttrs);
John McCall9b72f892010-11-10 02:40:36 +0000214
John McCall796c2a52010-07-16 08:13:16 +0000215 // Parse the declaration specifiers, stealing the accumulated
216 // diagnostics from the template parameters.
John McCall084e83d2011-03-24 11:26:52 +0000217 ParsingDeclSpec DS(*this, &DiagsFromTParams);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000218
John McCall53fa7142010-12-24 02:08:15 +0000219 DS.takeAttributesFrom(prefixAttrs);
Alexis Hunt96d5c762009-11-21 08:43:09 +0000220
Douglas Gregor9de54ea2010-01-13 17:31:36 +0000221 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
222 getDeclSpecContextFromDeclaratorContext(Context));
Douglas Gregor23996282009-05-12 21:31:51 +0000223
224 if (Tok.is(tok::semi)) {
225 DeclEnd = ConsumeToken();
John McCall48871652010-08-21 09:40:31 +0000226 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
John McCall28a6aea2009-11-04 02:18:39 +0000227 DS.complete(Decl);
228 return Decl;
Douglas Gregor23996282009-05-12 21:31:51 +0000229 }
230
231 // Parse the declarator.
John McCall28a6aea2009-11-04 02:18:39 +0000232 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
Douglas Gregor23996282009-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 McCall48871652010-08-21 09:40:31 +0000240 return 0;
Douglas Gregor23996282009-05-12 21:31:51 +0000241 }
Mike Stump11289f42009-09-09 15:08:12 +0000242
Richard Smith675ea992011-11-29 05:27:40 +0000243 // Check for a stray semicolon in a function definition.
244 if (DeclaratorInfo.isFunctionDeclarator() && Tok.is(tok::semi) &&
245 Context == Declarator::FileContext) {
246 const Token &Next = NextToken();
247 if (Next.is(tok::l_brace) || Next.is(tok::kw_try) ||
248 Next.is(tok::equal) || Next.is(tok::colon)) {
249 SourceLocation SemiLoc = ConsumeToken();
250 Diag(SemiLoc, diag::err_stray_semi_function_definition)
251 << FixItHint::CreateRemoval(SemiLoc);
252 assert(!isDeclarationAfterDeclarator() &&
253 isStartOfFunctionDefinition(DeclaratorInfo));
254 }
255 }
256
Douglas Gregor23996282009-05-12 21:31:51 +0000257 // If we have a declaration or declarator list, handle it.
258 if (isDeclarationAfterDeclarator()) {
259 // Parse this declaration.
John McCall48871652010-08-21 09:40:31 +0000260 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
261 TemplateInfo);
Douglas Gregor23996282009-05-12 21:31:51 +0000262
263 if (Tok.is(tok::comma)) {
264 Diag(Tok, diag::err_multiple_template_declarators)
Douglas Gregor1b57ff32009-05-12 23:25:50 +0000265 << (int)TemplateInfo.Kind;
Douglas Gregor23996282009-05-12 21:31:51 +0000266 SkipUntil(tok::semi, true, false);
267 return ThisDecl;
268 }
269
270 // Eat the semi colon after the declaration.
John McCallef50e992009-07-31 02:20:35 +0000271 ExpectAndConsume(tok::semi, diag::err_expected_semi_declaration);
John McCallc1465822011-02-14 07:13:47 +0000272 DeclaratorInfo.complete(ThisDecl);
Douglas Gregor23996282009-05-12 21:31:51 +0000273 return ThisDecl;
274 }
275
276 if (DeclaratorInfo.isFunctionDeclarator() &&
Chris Lattner13901342010-07-11 22:42:07 +0000277 isStartOfFunctionDefinition(DeclaratorInfo)) {
Douglas Gregor23996282009-05-12 21:31:51 +0000278 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
279 Diag(Tok, diag::err_function_declared_typedef);
280
Richard Smith675ea992011-11-29 05:27:40 +0000281 // Recover by ignoring the 'typedef'.
282 DS.ClearStorageClassSpecs();
Douglas Gregor23996282009-05-12 21:31:51 +0000283 }
Douglas Gregor17a7c122009-06-24 00:54:41 +0000284 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo);
Douglas Gregor23996282009-05-12 21:31:51 +0000285 }
286
287 if (DeclaratorInfo.isFunctionDeclarator())
288 Diag(Tok, diag::err_expected_fn_body);
289 else
290 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
291 SkipUntil(tok::semi);
John McCall48871652010-08-21 09:40:31 +0000292 return 0;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000293}
294
295/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000296/// angle brackets. Depth is the depth of this template-parameter-list, which
297/// is the number of template headers directly enclosing this template header.
298/// TemplateParams is the current list of template parameters we're building.
299/// The template parameter we parse will be added to this list. LAngleLoc and
Mike Stump11289f42009-09-09 15:08:12 +0000300/// RAngleLoc will receive the positions of the '<' and '>', respectively,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000301/// that enclose this template parameter list.
Douglas Gregore93e46c2009-07-22 23:48:44 +0000302///
303/// \returns true if an error occurred, false otherwise.
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000304bool Parser::ParseTemplateParameters(unsigned Depth,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000305 SmallVectorImpl<Decl*> &TemplateParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000306 SourceLocation &LAngleLoc,
307 SourceLocation &RAngleLoc) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000308 // Get the template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +0000309 if (!Tok.is(tok::less)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000310 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
Douglas Gregore93e46c2009-07-22 23:48:44 +0000311 return true;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000312 }
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000313 LAngleLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000314
Douglas Gregoreb31f392008-12-01 23:54:00 +0000315 // Try to parse the template parameter list.
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000316 if (Tok.is(tok::greater))
317 RAngleLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000318 else if (ParseTemplateParameterList(Depth, TemplateParams)) {
319 if (!Tok.is(tok::greater)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000320 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregore93e46c2009-07-22 23:48:44 +0000321 return true;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000322 }
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000323 RAngleLoc = ConsumeToken();
Douglas Gregoreb31f392008-12-01 23:54:00 +0000324 }
Douglas Gregore93e46c2009-07-22 23:48:44 +0000325 return false;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000326}
327
328/// ParseTemplateParameterList - Parse a template parameter list. If
329/// the parsing fails badly (i.e., closing bracket was left out), this
330/// will try to put the token stream in a reasonable position (closing
Mike Stump11289f42009-09-09 15:08:12 +0000331/// a statement, etc.) and return false.
Douglas Gregoreb31f392008-12-01 23:54:00 +0000332///
333/// template-parameter-list: [C++ temp]
334/// template-parameter
335/// template-parameter-list ',' template-parameter
Mike Stump11289f42009-09-09 15:08:12 +0000336bool
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000337Parser::ParseTemplateParameterList(unsigned Depth,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000338 SmallVectorImpl<Decl*> &TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +0000339 while (1) {
John McCall48871652010-08-21 09:40:31 +0000340 if (Decl *TmpParam
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000341 = ParseTemplateParameter(Depth, TemplateParams.size())) {
342 TemplateParams.push_back(TmpParam);
343 } else {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000344 // If we failed to parse a template parameter, skip until we find
345 // a comma or closing brace.
346 SkipUntil(tok::comma, tok::greater, true, true);
347 }
Mike Stump11289f42009-09-09 15:08:12 +0000348
Douglas Gregoreb31f392008-12-01 23:54:00 +0000349 // Did we find a comma or the end of the template parmeter list?
Mike Stump11289f42009-09-09 15:08:12 +0000350 if (Tok.is(tok::comma)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000351 ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000352 } else if (Tok.is(tok::greater)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000353 // Don't consume this... that's done by template parser.
354 break;
355 } else {
356 // Somebody probably forgot to close the template. Skip ahead and
357 // try to get out of the expression. This error is currently
358 // subsumed by whatever goes on in ParseTemplateParameter.
359 // TODO: This could match >>, and it would be nice to avoid those
360 // silly errors with template <vec<T>>.
Douglas Gregorb0484022010-10-15 01:15:58 +0000361 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000362 SkipUntil(tok::greater, true, true);
363 return false;
364 }
365 }
366 return true;
367}
368
Douglas Gregor26aedb72009-11-21 02:07:55 +0000369/// \brief Determine whether the parser is at the start of a template
370/// type parameter.
371bool Parser::isStartOfTemplateTypeParameter() {
Douglas Gregor71b209d2010-06-04 07:30:15 +0000372 if (Tok.is(tok::kw_class)) {
373 // "class" may be the start of an elaborated-type-specifier or a
374 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
375 switch (NextToken().getKind()) {
376 case tok::equal:
377 case tok::comma:
378 case tok::greater:
379 case tok::greatergreater:
380 case tok::ellipsis:
381 return true;
382
383 case tok::identifier:
384 // This may be either a type-parameter or an elaborated-type-specifier.
385 // We have to look further.
386 break;
387
388 default:
389 return false;
390 }
391
392 switch (GetLookAheadToken(2).getKind()) {
393 case tok::equal:
394 case tok::comma:
395 case tok::greater:
396 case tok::greatergreater:
397 return true;
398
399 default:
400 return false;
401 }
402 }
Douglas Gregor26aedb72009-11-21 02:07:55 +0000403
404 if (Tok.isNot(tok::kw_typename))
405 return false;
406
407 // C++ [temp.param]p2:
408 // There is no semantic difference between class and typename in a
409 // template-parameter. typename followed by an unqualified-id
410 // names a template type parameter. typename followed by a
411 // qualified-id denotes the type in a non-type
412 // parameter-declaration.
413 Token Next = NextToken();
414
415 // If we have an identifier, skip over it.
416 if (Next.getKind() == tok::identifier)
417 Next = GetLookAheadToken(2);
418
419 switch (Next.getKind()) {
420 case tok::equal:
421 case tok::comma:
422 case tok::greater:
423 case tok::greatergreater:
424 case tok::ellipsis:
425 return true;
426
427 default:
428 return false;
429 }
430}
431
Douglas Gregoreb31f392008-12-01 23:54:00 +0000432/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
433///
434/// template-parameter: [C++ temp.param]
435/// type-parameter
436/// parameter-declaration
437///
438/// type-parameter: (see below)
Douglas Gregorf5500772011-01-05 15:48:55 +0000439/// 'class' ...[opt] identifier[opt]
Douglas Gregoreb31f392008-12-01 23:54:00 +0000440/// 'class' identifier[opt] '=' type-id
Douglas Gregorf5500772011-01-05 15:48:55 +0000441/// 'typename' ...[opt] identifier[opt]
Douglas Gregoreb31f392008-12-01 23:54:00 +0000442/// 'typename' identifier[opt] '=' type-id
Douglas Gregorf5500772011-01-05 15:48:55 +0000443/// 'template' '<' template-parameter-list '>'
444/// 'class' ...[opt] identifier[opt]
445/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
446/// = id-expression
John McCall48871652010-08-21 09:40:31 +0000447Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26aedb72009-11-21 02:07:55 +0000448 if (isStartOfTemplateTypeParameter())
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000449 return ParseTypeParameter(Depth, Position);
Mike Stump11289f42009-09-09 15:08:12 +0000450
451 if (Tok.is(tok::kw_template))
Chris Lattnera21db612009-01-04 23:51:17 +0000452 return ParseTemplateTemplateParameter(Depth, Position);
453
454 // If it's none of the above, then it must be a parameter declaration.
455 // NOTE: This will pick up errors in the closure of the template parameter
456 // list (e.g., template < ; Check here to implement >> style closures.
457 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000458}
459
460/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
461/// Other kinds of template parameters are parsed in
462/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
463///
464/// type-parameter: [C++ temp.param]
Anders Carlssonf986ba72009-06-12 23:09:56 +0000465/// 'class' ...[opt][C++0x] identifier[opt]
Douglas Gregoreb31f392008-12-01 23:54:00 +0000466/// 'class' identifier[opt] '=' type-id
Anders Carlssonf986ba72009-06-12 23:09:56 +0000467/// 'typename' ...[opt][C++0x] identifier[opt]
Douglas Gregoreb31f392008-12-01 23:54:00 +0000468/// 'typename' identifier[opt] '=' type-id
John McCall48871652010-08-21 09:40:31 +0000469Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Douglas Gregorf5586182008-12-02 00:41:28 +0000470 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
Mike Stump11289f42009-09-09 15:08:12 +0000471 "A type-parameter starts with 'class' or 'typename'");
Douglas Gregorf5586182008-12-02 00:41:28 +0000472
473 // Consume the 'class' or 'typename' keyword.
474 bool TypenameKeyword = Tok.is(tok::kw_typename);
475 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregoreb31f392008-12-01 23:54:00 +0000476
Anders Carlsson01e9e932009-06-12 19:58:00 +0000477 // Grab the ellipsis (if given).
478 bool Ellipsis = false;
479 SourceLocation EllipsisLoc;
Anders Carlssonf986ba72009-06-12 23:09:56 +0000480 if (Tok.is(tok::ellipsis)) {
Anders Carlsson01e9e932009-06-12 19:58:00 +0000481 Ellipsis = true;
482 EllipsisLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000483
Richard Smith96bd62f2011-10-14 20:31:37 +0000484 Diag(EllipsisLoc,
485 getLang().CPlusPlus0x
486 ? diag::warn_cxx98_compat_variadic_templates
487 : diag::ext_variadic_templates);
Anders Carlsson01e9e932009-06-12 19:58:00 +0000488 }
Mike Stump11289f42009-09-09 15:08:12 +0000489
Douglas Gregoreb31f392008-12-01 23:54:00 +0000490 // Grab the template parameter name (if given)
Douglas Gregorf5586182008-12-02 00:41:28 +0000491 SourceLocation NameLoc;
492 IdentifierInfo* ParamName = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000493 if (Tok.is(tok::identifier)) {
Douglas Gregorf5586182008-12-02 00:41:28 +0000494 ParamName = Tok.getIdentifierInfo();
495 NameLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000496 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
497 Tok.is(tok::greater)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000498 // Unnamed template parameter. Don't have to do anything here, just
499 // don't consume this token.
500 } else {
501 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCall48871652010-08-21 09:40:31 +0000502 return 0;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000503 }
Mike Stump11289f42009-09-09 15:08:12 +0000504
Douglas Gregordc13ded2010-07-01 00:00:45 +0000505 // Grab a default argument (if available).
506 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
507 // we introduce the type parameter into the local scope.
508 SourceLocation EqualLoc;
John McCallba7bf592010-08-24 05:47:05 +0000509 ParsedType DefaultArg;
Mike Stump11289f42009-09-09 15:08:12 +0000510 if (Tok.is(tok::equal)) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000511 EqualLoc = ConsumeToken();
512 DefaultArg = ParseTypeName().get();
Douglas Gregoreb31f392008-12-01 23:54:00 +0000513 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000514
Douglas Gregor0be31a22010-07-02 17:43:08 +0000515 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000516 EllipsisLoc, KeyLoc, ParamName, NameLoc,
517 Depth, Position, EqualLoc, DefaultArg);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000518}
519
520/// ParseTemplateTemplateParameter - Handle the parsing of template
Mike Stump11289f42009-09-09 15:08:12 +0000521/// template parameters.
Douglas Gregoreb31f392008-12-01 23:54:00 +0000522///
523/// type-parameter: [C++ temp.param]
Douglas Gregorf5500772011-01-05 15:48:55 +0000524/// 'template' '<' template-parameter-list '>' 'class'
525/// ...[opt] identifier[opt]
526/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
527/// = id-expression
John McCall48871652010-08-21 09:40:31 +0000528Decl *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000529Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000530 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
531
532 // Handle the template <...> part.
533 SourceLocation TemplateLoc = ConsumeToken();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000534 SmallVector<Decl*,8> TemplateParams;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000535 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor85e8b3e2009-02-10 19:52:54 +0000536 {
537 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Mike Stump11289f42009-09-09 15:08:12 +0000538 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
Douglas Gregore93e46c2009-07-22 23:48:44 +0000539 RAngleLoc)) {
John McCall48871652010-08-21 09:40:31 +0000540 return 0;
Douglas Gregor85e8b3e2009-02-10 19:52:54 +0000541 }
Douglas Gregoreb31f392008-12-01 23:54:00 +0000542 }
543
544 // Generate a meaningful error if the user forgot to put class before the
545 // identifier, comma, or greater.
Mike Stump11289f42009-09-09 15:08:12 +0000546 if (!Tok.is(tok::kw_class)) {
547 Diag(Tok.getLocation(), diag::err_expected_class_before)
Douglas Gregoreb31f392008-12-01 23:54:00 +0000548 << PP.getSpelling(Tok);
John McCall48871652010-08-21 09:40:31 +0000549 return 0;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000550 }
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +0000551 ConsumeToken();
Douglas Gregoreb31f392008-12-01 23:54:00 +0000552
Douglas Gregorf5500772011-01-05 15:48:55 +0000553 // Parse the ellipsis, if given.
554 SourceLocation EllipsisLoc;
555 if (Tok.is(tok::ellipsis)) {
556 EllipsisLoc = ConsumeToken();
557
Richard Smith96bd62f2011-10-14 20:31:37 +0000558 Diag(EllipsisLoc,
559 getLang().CPlusPlus0x
560 ? diag::warn_cxx98_compat_variadic_templates
561 : diag::ext_variadic_templates);
Douglas Gregorf5500772011-01-05 15:48:55 +0000562 }
563
Douglas Gregoreb31f392008-12-01 23:54:00 +0000564 // Get the identifier, if given.
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000565 SourceLocation NameLoc;
566 IdentifierInfo* ParamName = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000567 if (Tok.is(tok::identifier)) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000568 ParamName = Tok.getIdentifierInfo();
569 NameLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000570 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000571 // Unnamed template parameter. Don't have to do anything here, just
572 // don't consume this token.
573 } else {
574 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCall48871652010-08-21 09:40:31 +0000575 return 0;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000576 }
577
Richard Trieu9becef62011-09-09 03:18:59 +0000578 TemplateParameterList *ParamList =
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000579 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
580 TemplateLoc, LAngleLoc,
Douglas Gregora02bb372010-10-21 17:26:49 +0000581 TemplateParams.data(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000582 TemplateParams.size(),
583 RAngleLoc);
584
Douglas Gregordc13ded2010-07-01 00:00:45 +0000585 // Grab a default argument (if available).
586 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
587 // we introduce the template parameter into the local scope.
588 SourceLocation EqualLoc;
589 ParsedTemplateArgument DefaultArg;
Douglas Gregordba32632009-02-10 19:49:53 +0000590 if (Tok.is(tok::equal)) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000591 EqualLoc = ConsumeToken();
592 DefaultArg = ParseTemplateTemplateArgument();
593 if (DefaultArg.isInvalid()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000594 Diag(Tok.getLocation(),
595 diag::err_default_template_template_parameter_not_template);
Nuno Lopes221c1fd2009-12-10 00:07:02 +0000596 static const tok::TokenKind EndToks[] = {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000597 tok::comma, tok::greater, tok::greatergreater
598 };
599 SkipUntil(EndToks, 3, true, true);
Douglas Gregordc13ded2010-07-01 00:00:45 +0000600 }
Douglas Gregordba32632009-02-10 19:49:53 +0000601 }
Douglas Gregordc13ded2010-07-01 00:00:45 +0000602
Douglas Gregor0be31a22010-07-02 17:43:08 +0000603 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
Douglas Gregorf5500772011-01-05 15:48:55 +0000604 ParamList, EllipsisLoc,
605 ParamName, NameLoc, Depth,
606 Position, EqualLoc, DefaultArg);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000607}
608
609/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
Mike Stump11289f42009-09-09 15:08:12 +0000610/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000611///
Douglas Gregoreb31f392008-12-01 23:54:00 +0000612/// template-parameter:
613/// ...
614/// parameter-declaration
John McCall48871652010-08-21 09:40:31 +0000615Decl *
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000616Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000617 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregorf5586182008-12-02 00:41:28 +0000618 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregoreb31f392008-12-01 23:54:00 +0000619 // declarators (parts of declarators?) are accepted for parameters.
John McCall084e83d2011-03-24 11:26:52 +0000620 DeclSpec DS(AttrFactory);
Douglas Gregorf5586182008-12-02 00:41:28 +0000621 ParseDeclarationSpecifiers(DS);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000622
623 // Parse this as a typename.
Douglas Gregorf5586182008-12-02 00:41:28 +0000624 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
625 ParseDeclarator(ParamDecl);
John McCallba7bf592010-08-24 05:47:05 +0000626 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
Douglas Gregoreb31f392008-12-01 23:54:00 +0000627 // This probably shouldn't happen - and it's more of a Sema thing, but
628 // basically we didn't parse the type name because we couldn't associate
629 // it with an AST node. we should just skip to the comma or greater.
630 // TODO: This is currently a placeholder for some kind of Sema Error.
631 Diag(Tok.getLocation(), diag::err_parse_error);
632 SkipUntil(tok::comma, tok::greater, true, true);
John McCall48871652010-08-21 09:40:31 +0000633 return 0;
Douglas Gregoreb31f392008-12-01 23:54:00 +0000634 }
635
Douglas Gregordba32632009-02-10 19:49:53 +0000636 // If there is a default value, parse it.
Douglas Gregordc13ded2010-07-01 00:00:45 +0000637 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
638 // we introduce the template parameter into the local scope.
639 SourceLocation EqualLoc;
John McCalldadc5752010-08-24 06:29:42 +0000640 ExprResult DefaultArg;
Chris Lattnerb5134c02009-01-05 01:24:05 +0000641 if (Tok.is(tok::equal)) {
Douglas Gregordc13ded2010-07-01 00:00:45 +0000642 EqualLoc = ConsumeToken();
Douglas Gregordba32632009-02-10 19:49:53 +0000643
644 // C++ [temp.param]p15:
645 // When parsing a default template-argument for a non-type
646 // template-parameter, the first non-nested > is taken as the
647 // end of the template-parameter-list rather than a greater-than
648 // operator.
Mike Stump11289f42009-09-09 15:08:12 +0000649 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000650
Douglas Gregordc13ded2010-07-01 00:00:45 +0000651 DefaultArg = ParseAssignmentExpression();
Douglas Gregordba32632009-02-10 19:49:53 +0000652 if (DefaultArg.isInvalid())
653 SkipUntil(tok::comma, tok::greater, true, true);
Douglas Gregoreb31f392008-12-01 23:54:00 +0000654 }
Mike Stump11289f42009-09-09 15:08:12 +0000655
Douglas Gregordc13ded2010-07-01 00:00:45 +0000656 // Create the parameter.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000657 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
Douglas Gregordc13ded2010-07-01 00:00:45 +0000658 Depth, Position, EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000659 DefaultArg.take());
Douglas Gregoreb31f392008-12-01 23:54:00 +0000660}
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000661
Douglas Gregor67a65642009-02-17 23:15:12 +0000662/// \brief Parses a template-id that after the template name has
663/// already been parsed.
664///
665/// This routine takes care of parsing the enclosed template argument
666/// list ('<' template-parameter-list [opt] '>') and placing the
667/// results into a form that can be transferred to semantic analysis.
668///
669/// \param Template the template declaration produced by isTemplateName
670///
671/// \param TemplateNameLoc the source location of the template name
672///
673/// \param SS if non-NULL, the nested-name-specifier preceding the
674/// template name.
675///
676/// \param ConsumeLastToken if true, then we will consume the last
677/// token that forms the template-id. Otherwise, we will leave the
678/// last token in the stream (e.g., so that it can be replaced with an
679/// annotation token).
Mike Stump11289f42009-09-09 15:08:12 +0000680bool
Douglas Gregordc572a32009-03-30 22:58:21 +0000681Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
Mike Stump11289f42009-09-09 15:08:12 +0000682 SourceLocation TemplateNameLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +0000683 const CXXScopeSpec &SS,
Douglas Gregor67a65642009-02-17 23:15:12 +0000684 bool ConsumeLastToken,
685 SourceLocation &LAngleLoc,
686 TemplateArgList &TemplateArgs,
Douglas Gregor67a65642009-02-17 23:15:12 +0000687 SourceLocation &RAngleLoc) {
688 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
689
690 // Consume the '<'.
691 LAngleLoc = ConsumeToken();
692
693 // Parse the optional template-argument-list.
694 bool Invalid = false;
695 {
696 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Douglas Gregor180dda92011-01-11 00:45:18 +0000697 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
Douglas Gregorb53edfb2009-11-10 19:49:08 +0000698 Invalid = ParseTemplateArgumentList(TemplateArgs);
Douglas Gregor67a65642009-02-17 23:15:12 +0000699
700 if (Invalid) {
701 // Try to find the closing '>'.
702 SkipUntil(tok::greater, true, !ConsumeLastToken);
703
704 return true;
705 }
706 }
707
Eli Friedmanaffd5fd2009-12-27 22:31:18 +0000708 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) {
709 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregor67a65642009-02-17 23:15:12 +0000710 return true;
Eli Friedmanaffd5fd2009-12-27 22:31:18 +0000711 }
Douglas Gregor67a65642009-02-17 23:15:12 +0000712
Douglas Gregorcbb45d02009-02-25 23:02:36 +0000713 // Determine the location of the '>' or '>>'. Only consume this
714 // token if the caller asked us to.
Douglas Gregor67a65642009-02-17 23:15:12 +0000715 RAngleLoc = Tok.getLocation();
716
Douglas Gregorcbb45d02009-02-25 23:02:36 +0000717 if (Tok.is(tok::greatergreater)) {
Richard Smith5d164bc2011-10-15 05:09:34 +0000718 const char *ReplaceStr = "> >";
719 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
720 ReplaceStr = "> > ";
Douglas Gregor87f95b02009-02-26 21:00:50 +0000721
Richard Smith5d164bc2011-10-15 05:09:34 +0000722 Diag(Tok.getLocation(), getLang().CPlusPlus0x ?
723 diag::warn_cxx98_compat_two_right_angle_brackets :
724 diag::err_two_right_angle_brackets_need_space)
725 << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()),
726 ReplaceStr);
Douglas Gregorcbb45d02009-02-25 23:02:36 +0000727
728 Tok.setKind(tok::greater);
729 if (!ConsumeLastToken) {
730 // Since we're not supposed to consume the '>>' token, we need
731 // to insert a second '>' token after the first.
732 PP.EnterToken(Tok);
733 }
734 } else if (ConsumeLastToken)
Douglas Gregor67a65642009-02-17 23:15:12 +0000735 ConsumeToken();
736
737 return false;
738}
Mike Stump11289f42009-09-09 15:08:12 +0000739
Douglas Gregor7f741122009-02-25 19:37:18 +0000740/// \brief Replace the tokens that form a simple-template-id with an
741/// annotation token containing the complete template-id.
742///
743/// The first token in the stream must be the name of a template that
744/// is followed by a '<'. This routine will parse the complete
745/// simple-template-id and replace the tokens with a single annotation
746/// token with one of two different kinds: if the template-id names a
747/// type (and \p AllowTypeAnnotation is true), the annotation token is
748/// a type annotation that includes the optional nested-name-specifier
749/// (\p SS). Otherwise, the annotation token is a template-id
750/// annotation that does not include the optional
751/// nested-name-specifier.
752///
753/// \param Template the declaration of the template named by the first
754/// token (an identifier), as returned from \c Action::isTemplateName().
755///
756/// \param TemplateNameKind the kind of template that \p Template
757/// refers to, as returned from \c Action::isTemplateName().
758///
759/// \param SS if non-NULL, the nested-name-specifier that precedes
760/// this template name.
761///
762/// \param TemplateKWLoc if valid, specifies that this template-id
763/// annotation was preceded by the 'template' keyword and gives the
764/// location of that keyword. If invalid (the default), then this
765/// template-id was not preceded by a 'template' keyword.
766///
767/// \param AllowTypeAnnotation if true (the default), then a
768/// simple-template-id that refers to a class template, template
769/// template parameter, or other template that produces a type will be
770/// replaced with a type annotation token. Otherwise, the
771/// simple-template-id is always replaced with a template-id
772/// annotation token.
Chris Lattner5558e9f2009-06-26 04:27:47 +0000773///
774/// If an unrecoverable parse error occurs and no annotation token can be
775/// formed, this function returns true.
776///
777bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Douglas Gregore7c20652011-03-02 00:47:37 +0000778 CXXScopeSpec &SS,
Douglas Gregor71395fa2009-11-04 00:56:37 +0000779 UnqualifiedId &TemplateName,
Douglas Gregor7f741122009-02-25 19:37:18 +0000780 SourceLocation TemplateKWLoc,
781 bool AllowTypeAnnotation) {
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000782 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
Douglas Gregor71395fa2009-11-04 00:56:37 +0000783 assert(Template && Tok.is(tok::less) &&
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000784 "Parser isn't at the beginning of a template-id");
785
786 // Consume the template-name.
Douglas Gregor71395fa2009-11-04 00:56:37 +0000787 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000788
Douglas Gregor67a65642009-02-17 23:15:12 +0000789 // Parse the enclosed template argument list.
790 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor67b556a2009-02-09 19:34:22 +0000791 TemplateArgList TemplateArgs;
Douglas Gregor71395fa2009-11-04 00:56:37 +0000792 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
793 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000794 SS, false, LAngleLoc,
795 TemplateArgs,
Douglas Gregor67a65642009-02-17 23:15:12 +0000796 RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000797
Chris Lattner5558e9f2009-06-26 04:27:47 +0000798 if (Invalid) {
799 // If we failed to parse the template ID but skipped ahead to a >, we're not
800 // going to be able to form a token annotation. Eat the '>' if present.
801 if (Tok.is(tok::greater))
802 ConsumeToken();
803 return true;
804 }
Douglas Gregord32e0282009-02-09 23:23:08 +0000805
Jay Foad7d0479f2009-05-21 09:52:38 +0000806 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
Douglas Gregor67a65642009-02-17 23:15:12 +0000807 TemplateArgs.size());
Douglas Gregor0db4ccd2009-02-09 21:04:56 +0000808
Douglas Gregor8bf42052009-02-09 18:46:07 +0000809 // Build the annotation token.
Douglas Gregorb67535d2009-03-31 00:43:58 +0000810 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
John McCallfaf5fb42010-08-26 23:41:50 +0000811 TypeResult Type
Douglas Gregore7c20652011-03-02 00:47:37 +0000812 = Actions.ActOnTemplateIdType(SS,
813 Template, TemplateNameLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +0000814 LAngleLoc, TemplateArgsPtr,
Douglas Gregordc572a32009-03-30 22:58:21 +0000815 RAngleLoc);
Chris Lattner5558e9f2009-06-26 04:27:47 +0000816 if (Type.isInvalid()) {
817 // If we failed to parse the template ID but skipped ahead to a >, we're not
818 // going to be able to form a token annotation. Eat the '>' if present.
819 if (Tok.is(tok::greater))
820 ConsumeToken();
821 return true;
822 }
Douglas Gregor67a65642009-02-17 23:15:12 +0000823
824 Tok.setKind(tok::annot_typename);
John McCallba7bf592010-08-24 05:47:05 +0000825 setTypeAnnotation(Tok, Type.get());
Douglas Gregore7c20652011-03-02 00:47:37 +0000826 if (SS.isNotEmpty())
827 Tok.setLocation(SS.getBeginLoc());
Douglas Gregor7f741122009-02-25 19:37:18 +0000828 else if (TemplateKWLoc.isValid())
829 Tok.setLocation(TemplateKWLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000830 else
Douglas Gregor7f741122009-02-25 19:37:18 +0000831 Tok.setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +0000832 } else {
Douglas Gregorb67535d2009-03-31 00:43:58 +0000833 // Build a template-id annotation token that can be processed
834 // later.
Douglas Gregor7f741122009-02-25 19:37:18 +0000835 Tok.setKind(tok::annot_template_id);
Mike Stump11289f42009-09-09 15:08:12 +0000836 TemplateIdAnnotation *TemplateId
Douglas Gregor7f741122009-02-25 19:37:18 +0000837 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
Douglas Gregor8bf42052009-02-09 18:46:07 +0000838 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregor71395fa2009-11-04 00:56:37 +0000839 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
840 TemplateId->Name = TemplateName.Identifier;
841 TemplateId->Operator = OO_None;
842 } else {
843 TemplateId->Name = 0;
844 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
845 }
Douglas Gregore7c20652011-03-02 00:47:37 +0000846 TemplateId->SS = SS;
John McCall3e56fd42010-08-23 07:28:44 +0000847 TemplateId->Template = Template;
Douglas Gregor7f741122009-02-25 19:37:18 +0000848 TemplateId->Kind = TNK;
Douglas Gregor8bf42052009-02-09 18:46:07 +0000849 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor7f741122009-02-25 19:37:18 +0000850 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregorb53edfb2009-11-10 19:49:08 +0000851 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
852 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
Douglas Gregor869ad452011-02-24 17:54:50 +0000853 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
Douglas Gregor8bf42052009-02-09 18:46:07 +0000854 Tok.setAnnotationValue(TemplateId);
Douglas Gregor7f741122009-02-25 19:37:18 +0000855 if (TemplateKWLoc.isValid())
856 Tok.setLocation(TemplateKWLoc);
857 else
858 Tok.setLocation(TemplateNameLoc);
859
860 TemplateArgsPtr.release();
Douglas Gregor8bf42052009-02-09 18:46:07 +0000861 }
862
863 // Common fields for the annotation token
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000864 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000865
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000866 // In case the tokens were cached, have Preprocessor replace them with the
867 // annotation token.
868 PP.AnnotateCachedTokens(Tok);
Chris Lattner5558e9f2009-06-26 04:27:47 +0000869 return false;
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000870}
871
Douglas Gregor7f741122009-02-25 19:37:18 +0000872/// \brief Replaces a template-id annotation token with a type
873/// annotation token.
874///
Douglas Gregorfe3d7d02009-04-01 21:51:26 +0000875/// If there was a failure when forming the type from the template-id,
876/// a type annotation token will still be created, but will have a
877/// NULL type pointer to signify an error.
Douglas Gregore7c20652011-03-02 00:47:37 +0000878void Parser::AnnotateTemplateIdTokenAsType() {
Douglas Gregor7f741122009-02-25 19:37:18 +0000879 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
880
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +0000881 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorb67535d2009-03-31 00:43:58 +0000882 assert((TemplateId->Kind == TNK_Type_template ||
883 TemplateId->Kind == TNK_Dependent_template_name) &&
884 "Only works for type and dependent templates");
Mike Stump11289f42009-09-09 15:08:12 +0000885
886 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
Douglas Gregor7f741122009-02-25 19:37:18 +0000887 TemplateId->getTemplateArgs(),
Douglas Gregor7f741122009-02-25 19:37:18 +0000888 TemplateId->NumArgs);
889
John McCallfaf5fb42010-08-26 23:41:50 +0000890 TypeResult Type
Douglas Gregore7c20652011-03-02 00:47:37 +0000891 = Actions.ActOnTemplateIdType(TemplateId->SS,
892 TemplateId->Template,
Douglas Gregordc572a32009-03-30 22:58:21 +0000893 TemplateId->TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000894 TemplateId->LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +0000895 TemplateArgsPtr,
Douglas Gregordc572a32009-03-30 22:58:21 +0000896 TemplateId->RAngleLoc);
Douglas Gregor7f741122009-02-25 19:37:18 +0000897 // Create the new "type" annotation token.
898 Tok.setKind(tok::annot_typename);
John McCallba7bf592010-08-24 05:47:05 +0000899 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
Douglas Gregore7c20652011-03-02 00:47:37 +0000900 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
901 Tok.setLocation(TemplateId->SS.getBeginLoc());
Sebastian Redlb0e3e1b2010-02-08 19:35:18 +0000902 // End location stays the same
Douglas Gregor7f741122009-02-25 19:37:18 +0000903
Douglas Gregor35522592009-11-04 18:18:19 +0000904 // Replace the template-id annotation token, and possible the scope-specifier
905 // that precedes it, with the typename annotation token.
906 PP.AnnotateCachedTokens(Tok);
Douglas Gregor7f741122009-02-25 19:37:18 +0000907}
908
Douglas Gregorb53edfb2009-11-10 19:49:08 +0000909/// \brief Determine whether the given token can end a template argument.
Benjamin Kramer2c9a91c2009-11-10 21:29:56 +0000910static bool isEndOfTemplateArgument(Token Tok) {
Douglas Gregorb53edfb2009-11-10 19:49:08 +0000911 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
912 Tok.is(tok::greatergreater);
913}
914
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000915/// \brief Parse a C++ template template argument.
916ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
917 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
918 !Tok.is(tok::annot_cxxscope))
919 return ParsedTemplateArgument();
920
921 // C++0x [temp.arg.template]p1:
922 // A template-argument for a template template-parameter shall be the name
Richard Smith3f1b5d02011-05-05 21:57:07 +0000923 // of a class template or an alias template, expressed as id-expression.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000924 //
Richard Smith3f1b5d02011-05-05 21:57:07 +0000925 // We parse an id-expression that refers to a class template or alias
926 // template. The grammar we parse is:
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000927 //
Douglas Gregore9a80352011-01-05 17:33:50 +0000928 // nested-name-specifier[opt] template[opt] identifier ...[opt]
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000929 //
930 // followed by a token that terminates a template argument, such as ',',
931 // '>', or (in some cases) '>>'.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000932 CXXScopeSpec SS; // nested-name-specifier, if present
John McCallba7bf592010-08-24 05:47:05 +0000933 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000934 /*EnteringContext=*/false);
935
Douglas Gregore9a80352011-01-05 17:33:50 +0000936 ParsedTemplateArgument Result;
937 SourceLocation EllipsisLoc;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000938 if (SS.isSet() && Tok.is(tok::kw_template)) {
939 // Parse the optional 'template' keyword following the
940 // nested-name-specifier.
941 SourceLocation TemplateLoc = ConsumeToken();
942
943 if (Tok.is(tok::identifier)) {
944 // We appear to have a dependent template name.
945 UnqualifiedId Name;
946 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
947 ConsumeToken(); // the identifier
948
Douglas Gregore9a80352011-01-05 17:33:50 +0000949 // Parse the ellipsis.
950 if (Tok.is(tok::ellipsis))
951 EllipsisLoc = ConsumeToken();
952
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000953 // If the next token signals the end of a template argument,
954 // then we have a dependent template name that could be a template
955 // template argument.
Douglas Gregorbb119652010-06-16 23:00:59 +0000956 TemplateTy Template;
957 if (isEndOfTemplateArgument(Tok) &&
John McCallba7bf592010-08-24 05:47:05 +0000958 Actions.ActOnDependentTemplateName(getCurScope(), TemplateLoc,
959 SS, Name,
960 /*ObjectType=*/ ParsedType(),
Douglas Gregorbb119652010-06-16 23:00:59 +0000961 /*EnteringContext=*/false,
962 Template))
Douglas Gregore9a80352011-01-05 17:33:50 +0000963 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregorbb119652010-06-16 23:00:59 +0000964 }
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000965 } else if (Tok.is(tok::identifier)) {
966 // We may have a (non-dependent) template name.
967 TemplateTy Template;
968 UnqualifiedId Name;
969 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
970 ConsumeToken(); // the identifier
971
Douglas Gregore9a80352011-01-05 17:33:50 +0000972 // Parse the ellipsis.
973 if (Tok.is(tok::ellipsis))
974 EllipsisLoc = ConsumeToken();
975
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000976 if (isEndOfTemplateArgument(Tok)) {
Douglas Gregor786123d2010-05-21 23:18:07 +0000977 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000978 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
979 /*hasTemplateKeyword=*/false,
980 Name,
John McCallba7bf592010-08-24 05:47:05 +0000981 /*ObjectType=*/ ParsedType(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000982 /*EnteringContext=*/false,
Douglas Gregor786123d2010-05-21 23:18:07 +0000983 Template,
984 MemberOfUnknownSpecialization);
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000985 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
986 // We have an id-expression that refers to a class template or
Richard Smith3f1b5d02011-05-05 21:57:07 +0000987 // (C++0x) alias template.
Douglas Gregore9a80352011-01-05 17:33:50 +0000988 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000989 }
990 }
991 }
992
Douglas Gregore9a80352011-01-05 17:33:50 +0000993 // If this is a pack expansion, build it as such.
994 if (EllipsisLoc.isValid() && !Result.isInvalid())
995 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
996
997 return Result;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000998}
999
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001000/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1001///
1002/// template-argument: [C++ 14.2]
Douglas Gregor0b6a6242009-06-22 20:57:11 +00001003/// constant-expression
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001004/// type-id
1005/// id-expression
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001006ParsedTemplateArgument Parser::ParseTemplateArgument() {
Douglas Gregor8bf42052009-02-09 18:46:07 +00001007 // C++ [temp.arg]p2:
1008 // In a template-argument, an ambiguity between a type-id and an
1009 // expression is resolved to a type-id, regardless of the form of
1010 // the corresponding template-parameter.
1011 //
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001012 // Therefore, we initially try to parse a type-id.
Douglas Gregor97f34572009-02-10 00:53:15 +00001013 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001014 SourceLocation Loc = Tok.getLocation();
Douglas Gregor205d5e32011-01-31 16:09:46 +00001015 TypeResult TypeArg = ParseTypeName(/*Range=*/0,
1016 Declarator::TemplateTypeArgContext);
Douglas Gregor220cac52009-02-18 17:45:20 +00001017 if (TypeArg.isInvalid())
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001018 return ParsedTemplateArgument();
1019
John McCallba7bf592010-08-24 05:47:05 +00001020 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1021 TypeArg.get().getAsOpaquePtr(),
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001022 Loc);
Douglas Gregor8bf42052009-02-09 18:46:07 +00001023 }
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001024
1025 // Try to parse a template template argument.
Douglas Gregorc9984092009-11-12 00:03:40 +00001026 {
1027 TentativeParsingAction TPA(*this);
1028
1029 ParsedTemplateArgument TemplateTemplateArgument
1030 = ParseTemplateTemplateArgument();
1031 if (!TemplateTemplateArgument.isInvalid()) {
1032 TPA.Commit();
1033 return TemplateTemplateArgument;
1034 }
1035
1036 // Revert this tentative parse to parse a non-type template argument.
1037 TPA.Revert();
1038 }
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001039
1040 // Parse a non-type template argument.
1041 SourceLocation Loc = Tok.getLocation();
John McCalldadc5752010-08-24 06:29:42 +00001042 ExprResult ExprArg = ParseConstantExpression();
Douglas Gregord32e0282009-02-09 23:23:08 +00001043 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001044 return ParsedTemplateArgument();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001045
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001046 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1047 ExprArg.release(), Loc);
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001048}
1049
Douglas Gregor786123d2010-05-21 23:18:07 +00001050/// \brief Determine whether the current tokens can only be parsed as a
1051/// template argument list (starting with the '<') and never as a '<'
1052/// expression.
Douglas Gregor20c38a72010-05-21 23:43:39 +00001053bool Parser::IsTemplateArgumentList(unsigned Skip) {
Douglas Gregor786123d2010-05-21 23:18:07 +00001054 struct AlwaysRevertAction : TentativeParsingAction {
1055 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1056 ~AlwaysRevertAction() { Revert(); }
1057 } Tentative(*this);
1058
Douglas Gregor20c38a72010-05-21 23:43:39 +00001059 while (Skip) {
1060 ConsumeToken();
1061 --Skip;
1062 }
1063
Douglas Gregor786123d2010-05-21 23:18:07 +00001064 // '<'
1065 if (!Tok.is(tok::less))
1066 return false;
1067 ConsumeToken();
1068
1069 // An empty template argument list.
1070 if (Tok.is(tok::greater))
1071 return true;
1072
1073 // See whether we have declaration specifiers, which indicate a type.
1074 while (isCXXDeclarationSpecifier() == TPResult::True())
1075 ConsumeToken();
1076
1077 // If we have a '>' or a ',' then this is a template argument list.
1078 return Tok.is(tok::greater) || Tok.is(tok::comma);
1079}
1080
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001081/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1082/// (C++ [temp.names]). Returns true if there was an error.
1083///
1084/// template-argument-list: [C++ 14.2]
1085/// template-argument
1086/// template-argument-list ',' template-argument
Mike Stump11289f42009-09-09 15:08:12 +00001087bool
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001088Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001089 while (true) {
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001090 ParsedTemplateArgument Arg = ParseTemplateArgument();
Douglas Gregord2fa7662010-12-20 02:24:11 +00001091 if (Tok.is(tok::ellipsis)) {
1092 SourceLocation EllipsisLoc = ConsumeToken();
1093 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1094 }
1095
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001096 if (Arg.isInvalid()) {
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001097 SkipUntil(tok::comma, tok::greater, true, true);
1098 return true;
1099 }
Douglas Gregor67b556a2009-02-09 19:34:22 +00001100
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001101 // Save this template argument.
1102 TemplateArgs.push_back(Arg);
1103
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001104 // If the next token is a comma, consume it and keep reading
1105 // arguments.
1106 if (Tok.isNot(tok::comma)) break;
1107
1108 // Consume the comma.
1109 ConsumeToken();
1110 }
1111
Eli Friedmanaffd5fd2009-12-27 22:31:18 +00001112 return false;
Douglas Gregor55ad91f2008-12-18 19:37:40 +00001113}
1114
Mike Stump11289f42009-09-09 15:08:12 +00001115/// \brief Parse a C++ explicit template instantiation
Douglas Gregor23996282009-05-12 21:31:51 +00001116/// (C++ [temp.explicit]).
1117///
1118/// explicit-instantiation:
Douglas Gregor43e75172009-09-04 06:33:52 +00001119/// 'extern' [opt] 'template' declaration
1120///
1121/// Note that the 'extern' is a GNU extension and C++0x feature.
John McCall48871652010-08-21 09:40:31 +00001122Decl *Parser::ParseExplicitInstantiation(SourceLocation ExternLoc,
1123 SourceLocation TemplateLoc,
1124 SourceLocation &DeclEnd) {
John McCall796c2a52010-07-16 08:13:16 +00001125 // This isn't really required here.
1126 ParsingDeclRAIIObject ParsingTemplateParams(*this);
1127
Mike Stump11289f42009-09-09 15:08:12 +00001128 return ParseSingleDeclarationAfterTemplate(Declarator::FileContext,
Douglas Gregor43e75172009-09-04 06:33:52 +00001129 ParsedTemplateInfo(ExternLoc,
1130 TemplateLoc),
John McCall796c2a52010-07-16 08:13:16 +00001131 ParsingTemplateParams,
Douglas Gregor1b57ff32009-05-12 23:25:50 +00001132 DeclEnd, AS_none);
Douglas Gregor23996282009-05-12 21:31:51 +00001133}
John McCall9b72f892010-11-10 02:40:36 +00001134
1135SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1136 if (TemplateParams)
1137 return getTemplateParamsRange(TemplateParams->data(),
1138 TemplateParams->size());
1139
1140 SourceRange R(TemplateLoc);
1141 if (ExternLoc.isValid())
1142 R.setBegin(ExternLoc);
1143 return R;
1144}
Francois Pichet1c229c02011-04-22 22:18:13 +00001145
Francois Picheta7d337d2011-04-23 11:52:20 +00001146void Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) {
Francois Pichet1c229c02011-04-22 22:18:13 +00001147 ((Parser*)P)->LateTemplateParser(FD);
1148}
1149
1150
Francois Picheta7d337d2011-04-23 11:52:20 +00001151void Parser::LateTemplateParser(const FunctionDecl *FD) {
Francois Pichet1c229c02011-04-22 22:18:13 +00001152 LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD];
1153 if (LPT) {
1154 ParseLateTemplatedFuncDef(*LPT);
1155 return;
1156 }
1157
1158 llvm_unreachable("Late templated function without associated lexed tokens");
1159}
1160
1161/// \brief Late parse a C++ function template in Microsoft mode.
1162void Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) {
1163 if(!LMT.D)
1164 return;
1165
1166 // If this is a member template, introduce the template parameter scope.
1167 ParseScope TemplateScope(this, Scope::TemplateParamScope);
1168
1169 // Get the FunctionDecl.
1170 FunctionDecl *FD = 0;
1171 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(LMT.D))
1172 FD = FunTmpl->getTemplatedDecl();
1173 else
1174 FD = cast<FunctionDecl>(LMT.D);
1175
1176 // Reinject the template parameters.
Francois Pichet81345182011-09-22 22:14:56 +00001177 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
Francois Pichet1c229c02011-04-22 22:18:13 +00001178 DeclaratorDecl* Declarator = dyn_cast<DeclaratorDecl>(FD);
1179 if (Declarator && Declarator->getNumTemplateParameterLists() != 0) {
1180 Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
1181 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1182 } else {
1183 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1184
Francois Pichet81345182011-09-22 22:14:56 +00001185 // Get the list of DeclContext to reenter.
1186 SmallVector<DeclContext*, 4> DeclContextToReenter;
Francois Pichet1c229c02011-04-22 22:18:13 +00001187 DeclContext *DD = FD->getLexicalParent();
1188 while (DD && DD->isRecord()) {
Francois Pichet81345182011-09-22 22:14:56 +00001189 DeclContextToReenter.push_back(DD);
Francois Pichet1c229c02011-04-22 22:18:13 +00001190 DD = DD->getLexicalParent();
1191 }
Francois Pichet81345182011-09-22 22:14:56 +00001192
Francois Pichet44bb90d2011-09-23 16:02:49 +00001193 // Reenter template scopes from outmost to innermost.
Francois Pichet81345182011-09-22 22:14:56 +00001194 SmallVector<DeclContext*, 4>::reverse_iterator II =
1195 DeclContextToReenter.rbegin();
1196 for (; II != DeclContextToReenter.rend(); ++II) {
1197 if (ClassTemplatePartialSpecializationDecl* MD =
1198 dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) {
Sebastian Redl0d164012011-09-30 08:32:17 +00001199 TemplateParamScopeStack.push_back(new ParseScope(this,
1200 Scope::TemplateParamScope));
Francois Pichet81345182011-09-22 22:14:56 +00001201 Actions.ActOnReenterTemplateScope(getCurScope(), MD);
1202 } else if (CXXRecordDecl* MD = dyn_cast_or_null<CXXRecordDecl>(*II)) {
Sebastian Redl0d164012011-09-30 08:32:17 +00001203 TemplateParamScopeStack.push_back(new ParseScope(this,
1204 Scope::TemplateParamScope,
1205 MD->getDescribedClassTemplate() != 0 ));
Francois Pichet81345182011-09-22 22:14:56 +00001206 Actions.ActOnReenterTemplateScope(getCurScope(),
1207 MD->getDescribedClassTemplate());
1208 }
1209 }
Francois Pichet1c229c02011-04-22 22:18:13 +00001210 }
1211 assert(!LMT.Toks.empty() && "Empty body!");
1212
1213 // Append the current token at the end of the new token stream so that it
1214 // doesn't get lost.
1215 LMT.Toks.push_back(Tok);
1216 PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false);
1217
1218 // Consume the previously pushed token.
1219 ConsumeAnyToken();
1220 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1221 && "Inline method not starting with '{', ':' or 'try'");
1222
1223 // Parse the method body. Function body parsing code is similar enough
1224 // to be re-used for method bodies as well.
1225 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1226
1227 // Recreate the DeclContext.
1228 Sema::ContextRAII SavedContext(Actions, Actions.getContainingDC(FD));
1229
1230 if (FunctionTemplateDecl *FunctionTemplate
1231 = dyn_cast_or_null<FunctionTemplateDecl>(LMT.D))
1232 Actions.ActOnStartOfFunctionDef(getCurScope(),
1233 FunctionTemplate->getTemplatedDecl());
1234 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(LMT.D))
1235 Actions.ActOnStartOfFunctionDef(getCurScope(), Function);
1236
1237
1238 if (Tok.is(tok::kw_try)) {
1239 ParseFunctionTryBlock(LMT.D, FnScope);
Francois Pichet81345182011-09-22 22:14:56 +00001240 } else {
1241 if (Tok.is(tok::colon))
1242 ParseConstructorInitializer(LMT.D);
1243 else
1244 Actions.ActOnDefaultCtorInitializers(LMT.D);
Francois Pichet1c229c02011-04-22 22:18:13 +00001245
Francois Pichet81345182011-09-22 22:14:56 +00001246 if (Tok.is(tok::l_brace)) {
1247 ParseFunctionStatementBody(LMT.D, FnScope);
1248 Actions.MarkAsLateParsedTemplate(FD, false);
1249 } else
Francois Pichet1c229c02011-04-22 22:18:13 +00001250 Actions.ActOnFinishFunctionBody(LMT.D, 0);
Francois Pichet81345182011-09-22 22:14:56 +00001251 }
Francois Pichet1c229c02011-04-22 22:18:13 +00001252
Francois Pichet81345182011-09-22 22:14:56 +00001253 // Exit scopes.
1254 FnScope.Exit();
1255 SmallVector<ParseScope*, 4>::reverse_iterator I =
1256 TemplateParamScopeStack.rbegin();
1257 for (; I != TemplateParamScopeStack.rend(); ++I)
1258 delete *I;
Francois Pichet1c229c02011-04-22 22:18:13 +00001259
1260 DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D);
1261 if (grp)
1262 Actions.getASTConsumer().HandleTopLevelDecl(grp.get());
1263}
1264
1265/// \brief Lex a delayed template function for late parsing.
1266void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1267 tok::TokenKind kind = Tok.getKind();
Sebastian Redl0d164012011-09-30 08:32:17 +00001268 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1269 // Consume everything up to (and including) the matching right brace.
1270 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Francois Pichet1c229c02011-04-22 22:18:13 +00001271 }
Francois Pichet1c229c02011-04-22 22:18:13 +00001272
1273 // If we're in a function-try-block, we need to store all the catch blocks.
1274 if (kind == tok::kw_try) {
1275 while (Tok.is(tok::kw_catch)) {
1276 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1277 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1278 }
1279 }
1280}