blob: 613246ef7121facdb173b76c6540beec828d5152 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expression parsing implementation for C++.
11//
12//===----------------------------------------------------------------------===//
Stephen Hines651f13c2014-04-23 16:59:28 -070013#include "clang/AST/ASTContext.h"
Douglas Gregorbc61bd82011-01-11 00:33:19 +000014#include "RAIIObjectsForParser.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070015#include "clang/AST/DeclTemplate.h"
Eli Friedmandc3b7232012-01-04 02:40:39 +000016#include "clang/Basic/PrettyStackTrace.h"
Richard Smith33762772012-03-08 23:06:02 +000017#include "clang/Lex/LiteralSupport.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/Parse/ParseDiagnostic.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070019#include "clang/Parse/Parser.h"
John McCall19510852010-08-20 18:27:03 +000020#include "clang/Sema/DeclSpec.h"
21#include "clang/Sema/ParsedTemplate.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Sema/Scope.h"
Douglas Gregor3f9a0562009-11-03 01:35:08 +000023#include "llvm/Support/ErrorHandling.h"
24
Faisal Valifad9e132013-09-26 19:54:12 +000025
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27
Richard Smithea698b32011-04-14 21:45:45 +000028static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
29 switch (Kind) {
Stephen Hines651f13c2014-04-23 16:59:28 -070030 // template name
31 case tok::unknown: return 0;
32 // casts
Richard Smithea698b32011-04-14 21:45:45 +000033 case tok::kw_const_cast: return 1;
34 case tok::kw_dynamic_cast: return 2;
35 case tok::kw_reinterpret_cast: return 3;
36 case tok::kw_static_cast: return 4;
37 default:
David Blaikieb219cfc2011-09-23 05:06:16 +000038 llvm_unreachable("Unknown type for digraph error message.");
Richard Smithea698b32011-04-14 21:45:45 +000039 }
40}
41
42// Are the two tokens adjacent in the same source file?
Richard Smith19a27022012-06-18 06:11:04 +000043bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
Richard Smithea698b32011-04-14 21:45:45 +000044 SourceManager &SM = PP.getSourceManager();
45 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +000046 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
Richard Smithea698b32011-04-14 21:45:45 +000047 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
48}
49
50// Suggest fixit for "<::" after a cast.
51static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
52 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
53 // Pull '<:' and ':' off token stream.
54 if (!AtDigraph)
55 PP.Lex(DigraphToken);
56 PP.Lex(ColonToken);
57
58 SourceRange Range;
59 Range.setBegin(DigraphToken.getLocation());
60 Range.setEnd(ColonToken.getLocation());
61 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
62 << SelectDigraphErrorMessage(Kind)
63 << FixItHint::CreateReplacement(Range, "< ::");
64
65 // Update token information to reflect their change in token type.
66 ColonToken.setKind(tok::coloncolon);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +000067 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
Richard Smithea698b32011-04-14 21:45:45 +000068 ColonToken.setLength(2);
69 DigraphToken.setKind(tok::less);
70 DigraphToken.setLength(1);
71
72 // Push new tokens back to token stream.
73 PP.EnterToken(ColonToken);
74 if (!AtDigraph)
75 PP.EnterToken(DigraphToken);
76}
77
Richard Trieu950be712011-09-19 19:01:00 +000078// Check for '<::' which should be '< ::' instead of '[:' when following
79// a template name.
80void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
81 bool EnteringContext,
82 IdentifierInfo &II, CXXScopeSpec &SS) {
Richard Trieuc11030e2011-09-20 20:03:50 +000083 if (!Next.is(tok::l_square) || Next.getLength() != 2)
Richard Trieu950be712011-09-19 19:01:00 +000084 return;
85
86 Token SecondToken = GetLookAheadToken(2);
Richard Smith19a27022012-06-18 06:11:04 +000087 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
Richard Trieu950be712011-09-19 19:01:00 +000088 return;
89
90 TemplateTy Template;
91 UnqualifiedId TemplateName;
92 TemplateName.setIdentifier(&II, Tok.getLocation());
93 bool MemberOfUnknownSpecialization;
94 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
95 TemplateName, ObjectType, EnteringContext,
96 Template, MemberOfUnknownSpecialization))
97 return;
98
Stephen Hines651f13c2014-04-23 16:59:28 -070099 FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
Richard Trieu950be712011-09-19 19:01:00 +0000100 /*AtDigraph*/false);
101}
102
Richard Trieu919b9552012-11-02 01:08:58 +0000103/// \brief Emits an error for a left parentheses after a double colon.
104///
105/// When a '(' is found after a '::', emit an error. Attempt to fix the token
Nico Weberbba91b82012-11-29 05:29:23 +0000106/// stream by removing the '(', and the matching ')' if found.
Richard Trieu919b9552012-11-02 01:08:58 +0000107void Parser::CheckForLParenAfterColonColon() {
108 if (!Tok.is(tok::l_paren))
109 return;
110
111 SourceLocation l_parenLoc = ConsumeParen(), r_parenLoc;
112 Token Tok1 = getCurToken();
113 if (!Tok1.is(tok::identifier) && !Tok1.is(tok::star))
114 return;
115
116 if (Tok1.is(tok::identifier)) {
117 Token Tok2 = GetLookAheadToken(1);
118 if (Tok2.is(tok::r_paren)) {
119 ConsumeToken();
120 PP.EnterToken(Tok1);
121 r_parenLoc = ConsumeParen();
122 }
123 } else if (Tok1.is(tok::star)) {
124 Token Tok2 = GetLookAheadToken(1);
125 if (Tok2.is(tok::identifier)) {
126 Token Tok3 = GetLookAheadToken(2);
127 if (Tok3.is(tok::r_paren)) {
128 ConsumeToken();
129 ConsumeToken();
130 PP.EnterToken(Tok2);
131 PP.EnterToken(Tok1);
132 r_parenLoc = ConsumeParen();
133 }
134 }
135 }
136
137 Diag(l_parenLoc, diag::err_paren_after_colon_colon)
138 << FixItHint::CreateRemoval(l_parenLoc)
139 << FixItHint::CreateRemoval(r_parenLoc);
140}
141
Mike Stump1eb44332009-09-09 15:08:12 +0000142/// \brief Parse global scope or nested-name-specifier if present.
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000143///
144/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
Mike Stump1eb44332009-09-09 15:08:12 +0000145/// may be preceded by '::'). Note that this routine will not parse ::new or
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000146/// ::delete; it will just leave them in the token stream.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000147///
148/// '::'[opt] nested-name-specifier
149/// '::'
150///
151/// nested-name-specifier:
152/// type-name '::'
153/// namespace-name '::'
154/// nested-name-specifier identifier '::'
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000155/// nested-name-specifier 'template'[opt] simple-template-id '::'
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000156///
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000157///
Mike Stump1eb44332009-09-09 15:08:12 +0000158/// \param SS the scope specifier that will be set to the parsed
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000159/// nested-name-specifier (or empty)
160///
Mike Stump1eb44332009-09-09 15:08:12 +0000161/// \param ObjectType if this nested-name-specifier is being parsed following
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000162/// the "." or "->" of a member access expression, this parameter provides the
163/// type of the object whose members are being accessed.
164///
165/// \param EnteringContext whether we will be entering into the context of
166/// the nested-name-specifier after parsing it.
167///
Douglas Gregord4dca082010-02-24 18:44:31 +0000168/// \param MayBePseudoDestructor When non-NULL, points to a flag that
169/// indicates whether this nested-name-specifier may be part of a
170/// pseudo-destructor name. In this case, the flag will be set false
171/// if we don't actually end up parsing a destructor name. Moreorover,
172/// if we do end up determining that we are parsing a destructor name,
173/// the last component of the nested-name-specifier is not parsed as
174/// part of the scope specifier.
Richard Smith2db075b2013-03-26 01:15:19 +0000175///
176/// \param IsTypename If \c true, this nested-name-specifier is known to be
177/// part of a type name. This is used to improve error recovery.
178///
179/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
180/// filled in with the leading identifier in the last component of the
181/// nested-name-specifier, if any.
Douglas Gregorb10cd042010-02-21 18:36:56 +0000182///
John McCall9ba61662010-02-26 08:45:28 +0000183/// \returns true if there was an error parsing a scope specifier
Douglas Gregor495c35d2009-08-25 22:51:20 +0000184bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
John McCallb3d87482010-08-24 05:47:05 +0000185 ParsedType ObjectType,
Douglas Gregorb10cd042010-02-21 18:36:56 +0000186 bool EnteringContext,
Francois Pichet4147d302011-03-27 19:41:34 +0000187 bool *MayBePseudoDestructor,
Richard Smith2db075b2013-03-26 01:15:19 +0000188 bool IsTypename,
189 IdentifierInfo **LastII) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000190 assert(getLangOpts().CPlusPlus &&
Chris Lattner7452c6f2009-01-05 01:24:05 +0000191 "Call sites of this function should be guarded by checking for C++");
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000193 if (Tok.is(tok::annot_cxxscope)) {
Richard Smith2db075b2013-03-26 01:15:19 +0000194 assert(!LastII && "want last identifier but have already annotated scope");
Douglas Gregorc34348a2011-02-24 17:54:50 +0000195 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
196 Tok.getAnnotationRange(),
197 SS);
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000198 ConsumeToken();
John McCall9ba61662010-02-26 08:45:28 +0000199 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000200 }
Chris Lattnere607e802009-01-04 21:14:15 +0000201
Larisse Voufo9c90f7f2013-08-06 05:49:26 +0000202 if (Tok.is(tok::annot_template_id)) {
203 // If the current token is an annotated template id, it may already have
204 // a scope specifier. Restore it.
205 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
206 SS = TemplateId->SS;
207 }
208
Richard Smith2db075b2013-03-26 01:15:19 +0000209 if (LastII)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700210 *LastII = nullptr;
Richard Smith2db075b2013-03-26 01:15:19 +0000211
Douglas Gregor39a8de12009-02-25 19:37:18 +0000212 bool HasScopeSpecifier = false;
213
Chris Lattner5b454732009-01-05 03:55:46 +0000214 if (Tok.is(tok::coloncolon)) {
215 // ::new and ::delete aren't nested-name-specifiers.
216 tok::TokenKind NextKind = NextToken().getKind();
217 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
218 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Chris Lattner55a7cef2009-01-05 00:13:00 +0000220 // '::' - Global scope qualifier.
Stephen Hines176edba2014-12-01 14:53:08 -0800221 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000222 return true;
Richard Trieu919b9552012-11-02 01:08:58 +0000223
224 CheckForLParenAfterColonColon();
225
Douglas Gregor39a8de12009-02-25 19:37:18 +0000226 HasScopeSpecifier = true;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000227 }
228
Stephen Hines176edba2014-12-01 14:53:08 -0800229 if (Tok.is(tok::kw___super)) {
230 SourceLocation SuperLoc = ConsumeToken();
231 if (!Tok.is(tok::coloncolon)) {
232 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
233 return true;
234 }
235
236 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
237 }
238
Douglas Gregord4dca082010-02-24 18:44:31 +0000239 bool CheckForDestructor = false;
240 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
241 CheckForDestructor = true;
242 *MayBePseudoDestructor = false;
243 }
244
Stephen Hines176edba2014-12-01 14:53:08 -0800245 if (!HasScopeSpecifier &&
246 (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))) {
David Blaikie42d6d0c2011-12-04 05:04:18 +0000247 DeclSpec DS(AttrFactory);
248 SourceLocation DeclLoc = Tok.getLocation();
249 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Stephen Hines651f13c2014-04-23 16:59:28 -0700250
251 SourceLocation CCLoc;
252 if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
David Blaikie42d6d0c2011-12-04 05:04:18 +0000253 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
254 return false;
255 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700256
David Blaikie42d6d0c2011-12-04 05:04:18 +0000257 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
258 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
259
260 HasScopeSpecifier = true;
261 }
262
Douglas Gregor39a8de12009-02-25 19:37:18 +0000263 while (true) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000264 if (HasScopeSpecifier) {
265 // C++ [basic.lookup.classref]p5:
266 // If the qualified-id has the form
Douglas Gregor3b6afbb2009-09-09 00:23:06 +0000267 //
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000268 // ::class-name-or-namespace-name::...
Douglas Gregor3b6afbb2009-09-09 00:23:06 +0000269 //
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000270 // the class-name-or-namespace-name is looked up in global scope as a
271 // class-name or namespace-name.
272 //
273 // To implement this, we clear out the object type as soon as we've
274 // seen a leading '::' or part of a nested-name-specifier.
John McCallb3d87482010-08-24 05:47:05 +0000275 ObjectType = ParsedType();
Douglas Gregor81b747b2009-09-17 21:32:03 +0000276
277 if (Tok.is(tok::code_completion)) {
278 // Code completion for a nested-name-specifier, where the code
279 // code completion token follows the '::'.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000280 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
Argyrios Kyrtzidisb6b2b182011-04-23 01:04:12 +0000281 // Include code completion token into the range of the scope otherwise
282 // when we try to annotate the scope tokens the dangling code completion
283 // token will cause assertion in
284 // Preprocessor::AnnotatePreviousCachedTokens.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000285 SS.setEndLoc(Tok.getLocation());
286 cutOffParsing();
287 return true;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000288 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000289 }
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Douglas Gregor39a8de12009-02-25 19:37:18 +0000291 // nested-name-specifier:
Chris Lattner77cf72a2009-06-26 03:47:46 +0000292 // nested-name-specifier 'template'[opt] simple-template-id '::'
293
294 // Parse the optional 'template' keyword, then make sure we have
295 // 'identifier <' after it.
296 if (Tok.is(tok::kw_template)) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000297 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedmaneab975d2009-08-29 04:08:08 +0000298 // nested-name-specifier, since they aren't allowed to start with
299 // 'template'.
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000300 if (!HasScopeSpecifier && !ObjectType)
Eli Friedmaneab975d2009-08-29 04:08:08 +0000301 break;
302
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000303 TentativeParsingAction TPA(*this);
Chris Lattner77cf72a2009-06-26 03:47:46 +0000304 SourceLocation TemplateKWLoc = ConsumeToken();
Stephen Hines651f13c2014-04-23 16:59:28 -0700305
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000306 UnqualifiedId TemplateName;
307 if (Tok.is(tok::identifier)) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000308 // Consume the identifier.
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000309 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000310 ConsumeToken();
311 } else if (Tok.is(tok::kw_operator)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700312 // We don't need to actually parse the unqualified-id in this case,
313 // because a simple-template-id cannot start with 'operator', but
314 // go ahead and parse it anyway for consistency with the case where
315 // we already annotated the template-id.
316 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000317 TemplateName)) {
318 TPA.Commit();
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000319 break;
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000320 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700321
Sean Hunte6252d12009-11-28 08:58:14 +0000322 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
323 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000324 Diag(TemplateName.getSourceRange().getBegin(),
325 diag::err_id_after_template_in_nested_name_spec)
326 << TemplateName.getSourceRange();
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000327 TPA.Commit();
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000328 break;
329 }
330 } else {
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000331 TPA.Revert();
Chris Lattner77cf72a2009-06-26 03:47:46 +0000332 break;
333 }
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000335 // If the next token is not '<', we have a qualified-id that refers
336 // to a template name, such as T::template apply, but is not a
337 // template-id.
338 if (Tok.isNot(tok::less)) {
339 TPA.Revert();
340 break;
341 }
342
343 // Commit to parsing the template-id.
344 TPA.Commit();
Douglas Gregord6ab2322010-06-16 23:00:59 +0000345 TemplateTy Template;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000346 if (TemplateNameKind TNK
347 = Actions.ActOnDependentTemplateName(getCurScope(),
348 SS, TemplateKWLoc, TemplateName,
349 ObjectType, EnteringContext,
350 Template)) {
351 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
352 TemplateName, false))
Douglas Gregord6ab2322010-06-16 23:00:59 +0000353 return true;
354 } else
John McCall9ba61662010-02-26 08:45:28 +0000355 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Chris Lattner77cf72a2009-06-26 03:47:46 +0000357 continue;
358 }
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Douglas Gregor39a8de12009-02-25 19:37:18 +0000360 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000361 // We have
Douglas Gregor39a8de12009-02-25 19:37:18 +0000362 //
Stephen Hines651f13c2014-04-23 16:59:28 -0700363 // template-id '::'
Douglas Gregor39a8de12009-02-25 19:37:18 +0000364 //
Stephen Hines651f13c2014-04-23 16:59:28 -0700365 // So we need to check whether the template-id is a simple-template-id of
366 // the right kind (it should name a type or be dependent), and then
Douglas Gregorc45c2322009-03-31 00:43:58 +0000367 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +0000368 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregord4dca082010-02-24 18:44:31 +0000369 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
370 *MayBePseudoDestructor = true;
John McCall9ba61662010-02-26 08:45:28 +0000371 return false;
Douglas Gregord4dca082010-02-24 18:44:31 +0000372 }
373
Richard Smith2db075b2013-03-26 01:15:19 +0000374 if (LastII)
375 *LastII = TemplateId->Name;
376
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000377 // Consume the template-id token.
378 ConsumeToken();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700379
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000380 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
381 SourceLocation CCLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000382
David Blaikie6796fc12011-11-07 03:30:03 +0000383 HasScopeSpecifier = true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700384
Benjamin Kramer5354e772012-08-23 23:38:35 +0000385 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000386 TemplateId->NumArgs);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700387
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000388 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000389 SS,
390 TemplateId->TemplateKWLoc,
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000391 TemplateId->Template,
392 TemplateId->TemplateNameLoc,
393 TemplateId->LAngleLoc,
394 TemplateArgsPtr,
395 TemplateId->RAngleLoc,
396 CCLoc,
397 EnteringContext)) {
398 SourceLocation StartLoc
399 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
400 : TemplateId->TemplateNameLoc;
401 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner67b9e832009-06-26 03:45:46 +0000402 }
Argyrios Kyrtzidiseccce7e2011-05-03 18:45:38 +0000403
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000404 continue;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000405 }
406
Chris Lattner5c7f7862009-06-26 03:52:38 +0000407 // The rest of the nested-name-specifier possibilities start with
408 // tok::identifier.
409 if (Tok.isNot(tok::identifier))
410 break;
411
412 IdentifierInfo &II = *Tok.getIdentifierInfo();
413
414 // nested-name-specifier:
415 // type-name '::'
416 // namespace-name '::'
417 // nested-name-specifier identifier '::'
418 Token Next = NextToken();
Chris Lattner46646492009-12-07 01:36:53 +0000419
420 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
421 // and emit a fixit hint for it.
Douglas Gregorb10cd042010-02-21 18:36:56 +0000422 if (Next.is(tok::colon) && !ColonIsSacred) {
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000423 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
424 Tok.getLocation(),
425 Next.getLocation(), ObjectType,
Douglas Gregorb10cd042010-02-21 18:36:56 +0000426 EnteringContext) &&
427 // If the token after the colon isn't an identifier, it's still an
428 // error, but they probably meant something else strange so don't
429 // recover like this.
430 PP.LookAhead(1).is(tok::identifier)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700431 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
Douglas Gregor849b2432010-03-31 17:46:05 +0000432 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregorb10cd042010-02-21 18:36:56 +0000433 // Recover as if the user wrote '::'.
434 Next.setKind(tok::coloncolon);
435 }
Chris Lattner46646492009-12-07 01:36:53 +0000436 }
437
Chris Lattner5c7f7862009-06-26 03:52:38 +0000438 if (Next.is(tok::coloncolon)) {
Douglas Gregor77549082010-02-24 21:29:12 +0000439 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Stephen Hines176edba2014-12-01 14:53:08 -0800440 !Actions.isNonTypeNestedNameSpecifier(
441 getCurScope(), SS, Tok.getLocation(), II, ObjectType)) {
Douglas Gregord4dca082010-02-24 18:44:31 +0000442 *MayBePseudoDestructor = true;
John McCall9ba61662010-02-26 08:45:28 +0000443 return false;
Douglas Gregord4dca082010-02-24 18:44:31 +0000444 }
445
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700446 if (ColonIsSacred) {
447 const Token &Next2 = GetLookAheadToken(2);
448 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
449 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
450 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
451 << Next2.getName()
452 << FixItHint::CreateReplacement(Next.getLocation(), ":");
453 Token ColonColon;
454 PP.Lex(ColonColon);
455 ColonColon.setKind(tok::colon);
456 PP.EnterToken(ColonColon);
457 break;
458 }
459 }
460
Richard Smith2db075b2013-03-26 01:15:19 +0000461 if (LastII)
462 *LastII = &II;
463
Chris Lattner5c7f7862009-06-26 03:52:38 +0000464 // We have an identifier followed by a '::'. Lookup this name
465 // as the name in a nested-name-specifier.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700466 Token Identifier = Tok;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000467 SourceLocation IdLoc = ConsumeToken();
Chris Lattner46646492009-12-07 01:36:53 +0000468 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
469 "NextToken() not working properly!");
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700470 Token ColonColon = Tok;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000471 SourceLocation CCLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Richard Trieu919b9552012-11-02 01:08:58 +0000473 CheckForLParenAfterColonColon();
474
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700475 bool IsCorrectedToColon = false;
476 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000477 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700478 ObjectType, EnteringContext, SS,
479 false, CorrectionFlagPtr)) {
480 // Identifier is not recognized as a nested name, but we can have
481 // mistyped '::' instead of ':'.
482 if (CorrectionFlagPtr && IsCorrectedToColon) {
483 ColonColon.setKind(tok::colon);
484 PP.EnterToken(Tok);
485 PP.EnterToken(ColonColon);
486 Tok = Identifier;
487 break;
488 }
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000489 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700490 }
491 HasScopeSpecifier = true;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000492 continue;
493 }
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Richard Trieu950be712011-09-19 19:01:00 +0000495 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smithea698b32011-04-14 21:45:45 +0000496
Chris Lattner5c7f7862009-06-26 03:52:38 +0000497 // nested-name-specifier:
498 // type-name '<'
499 if (Next.is(tok::less)) {
500 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000501 UnqualifiedId TemplateName;
502 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000503 bool MemberOfUnknownSpecialization;
Douglas Gregor23c94db2010-07-02 17:43:08 +0000504 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c153532010-08-06 12:11:11 +0000505 /*hasTemplateKeyword=*/false,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000506 TemplateName,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000507 ObjectType,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000508 EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000509 Template,
510 MemberOfUnknownSpecialization)) {
David Blaikie6796fc12011-11-07 03:30:03 +0000511 // We have found a template name, so annotate this token
Chris Lattner5c7f7862009-06-26 03:52:38 +0000512 // with a template-id annotation. We do not permit the
513 // template-id to be translated into a type annotation,
514 // because some clients (e.g., the parsing of class template
515 // specializations) still want to see the original template-id
516 // token.
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000517 ConsumeToken();
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000518 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
519 TemplateName, false))
John McCall9ba61662010-02-26 08:45:28 +0000520 return true;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000521 continue;
Larisse Voufoef4579c2013-08-06 01:03:05 +0000522 }
523
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000524 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4147d302011-03-27 19:41:34 +0000525 (IsTypename || IsTemplateArgumentList(1))) {
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000526 // We have something like t::getAs<T>, where getAs is a
527 // member of an unknown specialization. However, this will only
528 // parse correctly as a template, so suggest the keyword 'template'
529 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4147d302011-03-27 19:41:34 +0000530 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikie4e4d0842012-03-11 07:00:24 +0000531 if (getLangOpts().MicrosoftExt)
Francois Pichetcf320c62011-04-22 08:25:24 +0000532 DiagID = diag::warn_missing_dependent_template_keyword;
Francois Pichet4147d302011-03-27 19:41:34 +0000533
534 Diag(Tok.getLocation(), DiagID)
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000535 << II.getName()
536 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
537
Douglas Gregord6ab2322010-06-16 23:00:59 +0000538 if (TemplateNameKind TNK
Douglas Gregor23c94db2010-07-02 17:43:08 +0000539 = Actions.ActOnDependentTemplateName(getCurScope(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000540 SS, SourceLocation(),
Douglas Gregord6ab2322010-06-16 23:00:59 +0000541 TemplateName, ObjectType,
542 EnteringContext, Template)) {
543 // Consume the identifier.
544 ConsumeToken();
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000545 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
546 TemplateName, false))
547 return true;
Douglas Gregord6ab2322010-06-16 23:00:59 +0000548 }
549 else
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000550 return true;
Douglas Gregord6ab2322010-06-16 23:00:59 +0000551
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000552 continue;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000553 }
554 }
555
Douglas Gregor39a8de12009-02-25 19:37:18 +0000556 // We don't have any tokens that form the beginning of a
557 // nested-name-specifier, so we're done.
558 break;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000559 }
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Douglas Gregord4dca082010-02-24 18:44:31 +0000561 // Even if we didn't see any pieces of a nested-name-specifier, we
562 // still check whether there is a tilde in this position, which
563 // indicates a potential pseudo-destructor.
564 if (CheckForDestructor && Tok.is(tok::tilde))
565 *MayBePseudoDestructor = true;
566
John McCall9ba61662010-02-26 08:45:28 +0000567 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000568}
569
Stephen Hines176edba2014-12-01 14:53:08 -0800570ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
571 Token &Replacement) {
572 SourceLocation TemplateKWLoc;
573 UnqualifiedId Name;
574 if (ParseUnqualifiedId(SS,
575 /*EnteringContext=*/false,
576 /*AllowDestructorName=*/false,
577 /*AllowConstructorName=*/false,
578 /*ObjectType=*/ParsedType(), TemplateKWLoc, Name))
579 return ExprError();
580
581 // This is only the direct operand of an & operator if it is not
582 // followed by a postfix-expression suffix.
583 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
584 isAddressOfOperand = false;
585
586 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
587 Tok.is(tok::l_paren), isAddressOfOperand,
588 nullptr, /*IsInlineAsmIdentifier=*/false,
589 &Replacement);
590}
591
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000592/// ParseCXXIdExpression - Handle id-expression.
593///
594/// id-expression:
595/// unqualified-id
596/// qualified-id
597///
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000598/// qualified-id:
599/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
600/// '::' identifier
601/// '::' operator-function-id
Douglas Gregoredce4dd2009-06-30 22:34:41 +0000602/// '::' template-id
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000603///
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000604/// NOTE: The standard specifies that, for qualified-id, the parser does not
605/// expect:
606///
607/// '::' conversion-function-id
608/// '::' '~' class-name
609///
610/// This may cause a slight inconsistency on diagnostics:
611///
612/// class C {};
613/// namespace A {}
614/// void f() {
615/// :: A :: ~ C(); // Some Sema error about using destructor with a
616/// // namespace.
617/// :: ~ C(); // Some Parser error like 'unexpected ~'.
618/// }
619///
620/// We simplify the parser a bit and make it work like:
621///
622/// qualified-id:
623/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
624/// '::' unqualified-id
625///
626/// That way Sema can handle and report similar errors for namespaces and the
627/// global scope.
628///
Sebastian Redlebc07d52009-02-03 20:19:35 +0000629/// The isAddressOfOperand parameter indicates that this id-expression is a
630/// direct operand of the address-of operator. This is, besides member contexts,
631/// the only place where a qualified-id naming a non-static class member may
632/// appear.
633///
John McCall60d7b3a2010-08-24 06:29:42 +0000634ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000635 // qualified-id:
636 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
637 // '::' unqualified-id
638 //
639 CXXScopeSpec SS;
Douglas Gregorefaa93a2011-11-07 17:33:42 +0000640 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000641
Stephen Hines176edba2014-12-01 14:53:08 -0800642 Token Replacement;
643 ExprResult Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
644 if (Result.isUnset()) {
645 // If the ExprResult is valid but null, then typo correction suggested a
646 // keyword replacement that needs to be reparsed.
647 UnconsumeToken(Replacement);
648 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
649 }
650 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
651 "for a previous keyword suggestion");
652 return Result;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000653}
654
Richard Smith0a664b82013-05-09 21:36:41 +0000655/// ParseLambdaExpression - Parse a C++11 lambda expression.
Douglas Gregorae7902c2011-08-04 15:30:47 +0000656///
657/// lambda-expression:
658/// lambda-introducer lambda-declarator[opt] compound-statement
659///
660/// lambda-introducer:
661/// '[' lambda-capture[opt] ']'
662///
663/// lambda-capture:
664/// capture-default
665/// capture-list
666/// capture-default ',' capture-list
667///
668/// capture-default:
669/// '&'
670/// '='
671///
672/// capture-list:
673/// capture
674/// capture-list ',' capture
675///
676/// capture:
Richard Smith0a664b82013-05-09 21:36:41 +0000677/// simple-capture
678/// init-capture [C++1y]
679///
680/// simple-capture:
Douglas Gregorae7902c2011-08-04 15:30:47 +0000681/// identifier
682/// '&' identifier
683/// 'this'
684///
Richard Smith0a664b82013-05-09 21:36:41 +0000685/// init-capture: [C++1y]
686/// identifier initializer
687/// '&' identifier initializer
688///
Douglas Gregorae7902c2011-08-04 15:30:47 +0000689/// lambda-declarator:
690/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
691/// 'mutable'[opt] exception-specification[opt]
692/// trailing-return-type[opt]
693///
694ExprResult Parser::ParseLambdaExpression() {
695 // Parse lambda-introducer.
696 LambdaIntroducer Intro;
Bill Wendling2434dcf2013-12-05 05:25:04 +0000697 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
Douglas Gregorae7902c2011-08-04 15:30:47 +0000698 if (DiagID) {
699 Diag(Tok, DiagID.getValue());
Alexey Bataev8fe24752013-11-18 08:17:37 +0000700 SkipUntil(tok::r_square, StopAtSemi);
701 SkipUntil(tok::l_brace, StopAtSemi);
702 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmandc3b7232012-01-04 02:40:39 +0000703 return ExprError();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000704 }
705
706 return ParseLambdaExpressionAfterIntroducer(Intro);
707}
708
709/// TryParseLambdaExpression - Use lookahead and potentially tentative
710/// parsing to determine if we are looking at a C++0x lambda expression, and parse
711/// it if we are.
712///
713/// If we are not looking at a lambda expression, returns ExprError().
714ExprResult Parser::TryParseLambdaExpression() {
Richard Smith80ad52f2013-01-02 11:42:31 +0000715 assert(getLangOpts().CPlusPlus11
Douglas Gregorae7902c2011-08-04 15:30:47 +0000716 && Tok.is(tok::l_square)
717 && "Not at the start of a possible lambda expression.");
718
719 const Token Next = NextToken(), After = GetLookAheadToken(2);
720
721 // If lookahead indicates this is a lambda...
722 if (Next.is(tok::r_square) || // []
723 Next.is(tok::equal) || // [=
724 (Next.is(tok::amp) && // [&] or [&,
725 (After.is(tok::r_square) ||
726 After.is(tok::comma))) ||
727 (Next.is(tok::identifier) && // [identifier]
728 After.is(tok::r_square))) {
729 return ParseLambdaExpression();
730 }
731
Eli Friedmandc3b7232012-01-04 02:40:39 +0000732 // If lookahead indicates an ObjC message send...
733 // [identifier identifier
Douglas Gregorae7902c2011-08-04 15:30:47 +0000734 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmandc3b7232012-01-04 02:40:39 +0000735 return ExprEmpty();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000736 }
Bill Wendling2434dcf2013-12-05 05:25:04 +0000737
Eli Friedmandc3b7232012-01-04 02:40:39 +0000738 // Here, we're stuck: lambda introducers and Objective-C message sends are
739 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
740 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
741 // writing two routines to parse a lambda introducer, just try to parse
742 // a lambda introducer first, and fall back if that fails.
743 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregorae7902c2011-08-04 15:30:47 +0000744 LambdaIntroducer Intro;
745 if (TryParseLambdaIntroducer(Intro))
Eli Friedmandc3b7232012-01-04 02:40:39 +0000746 return ExprEmpty();
Bill Wendling2434dcf2013-12-05 05:25:04 +0000747
Douglas Gregorae7902c2011-08-04 15:30:47 +0000748 return ParseLambdaExpressionAfterIntroducer(Intro);
749}
750
Richard Smith440d4562013-05-21 22:21:19 +0000751/// \brief Parse a lambda introducer.
752/// \param Intro A LambdaIntroducer filled in with information about the
753/// contents of the lambda-introducer.
754/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
755/// message send and a lambda expression. In this mode, we will
756/// sometimes skip the initializers for init-captures and not fully
757/// populate \p Intro. This flag will be set to \c true if we do so.
758/// \return A DiagnosticID if it hit something unexpected. The location for
759/// for the diagnostic is that of the current token.
760Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
761 bool *SkippedInits) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000762 typedef Optional<unsigned> DiagResult;
Douglas Gregorae7902c2011-08-04 15:30:47 +0000763
764 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000765 BalancedDelimiterTracker T(*this, tok::l_square);
766 T.consumeOpen();
767
768 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregorae7902c2011-08-04 15:30:47 +0000769
770 bool first = true;
771
772 // Parse capture-default.
773 if (Tok.is(tok::amp) &&
774 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
775 Intro.Default = LCD_ByRef;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000776 Intro.DefaultLoc = ConsumeToken();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000777 first = false;
778 } else if (Tok.is(tok::equal)) {
779 Intro.Default = LCD_ByCopy;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000780 Intro.DefaultLoc = ConsumeToken();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000781 first = false;
782 }
783
784 while (Tok.isNot(tok::r_square)) {
785 if (!first) {
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000786 if (Tok.isNot(tok::comma)) {
Douglas Gregor437fbc52012-07-31 00:50:07 +0000787 // Provide a completion for a lambda introducer here. Except
788 // in Objective-C, where this is Almost Surely meant to be a message
789 // send. In that case, fail here and let the ObjC message
790 // expression parser perform the completion.
Douglas Gregord48ab062012-07-31 15:27:48 +0000791 if (Tok.is(tok::code_completion) &&
792 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
793 !Intro.Captures.empty())) {
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000794 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
795 /*AfterAmpersand=*/false);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700796 cutOffParsing();
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000797 break;
798 }
799
Douglas Gregorae7902c2011-08-04 15:30:47 +0000800 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000801 }
Douglas Gregorae7902c2011-08-04 15:30:47 +0000802 ConsumeToken();
803 }
804
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000805 if (Tok.is(tok::code_completion)) {
806 // If we're in Objective-C++ and we have a bare '[', then this is more
807 // likely to be a message receiver.
David Blaikie4e4d0842012-03-11 07:00:24 +0000808 if (getLangOpts().ObjC1 && first)
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000809 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
810 else
811 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
812 /*AfterAmpersand=*/false);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700813 cutOffParsing();
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000814 break;
815 }
Douglas Gregorae7902c2011-08-04 15:30:47 +0000816
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000817 first = false;
818
Douglas Gregorae7902c2011-08-04 15:30:47 +0000819 // Parse capture.
820 LambdaCaptureKind Kind = LCK_ByCopy;
821 SourceLocation Loc;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700822 IdentifierInfo *Id = nullptr;
Douglas Gregora7365242012-02-14 19:27:52 +0000823 SourceLocation EllipsisLoc;
Richard Smith0a664b82013-05-09 21:36:41 +0000824 ExprResult Init;
Douglas Gregora7365242012-02-14 19:27:52 +0000825
Douglas Gregorae7902c2011-08-04 15:30:47 +0000826 if (Tok.is(tok::kw_this)) {
827 Kind = LCK_This;
828 Loc = ConsumeToken();
829 } else {
830 if (Tok.is(tok::amp)) {
831 Kind = LCK_ByRef;
832 ConsumeToken();
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000833
834 if (Tok.is(tok::code_completion)) {
835 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
836 /*AfterAmpersand=*/true);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700837 cutOffParsing();
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000838 break;
839 }
Douglas Gregorae7902c2011-08-04 15:30:47 +0000840 }
841
842 if (Tok.is(tok::identifier)) {
843 Id = Tok.getIdentifierInfo();
844 Loc = ConsumeToken();
845 } else if (Tok.is(tok::kw_this)) {
846 // FIXME: If we want to suggest a fixit here, will need to return more
847 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
848 // Clear()ed to prevent emission in case of tentative parsing?
849 return DiagResult(diag::err_this_captured_by_reference);
850 } else {
851 return DiagResult(diag::err_expected_capture);
852 }
Richard Smith0a664b82013-05-09 21:36:41 +0000853
854 if (Tok.is(tok::l_paren)) {
855 BalancedDelimiterTracker Parens(*this, tok::l_paren);
856 Parens.consumeOpen();
857
858 ExprVector Exprs;
859 CommaLocsTy Commas;
Richard Smith440d4562013-05-21 22:21:19 +0000860 if (SkippedInits) {
861 Parens.skipToEnd();
862 *SkippedInits = true;
863 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith0a664b82013-05-09 21:36:41 +0000864 Parens.skipToEnd();
865 Init = ExprError();
866 } else {
867 Parens.consumeClose();
868 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
869 Parens.getCloseLocation(),
870 Exprs);
871 }
872 } else if (Tok.is(tok::l_brace) || Tok.is(tok::equal)) {
Bill Wendling2434dcf2013-12-05 05:25:04 +0000873 // Each lambda init-capture forms its own full expression, which clears
874 // Actions.MaybeODRUseExprs. So create an expression evaluation context
875 // to save the necessary state, and restore it later.
876 EnterExpressionEvaluationContext EC(Actions,
877 Sema::PotentiallyEvaluated);
Stephen Hines651f13c2014-04-23 16:59:28 -0700878 TryConsumeToken(tok::equal);
Richard Smith0a664b82013-05-09 21:36:41 +0000879
Richard Smith440d4562013-05-21 22:21:19 +0000880 if (!SkippedInits)
881 Init = ParseInitializer();
882 else if (Tok.is(tok::l_brace)) {
883 BalancedDelimiterTracker Braces(*this, tok::l_brace);
884 Braces.consumeOpen();
885 Braces.skipToEnd();
886 *SkippedInits = true;
887 } else {
888 // We're disambiguating this:
889 //
890 // [..., x = expr
891 //
892 // We need to find the end of the following expression in order to
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700893 // determine whether this is an Obj-C message send's receiver, a
894 // C99 designator, or a lambda init-capture.
Richard Smith440d4562013-05-21 22:21:19 +0000895 //
896 // Parse the expression to find where it ends, and annotate it back
897 // onto the tokens. We would have parsed this expression the same way
898 // in either case: both the RHS of an init-capture and the RHS of an
899 // assignment expression are parsed as an initializer-clause, and in
900 // neither case can anything be added to the scope between the '[' and
901 // here.
902 //
903 // FIXME: This is horrible. Adding a mechanism to skip an expression
904 // would be much cleaner.
905 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
906 // that instead. (And if we see a ':' with no matching '?', we can
907 // classify this as an Obj-C message send.)
908 SourceLocation StartLoc = Tok.getLocation();
909 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
910 Init = ParseInitializer();
911
912 if (Tok.getLocation() != StartLoc) {
913 // Back out the lexing of the token after the initializer.
914 PP.RevertCachedTokens(1);
915
916 // Replace the consumed tokens with an appropriate annotation.
917 Tok.setLocation(StartLoc);
918 Tok.setKind(tok::annot_primary_expr);
919 setExprAnnotation(Tok, Init);
920 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
921 PP.AnnotateCachedTokens(Tok);
922
923 // Consume the annotated initializer.
924 ConsumeToken();
925 }
926 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700927 } else
928 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Douglas Gregorae7902c2011-08-04 15:30:47 +0000929 }
Bill Wendling2434dcf2013-12-05 05:25:04 +0000930 // If this is an init capture, process the initialization expression
931 // right away. For lambda init-captures such as the following:
932 // const int x = 10;
933 // auto L = [i = x+1](int a) {
934 // return [j = x+2,
935 // &k = x](char b) { };
936 // };
937 // keep in mind that each lambda init-capture has to have:
938 // - its initialization expression executed in the context
939 // of the enclosing/parent decl-context.
940 // - but the variable itself has to be 'injected' into the
941 // decl-context of its lambda's call-operator (which has
942 // not yet been created).
943 // Each init-expression is a full-expression that has to get
944 // Sema-analyzed (for capturing etc.) before its lambda's
945 // call-operator's decl-context, scope & scopeinfo are pushed on their
946 // respective stacks. Thus if any variable is odr-used in the init-capture
947 // it will correctly get captured in the enclosing lambda, if one exists.
948 // The init-variables above are created later once the lambdascope and
949 // call-operators decl-context is pushed onto its respective stack.
Douglas Gregorae7902c2011-08-04 15:30:47 +0000950
Bill Wendling2434dcf2013-12-05 05:25:04 +0000951 // Since the lambda init-capture's initializer expression occurs in the
952 // context of the enclosing function or lambda, therefore we can not wait
953 // till a lambda scope has been pushed on before deciding whether the
954 // variable needs to be captured. We also need to process all
955 // lvalue-to-rvalue conversions and discarded-value conversions,
956 // so that we can avoid capturing certain constant variables.
957 // For e.g.,
958 // void test() {
959 // const int x = 10;
960 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
961 // return [y = x](int i) { <-- don't capture by enclosing lambda
962 // return y;
963 // }
964 // };
965 // If x was not const, the second use would require 'L' to capture, and
966 // that would be an error.
967
968 ParsedType InitCaptureParsedType;
969 if (Init.isUsable()) {
970 // Get the pointer and store it in an lvalue, so we can use it as an
971 // out argument.
972 Expr *InitExpr = Init.get();
973 // This performs any lvalue-to-rvalue conversions if necessary, which
974 // can affect what gets captured in the containing decl-context.
975 QualType InitCaptureType = Actions.performLambdaInitCaptureInitialization(
976 Loc, Kind == LCK_ByRef, Id, InitExpr);
977 Init = InitExpr;
978 InitCaptureParsedType.set(InitCaptureType);
979 }
980 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init, InitCaptureParsedType);
Douglas Gregorae7902c2011-08-04 15:30:47 +0000981 }
982
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000983 T.consumeClose();
984 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregorae7902c2011-08-04 15:30:47 +0000985 return DiagResult();
986}
987
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000988/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregorae7902c2011-08-04 15:30:47 +0000989///
990/// Returns true if it hit something unexpected.
991bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
992 TentativeParsingAction PA(*this);
993
Richard Smith440d4562013-05-21 22:21:19 +0000994 bool SkippedInits = false;
995 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
Douglas Gregorae7902c2011-08-04 15:30:47 +0000996
997 if (DiagID) {
998 PA.Revert();
999 return true;
1000 }
1001
Richard Smith440d4562013-05-21 22:21:19 +00001002 if (SkippedInits) {
1003 // Parse it again, but this time parse the init-captures too.
1004 PA.Revert();
1005 Intro = LambdaIntroducer();
1006 DiagID = ParseLambdaIntroducer(Intro);
1007 assert(!DiagID && "parsing lambda-introducer failed on reparse");
1008 return false;
1009 }
1010
Douglas Gregorae7902c2011-08-04 15:30:47 +00001011 PA.Commit();
1012 return false;
1013}
1014
1015/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1016/// expression.
1017ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1018 LambdaIntroducer &Intro) {
Eli Friedmandc3b7232012-01-04 02:40:39 +00001019 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1020 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1021
1022 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1023 "lambda expression parsing");
1024
Faisal Valifad9e132013-09-26 19:54:12 +00001025
1026
Richard Smith0a664b82013-05-09 21:36:41 +00001027 // FIXME: Call into Actions to add any init-capture declarations to the
1028 // scope while parsing the lambda-declarator and compound-statement.
1029
Douglas Gregorae7902c2011-08-04 15:30:47 +00001030 // Parse lambda-declarator[opt].
1031 DeclSpec DS(AttrFactory);
Eli Friedmanf88c4002012-01-04 04:41:38 +00001032 Declarator D(DS, Declarator::LambdaExprContext);
Faisal Valifad9e132013-09-26 19:54:12 +00001033 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1034 Actions.PushLambdaScope();
Douglas Gregorae7902c2011-08-04 15:30:47 +00001035
1036 if (Tok.is(tok::l_paren)) {
1037 ParseScope PrototypeScope(this,
1038 Scope::FunctionPrototypeScope |
Richard Smith3a2b7a12013-01-28 22:42:45 +00001039 Scope::FunctionDeclarationScope |
Douglas Gregorae7902c2011-08-04 15:30:47 +00001040 Scope::DeclScope);
1041
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001042 SourceLocation DeclEndLoc;
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001043 BalancedDelimiterTracker T(*this, tok::l_paren);
1044 T.consumeOpen();
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001045 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregorae7902c2011-08-04 15:30:47 +00001046
1047 // Parse parameter-declaration-clause.
1048 ParsedAttributes Attr(AttrFactory);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001049 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001050 SourceLocation EllipsisLoc;
Faisal Valifad9e132013-09-26 19:54:12 +00001051
1052 if (Tok.isNot(tok::r_paren)) {
Faisal Valifad9e132013-09-26 19:54:12 +00001053 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
Douglas Gregorae7902c2011-08-04 15:30:47 +00001054 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
Faisal Valifad9e132013-09-26 19:54:12 +00001055 // For a generic lambda, each 'auto' within the parameter declaration
1056 // clause creates a template type parameter, so increment the depth.
1057 if (Actions.getCurGenericLambda())
1058 ++CurTemplateDepthTracker;
1059 }
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001060 T.consumeClose();
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001061 SourceLocation RParenLoc = T.getCloseLocation();
1062 DeclEndLoc = RParenLoc;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001063
Stephen Hines651f13c2014-04-23 16:59:28 -07001064 // GNU-style attributes must be parsed before the mutable specifier to be
1065 // compatible with GCC.
1066 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1067
Douglas Gregorae7902c2011-08-04 15:30:47 +00001068 // Parse 'mutable'[opt].
1069 SourceLocation MutableLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -07001070 if (TryConsumeToken(tok::kw_mutable, MutableLoc))
Douglas Gregorae7902c2011-08-04 15:30:47 +00001071 DeclEndLoc = MutableLoc;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001072
1073 // Parse exception-specification[opt].
1074 ExceptionSpecificationType ESpecType = EST_None;
1075 SourceRange ESpecRange;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001076 SmallVector<ParsedType, 2> DynamicExceptions;
1077 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001078 ExprResult NoexceptExpr;
Stephen Hines176edba2014-12-01 14:53:08 -08001079 CachedTokens *ExceptionSpecTokens;
1080 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1081 ESpecRange,
Douglas Gregor74e2fc32012-04-16 18:27:27 +00001082 DynamicExceptions,
1083 DynamicExceptionRanges,
Stephen Hines176edba2014-12-01 14:53:08 -08001084 NoexceptExpr,
1085 ExceptionSpecTokens);
Douglas Gregorae7902c2011-08-04 15:30:47 +00001086
1087 if (ESpecType != EST_None)
1088 DeclEndLoc = ESpecRange.getEnd();
1089
1090 // Parse attribute-specifier[opt].
Richard Smith4e24f0f2013-01-02 12:01:23 +00001091 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregorae7902c2011-08-04 15:30:47 +00001092
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001093 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1094
Douglas Gregorae7902c2011-08-04 15:30:47 +00001095 // Parse trailing-return-type[opt].
Richard Smith54655be2012-06-12 01:51:59 +00001096 TypeResult TrailingReturnType;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001097 if (Tok.is(tok::arrow)) {
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001098 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregorae7902c2011-08-04 15:30:47 +00001099 SourceRange Range;
Richard Smith54655be2012-06-12 01:51:59 +00001100 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregorae7902c2011-08-04 15:30:47 +00001101 if (Range.getEnd().isValid())
1102 DeclEndLoc = Range.getEnd();
1103 }
1104
1105 PrototypeScope.Exit();
1106
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001107 SourceLocation NoLoc;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001108 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001109 /*isAmbiguous=*/false,
1110 LParenLoc,
Douglas Gregorae7902c2011-08-04 15:30:47 +00001111 ParamInfo.data(), ParamInfo.size(),
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001112 EllipsisLoc, RParenLoc,
Douglas Gregorae7902c2011-08-04 15:30:47 +00001113 DS.getTypeQualifiers(),
1114 /*RefQualifierIsLValueRef=*/true,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001115 /*RefQualifierLoc=*/NoLoc,
1116 /*ConstQualifierLoc=*/NoLoc,
1117 /*VolatileQualifierLoc=*/NoLoc,
Stephen Hines176edba2014-12-01 14:53:08 -08001118 /*RestrictQualifierLoc=*/NoLoc,
Douglas Gregorae7902c2011-08-04 15:30:47 +00001119 MutableLoc,
1120 ESpecType, ESpecRange.getBegin(),
1121 DynamicExceptions.data(),
1122 DynamicExceptionRanges.data(),
1123 DynamicExceptions.size(),
1124 NoexceptExpr.isUsable() ?
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001125 NoexceptExpr.get() : nullptr,
Stephen Hines176edba2014-12-01 14:53:08 -08001126 /*ExceptionSpecTokens*/nullptr,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001127 LParenLoc, FunLocalRangeEnd, D,
Douglas Gregorae7902c2011-08-04 15:30:47 +00001128 TrailingReturnType),
1129 Attr, DeclEndLoc);
Stephen Hines651f13c2014-04-23 16:59:28 -07001130 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow) ||
1131 Tok.is(tok::kw___attribute) ||
1132 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1133 // It's common to forget that one needs '()' before 'mutable', an attribute
1134 // specifier, or the result type. Deal with this.
1135 unsigned TokKind = 0;
1136 switch (Tok.getKind()) {
1137 case tok::kw_mutable: TokKind = 0; break;
1138 case tok::arrow: TokKind = 1; break;
1139 case tok::kw___attribute:
1140 case tok::l_square: TokKind = 2; break;
1141 default: llvm_unreachable("Unknown token kind");
1142 }
1143
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001144 Diag(Tok, diag::err_lambda_missing_parens)
Stephen Hines651f13c2014-04-23 16:59:28 -07001145 << TokKind
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001146 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1147 SourceLocation DeclLoc = Tok.getLocation();
1148 SourceLocation DeclEndLoc = DeclLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -07001149
1150 // GNU-style attributes must be parsed before the mutable specifier to be
1151 // compatible with GCC.
1152 ParsedAttributes Attr(AttrFactory);
1153 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1154
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001155 // Parse 'mutable', if it's there.
1156 SourceLocation MutableLoc;
1157 if (Tok.is(tok::kw_mutable)) {
1158 MutableLoc = ConsumeToken();
1159 DeclEndLoc = MutableLoc;
1160 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001161
1162 // Parse attribute-specifier[opt].
1163 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1164
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001165 // Parse the return type, if there is one.
Richard Smith54655be2012-06-12 01:51:59 +00001166 TypeResult TrailingReturnType;
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001167 if (Tok.is(tok::arrow)) {
1168 SourceRange Range;
Richard Smith54655be2012-06-12 01:51:59 +00001169 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001170 if (Range.getEnd().isValid())
1171 DeclEndLoc = Range.getEnd();
1172 }
1173
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001174 SourceLocation NoLoc;
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001175 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001176 /*isAmbiguous=*/false,
1177 /*LParenLoc=*/NoLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001178 /*Params=*/nullptr,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001179 /*NumParams=*/0,
1180 /*EllipsisLoc=*/NoLoc,
1181 /*RParenLoc=*/NoLoc,
1182 /*TypeQuals=*/0,
1183 /*RefQualifierIsLValueRef=*/true,
1184 /*RefQualifierLoc=*/NoLoc,
1185 /*ConstQualifierLoc=*/NoLoc,
1186 /*VolatileQualifierLoc=*/NoLoc,
Stephen Hines176edba2014-12-01 14:53:08 -08001187 /*RestrictQualifierLoc=*/NoLoc,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001188 MutableLoc,
1189 EST_None,
1190 /*ESpecLoc=*/NoLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001191 /*Exceptions=*/nullptr,
1192 /*ExceptionRanges=*/nullptr,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001193 /*NumExceptions=*/0,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001194 /*NoexceptExpr=*/nullptr,
Stephen Hines176edba2014-12-01 14:53:08 -08001195 /*ExceptionSpecTokens=*/nullptr,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001196 DeclLoc, DeclEndLoc, D,
1197 TrailingReturnType),
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001198 Attr, DeclEndLoc);
Douglas Gregorae7902c2011-08-04 15:30:47 +00001199 }
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001200
Douglas Gregorae7902c2011-08-04 15:30:47 +00001201
Eli Friedman906a7e12012-01-06 03:05:34 +00001202 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1203 // it.
Douglas Gregorfccfb622012-02-21 22:51:27 +00001204 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
Douglas Gregorfccfb622012-02-21 22:51:27 +00001205 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman906a7e12012-01-06 03:05:34 +00001206
Eli Friedmanec9ea722012-01-05 03:35:19 +00001207 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1208
Douglas Gregorae7902c2011-08-04 15:30:47 +00001209 // Parse compound-statement.
Eli Friedmandc3b7232012-01-04 02:40:39 +00001210 if (!Tok.is(tok::l_brace)) {
Douglas Gregorae7902c2011-08-04 15:30:47 +00001211 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmandc3b7232012-01-04 02:40:39 +00001212 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1213 return ExprError();
Douglas Gregorae7902c2011-08-04 15:30:47 +00001214 }
1215
Eli Friedmandc3b7232012-01-04 02:40:39 +00001216 StmtResult Stmt(ParseCompoundStatementBody());
1217 BodyScope.Exit();
1218
Eli Friedmandeeab902012-01-04 02:46:53 +00001219 if (!Stmt.isInvalid())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001220 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
Eli Friedmandc3b7232012-01-04 02:40:39 +00001221
Eli Friedmandeeab902012-01-04 02:46:53 +00001222 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1223 return ExprError();
Douglas Gregorae7902c2011-08-04 15:30:47 +00001224}
1225
Reid Spencer5f016e22007-07-11 17:01:13 +00001226/// ParseCXXCasts - This handles the various ways to cast expressions to another
1227/// type.
1228///
1229/// postfix-expression: [C++ 5.2p1]
1230/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1231/// 'static_cast' '<' type-name '>' '(' expression ')'
1232/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1233/// 'const_cast' '<' type-name '>' '(' expression ')'
1234///
John McCall60d7b3a2010-08-24 06:29:42 +00001235ExprResult Parser::ParseCXXCasts() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001236 tok::TokenKind Kind = Tok.getKind();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001237 const char *CastName = nullptr; // For error messages
Reid Spencer5f016e22007-07-11 17:01:13 +00001238
1239 switch (Kind) {
David Blaikieeb2d1f12011-09-23 20:26:49 +00001240 default: llvm_unreachable("Unknown C++ cast!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 case tok::kw_const_cast: CastName = "const_cast"; break;
1242 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1243 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1244 case tok::kw_static_cast: CastName = "static_cast"; break;
1245 }
1246
1247 SourceLocation OpLoc = ConsumeToken();
1248 SourceLocation LAngleBracketLoc = Tok.getLocation();
1249
Richard Smithea698b32011-04-14 21:45:45 +00001250 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1251 // diagnose error, suggest fix, and recover parsing.
Richard Smith78fe3e02012-08-20 17:37:52 +00001252 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1253 Token Next = NextToken();
1254 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1255 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1256 }
Richard Smithea698b32011-04-14 21:45:45 +00001257
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redl20df9b72008-12-11 22:51:44 +00001259 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001260
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00001261 // Parse the common declaration-specifiers piece.
1262 DeclSpec DS(AttrFactory);
1263 ParseSpecifierQualifierList(DS);
1264
1265 // Parse the abstract-declarator, if present.
1266 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1267 ParseDeclarator(DeclaratorInfo);
1268
Reid Spencer5f016e22007-07-11 17:01:13 +00001269 SourceLocation RAngleBracketLoc = Tok.getLocation();
1270
Stephen Hines651f13c2014-04-23 16:59:28 -07001271 if (ExpectAndConsume(tok::greater))
1272 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001273
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001274 SourceLocation LParenLoc, RParenLoc;
1275 BalancedDelimiterTracker T(*this, tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00001276
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001277 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis21e7ad22009-05-22 10:23:16 +00001278 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001279
John McCall60d7b3a2010-08-24 06:29:42 +00001280 ExprResult Result = ParseExpression();
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Argyrios Kyrtzidis21e7ad22009-05-22 10:23:16 +00001282 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001283 T.consumeClose();
Reid Spencer5f016e22007-07-11 17:01:13 +00001284
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00001285 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregor49badde2008-10-27 19:41:14 +00001286 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00001287 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor809070a2009-02-18 17:45:20 +00001288 RAngleBracketLoc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001289 T.getOpenLocation(), Result.get(),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001290 T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001291
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001292 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00001293}
1294
Sebastian Redlc42e1182008-11-11 11:37:55 +00001295/// ParseCXXTypeid - This handles the C++ typeid expression.
1296///
1297/// postfix-expression: [C++ 5.2p1]
1298/// 'typeid' '(' expression ')'
1299/// 'typeid' '(' type-id ')'
1300///
John McCall60d7b3a2010-08-24 06:29:42 +00001301ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc42e1182008-11-11 11:37:55 +00001302 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1303
1304 SourceLocation OpLoc = ConsumeToken();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001305 SourceLocation LParenLoc, RParenLoc;
1306 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc42e1182008-11-11 11:37:55 +00001307
1308 // typeid expressions are always parenthesized.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001309 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redl20df9b72008-12-11 22:51:44 +00001310 return ExprError();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001311 LParenLoc = T.getOpenLocation();
Sebastian Redlc42e1182008-11-11 11:37:55 +00001312
John McCall60d7b3a2010-08-24 06:29:42 +00001313 ExprResult Result;
Sebastian Redlc42e1182008-11-11 11:37:55 +00001314
Richard Smith05766812012-08-18 00:55:03 +00001315 // C++0x [expr.typeid]p3:
1316 // When typeid is applied to an expression other than an lvalue of a
1317 // polymorphic class type [...] The expression is an unevaluated
1318 // operand (Clause 5).
1319 //
1320 // Note that we can't tell whether the expression is an lvalue of a
1321 // polymorphic class type until after we've parsed the expression; we
1322 // speculatively assume the subexpression is unevaluated, and fix it up
1323 // later.
1324 //
1325 // We enter the unevaluated context before trying to determine whether we
1326 // have a type-id, because the tentative parse logic will try to resolve
1327 // names, and must treat them as unevaluated.
Eli Friedman80bfa3d2012-09-26 04:34:21 +00001328 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1329 Sema::ReuseLambdaContextDecl);
Richard Smith05766812012-08-18 00:55:03 +00001330
Sebastian Redlc42e1182008-11-11 11:37:55 +00001331 if (isTypeIdInParens()) {
Douglas Gregor809070a2009-02-18 17:45:20 +00001332 TypeResult Ty = ParseTypeName();
Sebastian Redlc42e1182008-11-11 11:37:55 +00001333
1334 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001335 T.consumeClose();
1336 RParenLoc = T.getCloseLocation();
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +00001337 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redl20df9b72008-12-11 22:51:44 +00001338 return ExprError();
Sebastian Redlc42e1182008-11-11 11:37:55 +00001339
1340 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallb3d87482010-08-24 05:47:05 +00001341 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +00001342 } else {
1343 Result = ParseExpression();
1344
1345 // Match the ')'.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001346 if (Result.isInvalid())
Alexey Bataev8fe24752013-11-18 08:17:37 +00001347 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc42e1182008-11-11 11:37:55 +00001348 else {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001349 T.consumeClose();
1350 RParenLoc = T.getCloseLocation();
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +00001351 if (RParenLoc.isInvalid())
1352 return ExprError();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001353
Sebastian Redlc42e1182008-11-11 11:37:55 +00001354 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001355 Result.get(), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +00001356 }
1357 }
1358
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001359 return Result;
Sebastian Redlc42e1182008-11-11 11:37:55 +00001360}
1361
Francois Pichet01b7c302010-09-08 12:20:18 +00001362/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1363///
1364/// '__uuidof' '(' expression ')'
1365/// '__uuidof' '(' type-id ')'
1366///
1367ExprResult Parser::ParseCXXUuidof() {
1368 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1369
1370 SourceLocation OpLoc = ConsumeToken();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001371 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet01b7c302010-09-08 12:20:18 +00001372
1373 // __uuidof expressions are always parenthesized.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001374 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet01b7c302010-09-08 12:20:18 +00001375 return ExprError();
1376
1377 ExprResult Result;
1378
1379 if (isTypeIdInParens()) {
1380 TypeResult Ty = ParseTypeName();
1381
1382 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001383 T.consumeClose();
Francois Pichet01b7c302010-09-08 12:20:18 +00001384
1385 if (Ty.isInvalid())
1386 return ExprError();
1387
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001388 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1389 Ty.get().getAsOpaquePtr(),
1390 T.getCloseLocation());
Francois Pichet01b7c302010-09-08 12:20:18 +00001391 } else {
1392 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1393 Result = ParseExpression();
1394
1395 // Match the ')'.
1396 if (Result.isInvalid())
Alexey Bataev8fe24752013-11-18 08:17:37 +00001397 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet01b7c302010-09-08 12:20:18 +00001398 else {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001399 T.consumeClose();
Francois Pichet01b7c302010-09-08 12:20:18 +00001400
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001401 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1402 /*isType=*/false,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001403 Result.get(), T.getCloseLocation());
Francois Pichet01b7c302010-09-08 12:20:18 +00001404 }
1405 }
1406
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001407 return Result;
Francois Pichet01b7c302010-09-08 12:20:18 +00001408}
1409
Douglas Gregord4dca082010-02-24 18:44:31 +00001410/// \brief Parse a C++ pseudo-destructor expression after the base,
1411/// . or -> operator, and nested-name-specifier have already been
1412/// parsed.
1413///
1414/// postfix-expression: [C++ 5.2]
1415/// postfix-expression . pseudo-destructor-name
1416/// postfix-expression -> pseudo-destructor-name
1417///
1418/// pseudo-destructor-name:
1419/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1420/// ::[opt] nested-name-specifier template simple-template-id ::
1421/// ~type-name
1422/// ::[opt] nested-name-specifier[opt] ~type-name
1423///
John McCall60d7b3a2010-08-24 06:29:42 +00001424ExprResult
Stephen Hines176edba2014-12-01 14:53:08 -08001425Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00001426 tok::TokenKind OpKind,
1427 CXXScopeSpec &SS,
John McCallb3d87482010-08-24 05:47:05 +00001428 ParsedType ObjectType) {
Douglas Gregord4dca082010-02-24 18:44:31 +00001429 // We're parsing either a pseudo-destructor-name or a dependent
1430 // member access that has the same form as a
1431 // pseudo-destructor-name. We parse both in the same way and let
1432 // the action model sort them out.
1433 //
1434 // Note that the ::[opt] nested-name-specifier[opt] has already
1435 // been parsed, and if there was a simple-template-id, it has
1436 // been coalesced into a template-id annotation token.
1437 UnqualifiedId FirstTypeName;
1438 SourceLocation CCLoc;
1439 if (Tok.is(tok::identifier)) {
1440 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1441 ConsumeToken();
1442 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1443 CCLoc = ConsumeToken();
1444 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001445 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1446 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregord4dca082010-02-24 18:44:31 +00001447 FirstTypeName.setTemplateId(
1448 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1449 ConsumeToken();
1450 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1451 CCLoc = ConsumeToken();
1452 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001453 FirstTypeName.setIdentifier(nullptr, SourceLocation());
Douglas Gregord4dca082010-02-24 18:44:31 +00001454 }
1455
1456 // Parse the tilde.
1457 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1458 SourceLocation TildeLoc = ConsumeToken();
David Blaikie91ec7892011-12-16 16:03:09 +00001459
1460 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1461 DeclSpec DS(AttrFactory);
Benjamin Kramer85c60db2011-12-18 12:18:02 +00001462 ParseDecltypeSpecifier(DS);
David Blaikie91ec7892011-12-16 16:03:09 +00001463 if (DS.getTypeSpecType() == TST_error)
1464 return ExprError();
1465 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1466 OpKind, TildeLoc, DS,
1467 Tok.is(tok::l_paren));
1468 }
1469
Douglas Gregord4dca082010-02-24 18:44:31 +00001470 if (!Tok.is(tok::identifier)) {
1471 Diag(Tok, diag::err_destructor_tilde_identifier);
1472 return ExprError();
1473 }
1474
1475 // Parse the second type.
1476 UnqualifiedId SecondTypeName;
1477 IdentifierInfo *Name = Tok.getIdentifierInfo();
1478 SourceLocation NameLoc = ConsumeToken();
1479 SecondTypeName.setIdentifier(Name, NameLoc);
1480
1481 // If there is a '<', the second type name is a template-id. Parse
1482 // it as such.
1483 if (Tok.is(tok::less) &&
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001484 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1485 Name, NameLoc,
1486 false, ObjectType, SecondTypeName,
1487 /*AssumeTemplateName=*/true))
Douglas Gregord4dca082010-02-24 18:44:31 +00001488 return ExprError();
1489
John McCall9ae2f072010-08-23 23:25:46 +00001490 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1491 OpLoc, OpKind,
Douglas Gregord4dca082010-02-24 18:44:31 +00001492 SS, FirstTypeName, CCLoc,
1493 TildeLoc, SecondTypeName,
1494 Tok.is(tok::l_paren));
1495}
1496
Reid Spencer5f016e22007-07-11 17:01:13 +00001497/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1498///
1499/// boolean-literal: [C++ 2.13.5]
1500/// 'true'
1501/// 'false'
John McCall60d7b3a2010-08-24 06:29:42 +00001502ExprResult Parser::ParseCXXBoolLiteral() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 tok::TokenKind Kind = Tok.getKind();
Sebastian Redlf53597f2009-03-15 17:47:39 +00001504 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001505}
Chris Lattner50dd2892008-02-26 00:51:44 +00001506
1507/// ParseThrowExpression - This handles the C++ throw expression.
1508///
1509/// throw-expression: [C++ 15]
1510/// 'throw' assignment-expression[opt]
John McCall60d7b3a2010-08-24 06:29:42 +00001511ExprResult Parser::ParseThrowExpression() {
Chris Lattner50dd2892008-02-26 00:51:44 +00001512 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattner50dd2892008-02-26 00:51:44 +00001513 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redl20df9b72008-12-11 22:51:44 +00001514
Chris Lattner2a2819a2008-04-06 06:02:23 +00001515 // If the current token isn't the start of an assignment-expression,
1516 // then the expression is not present. This handles things like:
1517 // "C ? throw : (void)42", which is crazy but legal.
1518 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1519 case tok::semi:
1520 case tok::r_paren:
1521 case tok::r_square:
1522 case tok::r_brace:
1523 case tok::colon:
1524 case tok::comma:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001525 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
Chris Lattner50dd2892008-02-26 00:51:44 +00001526
Chris Lattner2a2819a2008-04-06 06:02:23 +00001527 default:
John McCall60d7b3a2010-08-24 06:29:42 +00001528 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001529 if (Expr.isInvalid()) return Expr;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001530 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
Chris Lattner2a2819a2008-04-06 06:02:23 +00001531 }
Chris Lattner50dd2892008-02-26 00:51:44 +00001532}
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +00001533
1534/// ParseCXXThis - This handles the C++ 'this' pointer.
1535///
1536/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1537/// a non-lvalue expression whose value is the address of the object for which
1538/// the function is called.
John McCall60d7b3a2010-08-24 06:29:42 +00001539ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +00001540 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1541 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redlf53597f2009-03-15 17:47:39 +00001542 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +00001543}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001544
1545/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1546/// Can be interpreted either as function-style casting ("int(x)")
1547/// or class type construction ("ClassType(x,y,z)")
1548/// or creation of a value-initialized type ("int()").
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001549/// See [C++ 5.2.3].
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001550///
1551/// postfix-expression: [C++ 5.2p1]
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001552/// simple-type-specifier '(' expression-list[opt] ')'
1553/// [C++0x] simple-type-specifier braced-init-list
1554/// typename-specifier '(' expression-list[opt] ')'
1555/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001556///
John McCall60d7b3a2010-08-24 06:29:42 +00001557ExprResult
Sebastian Redl20df9b72008-12-11 22:51:44 +00001558Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001559 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
John McCallb3d87482010-08-24 05:47:05 +00001560 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001561
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001562 assert((Tok.is(tok::l_paren) ||
Richard Smith80ad52f2013-01-02 11:42:31 +00001563 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001564 && "Expected '(' or '{'!");
Douglas Gregorbc61bd82011-01-11 00:33:19 +00001565
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001566 if (Tok.is(tok::l_brace)) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001567 ExprResult Init = ParseBraceInitializer();
1568 if (Init.isInvalid())
1569 return Init;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001570 Expr *InitList = Init.get();
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001571 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1572 MultiExprArg(&InitList, 1),
1573 SourceLocation());
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001574 } else {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001575 BalancedDelimiterTracker T(*this, tok::l_paren);
1576 T.consumeOpen();
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001577
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00001578 ExprVector Exprs;
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001579 CommaLocsTy CommaLocs;
1580
1581 if (Tok.isNot(tok::r_paren)) {
1582 if (ParseExpressionList(Exprs, CommaLocs)) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00001583 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001584 return ExprError();
1585 }
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001586 }
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001587
1588 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001589 T.consumeClose();
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001590
1591 // TypeRep could be null, if it references an invalid typedef.
1592 if (!TypeRep)
1593 return ExprError();
1594
1595 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1596 "Unexpected number of commas!");
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001597 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001598 Exprs,
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001599 T.getCloseLocation());
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001600 }
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001601}
1602
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001603/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001604///
1605/// condition:
1606/// expression
1607/// type-specifier-seq declarator '=' assignment-expression
Richard Smith0635aa72012-02-22 06:49:09 +00001608/// [C++11] type-specifier-seq declarator '=' initializer-clause
1609/// [C++11] type-specifier-seq declarator braced-init-list
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001610/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1611/// '=' assignment-expression
1612///
Dmitri Gribenko1ddbd892012-08-24 00:01:24 +00001613/// \param ExprOut if the condition was parsed as an expression, the parsed
1614/// expression.
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001615///
Dmitri Gribenko1ddbd892012-08-24 00:01:24 +00001616/// \param DeclOut if the condition was parsed as a declaration, the parsed
1617/// declaration.
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001618///
Douglas Gregor586596f2010-05-06 17:25:47 +00001619/// \param Loc The location of the start of the statement that requires this
1620/// condition, e.g., the "for" in a for loop.
1621///
1622/// \param ConvertToBoolean Whether the condition expression should be
1623/// converted to a boolean value.
1624///
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001625/// \returns true if there was a parsing, false otherwise.
John McCall60d7b3a2010-08-24 06:29:42 +00001626bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1627 Decl *&DeclOut,
Douglas Gregor586596f2010-05-06 17:25:47 +00001628 SourceLocation Loc,
1629 bool ConvertToBoolean) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001630 if (Tok.is(tok::code_completion)) {
John McCallf312b1e2010-08-26 23:41:50 +00001631 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001632 cutOffParsing();
1633 return true;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001634 }
1635
Sean Hunt2edf0a22012-06-23 05:07:58 +00001636 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +00001637 MaybeParseCXX11Attributes(attrs);
Sean Hunt2edf0a22012-06-23 05:07:58 +00001638
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001639 if (!isCXXConditionDeclaration()) {
Sean Hunt2edf0a22012-06-23 05:07:58 +00001640 ProhibitAttributes(attrs);
1641
Douglas Gregor586596f2010-05-06 17:25:47 +00001642 // Parse the expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001643 ExprOut = ParseExpression(); // expression
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001644 DeclOut = nullptr;
John McCall60d7b3a2010-08-24 06:29:42 +00001645 if (ExprOut.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001646 return true;
1647
1648 // If required, convert to a boolean value.
1649 if (ConvertToBoolean)
John McCall60d7b3a2010-08-24 06:29:42 +00001650 ExprOut
1651 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1652 return ExprOut.isInvalid();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001653 }
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001654
1655 // type-specifier-seq
John McCall0b7e6782011-03-24 11:26:52 +00001656 DeclSpec DS(AttrFactory);
Richard Smith6b3d3e52013-02-20 19:22:51 +00001657 DS.takeAttributesFrom(attrs);
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001658 ParseSpecifierQualifierList(DS);
1659
1660 // declarator
1661 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1662 ParseDeclarator(DeclaratorInfo);
1663
1664 // simple-asm-expr[opt]
1665 if (Tok.is(tok::kw_asm)) {
Sebastian Redlab197ba2009-02-09 18:23:29 +00001666 SourceLocation Loc;
John McCall60d7b3a2010-08-24 06:29:42 +00001667 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001668 if (AsmLabel.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00001669 SkipUntil(tok::semi, StopAtSemi);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001670 return true;
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001671 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001672 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Sebastian Redlab197ba2009-02-09 18:23:29 +00001673 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001674 }
1675
1676 // If attributes are present, parse them.
John McCall7f040a92010-12-24 02:08:15 +00001677 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001678
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001679 // Type-check the declaration itself.
John McCall60d7b3a2010-08-24 06:29:42 +00001680 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall7f040a92010-12-24 02:08:15 +00001681 DeclaratorInfo);
John McCall60d7b3a2010-08-24 06:29:42 +00001682 DeclOut = Dcl.get();
1683 ExprOut = ExprError();
Argyrios Kyrtzidisa6eb5f82010-10-08 02:39:23 +00001684
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001685 // '=' assignment-expression
Richard Trieud6c7c672012-01-18 22:54:52 +00001686 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith0635aa72012-02-22 06:49:09 +00001687 bool CopyInitialization = isTokenEqualOrEqualTypo();
1688 if (CopyInitialization)
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001689 ConsumeToken();
Richard Smith0635aa72012-02-22 06:49:09 +00001690
1691 ExprResult InitExpr = ExprError();
Richard Smith80ad52f2013-01-02 11:42:31 +00001692 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith0635aa72012-02-22 06:49:09 +00001693 Diag(Tok.getLocation(),
1694 diag::warn_cxx98_compat_generalized_initializer_lists);
1695 InitExpr = ParseBraceInitializer();
1696 } else if (CopyInitialization) {
1697 InitExpr = ParseAssignmentExpression();
1698 } else if (Tok.is(tok::l_paren)) {
1699 // This was probably an attempt to initialize the variable.
1700 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataev8fe24752013-11-18 08:17:37 +00001701 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith0635aa72012-02-22 06:49:09 +00001702 RParen = ConsumeParen();
1703 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1704 diag::err_expected_init_in_condition_lparen)
1705 << SourceRange(LParen, RParen);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001706 } else {
Richard Smith0635aa72012-02-22 06:49:09 +00001707 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1708 diag::err_expected_init_in_condition);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001709 }
Richard Smith0635aa72012-02-22 06:49:09 +00001710
1711 if (!InitExpr.isInvalid())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001712 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization,
Richard Smitha2c36462013-04-26 16:15:35 +00001713 DS.containsPlaceholderType());
Richard Smithdc7a4f52013-04-30 13:56:41 +00001714 else
1715 Actions.ActOnInitializerError(DeclOut);
Richard Smith0635aa72012-02-22 06:49:09 +00001716
Douglas Gregor586596f2010-05-06 17:25:47 +00001717 // FIXME: Build a reference to this declaration? Convert it to bool?
1718 // (This is currently handled by Sema).
Richard Smith483b9f32011-02-21 20:05:19 +00001719
1720 Actions.FinalizeDeclaration(DeclOut);
Douglas Gregor586596f2010-05-06 17:25:47 +00001721
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001722 return false;
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001723}
1724
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001725/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1726/// This should only be called when the current token is known to be part of
1727/// simple-type-specifier.
1728///
1729/// simple-type-specifier:
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001730/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001731/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1732/// char
1733/// wchar_t
1734/// bool
1735/// short
1736/// int
1737/// long
1738/// signed
1739/// unsigned
1740/// float
1741/// double
1742/// void
1743/// [GNU] typeof-specifier
1744/// [C++0x] auto [TODO]
1745///
1746/// type-name:
1747/// class-name
1748/// enum-name
1749/// typedef-name
1750///
1751void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1752 DS.SetRangeStart(Tok.getLocation());
1753 const char *PrevSpec;
John McCallfec54012009-08-03 20:12:06 +00001754 unsigned DiagID;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001755 SourceLocation Loc = Tok.getLocation();
Stephen Hines651f13c2014-04-23 16:59:28 -07001756 const clang::PrintingPolicy &Policy =
1757 Actions.getASTContext().getPrintingPolicy();
Mike Stump1eb44332009-09-09 15:08:12 +00001758
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001759 switch (Tok.getKind()) {
Chris Lattner55a7cef2009-01-05 00:13:00 +00001760 case tok::identifier: // foo::bar
1761 case tok::coloncolon: // ::foo::bar
David Blaikieb219cfc2011-09-23 05:06:16 +00001762 llvm_unreachable("Annotation token should already be formed!");
Mike Stump1eb44332009-09-09 15:08:12 +00001763 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00001764 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner55a7cef2009-01-05 00:13:00 +00001765
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001766 // type-name
Chris Lattnerb31757b2009-01-06 05:06:21 +00001767 case tok::annot_typename: {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001768 if (getTypeAnnotation(Tok))
1769 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
Stephen Hines651f13c2014-04-23 16:59:28 -07001770 getTypeAnnotation(Tok), Policy);
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001771 else
1772 DS.SetTypeSpecError();
Douglas Gregor9bd1d8d2010-10-21 23:17:00 +00001773
1774 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1775 ConsumeToken();
1776
1777 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1778 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1779 // Objective-C interface. If we don't have Objective-C or a '<', this is
1780 // just a normal reference to a typedef name.
David Blaikie4e4d0842012-03-11 07:00:24 +00001781 if (Tok.is(tok::less) && getLangOpts().ObjC1)
Douglas Gregor9bd1d8d2010-10-21 23:17:00 +00001782 ParseObjCProtocolQualifiers(DS);
1783
Stephen Hines651f13c2014-04-23 16:59:28 -07001784 DS.Finish(Diags, PP, Policy);
Douglas Gregor9bd1d8d2010-10-21 23:17:00 +00001785 return;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001786 }
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001788 // builtin types
1789 case tok::kw_short:
Stephen Hines651f13c2014-04-23 16:59:28 -07001790 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001791 break;
1792 case tok::kw_long:
Stephen Hines651f13c2014-04-23 16:59:28 -07001793 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001794 break;
Francois Pichet338d7f72011-04-28 01:59:37 +00001795 case tok::kw___int64:
Stephen Hines651f13c2014-04-23 16:59:28 -07001796 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
Francois Pichet338d7f72011-04-28 01:59:37 +00001797 break;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001798 case tok::kw_signed:
John McCallfec54012009-08-03 20:12:06 +00001799 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001800 break;
1801 case tok::kw_unsigned:
John McCallfec54012009-08-03 20:12:06 +00001802 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001803 break;
1804 case tok::kw_void:
Stephen Hines651f13c2014-04-23 16:59:28 -07001805 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001806 break;
1807 case tok::kw_char:
Stephen Hines651f13c2014-04-23 16:59:28 -07001808 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001809 break;
1810 case tok::kw_int:
Stephen Hines651f13c2014-04-23 16:59:28 -07001811 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001812 break;
Richard Smith5a5a9712012-04-04 06:24:32 +00001813 case tok::kw___int128:
Stephen Hines651f13c2014-04-23 16:59:28 -07001814 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
Richard Smith5a5a9712012-04-04 06:24:32 +00001815 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001816 case tok::kw_half:
Stephen Hines651f13c2014-04-23 16:59:28 -07001817 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001818 break;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001819 case tok::kw_float:
Stephen Hines651f13c2014-04-23 16:59:28 -07001820 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001821 break;
1822 case tok::kw_double:
Stephen Hines651f13c2014-04-23 16:59:28 -07001823 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001824 break;
1825 case tok::kw_wchar_t:
Stephen Hines651f13c2014-04-23 16:59:28 -07001826 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001827 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001828 case tok::kw_char16_t:
Stephen Hines651f13c2014-04-23 16:59:28 -07001829 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001830 break;
1831 case tok::kw_char32_t:
Stephen Hines651f13c2014-04-23 16:59:28 -07001832 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001833 break;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001834 case tok::kw_bool:
Stephen Hines651f13c2014-04-23 16:59:28 -07001835 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001836 break;
David Blaikie5e089fe2012-01-24 05:47:35 +00001837 case tok::annot_decltype:
1838 case tok::kw_decltype:
1839 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
Stephen Hines651f13c2014-04-23 16:59:28 -07001840 return DS.Finish(Diags, PP, Policy);
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001842 // GNU typeof support.
1843 case tok::kw_typeof:
1844 ParseTypeofSpecifier(DS);
Stephen Hines651f13c2014-04-23 16:59:28 -07001845 DS.Finish(Diags, PP, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001846 return;
1847 }
Chris Lattnerb31757b2009-01-06 05:06:21 +00001848 if (Tok.is(tok::annot_typename))
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001849 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1850 else
1851 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001852 ConsumeToken();
Stephen Hines651f13c2014-04-23 16:59:28 -07001853 DS.Finish(Diags, PP, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001854}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001855
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001856/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1857/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1858/// e.g., "const short int". Note that the DeclSpec is *not* finished
1859/// by parsing the type-specifier-seq, because these sequences are
1860/// typically followed by some form of declarator. Returns true and
1861/// emits diagnostics if this is not a type-specifier-seq, false
1862/// otherwise.
1863///
1864/// type-specifier-seq: [C++ 8.1]
1865/// type-specifier type-specifier-seq[opt]
1866///
1867bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Richard Smith69730c12012-03-12 07:56:15 +00001868 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
Stephen Hines651f13c2014-04-23 16:59:28 -07001869 DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001870 return false;
1871}
1872
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001873/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1874/// some form.
1875///
1876/// This routine is invoked when a '<' is encountered after an identifier or
1877/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1878/// whether the unqualified-id is actually a template-id. This routine will
1879/// then parse the template arguments and form the appropriate template-id to
1880/// return to the caller.
1881///
1882/// \param SS the nested-name-specifier that precedes this template-id, if
1883/// we're actually parsing a qualified-id.
1884///
1885/// \param Name for constructor and destructor names, this is the actual
1886/// identifier that may be a template-name.
1887///
1888/// \param NameLoc the location of the class-name in a constructor or
1889/// destructor.
1890///
1891/// \param EnteringContext whether we're entering the scope of the
1892/// nested-name-specifier.
1893///
Douglas Gregor46df8cc2009-11-03 21:24:04 +00001894/// \param ObjectType if this unqualified-id occurs within a member access
1895/// expression, the type of the base object whose member is being accessed.
1896///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001897/// \param Id as input, describes the template-name or operator-function-id
1898/// that precedes the '<'. If template arguments were parsed successfully,
1899/// will be updated with the template-id.
1900///
Douglas Gregord4dca082010-02-24 18:44:31 +00001901/// \param AssumeTemplateId When true, this routine will assume that the name
1902/// refers to a template without performing name lookup to verify.
1903///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001904/// \returns true if a parse error occurred, false otherwise.
1905bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001906 SourceLocation TemplateKWLoc,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001907 IdentifierInfo *Name,
1908 SourceLocation NameLoc,
1909 bool EnteringContext,
John McCallb3d87482010-08-24 05:47:05 +00001910 ParsedType ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00001911 UnqualifiedId &Id,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001912 bool AssumeTemplateId) {
Douglas Gregor0278e122010-05-05 05:58:24 +00001913 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1914 "Expected '<' to finish parsing a template-id");
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001915
1916 TemplateTy Template;
1917 TemplateNameKind TNK = TNK_Non_template;
1918 switch (Id.getKind()) {
1919 case UnqualifiedId::IK_Identifier:
Douglas Gregor014e88d2009-11-03 23:16:33 +00001920 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunte6252d12009-11-28 08:58:14 +00001921 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregord4dca082010-02-24 18:44:31 +00001922 if (AssumeTemplateId) {
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001923 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001924 Id, ObjectType, EnteringContext,
1925 Template);
1926 if (TNK == TNK_Non_template)
1927 return true;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001928 } else {
1929 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001930 TNK = Actions.isTemplateName(getCurScope(), SS,
1931 TemplateKWLoc.isValid(), Id,
1932 ObjectType, EnteringContext, Template,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001933 MemberOfUnknownSpecialization);
1934
1935 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1936 ObjectType && IsTemplateArgumentList()) {
1937 // We have something like t->getAs<T>(), where getAs is a
1938 // member of an unknown specialization. However, this will only
1939 // parse correctly as a template, so suggest the keyword 'template'
1940 // before 'getAs' and treat this as a dependent template name.
1941 std::string Name;
1942 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1943 Name = Id.Identifier->getName();
1944 else {
1945 Name = "operator ";
1946 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1947 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1948 else
1949 Name += Id.Identifier->getName();
1950 }
1951 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1952 << Name
1953 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001954 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1955 SS, TemplateKWLoc, Id,
1956 ObjectType, EnteringContext,
1957 Template);
Douglas Gregord6ab2322010-06-16 23:00:59 +00001958 if (TNK == TNK_Non_template)
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001959 return true;
1960 }
1961 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001962 break;
1963
Douglas Gregor014e88d2009-11-03 23:16:33 +00001964 case UnqualifiedId::IK_ConstructorName: {
1965 UnqualifiedId TemplateName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001966 bool MemberOfUnknownSpecialization;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001967 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c153532010-08-06 12:11:11 +00001968 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1969 TemplateName, ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001970 EnteringContext, Template,
1971 MemberOfUnknownSpecialization);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001972 break;
1973 }
1974
Douglas Gregor014e88d2009-11-03 23:16:33 +00001975 case UnqualifiedId::IK_DestructorName: {
1976 UnqualifiedId TemplateName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001977 bool MemberOfUnknownSpecialization;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001978 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001979 if (ObjectType) {
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001980 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1981 SS, TemplateKWLoc, TemplateName,
1982 ObjectType, EnteringContext,
1983 Template);
Douglas Gregord6ab2322010-06-16 23:00:59 +00001984 if (TNK == TNK_Non_template)
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001985 return true;
1986 } else {
Abramo Bagnara7c153532010-08-06 12:11:11 +00001987 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1988 TemplateName, ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001989 EnteringContext, Template,
1990 MemberOfUnknownSpecialization);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001991
John McCallb3d87482010-08-24 05:47:05 +00001992 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregor124b8782010-02-16 19:09:40 +00001993 Diag(NameLoc, diag::err_destructor_template_id)
1994 << Name << SS.getRange();
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001995 return true;
1996 }
1997 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001998 break;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001999 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002000
2001 default:
2002 return false;
2003 }
2004
2005 if (TNK == TNK_Non_template)
2006 return false;
2007
2008 // Parse the enclosed template argument list.
2009 SourceLocation LAngleLoc, RAngleLoc;
2010 TemplateArgList TemplateArgs;
Douglas Gregor0278e122010-05-05 05:58:24 +00002011 if (Tok.is(tok::less) &&
2012 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
Douglas Gregor059101f2011-03-02 00:47:37 +00002013 SS, true, LAngleLoc,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002014 TemplateArgs,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002015 RAngleLoc))
2016 return true;
2017
2018 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
Sean Hunte6252d12009-11-28 08:58:14 +00002019 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2020 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002021 // Form a parsed representation of the template-id to be stored in the
2022 // UnqualifiedId.
2023 TemplateIdAnnotation *TemplateId
Benjamin Kramer13bb7012012-04-14 12:14:03 +00002024 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002025
Stephen Hines651f13c2014-04-23 16:59:28 -07002026 // FIXME: Store name for literal operator too.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002027 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
2028 TemplateId->Name = Id.Identifier;
Douglas Gregor014e88d2009-11-03 23:16:33 +00002029 TemplateId->Operator = OO_None;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002030 TemplateId->TemplateNameLoc = Id.StartLocation;
2031 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002032 TemplateId->Name = nullptr;
Douglas Gregor014e88d2009-11-03 23:16:33 +00002033 TemplateId->Operator = Id.OperatorFunctionId.Operator;
2034 TemplateId->TemplateNameLoc = Id.StartLocation;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002035 }
2036
Douglas Gregor059101f2011-03-02 00:47:37 +00002037 TemplateId->SS = SS;
Benjamin Kramer2b28bf12012-02-19 23:37:39 +00002038 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall2b5289b2010-08-23 07:28:44 +00002039 TemplateId->Template = Template;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002040 TemplateId->Kind = TNK;
2041 TemplateId->LAngleLoc = LAngleLoc;
2042 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregor314b97f2009-11-10 19:49:08 +00002043 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002044 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
Douglas Gregor314b97f2009-11-10 19:49:08 +00002045 Arg != ArgEnd; ++Arg)
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002046 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002047
2048 Id.setTemplateId(TemplateId);
2049 return false;
2050 }
2051
2052 // Bundle the template arguments together.
Benjamin Kramer5354e772012-08-23 23:38:35 +00002053 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002054
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002055 // Constructor and destructor names.
John McCallf312b1e2010-08-26 23:41:50 +00002056 TypeResult Type
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002057 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2058 Template, NameLoc,
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002059 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2060 /*IsCtorOrDtorName=*/true);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002061 if (Type.isInvalid())
2062 return true;
2063
2064 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2065 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2066 else
2067 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2068
2069 return false;
2070}
2071
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002072/// \brief Parse an operator-function-id or conversion-function-id as part
2073/// of a C++ unqualified-id.
2074///
2075/// This routine is responsible only for parsing the operator-function-id or
2076/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002077///
2078/// \code
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002079/// operator-function-id: [C++ 13.5]
2080/// 'operator' operator
2081///
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002082/// operator: one of
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002083/// new delete new[] delete[]
2084/// + - * / % ^ & | ~
2085/// ! = < > += -= *= /= %=
2086/// ^= &= |= << >> >>= <<= == !=
2087/// <= >= && || ++ -- , ->* ->
2088/// () []
2089///
2090/// conversion-function-id: [C++ 12.3.2]
2091/// operator conversion-type-id
2092///
2093/// conversion-type-id:
2094/// type-specifier-seq conversion-declarator[opt]
2095///
2096/// conversion-declarator:
2097/// ptr-operator conversion-declarator[opt]
2098/// \endcode
2099///
Dmitri Gribenko1ddbd892012-08-24 00:01:24 +00002100/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002101/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2102///
2103/// \param EnteringContext whether we are entering the scope of the
2104/// nested-name-specifier.
2105///
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002106/// \param ObjectType if this unqualified-id occurs within a member access
2107/// expression, the type of the base object whose member is being accessed.
2108///
2109/// \param Result on a successful parse, contains the parsed unqualified-id.
2110///
2111/// \returns true if parsing fails, false otherwise.
2112bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallb3d87482010-08-24 05:47:05 +00002113 ParsedType ObjectType,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002114 UnqualifiedId &Result) {
2115 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2116
2117 // Consume the 'operator' keyword.
2118 SourceLocation KeywordLoc = ConsumeToken();
2119
2120 // Determine what kind of operator name we have.
2121 unsigned SymbolIdx = 0;
2122 SourceLocation SymbolLocations[3];
2123 OverloadedOperatorKind Op = OO_None;
2124 switch (Tok.getKind()) {
2125 case tok::kw_new:
2126 case tok::kw_delete: {
2127 bool isNew = Tok.getKind() == tok::kw_new;
2128 // Consume the 'new' or 'delete'.
2129 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith6ee326a2012-04-10 01:32:12 +00002130 // Check for array new/delete.
2131 if (Tok.is(tok::l_square) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00002132 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002133 // Consume the '[' and ']'.
2134 BalancedDelimiterTracker T(*this, tok::l_square);
2135 T.consumeOpen();
2136 T.consumeClose();
2137 if (T.getCloseLocation().isInvalid())
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002138 return true;
2139
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002140 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2141 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002142 Op = isNew? OO_Array_New : OO_Array_Delete;
2143 } else {
2144 Op = isNew? OO_New : OO_Delete;
2145 }
2146 break;
2147 }
2148
2149#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2150 case tok::Token: \
2151 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2152 Op = OO_##Name; \
2153 break;
2154#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2155#include "clang/Basic/OperatorKinds.def"
2156
2157 case tok::l_paren: {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002158 // Consume the '(' and ')'.
2159 BalancedDelimiterTracker T(*this, tok::l_paren);
2160 T.consumeOpen();
2161 T.consumeClose();
2162 if (T.getCloseLocation().isInvalid())
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002163 return true;
2164
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002165 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2166 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002167 Op = OO_Call;
2168 break;
2169 }
2170
2171 case tok::l_square: {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002172 // Consume the '[' and ']'.
2173 BalancedDelimiterTracker T(*this, tok::l_square);
2174 T.consumeOpen();
2175 T.consumeClose();
2176 if (T.getCloseLocation().isInvalid())
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002177 return true;
2178
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002179 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2180 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002181 Op = OO_Subscript;
2182 break;
2183 }
2184
2185 case tok::code_completion: {
2186 // Code completion for the operator name.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002187 Actions.CodeCompleteOperatorName(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002188 cutOffParsing();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002189 // Don't try to parse any further.
2190 return true;
2191 }
2192
2193 default:
2194 break;
2195 }
2196
2197 if (Op != OO_None) {
2198 // We have parsed an operator-function-id.
2199 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2200 return false;
2201 }
Sean Hunt0486d742009-11-28 04:44:28 +00002202
2203 // Parse a literal-operator-id.
2204 //
Richard Smithaa9a8ce2012-10-20 08:41:10 +00002205 // literal-operator-id: C++11 [over.literal]
2206 // operator string-literal identifier
2207 // operator user-defined-string-literal
Sean Hunt0486d742009-11-28 04:44:28 +00002208
Richard Smith80ad52f2013-01-02 11:42:31 +00002209 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith7fe62082011-10-15 05:09:34 +00002210 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Sean Hunt0486d742009-11-28 04:44:28 +00002211
Richard Smith33762772012-03-08 23:06:02 +00002212 SourceLocation DiagLoc;
2213 unsigned DiagId = 0;
2214
2215 // We're past translation phase 6, so perform string literal concatenation
2216 // before checking for "".
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002217 SmallVector<Token, 4> Toks;
2218 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith33762772012-03-08 23:06:02 +00002219 while (isTokenStringLiteral()) {
2220 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smithaa9a8ce2012-10-20 08:41:10 +00002221 // C++11 [over.literal]p1:
2222 // The string-literal or user-defined-string-literal in a
2223 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith33762772012-03-08 23:06:02 +00002224 DiagLoc = Tok.getLocation();
2225 DiagId = diag::err_literal_operator_string_prefix;
2226 }
2227 Toks.push_back(Tok);
2228 TokLocs.push_back(ConsumeStringToken());
2229 }
2230
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002231 StringLiteralParser Literal(Toks, PP);
Richard Smith33762772012-03-08 23:06:02 +00002232 if (Literal.hadError)
2233 return true;
2234
2235 // Grab the literal operator's suffix, which will be either the next token
2236 // or a ud-suffix from the string literal.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002237 IdentifierInfo *II = nullptr;
Richard Smith33762772012-03-08 23:06:02 +00002238 SourceLocation SuffixLoc;
2239 if (!Literal.getUDSuffix().empty()) {
2240 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2241 SuffixLoc =
2242 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2243 Literal.getUDSuffixOffset(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002244 PP.getSourceManager(), getLangOpts());
Richard Smith33762772012-03-08 23:06:02 +00002245 } else if (Tok.is(tok::identifier)) {
2246 II = Tok.getIdentifierInfo();
2247 SuffixLoc = ConsumeToken();
2248 TokLocs.push_back(SuffixLoc);
2249 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -07002250 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Sean Hunt0486d742009-11-28 04:44:28 +00002251 return true;
2252 }
2253
Richard Smith33762772012-03-08 23:06:02 +00002254 // The string literal must be empty.
2255 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smithaa9a8ce2012-10-20 08:41:10 +00002256 // C++11 [over.literal]p1:
2257 // The string-literal or user-defined-string-literal in a
2258 // literal-operator-id shall [...] contain no characters
2259 // other than the implicit terminating '\0'.
Richard Smith33762772012-03-08 23:06:02 +00002260 DiagLoc = TokLocs.front();
2261 DiagId = diag::err_literal_operator_string_not_empty;
2262 }
2263
2264 if (DiagId) {
2265 // This isn't a valid literal-operator-id, but we think we know
2266 // what the user meant. Tell them what they should have written.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002267 SmallString<32> Str;
Richard Smith33762772012-03-08 23:06:02 +00002268 Str += "\"\" ";
2269 Str += II->getName();
2270 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2271 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2272 }
2273
2274 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Stephen Hines651f13c2014-04-23 16:59:28 -07002275
2276 return Actions.checkLiteralOperatorId(SS, Result);
Sean Hunt0486d742009-11-28 04:44:28 +00002277 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002278
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002279 // Parse a conversion-function-id.
2280 //
2281 // conversion-function-id: [C++ 12.3.2]
2282 // operator conversion-type-id
2283 //
2284 // conversion-type-id:
2285 // type-specifier-seq conversion-declarator[opt]
2286 //
2287 // conversion-declarator:
2288 // ptr-operator conversion-declarator[opt]
2289
2290 // Parse the type-specifier-seq.
John McCall0b7e6782011-03-24 11:26:52 +00002291 DeclSpec DS(AttrFactory);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +00002292 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002293 return true;
2294
2295 // Parse the conversion-declarator, which is merely a sequence of
2296 // ptr-operators.
Richard Smith14f78f42013-05-04 01:26:46 +00002297 Declarator D(DS, Declarator::ConversionIdContext);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002298 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2299
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002300 // Finish up the type.
John McCallf312b1e2010-08-26 23:41:50 +00002301 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002302 if (Ty.isInvalid())
2303 return true;
2304
2305 // Note that this is a conversion-function-id.
2306 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2307 D.getSourceRange().getEnd());
2308 return false;
2309}
2310
2311/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2312/// name of an entity.
2313///
2314/// \code
2315/// unqualified-id: [C++ expr.prim.general]
2316/// identifier
2317/// operator-function-id
2318/// conversion-function-id
2319/// [C++0x] literal-operator-id [TODO]
2320/// ~ class-name
2321/// template-id
2322///
2323/// \endcode
2324///
Dmitri Gribenko1ddbd892012-08-24 00:01:24 +00002325/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002326/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2327///
2328/// \param EnteringContext whether we are entering the scope of the
2329/// nested-name-specifier.
2330///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002331/// \param AllowDestructorName whether we allow parsing of a destructor name.
2332///
2333/// \param AllowConstructorName whether we allow parsing a constructor name.
2334///
Douglas Gregor46df8cc2009-11-03 21:24:04 +00002335/// \param ObjectType if this unqualified-id occurs within a member access
2336/// expression, the type of the base object whose member is being accessed.
2337///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002338/// \param Result on a successful parse, contains the parsed unqualified-id.
2339///
2340/// \returns true if parsing fails, false otherwise.
2341bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2342 bool AllowDestructorName,
2343 bool AllowConstructorName,
John McCallb3d87482010-08-24 05:47:05 +00002344 ParsedType ObjectType,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002345 SourceLocation& TemplateKWLoc,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002346 UnqualifiedId &Result) {
Douglas Gregor0278e122010-05-05 05:58:24 +00002347
2348 // Handle 'A::template B'. This is for template-ids which have not
2349 // already been annotated by ParseOptionalCXXScopeSpecifier().
2350 bool TemplateSpecified = false;
David Blaikie4e4d0842012-03-11 07:00:24 +00002351 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
Douglas Gregor0278e122010-05-05 05:58:24 +00002352 (ObjectType || SS.isSet())) {
2353 TemplateSpecified = true;
2354 TemplateKWLoc = ConsumeToken();
2355 }
2356
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002357 // unqualified-id:
2358 // identifier
2359 // template-id (when it hasn't already been annotated)
2360 if (Tok.is(tok::identifier)) {
2361 // Consume the identifier.
2362 IdentifierInfo *Id = Tok.getIdentifierInfo();
2363 SourceLocation IdLoc = ConsumeToken();
2364
David Blaikie4e4d0842012-03-11 07:00:24 +00002365 if (!getLangOpts().CPlusPlus) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +00002366 // If we're not in C++, only identifiers matter. Record the
2367 // identifier and return.
2368 Result.setIdentifier(Id, IdLoc);
2369 return false;
2370 }
2371
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002372 if (AllowConstructorName &&
Douglas Gregor23c94db2010-07-02 17:43:08 +00002373 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002374 // We have parsed a constructor name.
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002375 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2376 &SS, false, false,
2377 ParsedType(),
2378 /*IsCtorOrDtorName=*/true,
2379 /*NonTrivialTypeSourceInfo=*/true);
2380 Result.setConstructorName(Ty, IdLoc, IdLoc);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002381 } else {
2382 // We have parsed an identifier.
2383 Result.setIdentifier(Id, IdLoc);
2384 }
2385
2386 // If the next token is a '<', we may have a template.
Douglas Gregor0278e122010-05-05 05:58:24 +00002387 if (TemplateSpecified || Tok.is(tok::less))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002388 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2389 EnteringContext, ObjectType,
2390 Result, TemplateSpecified);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002391
2392 return false;
2393 }
2394
2395 // unqualified-id:
2396 // template-id (already parsed and annotated)
2397 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +00002398 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002399
2400 // If the template-name names the current class, then this is a constructor
2401 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor23c94db2010-07-02 17:43:08 +00002402 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002403 if (SS.isSet()) {
2404 // C++ [class.qual]p2 specifies that a qualified template-name
2405 // is taken as the constructor name where a constructor can be
2406 // declared. Thus, the template arguments are extraneous, so
2407 // complain about them and remove them entirely.
2408 Diag(TemplateId->TemplateNameLoc,
2409 diag::err_out_of_line_constructor_template_id)
2410 << TemplateId->Name
Douglas Gregor849b2432010-03-31 17:46:05 +00002411 << FixItHint::CreateRemoval(
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002412 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002413 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2414 TemplateId->TemplateNameLoc,
2415 getCurScope(),
2416 &SS, false, false,
2417 ParsedType(),
2418 /*IsCtorOrDtorName=*/true,
2419 /*NontrivialTypeSourceInfo=*/true);
2420 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002421 TemplateId->RAngleLoc);
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002422 ConsumeToken();
2423 return false;
2424 }
2425
2426 Result.setConstructorTemplateId(TemplateId);
2427 ConsumeToken();
2428 return false;
2429 }
2430
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002431 // We have already parsed a template-id; consume the annotation token as
2432 // our unqualified-id.
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002433 Result.setTemplateId(TemplateId);
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002434 TemplateKWLoc = TemplateId->TemplateKWLoc;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002435 ConsumeToken();
2436 return false;
2437 }
2438
2439 // unqualified-id:
2440 // operator-function-id
2441 // conversion-function-id
2442 if (Tok.is(tok::kw_operator)) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002443 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002444 return true;
2445
Sean Hunte6252d12009-11-28 08:58:14 +00002446 // If we have an operator-function-id or a literal-operator-id and the next
2447 // token is a '<', we may have a
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002448 //
2449 // template-id:
2450 // operator-function-id < template-argument-list[opt] >
Sean Hunte6252d12009-11-28 08:58:14 +00002451 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2452 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
Douglas Gregor0278e122010-05-05 05:58:24 +00002453 (TemplateSpecified || Tok.is(tok::less)))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002454 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002455 nullptr, SourceLocation(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002456 EnteringContext, ObjectType,
2457 Result, TemplateSpecified);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002458
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002459 return false;
2460 }
2461
David Blaikie4e4d0842012-03-11 07:00:24 +00002462 if (getLangOpts().CPlusPlus &&
Douglas Gregorb862b8f2010-01-11 23:29:10 +00002463 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002464 // C++ [expr.unary.op]p10:
2465 // There is an ambiguity in the unary-expression ~X(), where X is a
2466 // class-name. The ambiguity is resolved in favor of treating ~ as a
2467 // unary complement rather than treating ~X as referring to a destructor.
2468
2469 // Parse the '~'.
2470 SourceLocation TildeLoc = ConsumeToken();
David Blaikie53a75c02011-12-08 16:13:53 +00002471
2472 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2473 DeclSpec DS(AttrFactory);
2474 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2475 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2476 Result.setDestructorName(TildeLoc, Type, EndLoc);
2477 return false;
2478 }
2479 return true;
2480 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002481
2482 // Parse the class-name.
2483 if (Tok.isNot(tok::identifier)) {
Douglas Gregor124b8782010-02-16 19:09:40 +00002484 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002485 return true;
2486 }
2487
Stephen Hines176edba2014-12-01 14:53:08 -08002488 // If the user wrote ~T::T, correct it to T::~T.
2489 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2490 if (SS.isSet()) {
2491 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2492 SS.clear();
2493 }
2494 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2495 return true;
2496 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon)) {
2497 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2498 return true;
2499 }
2500
2501 // Recover as if the tilde had been written before the identifier.
2502 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2503 << FixItHint::CreateRemoval(TildeLoc)
2504 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2505 }
2506
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002507 // Parse the class-name (or template-name in a simple-template-id).
2508 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2509 SourceLocation ClassNameLoc = ConsumeToken();
Stephen Hines176edba2014-12-01 14:53:08 -08002510
Douglas Gregor0278e122010-05-05 05:58:24 +00002511 if (TemplateSpecified || Tok.is(tok::less)) {
John McCallb3d87482010-08-24 05:47:05 +00002512 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002513 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2514 ClassName, ClassNameLoc,
2515 EnteringContext, ObjectType,
2516 Result, TemplateSpecified);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002517 }
Stephen Hines176edba2014-12-01 14:53:08 -08002518
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002519 // Note that this is a destructor name.
John McCallb3d87482010-08-24 05:47:05 +00002520 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2521 ClassNameLoc, getCurScope(),
2522 SS, ObjectType,
2523 EnteringContext);
Douglas Gregor124b8782010-02-16 19:09:40 +00002524 if (!Ty)
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002525 return true;
Douglas Gregor124b8782010-02-16 19:09:40 +00002526
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002527 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002528 return false;
2529 }
2530
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002531 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikie4e4d0842012-03-11 07:00:24 +00002532 << getLangOpts().CPlusPlus;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002533 return true;
2534}
2535
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002536/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2537/// memory in a typesafe manner and call constructors.
Mike Stump1eb44332009-09-09 15:08:12 +00002538///
Chris Lattner59232d32009-01-04 21:25:24 +00002539/// This method is called to parse the new expression after the optional :: has
2540/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2541/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002542///
2543/// new-expression:
2544/// '::'[opt] 'new' new-placement[opt] new-type-id
2545/// new-initializer[opt]
2546/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2547/// new-initializer[opt]
2548///
2549/// new-placement:
2550/// '(' expression-list ')'
2551///
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002552/// new-type-id:
2553/// type-specifier-seq new-declarator[opt]
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002554/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002555///
2556/// new-declarator:
2557/// ptr-operator new-declarator[opt]
2558/// direct-new-declarator
2559///
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002560/// new-initializer:
2561/// '(' expression-list[opt] ')'
Sebastian Redldbef1bb2011-06-05 12:23:16 +00002562/// [C++0x] braced-init-list
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002563///
John McCall60d7b3a2010-08-24 06:29:42 +00002564ExprResult
Chris Lattner59232d32009-01-04 21:25:24 +00002565Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2566 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2567 ConsumeToken(); // Consume 'new'
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002568
2569 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2570 // second form of new-expression. It can't be a new-type-id.
2571
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00002572 ExprVector PlacementArgs;
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002573 SourceLocation PlacementLParen, PlacementRParen;
2574
Douglas Gregor4bd40312010-07-13 15:54:32 +00002575 SourceRange TypeIdParens;
John McCall0b7e6782011-03-24 11:26:52 +00002576 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00002577 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002578 if (Tok.is(tok::l_paren)) {
2579 // If it turns out to be a placement, we change the type location.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002580 BalancedDelimiterTracker T(*this, tok::l_paren);
2581 T.consumeOpen();
2582 PlacementLParen = T.getOpenLocation();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002583 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002584 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002585 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002586 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002587
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002588 T.consumeClose();
2589 PlacementRParen = T.getCloseLocation();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002590 if (PlacementRParen.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002591 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002592 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002593 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002594
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002595 if (PlacementArgs.empty()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002596 // Reset the placement locations. There was no placement.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002597 TypeIdParens = T.getRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002598 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002599 } else {
2600 // We still need the type.
2601 if (Tok.is(tok::l_paren)) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002602 BalancedDelimiterTracker T(*this, tok::l_paren);
2603 T.consumeOpen();
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002604 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002605 ParseSpecifierQualifierList(DS);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002606 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002607 ParseDeclarator(DeclaratorInfo);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002608 T.consumeClose();
2609 TypeIdParens = T.getRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002610 } else {
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002611 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002612 if (ParseCXXTypeSpecifierSeq(DS))
2613 DeclaratorInfo.setInvalidType(true);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002614 else {
2615 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002616 ParseDeclaratorInternal(DeclaratorInfo,
2617 &Parser::ParseDirectNewDeclarator);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002618 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002619 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002620 }
2621 } else {
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002622 // A new-type-id is a simplified type-id, where essentially the
2623 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002624 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002625 if (ParseCXXTypeSpecifierSeq(DS))
2626 DeclaratorInfo.setInvalidType(true);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002627 else {
2628 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002629 ParseDeclaratorInternal(DeclaratorInfo,
2630 &Parser::ParseDirectNewDeclarator);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002631 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002632 }
Chris Lattnereaaebc72009-04-25 08:06:05 +00002633 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002634 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002635 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002636 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002637
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002638 ExprResult Initializer;
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002639
2640 if (Tok.is(tok::l_paren)) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002641 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00002642 ExprVector ConstructorArgs;
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002643 BalancedDelimiterTracker T(*this, tok::l_paren);
2644 T.consumeOpen();
2645 ConstructorLParen = T.getOpenLocation();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002646 if (Tok.isNot(tok::r_paren)) {
2647 CommaLocsTy CommaLocs;
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002648 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002649 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002650 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002651 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002652 }
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002653 T.consumeClose();
2654 ConstructorRParen = T.getCloseLocation();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002655 if (ConstructorRParen.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002656 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002657 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002658 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002659 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2660 ConstructorRParen,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002661 ConstructorArgs);
Richard Smith80ad52f2013-01-02 11:42:31 +00002662 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith7fe62082011-10-15 05:09:34 +00002663 Diag(Tok.getLocation(),
2664 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002665 Initializer = ParseBraceInitializer();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002666 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002667 if (Initializer.isInvalid())
2668 return Initializer;
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002669
Sebastian Redlf53597f2009-03-15 17:47:39 +00002670 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002671 PlacementArgs, PlacementRParen,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002672 TypeIdParens, DeclaratorInfo, Initializer.get());
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002673}
2674
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002675/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2676/// passed to ParseDeclaratorInternal.
2677///
2678/// direct-new-declarator:
2679/// '[' expression ']'
2680/// direct-new-declarator '[' constant-expression ']'
2681///
Chris Lattner59232d32009-01-04 21:25:24 +00002682void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002683 // Parse the array dimensions.
2684 bool first = true;
2685 while (Tok.is(tok::l_square)) {
Richard Smith6ee326a2012-04-10 01:32:12 +00002686 // An array-size expression can't start with a lambda.
2687 if (CheckProhibitedCXX11Attribute())
2688 continue;
2689
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002690 BalancedDelimiterTracker T(*this, tok::l_square);
2691 T.consumeOpen();
2692
John McCall60d7b3a2010-08-24 06:29:42 +00002693 ExprResult Size(first ? ParseExpression()
Sebastian Redl2f7ece72008-12-11 21:36:32 +00002694 : ParseConstantExpression());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002695 if (Size.isInvalid()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002696 // Recover
Alexey Bataev8fe24752013-11-18 08:17:37 +00002697 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002698 return;
2699 }
2700 first = false;
2701
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002702 T.consumeClose();
John McCall0b7e6782011-03-24 11:26:52 +00002703
Bill Wendlingad017fa2012-12-20 19:22:21 +00002704 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith6ee326a2012-04-10 01:32:12 +00002705 ParsedAttributes Attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +00002706 MaybeParseCXX11Attributes(Attrs);
Richard Smith6ee326a2012-04-10 01:32:12 +00002707
John McCall0b7e6782011-03-24 11:26:52 +00002708 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall7f040a92010-12-24 02:08:15 +00002709 /*static=*/false, /*star=*/false,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002710 Size.get(),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002711 T.getOpenLocation(),
2712 T.getCloseLocation()),
Richard Smith6ee326a2012-04-10 01:32:12 +00002713 Attrs, T.getCloseLocation());
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002714
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002715 if (T.getCloseLocation().isInvalid())
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002716 return;
2717 }
2718}
2719
2720/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2721/// This ambiguity appears in the syntax of the C++ new operator.
2722///
2723/// new-expression:
2724/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2725/// new-initializer[opt]
2726///
2727/// new-placement:
2728/// '(' expression-list ')'
2729///
John McCallca0408f2010-08-23 06:44:23 +00002730bool Parser::ParseExpressionListOrTypeId(
Chris Lattner5f9e2722011-07-23 10:55:15 +00002731 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner59232d32009-01-04 21:25:24 +00002732 Declarator &D) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002733 // The '(' was already consumed.
2734 if (isTypeIdInParens()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002735 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlab197ba2009-02-09 18:23:29 +00002736 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002737 ParseDeclarator(D);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002738 return D.isInvalidType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002739 }
2740
2741 // It's not a type, it has to be an expression list.
2742 // Discard the comma locations - ActOnCXXNew has enough parameters.
2743 CommaLocsTy CommaLocs;
2744 return ParseExpressionList(PlacementArgs, CommaLocs);
2745}
2746
2747/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2748/// to free memory allocated by new.
2749///
Chris Lattner59232d32009-01-04 21:25:24 +00002750/// This method is called to parse the 'delete' expression after the optional
2751/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2752/// and "Start" is its location. Otherwise, "Start" is the location of the
2753/// 'delete' token.
2754///
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002755/// delete-expression:
2756/// '::'[opt] 'delete' cast-expression
2757/// '::'[opt] 'delete' '[' ']' cast-expression
John McCall60d7b3a2010-08-24 06:29:42 +00002758ExprResult
Chris Lattner59232d32009-01-04 21:25:24 +00002759Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2760 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2761 ConsumeToken(); // Consume 'delete'
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002762
2763 // Array delete?
2764 bool ArrayDelete = false;
Richard Smith6ee326a2012-04-10 01:32:12 +00002765 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith950435c2012-08-09 19:01:51 +00002766 // C++11 [expr.delete]p1:
2767 // Whenever the delete keyword is followed by empty square brackets, it
2768 // shall be interpreted as [array delete].
2769 // [Footnote: A lambda expression with a lambda-introducer that consists
2770 // of empty square brackets can follow the delete keyword if
2771 // the lambda expression is enclosed in parentheses.]
2772 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2773 // lambda-introducer.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002774 ArrayDelete = true;
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002775 BalancedDelimiterTracker T(*this, tok::l_square);
2776
2777 T.consumeOpen();
2778 T.consumeClose();
2779 if (T.getCloseLocation().isInvalid())
Sebastian Redl20df9b72008-12-11 22:51:44 +00002780 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002781 }
2782
John McCall60d7b3a2010-08-24 06:29:42 +00002783 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002784 if (Operand.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002785 return Operand;
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002786
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002787 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002788}
Sebastian Redl64b45f72009-01-05 20:52:13 +00002789
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002790static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2791 switch (kind) {
2792 default: llvm_unreachable("Not a known type trait");
Stephen Hines651f13c2014-04-23 16:59:28 -07002793#define TYPE_TRAIT_1(Spelling, Name, Key) \
2794case tok::kw_ ## Spelling: return UTT_ ## Name;
2795#define TYPE_TRAIT_2(Spelling, Name, Key) \
2796case tok::kw_ ## Spelling: return BTT_ ## Name;
2797#include "clang/Basic/TokenKinds.def"
2798#define TYPE_TRAIT_N(Spelling, Name, Key) \
2799 case tok::kw_ ## Spelling: return TT_ ## Name;
2800#include "clang/Basic/TokenKinds.def"
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002801 }
2802}
2803
John Wiegley21ff2e52011-04-28 00:16:57 +00002804static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2805 switch(kind) {
2806 default: llvm_unreachable("Not a known binary type trait");
2807 case tok::kw___array_rank: return ATT_ArrayRank;
2808 case tok::kw___array_extent: return ATT_ArrayExtent;
2809 }
2810}
2811
John Wiegley55262202011-04-25 06:54:41 +00002812static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2813 switch(kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002814 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegley55262202011-04-25 06:54:41 +00002815 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2816 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2817 }
2818}
2819
Stephen Hines651f13c2014-04-23 16:59:28 -07002820static unsigned TypeTraitArity(tok::TokenKind kind) {
2821 switch (kind) {
2822 default: llvm_unreachable("Not a known type trait");
2823#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2824#include "clang/Basic/TokenKinds.def"
Francois Pichet6ad6f282010-12-07 00:08:36 +00002825 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002826}
2827
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002828/// \brief Parse the built-in type-trait pseudo-functions that allow
2829/// implementation of the TR1/C++11 type traits templates.
2830///
2831/// primary-expression:
Stephen Hines651f13c2014-04-23 16:59:28 -07002832/// unary-type-trait '(' type-id ')'
2833/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002834/// type-trait '(' type-id-seq ')'
2835///
2836/// type-id-seq:
2837/// type-id ...[opt] type-id-seq[opt]
2838///
2839ExprResult Parser::ParseTypeTrait() {
Stephen Hines651f13c2014-04-23 16:59:28 -07002840 tok::TokenKind Kind = Tok.getKind();
2841 unsigned Arity = TypeTraitArity(Kind);
2842
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002843 SourceLocation Loc = ConsumeToken();
2844
2845 BalancedDelimiterTracker Parens(*this, tok::l_paren);
Stephen Hines651f13c2014-04-23 16:59:28 -07002846 if (Parens.expectAndConsume())
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002847 return ExprError();
2848
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002849 SmallVector<ParsedType, 2> Args;
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002850 do {
2851 // Parse the next type.
2852 TypeResult Ty = ParseTypeName();
2853 if (Ty.isInvalid()) {
2854 Parens.skipToEnd();
2855 return ExprError();
2856 }
2857
2858 // Parse the ellipsis, if present.
2859 if (Tok.is(tok::ellipsis)) {
2860 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2861 if (Ty.isInvalid()) {
2862 Parens.skipToEnd();
2863 return ExprError();
2864 }
2865 }
2866
2867 // Add this type to the list of arguments.
2868 Args.push_back(Ty.get());
Stephen Hines651f13c2014-04-23 16:59:28 -07002869 } while (TryConsumeToken(tok::comma));
2870
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002871 if (Parens.consumeClose())
2872 return ExprError();
Stephen Hines651f13c2014-04-23 16:59:28 -07002873
2874 SourceLocation EndLoc = Parens.getCloseLocation();
2875
2876 if (Arity && Args.size() != Arity) {
2877 Diag(EndLoc, diag::err_type_trait_arity)
2878 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
2879 return ExprError();
2880 }
2881
2882 if (!Arity && Args.empty()) {
2883 Diag(EndLoc, diag::err_type_trait_arity)
2884 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
2885 return ExprError();
2886 }
2887
2888 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002889}
2890
John Wiegley21ff2e52011-04-28 00:16:57 +00002891/// ParseArrayTypeTrait - Parse the built-in array type-trait
2892/// pseudo-functions.
2893///
2894/// primary-expression:
2895/// [Embarcadero] '__array_rank' '(' type-id ')'
2896/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2897///
2898ExprResult Parser::ParseArrayTypeTrait() {
2899 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2900 SourceLocation Loc = ConsumeToken();
2901
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002902 BalancedDelimiterTracker T(*this, tok::l_paren);
Stephen Hines651f13c2014-04-23 16:59:28 -07002903 if (T.expectAndConsume())
John Wiegley21ff2e52011-04-28 00:16:57 +00002904 return ExprError();
2905
2906 TypeResult Ty = ParseTypeName();
2907 if (Ty.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002908 SkipUntil(tok::comma, StopAtSemi);
2909 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley21ff2e52011-04-28 00:16:57 +00002910 return ExprError();
2911 }
2912
2913 switch (ATT) {
2914 case ATT_ArrayRank: {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002915 T.consumeClose();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002916 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002917 T.getCloseLocation());
John Wiegley21ff2e52011-04-28 00:16:57 +00002918 }
2919 case ATT_ArrayExtent: {
Stephen Hines651f13c2014-04-23 16:59:28 -07002920 if (ExpectAndConsume(tok::comma)) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002921 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley21ff2e52011-04-28 00:16:57 +00002922 return ExprError();
2923 }
2924
2925 ExprResult DimExpr = ParseExpression();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002926 T.consumeClose();
John Wiegley21ff2e52011-04-28 00:16:57 +00002927
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002928 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2929 T.getCloseLocation());
John Wiegley21ff2e52011-04-28 00:16:57 +00002930 }
John Wiegley21ff2e52011-04-28 00:16:57 +00002931 }
David Blaikie30263482012-01-20 21:50:17 +00002932 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley21ff2e52011-04-28 00:16:57 +00002933}
2934
John Wiegley55262202011-04-25 06:54:41 +00002935/// ParseExpressionTrait - Parse built-in expression-trait
2936/// pseudo-functions like __is_lvalue_expr( xxx ).
2937///
2938/// primary-expression:
2939/// [Embarcadero] expression-trait '(' expression ')'
2940///
2941ExprResult Parser::ParseExpressionTrait() {
2942 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2943 SourceLocation Loc = ConsumeToken();
2944
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002945 BalancedDelimiterTracker T(*this, tok::l_paren);
Stephen Hines651f13c2014-04-23 16:59:28 -07002946 if (T.expectAndConsume())
John Wiegley55262202011-04-25 06:54:41 +00002947 return ExprError();
2948
2949 ExprResult Expr = ParseExpression();
2950
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002951 T.consumeClose();
John Wiegley55262202011-04-25 06:54:41 +00002952
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002953 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2954 T.getCloseLocation());
John Wiegley55262202011-04-25 06:54:41 +00002955}
2956
2957
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002958/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2959/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2960/// based on the context past the parens.
John McCall60d7b3a2010-08-24 06:29:42 +00002961ExprResult
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002962Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallb3d87482010-08-24 05:47:05 +00002963 ParsedType &CastTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002964 BalancedDelimiterTracker &Tracker,
2965 ColonProtectionRAIIObject &ColonProt) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002966 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002967 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2968 assert(isTypeIdInParens() && "Not a type-id!");
2969
John McCall60d7b3a2010-08-24 06:29:42 +00002970 ExprResult Result(true);
John McCallb3d87482010-08-24 05:47:05 +00002971 CastTy = ParsedType();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002972
2973 // We need to disambiguate a very ugly part of the C++ syntax:
2974 //
2975 // (T())x; - type-id
2976 // (T())*x; - type-id
2977 // (T())/x; - expression
2978 // (T()); - expression
2979 //
2980 // The bad news is that we cannot use the specialized tentative parser, since
2981 // it can only verify that the thing inside the parens can be parsed as
2982 // type-id, it is not useful for determining the context past the parens.
2983 //
2984 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidisa558a892009-05-22 15:12:46 +00002985 // making any unnecessary Action calls.
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002986 //
2987 // It uses a scheme similar to parsing inline methods. The parenthesized
2988 // tokens are cached, the context that follows is determined (possibly by
2989 // parsing a cast-expression), and then we re-introduce the cached tokens
2990 // into the token stream and parse them appropriately.
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002991
Mike Stump1eb44332009-09-09 15:08:12 +00002992 ParenParseOption ParseAs;
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002993 CachedTokens Toks;
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002994
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002995 // Store the tokens of the parentheses. We will parse them after we determine
2996 // the context that follows them.
Argyrios Kyrtzidis14b91622010-04-23 21:20:12 +00002997 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002998 // We didn't find the ')' we expected.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002999 Tracker.consumeClose();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003000 return ExprError();
3001 }
3002
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003003 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003004 ParseAs = CompoundLiteral;
3005 } else {
3006 bool NotCastExpr;
Eli Friedmanb53f08a2009-05-25 19:41:42 +00003007 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3008 NotCastExpr = true;
3009 } else {
3010 // Try parsing the cast-expression that may follow.
3011 // If it is not a cast-expression, NotCastExpr will be true and no token
3012 // will be consumed.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003013 ColonProt.restore();
Eli Friedmanb53f08a2009-05-25 19:41:42 +00003014 Result = ParseCastExpression(false/*isUnaryExpression*/,
3015 false/*isAddressofOperand*/,
John McCallb3d87482010-08-24 05:47:05 +00003016 NotCastExpr,
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00003017 // type-id has priority.
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00003018 IsTypeCast);
Eli Friedmanb53f08a2009-05-25 19:41:42 +00003019 }
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003020
3021 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3022 // an expression.
3023 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003024 }
3025
Mike Stump1eb44332009-09-09 15:08:12 +00003026 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003027 Toks.push_back(Tok);
3028 // Re-enter the stored parenthesized tokens into the token stream, so we may
3029 // parse them now.
3030 PP.EnterTokenStream(Toks.data(), Toks.size(),
3031 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
3032 // Drop the current token and bring the first cached one. It's the same token
3033 // as when we entered this function.
3034 ConsumeAnyToken();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003035
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003036 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00003037 // Parse the type declarator.
3038 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00003039 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003040 {
3041 ColonProtectionRAIIObject InnerColonProtection(*this);
3042 ParseSpecifierQualifierList(DS);
3043 ParseDeclarator(DeclaratorInfo);
3044 }
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003045
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003046 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003047 Tracker.consumeClose();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003048 ColonProt.restore();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003049
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003050 if (ParseAs == CompoundLiteral) {
3051 ExprType = CompoundLiteral;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003052 if (DeclaratorInfo.isInvalidType())
3053 return ExprError();
3054
3055 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3056 return ParseCompoundLiteralExpression(Ty.get(),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003057 Tracker.getOpenLocation(),
3058 Tracker.getCloseLocation());
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003059 }
Mike Stump1eb44332009-09-09 15:08:12 +00003060
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003061 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3062 assert(ParseAs == CastExpr);
3063
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00003064 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003065 return ExprError();
3066
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003067 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003068 if (!Result.isInvalid())
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003069 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3070 DeclaratorInfo, CastTy,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003071 Tracker.getCloseLocation(), Result.get());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003072 return Result;
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003073 }
Mike Stump1eb44332009-09-09 15:08:12 +00003074
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003075 // Not a compound literal, and not followed by a cast-expression.
3076 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003077
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003078 ExprType = SimpleExpr;
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003079 Result = ParseExpression();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003080 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003081 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003082 Tok.getLocation(), Result.get());
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003083
3084 // Match the ')'.
3085 if (Result.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00003086 SkipUntil(tok::r_paren, StopAtSemi);
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003087 return ExprError();
3088 }
Mike Stump1eb44332009-09-09 15:08:12 +00003089
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003090 Tracker.consumeClose();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003091 return Result;
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003092}