blob: d38df93ace1b736725af0bd17f58275c8e63a112 [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,
Chris Lattner97144fc2009-04-02 04:16:50 +000038 SourceLocation &DeclEnd,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +000039 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);
Chris Lattnerb28317a2009-03-28 19:18:32 +000081 return DeclPtrTy();
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +000082 }
83
84 // Parse the '<' template-parameter-list '>'
85 SourceLocation LAngleLoc, RAngleLoc;
86 TemplateParameterList TemplateParams;
87 ParseTemplateParameters(ParamLists.size(), TemplateParams, LAngleLoc,
88 RAngleLoc);
89
90 ParamLists.push_back(
91 Actions.ActOnTemplateParameterList(ParamLists.size(), ExportLoc,
92 TemplateLoc, LAngleLoc,
93 &TemplateParams[0],
94 TemplateParams.size(), RAngleLoc));
95 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
96
97 // Parse the actual template declaration.
Chris Lattner682bf922009-03-29 16:50:03 +000098
99 // FIXME: This accepts template<typename x> int y;
100 // FIXME: Converting DeclGroupPtr to DeclPtr like this is an insanely gruesome
101 // hack, will bring up on cfe-dev.
102 DeclGroupPtrTy DG = ParseDeclarationOrFunctionDefinition(&ParamLists, AS);
Chris Lattner97144fc2009-04-02 04:16:50 +0000103 // FIXME: Should be ';' location not the token after it. Resolve with above
104 // fixmes.
105 DeclEnd = Tok.getLocation();
Chris Lattner682bf922009-03-29 16:50:03 +0000106 return DeclPtrTy::make(DG.get());
Douglas Gregoradcac882008-12-01 23:54:00 +0000107}
108
109/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000110/// angle brackets. Depth is the depth of this template-parameter-list, which
111/// is the number of template headers directly enclosing this template header.
112/// TemplateParams is the current list of template parameters we're building.
113/// The template parameter we parse will be added to this list. LAngleLoc and
114/// RAngleLoc will receive the positions of the '<' and '>', respectively,
115/// that enclose this template parameter list.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000116bool Parser::ParseTemplateParameters(unsigned Depth,
117 TemplateParameterList &TemplateParams,
118 SourceLocation &LAngleLoc,
119 SourceLocation &RAngleLoc) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000120 // Get the template parameter list.
121 if(!Tok.is(tok::less)) {
122 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
123 return false;
124 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000125 LAngleLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000126
127 // Try to parse the template parameter list.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000128 if (Tok.is(tok::greater))
129 RAngleLoc = ConsumeToken();
130 else if(ParseTemplateParameterList(Depth, TemplateParams)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000131 if(!Tok.is(tok::greater)) {
132 Diag(Tok.getLocation(), diag::err_expected_greater);
133 return false;
134 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000135 RAngleLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000136 }
137 return true;
138}
139
140/// ParseTemplateParameterList - Parse a template parameter list. If
141/// the parsing fails badly (i.e., closing bracket was left out), this
142/// will try to put the token stream in a reasonable position (closing
143/// a statement, etc.) and return false.
144///
145/// template-parameter-list: [C++ temp]
146/// template-parameter
147/// template-parameter-list ',' template-parameter
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000148bool
149Parser::ParseTemplateParameterList(unsigned Depth,
150 TemplateParameterList &TemplateParams) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000151 while(1) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000152 if (DeclPtrTy TmpParam
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000153 = ParseTemplateParameter(Depth, TemplateParams.size())) {
154 TemplateParams.push_back(TmpParam);
155 } else {
Douglas Gregoradcac882008-12-01 23:54:00 +0000156 // If we failed to parse a template parameter, skip until we find
157 // a comma or closing brace.
158 SkipUntil(tok::comma, tok::greater, true, true);
159 }
160
161 // Did we find a comma or the end of the template parmeter list?
162 if(Tok.is(tok::comma)) {
163 ConsumeToken();
164 } else if(Tok.is(tok::greater)) {
165 // Don't consume this... that's done by template parser.
166 break;
167 } else {
168 // Somebody probably forgot to close the template. Skip ahead and
169 // try to get out of the expression. This error is currently
170 // subsumed by whatever goes on in ParseTemplateParameter.
171 // TODO: This could match >>, and it would be nice to avoid those
172 // silly errors with template <vec<T>>.
173 // Diag(Tok.getLocation(), diag::err_expected_comma_greater);
174 SkipUntil(tok::greater, true, true);
175 return false;
176 }
177 }
178 return true;
179}
180
181/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
182///
183/// template-parameter: [C++ temp.param]
184/// type-parameter
185/// parameter-declaration
186///
187/// type-parameter: (see below)
188/// 'class' identifier[opt]
189/// 'class' identifier[opt] '=' type-id
190/// 'typename' identifier[opt]
191/// 'typename' identifier[opt] '=' type-id
192/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
193/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
Chris Lattnerb28317a2009-03-28 19:18:32 +0000194Parser::DeclPtrTy
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000195Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Chris Lattner532e19b2009-01-04 23:51:17 +0000196 if(Tok.is(tok::kw_class) ||
197 (Tok.is(tok::kw_typename) &&
198 // FIXME: Next token has not been annotated!
Chris Lattnerb31757b2009-01-06 05:06:21 +0000199 NextToken().isNot(tok::annot_typename))) {
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000200 return ParseTypeParameter(Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000201 }
Chris Lattner532e19b2009-01-04 23:51:17 +0000202
203 if(Tok.is(tok::kw_template))
204 return ParseTemplateTemplateParameter(Depth, Position);
205
206 // If it's none of the above, then it must be a parameter declaration.
207 // NOTE: This will pick up errors in the closure of the template parameter
208 // list (e.g., template < ; Check here to implement >> style closures.
209 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000210}
211
212/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
213/// Other kinds of template parameters are parsed in
214/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
215///
216/// type-parameter: [C++ temp.param]
217/// 'class' identifier[opt]
218/// 'class' identifier[opt] '=' type-id
219/// 'typename' identifier[opt]
220/// 'typename' identifier[opt] '=' type-id
Chris Lattnerb28317a2009-03-28 19:18:32 +0000221Parser::DeclPtrTy Parser::ParseTypeParameter(unsigned Depth, unsigned Position){
Douglas Gregor26236e82008-12-02 00:41:28 +0000222 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
223 "A type-parameter starts with 'class' or 'typename'");
224
225 // Consume the 'class' or 'typename' keyword.
226 bool TypenameKeyword = Tok.is(tok::kw_typename);
227 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000228
229 // Grab the template parameter name (if given)
Douglas Gregor26236e82008-12-02 00:41:28 +0000230 SourceLocation NameLoc;
231 IdentifierInfo* ParamName = 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000232 if(Tok.is(tok::identifier)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000233 ParamName = Tok.getIdentifierInfo();
234 NameLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000235 } else if(Tok.is(tok::equal) || Tok.is(tok::comma) ||
236 Tok.is(tok::greater)) {
237 // Unnamed template parameter. Don't have to do anything here, just
238 // don't consume this token.
239 } else {
240 Diag(Tok.getLocation(), diag::err_expected_ident);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000241 return DeclPtrTy();
Douglas Gregoradcac882008-12-01 23:54:00 +0000242 }
243
Chris Lattnerb28317a2009-03-28 19:18:32 +0000244 DeclPtrTy TypeParam = Actions.ActOnTypeParameter(CurScope, TypenameKeyword,
245 KeyLoc, ParamName, NameLoc,
246 Depth, Position);
Douglas Gregor26236e82008-12-02 00:41:28 +0000247
Douglas Gregoradcac882008-12-01 23:54:00 +0000248 // Grab a default type id (if given).
Douglas Gregoradcac882008-12-01 23:54:00 +0000249 if(Tok.is(tok::equal)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000250 SourceLocation EqualLoc = ConsumeToken();
Douglas Gregord684b002009-02-10 19:49:53 +0000251 SourceLocation DefaultLoc = Tok.getLocation();
Douglas Gregor809070a2009-02-18 17:45:20 +0000252 TypeResult DefaultType = ParseTypeName();
253 if (!DefaultType.isInvalid())
Douglas Gregord684b002009-02-10 19:49:53 +0000254 Actions.ActOnTypeParameterDefault(TypeParam, EqualLoc, DefaultLoc,
Douglas Gregor809070a2009-02-18 17:45:20 +0000255 DefaultType.get());
Douglas Gregoradcac882008-12-01 23:54:00 +0000256 }
257
Douglas Gregor26236e82008-12-02 00:41:28 +0000258 return TypeParam;
Douglas Gregoradcac882008-12-01 23:54:00 +0000259}
260
261/// ParseTemplateTemplateParameter - Handle the parsing of template
262/// template parameters.
263///
264/// type-parameter: [C++ temp.param]
265/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
266/// 'template' '<' template-parameter-list '>' 'class' identifier[opt] = id-expression
Chris Lattnerb28317a2009-03-28 19:18:32 +0000267Parser::DeclPtrTy
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000268Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000269 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
270
271 // Handle the template <...> part.
272 SourceLocation TemplateLoc = ConsumeToken();
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000273 TemplateParameterList TemplateParams;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000274 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor68c69932009-02-10 19:52:54 +0000275 {
276 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
277 if(!ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
278 RAngleLoc)) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000279 return DeclPtrTy();
Douglas Gregor68c69932009-02-10 19:52:54 +0000280 }
Douglas Gregoradcac882008-12-01 23:54:00 +0000281 }
282
283 // Generate a meaningful error if the user forgot to put class before the
284 // identifier, comma, or greater.
285 if(!Tok.is(tok::kw_class)) {
286 Diag(Tok.getLocation(), diag::err_expected_class_before)
287 << PP.getSpelling(Tok);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000288 return DeclPtrTy();
Douglas Gregoradcac882008-12-01 23:54:00 +0000289 }
290 SourceLocation ClassLoc = ConsumeToken();
291
292 // Get the identifier, if given.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000293 SourceLocation NameLoc;
294 IdentifierInfo* ParamName = 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000295 if(Tok.is(tok::identifier)) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000296 ParamName = Tok.getIdentifierInfo();
297 NameLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000298 } else if(Tok.is(tok::equal) || Tok.is(tok::comma) || Tok.is(tok::greater)) {
299 // Unnamed template parameter. Don't have to do anything here, just
300 // don't consume this token.
301 } else {
302 Diag(Tok.getLocation(), diag::err_expected_ident);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000303 return DeclPtrTy();
Douglas Gregoradcac882008-12-01 23:54:00 +0000304 }
305
Douglas Gregorddc29e12009-02-06 22:42:48 +0000306 TemplateParamsTy *ParamList =
307 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
308 TemplateLoc, LAngleLoc,
309 &TemplateParams[0],
310 TemplateParams.size(),
311 RAngleLoc);
312
Chris Lattnerb28317a2009-03-28 19:18:32 +0000313 Parser::DeclPtrTy Param
Douglas Gregord684b002009-02-10 19:49:53 +0000314 = Actions.ActOnTemplateTemplateParameter(CurScope, TemplateLoc,
315 ParamList, ParamName,
316 NameLoc, Depth, Position);
317
318 // Get the a default value, if given.
319 if (Tok.is(tok::equal)) {
320 SourceLocation EqualLoc = ConsumeToken();
321 OwningExprResult DefaultExpr = ParseCXXIdExpression();
322 if (DefaultExpr.isInvalid())
323 return Param;
324 else if (Param)
325 Actions.ActOnTemplateTemplateParameterDefault(Param, EqualLoc,
326 move(DefaultExpr));
327 }
328
329 return Param;
Douglas Gregoradcac882008-12-01 23:54:00 +0000330}
331
332/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
333/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000334///
Douglas Gregoradcac882008-12-01 23:54:00 +0000335/// template-parameter:
336/// ...
337/// parameter-declaration
338///
339/// NOTE: It would be ideal to simply call out to ParseParameterDeclaration(),
340/// but that didn't work out to well. Instead, this tries to recrate the basic
341/// parsing of parameter declarations, but tries to constrain it for template
342/// parameters.
Douglas Gregor26236e82008-12-02 00:41:28 +0000343/// FIXME: We need to make a ParseParameterDeclaration that works for
344/// non-type template parameters and normal function parameters.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000345Parser::DeclPtrTy
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000346Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000347 SourceLocation StartLoc = Tok.getLocation();
Douglas Gregoradcac882008-12-01 23:54:00 +0000348
349 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor26236e82008-12-02 00:41:28 +0000350 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregoradcac882008-12-01 23:54:00 +0000351 // declarators (parts of declarators?) are accepted for parameters.
Douglas Gregor26236e82008-12-02 00:41:28 +0000352 DeclSpec DS;
353 ParseDeclarationSpecifiers(DS);
Douglas Gregoradcac882008-12-01 23:54:00 +0000354
355 // Parse this as a typename.
Douglas Gregor26236e82008-12-02 00:41:28 +0000356 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
357 ParseDeclarator(ParamDecl);
Chris Lattner7452c6f2009-01-05 01:24:05 +0000358 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified && !DS.getTypeRep()) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000359 // This probably shouldn't happen - and it's more of a Sema thing, but
360 // basically we didn't parse the type name because we couldn't associate
361 // it with an AST node. we should just skip to the comma or greater.
362 // TODO: This is currently a placeholder for some kind of Sema Error.
363 Diag(Tok.getLocation(), diag::err_parse_error);
364 SkipUntil(tok::comma, tok::greater, true, true);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000365 return DeclPtrTy();
Douglas Gregoradcac882008-12-01 23:54:00 +0000366 }
367
Douglas Gregor26236e82008-12-02 00:41:28 +0000368 // Create the parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000369 DeclPtrTy Param = Actions.ActOnNonTypeTemplateParameter(CurScope, ParamDecl,
370 Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000371
Douglas Gregord684b002009-02-10 19:49:53 +0000372 // If there is a default value, parse it.
Chris Lattner7452c6f2009-01-05 01:24:05 +0000373 if (Tok.is(tok::equal)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000374 SourceLocation EqualLoc = ConsumeToken();
375
376 // C++ [temp.param]p15:
377 // When parsing a default template-argument for a non-type
378 // template-parameter, the first non-nested > is taken as the
379 // end of the template-parameter-list rather than a greater-than
380 // operator.
381 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
382
383 OwningExprResult DefaultArg = ParseAssignmentExpression();
384 if (DefaultArg.isInvalid())
385 SkipUntil(tok::comma, tok::greater, true, true);
386 else if (Param)
387 Actions.ActOnNonTypeTemplateParameterDefault(Param, EqualLoc,
388 move(DefaultArg));
Douglas Gregoradcac882008-12-01 23:54:00 +0000389 }
390
Douglas Gregor26236e82008-12-02 00:41:28 +0000391 return Param;
Douglas Gregoradcac882008-12-01 23:54:00 +0000392}
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000393
Douglas Gregorcc636682009-02-17 23:15:12 +0000394/// \brief Parses a template-id that after the template name has
395/// already been parsed.
396///
397/// This routine takes care of parsing the enclosed template argument
398/// list ('<' template-parameter-list [opt] '>') and placing the
399/// results into a form that can be transferred to semantic analysis.
400///
401/// \param Template the template declaration produced by isTemplateName
402///
403/// \param TemplateNameLoc the source location of the template name
404///
405/// \param SS if non-NULL, the nested-name-specifier preceding the
406/// template name.
407///
408/// \param ConsumeLastToken if true, then we will consume the last
409/// token that forms the template-id. Otherwise, we will leave the
410/// last token in the stream (e.g., so that it can be replaced with an
411/// annotation token).
412bool
Douglas Gregor7532dc62009-03-30 22:58:21 +0000413Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
Douglas Gregorcc636682009-02-17 23:15:12 +0000414 SourceLocation TemplateNameLoc,
415 const CXXScopeSpec *SS,
416 bool ConsumeLastToken,
417 SourceLocation &LAngleLoc,
418 TemplateArgList &TemplateArgs,
419 TemplateArgIsTypeList &TemplateArgIsType,
420 TemplateArgLocationList &TemplateArgLocations,
421 SourceLocation &RAngleLoc) {
422 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
423
424 // Consume the '<'.
425 LAngleLoc = ConsumeToken();
426
427 // Parse the optional template-argument-list.
428 bool Invalid = false;
429 {
430 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
431 if (Tok.isNot(tok::greater))
432 Invalid = ParseTemplateArgumentList(TemplateArgs, TemplateArgIsType,
433 TemplateArgLocations);
434
435 if (Invalid) {
436 // Try to find the closing '>'.
437 SkipUntil(tok::greater, true, !ConsumeLastToken);
438
439 return true;
440 }
441 }
442
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000443 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
Douglas Gregorcc636682009-02-17 23:15:12 +0000444 return true;
445
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000446 // Determine the location of the '>' or '>>'. Only consume this
447 // token if the caller asked us to.
Douglas Gregorcc636682009-02-17 23:15:12 +0000448 RAngleLoc = Tok.getLocation();
449
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000450 if (Tok.is(tok::greatergreater)) {
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000451 if (!getLang().CPlusPlus0x) {
452 const char *ReplaceStr = "> >";
453 if (NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))
454 ReplaceStr = "> > ";
455
456 Diag(Tok.getLocation(), diag::err_two_right_angle_brackets_need_space)
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000457 << CodeModificationHint::CreateReplacement(
458 SourceRange(Tok.getLocation()), ReplaceStr);
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000459 }
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000460
461 Tok.setKind(tok::greater);
462 if (!ConsumeLastToken) {
463 // Since we're not supposed to consume the '>>' token, we need
464 // to insert a second '>' token after the first.
465 PP.EnterToken(Tok);
466 }
467 } else if (ConsumeLastToken)
Douglas Gregorcc636682009-02-17 23:15:12 +0000468 ConsumeToken();
469
470 return false;
471}
472
Douglas Gregor39a8de12009-02-25 19:37:18 +0000473/// \brief Replace the tokens that form a simple-template-id with an
474/// annotation token containing the complete template-id.
475///
476/// The first token in the stream must be the name of a template that
477/// is followed by a '<'. This routine will parse the complete
478/// simple-template-id and replace the tokens with a single annotation
479/// token with one of two different kinds: if the template-id names a
480/// type (and \p AllowTypeAnnotation is true), the annotation token is
481/// a type annotation that includes the optional nested-name-specifier
482/// (\p SS). Otherwise, the annotation token is a template-id
483/// annotation that does not include the optional
484/// nested-name-specifier.
485///
486/// \param Template the declaration of the template named by the first
487/// token (an identifier), as returned from \c Action::isTemplateName().
488///
489/// \param TemplateNameKind the kind of template that \p Template
490/// refers to, as returned from \c Action::isTemplateName().
491///
492/// \param SS if non-NULL, the nested-name-specifier that precedes
493/// this template name.
494///
495/// \param TemplateKWLoc if valid, specifies that this template-id
496/// annotation was preceded by the 'template' keyword and gives the
497/// location of that keyword. If invalid (the default), then this
498/// template-id was not preceded by a 'template' keyword.
499///
500/// \param AllowTypeAnnotation if true (the default), then a
501/// simple-template-id that refers to a class template, template
502/// template parameter, or other template that produces a type will be
503/// replaced with a type annotation token. Otherwise, the
504/// simple-template-id is always replaced with a template-id
505/// annotation token.
Douglas Gregor7532dc62009-03-30 22:58:21 +0000506void Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000507 const CXXScopeSpec *SS,
508 SourceLocation TemplateKWLoc,
509 bool AllowTypeAnnotation) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000510 assert(getLang().CPlusPlus && "Can only annotate template-ids in C++");
511 assert(Template && Tok.is(tok::identifier) && NextToken().is(tok::less) &&
512 "Parser isn't at the beginning of a template-id");
513
514 // Consume the template-name.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000515 IdentifierInfo *Name = Tok.getIdentifierInfo();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000516 SourceLocation TemplateNameLoc = ConsumeToken();
517
Douglas Gregorcc636682009-02-17 23:15:12 +0000518 // Parse the enclosed template argument list.
519 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000520 TemplateArgList TemplateArgs;
521 TemplateArgIsTypeList TemplateArgIsType;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000522 TemplateArgLocationList TemplateArgLocations;
Douglas Gregorcc636682009-02-17 23:15:12 +0000523 bool Invalid = ParseTemplateIdAfterTemplateName(Template, TemplateNameLoc,
524 SS, false, LAngleLoc,
525 TemplateArgs,
526 TemplateArgIsType,
527 TemplateArgLocations,
528 RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000529
Douglas Gregorcc636682009-02-17 23:15:12 +0000530 ASTTemplateArgsPtr TemplateArgsPtr(Actions, &TemplateArgs[0],
531 &TemplateArgIsType[0],
532 TemplateArgs.size());
Douglas Gregorf02da892009-02-09 21:04:56 +0000533
Douglas Gregorcc636682009-02-17 23:15:12 +0000534 if (Invalid) // FIXME: How to recover from a broken template-id?
535 return;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000536
Douglas Gregor55f6b142009-02-09 18:46:07 +0000537 // Build the annotation token.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000538 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
Douglas Gregorcc636682009-02-17 23:15:12 +0000539 Action::TypeResult Type
Douglas Gregor7532dc62009-03-30 22:58:21 +0000540 = Actions.ActOnTemplateIdType(Template, TemplateNameLoc,
541 LAngleLoc, TemplateArgsPtr,
542 &TemplateArgLocations[0],
543 RAngleLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +0000544 if (Type.isInvalid()) // FIXME: better recovery?
545 return;
546
547 Tok.setKind(tok::annot_typename);
548 Tok.setAnnotationValue(Type.get());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000549 if (SS && SS->isNotEmpty())
550 Tok.setLocation(SS->getBeginLoc());
551 else if (TemplateKWLoc.isValid())
552 Tok.setLocation(TemplateKWLoc);
553 else
554 Tok.setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +0000555 } else {
Douglas Gregorc45c2322009-03-31 00:43:58 +0000556 // Build a template-id annotation token that can be processed
557 // later.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000558 Tok.setKind(tok::annot_template_id);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000559 TemplateIdAnnotation *TemplateId
Douglas Gregor39a8de12009-02-25 19:37:18 +0000560 = TemplateIdAnnotation::Allocate(TemplateArgs.size());
Douglas Gregor55f6b142009-02-09 18:46:07 +0000561 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000562 TemplateId->Name = Name;
Chris Lattnerb28317a2009-03-28 19:18:32 +0000563 TemplateId->Template = Template.getAs<void*>();
Douglas Gregor39a8de12009-02-25 19:37:18 +0000564 TemplateId->Kind = TNK;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000565 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000566 TemplateId->RAngleLoc = RAngleLoc;
567 void **Args = TemplateId->getTemplateArgs();
568 bool *ArgIsType = TemplateId->getTemplateArgIsType();
569 SourceLocation *ArgLocs = TemplateId->getTemplateArgLocations();
570 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg) {
Douglas Gregor55f6b142009-02-09 18:46:07 +0000571 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor39a8de12009-02-25 19:37:18 +0000572 ArgIsType[Arg] = TemplateArgIsType[Arg];
573 ArgLocs[Arg] = TemplateArgLocations[Arg];
574 }
Douglas Gregor55f6b142009-02-09 18:46:07 +0000575 Tok.setAnnotationValue(TemplateId);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000576 if (TemplateKWLoc.isValid())
577 Tok.setLocation(TemplateKWLoc);
578 else
579 Tok.setLocation(TemplateNameLoc);
580
581 TemplateArgsPtr.release();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000582 }
583
584 // Common fields for the annotation token
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000585 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000586
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000587 // In case the tokens were cached, have Preprocessor replace them with the
588 // annotation token.
589 PP.AnnotateCachedTokens(Tok);
590}
591
Douglas Gregor39a8de12009-02-25 19:37:18 +0000592/// \brief Replaces a template-id annotation token with a type
593/// annotation token.
594///
Douglas Gregor31a19b62009-04-01 21:51:26 +0000595/// If there was a failure when forming the type from the template-id,
596/// a type annotation token will still be created, but will have a
597/// NULL type pointer to signify an error.
598void Parser::AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS) {
Douglas Gregor39a8de12009-02-25 19:37:18 +0000599 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
600
601 TemplateIdAnnotation *TemplateId
602 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue());
Douglas Gregorc45c2322009-03-31 00:43:58 +0000603 assert((TemplateId->Kind == TNK_Type_template ||
604 TemplateId->Kind == TNK_Dependent_template_name) &&
605 "Only works for type and dependent templates");
Douglas Gregor39a8de12009-02-25 19:37:18 +0000606
607 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
608 TemplateId->getTemplateArgs(),
609 TemplateId->getTemplateArgIsType(),
610 TemplateId->NumArgs);
611
612 Action::TypeResult Type
Douglas Gregor7532dc62009-03-30 22:58:21 +0000613 = Actions.ActOnTemplateIdType(TemplateTy::make(TemplateId->Template),
614 TemplateId->TemplateNameLoc,
615 TemplateId->LAngleLoc,
616 TemplateArgsPtr,
617 TemplateId->getTemplateArgLocations(),
618 TemplateId->RAngleLoc);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000619 // Create the new "type" annotation token.
620 Tok.setKind(tok::annot_typename);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000621 Tok.setAnnotationValue(Type.isInvalid()? 0 : Type.get());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000622 if (SS && SS->isNotEmpty()) // it was a C++ qualified type name.
623 Tok.setLocation(SS->getBeginLoc());
624
625 // We might be backtracking, in which case we need to replace the
626 // template-id annotation token with the type annotation within the
627 // set of cached tokens. That way, we won't try to form the same
628 // class template specialization again.
629 PP.ReplaceLastTokenWithAnnotation(Tok);
630 TemplateId->Destroy();
Douglas Gregor39a8de12009-02-25 19:37:18 +0000631}
632
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000633/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
634///
635/// template-argument: [C++ 14.2]
636/// assignment-expression
637/// type-id
638/// id-expression
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000639void *Parser::ParseTemplateArgument(bool &ArgIsType) {
Douglas Gregor55f6b142009-02-09 18:46:07 +0000640 // C++ [temp.arg]p2:
641 // In a template-argument, an ambiguity between a type-id and an
642 // expression is resolved to a type-id, regardless of the form of
643 // the corresponding template-parameter.
644 //
645 // Therefore, we initially try to parse a type-id.
Douglas Gregor8b642592009-02-10 00:53:15 +0000646 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000647 ArgIsType = true;
Douglas Gregor809070a2009-02-18 17:45:20 +0000648 TypeResult TypeArg = ParseTypeName();
649 if (TypeArg.isInvalid())
650 return 0;
651 return TypeArg.get();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000652 }
653
Douglas Gregorc15cb382009-02-09 23:23:08 +0000654 OwningExprResult ExprArg = ParseAssignmentExpression();
655 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000656 return 0;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000657
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000658 ArgIsType = false;
659 return ExprArg.release();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000660}
661
662/// ParseTemplateArgumentList - Parse a C++ template-argument-list
663/// (C++ [temp.names]). Returns true if there was an error.
664///
665/// template-argument-list: [C++ 14.2]
666/// template-argument
667/// template-argument-list ',' template-argument
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000668bool
669Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs,
Douglas Gregorc15cb382009-02-09 23:23:08 +0000670 TemplateArgIsTypeList &TemplateArgIsType,
671 TemplateArgLocationList &TemplateArgLocations) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000672 while (true) {
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000673 bool IsType = false;
Douglas Gregorc15cb382009-02-09 23:23:08 +0000674 SourceLocation Loc = Tok.getLocation();
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000675 void *Arg = ParseTemplateArgument(IsType);
676 if (Arg) {
677 TemplateArgs.push_back(Arg);
678 TemplateArgIsType.push_back(IsType);
Douglas Gregorc15cb382009-02-09 23:23:08 +0000679 TemplateArgLocations.push_back(Loc);
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000680 } else {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000681 SkipUntil(tok::comma, tok::greater, true, true);
682 return true;
683 }
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000684
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000685 // If the next token is a comma, consume it and keep reading
686 // arguments.
687 if (Tok.isNot(tok::comma)) break;
688
689 // Consume the comma.
690 ConsumeToken();
691 }
692
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000693 return Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000694}
695