blob: 2c07823aba2bc0655387a8609d35752d57d2e8e2 [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 +000019
20using namespace clang;
21
Douglas Gregorcc636682009-02-17 23:15:12 +000022/// \brief Parse a template declaration or an explicit specialization.
23///
24/// Template declarations include one or more template parameter lists
25/// and either the function or class template declaration. Explicit
26/// specializations contain one or more 'template < >' prefixes
27/// followed by a (possibly templated) declaration. Since the
28/// syntactic form of both features is nearly identical, we parse all
29/// of the template headers together and let semantic analysis sort
30/// the declarations from the explicit specializations.
Douglas Gregoradcac882008-12-01 23:54:00 +000031///
32/// template-declaration: [C++ temp]
33/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
Douglas Gregorcc636682009-02-17 23:15:12 +000034///
35/// explicit-specialization: [ C++ temp.expl.spec]
36/// 'template' '<' '>' declaration
37Parser::DeclTy *
Anders Carlsson5aeccdb2009-03-26 00:52:18 +000038Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
39 AccessSpecifier AS) {
Douglas Gregoradcac882008-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 Gregor26236e82008-12-02 00:41:28 +000043 // Enter template-parameter scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +000044 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Douglas Gregor26236e82008-12-02 00:41:28 +000045
Douglas Gregorc4b4e7b2008-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 Gregorcc636682009-02-17 23:15:12 +000055 // lists to easily differentiate between the case above and:
Douglas Gregorc4b4e7b2008-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);
81 return 0;
82 }
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.
Anders Carlsson5aeccdb2009-03-26 00:52:18 +000098 return ParseDeclarationOrFunctionDefinition(&ParamLists, AS);
Douglas Gregoradcac882008-12-01 23:54:00 +000099}
100
101/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000102/// angle brackets. Depth is the depth of this template-parameter-list, which
103/// is the number of template headers directly enclosing this template header.
104/// TemplateParams is the current list of template parameters we're building.
105/// The template parameter we parse will be added to this list. LAngleLoc and
106/// RAngleLoc will receive the positions of the '<' and '>', respectively,
107/// that enclose this template parameter list.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000108bool Parser::ParseTemplateParameters(unsigned Depth,
109 TemplateParameterList &TemplateParams,
110 SourceLocation &LAngleLoc,
111 SourceLocation &RAngleLoc) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000112 // Get the template parameter list.
113 if(!Tok.is(tok::less)) {
114 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
115 return false;
116 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000117 LAngleLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000118
119 // Try to parse the template parameter list.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000120 if (Tok.is(tok::greater))
121 RAngleLoc = ConsumeToken();
122 else if(ParseTemplateParameterList(Depth, TemplateParams)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000123 if(!Tok.is(tok::greater)) {
124 Diag(Tok.getLocation(), diag::err_expected_greater);
125 return false;
126 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000127 RAngleLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000128 }
129 return true;
130}
131
132/// ParseTemplateParameterList - Parse a template parameter list. If
133/// the parsing fails badly (i.e., closing bracket was left out), this
134/// will try to put the token stream in a reasonable position (closing
135/// a statement, etc.) and return false.
136///
137/// template-parameter-list: [C++ temp]
138/// template-parameter
139/// template-parameter-list ',' template-parameter
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000140bool
141Parser::ParseTemplateParameterList(unsigned Depth,
142 TemplateParameterList &TemplateParams) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000143 while(1) {
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000144 if (DeclTy* TmpParam
145 = ParseTemplateParameter(Depth, TemplateParams.size())) {
146 TemplateParams.push_back(TmpParam);
147 } else {
Douglas Gregoradcac882008-12-01 23:54:00 +0000148 // If we failed to parse a template parameter, skip until we find
149 // a comma or closing brace.
150 SkipUntil(tok::comma, tok::greater, true, true);
151 }
152
153 // Did we find a comma or the end of the template parmeter list?
154 if(Tok.is(tok::comma)) {
155 ConsumeToken();
156 } else if(Tok.is(tok::greater)) {
157 // Don't consume this... that's done by template parser.
158 break;
159 } else {
160 // Somebody probably forgot to close the template. Skip ahead and
161 // try to get out of the expression. This error is currently
162 // subsumed by whatever goes on in ParseTemplateParameter.
163 // TODO: This could match >>, and it would be nice to avoid those
164 // silly errors with template <vec<T>>.
165 // Diag(Tok.getLocation(), diag::err_expected_comma_greater);
166 SkipUntil(tok::greater, true, true);
167 return false;
168 }
169 }
170 return true;
171}
172
173/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
174///
175/// template-parameter: [C++ temp.param]
176/// type-parameter
177/// parameter-declaration
178///
179/// type-parameter: (see below)
180/// 'class' identifier[opt]
181/// 'class' identifier[opt] '=' type-id
182/// 'typename' identifier[opt]
183/// 'typename' identifier[opt] '=' type-id
184/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
185/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000186Parser::DeclTy *
187Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Chris Lattner532e19b2009-01-04 23:51:17 +0000188 if(Tok.is(tok::kw_class) ||
189 (Tok.is(tok::kw_typename) &&
190 // FIXME: Next token has not been annotated!
Chris Lattnerb31757b2009-01-06 05:06:21 +0000191 NextToken().isNot(tok::annot_typename))) {
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000192 return ParseTypeParameter(Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000193 }
Chris Lattner532e19b2009-01-04 23:51:17 +0000194
195 if(Tok.is(tok::kw_template))
196 return ParseTemplateTemplateParameter(Depth, Position);
197
198 // If it's none of the above, then it must be a parameter declaration.
199 // NOTE: This will pick up errors in the closure of the template parameter
200 // list (e.g., template < ; Check here to implement >> style closures.
201 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000202}
203
204/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
205/// Other kinds of template parameters are parsed in
206/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
207///
208/// type-parameter: [C++ temp.param]
209/// 'class' identifier[opt]
210/// 'class' identifier[opt] '=' type-id
211/// 'typename' identifier[opt]
212/// 'typename' identifier[opt] '=' type-id
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000213Parser::DeclTy *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000214 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
215 "A type-parameter starts with 'class' or 'typename'");
216
217 // Consume the 'class' or 'typename' keyword.
218 bool TypenameKeyword = Tok.is(tok::kw_typename);
219 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000220
221 // Grab the template parameter name (if given)
Douglas Gregor26236e82008-12-02 00:41:28 +0000222 SourceLocation NameLoc;
223 IdentifierInfo* ParamName = 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000224 if(Tok.is(tok::identifier)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000225 ParamName = Tok.getIdentifierInfo();
226 NameLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000227 } else if(Tok.is(tok::equal) || Tok.is(tok::comma) ||
228 Tok.is(tok::greater)) {
229 // Unnamed template parameter. Don't have to do anything here, just
230 // don't consume this token.
231 } else {
232 Diag(Tok.getLocation(), diag::err_expected_ident);
233 return 0;
234 }
235
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000236 DeclTy *TypeParam = Actions.ActOnTypeParameter(CurScope, TypenameKeyword,
237 KeyLoc, ParamName, NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000238 Depth, Position);
Douglas Gregor26236e82008-12-02 00:41:28 +0000239
Douglas Gregoradcac882008-12-01 23:54:00 +0000240 // Grab a default type id (if given).
Douglas Gregoradcac882008-12-01 23:54:00 +0000241 if(Tok.is(tok::equal)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000242 SourceLocation EqualLoc = ConsumeToken();
Douglas Gregord684b002009-02-10 19:49:53 +0000243 SourceLocation DefaultLoc = Tok.getLocation();
Douglas Gregor809070a2009-02-18 17:45:20 +0000244 TypeResult DefaultType = ParseTypeName();
245 if (!DefaultType.isInvalid())
Douglas Gregord684b002009-02-10 19:49:53 +0000246 Actions.ActOnTypeParameterDefault(TypeParam, EqualLoc, DefaultLoc,
Douglas Gregor809070a2009-02-18 17:45:20 +0000247 DefaultType.get());
Douglas Gregoradcac882008-12-01 23:54:00 +0000248 }
249
Douglas Gregor26236e82008-12-02 00:41:28 +0000250 return TypeParam;
Douglas Gregoradcac882008-12-01 23:54:00 +0000251}
252
253/// ParseTemplateTemplateParameter - Handle the parsing of template
254/// template parameters.
255///
256/// type-parameter: [C++ temp.param]
257/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
258/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000259Parser::DeclTy *
260Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000261 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
262
263 // Handle the template <...> part.
264 SourceLocation TemplateLoc = ConsumeToken();
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000265 TemplateParameterList TemplateParams;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000266 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor68c69932009-02-10 19:52:54 +0000267 {
268 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
269 if(!ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
270 RAngleLoc)) {
271 return 0;
272 }
Douglas Gregoradcac882008-12-01 23:54:00 +0000273 }
274
275 // Generate a meaningful error if the user forgot to put class before the
276 // identifier, comma, or greater.
277 if(!Tok.is(tok::kw_class)) {
278 Diag(Tok.getLocation(), diag::err_expected_class_before)
279 << PP.getSpelling(Tok);
280 return 0;
281 }
282 SourceLocation ClassLoc = ConsumeToken();
283
284 // Get the identifier, if given.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000285 SourceLocation NameLoc;
286 IdentifierInfo* ParamName = 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000287 if(Tok.is(tok::identifier)) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000288 ParamName = Tok.getIdentifierInfo();
289 NameLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000290 } else if(Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
291 // Unnamed template parameter. Don't have to do anything here, just
292 // don't consume this token.
293 } else {
294 Diag(Tok.getLocation(), diag::err_expected_ident);
295 return 0;
296 }
297
Douglas Gregorddc29e12009-02-06 22:42:48 +0000298 TemplateParamsTy *ParamList =
299 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
300 TemplateLoc, LAngleLoc,
301 &TemplateParams[0],
302 TemplateParams.size(),
303 RAngleLoc);
304
Douglas Gregord684b002009-02-10 19:49:53 +0000305 Parser::DeclTy * Param
306 = Actions.ActOnTemplateTemplateParameter(CurScope, TemplateLoc,
307 ParamList, ParamName,
308 NameLoc, Depth, Position);
309
310 // Get the a default value, if given.
311 if (Tok.is(tok::equal)) {
312 SourceLocation EqualLoc = ConsumeToken();
313 OwningExprResult DefaultExpr = ParseCXXIdExpression();
314 if (DefaultExpr.isInvalid())
315 return Param;
316 else if (Param)
317 Actions.ActOnTemplateTemplateParameterDefault(Param, EqualLoc,
318 move(DefaultExpr));
319 }
320
321 return Param;
Douglas Gregoradcac882008-12-01 23:54:00 +0000322}
323
324/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
325/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000326///
Douglas Gregoradcac882008-12-01 23:54:00 +0000327/// template-parameter:
328/// ...
329/// parameter-declaration
330///
331/// NOTE: It would be ideal to simply call out to ParseParameterDeclaration(),
332/// but that didn't work out to well. Instead, this tries to recrate the basic
333/// parsing of parameter declarations, but tries to constrain it for template
334/// parameters.
Douglas Gregor26236e82008-12-02 00:41:28 +0000335/// FIXME: We need to make a ParseParameterDeclaration that works for
336/// non-type template parameters and normal function parameters.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000337Parser::DeclTy *
338Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000339 SourceLocation StartLoc = Tok.getLocation();
Douglas Gregoradcac882008-12-01 23:54:00 +0000340
341 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor26236e82008-12-02 00:41:28 +0000342 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregoradcac882008-12-01 23:54:00 +0000343 // declarators (parts of declarators?) are accepted for parameters.
Douglas Gregor26236e82008-12-02 00:41:28 +0000344 DeclSpec DS;
345 ParseDeclarationSpecifiers(DS);
Douglas Gregoradcac882008-12-01 23:54:00 +0000346
347 // Parse this as a typename.
Douglas Gregor26236e82008-12-02 00:41:28 +0000348 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
349 ParseDeclarator(ParamDecl);
Chris Lattner7452c6f2009-01-05 01:24:05 +0000350 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified && !DS.getTypeRep()) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000351 // This probably shouldn't happen - and it's more of a Sema thing, but
352 // basically we didn't parse the type name because we couldn't associate
353 // it with an AST node. we should just skip to the comma or greater.
354 // TODO: This is currently a placeholder for some kind of Sema Error.
355 Diag(Tok.getLocation(), diag::err_parse_error);
356 SkipUntil(tok::comma, tok::greater, true, true);
357 return 0;
358 }
359
Douglas Gregor26236e82008-12-02 00:41:28 +0000360 // Create the parameter.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000361 DeclTy *Param = Actions.ActOnNonTypeTemplateParameter(CurScope, ParamDecl,
362 Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000363
Douglas Gregord684b002009-02-10 19:49:53 +0000364 // If there is a default value, parse it.
Chris Lattner7452c6f2009-01-05 01:24:05 +0000365 if (Tok.is(tok::equal)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000366 SourceLocation EqualLoc = ConsumeToken();
367
368 // C++ [temp.param]p15:
369 // When parsing a default template-argument for a non-type
370 // template-parameter, the first non-nested > is taken as the
371 // end of the template-parameter-list rather than a greater-than
372 // operator.
373 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
374
375 OwningExprResult DefaultArg = ParseAssignmentExpression();
376 if (DefaultArg.isInvalid())
377 SkipUntil(tok::comma, tok::greater, true, true);
378 else if (Param)
379 Actions.ActOnNonTypeTemplateParameterDefault(Param, EqualLoc,
380 move(DefaultArg));
Douglas Gregoradcac882008-12-01 23:54:00 +0000381 }
382
Douglas Gregor26236e82008-12-02 00:41:28 +0000383 return Param;
Douglas Gregoradcac882008-12-01 23:54:00 +0000384}
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000385
Douglas Gregorcc636682009-02-17 23:15:12 +0000386/// \brief Parses a template-id that after the template name has
387/// already been parsed.
388///
389/// This routine takes care of parsing the enclosed template argument
390/// list ('<' template-parameter-list [opt] '>') and placing the
391/// results into a form that can be transferred to semantic analysis.
392///
393/// \param Template the template declaration produced by isTemplateName
394///
395/// \param TemplateNameLoc the source location of the template name
396///
397/// \param SS if non-NULL, the nested-name-specifier preceding the
398/// template name.
399///
400/// \param ConsumeLastToken if true, then we will consume the last
401/// token that forms the template-id. Otherwise, we will leave the
402/// last token in the stream (e.g., so that it can be replaced with an
403/// annotation token).
404bool
405Parser::ParseTemplateIdAfterTemplateName(DeclTy *Template,
406 SourceLocation TemplateNameLoc,
407 const CXXScopeSpec *SS,
408 bool ConsumeLastToken,
409 SourceLocation &LAngleLoc,
410 TemplateArgList &TemplateArgs,
411 TemplateArgIsTypeList &TemplateArgIsType,
412 TemplateArgLocationList &TemplateArgLocations,
413 SourceLocation &RAngleLoc) {
414 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
415
416 // Consume the '<'.
417 LAngleLoc = ConsumeToken();
418
419 // Parse the optional template-argument-list.
420 bool Invalid = false;
421 {
422 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
423 if (Tok.isNot(tok::greater))
424 Invalid = ParseTemplateArgumentList(TemplateArgs, TemplateArgIsType,
425 TemplateArgLocations);
426
427 if (Invalid) {
428 // Try to find the closing '>'.
429 SkipUntil(tok::greater, true, !ConsumeLastToken);
430
431 return true;
432 }
433 }
434
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000435 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
Douglas Gregorcc636682009-02-17 23:15:12 +0000436 return true;
437
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000438 // Determine the location of the '>' or '>>'. Only consume this
439 // token if the caller asked us to.
Douglas Gregorcc636682009-02-17 23:15:12 +0000440 RAngleLoc = Tok.getLocation();
441
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000442 if (Tok.is(tok::greatergreater)) {
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000443 if (!getLang().CPlusPlus0x) {
444 const char *ReplaceStr = "> >";
445 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
446 ReplaceStr = "> > ";
447
448 Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000449 << CodeModificationHint::CreateReplacement(
450 SourceRange(Tok.getLocation()), ReplaceStr);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000451 }
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000452
453 Tok.setKind(tok::greater);
454 if (!ConsumeLastToken) {
455 // Since we're not supposed to consume the '>>' token, we need
456 // to insert a second '>' token after the first.
457 PP.EnterToken(Tok);
458 }
459 } else if (ConsumeLastToken)
Douglas Gregorcc636682009-02-17 23:15:12 +0000460 ConsumeToken();
461
462 return false;
463}
464
Douglas Gregor39a8de12009-02-25 19:37:18 +0000465/// \brief Replace the tokens that form a simple-template-id with an
466/// annotation token containing the complete template-id.
467///
468/// The first token in the stream must be the name of a template that
469/// is followed by a '<'. This routine will parse the complete
470/// simple-template-id and replace the tokens with a single annotation
471/// token with one of two different kinds: if the template-id names a
472/// type (and \p AllowTypeAnnotation is true), the annotation token is
473/// a type annotation that includes the optional nested-name-specifier
474/// (\p SS). Otherwise, the annotation token is a template-id
475/// annotation that does not include the optional
476/// nested-name-specifier.
477///
478/// \param Template the declaration of the template named by the first
479/// token (an identifier), as returned from \c Action::isTemplateName().
480///
481/// \param TemplateNameKind the kind of template that \p Template
482/// refers to, as returned from \c Action::isTemplateName().
483///
484/// \param SS if non-NULL, the nested-name-specifier that precedes
485/// this template name.
486///
487/// \param TemplateKWLoc if valid, specifies that this template-id
488/// annotation was preceded by the 'template' keyword and gives the
489/// location of that keyword. If invalid (the default), then this
490/// template-id was not preceded by a 'template' keyword.
491///
492/// \param AllowTypeAnnotation if true (the default), then a
493/// simple-template-id that refers to a class template, template
494/// template parameter, or other template that produces a type will be
495/// replaced with a type annotation token. Otherwise, the
496/// simple-template-id is always replaced with a template-id
497/// annotation token.
Douglas Gregor55f6b142009-02-09 18:46:07 +0000498void Parser::AnnotateTemplateIdToken(DeclTy *Template, TemplateNameKind TNK,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000499 const CXXScopeSpec *SS,
500 SourceLocation TemplateKWLoc,
501 bool AllowTypeAnnotation) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000502 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
503 assert(Template && Tok.is(tok::identifier) && NextToken().is(tok::less) &&
504 "Parser isn't at the beginning of a template-id");
505
506 // Consume the template-name.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000507 IdentifierInfo *Name = Tok.getIdentifierInfo();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000508 SourceLocation TemplateNameLoc = ConsumeToken();
509
Douglas Gregorcc636682009-02-17 23:15:12 +0000510 // Parse the enclosed template argument list.
511 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000512 TemplateArgList TemplateArgs;
513 TemplateArgIsTypeList TemplateArgIsType;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000514 TemplateArgLocationList TemplateArgLocations;
Douglas Gregorcc636682009-02-17 23:15:12 +0000515 bool Invalid = ParseTemplateIdAfterTemplateName(Template, TemplateNameLoc,
516 SS, false, LAngleLoc,
517 TemplateArgs,
518 TemplateArgIsType,
519 TemplateArgLocations,
520 RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000521
Douglas Gregorcc636682009-02-17 23:15:12 +0000522 ASTTemplateArgsPtr TemplateArgsPtr(Actions, &TemplateArgs[0],
523 &TemplateArgIsType[0],
524 TemplateArgs.size());
Douglas Gregorf02da892009-02-09 21:04:56 +0000525
Douglas Gregorcc636682009-02-17 23:15:12 +0000526 if (Invalid) // FIXME: How to recover from a broken template-id?
527 return;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000528
Douglas Gregor55f6b142009-02-09 18:46:07 +0000529 // Build the annotation token.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000530 if (TNK == TNK_Class_template && AllowTypeAnnotation) {
Douglas Gregorcc636682009-02-17 23:15:12 +0000531 Action::TypeResult Type
532 = Actions.ActOnClassTemplateId(Template, TemplateNameLoc,
533 LAngleLoc, TemplateArgsPtr,
534 &TemplateArgLocations[0],
535 RAngleLoc, SS);
536 if (Type.isInvalid()) // FIXME: better recovery?
537 return;
538
539 Tok.setKind(tok::annot_typename);
540 Tok.setAnnotationValue(Type.get());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000541 if (SS && SS->isNotEmpty())
542 Tok.setLocation(SS->getBeginLoc());
543 else if (TemplateKWLoc.isValid())
544 Tok.setLocation(TemplateKWLoc);
545 else
546 Tok.setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +0000547 } else {
Douglas Gregor55f6b142009-02-09 18:46:07 +0000548 // This is a function template. We'll be building a template-id
549 // annotation token.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000550 Tok.setKind(tok::annot_template_id);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000551 TemplateIdAnnotation *TemplateId
Douglas Gregor39a8de12009-02-25 19:37:18 +0000552 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
Douglas Gregor55f6b142009-02-09 18:46:07 +0000553 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000554 TemplateId->Name = Name;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000555 TemplateId->Template = Template;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000556 TemplateId->Kind = TNK;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000557 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000558 TemplateId->RAngleLoc = RAngleLoc;
559 void **Args = TemplateId->getTemplateArgs();
560 bool *ArgIsType = TemplateId->getTemplateArgIsType();
561 SourceLocation *ArgLocs = TemplateId->getTemplateArgLocations();
562 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg) {
Douglas Gregor55f6b142009-02-09 18:46:07 +0000563 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor39a8de12009-02-25 19:37:18 +0000564 ArgIsType[Arg] = TemplateArgIsType[Arg];
565 ArgLocs[Arg] = TemplateArgLocations[Arg];
566 }
Douglas Gregor55f6b142009-02-09 18:46:07 +0000567 Tok.setAnnotationValue(TemplateId);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000568 if (TemplateKWLoc.isValid())
569 Tok.setLocation(TemplateKWLoc);
570 else
571 Tok.setLocation(TemplateNameLoc);
572
573 TemplateArgsPtr.release();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000574 }
575
576 // Common fields for the annotation token
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000577 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000578
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000579 // In case the tokens were cached, have Preprocessor replace them with the
580 // annotation token.
581 PP.AnnotateCachedTokens(Tok);
582}
583
Douglas Gregor39a8de12009-02-25 19:37:18 +0000584/// \brief Replaces a template-id annotation token with a type
585/// annotation token.
586///
587/// \returns true if there was an error, false otherwise.
588bool Parser::AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS) {
589 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
590
591 TemplateIdAnnotation *TemplateId
592 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
593 assert(TemplateId->Kind == TNK_Class_template &&
594 "Only works for class templates");
595
596 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
597 TemplateId->getTemplateArgs(),
598 TemplateId->getTemplateArgIsType(),
599 TemplateId->NumArgs);
600
601 Action::TypeResult Type
602 = Actions.ActOnClassTemplateId(TemplateId->Template,
603 TemplateId->TemplateNameLoc,
604 TemplateId->LAngleLoc,
605 TemplateArgsPtr,
606 TemplateId->getTemplateArgLocations(),
607 TemplateId->RAngleLoc, SS);
608 if (Type.isInvalid()) {
609 // FIXME: better recovery?
610 ConsumeToken();
611 TemplateId->Destroy();
612 return true;
613 }
614
615 // Create the new "type" annotation token.
616 Tok.setKind(tok::annot_typename);
617 Tok.setAnnotationValue(Type.get());
618 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();
627
628 return false;
629}
630
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000631/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
632///
633/// template-argument: [C++ 14.2]
634/// assignment-expression
635/// type-id
636/// id-expression
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000637void *Parser::ParseTemplateArgument(bool &ArgIsType) {
Douglas Gregor55f6b142009-02-09 18:46:07 +0000638 // C++ [temp.arg]p2:
639 // In a template-argument, an ambiguity between a type-id and an
640 // expression is resolved to a type-id, regardless of the form of
641 // the corresponding template-parameter.
642 //
643 // Therefore, we initially try to parse a type-id.
Douglas Gregor8b642592009-02-10 00:53:15 +0000644 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000645 ArgIsType = true;
Douglas Gregor809070a2009-02-18 17:45:20 +0000646 TypeResult TypeArg = ParseTypeName();
647 if (TypeArg.isInvalid())
648 return 0;
649 return TypeArg.get();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000650 }
651
Douglas Gregorc15cb382009-02-09 23:23:08 +0000652 OwningExprResult ExprArg = ParseAssignmentExpression();
653 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000654 return 0;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000655
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000656 ArgIsType = false;
657 return ExprArg.release();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000658}
659
660/// ParseTemplateArgumentList - Parse a C++ template-argument-list
661/// (C++ [temp.names]). Returns true if there was an error.
662///
663/// template-argument-list: [C++ 14.2]
664/// template-argument
665/// template-argument-list ',' template-argument
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000666bool
667Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
Douglas Gregorc15cb382009-02-09 23:23:08 +0000668 TemplateArgIsTypeList &TemplateArgIsType,
669 TemplateArgLocationList &TemplateArgLocations) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000670 while (true) {
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000671 bool IsType = false;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000672 SourceLocation Loc = Tok.getLocation();
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000673 void *Arg = ParseTemplateArgument(IsType);
674 if (Arg) {
675 TemplateArgs.push_back(Arg);
676 TemplateArgIsType.push_back(IsType);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000677 TemplateArgLocations.push_back(Loc);
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000678 } else {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000679 SkipUntil(tok::comma, tok::greater, true, true);
680 return true;
681 }
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000682
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000683 // If the next token is a comma, consume it and keep reading
684 // arguments.
685 if (Tok.isNot(tok::comma)) break;
686
687 // Consume the comma.
688 ConsumeToken();
689 }
690
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000691 return Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000692}
693