blob: 2a79b99d29c9bfcd282f28b96842703d184e5d04 [file] [log] [blame]
Douglas Gregorb3bec712008-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 Lattner545f39e2009-01-29 05:15:15 +000015#include "clang/Parse/ParseDiagnostic.h"
Douglas Gregorb3bec712008-12-01 23:54:00 +000016#include "clang/Parse/DeclSpec.h"
17#include "clang/Parse/Scope.h"
Douglas Gregorb3bec712008-12-01 23:54:00 +000018using namespace clang;
19
Douglas Gregora9db0fa2009-05-12 23:25:50 +000020/// \brief Parse a template declaration, explicit instantiation, or
21/// explicit specialization.
22Parser::DeclPtrTy
23Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
24 SourceLocation &DeclEnd,
25 AccessSpecifier AS) {
26 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less))
27 return ParseExplicitInstantiation(ConsumeToken(), DeclEnd);
28
29 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS);
30}
31
Douglas Gregora08b6c72009-02-17 23:15:12 +000032/// \brief Parse a template declaration or an explicit specialization.
33///
34/// Template declarations include one or more template parameter lists
35/// and either the function or class template declaration. Explicit
36/// specializations contain one or more 'template < >' prefixes
37/// followed by a (possibly templated) declaration. Since the
38/// syntactic form of both features is nearly identical, we parse all
39/// of the template headers together and let semantic analysis sort
40/// the declarations from the explicit specializations.
Douglas Gregorb3bec712008-12-01 23:54:00 +000041///
42/// template-declaration: [C++ temp]
43/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
Douglas Gregora08b6c72009-02-17 23:15:12 +000044///
45/// explicit-specialization: [ C++ temp.expl.spec]
46/// 'template' '<' '>' declaration
Chris Lattner5261d0c2009-03-28 19:18:32 +000047Parser::DeclPtrTy
Anders Carlssoned20fb92009-03-26 00:52:18 +000048Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
Chris Lattner9802a0a2009-04-02 04:16:50 +000049 SourceLocation &DeclEnd,
Anders Carlssoned20fb92009-03-26 00:52:18 +000050 AccessSpecifier AS) {
Douglas Gregorb3bec712008-12-01 23:54:00 +000051 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
52 "Token does not start a template declaration.");
53
Douglas Gregor8e7f9572008-12-02 00:41:28 +000054 // Enter template-parameter scope.
Douglas Gregor95d40792008-12-10 06:34:36 +000055 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Douglas Gregor8e7f9572008-12-02 00:41:28 +000056
Douglas Gregor52473432008-12-24 02:52:09 +000057 // Parse multiple levels of template headers within this template
58 // parameter scope, e.g.,
59 //
60 // template<typename T>
61 // template<typename U>
62 // class A<T>::B { ... };
63 //
64 // We parse multiple levels non-recursively so that we can build a
65 // single data structure containing all of the template parameter
Douglas Gregora08b6c72009-02-17 23:15:12 +000066 // lists to easily differentiate between the case above and:
Douglas Gregor52473432008-12-24 02:52:09 +000067 //
68 // template<typename T>
69 // class A {
70 // template<typename U> class B;
71 // };
72 //
73 // In the first case, the action for declaring A<T>::B receives
74 // both template parameter lists. In the second case, the action for
75 // defining A<T>::B receives just the inner template parameter list
76 // (and retrieves the outer template parameter list from its
77 // context).
Douglas Gregora9db0fa2009-05-12 23:25:50 +000078 bool isSpecialiation = true;
Douglas Gregor52473432008-12-24 02:52:09 +000079 TemplateParameterLists ParamLists;
80 do {
81 // Consume the 'export', if any.
82 SourceLocation ExportLoc;
83 if (Tok.is(tok::kw_export)) {
84 ExportLoc = ConsumeToken();
85 }
86
87 // Consume the 'template', which should be here.
88 SourceLocation TemplateLoc;
89 if (Tok.is(tok::kw_template)) {
90 TemplateLoc = ConsumeToken();
91 } else {
92 Diag(Tok.getLocation(), diag::err_expected_template);
Chris Lattner5261d0c2009-03-28 19:18:32 +000093 return DeclPtrTy();
Douglas Gregor52473432008-12-24 02:52:09 +000094 }
95
96 // Parse the '<' template-parameter-list '>'
97 SourceLocation LAngleLoc, RAngleLoc;
98 TemplateParameterList TemplateParams;
99 ParseTemplateParameters(ParamLists.size(), TemplateParams, LAngleLoc,
100 RAngleLoc);
101
Douglas Gregora9db0fa2009-05-12 23:25:50 +0000102 if (!TemplateParams.empty())
103 isSpecialiation = false;
104
Douglas Gregor52473432008-12-24 02:52:09 +0000105 ParamLists.push_back(
106 Actions.ActOnTemplateParameterList(ParamLists.size(), ExportLoc,
107 TemplateLoc, LAngleLoc,
Jay Foad9e6bef42009-05-21 09:52:38 +0000108 TemplateParams.data(),
Douglas Gregor52473432008-12-24 02:52:09 +0000109 TemplateParams.size(), RAngleLoc));
110 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
111
112 // Parse the actual template declaration.
Douglas Gregora9db0fa2009-05-12 23:25:50 +0000113 return ParseSingleDeclarationAfterTemplate(Context,
114 ParsedTemplateInfo(&ParamLists,
115 isSpecialiation),
Douglas Gregore3298aa2009-05-12 21:31:51 +0000116 DeclEnd, AS);
117}
Chris Lattnera17991f2009-03-29 16:50:03 +0000118
Douglas Gregore3298aa2009-05-12 21:31:51 +0000119/// \brief Parse a single declaration that declares a template,
120/// template specialization, or explicit instantiation of a template.
121///
122/// \param TemplateParams if non-NULL, the template parameter lists
123/// that preceded this declaration. In this case, the declaration is a
124/// template declaration, out-of-line definition of a template, or an
125/// explicit template specialization. When NULL, the declaration is an
126/// explicit template instantiation.
127///
128/// \param TemplateLoc when TemplateParams is NULL, the location of
129/// the 'template' keyword that indicates that we have an explicit
130/// template instantiation.
131///
132/// \param DeclEnd will receive the source location of the last token
133/// within this declaration.
134///
135/// \param AS the access specifier associated with this
136/// declaration. Will be AS_none for namespace-scope declarations.
137///
138/// \returns the new declaration.
139Parser::DeclPtrTy
140Parser::ParseSingleDeclarationAfterTemplate(
141 unsigned Context,
Douglas Gregora9db0fa2009-05-12 23:25:50 +0000142 const ParsedTemplateInfo &TemplateInfo,
Douglas Gregore3298aa2009-05-12 21:31:51 +0000143 SourceLocation &DeclEnd,
144 AccessSpecifier AS) {
Douglas Gregora9db0fa2009-05-12 23:25:50 +0000145 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
146 "Template information required");
147
Douglas Gregore3298aa2009-05-12 21:31:51 +0000148 // Parse the declaration specifiers.
149 DeclSpec DS;
150 // FIXME: Pass TemplateLoc through for explicit template instantiations
Douglas Gregora9db0fa2009-05-12 23:25:50 +0000151 ParseDeclarationSpecifiers(DS, TemplateInfo, AS);
Douglas Gregore3298aa2009-05-12 21:31:51 +0000152
153 if (Tok.is(tok::semi)) {
154 DeclEnd = ConsumeToken();
155 return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
156 }
157
158 // Parse the declarator.
159 Declarator DeclaratorInfo(DS, (Declarator::TheContext)Context);
160 ParseDeclarator(DeclaratorInfo);
161 // Error parsing the declarator?
162 if (!DeclaratorInfo.hasName()) {
163 // If so, skip until the semi-colon or a }.
164 SkipUntil(tok::r_brace, true, true);
165 if (Tok.is(tok::semi))
166 ConsumeToken();
167 return DeclPtrTy();
168 }
169
170 // If we have a declaration or declarator list, handle it.
171 if (isDeclarationAfterDeclarator()) {
172 // Parse this declaration.
173 DeclPtrTy ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo);
174
175 if (Tok.is(tok::comma)) {
176 Diag(Tok, diag::err_multiple_template_declarators)
Douglas Gregora9db0fa2009-05-12 23:25:50 +0000177 << (int)TemplateInfo.Kind;
Douglas Gregore3298aa2009-05-12 21:31:51 +0000178 SkipUntil(tok::semi, true, false);
179 return ThisDecl;
180 }
181
182 // Eat the semi colon after the declaration.
183 ExpectAndConsume(tok::semi, diag::err_expected_semi_declation);
184 return ThisDecl;
185 }
186
187 if (DeclaratorInfo.isFunctionDeclarator() &&
188 isStartOfFunctionDefinition()) {
189 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
190 Diag(Tok, diag::err_function_declared_typedef);
191
192 if (Tok.is(tok::l_brace)) {
193 // This recovery skips the entire function body. It would be nice
194 // to simply call ParseFunctionDefinition() below, however Sema
195 // assumes the declarator represents a function, not a typedef.
196 ConsumeBrace();
197 SkipUntil(tok::r_brace, true);
198 } else {
199 SkipUntil(tok::semi);
200 }
201 return DeclPtrTy();
202 }
203 return ParseFunctionDefinition(DeclaratorInfo);
204 }
205
206 if (DeclaratorInfo.isFunctionDeclarator())
207 Diag(Tok, diag::err_expected_fn_body);
208 else
209 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
210 SkipUntil(tok::semi);
211 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000212}
213
214/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregor279272e2009-02-04 19:02:06 +0000215/// angle brackets. Depth is the depth of this template-parameter-list, which
216/// is the number of template headers directly enclosing this template header.
217/// TemplateParams is the current list of template parameters we're building.
218/// The template parameter we parse will be added to this list. LAngleLoc and
219/// RAngleLoc will receive the positions of the '<' and '>', respectively,
220/// that enclose this template parameter list.
Douglas Gregor52473432008-12-24 02:52:09 +0000221bool Parser::ParseTemplateParameters(unsigned Depth,
222 TemplateParameterList &TemplateParams,
223 SourceLocation &LAngleLoc,
224 SourceLocation &RAngleLoc) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000225 // Get the template parameter list.
226 if(!Tok.is(tok::less)) {
227 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
228 return false;
229 }
Douglas Gregor52473432008-12-24 02:52:09 +0000230 LAngleLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000231
232 // Try to parse the template parameter list.
Douglas Gregor52473432008-12-24 02:52:09 +0000233 if (Tok.is(tok::greater))
234 RAngleLoc = ConsumeToken();
235 else if(ParseTemplateParameterList(Depth, TemplateParams)) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000236 if(!Tok.is(tok::greater)) {
237 Diag(Tok.getLocation(), diag::err_expected_greater);
238 return false;
239 }
Douglas Gregor52473432008-12-24 02:52:09 +0000240 RAngleLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000241 }
242 return true;
243}
244
245/// ParseTemplateParameterList - Parse a template parameter list. If
246/// the parsing fails badly (i.e., closing bracket was left out), this
247/// will try to put the token stream in a reasonable position (closing
248/// a statement, etc.) and return false.
249///
250/// template-parameter-list: [C++ temp]
251/// template-parameter
252/// template-parameter-list ',' template-parameter
Douglas Gregor52473432008-12-24 02:52:09 +0000253bool
254Parser::ParseTemplateParameterList(unsigned Depth,
255 TemplateParameterList &TemplateParams) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000256 while(1) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000257 if (DeclPtrTy TmpParam
Douglas Gregor52473432008-12-24 02:52:09 +0000258 = ParseTemplateParameter(Depth, TemplateParams.size())) {
259 TemplateParams.push_back(TmpParam);
260 } else {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000261 // If we failed to parse a template parameter, skip until we find
262 // a comma or closing brace.
263 SkipUntil(tok::comma, tok::greater, true, true);
264 }
265
266 // Did we find a comma or the end of the template parmeter list?
267 if(Tok.is(tok::comma)) {
268 ConsumeToken();
269 } else if(Tok.is(tok::greater)) {
270 // Don't consume this... that's done by template parser.
271 break;
272 } else {
273 // Somebody probably forgot to close the template. Skip ahead and
274 // try to get out of the expression. This error is currently
275 // subsumed by whatever goes on in ParseTemplateParameter.
276 // TODO: This could match >>, and it would be nice to avoid those
277 // silly errors with template <vec<T>>.
278 // Diag(Tok.getLocation(), diag::err_expected_comma_greater);
279 SkipUntil(tok::greater, true, true);
280 return false;
281 }
282 }
283 return true;
284}
285
286/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
287///
288/// template-parameter: [C++ temp.param]
289/// type-parameter
290/// parameter-declaration
291///
292/// type-parameter: (see below)
293/// 'class' identifier[opt]
294/// 'class' identifier[opt] '=' type-id
295/// 'typename' identifier[opt]
296/// 'typename' identifier[opt] '=' type-id
297/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
298/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
Chris Lattner5261d0c2009-03-28 19:18:32 +0000299Parser::DeclPtrTy
Douglas Gregor52473432008-12-24 02:52:09 +0000300Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Chris Lattner4e7a4202009-01-04 23:51:17 +0000301 if(Tok.is(tok::kw_class) ||
302 (Tok.is(tok::kw_typename) &&
303 // FIXME: Next token has not been annotated!
Chris Lattner5d7eace2009-01-06 05:06:21 +0000304 NextToken().isNot(tok::annot_typename))) {
Douglas Gregor52473432008-12-24 02:52:09 +0000305 return ParseTypeParameter(Depth, Position);
Douglas Gregorb3bec712008-12-01 23:54:00 +0000306 }
Chris Lattner4e7a4202009-01-04 23:51:17 +0000307
308 if(Tok.is(tok::kw_template))
309 return ParseTemplateTemplateParameter(Depth, Position);
310
311 // If it's none of the above, then it must be a parameter declaration.
312 // NOTE: This will pick up errors in the closure of the template parameter
313 // list (e.g., template < ; Check here to implement >> style closures.
314 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregorb3bec712008-12-01 23:54:00 +0000315}
316
317/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
318/// Other kinds of template parameters are parsed in
319/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
320///
321/// type-parameter: [C++ temp.param]
322/// 'class' identifier[opt]
323/// 'class' identifier[opt] '=' type-id
324/// 'typename' identifier[opt]
325/// 'typename' identifier[opt] '=' type-id
Chris Lattner5261d0c2009-03-28 19:18:32 +0000326Parser::DeclPtrTy Parser::ParseTypeParameter(unsigned Depth, unsigned Position){
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000327 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
328 "A type-parameter starts with 'class' or 'typename'");
329
330 // Consume the 'class' or 'typename' keyword.
331 bool TypenameKeyword = Tok.is(tok::kw_typename);
332 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000333
334 // Grab the template parameter name (if given)
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000335 SourceLocation NameLoc;
336 IdentifierInfo* ParamName = 0;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000337 if(Tok.is(tok::identifier)) {
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000338 ParamName = Tok.getIdentifierInfo();
339 NameLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000340 } else if(Tok.is(tok::equal) || Tok.is(tok::comma) ||
341 Tok.is(tok::greater)) {
342 // Unnamed template parameter. Don't have to do anything here, just
343 // don't consume this token.
344 } else {
345 Diag(Tok.getLocation(), diag::err_expected_ident);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000346 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000347 }
348
Chris Lattner5261d0c2009-03-28 19:18:32 +0000349 DeclPtrTy TypeParam = Actions.ActOnTypeParameter(CurScope, TypenameKeyword,
350 KeyLoc, ParamName, NameLoc,
351 Depth, Position);
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000352
Douglas Gregorb3bec712008-12-01 23:54:00 +0000353 // Grab a default type id (if given).
Douglas Gregorb3bec712008-12-01 23:54:00 +0000354 if(Tok.is(tok::equal)) {
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000355 SourceLocation EqualLoc = ConsumeToken();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000356 SourceLocation DefaultLoc = Tok.getLocation();
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000357 TypeResult DefaultType = ParseTypeName();
358 if (!DefaultType.isInvalid())
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000359 Actions.ActOnTypeParameterDefault(TypeParam, EqualLoc, DefaultLoc,
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000360 DefaultType.get());
Douglas Gregorb3bec712008-12-01 23:54:00 +0000361 }
362
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000363 return TypeParam;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000364}
365
366/// ParseTemplateTemplateParameter - Handle the parsing of template
367/// template parameters.
368///
369/// type-parameter: [C++ temp.param]
370/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
371/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
Chris Lattner5261d0c2009-03-28 19:18:32 +0000372Parser::DeclPtrTy
Douglas Gregor52473432008-12-24 02:52:09 +0000373Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000374 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
375
376 // Handle the template <...> part.
377 SourceLocation TemplateLoc = ConsumeToken();
Douglas Gregor52473432008-12-24 02:52:09 +0000378 TemplateParameterList TemplateParams;
Douglas Gregord406b032009-02-06 22:42:48 +0000379 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor77f7ced2009-02-10 19:52:54 +0000380 {
381 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
382 if(!ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
383 RAngleLoc)) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000384 return DeclPtrTy();
Douglas Gregor77f7ced2009-02-10 19:52:54 +0000385 }
Douglas Gregorb3bec712008-12-01 23:54:00 +0000386 }
387
388 // Generate a meaningful error if the user forgot to put class before the
389 // identifier, comma, or greater.
390 if(!Tok.is(tok::kw_class)) {
391 Diag(Tok.getLocation(), diag::err_expected_class_before)
392 << PP.getSpelling(Tok);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000393 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000394 }
395 SourceLocation ClassLoc = ConsumeToken();
396
397 // Get the identifier, if given.
Douglas Gregor279272e2009-02-04 19:02:06 +0000398 SourceLocation NameLoc;
399 IdentifierInfo* ParamName = 0;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000400 if(Tok.is(tok::identifier)) {
Douglas Gregor279272e2009-02-04 19:02:06 +0000401 ParamName = Tok.getIdentifierInfo();
402 NameLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000403 } else if(Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
404 // Unnamed template parameter. Don't have to do anything here, just
405 // don't consume this token.
406 } else {
407 Diag(Tok.getLocation(), diag::err_expected_ident);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000408 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000409 }
410
Douglas Gregord406b032009-02-06 22:42:48 +0000411 TemplateParamsTy *ParamList =
412 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
413 TemplateLoc, LAngleLoc,
414 &TemplateParams[0],
415 TemplateParams.size(),
416 RAngleLoc);
417
Chris Lattner5261d0c2009-03-28 19:18:32 +0000418 Parser::DeclPtrTy Param
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000419 = Actions.ActOnTemplateTemplateParameter(CurScope, TemplateLoc,
420 ParamList, ParamName,
421 NameLoc, Depth, Position);
422
423 // Get the a default value, if given.
424 if (Tok.is(tok::equal)) {
425 SourceLocation EqualLoc = ConsumeToken();
426 OwningExprResult DefaultExpr = ParseCXXIdExpression();
427 if (DefaultExpr.isInvalid())
428 return Param;
429 else if (Param)
430 Actions.ActOnTemplateTemplateParameterDefault(Param, EqualLoc,
431 move(DefaultExpr));
432 }
433
434 return Param;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000435}
436
437/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
438/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregor2fa10442008-12-18 19:37:40 +0000439///
Douglas Gregorb3bec712008-12-01 23:54:00 +0000440/// template-parameter:
441/// ...
442/// parameter-declaration
443///
444/// NOTE: It would be ideal to simply call out to ParseParameterDeclaration(),
445/// but that didn't work out to well. Instead, this tries to recrate the basic
446/// parsing of parameter declarations, but tries to constrain it for template
447/// parameters.
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000448/// FIXME: We need to make a ParseParameterDeclaration that works for
449/// non-type template parameters and normal function parameters.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000450Parser::DeclPtrTy
Douglas Gregor52473432008-12-24 02:52:09 +0000451Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000452 SourceLocation StartLoc = Tok.getLocation();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000453
454 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000455 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregorb3bec712008-12-01 23:54:00 +0000456 // declarators (parts of declarators?) are accepted for parameters.
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000457 DeclSpec DS;
458 ParseDeclarationSpecifiers(DS);
Douglas Gregorb3bec712008-12-01 23:54:00 +0000459
460 // Parse this as a typename.
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000461 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
462 ParseDeclarator(ParamDecl);
Chris Lattner8376d2e2009-01-05 01:24:05 +0000463 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified && !DS.getTypeRep()) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000464 // This probably shouldn't happen - and it's more of a Sema thing, but
465 // basically we didn't parse the type name because we couldn't associate
466 // it with an AST node. we should just skip to the comma or greater.
467 // TODO: This is currently a placeholder for some kind of Sema Error.
468 Diag(Tok.getLocation(), diag::err_parse_error);
469 SkipUntil(tok::comma, tok::greater, true, true);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000470 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000471 }
472
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000473 // Create the parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000474 DeclPtrTy Param = Actions.ActOnNonTypeTemplateParameter(CurScope, ParamDecl,
475 Depth, Position);
Douglas Gregorb3bec712008-12-01 23:54:00 +0000476
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000477 // If there is a default value, parse it.
Chris Lattner8376d2e2009-01-05 01:24:05 +0000478 if (Tok.is(tok::equal)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000479 SourceLocation EqualLoc = ConsumeToken();
480
481 // C++ [temp.param]p15:
482 // When parsing a default template-argument for a non-type
483 // template-parameter, the first non-nested > is taken as the
484 // end of the template-parameter-list rather than a greater-than
485 // operator.
486 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
487
488 OwningExprResult DefaultArg = ParseAssignmentExpression();
489 if (DefaultArg.isInvalid())
490 SkipUntil(tok::comma, tok::greater, true, true);
491 else if (Param)
492 Actions.ActOnNonTypeTemplateParameterDefault(Param, EqualLoc,
493 move(DefaultArg));
Douglas Gregorb3bec712008-12-01 23:54:00 +0000494 }
495
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000496 return Param;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000497}
Douglas Gregor2fa10442008-12-18 19:37:40 +0000498
Douglas Gregora08b6c72009-02-17 23:15:12 +0000499/// \brief Parses a template-id that after the template name has
500/// already been parsed.
501///
502/// This routine takes care of parsing the enclosed template argument
503/// list ('<' template-parameter-list [opt] '>') and placing the
504/// results into a form that can be transferred to semantic analysis.
505///
506/// \param Template the template declaration produced by isTemplateName
507///
508/// \param TemplateNameLoc the source location of the template name
509///
510/// \param SS if non-NULL, the nested-name-specifier preceding the
511/// template name.
512///
513/// \param ConsumeLastToken if true, then we will consume the last
514/// token that forms the template-id. Otherwise, we will leave the
515/// last token in the stream (e.g., so that it can be replaced with an
516/// annotation token).
517bool
Douglas Gregordd13e842009-03-30 22:58:21 +0000518Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
Douglas Gregora08b6c72009-02-17 23:15:12 +0000519 SourceLocation TemplateNameLoc,
520 const CXXScopeSpec *SS,
521 bool ConsumeLastToken,
522 SourceLocation &LAngleLoc,
523 TemplateArgList &TemplateArgs,
524 TemplateArgIsTypeList &TemplateArgIsType,
525 TemplateArgLocationList &TemplateArgLocations,
526 SourceLocation &RAngleLoc) {
527 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
528
529 // Consume the '<'.
530 LAngleLoc = ConsumeToken();
531
532 // Parse the optional template-argument-list.
533 bool Invalid = false;
534 {
535 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
536 if (Tok.isNot(tok::greater))
537 Invalid = ParseTemplateArgumentList(TemplateArgs, TemplateArgIsType,
538 TemplateArgLocations);
539
540 if (Invalid) {
541 // Try to find the closing '>'.
542 SkipUntil(tok::greater, true, !ConsumeLastToken);
543
544 return true;
545 }
546 }
547
Douglas Gregorf2d87392009-02-25 23:02:36 +0000548 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
Douglas Gregora08b6c72009-02-17 23:15:12 +0000549 return true;
550
Douglas Gregorf2d87392009-02-25 23:02:36 +0000551 // Determine the location of the '>' or '>>'. Only consume this
552 // token if the caller asked us to.
Douglas Gregora08b6c72009-02-17 23:15:12 +0000553 RAngleLoc = Tok.getLocation();
554
Douglas Gregorf2d87392009-02-25 23:02:36 +0000555 if (Tok.is(tok::greatergreater)) {
Douglas Gregor3bb30002009-02-26 21:00:50 +0000556 if (!getLang().CPlusPlus0x) {
557 const char *ReplaceStr = "> >";
558 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
559 ReplaceStr = "> > ";
560
561 Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space)
Douglas Gregor61be3602009-02-27 17:53:17 +0000562 << CodeModificationHint::CreateReplacement(
563 SourceRange(Tok.getLocation()), ReplaceStr);
Douglas Gregor3bb30002009-02-26 21:00:50 +0000564 }
Douglas Gregorf2d87392009-02-25 23:02:36 +0000565
566 Tok.setKind(tok::greater);
567 if (!ConsumeLastToken) {
568 // Since we're not supposed to consume the '>>' token, we need
569 // to insert a second '>' token after the first.
570 PP.EnterToken(Tok);
571 }
572 } else if (ConsumeLastToken)
Douglas Gregora08b6c72009-02-17 23:15:12 +0000573 ConsumeToken();
574
575 return false;
576}
577
Douglas Gregor0c281a82009-02-25 19:37:18 +0000578/// \brief Replace the tokens that form a simple-template-id with an
579/// annotation token containing the complete template-id.
580///
581/// The first token in the stream must be the name of a template that
582/// is followed by a '<'. This routine will parse the complete
583/// simple-template-id and replace the tokens with a single annotation
584/// token with one of two different kinds: if the template-id names a
585/// type (and \p AllowTypeAnnotation is true), the annotation token is
586/// a type annotation that includes the optional nested-name-specifier
587/// (\p SS). Otherwise, the annotation token is a template-id
588/// annotation that does not include the optional
589/// nested-name-specifier.
590///
591/// \param Template the declaration of the template named by the first
592/// token (an identifier), as returned from \c Action::isTemplateName().
593///
594/// \param TemplateNameKind the kind of template that \p Template
595/// refers to, as returned from \c Action::isTemplateName().
596///
597/// \param SS if non-NULL, the nested-name-specifier that precedes
598/// this template name.
599///
600/// \param TemplateKWLoc if valid, specifies that this template-id
601/// annotation was preceded by the 'template' keyword and gives the
602/// location of that keyword. If invalid (the default), then this
603/// template-id was not preceded by a 'template' keyword.
604///
605/// \param AllowTypeAnnotation if true (the default), then a
606/// simple-template-id that refers to a class template, template
607/// template parameter, or other template that produces a type will be
608/// replaced with a type annotation token. Otherwise, the
609/// simple-template-id is always replaced with a template-id
610/// annotation token.
Douglas Gregordd13e842009-03-30 22:58:21 +0000611void Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Douglas Gregor0c281a82009-02-25 19:37:18 +0000612 const CXXScopeSpec *SS,
613 SourceLocation TemplateKWLoc,
614 bool AllowTypeAnnotation) {
Douglas Gregor2fa10442008-12-18 19:37:40 +0000615 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
616 assert(Template && Tok.is(tok::identifier) && NextToken().is(tok::less) &&
617 "Parser isn't at the beginning of a template-id");
618
619 // Consume the template-name.
Douglas Gregor0c281a82009-02-25 19:37:18 +0000620 IdentifierInfo *Name = Tok.getIdentifierInfo();
Douglas Gregor2fa10442008-12-18 19:37:40 +0000621 SourceLocation TemplateNameLoc = ConsumeToken();
622
Douglas Gregora08b6c72009-02-17 23:15:12 +0000623 // Parse the enclosed template argument list.
624 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor6f37b582009-02-09 19:34:22 +0000625 TemplateArgList TemplateArgs;
626 TemplateArgIsTypeList TemplateArgIsType;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000627 TemplateArgLocationList TemplateArgLocations;
Douglas Gregora08b6c72009-02-17 23:15:12 +0000628 bool Invalid = ParseTemplateIdAfterTemplateName(Template, TemplateNameLoc,
629 SS, false, LAngleLoc,
630 TemplateArgs,
631 TemplateArgIsType,
632 TemplateArgLocations,
633 RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000634
Jay Foad9e6bef42009-05-21 09:52:38 +0000635 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
636 TemplateArgIsType.data(),
Douglas Gregora08b6c72009-02-17 23:15:12 +0000637 TemplateArgs.size());
Douglas Gregoraf0d0092009-02-09 21:04:56 +0000638
Douglas Gregora08b6c72009-02-17 23:15:12 +0000639 if (Invalid) // FIXME: How to recover from a broken template-id?
640 return;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000641
Douglas Gregor8e458f42009-02-09 18:46:07 +0000642 // Build the annotation token.
Douglas Gregoraabb8502009-03-31 00:43:58 +0000643 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
Douglas Gregora08b6c72009-02-17 23:15:12 +0000644 Action::TypeResult Type
Douglas Gregordd13e842009-03-30 22:58:21 +0000645 = Actions.ActOnTemplateIdType(Template, TemplateNameLoc,
646 LAngleLoc, TemplateArgsPtr,
647 &TemplateArgLocations[0],
648 RAngleLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +0000649 if (Type.isInvalid()) // FIXME: better recovery?
650 return;
651
652 Tok.setKind(tok::annot_typename);
653 Tok.setAnnotationValue(Type.get());
Douglas Gregor0c281a82009-02-25 19:37:18 +0000654 if (SS && SS->isNotEmpty())
655 Tok.setLocation(SS->getBeginLoc());
656 else if (TemplateKWLoc.isValid())
657 Tok.setLocation(TemplateKWLoc);
658 else
659 Tok.setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +0000660 } else {
Douglas Gregoraabb8502009-03-31 00:43:58 +0000661 // Build a template-id annotation token that can be processed
662 // later.
Douglas Gregor0c281a82009-02-25 19:37:18 +0000663 Tok.setKind(tok::annot_template_id);
Douglas Gregor8e458f42009-02-09 18:46:07 +0000664 TemplateIdAnnotation *TemplateId
Douglas Gregor0c281a82009-02-25 19:37:18 +0000665 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
Douglas Gregor8e458f42009-02-09 18:46:07 +0000666 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregor0c281a82009-02-25 19:37:18 +0000667 TemplateId->Name = Name;
Chris Lattner5261d0c2009-03-28 19:18:32 +0000668 TemplateId->Template = Template.getAs<void*>();
Douglas Gregor0c281a82009-02-25 19:37:18 +0000669 TemplateId->Kind = TNK;
Douglas Gregor8e458f42009-02-09 18:46:07 +0000670 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor0c281a82009-02-25 19:37:18 +0000671 TemplateId->RAngleLoc = RAngleLoc;
672 void **Args = TemplateId->getTemplateArgs();
673 bool *ArgIsType = TemplateId->getTemplateArgIsType();
674 SourceLocation *ArgLocs = TemplateId->getTemplateArgLocations();
675 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg) {
Douglas Gregor8e458f42009-02-09 18:46:07 +0000676 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor0c281a82009-02-25 19:37:18 +0000677 ArgIsType[Arg] = TemplateArgIsType[Arg];
678 ArgLocs[Arg] = TemplateArgLocations[Arg];
679 }
Douglas Gregor8e458f42009-02-09 18:46:07 +0000680 Tok.setAnnotationValue(TemplateId);
Douglas Gregor0c281a82009-02-25 19:37:18 +0000681 if (TemplateKWLoc.isValid())
682 Tok.setLocation(TemplateKWLoc);
683 else
684 Tok.setLocation(TemplateNameLoc);
685
686 TemplateArgsPtr.release();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000687 }
688
689 // Common fields for the annotation token
Douglas Gregor2fa10442008-12-18 19:37:40 +0000690 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregor2fa10442008-12-18 19:37:40 +0000691
Douglas Gregor2fa10442008-12-18 19:37:40 +0000692 // In case the tokens were cached, have Preprocessor replace them with the
693 // annotation token.
694 PP.AnnotateCachedTokens(Tok);
695}
696
Douglas Gregor0c281a82009-02-25 19:37:18 +0000697/// \brief Replaces a template-id annotation token with a type
698/// annotation token.
699///
Douglas Gregord7cb0372009-04-01 21:51:26 +0000700/// If there was a failure when forming the type from the template-id,
701/// a type annotation token will still be created, but will have a
702/// NULL type pointer to signify an error.
703void Parser::AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS) {
Douglas Gregor0c281a82009-02-25 19:37:18 +0000704 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
705
706 TemplateIdAnnotation *TemplateId
707 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
Douglas Gregoraabb8502009-03-31 00:43:58 +0000708 assert((TemplateId->Kind == TNK_Type_template ||
709 TemplateId->Kind == TNK_Dependent_template_name) &&
710 "Only works for type and dependent templates");
Douglas Gregor0c281a82009-02-25 19:37:18 +0000711
712 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
713 TemplateId->getTemplateArgs(),
714 TemplateId->getTemplateArgIsType(),
715 TemplateId->NumArgs);
716
717 Action::TypeResult Type
Douglas Gregordd13e842009-03-30 22:58:21 +0000718 = Actions.ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
719 TemplateId->TemplateNameLoc,
720 TemplateId->LAngleLoc,
721 TemplateArgsPtr,
722 TemplateId->getTemplateArgLocations(),
723 TemplateId->RAngleLoc);
Douglas Gregor0c281a82009-02-25 19:37:18 +0000724 // Create the new "type" annotation token.
725 Tok.setKind(tok::annot_typename);
Douglas Gregord7cb0372009-04-01 21:51:26 +0000726 Tok.setAnnotationValue(Type.isInvalid()? 0 : Type.get());
Douglas Gregor0c281a82009-02-25 19:37:18 +0000727 if (SS && SS->isNotEmpty()) // it was a C++ qualified type name.
728 Tok.setLocation(SS->getBeginLoc());
729
730 // We might be backtracking, in which case we need to replace the
731 // template-id annotation token with the type annotation within the
732 // set of cached tokens. That way, we won't try to form the same
733 // class template specialization again.
734 PP.ReplaceLastTokenWithAnnotation(Tok);
735 TemplateId->Destroy();
Douglas Gregor0c281a82009-02-25 19:37:18 +0000736}
737
Douglas Gregor2fa10442008-12-18 19:37:40 +0000738/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
739///
740/// template-argument: [C++ 14.2]
741/// assignment-expression
742/// type-id
743/// id-expression
Douglas Gregor6f37b582009-02-09 19:34:22 +0000744void *Parser::ParseTemplateArgument(bool &ArgIsType) {
Douglas Gregor8e458f42009-02-09 18:46:07 +0000745 // C++ [temp.arg]p2:
746 // In a template-argument, an ambiguity between a type-id and an
747 // expression is resolved to a type-id, regardless of the form of
748 // the corresponding template-parameter.
749 //
750 // Therefore, we initially try to parse a type-id.
Douglas Gregor341ac792009-02-10 00:53:15 +0000751 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor6f37b582009-02-09 19:34:22 +0000752 ArgIsType = true;
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000753 TypeResult TypeArg = ParseTypeName();
754 if (TypeArg.isInvalid())
755 return 0;
756 return TypeArg.get();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000757 }
758
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000759 OwningExprResult ExprArg = ParseAssignmentExpression();
760 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor6f37b582009-02-09 19:34:22 +0000761 return 0;
Douglas Gregor8e458f42009-02-09 18:46:07 +0000762
Douglas Gregor6f37b582009-02-09 19:34:22 +0000763 ArgIsType = false;
764 return ExprArg.release();
Douglas Gregor2fa10442008-12-18 19:37:40 +0000765}
766
767/// ParseTemplateArgumentList - Parse a C++ template-argument-list
768/// (C++ [temp.names]). Returns true if there was an error.
769///
770/// template-argument-list: [C++ 14.2]
771/// template-argument
772/// template-argument-list ',' template-argument
Douglas Gregor6f37b582009-02-09 19:34:22 +0000773bool
774Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000775 TemplateArgIsTypeList &TemplateArgIsType,
776 TemplateArgLocationList &TemplateArgLocations) {
Douglas Gregor2fa10442008-12-18 19:37:40 +0000777 while (true) {
Douglas Gregor6f37b582009-02-09 19:34:22 +0000778 bool IsType = false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000779 SourceLocation Loc = Tok.getLocation();
Douglas Gregor6f37b582009-02-09 19:34:22 +0000780 void *Arg = ParseTemplateArgument(IsType);
781 if (Arg) {
782 TemplateArgs.push_back(Arg);
783 TemplateArgIsType.push_back(IsType);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000784 TemplateArgLocations.push_back(Loc);
Douglas Gregor6f37b582009-02-09 19:34:22 +0000785 } else {
Douglas Gregor2fa10442008-12-18 19:37:40 +0000786 SkipUntil(tok::comma, tok::greater, true, true);
787 return true;
788 }
Douglas Gregor6f37b582009-02-09 19:34:22 +0000789
Douglas Gregor2fa10442008-12-18 19:37:40 +0000790 // If the next token is a comma, consume it and keep reading
791 // arguments.
792 if (Tok.isNot(tok::comma)) break;
793
794 // Consume the comma.
795 ConsumeToken();
796 }
797
Douglas Gregorf2d87392009-02-25 23:02:36 +0000798 return Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater);
Douglas Gregor2fa10442008-12-18 19:37:40 +0000799}
800
Douglas Gregore3298aa2009-05-12 21:31:51 +0000801/// \brief Parse a C++ explicit template instantiation
802/// (C++ [temp.explicit]).
803///
804/// explicit-instantiation:
805/// 'template' declaration
Douglas Gregora9db0fa2009-05-12 23:25:50 +0000806Parser::DeclPtrTy
807Parser::ParseExplicitInstantiation(SourceLocation TemplateLoc,
808 SourceLocation &DeclEnd) {
809 return ParseSingleDeclarationAfterTemplate(Declarator::FileContext,
810 ParsedTemplateInfo(TemplateLoc),
811 DeclEnd, AS_none);
Douglas Gregore3298aa2009-05-12 21:31:51 +0000812}