blob: 0f9bcd2219b11725921e5d21d5bb1fedfbc30743 [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,
38 AccessSpecifier AS) {
Douglas Gregorb3bec712008-12-01 23:54:00 +000039 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
40 "Token does not start a template declaration.");
41
Douglas Gregor8e7f9572008-12-02 00:41:28 +000042 // Enter template-parameter scope.
Douglas Gregor95d40792008-12-10 06:34:36 +000043 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Douglas Gregor8e7f9572008-12-02 00:41:28 +000044
Douglas Gregor52473432008-12-24 02:52:09 +000045 // Parse multiple levels of template headers within this template
46 // parameter scope, e.g.,
47 //
48 // template<typename T>
49 // template<typename U>
50 // class A<T>::B { ... };
51 //
52 // We parse multiple levels non-recursively so that we can build a
53 // single data structure containing all of the template parameter
Douglas Gregora08b6c72009-02-17 23:15:12 +000054 // lists to easily differentiate between the case above and:
Douglas Gregor52473432008-12-24 02:52:09 +000055 //
56 // template<typename T>
57 // class A {
58 // template<typename U> class B;
59 // };
60 //
61 // In the first case, the action for declaring A<T>::B receives
62 // both template parameter lists. In the second case, the action for
63 // defining A<T>::B receives just the inner template parameter list
64 // (and retrieves the outer template parameter list from its
65 // context).
66 TemplateParameterLists ParamLists;
67 do {
68 // Consume the 'export', if any.
69 SourceLocation ExportLoc;
70 if (Tok.is(tok::kw_export)) {
71 ExportLoc = ConsumeToken();
72 }
73
74 // Consume the 'template', which should be here.
75 SourceLocation TemplateLoc;
76 if (Tok.is(tok::kw_template)) {
77 TemplateLoc = ConsumeToken();
78 } else {
79 Diag(Tok.getLocation(), diag::err_expected_template);
Chris Lattner5261d0c2009-03-28 19:18:32 +000080 return DeclPtrTy();
Douglas Gregor52473432008-12-24 02:52:09 +000081 }
82
83 // Parse the '<' template-parameter-list '>'
84 SourceLocation LAngleLoc, RAngleLoc;
85 TemplateParameterList TemplateParams;
86 ParseTemplateParameters(ParamLists.size(), TemplateParams, LAngleLoc,
87 RAngleLoc);
88
89 ParamLists.push_back(
90 Actions.ActOnTemplateParameterList(ParamLists.size(), ExportLoc,
91 TemplateLoc, LAngleLoc,
92 &TemplateParams[0],
93 TemplateParams.size(), RAngleLoc));
94 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
95
96 // Parse the actual template declaration.
Chris Lattnera17991f2009-03-29 16:50:03 +000097
98 // FIXME: This accepts template<typename x> int y;
99 // FIXME: Converting DeclGroupPtr to DeclPtr like this is an insanely gruesome
100 // hack, will bring up on cfe-dev.
101 DeclGroupPtrTy DG = ParseDeclarationOrFunctionDefinition(&ParamLists, AS);
102 return DeclPtrTy::make(DG.get());
Douglas Gregorb3bec712008-12-01 23:54:00 +0000103}
104
105/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregor279272e2009-02-04 19:02:06 +0000106/// angle brackets. Depth is the depth of this template-parameter-list, which
107/// is the number of template headers directly enclosing this template header.
108/// TemplateParams is the current list of template parameters we're building.
109/// The template parameter we parse will be added to this list. LAngleLoc and
110/// RAngleLoc will receive the positions of the '<' and '>', respectively,
111/// that enclose this template parameter list.
Douglas Gregor52473432008-12-24 02:52:09 +0000112bool Parser::ParseTemplateParameters(unsigned Depth,
113 TemplateParameterList &TemplateParams,
114 SourceLocation &LAngleLoc,
115 SourceLocation &RAngleLoc) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000116 // Get the template parameter list.
117 if(!Tok.is(tok::less)) {
118 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
119 return false;
120 }
Douglas Gregor52473432008-12-24 02:52:09 +0000121 LAngleLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000122
123 // Try to parse the template parameter list.
Douglas Gregor52473432008-12-24 02:52:09 +0000124 if (Tok.is(tok::greater))
125 RAngleLoc = ConsumeToken();
126 else if(ParseTemplateParameterList(Depth, TemplateParams)) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000127 if(!Tok.is(tok::greater)) {
128 Diag(Tok.getLocation(), diag::err_expected_greater);
129 return false;
130 }
Douglas Gregor52473432008-12-24 02:52:09 +0000131 RAngleLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000132 }
133 return true;
134}
135
136/// ParseTemplateParameterList - Parse a template parameter list. If
137/// the parsing fails badly (i.e., closing bracket was left out), this
138/// will try to put the token stream in a reasonable position (closing
139/// a statement, etc.) and return false.
140///
141/// template-parameter-list: [C++ temp]
142/// template-parameter
143/// template-parameter-list ',' template-parameter
Douglas Gregor52473432008-12-24 02:52:09 +0000144bool
145Parser::ParseTemplateParameterList(unsigned Depth,
146 TemplateParameterList &TemplateParams) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000147 while(1) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000148 if (DeclPtrTy TmpParam
Douglas Gregor52473432008-12-24 02:52:09 +0000149 = ParseTemplateParameter(Depth, TemplateParams.size())) {
150 TemplateParams.push_back(TmpParam);
151 } else {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000152 // If we failed to parse a template parameter, skip until we find
153 // a comma or closing brace.
154 SkipUntil(tok::comma, tok::greater, true, true);
155 }
156
157 // Did we find a comma or the end of the template parmeter list?
158 if(Tok.is(tok::comma)) {
159 ConsumeToken();
160 } else if(Tok.is(tok::greater)) {
161 // Don't consume this... that's done by template parser.
162 break;
163 } else {
164 // Somebody probably forgot to close the template. Skip ahead and
165 // try to get out of the expression. This error is currently
166 // subsumed by whatever goes on in ParseTemplateParameter.
167 // TODO: This could match >>, and it would be nice to avoid those
168 // silly errors with template <vec<T>>.
169 // Diag(Tok.getLocation(), diag::err_expected_comma_greater);
170 SkipUntil(tok::greater, true, true);
171 return false;
172 }
173 }
174 return true;
175}
176
177/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
178///
179/// template-parameter: [C++ temp.param]
180/// type-parameter
181/// parameter-declaration
182///
183/// type-parameter: (see below)
184/// 'class' identifier[opt]
185/// 'class' identifier[opt] '=' type-id
186/// 'typename' identifier[opt]
187/// 'typename' identifier[opt] '=' type-id
188/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
189/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
Chris Lattner5261d0c2009-03-28 19:18:32 +0000190Parser::DeclPtrTy
Douglas Gregor52473432008-12-24 02:52:09 +0000191Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Chris Lattner4e7a4202009-01-04 23:51:17 +0000192 if(Tok.is(tok::kw_class) ||
193 (Tok.is(tok::kw_typename) &&
194 // FIXME: Next token has not been annotated!
Chris Lattner5d7eace2009-01-06 05:06:21 +0000195 NextToken().isNot(tok::annot_typename))) {
Douglas Gregor52473432008-12-24 02:52:09 +0000196 return ParseTypeParameter(Depth, Position);
Douglas Gregorb3bec712008-12-01 23:54:00 +0000197 }
Chris Lattner4e7a4202009-01-04 23:51:17 +0000198
199 if(Tok.is(tok::kw_template))
200 return ParseTemplateTemplateParameter(Depth, Position);
201
202 // If it's none of the above, then it must be a parameter declaration.
203 // NOTE: This will pick up errors in the closure of the template parameter
204 // list (e.g., template < ; Check here to implement >> style closures.
205 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregorb3bec712008-12-01 23:54:00 +0000206}
207
208/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
209/// Other kinds of template parameters are parsed in
210/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
211///
212/// type-parameter: [C++ temp.param]
213/// 'class' identifier[opt]
214/// 'class' identifier[opt] '=' type-id
215/// 'typename' identifier[opt]
216/// 'typename' identifier[opt] '=' type-id
Chris Lattner5261d0c2009-03-28 19:18:32 +0000217Parser::DeclPtrTy Parser::ParseTypeParameter(unsigned Depth, unsigned Position){
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000218 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
219 "A type-parameter starts with 'class' or 'typename'");
220
221 // Consume the 'class' or 'typename' keyword.
222 bool TypenameKeyword = Tok.is(tok::kw_typename);
223 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000224
225 // Grab the template parameter name (if given)
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000226 SourceLocation NameLoc;
227 IdentifierInfo* ParamName = 0;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000228 if(Tok.is(tok::identifier)) {
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000229 ParamName = Tok.getIdentifierInfo();
230 NameLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000231 } else if(Tok.is(tok::equal) || Tok.is(tok::comma) ||
232 Tok.is(tok::greater)) {
233 // Unnamed template parameter. Don't have to do anything here, just
234 // don't consume this token.
235 } else {
236 Diag(Tok.getLocation(), diag::err_expected_ident);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000237 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000238 }
239
Chris Lattner5261d0c2009-03-28 19:18:32 +0000240 DeclPtrTy TypeParam = Actions.ActOnTypeParameter(CurScope, TypenameKeyword,
241 KeyLoc, ParamName, NameLoc,
242 Depth, Position);
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000243
Douglas Gregorb3bec712008-12-01 23:54:00 +0000244 // Grab a default type id (if given).
Douglas Gregorb3bec712008-12-01 23:54:00 +0000245 if(Tok.is(tok::equal)) {
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000246 SourceLocation EqualLoc = ConsumeToken();
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000247 SourceLocation DefaultLoc = Tok.getLocation();
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000248 TypeResult DefaultType = ParseTypeName();
249 if (!DefaultType.isInvalid())
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000250 Actions.ActOnTypeParameterDefault(TypeParam, EqualLoc, DefaultLoc,
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000251 DefaultType.get());
Douglas Gregorb3bec712008-12-01 23:54:00 +0000252 }
253
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000254 return TypeParam;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000255}
256
257/// ParseTemplateTemplateParameter - Handle the parsing of template
258/// template parameters.
259///
260/// type-parameter: [C++ temp.param]
261/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
262/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
Chris Lattner5261d0c2009-03-28 19:18:32 +0000263Parser::DeclPtrTy
Douglas Gregor52473432008-12-24 02:52:09 +0000264Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000265 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
266
267 // Handle the template <...> part.
268 SourceLocation TemplateLoc = ConsumeToken();
Douglas Gregor52473432008-12-24 02:52:09 +0000269 TemplateParameterList TemplateParams;
Douglas Gregord406b032009-02-06 22:42:48 +0000270 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor77f7ced2009-02-10 19:52:54 +0000271 {
272 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
273 if(!ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
274 RAngleLoc)) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000275 return DeclPtrTy();
Douglas Gregor77f7ced2009-02-10 19:52:54 +0000276 }
Douglas Gregorb3bec712008-12-01 23:54:00 +0000277 }
278
279 // Generate a meaningful error if the user forgot to put class before the
280 // identifier, comma, or greater.
281 if(!Tok.is(tok::kw_class)) {
282 Diag(Tok.getLocation(), diag::err_expected_class_before)
283 << PP.getSpelling(Tok);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000284 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000285 }
286 SourceLocation ClassLoc = ConsumeToken();
287
288 // Get the identifier, if given.
Douglas Gregor279272e2009-02-04 19:02:06 +0000289 SourceLocation NameLoc;
290 IdentifierInfo* ParamName = 0;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000291 if(Tok.is(tok::identifier)) {
Douglas Gregor279272e2009-02-04 19:02:06 +0000292 ParamName = Tok.getIdentifierInfo();
293 NameLoc = ConsumeToken();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000294 } else if(Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
295 // Unnamed template parameter. Don't have to do anything here, just
296 // don't consume this token.
297 } else {
298 Diag(Tok.getLocation(), diag::err_expected_ident);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000299 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000300 }
301
Douglas Gregord406b032009-02-06 22:42:48 +0000302 TemplateParamsTy *ParamList =
303 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
304 TemplateLoc, LAngleLoc,
305 &TemplateParams[0],
306 TemplateParams.size(),
307 RAngleLoc);
308
Chris Lattner5261d0c2009-03-28 19:18:32 +0000309 Parser::DeclPtrTy Param
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000310 = Actions.ActOnTemplateTemplateParameter(CurScope, TemplateLoc,
311 ParamList, ParamName,
312 NameLoc, Depth, Position);
313
314 // Get the a default value, if given.
315 if (Tok.is(tok::equal)) {
316 SourceLocation EqualLoc = ConsumeToken();
317 OwningExprResult DefaultExpr = ParseCXXIdExpression();
318 if (DefaultExpr.isInvalid())
319 return Param;
320 else if (Param)
321 Actions.ActOnTemplateTemplateParameterDefault(Param, EqualLoc,
322 move(DefaultExpr));
323 }
324
325 return Param;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000326}
327
328/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
329/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregor2fa10442008-12-18 19:37:40 +0000330///
Douglas Gregorb3bec712008-12-01 23:54:00 +0000331/// template-parameter:
332/// ...
333/// parameter-declaration
334///
335/// NOTE: It would be ideal to simply call out to ParseParameterDeclaration(),
336/// but that didn't work out to well. Instead, this tries to recrate the basic
337/// parsing of parameter declarations, but tries to constrain it for template
338/// parameters.
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000339/// FIXME: We need to make a ParseParameterDeclaration that works for
340/// non-type template parameters and normal function parameters.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000341Parser::DeclPtrTy
Douglas Gregor52473432008-12-24 02:52:09 +0000342Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000343 SourceLocation StartLoc = Tok.getLocation();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000344
345 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000346 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregorb3bec712008-12-01 23:54:00 +0000347 // declarators (parts of declarators?) are accepted for parameters.
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000348 DeclSpec DS;
349 ParseDeclarationSpecifiers(DS);
Douglas Gregorb3bec712008-12-01 23:54:00 +0000350
351 // Parse this as a typename.
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000352 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
353 ParseDeclarator(ParamDecl);
Chris Lattner8376d2e2009-01-05 01:24:05 +0000354 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified && !DS.getTypeRep()) {
Douglas Gregorb3bec712008-12-01 23:54:00 +0000355 // This probably shouldn't happen - and it's more of a Sema thing, but
356 // basically we didn't parse the type name because we couldn't associate
357 // it with an AST node. we should just skip to the comma or greater.
358 // TODO: This is currently a placeholder for some kind of Sema Error.
359 Diag(Tok.getLocation(), diag::err_parse_error);
360 SkipUntil(tok::comma, tok::greater, true, true);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000361 return DeclPtrTy();
Douglas Gregorb3bec712008-12-01 23:54:00 +0000362 }
363
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000364 // Create the parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000365 DeclPtrTy Param = Actions.ActOnNonTypeTemplateParameter(CurScope, ParamDecl,
366 Depth, Position);
Douglas Gregorb3bec712008-12-01 23:54:00 +0000367
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000368 // If there is a default value, parse it.
Chris Lattner8376d2e2009-01-05 01:24:05 +0000369 if (Tok.is(tok::equal)) {
Douglas Gregor9225a7e2009-02-10 19:49:53 +0000370 SourceLocation EqualLoc = ConsumeToken();
371
372 // C++ [temp.param]p15:
373 // When parsing a default template-argument for a non-type
374 // template-parameter, the first non-nested > is taken as the
375 // end of the template-parameter-list rather than a greater-than
376 // operator.
377 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
378
379 OwningExprResult DefaultArg = ParseAssignmentExpression();
380 if (DefaultArg.isInvalid())
381 SkipUntil(tok::comma, tok::greater, true, true);
382 else if (Param)
383 Actions.ActOnNonTypeTemplateParameterDefault(Param, EqualLoc,
384 move(DefaultArg));
Douglas Gregorb3bec712008-12-01 23:54:00 +0000385 }
386
Douglas Gregor8e7f9572008-12-02 00:41:28 +0000387 return Param;
Douglas Gregorb3bec712008-12-01 23:54:00 +0000388}
Douglas Gregor2fa10442008-12-18 19:37:40 +0000389
Douglas Gregora08b6c72009-02-17 23:15:12 +0000390/// \brief Parses a template-id that after the template name has
391/// already been parsed.
392///
393/// This routine takes care of parsing the enclosed template argument
394/// list ('<' template-parameter-list [opt] '>') and placing the
395/// results into a form that can be transferred to semantic analysis.
396///
397/// \param Template the template declaration produced by isTemplateName
398///
399/// \param TemplateNameLoc the source location of the template name
400///
401/// \param SS if non-NULL, the nested-name-specifier preceding the
402/// template name.
403///
404/// \param ConsumeLastToken if true, then we will consume the last
405/// token that forms the template-id. Otherwise, we will leave the
406/// last token in the stream (e.g., so that it can be replaced with an
407/// annotation token).
408bool
Douglas Gregordd13e842009-03-30 22:58:21 +0000409Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
Douglas Gregora08b6c72009-02-17 23:15:12 +0000410 SourceLocation TemplateNameLoc,
411 const CXXScopeSpec *SS,
412 bool ConsumeLastToken,
413 SourceLocation &LAngleLoc,
414 TemplateArgList &TemplateArgs,
415 TemplateArgIsTypeList &TemplateArgIsType,
416 TemplateArgLocationList &TemplateArgLocations,
417 SourceLocation &RAngleLoc) {
418 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
419
420 // Consume the '<'.
421 LAngleLoc = ConsumeToken();
422
423 // Parse the optional template-argument-list.
424 bool Invalid = false;
425 {
426 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
427 if (Tok.isNot(tok::greater))
428 Invalid = ParseTemplateArgumentList(TemplateArgs, TemplateArgIsType,
429 TemplateArgLocations);
430
431 if (Invalid) {
432 // Try to find the closing '>'.
433 SkipUntil(tok::greater, true, !ConsumeLastToken);
434
435 return true;
436 }
437 }
438
Douglas Gregorf2d87392009-02-25 23:02:36 +0000439 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
Douglas Gregora08b6c72009-02-17 23:15:12 +0000440 return true;
441
Douglas Gregorf2d87392009-02-25 23:02:36 +0000442 // Determine the location of the '>' or '>>'. Only consume this
443 // token if the caller asked us to.
Douglas Gregora08b6c72009-02-17 23:15:12 +0000444 RAngleLoc = Tok.getLocation();
445
Douglas Gregorf2d87392009-02-25 23:02:36 +0000446 if (Tok.is(tok::greatergreater)) {
Douglas Gregor3bb30002009-02-26 21:00:50 +0000447 if (!getLang().CPlusPlus0x) {
448 const char *ReplaceStr = "> >";
449 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
450 ReplaceStr = "> > ";
451
452 Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space)
Douglas Gregor61be3602009-02-27 17:53:17 +0000453 << CodeModificationHint::CreateReplacement(
454 SourceRange(Tok.getLocation()), ReplaceStr);
Douglas Gregor3bb30002009-02-26 21:00:50 +0000455 }
Douglas Gregorf2d87392009-02-25 23:02:36 +0000456
457 Tok.setKind(tok::greater);
458 if (!ConsumeLastToken) {
459 // Since we're not supposed to consume the '>>' token, we need
460 // to insert a second '>' token after the first.
461 PP.EnterToken(Tok);
462 }
463 } else if (ConsumeLastToken)
Douglas Gregora08b6c72009-02-17 23:15:12 +0000464 ConsumeToken();
465
466 return false;
467}
468
Douglas Gregor0c281a82009-02-25 19:37:18 +0000469/// \brief Replace the tokens that form a simple-template-id with an
470/// annotation token containing the complete template-id.
471///
472/// The first token in the stream must be the name of a template that
473/// is followed by a '<'. This routine will parse the complete
474/// simple-template-id and replace the tokens with a single annotation
475/// token with one of two different kinds: if the template-id names a
476/// type (and \p AllowTypeAnnotation is true), the annotation token is
477/// a type annotation that includes the optional nested-name-specifier
478/// (\p SS). Otherwise, the annotation token is a template-id
479/// annotation that does not include the optional
480/// nested-name-specifier.
481///
482/// \param Template the declaration of the template named by the first
483/// token (an identifier), as returned from \c Action::isTemplateName().
484///
485/// \param TemplateNameKind the kind of template that \p Template
486/// refers to, as returned from \c Action::isTemplateName().
487///
488/// \param SS if non-NULL, the nested-name-specifier that precedes
489/// this template name.
490///
491/// \param TemplateKWLoc if valid, specifies that this template-id
492/// annotation was preceded by the 'template' keyword and gives the
493/// location of that keyword. If invalid (the default), then this
494/// template-id was not preceded by a 'template' keyword.
495///
496/// \param AllowTypeAnnotation if true (the default), then a
497/// simple-template-id that refers to a class template, template
498/// template parameter, or other template that produces a type will be
499/// replaced with a type annotation token. Otherwise, the
500/// simple-template-id is always replaced with a template-id
501/// annotation token.
Douglas Gregordd13e842009-03-30 22:58:21 +0000502void Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Douglas Gregor0c281a82009-02-25 19:37:18 +0000503 const CXXScopeSpec *SS,
504 SourceLocation TemplateKWLoc,
505 bool AllowTypeAnnotation) {
Douglas Gregor2fa10442008-12-18 19:37:40 +0000506 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
507 assert(Template && Tok.is(tok::identifier) && NextToken().is(tok::less) &&
508 "Parser isn't at the beginning of a template-id");
509
510 // Consume the template-name.
Douglas Gregor0c281a82009-02-25 19:37:18 +0000511 IdentifierInfo *Name = Tok.getIdentifierInfo();
Douglas Gregor2fa10442008-12-18 19:37:40 +0000512 SourceLocation TemplateNameLoc = ConsumeToken();
513
Douglas Gregora08b6c72009-02-17 23:15:12 +0000514 // Parse the enclosed template argument list.
515 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor6f37b582009-02-09 19:34:22 +0000516 TemplateArgList TemplateArgs;
517 TemplateArgIsTypeList TemplateArgIsType;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000518 TemplateArgLocationList TemplateArgLocations;
Douglas Gregora08b6c72009-02-17 23:15:12 +0000519 bool Invalid = ParseTemplateIdAfterTemplateName(Template, TemplateNameLoc,
520 SS, false, LAngleLoc,
521 TemplateArgs,
522 TemplateArgIsType,
523 TemplateArgLocations,
524 RAngleLoc);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000525
Douglas Gregora08b6c72009-02-17 23:15:12 +0000526 ASTTemplateArgsPtr TemplateArgsPtr(Actions, &TemplateArgs[0],
527 &TemplateArgIsType[0],
528 TemplateArgs.size());
Douglas Gregoraf0d0092009-02-09 21:04:56 +0000529
Douglas Gregora08b6c72009-02-17 23:15:12 +0000530 if (Invalid) // FIXME: How to recover from a broken template-id?
531 return;
Douglas Gregor2fa10442008-12-18 19:37:40 +0000532
Douglas Gregor8e458f42009-02-09 18:46:07 +0000533 // Build the annotation token.
Douglas Gregoraabb8502009-03-31 00:43:58 +0000534 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
Douglas Gregora08b6c72009-02-17 23:15:12 +0000535 Action::TypeResult Type
Douglas Gregordd13e842009-03-30 22:58:21 +0000536 = Actions.ActOnTemplateIdType(Template, TemplateNameLoc,
537 LAngleLoc, TemplateArgsPtr,
538 &TemplateArgLocations[0],
539 RAngleLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +0000540 if (Type.isInvalid()) // FIXME: better recovery?
541 return;
542
543 Tok.setKind(tok::annot_typename);
544 Tok.setAnnotationValue(Type.get());
Douglas Gregor0c281a82009-02-25 19:37:18 +0000545 if (SS && SS->isNotEmpty())
546 Tok.setLocation(SS->getBeginLoc());
547 else if (TemplateKWLoc.isValid())
548 Tok.setLocation(TemplateKWLoc);
549 else
550 Tok.setLocation(TemplateNameLoc);
Douglas Gregora08b6c72009-02-17 23:15:12 +0000551 } else {
Douglas Gregoraabb8502009-03-31 00:43:58 +0000552 // Build a template-id annotation token that can be processed
553 // later.
Douglas Gregor0c281a82009-02-25 19:37:18 +0000554 Tok.setKind(tok::annot_template_id);
Douglas Gregor8e458f42009-02-09 18:46:07 +0000555 TemplateIdAnnotation *TemplateId
Douglas Gregor0c281a82009-02-25 19:37:18 +0000556 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
Douglas Gregor8e458f42009-02-09 18:46:07 +0000557 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregor0c281a82009-02-25 19:37:18 +0000558 TemplateId->Name = Name;
Chris Lattner5261d0c2009-03-28 19:18:32 +0000559 TemplateId->Template = Template.getAs<void*>();
Douglas Gregor0c281a82009-02-25 19:37:18 +0000560 TemplateId->Kind = TNK;
Douglas Gregor8e458f42009-02-09 18:46:07 +0000561 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor0c281a82009-02-25 19:37:18 +0000562 TemplateId->RAngleLoc = RAngleLoc;
563 void **Args = TemplateId->getTemplateArgs();
564 bool *ArgIsType = TemplateId->getTemplateArgIsType();
565 SourceLocation *ArgLocs = TemplateId->getTemplateArgLocations();
566 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg) {
Douglas Gregor8e458f42009-02-09 18:46:07 +0000567 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor0c281a82009-02-25 19:37:18 +0000568 ArgIsType[Arg] = TemplateArgIsType[Arg];
569 ArgLocs[Arg] = TemplateArgLocations[Arg];
570 }
Douglas Gregor8e458f42009-02-09 18:46:07 +0000571 Tok.setAnnotationValue(TemplateId);
Douglas Gregor0c281a82009-02-25 19:37:18 +0000572 if (TemplateKWLoc.isValid())
573 Tok.setLocation(TemplateKWLoc);
574 else
575 Tok.setLocation(TemplateNameLoc);
576
577 TemplateArgsPtr.release();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000578 }
579
580 // Common fields for the annotation token
Douglas Gregor2fa10442008-12-18 19:37:40 +0000581 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregor2fa10442008-12-18 19:37:40 +0000582
Douglas Gregor2fa10442008-12-18 19:37:40 +0000583 // In case the tokens were cached, have Preprocessor replace them with the
584 // annotation token.
585 PP.AnnotateCachedTokens(Tok);
586}
587
Douglas Gregor0c281a82009-02-25 19:37:18 +0000588/// \brief Replaces a template-id annotation token with a type
589/// annotation token.
590///
Douglas Gregord7cb0372009-04-01 21:51:26 +0000591/// If there was a failure when forming the type from the template-id,
592/// a type annotation token will still be created, but will have a
593/// NULL type pointer to signify an error.
594void Parser::AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS) {
Douglas Gregor0c281a82009-02-25 19:37:18 +0000595 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
596
597 TemplateIdAnnotation *TemplateId
598 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
Douglas Gregoraabb8502009-03-31 00:43:58 +0000599 assert((TemplateId->Kind == TNK_Type_template ||
600 TemplateId->Kind == TNK_Dependent_template_name) &&
601 "Only works for type and dependent templates");
Douglas Gregor0c281a82009-02-25 19:37:18 +0000602
603 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
604 TemplateId->getTemplateArgs(),
605 TemplateId->getTemplateArgIsType(),
606 TemplateId->NumArgs);
607
608 Action::TypeResult Type
Douglas Gregordd13e842009-03-30 22:58:21 +0000609 = Actions.ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
610 TemplateId->TemplateNameLoc,
611 TemplateId->LAngleLoc,
612 TemplateArgsPtr,
613 TemplateId->getTemplateArgLocations(),
614 TemplateId->RAngleLoc);
Douglas Gregor0c281a82009-02-25 19:37:18 +0000615 // Create the new "type" annotation token.
616 Tok.setKind(tok::annot_typename);
Douglas Gregord7cb0372009-04-01 21:51:26 +0000617 Tok.setAnnotationValue(Type.isInvalid()? 0 : Type.get());
Douglas Gregor0c281a82009-02-25 19:37:18 +0000618 if (SS && SS->isNotEmpty()) // it was a C++ qualified type name.
619 Tok.setLocation(SS->getBeginLoc());
620
621 // We might be backtracking, in which case we need to replace the
622 // template-id annotation token with the type annotation within the
623 // set of cached tokens. That way, we won't try to form the same
624 // class template specialization again.
625 PP.ReplaceLastTokenWithAnnotation(Tok);
626 TemplateId->Destroy();
Douglas Gregor0c281a82009-02-25 19:37:18 +0000627}
628
Douglas Gregor2fa10442008-12-18 19:37:40 +0000629/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
630///
631/// template-argument: [C++ 14.2]
632/// assignment-expression
633/// type-id
634/// id-expression
Douglas Gregor6f37b582009-02-09 19:34:22 +0000635void *Parser::ParseTemplateArgument(bool &ArgIsType) {
Douglas Gregor8e458f42009-02-09 18:46:07 +0000636 // C++ [temp.arg]p2:
637 // In a template-argument, an ambiguity between a type-id and an
638 // expression is resolved to a type-id, regardless of the form of
639 // the corresponding template-parameter.
640 //
641 // Therefore, we initially try to parse a type-id.
Douglas Gregor341ac792009-02-10 00:53:15 +0000642 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor6f37b582009-02-09 19:34:22 +0000643 ArgIsType = true;
Douglas Gregor6c0f4062009-02-18 17:45:20 +0000644 TypeResult TypeArg = ParseTypeName();
645 if (TypeArg.isInvalid())
646 return 0;
647 return TypeArg.get();
Douglas Gregor8e458f42009-02-09 18:46:07 +0000648 }
649
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000650 OwningExprResult ExprArg = ParseAssignmentExpression();
651 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor6f37b582009-02-09 19:34:22 +0000652 return 0;
Douglas Gregor8e458f42009-02-09 18:46:07 +0000653
Douglas Gregor6f37b582009-02-09 19:34:22 +0000654 ArgIsType = false;
655 return ExprArg.release();
Douglas Gregor2fa10442008-12-18 19:37:40 +0000656}
657
658/// ParseTemplateArgumentList - Parse a C++ template-argument-list
659/// (C++ [temp.names]). Returns true if there was an error.
660///
661/// template-argument-list: [C++ 14.2]
662/// template-argument
663/// template-argument-list ',' template-argument
Douglas Gregor6f37b582009-02-09 19:34:22 +0000664bool
665Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000666 TemplateArgIsTypeList &TemplateArgIsType,
667 TemplateArgLocationList &TemplateArgLocations) {
Douglas Gregor2fa10442008-12-18 19:37:40 +0000668 while (true) {
Douglas Gregor6f37b582009-02-09 19:34:22 +0000669 bool IsType = false;
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000670 SourceLocation Loc = Tok.getLocation();
Douglas Gregor6f37b582009-02-09 19:34:22 +0000671 void *Arg = ParseTemplateArgument(IsType);
672 if (Arg) {
673 TemplateArgs.push_back(Arg);
674 TemplateArgIsType.push_back(IsType);
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000675 TemplateArgLocations.push_back(Loc);
Douglas Gregor6f37b582009-02-09 19:34:22 +0000676 } else {
Douglas Gregor2fa10442008-12-18 19:37:40 +0000677 SkipUntil(tok::comma, tok::greater, true, true);
678 return true;
679 }
Douglas Gregor6f37b582009-02-09 19:34:22 +0000680
Douglas Gregor2fa10442008-12-18 19:37:40 +0000681 // If the next token is a comma, consume it and keep reading
682 // arguments.
683 if (Tok.isNot(tok::comma)) break;
684
685 // Consume the comma.
686 ConsumeToken();
687 }
688
Douglas Gregorf2d87392009-02-25 23:02:36 +0000689 return Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater);
Douglas Gregor2fa10442008-12-18 19:37:40 +0000690}
691