blob: 29b8a147db4b7543c9d4edf40126a21c222e66e8 [file] [log] [blame]
Douglas Gregoradcac882008-12-01 23:54:00 +00001//===--- ParseTemplate.cpp - Template Parsing -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements parsing of C++ templates.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Parse/Parser.h"
Chris Lattner500d3292009-01-29 05:15:15 +000015#include "clang/Parse/ParseDiagnostic.h"
Douglas Gregoradcac882008-12-01 23:54:00 +000016#include "clang/Parse/DeclSpec.h"
17#include "clang/Parse/Scope.h"
Douglas Gregor55f6b142009-02-09 18:46:07 +000018#include "AstGuard.h"
Douglas Gregoradcac882008-12-01 23:54:00 +000019using namespace clang;
20
Douglas Gregorcc636682009-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 Gregoradcac882008-12-01 23:54:00 +000030///
31/// template-declaration: [C++ temp]
32/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
Douglas Gregorcc636682009-02-17 23:15:12 +000033///
34/// explicit-specialization: [ C++ temp.expl.spec]
35/// 'template' '<' '>' declaration
Chris Lattnerb28317a2009-03-28 19:18:32 +000036Parser::DeclPtrTy
Anders Carlsson5aeccdb2009-03-26 00:52:18 +000037Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
38 AccessSpecifier AS) {
Douglas Gregoradcac882008-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 Gregor26236e82008-12-02 00:41:28 +000042 // Enter template-parameter scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +000043 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Douglas Gregor26236e82008-12-02 00:41:28 +000044
Douglas Gregorc4b4e7b2008-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 Gregorcc636682009-02-17 23:15:12 +000054 // lists to easily differentiate between the case above and:
Douglas Gregorc4b4e7b2008-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 Lattnerb28317a2009-03-28 19:18:32 +000080 return DeclPtrTy();
Douglas Gregorc4b4e7b2008-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.
Anders Carlsson5aeccdb2009-03-26 00:52:18 +000097 return ParseDeclarationOrFunctionDefinition(&ParamLists, AS);
Douglas Gregoradcac882008-12-01 23:54:00 +000098}
99
100/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000101/// angle brackets. Depth is the depth of this template-parameter-list, which
102/// is the number of template headers directly enclosing this template header.
103/// TemplateParams is the current list of template parameters we're building.
104/// The template parameter we parse will be added to this list. LAngleLoc and
105/// RAngleLoc will receive the positions of the '<' and '>', respectively,
106/// that enclose this template parameter list.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000107bool Parser::ParseTemplateParameters(unsigned Depth,
108 TemplateParameterList &TemplateParams,
109 SourceLocation &LAngleLoc,
110 SourceLocation &RAngleLoc) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000111 // Get the template parameter list.
112 if(!Tok.is(tok::less)) {
113 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
114 return false;
115 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000116 LAngleLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000117
118 // Try to parse the template parameter list.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000119 if (Tok.is(tok::greater))
120 RAngleLoc = ConsumeToken();
121 else if(ParseTemplateParameterList(Depth, TemplateParams)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000122 if(!Tok.is(tok::greater)) {
123 Diag(Tok.getLocation(), diag::err_expected_greater);
124 return false;
125 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000126 RAngleLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000127 }
128 return true;
129}
130
131/// ParseTemplateParameterList - Parse a template parameter list. If
132/// the parsing fails badly (i.e., closing bracket was left out), this
133/// will try to put the token stream in a reasonable position (closing
134/// a statement, etc.) and return false.
135///
136/// template-parameter-list: [C++ temp]
137/// template-parameter
138/// template-parameter-list ',' template-parameter
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000139bool
140Parser::ParseTemplateParameterList(unsigned Depth,
141 TemplateParameterList &TemplateParams) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000142 while(1) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000143 if (DeclPtrTy TmpParam
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000144 = ParseTemplateParameter(Depth, TemplateParams.size())) {
145 TemplateParams.push_back(TmpParam);
146 } else {
Douglas Gregoradcac882008-12-01 23:54:00 +0000147 // If we failed to parse a template parameter, skip until we find
148 // a comma or closing brace.
149 SkipUntil(tok::comma, tok::greater, true, true);
150 }
151
152 // Did we find a comma or the end of the template parmeter list?
153 if(Tok.is(tok::comma)) {
154 ConsumeToken();
155 } else if(Tok.is(tok::greater)) {
156 // Don't consume this... that's done by template parser.
157 break;
158 } else {
159 // Somebody probably forgot to close the template. Skip ahead and
160 // try to get out of the expression. This error is currently
161 // subsumed by whatever goes on in ParseTemplateParameter.
162 // TODO: This could match >>, and it would be nice to avoid those
163 // silly errors with template <vec<T>>.
164 // Diag(Tok.getLocation(), diag::err_expected_comma_greater);
165 SkipUntil(tok::greater, true, true);
166 return false;
167 }
168 }
169 return true;
170}
171
172/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
173///
174/// template-parameter: [C++ temp.param]
175/// type-parameter
176/// parameter-declaration
177///
178/// type-parameter: (see below)
179/// 'class' identifier[opt]
180/// 'class' identifier[opt] '=' type-id
181/// 'typename' identifier[opt]
182/// 'typename' identifier[opt] '=' type-id
183/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
184/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
Chris Lattnerb28317a2009-03-28 19:18:32 +0000185Parser::DeclPtrTy
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000186Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Chris Lattner532e19b2009-01-04 23:51:17 +0000187 if(Tok.is(tok::kw_class) ||
188 (Tok.is(tok::kw_typename) &&
189 // FIXME: Next token has not been annotated!
Chris Lattnerb31757b2009-01-06 05:06:21 +0000190 NextToken().isNot(tok::annot_typename))) {
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000191 return ParseTypeParameter(Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000192 }
Chris Lattner532e19b2009-01-04 23:51:17 +0000193
194 if(Tok.is(tok::kw_template))
195 return ParseTemplateTemplateParameter(Depth, Position);
196
197 // If it's none of the above, then it must be a parameter declaration.
198 // NOTE: This will pick up errors in the closure of the template parameter
199 // list (e.g., template < ; Check here to implement >> style closures.
200 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000201}
202
203/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
204/// Other kinds of template parameters are parsed in
205/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
206///
207/// type-parameter: [C++ temp.param]
208/// 'class' identifier[opt]
209/// 'class' identifier[opt] '=' type-id
210/// 'typename' identifier[opt]
211/// 'typename' identifier[opt] '=' type-id
Chris Lattnerb28317a2009-03-28 19:18:32 +0000212Parser::DeclPtrTy Parser::ParseTypeParameter(unsigned Depth, unsigned Position){
Douglas Gregor26236e82008-12-02 00:41:28 +0000213 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
214 "A type-parameter starts with 'class' or 'typename'");
215
216 // Consume the 'class' or 'typename' keyword.
217 bool TypenameKeyword = Tok.is(tok::kw_typename);
218 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000219
220 // Grab the template parameter name (if given)
Douglas Gregor26236e82008-12-02 00:41:28 +0000221 SourceLocation NameLoc;
222 IdentifierInfo* ParamName = 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000223 if(Tok.is(tok::identifier)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000224 ParamName = Tok.getIdentifierInfo();
225 NameLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000226 } else if(Tok.is(tok::equal) || Tok.is(tok::comma) ||
227 Tok.is(tok::greater)) {
228 // Unnamed template parameter. Don't have to do anything here, just
229 // don't consume this token.
230 } else {
231 Diag(Tok.getLocation(), diag::err_expected_ident);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000232 return DeclPtrTy();
Douglas Gregoradcac882008-12-01 23:54:00 +0000233 }
234
Chris Lattnerb28317a2009-03-28 19:18:32 +0000235 DeclPtrTy TypeParam = Actions.ActOnTypeParameter(CurScope, TypenameKeyword,
236 KeyLoc, ParamName, NameLoc,
237 Depth, Position);
Douglas Gregor26236e82008-12-02 00:41:28 +0000238
Douglas Gregoradcac882008-12-01 23:54:00 +0000239 // Grab a default type id (if given).
Douglas Gregoradcac882008-12-01 23:54:00 +0000240 if(Tok.is(tok::equal)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000241 SourceLocation EqualLoc = ConsumeToken();
Douglas Gregord684b002009-02-10 19:49:53 +0000242 SourceLocation DefaultLoc = Tok.getLocation();
Douglas Gregor809070a2009-02-18 17:45:20 +0000243 TypeResult DefaultType = ParseTypeName();
244 if (!DefaultType.isInvalid())
Douglas Gregord684b002009-02-10 19:49:53 +0000245 Actions.ActOnTypeParameterDefault(TypeParam, EqualLoc, DefaultLoc,
Douglas Gregor809070a2009-02-18 17:45:20 +0000246 DefaultType.get());
Douglas Gregoradcac882008-12-01 23:54:00 +0000247 }
248
Douglas Gregor26236e82008-12-02 00:41:28 +0000249 return TypeParam;
Douglas Gregoradcac882008-12-01 23:54:00 +0000250}
251
252/// ParseTemplateTemplateParameter - Handle the parsing of template
253/// template parameters.
254///
255/// type-parameter: [C++ temp.param]
256/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
257/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
Chris Lattnerb28317a2009-03-28 19:18:32 +0000258Parser::DeclPtrTy
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000259Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000260 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
261
262 // Handle the template <...> part.
263 SourceLocation TemplateLoc = ConsumeToken();
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000264 TemplateParameterList TemplateParams;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000265 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor68c69932009-02-10 19:52:54 +0000266 {
267 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
268 if(!ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
269 RAngleLoc)) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000270 return DeclPtrTy();
Douglas Gregor68c69932009-02-10 19:52:54 +0000271 }
Douglas Gregoradcac882008-12-01 23:54:00 +0000272 }
273
274 // Generate a meaningful error if the user forgot to put class before the
275 // identifier, comma, or greater.
276 if(!Tok.is(tok::kw_class)) {
277 Diag(Tok.getLocation(), diag::err_expected_class_before)
278 << PP.getSpelling(Tok);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000279 return DeclPtrTy();
Douglas Gregoradcac882008-12-01 23:54:00 +0000280 }
281 SourceLocation ClassLoc = ConsumeToken();
282
283 // Get the identifier, if given.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000284 SourceLocation NameLoc;
285 IdentifierInfo* ParamName = 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000286 if(Tok.is(tok::identifier)) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000287 ParamName = Tok.getIdentifierInfo();
288 NameLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000289 } else if(Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
290 // Unnamed template parameter. Don't have to do anything here, just
291 // don't consume this token.
292 } else {
293 Diag(Tok.getLocation(), diag::err_expected_ident);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000294 return DeclPtrTy();
Douglas Gregoradcac882008-12-01 23:54:00 +0000295 }
296
Douglas Gregorddc29e12009-02-06 22:42:48 +0000297 TemplateParamsTy *ParamList =
298 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
299 TemplateLoc, LAngleLoc,
300 &TemplateParams[0],
301 TemplateParams.size(),
302 RAngleLoc);
303
Chris Lattnerb28317a2009-03-28 19:18:32 +0000304 Parser::DeclPtrTy Param
Douglas Gregord684b002009-02-10 19:49:53 +0000305 = Actions.ActOnTemplateTemplateParameter(CurScope, TemplateLoc,
306 ParamList, ParamName,
307 NameLoc, Depth, Position);
308
309 // Get the a default value, if given.
310 if (Tok.is(tok::equal)) {
311 SourceLocation EqualLoc = ConsumeToken();
312 OwningExprResult DefaultExpr = ParseCXXIdExpression();
313 if (DefaultExpr.isInvalid())
314 return Param;
315 else if (Param)
316 Actions.ActOnTemplateTemplateParameterDefault(Param, EqualLoc,
317 move(DefaultExpr));
318 }
319
320 return Param;
Douglas Gregoradcac882008-12-01 23:54:00 +0000321}
322
323/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
324/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000325///
Douglas Gregoradcac882008-12-01 23:54:00 +0000326/// template-parameter:
327/// ...
328/// parameter-declaration
329///
330/// NOTE: It would be ideal to simply call out to ParseParameterDeclaration(),
331/// but that didn't work out to well. Instead, this tries to recrate the basic
332/// parsing of parameter declarations, but tries to constrain it for template
333/// parameters.
Douglas Gregor26236e82008-12-02 00:41:28 +0000334/// FIXME: We need to make a ParseParameterDeclaration that works for
335/// non-type template parameters and normal function parameters.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000336Parser::DeclPtrTy
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000337Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000338 SourceLocation StartLoc = Tok.getLocation();
Douglas Gregoradcac882008-12-01 23:54:00 +0000339
340 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor26236e82008-12-02 00:41:28 +0000341 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregoradcac882008-12-01 23:54:00 +0000342 // declarators (parts of declarators?) are accepted for parameters.
Douglas Gregor26236e82008-12-02 00:41:28 +0000343 DeclSpec DS;
344 ParseDeclarationSpecifiers(DS);
Douglas Gregoradcac882008-12-01 23:54:00 +0000345
346 // Parse this as a typename.
Douglas Gregor26236e82008-12-02 00:41:28 +0000347 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
348 ParseDeclarator(ParamDecl);
Chris Lattner7452c6f2009-01-05 01:24:05 +0000349 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified && !DS.getTypeRep()) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000350 // This probably shouldn't happen - and it's more of a Sema thing, but
351 // basically we didn't parse the type name because we couldn't associate
352 // it with an AST node. we should just skip to the comma or greater.
353 // TODO: This is currently a placeholder for some kind of Sema Error.
354 Diag(Tok.getLocation(), diag::err_parse_error);
355 SkipUntil(tok::comma, tok::greater, true, true);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000356 return DeclPtrTy();
Douglas Gregoradcac882008-12-01 23:54:00 +0000357 }
358
Douglas Gregor26236e82008-12-02 00:41:28 +0000359 // Create the parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000360 DeclPtrTy Param = Actions.ActOnNonTypeTemplateParameter(CurScope, ParamDecl,
361 Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000362
Douglas Gregord684b002009-02-10 19:49:53 +0000363 // If there is a default value, parse it.
Chris Lattner7452c6f2009-01-05 01:24:05 +0000364 if (Tok.is(tok::equal)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000365 SourceLocation EqualLoc = ConsumeToken();
366
367 // C++ [temp.param]p15:
368 // When parsing a default template-argument for a non-type
369 // template-parameter, the first non-nested > is taken as the
370 // end of the template-parameter-list rather than a greater-than
371 // operator.
372 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
373
374 OwningExprResult DefaultArg = ParseAssignmentExpression();
375 if (DefaultArg.isInvalid())
376 SkipUntil(tok::comma, tok::greater, true, true);
377 else if (Param)
378 Actions.ActOnNonTypeTemplateParameterDefault(Param, EqualLoc,
379 move(DefaultArg));
Douglas Gregoradcac882008-12-01 23:54:00 +0000380 }
381
Douglas Gregor26236e82008-12-02 00:41:28 +0000382 return Param;
Douglas Gregoradcac882008-12-01 23:54:00 +0000383}
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000384
Douglas Gregorcc636682009-02-17 23:15:12 +0000385/// \brief Parses a template-id that after the template name has
386/// already been parsed.
387///
388/// This routine takes care of parsing the enclosed template argument
389/// list ('<' template-parameter-list [opt] '>') and placing the
390/// results into a form that can be transferred to semantic analysis.
391///
392/// \param Template the template declaration produced by isTemplateName
393///
394/// \param TemplateNameLoc the source location of the template name
395///
396/// \param SS if non-NULL, the nested-name-specifier preceding the
397/// template name.
398///
399/// \param ConsumeLastToken if true, then we will consume the last
400/// token that forms the template-id. Otherwise, we will leave the
401/// last token in the stream (e.g., so that it can be replaced with an
402/// annotation token).
403bool
Chris Lattnerb28317a2009-03-28 19:18:32 +0000404Parser::ParseTemplateIdAfterTemplateName(DeclPtrTy Template,
Douglas Gregorcc636682009-02-17 23:15:12 +0000405 SourceLocation TemplateNameLoc,
406 const CXXScopeSpec *SS,
407 bool ConsumeLastToken,
408 SourceLocation &LAngleLoc,
409 TemplateArgList &TemplateArgs,
410 TemplateArgIsTypeList &TemplateArgIsType,
411 TemplateArgLocationList &TemplateArgLocations,
412 SourceLocation &RAngleLoc) {
413 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
414
415 // Consume the '<'.
416 LAngleLoc = ConsumeToken();
417
418 // Parse the optional template-argument-list.
419 bool Invalid = false;
420 {
421 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
422 if (Tok.isNot(tok::greater))
423 Invalid = ParseTemplateArgumentList(TemplateArgs, TemplateArgIsType,
424 TemplateArgLocations);
425
426 if (Invalid) {
427 // Try to find the closing '>'.
428 SkipUntil(tok::greater, true, !ConsumeLastToken);
429
430 return true;
431 }
432 }
433
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000434 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
Douglas Gregorcc636682009-02-17 23:15:12 +0000435 return true;
436
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000437 // Determine the location of the '>' or '>>'. Only consume this
438 // token if the caller asked us to.
Douglas Gregorcc636682009-02-17 23:15:12 +0000439 RAngleLoc = Tok.getLocation();
440
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000441 if (Tok.is(tok::greatergreater)) {
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000442 if (!getLang().CPlusPlus0x) {
443 const char *ReplaceStr = "> >";
444 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
445 ReplaceStr = "> > ";
446
447 Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000448 << CodeModificationHint::CreateReplacement(
449 SourceRange(Tok.getLocation()), ReplaceStr);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000450 }
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000451
452 Tok.setKind(tok::greater);
453 if (!ConsumeLastToken) {
454 // Since we're not supposed to consume the '>>' token, we need
455 // to insert a second '>' token after the first.
456 PP.EnterToken(Tok);
457 }
458 } else if (ConsumeLastToken)
Douglas Gregorcc636682009-02-17 23:15:12 +0000459 ConsumeToken();
460
461 return false;
462}
463
Douglas Gregor39a8de12009-02-25 19:37:18 +0000464/// \brief Replace the tokens that form a simple-template-id with an
465/// annotation token containing the complete template-id.
466///
467/// The first token in the stream must be the name of a template that
468/// is followed by a '<'. This routine will parse the complete
469/// simple-template-id and replace the tokens with a single annotation
470/// token with one of two different kinds: if the template-id names a
471/// type (and \p AllowTypeAnnotation is true), the annotation token is
472/// a type annotation that includes the optional nested-name-specifier
473/// (\p SS). Otherwise, the annotation token is a template-id
474/// annotation that does not include the optional
475/// nested-name-specifier.
476///
477/// \param Template the declaration of the template named by the first
478/// token (an identifier), as returned from \c Action::isTemplateName().
479///
480/// \param TemplateNameKind the kind of template that \p Template
481/// refers to, as returned from \c Action::isTemplateName().
482///
483/// \param SS if non-NULL, the nested-name-specifier that precedes
484/// this template name.
485///
486/// \param TemplateKWLoc if valid, specifies that this template-id
487/// annotation was preceded by the 'template' keyword and gives the
488/// location of that keyword. If invalid (the default), then this
489/// template-id was not preceded by a 'template' keyword.
490///
491/// \param AllowTypeAnnotation if true (the default), then a
492/// simple-template-id that refers to a class template, template
493/// template parameter, or other template that produces a type will be
494/// replaced with a type annotation token. Otherwise, the
495/// simple-template-id is always replaced with a template-id
496/// annotation token.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000497void Parser::AnnotateTemplateIdToken(DeclPtrTy Template, TemplateNameKind TNK,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000498 const CXXScopeSpec *SS,
499 SourceLocation TemplateKWLoc,
500 bool AllowTypeAnnotation) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000501 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
502 assert(Template && Tok.is(tok::identifier) && NextToken().is(tok::less) &&
503 "Parser isn't at the beginning of a template-id");
504
505 // Consume the template-name.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000506 IdentifierInfo *Name = Tok.getIdentifierInfo();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000507 SourceLocation TemplateNameLoc = ConsumeToken();
508
Douglas Gregorcc636682009-02-17 23:15:12 +0000509 // Parse the enclosed template argument list.
510 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000511 TemplateArgList TemplateArgs;
512 TemplateArgIsTypeList TemplateArgIsType;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000513 TemplateArgLocationList TemplateArgLocations;
Douglas Gregorcc636682009-02-17 23:15:12 +0000514 bool Invalid = ParseTemplateIdAfterTemplateName(Template, TemplateNameLoc,
515 SS, false, LAngleLoc,
516 TemplateArgs,
517 TemplateArgIsType,
518 TemplateArgLocations,
519 RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000520
Douglas Gregorcc636682009-02-17 23:15:12 +0000521 ASTTemplateArgsPtr TemplateArgsPtr(Actions, &TemplateArgs[0],
522 &TemplateArgIsType[0],
523 TemplateArgs.size());
Douglas Gregorf02da892009-02-09 21:04:56 +0000524
Douglas Gregorcc636682009-02-17 23:15:12 +0000525 if (Invalid) // FIXME: How to recover from a broken template-id?
526 return;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000527
Douglas Gregor55f6b142009-02-09 18:46:07 +0000528 // Build the annotation token.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000529 if (TNK == TNK_Class_template && AllowTypeAnnotation) {
Douglas Gregorcc636682009-02-17 23:15:12 +0000530 Action::TypeResult Type
531 = Actions.ActOnClassTemplateId(Template, TemplateNameLoc,
532 LAngleLoc, TemplateArgsPtr,
533 &TemplateArgLocations[0],
534 RAngleLoc, SS);
535 if (Type.isInvalid()) // FIXME: better recovery?
536 return;
537
538 Tok.setKind(tok::annot_typename);
539 Tok.setAnnotationValue(Type.get());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000540 if (SS && SS->isNotEmpty())
541 Tok.setLocation(SS->getBeginLoc());
542 else if (TemplateKWLoc.isValid())
543 Tok.setLocation(TemplateKWLoc);
544 else
545 Tok.setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +0000546 } else {
Douglas Gregor55f6b142009-02-09 18:46:07 +0000547 // This is a function template. We'll be building a template-id
548 // annotation token.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000549 Tok.setKind(tok::annot_template_id);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000550 TemplateIdAnnotation *TemplateId
Douglas Gregor39a8de12009-02-25 19:37:18 +0000551 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
Douglas Gregor55f6b142009-02-09 18:46:07 +0000552 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000553 TemplateId->Name = Name;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000554 TemplateId->Template = Template.getAs<void*>();
Douglas Gregor39a8de12009-02-25 19:37:18 +0000555 TemplateId->Kind = TNK;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000556 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000557 TemplateId->RAngleLoc = RAngleLoc;
558 void **Args = TemplateId->getTemplateArgs();
559 bool *ArgIsType = TemplateId->getTemplateArgIsType();
560 SourceLocation *ArgLocs = TemplateId->getTemplateArgLocations();
561 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg) {
Douglas Gregor55f6b142009-02-09 18:46:07 +0000562 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor39a8de12009-02-25 19:37:18 +0000563 ArgIsType[Arg] = TemplateArgIsType[Arg];
564 ArgLocs[Arg] = TemplateArgLocations[Arg];
565 }
Douglas Gregor55f6b142009-02-09 18:46:07 +0000566 Tok.setAnnotationValue(TemplateId);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000567 if (TemplateKWLoc.isValid())
568 Tok.setLocation(TemplateKWLoc);
569 else
570 Tok.setLocation(TemplateNameLoc);
571
572 TemplateArgsPtr.release();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000573 }
574
575 // Common fields for the annotation token
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000576 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000577
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000578 // In case the tokens were cached, have Preprocessor replace them with the
579 // annotation token.
580 PP.AnnotateCachedTokens(Tok);
581}
582
Douglas Gregor39a8de12009-02-25 19:37:18 +0000583/// \brief Replaces a template-id annotation token with a type
584/// annotation token.
585///
586/// \returns true if there was an error, false otherwise.
587bool Parser::AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS) {
588 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
589
590 TemplateIdAnnotation *TemplateId
591 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
592 assert(TemplateId->Kind == TNK_Class_template &&
593 "Only works for class templates");
594
595 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
596 TemplateId->getTemplateArgs(),
597 TemplateId->getTemplateArgIsType(),
598 TemplateId->NumArgs);
599
600 Action::TypeResult Type
Chris Lattnerb28317a2009-03-28 19:18:32 +0000601 = Actions.ActOnClassTemplateId(DeclPtrTy::make(TemplateId->Template),
Douglas Gregor39a8de12009-02-25 19:37:18 +0000602 TemplateId->TemplateNameLoc,
603 TemplateId->LAngleLoc,
604 TemplateArgsPtr,
605 TemplateId->getTemplateArgLocations(),
606 TemplateId->RAngleLoc, SS);
607 if (Type.isInvalid()) {
608 // FIXME: better recovery?
609 ConsumeToken();
610 TemplateId->Destroy();
611 return true;
612 }
613
614 // Create the new "type" annotation token.
615 Tok.setKind(tok::annot_typename);
616 Tok.setAnnotationValue(Type.get());
617 if (SS && SS->isNotEmpty()) // it was a C++ qualified type name.
618 Tok.setLocation(SS->getBeginLoc());
619
620 // We might be backtracking, in which case we need to replace the
621 // template-id annotation token with the type annotation within the
622 // set of cached tokens. That way, we won't try to form the same
623 // class template specialization again.
624 PP.ReplaceLastTokenWithAnnotation(Tok);
625 TemplateId->Destroy();
626
627 return false;
628}
629
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000630/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
631///
632/// template-argument: [C++ 14.2]
633/// assignment-expression
634/// type-id
635/// id-expression
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000636void *Parser::ParseTemplateArgument(bool &ArgIsType) {
Douglas Gregor55f6b142009-02-09 18:46:07 +0000637 // C++ [temp.arg]p2:
638 // In a template-argument, an ambiguity between a type-id and an
639 // expression is resolved to a type-id, regardless of the form of
640 // the corresponding template-parameter.
641 //
642 // Therefore, we initially try to parse a type-id.
Douglas Gregor8b642592009-02-10 00:53:15 +0000643 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000644 ArgIsType = true;
Douglas Gregor809070a2009-02-18 17:45:20 +0000645 TypeResult TypeArg = ParseTypeName();
646 if (TypeArg.isInvalid())
647 return 0;
648 return TypeArg.get();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000649 }
650
Douglas Gregorc15cb382009-02-09 23:23:08 +0000651 OwningExprResult ExprArg = ParseAssignmentExpression();
652 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000653 return 0;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000654
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000655 ArgIsType = false;
656 return ExprArg.release();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000657}
658
659/// ParseTemplateArgumentList - Parse a C++ template-argument-list
660/// (C++ [temp.names]). Returns true if there was an error.
661///
662/// template-argument-list: [C++ 14.2]
663/// template-argument
664/// template-argument-list ',' template-argument
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000665bool
666Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
Douglas Gregorc15cb382009-02-09 23:23:08 +0000667 TemplateArgIsTypeList &TemplateArgIsType,
668 TemplateArgLocationList &TemplateArgLocations) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000669 while (true) {
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000670 bool IsType = false;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000671 SourceLocation Loc = Tok.getLocation();
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000672 void *Arg = ParseTemplateArgument(IsType);
673 if (Arg) {
674 TemplateArgs.push_back(Arg);
675 TemplateArgIsType.push_back(IsType);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000676 TemplateArgLocations.push_back(Loc);
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000677 } else {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000678 SkipUntil(tok::comma, tok::greater, true, true);
679 return true;
680 }
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000681
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000682 // If the next token is a comma, consume it and keep reading
683 // arguments.
684 if (Tok.isNot(tok::comma)) break;
685
686 // Consume the comma.
687 ConsumeToken();
688 }
689
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000690 return Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000691}
692