blob: 30924b217f2b527b5e3e4d42f5655030fd885c62 [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)
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000293/// 'class' ...[opt] identifier[opt]
Douglas Gregorb3bec712008-12-01 23:54:00 +0000294/// 'class' identifier[opt] '=' type-id
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000295/// 'typename' ...[opt] identifier[opt]
Douglas Gregorb3bec712008-12-01 23:54:00 +0000296/// 'typename' identifier[opt] '=' type-id
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000297/// 'template' ...[opt] '<' template-parameter-list '>' 'class' identifier[opt]
Douglas Gregorb3bec712008-12-01 23:54:00 +0000298/// '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]
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000322/// 'class' ...[opt] identifier[opt]
Douglas Gregorb3bec712008-12-01 23:54:00 +0000323/// 'class' identifier[opt] '=' type-id
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000324/// 'typename' ...[opt] identifier[opt]
Douglas Gregorb3bec712008-12-01 23:54:00 +0000325/// '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
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000334 // Grab the ellipsis (if given).
335 bool Ellipsis = false;
336 SourceLocation EllipsisLoc;
337 if (getLang().CPlusPlus0x && Tok.is(tok::ellipsis)) {
338 Ellipsis = true;
339 EllipsisLoc = ConsumeToken();
340 }
341
Douglas Gregorb3bec712008-12-01 23:54:00 +0000342 // Grab the template parameter name (if given)
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000343 SourceLocation NameLoc;
344 IdentifierInfo* ParamName = 0;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000345 if(Tok.is(tok::identifier)) {
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000346 ParamName = Tok.getIdentifierInfo();
347 NameLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000348 } else if(Tok.is(tok::equal) || Tok.is(tok::comma) ||
349 Tok.is(tok::greater)) {
350 // Unnamed template parameter. Don't have to do anything here, just
351 // don't consume this token.
352 } else {
353 Diag(Tok.getLocation(), diag::err_expected_ident);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000354 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000355 }
356
Chris Lattner5261d0c2009-03-28 19:18:32 +0000357 DeclPtrTy TypeParam = Actions.ActOnTypeParameter(CurScope, TypenameKeyword,
Anders Carlsson9c85fa02009-06-12 19:58:00 +0000358 Ellipsis, EllipsisLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000359 KeyLoc, ParamName, NameLoc,
360 Depth, Position);
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000361
Douglas Gregorb3bec712008-12-01 23:54:00 +0000362 // Grab a default type id (if given).
Douglas Gregorb3bec712008-12-01 23:54:00 +0000363 if(Tok.is(tok::equal)) {
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000364 SourceLocation EqualLoc = ConsumeToken();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000365 SourceLocation DefaultLoc = Tok.getLocation();
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000366 TypeResult DefaultType = ParseTypeName();
367 if (!DefaultType.isInvalid())
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000368 Actions.ActOnTypeParameterDefault(TypeParam, EqualLoc, DefaultLoc,
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000369 DefaultType.get());
Douglas Gregorb3bec712008-12-01 23:54:00 +0000370 }
371
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000372 return TypeParam;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000373}
374
375/// ParseTemplateTemplateParameter - Handle the parsing of template
376/// template parameters.
377///
378/// type-parameter: [C++ temp.param]
379/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
380/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
Chris Lattner5261d0c2009-03-28 19:18:32 +0000381Parser::DeclPtrTy
Douglas Gregor52473432008-12-24 02:52:09 +0000382Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000383 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
384
385 // Handle the template <...> part.
386 SourceLocation TemplateLoc = ConsumeToken();
Douglas Gregor52473432008-12-24 02:52:09 +0000387 TemplateParameterList TemplateParams;
Douglas Gregord406b032009-02-06 22:42:48 +0000388 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor77f7ced2009-02-10 19:52:54 +0000389 {
390 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
391 if(!ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
392 RAngleLoc)) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000393 return DeclPtrTy();
Douglas Gregor77f7ced2009-02-10 19:52:54 +0000394 }
Douglas Gregorb3bec712008-12-01 23:54:00 +0000395 }
396
397 // Generate a meaningful error if the user forgot to put class before the
398 // identifier, comma, or greater.
399 if(!Tok.is(tok::kw_class)) {
400 Diag(Tok.getLocation(), diag::err_expected_class_before)
401 << PP.getSpelling(Tok);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000402 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000403 }
404 SourceLocation ClassLoc = ConsumeToken();
405
406 // Get the identifier, if given.
Douglas Gregor279272e2009-02-04 19:02:06 +0000407 SourceLocation NameLoc;
408 IdentifierInfo* ParamName = 0;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000409 if(Tok.is(tok::identifier)) {
Douglas Gregor279272e2009-02-04 19:02:06 +0000410 ParamName = Tok.getIdentifierInfo();
411 NameLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000412 } else if(Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
413 // Unnamed template parameter. Don't have to do anything here, just
414 // don't consume this token.
415 } else {
416 Diag(Tok.getLocation(), diag::err_expected_ident);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000417 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000418 }
419
Douglas Gregord406b032009-02-06 22:42:48 +0000420 TemplateParamsTy *ParamList =
421 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
422 TemplateLoc, LAngleLoc,
423 &TemplateParams[0],
424 TemplateParams.size(),
425 RAngleLoc);
426
Chris Lattner5261d0c2009-03-28 19:18:32 +0000427 Parser::DeclPtrTy Param
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000428 = Actions.ActOnTemplateTemplateParameter(CurScope, TemplateLoc,
429 ParamList, ParamName,
430 NameLoc, Depth, Position);
431
432 // Get the a default value, if given.
433 if (Tok.is(tok::equal)) {
434 SourceLocation EqualLoc = ConsumeToken();
435 OwningExprResult DefaultExpr = ParseCXXIdExpression();
436 if (DefaultExpr.isInvalid())
437 return Param;
438 else if (Param)
439 Actions.ActOnTemplateTemplateParameterDefault(Param, EqualLoc,
440 move(DefaultExpr));
441 }
442
443 return Param;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000444}
445
446/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
447/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregor2fa10442008-12-18 19:37:40 +0000448///
Douglas Gregorb3bec712008-12-01 23:54:00 +0000449/// template-parameter:
450/// ...
451/// parameter-declaration
452///
453/// NOTE: It would be ideal to simply call out to ParseParameterDeclaration(),
454/// but that didn't work out to well. Instead, this tries to recrate the basic
455/// parsing of parameter declarations, but tries to constrain it for template
456/// parameters.
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000457/// FIXME: We need to make a ParseParameterDeclaration that works for
458/// non-type template parameters and normal function parameters.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000459Parser::DeclPtrTy
Douglas Gregor52473432008-12-24 02:52:09 +0000460Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000461 SourceLocation StartLoc = Tok.getLocation();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000462
463 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000464 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregorb3bec712008-12-01 23:54:00 +0000465 // declarators (parts of declarators?) are accepted for parameters.
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000466 DeclSpec DS;
467 ParseDeclarationSpecifiers(DS);
Douglas Gregorb3bec712008-12-01 23:54:00 +0000468
469 // Parse this as a typename.
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000470 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
471 ParseDeclarator(ParamDecl);
Chris Lattner8376d2e2009-01-05 01:24:05 +0000472 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified && !DS.getTypeRep()) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000473 // This probably shouldn't happen - and it's more of a Sema thing, but
474 // basically we didn't parse the type name because we couldn't associate
475 // it with an AST node. we should just skip to the comma or greater.
476 // TODO: This is currently a placeholder for some kind of Sema Error.
477 Diag(Tok.getLocation(), diag::err_parse_error);
478 SkipUntil(tok::comma, tok::greater, true, true);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000479 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000480 }
481
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000482 // Create the parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000483 DeclPtrTy Param = Actions.ActOnNonTypeTemplateParameter(CurScope, ParamDecl,
484 Depth, Position);
Douglas Gregorb3bec712008-12-01 23:54:00 +0000485
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000486 // If there is a default value, parse it.
Chris Lattner8376d2e2009-01-05 01:24:05 +0000487 if (Tok.is(tok::equal)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000488 SourceLocation EqualLoc = ConsumeToken();
489
490 // C++ [temp.param]p15:
491 // When parsing a default template-argument for a non-type
492 // template-parameter, the first non-nested > is taken as the
493 // end of the template-parameter-list rather than a greater-than
494 // operator.
495 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
496
497 OwningExprResult DefaultArg = ParseAssignmentExpression();
498 if (DefaultArg.isInvalid())
499 SkipUntil(tok::comma, tok::greater, true, true);
500 else if (Param)
501 Actions.ActOnNonTypeTemplateParameterDefault(Param, EqualLoc,
502 move(DefaultArg));
Douglas Gregorb3bec712008-12-01 23:54:00 +0000503 }
504
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000505 return Param;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000506}
Douglas Gregor2fa10442008-12-18 19:37:40 +0000507
Douglas Gregora08b6c72009-02-17 23:15:12 +0000508/// \brief Parses a template-id that after the template name has
509/// already been parsed.
510///
511/// This routine takes care of parsing the enclosed template argument
512/// list ('<' template-parameter-list [opt] '>') and placing the
513/// results into a form that can be transferred to semantic analysis.
514///
515/// \param Template the template declaration produced by isTemplateName
516///
517/// \param TemplateNameLoc the source location of the template name
518///
519/// \param SS if non-NULL, the nested-name-specifier preceding the
520/// template name.
521///
522/// \param ConsumeLastToken if true, then we will consume the last
523/// token that forms the template-id. Otherwise, we will leave the
524/// last token in the stream (e.g., so that it can be replaced with an
525/// annotation token).
526bool
Douglas Gregordd13e842009-03-30 22:58:21 +0000527Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
Douglas Gregora08b6c72009-02-17 23:15:12 +0000528 SourceLocation TemplateNameLoc,
529 const CXXScopeSpec *SS,
530 bool ConsumeLastToken,
531 SourceLocation &LAngleLoc,
532 TemplateArgList &TemplateArgs,
533 TemplateArgIsTypeList &TemplateArgIsType,
534 TemplateArgLocationList &TemplateArgLocations,
535 SourceLocation &RAngleLoc) {
536 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
537
538 // Consume the '<'.
539 LAngleLoc = ConsumeToken();
540
541 // Parse the optional template-argument-list.
542 bool Invalid = false;
543 {
544 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
545 if (Tok.isNot(tok::greater))
546 Invalid = ParseTemplateArgumentList(TemplateArgs, TemplateArgIsType,
547 TemplateArgLocations);
548
549 if (Invalid) {
550 // Try to find the closing '>'.
551 SkipUntil(tok::greater, true, !ConsumeLastToken);
552
553 return true;
554 }
555 }
556
Douglas Gregorf2d87392009-02-25 23:02:36 +0000557 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
Douglas Gregora08b6c72009-02-17 23:15:12 +0000558 return true;
559
Douglas Gregorf2d87392009-02-25 23:02:36 +0000560 // Determine the location of the '>' or '>>'. Only consume this
561 // token if the caller asked us to.
Douglas Gregora08b6c72009-02-17 23:15:12 +0000562 RAngleLoc = Tok.getLocation();
563
Douglas Gregorf2d87392009-02-25 23:02:36 +0000564 if (Tok.is(tok::greatergreater)) {
Douglas Gregor3bb30002009-02-26 21:00:50 +0000565 if (!getLang().CPlusPlus0x) {
566 const char *ReplaceStr = "> >";
567 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
568 ReplaceStr = "> > ";
569
570 Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space)
Douglas Gregor61be3602009-02-27 17:53:17 +0000571 << CodeModificationHint::CreateReplacement(
572 SourceRange(Tok.getLocation()), ReplaceStr);
Douglas Gregor3bb30002009-02-26 21:00:50 +0000573 }
Douglas Gregorf2d87392009-02-25 23:02:36 +0000574
575 Tok.setKind(tok::greater);
576 if (!ConsumeLastToken) {
577 // Since we're not supposed to consume the '>>' token, we need
578 // to insert a second '>' token after the first.
579 PP.EnterToken(Tok);
580 }
581 } else if (ConsumeLastToken)
Douglas Gregora08b6c72009-02-17 23:15:12 +0000582 ConsumeToken();
583
584 return false;
585}
586
Douglas Gregor0c281a82009-02-25 19:37:18 +0000587/// \brief Replace the tokens that form a simple-template-id with an
588/// annotation token containing the complete template-id.
589///
590/// The first token in the stream must be the name of a template that
591/// is followed by a '<'. This routine will parse the complete
592/// simple-template-id and replace the tokens with a single annotation
593/// token with one of two different kinds: if the template-id names a
594/// type (and \p AllowTypeAnnotation is true), the annotation token is
595/// a type annotation that includes the optional nested-name-specifier
596/// (\p SS). Otherwise, the annotation token is a template-id
597/// annotation that does not include the optional
598/// nested-name-specifier.
599///
600/// \param Template the declaration of the template named by the first
601/// token (an identifier), as returned from \c Action::isTemplateName().
602///
603/// \param TemplateNameKind the kind of template that \p Template
604/// refers to, as returned from \c Action::isTemplateName().
605///
606/// \param SS if non-NULL, the nested-name-specifier that precedes
607/// this template name.
608///
609/// \param TemplateKWLoc if valid, specifies that this template-id
610/// annotation was preceded by the 'template' keyword and gives the
611/// location of that keyword. If invalid (the default), then this
612/// template-id was not preceded by a 'template' keyword.
613///
614/// \param AllowTypeAnnotation if true (the default), then a
615/// simple-template-id that refers to a class template, template
616/// template parameter, or other template that produces a type will be
617/// replaced with a type annotation token. Otherwise, the
618/// simple-template-id is always replaced with a template-id
619/// annotation token.
Douglas Gregordd13e842009-03-30 22:58:21 +0000620void Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Douglas Gregor0c281a82009-02-25 19:37:18 +0000621 const CXXScopeSpec *SS,
622 SourceLocation TemplateKWLoc,
623 bool AllowTypeAnnotation) {
Douglas Gregor2fa10442008-12-18 19:37:40 +0000624 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
625 assert(Template && Tok.is(tok::identifier) && NextToken().is(tok::less) &&
626 "Parser isn't at the beginning of a template-id");
627
628 // Consume the template-name.
Douglas Gregor0c281a82009-02-25 19:37:18 +0000629 IdentifierInfo *Name = Tok.getIdentifierInfo();
Douglas Gregor2fa10442008-12-18 19:37:40 +0000630 SourceLocation TemplateNameLoc = ConsumeToken();
631
Douglas Gregora08b6c72009-02-17 23:15:12 +0000632 // Parse the enclosed template argument list.
633 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor6f37b582009-02-09 19:34:22 +0000634 TemplateArgList TemplateArgs;
635 TemplateArgIsTypeList TemplateArgIsType;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000636 TemplateArgLocationList TemplateArgLocations;
Douglas Gregora08b6c72009-02-17 23:15:12 +0000637 bool Invalid = ParseTemplateIdAfterTemplateName(Template, TemplateNameLoc,
638 SS, false, LAngleLoc,
639 TemplateArgs,
640 TemplateArgIsType,
641 TemplateArgLocations,
642 RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000643
Jay Foad9e6bef42009-05-21 09:52:38 +0000644 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
645 TemplateArgIsType.data(),
Douglas Gregora08b6c72009-02-17 23:15:12 +0000646 TemplateArgs.size());
Douglas Gregoraf0d0092009-02-09 21:04:56 +0000647
Douglas Gregora08b6c72009-02-17 23:15:12 +0000648 if (Invalid) // FIXME: How to recover from a broken template-id?
649 return;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000650
Douglas Gregor8e458f42009-02-09 18:46:07 +0000651 // Build the annotation token.
Douglas Gregoraabb8502009-03-31 00:43:58 +0000652 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
Douglas Gregora08b6c72009-02-17 23:15:12 +0000653 Action::TypeResult Type
Douglas Gregordd13e842009-03-30 22:58:21 +0000654 = Actions.ActOnTemplateIdType(Template, TemplateNameLoc,
655 LAngleLoc, TemplateArgsPtr,
656 &TemplateArgLocations[0],
657 RAngleLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +0000658 if (Type.isInvalid()) // FIXME: better recovery?
659 return;
660
661 Tok.setKind(tok::annot_typename);
662 Tok.setAnnotationValue(Type.get());
Douglas Gregor0c281a82009-02-25 19:37:18 +0000663 if (SS && SS->isNotEmpty())
664 Tok.setLocation(SS->getBeginLoc());
665 else if (TemplateKWLoc.isValid())
666 Tok.setLocation(TemplateKWLoc);
667 else
668 Tok.setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +0000669 } else {
Douglas Gregoraabb8502009-03-31 00:43:58 +0000670 // Build a template-id annotation token that can be processed
671 // later.
Douglas Gregor0c281a82009-02-25 19:37:18 +0000672 Tok.setKind(tok::annot_template_id);
Douglas Gregor8e458f42009-02-09 18:46:07 +0000673 TemplateIdAnnotation *TemplateId
Douglas Gregor0c281a82009-02-25 19:37:18 +0000674 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
Douglas Gregor8e458f42009-02-09 18:46:07 +0000675 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregor0c281a82009-02-25 19:37:18 +0000676 TemplateId->Name = Name;
Chris Lattner5261d0c2009-03-28 19:18:32 +0000677 TemplateId->Template = Template.getAs<void*>();
Douglas Gregor0c281a82009-02-25 19:37:18 +0000678 TemplateId->Kind = TNK;
Douglas Gregor8e458f42009-02-09 18:46:07 +0000679 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor0c281a82009-02-25 19:37:18 +0000680 TemplateId->RAngleLoc = RAngleLoc;
681 void **Args = TemplateId->getTemplateArgs();
682 bool *ArgIsType = TemplateId->getTemplateArgIsType();
683 SourceLocation *ArgLocs = TemplateId->getTemplateArgLocations();
684 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg) {
Douglas Gregor8e458f42009-02-09 18:46:07 +0000685 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor0c281a82009-02-25 19:37:18 +0000686 ArgIsType[Arg] = TemplateArgIsType[Arg];
687 ArgLocs[Arg] = TemplateArgLocations[Arg];
688 }
Douglas Gregor8e458f42009-02-09 18:46:07 +0000689 Tok.setAnnotationValue(TemplateId);
Douglas Gregor0c281a82009-02-25 19:37:18 +0000690 if (TemplateKWLoc.isValid())
691 Tok.setLocation(TemplateKWLoc);
692 else
693 Tok.setLocation(TemplateNameLoc);
694
695 TemplateArgsPtr.release();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000696 }
697
698 // Common fields for the annotation token
Douglas Gregor2fa10442008-12-18 19:37:40 +0000699 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregor2fa10442008-12-18 19:37:40 +0000700
Douglas Gregor2fa10442008-12-18 19:37:40 +0000701 // In case the tokens were cached, have Preprocessor replace them with the
702 // annotation token.
703 PP.AnnotateCachedTokens(Tok);
704}
705
Douglas Gregor0c281a82009-02-25 19:37:18 +0000706/// \brief Replaces a template-id annotation token with a type
707/// annotation token.
708///
Douglas Gregord7cb0372009-04-01 21:51:26 +0000709/// If there was a failure when forming the type from the template-id,
710/// a type annotation token will still be created, but will have a
711/// NULL type pointer to signify an error.
712void Parser::AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS) {
Douglas Gregor0c281a82009-02-25 19:37:18 +0000713 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
714
715 TemplateIdAnnotation *TemplateId
716 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
Douglas Gregoraabb8502009-03-31 00:43:58 +0000717 assert((TemplateId->Kind == TNK_Type_template ||
718 TemplateId->Kind == TNK_Dependent_template_name) &&
719 "Only works for type and dependent templates");
Douglas Gregor0c281a82009-02-25 19:37:18 +0000720
721 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
722 TemplateId->getTemplateArgs(),
723 TemplateId->getTemplateArgIsType(),
724 TemplateId->NumArgs);
725
726 Action::TypeResult Type
Douglas Gregordd13e842009-03-30 22:58:21 +0000727 = Actions.ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
728 TemplateId->TemplateNameLoc,
729 TemplateId->LAngleLoc,
730 TemplateArgsPtr,
731 TemplateId->getTemplateArgLocations(),
732 TemplateId->RAngleLoc);
Douglas Gregor0c281a82009-02-25 19:37:18 +0000733 // Create the new "type" annotation token.
734 Tok.setKind(tok::annot_typename);
Douglas Gregord7cb0372009-04-01 21:51:26 +0000735 Tok.setAnnotationValue(Type.isInvalid()? 0 : Type.get());
Douglas Gregor0c281a82009-02-25 19:37:18 +0000736 if (SS && SS->isNotEmpty()) // it was a C++ qualified type name.
737 Tok.setLocation(SS->getBeginLoc());
738
739 // We might be backtracking, in which case we need to replace the
740 // template-id annotation token with the type annotation within the
741 // set of cached tokens. That way, we won't try to form the same
742 // class template specialization again.
743 PP.ReplaceLastTokenWithAnnotation(Tok);
744 TemplateId->Destroy();
Douglas Gregor0c281a82009-02-25 19:37:18 +0000745}
746
Douglas Gregor2fa10442008-12-18 19:37:40 +0000747/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
748///
749/// template-argument: [C++ 14.2]
750/// assignment-expression
751/// type-id
752/// id-expression
Douglas Gregor6f37b582009-02-09 19:34:22 +0000753void *Parser::ParseTemplateArgument(bool &ArgIsType) {
Douglas Gregor8e458f42009-02-09 18:46:07 +0000754 // C++ [temp.arg]p2:
755 // In a template-argument, an ambiguity between a type-id and an
756 // expression is resolved to a type-id, regardless of the form of
757 // the corresponding template-parameter.
758 //
759 // Therefore, we initially try to parse a type-id.
Douglas Gregor341ac792009-02-10 00:53:15 +0000760 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor6f37b582009-02-09 19:34:22 +0000761 ArgIsType = true;
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000762 TypeResult TypeArg = ParseTypeName();
763 if (TypeArg.isInvalid())
764 return 0;
765 return TypeArg.get();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000766 }
767
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000768 OwningExprResult ExprArg = ParseAssignmentExpression();
769 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor6f37b582009-02-09 19:34:22 +0000770 return 0;
Douglas Gregor8e458f42009-02-09 18:46:07 +0000771
Douglas Gregor6f37b582009-02-09 19:34:22 +0000772 ArgIsType = false;
773 return ExprArg.release();
Douglas Gregor2fa10442008-12-18 19:37:40 +0000774}
775
776/// ParseTemplateArgumentList - Parse a C++ template-argument-list
777/// (C++ [temp.names]). Returns true if there was an error.
778///
779/// template-argument-list: [C++ 14.2]
780/// template-argument
781/// template-argument-list ',' template-argument
Douglas Gregor6f37b582009-02-09 19:34:22 +0000782bool
783Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000784 TemplateArgIsTypeList &TemplateArgIsType,
785 TemplateArgLocationList &TemplateArgLocations) {
Douglas Gregor2fa10442008-12-18 19:37:40 +0000786 while (true) {
Douglas Gregor6f37b582009-02-09 19:34:22 +0000787 bool IsType = false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000788 SourceLocation Loc = Tok.getLocation();
Douglas Gregor6f37b582009-02-09 19:34:22 +0000789 void *Arg = ParseTemplateArgument(IsType);
790 if (Arg) {
791 TemplateArgs.push_back(Arg);
792 TemplateArgIsType.push_back(IsType);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000793 TemplateArgLocations.push_back(Loc);
Douglas Gregor6f37b582009-02-09 19:34:22 +0000794 } else {
Douglas Gregor2fa10442008-12-18 19:37:40 +0000795 SkipUntil(tok::comma, tok::greater, true, true);
796 return true;
797 }
Douglas Gregor6f37b582009-02-09 19:34:22 +0000798
Douglas Gregor2fa10442008-12-18 19:37:40 +0000799 // If the next token is a comma, consume it and keep reading
800 // arguments.
801 if (Tok.isNot(tok::comma)) break;
802
803 // Consume the comma.
804 ConsumeToken();
805 }
806
Douglas Gregorf2d87392009-02-25 23:02:36 +0000807 return Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater);
Douglas Gregor2fa10442008-12-18 19:37:40 +0000808}
809
Douglas Gregore3298aa2009-05-12 21:31:51 +0000810/// \brief Parse a C++ explicit template instantiation
811/// (C++ [temp.explicit]).
812///
813/// explicit-instantiation:
814/// 'template' declaration
Douglas Gregora9db0fa2009-05-12 23:25:50 +0000815Parser::DeclPtrTy
816Parser::ParseExplicitInstantiation(SourceLocation TemplateLoc,
817 SourceLocation &DeclEnd) {
818 return ParseSingleDeclarationAfterTemplate(Declarator::FileContext,
819 ParsedTemplateInfo(TemplateLoc),
820 DeclEnd, AS_none);
Douglas Gregore3298aa2009-05-12 21:31:51 +0000821}