blob: 3d1925c25d355b20ceddd65b459b2e6eb2e73eaf [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.
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000221 if (Actions.ActOnCXXGlobalScopeSpecifier(getCurScope(), ConsumeToken(), SS))
222 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
Douglas Gregord4dca082010-02-24 18:44:31 +0000229 bool CheckForDestructor = false;
230 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
231 CheckForDestructor = true;
232 *MayBePseudoDestructor = false;
233 }
234
David Blaikie42d6d0c2011-12-04 05:04:18 +0000235 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
236 DeclSpec DS(AttrFactory);
237 SourceLocation DeclLoc = Tok.getLocation();
238 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Stephen Hines651f13c2014-04-23 16:59:28 -0700239
240 SourceLocation CCLoc;
241 if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
David Blaikie42d6d0c2011-12-04 05:04:18 +0000242 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
243 return false;
244 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700245
David Blaikie42d6d0c2011-12-04 05:04:18 +0000246 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
247 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
248
249 HasScopeSpecifier = true;
250 }
251
Douglas Gregor39a8de12009-02-25 19:37:18 +0000252 while (true) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000253 if (HasScopeSpecifier) {
254 // C++ [basic.lookup.classref]p5:
255 // If the qualified-id has the form
Douglas Gregor3b6afbb2009-09-09 00:23:06 +0000256 //
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000257 // ::class-name-or-namespace-name::...
Douglas Gregor3b6afbb2009-09-09 00:23:06 +0000258 //
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000259 // the class-name-or-namespace-name is looked up in global scope as a
260 // class-name or namespace-name.
261 //
262 // To implement this, we clear out the object type as soon as we've
263 // seen a leading '::' or part of a nested-name-specifier.
John McCallb3d87482010-08-24 05:47:05 +0000264 ObjectType = ParsedType();
Douglas Gregor81b747b2009-09-17 21:32:03 +0000265
266 if (Tok.is(tok::code_completion)) {
267 // Code completion for a nested-name-specifier, where the code
268 // code completion token follows the '::'.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000269 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
Argyrios Kyrtzidisb6b2b182011-04-23 01:04:12 +0000270 // Include code completion token into the range of the scope otherwise
271 // when we try to annotate the scope tokens the dangling code completion
272 // token will cause assertion in
273 // Preprocessor::AnnotatePreviousCachedTokens.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000274 SS.setEndLoc(Tok.getLocation());
275 cutOffParsing();
276 return true;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000277 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000278 }
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregor39a8de12009-02-25 19:37:18 +0000280 // nested-name-specifier:
Chris Lattner77cf72a2009-06-26 03:47:46 +0000281 // nested-name-specifier 'template'[opt] simple-template-id '::'
282
283 // Parse the optional 'template' keyword, then make sure we have
284 // 'identifier <' after it.
285 if (Tok.is(tok::kw_template)) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000286 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedmaneab975d2009-08-29 04:08:08 +0000287 // nested-name-specifier, since they aren't allowed to start with
288 // 'template'.
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000289 if (!HasScopeSpecifier && !ObjectType)
Eli Friedmaneab975d2009-08-29 04:08:08 +0000290 break;
291
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000292 TentativeParsingAction TPA(*this);
Chris Lattner77cf72a2009-06-26 03:47:46 +0000293 SourceLocation TemplateKWLoc = ConsumeToken();
Stephen Hines651f13c2014-04-23 16:59:28 -0700294
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000295 UnqualifiedId TemplateName;
296 if (Tok.is(tok::identifier)) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000297 // Consume the identifier.
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000298 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000299 ConsumeToken();
300 } else if (Tok.is(tok::kw_operator)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700301 // We don't need to actually parse the unqualified-id in this case,
302 // because a simple-template-id cannot start with 'operator', but
303 // go ahead and parse it anyway for consistency with the case where
304 // we already annotated the template-id.
305 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000306 TemplateName)) {
307 TPA.Commit();
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000308 break;
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000309 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700310
Sean Hunte6252d12009-11-28 08:58:14 +0000311 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
312 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000313 Diag(TemplateName.getSourceRange().getBegin(),
314 diag::err_id_after_template_in_nested_name_spec)
315 << TemplateName.getSourceRange();
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000316 TPA.Commit();
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000317 break;
318 }
319 } else {
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000320 TPA.Revert();
Chris Lattner77cf72a2009-06-26 03:47:46 +0000321 break;
322 }
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000324 // If the next token is not '<', we have a qualified-id that refers
325 // to a template name, such as T::template apply, but is not a
326 // template-id.
327 if (Tok.isNot(tok::less)) {
328 TPA.Revert();
329 break;
330 }
331
332 // Commit to parsing the template-id.
333 TPA.Commit();
Douglas Gregord6ab2322010-06-16 23:00:59 +0000334 TemplateTy Template;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000335 if (TemplateNameKind TNK
336 = Actions.ActOnDependentTemplateName(getCurScope(),
337 SS, TemplateKWLoc, TemplateName,
338 ObjectType, EnteringContext,
339 Template)) {
340 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
341 TemplateName, false))
Douglas Gregord6ab2322010-06-16 23:00:59 +0000342 return true;
343 } else
John McCall9ba61662010-02-26 08:45:28 +0000344 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Chris Lattner77cf72a2009-06-26 03:47:46 +0000346 continue;
347 }
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Douglas Gregor39a8de12009-02-25 19:37:18 +0000349 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000350 // We have
Douglas Gregor39a8de12009-02-25 19:37:18 +0000351 //
Stephen Hines651f13c2014-04-23 16:59:28 -0700352 // template-id '::'
Douglas Gregor39a8de12009-02-25 19:37:18 +0000353 //
Stephen Hines651f13c2014-04-23 16:59:28 -0700354 // So we need to check whether the template-id is a simple-template-id of
355 // the right kind (it should name a type or be dependent), and then
Douglas Gregorc45c2322009-03-31 00:43:58 +0000356 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +0000357 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregord4dca082010-02-24 18:44:31 +0000358 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
359 *MayBePseudoDestructor = true;
John McCall9ba61662010-02-26 08:45:28 +0000360 return false;
Douglas Gregord4dca082010-02-24 18:44:31 +0000361 }
362
Richard Smith2db075b2013-03-26 01:15:19 +0000363 if (LastII)
364 *LastII = TemplateId->Name;
365
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000366 // Consume the template-id token.
367 ConsumeToken();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700368
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000369 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
370 SourceLocation CCLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000371
David Blaikie6796fc12011-11-07 03:30:03 +0000372 HasScopeSpecifier = true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700373
Benjamin Kramer5354e772012-08-23 23:38:35 +0000374 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000375 TemplateId->NumArgs);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700376
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000377 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000378 SS,
379 TemplateId->TemplateKWLoc,
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000380 TemplateId->Template,
381 TemplateId->TemplateNameLoc,
382 TemplateId->LAngleLoc,
383 TemplateArgsPtr,
384 TemplateId->RAngleLoc,
385 CCLoc,
386 EnteringContext)) {
387 SourceLocation StartLoc
388 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
389 : TemplateId->TemplateNameLoc;
390 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner67b9e832009-06-26 03:45:46 +0000391 }
Argyrios Kyrtzidiseccce7e2011-05-03 18:45:38 +0000392
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000393 continue;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000394 }
395
Chris Lattner5c7f7862009-06-26 03:52:38 +0000396 // The rest of the nested-name-specifier possibilities start with
397 // tok::identifier.
398 if (Tok.isNot(tok::identifier))
399 break;
400
401 IdentifierInfo &II = *Tok.getIdentifierInfo();
402
403 // nested-name-specifier:
404 // type-name '::'
405 // namespace-name '::'
406 // nested-name-specifier identifier '::'
407 Token Next = NextToken();
Chris Lattner46646492009-12-07 01:36:53 +0000408
409 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
410 // and emit a fixit hint for it.
Douglas Gregorb10cd042010-02-21 18:36:56 +0000411 if (Next.is(tok::colon) && !ColonIsSacred) {
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000412 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
413 Tok.getLocation(),
414 Next.getLocation(), ObjectType,
Douglas Gregorb10cd042010-02-21 18:36:56 +0000415 EnteringContext) &&
416 // If the token after the colon isn't an identifier, it's still an
417 // error, but they probably meant something else strange so don't
418 // recover like this.
419 PP.LookAhead(1).is(tok::identifier)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700420 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
Douglas Gregor849b2432010-03-31 17:46:05 +0000421 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregorb10cd042010-02-21 18:36:56 +0000422 // Recover as if the user wrote '::'.
423 Next.setKind(tok::coloncolon);
424 }
Chris Lattner46646492009-12-07 01:36:53 +0000425 }
426
Chris Lattner5c7f7862009-06-26 03:52:38 +0000427 if (Next.is(tok::coloncolon)) {
Douglas Gregor77549082010-02-24 21:29:12 +0000428 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Douglas Gregor23c94db2010-07-02 17:43:08 +0000429 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(),
Douglas Gregor77549082010-02-24 21:29:12 +0000430 II, ObjectType)) {
Douglas Gregord4dca082010-02-24 18:44:31 +0000431 *MayBePseudoDestructor = true;
John McCall9ba61662010-02-26 08:45:28 +0000432 return false;
Douglas Gregord4dca082010-02-24 18:44:31 +0000433 }
434
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700435 if (ColonIsSacred) {
436 const Token &Next2 = GetLookAheadToken(2);
437 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
438 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
439 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
440 << Next2.getName()
441 << FixItHint::CreateReplacement(Next.getLocation(), ":");
442 Token ColonColon;
443 PP.Lex(ColonColon);
444 ColonColon.setKind(tok::colon);
445 PP.EnterToken(ColonColon);
446 break;
447 }
448 }
449
Richard Smith2db075b2013-03-26 01:15:19 +0000450 if (LastII)
451 *LastII = &II;
452
Chris Lattner5c7f7862009-06-26 03:52:38 +0000453 // We have an identifier followed by a '::'. Lookup this name
454 // as the name in a nested-name-specifier.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700455 Token Identifier = Tok;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000456 SourceLocation IdLoc = ConsumeToken();
Chris Lattner46646492009-12-07 01:36:53 +0000457 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
458 "NextToken() not working properly!");
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700459 Token ColonColon = Tok;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000460 SourceLocation CCLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Richard Trieu919b9552012-11-02 01:08:58 +0000462 CheckForLParenAfterColonColon();
463
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700464 bool IsCorrectedToColon = false;
465 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000466 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700467 ObjectType, EnteringContext, SS,
468 false, CorrectionFlagPtr)) {
469 // Identifier is not recognized as a nested name, but we can have
470 // mistyped '::' instead of ':'.
471 if (CorrectionFlagPtr && IsCorrectedToColon) {
472 ColonColon.setKind(tok::colon);
473 PP.EnterToken(Tok);
474 PP.EnterToken(ColonColon);
475 Tok = Identifier;
476 break;
477 }
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000478 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700479 }
480 HasScopeSpecifier = true;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000481 continue;
482 }
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Richard Trieu950be712011-09-19 19:01:00 +0000484 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smithea698b32011-04-14 21:45:45 +0000485
Chris Lattner5c7f7862009-06-26 03:52:38 +0000486 // nested-name-specifier:
487 // type-name '<'
488 if (Next.is(tok::less)) {
489 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000490 UnqualifiedId TemplateName;
491 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000492 bool MemberOfUnknownSpecialization;
Douglas Gregor23c94db2010-07-02 17:43:08 +0000493 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c153532010-08-06 12:11:11 +0000494 /*hasTemplateKeyword=*/false,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000495 TemplateName,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000496 ObjectType,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000497 EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000498 Template,
499 MemberOfUnknownSpecialization)) {
David Blaikie6796fc12011-11-07 03:30:03 +0000500 // We have found a template name, so annotate this token
Chris Lattner5c7f7862009-06-26 03:52:38 +0000501 // with a template-id annotation. We do not permit the
502 // template-id to be translated into a type annotation,
503 // because some clients (e.g., the parsing of class template
504 // specializations) still want to see the original template-id
505 // token.
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000506 ConsumeToken();
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000507 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
508 TemplateName, false))
John McCall9ba61662010-02-26 08:45:28 +0000509 return true;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000510 continue;
Larisse Voufoef4579c2013-08-06 01:03:05 +0000511 }
512
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000513 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4147d302011-03-27 19:41:34 +0000514 (IsTypename || IsTemplateArgumentList(1))) {
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000515 // We have something like t::getAs<T>, where getAs is a
516 // member of an unknown specialization. However, this will only
517 // parse correctly as a template, so suggest the keyword 'template'
518 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4147d302011-03-27 19:41:34 +0000519 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikie4e4d0842012-03-11 07:00:24 +0000520 if (getLangOpts().MicrosoftExt)
Francois Pichetcf320c62011-04-22 08:25:24 +0000521 DiagID = diag::warn_missing_dependent_template_keyword;
Francois Pichet4147d302011-03-27 19:41:34 +0000522
523 Diag(Tok.getLocation(), DiagID)
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000524 << II.getName()
525 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
526
Douglas Gregord6ab2322010-06-16 23:00:59 +0000527 if (TemplateNameKind TNK
Douglas Gregor23c94db2010-07-02 17:43:08 +0000528 = Actions.ActOnDependentTemplateName(getCurScope(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000529 SS, SourceLocation(),
Douglas Gregord6ab2322010-06-16 23:00:59 +0000530 TemplateName, ObjectType,
531 EnteringContext, Template)) {
532 // Consume the identifier.
533 ConsumeToken();
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000534 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
535 TemplateName, false))
536 return true;
Douglas Gregord6ab2322010-06-16 23:00:59 +0000537 }
538 else
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000539 return true;
Douglas Gregord6ab2322010-06-16 23:00:59 +0000540
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000541 continue;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000542 }
543 }
544
Douglas Gregor39a8de12009-02-25 19:37:18 +0000545 // We don't have any tokens that form the beginning of a
546 // nested-name-specifier, so we're done.
547 break;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000548 }
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Douglas Gregord4dca082010-02-24 18:44:31 +0000550 // Even if we didn't see any pieces of a nested-name-specifier, we
551 // still check whether there is a tilde in this position, which
552 // indicates a potential pseudo-destructor.
553 if (CheckForDestructor && Tok.is(tok::tilde))
554 *MayBePseudoDestructor = true;
555
John McCall9ba61662010-02-26 08:45:28 +0000556 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000557}
558
559/// ParseCXXIdExpression - Handle id-expression.
560///
561/// id-expression:
562/// unqualified-id
563/// qualified-id
564///
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000565/// qualified-id:
566/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
567/// '::' identifier
568/// '::' operator-function-id
Douglas Gregoredce4dd2009-06-30 22:34:41 +0000569/// '::' template-id
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000570///
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000571/// NOTE: The standard specifies that, for qualified-id, the parser does not
572/// expect:
573///
574/// '::' conversion-function-id
575/// '::' '~' class-name
576///
577/// This may cause a slight inconsistency on diagnostics:
578///
579/// class C {};
580/// namespace A {}
581/// void f() {
582/// :: A :: ~ C(); // Some Sema error about using destructor with a
583/// // namespace.
584/// :: ~ C(); // Some Parser error like 'unexpected ~'.
585/// }
586///
587/// We simplify the parser a bit and make it work like:
588///
589/// qualified-id:
590/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
591/// '::' unqualified-id
592///
593/// That way Sema can handle and report similar errors for namespaces and the
594/// global scope.
595///
Sebastian Redlebc07d52009-02-03 20:19:35 +0000596/// The isAddressOfOperand parameter indicates that this id-expression is a
597/// direct operand of the address-of operator. This is, besides member contexts,
598/// the only place where a qualified-id naming a non-static class member may
599/// appear.
600///
John McCall60d7b3a2010-08-24 06:29:42 +0000601ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000602 // qualified-id:
603 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
604 // '::' unqualified-id
605 //
606 CXXScopeSpec SS;
Douglas Gregorefaa93a2011-11-07 17:33:42 +0000607 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000608
609 SourceLocation TemplateKWLoc;
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000610 UnqualifiedId Name;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000611 if (ParseUnqualifiedId(SS,
612 /*EnteringContext=*/false,
613 /*AllowDestructorName=*/false,
614 /*AllowConstructorName=*/false,
John McCallb3d87482010-08-24 05:47:05 +0000615 /*ObjectType=*/ ParsedType(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000616 TemplateKWLoc,
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000617 Name))
618 return ExprError();
John McCallb681b612009-11-22 02:49:43 +0000619
620 // This is only the direct operand of an & operator if it is not
621 // followed by a postfix-expression suffix.
John McCall9c72c602010-08-27 09:08:28 +0000622 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
623 isAddressOfOperand = false;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000624
625 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
626 Tok.is(tok::l_paren), isAddressOfOperand);
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000627}
628
Richard Smith0a664b82013-05-09 21:36:41 +0000629/// ParseLambdaExpression - Parse a C++11 lambda expression.
Douglas Gregorae7902c2011-08-04 15:30:47 +0000630///
631/// lambda-expression:
632/// lambda-introducer lambda-declarator[opt] compound-statement
633///
634/// lambda-introducer:
635/// '[' lambda-capture[opt] ']'
636///
637/// lambda-capture:
638/// capture-default
639/// capture-list
640/// capture-default ',' capture-list
641///
642/// capture-default:
643/// '&'
644/// '='
645///
646/// capture-list:
647/// capture
648/// capture-list ',' capture
649///
650/// capture:
Richard Smith0a664b82013-05-09 21:36:41 +0000651/// simple-capture
652/// init-capture [C++1y]
653///
654/// simple-capture:
Douglas Gregorae7902c2011-08-04 15:30:47 +0000655/// identifier
656/// '&' identifier
657/// 'this'
658///
Richard Smith0a664b82013-05-09 21:36:41 +0000659/// init-capture: [C++1y]
660/// identifier initializer
661/// '&' identifier initializer
662///
Douglas Gregorae7902c2011-08-04 15:30:47 +0000663/// lambda-declarator:
664/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
665/// 'mutable'[opt] exception-specification[opt]
666/// trailing-return-type[opt]
667///
668ExprResult Parser::ParseLambdaExpression() {
669 // Parse lambda-introducer.
670 LambdaIntroducer Intro;
Bill Wendling2434dcf2013-12-05 05:25:04 +0000671 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
Douglas Gregorae7902c2011-08-04 15:30:47 +0000672 if (DiagID) {
673 Diag(Tok, DiagID.getValue());
Alexey Bataev8fe24752013-11-18 08:17:37 +0000674 SkipUntil(tok::r_square, StopAtSemi);
675 SkipUntil(tok::l_brace, StopAtSemi);
676 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmandc3b7232012-01-04 02:40:39 +0000677 return ExprError();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000678 }
679
680 return ParseLambdaExpressionAfterIntroducer(Intro);
681}
682
683/// TryParseLambdaExpression - Use lookahead and potentially tentative
684/// parsing to determine if we are looking at a C++0x lambda expression, and parse
685/// it if we are.
686///
687/// If we are not looking at a lambda expression, returns ExprError().
688ExprResult Parser::TryParseLambdaExpression() {
Richard Smith80ad52f2013-01-02 11:42:31 +0000689 assert(getLangOpts().CPlusPlus11
Douglas Gregorae7902c2011-08-04 15:30:47 +0000690 && Tok.is(tok::l_square)
691 && "Not at the start of a possible lambda expression.");
692
693 const Token Next = NextToken(), After = GetLookAheadToken(2);
694
695 // If lookahead indicates this is a lambda...
696 if (Next.is(tok::r_square) || // []
697 Next.is(tok::equal) || // [=
698 (Next.is(tok::amp) && // [&] or [&,
699 (After.is(tok::r_square) ||
700 After.is(tok::comma))) ||
701 (Next.is(tok::identifier) && // [identifier]
702 After.is(tok::r_square))) {
703 return ParseLambdaExpression();
704 }
705
Eli Friedmandc3b7232012-01-04 02:40:39 +0000706 // If lookahead indicates an ObjC message send...
707 // [identifier identifier
Douglas Gregorae7902c2011-08-04 15:30:47 +0000708 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmandc3b7232012-01-04 02:40:39 +0000709 return ExprEmpty();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000710 }
Bill Wendling2434dcf2013-12-05 05:25:04 +0000711
Eli Friedmandc3b7232012-01-04 02:40:39 +0000712 // Here, we're stuck: lambda introducers and Objective-C message sends are
713 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
714 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
715 // writing two routines to parse a lambda introducer, just try to parse
716 // a lambda introducer first, and fall back if that fails.
717 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregorae7902c2011-08-04 15:30:47 +0000718 LambdaIntroducer Intro;
719 if (TryParseLambdaIntroducer(Intro))
Eli Friedmandc3b7232012-01-04 02:40:39 +0000720 return ExprEmpty();
Bill Wendling2434dcf2013-12-05 05:25:04 +0000721
Douglas Gregorae7902c2011-08-04 15:30:47 +0000722 return ParseLambdaExpressionAfterIntroducer(Intro);
723}
724
Richard Smith440d4562013-05-21 22:21:19 +0000725/// \brief Parse a lambda introducer.
726/// \param Intro A LambdaIntroducer filled in with information about the
727/// contents of the lambda-introducer.
728/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
729/// message send and a lambda expression. In this mode, we will
730/// sometimes skip the initializers for init-captures and not fully
731/// populate \p Intro. This flag will be set to \c true if we do so.
732/// \return A DiagnosticID if it hit something unexpected. The location for
733/// for the diagnostic is that of the current token.
734Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
735 bool *SkippedInits) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000736 typedef Optional<unsigned> DiagResult;
Douglas Gregorae7902c2011-08-04 15:30:47 +0000737
738 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000739 BalancedDelimiterTracker T(*this, tok::l_square);
740 T.consumeOpen();
741
742 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregorae7902c2011-08-04 15:30:47 +0000743
744 bool first = true;
745
746 // Parse capture-default.
747 if (Tok.is(tok::amp) &&
748 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
749 Intro.Default = LCD_ByRef;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000750 Intro.DefaultLoc = ConsumeToken();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000751 first = false;
752 } else if (Tok.is(tok::equal)) {
753 Intro.Default = LCD_ByCopy;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000754 Intro.DefaultLoc = ConsumeToken();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000755 first = false;
756 }
757
758 while (Tok.isNot(tok::r_square)) {
759 if (!first) {
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000760 if (Tok.isNot(tok::comma)) {
Douglas Gregor437fbc52012-07-31 00:50:07 +0000761 // Provide a completion for a lambda introducer here. Except
762 // in Objective-C, where this is Almost Surely meant to be a message
763 // send. In that case, fail here and let the ObjC message
764 // expression parser perform the completion.
Douglas Gregord48ab062012-07-31 15:27:48 +0000765 if (Tok.is(tok::code_completion) &&
766 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
767 !Intro.Captures.empty())) {
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000768 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
769 /*AfterAmpersand=*/false);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700770 cutOffParsing();
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000771 break;
772 }
773
Douglas Gregorae7902c2011-08-04 15:30:47 +0000774 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000775 }
Douglas Gregorae7902c2011-08-04 15:30:47 +0000776 ConsumeToken();
777 }
778
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000779 if (Tok.is(tok::code_completion)) {
780 // If we're in Objective-C++ and we have a bare '[', then this is more
781 // likely to be a message receiver.
David Blaikie4e4d0842012-03-11 07:00:24 +0000782 if (getLangOpts().ObjC1 && first)
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000783 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
784 else
785 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
786 /*AfterAmpersand=*/false);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700787 cutOffParsing();
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000788 break;
789 }
Douglas Gregorae7902c2011-08-04 15:30:47 +0000790
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000791 first = false;
792
Douglas Gregorae7902c2011-08-04 15:30:47 +0000793 // Parse capture.
794 LambdaCaptureKind Kind = LCK_ByCopy;
795 SourceLocation Loc;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700796 IdentifierInfo *Id = nullptr;
Douglas Gregora7365242012-02-14 19:27:52 +0000797 SourceLocation EllipsisLoc;
Richard Smith0a664b82013-05-09 21:36:41 +0000798 ExprResult Init;
Douglas Gregora7365242012-02-14 19:27:52 +0000799
Douglas Gregorae7902c2011-08-04 15:30:47 +0000800 if (Tok.is(tok::kw_this)) {
801 Kind = LCK_This;
802 Loc = ConsumeToken();
803 } else {
804 if (Tok.is(tok::amp)) {
805 Kind = LCK_ByRef;
806 ConsumeToken();
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000807
808 if (Tok.is(tok::code_completion)) {
809 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
810 /*AfterAmpersand=*/true);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700811 cutOffParsing();
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000812 break;
813 }
Douglas Gregorae7902c2011-08-04 15:30:47 +0000814 }
815
816 if (Tok.is(tok::identifier)) {
817 Id = Tok.getIdentifierInfo();
818 Loc = ConsumeToken();
819 } else if (Tok.is(tok::kw_this)) {
820 // FIXME: If we want to suggest a fixit here, will need to return more
821 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
822 // Clear()ed to prevent emission in case of tentative parsing?
823 return DiagResult(diag::err_this_captured_by_reference);
824 } else {
825 return DiagResult(diag::err_expected_capture);
826 }
Richard Smith0a664b82013-05-09 21:36:41 +0000827
828 if (Tok.is(tok::l_paren)) {
829 BalancedDelimiterTracker Parens(*this, tok::l_paren);
830 Parens.consumeOpen();
831
832 ExprVector Exprs;
833 CommaLocsTy Commas;
Richard Smith440d4562013-05-21 22:21:19 +0000834 if (SkippedInits) {
835 Parens.skipToEnd();
836 *SkippedInits = true;
837 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith0a664b82013-05-09 21:36:41 +0000838 Parens.skipToEnd();
839 Init = ExprError();
840 } else {
841 Parens.consumeClose();
842 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
843 Parens.getCloseLocation(),
844 Exprs);
845 }
846 } else if (Tok.is(tok::l_brace) || Tok.is(tok::equal)) {
Bill Wendling2434dcf2013-12-05 05:25:04 +0000847 // Each lambda init-capture forms its own full expression, which clears
848 // Actions.MaybeODRUseExprs. So create an expression evaluation context
849 // to save the necessary state, and restore it later.
850 EnterExpressionEvaluationContext EC(Actions,
851 Sema::PotentiallyEvaluated);
Stephen Hines651f13c2014-04-23 16:59:28 -0700852 TryConsumeToken(tok::equal);
Richard Smith0a664b82013-05-09 21:36:41 +0000853
Richard Smith440d4562013-05-21 22:21:19 +0000854 if (!SkippedInits)
855 Init = ParseInitializer();
856 else if (Tok.is(tok::l_brace)) {
857 BalancedDelimiterTracker Braces(*this, tok::l_brace);
858 Braces.consumeOpen();
859 Braces.skipToEnd();
860 *SkippedInits = true;
861 } else {
862 // We're disambiguating this:
863 //
864 // [..., x = expr
865 //
866 // We need to find the end of the following expression in order to
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700867 // determine whether this is an Obj-C message send's receiver, a
868 // C99 designator, or a lambda init-capture.
Richard Smith440d4562013-05-21 22:21:19 +0000869 //
870 // Parse the expression to find where it ends, and annotate it back
871 // onto the tokens. We would have parsed this expression the same way
872 // in either case: both the RHS of an init-capture and the RHS of an
873 // assignment expression are parsed as an initializer-clause, and in
874 // neither case can anything be added to the scope between the '[' and
875 // here.
876 //
877 // FIXME: This is horrible. Adding a mechanism to skip an expression
878 // would be much cleaner.
879 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
880 // that instead. (And if we see a ':' with no matching '?', we can
881 // classify this as an Obj-C message send.)
882 SourceLocation StartLoc = Tok.getLocation();
883 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
884 Init = ParseInitializer();
885
886 if (Tok.getLocation() != StartLoc) {
887 // Back out the lexing of the token after the initializer.
888 PP.RevertCachedTokens(1);
889
890 // Replace the consumed tokens with an appropriate annotation.
891 Tok.setLocation(StartLoc);
892 Tok.setKind(tok::annot_primary_expr);
893 setExprAnnotation(Tok, Init);
894 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
895 PP.AnnotateCachedTokens(Tok);
896
897 // Consume the annotated initializer.
898 ConsumeToken();
899 }
900 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700901 } else
902 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Douglas Gregorae7902c2011-08-04 15:30:47 +0000903 }
Bill Wendling2434dcf2013-12-05 05:25:04 +0000904 // If this is an init capture, process the initialization expression
905 // right away. For lambda init-captures such as the following:
906 // const int x = 10;
907 // auto L = [i = x+1](int a) {
908 // return [j = x+2,
909 // &k = x](char b) { };
910 // };
911 // keep in mind that each lambda init-capture has to have:
912 // - its initialization expression executed in the context
913 // of the enclosing/parent decl-context.
914 // - but the variable itself has to be 'injected' into the
915 // decl-context of its lambda's call-operator (which has
916 // not yet been created).
917 // Each init-expression is a full-expression that has to get
918 // Sema-analyzed (for capturing etc.) before its lambda's
919 // call-operator's decl-context, scope & scopeinfo are pushed on their
920 // respective stacks. Thus if any variable is odr-used in the init-capture
921 // it will correctly get captured in the enclosing lambda, if one exists.
922 // The init-variables above are created later once the lambdascope and
923 // call-operators decl-context is pushed onto its respective stack.
Douglas Gregorae7902c2011-08-04 15:30:47 +0000924
Bill Wendling2434dcf2013-12-05 05:25:04 +0000925 // Since the lambda init-capture's initializer expression occurs in the
926 // context of the enclosing function or lambda, therefore we can not wait
927 // till a lambda scope has been pushed on before deciding whether the
928 // variable needs to be captured. We also need to process all
929 // lvalue-to-rvalue conversions and discarded-value conversions,
930 // so that we can avoid capturing certain constant variables.
931 // For e.g.,
932 // void test() {
933 // const int x = 10;
934 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
935 // return [y = x](int i) { <-- don't capture by enclosing lambda
936 // return y;
937 // }
938 // };
939 // If x was not const, the second use would require 'L' to capture, and
940 // that would be an error.
941
942 ParsedType InitCaptureParsedType;
943 if (Init.isUsable()) {
944 // Get the pointer and store it in an lvalue, so we can use it as an
945 // out argument.
946 Expr *InitExpr = Init.get();
947 // This performs any lvalue-to-rvalue conversions if necessary, which
948 // can affect what gets captured in the containing decl-context.
949 QualType InitCaptureType = Actions.performLambdaInitCaptureInitialization(
950 Loc, Kind == LCK_ByRef, Id, InitExpr);
951 Init = InitExpr;
952 InitCaptureParsedType.set(InitCaptureType);
953 }
954 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init, InitCaptureParsedType);
Douglas Gregorae7902c2011-08-04 15:30:47 +0000955 }
956
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000957 T.consumeClose();
958 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregorae7902c2011-08-04 15:30:47 +0000959 return DiagResult();
960}
961
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000962/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregorae7902c2011-08-04 15:30:47 +0000963///
964/// Returns true if it hit something unexpected.
965bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
966 TentativeParsingAction PA(*this);
967
Richard Smith440d4562013-05-21 22:21:19 +0000968 bool SkippedInits = false;
969 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
Douglas Gregorae7902c2011-08-04 15:30:47 +0000970
971 if (DiagID) {
972 PA.Revert();
973 return true;
974 }
975
Richard Smith440d4562013-05-21 22:21:19 +0000976 if (SkippedInits) {
977 // Parse it again, but this time parse the init-captures too.
978 PA.Revert();
979 Intro = LambdaIntroducer();
980 DiagID = ParseLambdaIntroducer(Intro);
981 assert(!DiagID && "parsing lambda-introducer failed on reparse");
982 return false;
983 }
984
Douglas Gregorae7902c2011-08-04 15:30:47 +0000985 PA.Commit();
986 return false;
987}
988
989/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
990/// expression.
991ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
992 LambdaIntroducer &Intro) {
Eli Friedmandc3b7232012-01-04 02:40:39 +0000993 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
994 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
995
996 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
997 "lambda expression parsing");
998
Faisal Valifad9e132013-09-26 19:54:12 +0000999
1000
Richard Smith0a664b82013-05-09 21:36:41 +00001001 // FIXME: Call into Actions to add any init-capture declarations to the
1002 // scope while parsing the lambda-declarator and compound-statement.
1003
Douglas Gregorae7902c2011-08-04 15:30:47 +00001004 // Parse lambda-declarator[opt].
1005 DeclSpec DS(AttrFactory);
Eli Friedmanf88c4002012-01-04 04:41:38 +00001006 Declarator D(DS, Declarator::LambdaExprContext);
Faisal Valifad9e132013-09-26 19:54:12 +00001007 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1008 Actions.PushLambdaScope();
Douglas Gregorae7902c2011-08-04 15:30:47 +00001009
1010 if (Tok.is(tok::l_paren)) {
1011 ParseScope PrototypeScope(this,
1012 Scope::FunctionPrototypeScope |
Richard Smith3a2b7a12013-01-28 22:42:45 +00001013 Scope::FunctionDeclarationScope |
Douglas Gregorae7902c2011-08-04 15:30:47 +00001014 Scope::DeclScope);
1015
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001016 SourceLocation DeclEndLoc;
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001017 BalancedDelimiterTracker T(*this, tok::l_paren);
1018 T.consumeOpen();
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001019 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregorae7902c2011-08-04 15:30:47 +00001020
1021 // Parse parameter-declaration-clause.
1022 ParsedAttributes Attr(AttrFactory);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001023 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001024 SourceLocation EllipsisLoc;
Faisal Valifad9e132013-09-26 19:54:12 +00001025
1026 if (Tok.isNot(tok::r_paren)) {
Faisal Valifad9e132013-09-26 19:54:12 +00001027 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
Douglas Gregorae7902c2011-08-04 15:30:47 +00001028 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
Faisal Valifad9e132013-09-26 19:54:12 +00001029 // For a generic lambda, each 'auto' within the parameter declaration
1030 // clause creates a template type parameter, so increment the depth.
1031 if (Actions.getCurGenericLambda())
1032 ++CurTemplateDepthTracker;
1033 }
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001034 T.consumeClose();
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001035 SourceLocation RParenLoc = T.getCloseLocation();
1036 DeclEndLoc = RParenLoc;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001037
Stephen Hines651f13c2014-04-23 16:59:28 -07001038 // GNU-style attributes must be parsed before the mutable specifier to be
1039 // compatible with GCC.
1040 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1041
Douglas Gregorae7902c2011-08-04 15:30:47 +00001042 // Parse 'mutable'[opt].
1043 SourceLocation MutableLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -07001044 if (TryConsumeToken(tok::kw_mutable, MutableLoc))
Douglas Gregorae7902c2011-08-04 15:30:47 +00001045 DeclEndLoc = MutableLoc;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001046
1047 // Parse exception-specification[opt].
1048 ExceptionSpecificationType ESpecType = EST_None;
1049 SourceRange ESpecRange;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001050 SmallVector<ParsedType, 2> DynamicExceptions;
1051 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001052 ExprResult NoexceptExpr;
Richard Smitha058fd42012-05-02 22:22:32 +00001053 ESpecType = tryParseExceptionSpecification(ESpecRange,
Douglas Gregor74e2fc32012-04-16 18:27:27 +00001054 DynamicExceptions,
1055 DynamicExceptionRanges,
Richard Smitha058fd42012-05-02 22:22:32 +00001056 NoexceptExpr);
Douglas Gregorae7902c2011-08-04 15:30:47 +00001057
1058 if (ESpecType != EST_None)
1059 DeclEndLoc = ESpecRange.getEnd();
1060
1061 // Parse attribute-specifier[opt].
Richard Smith4e24f0f2013-01-02 12:01:23 +00001062 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregorae7902c2011-08-04 15:30:47 +00001063
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001064 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1065
Douglas Gregorae7902c2011-08-04 15:30:47 +00001066 // Parse trailing-return-type[opt].
Richard Smith54655be2012-06-12 01:51:59 +00001067 TypeResult TrailingReturnType;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001068 if (Tok.is(tok::arrow)) {
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001069 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregorae7902c2011-08-04 15:30:47 +00001070 SourceRange Range;
Richard Smith54655be2012-06-12 01:51:59 +00001071 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregorae7902c2011-08-04 15:30:47 +00001072 if (Range.getEnd().isValid())
1073 DeclEndLoc = Range.getEnd();
1074 }
1075
1076 PrototypeScope.Exit();
1077
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001078 SourceLocation NoLoc;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001079 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001080 /*isAmbiguous=*/false,
1081 LParenLoc,
Douglas Gregorae7902c2011-08-04 15:30:47 +00001082 ParamInfo.data(), ParamInfo.size(),
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001083 EllipsisLoc, RParenLoc,
Douglas Gregorae7902c2011-08-04 15:30:47 +00001084 DS.getTypeQualifiers(),
1085 /*RefQualifierIsLValueRef=*/true,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001086 /*RefQualifierLoc=*/NoLoc,
1087 /*ConstQualifierLoc=*/NoLoc,
1088 /*VolatileQualifierLoc=*/NoLoc,
Douglas Gregorae7902c2011-08-04 15:30:47 +00001089 MutableLoc,
1090 ESpecType, ESpecRange.getBegin(),
1091 DynamicExceptions.data(),
1092 DynamicExceptionRanges.data(),
1093 DynamicExceptions.size(),
1094 NoexceptExpr.isUsable() ?
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001095 NoexceptExpr.get() : nullptr,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001096 LParenLoc, FunLocalRangeEnd, D,
Douglas Gregorae7902c2011-08-04 15:30:47 +00001097 TrailingReturnType),
1098 Attr, DeclEndLoc);
Stephen Hines651f13c2014-04-23 16:59:28 -07001099 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow) ||
1100 Tok.is(tok::kw___attribute) ||
1101 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1102 // It's common to forget that one needs '()' before 'mutable', an attribute
1103 // specifier, or the result type. Deal with this.
1104 unsigned TokKind = 0;
1105 switch (Tok.getKind()) {
1106 case tok::kw_mutable: TokKind = 0; break;
1107 case tok::arrow: TokKind = 1; break;
1108 case tok::kw___attribute:
1109 case tok::l_square: TokKind = 2; break;
1110 default: llvm_unreachable("Unknown token kind");
1111 }
1112
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001113 Diag(Tok, diag::err_lambda_missing_parens)
Stephen Hines651f13c2014-04-23 16:59:28 -07001114 << TokKind
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001115 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1116 SourceLocation DeclLoc = Tok.getLocation();
1117 SourceLocation DeclEndLoc = DeclLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -07001118
1119 // GNU-style attributes must be parsed before the mutable specifier to be
1120 // compatible with GCC.
1121 ParsedAttributes Attr(AttrFactory);
1122 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1123
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001124 // Parse 'mutable', if it's there.
1125 SourceLocation MutableLoc;
1126 if (Tok.is(tok::kw_mutable)) {
1127 MutableLoc = ConsumeToken();
1128 DeclEndLoc = MutableLoc;
1129 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001130
1131 // Parse attribute-specifier[opt].
1132 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1133
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001134 // Parse the return type, if there is one.
Richard Smith54655be2012-06-12 01:51:59 +00001135 TypeResult TrailingReturnType;
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001136 if (Tok.is(tok::arrow)) {
1137 SourceRange Range;
Richard Smith54655be2012-06-12 01:51:59 +00001138 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001139 if (Range.getEnd().isValid())
1140 DeclEndLoc = Range.getEnd();
1141 }
1142
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001143 SourceLocation NoLoc;
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001144 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001145 /*isAmbiguous=*/false,
1146 /*LParenLoc=*/NoLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001147 /*Params=*/nullptr,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001148 /*NumParams=*/0,
1149 /*EllipsisLoc=*/NoLoc,
1150 /*RParenLoc=*/NoLoc,
1151 /*TypeQuals=*/0,
1152 /*RefQualifierIsLValueRef=*/true,
1153 /*RefQualifierLoc=*/NoLoc,
1154 /*ConstQualifierLoc=*/NoLoc,
1155 /*VolatileQualifierLoc=*/NoLoc,
1156 MutableLoc,
1157 EST_None,
1158 /*ESpecLoc=*/NoLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001159 /*Exceptions=*/nullptr,
1160 /*ExceptionRanges=*/nullptr,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001161 /*NumExceptions=*/0,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001162 /*NoexceptExpr=*/nullptr,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001163 DeclLoc, DeclEndLoc, D,
1164 TrailingReturnType),
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001165 Attr, DeclEndLoc);
Douglas Gregorae7902c2011-08-04 15:30:47 +00001166 }
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001167
Douglas Gregorae7902c2011-08-04 15:30:47 +00001168
Eli Friedman906a7e12012-01-06 03:05:34 +00001169 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1170 // it.
Douglas Gregorfccfb622012-02-21 22:51:27 +00001171 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
Douglas Gregorfccfb622012-02-21 22:51:27 +00001172 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman906a7e12012-01-06 03:05:34 +00001173
Eli Friedmanec9ea722012-01-05 03:35:19 +00001174 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1175
Douglas Gregorae7902c2011-08-04 15:30:47 +00001176 // Parse compound-statement.
Eli Friedmandc3b7232012-01-04 02:40:39 +00001177 if (!Tok.is(tok::l_brace)) {
Douglas Gregorae7902c2011-08-04 15:30:47 +00001178 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmandc3b7232012-01-04 02:40:39 +00001179 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1180 return ExprError();
Douglas Gregorae7902c2011-08-04 15:30:47 +00001181 }
1182
Eli Friedmandc3b7232012-01-04 02:40:39 +00001183 StmtResult Stmt(ParseCompoundStatementBody());
1184 BodyScope.Exit();
1185
Eli Friedmandeeab902012-01-04 02:46:53 +00001186 if (!Stmt.isInvalid())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001187 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
Eli Friedmandc3b7232012-01-04 02:40:39 +00001188
Eli Friedmandeeab902012-01-04 02:46:53 +00001189 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1190 return ExprError();
Douglas Gregorae7902c2011-08-04 15:30:47 +00001191}
1192
Reid Spencer5f016e22007-07-11 17:01:13 +00001193/// ParseCXXCasts - This handles the various ways to cast expressions to another
1194/// type.
1195///
1196/// postfix-expression: [C++ 5.2p1]
1197/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1198/// 'static_cast' '<' type-name '>' '(' expression ')'
1199/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1200/// 'const_cast' '<' type-name '>' '(' expression ')'
1201///
John McCall60d7b3a2010-08-24 06:29:42 +00001202ExprResult Parser::ParseCXXCasts() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001203 tok::TokenKind Kind = Tok.getKind();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001204 const char *CastName = nullptr; // For error messages
Reid Spencer5f016e22007-07-11 17:01:13 +00001205
1206 switch (Kind) {
David Blaikieeb2d1f12011-09-23 20:26:49 +00001207 default: llvm_unreachable("Unknown C++ cast!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001208 case tok::kw_const_cast: CastName = "const_cast"; break;
1209 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1210 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1211 case tok::kw_static_cast: CastName = "static_cast"; break;
1212 }
1213
1214 SourceLocation OpLoc = ConsumeToken();
1215 SourceLocation LAngleBracketLoc = Tok.getLocation();
1216
Richard Smithea698b32011-04-14 21:45:45 +00001217 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1218 // diagnose error, suggest fix, and recover parsing.
Richard Smith78fe3e02012-08-20 17:37:52 +00001219 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1220 Token Next = NextToken();
1221 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1222 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1223 }
Richard Smithea698b32011-04-14 21:45:45 +00001224
Reid Spencer5f016e22007-07-11 17:01:13 +00001225 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redl20df9b72008-12-11 22:51:44 +00001226 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001227
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00001228 // Parse the common declaration-specifiers piece.
1229 DeclSpec DS(AttrFactory);
1230 ParseSpecifierQualifierList(DS);
1231
1232 // Parse the abstract-declarator, if present.
1233 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1234 ParseDeclarator(DeclaratorInfo);
1235
Reid Spencer5f016e22007-07-11 17:01:13 +00001236 SourceLocation RAngleBracketLoc = Tok.getLocation();
1237
Stephen Hines651f13c2014-04-23 16:59:28 -07001238 if (ExpectAndConsume(tok::greater))
1239 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001240
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001241 SourceLocation LParenLoc, RParenLoc;
1242 BalancedDelimiterTracker T(*this, tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00001243
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001244 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis21e7ad22009-05-22 10:23:16 +00001245 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001246
John McCall60d7b3a2010-08-24 06:29:42 +00001247 ExprResult Result = ParseExpression();
Mike Stump1eb44332009-09-09 15:08:12 +00001248
Argyrios Kyrtzidis21e7ad22009-05-22 10:23:16 +00001249 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001250 T.consumeClose();
Reid Spencer5f016e22007-07-11 17:01:13 +00001251
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00001252 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregor49badde2008-10-27 19:41:14 +00001253 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00001254 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor809070a2009-02-18 17:45:20 +00001255 RAngleBracketLoc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001256 T.getOpenLocation(), Result.get(),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001257 T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001258
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001259 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00001260}
1261
Sebastian Redlc42e1182008-11-11 11:37:55 +00001262/// ParseCXXTypeid - This handles the C++ typeid expression.
1263///
1264/// postfix-expression: [C++ 5.2p1]
1265/// 'typeid' '(' expression ')'
1266/// 'typeid' '(' type-id ')'
1267///
John McCall60d7b3a2010-08-24 06:29:42 +00001268ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc42e1182008-11-11 11:37:55 +00001269 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1270
1271 SourceLocation OpLoc = ConsumeToken();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001272 SourceLocation LParenLoc, RParenLoc;
1273 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc42e1182008-11-11 11:37:55 +00001274
1275 // typeid expressions are always parenthesized.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001276 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redl20df9b72008-12-11 22:51:44 +00001277 return ExprError();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001278 LParenLoc = T.getOpenLocation();
Sebastian Redlc42e1182008-11-11 11:37:55 +00001279
John McCall60d7b3a2010-08-24 06:29:42 +00001280 ExprResult Result;
Sebastian Redlc42e1182008-11-11 11:37:55 +00001281
Richard Smith05766812012-08-18 00:55:03 +00001282 // C++0x [expr.typeid]p3:
1283 // When typeid is applied to an expression other than an lvalue of a
1284 // polymorphic class type [...] The expression is an unevaluated
1285 // operand (Clause 5).
1286 //
1287 // Note that we can't tell whether the expression is an lvalue of a
1288 // polymorphic class type until after we've parsed the expression; we
1289 // speculatively assume the subexpression is unevaluated, and fix it up
1290 // later.
1291 //
1292 // We enter the unevaluated context before trying to determine whether we
1293 // have a type-id, because the tentative parse logic will try to resolve
1294 // names, and must treat them as unevaluated.
Eli Friedman80bfa3d2012-09-26 04:34:21 +00001295 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1296 Sema::ReuseLambdaContextDecl);
Richard Smith05766812012-08-18 00:55:03 +00001297
Sebastian Redlc42e1182008-11-11 11:37:55 +00001298 if (isTypeIdInParens()) {
Douglas Gregor809070a2009-02-18 17:45:20 +00001299 TypeResult Ty = ParseTypeName();
Sebastian Redlc42e1182008-11-11 11:37:55 +00001300
1301 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001302 T.consumeClose();
1303 RParenLoc = T.getCloseLocation();
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +00001304 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redl20df9b72008-12-11 22:51:44 +00001305 return ExprError();
Sebastian Redlc42e1182008-11-11 11:37:55 +00001306
1307 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallb3d87482010-08-24 05:47:05 +00001308 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +00001309 } else {
1310 Result = ParseExpression();
1311
1312 // Match the ')'.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001313 if (Result.isInvalid())
Alexey Bataev8fe24752013-11-18 08:17:37 +00001314 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc42e1182008-11-11 11:37:55 +00001315 else {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001316 T.consumeClose();
1317 RParenLoc = T.getCloseLocation();
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +00001318 if (RParenLoc.isInvalid())
1319 return ExprError();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001320
Sebastian Redlc42e1182008-11-11 11:37:55 +00001321 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001322 Result.get(), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +00001323 }
1324 }
1325
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001326 return Result;
Sebastian Redlc42e1182008-11-11 11:37:55 +00001327}
1328
Francois Pichet01b7c302010-09-08 12:20:18 +00001329/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1330///
1331/// '__uuidof' '(' expression ')'
1332/// '__uuidof' '(' type-id ')'
1333///
1334ExprResult Parser::ParseCXXUuidof() {
1335 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1336
1337 SourceLocation OpLoc = ConsumeToken();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001338 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet01b7c302010-09-08 12:20:18 +00001339
1340 // __uuidof expressions are always parenthesized.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001341 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet01b7c302010-09-08 12:20:18 +00001342 return ExprError();
1343
1344 ExprResult Result;
1345
1346 if (isTypeIdInParens()) {
1347 TypeResult Ty = ParseTypeName();
1348
1349 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001350 T.consumeClose();
Francois Pichet01b7c302010-09-08 12:20:18 +00001351
1352 if (Ty.isInvalid())
1353 return ExprError();
1354
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001355 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1356 Ty.get().getAsOpaquePtr(),
1357 T.getCloseLocation());
Francois Pichet01b7c302010-09-08 12:20:18 +00001358 } else {
1359 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1360 Result = ParseExpression();
1361
1362 // Match the ')'.
1363 if (Result.isInvalid())
Alexey Bataev8fe24752013-11-18 08:17:37 +00001364 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet01b7c302010-09-08 12:20:18 +00001365 else {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001366 T.consumeClose();
Francois Pichet01b7c302010-09-08 12:20:18 +00001367
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001368 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1369 /*isType=*/false,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001370 Result.get(), T.getCloseLocation());
Francois Pichet01b7c302010-09-08 12:20:18 +00001371 }
1372 }
1373
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001374 return Result;
Francois Pichet01b7c302010-09-08 12:20:18 +00001375}
1376
Douglas Gregord4dca082010-02-24 18:44:31 +00001377/// \brief Parse a C++ pseudo-destructor expression after the base,
1378/// . or -> operator, and nested-name-specifier have already been
1379/// parsed.
1380///
1381/// postfix-expression: [C++ 5.2]
1382/// postfix-expression . pseudo-destructor-name
1383/// postfix-expression -> pseudo-destructor-name
1384///
1385/// pseudo-destructor-name:
1386/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1387/// ::[opt] nested-name-specifier template simple-template-id ::
1388/// ~type-name
1389/// ::[opt] nested-name-specifier[opt] ~type-name
1390///
John McCall60d7b3a2010-08-24 06:29:42 +00001391ExprResult
Douglas Gregord4dca082010-02-24 18:44:31 +00001392Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1393 tok::TokenKind OpKind,
1394 CXXScopeSpec &SS,
John McCallb3d87482010-08-24 05:47:05 +00001395 ParsedType ObjectType) {
Douglas Gregord4dca082010-02-24 18:44:31 +00001396 // We're parsing either a pseudo-destructor-name or a dependent
1397 // member access that has the same form as a
1398 // pseudo-destructor-name. We parse both in the same way and let
1399 // the action model sort them out.
1400 //
1401 // Note that the ::[opt] nested-name-specifier[opt] has already
1402 // been parsed, and if there was a simple-template-id, it has
1403 // been coalesced into a template-id annotation token.
1404 UnqualifiedId FirstTypeName;
1405 SourceLocation CCLoc;
1406 if (Tok.is(tok::identifier)) {
1407 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1408 ConsumeToken();
1409 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1410 CCLoc = ConsumeToken();
1411 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001412 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1413 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregord4dca082010-02-24 18:44:31 +00001414 FirstTypeName.setTemplateId(
1415 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1416 ConsumeToken();
1417 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1418 CCLoc = ConsumeToken();
1419 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001420 FirstTypeName.setIdentifier(nullptr, SourceLocation());
Douglas Gregord4dca082010-02-24 18:44:31 +00001421 }
1422
1423 // Parse the tilde.
1424 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1425 SourceLocation TildeLoc = ConsumeToken();
David Blaikie91ec7892011-12-16 16:03:09 +00001426
1427 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1428 DeclSpec DS(AttrFactory);
Benjamin Kramer85c60db2011-12-18 12:18:02 +00001429 ParseDecltypeSpecifier(DS);
David Blaikie91ec7892011-12-16 16:03:09 +00001430 if (DS.getTypeSpecType() == TST_error)
1431 return ExprError();
1432 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1433 OpKind, TildeLoc, DS,
1434 Tok.is(tok::l_paren));
1435 }
1436
Douglas Gregord4dca082010-02-24 18:44:31 +00001437 if (!Tok.is(tok::identifier)) {
1438 Diag(Tok, diag::err_destructor_tilde_identifier);
1439 return ExprError();
1440 }
1441
1442 // Parse the second type.
1443 UnqualifiedId SecondTypeName;
1444 IdentifierInfo *Name = Tok.getIdentifierInfo();
1445 SourceLocation NameLoc = ConsumeToken();
1446 SecondTypeName.setIdentifier(Name, NameLoc);
1447
1448 // If there is a '<', the second type name is a template-id. Parse
1449 // it as such.
1450 if (Tok.is(tok::less) &&
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001451 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1452 Name, NameLoc,
1453 false, ObjectType, SecondTypeName,
1454 /*AssumeTemplateName=*/true))
Douglas Gregord4dca082010-02-24 18:44:31 +00001455 return ExprError();
1456
John McCall9ae2f072010-08-23 23:25:46 +00001457 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1458 OpLoc, OpKind,
Douglas Gregord4dca082010-02-24 18:44:31 +00001459 SS, FirstTypeName, CCLoc,
1460 TildeLoc, SecondTypeName,
1461 Tok.is(tok::l_paren));
1462}
1463
Reid Spencer5f016e22007-07-11 17:01:13 +00001464/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1465///
1466/// boolean-literal: [C++ 2.13.5]
1467/// 'true'
1468/// 'false'
John McCall60d7b3a2010-08-24 06:29:42 +00001469ExprResult Parser::ParseCXXBoolLiteral() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001470 tok::TokenKind Kind = Tok.getKind();
Sebastian Redlf53597f2009-03-15 17:47:39 +00001471 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001472}
Chris Lattner50dd2892008-02-26 00:51:44 +00001473
1474/// ParseThrowExpression - This handles the C++ throw expression.
1475///
1476/// throw-expression: [C++ 15]
1477/// 'throw' assignment-expression[opt]
John McCall60d7b3a2010-08-24 06:29:42 +00001478ExprResult Parser::ParseThrowExpression() {
Chris Lattner50dd2892008-02-26 00:51:44 +00001479 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattner50dd2892008-02-26 00:51:44 +00001480 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redl20df9b72008-12-11 22:51:44 +00001481
Chris Lattner2a2819a2008-04-06 06:02:23 +00001482 // If the current token isn't the start of an assignment-expression,
1483 // then the expression is not present. This handles things like:
1484 // "C ? throw : (void)42", which is crazy but legal.
1485 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1486 case tok::semi:
1487 case tok::r_paren:
1488 case tok::r_square:
1489 case tok::r_brace:
1490 case tok::colon:
1491 case tok::comma:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001492 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
Chris Lattner50dd2892008-02-26 00:51:44 +00001493
Chris Lattner2a2819a2008-04-06 06:02:23 +00001494 default:
John McCall60d7b3a2010-08-24 06:29:42 +00001495 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001496 if (Expr.isInvalid()) return Expr;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001497 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
Chris Lattner2a2819a2008-04-06 06:02:23 +00001498 }
Chris Lattner50dd2892008-02-26 00:51:44 +00001499}
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +00001500
1501/// ParseCXXThis - This handles the C++ 'this' pointer.
1502///
1503/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1504/// a non-lvalue expression whose value is the address of the object for which
1505/// the function is called.
John McCall60d7b3a2010-08-24 06:29:42 +00001506ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +00001507 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1508 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redlf53597f2009-03-15 17:47:39 +00001509 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +00001510}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001511
1512/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1513/// Can be interpreted either as function-style casting ("int(x)")
1514/// or class type construction ("ClassType(x,y,z)")
1515/// or creation of a value-initialized type ("int()").
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001516/// See [C++ 5.2.3].
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001517///
1518/// postfix-expression: [C++ 5.2p1]
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001519/// simple-type-specifier '(' expression-list[opt] ')'
1520/// [C++0x] simple-type-specifier braced-init-list
1521/// typename-specifier '(' expression-list[opt] ')'
1522/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001523///
John McCall60d7b3a2010-08-24 06:29:42 +00001524ExprResult
Sebastian Redl20df9b72008-12-11 22:51:44 +00001525Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001526 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
John McCallb3d87482010-08-24 05:47:05 +00001527 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001528
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001529 assert((Tok.is(tok::l_paren) ||
Richard Smith80ad52f2013-01-02 11:42:31 +00001530 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001531 && "Expected '(' or '{'!");
Douglas Gregorbc61bd82011-01-11 00:33:19 +00001532
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001533 if (Tok.is(tok::l_brace)) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001534 ExprResult Init = ParseBraceInitializer();
1535 if (Init.isInvalid())
1536 return Init;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001537 Expr *InitList = Init.get();
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001538 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1539 MultiExprArg(&InitList, 1),
1540 SourceLocation());
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001541 } else {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001542 BalancedDelimiterTracker T(*this, tok::l_paren);
1543 T.consumeOpen();
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001544
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00001545 ExprVector Exprs;
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001546 CommaLocsTy CommaLocs;
1547
1548 if (Tok.isNot(tok::r_paren)) {
1549 if (ParseExpressionList(Exprs, CommaLocs)) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00001550 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001551 return ExprError();
1552 }
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001553 }
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001554
1555 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001556 T.consumeClose();
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001557
1558 // TypeRep could be null, if it references an invalid typedef.
1559 if (!TypeRep)
1560 return ExprError();
1561
1562 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1563 "Unexpected number of commas!");
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001564 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001565 Exprs,
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001566 T.getCloseLocation());
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001567 }
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001568}
1569
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001570/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001571///
1572/// condition:
1573/// expression
1574/// type-specifier-seq declarator '=' assignment-expression
Richard Smith0635aa72012-02-22 06:49:09 +00001575/// [C++11] type-specifier-seq declarator '=' initializer-clause
1576/// [C++11] type-specifier-seq declarator braced-init-list
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001577/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1578/// '=' assignment-expression
1579///
Dmitri Gribenko1ddbd892012-08-24 00:01:24 +00001580/// \param ExprOut if the condition was parsed as an expression, the parsed
1581/// expression.
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001582///
Dmitri Gribenko1ddbd892012-08-24 00:01:24 +00001583/// \param DeclOut if the condition was parsed as a declaration, the parsed
1584/// declaration.
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001585///
Douglas Gregor586596f2010-05-06 17:25:47 +00001586/// \param Loc The location of the start of the statement that requires this
1587/// condition, e.g., the "for" in a for loop.
1588///
1589/// \param ConvertToBoolean Whether the condition expression should be
1590/// converted to a boolean value.
1591///
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001592/// \returns true if there was a parsing, false otherwise.
John McCall60d7b3a2010-08-24 06:29:42 +00001593bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1594 Decl *&DeclOut,
Douglas Gregor586596f2010-05-06 17:25:47 +00001595 SourceLocation Loc,
1596 bool ConvertToBoolean) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001597 if (Tok.is(tok::code_completion)) {
John McCallf312b1e2010-08-26 23:41:50 +00001598 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001599 cutOffParsing();
1600 return true;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001601 }
1602
Sean Hunt2edf0a22012-06-23 05:07:58 +00001603 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +00001604 MaybeParseCXX11Attributes(attrs);
Sean Hunt2edf0a22012-06-23 05:07:58 +00001605
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001606 if (!isCXXConditionDeclaration()) {
Sean Hunt2edf0a22012-06-23 05:07:58 +00001607 ProhibitAttributes(attrs);
1608
Douglas Gregor586596f2010-05-06 17:25:47 +00001609 // Parse the expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001610 ExprOut = ParseExpression(); // expression
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001611 DeclOut = nullptr;
John McCall60d7b3a2010-08-24 06:29:42 +00001612 if (ExprOut.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001613 return true;
1614
1615 // If required, convert to a boolean value.
1616 if (ConvertToBoolean)
John McCall60d7b3a2010-08-24 06:29:42 +00001617 ExprOut
1618 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1619 return ExprOut.isInvalid();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001620 }
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001621
1622 // type-specifier-seq
John McCall0b7e6782011-03-24 11:26:52 +00001623 DeclSpec DS(AttrFactory);
Richard Smith6b3d3e52013-02-20 19:22:51 +00001624 DS.takeAttributesFrom(attrs);
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001625 ParseSpecifierQualifierList(DS);
1626
1627 // declarator
1628 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1629 ParseDeclarator(DeclaratorInfo);
1630
1631 // simple-asm-expr[opt]
1632 if (Tok.is(tok::kw_asm)) {
Sebastian Redlab197ba2009-02-09 18:23:29 +00001633 SourceLocation Loc;
John McCall60d7b3a2010-08-24 06:29:42 +00001634 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001635 if (AsmLabel.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00001636 SkipUntil(tok::semi, StopAtSemi);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001637 return true;
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001638 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001639 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Sebastian Redlab197ba2009-02-09 18:23:29 +00001640 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001641 }
1642
1643 // If attributes are present, parse them.
John McCall7f040a92010-12-24 02:08:15 +00001644 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001645
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001646 // Type-check the declaration itself.
John McCall60d7b3a2010-08-24 06:29:42 +00001647 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall7f040a92010-12-24 02:08:15 +00001648 DeclaratorInfo);
John McCall60d7b3a2010-08-24 06:29:42 +00001649 DeclOut = Dcl.get();
1650 ExprOut = ExprError();
Argyrios Kyrtzidisa6eb5f82010-10-08 02:39:23 +00001651
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001652 // '=' assignment-expression
Richard Trieud6c7c672012-01-18 22:54:52 +00001653 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith0635aa72012-02-22 06:49:09 +00001654 bool CopyInitialization = isTokenEqualOrEqualTypo();
1655 if (CopyInitialization)
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001656 ConsumeToken();
Richard Smith0635aa72012-02-22 06:49:09 +00001657
1658 ExprResult InitExpr = ExprError();
Richard Smith80ad52f2013-01-02 11:42:31 +00001659 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith0635aa72012-02-22 06:49:09 +00001660 Diag(Tok.getLocation(),
1661 diag::warn_cxx98_compat_generalized_initializer_lists);
1662 InitExpr = ParseBraceInitializer();
1663 } else if (CopyInitialization) {
1664 InitExpr = ParseAssignmentExpression();
1665 } else if (Tok.is(tok::l_paren)) {
1666 // This was probably an attempt to initialize the variable.
1667 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataev8fe24752013-11-18 08:17:37 +00001668 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith0635aa72012-02-22 06:49:09 +00001669 RParen = ConsumeParen();
1670 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1671 diag::err_expected_init_in_condition_lparen)
1672 << SourceRange(LParen, RParen);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001673 } else {
Richard Smith0635aa72012-02-22 06:49:09 +00001674 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1675 diag::err_expected_init_in_condition);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001676 }
Richard Smith0635aa72012-02-22 06:49:09 +00001677
1678 if (!InitExpr.isInvalid())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001679 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization,
Richard Smitha2c36462013-04-26 16:15:35 +00001680 DS.containsPlaceholderType());
Richard Smithdc7a4f52013-04-30 13:56:41 +00001681 else
1682 Actions.ActOnInitializerError(DeclOut);
Richard Smith0635aa72012-02-22 06:49:09 +00001683
Douglas Gregor586596f2010-05-06 17:25:47 +00001684 // FIXME: Build a reference to this declaration? Convert it to bool?
1685 // (This is currently handled by Sema).
Richard Smith483b9f32011-02-21 20:05:19 +00001686
1687 Actions.FinalizeDeclaration(DeclOut);
Douglas Gregor586596f2010-05-06 17:25:47 +00001688
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001689 return false;
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001690}
1691
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001692/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1693/// This should only be called when the current token is known to be part of
1694/// simple-type-specifier.
1695///
1696/// simple-type-specifier:
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001697/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001698/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1699/// char
1700/// wchar_t
1701/// bool
1702/// short
1703/// int
1704/// long
1705/// signed
1706/// unsigned
1707/// float
1708/// double
1709/// void
1710/// [GNU] typeof-specifier
1711/// [C++0x] auto [TODO]
1712///
1713/// type-name:
1714/// class-name
1715/// enum-name
1716/// typedef-name
1717///
1718void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1719 DS.SetRangeStart(Tok.getLocation());
1720 const char *PrevSpec;
John McCallfec54012009-08-03 20:12:06 +00001721 unsigned DiagID;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001722 SourceLocation Loc = Tok.getLocation();
Stephen Hines651f13c2014-04-23 16:59:28 -07001723 const clang::PrintingPolicy &Policy =
1724 Actions.getASTContext().getPrintingPolicy();
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001726 switch (Tok.getKind()) {
Chris Lattner55a7cef2009-01-05 00:13:00 +00001727 case tok::identifier: // foo::bar
1728 case tok::coloncolon: // ::foo::bar
David Blaikieb219cfc2011-09-23 05:06:16 +00001729 llvm_unreachable("Annotation token should already be formed!");
Mike Stump1eb44332009-09-09 15:08:12 +00001730 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00001731 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner55a7cef2009-01-05 00:13:00 +00001732
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001733 // type-name
Chris Lattnerb31757b2009-01-06 05:06:21 +00001734 case tok::annot_typename: {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001735 if (getTypeAnnotation(Tok))
1736 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
Stephen Hines651f13c2014-04-23 16:59:28 -07001737 getTypeAnnotation(Tok), Policy);
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001738 else
1739 DS.SetTypeSpecError();
Douglas Gregor9bd1d8d2010-10-21 23:17:00 +00001740
1741 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1742 ConsumeToken();
1743
1744 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1745 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1746 // Objective-C interface. If we don't have Objective-C or a '<', this is
1747 // just a normal reference to a typedef name.
David Blaikie4e4d0842012-03-11 07:00:24 +00001748 if (Tok.is(tok::less) && getLangOpts().ObjC1)
Douglas Gregor9bd1d8d2010-10-21 23:17:00 +00001749 ParseObjCProtocolQualifiers(DS);
1750
Stephen Hines651f13c2014-04-23 16:59:28 -07001751 DS.Finish(Diags, PP, Policy);
Douglas Gregor9bd1d8d2010-10-21 23:17:00 +00001752 return;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001753 }
Mike Stump1eb44332009-09-09 15:08:12 +00001754
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001755 // builtin types
1756 case tok::kw_short:
Stephen Hines651f13c2014-04-23 16:59:28 -07001757 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001758 break;
1759 case tok::kw_long:
Stephen Hines651f13c2014-04-23 16:59:28 -07001760 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001761 break;
Francois Pichet338d7f72011-04-28 01:59:37 +00001762 case tok::kw___int64:
Stephen Hines651f13c2014-04-23 16:59:28 -07001763 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
Francois Pichet338d7f72011-04-28 01:59:37 +00001764 break;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001765 case tok::kw_signed:
John McCallfec54012009-08-03 20:12:06 +00001766 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001767 break;
1768 case tok::kw_unsigned:
John McCallfec54012009-08-03 20:12:06 +00001769 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001770 break;
1771 case tok::kw_void:
Stephen Hines651f13c2014-04-23 16:59:28 -07001772 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001773 break;
1774 case tok::kw_char:
Stephen Hines651f13c2014-04-23 16:59:28 -07001775 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001776 break;
1777 case tok::kw_int:
Stephen Hines651f13c2014-04-23 16:59:28 -07001778 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001779 break;
Richard Smith5a5a9712012-04-04 06:24:32 +00001780 case tok::kw___int128:
Stephen Hines651f13c2014-04-23 16:59:28 -07001781 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
Richard Smith5a5a9712012-04-04 06:24:32 +00001782 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001783 case tok::kw_half:
Stephen Hines651f13c2014-04-23 16:59:28 -07001784 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001785 break;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001786 case tok::kw_float:
Stephen Hines651f13c2014-04-23 16:59:28 -07001787 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001788 break;
1789 case tok::kw_double:
Stephen Hines651f13c2014-04-23 16:59:28 -07001790 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001791 break;
1792 case tok::kw_wchar_t:
Stephen Hines651f13c2014-04-23 16:59:28 -07001793 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001794 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001795 case tok::kw_char16_t:
Stephen Hines651f13c2014-04-23 16:59:28 -07001796 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001797 break;
1798 case tok::kw_char32_t:
Stephen Hines651f13c2014-04-23 16:59:28 -07001799 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001800 break;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001801 case tok::kw_bool:
Stephen Hines651f13c2014-04-23 16:59:28 -07001802 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001803 break;
David Blaikie5e089fe2012-01-24 05:47:35 +00001804 case tok::annot_decltype:
1805 case tok::kw_decltype:
1806 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
Stephen Hines651f13c2014-04-23 16:59:28 -07001807 return DS.Finish(Diags, PP, Policy);
Mike Stump1eb44332009-09-09 15:08:12 +00001808
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001809 // GNU typeof support.
1810 case tok::kw_typeof:
1811 ParseTypeofSpecifier(DS);
Stephen Hines651f13c2014-04-23 16:59:28 -07001812 DS.Finish(Diags, PP, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001813 return;
1814 }
Chris Lattnerb31757b2009-01-06 05:06:21 +00001815 if (Tok.is(tok::annot_typename))
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001816 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1817 else
1818 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001819 ConsumeToken();
Stephen Hines651f13c2014-04-23 16:59:28 -07001820 DS.Finish(Diags, PP, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001821}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001822
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001823/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1824/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1825/// e.g., "const short int". Note that the DeclSpec is *not* finished
1826/// by parsing the type-specifier-seq, because these sequences are
1827/// typically followed by some form of declarator. Returns true and
1828/// emits diagnostics if this is not a type-specifier-seq, false
1829/// otherwise.
1830///
1831/// type-specifier-seq: [C++ 8.1]
1832/// type-specifier type-specifier-seq[opt]
1833///
1834bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Richard Smith69730c12012-03-12 07:56:15 +00001835 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
Stephen Hines651f13c2014-04-23 16:59:28 -07001836 DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001837 return false;
1838}
1839
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001840/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1841/// some form.
1842///
1843/// This routine is invoked when a '<' is encountered after an identifier or
1844/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1845/// whether the unqualified-id is actually a template-id. This routine will
1846/// then parse the template arguments and form the appropriate template-id to
1847/// return to the caller.
1848///
1849/// \param SS the nested-name-specifier that precedes this template-id, if
1850/// we're actually parsing a qualified-id.
1851///
1852/// \param Name for constructor and destructor names, this is the actual
1853/// identifier that may be a template-name.
1854///
1855/// \param NameLoc the location of the class-name in a constructor or
1856/// destructor.
1857///
1858/// \param EnteringContext whether we're entering the scope of the
1859/// nested-name-specifier.
1860///
Douglas Gregor46df8cc2009-11-03 21:24:04 +00001861/// \param ObjectType if this unqualified-id occurs within a member access
1862/// expression, the type of the base object whose member is being accessed.
1863///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001864/// \param Id as input, describes the template-name or operator-function-id
1865/// that precedes the '<'. If template arguments were parsed successfully,
1866/// will be updated with the template-id.
1867///
Douglas Gregord4dca082010-02-24 18:44:31 +00001868/// \param AssumeTemplateId When true, this routine will assume that the name
1869/// refers to a template without performing name lookup to verify.
1870///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001871/// \returns true if a parse error occurred, false otherwise.
1872bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001873 SourceLocation TemplateKWLoc,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001874 IdentifierInfo *Name,
1875 SourceLocation NameLoc,
1876 bool EnteringContext,
John McCallb3d87482010-08-24 05:47:05 +00001877 ParsedType ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00001878 UnqualifiedId &Id,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001879 bool AssumeTemplateId) {
Douglas Gregor0278e122010-05-05 05:58:24 +00001880 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1881 "Expected '<' to finish parsing a template-id");
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001882
1883 TemplateTy Template;
1884 TemplateNameKind TNK = TNK_Non_template;
1885 switch (Id.getKind()) {
1886 case UnqualifiedId::IK_Identifier:
Douglas Gregor014e88d2009-11-03 23:16:33 +00001887 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunte6252d12009-11-28 08:58:14 +00001888 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregord4dca082010-02-24 18:44:31 +00001889 if (AssumeTemplateId) {
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001890 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001891 Id, ObjectType, EnteringContext,
1892 Template);
1893 if (TNK == TNK_Non_template)
1894 return true;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001895 } else {
1896 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001897 TNK = Actions.isTemplateName(getCurScope(), SS,
1898 TemplateKWLoc.isValid(), Id,
1899 ObjectType, EnteringContext, Template,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001900 MemberOfUnknownSpecialization);
1901
1902 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1903 ObjectType && IsTemplateArgumentList()) {
1904 // We have something like t->getAs<T>(), where getAs is a
1905 // member of an unknown specialization. However, this will only
1906 // parse correctly as a template, so suggest the keyword 'template'
1907 // before 'getAs' and treat this as a dependent template name.
1908 std::string Name;
1909 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1910 Name = Id.Identifier->getName();
1911 else {
1912 Name = "operator ";
1913 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1914 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1915 else
1916 Name += Id.Identifier->getName();
1917 }
1918 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1919 << Name
1920 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001921 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1922 SS, TemplateKWLoc, Id,
1923 ObjectType, EnteringContext,
1924 Template);
Douglas Gregord6ab2322010-06-16 23:00:59 +00001925 if (TNK == TNK_Non_template)
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001926 return true;
1927 }
1928 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001929 break;
1930
Douglas Gregor014e88d2009-11-03 23:16:33 +00001931 case UnqualifiedId::IK_ConstructorName: {
1932 UnqualifiedId TemplateName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001933 bool MemberOfUnknownSpecialization;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001934 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c153532010-08-06 12:11:11 +00001935 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1936 TemplateName, ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001937 EnteringContext, Template,
1938 MemberOfUnknownSpecialization);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001939 break;
1940 }
1941
Douglas Gregor014e88d2009-11-03 23:16:33 +00001942 case UnqualifiedId::IK_DestructorName: {
1943 UnqualifiedId TemplateName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001944 bool MemberOfUnknownSpecialization;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001945 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001946 if (ObjectType) {
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001947 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1948 SS, TemplateKWLoc, TemplateName,
1949 ObjectType, EnteringContext,
1950 Template);
Douglas Gregord6ab2322010-06-16 23:00:59 +00001951 if (TNK == TNK_Non_template)
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001952 return true;
1953 } else {
Abramo Bagnara7c153532010-08-06 12:11:11 +00001954 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1955 TemplateName, ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001956 EnteringContext, Template,
1957 MemberOfUnknownSpecialization);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001958
John McCallb3d87482010-08-24 05:47:05 +00001959 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregor124b8782010-02-16 19:09:40 +00001960 Diag(NameLoc, diag::err_destructor_template_id)
1961 << Name << SS.getRange();
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001962 return true;
1963 }
1964 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001965 break;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001966 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001967
1968 default:
1969 return false;
1970 }
1971
1972 if (TNK == TNK_Non_template)
1973 return false;
1974
1975 // Parse the enclosed template argument list.
1976 SourceLocation LAngleLoc, RAngleLoc;
1977 TemplateArgList TemplateArgs;
Douglas Gregor0278e122010-05-05 05:58:24 +00001978 if (Tok.is(tok::less) &&
1979 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
Douglas Gregor059101f2011-03-02 00:47:37 +00001980 SS, true, LAngleLoc,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001981 TemplateArgs,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001982 RAngleLoc))
1983 return true;
1984
1985 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
Sean Hunte6252d12009-11-28 08:58:14 +00001986 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1987 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001988 // Form a parsed representation of the template-id to be stored in the
1989 // UnqualifiedId.
1990 TemplateIdAnnotation *TemplateId
Benjamin Kramer13bb7012012-04-14 12:14:03 +00001991 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001992
Stephen Hines651f13c2014-04-23 16:59:28 -07001993 // FIXME: Store name for literal operator too.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001994 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
1995 TemplateId->Name = Id.Identifier;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001996 TemplateId->Operator = OO_None;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001997 TemplateId->TemplateNameLoc = Id.StartLocation;
1998 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001999 TemplateId->Name = nullptr;
Douglas Gregor014e88d2009-11-03 23:16:33 +00002000 TemplateId->Operator = Id.OperatorFunctionId.Operator;
2001 TemplateId->TemplateNameLoc = Id.StartLocation;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002002 }
2003
Douglas Gregor059101f2011-03-02 00:47:37 +00002004 TemplateId->SS = SS;
Benjamin Kramer2b28bf12012-02-19 23:37:39 +00002005 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall2b5289b2010-08-23 07:28:44 +00002006 TemplateId->Template = Template;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002007 TemplateId->Kind = TNK;
2008 TemplateId->LAngleLoc = LAngleLoc;
2009 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregor314b97f2009-11-10 19:49:08 +00002010 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002011 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
Douglas Gregor314b97f2009-11-10 19:49:08 +00002012 Arg != ArgEnd; ++Arg)
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002013 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002014
2015 Id.setTemplateId(TemplateId);
2016 return false;
2017 }
2018
2019 // Bundle the template arguments together.
Benjamin Kramer5354e772012-08-23 23:38:35 +00002020 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002021
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002022 // Constructor and destructor names.
John McCallf312b1e2010-08-26 23:41:50 +00002023 TypeResult Type
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002024 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2025 Template, NameLoc,
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002026 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2027 /*IsCtorOrDtorName=*/true);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002028 if (Type.isInvalid())
2029 return true;
2030
2031 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2032 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2033 else
2034 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2035
2036 return false;
2037}
2038
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002039/// \brief Parse an operator-function-id or conversion-function-id as part
2040/// of a C++ unqualified-id.
2041///
2042/// This routine is responsible only for parsing the operator-function-id or
2043/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002044///
2045/// \code
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002046/// operator-function-id: [C++ 13.5]
2047/// 'operator' operator
2048///
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002049/// operator: one of
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002050/// new delete new[] delete[]
2051/// + - * / % ^ & | ~
2052/// ! = < > += -= *= /= %=
2053/// ^= &= |= << >> >>= <<= == !=
2054/// <= >= && || ++ -- , ->* ->
2055/// () []
2056///
2057/// conversion-function-id: [C++ 12.3.2]
2058/// operator conversion-type-id
2059///
2060/// conversion-type-id:
2061/// type-specifier-seq conversion-declarator[opt]
2062///
2063/// conversion-declarator:
2064/// ptr-operator conversion-declarator[opt]
2065/// \endcode
2066///
Dmitri Gribenko1ddbd892012-08-24 00:01:24 +00002067/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002068/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2069///
2070/// \param EnteringContext whether we are entering the scope of the
2071/// nested-name-specifier.
2072///
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002073/// \param ObjectType if this unqualified-id occurs within a member access
2074/// expression, the type of the base object whose member is being accessed.
2075///
2076/// \param Result on a successful parse, contains the parsed unqualified-id.
2077///
2078/// \returns true if parsing fails, false otherwise.
2079bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallb3d87482010-08-24 05:47:05 +00002080 ParsedType ObjectType,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002081 UnqualifiedId &Result) {
2082 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2083
2084 // Consume the 'operator' keyword.
2085 SourceLocation KeywordLoc = ConsumeToken();
2086
2087 // Determine what kind of operator name we have.
2088 unsigned SymbolIdx = 0;
2089 SourceLocation SymbolLocations[3];
2090 OverloadedOperatorKind Op = OO_None;
2091 switch (Tok.getKind()) {
2092 case tok::kw_new:
2093 case tok::kw_delete: {
2094 bool isNew = Tok.getKind() == tok::kw_new;
2095 // Consume the 'new' or 'delete'.
2096 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith6ee326a2012-04-10 01:32:12 +00002097 // Check for array new/delete.
2098 if (Tok.is(tok::l_square) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00002099 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002100 // Consume the '[' and ']'.
2101 BalancedDelimiterTracker T(*this, tok::l_square);
2102 T.consumeOpen();
2103 T.consumeClose();
2104 if (T.getCloseLocation().isInvalid())
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002105 return true;
2106
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002107 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2108 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002109 Op = isNew? OO_Array_New : OO_Array_Delete;
2110 } else {
2111 Op = isNew? OO_New : OO_Delete;
2112 }
2113 break;
2114 }
2115
2116#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2117 case tok::Token: \
2118 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2119 Op = OO_##Name; \
2120 break;
2121#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2122#include "clang/Basic/OperatorKinds.def"
2123
2124 case tok::l_paren: {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002125 // Consume the '(' and ')'.
2126 BalancedDelimiterTracker T(*this, tok::l_paren);
2127 T.consumeOpen();
2128 T.consumeClose();
2129 if (T.getCloseLocation().isInvalid())
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002130 return true;
2131
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002132 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2133 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002134 Op = OO_Call;
2135 break;
2136 }
2137
2138 case tok::l_square: {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002139 // Consume the '[' and ']'.
2140 BalancedDelimiterTracker T(*this, tok::l_square);
2141 T.consumeOpen();
2142 T.consumeClose();
2143 if (T.getCloseLocation().isInvalid())
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002144 return true;
2145
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002146 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2147 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002148 Op = OO_Subscript;
2149 break;
2150 }
2151
2152 case tok::code_completion: {
2153 // Code completion for the operator name.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002154 Actions.CodeCompleteOperatorName(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002155 cutOffParsing();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002156 // Don't try to parse any further.
2157 return true;
2158 }
2159
2160 default:
2161 break;
2162 }
2163
2164 if (Op != OO_None) {
2165 // We have parsed an operator-function-id.
2166 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2167 return false;
2168 }
Sean Hunt0486d742009-11-28 04:44:28 +00002169
2170 // Parse a literal-operator-id.
2171 //
Richard Smithaa9a8ce2012-10-20 08:41:10 +00002172 // literal-operator-id: C++11 [over.literal]
2173 // operator string-literal identifier
2174 // operator user-defined-string-literal
Sean Hunt0486d742009-11-28 04:44:28 +00002175
Richard Smith80ad52f2013-01-02 11:42:31 +00002176 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith7fe62082011-10-15 05:09:34 +00002177 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Sean Hunt0486d742009-11-28 04:44:28 +00002178
Richard Smith33762772012-03-08 23:06:02 +00002179 SourceLocation DiagLoc;
2180 unsigned DiagId = 0;
2181
2182 // We're past translation phase 6, so perform string literal concatenation
2183 // before checking for "".
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002184 SmallVector<Token, 4> Toks;
2185 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith33762772012-03-08 23:06:02 +00002186 while (isTokenStringLiteral()) {
2187 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smithaa9a8ce2012-10-20 08:41:10 +00002188 // C++11 [over.literal]p1:
2189 // The string-literal or user-defined-string-literal in a
2190 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith33762772012-03-08 23:06:02 +00002191 DiagLoc = Tok.getLocation();
2192 DiagId = diag::err_literal_operator_string_prefix;
2193 }
2194 Toks.push_back(Tok);
2195 TokLocs.push_back(ConsumeStringToken());
2196 }
2197
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002198 StringLiteralParser Literal(Toks, PP);
Richard Smith33762772012-03-08 23:06:02 +00002199 if (Literal.hadError)
2200 return true;
2201
2202 // Grab the literal operator's suffix, which will be either the next token
2203 // or a ud-suffix from the string literal.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002204 IdentifierInfo *II = nullptr;
Richard Smith33762772012-03-08 23:06:02 +00002205 SourceLocation SuffixLoc;
2206 if (!Literal.getUDSuffix().empty()) {
2207 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2208 SuffixLoc =
2209 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2210 Literal.getUDSuffixOffset(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002211 PP.getSourceManager(), getLangOpts());
Richard Smith33762772012-03-08 23:06:02 +00002212 } else if (Tok.is(tok::identifier)) {
2213 II = Tok.getIdentifierInfo();
2214 SuffixLoc = ConsumeToken();
2215 TokLocs.push_back(SuffixLoc);
2216 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -07002217 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Sean Hunt0486d742009-11-28 04:44:28 +00002218 return true;
2219 }
2220
Richard Smith33762772012-03-08 23:06:02 +00002221 // The string literal must be empty.
2222 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smithaa9a8ce2012-10-20 08:41:10 +00002223 // C++11 [over.literal]p1:
2224 // The string-literal or user-defined-string-literal in a
2225 // literal-operator-id shall [...] contain no characters
2226 // other than the implicit terminating '\0'.
Richard Smith33762772012-03-08 23:06:02 +00002227 DiagLoc = TokLocs.front();
2228 DiagId = diag::err_literal_operator_string_not_empty;
2229 }
2230
2231 if (DiagId) {
2232 // This isn't a valid literal-operator-id, but we think we know
2233 // what the user meant. Tell them what they should have written.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002234 SmallString<32> Str;
Richard Smith33762772012-03-08 23:06:02 +00002235 Str += "\"\" ";
2236 Str += II->getName();
2237 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2238 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2239 }
2240
2241 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Stephen Hines651f13c2014-04-23 16:59:28 -07002242
2243 return Actions.checkLiteralOperatorId(SS, Result);
Sean Hunt0486d742009-11-28 04:44:28 +00002244 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002245
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002246 // Parse a conversion-function-id.
2247 //
2248 // conversion-function-id: [C++ 12.3.2]
2249 // operator conversion-type-id
2250 //
2251 // conversion-type-id:
2252 // type-specifier-seq conversion-declarator[opt]
2253 //
2254 // conversion-declarator:
2255 // ptr-operator conversion-declarator[opt]
2256
2257 // Parse the type-specifier-seq.
John McCall0b7e6782011-03-24 11:26:52 +00002258 DeclSpec DS(AttrFactory);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +00002259 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002260 return true;
2261
2262 // Parse the conversion-declarator, which is merely a sequence of
2263 // ptr-operators.
Richard Smith14f78f42013-05-04 01:26:46 +00002264 Declarator D(DS, Declarator::ConversionIdContext);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002265 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2266
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002267 // Finish up the type.
John McCallf312b1e2010-08-26 23:41:50 +00002268 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002269 if (Ty.isInvalid())
2270 return true;
2271
2272 // Note that this is a conversion-function-id.
2273 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2274 D.getSourceRange().getEnd());
2275 return false;
2276}
2277
2278/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2279/// name of an entity.
2280///
2281/// \code
2282/// unqualified-id: [C++ expr.prim.general]
2283/// identifier
2284/// operator-function-id
2285/// conversion-function-id
2286/// [C++0x] literal-operator-id [TODO]
2287/// ~ class-name
2288/// template-id
2289///
2290/// \endcode
2291///
Dmitri Gribenko1ddbd892012-08-24 00:01:24 +00002292/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002293/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2294///
2295/// \param EnteringContext whether we are entering the scope of the
2296/// nested-name-specifier.
2297///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002298/// \param AllowDestructorName whether we allow parsing of a destructor name.
2299///
2300/// \param AllowConstructorName whether we allow parsing a constructor name.
2301///
Douglas Gregor46df8cc2009-11-03 21:24:04 +00002302/// \param ObjectType if this unqualified-id occurs within a member access
2303/// expression, the type of the base object whose member is being accessed.
2304///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002305/// \param Result on a successful parse, contains the parsed unqualified-id.
2306///
2307/// \returns true if parsing fails, false otherwise.
2308bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2309 bool AllowDestructorName,
2310 bool AllowConstructorName,
John McCallb3d87482010-08-24 05:47:05 +00002311 ParsedType ObjectType,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002312 SourceLocation& TemplateKWLoc,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002313 UnqualifiedId &Result) {
Douglas Gregor0278e122010-05-05 05:58:24 +00002314
2315 // Handle 'A::template B'. This is for template-ids which have not
2316 // already been annotated by ParseOptionalCXXScopeSpecifier().
2317 bool TemplateSpecified = false;
David Blaikie4e4d0842012-03-11 07:00:24 +00002318 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
Douglas Gregor0278e122010-05-05 05:58:24 +00002319 (ObjectType || SS.isSet())) {
2320 TemplateSpecified = true;
2321 TemplateKWLoc = ConsumeToken();
2322 }
2323
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002324 // unqualified-id:
2325 // identifier
2326 // template-id (when it hasn't already been annotated)
2327 if (Tok.is(tok::identifier)) {
2328 // Consume the identifier.
2329 IdentifierInfo *Id = Tok.getIdentifierInfo();
2330 SourceLocation IdLoc = ConsumeToken();
2331
David Blaikie4e4d0842012-03-11 07:00:24 +00002332 if (!getLangOpts().CPlusPlus) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +00002333 // If we're not in C++, only identifiers matter. Record the
2334 // identifier and return.
2335 Result.setIdentifier(Id, IdLoc);
2336 return false;
2337 }
2338
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002339 if (AllowConstructorName &&
Douglas Gregor23c94db2010-07-02 17:43:08 +00002340 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002341 // We have parsed a constructor name.
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002342 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2343 &SS, false, false,
2344 ParsedType(),
2345 /*IsCtorOrDtorName=*/true,
2346 /*NonTrivialTypeSourceInfo=*/true);
2347 Result.setConstructorName(Ty, IdLoc, IdLoc);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002348 } else {
2349 // We have parsed an identifier.
2350 Result.setIdentifier(Id, IdLoc);
2351 }
2352
2353 // If the next token is a '<', we may have a template.
Douglas Gregor0278e122010-05-05 05:58:24 +00002354 if (TemplateSpecified || Tok.is(tok::less))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002355 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2356 EnteringContext, ObjectType,
2357 Result, TemplateSpecified);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002358
2359 return false;
2360 }
2361
2362 // unqualified-id:
2363 // template-id (already parsed and annotated)
2364 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +00002365 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002366
2367 // If the template-name names the current class, then this is a constructor
2368 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor23c94db2010-07-02 17:43:08 +00002369 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002370 if (SS.isSet()) {
2371 // C++ [class.qual]p2 specifies that a qualified template-name
2372 // is taken as the constructor name where a constructor can be
2373 // declared. Thus, the template arguments are extraneous, so
2374 // complain about them and remove them entirely.
2375 Diag(TemplateId->TemplateNameLoc,
2376 diag::err_out_of_line_constructor_template_id)
2377 << TemplateId->Name
Douglas Gregor849b2432010-03-31 17:46:05 +00002378 << FixItHint::CreateRemoval(
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002379 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002380 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2381 TemplateId->TemplateNameLoc,
2382 getCurScope(),
2383 &SS, false, false,
2384 ParsedType(),
2385 /*IsCtorOrDtorName=*/true,
2386 /*NontrivialTypeSourceInfo=*/true);
2387 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002388 TemplateId->RAngleLoc);
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002389 ConsumeToken();
2390 return false;
2391 }
2392
2393 Result.setConstructorTemplateId(TemplateId);
2394 ConsumeToken();
2395 return false;
2396 }
2397
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002398 // We have already parsed a template-id; consume the annotation token as
2399 // our unqualified-id.
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002400 Result.setTemplateId(TemplateId);
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002401 TemplateKWLoc = TemplateId->TemplateKWLoc;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002402 ConsumeToken();
2403 return false;
2404 }
2405
2406 // unqualified-id:
2407 // operator-function-id
2408 // conversion-function-id
2409 if (Tok.is(tok::kw_operator)) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002410 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002411 return true;
2412
Sean Hunte6252d12009-11-28 08:58:14 +00002413 // If we have an operator-function-id or a literal-operator-id and the next
2414 // token is a '<', we may have a
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002415 //
2416 // template-id:
2417 // operator-function-id < template-argument-list[opt] >
Sean Hunte6252d12009-11-28 08:58:14 +00002418 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2419 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
Douglas Gregor0278e122010-05-05 05:58:24 +00002420 (TemplateSpecified || Tok.is(tok::less)))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002421 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002422 nullptr, SourceLocation(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002423 EnteringContext, ObjectType,
2424 Result, TemplateSpecified);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002425
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002426 return false;
2427 }
2428
David Blaikie4e4d0842012-03-11 07:00:24 +00002429 if (getLangOpts().CPlusPlus &&
Douglas Gregorb862b8f2010-01-11 23:29:10 +00002430 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002431 // C++ [expr.unary.op]p10:
2432 // There is an ambiguity in the unary-expression ~X(), where X is a
2433 // class-name. The ambiguity is resolved in favor of treating ~ as a
2434 // unary complement rather than treating ~X as referring to a destructor.
2435
2436 // Parse the '~'.
2437 SourceLocation TildeLoc = ConsumeToken();
David Blaikie53a75c02011-12-08 16:13:53 +00002438
2439 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2440 DeclSpec DS(AttrFactory);
2441 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2442 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2443 Result.setDestructorName(TildeLoc, Type, EndLoc);
2444 return false;
2445 }
2446 return true;
2447 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002448
2449 // Parse the class-name.
2450 if (Tok.isNot(tok::identifier)) {
Douglas Gregor124b8782010-02-16 19:09:40 +00002451 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002452 return true;
2453 }
2454
2455 // Parse the class-name (or template-name in a simple-template-id).
2456 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2457 SourceLocation ClassNameLoc = ConsumeToken();
2458
Douglas Gregor0278e122010-05-05 05:58:24 +00002459 if (TemplateSpecified || Tok.is(tok::less)) {
John McCallb3d87482010-08-24 05:47:05 +00002460 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002461 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2462 ClassName, ClassNameLoc,
2463 EnteringContext, ObjectType,
2464 Result, TemplateSpecified);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002465 }
2466
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002467 // Note that this is a destructor name.
John McCallb3d87482010-08-24 05:47:05 +00002468 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2469 ClassNameLoc, getCurScope(),
2470 SS, ObjectType,
2471 EnteringContext);
Douglas Gregor124b8782010-02-16 19:09:40 +00002472 if (!Ty)
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002473 return true;
Douglas Gregor124b8782010-02-16 19:09:40 +00002474
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002475 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002476 return false;
2477 }
2478
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002479 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikie4e4d0842012-03-11 07:00:24 +00002480 << getLangOpts().CPlusPlus;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002481 return true;
2482}
2483
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002484/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2485/// memory in a typesafe manner and call constructors.
Mike Stump1eb44332009-09-09 15:08:12 +00002486///
Chris Lattner59232d32009-01-04 21:25:24 +00002487/// This method is called to parse the new expression after the optional :: has
2488/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2489/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002490///
2491/// new-expression:
2492/// '::'[opt] 'new' new-placement[opt] new-type-id
2493/// new-initializer[opt]
2494/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2495/// new-initializer[opt]
2496///
2497/// new-placement:
2498/// '(' expression-list ')'
2499///
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002500/// new-type-id:
2501/// type-specifier-seq new-declarator[opt]
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002502/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002503///
2504/// new-declarator:
2505/// ptr-operator new-declarator[opt]
2506/// direct-new-declarator
2507///
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002508/// new-initializer:
2509/// '(' expression-list[opt] ')'
Sebastian Redldbef1bb2011-06-05 12:23:16 +00002510/// [C++0x] braced-init-list
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002511///
John McCall60d7b3a2010-08-24 06:29:42 +00002512ExprResult
Chris Lattner59232d32009-01-04 21:25:24 +00002513Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2514 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2515 ConsumeToken(); // Consume 'new'
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002516
2517 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2518 // second form of new-expression. It can't be a new-type-id.
2519
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00002520 ExprVector PlacementArgs;
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002521 SourceLocation PlacementLParen, PlacementRParen;
2522
Douglas Gregor4bd40312010-07-13 15:54:32 +00002523 SourceRange TypeIdParens;
John McCall0b7e6782011-03-24 11:26:52 +00002524 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00002525 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002526 if (Tok.is(tok::l_paren)) {
2527 // If it turns out to be a placement, we change the type location.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002528 BalancedDelimiterTracker T(*this, tok::l_paren);
2529 T.consumeOpen();
2530 PlacementLParen = T.getOpenLocation();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002531 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002532 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002533 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002534 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002535
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002536 T.consumeClose();
2537 PlacementRParen = T.getCloseLocation();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002538 if (PlacementRParen.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002539 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002540 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002541 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002542
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002543 if (PlacementArgs.empty()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002544 // Reset the placement locations. There was no placement.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002545 TypeIdParens = T.getRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002546 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002547 } else {
2548 // We still need the type.
2549 if (Tok.is(tok::l_paren)) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002550 BalancedDelimiterTracker T(*this, tok::l_paren);
2551 T.consumeOpen();
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002552 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002553 ParseSpecifierQualifierList(DS);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002554 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002555 ParseDeclarator(DeclaratorInfo);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002556 T.consumeClose();
2557 TypeIdParens = T.getRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002558 } else {
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002559 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002560 if (ParseCXXTypeSpecifierSeq(DS))
2561 DeclaratorInfo.setInvalidType(true);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002562 else {
2563 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002564 ParseDeclaratorInternal(DeclaratorInfo,
2565 &Parser::ParseDirectNewDeclarator);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002566 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002567 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002568 }
2569 } else {
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002570 // A new-type-id is a simplified type-id, where essentially the
2571 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002572 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002573 if (ParseCXXTypeSpecifierSeq(DS))
2574 DeclaratorInfo.setInvalidType(true);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002575 else {
2576 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002577 ParseDeclaratorInternal(DeclaratorInfo,
2578 &Parser::ParseDirectNewDeclarator);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002579 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002580 }
Chris Lattnereaaebc72009-04-25 08:06:05 +00002581 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002582 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002583 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002584 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002585
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002586 ExprResult Initializer;
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002587
2588 if (Tok.is(tok::l_paren)) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002589 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00002590 ExprVector ConstructorArgs;
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002591 BalancedDelimiterTracker T(*this, tok::l_paren);
2592 T.consumeOpen();
2593 ConstructorLParen = T.getOpenLocation();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002594 if (Tok.isNot(tok::r_paren)) {
2595 CommaLocsTy CommaLocs;
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002596 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002597 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002598 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002599 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002600 }
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002601 T.consumeClose();
2602 ConstructorRParen = T.getCloseLocation();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002603 if (ConstructorRParen.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002604 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002605 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002606 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002607 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2608 ConstructorRParen,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002609 ConstructorArgs);
Richard Smith80ad52f2013-01-02 11:42:31 +00002610 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith7fe62082011-10-15 05:09:34 +00002611 Diag(Tok.getLocation(),
2612 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002613 Initializer = ParseBraceInitializer();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002614 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002615 if (Initializer.isInvalid())
2616 return Initializer;
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002617
Sebastian Redlf53597f2009-03-15 17:47:39 +00002618 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002619 PlacementArgs, PlacementRParen,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002620 TypeIdParens, DeclaratorInfo, Initializer.get());
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002621}
2622
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002623/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2624/// passed to ParseDeclaratorInternal.
2625///
2626/// direct-new-declarator:
2627/// '[' expression ']'
2628/// direct-new-declarator '[' constant-expression ']'
2629///
Chris Lattner59232d32009-01-04 21:25:24 +00002630void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002631 // Parse the array dimensions.
2632 bool first = true;
2633 while (Tok.is(tok::l_square)) {
Richard Smith6ee326a2012-04-10 01:32:12 +00002634 // An array-size expression can't start with a lambda.
2635 if (CheckProhibitedCXX11Attribute())
2636 continue;
2637
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002638 BalancedDelimiterTracker T(*this, tok::l_square);
2639 T.consumeOpen();
2640
John McCall60d7b3a2010-08-24 06:29:42 +00002641 ExprResult Size(first ? ParseExpression()
Sebastian Redl2f7ece72008-12-11 21:36:32 +00002642 : ParseConstantExpression());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002643 if (Size.isInvalid()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002644 // Recover
Alexey Bataev8fe24752013-11-18 08:17:37 +00002645 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002646 return;
2647 }
2648 first = false;
2649
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002650 T.consumeClose();
John McCall0b7e6782011-03-24 11:26:52 +00002651
Bill Wendlingad017fa2012-12-20 19:22:21 +00002652 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith6ee326a2012-04-10 01:32:12 +00002653 ParsedAttributes Attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +00002654 MaybeParseCXX11Attributes(Attrs);
Richard Smith6ee326a2012-04-10 01:32:12 +00002655
John McCall0b7e6782011-03-24 11:26:52 +00002656 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall7f040a92010-12-24 02:08:15 +00002657 /*static=*/false, /*star=*/false,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002658 Size.get(),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002659 T.getOpenLocation(),
2660 T.getCloseLocation()),
Richard Smith6ee326a2012-04-10 01:32:12 +00002661 Attrs, T.getCloseLocation());
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002662
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002663 if (T.getCloseLocation().isInvalid())
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002664 return;
2665 }
2666}
2667
2668/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2669/// This ambiguity appears in the syntax of the C++ new operator.
2670///
2671/// new-expression:
2672/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2673/// new-initializer[opt]
2674///
2675/// new-placement:
2676/// '(' expression-list ')'
2677///
John McCallca0408f2010-08-23 06:44:23 +00002678bool Parser::ParseExpressionListOrTypeId(
Chris Lattner5f9e2722011-07-23 10:55:15 +00002679 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner59232d32009-01-04 21:25:24 +00002680 Declarator &D) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002681 // The '(' was already consumed.
2682 if (isTypeIdInParens()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002683 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlab197ba2009-02-09 18:23:29 +00002684 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002685 ParseDeclarator(D);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002686 return D.isInvalidType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002687 }
2688
2689 // It's not a type, it has to be an expression list.
2690 // Discard the comma locations - ActOnCXXNew has enough parameters.
2691 CommaLocsTy CommaLocs;
2692 return ParseExpressionList(PlacementArgs, CommaLocs);
2693}
2694
2695/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2696/// to free memory allocated by new.
2697///
Chris Lattner59232d32009-01-04 21:25:24 +00002698/// This method is called to parse the 'delete' expression after the optional
2699/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2700/// and "Start" is its location. Otherwise, "Start" is the location of the
2701/// 'delete' token.
2702///
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002703/// delete-expression:
2704/// '::'[opt] 'delete' cast-expression
2705/// '::'[opt] 'delete' '[' ']' cast-expression
John McCall60d7b3a2010-08-24 06:29:42 +00002706ExprResult
Chris Lattner59232d32009-01-04 21:25:24 +00002707Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2708 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2709 ConsumeToken(); // Consume 'delete'
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002710
2711 // Array delete?
2712 bool ArrayDelete = false;
Richard Smith6ee326a2012-04-10 01:32:12 +00002713 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith950435c2012-08-09 19:01:51 +00002714 // C++11 [expr.delete]p1:
2715 // Whenever the delete keyword is followed by empty square brackets, it
2716 // shall be interpreted as [array delete].
2717 // [Footnote: A lambda expression with a lambda-introducer that consists
2718 // of empty square brackets can follow the delete keyword if
2719 // the lambda expression is enclosed in parentheses.]
2720 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2721 // lambda-introducer.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002722 ArrayDelete = true;
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002723 BalancedDelimiterTracker T(*this, tok::l_square);
2724
2725 T.consumeOpen();
2726 T.consumeClose();
2727 if (T.getCloseLocation().isInvalid())
Sebastian Redl20df9b72008-12-11 22:51:44 +00002728 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002729 }
2730
John McCall60d7b3a2010-08-24 06:29:42 +00002731 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002732 if (Operand.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002733 return Operand;
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002734
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002735 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002736}
Sebastian Redl64b45f72009-01-05 20:52:13 +00002737
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002738static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2739 switch (kind) {
2740 default: llvm_unreachable("Not a known type trait");
Stephen Hines651f13c2014-04-23 16:59:28 -07002741#define TYPE_TRAIT_1(Spelling, Name, Key) \
2742case tok::kw_ ## Spelling: return UTT_ ## Name;
2743#define TYPE_TRAIT_2(Spelling, Name, Key) \
2744case tok::kw_ ## Spelling: return BTT_ ## Name;
2745#include "clang/Basic/TokenKinds.def"
2746#define TYPE_TRAIT_N(Spelling, Name, Key) \
2747 case tok::kw_ ## Spelling: return TT_ ## Name;
2748#include "clang/Basic/TokenKinds.def"
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002749 }
2750}
2751
John Wiegley21ff2e52011-04-28 00:16:57 +00002752static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2753 switch(kind) {
2754 default: llvm_unreachable("Not a known binary type trait");
2755 case tok::kw___array_rank: return ATT_ArrayRank;
2756 case tok::kw___array_extent: return ATT_ArrayExtent;
2757 }
2758}
2759
John Wiegley55262202011-04-25 06:54:41 +00002760static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2761 switch(kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002762 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegley55262202011-04-25 06:54:41 +00002763 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2764 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2765 }
2766}
2767
Stephen Hines651f13c2014-04-23 16:59:28 -07002768static unsigned TypeTraitArity(tok::TokenKind kind) {
2769 switch (kind) {
2770 default: llvm_unreachable("Not a known type trait");
2771#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2772#include "clang/Basic/TokenKinds.def"
Francois Pichet6ad6f282010-12-07 00:08:36 +00002773 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002774}
2775
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002776/// \brief Parse the built-in type-trait pseudo-functions that allow
2777/// implementation of the TR1/C++11 type traits templates.
2778///
2779/// primary-expression:
Stephen Hines651f13c2014-04-23 16:59:28 -07002780/// unary-type-trait '(' type-id ')'
2781/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002782/// type-trait '(' type-id-seq ')'
2783///
2784/// type-id-seq:
2785/// type-id ...[opt] type-id-seq[opt]
2786///
2787ExprResult Parser::ParseTypeTrait() {
Stephen Hines651f13c2014-04-23 16:59:28 -07002788 tok::TokenKind Kind = Tok.getKind();
2789 unsigned Arity = TypeTraitArity(Kind);
2790
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002791 SourceLocation Loc = ConsumeToken();
2792
2793 BalancedDelimiterTracker Parens(*this, tok::l_paren);
Stephen Hines651f13c2014-04-23 16:59:28 -07002794 if (Parens.expectAndConsume())
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002795 return ExprError();
2796
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002797 SmallVector<ParsedType, 2> Args;
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002798 do {
2799 // Parse the next type.
2800 TypeResult Ty = ParseTypeName();
2801 if (Ty.isInvalid()) {
2802 Parens.skipToEnd();
2803 return ExprError();
2804 }
2805
2806 // Parse the ellipsis, if present.
2807 if (Tok.is(tok::ellipsis)) {
2808 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2809 if (Ty.isInvalid()) {
2810 Parens.skipToEnd();
2811 return ExprError();
2812 }
2813 }
2814
2815 // Add this type to the list of arguments.
2816 Args.push_back(Ty.get());
Stephen Hines651f13c2014-04-23 16:59:28 -07002817 } while (TryConsumeToken(tok::comma));
2818
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002819 if (Parens.consumeClose())
2820 return ExprError();
Stephen Hines651f13c2014-04-23 16:59:28 -07002821
2822 SourceLocation EndLoc = Parens.getCloseLocation();
2823
2824 if (Arity && Args.size() != Arity) {
2825 Diag(EndLoc, diag::err_type_trait_arity)
2826 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
2827 return ExprError();
2828 }
2829
2830 if (!Arity && Args.empty()) {
2831 Diag(EndLoc, diag::err_type_trait_arity)
2832 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
2833 return ExprError();
2834 }
2835
2836 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002837}
2838
John Wiegley21ff2e52011-04-28 00:16:57 +00002839/// ParseArrayTypeTrait - Parse the built-in array type-trait
2840/// pseudo-functions.
2841///
2842/// primary-expression:
2843/// [Embarcadero] '__array_rank' '(' type-id ')'
2844/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2845///
2846ExprResult Parser::ParseArrayTypeTrait() {
2847 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2848 SourceLocation Loc = ConsumeToken();
2849
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002850 BalancedDelimiterTracker T(*this, tok::l_paren);
Stephen Hines651f13c2014-04-23 16:59:28 -07002851 if (T.expectAndConsume())
John Wiegley21ff2e52011-04-28 00:16:57 +00002852 return ExprError();
2853
2854 TypeResult Ty = ParseTypeName();
2855 if (Ty.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002856 SkipUntil(tok::comma, StopAtSemi);
2857 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley21ff2e52011-04-28 00:16:57 +00002858 return ExprError();
2859 }
2860
2861 switch (ATT) {
2862 case ATT_ArrayRank: {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002863 T.consumeClose();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002864 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002865 T.getCloseLocation());
John Wiegley21ff2e52011-04-28 00:16:57 +00002866 }
2867 case ATT_ArrayExtent: {
Stephen Hines651f13c2014-04-23 16:59:28 -07002868 if (ExpectAndConsume(tok::comma)) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002869 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley21ff2e52011-04-28 00:16:57 +00002870 return ExprError();
2871 }
2872
2873 ExprResult DimExpr = ParseExpression();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002874 T.consumeClose();
John Wiegley21ff2e52011-04-28 00:16:57 +00002875
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002876 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2877 T.getCloseLocation());
John Wiegley21ff2e52011-04-28 00:16:57 +00002878 }
John Wiegley21ff2e52011-04-28 00:16:57 +00002879 }
David Blaikie30263482012-01-20 21:50:17 +00002880 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley21ff2e52011-04-28 00:16:57 +00002881}
2882
John Wiegley55262202011-04-25 06:54:41 +00002883/// ParseExpressionTrait - Parse built-in expression-trait
2884/// pseudo-functions like __is_lvalue_expr( xxx ).
2885///
2886/// primary-expression:
2887/// [Embarcadero] expression-trait '(' expression ')'
2888///
2889ExprResult Parser::ParseExpressionTrait() {
2890 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2891 SourceLocation Loc = ConsumeToken();
2892
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002893 BalancedDelimiterTracker T(*this, tok::l_paren);
Stephen Hines651f13c2014-04-23 16:59:28 -07002894 if (T.expectAndConsume())
John Wiegley55262202011-04-25 06:54:41 +00002895 return ExprError();
2896
2897 ExprResult Expr = ParseExpression();
2898
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002899 T.consumeClose();
John Wiegley55262202011-04-25 06:54:41 +00002900
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002901 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2902 T.getCloseLocation());
John Wiegley55262202011-04-25 06:54:41 +00002903}
2904
2905
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002906/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2907/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2908/// based on the context past the parens.
John McCall60d7b3a2010-08-24 06:29:42 +00002909ExprResult
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002910Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallb3d87482010-08-24 05:47:05 +00002911 ParsedType &CastTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002912 BalancedDelimiterTracker &Tracker,
2913 ColonProtectionRAIIObject &ColonProt) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002914 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002915 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2916 assert(isTypeIdInParens() && "Not a type-id!");
2917
John McCall60d7b3a2010-08-24 06:29:42 +00002918 ExprResult Result(true);
John McCallb3d87482010-08-24 05:47:05 +00002919 CastTy = ParsedType();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002920
2921 // We need to disambiguate a very ugly part of the C++ syntax:
2922 //
2923 // (T())x; - type-id
2924 // (T())*x; - type-id
2925 // (T())/x; - expression
2926 // (T()); - expression
2927 //
2928 // The bad news is that we cannot use the specialized tentative parser, since
2929 // it can only verify that the thing inside the parens can be parsed as
2930 // type-id, it is not useful for determining the context past the parens.
2931 //
2932 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidisa558a892009-05-22 15:12:46 +00002933 // making any unnecessary Action calls.
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002934 //
2935 // It uses a scheme similar to parsing inline methods. The parenthesized
2936 // tokens are cached, the context that follows is determined (possibly by
2937 // parsing a cast-expression), and then we re-introduce the cached tokens
2938 // into the token stream and parse them appropriately.
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002939
Mike Stump1eb44332009-09-09 15:08:12 +00002940 ParenParseOption ParseAs;
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002941 CachedTokens Toks;
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002942
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002943 // Store the tokens of the parentheses. We will parse them after we determine
2944 // the context that follows them.
Argyrios Kyrtzidis14b91622010-04-23 21:20:12 +00002945 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002946 // We didn't find the ')' we expected.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002947 Tracker.consumeClose();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002948 return ExprError();
2949 }
2950
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002951 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002952 ParseAs = CompoundLiteral;
2953 } else {
2954 bool NotCastExpr;
Eli Friedmanb53f08a2009-05-25 19:41:42 +00002955 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
2956 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
2957 NotCastExpr = true;
2958 } else {
2959 // Try parsing the cast-expression that may follow.
2960 // If it is not a cast-expression, NotCastExpr will be true and no token
2961 // will be consumed.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002962 ColonProt.restore();
Eli Friedmanb53f08a2009-05-25 19:41:42 +00002963 Result = ParseCastExpression(false/*isUnaryExpression*/,
2964 false/*isAddressofOperand*/,
John McCallb3d87482010-08-24 05:47:05 +00002965 NotCastExpr,
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00002966 // type-id has priority.
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00002967 IsTypeCast);
Eli Friedmanb53f08a2009-05-25 19:41:42 +00002968 }
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002969
2970 // If we parsed a cast-expression, it's really a type-id, otherwise it's
2971 // an expression.
2972 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002973 }
2974
Mike Stump1eb44332009-09-09 15:08:12 +00002975 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002976 Toks.push_back(Tok);
2977 // Re-enter the stored parenthesized tokens into the token stream, so we may
2978 // parse them now.
2979 PP.EnterTokenStream(Toks.data(), Toks.size(),
2980 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
2981 // Drop the current token and bring the first cached one. It's the same token
2982 // as when we entered this function.
2983 ConsumeAnyToken();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002984
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002985 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00002986 // Parse the type declarator.
2987 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00002988 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002989 {
2990 ColonProtectionRAIIObject InnerColonProtection(*this);
2991 ParseSpecifierQualifierList(DS);
2992 ParseDeclarator(DeclaratorInfo);
2993 }
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002994
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002995 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002996 Tracker.consumeClose();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002997 ColonProt.restore();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002998
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002999 if (ParseAs == CompoundLiteral) {
3000 ExprType = CompoundLiteral;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003001 if (DeclaratorInfo.isInvalidType())
3002 return ExprError();
3003
3004 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3005 return ParseCompoundLiteralExpression(Ty.get(),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003006 Tracker.getOpenLocation(),
3007 Tracker.getCloseLocation());
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003008 }
Mike Stump1eb44332009-09-09 15:08:12 +00003009
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003010 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3011 assert(ParseAs == CastExpr);
3012
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00003013 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003014 return ExprError();
3015
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003016 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003017 if (!Result.isInvalid())
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003018 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3019 DeclaratorInfo, CastTy,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003020 Tracker.getCloseLocation(), Result.get());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003021 return Result;
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003022 }
Mike Stump1eb44332009-09-09 15:08:12 +00003023
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003024 // Not a compound literal, and not followed by a cast-expression.
3025 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003026
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003027 ExprType = SimpleExpr;
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003028 Result = ParseExpression();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003029 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003030 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003031 Tok.getLocation(), Result.get());
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003032
3033 // Match the ')'.
3034 if (Result.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00003035 SkipUntil(tok::r_paren, StopAtSemi);
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003036 return ExprError();
3037 }
Mike Stump1eb44332009-09-09 15:08:12 +00003038
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003039 Tracker.consumeClose();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003040 return Result;
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003041}