blob: 46a15c39c6f8ebf42e37eb064b18c93ac6a377d0 [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"
John McCall19510852010-08-20 18:27:03 +000016#include "clang/Sema/DeclSpec.h"
17#include "clang/Sema/ParsedTemplate.h"
18#include "clang/Sema/Scope.h"
Chris Lattnerde138eb2009-12-10 00:45:15 +000019#include "RAIIObjectsForParser.h"
Francois Pichet8387e2a2011-04-22 22:18:13 +000020#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/ASTConsumer.h"
Douglas Gregoradcac882008-12-01 23:54:00 +000022using namespace clang;
23
Douglas Gregor4d9a16f2009-05-12 23:25:50 +000024/// \brief Parse a template declaration, explicit instantiation, or
25/// explicit specialization.
John McCalld226f652010-08-21 09:40:31 +000026Decl *
Douglas Gregor4d9a16f2009-05-12 23:25:50 +000027Parser::ParseDeclarationStartingWithTemplate(unsigned Context,
28 SourceLocation &DeclEnd,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +000029 AccessSpecifier AS,
30 AttributeList *AccessAttrs) {
Fariborz Jahanian9735c5e2011-08-22 17:59:19 +000031 ObjCDeclContextSwitch ObjCDC(*this);
32
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000033 if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) {
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +000034 return ParseExplicitInstantiation(Context,
35 SourceLocation(), ConsumeToken(),
36 DeclEnd, AS);
Fariborz Jahaniana28948f2011-08-22 15:54:49 +000037 }
Erik Verbruggen5f1c8222011-10-13 09:41:32 +000038 return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS,
39 AccessAttrs);
Douglas Gregor4d9a16f2009-05-12 23:25:50 +000040}
41
Douglas Gregorc3058332009-08-24 23:03:25 +000042/// \brief RAII class that manages the template parameter depth.
43namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000044 class TemplateParameterDepthCounter {
Douglas Gregorc3058332009-08-24 23:03:25 +000045 unsigned &Depth;
46 unsigned AddedLevels;
47
48 public:
Mike Stump1eb44332009-09-09 15:08:12 +000049 explicit TemplateParameterDepthCounter(unsigned &Depth)
Douglas Gregorc3058332009-08-24 23:03:25 +000050 : Depth(Depth), AddedLevels(0) { }
Mike Stump1eb44332009-09-09 15:08:12 +000051
Douglas Gregorc3058332009-08-24 23:03:25 +000052 ~TemplateParameterDepthCounter() {
53 Depth -= AddedLevels;
54 }
Mike Stump1eb44332009-09-09 15:08:12 +000055
56 void operator++() {
Douglas Gregorc3058332009-08-24 23:03:25 +000057 ++Depth;
58 ++AddedLevels;
59 }
Mike Stump1eb44332009-09-09 15:08:12 +000060
Douglas Gregorc3058332009-08-24 23:03:25 +000061 operator unsigned() const { return Depth; }
62 };
63}
64
Douglas Gregorcc636682009-02-17 23:15:12 +000065/// \brief Parse a template declaration or an explicit specialization.
66///
67/// Template declarations include one or more template parameter lists
68/// and either the function or class template declaration. Explicit
69/// specializations contain one or more 'template < >' prefixes
70/// followed by a (possibly templated) declaration. Since the
71/// syntactic form of both features is nearly identical, we parse all
72/// of the template headers together and let semantic analysis sort
73/// the declarations from the explicit specializations.
Douglas Gregoradcac882008-12-01 23:54:00 +000074///
75/// template-declaration: [C++ temp]
76/// 'export'[opt] 'template' '<' template-parameter-list '>' declaration
Douglas Gregorcc636682009-02-17 23:15:12 +000077///
78/// explicit-specialization: [ C++ temp.expl.spec]
79/// 'template' '<' '>' declaration
John McCalld226f652010-08-21 09:40:31 +000080Decl *
Anders Carlsson5aeccdb2009-03-26 00:52:18 +000081Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context,
Chris Lattner97144fc2009-04-02 04:16:50 +000082 SourceLocation &DeclEnd,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +000083 AccessSpecifier AS,
84 AttributeList *AccessAttrs) {
Mike Stump1eb44332009-09-09 15:08:12 +000085 assert((Tok.is(tok::kw_export) || Tok.is(tok::kw_template)) &&
86 "Token does not start a template declaration.");
87
Douglas Gregor26236e82008-12-02 00:41:28 +000088 // Enter template-parameter scope.
Douglas Gregor8935b8b2008-12-10 06:34:36 +000089 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Douglas Gregor26236e82008-12-02 00:41:28 +000090
John McCallc9068d72010-07-16 08:13:16 +000091 // Tell the action that names should be checked in the context of
92 // the declaration to come.
John McCall92576642012-05-07 06:16:41 +000093 ParsingDeclRAIIObject
94 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
John McCallc9068d72010-07-16 08:13:16 +000095
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +000096 // Parse multiple levels of template headers within this template
97 // parameter scope, e.g.,
98 //
99 // template<typename T>
100 // template<typename U>
101 // class A<T>::B { ... };
102 //
103 // We parse multiple levels non-recursively so that we can build a
104 // single data structure containing all of the template parameter
Douglas Gregorcc636682009-02-17 23:15:12 +0000105 // lists to easily differentiate between the case above and:
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000106 //
107 // template<typename T>
108 // class A {
109 // template<typename U> class B;
110 // };
111 //
112 // In the first case, the action for declaring A<T>::B receives
113 // both template parameter lists. In the second case, the action for
114 // defining A<T>::B receives just the inner template parameter list
115 // (and retrieves the outer template parameter list from its
116 // context).
Douglas Gregor0f499d92009-08-20 18:46:05 +0000117 bool isSpecialization = true;
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000118 bool LastParamListWasEmpty = false;
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000119 TemplateParameterLists ParamLists;
Douglas Gregorc3058332009-08-24 23:03:25 +0000120 TemplateParameterDepthCounter Depth(TemplateParameterDepth);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000121 do {
122 // Consume the 'export', if any.
123 SourceLocation ExportLoc;
124 if (Tok.is(tok::kw_export)) {
125 ExportLoc = ConsumeToken();
126 }
127
128 // Consume the 'template', which should be here.
129 SourceLocation TemplateLoc;
130 if (Tok.is(tok::kw_template)) {
131 TemplateLoc = ConsumeToken();
132 } else {
133 Diag(Tok.getLocation(), diag::err_expected_template);
John McCalld226f652010-08-21 09:40:31 +0000134 return 0;
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000135 }
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000137 // Parse the '<' template-parameter-list '>'
138 SourceLocation LAngleLoc, RAngleLoc;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000139 SmallVector<Decl*, 4> TemplateParams;
Mike Stump1eb44332009-09-09 15:08:12 +0000140 if (ParseTemplateParameters(Depth, TemplateParams, LAngleLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000141 RAngleLoc)) {
142 // Skip until the semi-colon or a }.
143 SkipUntil(tok::r_brace, true, true);
144 if (Tok.is(tok::semi))
145 ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000146 return 0;
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000147 }
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000148
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000149 ParamLists.push_back(
Mike Stump1eb44332009-09-09 15:08:12 +0000150 Actions.ActOnTemplateParameterList(Depth, ExportLoc,
151 TemplateLoc, LAngleLoc,
Jay Foadbeaaccd2009-05-21 09:52:38 +0000152 TemplateParams.data(),
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000153 TemplateParams.size(), RAngleLoc));
Douglas Gregorc3058332009-08-24 23:03:25 +0000154
155 if (!TemplateParams.empty()) {
156 isSpecialization = false;
157 ++Depth;
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000158 } else {
159 LastParamListWasEmpty = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000160 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000161 } while (Tok.is(tok::kw_export) || Tok.is(tok::kw_template));
162
163 // Parse the actual template declaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000164 return ParseSingleDeclarationAfterTemplate(Context,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000165 ParsedTemplateInfo(&ParamLists,
Douglas Gregorc78c06d2009-10-30 22:09:44 +0000166 isSpecialization,
167 LastParamListWasEmpty),
John McCallc9068d72010-07-16 08:13:16 +0000168 ParsingTemplateParams,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +0000169 DeclEnd, AS, AccessAttrs);
Douglas Gregor1426e532009-05-12 21:31:51 +0000170}
Chris Lattner682bf922009-03-29 16:50:03 +0000171
Douglas Gregor1426e532009-05-12 21:31:51 +0000172/// \brief Parse a single declaration that declares a template,
173/// template specialization, or explicit instantiation of a template.
174///
175/// \param TemplateParams if non-NULL, the template parameter lists
176/// that preceded this declaration. In this case, the declaration is a
177/// template declaration, out-of-line definition of a template, or an
178/// explicit template specialization. When NULL, the declaration is an
179/// explicit template instantiation.
180///
181/// \param TemplateLoc when TemplateParams is NULL, the location of
182/// the 'template' keyword that indicates that we have an explicit
183/// template instantiation.
184///
185/// \param DeclEnd will receive the source location of the last token
186/// within this declaration.
187///
188/// \param AS the access specifier associated with this
189/// declaration. Will be AS_none for namespace-scope declarations.
190///
191/// \returns the new declaration.
John McCalld226f652010-08-21 09:40:31 +0000192Decl *
Douglas Gregor1426e532009-05-12 21:31:51 +0000193Parser::ParseSingleDeclarationAfterTemplate(
194 unsigned Context,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000195 const ParsedTemplateInfo &TemplateInfo,
John McCallc9068d72010-07-16 08:13:16 +0000196 ParsingDeclRAIIObject &DiagsFromTParams,
Douglas Gregor1426e532009-05-12 21:31:51 +0000197 SourceLocation &DeclEnd,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +0000198 AccessSpecifier AS,
199 AttributeList *AccessAttrs) {
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000200 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
201 "Template information required");
202
Douglas Gregor37b372b2009-08-20 22:52:58 +0000203 if (Context == Declarator::MemberContext) {
204 // We are parsing a member template.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +0000205 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
206 &DiagsFromTParams);
John McCalld226f652010-08-21 09:40:31 +0000207 return 0;
Douglas Gregor37b372b2009-08-20 22:52:58 +0000208 }
Mike Stump1eb44332009-09-09 15:08:12 +0000209
John McCall0b7e6782011-03-24 11:26:52 +0000210 ParsedAttributesWithRange prefixAttrs(AttrFactory);
John McCall7f040a92010-12-24 02:08:15 +0000211 MaybeParseCXX0XAttributes(prefixAttrs);
John McCall78b81052010-11-10 02:40:36 +0000212
213 if (Tok.is(tok::kw_using))
214 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
John McCall7f040a92010-12-24 02:08:15 +0000215 prefixAttrs);
John McCall78b81052010-11-10 02:40:36 +0000216
John McCall92576642012-05-07 06:16:41 +0000217 // Parse the declaration specifiers, stealing any diagnostics from
218 // the template parameters.
John McCall0b7e6782011-03-24 11:26:52 +0000219 ParsingDeclSpec DS(*this, &DiagsFromTParams);
Sean Huntbbd37c62009-11-21 08:43:09 +0000220
John McCall92576642012-05-07 06:16:41 +0000221 // Move the attributes from the prefix into the DS.
John McCall7f040a92010-12-24 02:08:15 +0000222 DS.takeAttributesFrom(prefixAttrs);
Sean Huntbbd37c62009-11-21 08:43:09 +0000223
Douglas Gregor0efc2c12010-01-13 17:31:36 +0000224 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
225 getDeclSpecContextFromDeclaratorContext(Context));
Douglas Gregor1426e532009-05-12 21:31:51 +0000226
227 if (Tok.is(tok::semi)) {
228 DeclEnd = ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000229 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
John McCall54abf7d2009-11-04 02:18:39 +0000230 DS.complete(Decl);
231 return Decl;
Douglas Gregor1426e532009-05-12 21:31:51 +0000232 }
233
234 // Parse the declarator.
John McCall54abf7d2009-11-04 02:18:39 +0000235 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
Douglas Gregor1426e532009-05-12 21:31:51 +0000236 ParseDeclarator(DeclaratorInfo);
237 // Error parsing the declarator?
238 if (!DeclaratorInfo.hasName()) {
239 // If so, skip until the semi-colon or a }.
240 SkipUntil(tok::r_brace, true, true);
241 if (Tok.is(tok::semi))
242 ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000243 return 0;
Douglas Gregor1426e532009-05-12 21:31:51 +0000244 }
Mike Stump1eb44332009-09-09 15:08:12 +0000245
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000246 LateParsedAttrList LateParsedAttrs;
247 if (DeclaratorInfo.isFunctionDeclarator())
248 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
249
Douglas Gregor1426e532009-05-12 21:31:51 +0000250 // If we have a declaration or declarator list, handle it.
251 if (isDeclarationAfterDeclarator()) {
252 // Parse this declaration.
John McCalld226f652010-08-21 09:40:31 +0000253 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
254 TemplateInfo);
Douglas Gregor1426e532009-05-12 21:31:51 +0000255
256 if (Tok.is(tok::comma)) {
257 Diag(Tok, diag::err_multiple_template_declarators)
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000258 << (int)TemplateInfo.Kind;
Douglas Gregor1426e532009-05-12 21:31:51 +0000259 SkipUntil(tok::semi, true, false);
260 return ThisDecl;
261 }
262
263 // Eat the semi colon after the declaration.
Chris Lattner8bb21d32012-04-28 16:12:17 +0000264 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000265 if (LateParsedAttrs.size() > 0)
266 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
John McCalleee1d542011-02-14 07:13:47 +0000267 DeclaratorInfo.complete(ThisDecl);
Douglas Gregor1426e532009-05-12 21:31:51 +0000268 return ThisDecl;
269 }
270
271 if (DeclaratorInfo.isFunctionDeclarator() &&
Chris Lattner004659a2010-07-11 22:42:07 +0000272 isStartOfFunctionDefinition(DeclaratorInfo)) {
Douglas Gregor1426e532009-05-12 21:31:51 +0000273 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Smith6e1fd332011-11-29 09:09:06 +0000274 // Recover by ignoring the 'typedef'. This was probably supposed to be
275 // the 'typename' keyword, which we should have already suggested adding
276 // if it's appropriate.
277 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
278 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith874d2532011-11-29 05:27:40 +0000279 DS.ClearStorageClassSpecs();
Douglas Gregor1426e532009-05-12 21:31:51 +0000280 }
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000281 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
282 &LateParsedAttrs);
Douglas Gregor1426e532009-05-12 21:31:51 +0000283 }
284
285 if (DeclaratorInfo.isFunctionDeclarator())
286 Diag(Tok, diag::err_expected_fn_body);
287 else
288 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
289 SkipUntil(tok::semi);
John McCalld226f652010-08-21 09:40:31 +0000290 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000291}
292
293/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000294/// angle brackets. Depth is the depth of this template-parameter-list, which
295/// is the number of template headers directly enclosing this template header.
296/// TemplateParams is the current list of template parameters we're building.
297/// The template parameter we parse will be added to this list. LAngleLoc and
Mike Stump1eb44332009-09-09 15:08:12 +0000298/// RAngleLoc will receive the positions of the '<' and '>', respectively,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000299/// that enclose this template parameter list.
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000300///
301/// \returns true if an error occurred, false otherwise.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000302bool Parser::ParseTemplateParameters(unsigned Depth,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000303 SmallVectorImpl<Decl*> &TemplateParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000304 SourceLocation &LAngleLoc,
305 SourceLocation &RAngleLoc) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000306 // Get the template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +0000307 if (!Tok.is(tok::less)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000308 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000309 return true;
Douglas Gregoradcac882008-12-01 23:54:00 +0000310 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000311 LAngleLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Douglas Gregoradcac882008-12-01 23:54:00 +0000313 // Try to parse the template parameter list.
David Blaikieeb52f86a2012-04-09 16:37:11 +0000314 bool Failed = false;
315 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
316 Failed = ParseTemplateParameterList(Depth, TemplateParams);
317
318 if (Tok.is(tok::greatergreater)) {
Richard Smith19a27022012-06-18 06:11:04 +0000319 // No diagnostic required here: a template-parameter-list can only be
320 // followed by a declaration or, for a template template parameter, the
321 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
322 // This matters for elegant diagnosis of:
323 // template<template<typename>> struct S;
David Blaikieeb52f86a2012-04-09 16:37:11 +0000324 Tok.setKind(tok::greater);
325 RAngleLoc = Tok.getLocation();
326 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
327 } else if (Tok.is(tok::greater))
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000328 RAngleLoc = ConsumeToken();
David Blaikieeb52f86a2012-04-09 16:37:11 +0000329 else if (Failed) {
330 Diag(Tok.getLocation(), diag::err_expected_greater);
331 return true;
Douglas Gregoradcac882008-12-01 23:54:00 +0000332 }
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000333 return false;
Douglas Gregoradcac882008-12-01 23:54:00 +0000334}
335
336/// ParseTemplateParameterList - Parse a template parameter list. If
337/// the parsing fails badly (i.e., closing bracket was left out), this
338/// will try to put the token stream in a reasonable position (closing
Mike Stump1eb44332009-09-09 15:08:12 +0000339/// a statement, etc.) and return false.
Douglas Gregoradcac882008-12-01 23:54:00 +0000340///
341/// template-parameter-list: [C++ temp]
342/// template-parameter
343/// template-parameter-list ',' template-parameter
Mike Stump1eb44332009-09-09 15:08:12 +0000344bool
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000345Parser::ParseTemplateParameterList(unsigned Depth,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000346 SmallVectorImpl<Decl*> &TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000347 while (1) {
John McCalld226f652010-08-21 09:40:31 +0000348 if (Decl *TmpParam
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000349 = ParseTemplateParameter(Depth, TemplateParams.size())) {
350 TemplateParams.push_back(TmpParam);
351 } else {
Douglas Gregoradcac882008-12-01 23:54:00 +0000352 // If we failed to parse a template parameter, skip until we find
353 // a comma or closing brace.
David Blaikie9df1b962012-04-06 05:26:43 +0000354 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000355 }
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Douglas Gregoradcac882008-12-01 23:54:00 +0000357 // Did we find a comma or the end of the template parmeter list?
Mike Stump1eb44332009-09-09 15:08:12 +0000358 if (Tok.is(tok::comma)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000359 ConsumeToken();
David Blaikie9df1b962012-04-06 05:26:43 +0000360 } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000361 // Don't consume this... that's done by template parser.
362 break;
363 } else {
364 // Somebody probably forgot to close the template. Skip ahead and
365 // try to get out of the expression. This error is currently
366 // subsumed by whatever goes on in ParseTemplateParameter.
Douglas Gregor99ea7342010-10-15 01:15:58 +0000367 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
David Blaikieeb52f86a2012-04-09 16:37:11 +0000368 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000369 return false;
370 }
371 }
372 return true;
373}
374
Douglas Gregor98440b42009-11-21 02:07:55 +0000375/// \brief Determine whether the parser is at the start of a template
376/// type parameter.
377bool Parser::isStartOfTemplateTypeParameter() {
Douglas Gregor7b6d25b2010-06-04 07:30:15 +0000378 if (Tok.is(tok::kw_class)) {
379 // "class" may be the start of an elaborated-type-specifier or a
380 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
381 switch (NextToken().getKind()) {
382 case tok::equal:
383 case tok::comma:
384 case tok::greater:
385 case tok::greatergreater:
386 case tok::ellipsis:
387 return true;
388
389 case tok::identifier:
390 // This may be either a type-parameter or an elaborated-type-specifier.
391 // We have to look further.
392 break;
393
394 default:
395 return false;
396 }
397
398 switch (GetLookAheadToken(2).getKind()) {
399 case tok::equal:
400 case tok::comma:
401 case tok::greater:
402 case tok::greatergreater:
403 return true;
404
405 default:
406 return false;
407 }
408 }
Douglas Gregor98440b42009-11-21 02:07:55 +0000409
410 if (Tok.isNot(tok::kw_typename))
411 return false;
412
413 // C++ [temp.param]p2:
414 // There is no semantic difference between class and typename in a
415 // template-parameter. typename followed by an unqualified-id
416 // names a template type parameter. typename followed by a
417 // qualified-id denotes the type in a non-type
418 // parameter-declaration.
419 Token Next = NextToken();
420
421 // If we have an identifier, skip over it.
422 if (Next.getKind() == tok::identifier)
423 Next = GetLookAheadToken(2);
424
425 switch (Next.getKind()) {
426 case tok::equal:
427 case tok::comma:
428 case tok::greater:
429 case tok::greatergreater:
430 case tok::ellipsis:
431 return true;
432
433 default:
434 return false;
435 }
436}
437
Douglas Gregoradcac882008-12-01 23:54:00 +0000438/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
439///
440/// template-parameter: [C++ temp.param]
441/// type-parameter
442/// parameter-declaration
443///
444/// type-parameter: (see below)
Douglas Gregor61c4d282011-01-05 15:48:55 +0000445/// 'class' ...[opt] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000446/// 'class' identifier[opt] '=' type-id
Douglas Gregor61c4d282011-01-05 15:48:55 +0000447/// 'typename' ...[opt] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000448/// 'typename' identifier[opt] '=' type-id
Douglas Gregor61c4d282011-01-05 15:48:55 +0000449/// 'template' '<' template-parameter-list '>'
450/// 'class' ...[opt] identifier[opt]
451/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
452/// = id-expression
John McCalld226f652010-08-21 09:40:31 +0000453Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor98440b42009-11-21 02:07:55 +0000454 if (isStartOfTemplateTypeParameter())
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000455 return ParseTypeParameter(Depth, Position);
Mike Stump1eb44332009-09-09 15:08:12 +0000456
457 if (Tok.is(tok::kw_template))
Chris Lattner532e19b2009-01-04 23:51:17 +0000458 return ParseTemplateTemplateParameter(Depth, Position);
459
460 // If it's none of the above, then it must be a parameter declaration.
461 // NOTE: This will pick up errors in the closure of the template parameter
462 // list (e.g., template < ; Check here to implement >> style closures.
463 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000464}
465
466/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
467/// Other kinds of template parameters are parsed in
468/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
469///
470/// type-parameter: [C++ temp.param]
Anders Carlssonce5635a2009-06-12 23:09:56 +0000471/// 'class' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000472/// 'class' identifier[opt] '=' type-id
Anders Carlssonce5635a2009-06-12 23:09:56 +0000473/// 'typename' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000474/// 'typename' identifier[opt] '=' type-id
John McCalld226f652010-08-21 09:40:31 +0000475Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000476 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
Mike Stump1eb44332009-09-09 15:08:12 +0000477 "A type-parameter starts with 'class' or 'typename'");
Douglas Gregor26236e82008-12-02 00:41:28 +0000478
479 // Consume the 'class' or 'typename' keyword.
480 bool TypenameKeyword = Tok.is(tok::kw_typename);
481 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000482
Anders Carlsson941df7d2009-06-12 19:58:00 +0000483 // Grab the ellipsis (if given).
484 bool Ellipsis = false;
485 SourceLocation EllipsisLoc;
Anders Carlssonce5635a2009-06-12 23:09:56 +0000486 if (Tok.is(tok::ellipsis)) {
Anders Carlsson941df7d2009-06-12 19:58:00 +0000487 Ellipsis = true;
488 EllipsisLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Richard Smithe5acd132011-10-14 20:31:37 +0000490 Diag(EllipsisLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +0000491 getLangOpts().CPlusPlus0x
Richard Smithe5acd132011-10-14 20:31:37 +0000492 ? diag::warn_cxx98_compat_variadic_templates
493 : diag::ext_variadic_templates);
Anders Carlsson941df7d2009-06-12 19:58:00 +0000494 }
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Douglas Gregoradcac882008-12-01 23:54:00 +0000496 // Grab the template parameter name (if given)
Douglas Gregor26236e82008-12-02 00:41:28 +0000497 SourceLocation NameLoc;
498 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000499 if (Tok.is(tok::identifier)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000500 ParamName = Tok.getIdentifierInfo();
501 NameLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000502 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
David Blaikie9df1b962012-04-06 05:26:43 +0000503 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000504 // Unnamed template parameter. Don't have to do anything here, just
505 // don't consume this token.
506 } else {
507 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000508 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000509 }
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000511 // Grab a default argument (if available).
512 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
513 // we introduce the type parameter into the local scope.
514 SourceLocation EqualLoc;
John McCallb3d87482010-08-24 05:47:05 +0000515 ParsedType DefaultArg;
Mike Stump1eb44332009-09-09 15:08:12 +0000516 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000517 EqualLoc = ConsumeToken();
Richard Smithd37b3602012-02-10 11:05:11 +0000518 DefaultArg = ParseTypeName(/*Range=*/0,
519 Declarator::TemplateTypeArgContext).get();
Douglas Gregoradcac882008-12-01 23:54:00 +0000520 }
Richard Smithd37b3602012-02-10 11:05:11 +0000521
Douglas Gregor23c94db2010-07-02 17:43:08 +0000522 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000523 EllipsisLoc, KeyLoc, ParamName, NameLoc,
524 Depth, Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000525}
526
527/// ParseTemplateTemplateParameter - Handle the parsing of template
Mike Stump1eb44332009-09-09 15:08:12 +0000528/// template parameters.
Douglas Gregoradcac882008-12-01 23:54:00 +0000529///
530/// type-parameter: [C++ temp.param]
Douglas Gregor61c4d282011-01-05 15:48:55 +0000531/// 'template' '<' template-parameter-list '>' 'class'
532/// ...[opt] identifier[opt]
533/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
534/// = id-expression
John McCalld226f652010-08-21 09:40:31 +0000535Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000536Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000537 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
538
539 // Handle the template <...> part.
540 SourceLocation TemplateLoc = ConsumeToken();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000541 SmallVector<Decl*,8> TemplateParams;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000542 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor68c69932009-02-10 19:52:54 +0000543 {
544 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000545 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000546 RAngleLoc)) {
John McCalld226f652010-08-21 09:40:31 +0000547 return 0;
Douglas Gregor68c69932009-02-10 19:52:54 +0000548 }
Douglas Gregoradcac882008-12-01 23:54:00 +0000549 }
550
551 // Generate a meaningful error if the user forgot to put class before the
David Blaikie9df1b962012-04-06 05:26:43 +0000552 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
553 // or greater appear immediately or after 'typename' or 'struct'. In the
554 // latter case, replace the keyword with 'class'.
555 if (!Tok.is(tok::kw_class)) {
556 bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
557 const Token& Next = Replace ? NextToken() : Tok;
558 if (Next.is(tok::identifier) || Next.is(tok::comma) ||
559 Next.is(tok::greater) || Next.is(tok::greatergreater) ||
560 Next.is(tok::ellipsis))
561 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
562 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
563 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
564 else
565 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
566
567 if (Replace)
568 ConsumeToken();
569 } else
David Blaikie460ef132012-04-02 19:15:28 +0000570 ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000571
Douglas Gregor61c4d282011-01-05 15:48:55 +0000572 // Parse the ellipsis, if given.
573 SourceLocation EllipsisLoc;
574 if (Tok.is(tok::ellipsis)) {
575 EllipsisLoc = ConsumeToken();
576
Richard Smithe5acd132011-10-14 20:31:37 +0000577 Diag(EllipsisLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +0000578 getLangOpts().CPlusPlus0x
Richard Smithe5acd132011-10-14 20:31:37 +0000579 ? diag::warn_cxx98_compat_variadic_templates
580 : diag::ext_variadic_templates);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000581 }
582
Douglas Gregoradcac882008-12-01 23:54:00 +0000583 // Get the identifier, if given.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000584 SourceLocation NameLoc;
585 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000586 if (Tok.is(tok::identifier)) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000587 ParamName = Tok.getIdentifierInfo();
588 NameLoc = ConsumeToken();
David Blaikie9df1b962012-04-06 05:26:43 +0000589 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
590 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000591 // Unnamed template parameter. Don't have to do anything here, just
592 // don't consume this token.
593 } else {
594 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000595 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000596 }
597
Richard Trieu90ab75b2011-09-09 03:18:59 +0000598 TemplateParameterList *ParamList =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000599 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
600 TemplateLoc, LAngleLoc,
Douglas Gregor369ea272010-10-21 17:26:49 +0000601 TemplateParams.data(),
Douglas Gregorddc29e12009-02-06 22:42:48 +0000602 TemplateParams.size(),
603 RAngleLoc);
604
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000605 // Grab a default argument (if available).
606 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
607 // we introduce the template parameter into the local scope.
608 SourceLocation EqualLoc;
609 ParsedTemplateArgument DefaultArg;
Douglas Gregord684b002009-02-10 19:49:53 +0000610 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000611 EqualLoc = ConsumeToken();
612 DefaultArg = ParseTemplateTemplateArgument();
613 if (DefaultArg.isInvalid()) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000614 Diag(Tok.getLocation(),
615 diag::err_default_template_template_parameter_not_template);
David Blaikieeb52f86a2012-04-09 16:37:11 +0000616 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000617 }
Douglas Gregord684b002009-02-10 19:49:53 +0000618 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000619
Douglas Gregor23c94db2010-07-02 17:43:08 +0000620 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000621 ParamList, EllipsisLoc,
622 ParamName, NameLoc, Depth,
623 Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000624}
625
626/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
Mike Stump1eb44332009-09-09 15:08:12 +0000627/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000628///
Douglas Gregoradcac882008-12-01 23:54:00 +0000629/// template-parameter:
630/// ...
631/// parameter-declaration
John McCalld226f652010-08-21 09:40:31 +0000632Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000633Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000634 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor26236e82008-12-02 00:41:28 +0000635 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregoradcac882008-12-01 23:54:00 +0000636 // declarators (parts of declarators?) are accepted for parameters.
John McCall0b7e6782011-03-24 11:26:52 +0000637 DeclSpec DS(AttrFactory);
Douglas Gregor26236e82008-12-02 00:41:28 +0000638 ParseDeclarationSpecifiers(DS);
Douglas Gregoradcac882008-12-01 23:54:00 +0000639
640 // Parse this as a typename.
Douglas Gregor26236e82008-12-02 00:41:28 +0000641 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
642 ParseDeclarator(ParamDecl);
John McCallb3d87482010-08-24 05:47:05 +0000643 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
David Blaikieb031eab2012-04-06 23:33:59 +0000644 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
John McCalld226f652010-08-21 09:40:31 +0000645 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000646 }
647
Douglas Gregord684b002009-02-10 19:49:53 +0000648 // If there is a default value, parse it.
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000649 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
650 // we introduce the template parameter into the local scope.
651 SourceLocation EqualLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000652 ExprResult DefaultArg;
Chris Lattner7452c6f2009-01-05 01:24:05 +0000653 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000654 EqualLoc = ConsumeToken();
Douglas Gregord684b002009-02-10 19:49:53 +0000655
656 // C++ [temp.param]p15:
657 // When parsing a default template-argument for a non-type
658 // template-parameter, the first non-nested > is taken as the
659 // end of the template-parameter-list rather than a greater-than
660 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +0000661 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Eli Friedman9b94cd12012-04-26 22:43:24 +0000662 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
Douglas Gregord684b002009-02-10 19:49:53 +0000663
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000664 DefaultArg = ParseAssignmentExpression();
Douglas Gregord684b002009-02-10 19:49:53 +0000665 if (DefaultArg.isInvalid())
666 SkipUntil(tok::comma, tok::greater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000667 }
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000669 // Create the parameter.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000670 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000671 Depth, Position, EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000672 DefaultArg.take());
Douglas Gregoradcac882008-12-01 23:54:00 +0000673}
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000674
Douglas Gregorcc636682009-02-17 23:15:12 +0000675/// \brief Parses a template-id that after the template name has
676/// already been parsed.
677///
678/// This routine takes care of parsing the enclosed template argument
679/// list ('<' template-parameter-list [opt] '>') and placing the
680/// results into a form that can be transferred to semantic analysis.
681///
682/// \param Template the template declaration produced by isTemplateName
683///
684/// \param TemplateNameLoc the source location of the template name
685///
686/// \param SS if non-NULL, the nested-name-specifier preceding the
687/// template name.
688///
689/// \param ConsumeLastToken if true, then we will consume the last
690/// token that forms the template-id. Otherwise, we will leave the
691/// last token in the stream (e.g., so that it can be replaced with an
692/// annotation token).
Mike Stump1eb44332009-09-09 15:08:12 +0000693bool
Douglas Gregor7532dc62009-03-30 22:58:21 +0000694Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
Mike Stump1eb44332009-09-09 15:08:12 +0000695 SourceLocation TemplateNameLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +0000696 const CXXScopeSpec &SS,
Douglas Gregorcc636682009-02-17 23:15:12 +0000697 bool ConsumeLastToken,
698 SourceLocation &LAngleLoc,
699 TemplateArgList &TemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +0000700 SourceLocation &RAngleLoc) {
701 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
702
703 // Consume the '<'.
704 LAngleLoc = ConsumeToken();
705
706 // Parse the optional template-argument-list.
707 bool Invalid = false;
708 {
709 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Douglas Gregor4f3018e2011-01-11 00:45:18 +0000710 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
Douglas Gregor314b97f2009-11-10 19:49:08 +0000711 Invalid = ParseTemplateArgumentList(TemplateArgs);
Douglas Gregorcc636682009-02-17 23:15:12 +0000712
713 if (Invalid) {
714 // Try to find the closing '>'.
715 SkipUntil(tok::greater, true, !ConsumeLastToken);
716
717 return true;
718 }
719 }
720
Richard Smith19a27022012-06-18 06:11:04 +0000721 // What will be left once we've consumed the '>'.
722 tok::TokenKind RemainingToken;
723 const char *ReplacementStr = "> >";
724
725 switch (Tok.getKind()) {
726 default:
Eli Friedman64a4eb22009-12-27 22:31:18 +0000727 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregorcc636682009-02-17 23:15:12 +0000728 return true;
Richard Smith19a27022012-06-18 06:11:04 +0000729
730 case tok::greater:
731 // Determine the location of the '>' token. Only consume this token
732 // if the caller asked us to.
733 RAngleLoc = Tok.getLocation();
734 if (ConsumeLastToken)
735 ConsumeToken();
736 return false;
737
738 case tok::greatergreater:
739 RemainingToken = tok::greater;
740 break;
741
742 case tok::greatergreatergreater:
743 RemainingToken = tok::greatergreater;
744 break;
745
746 case tok::greaterequal:
747 RemainingToken = tok::equal;
748 ReplacementStr = "> =";
749 break;
750
751 case tok::greatergreaterequal:
752 RemainingToken = tok::greaterequal;
753 break;
Eli Friedman64a4eb22009-12-27 22:31:18 +0000754 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000755
Richard Smith19a27022012-06-18 06:11:04 +0000756 // This template-id is terminated by a token which starts with a '>'. Outside
757 // C++11, this is now error recovery, and in C++11, this is error recovery if
758 // the token isn't '>>'.
759
Douglas Gregorcc636682009-02-17 23:15:12 +0000760 RAngleLoc = Tok.getLocation();
761
Richard Smith19a27022012-06-18 06:11:04 +0000762 // The source range of the '>>' or '>=' at the start of the token.
763 CharSourceRange ReplacementRange =
764 CharSourceRange::getCharRange(RAngleLoc,
765 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
766 getLangOpts()));
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000767
Richard Smith19a27022012-06-18 06:11:04 +0000768 // A hint to put a space between the '>>'s. In order to make the hint as
769 // clear as possible, we include the characters either side of the space in
770 // the replacement, rather than just inserting a space at SecondCharLoc.
771 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
772 ReplacementStr);
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000773
Richard Smith19a27022012-06-18 06:11:04 +0000774 // A hint to put another space after the token, if it would otherwise be
775 // lexed differently.
776 FixItHint Hint2;
777 Token Next = NextToken();
778 if ((RemainingToken == tok::greater ||
779 RemainingToken == tok::greatergreater) &&
780 (Next.is(tok::greater) || Next.is(tok::greatergreater) ||
781 Next.is(tok::greatergreatergreater) || Next.is(tok::equal) ||
782 Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) ||
783 Next.is(tok::equalequal)) &&
784 areTokensAdjacent(Tok, Next))
785 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
786
787 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
788 if (getLangOpts().CPlusPlus0x && Tok.is(tok::greatergreater))
789 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
790 else if (Tok.is(tok::greaterequal))
791 DiagId = diag::err_right_angle_bracket_equal_needs_space;
792 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
793
794 // Strip the initial '>' from the token.
795 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
796 areTokensAdjacent(Tok, Next)) {
797 // Join two adjacent '=' tokens into one, for cases like:
798 // void (*p)() = f<int>;
799 // return f<int>==p;
Douglas Gregorcc636682009-02-17 23:15:12 +0000800 ConsumeToken();
Richard Smith19a27022012-06-18 06:11:04 +0000801 Tok.setKind(tok::equalequal);
802 Tok.setLength(Tok.getLength() + 1);
803 } else {
804 Tok.setKind(RemainingToken);
805 Tok.setLength(Tok.getLength() - 1);
806 }
807 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
808 PP.getSourceManager(),
809 getLangOpts()));
810
811 if (!ConsumeLastToken) {
812 // Since we're not supposed to consume the '>' token, we need to push
813 // this token and revert the current token back to the '>'.
814 PP.EnterToken(Tok);
815 Tok.setKind(tok::greater);
816 Tok.setLength(1);
817 Tok.setLocation(RAngleLoc);
818 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000819
820 return false;
821}
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Douglas Gregor39a8de12009-02-25 19:37:18 +0000823/// \brief Replace the tokens that form a simple-template-id with an
824/// annotation token containing the complete template-id.
825///
826/// The first token in the stream must be the name of a template that
827/// is followed by a '<'. This routine will parse the complete
828/// simple-template-id and replace the tokens with a single annotation
829/// token with one of two different kinds: if the template-id names a
830/// type (and \p AllowTypeAnnotation is true), the annotation token is
831/// a type annotation that includes the optional nested-name-specifier
832/// (\p SS). Otherwise, the annotation token is a template-id
833/// annotation that does not include the optional
834/// nested-name-specifier.
835///
836/// \param Template the declaration of the template named by the first
837/// token (an identifier), as returned from \c Action::isTemplateName().
838///
839/// \param TemplateNameKind the kind of template that \p Template
840/// refers to, as returned from \c Action::isTemplateName().
841///
842/// \param SS if non-NULL, the nested-name-specifier that precedes
843/// this template name.
844///
845/// \param TemplateKWLoc if valid, specifies that this template-id
846/// annotation was preceded by the 'template' keyword and gives the
847/// location of that keyword. If invalid (the default), then this
848/// template-id was not preceded by a 'template' keyword.
849///
850/// \param AllowTypeAnnotation if true (the default), then a
851/// simple-template-id that refers to a class template, template
852/// template parameter, or other template that produces a type will be
853/// replaced with a type annotation token. Otherwise, the
854/// simple-template-id is always replaced with a template-id
855/// annotation token.
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000856///
857/// If an unrecoverable parse error occurs and no annotation token can be
858/// formed, this function returns true.
859///
860bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Douglas Gregor059101f2011-03-02 00:47:37 +0000861 CXXScopeSpec &SS,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000862 SourceLocation TemplateKWLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000863 UnqualifiedId &TemplateName,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000864 bool AllowTypeAnnotation) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000865 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000866 assert(Template && Tok.is(tok::less) &&
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000867 "Parser isn't at the beginning of a template-id");
868
869 // Consume the template-name.
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000870 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000871
Douglas Gregorcc636682009-02-17 23:15:12 +0000872 // Parse the enclosed template argument list.
873 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000874 TemplateArgList TemplateArgs;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000875 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
876 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000877 SS, false, LAngleLoc,
878 TemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +0000879 RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000881 if (Invalid) {
882 // If we failed to parse the template ID but skipped ahead to a >, we're not
883 // going to be able to form a token annotation. Eat the '>' if present.
884 if (Tok.is(tok::greater))
885 ConsumeToken();
886 return true;
887 }
Douglas Gregorc15cb382009-02-09 23:23:08 +0000888
Jay Foadbeaaccd2009-05-21 09:52:38 +0000889 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
Douglas Gregorcc636682009-02-17 23:15:12 +0000890 TemplateArgs.size());
Douglas Gregorf02da892009-02-09 21:04:56 +0000891
Douglas Gregor55f6b142009-02-09 18:46:07 +0000892 // Build the annotation token.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000893 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
John McCallf312b1e2010-08-26 23:41:50 +0000894 TypeResult Type
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000895 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +0000896 Template, TemplateNameLoc,
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000897 LAngleLoc, TemplateArgsPtr, RAngleLoc);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000898 if (Type.isInvalid()) {
899 // If we failed to parse the template ID but skipped ahead to a >, we're not
900 // going to be able to form a token annotation. Eat the '>' if present.
901 if (Tok.is(tok::greater))
902 ConsumeToken();
903 return true;
904 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000905
906 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000907 setTypeAnnotation(Tok, Type.get());
Douglas Gregor059101f2011-03-02 00:47:37 +0000908 if (SS.isNotEmpty())
909 Tok.setLocation(SS.getBeginLoc());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000910 else if (TemplateKWLoc.isValid())
911 Tok.setLocation(TemplateKWLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000912 else
Douglas Gregor39a8de12009-02-25 19:37:18 +0000913 Tok.setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +0000914 } else {
Douglas Gregorc45c2322009-03-31 00:43:58 +0000915 // Build a template-id annotation token that can be processed
916 // later.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000917 Tok.setKind(tok::annot_template_id);
Mike Stump1eb44332009-09-09 15:08:12 +0000918 TemplateIdAnnotation *TemplateId
Benjamin Kramer13bb7012012-04-14 12:14:03 +0000919 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000920 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000921 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
922 TemplateId->Name = TemplateName.Identifier;
923 TemplateId->Operator = OO_None;
924 } else {
925 TemplateId->Name = 0;
926 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
927 }
Douglas Gregor059101f2011-03-02 00:47:37 +0000928 TemplateId->SS = SS;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000929 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall2b5289b2010-08-23 07:28:44 +0000930 TemplateId->Template = Template;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000931 TemplateId->Kind = TNK;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000932 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000933 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregor314b97f2009-11-10 19:49:08 +0000934 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
935 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
Douglas Gregorc34348a2011-02-24 17:54:50 +0000936 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000937 Tok.setAnnotationValue(TemplateId);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000938 if (TemplateKWLoc.isValid())
939 Tok.setLocation(TemplateKWLoc);
940 else
941 Tok.setLocation(TemplateNameLoc);
942
943 TemplateArgsPtr.release();
Douglas Gregor55f6b142009-02-09 18:46:07 +0000944 }
945
946 // Common fields for the annotation token
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000947 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000948
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000949 // In case the tokens were cached, have Preprocessor replace them with the
950 // annotation token.
951 PP.AnnotateCachedTokens(Tok);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000952 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000953}
954
Douglas Gregor39a8de12009-02-25 19:37:18 +0000955/// \brief Replaces a template-id annotation token with a type
956/// annotation token.
957///
Douglas Gregor31a19b62009-04-01 21:51:26 +0000958/// If there was a failure when forming the type from the template-id,
959/// a type annotation token will still be created, but will have a
960/// NULL type pointer to signify an error.
Douglas Gregor059101f2011-03-02 00:47:37 +0000961void Parser::AnnotateTemplateIdTokenAsType() {
Douglas Gregor39a8de12009-02-25 19:37:18 +0000962 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
963
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +0000964 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000965 assert((TemplateId->Kind == TNK_Type_template ||
966 TemplateId->Kind == TNK_Dependent_template_name) &&
967 "Only works for type and dependent templates");
Mike Stump1eb44332009-09-09 15:08:12 +0000968
969 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000970 TemplateId->getTemplateArgs(),
Douglas Gregor39a8de12009-02-25 19:37:18 +0000971 TemplateId->NumArgs);
972
John McCallf312b1e2010-08-26 23:41:50 +0000973 TypeResult Type
Douglas Gregor059101f2011-03-02 00:47:37 +0000974 = Actions.ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000975 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +0000976 TemplateId->Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000977 TemplateId->TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000978 TemplateId->LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000979 TemplateArgsPtr,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000980 TemplateId->RAngleLoc);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000981 // Create the new "type" annotation token.
982 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000983 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
Douglas Gregor059101f2011-03-02 00:47:37 +0000984 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
985 Tok.setLocation(TemplateId->SS.getBeginLoc());
Sebastian Redl39d67112010-02-08 19:35:18 +0000986 // End location stays the same
Douglas Gregor39a8de12009-02-25 19:37:18 +0000987
Douglas Gregor86235412009-11-04 18:18:19 +0000988 // Replace the template-id annotation token, and possible the scope-specifier
989 // that precedes it, with the typename annotation token.
990 PP.AnnotateCachedTokens(Tok);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000991}
992
Douglas Gregor314b97f2009-11-10 19:49:08 +0000993/// \brief Determine whether the given token can end a template argument.
Benjamin Kramer3a4a2b32009-11-10 21:29:56 +0000994static bool isEndOfTemplateArgument(Token Tok) {
Douglas Gregor314b97f2009-11-10 19:49:08 +0000995 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
996 Tok.is(tok::greatergreater);
997}
998
Douglas Gregor788cd062009-11-11 01:00:40 +0000999/// \brief Parse a C++ template template argument.
1000ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1001 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1002 !Tok.is(tok::annot_cxxscope))
1003 return ParsedTemplateArgument();
1004
1005 // C++0x [temp.arg.template]p1:
1006 // A template-argument for a template template-parameter shall be the name
Richard Smith3e4c6c42011-05-05 21:57:07 +00001007 // of a class template or an alias template, expressed as id-expression.
Douglas Gregor788cd062009-11-11 01:00:40 +00001008 //
Richard Smith3e4c6c42011-05-05 21:57:07 +00001009 // We parse an id-expression that refers to a class template or alias
1010 // template. The grammar we parse is:
Douglas Gregor788cd062009-11-11 01:00:40 +00001011 //
Douglas Gregorec5e6962011-01-05 17:33:50 +00001012 // nested-name-specifier[opt] template[opt] identifier ...[opt]
Douglas Gregor788cd062009-11-11 01:00:40 +00001013 //
1014 // followed by a token that terminates a template argument, such as ',',
1015 // '>', or (in some cases) '>>'.
Douglas Gregor788cd062009-11-11 01:00:40 +00001016 CXXScopeSpec SS; // nested-name-specifier, if present
John McCallb3d87482010-08-24 05:47:05 +00001017 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001018 /*EnteringContext=*/false);
1019
Douglas Gregorec5e6962011-01-05 17:33:50 +00001020 ParsedTemplateArgument Result;
1021 SourceLocation EllipsisLoc;
Douglas Gregor788cd062009-11-11 01:00:40 +00001022 if (SS.isSet() && Tok.is(tok::kw_template)) {
1023 // Parse the optional 'template' keyword following the
1024 // nested-name-specifier.
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001025 SourceLocation TemplateKWLoc = ConsumeToken();
Douglas Gregor788cd062009-11-11 01:00:40 +00001026
1027 if (Tok.is(tok::identifier)) {
1028 // We appear to have a dependent template name.
1029 UnqualifiedId Name;
1030 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1031 ConsumeToken(); // the identifier
1032
Douglas Gregorec5e6962011-01-05 17:33:50 +00001033 // Parse the ellipsis.
1034 if (Tok.is(tok::ellipsis))
1035 EllipsisLoc = ConsumeToken();
1036
Douglas Gregor788cd062009-11-11 01:00:40 +00001037 // If the next token signals the end of a template argument,
1038 // then we have a dependent template name that could be a template
1039 // template argument.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001040 TemplateTy Template;
1041 if (isEndOfTemplateArgument(Tok) &&
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001042 Actions.ActOnDependentTemplateName(getCurScope(),
1043 SS, TemplateKWLoc, Name,
John McCallb3d87482010-08-24 05:47:05 +00001044 /*ObjectType=*/ ParsedType(),
Douglas Gregord6ab2322010-06-16 23:00:59 +00001045 /*EnteringContext=*/false,
1046 Template))
Douglas Gregorec5e6962011-01-05 17:33:50 +00001047 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregord6ab2322010-06-16 23:00:59 +00001048 }
Douglas Gregor788cd062009-11-11 01:00:40 +00001049 } else if (Tok.is(tok::identifier)) {
1050 // We may have a (non-dependent) template name.
1051 TemplateTy Template;
1052 UnqualifiedId Name;
1053 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1054 ConsumeToken(); // the identifier
1055
Douglas Gregorec5e6962011-01-05 17:33:50 +00001056 // Parse the ellipsis.
1057 if (Tok.is(tok::ellipsis))
1058 EllipsisLoc = ConsumeToken();
1059
Douglas Gregor788cd062009-11-11 01:00:40 +00001060 if (isEndOfTemplateArgument(Tok)) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001061 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001062 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1063 /*hasTemplateKeyword=*/false,
1064 Name,
John McCallb3d87482010-08-24 05:47:05 +00001065 /*ObjectType=*/ ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001066 /*EnteringContext=*/false,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001067 Template,
1068 MemberOfUnknownSpecialization);
Douglas Gregor788cd062009-11-11 01:00:40 +00001069 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1070 // We have an id-expression that refers to a class template or
Richard Smith3e4c6c42011-05-05 21:57:07 +00001071 // (C++0x) alias template.
Douglas Gregorec5e6962011-01-05 17:33:50 +00001072 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregor788cd062009-11-11 01:00:40 +00001073 }
1074 }
1075 }
1076
Douglas Gregorec5e6962011-01-05 17:33:50 +00001077 // If this is a pack expansion, build it as such.
1078 if (EllipsisLoc.isValid() && !Result.isInvalid())
1079 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1080
1081 return Result;
Douglas Gregor788cd062009-11-11 01:00:40 +00001082}
1083
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001084/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1085///
1086/// template-argument: [C++ 14.2]
Douglas Gregorac7610d2009-06-22 20:57:11 +00001087/// constant-expression
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001088/// type-id
1089/// id-expression
Douglas Gregor314b97f2009-11-10 19:49:08 +00001090ParsedTemplateArgument Parser::ParseTemplateArgument() {
Douglas Gregor55f6b142009-02-09 18:46:07 +00001091 // C++ [temp.arg]p2:
1092 // In a template-argument, an ambiguity between a type-id and an
1093 // expression is resolved to a type-id, regardless of the form of
1094 // the corresponding template-parameter.
1095 //
Douglas Gregor314b97f2009-11-10 19:49:08 +00001096 // Therefore, we initially try to parse a type-id.
Douglas Gregor8b642592009-02-10 00:53:15 +00001097 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor314b97f2009-11-10 19:49:08 +00001098 SourceLocation Loc = Tok.getLocation();
Douglas Gregor683a81f2011-01-31 16:09:46 +00001099 TypeResult TypeArg = ParseTypeName(/*Range=*/0,
1100 Declarator::TemplateTypeArgContext);
Douglas Gregor809070a2009-02-18 17:45:20 +00001101 if (TypeArg.isInvalid())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001102 return ParsedTemplateArgument();
1103
John McCallb3d87482010-08-24 05:47:05 +00001104 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1105 TypeArg.get().getAsOpaquePtr(),
Douglas Gregor314b97f2009-11-10 19:49:08 +00001106 Loc);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001107 }
Douglas Gregor788cd062009-11-11 01:00:40 +00001108
1109 // Try to parse a template template argument.
Douglas Gregoreaf75f42009-11-12 00:03:40 +00001110 {
1111 TentativeParsingAction TPA(*this);
1112
1113 ParsedTemplateArgument TemplateTemplateArgument
1114 = ParseTemplateTemplateArgument();
1115 if (!TemplateTemplateArgument.isInvalid()) {
1116 TPA.Commit();
1117 return TemplateTemplateArgument;
1118 }
1119
1120 // Revert this tentative parse to parse a non-type template argument.
1121 TPA.Revert();
1122 }
Douglas Gregor314b97f2009-11-10 19:49:08 +00001123
1124 // Parse a non-type template argument.
1125 SourceLocation Loc = Tok.getLocation();
Kaelyn Uhraine43fe992012-02-22 01:03:07 +00001126 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001127 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001128 return ParsedTemplateArgument();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001129
Douglas Gregor314b97f2009-11-10 19:49:08 +00001130 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1131 ExprArg.release(), Loc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001132}
1133
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001134/// \brief Determine whether the current tokens can only be parsed as a
1135/// template argument list (starting with the '<') and never as a '<'
1136/// expression.
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001137bool Parser::IsTemplateArgumentList(unsigned Skip) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001138 struct AlwaysRevertAction : TentativeParsingAction {
1139 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1140 ~AlwaysRevertAction() { Revert(); }
1141 } Tentative(*this);
1142
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001143 while (Skip) {
1144 ConsumeToken();
1145 --Skip;
1146 }
1147
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001148 // '<'
1149 if (!Tok.is(tok::less))
1150 return false;
1151 ConsumeToken();
1152
1153 // An empty template argument list.
1154 if (Tok.is(tok::greater))
1155 return true;
1156
1157 // See whether we have declaration specifiers, which indicate a type.
1158 while (isCXXDeclarationSpecifier() == TPResult::True())
1159 ConsumeToken();
1160
1161 // If we have a '>' or a ',' then this is a template argument list.
1162 return Tok.is(tok::greater) || Tok.is(tok::comma);
1163}
1164
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001165/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1166/// (C++ [temp.names]). Returns true if there was an error.
1167///
1168/// template-argument-list: [C++ 14.2]
1169/// template-argument
1170/// template-argument-list ',' template-argument
Mike Stump1eb44332009-09-09 15:08:12 +00001171bool
Douglas Gregor314b97f2009-11-10 19:49:08 +00001172Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001173 while (true) {
Douglas Gregor314b97f2009-11-10 19:49:08 +00001174 ParsedTemplateArgument Arg = ParseTemplateArgument();
Douglas Gregor7536dd52010-12-20 02:24:11 +00001175 if (Tok.is(tok::ellipsis)) {
1176 SourceLocation EllipsisLoc = ConsumeToken();
1177 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1178 }
1179
Douglas Gregor314b97f2009-11-10 19:49:08 +00001180 if (Arg.isInvalid()) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001181 SkipUntil(tok::comma, tok::greater, true, true);
1182 return true;
1183 }
Douglas Gregor5908e9f2009-02-09 19:34:22 +00001184
Douglas Gregor314b97f2009-11-10 19:49:08 +00001185 // Save this template argument.
1186 TemplateArgs.push_back(Arg);
1187
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001188 // If the next token is a comma, consume it and keep reading
1189 // arguments.
1190 if (Tok.isNot(tok::comma)) break;
1191
1192 // Consume the comma.
1193 ConsumeToken();
1194 }
1195
Eli Friedman64a4eb22009-12-27 22:31:18 +00001196 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001197}
1198
Mike Stump1eb44332009-09-09 15:08:12 +00001199/// \brief Parse a C++ explicit template instantiation
Douglas Gregor1426e532009-05-12 21:31:51 +00001200/// (C++ [temp.explicit]).
1201///
1202/// explicit-instantiation:
Douglas Gregor45f96552009-09-04 06:33:52 +00001203/// 'extern' [opt] 'template' declaration
1204///
1205/// Note that the 'extern' is a GNU extension and C++0x feature.
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001206Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1207 SourceLocation ExternLoc,
John McCalld226f652010-08-21 09:40:31 +00001208 SourceLocation TemplateLoc,
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001209 SourceLocation &DeclEnd,
1210 AccessSpecifier AS) {
John McCallc9068d72010-07-16 08:13:16 +00001211 // This isn't really required here.
John McCall92576642012-05-07 06:16:41 +00001212 ParsingDeclRAIIObject
1213 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
John McCallc9068d72010-07-16 08:13:16 +00001214
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001215 return ParseSingleDeclarationAfterTemplate(Context,
Douglas Gregor45f96552009-09-04 06:33:52 +00001216 ParsedTemplateInfo(ExternLoc,
1217 TemplateLoc),
John McCallc9068d72010-07-16 08:13:16 +00001218 ParsingTemplateParams,
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001219 DeclEnd, AS);
Douglas Gregor1426e532009-05-12 21:31:51 +00001220}
John McCall78b81052010-11-10 02:40:36 +00001221
1222SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1223 if (TemplateParams)
1224 return getTemplateParamsRange(TemplateParams->data(),
1225 TemplateParams->size());
1226
1227 SourceRange R(TemplateLoc);
1228 if (ExternLoc.isValid())
1229 R.setBegin(ExternLoc);
1230 return R;
1231}
Francois Pichet8387e2a2011-04-22 22:18:13 +00001232
Francois Pichet4a47e8d2011-04-23 11:52:20 +00001233void Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001234 ((Parser*)P)->LateTemplateParser(FD);
1235}
1236
1237
Francois Pichet4a47e8d2011-04-23 11:52:20 +00001238void Parser::LateTemplateParser(const FunctionDecl *FD) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001239 LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD];
1240 if (LPT) {
1241 ParseLateTemplatedFuncDef(*LPT);
1242 return;
1243 }
1244
1245 llvm_unreachable("Late templated function without associated lexed tokens");
1246}
David Blaikie219c2e22012-04-02 20:59:49 +00001247
1248/// \brief Late parse a C++ function template in Microsoft mode.
1249void Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) {
1250 if(!LMT.D)
1251 return;
1252
1253 // Get the FunctionDecl.
1254 FunctionDecl *FD = 0;
1255 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(LMT.D))
1256 FD = FunTmpl->getTemplatedDecl();
1257 else
1258 FD = cast<FunctionDecl>(LMT.D);
1259
Francois Pichetd77177a2012-02-22 08:25:53 +00001260 // To restore the context after late parsing.
David Blaikie219c2e22012-04-02 20:59:49 +00001261 Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
1262
1263 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1264 DeclaratorDecl* Declarator = dyn_cast<DeclaratorDecl>(FD);
1265 if (Declarator && Declarator->getNumTemplateParameterLists() != 0) {
1266 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::TemplateParamScope));
1267 Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
1268 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1269 } else {
1270 // Get the list of DeclContext to reenter.
1271 SmallVector<DeclContext*, 4> DeclContextToReenter;
1272 DeclContext *DD = FD->getLexicalParent();
1273 while (DD && !DD->isTranslationUnit()) {
1274 DeclContextToReenter.push_back(DD);
1275 DD = DD->getLexicalParent();
1276 }
1277
1278 // Reenter template scopes from outmost to innermost.
1279 SmallVector<DeclContext*, 4>::reverse_iterator II =
1280 DeclContextToReenter.rbegin();
1281 for (; II != DeclContextToReenter.rend(); ++II) {
1282 if (ClassTemplatePartialSpecializationDecl* MD =
1283 dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) {
1284 TemplateParamScopeStack.push_back(new ParseScope(this,
1285 Scope::TemplateParamScope));
1286 Actions.ActOnReenterTemplateScope(getCurScope(), MD);
1287 } else if (CXXRecordDecl* MD = dyn_cast_or_null<CXXRecordDecl>(*II)) {
1288 TemplateParamScopeStack.push_back(new ParseScope(this,
1289 Scope::TemplateParamScope,
1290 MD->getDescribedClassTemplate() != 0 ));
1291 Actions.ActOnReenterTemplateScope(getCurScope(),
1292 MD->getDescribedClassTemplate());
1293 }
1294 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1295 Actions.PushDeclContext(Actions.getCurScope(), *II);
1296 }
1297 TemplateParamScopeStack.push_back(new ParseScope(this,
1298 Scope::TemplateParamScope));
1299 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1300 }
1301
1302 assert(!LMT.Toks.empty() && "Empty body!");
1303
1304 // Append the current token at the end of the new token stream so that it
1305 // doesn't get lost.
1306 LMT.Toks.push_back(Tok);
1307 PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false);
1308
1309 // Consume the previously pushed token.
1310 ConsumeAnyToken();
1311 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1312 && "Inline method not starting with '{', ':' or 'try'");
1313
1314 // Parse the method body. Function body parsing code is similar enough
1315 // to be re-used for method bodies as well.
1316 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1317
1318 // Recreate the containing function DeclContext.
1319 Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FD));
1320
1321 if (FunctionTemplateDecl *FunctionTemplate
1322 = dyn_cast_or_null<FunctionTemplateDecl>(LMT.D))
1323 Actions.ActOnStartOfFunctionDef(getCurScope(),
1324 FunctionTemplate->getTemplatedDecl());
1325 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(LMT.D))
1326 Actions.ActOnStartOfFunctionDef(getCurScope(), Function);
1327
1328
1329 if (Tok.is(tok::kw_try)) {
1330 ParseFunctionTryBlock(LMT.D, FnScope);
1331 } else {
1332 if (Tok.is(tok::colon))
1333 ParseConstructorInitializer(LMT.D);
1334 else
1335 Actions.ActOnDefaultCtorInitializers(LMT.D);
1336
1337 if (Tok.is(tok::l_brace)) {
1338 ParseFunctionStatementBody(LMT.D, FnScope);
1339 Actions.MarkAsLateParsedTemplate(FD, false);
1340 } else
1341 Actions.ActOnFinishFunctionBody(LMT.D, 0);
1342 }
1343
1344 // Exit scopes.
Francois Pichetfdde4702011-09-22 22:14:56 +00001345 FnScope.Exit();
David Blaikie219c2e22012-04-02 20:59:49 +00001346 SmallVector<ParseScope*, 4>::reverse_iterator I =
1347 TemplateParamScopeStack.rbegin();
1348 for (; I != TemplateParamScopeStack.rend(); ++I)
1349 delete *I;
1350
1351 DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D);
1352 if (grp)
1353 Actions.getASTConsumer().HandleTopLevelDecl(grp.get());
Francois Pichet8387e2a2011-04-22 22:18:13 +00001354}
1355
1356/// \brief Lex a delayed template function for late parsing.
1357void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1358 tok::TokenKind kind = Tok.getKind();
Sebastian Redla891a322011-09-30 08:32:17 +00001359 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1360 // Consume everything up to (and including) the matching right brace.
1361 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001362 }
Francois Pichet8387e2a2011-04-22 22:18:13 +00001363
1364 // If we're in a function-try-block, we need to store all the catch blocks.
1365 if (kind == tok::kw_try) {
1366 while (Tok.is(tok::kw_catch)) {
1367 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1368 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1369 }
1370 }
1371}