blob: 155d333fa84c7a7b5ac7198b02a48cad319417e6 [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
John McCall92576642012-05-07 06:16:41 +0000211 // Move the attributes from the prefix into the DS.
Sean Hunt2edf0a22012-06-23 05:07:58 +0000212 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation)
213 ProhibitAttributes(prefixAttrs);
214 else
215 DS.takeAttributesFrom(prefixAttrs);
Sean Huntbbd37c62009-11-21 08:43:09 +0000216
Douglas Gregor0efc2c12010-01-13 17:31:36 +0000217 ParseDeclarationSpecifiers(DS, TemplateInfo, AS,
218 getDeclSpecContextFromDeclaratorContext(Context));
Douglas Gregor1426e532009-05-12 21:31:51 +0000219
220 if (Tok.is(tok::semi)) {
221 DeclEnd = ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000222 Decl *Decl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS);
John McCall54abf7d2009-11-04 02:18:39 +0000223 DS.complete(Decl);
224 return Decl;
Douglas Gregor1426e532009-05-12 21:31:51 +0000225 }
226
227 // Parse the declarator.
John McCall54abf7d2009-11-04 02:18:39 +0000228 ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context);
Douglas Gregor1426e532009-05-12 21:31:51 +0000229 ParseDeclarator(DeclaratorInfo);
230 // Error parsing the declarator?
231 if (!DeclaratorInfo.hasName()) {
232 // If so, skip until the semi-colon or a }.
233 SkipUntil(tok::r_brace, true, true);
234 if (Tok.is(tok::semi))
235 ConsumeToken();
John McCalld226f652010-08-21 09:40:31 +0000236 return 0;
Douglas Gregor1426e532009-05-12 21:31:51 +0000237 }
Mike Stump1eb44332009-09-09 15:08:12 +0000238
DeLesley Hutchins161db022012-11-02 21:44:32 +0000239 LateParsedAttrList LateParsedAttrs(true);
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000240 if (DeclaratorInfo.isFunctionDeclarator())
241 MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs);
242
Douglas Gregor1426e532009-05-12 21:31:51 +0000243 // If we have a declaration or declarator list, handle it.
244 if (isDeclarationAfterDeclarator()) {
245 // Parse this declaration.
John McCalld226f652010-08-21 09:40:31 +0000246 Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo,
247 TemplateInfo);
Douglas Gregor1426e532009-05-12 21:31:51 +0000248
249 if (Tok.is(tok::comma)) {
250 Diag(Tok, diag::err_multiple_template_declarators)
Douglas Gregor4d9a16f2009-05-12 23:25:50 +0000251 << (int)TemplateInfo.Kind;
Douglas Gregor1426e532009-05-12 21:31:51 +0000252 SkipUntil(tok::semi, true, false);
253 return ThisDecl;
254 }
255
256 // Eat the semi colon after the declaration.
Chris Lattner8bb21d32012-04-28 16:12:17 +0000257 ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000258 if (LateParsedAttrs.size() > 0)
259 ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false);
John McCalleee1d542011-02-14 07:13:47 +0000260 DeclaratorInfo.complete(ThisDecl);
Douglas Gregor1426e532009-05-12 21:31:51 +0000261 return ThisDecl;
262 }
263
264 if (DeclaratorInfo.isFunctionDeclarator() &&
Chris Lattner004659a2010-07-11 22:42:07 +0000265 isStartOfFunctionDefinition(DeclaratorInfo)) {
Douglas Gregor1426e532009-05-12 21:31:51 +0000266 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
Richard Smith6e1fd332011-11-29 09:09:06 +0000267 // Recover by ignoring the 'typedef'. This was probably supposed to be
268 // the 'typename' keyword, which we should have already suggested adding
269 // if it's appropriate.
270 Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef)
271 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
Richard Smith874d2532011-11-29 05:27:40 +0000272 DS.ClearStorageClassSpecs();
Douglas Gregor1426e532009-05-12 21:31:51 +0000273 }
DeLesley Hutchinsc24a2332012-02-16 16:50:43 +0000274 return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo,
275 &LateParsedAttrs);
Douglas Gregor1426e532009-05-12 21:31:51 +0000276 }
277
278 if (DeclaratorInfo.isFunctionDeclarator())
279 Diag(Tok, diag::err_expected_fn_body);
280 else
281 Diag(Tok, diag::err_invalid_token_after_toplevel_declarator);
282 SkipUntil(tok::semi);
John McCalld226f652010-08-21 09:40:31 +0000283 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000284}
285
286/// ParseTemplateParameters - Parses a template-parameter-list enclosed in
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000287/// angle brackets. Depth is the depth of this template-parameter-list, which
288/// is the number of template headers directly enclosing this template header.
289/// TemplateParams is the current list of template parameters we're building.
290/// The template parameter we parse will be added to this list. LAngleLoc and
Mike Stump1eb44332009-09-09 15:08:12 +0000291/// RAngleLoc will receive the positions of the '<' and '>', respectively,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000292/// that enclose this template parameter list.
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000293///
294/// \returns true if an error occurred, false otherwise.
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000295bool Parser::ParseTemplateParameters(unsigned Depth,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000296 SmallVectorImpl<Decl*> &TemplateParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000297 SourceLocation &LAngleLoc,
298 SourceLocation &RAngleLoc) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000299 // Get the template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +0000300 if (!Tok.is(tok::less)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000301 Diag(Tok.getLocation(), diag::err_expected_less_after) << "template";
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000302 return true;
Douglas Gregoradcac882008-12-01 23:54:00 +0000303 }
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000304 LAngleLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Douglas Gregoradcac882008-12-01 23:54:00 +0000306 // Try to parse the template parameter list.
David Blaikieeb52f86a2012-04-09 16:37:11 +0000307 bool Failed = false;
308 if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater))
309 Failed = ParseTemplateParameterList(Depth, TemplateParams);
310
311 if (Tok.is(tok::greatergreater)) {
Richard Smith19a27022012-06-18 06:11:04 +0000312 // No diagnostic required here: a template-parameter-list can only be
313 // followed by a declaration or, for a template template parameter, the
314 // 'class' keyword. Therefore, the second '>' will be diagnosed later.
315 // This matters for elegant diagnosis of:
316 // template<template<typename>> struct S;
David Blaikieeb52f86a2012-04-09 16:37:11 +0000317 Tok.setKind(tok::greater);
318 RAngleLoc = Tok.getLocation();
319 Tok.setLocation(Tok.getLocation().getLocWithOffset(1));
320 } else if (Tok.is(tok::greater))
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000321 RAngleLoc = ConsumeToken();
David Blaikieeb52f86a2012-04-09 16:37:11 +0000322 else if (Failed) {
323 Diag(Tok.getLocation(), diag::err_expected_greater);
324 return true;
Douglas Gregoradcac882008-12-01 23:54:00 +0000325 }
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000326 return false;
Douglas Gregoradcac882008-12-01 23:54:00 +0000327}
328
329/// ParseTemplateParameterList - Parse a template parameter list. If
330/// the parsing fails badly (i.e., closing bracket was left out), this
331/// will try to put the token stream in a reasonable position (closing
Mike Stump1eb44332009-09-09 15:08:12 +0000332/// a statement, etc.) and return false.
Douglas Gregoradcac882008-12-01 23:54:00 +0000333///
334/// template-parameter-list: [C++ temp]
335/// template-parameter
336/// template-parameter-list ',' template-parameter
Mike Stump1eb44332009-09-09 15:08:12 +0000337bool
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000338Parser::ParseTemplateParameterList(unsigned Depth,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000339 SmallVectorImpl<Decl*> &TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +0000340 while (1) {
John McCalld226f652010-08-21 09:40:31 +0000341 if (Decl *TmpParam
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000342 = ParseTemplateParameter(Depth, TemplateParams.size())) {
343 TemplateParams.push_back(TmpParam);
344 } else {
Douglas Gregoradcac882008-12-01 23:54:00 +0000345 // If we failed to parse a template parameter, skip until we find
346 // a comma or closing brace.
David Blaikie9df1b962012-04-06 05:26:43 +0000347 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000348 }
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Nico Weber001397e2012-12-14 02:40:09 +0000350 // Did we find a comma or the end of the template parameter list?
Mike Stump1eb44332009-09-09 15:08:12 +0000351 if (Tok.is(tok::comma)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000352 ConsumeToken();
David Blaikie9df1b962012-04-06 05:26:43 +0000353 } else if (Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000354 // Don't consume this... that's done by template parser.
355 break;
356 } else {
357 // Somebody probably forgot to close the template. Skip ahead and
358 // try to get out of the expression. This error is currently
359 // subsumed by whatever goes on in ParseTemplateParameter.
Douglas Gregor99ea7342010-10-15 01:15:58 +0000360 Diag(Tok.getLocation(), diag::err_expected_comma_greater);
David Blaikieeb52f86a2012-04-09 16:37:11 +0000361 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000362 return false;
363 }
364 }
365 return true;
366}
367
Douglas Gregor98440b42009-11-21 02:07:55 +0000368/// \brief Determine whether the parser is at the start of a template
369/// type parameter.
370bool Parser::isStartOfTemplateTypeParameter() {
Douglas Gregor7b6d25b2010-06-04 07:30:15 +0000371 if (Tok.is(tok::kw_class)) {
372 // "class" may be the start of an elaborated-type-specifier or a
373 // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter.
374 switch (NextToken().getKind()) {
375 case tok::equal:
376 case tok::comma:
377 case tok::greater:
378 case tok::greatergreater:
379 case tok::ellipsis:
380 return true;
381
382 case tok::identifier:
383 // This may be either a type-parameter or an elaborated-type-specifier.
384 // We have to look further.
385 break;
386
387 default:
388 return false;
389 }
390
391 switch (GetLookAheadToken(2).getKind()) {
392 case tok::equal:
393 case tok::comma:
394 case tok::greater:
395 case tok::greatergreater:
396 return true;
397
398 default:
399 return false;
400 }
401 }
Douglas Gregor98440b42009-11-21 02:07:55 +0000402
403 if (Tok.isNot(tok::kw_typename))
404 return false;
405
406 // C++ [temp.param]p2:
407 // There is no semantic difference between class and typename in a
408 // template-parameter. typename followed by an unqualified-id
409 // names a template type parameter. typename followed by a
410 // qualified-id denotes the type in a non-type
411 // parameter-declaration.
412 Token Next = NextToken();
413
414 // If we have an identifier, skip over it.
415 if (Next.getKind() == tok::identifier)
416 Next = GetLookAheadToken(2);
417
418 switch (Next.getKind()) {
419 case tok::equal:
420 case tok::comma:
421 case tok::greater:
422 case tok::greatergreater:
423 case tok::ellipsis:
424 return true;
425
426 default:
427 return false;
428 }
429}
430
Douglas Gregoradcac882008-12-01 23:54:00 +0000431/// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]).
432///
433/// template-parameter: [C++ temp.param]
434/// type-parameter
435/// parameter-declaration
436///
437/// type-parameter: (see below)
Douglas Gregor61c4d282011-01-05 15:48:55 +0000438/// 'class' ...[opt] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000439/// 'class' identifier[opt] '=' type-id
Douglas Gregor61c4d282011-01-05 15:48:55 +0000440/// 'typename' ...[opt] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000441/// 'typename' identifier[opt] '=' type-id
Douglas Gregor61c4d282011-01-05 15:48:55 +0000442/// 'template' '<' template-parameter-list '>'
443/// 'class' ...[opt] identifier[opt]
444/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
445/// = id-expression
John McCalld226f652010-08-21 09:40:31 +0000446Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregor98440b42009-11-21 02:07:55 +0000447 if (isStartOfTemplateTypeParameter())
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000448 return ParseTypeParameter(Depth, Position);
Mike Stump1eb44332009-09-09 15:08:12 +0000449
450 if (Tok.is(tok::kw_template))
Chris Lattner532e19b2009-01-04 23:51:17 +0000451 return ParseTemplateTemplateParameter(Depth, Position);
452
453 // If it's none of the above, then it must be a parameter declaration.
454 // NOTE: This will pick up errors in the closure of the template parameter
455 // list (e.g., template < ; Check here to implement >> style closures.
456 return ParseNonTypeTemplateParameter(Depth, Position);
Douglas Gregoradcac882008-12-01 23:54:00 +0000457}
458
459/// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]).
460/// Other kinds of template parameters are parsed in
461/// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter.
462///
463/// type-parameter: [C++ temp.param]
Anders Carlssonce5635a2009-06-12 23:09:56 +0000464/// 'class' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000465/// 'class' identifier[opt] '=' type-id
Anders Carlssonce5635a2009-06-12 23:09:56 +0000466/// 'typename' ...[opt][C++0x] identifier[opt]
Douglas Gregoradcac882008-12-01 23:54:00 +0000467/// 'typename' identifier[opt] '=' type-id
John McCalld226f652010-08-21 09:40:31 +0000468Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000469 assert((Tok.is(tok::kw_class) || Tok.is(tok::kw_typename)) &&
Mike Stump1eb44332009-09-09 15:08:12 +0000470 "A type-parameter starts with 'class' or 'typename'");
Douglas Gregor26236e82008-12-02 00:41:28 +0000471
472 // Consume the 'class' or 'typename' keyword.
473 bool TypenameKeyword = Tok.is(tok::kw_typename);
474 SourceLocation KeyLoc = ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000475
Anders Carlsson941df7d2009-06-12 19:58:00 +0000476 // Grab the ellipsis (if given).
477 bool Ellipsis = false;
478 SourceLocation EllipsisLoc;
Anders Carlssonce5635a2009-06-12 23:09:56 +0000479 if (Tok.is(tok::ellipsis)) {
Anders Carlsson941df7d2009-06-12 19:58:00 +0000480 Ellipsis = true;
481 EllipsisLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Richard Smithe5acd132011-10-14 20:31:37 +0000483 Diag(EllipsisLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +0000484 getLangOpts().CPlusPlus11
Richard Smithe5acd132011-10-14 20:31:37 +0000485 ? diag::warn_cxx98_compat_variadic_templates
486 : diag::ext_variadic_templates);
Anders Carlsson941df7d2009-06-12 19:58:00 +0000487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Douglas Gregoradcac882008-12-01 23:54:00 +0000489 // Grab the template parameter name (if given)
Douglas Gregor26236e82008-12-02 00:41:28 +0000490 SourceLocation NameLoc;
491 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000492 if (Tok.is(tok::identifier)) {
Douglas Gregor26236e82008-12-02 00:41:28 +0000493 ParamName = Tok.getIdentifierInfo();
494 NameLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000495 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
David Blaikie9df1b962012-04-06 05:26:43 +0000496 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000497 // Unnamed template parameter. Don't have to do anything here, just
498 // don't consume this token.
499 } else {
500 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000501 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000502 }
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000504 // Grab a default argument (if available).
505 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
506 // we introduce the type parameter into the local scope.
507 SourceLocation EqualLoc;
John McCallb3d87482010-08-24 05:47:05 +0000508 ParsedType DefaultArg;
Mike Stump1eb44332009-09-09 15:08:12 +0000509 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000510 EqualLoc = ConsumeToken();
Richard Smithd37b3602012-02-10 11:05:11 +0000511 DefaultArg = ParseTypeName(/*Range=*/0,
512 Declarator::TemplateTypeArgContext).get();
Douglas Gregoradcac882008-12-01 23:54:00 +0000513 }
Richard Smithd37b3602012-02-10 11:05:11 +0000514
Douglas Gregor23c94db2010-07-02 17:43:08 +0000515 return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, Ellipsis,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000516 EllipsisLoc, KeyLoc, ParamName, NameLoc,
517 Depth, Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000518}
519
520/// ParseTemplateTemplateParameter - Handle the parsing of template
Mike Stump1eb44332009-09-09 15:08:12 +0000521/// template parameters.
Douglas Gregoradcac882008-12-01 23:54:00 +0000522///
523/// type-parameter: [C++ temp.param]
Douglas Gregor61c4d282011-01-05 15:48:55 +0000524/// 'template' '<' template-parameter-list '>' 'class'
525/// ...[opt] identifier[opt]
526/// 'template' '<' template-parameter-list '>' 'class' identifier[opt]
527/// = id-expression
John McCalld226f652010-08-21 09:40:31 +0000528Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000529Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000530 assert(Tok.is(tok::kw_template) && "Expected 'template' keyword");
531
532 // Handle the template <...> part.
533 SourceLocation TemplateLoc = ConsumeToken();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000534 SmallVector<Decl*,8> TemplateParams;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000535 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor68c69932009-02-10 19:52:54 +0000536 {
537 ParseScope TemplateParmScope(this, Scope::TemplateParamScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000538 if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc,
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000539 RAngleLoc)) {
John McCalld226f652010-08-21 09:40:31 +0000540 return 0;
Douglas Gregor68c69932009-02-10 19:52:54 +0000541 }
Douglas Gregoradcac882008-12-01 23:54:00 +0000542 }
543
544 // Generate a meaningful error if the user forgot to put class before the
David Blaikie9df1b962012-04-06 05:26:43 +0000545 // identifier, comma, or greater. Provide a fixit if the identifier, comma,
546 // or greater appear immediately or after 'typename' or 'struct'. In the
547 // latter case, replace the keyword with 'class'.
548 if (!Tok.is(tok::kw_class)) {
549 bool Replace = Tok.is(tok::kw_typename) || Tok.is(tok::kw_struct);
550 const Token& Next = Replace ? NextToken() : Tok;
551 if (Next.is(tok::identifier) || Next.is(tok::comma) ||
552 Next.is(tok::greater) || Next.is(tok::greatergreater) ||
553 Next.is(tok::ellipsis))
554 Diag(Tok.getLocation(), diag::err_class_on_template_template_param)
555 << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class")
556 : FixItHint::CreateInsertion(Tok.getLocation(), "class "));
557 else
558 Diag(Tok.getLocation(), diag::err_class_on_template_template_param);
559
560 if (Replace)
561 ConsumeToken();
562 } else
David Blaikie460ef132012-04-02 19:15:28 +0000563 ConsumeToken();
Douglas Gregoradcac882008-12-01 23:54:00 +0000564
Douglas Gregor61c4d282011-01-05 15:48:55 +0000565 // Parse the ellipsis, if given.
566 SourceLocation EllipsisLoc;
567 if (Tok.is(tok::ellipsis)) {
568 EllipsisLoc = ConsumeToken();
569
Richard Smithe5acd132011-10-14 20:31:37 +0000570 Diag(EllipsisLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +0000571 getLangOpts().CPlusPlus11
Richard Smithe5acd132011-10-14 20:31:37 +0000572 ? diag::warn_cxx98_compat_variadic_templates
573 : diag::ext_variadic_templates);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000574 }
575
Douglas Gregoradcac882008-12-01 23:54:00 +0000576 // Get the identifier, if given.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000577 SourceLocation NameLoc;
578 IdentifierInfo* ParamName = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000579 if (Tok.is(tok::identifier)) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000580 ParamName = Tok.getIdentifierInfo();
581 NameLoc = ConsumeToken();
David Blaikie9df1b962012-04-06 05:26:43 +0000582 } else if (Tok.is(tok::equal) || Tok.is(tok::comma) ||
583 Tok.is(tok::greater) || Tok.is(tok::greatergreater)) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000584 // Unnamed template parameter. Don't have to do anything here, just
585 // don't consume this token.
586 } else {
587 Diag(Tok.getLocation(), diag::err_expected_ident);
John McCalld226f652010-08-21 09:40:31 +0000588 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000589 }
590
Richard Trieu90ab75b2011-09-09 03:18:59 +0000591 TemplateParameterList *ParamList =
Douglas Gregorddc29e12009-02-06 22:42:48 +0000592 Actions.ActOnTemplateParameterList(Depth, SourceLocation(),
593 TemplateLoc, LAngleLoc,
Douglas Gregor369ea272010-10-21 17:26:49 +0000594 TemplateParams.data(),
Douglas Gregorddc29e12009-02-06 22:42:48 +0000595 TemplateParams.size(),
596 RAngleLoc);
597
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000598 // Grab a default argument (if available).
599 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
600 // we introduce the template parameter into the local scope.
601 SourceLocation EqualLoc;
602 ParsedTemplateArgument DefaultArg;
Douglas Gregord684b002009-02-10 19:49:53 +0000603 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000604 EqualLoc = ConsumeToken();
605 DefaultArg = ParseTemplateTemplateArgument();
606 if (DefaultArg.isInvalid()) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000607 Diag(Tok.getLocation(),
608 diag::err_default_template_template_parameter_not_template);
David Blaikieeb52f86a2012-04-09 16:37:11 +0000609 SkipUntil(tok::comma, tok::greater, tok::greatergreater, true, true);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000610 }
Douglas Gregord684b002009-02-10 19:49:53 +0000611 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000612
Douglas Gregor23c94db2010-07-02 17:43:08 +0000613 return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc,
Douglas Gregor61c4d282011-01-05 15:48:55 +0000614 ParamList, EllipsisLoc,
615 ParamName, NameLoc, Depth,
616 Position, EqualLoc, DefaultArg);
Douglas Gregoradcac882008-12-01 23:54:00 +0000617}
618
619/// ParseNonTypeTemplateParameter - Handle the parsing of non-type
Mike Stump1eb44332009-09-09 15:08:12 +0000620/// template parameters (e.g., in "template<int Size> class array;").
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000621///
Douglas Gregoradcac882008-12-01 23:54:00 +0000622/// template-parameter:
623/// ...
624/// parameter-declaration
John McCalld226f652010-08-21 09:40:31 +0000625Decl *
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000626Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) {
Douglas Gregoradcac882008-12-01 23:54:00 +0000627 // Parse the declaration-specifiers (i.e., the type).
Douglas Gregor26236e82008-12-02 00:41:28 +0000628 // FIXME: The type should probably be restricted in some way... Not all
Douglas Gregoradcac882008-12-01 23:54:00 +0000629 // declarators (parts of declarators?) are accepted for parameters.
John McCall0b7e6782011-03-24 11:26:52 +0000630 DeclSpec DS(AttrFactory);
Douglas Gregor26236e82008-12-02 00:41:28 +0000631 ParseDeclarationSpecifiers(DS);
Douglas Gregoradcac882008-12-01 23:54:00 +0000632
633 // Parse this as a typename.
Douglas Gregor26236e82008-12-02 00:41:28 +0000634 Declarator ParamDecl(DS, Declarator::TemplateParamContext);
635 ParseDeclarator(ParamDecl);
John McCallb3d87482010-08-24 05:47:05 +0000636 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
David Blaikieb031eab2012-04-06 23:33:59 +0000637 Diag(Tok.getLocation(), diag::err_expected_template_parameter);
John McCalld226f652010-08-21 09:40:31 +0000638 return 0;
Douglas Gregoradcac882008-12-01 23:54:00 +0000639 }
640
Douglas Gregord684b002009-02-10 19:49:53 +0000641 // If there is a default value, parse it.
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000642 // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before
643 // we introduce the template parameter into the local scope.
644 SourceLocation EqualLoc;
John McCall60d7b3a2010-08-24 06:29:42 +0000645 ExprResult DefaultArg;
Chris Lattner7452c6f2009-01-05 01:24:05 +0000646 if (Tok.is(tok::equal)) {
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000647 EqualLoc = ConsumeToken();
Douglas Gregord684b002009-02-10 19:49:53 +0000648
649 // C++ [temp.param]p15:
650 // When parsing a default template-argument for a non-type
651 // template-parameter, the first non-nested > is taken as the
652 // end of the template-parameter-list rather than a greater-than
653 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +0000654 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
Eli Friedman9b94cd12012-04-26 22:43:24 +0000655 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
Douglas Gregord684b002009-02-10 19:49:53 +0000656
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000657 DefaultArg = ParseAssignmentExpression();
Douglas Gregord684b002009-02-10 19:49:53 +0000658 if (DefaultArg.isInvalid())
659 SkipUntil(tok::comma, tok::greater, true, true);
Douglas Gregoradcac882008-12-01 23:54:00 +0000660 }
Mike Stump1eb44332009-09-09 15:08:12 +0000661
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000662 // Create the parameter.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000663 return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000664 Depth, Position, EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000665 DefaultArg.take());
Douglas Gregoradcac882008-12-01 23:54:00 +0000666}
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000667
Nico Weberb707a472012-12-14 18:22:38 +0000668/// \brief Parses a '>' at the end of a template list.
Douglas Gregorcc636682009-02-17 23:15:12 +0000669///
Nico Weberb707a472012-12-14 18:22:38 +0000670/// If this function encounters '>>', '>>>', '>=', or '>>=', it tries
671/// to determine if these tokens were supposed to be a '>' followed by
672/// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary.
Douglas Gregorcc636682009-02-17 23:15:12 +0000673///
Nico Weberb707a472012-12-14 18:22:38 +0000674/// \param RAngleLoc the location of the consumed '>'.
Douglas Gregorcc636682009-02-17 23:15:12 +0000675///
Nico Weberb707a472012-12-14 18:22:38 +0000676/// \param ConsumeLastToken if true, the '>' is not consumed.
677bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
678 bool ConsumeLastToken) {
Richard Smith19a27022012-06-18 06:11:04 +0000679 // What will be left once we've consumed the '>'.
680 tok::TokenKind RemainingToken;
681 const char *ReplacementStr = "> >";
682
683 switch (Tok.getKind()) {
684 default:
Eli Friedman64a4eb22009-12-27 22:31:18 +0000685 Diag(Tok.getLocation(), diag::err_expected_greater);
Douglas Gregorcc636682009-02-17 23:15:12 +0000686 return true;
Richard Smith19a27022012-06-18 06:11:04 +0000687
688 case tok::greater:
689 // Determine the location of the '>' token. Only consume this token
690 // if the caller asked us to.
691 RAngleLoc = Tok.getLocation();
692 if (ConsumeLastToken)
693 ConsumeToken();
694 return false;
695
696 case tok::greatergreater:
697 RemainingToken = tok::greater;
698 break;
699
700 case tok::greatergreatergreater:
701 RemainingToken = tok::greatergreater;
702 break;
703
704 case tok::greaterequal:
705 RemainingToken = tok::equal;
706 ReplacementStr = "> =";
707 break;
708
709 case tok::greatergreaterequal:
710 RemainingToken = tok::greaterequal;
711 break;
Eli Friedman64a4eb22009-12-27 22:31:18 +0000712 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000713
Richard Smith19a27022012-06-18 06:11:04 +0000714 // This template-id is terminated by a token which starts with a '>'. Outside
715 // C++11, this is now error recovery, and in C++11, this is error recovery if
716 // the token isn't '>>'.
717
Douglas Gregorcc636682009-02-17 23:15:12 +0000718 RAngleLoc = Tok.getLocation();
719
Richard Smith19a27022012-06-18 06:11:04 +0000720 // The source range of the '>>' or '>=' at the start of the token.
721 CharSourceRange ReplacementRange =
722 CharSourceRange::getCharRange(RAngleLoc,
723 Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(),
724 getLangOpts()));
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000725
Richard Smith19a27022012-06-18 06:11:04 +0000726 // A hint to put a space between the '>>'s. In order to make the hint as
727 // clear as possible, we include the characters either side of the space in
728 // the replacement, rather than just inserting a space at SecondCharLoc.
729 FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange,
730 ReplacementStr);
Douglas Gregor3965b7b2009-02-25 23:02:36 +0000731
Richard Smith19a27022012-06-18 06:11:04 +0000732 // A hint to put another space after the token, if it would otherwise be
733 // lexed differently.
734 FixItHint Hint2;
735 Token Next = NextToken();
736 if ((RemainingToken == tok::greater ||
737 RemainingToken == tok::greatergreater) &&
738 (Next.is(tok::greater) || Next.is(tok::greatergreater) ||
739 Next.is(tok::greatergreatergreater) || Next.is(tok::equal) ||
740 Next.is(tok::greaterequal) || Next.is(tok::greatergreaterequal) ||
741 Next.is(tok::equalequal)) &&
742 areTokensAdjacent(Tok, Next))
743 Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " ");
744
745 unsigned DiagId = diag::err_two_right_angle_brackets_need_space;
Richard Smith80ad52f2013-01-02 11:42:31 +0000746 if (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater))
Richard Smith19a27022012-06-18 06:11:04 +0000747 DiagId = diag::warn_cxx98_compat_two_right_angle_brackets;
748 else if (Tok.is(tok::greaterequal))
749 DiagId = diag::err_right_angle_bracket_equal_needs_space;
750 Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2;
751
752 // Strip the initial '>' from the token.
753 if (RemainingToken == tok::equal && Next.is(tok::equal) &&
754 areTokensAdjacent(Tok, Next)) {
755 // Join two adjacent '=' tokens into one, for cases like:
756 // void (*p)() = f<int>;
757 // return f<int>==p;
Douglas Gregorcc636682009-02-17 23:15:12 +0000758 ConsumeToken();
Richard Smith19a27022012-06-18 06:11:04 +0000759 Tok.setKind(tok::equalequal);
760 Tok.setLength(Tok.getLength() + 1);
761 } else {
762 Tok.setKind(RemainingToken);
763 Tok.setLength(Tok.getLength() - 1);
764 }
765 Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1,
766 PP.getSourceManager(),
767 getLangOpts()));
768
769 if (!ConsumeLastToken) {
770 // Since we're not supposed to consume the '>' token, we need to push
771 // this token and revert the current token back to the '>'.
772 PP.EnterToken(Tok);
773 Tok.setKind(tok::greater);
774 Tok.setLength(1);
775 Tok.setLocation(RAngleLoc);
776 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000777 return false;
778}
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Nico Weberb707a472012-12-14 18:22:38 +0000780
781/// \brief Parses a template-id that after the template name has
782/// already been parsed.
783///
784/// This routine takes care of parsing the enclosed template argument
785/// list ('<' template-parameter-list [opt] '>') and placing the
786/// results into a form that can be transferred to semantic analysis.
787///
788/// \param Template the template declaration produced by isTemplateName
789///
790/// \param TemplateNameLoc the source location of the template name
791///
792/// \param SS if non-NULL, the nested-name-specifier preceding the
793/// template name.
794///
795/// \param ConsumeLastToken if true, then we will consume the last
796/// token that forms the template-id. Otherwise, we will leave the
797/// last token in the stream (e.g., so that it can be replaced with an
798/// annotation token).
799bool
800Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template,
801 SourceLocation TemplateNameLoc,
802 const CXXScopeSpec &SS,
803 bool ConsumeLastToken,
804 SourceLocation &LAngleLoc,
805 TemplateArgList &TemplateArgs,
806 SourceLocation &RAngleLoc) {
807 assert(Tok.is(tok::less) && "Must have already parsed the template-name");
808
809 // Consume the '<'.
810 LAngleLoc = ConsumeToken();
811
812 // Parse the optional template-argument-list.
813 bool Invalid = false;
814 {
815 GreaterThanIsOperatorScope G(GreaterThanIsOperator, false);
816 if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater))
817 Invalid = ParseTemplateArgumentList(TemplateArgs);
818
819 if (Invalid) {
820 // Try to find the closing '>'.
821 SkipUntil(tok::greater, true, !ConsumeLastToken);
822
823 return true;
824 }
825 }
826
827 return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken);
828}
829
Douglas Gregor39a8de12009-02-25 19:37:18 +0000830/// \brief Replace the tokens that form a simple-template-id with an
831/// annotation token containing the complete template-id.
832///
833/// The first token in the stream must be the name of a template that
834/// is followed by a '<'. This routine will parse the complete
835/// simple-template-id and replace the tokens with a single annotation
836/// token with one of two different kinds: if the template-id names a
837/// type (and \p AllowTypeAnnotation is true), the annotation token is
838/// a type annotation that includes the optional nested-name-specifier
839/// (\p SS). Otherwise, the annotation token is a template-id
840/// annotation that does not include the optional
841/// nested-name-specifier.
842///
843/// \param Template the declaration of the template named by the first
844/// token (an identifier), as returned from \c Action::isTemplateName().
845///
NAKAMURA Takumi384d3fc2012-11-14 02:21:42 +0000846/// \param TNK the kind of template that \p Template
Douglas Gregor39a8de12009-02-25 19:37:18 +0000847/// refers to, as returned from \c Action::isTemplateName().
848///
849/// \param SS if non-NULL, the nested-name-specifier that precedes
850/// this template name.
851///
852/// \param TemplateKWLoc if valid, specifies that this template-id
853/// annotation was preceded by the 'template' keyword and gives the
854/// location of that keyword. If invalid (the default), then this
855/// template-id was not preceded by a 'template' keyword.
856///
857/// \param AllowTypeAnnotation if true (the default), then a
858/// simple-template-id that refers to a class template, template
859/// template parameter, or other template that produces a type will be
860/// replaced with a type annotation token. Otherwise, the
861/// simple-template-id is always replaced with a template-id
862/// annotation token.
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000863///
864/// If an unrecoverable parse error occurs and no annotation token can be
865/// formed, this function returns true.
866///
867bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
Douglas Gregor059101f2011-03-02 00:47:37 +0000868 CXXScopeSpec &SS,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000869 SourceLocation TemplateKWLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000870 UnqualifiedId &TemplateName,
Douglas Gregor39a8de12009-02-25 19:37:18 +0000871 bool AllowTypeAnnotation) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000872 assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++");
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000873 assert(Template && Tok.is(tok::less) &&
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000874 "Parser isn't at the beginning of a template-id");
875
876 // Consume the template-name.
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000877 SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin();
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000878
Douglas Gregorcc636682009-02-17 23:15:12 +0000879 // Parse the enclosed template argument list.
880 SourceLocation LAngleLoc, RAngleLoc;
Douglas Gregor5908e9f2009-02-09 19:34:22 +0000881 TemplateArgList TemplateArgs;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000882 bool Invalid = ParseTemplateIdAfterTemplateName(Template,
883 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000884 SS, false, LAngleLoc,
885 TemplateArgs,
Douglas Gregorcc636682009-02-17 23:15:12 +0000886 RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000888 if (Invalid) {
889 // If we failed to parse the template ID but skipped ahead to a >, we're not
890 // going to be able to form a token annotation. Eat the '>' if present.
891 if (Tok.is(tok::greater))
892 ConsumeToken();
893 return true;
894 }
Douglas Gregorc15cb382009-02-09 23:23:08 +0000895
Benjamin Kramer5354e772012-08-23 23:38:35 +0000896 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Douglas Gregorf02da892009-02-09 21:04:56 +0000897
Douglas Gregor55f6b142009-02-09 18:46:07 +0000898 // Build the annotation token.
Douglas Gregorc45c2322009-03-31 00:43:58 +0000899 if (TNK == TNK_Type_template && AllowTypeAnnotation) {
John McCallf312b1e2010-08-26 23:41:50 +0000900 TypeResult Type
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000901 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +0000902 Template, TemplateNameLoc,
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000903 LAngleLoc, TemplateArgsPtr, RAngleLoc);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000904 if (Type.isInvalid()) {
905 // If we failed to parse the template ID but skipped ahead to a >, we're not
906 // going to be able to form a token annotation. Eat the '>' if present.
907 if (Tok.is(tok::greater))
908 ConsumeToken();
909 return true;
910 }
Douglas Gregorcc636682009-02-17 23:15:12 +0000911
912 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000913 setTypeAnnotation(Tok, Type.get());
Douglas Gregor059101f2011-03-02 00:47:37 +0000914 if (SS.isNotEmpty())
915 Tok.setLocation(SS.getBeginLoc());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000916 else if (TemplateKWLoc.isValid())
917 Tok.setLocation(TemplateKWLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000918 else
Douglas Gregor39a8de12009-02-25 19:37:18 +0000919 Tok.setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +0000920 } else {
Douglas Gregorc45c2322009-03-31 00:43:58 +0000921 // Build a template-id annotation token that can be processed
922 // later.
Douglas Gregor39a8de12009-02-25 19:37:18 +0000923 Tok.setKind(tok::annot_template_id);
Mike Stump1eb44332009-09-09 15:08:12 +0000924 TemplateIdAnnotation *TemplateId
Benjamin Kramer13bb7012012-04-14 12:14:03 +0000925 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000926 TemplateId->TemplateNameLoc = TemplateNameLoc;
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000927 if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) {
928 TemplateId->Name = TemplateName.Identifier;
929 TemplateId->Operator = OO_None;
930 } else {
931 TemplateId->Name = 0;
932 TemplateId->Operator = TemplateName.OperatorFunctionId.Operator;
933 }
Douglas Gregor059101f2011-03-02 00:47:37 +0000934 TemplateId->SS = SS;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000935 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall2b5289b2010-08-23 07:28:44 +0000936 TemplateId->Template = Template;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000937 TemplateId->Kind = TNK;
Douglas Gregor55f6b142009-02-09 18:46:07 +0000938 TemplateId->LAngleLoc = LAngleLoc;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000939 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregor314b97f2009-11-10 19:49:08 +0000940 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
941 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg)
Douglas Gregorc34348a2011-02-24 17:54:50 +0000942 Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000943 Tok.setAnnotationValue(TemplateId);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000944 if (TemplateKWLoc.isValid())
945 Tok.setLocation(TemplateKWLoc);
946 else
947 Tok.setLocation(TemplateNameLoc);
Douglas Gregor55f6b142009-02-09 18:46:07 +0000948 }
949
950 // Common fields for the annotation token
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000951 Tok.setAnnotationEndLoc(RAngleLoc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000952
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000953 // In case the tokens were cached, have Preprocessor replace them with the
954 // annotation token.
955 PP.AnnotateCachedTokens(Tok);
Chris Lattnerc8e27cc2009-06-26 04:27:47 +0000956 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000957}
958
Douglas Gregor39a8de12009-02-25 19:37:18 +0000959/// \brief Replaces a template-id annotation token with a type
960/// annotation token.
961///
Douglas Gregor31a19b62009-04-01 21:51:26 +0000962/// If there was a failure when forming the type from the template-id,
963/// a type annotation token will still be created, but will have a
964/// NULL type pointer to signify an error.
Douglas Gregor059101f2011-03-02 00:47:37 +0000965void Parser::AnnotateTemplateIdTokenAsType() {
Douglas Gregor39a8de12009-02-25 19:37:18 +0000966 assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens");
967
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +0000968 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregorc45c2322009-03-31 00:43:58 +0000969 assert((TemplateId->Kind == TNK_Type_template ||
970 TemplateId->Kind == TNK_Dependent_template_name) &&
971 "Only works for type and dependent templates");
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Benjamin Kramer5354e772012-08-23 23:38:35 +0000973 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor39a8de12009-02-25 19:37:18 +0000974 TemplateId->NumArgs);
975
John McCallf312b1e2010-08-26 23:41:50 +0000976 TypeResult Type
Douglas Gregor059101f2011-03-02 00:47:37 +0000977 = Actions.ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +0000978 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +0000979 TemplateId->Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000980 TemplateId->TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000981 TemplateId->LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000982 TemplateArgsPtr,
Douglas Gregor7532dc62009-03-30 22:58:21 +0000983 TemplateId->RAngleLoc);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000984 // Create the new "type" annotation token.
985 Tok.setKind(tok::annot_typename);
John McCallb3d87482010-08-24 05:47:05 +0000986 setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get());
Douglas Gregor059101f2011-03-02 00:47:37 +0000987 if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name.
988 Tok.setLocation(TemplateId->SS.getBeginLoc());
Sebastian Redl39d67112010-02-08 19:35:18 +0000989 // End location stays the same
Douglas Gregor39a8de12009-02-25 19:37:18 +0000990
Douglas Gregor86235412009-11-04 18:18:19 +0000991 // Replace the template-id annotation token, and possible the scope-specifier
992 // that precedes it, with the typename annotation token.
993 PP.AnnotateCachedTokens(Tok);
Douglas Gregor39a8de12009-02-25 19:37:18 +0000994}
995
Douglas Gregor314b97f2009-11-10 19:49:08 +0000996/// \brief Determine whether the given token can end a template argument.
Benjamin Kramer3a4a2b32009-11-10 21:29:56 +0000997static bool isEndOfTemplateArgument(Token Tok) {
Douglas Gregor314b97f2009-11-10 19:49:08 +0000998 return Tok.is(tok::comma) || Tok.is(tok::greater) ||
999 Tok.is(tok::greatergreater);
1000}
1001
Douglas Gregor788cd062009-11-11 01:00:40 +00001002/// \brief Parse a C++ template template argument.
1003ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() {
1004 if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) &&
1005 !Tok.is(tok::annot_cxxscope))
1006 return ParsedTemplateArgument();
1007
1008 // C++0x [temp.arg.template]p1:
1009 // A template-argument for a template template-parameter shall be the name
Richard Smith3e4c6c42011-05-05 21:57:07 +00001010 // of a class template or an alias template, expressed as id-expression.
Douglas Gregor788cd062009-11-11 01:00:40 +00001011 //
Richard Smith3e4c6c42011-05-05 21:57:07 +00001012 // We parse an id-expression that refers to a class template or alias
1013 // template. The grammar we parse is:
Douglas Gregor788cd062009-11-11 01:00:40 +00001014 //
Douglas Gregorec5e6962011-01-05 17:33:50 +00001015 // nested-name-specifier[opt] template[opt] identifier ...[opt]
Douglas Gregor788cd062009-11-11 01:00:40 +00001016 //
1017 // followed by a token that terminates a template argument, such as ',',
1018 // '>', or (in some cases) '>>'.
Douglas Gregor788cd062009-11-11 01:00:40 +00001019 CXXScopeSpec SS; // nested-name-specifier, if present
John McCallb3d87482010-08-24 05:47:05 +00001020 ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001021 /*EnteringContext=*/false);
1022
Douglas Gregorec5e6962011-01-05 17:33:50 +00001023 ParsedTemplateArgument Result;
1024 SourceLocation EllipsisLoc;
Douglas Gregor788cd062009-11-11 01:00:40 +00001025 if (SS.isSet() && Tok.is(tok::kw_template)) {
1026 // Parse the optional 'template' keyword following the
1027 // nested-name-specifier.
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001028 SourceLocation TemplateKWLoc = ConsumeToken();
Douglas Gregor788cd062009-11-11 01:00:40 +00001029
1030 if (Tok.is(tok::identifier)) {
1031 // We appear to have a dependent template name.
1032 UnqualifiedId Name;
1033 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1034 ConsumeToken(); // the identifier
1035
Douglas Gregorec5e6962011-01-05 17:33:50 +00001036 // Parse the ellipsis.
1037 if (Tok.is(tok::ellipsis))
1038 EllipsisLoc = ConsumeToken();
1039
Douglas Gregor788cd062009-11-11 01:00:40 +00001040 // If the next token signals the end of a template argument,
1041 // then we have a dependent template name that could be a template
1042 // template argument.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001043 TemplateTy Template;
1044 if (isEndOfTemplateArgument(Tok) &&
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001045 Actions.ActOnDependentTemplateName(getCurScope(),
1046 SS, TemplateKWLoc, Name,
John McCallb3d87482010-08-24 05:47:05 +00001047 /*ObjectType=*/ ParsedType(),
Douglas Gregord6ab2322010-06-16 23:00:59 +00001048 /*EnteringContext=*/false,
1049 Template))
Douglas Gregorec5e6962011-01-05 17:33:50 +00001050 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregord6ab2322010-06-16 23:00:59 +00001051 }
Douglas Gregor788cd062009-11-11 01:00:40 +00001052 } else if (Tok.is(tok::identifier)) {
1053 // We may have a (non-dependent) template name.
1054 TemplateTy Template;
1055 UnqualifiedId Name;
1056 Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1057 ConsumeToken(); // the identifier
1058
Douglas Gregorec5e6962011-01-05 17:33:50 +00001059 // Parse the ellipsis.
1060 if (Tok.is(tok::ellipsis))
1061 EllipsisLoc = ConsumeToken();
1062
Douglas Gregor788cd062009-11-11 01:00:40 +00001063 if (isEndOfTemplateArgument(Tok)) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001064 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001065 TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
1066 /*hasTemplateKeyword=*/false,
1067 Name,
John McCallb3d87482010-08-24 05:47:05 +00001068 /*ObjectType=*/ ParsedType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001069 /*EnteringContext=*/false,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001070 Template,
1071 MemberOfUnknownSpecialization);
Douglas Gregor788cd062009-11-11 01:00:40 +00001072 if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) {
1073 // We have an id-expression that refers to a class template or
Richard Smith3e4c6c42011-05-05 21:57:07 +00001074 // (C++0x) alias template.
Douglas Gregorec5e6962011-01-05 17:33:50 +00001075 Result = ParsedTemplateArgument(SS, Template, Name.StartLocation);
Douglas Gregor788cd062009-11-11 01:00:40 +00001076 }
1077 }
1078 }
1079
Douglas Gregorec5e6962011-01-05 17:33:50 +00001080 // If this is a pack expansion, build it as such.
1081 if (EllipsisLoc.isValid() && !Result.isInvalid())
1082 Result = Actions.ActOnPackExpansion(Result, EllipsisLoc);
1083
1084 return Result;
Douglas Gregor788cd062009-11-11 01:00:40 +00001085}
1086
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001087/// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]).
1088///
1089/// template-argument: [C++ 14.2]
Douglas Gregorac7610d2009-06-22 20:57:11 +00001090/// constant-expression
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001091/// type-id
1092/// id-expression
Douglas Gregor314b97f2009-11-10 19:49:08 +00001093ParsedTemplateArgument Parser::ParseTemplateArgument() {
Douglas Gregor55f6b142009-02-09 18:46:07 +00001094 // C++ [temp.arg]p2:
1095 // In a template-argument, an ambiguity between a type-id and an
1096 // expression is resolved to a type-id, regardless of the form of
1097 // the corresponding template-parameter.
1098 //
Douglas Gregor314b97f2009-11-10 19:49:08 +00001099 // Therefore, we initially try to parse a type-id.
Douglas Gregor8b642592009-02-10 00:53:15 +00001100 if (isCXXTypeId(TypeIdAsTemplateArgument)) {
Douglas Gregor314b97f2009-11-10 19:49:08 +00001101 SourceLocation Loc = Tok.getLocation();
Douglas Gregor683a81f2011-01-31 16:09:46 +00001102 TypeResult TypeArg = ParseTypeName(/*Range=*/0,
1103 Declarator::TemplateTypeArgContext);
Douglas Gregor809070a2009-02-18 17:45:20 +00001104 if (TypeArg.isInvalid())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001105 return ParsedTemplateArgument();
1106
John McCallb3d87482010-08-24 05:47:05 +00001107 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1108 TypeArg.get().getAsOpaquePtr(),
Douglas Gregor314b97f2009-11-10 19:49:08 +00001109 Loc);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001110 }
Douglas Gregor788cd062009-11-11 01:00:40 +00001111
1112 // Try to parse a template template argument.
Douglas Gregoreaf75f42009-11-12 00:03:40 +00001113 {
1114 TentativeParsingAction TPA(*this);
1115
1116 ParsedTemplateArgument TemplateTemplateArgument
1117 = ParseTemplateTemplateArgument();
1118 if (!TemplateTemplateArgument.isInvalid()) {
1119 TPA.Commit();
1120 return TemplateTemplateArgument;
1121 }
1122
1123 // Revert this tentative parse to parse a non-type template argument.
1124 TPA.Revert();
1125 }
Douglas Gregor314b97f2009-11-10 19:49:08 +00001126
1127 // Parse a non-type template argument.
1128 SourceLocation Loc = Tok.getLocation();
Kaelyn Uhraine43fe992012-02-22 01:03:07 +00001129 ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001130 if (ExprArg.isInvalid() || !ExprArg.get())
Douglas Gregor314b97f2009-11-10 19:49:08 +00001131 return ParsedTemplateArgument();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001132
Douglas Gregor314b97f2009-11-10 19:49:08 +00001133 return ParsedTemplateArgument(ParsedTemplateArgument::NonType,
1134 ExprArg.release(), Loc);
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001135}
1136
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001137/// \brief Determine whether the current tokens can only be parsed as a
1138/// template argument list (starting with the '<') and never as a '<'
1139/// expression.
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001140bool Parser::IsTemplateArgumentList(unsigned Skip) {
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001141 struct AlwaysRevertAction : TentativeParsingAction {
1142 AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { }
1143 ~AlwaysRevertAction() { Revert(); }
1144 } Tentative(*this);
1145
Douglas Gregord5ab9b02010-05-21 23:43:39 +00001146 while (Skip) {
1147 ConsumeToken();
1148 --Skip;
1149 }
1150
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001151 // '<'
1152 if (!Tok.is(tok::less))
1153 return false;
1154 ConsumeToken();
1155
1156 // An empty template argument list.
1157 if (Tok.is(tok::greater))
1158 return true;
1159
1160 // See whether we have declaration specifiers, which indicate a type.
1161 while (isCXXDeclarationSpecifier() == TPResult::True())
1162 ConsumeToken();
1163
1164 // If we have a '>' or a ',' then this is a template argument list.
1165 return Tok.is(tok::greater) || Tok.is(tok::comma);
1166}
1167
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001168/// ParseTemplateArgumentList - Parse a C++ template-argument-list
1169/// (C++ [temp.names]). Returns true if there was an error.
1170///
1171/// template-argument-list: [C++ 14.2]
1172/// template-argument
1173/// template-argument-list ',' template-argument
Mike Stump1eb44332009-09-09 15:08:12 +00001174bool
Douglas Gregor314b97f2009-11-10 19:49:08 +00001175Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001176 while (true) {
Douglas Gregor314b97f2009-11-10 19:49:08 +00001177 ParsedTemplateArgument Arg = ParseTemplateArgument();
Douglas Gregor7536dd52010-12-20 02:24:11 +00001178 if (Tok.is(tok::ellipsis)) {
1179 SourceLocation EllipsisLoc = ConsumeToken();
1180 Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc);
1181 }
1182
Douglas Gregor314b97f2009-11-10 19:49:08 +00001183 if (Arg.isInvalid()) {
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001184 SkipUntil(tok::comma, tok::greater, true, true);
1185 return true;
1186 }
Douglas Gregor5908e9f2009-02-09 19:34:22 +00001187
Douglas Gregor314b97f2009-11-10 19:49:08 +00001188 // Save this template argument.
1189 TemplateArgs.push_back(Arg);
1190
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001191 // If the next token is a comma, consume it and keep reading
1192 // arguments.
1193 if (Tok.isNot(tok::comma)) break;
1194
1195 // Consume the comma.
1196 ConsumeToken();
1197 }
1198
Eli Friedman64a4eb22009-12-27 22:31:18 +00001199 return false;
Douglas Gregord6fb7ef2008-12-18 19:37:40 +00001200}
1201
Mike Stump1eb44332009-09-09 15:08:12 +00001202/// \brief Parse a C++ explicit template instantiation
Douglas Gregor1426e532009-05-12 21:31:51 +00001203/// (C++ [temp.explicit]).
1204///
1205/// explicit-instantiation:
Douglas Gregor45f96552009-09-04 06:33:52 +00001206/// 'extern' [opt] 'template' declaration
1207///
1208/// Note that the 'extern' is a GNU extension and C++0x feature.
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001209Decl *Parser::ParseExplicitInstantiation(unsigned Context,
1210 SourceLocation ExternLoc,
John McCalld226f652010-08-21 09:40:31 +00001211 SourceLocation TemplateLoc,
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001212 SourceLocation &DeclEnd,
1213 AccessSpecifier AS) {
John McCallc9068d72010-07-16 08:13:16 +00001214 // This isn't really required here.
John McCall92576642012-05-07 06:16:41 +00001215 ParsingDeclRAIIObject
1216 ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent);
John McCallc9068d72010-07-16 08:13:16 +00001217
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001218 return ParseSingleDeclarationAfterTemplate(Context,
Douglas Gregor45f96552009-09-04 06:33:52 +00001219 ParsedTemplateInfo(ExternLoc,
1220 TemplateLoc),
John McCallc9068d72010-07-16 08:13:16 +00001221 ParsingTemplateParams,
Argyrios Kyrtzidis92410572011-12-23 02:16:45 +00001222 DeclEnd, AS);
Douglas Gregor1426e532009-05-12 21:31:51 +00001223}
John McCall78b81052010-11-10 02:40:36 +00001224
1225SourceRange Parser::ParsedTemplateInfo::getSourceRange() const {
1226 if (TemplateParams)
1227 return getTemplateParamsRange(TemplateParams->data(),
1228 TemplateParams->size());
1229
1230 SourceRange R(TemplateLoc);
1231 if (ExternLoc.isValid())
1232 R.setBegin(ExternLoc);
1233 return R;
1234}
Francois Pichet8387e2a2011-04-22 22:18:13 +00001235
Francois Pichet4a47e8d2011-04-23 11:52:20 +00001236void Parser::LateTemplateParserCallback(void *P, const FunctionDecl *FD) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001237 ((Parser*)P)->LateTemplateParser(FD);
1238}
1239
1240
Francois Pichet4a47e8d2011-04-23 11:52:20 +00001241void Parser::LateTemplateParser(const FunctionDecl *FD) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001242 LateParsedTemplatedFunction *LPT = LateParsedTemplateMap[FD];
1243 if (LPT) {
1244 ParseLateTemplatedFuncDef(*LPT);
1245 return;
1246 }
1247
1248 llvm_unreachable("Late templated function without associated lexed tokens");
1249}
David Blaikie219c2e22012-04-02 20:59:49 +00001250
1251/// \brief Late parse a C++ function template in Microsoft mode.
1252void Parser::ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT) {
1253 if(!LMT.D)
1254 return;
1255
1256 // Get the FunctionDecl.
1257 FunctionDecl *FD = 0;
1258 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(LMT.D))
1259 FD = FunTmpl->getTemplatedDecl();
1260 else
1261 FD = cast<FunctionDecl>(LMT.D);
1262
Francois Pichetd77177a2012-02-22 08:25:53 +00001263 // To restore the context after late parsing.
David Blaikie219c2e22012-04-02 20:59:49 +00001264 Sema::ContextRAII GlobalSavedContext(Actions, Actions.CurContext);
1265
1266 SmallVector<ParseScope*, 4> TemplateParamScopeStack;
1267 DeclaratorDecl* Declarator = dyn_cast<DeclaratorDecl>(FD);
1268 if (Declarator && Declarator->getNumTemplateParameterLists() != 0) {
1269 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::TemplateParamScope));
1270 Actions.ActOnReenterDeclaratorTemplateScope(getCurScope(), Declarator);
1271 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1272 } else {
1273 // Get the list of DeclContext to reenter.
1274 SmallVector<DeclContext*, 4> DeclContextToReenter;
1275 DeclContext *DD = FD->getLexicalParent();
1276 while (DD && !DD->isTranslationUnit()) {
1277 DeclContextToReenter.push_back(DD);
1278 DD = DD->getLexicalParent();
1279 }
1280
1281 // Reenter template scopes from outmost to innermost.
1282 SmallVector<DeclContext*, 4>::reverse_iterator II =
1283 DeclContextToReenter.rbegin();
1284 for (; II != DeclContextToReenter.rend(); ++II) {
1285 if (ClassTemplatePartialSpecializationDecl* MD =
1286 dyn_cast_or_null<ClassTemplatePartialSpecializationDecl>(*II)) {
1287 TemplateParamScopeStack.push_back(new ParseScope(this,
1288 Scope::TemplateParamScope));
1289 Actions.ActOnReenterTemplateScope(getCurScope(), MD);
1290 } else if (CXXRecordDecl* MD = dyn_cast_or_null<CXXRecordDecl>(*II)) {
1291 TemplateParamScopeStack.push_back(new ParseScope(this,
1292 Scope::TemplateParamScope,
1293 MD->getDescribedClassTemplate() != 0 ));
1294 Actions.ActOnReenterTemplateScope(getCurScope(),
1295 MD->getDescribedClassTemplate());
1296 }
1297 TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope));
1298 Actions.PushDeclContext(Actions.getCurScope(), *II);
1299 }
1300 TemplateParamScopeStack.push_back(new ParseScope(this,
1301 Scope::TemplateParamScope));
1302 Actions.ActOnReenterTemplateScope(getCurScope(), LMT.D);
1303 }
1304
1305 assert(!LMT.Toks.empty() && "Empty body!");
1306
1307 // Append the current token at the end of the new token stream so that it
1308 // doesn't get lost.
1309 LMT.Toks.push_back(Tok);
1310 PP.EnterTokenStream(LMT.Toks.data(), LMT.Toks.size(), true, false);
1311
1312 // Consume the previously pushed token.
1313 ConsumeAnyToken();
1314 assert((Tok.is(tok::l_brace) || Tok.is(tok::colon) || Tok.is(tok::kw_try))
1315 && "Inline method not starting with '{', ':' or 'try'");
1316
1317 // Parse the method body. Function body parsing code is similar enough
1318 // to be re-used for method bodies as well.
1319 ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope);
1320
1321 // Recreate the containing function DeclContext.
1322 Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FD));
1323
1324 if (FunctionTemplateDecl *FunctionTemplate
1325 = dyn_cast_or_null<FunctionTemplateDecl>(LMT.D))
1326 Actions.ActOnStartOfFunctionDef(getCurScope(),
1327 FunctionTemplate->getTemplatedDecl());
1328 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(LMT.D))
1329 Actions.ActOnStartOfFunctionDef(getCurScope(), Function);
1330
1331
1332 if (Tok.is(tok::kw_try)) {
1333 ParseFunctionTryBlock(LMT.D, FnScope);
1334 } else {
1335 if (Tok.is(tok::colon))
1336 ParseConstructorInitializer(LMT.D);
1337 else
1338 Actions.ActOnDefaultCtorInitializers(LMT.D);
1339
1340 if (Tok.is(tok::l_brace)) {
1341 ParseFunctionStatementBody(LMT.D, FnScope);
1342 Actions.MarkAsLateParsedTemplate(FD, false);
1343 } else
1344 Actions.ActOnFinishFunctionBody(LMT.D, 0);
1345 }
1346
1347 // Exit scopes.
Francois Pichetfdde4702011-09-22 22:14:56 +00001348 FnScope.Exit();
David Blaikie219c2e22012-04-02 20:59:49 +00001349 SmallVector<ParseScope*, 4>::reverse_iterator I =
1350 TemplateParamScopeStack.rbegin();
1351 for (; I != TemplateParamScopeStack.rend(); ++I)
1352 delete *I;
1353
1354 DeclGroupPtrTy grp = Actions.ConvertDeclToDeclGroup(LMT.D);
1355 if (grp)
1356 Actions.getASTConsumer().HandleTopLevelDecl(grp.get());
Francois Pichet8387e2a2011-04-22 22:18:13 +00001357}
1358
1359/// \brief Lex a delayed template function for late parsing.
1360void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) {
1361 tok::TokenKind kind = Tok.getKind();
Sebastian Redla891a322011-09-30 08:32:17 +00001362 if (!ConsumeAndStoreFunctionPrologue(Toks)) {
1363 // Consume everything up to (and including) the matching right brace.
1364 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
Francois Pichet8387e2a2011-04-22 22:18:13 +00001365 }
Francois Pichet8387e2a2011-04-22 22:18:13 +00001366
1367 // If we're in a function-try-block, we need to store all the catch blocks.
1368 if (kind == tok::kw_try) {
1369 while (Tok.is(tok::kw_catch)) {
1370 ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false);
1371 ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false);
1372 }
1373 }
1374}