blob: 490f2769e12a6a01ddb6454c179ccda0ece060f8 [file] [log] [blame]
Douglas Gregoradcac882008-12-01 23:54:00 +00001//===--- ParseTemplate.cpp - Template Parsing -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements parsing of C++ templates.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
Chris Lattner500d3292009-01-29 05:15:15 +000015#include "clang/Parse/ParseDiagnostic.h"
Douglas Gregoradcac882008-12-01 23:54:00 +000016#include "clang/Parse/DeclSpec.h"
17#include "clang/Parse/Scope.h"
Douglas Gregor55f6b142009-02-09 18:46:07 +000018#include "AstGuard.h"
Douglas Gregoradcac882008-12-01 23:54:00 +000019using namespace clang;
20
Douglas Gregor4d9a16f2009-05-12 23:25:50 +000021/// \brief Parse a template declaration, explicit instantiation, or
22/// explicit specialization.
23Parser::DeclPtrTy
24Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
25 SourceLocation &DeclEnd,
26 AccessSpecifier AS) {
27 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less))
28 return ParseExplicitInstantiation(ConsumeToken(), DeclEnd);
29
30 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS);
31}
32
Douglas Gregorcc636682009-02-17 23:15:12 +000033/// \brief Parse a template declaration or an explicit specialization.
34///
35/// Template declarations include one or more template parameter lists
36/// and either the function or class template declaration. Explicit
37/// specializations contain one or more 'template < >' prefixes
38/// followed by a (possibly templated) declaration. Since the
39/// syntactic form of both features is nearly identical, we parse all
40/// of the template headers together and let semantic analysis sort
41/// the declarations from the explicit specializations.
Douglas Gregoradcac882008-12-01 23:54:00 +000042///
43/// template-declaration: [C++ temp]
44/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
Douglas Gregorcc636682009-02-17 23:15:12 +000045///
46/// explicit-specialization: [ C++ temp.expl.spec]
47/// 'template' '<' '>' declaration
Chris Lattnerb28317a2009-03-28 19:18:32 +000048Parser::DeclPtrTy
Anders Carlsson5aeccdb2009-03-26 00:52:18 +000049Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
Chris Lattner97144fc2009-04-02 04:16:50 +000050 SourceLocation &DeclEnd,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +000051 AccessSpecifier AS) {
Douglas Gregoradcac882008-12-01 23:54:00 +000052 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
53 "Token does not start a template declaration.");
54
Douglas Gregor26236e82008-12-02 00:41:28 +000055 // Enter template-parameter scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +000056 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Douglas Gregor26236e82008-12-02 00:41:28 +000057
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +000058 // Parse multiple levels of template headers within this template
59 // parameter scope, e.g.,
60 //
61 // template<typename T>
62 // template<typename U>
63 // class A<T>::B { ... };
64 //
65 // We parse multiple levels non-recursively so that we can build a
66 // single data structure containing all of the template parameter
Douglas Gregorcc636682009-02-17 23:15:12 +000067 // lists to easily differentiate between the case above and:
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +000068 //
69 // template<typename T>
70 // class A {
71 // template<typename U> class B;
72 // };
73 //
74 // In the first case, the action for declaring A<T>::B receives
75 // both template parameter lists. In the second case, the action for
76 // defining A<T>::B receives just the inner template parameter list
77 // (and retrieves the outer template parameter list from its
78 // context).
Douglas Gregor4d9a16f2009-05-12 23:25:50 +000079 bool isSpecialiation = true;
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +000080 TemplateParameterLists ParamLists;
81 do {
82 // Consume the 'export', if any.
83 SourceLocation ExportLoc;
84 if (Tok.is(tok::kw_export)) {
85 ExportLoc = ConsumeToken();
86 }
87
88 // Consume the 'template', which should be here.
89 SourceLocation TemplateLoc;
90 if (Tok.is(tok::kw_template)) {
91 TemplateLoc = ConsumeToken();
92 } else {
93 Diag(Tok.getLocation(), diag::err_expected_template);
Chris Lattnerb28317a2009-03-28 19:18:32 +000094 return DeclPtrTy();
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +000095 }
96
97 // Parse the '<' template-parameter-list '>'
98 SourceLocation LAngleLoc, RAngleLoc;
99 TemplateParameterList TemplateParams;
100 ParseTemplateParameters(ParamLists.size(), TemplateParams, LAngleLoc,
101 RAngleLoc);
102
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000103 if (!TemplateParams.empty())
104 isSpecialiation = false;
105
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000106 ParamLists.push_back(
107 Actions.ActOnTemplateParameterList(ParamLists.size(), ExportLoc,
108 TemplateLoc, LAngleLoc,
109 &TemplateParams[0],
110 TemplateParams.size(), RAngleLoc));
111 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
112
113 // Parse the actual template declaration.
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000114 return ParseSingleDeclarationAfterTemplate(Context,
115 ParsedTemplateInfo(&ParamLists,
116 isSpecialiation),
Douglas Gregor1426e532009-05-12 21:31:51 +0000117 DeclEnd, AS);
118}
Chris Lattner682bf922009-03-29 16:50:03 +0000119
Douglas Gregor1426e532009-05-12 21:31:51 +0000120/// \brief Parse a single declaration that declares a template,
121/// template specialization, or explicit instantiation of a template.
122///
123/// \param TemplateParams if non-NULL, the template parameter lists
124/// that preceded this declaration. In this case, the declaration is a
125/// template declaration, out-of-line definition of a template, or an
126/// explicit template specialization. When NULL, the declaration is an
127/// explicit template instantiation.
128///
129/// \param TemplateLoc when TemplateParams is NULL, the location of
130/// the 'template' keyword that indicates that we have an explicit
131/// template instantiation.
132///
133/// \param DeclEnd will receive the source location of the last token
134/// within this declaration.
135///
136/// \param AS the access specifier associated with this
137/// declaration. Will be AS_none for namespace-scope declarations.
138///
139/// \returns the new declaration.
140Parser::DeclPtrTy
141Parser::ParseSingleDeclarationAfterTemplate(
142 unsigned Context,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000143 const ParsedTemplateInfo &TemplateInfo,
Douglas Gregor1426e532009-05-12 21:31:51 +0000144 SourceLocation &DeclEnd,
145 AccessSpecifier AS) {
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000146 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
147 "Template information required");
148
Douglas Gregor1426e532009-05-12 21:31:51 +0000149 // Parse the declaration specifiers.
150 DeclSpec DS;
151 // FIXME: Pass TemplateLoc through for explicit template instantiations
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000152 ParseDeclarationSpecifiers(DS, TemplateInfo, AS);
Douglas Gregor1426e532009-05-12 21:31:51 +0000153
154 if (Tok.is(tok::semi)) {
155 DeclEnd = ConsumeToken();
156 return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
157 }
158
159 // Parse the declarator.
160 Declarator DeclaratorInfo(DS, (Declarator::TheContext)Context);
161 ParseDeclarator(DeclaratorInfo);
162 // Error parsing the declarator?
163 if (!DeclaratorInfo.hasName()) {
164 // If so, skip until the semi-colon or a }.
165 SkipUntil(tok::r_brace, true, true);
166 if (Tok.is(tok::semi))
167 ConsumeToken();
168 return DeclPtrTy();
169 }
170
171 // If we have a declaration or declarator list, handle it.
172 if (isDeclarationAfterDeclarator()) {
173 // Parse this declaration.
174 DeclPtrTy ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo);
175
176 if (Tok.is(tok::comma)) {
177 Diag(Tok, diag::err_multiple_template_declarators)
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000178 << (int)TemplateInfo.Kind;
Douglas Gregor1426e532009-05-12 21:31:51 +0000179 SkipUntil(tok::semi, true, false);
180 return ThisDecl;
181 }
182
183 // Eat the semi colon after the declaration.
184 ExpectAndConsume(tok::semi, diag::err_expected_semi_declation);
185 return ThisDecl;
186 }
187
188 if (DeclaratorInfo.isFunctionDeclarator() &&
189 isStartOfFunctionDefinition()) {
190 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
191 Diag(Tok, diag::err_function_declared_typedef);
192
193 if (Tok.is(tok::l_brace)) {
194 // This recovery skips the entire function body. It would be nice
195 // to simply call ParseFunctionDefinition() below, however Sema
196 // assumes the declarator represents a function, not a typedef.
197 ConsumeBrace();
198 SkipUntil(tok::r_brace, true);
199 } else {
200 SkipUntil(tok::semi);
201 }
202 return DeclPtrTy();
203 }
204 return ParseFunctionDefinition(DeclaratorInfo);
205 }
206
207 if (DeclaratorInfo.isFunctionDeclarator())
208 Diag(Tok, diag::err_expected_fn_body);
209 else
210 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
211 SkipUntil(tok::semi);
212 return DeclPtrTy();
Douglas Gregoradcac882008-12-01 23:54:00 +0000213}
214
215/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000216/// angle brackets. Depth is the depth of this template-parameter-list, which
217/// is the number of template headers directly enclosing this template header.
218/// TemplateParams is the current list of template parameters we're building.
219/// The template parameter we parse will be added to this list. LAngleLoc and
220/// RAngleLoc will receive the positions of the '<' and '>', respectively,
221/// that enclose this template parameter list.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000222bool Parser::ParseTemplateParameters(unsigned Depth,
223 TemplateParameterList &TemplateParams,
224 SourceLocation &LAngleLoc,
225 SourceLocation &RAngleLoc) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000226 // Get the template parameter list.
227 if(!Tok.is(tok::less)) {
228 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
229 return false;
230 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000231 LAngleLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000232
233 // Try to parse the template parameter list.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000234 if (Tok.is(tok::greater))
235 RAngleLoc = ConsumeToken();
236 else if(ParseTemplateParameterList(Depth, TemplateParams)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000237 if(!Tok.is(tok::greater)) {
238 Diag(Tok.getLocation(), diag::err_expected_greater);
239 return false;
240 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000241 RAngleLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000242 }
243 return true;
244}
245
246/// ParseTemplateParameterList - Parse a template parameter list. If
247/// the parsing fails badly (i.e., closing bracket was left out), this
248/// will try to put the token stream in a reasonable position (closing
249/// a statement, etc.) and return false.
250///
251/// template-parameter-list: [C++ temp]
252/// template-parameter
253/// template-parameter-list ',' template-parameter
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000254bool
255Parser::ParseTemplateParameterList(unsigned Depth,
256 TemplateParameterList &TemplateParams) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000257 while(1) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000258 if (DeclPtrTy TmpParam
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000259 = ParseTemplateParameter(Depth, TemplateParams.size())) {
260 TemplateParams.push_back(TmpParam);
261 } else {
Douglas Gregoradcac882008-12-01 23:54:00 +0000262 // If we failed to parse a template parameter, skip until we find
263 // a comma or closing brace.
264 SkipUntil(tok::comma, tok::greater, true, true);
265 }
266
267 // Did we find a comma or the end of the template parmeter list?
268 if(Tok.is(tok::comma)) {
269 ConsumeToken();
270 } else if(Tok.is(tok::greater)) {
271 // Don't consume this... that's done by template parser.
272 break;
273 } else {
274 // Somebody probably forgot to close the template. Skip ahead and
275 // try to get out of the expression. This error is currently
276 // subsumed by whatever goes on in ParseTemplateParameter.
277 // TODO: This could match >>, and it would be nice to avoid those
278 // silly errors with template <vec<T>>.
279 // Diag(Tok.getLocation(), diag::err_expected_comma_greater);
280 SkipUntil(tok::greater, true, true);
281 return false;
282 }
283 }
284 return true;
285}
286
287/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
288///
289/// template-parameter: [C++ temp.param]
290/// type-parameter
291/// parameter-declaration
292///
293/// type-parameter: (see below)
294/// 'class' identifier[opt]
295/// 'class' identifier[opt] '=' type-id
296/// 'typename' identifier[opt]
297/// 'typename' identifier[opt] '=' type-id
298/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
299/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
Chris Lattnerb28317a2009-03-28 19:18:32 +0000300Parser::DeclPtrTy
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000301Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Chris Lattner532e19b2009-01-04 23:51:17 +0000302 if(Tok.is(tok::kw_class) ||
303 (Tok.is(tok::kw_typename) &&
304 // FIXME: Next token has not been annotated!
Chris Lattnerb31757b2009-01-06 05:06:21 +0000305 NextToken().isNot(tok::annot_typename))) {
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000306 return ParseTypeParameter(Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000307 }
Chris Lattner532e19b2009-01-04 23:51:17 +0000308
309 if(Tok.is(tok::kw_template))
310 return ParseTemplateTemplateParameter(Depth, Position);
311
312 // If it's none of the above, then it must be a parameter declaration.
313 // NOTE: This will pick up errors in the closure of the template parameter
314 // list (e.g., template < ; Check here to implement >> style closures.
315 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000316}
317
318/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
319/// Other kinds of template parameters are parsed in
320/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
321///
322/// type-parameter: [C++ temp.param]
323/// 'class' identifier[opt]
324/// 'class' identifier[opt] '=' type-id
325/// 'typename' identifier[opt]
326/// 'typename' identifier[opt] '=' type-id
Chris Lattnerb28317a2009-03-28 19:18:32 +0000327Parser::DeclPtrTy Parser::ParseTypeParameter(unsigned Depth, unsigned Position){
Douglas Gregor26236e82008-12-02 00:41:28 +0000328 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
329 "A type-parameter starts with 'class' or 'typename'");
330
331 // Consume the 'class' or 'typename' keyword.
332 bool TypenameKeyword = Tok.is(tok::kw_typename);
333 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000334
335 // Grab the template parameter name (if given)
Douglas Gregor26236e82008-12-02 00:41:28 +0000336 SourceLocation NameLoc;
337 IdentifierInfo* ParamName = 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000338 if(Tok.is(tok::identifier)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000339 ParamName = Tok.getIdentifierInfo();
340 NameLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000341 } else if(Tok.is(tok::equal) || Tok.is(tok::comma) ||
342 Tok.is(tok::greater)) {
343 // Unnamed template parameter. Don't have to do anything here, just
344 // don't consume this token.
345 } else {
346 Diag(Tok.getLocation(), diag::err_expected_ident);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000347 return DeclPtrTy();
Douglas Gregoradcac882008-12-01 23:54:00 +0000348 }
349
Chris Lattnerb28317a2009-03-28 19:18:32 +0000350 DeclPtrTy TypeParam = Actions.ActOnTypeParameter(CurScope, TypenameKeyword,
351 KeyLoc, ParamName, NameLoc,
352 Depth, Position);
Douglas Gregor26236e82008-12-02 00:41:28 +0000353
Douglas Gregoradcac882008-12-01 23:54:00 +0000354 // Grab a default type id (if given).
Douglas Gregoradcac882008-12-01 23:54:00 +0000355 if(Tok.is(tok::equal)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000356 SourceLocation EqualLoc = ConsumeToken();
Douglas Gregord684b002009-02-10 19:49:53 +0000357 SourceLocation DefaultLoc = Tok.getLocation();
Douglas Gregor809070a2009-02-18 17:45:20 +0000358 TypeResult DefaultType = ParseTypeName();
359 if (!DefaultType.isInvalid())
Douglas Gregord684b002009-02-10 19:49:53 +0000360 Actions.ActOnTypeParameterDefault(TypeParam, EqualLoc, DefaultLoc,
Douglas Gregor809070a2009-02-18 17:45:20 +0000361 DefaultType.get());
Douglas Gregoradcac882008-12-01 23:54:00 +0000362 }
363
Douglas Gregor26236e82008-12-02 00:41:28 +0000364 return TypeParam;
Douglas Gregoradcac882008-12-01 23:54:00 +0000365}
366
367/// ParseTemplateTemplateParameter - Handle the parsing of template
368/// template parameters.
369///
370/// type-parameter: [C++ temp.param]
371/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
372/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
Chris Lattnerb28317a2009-03-28 19:18:32 +0000373Parser::DeclPtrTy
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000374Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000375 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
376
377 // Handle the template <...> part.
378 SourceLocation TemplateLoc = ConsumeToken();
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000379 TemplateParameterList TemplateParams;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000380 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor68c69932009-02-10 19:52:54 +0000381 {
382 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
383 if(!ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
384 RAngleLoc)) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000385 return DeclPtrTy();
Douglas Gregor68c69932009-02-10 19:52:54 +0000386 }
Douglas Gregoradcac882008-12-01 23:54:00 +0000387 }
388
389 // Generate a meaningful error if the user forgot to put class before the
390 // identifier, comma, or greater.
391 if(!Tok.is(tok::kw_class)) {
392 Diag(Tok.getLocation(), diag::err_expected_class_before)
393 << PP.getSpelling(Tok);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000394 return DeclPtrTy();
Douglas Gregoradcac882008-12-01 23:54:00 +0000395 }
396 SourceLocation ClassLoc = ConsumeToken();
397
398 // Get the identifier, if given.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000399 SourceLocation NameLoc;
400 IdentifierInfo* ParamName = 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000401 if(Tok.is(tok::identifier)) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000402 ParamName = Tok.getIdentifierInfo();
403 NameLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000404 } else if(Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
405 // Unnamed template parameter. Don't have to do anything here, just
406 // don't consume this token.
407 } else {
408 Diag(Tok.getLocation(), diag::err_expected_ident);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000409 return DeclPtrTy();
Douglas Gregoradcac882008-12-01 23:54:00 +0000410 }
411
Douglas Gregorddc29e12009-02-06 22:42:48 +0000412 TemplateParamsTy *ParamList =
413 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
414 TemplateLoc, LAngleLoc,
415 &TemplateParams[0],
416 TemplateParams.size(),
417 RAngleLoc);
418
Chris Lattnerb28317a2009-03-28 19:18:32 +0000419 Parser::DeclPtrTy Param
Douglas Gregord684b002009-02-10 19:49:53 +0000420 = Actions.ActOnTemplateTemplateParameter(CurScope, TemplateLoc,
421 ParamList, ParamName,
422 NameLoc, Depth, Position);
423
424 // Get the a default value, if given.
425 if (Tok.is(tok::equal)) {
426 SourceLocation EqualLoc = ConsumeToken();
427 OwningExprResult DefaultExpr = ParseCXXIdExpression();
428 if (DefaultExpr.isInvalid())
429 return Param;
430 else if (Param)
431 Actions.ActOnTemplateTemplateParameterDefault(Param, EqualLoc,
432 move(DefaultExpr));
433 }
434
435 return Param;
Douglas Gregoradcac882008-12-01 23:54:00 +0000436}
437
438/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
439/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000440///
Douglas Gregoradcac882008-12-01 23:54:00 +0000441/// template-parameter:
442/// ...
443/// parameter-declaration
444///
445/// NOTE: It would be ideal to simply call out to ParseParameterDeclaration(),
446/// but that didn't work out to well. Instead, this tries to recrate the basic
447/// parsing of parameter declarations, but tries to constrain it for template
448/// parameters.
Douglas Gregor26236e82008-12-02 00:41:28 +0000449/// FIXME: We need to make a ParseParameterDeclaration that works for
450/// non-type template parameters and normal function parameters.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000451Parser::DeclPtrTy
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000452Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000453 SourceLocation StartLoc = Tok.getLocation();
Douglas Gregoradcac882008-12-01 23:54:00 +0000454
455 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor26236e82008-12-02 00:41:28 +0000456 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregoradcac882008-12-01 23:54:00 +0000457 // declarators (parts of declarators?) are accepted for parameters.
Douglas Gregor26236e82008-12-02 00:41:28 +0000458 DeclSpec DS;
459 ParseDeclarationSpecifiers(DS);
Douglas Gregoradcac882008-12-01 23:54:00 +0000460
461 // Parse this as a typename.
Douglas Gregor26236e82008-12-02 00:41:28 +0000462 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
463 ParseDeclarator(ParamDecl);
Chris Lattner7452c6f2009-01-05 01:24:05 +0000464 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified && !DS.getTypeRep()) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000465 // This probably shouldn't happen - and it's more of a Sema thing, but
466 // basically we didn't parse the type name because we couldn't associate
467 // it with an AST node. we should just skip to the comma or greater.
468 // TODO: This is currently a placeholder for some kind of Sema Error.
469 Diag(Tok.getLocation(), diag::err_parse_error);
470 SkipUntil(tok::comma, tok::greater, true, true);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000471 return DeclPtrTy();
Douglas Gregoradcac882008-12-01 23:54:00 +0000472 }
473
Douglas Gregor26236e82008-12-02 00:41:28 +0000474 // Create the parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000475 DeclPtrTy Param = Actions.ActOnNonTypeTemplateParameter(CurScope, ParamDecl,
476 Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000477
Douglas Gregord684b002009-02-10 19:49:53 +0000478 // If there is a default value, parse it.
Chris Lattner7452c6f2009-01-05 01:24:05 +0000479 if (Tok.is(tok::equal)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000480 SourceLocation EqualLoc = ConsumeToken();
481
482 // C++ [temp.param]p15:
483 // When parsing a default template-argument for a non-type
484 // template-parameter, the first non-nested > is taken as the
485 // end of the template-parameter-list rather than a greater-than
486 // operator.
487 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
488
489 OwningExprResult DefaultArg = ParseAssignmentExpression();
490 if (DefaultArg.isInvalid())
491 SkipUntil(tok::comma, tok::greater, true, true);
492 else if (Param)
493 Actions.ActOnNonTypeTemplateParameterDefault(Param, EqualLoc,
494 move(DefaultArg));
Douglas Gregoradcac882008-12-01 23:54:00 +0000495 }
496
Douglas Gregor26236e82008-12-02 00:41:28 +0000497 return Param;
Douglas Gregoradcac882008-12-01 23:54:00 +0000498}
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000499
Douglas Gregorcc636682009-02-17 23:15:12 +0000500/// \brief Parses a template-id that after the template name has
501/// already been parsed.
502///
503/// This routine takes care of parsing the enclosed template argument
504/// list ('<' template-parameter-list [opt] '>') and placing the
505/// results into a form that can be transferred to semantic analysis.
506///
507/// \param Template the template declaration produced by isTemplateName
508///
509/// \param TemplateNameLoc the source location of the template name
510///
511/// \param SS if non-NULL, the nested-name-specifier preceding the
512/// template name.
513///
514/// \param ConsumeLastToken if true, then we will consume the last
515/// token that forms the template-id. Otherwise, we will leave the
516/// last token in the stream (e.g., so that it can be replaced with an
517/// annotation token).
518bool
Douglas Gregor7532dc62009-03-30 22:58:21 +0000519Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
Douglas Gregorcc636682009-02-17 23:15:12 +0000520 SourceLocation TemplateNameLoc,
521 const CXXScopeSpec *SS,
522 bool ConsumeLastToken,
523 SourceLocation &LAngleLoc,
524 TemplateArgList &TemplateArgs,
525 TemplateArgIsTypeList &TemplateArgIsType,
526 TemplateArgLocationList &TemplateArgLocations,
527 SourceLocation &RAngleLoc) {
528 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
529
530 // Consume the '<'.
531 LAngleLoc = ConsumeToken();
532
533 // Parse the optional template-argument-list.
534 bool Invalid = false;
535 {
536 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
537 if (Tok.isNot(tok::greater))
538 Invalid = ParseTemplateArgumentList(TemplateArgs, TemplateArgIsType,
539 TemplateArgLocations);
540
541 if (Invalid) {
542 // Try to find the closing '>'.
543 SkipUntil(tok::greater, true, !ConsumeLastToken);
544
545 return true;
546 }
547 }
548
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000549 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
Douglas Gregorcc636682009-02-17 23:15:12 +0000550 return true;
551
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000552 // Determine the location of the '>' or '>>'. Only consume this
553 // token if the caller asked us to.
Douglas Gregorcc636682009-02-17 23:15:12 +0000554 RAngleLoc = Tok.getLocation();
555
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000556 if (Tok.is(tok::greatergreater)) {
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000557 if (!getLang().CPlusPlus0x) {
558 const char *ReplaceStr = "> >";
559 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
560 ReplaceStr = "> > ";
561
562 Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000563 << CodeModificationHint::CreateReplacement(
564 SourceRange(Tok.getLocation()), ReplaceStr);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000565 }
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000566
567 Tok.setKind(tok::greater);
568 if (!ConsumeLastToken) {
569 // Since we're not supposed to consume the '>>' token, we need
570 // to insert a second '>' token after the first.
571 PP.EnterToken(Tok);
572 }
573 } else if (ConsumeLastToken)
Douglas Gregorcc636682009-02-17 23:15:12 +0000574 ConsumeToken();
575
576 return false;
577}
578
Douglas Gregor39a8de12009-02-25 19:37:18 +0000579/// \brief Replace the tokens that form a simple-template-id with an
580/// annotation token containing the complete template-id.
581///
582/// The first token in the stream must be the name of a template that
583/// is followed by a '<'. This routine will parse the complete
584/// simple-template-id and replace the tokens with a single annotation
585/// token with one of two different kinds: if the template-id names a
586/// type (and \p AllowTypeAnnotation is true), the annotation token is
587/// a type annotation that includes the optional nested-name-specifier
588/// (\p SS). Otherwise, the annotation token is a template-id
589/// annotation that does not include the optional
590/// nested-name-specifier.
591///
592/// \param Template the declaration of the template named by the first
593/// token (an identifier), as returned from \c Action::isTemplateName().
594///
595/// \param TemplateNameKind the kind of template that \p Template
596/// refers to, as returned from \c Action::isTemplateName().
597///
598/// \param SS if non-NULL, the nested-name-specifier that precedes
599/// this template name.
600///
601/// \param TemplateKWLoc if valid, specifies that this template-id
602/// annotation was preceded by the 'template' keyword and gives the
603/// location of that keyword. If invalid (the default), then this
604/// template-id was not preceded by a 'template' keyword.
605///
606/// \param AllowTypeAnnotation if true (the default), then a
607/// simple-template-id that refers to a class template, template
608/// template parameter, or other template that produces a type will be
609/// replaced with a type annotation token. Otherwise, the
610/// simple-template-id is always replaced with a template-id
611/// annotation token.
Douglas Gregor7532dc62009-03-30 22:58:21 +0000612void Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000613 const CXXScopeSpec *SS,
614 SourceLocation TemplateKWLoc,
615 bool AllowTypeAnnotation) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000616 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
617 assert(Template && Tok.is(tok::identifier) && NextToken().is(tok::less) &&
618 "Parser isn't at the beginning of a template-id");
619
620 // Consume the template-name.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000621 IdentifierInfo *Name = Tok.getIdentifierInfo();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000622 SourceLocation TemplateNameLoc = ConsumeToken();
623
Douglas Gregorcc636682009-02-17 23:15:12 +0000624 // Parse the enclosed template argument list.
625 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000626 TemplateArgList TemplateArgs;
627 TemplateArgIsTypeList TemplateArgIsType;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000628 TemplateArgLocationList TemplateArgLocations;
Douglas Gregorcc636682009-02-17 23:15:12 +0000629 bool Invalid = ParseTemplateIdAfterTemplateName(Template, TemplateNameLoc,
630 SS, false, LAngleLoc,
631 TemplateArgs,
632 TemplateArgIsType,
633 TemplateArgLocations,
634 RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000635
Douglas Gregorcc636682009-02-17 23:15:12 +0000636 ASTTemplateArgsPtr TemplateArgsPtr(Actions, &TemplateArgs[0],
637 &TemplateArgIsType[0],
638 TemplateArgs.size());
Douglas Gregorf02da892009-02-09 21:04:56 +0000639
Douglas Gregorcc636682009-02-17 23:15:12 +0000640 if (Invalid) // FIXME: How to recover from a broken template-id?
641 return;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000642
Douglas Gregor55f6b142009-02-09 18:46:07 +0000643 // Build the annotation token.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000644 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
Douglas Gregorcc636682009-02-17 23:15:12 +0000645 Action::TypeResult Type
Douglas Gregor7532dc62009-03-30 22:58:21 +0000646 = Actions.ActOnTemplateIdType(Template, TemplateNameLoc,
647 LAngleLoc, TemplateArgsPtr,
648 &TemplateArgLocations[0],
649 RAngleLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +0000650 if (Type.isInvalid()) // FIXME: better recovery?
651 return;
652
653 Tok.setKind(tok::annot_typename);
654 Tok.setAnnotationValue(Type.get());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000655 if (SS && SS->isNotEmpty())
656 Tok.setLocation(SS->getBeginLoc());
657 else if (TemplateKWLoc.isValid())
658 Tok.setLocation(TemplateKWLoc);
659 else
660 Tok.setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +0000661 } else {
Douglas Gregorc45c2322009-03-31 00:43:58 +0000662 // Build a template-id annotation token that can be processed
663 // later.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000664 Tok.setKind(tok::annot_template_id);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000665 TemplateIdAnnotation *TemplateId
Douglas Gregor39a8de12009-02-25 19:37:18 +0000666 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
Douglas Gregor55f6b142009-02-09 18:46:07 +0000667 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000668 TemplateId->Name = Name;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000669 TemplateId->Template = Template.getAs<void*>();
Douglas Gregor39a8de12009-02-25 19:37:18 +0000670 TemplateId->Kind = TNK;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000671 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000672 TemplateId->RAngleLoc = RAngleLoc;
673 void **Args = TemplateId->getTemplateArgs();
674 bool *ArgIsType = TemplateId->getTemplateArgIsType();
675 SourceLocation *ArgLocs = TemplateId->getTemplateArgLocations();
676 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg) {
Douglas Gregor55f6b142009-02-09 18:46:07 +0000677 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor39a8de12009-02-25 19:37:18 +0000678 ArgIsType[Arg] = TemplateArgIsType[Arg];
679 ArgLocs[Arg] = TemplateArgLocations[Arg];
680 }
Douglas Gregor55f6b142009-02-09 18:46:07 +0000681 Tok.setAnnotationValue(TemplateId);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000682 if (TemplateKWLoc.isValid())
683 Tok.setLocation(TemplateKWLoc);
684 else
685 Tok.setLocation(TemplateNameLoc);
686
687 TemplateArgsPtr.release();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000688 }
689
690 // Common fields for the annotation token
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000691 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000692
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000693 // In case the tokens were cached, have Preprocessor replace them with the
694 // annotation token.
695 PP.AnnotateCachedTokens(Tok);
696}
697
Douglas Gregor39a8de12009-02-25 19:37:18 +0000698/// \brief Replaces a template-id annotation token with a type
699/// annotation token.
700///
Douglas Gregor31a19b62009-04-01 21:51:26 +0000701/// If there was a failure when forming the type from the template-id,
702/// a type annotation token will still be created, but will have a
703/// NULL type pointer to signify an error.
704void Parser::AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS) {
Douglas Gregor39a8de12009-02-25 19:37:18 +0000705 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
706
707 TemplateIdAnnotation *TemplateId
708 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
Douglas Gregorc45c2322009-03-31 00:43:58 +0000709 assert((TemplateId->Kind == TNK_Type_template ||
710 TemplateId->Kind == TNK_Dependent_template_name) &&
711 "Only works for type and dependent templates");
Douglas Gregor39a8de12009-02-25 19:37:18 +0000712
713 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
714 TemplateId->getTemplateArgs(),
715 TemplateId->getTemplateArgIsType(),
716 TemplateId->NumArgs);
717
718 Action::TypeResult Type
Douglas Gregor7532dc62009-03-30 22:58:21 +0000719 = Actions.ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
720 TemplateId->TemplateNameLoc,
721 TemplateId->LAngleLoc,
722 TemplateArgsPtr,
723 TemplateId->getTemplateArgLocations(),
724 TemplateId->RAngleLoc);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000725 // Create the new "type" annotation token.
726 Tok.setKind(tok::annot_typename);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000727 Tok.setAnnotationValue(Type.isInvalid()? 0 : Type.get());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000728 if (SS && SS->isNotEmpty()) // it was a C++ qualified type name.
729 Tok.setLocation(SS->getBeginLoc());
730
731 // We might be backtracking, in which case we need to replace the
732 // template-id annotation token with the type annotation within the
733 // set of cached tokens. That way, we won't try to form the same
734 // class template specialization again.
735 PP.ReplaceLastTokenWithAnnotation(Tok);
736 TemplateId->Destroy();
Douglas Gregor39a8de12009-02-25 19:37:18 +0000737}
738
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000739/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
740///
741/// template-argument: [C++ 14.2]
742/// assignment-expression
743/// type-id
744/// id-expression
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000745void *Parser::ParseTemplateArgument(bool &ArgIsType) {
Douglas Gregor55f6b142009-02-09 18:46:07 +0000746 // C++ [temp.arg]p2:
747 // In a template-argument, an ambiguity between a type-id and an
748 // expression is resolved to a type-id, regardless of the form of
749 // the corresponding template-parameter.
750 //
751 // Therefore, we initially try to parse a type-id.
Douglas Gregor8b642592009-02-10 00:53:15 +0000752 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000753 ArgIsType = true;
Douglas Gregor809070a2009-02-18 17:45:20 +0000754 TypeResult TypeArg = ParseTypeName();
755 if (TypeArg.isInvalid())
756 return 0;
757 return TypeArg.get();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000758 }
759
Douglas Gregorc15cb382009-02-09 23:23:08 +0000760 OwningExprResult ExprArg = ParseAssignmentExpression();
761 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000762 return 0;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000763
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000764 ArgIsType = false;
765 return ExprArg.release();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000766}
767
768/// ParseTemplateArgumentList - Parse a C++ template-argument-list
769/// (C++ [temp.names]). Returns true if there was an error.
770///
771/// template-argument-list: [C++ 14.2]
772/// template-argument
773/// template-argument-list ',' template-argument
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000774bool
775Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
Douglas Gregorc15cb382009-02-09 23:23:08 +0000776 TemplateArgIsTypeList &TemplateArgIsType,
777 TemplateArgLocationList &TemplateArgLocations) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000778 while (true) {
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000779 bool IsType = false;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000780 SourceLocation Loc = Tok.getLocation();
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000781 void *Arg = ParseTemplateArgument(IsType);
782 if (Arg) {
783 TemplateArgs.push_back(Arg);
784 TemplateArgIsType.push_back(IsType);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000785 TemplateArgLocations.push_back(Loc);
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000786 } else {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000787 SkipUntil(tok::comma, tok::greater, true, true);
788 return true;
789 }
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000790
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000791 // If the next token is a comma, consume it and keep reading
792 // arguments.
793 if (Tok.isNot(tok::comma)) break;
794
795 // Consume the comma.
796 ConsumeToken();
797 }
798
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000799 return Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000800}
801
Douglas Gregor1426e532009-05-12 21:31:51 +0000802/// \brief Parse a C++ explicit template instantiation
803/// (C++ [temp.explicit]).
804///
805/// explicit-instantiation:
806/// 'template' declaration
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000807Parser::DeclPtrTy
808Parser::ParseExplicitInstantiation(SourceLocation TemplateLoc,
809 SourceLocation &DeclEnd) {
810 return ParseSingleDeclarationAfterTemplate(Declarator::FileContext,
811 ParsedTemplateInfo(TemplateLoc),
812 DeclEnd, AS_none);
Douglas Gregor1426e532009-05-12 21:31:51 +0000813}