blob: 1327dd59e557d44172e14d6b1e3c1202f83d6d16 [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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "RAIIObjectsForParser.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/DeclTemplate.h"
Chris Lattner500d3292009-01-29 05:15:15 +000018#include "clang/Parse/ParseDiagnostic.h"
John McCall19510852010-08-20 18:27:03 +000019#include "clang/Sema/DeclSpec.h"
20#include "clang/Sema/ParsedTemplate.h"
21#include "clang/Sema/Scope.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///
Douglas Gregor1426e532009-05-12 21:31:51 +0000175/// \param DeclEnd will receive the source location of the last token
176/// within this declaration.
177///
178/// \param AS the access specifier associated with this
179/// declaration. Will be AS_none for namespace-scope declarations.
180///
181/// \returns the new declaration.
John McCalld226f652010-08-21 09:40:31 +0000182Decl *
Douglas Gregor1426e532009-05-12 21:31:51 +0000183Parser::ParseSingleDeclarationAfterTemplate(
184 unsigned Context,
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000185 const ParsedTemplateInfo &TemplateInfo,
John McCallc9068d72010-07-16 08:13:16 +0000186 ParsingDeclRAIIObject &DiagsFromTParams,
Douglas Gregor1426e532009-05-12 21:31:51 +0000187 SourceLocation &DeclEnd,
Erik Verbruggen5f1c8222011-10-13 09:41:32 +0000188 AccessSpecifier AS,
189 AttributeList *AccessAttrs) {
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000190 assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate &&
191 "Template information required");
192
Douglas Gregor37b372b2009-08-20 22:52:58 +0000193 if (Context == Declarator::MemberContext) {
194 // We are parsing a member template.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +0000195 ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo,
196 &DiagsFromTParams);
John McCalld226f652010-08-21 09:40:31 +0000197 return 0;
Douglas Gregor37b372b2009-08-20 22:52:58 +0000198 }
Mike Stump1eb44332009-09-09 15:08:12 +0000199
John McCall0b7e6782011-03-24 11:26:52 +0000200 ParsedAttributesWithRange prefixAttrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +0000201 MaybeParseCXX11Attributes(prefixAttrs);
John McCall78b81052010-11-10 02:40:36 +0000202
203 if (Tok.is(tok::kw_using))
204 return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd,
John McCall7f040a92010-12-24 02:08:15 +0000205 prefixAttrs);
John McCall78b81052010-11-10 02:40:36 +0000206
John McCall92576642012-05-07 06:16:41 +0000207 // Parse the declaration specifiers, stealing any diagnostics from
208 // the template parameters.
John McCall0b7e6782011-03-24 11:26:52 +0000209 ParsingDeclSpec DS(*this, &DiagsFromTParams);
Sean Huntbbd37c62009-11-21 08:43:09 +0000210
Douglas Gregor0efc2c12010-01-13 17:31:36 +0000211 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
212 getDeclSpecContextFromDeclaratorContext(Context));
Douglas Gregor1426e532009-05-12 21:31:51 +0000213
214 if (Tok.is(tok::semi)) {
Richard Smith68ea3ae2013-02-22 09:06:26 +0000215 ProhibitAttributes(prefixAttrs);
Douglas Gregor1426e532009-05-12 21:31:51 +0000216 DeclEnd = ConsumeToken();
Richard Smithc7f81162013-03-18 22:52:47 +0000217 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(
218 getCurScope(), AS, DS,
219 TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams
220 : MultiTemplateParamsArg(),
221 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation);
John McCall54abf7d2009-11-04 02:18:39 +0000222 DS.complete(Decl);
223 return Decl;
Douglas Gregor1426e532009-05-12 21:31:51 +0000224 }
225
Richard Smith68ea3ae2013-02-22 09:06:26 +0000226 // Move the attributes from the prefix into the DS.
227 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
228 ProhibitAttributes(prefixAttrs);
229 else
230 DS.takeAttributesFrom(prefixAttrs);
231
Douglas Gregor1426e532009-05-12 21:31:51 +0000232 // Parse the declarator.
John McCall54abf7d2009-11-04 02:18:39 +0000233 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
Douglas Gregor1426e532009-05-12 21:31:51 +0000234 ParseDeclarator(DeclaratorInfo);
235 // Error parsing the declarator?
236 if (!DeclaratorInfo.hasName()) {
237 // If so, skip until the semi-colon or a }.
238 SkipUntil(tok::r_brace, true, true);
239 if (Tok.is(tok::semi))
240 ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000241 return 0;
Douglas Gregor1426e532009-05-12 21:31:51 +0000242 }
Mike Stump1eb44332009-09-09 15:08:12 +0000243
DeLesley Hutchins161db022012-11-02 21:44:32 +0000244 LateParsedAttrList LateParsedAttrs(true);
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000245 if (DeclaratorInfo.isFunctionDeclarator())
246 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
247
Douglas Gregor1426e532009-05-12 21:31:51 +0000248 if (DeclaratorInfo.isFunctionDeclarator() &&
Chris Lattner004659a2010-07-11 22:42:07 +0000249 isStartOfFunctionDefinition(DeclaratorInfo)) {
Douglas Gregor1426e532009-05-12 21:31:51 +0000250 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Smith6e1fd332011-11-29 09:09:06 +0000251 // Recover by ignoring the 'typedef'. This was probably supposed to be
252 // the 'typename' keyword, which we should have already suggested adding
253 // if it's appropriate.
254 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
255 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith874d2532011-11-29 05:27:40 +0000256 DS.ClearStorageClassSpecs();
Douglas Gregor1426e532009-05-12 21:31:51 +0000257 }
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000258 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
259 &LateParsedAttrs);
Douglas Gregor1426e532009-05-12 21:31:51 +0000260 }
261
Richard Smithd3e723e2013-01-15 06:49:38 +0000262 // Parse this declaration.
263 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
264 TemplateInfo);
265
266 if (Tok.is(tok::comma)) {
267 Diag(Tok, diag::err_multiple_template_declarators)
268 << (int)TemplateInfo.Kind;
269 SkipUntil(tok::semi, true, false);
270 return ThisDecl;
271 }
272
273 // Eat the semi colon after the declaration.
274 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
275 if (LateParsedAttrs.size() > 0)
276 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
277 DeclaratorInfo.complete(ThisDecl);
278 return ThisDecl;
Douglas Gregoradcac882008-12-01 23:54:00 +0000279}
280
281/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000282/// angle brackets. Depth is the depth of this template-parameter-list, which
283/// is the number of template headers directly enclosing this template header.
284/// TemplateParams is the current list of template parameters we're building.
285/// The template parameter we parse will be added to this list. LAngleLoc and
Mike Stump1eb44332009-09-09 15:08:12 +0000286/// RAngleLoc will receive the positions of the '<' and '>', respectively,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000287/// that enclose this template parameter list.
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000288///
289/// \returns true if an error occurred, false otherwise.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000290bool Parser::ParseTemplateParameters(unsigned Depth,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000291 SmallVectorImpl<Decl*> &TemplateParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000292 SourceLocation &LAngleLoc,
293 SourceLocation &RAngleLoc) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000294 // Get the template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +0000295 if (!Tok.is(tok::less)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000296 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000297 return true;
Douglas Gregoradcac882008-12-01 23:54:00 +0000298 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000299 LAngleLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Douglas Gregoradcac882008-12-01 23:54:00 +0000301 // Try to parse the template parameter list.
David Blaikieeb52f86a2012-04-09 16:37:11 +0000302 bool Failed = false;
303 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
304 Failed = ParseTemplateParameterList(Depth, TemplateParams);
305
306 if (Tok.is(tok::greatergreater)) {
Richard Smith19a27022012-06-18 06:11:04 +0000307 // No diagnostic required here: a template-parameter-list can only be
308 // followed by a declaration or, for a template template parameter, the
309 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
310 // This matters for elegant diagnosis of:
311 // template<template<typename>> struct S;
David Blaikieeb52f86a2012-04-09 16:37:11 +0000312 Tok.setKind(tok::greater);
313 RAngleLoc = Tok.getLocation();
314 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
315 } else if (Tok.is(tok::greater))
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000316 RAngleLoc = ConsumeToken();
David Blaikieeb52f86a2012-04-09 16:37:11 +0000317 else if (Failed) {
318 Diag(Tok.getLocation(), diag::err_expected_greater);
319 return true;
Douglas Gregoradcac882008-12-01 23:54:00 +0000320 }
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000321 return false;
Douglas Gregoradcac882008-12-01 23:54:00 +0000322}
323
324/// ParseTemplateParameterList - Parse a template parameter list. If
325/// the parsing fails badly (i.e., closing bracket was left out), this
326/// will try to put the token stream in a reasonable position (closing
Mike Stump1eb44332009-09-09 15:08:12 +0000327/// a statement, etc.) and return false.
Douglas Gregoradcac882008-12-01 23:54:00 +0000328///
329/// template-parameter-list: [C++ temp]
330/// template-parameter
331/// template-parameter-list ',' template-parameter
Mike Stump1eb44332009-09-09 15:08:12 +0000332bool
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000333Parser::ParseTemplateParameterList(unsigned Depth,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000334 SmallVectorImpl<Decl*> &TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000335 while (1) {
John McCalld226f652010-08-21 09:40:31 +0000336 if (Decl *TmpParam
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000337 = ParseTemplateParameter(Depth, TemplateParams.size())) {
338 TemplateParams.push_back(TmpParam);
339 } else {
Douglas Gregoradcac882008-12-01 23:54:00 +0000340 // If we failed to parse a template parameter, skip until we find
341 // a comma or closing brace.
David Blaikie9df1b962012-04-06 05:26:43 +0000342 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000343 }
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Nico Weber001397e2012-12-14 02:40:09 +0000345 // Did we find a comma or the end of the template parameter list?
Mike Stump1eb44332009-09-09 15:08:12 +0000346 if (Tok.is(tok::comma)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000347 ConsumeToken();
David Blaikie9df1b962012-04-06 05:26:43 +0000348 } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000349 // Don't consume this... that's done by template parser.
350 break;
351 } else {
352 // Somebody probably forgot to close the template. Skip ahead and
353 // try to get out of the expression. This error is currently
354 // subsumed by whatever goes on in ParseTemplateParameter.
Douglas Gregor99ea7342010-10-15 01:15:58 +0000355 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
David Blaikieeb52f86a2012-04-09 16:37:11 +0000356 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000357 return false;
358 }
359 }
360 return true;
361}
362
Douglas Gregor98440b42009-11-21 02:07:55 +0000363/// \brief Determine whether the parser is at the start of a template
364/// type parameter.
365bool Parser::isStartOfTemplateTypeParameter() {
Douglas Gregor7b6d25b2010-06-04 07:30:15 +0000366 if (Tok.is(tok::kw_class)) {
367 // "class" may be the start of an elaborated-type-specifier or a
368 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
369 switch (NextToken().getKind()) {
370 case tok::equal:
371 case tok::comma:
372 case tok::greater:
373 case tok::greatergreater:
374 case tok::ellipsis:
375 return true;
376
377 case tok::identifier:
378 // This may be either a type-parameter or an elaborated-type-specifier.
379 // We have to look further.
380 break;
381
382 default:
383 return false;
384 }
385
386 switch (GetLookAheadToken(2).getKind()) {
387 case tok::equal:
388 case tok::comma:
389 case tok::greater:
390 case tok::greatergreater:
391 return true;
392
393 default:
394 return false;
395 }
396 }
Douglas Gregor98440b42009-11-21 02:07:55 +0000397
398 if (Tok.isNot(tok::kw_typename))
399 return false;
400
401 // C++ [temp.param]p2:
402 // There is no semantic difference between class and typename in a
403 // template-parameter. typename followed by an unqualified-id
404 // names a template type parameter. typename followed by a
405 // qualified-id denotes the type in a non-type
406 // parameter-declaration.
407 Token Next = NextToken();
408
409 // If we have an identifier, skip over it.
410 if (Next.getKind() == tok::identifier)
411 Next = GetLookAheadToken(2);
412
413 switch (Next.getKind()) {
414 case tok::equal:
415 case tok::comma:
416 case tok::greater:
417 case tok::greatergreater:
418 case tok::ellipsis:
419 return true;
420
421 default:
422 return false;
423 }
424}
425
Douglas Gregoradcac882008-12-01 23:54:00 +0000426/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
427///
428/// template-parameter: [C++ temp.param]
429/// type-parameter
430/// parameter-declaration
431///
432/// type-parameter: (see below)
Douglas Gregor61c4d282011-01-05 15:48:55 +0000433/// 'class' ...[opt] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000434/// 'class' identifier[opt] '=' type-id
Douglas Gregor61c4d282011-01-05 15:48:55 +0000435/// 'typename' ...[opt] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000436/// 'typename' identifier[opt] '=' type-id
Douglas Gregor61c4d282011-01-05 15:48:55 +0000437/// 'template' '<' template-parameter-list '>'
438/// 'class' ...[opt] identifier[opt]
439/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
440/// = id-expression
John McCalld226f652010-08-21 09:40:31 +0000441Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor98440b42009-11-21 02:07:55 +0000442 if (isStartOfTemplateTypeParameter())
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000443 return ParseTypeParameter(Depth, Position);
Mike Stump1eb44332009-09-09 15:08:12 +0000444
445 if (Tok.is(tok::kw_template))
Chris Lattner532e19b2009-01-04 23:51:17 +0000446 return ParseTemplateTemplateParameter(Depth, Position);
447
448 // If it's none of the above, then it must be a parameter declaration.
449 // NOTE: This will pick up errors in the closure of the template parameter
450 // list (e.g., template < ; Check here to implement >> style closures.
451 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000452}
453
454/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
455/// Other kinds of template parameters are parsed in
456/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
457///
458/// type-parameter: [C++ temp.param]
Anders Carlssonce5635a2009-06-12 23:09:56 +0000459/// 'class' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000460/// 'class' identifier[opt] '=' type-id
Anders Carlssonce5635a2009-06-12 23:09:56 +0000461/// 'typename' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000462/// 'typename' identifier[opt] '=' type-id
John McCalld226f652010-08-21 09:40:31 +0000463Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000464 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
Mike Stump1eb44332009-09-09 15:08:12 +0000465 "A type-parameter starts with 'class' or 'typename'");
Douglas Gregor26236e82008-12-02 00:41:28 +0000466
467 // Consume the 'class' or 'typename' keyword.
468 bool TypenameKeyword = Tok.is(tok::kw_typename);
469 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000470
Anders Carlsson941df7d2009-06-12 19:58:00 +0000471 // Grab the ellipsis (if given).
472 bool Ellipsis = false;
473 SourceLocation EllipsisLoc;
Anders Carlssonce5635a2009-06-12 23:09:56 +0000474 if (Tok.is(tok::ellipsis)) {
Anders Carlsson941df7d2009-06-12 19:58:00 +0000475 Ellipsis = true;
476 EllipsisLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Richard Smithe5acd132011-10-14 20:31:37 +0000478 Diag(EllipsisLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +0000479 getLangOpts().CPlusPlus11
Richard Smithe5acd132011-10-14 20:31:37 +0000480 ? diag::warn_cxx98_compat_variadic_templates
481 : diag::ext_variadic_templates);
Anders Carlsson941df7d2009-06-12 19:58:00 +0000482 }
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Douglas Gregoradcac882008-12-01 23:54:00 +0000484 // Grab the template parameter name (if given)
Douglas Gregor26236e82008-12-02 00:41:28 +0000485 SourceLocation NameLoc;
486 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000487 if (Tok.is(tok::identifier)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000488 ParamName = Tok.getIdentifierInfo();
489 NameLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000490 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
David Blaikie9df1b962012-04-06 05:26:43 +0000491 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000492 // Unnamed template parameter. Don't have to do anything here, just
493 // don't consume this token.
494 } else {
495 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000496 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000497 }
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000499 // Grab a default argument (if available).
500 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
501 // we introduce the type parameter into the local scope.
502 SourceLocation EqualLoc;
John McCallb3d87482010-08-24 05:47:05 +0000503 ParsedType DefaultArg;
Mike Stump1eb44332009-09-09 15:08:12 +0000504 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000505 EqualLoc = ConsumeToken();
Richard Smithd37b3602012-02-10 11:05:11 +0000506 DefaultArg = ParseTypeName(/*Range=*/0,
507 Declarator::TemplateTypeArgContext).get();
Douglas Gregoradcac882008-12-01 23:54:00 +0000508 }
Richard Smithd37b3602012-02-10 11:05:11 +0000509
Douglas Gregor23c94db2010-07-02 17:43:08 +0000510 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000511 EllipsisLoc, KeyLoc, ParamName, NameLoc,
512 Depth, Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000513}
514
515/// ParseTemplateTemplateParameter - Handle the parsing of template
Mike Stump1eb44332009-09-09 15:08:12 +0000516/// template parameters.
Douglas Gregoradcac882008-12-01 23:54:00 +0000517///
518/// type-parameter: [C++ temp.param]
Douglas Gregor61c4d282011-01-05 15:48:55 +0000519/// 'template' '<' template-parameter-list '>' 'class'
520/// ...[opt] identifier[opt]
521/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
522/// = id-expression
John McCalld226f652010-08-21 09:40:31 +0000523Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000524Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000525 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
526
527 // Handle the template <...> part.
528 SourceLocation TemplateLoc = ConsumeToken();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000529 SmallVector<Decl*,8> TemplateParams;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000530 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor68c69932009-02-10 19:52:54 +0000531 {
532 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000533 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000534 RAngleLoc)) {
John McCalld226f652010-08-21 09:40:31 +0000535 return 0;
Douglas Gregor68c69932009-02-10 19:52:54 +0000536 }
Douglas Gregoradcac882008-12-01 23:54:00 +0000537 }
538
539 // Generate a meaningful error if the user forgot to put class before the
David Blaikie9df1b962012-04-06 05:26:43 +0000540 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
541 // or greater appear immediately or after 'typename' or 'struct'. In the
542 // latter case, replace the keyword with 'class'.
543 if (!Tok.is(tok::kw_class)) {
544 bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
545 const Token& Next = Replace ? NextToken() : Tok;
546 if (Next.is(tok::identifier) || Next.is(tok::comma) ||
547 Next.is(tok::greater) || Next.is(tok::greatergreater) ||
548 Next.is(tok::ellipsis))
549 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
550 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
551 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
552 else
553 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
554
555 if (Replace)
556 ConsumeToken();
557 } else
David Blaikie460ef132012-04-02 19:15:28 +0000558 ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000559
Douglas Gregor61c4d282011-01-05 15:48:55 +0000560 // Parse the ellipsis, if given.
561 SourceLocation EllipsisLoc;
562 if (Tok.is(tok::ellipsis)) {
563 EllipsisLoc = ConsumeToken();
564
Richard Smithe5acd132011-10-14 20:31:37 +0000565 Diag(EllipsisLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +0000566 getLangOpts().CPlusPlus11
Richard Smithe5acd132011-10-14 20:31:37 +0000567 ? diag::warn_cxx98_compat_variadic_templates
568 : diag::ext_variadic_templates);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000569 }
570
Douglas Gregoradcac882008-12-01 23:54:00 +0000571 // Get the identifier, if given.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000572 SourceLocation NameLoc;
573 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000574 if (Tok.is(tok::identifier)) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000575 ParamName = Tok.getIdentifierInfo();
576 NameLoc = ConsumeToken();
David Blaikie9df1b962012-04-06 05:26:43 +0000577 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
578 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000579 // Unnamed template parameter. Don't have to do anything here, just
580 // don't consume this token.
581 } else {
582 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000583 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000584 }
585
Richard Trieu90ab75b2011-09-09 03:18:59 +0000586 TemplateParameterList *ParamList =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000587 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
588 TemplateLoc, LAngleLoc,
Douglas Gregor369ea272010-10-21 17:26:49 +0000589 TemplateParams.data(),
Douglas Gregorddc29e12009-02-06 22:42:48 +0000590 TemplateParams.size(),
591 RAngleLoc);
592
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000593 // Grab a default argument (if available).
594 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
595 // we introduce the template parameter into the local scope.
596 SourceLocation EqualLoc;
597 ParsedTemplateArgument DefaultArg;
Douglas Gregord684b002009-02-10 19:49:53 +0000598 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000599 EqualLoc = ConsumeToken();
600 DefaultArg = ParseTemplateTemplateArgument();
601 if (DefaultArg.isInvalid()) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000602 Diag(Tok.getLocation(),
603 diag::err_default_template_template_parameter_not_template);
David Blaikieeb52f86a2012-04-09 16:37:11 +0000604 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000605 }
Douglas Gregord684b002009-02-10 19:49:53 +0000606 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000607
Douglas Gregor23c94db2010-07-02 17:43:08 +0000608 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000609 ParamList, EllipsisLoc,
610 ParamName, NameLoc, Depth,
611 Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000612}
613
614/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
Mike Stump1eb44332009-09-09 15:08:12 +0000615/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000616///
Douglas Gregoradcac882008-12-01 23:54:00 +0000617/// template-parameter:
618/// ...
619/// parameter-declaration
John McCalld226f652010-08-21 09:40:31 +0000620Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000621Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000622 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor26236e82008-12-02 00:41:28 +0000623 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregoradcac882008-12-01 23:54:00 +0000624 // declarators (parts of declarators?) are accepted for parameters.
John McCall0b7e6782011-03-24 11:26:52 +0000625 DeclSpec DS(AttrFactory);
Douglas Gregor26236e82008-12-02 00:41:28 +0000626 ParseDeclarationSpecifiers(DS);
Douglas Gregoradcac882008-12-01 23:54:00 +0000627
628 // Parse this as a typename.
Douglas Gregor26236e82008-12-02 00:41:28 +0000629 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
630 ParseDeclarator(ParamDecl);
John McCallb3d87482010-08-24 05:47:05 +0000631 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
David Blaikieb031eab2012-04-06 23:33:59 +0000632 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
John McCalld226f652010-08-21 09:40:31 +0000633 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000634 }
635
Douglas Gregord684b002009-02-10 19:49:53 +0000636 // If there is a default value, parse it.
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000637 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
638 // we introduce the template parameter into the local scope.
639 SourceLocation EqualLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000640 ExprResult DefaultArg;
Chris Lattner7452c6f2009-01-05 01:24:05 +0000641 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000642 EqualLoc = ConsumeToken();
Douglas Gregord684b002009-02-10 19:49:53 +0000643
644 // C++ [temp.param]p15:
645 // When parsing a default template-argument for a non-type
646 // template-parameter, the first non-nested > is taken as the
647 // end of the template-parameter-list rather than a greater-than
648 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +0000649 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Eli Friedman9b94cd12012-04-26 22:43:24 +0000650 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
Douglas Gregord684b002009-02-10 19:49:53 +0000651
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000652 DefaultArg = ParseAssignmentExpression();
Douglas Gregord684b002009-02-10 19:49:53 +0000653 if (DefaultArg.isInvalid())
654 SkipUntil(tok::comma, tok::greater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000655 }
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000657 // Create the parameter.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000658 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000659 Depth, Position, EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000660 DefaultArg.take());
Douglas Gregoradcac882008-12-01 23:54:00 +0000661}
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000662
Nico Weberb707a472012-12-14 18:22:38 +0000663/// \brief Parses a '>' at the end of a template list.
Douglas Gregorcc636682009-02-17 23:15:12 +0000664///
Nico Weberb707a472012-12-14 18:22:38 +0000665/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
666/// to determine if these tokens were supposed to be a '>' followed by
667/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
Douglas Gregorcc636682009-02-17 23:15:12 +0000668///
Nico Weberb707a472012-12-14 18:22:38 +0000669/// \param RAngleLoc the location of the consumed '>'.
Douglas Gregorcc636682009-02-17 23:15:12 +0000670///
Nico Weberb707a472012-12-14 18:22:38 +0000671/// \param ConsumeLastToken if true, the '>' is not consumed.
672bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
673 bool ConsumeLastToken) {
Richard Smith19a27022012-06-18 06:11:04 +0000674 // What will be left once we've consumed the '>'.
675 tok::TokenKind RemainingToken;
676 const char *ReplacementStr = "> >";
677
678 switch (Tok.getKind()) {
679 default:
Eli Friedman64a4eb22009-12-27 22:31:18 +0000680 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregorcc636682009-02-17 23:15:12 +0000681 return true;
Richard Smith19a27022012-06-18 06:11:04 +0000682
683 case tok::greater:
684 // Determine the location of the '>' token. Only consume this token
685 // if the caller asked us to.
686 RAngleLoc = Tok.getLocation();
687 if (ConsumeLastToken)
688 ConsumeToken();
689 return false;
690
691 case tok::greatergreater:
692 RemainingToken = tok::greater;
693 break;
694
695 case tok::greatergreatergreater:
696 RemainingToken = tok::greatergreater;
697 break;
698
699 case tok::greaterequal:
700 RemainingToken = tok::equal;
701 ReplacementStr = "> =";
702 break;
703
704 case tok::greatergreaterequal:
705 RemainingToken = tok::greaterequal;
706 break;
Eli Friedman64a4eb22009-12-27 22:31:18 +0000707 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000708
Richard Smith19a27022012-06-18 06:11:04 +0000709 // This template-id is terminated by a token which starts with a '>'. Outside
710 // C++11, this is now error recovery, and in C++11, this is error recovery if
711 // the token isn't '>>'.
712
Douglas Gregorcc636682009-02-17 23:15:12 +0000713 RAngleLoc = Tok.getLocation();
714
Richard Smith19a27022012-06-18 06:11:04 +0000715 // The source range of the '>>' or '>=' at the start of the token.
716 CharSourceRange ReplacementRange =
717 CharSourceRange::getCharRange(RAngleLoc,
718 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
719 getLangOpts()));
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000720
Richard Smith19a27022012-06-18 06:11:04 +0000721 // A hint to put a space between the '>>'s. In order to make the hint as
722 // clear as possible, we include the characters either side of the space in
723 // the replacement, rather than just inserting a space at SecondCharLoc.
724 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
725 ReplacementStr);
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000726
Richard Smith19a27022012-06-18 06:11:04 +0000727 // A hint to put another space after the token, if it would otherwise be
728 // lexed differently.
729 FixItHint Hint2;
730 Token Next = NextToken();
731 if ((RemainingToken == tok::greater ||
732 RemainingToken == tok::greatergreater) &&
733 (Next.is(tok::greater) || Next.is(tok::greatergreater) ||
734 Next.is(tok::greatergreatergreater) || Next.is(tok::equal) ||
735 Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) ||
736 Next.is(tok::equalequal)) &&
737 areTokensAdjacent(Tok, Next))
738 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
739
740 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
Richard Smith80ad52f2013-01-02 11:42:31 +0000741 if (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater))
Richard Smith19a27022012-06-18 06:11:04 +0000742 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
743 else if (Tok.is(tok::greaterequal))
744 DiagId = diag::err_right_angle_bracket_equal_needs_space;
745 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
746
747 // Strip the initial '>' from the token.
748 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
749 areTokensAdjacent(Tok, Next)) {
750 // Join two adjacent '=' tokens into one, for cases like:
751 // void (*p)() = f<int>;
752 // return f<int>==p;
Douglas Gregorcc636682009-02-17 23:15:12 +0000753 ConsumeToken();
Richard Smith19a27022012-06-18 06:11:04 +0000754 Tok.setKind(tok::equalequal);
755 Tok.setLength(Tok.getLength() + 1);
756 } else {
757 Tok.setKind(RemainingToken);
758 Tok.setLength(Tok.getLength() - 1);
759 }
760 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
761 PP.getSourceManager(),
762 getLangOpts()));
763
764 if (!ConsumeLastToken) {
765 // Since we're not supposed to consume the '>' token, we need to push
766 // this token and revert the current token back to the '>'.
767 PP.EnterToken(Tok);
768 Tok.setKind(tok::greater);
769 Tok.setLength(1);
770 Tok.setLocation(RAngleLoc);
771 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000772 return false;
773}
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Nico Weberb707a472012-12-14 18:22:38 +0000775
776/// \brief Parses a template-id that after the template name has
777/// already been parsed.
778///
779/// This routine takes care of parsing the enclosed template argument
780/// list ('<' template-parameter-list [opt] '>') and placing the
781/// results into a form that can be transferred to semantic analysis.
782///
783/// \param Template the template declaration produced by isTemplateName
784///
785/// \param TemplateNameLoc the source location of the template name
786///
787/// \param SS if non-NULL, the nested-name-specifier preceding the
788/// template name.
789///
790/// \param ConsumeLastToken if true, then we will consume the last
791/// token that forms the template-id. Otherwise, we will leave the
792/// last token in the stream (e.g., so that it can be replaced with an
793/// annotation token).
794bool
795Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
796 SourceLocation TemplateNameLoc,
797 const CXXScopeSpec &SS,
798 bool ConsumeLastToken,
799 SourceLocation &LAngleLoc,
800 TemplateArgList &TemplateArgs,
801 SourceLocation &RAngleLoc) {
802 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
803
804 // Consume the '<'.
805 LAngleLoc = ConsumeToken();
806
807 // Parse the optional template-argument-list.
808 bool Invalid = false;
809 {
810 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
811 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
812 Invalid = ParseTemplateArgumentList(TemplateArgs);
813
814 if (Invalid) {
815 // Try to find the closing '>'.
816 SkipUntil(tok::greater, true, !ConsumeLastToken);
817
818 return true;
819 }
820 }
821
822 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken);
823}
824
Douglas Gregor39a8de12009-02-25 19:37:18 +0000825/// \brief Replace the tokens that form a simple-template-id with an
826/// annotation token containing the complete template-id.
827///
828/// The first token in the stream must be the name of a template that
829/// is followed by a '<'. This routine will parse the complete
830/// simple-template-id and replace the tokens with a single annotation
831/// token with one of two different kinds: if the template-id names a
832/// type (and \p AllowTypeAnnotation is true), the annotation token is
833/// a type annotation that includes the optional nested-name-specifier
834/// (\p SS). Otherwise, the annotation token is a template-id
835/// annotation that does not include the optional
836/// nested-name-specifier.
837///
838/// \param Template the declaration of the template named by the first
839/// token (an identifier), as returned from \c Action::isTemplateName().
840///
NAKAMURA Takumi384d3fc2012-11-14 02:21:42 +0000841/// \param TNK the kind of template that \p Template
Douglas Gregor39a8de12009-02-25 19:37:18 +0000842/// refers to, as returned from \c Action::isTemplateName().
843///
844/// \param SS if non-NULL, the nested-name-specifier that precedes
845/// this template name.
846///
847/// \param TemplateKWLoc if valid, specifies that this template-id
848/// annotation was preceded by the 'template' keyword and gives the
849/// location of that keyword. If invalid (the default), then this
850/// template-id was not preceded by a 'template' keyword.
851///
852/// \param AllowTypeAnnotation if true (the default), then a
853/// simple-template-id that refers to a class template, template
854/// template parameter, or other template that produces a type will be
855/// replaced with a type annotation token. Otherwise, the
856/// simple-template-id is always replaced with a template-id
857/// annotation token.
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000858///
859/// If an unrecoverable parse error occurs and no annotation token can be
860/// formed, this function returns true.
861///
862bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Douglas Gregor059101f2011-03-02 00:47:37 +0000863 CXXScopeSpec &SS,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000864 SourceLocation TemplateKWLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000865 UnqualifiedId &TemplateName,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000866 bool AllowTypeAnnotation) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000867 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000868 assert(Template && Tok.is(tok::less) &&
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000869 "Parser isn't at the beginning of a template-id");
870
871 // Consume the template-name.
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000872 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000873
Douglas Gregorcc636682009-02-17 23:15:12 +0000874 // Parse the enclosed template argument list.
875 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000876 TemplateArgList TemplateArgs;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000877 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
878 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000879 SS, false, LAngleLoc,
880 TemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +0000881 RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000883 if (Invalid) {
884 // If we failed to parse the template ID but skipped ahead to a >, we're not
885 // going to be able to form a token annotation. Eat the '>' if present.
886 if (Tok.is(tok::greater))
887 ConsumeToken();
888 return true;
889 }
Douglas Gregorc15cb382009-02-09 23:23:08 +0000890
Benjamin Kramer5354e772012-08-23 23:38:35 +0000891 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Douglas Gregorf02da892009-02-09 21:04:56 +0000892
Douglas Gregor55f6b142009-02-09 18:46:07 +0000893 // Build the annotation token.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000894 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
John McCallf312b1e2010-08-26 23:41:50 +0000895 TypeResult Type
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000896 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +0000897 Template, TemplateNameLoc,
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000898 LAngleLoc, TemplateArgsPtr, RAngleLoc);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000899 if (Type.isInvalid()) {
900 // If we failed to parse the template ID but skipped ahead to a >, we're not
901 // going to be able to form a token annotation. Eat the '>' if present.
902 if (Tok.is(tok::greater))
903 ConsumeToken();
904 return true;
905 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000906
907 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000908 setTypeAnnotation(Tok, Type.get());
Douglas Gregor059101f2011-03-02 00:47:37 +0000909 if (SS.isNotEmpty())
910 Tok.setLocation(SS.getBeginLoc());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000911 else if (TemplateKWLoc.isValid())
912 Tok.setLocation(TemplateKWLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000913 else
Douglas Gregor39a8de12009-02-25 19:37:18 +0000914 Tok.setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +0000915 } else {
Douglas Gregorc45c2322009-03-31 00:43:58 +0000916 // Build a template-id annotation token that can be processed
917 // later.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000918 Tok.setKind(tok::annot_template_id);
Mike Stump1eb44332009-09-09 15:08:12 +0000919 TemplateIdAnnotation *TemplateId
Benjamin Kramer13bb7012012-04-14 12:14:03 +0000920 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000921 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000922 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
923 TemplateId->Name = TemplateName.Identifier;
924 TemplateId->Operator = OO_None;
925 } else {
926 TemplateId->Name = 0;
927 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
928 }
Douglas Gregor059101f2011-03-02 00:47:37 +0000929 TemplateId->SS = SS;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000930 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall2b5289b2010-08-23 07:28:44 +0000931 TemplateId->Template = Template;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000932 TemplateId->Kind = TNK;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000933 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000934 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregor314b97f2009-11-10 19:49:08 +0000935 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
936 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
Douglas Gregorc34348a2011-02-24 17:54:50 +0000937 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000938 Tok.setAnnotationValue(TemplateId);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000939 if (TemplateKWLoc.isValid())
940 Tok.setLocation(TemplateKWLoc);
941 else
942 Tok.setLocation(TemplateNameLoc);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000943 }
944
945 // Common fields for the annotation token
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000946 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000947
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000948 // In case the tokens were cached, have Preprocessor replace them with the
949 // annotation token.
950 PP.AnnotateCachedTokens(Tok);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000951 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000952}
953
Douglas Gregor39a8de12009-02-25 19:37:18 +0000954/// \brief Replaces a template-id annotation token with a type
955/// annotation token.
956///
Douglas Gregor31a19b62009-04-01 21:51:26 +0000957/// If there was a failure when forming the type from the template-id,
958/// a type annotation token will still be created, but will have a
959/// NULL type pointer to signify an error.
Douglas Gregor059101f2011-03-02 00:47:37 +0000960void Parser::AnnotateTemplateIdTokenAsType() {
Douglas Gregor39a8de12009-02-25 19:37:18 +0000961 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
962
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +0000963 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000964 assert((TemplateId->Kind == TNK_Type_template ||
965 TemplateId->Kind == TNK_Dependent_template_name) &&
966 "Only works for type and dependent templates");
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Benjamin Kramer5354e772012-08-23 23:38:35 +0000968 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor39a8de12009-02-25 19:37:18 +0000969 TemplateId->NumArgs);
970
John McCallf312b1e2010-08-26 23:41:50 +0000971 TypeResult Type
Douglas Gregor059101f2011-03-02 00:47:37 +0000972 = Actions.ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000973 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +0000974 TemplateId->Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000975 TemplateId->TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000976 TemplateId->LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000977 TemplateArgsPtr,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000978 TemplateId->RAngleLoc);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000979 // Create the new "type" annotation token.
980 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000981 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
Douglas Gregor059101f2011-03-02 00:47:37 +0000982 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
983 Tok.setLocation(TemplateId->SS.getBeginLoc());
Sebastian Redl39d67112010-02-08 19:35:18 +0000984 // End location stays the same
Douglas Gregor39a8de12009-02-25 19:37:18 +0000985
Douglas Gregor86235412009-11-04 18:18:19 +0000986 // Replace the template-id annotation token, and possible the scope-specifier
987 // that precedes it, with the typename annotation token.
988 PP.AnnotateCachedTokens(Tok);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000989}
990
Douglas Gregor314b97f2009-11-10 19:49:08 +0000991/// \brief Determine whether the given token can end a template argument.
Benjamin Kramer3a4a2b32009-11-10 21:29:56 +0000992static bool isEndOfTemplateArgument(Token Tok) {
Douglas Gregor314b97f2009-11-10 19:49:08 +0000993 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
994 Tok.is(tok::greatergreater);
995}
996
Douglas Gregor788cd062009-11-11 01:00:40 +0000997/// \brief Parse a C++ template template argument.
998ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
999 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1000 !Tok.is(tok::annot_cxxscope))
1001 return ParsedTemplateArgument();
1002
1003 // C++0x [temp.arg.template]p1:
1004 // A template-argument for a template template-parameter shall be the name
Richard Smith3e4c6c42011-05-05 21:57:07 +00001005 // of a class template or an alias template, expressed as id-expression.
Douglas Gregor788cd062009-11-11 01:00:40 +00001006 //
Richard Smith3e4c6c42011-05-05 21:57:07 +00001007 // We parse an id-expression that refers to a class template or alias
1008 // template. The grammar we parse is:
Douglas Gregor788cd062009-11-11 01:00:40 +00001009 //
Douglas Gregorec5e6962011-01-05 17:33:50 +00001010 // nested-name-specifier[opt] template[opt] identifier ...[opt]
Douglas Gregor788cd062009-11-11 01:00:40 +00001011 //
1012 // followed by a token that terminates a template argument, such as ',',
1013 // '>', or (in some cases) '>>'.
Douglas Gregor788cd062009-11-11 01:00:40 +00001014 CXXScopeSpec SS; // nested-name-specifier, if present
John McCallb3d87482010-08-24 05:47:05 +00001015 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001016 /*EnteringContext=*/false);
1017
Douglas Gregorec5e6962011-01-05 17:33:50 +00001018 ParsedTemplateArgument Result;
1019 SourceLocation EllipsisLoc;
Douglas Gregor788cd062009-11-11 01:00:40 +00001020 if (SS.isSet() && Tok.is(tok::kw_template)) {
1021 // Parse the optional 'template' keyword following the
1022 // nested-name-specifier.
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001023 SourceLocation TemplateKWLoc = ConsumeToken();
Douglas Gregor788cd062009-11-11 01:00:40 +00001024
1025 if (Tok.is(tok::identifier)) {
1026 // We appear to have a dependent template name.
1027 UnqualifiedId Name;
1028 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1029 ConsumeToken(); // the identifier
1030
Douglas Gregorec5e6962011-01-05 17:33:50 +00001031 // Parse the ellipsis.
1032 if (Tok.is(tok::ellipsis))
1033 EllipsisLoc = ConsumeToken();
1034
Douglas Gregor788cd062009-11-11 01:00:40 +00001035 // If the next token signals the end of a template argument,
1036 // then we have a dependent template name that could be a template
1037 // template argument.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001038 TemplateTy Template;
1039 if (isEndOfTemplateArgument(Tok) &&
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001040 Actions.ActOnDependentTemplateName(getCurScope(),
1041 SS, TemplateKWLoc, Name,
John McCallb3d87482010-08-24 05:47:05 +00001042 /*ObjectType=*/ ParsedType(),
Douglas Gregord6ab2322010-06-16 23:00:59 +00001043 /*EnteringContext=*/false,
1044 Template))
Douglas Gregorec5e6962011-01-05 17:33:50 +00001045 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregord6ab2322010-06-16 23:00:59 +00001046 }
Douglas Gregor788cd062009-11-11 01:00:40 +00001047 } else if (Tok.is(tok::identifier)) {
1048 // We may have a (non-dependent) template name.
1049 TemplateTy Template;
1050 UnqualifiedId Name;
1051 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1052 ConsumeToken(); // the identifier
1053
Douglas Gregorec5e6962011-01-05 17:33:50 +00001054 // Parse the ellipsis.
1055 if (Tok.is(tok::ellipsis))
1056 EllipsisLoc = ConsumeToken();
1057
Douglas Gregor788cd062009-11-11 01:00:40 +00001058 if (isEndOfTemplateArgument(Tok)) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001059 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001060 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1061 /*hasTemplateKeyword=*/false,
1062 Name,
John McCallb3d87482010-08-24 05:47:05 +00001063 /*ObjectType=*/ ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001064 /*EnteringContext=*/false,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001065 Template,
1066 MemberOfUnknownSpecialization);
Douglas Gregor788cd062009-11-11 01:00:40 +00001067 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1068 // We have an id-expression that refers to a class template or
Richard Smith3e4c6c42011-05-05 21:57:07 +00001069 // (C++0x) alias template.
Douglas Gregorec5e6962011-01-05 17:33:50 +00001070 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregor788cd062009-11-11 01:00:40 +00001071 }
1072 }
1073 }
1074
Douglas Gregorec5e6962011-01-05 17:33:50 +00001075 // If this is a pack expansion, build it as such.
1076 if (EllipsisLoc.isValid() && !Result.isInvalid())
1077 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1078
1079 return Result;
Douglas Gregor788cd062009-11-11 01:00:40 +00001080}
1081
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001082/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1083///
1084/// template-argument: [C++ 14.2]
Douglas Gregorac7610d2009-06-22 20:57:11 +00001085/// constant-expression
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001086/// type-id
1087/// id-expression
Douglas Gregor314b97f2009-11-10 19:49:08 +00001088ParsedTemplateArgument Parser::ParseTemplateArgument() {
Douglas Gregor55f6b142009-02-09 18:46:07 +00001089 // C++ [temp.arg]p2:
1090 // In a template-argument, an ambiguity between a type-id and an
1091 // expression is resolved to a type-id, regardless of the form of
1092 // the corresponding template-parameter.
1093 //
Douglas Gregor314b97f2009-11-10 19:49:08 +00001094 // Therefore, we initially try to parse a type-id.
Douglas Gregor8b642592009-02-10 00:53:15 +00001095 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor314b97f2009-11-10 19:49:08 +00001096 SourceLocation Loc = Tok.getLocation();
Douglas Gregor683a81f2011-01-31 16:09:46 +00001097 TypeResult TypeArg = ParseTypeName(/*Range=*/0,
1098 Declarator::TemplateTypeArgContext);
Douglas Gregor809070a2009-02-18 17:45:20 +00001099 if (TypeArg.isInvalid())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001100 return ParsedTemplateArgument();
1101
John McCallb3d87482010-08-24 05:47:05 +00001102 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1103 TypeArg.get().getAsOpaquePtr(),
Douglas Gregor314b97f2009-11-10 19:49:08 +00001104 Loc);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001105 }
Douglas Gregor788cd062009-11-11 01:00:40 +00001106
1107 // Try to parse a template template argument.
Douglas Gregoreaf75f42009-11-12 00:03:40 +00001108 {
1109 TentativeParsingAction TPA(*this);
1110
1111 ParsedTemplateArgument TemplateTemplateArgument
1112 = ParseTemplateTemplateArgument();
1113 if (!TemplateTemplateArgument.isInvalid()) {
1114 TPA.Commit();
1115 return TemplateTemplateArgument;
1116 }
1117
1118 // Revert this tentative parse to parse a non-type template argument.
1119 TPA.Revert();
1120 }
Douglas Gregor314b97f2009-11-10 19:49:08 +00001121
1122 // Parse a non-type template argument.
1123 SourceLocation Loc = Tok.getLocation();
Kaelyn Uhraine43fe992012-02-22 01:03:07 +00001124 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001125 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001126 return ParsedTemplateArgument();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001127
Douglas Gregor314b97f2009-11-10 19:49:08 +00001128 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1129 ExprArg.release(), Loc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001130}
1131
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001132/// \brief Determine whether the current tokens can only be parsed as a
1133/// template argument list (starting with the '<') and never as a '<'
1134/// expression.
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001135bool Parser::IsTemplateArgumentList(unsigned Skip) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001136 struct AlwaysRevertAction : TentativeParsingAction {
1137 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1138 ~AlwaysRevertAction() { Revert(); }
1139 } Tentative(*this);
1140
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001141 while (Skip) {
1142 ConsumeToken();
1143 --Skip;
1144 }
1145
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001146 // '<'
1147 if (!Tok.is(tok::less))
1148 return false;
1149 ConsumeToken();
1150
1151 // An empty template argument list.
1152 if (Tok.is(tok::greater))
1153 return true;
1154
1155 // See whether we have declaration specifiers, which indicate a type.
1156 while (isCXXDeclarationSpecifier() == TPResult::True())
1157 ConsumeToken();
1158
1159 // If we have a '>' or a ',' then this is a template argument list.
1160 return Tok.is(tok::greater) || Tok.is(tok::comma);
1161}
1162
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001163/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1164/// (C++ [temp.names]). Returns true if there was an error.
1165///
1166/// template-argument-list: [C++ 14.2]
1167/// template-argument
1168/// template-argument-list ',' template-argument
Mike Stump1eb44332009-09-09 15:08:12 +00001169bool
Douglas Gregor314b97f2009-11-10 19:49:08 +00001170Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001171 while (true) {
Douglas Gregor314b97f2009-11-10 19:49:08 +00001172 ParsedTemplateArgument Arg = ParseTemplateArgument();
Douglas Gregor7536dd52010-12-20 02:24:11 +00001173 if (Tok.is(tok::ellipsis)) {
1174 SourceLocation EllipsisLoc = ConsumeToken();
1175 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1176 }
1177
Douglas Gregor314b97f2009-11-10 19:49:08 +00001178 if (Arg.isInvalid()) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001179 SkipUntil(tok::comma, tok::greater, true, true);
1180 return true;
1181 }
Douglas Gregor5908e9f2009-02-09 19:34:22 +00001182
Douglas Gregor314b97f2009-11-10 19:49:08 +00001183 // Save this template argument.
1184 TemplateArgs.push_back(Arg);
1185
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001186 // If the next token is a comma, consume it and keep reading
1187 // arguments.
1188 if (Tok.isNot(tok::comma)) break;
1189
1190 // Consume the comma.
1191 ConsumeToken();
1192 }
1193
Eli Friedman64a4eb22009-12-27 22:31:18 +00001194 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001195}
1196
Mike Stump1eb44332009-09-09 15:08:12 +00001197/// \brief Parse a C++ explicit template instantiation
Douglas Gregor1426e532009-05-12 21:31:51 +00001198/// (C++ [temp.explicit]).
1199///
1200/// explicit-instantiation:
Douglas Gregor45f96552009-09-04 06:33:52 +00001201/// 'extern' [opt] 'template' declaration
1202///
Richard Smithc7f81162013-03-18 22:52:47 +00001203/// Note that the 'extern' is a GNU extension and C++11 feature.
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001204Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1205 SourceLocation ExternLoc,
John McCalld226f652010-08-21 09:40:31 +00001206 SourceLocation TemplateLoc,
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001207 SourceLocation &DeclEnd,
1208 AccessSpecifier AS) {
John McCallc9068d72010-07-16 08:13:16 +00001209 // This isn't really required here.
John McCall92576642012-05-07 06:16:41 +00001210 ParsingDeclRAIIObject
1211 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
John McCallc9068d72010-07-16 08:13:16 +00001212
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001213 return ParseSingleDeclarationAfterTemplate(Context,
Douglas Gregor45f96552009-09-04 06:33:52 +00001214 ParsedTemplateInfo(ExternLoc,
1215 TemplateLoc),
John McCallc9068d72010-07-16 08:13:16 +00001216 ParsingTemplateParams,
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001217 DeclEnd, AS);
Douglas Gregor1426e532009-05-12 21:31:51 +00001218}
John McCall78b81052010-11-10 02:40:36 +00001219
1220SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1221 if (TemplateParams)
1222 return getTemplateParamsRange(TemplateParams->data(),
1223 TemplateParams->size());
1224
1225 SourceRange R(TemplateLoc);
1226 if (ExternLoc.isValid())
1227 R.setBegin(ExternLoc);
1228 return R;
1229}
Francois Pichet8387e2a2011-04-22 22:18:13 +00001230
Francois Pichet4a47e8d2011-04-23 11:52:20 +00001231void Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001232 ((Parser*)P)->LateTemplateParser(FD);
1233}
1234
1235
Francois Pichet4a47e8d2011-04-23 11:52:20 +00001236void Parser::LateTemplateParser(const FunctionDecl *FD) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001237 LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD];
1238 if (LPT) {
1239 ParseLateTemplatedFuncDef(*LPT);
1240 return;
1241 }
1242
1243 llvm_unreachable("Late templated function without associated lexed tokens");
1244}
David Blaikie219c2e22012-04-02 20:59:49 +00001245
1246/// \brief Late parse a C++ function template in Microsoft mode.
1247void Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) {
1248 if(!LMT.D)
1249 return;
1250
1251 // Get the FunctionDecl.
1252 FunctionDecl *FD = 0;
1253 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(LMT.D))
1254 FD = FunTmpl->getTemplatedDecl();
1255 else
1256 FD = cast<FunctionDecl>(LMT.D);
1257
Francois Pichetd77177a2012-02-22 08:25:53 +00001258 // To restore the context after late parsing.
David Blaikie219c2e22012-04-02 20:59:49 +00001259 Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
1260
1261 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1262 DeclaratorDecl* Declarator = dyn_cast<DeclaratorDecl>(FD);
1263 if (Declarator && Declarator->getNumTemplateParameterLists() != 0) {
1264 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::TemplateParamScope));
1265 Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
1266 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1267 } else {
1268 // Get the list of DeclContext to reenter.
1269 SmallVector<DeclContext*, 4> DeclContextToReenter;
1270 DeclContext *DD = FD->getLexicalParent();
1271 while (DD && !DD->isTranslationUnit()) {
1272 DeclContextToReenter.push_back(DD);
1273 DD = DD->getLexicalParent();
1274 }
1275
1276 // Reenter template scopes from outmost to innermost.
1277 SmallVector<DeclContext*, 4>::reverse_iterator II =
1278 DeclContextToReenter.rbegin();
1279 for (; II != DeclContextToReenter.rend(); ++II) {
1280 if (ClassTemplatePartialSpecializationDecl* MD =
1281 dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) {
1282 TemplateParamScopeStack.push_back(new ParseScope(this,
1283 Scope::TemplateParamScope));
1284 Actions.ActOnReenterTemplateScope(getCurScope(), MD);
1285 } else if (CXXRecordDecl* MD = dyn_cast_or_null<CXXRecordDecl>(*II)) {
1286 TemplateParamScopeStack.push_back(new ParseScope(this,
1287 Scope::TemplateParamScope,
1288 MD->getDescribedClassTemplate() != 0 ));
1289 Actions.ActOnReenterTemplateScope(getCurScope(),
1290 MD->getDescribedClassTemplate());
1291 }
1292 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1293 Actions.PushDeclContext(Actions.getCurScope(), *II);
1294 }
1295 TemplateParamScopeStack.push_back(new ParseScope(this,
1296 Scope::TemplateParamScope));
1297 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1298 }
1299
1300 assert(!LMT.Toks.empty() && "Empty body!");
1301
1302 // Append the current token at the end of the new token stream so that it
1303 // doesn't get lost.
1304 LMT.Toks.push_back(Tok);
1305 PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false);
1306
1307 // Consume the previously pushed token.
1308 ConsumeAnyToken();
1309 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1310 && "Inline method not starting with '{', ':' or 'try'");
1311
1312 // Parse the method body. Function body parsing code is similar enough
1313 // to be re-used for method bodies as well.
1314 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1315
1316 // Recreate the containing function DeclContext.
1317 Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FD));
1318
1319 if (FunctionTemplateDecl *FunctionTemplate
1320 = dyn_cast_or_null<FunctionTemplateDecl>(LMT.D))
1321 Actions.ActOnStartOfFunctionDef(getCurScope(),
1322 FunctionTemplate->getTemplatedDecl());
1323 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(LMT.D))
1324 Actions.ActOnStartOfFunctionDef(getCurScope(), Function);
1325
1326
1327 if (Tok.is(tok::kw_try)) {
1328 ParseFunctionTryBlock(LMT.D, FnScope);
1329 } else {
1330 if (Tok.is(tok::colon))
1331 ParseConstructorInitializer(LMT.D);
1332 else
1333 Actions.ActOnDefaultCtorInitializers(LMT.D);
1334
1335 if (Tok.is(tok::l_brace)) {
1336 ParseFunctionStatementBody(LMT.D, FnScope);
1337 Actions.MarkAsLateParsedTemplate(FD, false);
1338 } else
1339 Actions.ActOnFinishFunctionBody(LMT.D, 0);
1340 }
1341
1342 // Exit scopes.
Francois Pichetfdde4702011-09-22 22:14:56 +00001343 FnScope.Exit();
David Blaikie219c2e22012-04-02 20:59:49 +00001344 SmallVector<ParseScope*, 4>::reverse_iterator I =
1345 TemplateParamScopeStack.rbegin();
1346 for (; I != TemplateParamScopeStack.rend(); ++I)
1347 delete *I;
1348
1349 DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D);
1350 if (grp)
1351 Actions.getASTConsumer().HandleTopLevelDecl(grp.get());
Francois Pichet8387e2a2011-04-22 22:18:13 +00001352}
1353
1354/// \brief Lex a delayed template function for late parsing.
1355void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1356 tok::TokenKind kind = Tok.getKind();
Sebastian Redla891a322011-09-30 08:32:17 +00001357 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1358 // Consume everything up to (and including) the matching right brace.
1359 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001360 }
Francois Pichet8387e2a2011-04-22 22:18:13 +00001361
1362 // If we're in a function-try-block, we need to store all the catch blocks.
1363 if (kind == tok::kw_try) {
1364 while (Tok.is(tok::kw_catch)) {
1365 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1366 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1367 }
1368 }
1369}