blob: 22d11779ab32113cbe52e47efc77b88f828384c0 [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 Gregor8e458f42009-02-09 18:46:07 +000018#include "AstGuard.h"
Douglas Gregorb3bec712008-12-01 23:54:00 +000019using namespace clang;
20
Douglas Gregora08b6c72009-02-17 23:15:12 +000021/// \brief Parse a template declaration or an explicit specialization.
22///
23/// Template declarations include one or more template parameter lists
24/// and either the function or class template declaration. Explicit
25/// specializations contain one or more 'template < >' prefixes
26/// followed by a (possibly templated) declaration. Since the
27/// syntactic form of both features is nearly identical, we parse all
28/// of the template headers together and let semantic analysis sort
29/// the declarations from the explicit specializations.
Douglas Gregorb3bec712008-12-01 23:54:00 +000030///
31/// template-declaration: [C++ temp]
32/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
Douglas Gregora08b6c72009-02-17 23:15:12 +000033///
34/// explicit-specialization: [ C++ temp.expl.spec]
35/// 'template' '<' '>' declaration
Chris Lattner5261d0c2009-03-28 19:18:32 +000036Parser::DeclPtrTy
Anders Carlssoned20fb92009-03-26 00:52:18 +000037Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
Chris Lattner9802a0a2009-04-02 04:16:50 +000038 SourceLocation &DeclEnd,
Anders Carlssoned20fb92009-03-26 00:52:18 +000039 AccessSpecifier AS) {
Douglas Gregorb3bec712008-12-01 23:54:00 +000040 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
41 "Token does not start a template declaration.");
42
Douglas Gregor8e7f9572008-12-02 00:41:28 +000043 // Enter template-parameter scope.
Douglas Gregor95d40792008-12-10 06:34:36 +000044 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Douglas Gregor8e7f9572008-12-02 00:41:28 +000045
Douglas Gregor52473432008-12-24 02:52:09 +000046 // Parse multiple levels of template headers within this template
47 // parameter scope, e.g.,
48 //
49 // template<typename T>
50 // template<typename U>
51 // class A<T>::B { ... };
52 //
53 // We parse multiple levels non-recursively so that we can build a
54 // single data structure containing all of the template parameter
Douglas Gregora08b6c72009-02-17 23:15:12 +000055 // lists to easily differentiate between the case above and:
Douglas Gregor52473432008-12-24 02:52:09 +000056 //
57 // template<typename T>
58 // class A {
59 // template<typename U> class B;
60 // };
61 //
62 // In the first case, the action for declaring A<T>::B receives
63 // both template parameter lists. In the second case, the action for
64 // defining A<T>::B receives just the inner template parameter list
65 // (and retrieves the outer template parameter list from its
66 // context).
67 TemplateParameterLists ParamLists;
68 do {
69 // Consume the 'export', if any.
70 SourceLocation ExportLoc;
71 if (Tok.is(tok::kw_export)) {
72 ExportLoc = ConsumeToken();
73 }
74
75 // Consume the 'template', which should be here.
76 SourceLocation TemplateLoc;
77 if (Tok.is(tok::kw_template)) {
78 TemplateLoc = ConsumeToken();
79 } else {
80 Diag(Tok.getLocation(), diag::err_expected_template);
Chris Lattner5261d0c2009-03-28 19:18:32 +000081 return DeclPtrTy();
Douglas Gregor52473432008-12-24 02:52:09 +000082 }
83
84 // Parse the '<' template-parameter-list '>'
85 SourceLocation LAngleLoc, RAngleLoc;
86 TemplateParameterList TemplateParams;
87 ParseTemplateParameters(ParamLists.size(), TemplateParams, LAngleLoc,
88 RAngleLoc);
89
90 ParamLists.push_back(
91 Actions.ActOnTemplateParameterList(ParamLists.size(), ExportLoc,
92 TemplateLoc, LAngleLoc,
93 &TemplateParams[0],
94 TemplateParams.size(), RAngleLoc));
95 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
96
97 // Parse the actual template declaration.
Douglas Gregore3298aa2009-05-12 21:31:51 +000098 return ParseSingleDeclarationAfterTemplate(Context, &ParamLists,
99 SourceLocation(),
100 DeclEnd, AS);
101}
Chris Lattnera17991f2009-03-29 16:50:03 +0000102
Douglas Gregore3298aa2009-05-12 21:31:51 +0000103/// \brief Parse a single declaration that declares a template,
104/// template specialization, or explicit instantiation of a template.
105///
106/// \param TemplateParams if non-NULL, the template parameter lists
107/// that preceded this declaration. In this case, the declaration is a
108/// template declaration, out-of-line definition of a template, or an
109/// explicit template specialization. When NULL, the declaration is an
110/// explicit template instantiation.
111///
112/// \param TemplateLoc when TemplateParams is NULL, the location of
113/// the 'template' keyword that indicates that we have an explicit
114/// template instantiation.
115///
116/// \param DeclEnd will receive the source location of the last token
117/// within this declaration.
118///
119/// \param AS the access specifier associated with this
120/// declaration. Will be AS_none for namespace-scope declarations.
121///
122/// \returns the new declaration.
123Parser::DeclPtrTy
124Parser::ParseSingleDeclarationAfterTemplate(
125 unsigned Context,
126 TemplateParameterLists *TemplateParams,
127 SourceLocation TemplateLoc,
128 SourceLocation &DeclEnd,
129 AccessSpecifier AS) {
130 // Parse the declaration specifiers.
131 DeclSpec DS;
132 // FIXME: Pass TemplateLoc through for explicit template instantiations
133 ParseDeclarationSpecifiers(DS, TemplateParams, AS);
134
135 if (Tok.is(tok::semi)) {
136 DeclEnd = ConsumeToken();
137 return Actions.ParsedFreeStandingDeclSpec(CurScope, DS);
138 }
139
140 // Parse the declarator.
141 Declarator DeclaratorInfo(DS, (Declarator::TheContext)Context);
142 ParseDeclarator(DeclaratorInfo);
143 // Error parsing the declarator?
144 if (!DeclaratorInfo.hasName()) {
145 // If so, skip until the semi-colon or a }.
146 SkipUntil(tok::r_brace, true, true);
147 if (Tok.is(tok::semi))
148 ConsumeToken();
149 return DeclPtrTy();
150 }
151
152 // If we have a declaration or declarator list, handle it.
153 if (isDeclarationAfterDeclarator()) {
154 // Parse this declaration.
155 DeclPtrTy ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo);
156
157 if (Tok.is(tok::comma)) {
158 Diag(Tok, diag::err_multiple_template_declarators)
159 << (TemplateParams == 0);
160 SkipUntil(tok::semi, true, false);
161 return ThisDecl;
162 }
163
164 // Eat the semi colon after the declaration.
165 ExpectAndConsume(tok::semi, diag::err_expected_semi_declation);
166 return ThisDecl;
167 }
168
169 if (DeclaratorInfo.isFunctionDeclarator() &&
170 isStartOfFunctionDefinition()) {
171 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
172 Diag(Tok, diag::err_function_declared_typedef);
173
174 if (Tok.is(tok::l_brace)) {
175 // This recovery skips the entire function body. It would be nice
176 // to simply call ParseFunctionDefinition() below, however Sema
177 // assumes the declarator represents a function, not a typedef.
178 ConsumeBrace();
179 SkipUntil(tok::r_brace, true);
180 } else {
181 SkipUntil(tok::semi);
182 }
183 return DeclPtrTy();
184 }
185 return ParseFunctionDefinition(DeclaratorInfo);
186 }
187
188 if (DeclaratorInfo.isFunctionDeclarator())
189 Diag(Tok, diag::err_expected_fn_body);
190 else
191 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
192 SkipUntil(tok::semi);
193 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000194}
195
196/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregor279272e2009-02-04 19:02:06 +0000197/// angle brackets. Depth is the depth of this template-parameter-list, which
198/// is the number of template headers directly enclosing this template header.
199/// TemplateParams is the current list of template parameters we're building.
200/// The template parameter we parse will be added to this list. LAngleLoc and
201/// RAngleLoc will receive the positions of the '<' and '>', respectively,
202/// that enclose this template parameter list.
Douglas Gregor52473432008-12-24 02:52:09 +0000203bool Parser::ParseTemplateParameters(unsigned Depth,
204 TemplateParameterList &TemplateParams,
205 SourceLocation &LAngleLoc,
206 SourceLocation &RAngleLoc) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000207 // Get the template parameter list.
208 if(!Tok.is(tok::less)) {
209 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
210 return false;
211 }
Douglas Gregor52473432008-12-24 02:52:09 +0000212 LAngleLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000213
214 // Try to parse the template parameter list.
Douglas Gregor52473432008-12-24 02:52:09 +0000215 if (Tok.is(tok::greater))
216 RAngleLoc = ConsumeToken();
217 else if(ParseTemplateParameterList(Depth, TemplateParams)) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000218 if(!Tok.is(tok::greater)) {
219 Diag(Tok.getLocation(), diag::err_expected_greater);
220 return false;
221 }
Douglas Gregor52473432008-12-24 02:52:09 +0000222 RAngleLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000223 }
224 return true;
225}
226
227/// ParseTemplateParameterList - Parse a template parameter list. If
228/// the parsing fails badly (i.e., closing bracket was left out), this
229/// will try to put the token stream in a reasonable position (closing
230/// a statement, etc.) and return false.
231///
232/// template-parameter-list: [C++ temp]
233/// template-parameter
234/// template-parameter-list ',' template-parameter
Douglas Gregor52473432008-12-24 02:52:09 +0000235bool
236Parser::ParseTemplateParameterList(unsigned Depth,
237 TemplateParameterList &TemplateParams) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000238 while(1) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000239 if (DeclPtrTy TmpParam
Douglas Gregor52473432008-12-24 02:52:09 +0000240 = ParseTemplateParameter(Depth, TemplateParams.size())) {
241 TemplateParams.push_back(TmpParam);
242 } else {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000243 // If we failed to parse a template parameter, skip until we find
244 // a comma or closing brace.
245 SkipUntil(tok::comma, tok::greater, true, true);
246 }
247
248 // Did we find a comma or the end of the template parmeter list?
249 if(Tok.is(tok::comma)) {
250 ConsumeToken();
251 } else if(Tok.is(tok::greater)) {
252 // Don't consume this... that's done by template parser.
253 break;
254 } else {
255 // Somebody probably forgot to close the template. Skip ahead and
256 // try to get out of the expression. This error is currently
257 // subsumed by whatever goes on in ParseTemplateParameter.
258 // TODO: This could match >>, and it would be nice to avoid those
259 // silly errors with template <vec<T>>.
260 // Diag(Tok.getLocation(), diag::err_expected_comma_greater);
261 SkipUntil(tok::greater, true, true);
262 return false;
263 }
264 }
265 return true;
266}
267
268/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
269///
270/// template-parameter: [C++ temp.param]
271/// type-parameter
272/// parameter-declaration
273///
274/// type-parameter: (see below)
275/// 'class' identifier[opt]
276/// 'class' identifier[opt] '=' type-id
277/// 'typename' identifier[opt]
278/// 'typename' identifier[opt] '=' type-id
279/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
280/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
Chris Lattner5261d0c2009-03-28 19:18:32 +0000281Parser::DeclPtrTy
Douglas Gregor52473432008-12-24 02:52:09 +0000282Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Chris Lattner4e7a4202009-01-04 23:51:17 +0000283 if(Tok.is(tok::kw_class) ||
284 (Tok.is(tok::kw_typename) &&
285 // FIXME: Next token has not been annotated!
Chris Lattner5d7eace2009-01-06 05:06:21 +0000286 NextToken().isNot(tok::annot_typename))) {
Douglas Gregor52473432008-12-24 02:52:09 +0000287 return ParseTypeParameter(Depth, Position);
Douglas Gregorb3bec712008-12-01 23:54:00 +0000288 }
Chris Lattner4e7a4202009-01-04 23:51:17 +0000289
290 if(Tok.is(tok::kw_template))
291 return ParseTemplateTemplateParameter(Depth, Position);
292
293 // If it's none of the above, then it must be a parameter declaration.
294 // NOTE: This will pick up errors in the closure of the template parameter
295 // list (e.g., template < ; Check here to implement >> style closures.
296 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregorb3bec712008-12-01 23:54:00 +0000297}
298
299/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
300/// Other kinds of template parameters are parsed in
301/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
302///
303/// type-parameter: [C++ temp.param]
304/// 'class' identifier[opt]
305/// 'class' identifier[opt] '=' type-id
306/// 'typename' identifier[opt]
307/// 'typename' identifier[opt] '=' type-id
Chris Lattner5261d0c2009-03-28 19:18:32 +0000308Parser::DeclPtrTy Parser::ParseTypeParameter(unsigned Depth, unsigned Position){
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000309 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
310 "A type-parameter starts with 'class' or 'typename'");
311
312 // Consume the 'class' or 'typename' keyword.
313 bool TypenameKeyword = Tok.is(tok::kw_typename);
314 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000315
316 // Grab the template parameter name (if given)
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000317 SourceLocation NameLoc;
318 IdentifierInfo* ParamName = 0;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000319 if(Tok.is(tok::identifier)) {
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000320 ParamName = Tok.getIdentifierInfo();
321 NameLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000322 } else if(Tok.is(tok::equal) || Tok.is(tok::comma) ||
323 Tok.is(tok::greater)) {
324 // Unnamed template parameter. Don't have to do anything here, just
325 // don't consume this token.
326 } else {
327 Diag(Tok.getLocation(), diag::err_expected_ident);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000328 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000329 }
330
Chris Lattner5261d0c2009-03-28 19:18:32 +0000331 DeclPtrTy TypeParam = Actions.ActOnTypeParameter(CurScope, TypenameKeyword,
332 KeyLoc, ParamName, NameLoc,
333 Depth, Position);
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000334
Douglas Gregorb3bec712008-12-01 23:54:00 +0000335 // Grab a default type id (if given).
Douglas Gregorb3bec712008-12-01 23:54:00 +0000336 if(Tok.is(tok::equal)) {
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000337 SourceLocation EqualLoc = ConsumeToken();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000338 SourceLocation DefaultLoc = Tok.getLocation();
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000339 TypeResult DefaultType = ParseTypeName();
340 if (!DefaultType.isInvalid())
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000341 Actions.ActOnTypeParameterDefault(TypeParam, EqualLoc, DefaultLoc,
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000342 DefaultType.get());
Douglas Gregorb3bec712008-12-01 23:54:00 +0000343 }
344
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000345 return TypeParam;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000346}
347
348/// ParseTemplateTemplateParameter - Handle the parsing of template
349/// template parameters.
350///
351/// type-parameter: [C++ temp.param]
352/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
353/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
Chris Lattner5261d0c2009-03-28 19:18:32 +0000354Parser::DeclPtrTy
Douglas Gregor52473432008-12-24 02:52:09 +0000355Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000356 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
357
358 // Handle the template <...> part.
359 SourceLocation TemplateLoc = ConsumeToken();
Douglas Gregor52473432008-12-24 02:52:09 +0000360 TemplateParameterList TemplateParams;
Douglas Gregord406b032009-02-06 22:42:48 +0000361 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor77f7ced2009-02-10 19:52:54 +0000362 {
363 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
364 if(!ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
365 RAngleLoc)) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000366 return DeclPtrTy();
Douglas Gregor77f7ced2009-02-10 19:52:54 +0000367 }
Douglas Gregorb3bec712008-12-01 23:54:00 +0000368 }
369
370 // Generate a meaningful error if the user forgot to put class before the
371 // identifier, comma, or greater.
372 if(!Tok.is(tok::kw_class)) {
373 Diag(Tok.getLocation(), diag::err_expected_class_before)
374 << PP.getSpelling(Tok);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000375 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000376 }
377 SourceLocation ClassLoc = ConsumeToken();
378
379 // Get the identifier, if given.
Douglas Gregor279272e2009-02-04 19:02:06 +0000380 SourceLocation NameLoc;
381 IdentifierInfo* ParamName = 0;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000382 if(Tok.is(tok::identifier)) {
Douglas Gregor279272e2009-02-04 19:02:06 +0000383 ParamName = Tok.getIdentifierInfo();
384 NameLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000385 } else if(Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
386 // Unnamed template parameter. Don't have to do anything here, just
387 // don't consume this token.
388 } else {
389 Diag(Tok.getLocation(), diag::err_expected_ident);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000390 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000391 }
392
Douglas Gregord406b032009-02-06 22:42:48 +0000393 TemplateParamsTy *ParamList =
394 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
395 TemplateLoc, LAngleLoc,
396 &TemplateParams[0],
397 TemplateParams.size(),
398 RAngleLoc);
399
Chris Lattner5261d0c2009-03-28 19:18:32 +0000400 Parser::DeclPtrTy Param
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000401 = Actions.ActOnTemplateTemplateParameter(CurScope, TemplateLoc,
402 ParamList, ParamName,
403 NameLoc, Depth, Position);
404
405 // Get the a default value, if given.
406 if (Tok.is(tok::equal)) {
407 SourceLocation EqualLoc = ConsumeToken();
408 OwningExprResult DefaultExpr = ParseCXXIdExpression();
409 if (DefaultExpr.isInvalid())
410 return Param;
411 else if (Param)
412 Actions.ActOnTemplateTemplateParameterDefault(Param, EqualLoc,
413 move(DefaultExpr));
414 }
415
416 return Param;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000417}
418
419/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
420/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregor2fa10442008-12-18 19:37:40 +0000421///
Douglas Gregorb3bec712008-12-01 23:54:00 +0000422/// template-parameter:
423/// ...
424/// parameter-declaration
425///
426/// NOTE: It would be ideal to simply call out to ParseParameterDeclaration(),
427/// but that didn't work out to well. Instead, this tries to recrate the basic
428/// parsing of parameter declarations, but tries to constrain it for template
429/// parameters.
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000430/// FIXME: We need to make a ParseParameterDeclaration that works for
431/// non-type template parameters and normal function parameters.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000432Parser::DeclPtrTy
Douglas Gregor52473432008-12-24 02:52:09 +0000433Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000434 SourceLocation StartLoc = Tok.getLocation();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000435
436 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000437 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregorb3bec712008-12-01 23:54:00 +0000438 // declarators (parts of declarators?) are accepted for parameters.
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000439 DeclSpec DS;
440 ParseDeclarationSpecifiers(DS);
Douglas Gregorb3bec712008-12-01 23:54:00 +0000441
442 // Parse this as a typename.
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000443 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
444 ParseDeclarator(ParamDecl);
Chris Lattner8376d2e2009-01-05 01:24:05 +0000445 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified && !DS.getTypeRep()) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000446 // This probably shouldn't happen - and it's more of a Sema thing, but
447 // basically we didn't parse the type name because we couldn't associate
448 // it with an AST node. we should just skip to the comma or greater.
449 // TODO: This is currently a placeholder for some kind of Sema Error.
450 Diag(Tok.getLocation(), diag::err_parse_error);
451 SkipUntil(tok::comma, tok::greater, true, true);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000452 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000453 }
454
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000455 // Create the parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000456 DeclPtrTy Param = Actions.ActOnNonTypeTemplateParameter(CurScope, ParamDecl,
457 Depth, Position);
Douglas Gregorb3bec712008-12-01 23:54:00 +0000458
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000459 // If there is a default value, parse it.
Chris Lattner8376d2e2009-01-05 01:24:05 +0000460 if (Tok.is(tok::equal)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000461 SourceLocation EqualLoc = ConsumeToken();
462
463 // C++ [temp.param]p15:
464 // When parsing a default template-argument for a non-type
465 // template-parameter, the first non-nested > is taken as the
466 // end of the template-parameter-list rather than a greater-than
467 // operator.
468 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
469
470 OwningExprResult DefaultArg = ParseAssignmentExpression();
471 if (DefaultArg.isInvalid())
472 SkipUntil(tok::comma, tok::greater, true, true);
473 else if (Param)
474 Actions.ActOnNonTypeTemplateParameterDefault(Param, EqualLoc,
475 move(DefaultArg));
Douglas Gregorb3bec712008-12-01 23:54:00 +0000476 }
477
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000478 return Param;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000479}
Douglas Gregor2fa10442008-12-18 19:37:40 +0000480
Douglas Gregora08b6c72009-02-17 23:15:12 +0000481/// \brief Parses a template-id that after the template name has
482/// already been parsed.
483///
484/// This routine takes care of parsing the enclosed template argument
485/// list ('<' template-parameter-list [opt] '>') and placing the
486/// results into a form that can be transferred to semantic analysis.
487///
488/// \param Template the template declaration produced by isTemplateName
489///
490/// \param TemplateNameLoc the source location of the template name
491///
492/// \param SS if non-NULL, the nested-name-specifier preceding the
493/// template name.
494///
495/// \param ConsumeLastToken if true, then we will consume the last
496/// token that forms the template-id. Otherwise, we will leave the
497/// last token in the stream (e.g., so that it can be replaced with an
498/// annotation token).
499bool
Douglas Gregordd13e842009-03-30 22:58:21 +0000500Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
Douglas Gregora08b6c72009-02-17 23:15:12 +0000501 SourceLocation TemplateNameLoc,
502 const CXXScopeSpec *SS,
503 bool ConsumeLastToken,
504 SourceLocation &LAngleLoc,
505 TemplateArgList &TemplateArgs,
506 TemplateArgIsTypeList &TemplateArgIsType,
507 TemplateArgLocationList &TemplateArgLocations,
508 SourceLocation &RAngleLoc) {
509 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
510
511 // Consume the '<'.
512 LAngleLoc = ConsumeToken();
513
514 // Parse the optional template-argument-list.
515 bool Invalid = false;
516 {
517 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
518 if (Tok.isNot(tok::greater))
519 Invalid = ParseTemplateArgumentList(TemplateArgs, TemplateArgIsType,
520 TemplateArgLocations);
521
522 if (Invalid) {
523 // Try to find the closing '>'.
524 SkipUntil(tok::greater, true, !ConsumeLastToken);
525
526 return true;
527 }
528 }
529
Douglas Gregorf2d87392009-02-25 23:02:36 +0000530 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
Douglas Gregora08b6c72009-02-17 23:15:12 +0000531 return true;
532
Douglas Gregorf2d87392009-02-25 23:02:36 +0000533 // Determine the location of the '>' or '>>'. Only consume this
534 // token if the caller asked us to.
Douglas Gregora08b6c72009-02-17 23:15:12 +0000535 RAngleLoc = Tok.getLocation();
536
Douglas Gregorf2d87392009-02-25 23:02:36 +0000537 if (Tok.is(tok::greatergreater)) {
Douglas Gregor3bb30002009-02-26 21:00:50 +0000538 if (!getLang().CPlusPlus0x) {
539 const char *ReplaceStr = "> >";
540 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
541 ReplaceStr = "> > ";
542
543 Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space)
Douglas Gregor61be3602009-02-27 17:53:17 +0000544 << CodeModificationHint::CreateReplacement(
545 SourceRange(Tok.getLocation()), ReplaceStr);
Douglas Gregor3bb30002009-02-26 21:00:50 +0000546 }
Douglas Gregorf2d87392009-02-25 23:02:36 +0000547
548 Tok.setKind(tok::greater);
549 if (!ConsumeLastToken) {
550 // Since we're not supposed to consume the '>>' token, we need
551 // to insert a second '>' token after the first.
552 PP.EnterToken(Tok);
553 }
554 } else if (ConsumeLastToken)
Douglas Gregora08b6c72009-02-17 23:15:12 +0000555 ConsumeToken();
556
557 return false;
558}
559
Douglas Gregor0c281a82009-02-25 19:37:18 +0000560/// \brief Replace the tokens that form a simple-template-id with an
561/// annotation token containing the complete template-id.
562///
563/// The first token in the stream must be the name of a template that
564/// is followed by a '<'. This routine will parse the complete
565/// simple-template-id and replace the tokens with a single annotation
566/// token with one of two different kinds: if the template-id names a
567/// type (and \p AllowTypeAnnotation is true), the annotation token is
568/// a type annotation that includes the optional nested-name-specifier
569/// (\p SS). Otherwise, the annotation token is a template-id
570/// annotation that does not include the optional
571/// nested-name-specifier.
572///
573/// \param Template the declaration of the template named by the first
574/// token (an identifier), as returned from \c Action::isTemplateName().
575///
576/// \param TemplateNameKind the kind of template that \p Template
577/// refers to, as returned from \c Action::isTemplateName().
578///
579/// \param SS if non-NULL, the nested-name-specifier that precedes
580/// this template name.
581///
582/// \param TemplateKWLoc if valid, specifies that this template-id
583/// annotation was preceded by the 'template' keyword and gives the
584/// location of that keyword. If invalid (the default), then this
585/// template-id was not preceded by a 'template' keyword.
586///
587/// \param AllowTypeAnnotation if true (the default), then a
588/// simple-template-id that refers to a class template, template
589/// template parameter, or other template that produces a type will be
590/// replaced with a type annotation token. Otherwise, the
591/// simple-template-id is always replaced with a template-id
592/// annotation token.
Douglas Gregordd13e842009-03-30 22:58:21 +0000593void Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Douglas Gregor0c281a82009-02-25 19:37:18 +0000594 const CXXScopeSpec *SS,
595 SourceLocation TemplateKWLoc,
596 bool AllowTypeAnnotation) {
Douglas Gregor2fa10442008-12-18 19:37:40 +0000597 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
598 assert(Template && Tok.is(tok::identifier) && NextToken().is(tok::less) &&
599 "Parser isn't at the beginning of a template-id");
600
601 // Consume the template-name.
Douglas Gregor0c281a82009-02-25 19:37:18 +0000602 IdentifierInfo *Name = Tok.getIdentifierInfo();
Douglas Gregor2fa10442008-12-18 19:37:40 +0000603 SourceLocation TemplateNameLoc = ConsumeToken();
604
Douglas Gregora08b6c72009-02-17 23:15:12 +0000605 // Parse the enclosed template argument list.
606 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor6f37b582009-02-09 19:34:22 +0000607 TemplateArgList TemplateArgs;
608 TemplateArgIsTypeList TemplateArgIsType;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000609 TemplateArgLocationList TemplateArgLocations;
Douglas Gregora08b6c72009-02-17 23:15:12 +0000610 bool Invalid = ParseTemplateIdAfterTemplateName(Template, TemplateNameLoc,
611 SS, false, LAngleLoc,
612 TemplateArgs,
613 TemplateArgIsType,
614 TemplateArgLocations,
615 RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000616
Douglas Gregora08b6c72009-02-17 23:15:12 +0000617 ASTTemplateArgsPtr TemplateArgsPtr(Actions, &TemplateArgs[0],
618 &TemplateArgIsType[0],
619 TemplateArgs.size());
Douglas Gregoraf0d0092009-02-09 21:04:56 +0000620
Douglas Gregora08b6c72009-02-17 23:15:12 +0000621 if (Invalid) // FIXME: How to recover from a broken template-id?
622 return;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000623
Douglas Gregor8e458f42009-02-09 18:46:07 +0000624 // Build the annotation token.
Douglas Gregoraabb8502009-03-31 00:43:58 +0000625 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
Douglas Gregora08b6c72009-02-17 23:15:12 +0000626 Action::TypeResult Type
Douglas Gregordd13e842009-03-30 22:58:21 +0000627 = Actions.ActOnTemplateIdType(Template, TemplateNameLoc,
628 LAngleLoc, TemplateArgsPtr,
629 &TemplateArgLocations[0],
630 RAngleLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +0000631 if (Type.isInvalid()) // FIXME: better recovery?
632 return;
633
634 Tok.setKind(tok::annot_typename);
635 Tok.setAnnotationValue(Type.get());
Douglas Gregor0c281a82009-02-25 19:37:18 +0000636 if (SS && SS->isNotEmpty())
637 Tok.setLocation(SS->getBeginLoc());
638 else if (TemplateKWLoc.isValid())
639 Tok.setLocation(TemplateKWLoc);
640 else
641 Tok.setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +0000642 } else {
Douglas Gregoraabb8502009-03-31 00:43:58 +0000643 // Build a template-id annotation token that can be processed
644 // later.
Douglas Gregor0c281a82009-02-25 19:37:18 +0000645 Tok.setKind(tok::annot_template_id);
Douglas Gregor8e458f42009-02-09 18:46:07 +0000646 TemplateIdAnnotation *TemplateId
Douglas Gregor0c281a82009-02-25 19:37:18 +0000647 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
Douglas Gregor8e458f42009-02-09 18:46:07 +0000648 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregor0c281a82009-02-25 19:37:18 +0000649 TemplateId->Name = Name;
Chris Lattner5261d0c2009-03-28 19:18:32 +0000650 TemplateId->Template = Template.getAs<void*>();
Douglas Gregor0c281a82009-02-25 19:37:18 +0000651 TemplateId->Kind = TNK;
Douglas Gregor8e458f42009-02-09 18:46:07 +0000652 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor0c281a82009-02-25 19:37:18 +0000653 TemplateId->RAngleLoc = RAngleLoc;
654 void **Args = TemplateId->getTemplateArgs();
655 bool *ArgIsType = TemplateId->getTemplateArgIsType();
656 SourceLocation *ArgLocs = TemplateId->getTemplateArgLocations();
657 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg) {
Douglas Gregor8e458f42009-02-09 18:46:07 +0000658 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor0c281a82009-02-25 19:37:18 +0000659 ArgIsType[Arg] = TemplateArgIsType[Arg];
660 ArgLocs[Arg] = TemplateArgLocations[Arg];
661 }
Douglas Gregor8e458f42009-02-09 18:46:07 +0000662 Tok.setAnnotationValue(TemplateId);
Douglas Gregor0c281a82009-02-25 19:37:18 +0000663 if (TemplateKWLoc.isValid())
664 Tok.setLocation(TemplateKWLoc);
665 else
666 Tok.setLocation(TemplateNameLoc);
667
668 TemplateArgsPtr.release();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000669 }
670
671 // Common fields for the annotation token
Douglas Gregor2fa10442008-12-18 19:37:40 +0000672 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregor2fa10442008-12-18 19:37:40 +0000673
Douglas Gregor2fa10442008-12-18 19:37:40 +0000674 // In case the tokens were cached, have Preprocessor replace them with the
675 // annotation token.
676 PP.AnnotateCachedTokens(Tok);
677}
678
Douglas Gregor0c281a82009-02-25 19:37:18 +0000679/// \brief Replaces a template-id annotation token with a type
680/// annotation token.
681///
Douglas Gregord7cb0372009-04-01 21:51:26 +0000682/// If there was a failure when forming the type from the template-id,
683/// a type annotation token will still be created, but will have a
684/// NULL type pointer to signify an error.
685void Parser::AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS) {
Douglas Gregor0c281a82009-02-25 19:37:18 +0000686 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
687
688 TemplateIdAnnotation *TemplateId
689 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
Douglas Gregoraabb8502009-03-31 00:43:58 +0000690 assert((TemplateId->Kind == TNK_Type_template ||
691 TemplateId->Kind == TNK_Dependent_template_name) &&
692 "Only works for type and dependent templates");
Douglas Gregor0c281a82009-02-25 19:37:18 +0000693
694 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
695 TemplateId->getTemplateArgs(),
696 TemplateId->getTemplateArgIsType(),
697 TemplateId->NumArgs);
698
699 Action::TypeResult Type
Douglas Gregordd13e842009-03-30 22:58:21 +0000700 = Actions.ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
701 TemplateId->TemplateNameLoc,
702 TemplateId->LAngleLoc,
703 TemplateArgsPtr,
704 TemplateId->getTemplateArgLocations(),
705 TemplateId->RAngleLoc);
Douglas Gregor0c281a82009-02-25 19:37:18 +0000706 // Create the new "type" annotation token.
707 Tok.setKind(tok::annot_typename);
Douglas Gregord7cb0372009-04-01 21:51:26 +0000708 Tok.setAnnotationValue(Type.isInvalid()? 0 : Type.get());
Douglas Gregor0c281a82009-02-25 19:37:18 +0000709 if (SS && SS->isNotEmpty()) // it was a C++ qualified type name.
710 Tok.setLocation(SS->getBeginLoc());
711
712 // We might be backtracking, in which case we need to replace the
713 // template-id annotation token with the type annotation within the
714 // set of cached tokens. That way, we won't try to form the same
715 // class template specialization again.
716 PP.ReplaceLastTokenWithAnnotation(Tok);
717 TemplateId->Destroy();
Douglas Gregor0c281a82009-02-25 19:37:18 +0000718}
719
Douglas Gregor2fa10442008-12-18 19:37:40 +0000720/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
721///
722/// template-argument: [C++ 14.2]
723/// assignment-expression
724/// type-id
725/// id-expression
Douglas Gregor6f37b582009-02-09 19:34:22 +0000726void *Parser::ParseTemplateArgument(bool &ArgIsType) {
Douglas Gregor8e458f42009-02-09 18:46:07 +0000727 // C++ [temp.arg]p2:
728 // In a template-argument, an ambiguity between a type-id and an
729 // expression is resolved to a type-id, regardless of the form of
730 // the corresponding template-parameter.
731 //
732 // Therefore, we initially try to parse a type-id.
Douglas Gregor341ac792009-02-10 00:53:15 +0000733 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor6f37b582009-02-09 19:34:22 +0000734 ArgIsType = true;
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000735 TypeResult TypeArg = ParseTypeName();
736 if (TypeArg.isInvalid())
737 return 0;
738 return TypeArg.get();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000739 }
740
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000741 OwningExprResult ExprArg = ParseAssignmentExpression();
742 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor6f37b582009-02-09 19:34:22 +0000743 return 0;
Douglas Gregor8e458f42009-02-09 18:46:07 +0000744
Douglas Gregor6f37b582009-02-09 19:34:22 +0000745 ArgIsType = false;
746 return ExprArg.release();
Douglas Gregor2fa10442008-12-18 19:37:40 +0000747}
748
749/// ParseTemplateArgumentList - Parse a C++ template-argument-list
750/// (C++ [temp.names]). Returns true if there was an error.
751///
752/// template-argument-list: [C++ 14.2]
753/// template-argument
754/// template-argument-list ',' template-argument
Douglas Gregor6f37b582009-02-09 19:34:22 +0000755bool
756Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000757 TemplateArgIsTypeList &TemplateArgIsType,
758 TemplateArgLocationList &TemplateArgLocations) {
Douglas Gregor2fa10442008-12-18 19:37:40 +0000759 while (true) {
Douglas Gregor6f37b582009-02-09 19:34:22 +0000760 bool IsType = false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000761 SourceLocation Loc = Tok.getLocation();
Douglas Gregor6f37b582009-02-09 19:34:22 +0000762 void *Arg = ParseTemplateArgument(IsType);
763 if (Arg) {
764 TemplateArgs.push_back(Arg);
765 TemplateArgIsType.push_back(IsType);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000766 TemplateArgLocations.push_back(Loc);
Douglas Gregor6f37b582009-02-09 19:34:22 +0000767 } else {
Douglas Gregor2fa10442008-12-18 19:37:40 +0000768 SkipUntil(tok::comma, tok::greater, true, true);
769 return true;
770 }
Douglas Gregor6f37b582009-02-09 19:34:22 +0000771
Douglas Gregor2fa10442008-12-18 19:37:40 +0000772 // If the next token is a comma, consume it and keep reading
773 // arguments.
774 if (Tok.isNot(tok::comma)) break;
775
776 // Consume the comma.
777 ConsumeToken();
778 }
779
Douglas Gregorf2d87392009-02-25 23:02:36 +0000780 return Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater);
Douglas Gregor2fa10442008-12-18 19:37:40 +0000781}
782
Douglas Gregore3298aa2009-05-12 21:31:51 +0000783/// \brief Parse a C++ explicit template instantiation
784/// (C++ [temp.explicit]).
785///
786/// explicit-instantiation:
787/// 'template' declaration
788Parser::DeclPtrTy Parser::ParseExplicitInstantiation(SourceLocation &DeclEnd) {
789 assert(Tok.is(tok::kw_template) && NextToken().isNot(tok::less) &&
790 "Token does not start an explicit instantiation.");
791
792 SourceLocation TemplateLoc = ConsumeToken();
793 return ParseSingleDeclarationAfterTemplate(Declarator::FileContext, 0,
794 TemplateLoc, DeclEnd, AS_none);
795}