blob: 422b486c7b2d93f8f177f194a31552b898bda7b8 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expression parsing implementation for C++.
11//
12//===----------------------------------------------------------------------===//
Erik Verbruggen888d52a2014-01-15 09:15:43 +000013#include "clang/AST/ASTContext.h"
Douglas Gregor94a32472011-01-11 00:33:19 +000014#include "RAIIObjectsForParser.h"
Chandler Carruth757fcd62014-03-04 10:05:20 +000015#include "clang/AST/DeclTemplate.h"
Eli Friedmanc7c97142012-01-04 02:40:39 +000016#include "clang/Basic/PrettyStackTrace.h"
Richard Smith7d182a72012-03-08 23:06:02 +000017#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Parse/ParseDiagnostic.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000019#include "clang/Parse/Parser.h"
John McCall8b0666c2010-08-20 18:27:03 +000020#include "clang/Sema/DeclSpec.h"
21#include "clang/Sema/ParsedTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Sema/Scope.h"
Douglas Gregor7861a802009-11-03 01:35:08 +000023#include "llvm/Support/ErrorHandling.h"
24
Faisal Vali2b391ab2013-09-26 19:54:12 +000025
Chris Lattner29375652006-12-04 18:06:35 +000026using namespace clang;
27
Alp Tokerf990cef2014-01-07 02:35:33 +000028static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
29 switch (Kind) {
30 // template name
31 case tok::unknown: return 0;
32 // casts
33 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:
38 llvm_unreachable("Unknown type for digraph error message.");
39 }
40}
41
Richard Smith55858492011-04-14 21:45:45 +000042// Are the two tokens adjacent in the same source file?
Richard Smith7b3f3222012-06-18 06:11:04 +000043bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
Richard Smith55858492011-04-14 21:45:45 +000044 SourceManager &SM = PP.getSourceManager();
45 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000046 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
Richard Smith55858492011-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)
Alp Tokerf990cef2014-01-07 02:35:33 +000062 << SelectDigraphErrorMessage(Kind)
63 << FixItHint::CreateReplacement(Range, "< ::");
Richard Smith55858492011-04-14 21:45:45 +000064
65 // Update token information to reflect their change in token type.
66 ColonToken.setKind(tok::coloncolon);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000067 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
Richard Smith55858492011-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 Trieu01fc0012011-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 Trieu02e25db2011-09-20 20:03:50 +000083 if (!Next.is(tok::l_square) || Next.getLength() != 2)
Richard Trieu01fc0012011-09-19 19:01:00 +000084 return;
85
86 Token SecondToken = GetLookAheadToken(2);
Richard Smith7b3f3222012-06-18 06:11:04 +000087 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
Richard Trieu01fc0012011-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
Alp Tokerf990cef2014-01-07 02:35:33 +000099 FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
100 /*AtDigraph*/false);
Richard Trieu01fc0012011-09-19 19:01:00 +0000101}
102
Richard Trieu1f3ea7b2012-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 Weber6be9b252012-11-29 05:29:23 +0000106/// stream by removing the '(', and the matching ')' if found.
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000107void Parser::CheckForLParenAfterColonColon() {
108 if (!Tok.is(tok::l_paren))
109 return;
110
David Majnemer6ca445e2014-12-17 01:39:22 +0000111 Token LParen = Tok;
112 Token NextTok = GetLookAheadToken(1);
113 Token StarTok = NextTok;
114 // Check for (identifier or (*identifier
115 Token IdentifierTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : StarTok;
116 if (IdentifierTok.isNot(tok::identifier))
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000117 return;
David Majnemer6ca445e2014-12-17 01:39:22 +0000118 // Eat the '('.
119 ConsumeParen();
120 Token RParen;
121 // Do we have a ')' ?
122 NextTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : GetLookAheadToken(1);
123 if (NextTok.is(tok::r_paren)) {
124 RParen = NextTok;
125 // Eat the '*' if it is present.
126 if (StarTok.is(tok::star))
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000127 ConsumeToken();
David Majnemer6ca445e2014-12-17 01:39:22 +0000128 // Eat the identifier.
129 ConsumeToken();
130 // Add the identifier token back.
131 PP.EnterToken(IdentifierTok);
132 // Add the '*' back if it was present.
133 if (StarTok.is(tok::star))
134 PP.EnterToken(StarTok);
135 // Eat the ')'.
136 ConsumeParen();
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000137 }
138
David Majnemer6ca445e2014-12-17 01:39:22 +0000139 Diag(LParen.getLocation(), diag::err_paren_after_colon_colon)
140 << FixItHint::CreateRemoval(LParen.getLocation())
141 << FixItHint::CreateRemoval(RParen.getLocation());
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000142}
143
Mike Stump11289f42009-09-09 15:08:12 +0000144/// \brief Parse global scope or nested-name-specifier if present.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000145///
146/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
Mike Stump11289f42009-09-09 15:08:12 +0000147/// may be preceded by '::'). Note that this routine will not parse ::new or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000148/// ::delete; it will just leave them in the token stream.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000149///
150/// '::'[opt] nested-name-specifier
151/// '::'
152///
153/// nested-name-specifier:
154/// type-name '::'
155/// namespace-name '::'
156/// nested-name-specifier identifier '::'
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000157/// nested-name-specifier 'template'[opt] simple-template-id '::'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000158///
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000159///
Mike Stump11289f42009-09-09 15:08:12 +0000160/// \param SS the scope specifier that will be set to the parsed
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000161/// nested-name-specifier (or empty)
162///
Mike Stump11289f42009-09-09 15:08:12 +0000163/// \param ObjectType if this nested-name-specifier is being parsed following
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000164/// the "." or "->" of a member access expression, this parameter provides the
165/// type of the object whose members are being accessed.
166///
167/// \param EnteringContext whether we will be entering into the context of
168/// the nested-name-specifier after parsing it.
169///
Douglas Gregore610ada2010-02-24 18:44:31 +0000170/// \param MayBePseudoDestructor When non-NULL, points to a flag that
171/// indicates whether this nested-name-specifier may be part of a
172/// pseudo-destructor name. In this case, the flag will be set false
173/// if we don't actually end up parsing a destructor name. Moreorover,
174/// if we do end up determining that we are parsing a destructor name,
175/// the last component of the nested-name-specifier is not parsed as
176/// part of the scope specifier.
Richard Smith7447af42013-03-26 01:15:19 +0000177///
178/// \param IsTypename If \c true, this nested-name-specifier is known to be
179/// part of a type name. This is used to improve error recovery.
180///
181/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
182/// filled in with the leading identifier in the last component of the
183/// nested-name-specifier, if any.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000184///
John McCall1f476a12010-02-26 08:45:28 +0000185/// \returns true if there was an error parsing a scope specifier
Douglas Gregore861bac2009-08-25 22:51:20 +0000186bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +0000187 ParsedType ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000188 bool EnteringContext,
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000189 bool *MayBePseudoDestructor,
Richard Smith7447af42013-03-26 01:15:19 +0000190 bool IsTypename,
191 IdentifierInfo **LastII) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000192 assert(getLangOpts().CPlusPlus &&
Chris Lattnerb5134c02009-01-05 01:24:05 +0000193 "Call sites of this function should be guarded by checking for C++");
Mike Stump11289f42009-09-09 15:08:12 +0000194
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000195 if (Tok.is(tok::annot_cxxscope)) {
Richard Smith7447af42013-03-26 01:15:19 +0000196 assert(!LastII && "want last identifier but have already annotated scope");
Douglas Gregor869ad452011-02-24 17:54:50 +0000197 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
198 Tok.getAnnotationRange(),
199 SS);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000200 ConsumeToken();
John McCall1f476a12010-02-26 08:45:28 +0000201 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000202 }
Chris Lattnerf9b2cd42009-01-04 21:14:15 +0000203
Larisse Voufob959c3c2013-08-06 05:49:26 +0000204 if (Tok.is(tok::annot_template_id)) {
205 // If the current token is an annotated template id, it may already have
206 // a scope specifier. Restore it.
207 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
208 SS = TemplateId->SS;
209 }
210
Richard Smith7447af42013-03-26 01:15:19 +0000211 if (LastII)
Craig Topper161e4db2014-05-21 06:02:52 +0000212 *LastII = nullptr;
Richard Smith7447af42013-03-26 01:15:19 +0000213
Douglas Gregor7f741122009-02-25 19:37:18 +0000214 bool HasScopeSpecifier = false;
215
Chris Lattner8a7d10d2009-01-05 03:55:46 +0000216 if (Tok.is(tok::coloncolon)) {
217 // ::new and ::delete aren't nested-name-specifiers.
218 tok::TokenKind NextKind = NextToken().getKind();
219 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
220 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000221
David Majnemere8fb28f2014-12-29 19:19:18 +0000222 if (NextKind == tok::l_brace) {
223 // It is invalid to have :: {, consume the scope qualifier and pretend
224 // like we never saw it.
225 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
226 } else {
227 // '::' - Global scope qualifier.
228 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
229 return true;
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000230
David Majnemere8fb28f2014-12-29 19:19:18 +0000231 CheckForLParenAfterColonColon();
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000232
David Majnemere8fb28f2014-12-29 19:19:18 +0000233 HasScopeSpecifier = true;
234 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000235 }
236
Nikola Smiljanic67860242014-09-26 00:28:20 +0000237 if (Tok.is(tok::kw___super)) {
238 SourceLocation SuperLoc = ConsumeToken();
239 if (!Tok.is(tok::coloncolon)) {
240 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
241 return true;
242 }
243
244 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
245 }
246
Douglas Gregore610ada2010-02-24 18:44:31 +0000247 bool CheckForDestructor = false;
248 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
249 CheckForDestructor = true;
250 *MayBePseudoDestructor = false;
251 }
252
Richard Smitha9d10012014-10-04 01:57:39 +0000253 if (!HasScopeSpecifier &&
254 (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))) {
David Blaikie15a430a2011-12-04 05:04:18 +0000255 DeclSpec DS(AttrFactory);
256 SourceLocation DeclLoc = Tok.getLocation();
257 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000258
259 SourceLocation CCLoc;
260 if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
David Blaikie15a430a2011-12-04 05:04:18 +0000261 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
262 return false;
263 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000264
David Blaikie15a430a2011-12-04 05:04:18 +0000265 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
266 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
267
268 HasScopeSpecifier = true;
269 }
270
Douglas Gregor7f741122009-02-25 19:37:18 +0000271 while (true) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000272 if (HasScopeSpecifier) {
273 // C++ [basic.lookup.classref]p5:
274 // If the qualified-id has the form
Douglas Gregor308047d2009-09-09 00:23:06 +0000275 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000276 // ::class-name-or-namespace-name::...
Douglas Gregor308047d2009-09-09 00:23:06 +0000277 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000278 // the class-name-or-namespace-name is looked up in global scope as a
279 // class-name or namespace-name.
280 //
281 // To implement this, we clear out the object type as soon as we've
282 // seen a leading '::' or part of a nested-name-specifier.
John McCallba7bf592010-08-24 05:47:05 +0000283 ObjectType = ParsedType();
Douglas Gregor2436e712009-09-17 21:32:03 +0000284
285 if (Tok.is(tok::code_completion)) {
286 // Code completion for a nested-name-specifier, where the code
287 // code completion token follows the '::'.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000288 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
Argyrios Kyrtzidis7d94c922011-04-23 01:04:12 +0000289 // Include code completion token into the range of the scope otherwise
290 // when we try to annotate the scope tokens the dangling code completion
291 // token will cause assertion in
292 // Preprocessor::AnnotatePreviousCachedTokens.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000293 SS.setEndLoc(Tok.getLocation());
294 cutOffParsing();
295 return true;
Douglas Gregor2436e712009-09-17 21:32:03 +0000296 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000297 }
Mike Stump11289f42009-09-09 15:08:12 +0000298
Douglas Gregor7f741122009-02-25 19:37:18 +0000299 // nested-name-specifier:
Chris Lattner0eed3a62009-06-26 03:47:46 +0000300 // nested-name-specifier 'template'[opt] simple-template-id '::'
301
302 // Parse the optional 'template' keyword, then make sure we have
303 // 'identifier <' after it.
304 if (Tok.is(tok::kw_template)) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000305 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedman2624be42009-08-29 04:08:08 +0000306 // nested-name-specifier, since they aren't allowed to start with
307 // 'template'.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000308 if (!HasScopeSpecifier && !ObjectType)
Eli Friedman2624be42009-08-29 04:08:08 +0000309 break;
310
Douglas Gregor120635b2009-11-11 16:39:34 +0000311 TentativeParsingAction TPA(*this);
Chris Lattner0eed3a62009-06-26 03:47:46 +0000312 SourceLocation TemplateKWLoc = ConsumeToken();
Richard Smithd091dc12013-12-05 00:58:33 +0000313
Douglas Gregor71395fa2009-11-04 00:56:37 +0000314 UnqualifiedId TemplateName;
315 if (Tok.is(tok::identifier)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000316 // Consume the identifier.
Douglas Gregor120635b2009-11-11 16:39:34 +0000317 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregor71395fa2009-11-04 00:56:37 +0000318 ConsumeToken();
319 } else if (Tok.is(tok::kw_operator)) {
Richard Smithd091dc12013-12-05 00:58:33 +0000320 // We don't need to actually parse the unqualified-id in this case,
321 // because a simple-template-id cannot start with 'operator', but
322 // go ahead and parse it anyway for consistency with the case where
323 // we already annotated the template-id.
324 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor120635b2009-11-11 16:39:34 +0000325 TemplateName)) {
326 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000327 break;
Douglas Gregor120635b2009-11-11 16:39:34 +0000328 }
Richard Smithd091dc12013-12-05 00:58:33 +0000329
Alexis Hunted0530f2009-11-28 08:58:14 +0000330 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
331 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000332 Diag(TemplateName.getSourceRange().getBegin(),
333 diag::err_id_after_template_in_nested_name_spec)
334 << TemplateName.getSourceRange();
Douglas Gregor120635b2009-11-11 16:39:34 +0000335 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000336 break;
337 }
338 } else {
Douglas Gregor120635b2009-11-11 16:39:34 +0000339 TPA.Revert();
Chris Lattner0eed3a62009-06-26 03:47:46 +0000340 break;
341 }
Mike Stump11289f42009-09-09 15:08:12 +0000342
Douglas Gregor120635b2009-11-11 16:39:34 +0000343 // If the next token is not '<', we have a qualified-id that refers
344 // to a template name, such as T::template apply, but is not a
345 // template-id.
346 if (Tok.isNot(tok::less)) {
347 TPA.Revert();
348 break;
349 }
350
351 // Commit to parsing the template-id.
352 TPA.Commit();
Douglas Gregorbb119652010-06-16 23:00:59 +0000353 TemplateTy Template;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000354 if (TemplateNameKind TNK
355 = Actions.ActOnDependentTemplateName(getCurScope(),
356 SS, TemplateKWLoc, TemplateName,
357 ObjectType, EnteringContext,
358 Template)) {
359 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
360 TemplateName, false))
Douglas Gregorbb119652010-06-16 23:00:59 +0000361 return true;
362 } else
John McCall1f476a12010-02-26 08:45:28 +0000363 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000364
Chris Lattner0eed3a62009-06-26 03:47:46 +0000365 continue;
366 }
Mike Stump11289f42009-09-09 15:08:12 +0000367
Douglas Gregor7f741122009-02-25 19:37:18 +0000368 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump11289f42009-09-09 15:08:12 +0000369 // We have
Douglas Gregor7f741122009-02-25 19:37:18 +0000370 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000371 // template-id '::'
Douglas Gregor7f741122009-02-25 19:37:18 +0000372 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000373 // So we need to check whether the template-id is a simple-template-id of
374 // the right kind (it should name a type or be dependent), and then
Douglas Gregorb67535d2009-03-31 00:43:58 +0000375 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +0000376 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregore610ada2010-02-24 18:44:31 +0000377 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
378 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000379 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000380 }
381
Richard Smith7447af42013-03-26 01:15:19 +0000382 if (LastII)
383 *LastII = TemplateId->Name;
384
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000385 // Consume the template-id token.
386 ConsumeToken();
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000387
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000388 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
389 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000390
David Blaikie8c045bc2011-11-07 03:30:03 +0000391 HasScopeSpecifier = true;
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000392
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000393 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000394 TemplateId->NumArgs);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000395
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000396 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000397 SS,
398 TemplateId->TemplateKWLoc,
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000399 TemplateId->Template,
400 TemplateId->TemplateNameLoc,
401 TemplateId->LAngleLoc,
402 TemplateArgsPtr,
403 TemplateId->RAngleLoc,
404 CCLoc,
405 EnteringContext)) {
406 SourceLocation StartLoc
407 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
408 : TemplateId->TemplateNameLoc;
409 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner704edfb2009-06-26 03:45:46 +0000410 }
Argyrios Kyrtzidis13935672011-05-03 18:45:38 +0000411
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000412 continue;
Douglas Gregor7f741122009-02-25 19:37:18 +0000413 }
414
Chris Lattnere2355f72009-06-26 03:52:38 +0000415 // The rest of the nested-name-specifier possibilities start with
416 // tok::identifier.
417 if (Tok.isNot(tok::identifier))
418 break;
419
420 IdentifierInfo &II = *Tok.getIdentifierInfo();
421
422 // nested-name-specifier:
423 // type-name '::'
424 // namespace-name '::'
425 // nested-name-specifier identifier '::'
426 Token Next = NextToken();
Chris Lattner1c428032009-12-07 01:36:53 +0000427
428 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
429 // and emit a fixit hint for it.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000430 if (Next.is(tok::colon) && !ColonIsSacred) {
Douglas Gregor90c99722011-02-24 00:17:56 +0000431 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
432 Tok.getLocation(),
433 Next.getLocation(), ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000434 EnteringContext) &&
435 // If the token after the colon isn't an identifier, it's still an
436 // error, but they probably meant something else strange so don't
437 // recover like this.
438 PP.LookAhead(1).is(tok::identifier)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000439 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
Douglas Gregora771f462010-03-31 17:46:05 +0000440 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregor90d554e2010-02-21 18:36:56 +0000441 // Recover as if the user wrote '::'.
442 Next.setKind(tok::coloncolon);
443 }
Chris Lattner1c428032009-12-07 01:36:53 +0000444 }
David Majnemerf58efd92014-12-29 23:12:23 +0000445
446 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
447 // It is invalid to have :: {, consume the scope qualifier and pretend
448 // like we never saw it.
449 Token Identifier = Tok; // Stash away the identifier.
450 ConsumeToken(); // Eat the identifier, current token is now '::'.
David Majnemerec3f49d2014-12-29 23:24:27 +0000451 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
452 << tok::identifier;
David Majnemerf58efd92014-12-29 23:12:23 +0000453 UnconsumeToken(Identifier); // Stick the identifier back.
454 Next = NextToken(); // Point Next at the '{' token.
455 }
456
Chris Lattnere2355f72009-06-26 03:52:38 +0000457 if (Next.is(tok::coloncolon)) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +0000458 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Nico Weber61281fa2014-07-26 22:15:25 +0000459 !Actions.isNonTypeNestedNameSpecifier(
460 getCurScope(), SS, Tok.getLocation(), II, ObjectType)) {
Douglas Gregore610ada2010-02-24 18:44:31 +0000461 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000462 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000463 }
464
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000465 if (ColonIsSacred) {
466 const Token &Next2 = GetLookAheadToken(2);
467 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
468 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
469 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
470 << Next2.getName()
471 << FixItHint::CreateReplacement(Next.getLocation(), ":");
472 Token ColonColon;
473 PP.Lex(ColonColon);
474 ColonColon.setKind(tok::colon);
475 PP.EnterToken(ColonColon);
476 break;
477 }
478 }
479
Richard Smith7447af42013-03-26 01:15:19 +0000480 if (LastII)
481 *LastII = &II;
482
Chris Lattnere2355f72009-06-26 03:52:38 +0000483 // We have an identifier followed by a '::'. Lookup this name
484 // as the name in a nested-name-specifier.
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000485 Token Identifier = Tok;
Chris Lattnere2355f72009-06-26 03:52:38 +0000486 SourceLocation IdLoc = ConsumeToken();
Chris Lattner1c428032009-12-07 01:36:53 +0000487 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
488 "NextToken() not working properly!");
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000489 Token ColonColon = Tok;
Chris Lattnere2355f72009-06-26 03:52:38 +0000490 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000491
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000492 CheckForLParenAfterColonColon();
493
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000494 bool IsCorrectedToColon = false;
Craig Topper161e4db2014-05-21 06:02:52 +0000495 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
Douglas Gregor90c99722011-02-24 00:17:56 +0000496 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000497 ObjectType, EnteringContext, SS,
498 false, CorrectionFlagPtr)) {
499 // Identifier is not recognized as a nested name, but we can have
500 // mistyped '::' instead of ':'.
501 if (CorrectionFlagPtr && IsCorrectedToColon) {
502 ColonColon.setKind(tok::colon);
503 PP.EnterToken(Tok);
504 PP.EnterToken(ColonColon);
505 Tok = Identifier;
506 break;
507 }
Douglas Gregor90c99722011-02-24 00:17:56 +0000508 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000509 }
510 HasScopeSpecifier = true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000511 continue;
512 }
Mike Stump11289f42009-09-09 15:08:12 +0000513
Richard Trieu01fc0012011-09-19 19:01:00 +0000514 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smith55858492011-04-14 21:45:45 +0000515
Chris Lattnere2355f72009-06-26 03:52:38 +0000516 // nested-name-specifier:
517 // type-name '<'
518 if (Next.is(tok::less)) {
519 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000520 UnqualifiedId TemplateName;
521 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor786123d2010-05-21 23:18:07 +0000522 bool MemberOfUnknownSpecialization;
Douglas Gregor0be31a22010-07-02 17:43:08 +0000523 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000524 /*hasTemplateKeyword=*/false,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000525 TemplateName,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000526 ObjectType,
Douglas Gregore861bac2009-08-25 22:51:20 +0000527 EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000528 Template,
529 MemberOfUnknownSpecialization)) {
David Blaikie8c045bc2011-11-07 03:30:03 +0000530 // We have found a template name, so annotate this token
Chris Lattnere2355f72009-06-26 03:52:38 +0000531 // with a template-id annotation. We do not permit the
532 // template-id to be translated into a type annotation,
533 // because some clients (e.g., the parsing of class template
534 // specializations) still want to see the original template-id
535 // token.
Douglas Gregor71395fa2009-11-04 00:56:37 +0000536 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000537 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
538 TemplateName, false))
John McCall1f476a12010-02-26 08:45:28 +0000539 return true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000540 continue;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000541 }
542
Douglas Gregor20c38a72010-05-21 23:43:39 +0000543 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000544 (IsTypename || IsTemplateArgumentList(1))) {
Douglas Gregor20c38a72010-05-21 23:43:39 +0000545 // We have something like t::getAs<T>, where getAs is a
546 // member of an unknown specialization. However, this will only
547 // parse correctly as a template, so suggest the keyword 'template'
548 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000549 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000550 if (getLangOpts().MicrosoftExt)
Francois Pichet93921652011-04-22 08:25:24 +0000551 DiagID = diag::warn_missing_dependent_template_keyword;
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000552
553 Diag(Tok.getLocation(), DiagID)
Douglas Gregor20c38a72010-05-21 23:43:39 +0000554 << II.getName()
555 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
556
Douglas Gregorbb119652010-06-16 23:00:59 +0000557 if (TemplateNameKind TNK
Douglas Gregor0be31a22010-07-02 17:43:08 +0000558 = Actions.ActOnDependentTemplateName(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000559 SS, SourceLocation(),
Douglas Gregorbb119652010-06-16 23:00:59 +0000560 TemplateName, ObjectType,
561 EnteringContext, Template)) {
562 // Consume the identifier.
563 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000564 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
565 TemplateName, false))
566 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000567 }
568 else
Douglas Gregor20c38a72010-05-21 23:43:39 +0000569 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000570
Douglas Gregor20c38a72010-05-21 23:43:39 +0000571 continue;
Chris Lattnere2355f72009-06-26 03:52:38 +0000572 }
573 }
574
Douglas Gregor7f741122009-02-25 19:37:18 +0000575 // We don't have any tokens that form the beginning of a
576 // nested-name-specifier, so we're done.
577 break;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000578 }
Mike Stump11289f42009-09-09 15:08:12 +0000579
Douglas Gregore610ada2010-02-24 18:44:31 +0000580 // Even if we didn't see any pieces of a nested-name-specifier, we
581 // still check whether there is a tilde in this position, which
582 // indicates a potential pseudo-destructor.
583 if (CheckForDestructor && Tok.is(tok::tilde))
584 *MayBePseudoDestructor = true;
585
John McCall1f476a12010-02-26 08:45:28 +0000586 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000587}
588
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000589ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
590 Token &Replacement) {
591 SourceLocation TemplateKWLoc;
592 UnqualifiedId Name;
593 if (ParseUnqualifiedId(SS,
594 /*EnteringContext=*/false,
595 /*AllowDestructorName=*/false,
596 /*AllowConstructorName=*/false,
597 /*ObjectType=*/ParsedType(), TemplateKWLoc, Name))
598 return ExprError();
599
600 // This is only the direct operand of an & operator if it is not
601 // followed by a postfix-expression suffix.
602 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
603 isAddressOfOperand = false;
604
605 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
606 Tok.is(tok::l_paren), isAddressOfOperand,
607 nullptr, /*IsInlineAsmIdentifier=*/false,
608 &Replacement);
609}
610
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000611/// ParseCXXIdExpression - Handle id-expression.
612///
613/// id-expression:
614/// unqualified-id
615/// qualified-id
616///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000617/// qualified-id:
618/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
619/// '::' identifier
620/// '::' operator-function-id
Douglas Gregora727cb92009-06-30 22:34:41 +0000621/// '::' template-id
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000622///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000623/// NOTE: The standard specifies that, for qualified-id, the parser does not
624/// expect:
625///
626/// '::' conversion-function-id
627/// '::' '~' class-name
628///
629/// This may cause a slight inconsistency on diagnostics:
630///
631/// class C {};
632/// namespace A {}
633/// void f() {
634/// :: A :: ~ C(); // Some Sema error about using destructor with a
635/// // namespace.
636/// :: ~ C(); // Some Parser error like 'unexpected ~'.
637/// }
638///
639/// We simplify the parser a bit and make it work like:
640///
641/// qualified-id:
642/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
643/// '::' unqualified-id
644///
645/// That way Sema can handle and report similar errors for namespaces and the
646/// global scope.
647///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000648/// The isAddressOfOperand parameter indicates that this id-expression is a
649/// direct operand of the address-of operator. This is, besides member contexts,
650/// the only place where a qualified-id naming a non-static class member may
651/// appear.
652///
John McCalldadc5752010-08-24 06:29:42 +0000653ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000654 // qualified-id:
655 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
656 // '::' unqualified-id
657 //
658 CXXScopeSpec SS;
Douglas Gregordf593fb2011-11-07 17:33:42 +0000659 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000660
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000661 Token Replacement;
662 ExprResult Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
663 if (Result.isUnset()) {
664 // If the ExprResult is valid but null, then typo correction suggested a
665 // keyword replacement that needs to be reparsed.
666 UnconsumeToken(Replacement);
667 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
668 }
669 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
670 "for a previous keyword suggestion");
671 return Result;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000672}
673
Richard Smith21b3ab42013-05-09 21:36:41 +0000674/// ParseLambdaExpression - Parse a C++11 lambda expression.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000675///
676/// lambda-expression:
677/// lambda-introducer lambda-declarator[opt] compound-statement
678///
679/// lambda-introducer:
680/// '[' lambda-capture[opt] ']'
681///
682/// lambda-capture:
683/// capture-default
684/// capture-list
685/// capture-default ',' capture-list
686///
687/// capture-default:
688/// '&'
689/// '='
690///
691/// capture-list:
692/// capture
693/// capture-list ',' capture
694///
695/// capture:
Richard Smith21b3ab42013-05-09 21:36:41 +0000696/// simple-capture
697/// init-capture [C++1y]
698///
699/// simple-capture:
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000700/// identifier
701/// '&' identifier
702/// 'this'
703///
Richard Smith21b3ab42013-05-09 21:36:41 +0000704/// init-capture: [C++1y]
705/// identifier initializer
706/// '&' identifier initializer
707///
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000708/// lambda-declarator:
709/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
710/// 'mutable'[opt] exception-specification[opt]
711/// trailing-return-type[opt]
712///
713ExprResult Parser::ParseLambdaExpression() {
714 // Parse lambda-introducer.
715 LambdaIntroducer Intro;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000716 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000717 if (DiagID) {
718 Diag(Tok, DiagID.getValue());
David Majnemer234b8182015-01-12 03:36:37 +0000719 SkipUntil(tok::r_square, StopAtSemi);
720 SkipUntil(tok::l_brace, StopAtSemi);
721 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000722 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000723 }
724
725 return ParseLambdaExpressionAfterIntroducer(Intro);
726}
727
728/// TryParseLambdaExpression - Use lookahead and potentially tentative
729/// parsing to determine if we are looking at a C++0x lambda expression, and parse
730/// it if we are.
731///
732/// If we are not looking at a lambda expression, returns ExprError().
733ExprResult Parser::TryParseLambdaExpression() {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000734 assert(getLangOpts().CPlusPlus11
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000735 && Tok.is(tok::l_square)
736 && "Not at the start of a possible lambda expression.");
737
738 const Token Next = NextToken(), After = GetLookAheadToken(2);
739
740 // If lookahead indicates this is a lambda...
741 if (Next.is(tok::r_square) || // []
742 Next.is(tok::equal) || // [=
743 (Next.is(tok::amp) && // [&] or [&,
744 (After.is(tok::r_square) ||
745 After.is(tok::comma))) ||
746 (Next.is(tok::identifier) && // [identifier]
747 After.is(tok::r_square))) {
748 return ParseLambdaExpression();
749 }
750
Eli Friedmanc7c97142012-01-04 02:40:39 +0000751 // If lookahead indicates an ObjC message send...
752 // [identifier identifier
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000753 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000754 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000755 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000756
Eli Friedmanc7c97142012-01-04 02:40:39 +0000757 // Here, we're stuck: lambda introducers and Objective-C message sends are
758 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
759 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
760 // writing two routines to parse a lambda introducer, just try to parse
761 // a lambda introducer first, and fall back if that fails.
762 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000763 LambdaIntroducer Intro;
764 if (TryParseLambdaIntroducer(Intro))
Eli Friedmanc7c97142012-01-04 02:40:39 +0000765 return ExprEmpty();
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000766
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000767 return ParseLambdaExpressionAfterIntroducer(Intro);
768}
769
Richard Smithf44d2a82013-05-21 22:21:19 +0000770/// \brief Parse a lambda introducer.
771/// \param Intro A LambdaIntroducer filled in with information about the
772/// contents of the lambda-introducer.
773/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
774/// message send and a lambda expression. In this mode, we will
775/// sometimes skip the initializers for init-captures and not fully
776/// populate \p Intro. This flag will be set to \c true if we do so.
777/// \return A DiagnosticID if it hit something unexpected. The location for
778/// for the diagnostic is that of the current token.
779Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
780 bool *SkippedInits) {
David Blaikie05785d12013-02-20 22:23:23 +0000781 typedef Optional<unsigned> DiagResult;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000782
783 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000784 BalancedDelimiterTracker T(*this, tok::l_square);
785 T.consumeOpen();
786
787 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000788
789 bool first = true;
790
791 // Parse capture-default.
792 if (Tok.is(tok::amp) &&
793 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
794 Intro.Default = LCD_ByRef;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000795 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000796 first = false;
797 } else if (Tok.is(tok::equal)) {
798 Intro.Default = LCD_ByCopy;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000799 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000800 first = false;
801 }
802
803 while (Tok.isNot(tok::r_square)) {
804 if (!first) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000805 if (Tok.isNot(tok::comma)) {
Douglas Gregor721b14d2012-07-31 00:50:07 +0000806 // Provide a completion for a lambda introducer here. Except
807 // in Objective-C, where this is Almost Surely meant to be a message
808 // send. In that case, fail here and let the ObjC message
809 // expression parser perform the completion.
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000810 if (Tok.is(tok::code_completion) &&
811 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
812 !Intro.Captures.empty())) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000813 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
814 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000815 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000816 break;
817 }
818
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000819 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregord8c61782012-02-15 15:34:24 +0000820 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000821 ConsumeToken();
822 }
823
Douglas Gregord8c61782012-02-15 15:34:24 +0000824 if (Tok.is(tok::code_completion)) {
825 // If we're in Objective-C++ and we have a bare '[', then this is more
826 // likely to be a message receiver.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000827 if (getLangOpts().ObjC1 && first)
Douglas Gregord8c61782012-02-15 15:34:24 +0000828 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
829 else
830 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
831 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000832 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000833 break;
834 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000835
Douglas Gregord8c61782012-02-15 15:34:24 +0000836 first = false;
837
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000838 // Parse capture.
839 LambdaCaptureKind Kind = LCK_ByCopy;
840 SourceLocation Loc;
Craig Topper161e4db2014-05-21 06:02:52 +0000841 IdentifierInfo *Id = nullptr;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000842 SourceLocation EllipsisLoc;
Richard Smith21b3ab42013-05-09 21:36:41 +0000843 ExprResult Init;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000844
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000845 if (Tok.is(tok::kw_this)) {
846 Kind = LCK_This;
847 Loc = ConsumeToken();
848 } else {
849 if (Tok.is(tok::amp)) {
850 Kind = LCK_ByRef;
851 ConsumeToken();
Douglas Gregord8c61782012-02-15 15:34:24 +0000852
853 if (Tok.is(tok::code_completion)) {
854 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
855 /*AfterAmpersand=*/true);
Alp Toker1c583cc2014-05-02 03:43:14 +0000856 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000857 break;
858 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000859 }
860
861 if (Tok.is(tok::identifier)) {
862 Id = Tok.getIdentifierInfo();
863 Loc = ConsumeToken();
864 } else if (Tok.is(tok::kw_this)) {
865 // FIXME: If we want to suggest a fixit here, will need to return more
866 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
867 // Clear()ed to prevent emission in case of tentative parsing?
868 return DiagResult(diag::err_this_captured_by_reference);
869 } else {
870 return DiagResult(diag::err_expected_capture);
871 }
Richard Smith21b3ab42013-05-09 21:36:41 +0000872
873 if (Tok.is(tok::l_paren)) {
874 BalancedDelimiterTracker Parens(*this, tok::l_paren);
875 Parens.consumeOpen();
876
877 ExprVector Exprs;
878 CommaLocsTy Commas;
Richard Smithf44d2a82013-05-21 22:21:19 +0000879 if (SkippedInits) {
880 Parens.skipToEnd();
881 *SkippedInits = true;
882 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith21b3ab42013-05-09 21:36:41 +0000883 Parens.skipToEnd();
884 Init = ExprError();
885 } else {
886 Parens.consumeClose();
887 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
888 Parens.getCloseLocation(),
889 Exprs);
890 }
891 } else if (Tok.is(tok::l_brace) || Tok.is(tok::equal)) {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000892 // Each lambda init-capture forms its own full expression, which clears
893 // Actions.MaybeODRUseExprs. So create an expression evaluation context
894 // to save the necessary state, and restore it later.
895 EnterExpressionEvaluationContext EC(Actions,
896 Sema::PotentiallyEvaluated);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000897 TryConsumeToken(tok::equal);
Richard Smith21b3ab42013-05-09 21:36:41 +0000898
Richard Smithf44d2a82013-05-21 22:21:19 +0000899 if (!SkippedInits)
900 Init = ParseInitializer();
901 else if (Tok.is(tok::l_brace)) {
902 BalancedDelimiterTracker Braces(*this, tok::l_brace);
903 Braces.consumeOpen();
904 Braces.skipToEnd();
905 *SkippedInits = true;
906 } else {
907 // We're disambiguating this:
908 //
909 // [..., x = expr
910 //
911 // We need to find the end of the following expression in order to
Richard Smith9e2f0a42014-04-13 04:31:48 +0000912 // determine whether this is an Obj-C message send's receiver, a
913 // C99 designator, or a lambda init-capture.
Richard Smithf44d2a82013-05-21 22:21:19 +0000914 //
915 // Parse the expression to find where it ends, and annotate it back
916 // onto the tokens. We would have parsed this expression the same way
917 // in either case: both the RHS of an init-capture and the RHS of an
918 // assignment expression are parsed as an initializer-clause, and in
919 // neither case can anything be added to the scope between the '[' and
920 // here.
921 //
922 // FIXME: This is horrible. Adding a mechanism to skip an expression
923 // would be much cleaner.
924 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
925 // that instead. (And if we see a ':' with no matching '?', we can
926 // classify this as an Obj-C message send.)
927 SourceLocation StartLoc = Tok.getLocation();
928 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
929 Init = ParseInitializer();
930
931 if (Tok.getLocation() != StartLoc) {
932 // Back out the lexing of the token after the initializer.
933 PP.RevertCachedTokens(1);
934
935 // Replace the consumed tokens with an appropriate annotation.
936 Tok.setLocation(StartLoc);
937 Tok.setKind(tok::annot_primary_expr);
938 setExprAnnotation(Tok, Init);
939 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
940 PP.AnnotateCachedTokens(Tok);
941
942 // Consume the annotated initializer.
943 ConsumeToken();
944 }
945 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000946 } else
947 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000948 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000949 // If this is an init capture, process the initialization expression
950 // right away. For lambda init-captures such as the following:
951 // const int x = 10;
952 // auto L = [i = x+1](int a) {
953 // return [j = x+2,
954 // &k = x](char b) { };
955 // };
956 // keep in mind that each lambda init-capture has to have:
957 // - its initialization expression executed in the context
958 // of the enclosing/parent decl-context.
959 // - but the variable itself has to be 'injected' into the
960 // decl-context of its lambda's call-operator (which has
961 // not yet been created).
962 // Each init-expression is a full-expression that has to get
963 // Sema-analyzed (for capturing etc.) before its lambda's
964 // call-operator's decl-context, scope & scopeinfo are pushed on their
965 // respective stacks. Thus if any variable is odr-used in the init-capture
966 // it will correctly get captured in the enclosing lambda, if one exists.
967 // The init-variables above are created later once the lambdascope and
968 // call-operators decl-context is pushed onto its respective stack.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000969
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000970 // Since the lambda init-capture's initializer expression occurs in the
971 // context of the enclosing function or lambda, therefore we can not wait
972 // till a lambda scope has been pushed on before deciding whether the
973 // variable needs to be captured. We also need to process all
974 // lvalue-to-rvalue conversions and discarded-value conversions,
975 // so that we can avoid capturing certain constant variables.
976 // For e.g.,
977 // void test() {
978 // const int x = 10;
979 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
980 // return [y = x](int i) { <-- don't capture by enclosing lambda
981 // return y;
982 // }
983 // };
984 // If x was not const, the second use would require 'L' to capture, and
985 // that would be an error.
986
987 ParsedType InitCaptureParsedType;
988 if (Init.isUsable()) {
989 // Get the pointer and store it in an lvalue, so we can use it as an
990 // out argument.
991 Expr *InitExpr = Init.get();
992 // This performs any lvalue-to-rvalue conversions if necessary, which
993 // can affect what gets captured in the containing decl-context.
994 QualType InitCaptureType = Actions.performLambdaInitCaptureInitialization(
995 Loc, Kind == LCK_ByRef, Id, InitExpr);
996 Init = InitExpr;
997 InitCaptureParsedType.set(InitCaptureType);
998 }
999 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init, InitCaptureParsedType);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001000 }
1001
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001002 T.consumeClose();
1003 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001004 return DiagResult();
1005}
1006
Douglas Gregord8c61782012-02-15 15:34:24 +00001007/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001008///
1009/// Returns true if it hit something unexpected.
1010bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
1011 TentativeParsingAction PA(*this);
1012
Richard Smithf44d2a82013-05-21 22:21:19 +00001013 bool SkippedInits = false;
1014 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001015
1016 if (DiagID) {
1017 PA.Revert();
1018 return true;
1019 }
1020
Richard Smithf44d2a82013-05-21 22:21:19 +00001021 if (SkippedInits) {
1022 // Parse it again, but this time parse the init-captures too.
1023 PA.Revert();
1024 Intro = LambdaIntroducer();
1025 DiagID = ParseLambdaIntroducer(Intro);
1026 assert(!DiagID && "parsing lambda-introducer failed on reparse");
1027 return false;
1028 }
1029
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001030 PA.Commit();
1031 return false;
1032}
1033
1034/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1035/// expression.
1036ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1037 LambdaIntroducer &Intro) {
Eli Friedmanc7c97142012-01-04 02:40:39 +00001038 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1039 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1040
1041 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1042 "lambda expression parsing");
1043
Faisal Vali2b391ab2013-09-26 19:54:12 +00001044
1045
Richard Smith21b3ab42013-05-09 21:36:41 +00001046 // FIXME: Call into Actions to add any init-capture declarations to the
1047 // scope while parsing the lambda-declarator and compound-statement.
1048
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001049 // Parse lambda-declarator[opt].
1050 DeclSpec DS(AttrFactory);
Eli Friedman36d12942012-01-04 04:41:38 +00001051 Declarator D(DS, Declarator::LambdaExprContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001052 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1053 Actions.PushLambdaScope();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001054
David Majnemere01c4662015-01-09 05:10:55 +00001055 TypeResult TrailingReturnType;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001056 if (Tok.is(tok::l_paren)) {
1057 ParseScope PrototypeScope(this,
1058 Scope::FunctionPrototypeScope |
Richard Smithe233fbf2013-01-28 22:42:45 +00001059 Scope::FunctionDeclarationScope |
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001060 Scope::DeclScope);
1061
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001062 SourceLocation DeclEndLoc;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001063 BalancedDelimiterTracker T(*this, tok::l_paren);
1064 T.consumeOpen();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001065 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001066
1067 // Parse parameter-declaration-clause.
1068 ParsedAttributes Attr(AttrFactory);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001069 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001070 SourceLocation EllipsisLoc;
Faisal Vali2b391ab2013-09-26 19:54:12 +00001071
1072 if (Tok.isNot(tok::r_paren)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00001073 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001074 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001075 // For a generic lambda, each 'auto' within the parameter declaration
1076 // clause creates a template type parameter, so increment the depth.
1077 if (Actions.getCurGenericLambda())
1078 ++CurTemplateDepthTracker;
1079 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001080 T.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001081 SourceLocation RParenLoc = T.getCloseLocation();
1082 DeclEndLoc = RParenLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001083
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001084 // GNU-style attributes must be parsed before the mutable specifier to be
1085 // compatible with GCC.
1086 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1087
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001088 // Parse 'mutable'[opt].
1089 SourceLocation MutableLoc;
Alp Toker094e5212014-01-05 03:27:11 +00001090 if (TryConsumeToken(tok::kw_mutable, MutableLoc))
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001091 DeclEndLoc = MutableLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001092
1093 // Parse exception-specification[opt].
1094 ExceptionSpecificationType ESpecType = EST_None;
1095 SourceRange ESpecRange;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001096 SmallVector<ParsedType, 2> DynamicExceptions;
1097 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001098 ExprResult NoexceptExpr;
Richard Smith0b3a4622014-11-13 20:01:57 +00001099 CachedTokens *ExceptionSpecTokens;
1100 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1101 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00001102 DynamicExceptions,
1103 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00001104 NoexceptExpr,
1105 ExceptionSpecTokens);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001106
1107 if (ESpecType != EST_None)
1108 DeclEndLoc = ESpecRange.getEnd();
1109
1110 // Parse attribute-specifier[opt].
Richard Smith89645bc2013-01-02 12:01:23 +00001111 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001112
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001113 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1114
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001115 // Parse trailing-return-type[opt].
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001116 if (Tok.is(tok::arrow)) {
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001117 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001118 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001119 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001120 if (Range.getEnd().isValid())
1121 DeclEndLoc = Range.getEnd();
1122 }
1123
1124 PrototypeScope.Exit();
1125
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001126 SourceLocation NoLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001127 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001128 /*isAmbiguous=*/false,
1129 LParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001130 ParamInfo.data(), ParamInfo.size(),
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001131 EllipsisLoc, RParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001132 DS.getTypeQualifiers(),
1133 /*RefQualifierIsLValueRef=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001134 /*RefQualifierLoc=*/NoLoc,
1135 /*ConstQualifierLoc=*/NoLoc,
1136 /*VolatileQualifierLoc=*/NoLoc,
Hal Finkel23a07392014-10-20 17:32:04 +00001137 /*RestrictQualifierLoc=*/NoLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001138 MutableLoc,
1139 ESpecType, ESpecRange.getBegin(),
1140 DynamicExceptions.data(),
1141 DynamicExceptionRanges.data(),
1142 DynamicExceptions.size(),
1143 NoexceptExpr.isUsable() ?
Craig Topper161e4db2014-05-21 06:02:52 +00001144 NoexceptExpr.get() : nullptr,
Richard Smith0b3a4622014-11-13 20:01:57 +00001145 /*ExceptionSpecTokens*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001146 LParenLoc, FunLocalRangeEnd, D,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001147 TrailingReturnType),
1148 Attr, DeclEndLoc);
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001149 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow) ||
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001150 Tok.is(tok::kw___attribute) ||
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001151 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1152 // It's common to forget that one needs '()' before 'mutable', an attribute
1153 // specifier, or the result type. Deal with this.
1154 unsigned TokKind = 0;
1155 switch (Tok.getKind()) {
1156 case tok::kw_mutable: TokKind = 0; break;
1157 case tok::arrow: TokKind = 1; break;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001158 case tok::kw___attribute:
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001159 case tok::l_square: TokKind = 2; break;
1160 default: llvm_unreachable("Unknown token kind");
1161 }
1162
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001163 Diag(Tok, diag::err_lambda_missing_parens)
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001164 << TokKind
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001165 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1166 SourceLocation DeclLoc = Tok.getLocation();
1167 SourceLocation DeclEndLoc = DeclLoc;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001168
1169 // GNU-style attributes must be parsed before the mutable specifier to be
1170 // compatible with GCC.
1171 ParsedAttributes Attr(AttrFactory);
1172 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1173
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001174 // Parse 'mutable', if it's there.
1175 SourceLocation MutableLoc;
1176 if (Tok.is(tok::kw_mutable)) {
1177 MutableLoc = ConsumeToken();
1178 DeclEndLoc = MutableLoc;
1179 }
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001180
1181 // Parse attribute-specifier[opt].
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001182 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1183
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001184 // Parse the return type, if there is one.
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001185 if (Tok.is(tok::arrow)) {
1186 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001187 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001188 if (Range.getEnd().isValid())
David Majnemere01c4662015-01-09 05:10:55 +00001189 DeclEndLoc = Range.getEnd();
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001190 }
1191
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001192 SourceLocation NoLoc;
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001193 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001194 /*isAmbiguous=*/false,
1195 /*LParenLoc=*/NoLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00001196 /*Params=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001197 /*NumParams=*/0,
1198 /*EllipsisLoc=*/NoLoc,
1199 /*RParenLoc=*/NoLoc,
1200 /*TypeQuals=*/0,
1201 /*RefQualifierIsLValueRef=*/true,
1202 /*RefQualifierLoc=*/NoLoc,
1203 /*ConstQualifierLoc=*/NoLoc,
1204 /*VolatileQualifierLoc=*/NoLoc,
Hal Finkel23a07392014-10-20 17:32:04 +00001205 /*RestrictQualifierLoc=*/NoLoc,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001206 MutableLoc,
1207 EST_None,
1208 /*ESpecLoc=*/NoLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00001209 /*Exceptions=*/nullptr,
1210 /*ExceptionRanges=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001211 /*NumExceptions=*/0,
Craig Topper161e4db2014-05-21 06:02:52 +00001212 /*NoexceptExpr=*/nullptr,
Richard Smith0b3a4622014-11-13 20:01:57 +00001213 /*ExceptionSpecTokens=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001214 DeclLoc, DeclEndLoc, D,
1215 TrailingReturnType),
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001216 Attr, DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001217 }
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001218
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001219
Eli Friedman4817cf72012-01-06 03:05:34 +00001220 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1221 // it.
Douglas Gregorb8389972012-02-21 22:51:27 +00001222 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
Douglas Gregorb8389972012-02-21 22:51:27 +00001223 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman4817cf72012-01-06 03:05:34 +00001224
Eli Friedman71c80552012-01-05 03:35:19 +00001225 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1226
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001227 // Parse compound-statement.
Eli Friedmanc7c97142012-01-04 02:40:39 +00001228 if (!Tok.is(tok::l_brace)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001229 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmanc7c97142012-01-04 02:40:39 +00001230 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1231 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001232 }
1233
Eli Friedmanc7c97142012-01-04 02:40:39 +00001234 StmtResult Stmt(ParseCompoundStatementBody());
1235 BodyScope.Exit();
1236
David Majnemere01c4662015-01-09 05:10:55 +00001237 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001238 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
David Majnemere01c4662015-01-09 05:10:55 +00001239
Eli Friedman898caf82012-01-04 02:46:53 +00001240 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1241 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001242}
1243
Chris Lattner29375652006-12-04 18:06:35 +00001244/// ParseCXXCasts - This handles the various ways to cast expressions to another
1245/// type.
1246///
1247/// postfix-expression: [C++ 5.2p1]
1248/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1249/// 'static_cast' '<' type-name '>' '(' expression ')'
1250/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1251/// 'const_cast' '<' type-name '>' '(' expression ')'
1252///
John McCalldadc5752010-08-24 06:29:42 +00001253ExprResult Parser::ParseCXXCasts() {
Chris Lattner29375652006-12-04 18:06:35 +00001254 tok::TokenKind Kind = Tok.getKind();
Craig Topper161e4db2014-05-21 06:02:52 +00001255 const char *CastName = nullptr; // For error messages
Chris Lattner29375652006-12-04 18:06:35 +00001256
1257 switch (Kind) {
David Blaikieaa347f92011-09-23 20:26:49 +00001258 default: llvm_unreachable("Unknown C++ cast!");
Chris Lattner29375652006-12-04 18:06:35 +00001259 case tok::kw_const_cast: CastName = "const_cast"; break;
1260 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1261 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1262 case tok::kw_static_cast: CastName = "static_cast"; break;
1263 }
1264
1265 SourceLocation OpLoc = ConsumeToken();
1266 SourceLocation LAngleBracketLoc = Tok.getLocation();
1267
Richard Smith55858492011-04-14 21:45:45 +00001268 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1269 // diagnose error, suggest fix, and recover parsing.
Richard Smith62e66302012-08-20 17:37:52 +00001270 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1271 Token Next = NextToken();
1272 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1273 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1274 }
Richard Smith55858492011-04-14 21:45:45 +00001275
Chris Lattner29375652006-12-04 18:06:35 +00001276 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redld65cea82008-12-11 22:51:44 +00001277 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001278
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001279 // Parse the common declaration-specifiers piece.
1280 DeclSpec DS(AttrFactory);
1281 ParseSpecifierQualifierList(DS);
1282
1283 // Parse the abstract-declarator, if present.
1284 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1285 ParseDeclarator(DeclaratorInfo);
1286
Chris Lattner29375652006-12-04 18:06:35 +00001287 SourceLocation RAngleBracketLoc = Tok.getLocation();
1288
Alp Toker383d2c42014-01-01 03:08:43 +00001289 if (ExpectAndConsume(tok::greater))
Alp Tokerec543272013-12-24 09:48:30 +00001290 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
Chris Lattner29375652006-12-04 18:06:35 +00001291
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001292 SourceLocation LParenLoc, RParenLoc;
1293 BalancedDelimiterTracker T(*this, tok::l_paren);
Chris Lattner29375652006-12-04 18:06:35 +00001294
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001295 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001296 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001297
John McCalldadc5752010-08-24 06:29:42 +00001298 ExprResult Result = ParseExpression();
Mike Stump11289f42009-09-09 15:08:12 +00001299
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001300 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001301 T.consumeClose();
Chris Lattner29375652006-12-04 18:06:35 +00001302
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001303 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregore200adc2008-10-27 19:41:14 +00001304 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001305 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor220cac52009-02-18 17:45:20 +00001306 RAngleBracketLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001307 T.getOpenLocation(), Result.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001308 T.getCloseLocation());
Chris Lattner29375652006-12-04 18:06:35 +00001309
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001310 return Result;
Chris Lattner29375652006-12-04 18:06:35 +00001311}
Bill Wendling4073ed52007-02-13 01:51:42 +00001312
Sebastian Redlc4704762008-11-11 11:37:55 +00001313/// ParseCXXTypeid - This handles the C++ typeid expression.
1314///
1315/// postfix-expression: [C++ 5.2p1]
1316/// 'typeid' '(' expression ')'
1317/// 'typeid' '(' type-id ')'
1318///
John McCalldadc5752010-08-24 06:29:42 +00001319ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc4704762008-11-11 11:37:55 +00001320 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1321
1322 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001323 SourceLocation LParenLoc, RParenLoc;
1324 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc4704762008-11-11 11:37:55 +00001325
1326 // typeid expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001327 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redld65cea82008-12-11 22:51:44 +00001328 return ExprError();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001329 LParenLoc = T.getOpenLocation();
Sebastian Redlc4704762008-11-11 11:37:55 +00001330
John McCalldadc5752010-08-24 06:29:42 +00001331 ExprResult Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001332
Richard Smith4f605af2012-08-18 00:55:03 +00001333 // C++0x [expr.typeid]p3:
1334 // When typeid is applied to an expression other than an lvalue of a
1335 // polymorphic class type [...] The expression is an unevaluated
1336 // operand (Clause 5).
1337 //
1338 // Note that we can't tell whether the expression is an lvalue of a
1339 // polymorphic class type until after we've parsed the expression; we
1340 // speculatively assume the subexpression is unevaluated, and fix it up
1341 // later.
1342 //
1343 // We enter the unevaluated context before trying to determine whether we
1344 // have a type-id, because the tentative parse logic will try to resolve
1345 // names, and must treat them as unevaluated.
Eli Friedman15681d62012-09-26 04:34:21 +00001346 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1347 Sema::ReuseLambdaContextDecl);
Richard Smith4f605af2012-08-18 00:55:03 +00001348
Sebastian Redlc4704762008-11-11 11:37:55 +00001349 if (isTypeIdInParens()) {
Douglas Gregor220cac52009-02-18 17:45:20 +00001350 TypeResult Ty = ParseTypeName();
Sebastian Redlc4704762008-11-11 11:37:55 +00001351
1352 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001353 T.consumeClose();
1354 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001355 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00001356 return ExprError();
Sebastian Redlc4704762008-11-11 11:37:55 +00001357
1358 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallba7bf592010-08-24 05:47:05 +00001359 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001360 } else {
1361 Result = ParseExpression();
1362
1363 // Match the ')'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001364 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001365 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc4704762008-11-11 11:37:55 +00001366 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001367 T.consumeClose();
1368 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001369 if (RParenLoc.isInvalid())
1370 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00001371
Sebastian Redlc4704762008-11-11 11:37:55 +00001372 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001373 Result.get(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001374 }
1375 }
1376
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001377 return Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001378}
1379
Francois Pichet9f4f2072010-09-08 12:20:18 +00001380/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1381///
1382/// '__uuidof' '(' expression ')'
1383/// '__uuidof' '(' type-id ')'
1384///
1385ExprResult Parser::ParseCXXUuidof() {
1386 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1387
1388 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001389 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001390
1391 // __uuidof expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001392 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet9f4f2072010-09-08 12:20:18 +00001393 return ExprError();
1394
1395 ExprResult Result;
1396
1397 if (isTypeIdInParens()) {
1398 TypeResult Ty = ParseTypeName();
1399
1400 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001401 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001402
1403 if (Ty.isInvalid())
1404 return ExprError();
1405
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001406 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1407 Ty.get().getAsOpaquePtr(),
1408 T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001409 } else {
1410 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1411 Result = ParseExpression();
1412
1413 // Match the ')'.
1414 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001415 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001416 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001417 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001418
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001419 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1420 /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001421 Result.get(), T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001422 }
1423 }
1424
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001425 return Result;
Francois Pichet9f4f2072010-09-08 12:20:18 +00001426}
1427
Douglas Gregore610ada2010-02-24 18:44:31 +00001428/// \brief Parse a C++ pseudo-destructor expression after the base,
1429/// . or -> operator, and nested-name-specifier have already been
1430/// parsed.
1431///
1432/// postfix-expression: [C++ 5.2]
1433/// postfix-expression . pseudo-destructor-name
1434/// postfix-expression -> pseudo-destructor-name
1435///
1436/// pseudo-destructor-name:
1437/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1438/// ::[opt] nested-name-specifier template simple-template-id ::
1439/// ~type-name
1440/// ::[opt] nested-name-specifier[opt] ~type-name
1441///
John McCalldadc5752010-08-24 06:29:42 +00001442ExprResult
Craig Toppera2c51532014-10-30 05:30:05 +00001443Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00001444 tok::TokenKind OpKind,
1445 CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +00001446 ParsedType ObjectType) {
Douglas Gregore610ada2010-02-24 18:44:31 +00001447 // We're parsing either a pseudo-destructor-name or a dependent
1448 // member access that has the same form as a
1449 // pseudo-destructor-name. We parse both in the same way and let
1450 // the action model sort them out.
1451 //
1452 // Note that the ::[opt] nested-name-specifier[opt] has already
1453 // been parsed, and if there was a simple-template-id, it has
1454 // been coalesced into a template-id annotation token.
1455 UnqualifiedId FirstTypeName;
1456 SourceLocation CCLoc;
1457 if (Tok.is(tok::identifier)) {
1458 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1459 ConsumeToken();
1460 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1461 CCLoc = ConsumeToken();
1462 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001463 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1464 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregore610ada2010-02-24 18:44:31 +00001465 FirstTypeName.setTemplateId(
1466 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1467 ConsumeToken();
1468 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1469 CCLoc = ConsumeToken();
1470 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001471 FirstTypeName.setIdentifier(nullptr, SourceLocation());
Douglas Gregore610ada2010-02-24 18:44:31 +00001472 }
1473
1474 // Parse the tilde.
1475 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1476 SourceLocation TildeLoc = ConsumeToken();
David Blaikie1d578782011-12-16 16:03:09 +00001477
1478 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1479 DeclSpec DS(AttrFactory);
Benjamin Kramer198e0832011-12-18 12:18:02 +00001480 ParseDecltypeSpecifier(DS);
David Blaikie1d578782011-12-16 16:03:09 +00001481 if (DS.getTypeSpecType() == TST_error)
1482 return ExprError();
1483 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1484 OpKind, TildeLoc, DS,
1485 Tok.is(tok::l_paren));
1486 }
1487
Douglas Gregore610ada2010-02-24 18:44:31 +00001488 if (!Tok.is(tok::identifier)) {
1489 Diag(Tok, diag::err_destructor_tilde_identifier);
1490 return ExprError();
1491 }
1492
1493 // Parse the second type.
1494 UnqualifiedId SecondTypeName;
1495 IdentifierInfo *Name = Tok.getIdentifierInfo();
1496 SourceLocation NameLoc = ConsumeToken();
1497 SecondTypeName.setIdentifier(Name, NameLoc);
1498
1499 // If there is a '<', the second type name is a template-id. Parse
1500 // it as such.
1501 if (Tok.is(tok::less) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +00001502 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1503 Name, NameLoc,
1504 false, ObjectType, SecondTypeName,
1505 /*AssumeTemplateName=*/true))
Douglas Gregore610ada2010-02-24 18:44:31 +00001506 return ExprError();
1507
John McCallb268a282010-08-23 23:25:46 +00001508 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1509 OpLoc, OpKind,
Douglas Gregore610ada2010-02-24 18:44:31 +00001510 SS, FirstTypeName, CCLoc,
1511 TildeLoc, SecondTypeName,
1512 Tok.is(tok::l_paren));
1513}
1514
Bill Wendling4073ed52007-02-13 01:51:42 +00001515/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1516///
1517/// boolean-literal: [C++ 2.13.5]
1518/// 'true'
1519/// 'false'
John McCalldadc5752010-08-24 06:29:42 +00001520ExprResult Parser::ParseCXXBoolLiteral() {
Bill Wendling4073ed52007-02-13 01:51:42 +00001521 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001522 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Bill Wendling4073ed52007-02-13 01:51:42 +00001523}
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001524
1525/// ParseThrowExpression - This handles the C++ throw expression.
1526///
1527/// throw-expression: [C++ 15]
1528/// 'throw' assignment-expression[opt]
John McCalldadc5752010-08-24 06:29:42 +00001529ExprResult Parser::ParseThrowExpression() {
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001530 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001531 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redld65cea82008-12-11 22:51:44 +00001532
Chris Lattner65dd8432008-04-06 06:02:23 +00001533 // If the current token isn't the start of an assignment-expression,
1534 // then the expression is not present. This handles things like:
1535 // "C ? throw : (void)42", which is crazy but legal.
1536 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1537 case tok::semi:
1538 case tok::r_paren:
1539 case tok::r_square:
1540 case tok::r_brace:
1541 case tok::colon:
1542 case tok::comma:
Craig Topper161e4db2014-05-21 06:02:52 +00001543 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001544
Chris Lattner65dd8432008-04-06 06:02:23 +00001545 default:
John McCalldadc5752010-08-24 06:29:42 +00001546 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001547 if (Expr.isInvalid()) return Expr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001548 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
Chris Lattner65dd8432008-04-06 06:02:23 +00001549 }
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001550}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001551
1552/// ParseCXXThis - This handles the C++ 'this' pointer.
1553///
1554/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1555/// a non-lvalue expression whose value is the address of the object for which
1556/// the function is called.
John McCalldadc5752010-08-24 06:29:42 +00001557ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001558 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1559 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001560 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001561}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001562
1563/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1564/// Can be interpreted either as function-style casting ("int(x)")
1565/// or class type construction ("ClassType(x,y,z)")
1566/// or creation of a value-initialized type ("int()").
Sebastian Redl3da34892011-06-05 12:23:16 +00001567/// See [C++ 5.2.3].
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001568///
1569/// postfix-expression: [C++ 5.2p1]
Sebastian Redl3da34892011-06-05 12:23:16 +00001570/// simple-type-specifier '(' expression-list[opt] ')'
1571/// [C++0x] simple-type-specifier braced-init-list
1572/// typename-specifier '(' expression-list[opt] ')'
1573/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001574///
John McCalldadc5752010-08-24 06:29:42 +00001575ExprResult
Sebastian Redld65cea82008-12-11 22:51:44 +00001576Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001577 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
John McCallba7bf592010-08-24 05:47:05 +00001578 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001579
Sebastian Redl3da34892011-06-05 12:23:16 +00001580 assert((Tok.is(tok::l_paren) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001581 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redl3da34892011-06-05 12:23:16 +00001582 && "Expected '(' or '{'!");
Douglas Gregor94a32472011-01-11 00:33:19 +00001583
Sebastian Redl3da34892011-06-05 12:23:16 +00001584 if (Tok.is(tok::l_brace)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001585 ExprResult Init = ParseBraceInitializer();
1586 if (Init.isInvalid())
1587 return Init;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001588 Expr *InitList = Init.get();
Sebastian Redld74dd492012-02-12 18:41:05 +00001589 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1590 MultiExprArg(&InitList, 1),
1591 SourceLocation());
Sebastian Redl3da34892011-06-05 12:23:16 +00001592 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001593 BalancedDelimiterTracker T(*this, tok::l_paren);
1594 T.consumeOpen();
Sebastian Redl3da34892011-06-05 12:23:16 +00001595
Benjamin Kramerf0623432012-08-23 22:51:59 +00001596 ExprVector Exprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00001597 CommaLocsTy CommaLocs;
1598
1599 if (Tok.isNot(tok::r_paren)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00001600 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1601 Actions.CodeCompleteConstructor(getCurScope(),
1602 TypeRep.get()->getCanonicalTypeInternal(),
1603 DS.getLocEnd(), Exprs);
1604 })) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001605 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00001606 return ExprError();
1607 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001608 }
Sebastian Redl3da34892011-06-05 12:23:16 +00001609
1610 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001611 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00001612
1613 // TypeRep could be null, if it references an invalid typedef.
1614 if (!TypeRep)
1615 return ExprError();
1616
1617 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1618 "Unexpected number of commas!");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001619 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001620 Exprs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001621 T.getCloseLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001622 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001623}
1624
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001625/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001626///
1627/// condition:
1628/// expression
1629/// type-specifier-seq declarator '=' assignment-expression
Richard Smith2a15b742012-02-22 06:49:09 +00001630/// [C++11] type-specifier-seq declarator '=' initializer-clause
1631/// [C++11] type-specifier-seq declarator braced-init-list
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001632/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1633/// '=' assignment-expression
1634///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001635/// \param ExprOut if the condition was parsed as an expression, the parsed
1636/// expression.
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001637///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001638/// \param DeclOut if the condition was parsed as a declaration, the parsed
1639/// declaration.
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001640///
Douglas Gregore60e41a2010-05-06 17:25:47 +00001641/// \param Loc The location of the start of the statement that requires this
1642/// condition, e.g., the "for" in a for loop.
1643///
1644/// \param ConvertToBoolean Whether the condition expression should be
1645/// converted to a boolean value.
1646///
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001647/// \returns true if there was a parsing, false otherwise.
John McCalldadc5752010-08-24 06:29:42 +00001648bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1649 Decl *&DeclOut,
Douglas Gregore60e41a2010-05-06 17:25:47 +00001650 SourceLocation Loc,
1651 bool ConvertToBoolean) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001652 if (Tok.is(tok::code_completion)) {
John McCallfaf5fb42010-08-26 23:41:50 +00001653 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001654 cutOffParsing();
1655 return true;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001656 }
1657
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001658 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001659 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001660
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001661 if (!isCXXConditionDeclaration()) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001662 ProhibitAttributes(attrs);
1663
Douglas Gregore60e41a2010-05-06 17:25:47 +00001664 // Parse the expression.
John McCalldadc5752010-08-24 06:29:42 +00001665 ExprOut = ParseExpression(); // expression
Craig Topper161e4db2014-05-21 06:02:52 +00001666 DeclOut = nullptr;
John McCalldadc5752010-08-24 06:29:42 +00001667 if (ExprOut.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001668 return true;
1669
1670 // If required, convert to a boolean value.
1671 if (ConvertToBoolean)
John McCalldadc5752010-08-24 06:29:42 +00001672 ExprOut
1673 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1674 return ExprOut.isInvalid();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001675 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001676
1677 // type-specifier-seq
John McCall084e83d2011-03-24 11:26:52 +00001678 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +00001679 DS.takeAttributesFrom(attrs);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001680 ParseSpecifierQualifierList(DS);
1681
1682 // declarator
1683 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1684 ParseDeclarator(DeclaratorInfo);
1685
1686 // simple-asm-expr[opt]
1687 if (Tok.is(tok::kw_asm)) {
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001688 SourceLocation Loc;
John McCalldadc5752010-08-24 06:29:42 +00001689 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001690 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001691 SkipUntil(tok::semi, StopAtSemi);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001692 return true;
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001693 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001694 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001695 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001696 }
1697
1698 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001699 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001700
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001701 // Type-check the declaration itself.
John McCalldadc5752010-08-24 06:29:42 +00001702 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall53fa7142010-12-24 02:08:15 +00001703 DeclaratorInfo);
John McCalldadc5752010-08-24 06:29:42 +00001704 DeclOut = Dcl.get();
1705 ExprOut = ExprError();
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001706
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001707 // '=' assignment-expression
Richard Trieuc64d3232012-01-18 22:54:52 +00001708 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith2a15b742012-02-22 06:49:09 +00001709 bool CopyInitialization = isTokenEqualOrEqualTypo();
1710 if (CopyInitialization)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001711 ConsumeToken();
Richard Smith2a15b742012-02-22 06:49:09 +00001712
1713 ExprResult InitExpr = ExprError();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001714 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith2a15b742012-02-22 06:49:09 +00001715 Diag(Tok.getLocation(),
1716 diag::warn_cxx98_compat_generalized_initializer_lists);
1717 InitExpr = ParseBraceInitializer();
1718 } else if (CopyInitialization) {
1719 InitExpr = ParseAssignmentExpression();
1720 } else if (Tok.is(tok::l_paren)) {
1721 // This was probably an attempt to initialize the variable.
1722 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001723 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith2a15b742012-02-22 06:49:09 +00001724 RParen = ConsumeParen();
1725 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1726 diag::err_expected_init_in_condition_lparen)
1727 << SourceRange(LParen, RParen);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001728 } else {
Richard Smith2a15b742012-02-22 06:49:09 +00001729 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1730 diag::err_expected_init_in_condition);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001731 }
Richard Smith2a15b742012-02-22 06:49:09 +00001732
1733 if (!InitExpr.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001734 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization,
Richard Smith74aeef52013-04-26 16:15:35 +00001735 DS.containsPlaceholderType());
Richard Smith27d807c2013-04-30 13:56:41 +00001736 else
1737 Actions.ActOnInitializerError(DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001738
Douglas Gregore60e41a2010-05-06 17:25:47 +00001739 // FIXME: Build a reference to this declaration? Convert it to bool?
1740 // (This is currently handled by Sema).
Richard Smithb2bc2e62011-02-21 20:05:19 +00001741
1742 Actions.FinalizeDeclaration(DeclOut);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001743
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001744 return false;
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001745}
1746
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001747/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1748/// This should only be called when the current token is known to be part of
1749/// simple-type-specifier.
1750///
1751/// simple-type-specifier:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001752/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001753/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1754/// char
1755/// wchar_t
1756/// bool
1757/// short
1758/// int
1759/// long
1760/// signed
1761/// unsigned
1762/// float
1763/// double
1764/// void
1765/// [GNU] typeof-specifier
1766/// [C++0x] auto [TODO]
1767///
1768/// type-name:
1769/// class-name
1770/// enum-name
1771/// typedef-name
1772///
1773void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1774 DS.SetRangeStart(Tok.getLocation());
1775 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +00001776 unsigned DiagID;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001777 SourceLocation Loc = Tok.getLocation();
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001778 const clang::PrintingPolicy &Policy =
1779 Actions.getASTContext().getPrintingPolicy();
Mike Stump11289f42009-09-09 15:08:12 +00001780
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001781 switch (Tok.getKind()) {
Chris Lattner45ddec32009-01-05 00:13:00 +00001782 case tok::identifier: // foo::bar
1783 case tok::coloncolon: // ::foo::bar
David Blaikie83d382b2011-09-23 05:06:16 +00001784 llvm_unreachable("Annotation token should already be formed!");
Mike Stump11289f42009-09-09 15:08:12 +00001785 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001786 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner45ddec32009-01-05 00:13:00 +00001787
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001788 // type-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00001789 case tok::annot_typename: {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001790 if (getTypeAnnotation(Tok))
1791 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001792 getTypeAnnotation(Tok), Policy);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001793 else
1794 DS.SetTypeSpecError();
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001795
1796 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1797 ConsumeToken();
1798
1799 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1800 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1801 // Objective-C interface. If we don't have Objective-C or a '<', this is
1802 // just a normal reference to a typedef name.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001803 if (Tok.is(tok::less) && getLangOpts().ObjC1)
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001804 ParseObjCProtocolQualifiers(DS);
1805
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001806 DS.Finish(Diags, PP, Policy);
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001807 return;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001808 }
Mike Stump11289f42009-09-09 15:08:12 +00001809
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001810 // builtin types
1811 case tok::kw_short:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001812 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001813 break;
1814 case tok::kw_long:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001815 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001816 break;
Francois Pichet84133e42011-04-28 01:59:37 +00001817 case tok::kw___int64:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001818 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00001819 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001820 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00001821 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001822 break;
1823 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00001824 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001825 break;
1826 case tok::kw_void:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001827 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001828 break;
1829 case tok::kw_char:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001830 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001831 break;
1832 case tok::kw_int:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001833 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001834 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00001835 case tok::kw___int128:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001836 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00001837 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001838 case tok::kw_half:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001839 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001840 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001841 case tok::kw_float:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001842 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001843 break;
1844 case tok::kw_double:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001845 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001846 break;
1847 case tok::kw_wchar_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001848 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001849 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001850 case tok::kw_char16_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001851 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001852 break;
1853 case tok::kw_char32_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001854 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001855 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001856 case tok::kw_bool:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001857 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001858 break;
David Blaikie25896afb2012-01-24 05:47:35 +00001859 case tok::annot_decltype:
1860 case tok::kw_decltype:
1861 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001862 return DS.Finish(Diags, PP, Policy);
Mike Stump11289f42009-09-09 15:08:12 +00001863
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001864 // GNU typeof support.
1865 case tok::kw_typeof:
1866 ParseTypeofSpecifier(DS);
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001867 DS.Finish(Diags, PP, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001868 return;
1869 }
Chris Lattnera8a3f732009-01-06 05:06:21 +00001870 if (Tok.is(tok::annot_typename))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001871 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1872 else
1873 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001874 ConsumeToken();
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001875 DS.Finish(Diags, PP, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001876}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001877
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001878/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1879/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1880/// e.g., "const short int". Note that the DeclSpec is *not* finished
1881/// by parsing the type-specifier-seq, because these sequences are
1882/// typically followed by some form of declarator. Returns true and
1883/// emits diagnostics if this is not a type-specifier-seq, false
1884/// otherwise.
1885///
1886/// type-specifier-seq: [C++ 8.1]
1887/// type-specifier type-specifier-seq[opt]
1888///
1889bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Richard Smithc5b05522012-03-12 07:56:15 +00001890 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001891 DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001892 return false;
1893}
1894
Douglas Gregor7861a802009-11-03 01:35:08 +00001895/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1896/// some form.
1897///
1898/// This routine is invoked when a '<' is encountered after an identifier or
1899/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1900/// whether the unqualified-id is actually a template-id. This routine will
1901/// then parse the template arguments and form the appropriate template-id to
1902/// return to the caller.
1903///
1904/// \param SS the nested-name-specifier that precedes this template-id, if
1905/// we're actually parsing a qualified-id.
1906///
1907/// \param Name for constructor and destructor names, this is the actual
1908/// identifier that may be a template-name.
1909///
1910/// \param NameLoc the location of the class-name in a constructor or
1911/// destructor.
1912///
1913/// \param EnteringContext whether we're entering the scope of the
1914/// nested-name-specifier.
1915///
Douglas Gregor127ea592009-11-03 21:24:04 +00001916/// \param ObjectType if this unqualified-id occurs within a member access
1917/// expression, the type of the base object whose member is being accessed.
1918///
Douglas Gregor7861a802009-11-03 01:35:08 +00001919/// \param Id as input, describes the template-name or operator-function-id
1920/// that precedes the '<'. If template arguments were parsed successfully,
1921/// will be updated with the template-id.
1922///
Douglas Gregore610ada2010-02-24 18:44:31 +00001923/// \param AssumeTemplateId When true, this routine will assume that the name
1924/// refers to a template without performing name lookup to verify.
1925///
Douglas Gregor7861a802009-11-03 01:35:08 +00001926/// \returns true if a parse error occurred, false otherwise.
1927bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001928 SourceLocation TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00001929 IdentifierInfo *Name,
1930 SourceLocation NameLoc,
1931 bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00001932 ParsedType ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00001933 UnqualifiedId &Id,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001934 bool AssumeTemplateId) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00001935 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1936 "Expected '<' to finish parsing a template-id");
Douglas Gregor7861a802009-11-03 01:35:08 +00001937
1938 TemplateTy Template;
1939 TemplateNameKind TNK = TNK_Non_template;
1940 switch (Id.getKind()) {
1941 case UnqualifiedId::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +00001942 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunted0530f2009-11-28 08:58:14 +00001943 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregore610ada2010-02-24 18:44:31 +00001944 if (AssumeTemplateId) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001945 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00001946 Id, ObjectType, EnteringContext,
1947 Template);
1948 if (TNK == TNK_Non_template)
1949 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00001950 } else {
1951 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001952 TNK = Actions.isTemplateName(getCurScope(), SS,
1953 TemplateKWLoc.isValid(), Id,
1954 ObjectType, EnteringContext, Template,
Douglas Gregor786123d2010-05-21 23:18:07 +00001955 MemberOfUnknownSpecialization);
1956
1957 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1958 ObjectType && IsTemplateArgumentList()) {
1959 // We have something like t->getAs<T>(), where getAs is a
1960 // member of an unknown specialization. However, this will only
1961 // parse correctly as a template, so suggest the keyword 'template'
1962 // before 'getAs' and treat this as a dependent template name.
1963 std::string Name;
1964 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1965 Name = Id.Identifier->getName();
1966 else {
1967 Name = "operator ";
1968 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1969 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1970 else
1971 Name += Id.Identifier->getName();
1972 }
1973 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1974 << Name
1975 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Abramo Bagnara7945c982012-01-27 09:46:47 +00001976 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1977 SS, TemplateKWLoc, Id,
1978 ObjectType, EnteringContext,
1979 Template);
Douglas Gregorbb119652010-06-16 23:00:59 +00001980 if (TNK == TNK_Non_template)
Douglas Gregor786123d2010-05-21 23:18:07 +00001981 return true;
1982 }
1983 }
Douglas Gregor7861a802009-11-03 01:35:08 +00001984 break;
1985
Douglas Gregor3cf81312009-11-03 23:16:33 +00001986 case UnqualifiedId::IK_ConstructorName: {
1987 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00001988 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001989 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001990 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1991 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00001992 EnteringContext, Template,
1993 MemberOfUnknownSpecialization);
Douglas Gregor7861a802009-11-03 01:35:08 +00001994 break;
1995 }
1996
Douglas Gregor3cf81312009-11-03 23:16:33 +00001997 case UnqualifiedId::IK_DestructorName: {
1998 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00001999 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002000 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002001 if (ObjectType) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00002002 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
2003 SS, TemplateKWLoc, TemplateName,
2004 ObjectType, EnteringContext,
2005 Template);
Douglas Gregorbb119652010-06-16 23:00:59 +00002006 if (TNK == TNK_Non_template)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002007 return true;
2008 } else {
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002009 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2010 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002011 EnteringContext, Template,
2012 MemberOfUnknownSpecialization);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002013
John McCallba7bf592010-08-24 05:47:05 +00002014 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002015 Diag(NameLoc, diag::err_destructor_template_id)
2016 << Name << SS.getRange();
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002017 return true;
2018 }
2019 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002020 break;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002021 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002022
2023 default:
2024 return false;
2025 }
2026
2027 if (TNK == TNK_Non_template)
2028 return false;
2029
2030 // Parse the enclosed template argument list.
2031 SourceLocation LAngleLoc, RAngleLoc;
2032 TemplateArgList TemplateArgs;
Douglas Gregorb22ee882010-05-05 05:58:24 +00002033 if (Tok.is(tok::less) &&
2034 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
Douglas Gregore7c20652011-03-02 00:47:37 +00002035 SS, true, LAngleLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002036 TemplateArgs,
Douglas Gregor7861a802009-11-03 01:35:08 +00002037 RAngleLoc))
2038 return true;
2039
2040 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
Alexis Hunted0530f2009-11-28 08:58:14 +00002041 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2042 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002043 // Form a parsed representation of the template-id to be stored in the
2044 // UnqualifiedId.
2045 TemplateIdAnnotation *TemplateId
Benjamin Kramer1e6b6062012-04-14 12:14:03 +00002046 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor7861a802009-11-03 01:35:08 +00002047
Richard Smith72bfbd82013-12-04 00:28:23 +00002048 // FIXME: Store name for literal operator too.
Douglas Gregor7861a802009-11-03 01:35:08 +00002049 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
2050 TemplateId->Name = Id.Identifier;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002051 TemplateId->Operator = OO_None;
Douglas Gregor7861a802009-11-03 01:35:08 +00002052 TemplateId->TemplateNameLoc = Id.StartLocation;
2053 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00002054 TemplateId->Name = nullptr;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002055 TemplateId->Operator = Id.OperatorFunctionId.Operator;
2056 TemplateId->TemplateNameLoc = Id.StartLocation;
Douglas Gregor7861a802009-11-03 01:35:08 +00002057 }
2058
Douglas Gregore7c20652011-03-02 00:47:37 +00002059 TemplateId->SS = SS;
Benjamin Kramer807c2db2012-02-19 23:37:39 +00002060 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall3e56fd42010-08-23 07:28:44 +00002061 TemplateId->Template = Template;
Douglas Gregor7861a802009-11-03 01:35:08 +00002062 TemplateId->Kind = TNK;
2063 TemplateId->LAngleLoc = LAngleLoc;
2064 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002065 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
Douglas Gregor7861a802009-11-03 01:35:08 +00002066 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002067 Arg != ArgEnd; ++Arg)
Douglas Gregor7861a802009-11-03 01:35:08 +00002068 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor7861a802009-11-03 01:35:08 +00002069
2070 Id.setTemplateId(TemplateId);
2071 return false;
2072 }
2073
2074 // Bundle the template arguments together.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002075 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnara4244b432012-01-27 08:46:19 +00002076
Douglas Gregor7861a802009-11-03 01:35:08 +00002077 // Constructor and destructor names.
John McCallfaf5fb42010-08-26 23:41:50 +00002078 TypeResult Type
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002079 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2080 Template, NameLoc,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002081 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2082 /*IsCtorOrDtorName=*/true);
Douglas Gregor7861a802009-11-03 01:35:08 +00002083 if (Type.isInvalid())
2084 return true;
2085
2086 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2087 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2088 else
2089 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2090
2091 return false;
2092}
2093
Douglas Gregor71395fa2009-11-04 00:56:37 +00002094/// \brief Parse an operator-function-id or conversion-function-id as part
2095/// of a C++ unqualified-id.
2096///
2097/// This routine is responsible only for parsing the operator-function-id or
2098/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor7861a802009-11-03 01:35:08 +00002099///
2100/// \code
Douglas Gregor7861a802009-11-03 01:35:08 +00002101/// operator-function-id: [C++ 13.5]
2102/// 'operator' operator
2103///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002104/// operator: one of
Douglas Gregor7861a802009-11-03 01:35:08 +00002105/// new delete new[] delete[]
2106/// + - * / % ^ & | ~
2107/// ! = < > += -= *= /= %=
2108/// ^= &= |= << >> >>= <<= == !=
2109/// <= >= && || ++ -- , ->* ->
2110/// () []
2111///
2112/// conversion-function-id: [C++ 12.3.2]
2113/// operator conversion-type-id
2114///
2115/// conversion-type-id:
2116/// type-specifier-seq conversion-declarator[opt]
2117///
2118/// conversion-declarator:
2119/// ptr-operator conversion-declarator[opt]
2120/// \endcode
2121///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002122/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor7861a802009-11-03 01:35:08 +00002123/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2124///
2125/// \param EnteringContext whether we are entering the scope of the
2126/// nested-name-specifier.
2127///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002128/// \param ObjectType if this unqualified-id occurs within a member access
2129/// expression, the type of the base object whose member is being accessed.
2130///
2131/// \param Result on a successful parse, contains the parsed unqualified-id.
2132///
2133/// \returns true if parsing fails, false otherwise.
2134bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002135 ParsedType ObjectType,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002136 UnqualifiedId &Result) {
2137 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2138
2139 // Consume the 'operator' keyword.
2140 SourceLocation KeywordLoc = ConsumeToken();
2141
2142 // Determine what kind of operator name we have.
2143 unsigned SymbolIdx = 0;
2144 SourceLocation SymbolLocations[3];
2145 OverloadedOperatorKind Op = OO_None;
2146 switch (Tok.getKind()) {
2147 case tok::kw_new:
2148 case tok::kw_delete: {
2149 bool isNew = Tok.getKind() == tok::kw_new;
2150 // Consume the 'new' or 'delete'.
2151 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002152 // Check for array new/delete.
2153 if (Tok.is(tok::l_square) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002154 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002155 // Consume the '[' and ']'.
2156 BalancedDelimiterTracker T(*this, tok::l_square);
2157 T.consumeOpen();
2158 T.consumeClose();
2159 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002160 return true;
2161
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002162 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2163 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002164 Op = isNew? OO_Array_New : OO_Array_Delete;
2165 } else {
2166 Op = isNew? OO_New : OO_Delete;
2167 }
2168 break;
2169 }
2170
2171#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2172 case tok::Token: \
2173 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2174 Op = OO_##Name; \
2175 break;
2176#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2177#include "clang/Basic/OperatorKinds.def"
2178
2179 case tok::l_paren: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002180 // Consume the '(' and ')'.
2181 BalancedDelimiterTracker T(*this, tok::l_paren);
2182 T.consumeOpen();
2183 T.consumeClose();
2184 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002185 return true;
2186
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002187 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2188 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002189 Op = OO_Call;
2190 break;
2191 }
2192
2193 case tok::l_square: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002194 // Consume the '[' and ']'.
2195 BalancedDelimiterTracker T(*this, tok::l_square);
2196 T.consumeOpen();
2197 T.consumeClose();
2198 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002199 return true;
2200
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002201 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2202 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002203 Op = OO_Subscript;
2204 break;
2205 }
2206
2207 case tok::code_completion: {
2208 // Code completion for the operator name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002209 Actions.CodeCompleteOperatorName(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002210 cutOffParsing();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002211 // Don't try to parse any further.
2212 return true;
2213 }
2214
2215 default:
2216 break;
2217 }
2218
2219 if (Op != OO_None) {
2220 // We have parsed an operator-function-id.
2221 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2222 return false;
2223 }
Alexis Hunt34458502009-11-28 04:44:28 +00002224
2225 // Parse a literal-operator-id.
2226 //
Richard Smith6f212062012-10-20 08:41:10 +00002227 // literal-operator-id: C++11 [over.literal]
2228 // operator string-literal identifier
2229 // operator user-defined-string-literal
Alexis Hunt34458502009-11-28 04:44:28 +00002230
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002231 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002232 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Alexis Hunt34458502009-11-28 04:44:28 +00002233
Richard Smith7d182a72012-03-08 23:06:02 +00002234 SourceLocation DiagLoc;
2235 unsigned DiagId = 0;
2236
2237 // We're past translation phase 6, so perform string literal concatenation
2238 // before checking for "".
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002239 SmallVector<Token, 4> Toks;
2240 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith7d182a72012-03-08 23:06:02 +00002241 while (isTokenStringLiteral()) {
2242 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smith6f212062012-10-20 08:41:10 +00002243 // C++11 [over.literal]p1:
2244 // The string-literal or user-defined-string-literal in a
2245 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith7d182a72012-03-08 23:06:02 +00002246 DiagLoc = Tok.getLocation();
2247 DiagId = diag::err_literal_operator_string_prefix;
2248 }
2249 Toks.push_back(Tok);
2250 TokLocs.push_back(ConsumeStringToken());
2251 }
2252
Craig Topper9d5583e2014-06-26 04:58:39 +00002253 StringLiteralParser Literal(Toks, PP);
Richard Smith7d182a72012-03-08 23:06:02 +00002254 if (Literal.hadError)
2255 return true;
2256
2257 // Grab the literal operator's suffix, which will be either the next token
2258 // or a ud-suffix from the string literal.
Craig Topper161e4db2014-05-21 06:02:52 +00002259 IdentifierInfo *II = nullptr;
Richard Smith7d182a72012-03-08 23:06:02 +00002260 SourceLocation SuffixLoc;
2261 if (!Literal.getUDSuffix().empty()) {
2262 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2263 SuffixLoc =
2264 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2265 Literal.getUDSuffixOffset(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002266 PP.getSourceManager(), getLangOpts());
Richard Smith7d182a72012-03-08 23:06:02 +00002267 } else if (Tok.is(tok::identifier)) {
2268 II = Tok.getIdentifierInfo();
2269 SuffixLoc = ConsumeToken();
2270 TokLocs.push_back(SuffixLoc);
2271 } else {
Alp Tokerec543272013-12-24 09:48:30 +00002272 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexis Hunt34458502009-11-28 04:44:28 +00002273 return true;
2274 }
2275
Richard Smith7d182a72012-03-08 23:06:02 +00002276 // The string literal must be empty.
2277 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smith6f212062012-10-20 08:41:10 +00002278 // C++11 [over.literal]p1:
2279 // The string-literal or user-defined-string-literal in a
2280 // literal-operator-id shall [...] contain no characters
2281 // other than the implicit terminating '\0'.
Richard Smith7d182a72012-03-08 23:06:02 +00002282 DiagLoc = TokLocs.front();
2283 DiagId = diag::err_literal_operator_string_not_empty;
2284 }
2285
2286 if (DiagId) {
2287 // This isn't a valid literal-operator-id, but we think we know
2288 // what the user meant. Tell them what they should have written.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002289 SmallString<32> Str;
Richard Smith7d182a72012-03-08 23:06:02 +00002290 Str += "\"\" ";
2291 Str += II->getName();
2292 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2293 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2294 }
2295
2296 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Richard Smithd091dc12013-12-05 00:58:33 +00002297
2298 return Actions.checkLiteralOperatorId(SS, Result);
Alexis Hunt34458502009-11-28 04:44:28 +00002299 }
Richard Smithd091dc12013-12-05 00:58:33 +00002300
Douglas Gregor71395fa2009-11-04 00:56:37 +00002301 // Parse a conversion-function-id.
2302 //
2303 // conversion-function-id: [C++ 12.3.2]
2304 // operator conversion-type-id
2305 //
2306 // conversion-type-id:
2307 // type-specifier-seq conversion-declarator[opt]
2308 //
2309 // conversion-declarator:
2310 // ptr-operator conversion-declarator[opt]
2311
2312 // Parse the type-specifier-seq.
John McCall084e83d2011-03-24 11:26:52 +00002313 DeclSpec DS(AttrFactory);
Douglas Gregora25d65d2009-11-20 22:03:38 +00002314 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregor71395fa2009-11-04 00:56:37 +00002315 return true;
2316
2317 // Parse the conversion-declarator, which is merely a sequence of
2318 // ptr-operators.
Richard Smith01518fa2013-05-04 01:26:46 +00002319 Declarator D(DS, Declarator::ConversionIdContext);
Craig Topper161e4db2014-05-21 06:02:52 +00002320 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2321
Douglas Gregor71395fa2009-11-04 00:56:37 +00002322 // Finish up the type.
John McCallfaf5fb42010-08-26 23:41:50 +00002323 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002324 if (Ty.isInvalid())
2325 return true;
2326
2327 // Note that this is a conversion-function-id.
2328 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2329 D.getSourceRange().getEnd());
2330 return false;
2331}
2332
2333/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2334/// name of an entity.
2335///
2336/// \code
2337/// unqualified-id: [C++ expr.prim.general]
2338/// identifier
2339/// operator-function-id
2340/// conversion-function-id
2341/// [C++0x] literal-operator-id [TODO]
2342/// ~ class-name
2343/// template-id
2344///
2345/// \endcode
2346///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002347/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor71395fa2009-11-04 00:56:37 +00002348/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2349///
2350/// \param EnteringContext whether we are entering the scope of the
2351/// nested-name-specifier.
2352///
Douglas Gregor7861a802009-11-03 01:35:08 +00002353/// \param AllowDestructorName whether we allow parsing of a destructor name.
2354///
2355/// \param AllowConstructorName whether we allow parsing a constructor name.
2356///
Douglas Gregor127ea592009-11-03 21:24:04 +00002357/// \param ObjectType if this unqualified-id occurs within a member access
2358/// expression, the type of the base object whose member is being accessed.
2359///
Douglas Gregor7861a802009-11-03 01:35:08 +00002360/// \param Result on a successful parse, contains the parsed unqualified-id.
2361///
2362/// \returns true if parsing fails, false otherwise.
2363bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2364 bool AllowDestructorName,
2365 bool AllowConstructorName,
John McCallba7bf592010-08-24 05:47:05 +00002366 ParsedType ObjectType,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002367 SourceLocation& TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002368 UnqualifiedId &Result) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00002369
2370 // Handle 'A::template B'. This is for template-ids which have not
2371 // already been annotated by ParseOptionalCXXScopeSpecifier().
2372 bool TemplateSpecified = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002373 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002374 (ObjectType || SS.isSet())) {
2375 TemplateSpecified = true;
2376 TemplateKWLoc = ConsumeToken();
2377 }
2378
Douglas Gregor7861a802009-11-03 01:35:08 +00002379 // unqualified-id:
2380 // identifier
2381 // template-id (when it hasn't already been annotated)
2382 if (Tok.is(tok::identifier)) {
2383 // Consume the identifier.
2384 IdentifierInfo *Id = Tok.getIdentifierInfo();
2385 SourceLocation IdLoc = ConsumeToken();
2386
David Blaikiebbafb8a2012-03-11 07:00:24 +00002387 if (!getLangOpts().CPlusPlus) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002388 // If we're not in C++, only identifiers matter. Record the
2389 // identifier and return.
2390 Result.setIdentifier(Id, IdLoc);
2391 return false;
2392 }
2393
Douglas Gregor7861a802009-11-03 01:35:08 +00002394 if (AllowConstructorName &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002395 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002396 // We have parsed a constructor name.
Abramo Bagnara4244b432012-01-27 08:46:19 +00002397 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2398 &SS, false, false,
2399 ParsedType(),
2400 /*IsCtorOrDtorName=*/true,
2401 /*NonTrivialTypeSourceInfo=*/true);
2402 Result.setConstructorName(Ty, IdLoc, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002403 } else {
2404 // We have parsed an identifier.
2405 Result.setIdentifier(Id, IdLoc);
2406 }
2407
2408 // If the next token is a '<', we may have a template.
Douglas Gregorb22ee882010-05-05 05:58:24 +00002409 if (TemplateSpecified || Tok.is(tok::less))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002410 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2411 EnteringContext, ObjectType,
2412 Result, TemplateSpecified);
Douglas Gregor7861a802009-11-03 01:35:08 +00002413
2414 return false;
2415 }
2416
2417 // unqualified-id:
2418 // template-id (already parsed and annotated)
2419 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00002420 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002421
2422 // If the template-name names the current class, then this is a constructor
2423 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002424 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002425 if (SS.isSet()) {
2426 // C++ [class.qual]p2 specifies that a qualified template-name
2427 // is taken as the constructor name where a constructor can be
2428 // declared. Thus, the template arguments are extraneous, so
2429 // complain about them and remove them entirely.
2430 Diag(TemplateId->TemplateNameLoc,
2431 diag::err_out_of_line_constructor_template_id)
2432 << TemplateId->Name
Douglas Gregora771f462010-03-31 17:46:05 +00002433 << FixItHint::CreateRemoval(
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002434 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Abramo Bagnara4244b432012-01-27 08:46:19 +00002435 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2436 TemplateId->TemplateNameLoc,
2437 getCurScope(),
2438 &SS, false, false,
2439 ParsedType(),
2440 /*IsCtorOrDtorName=*/true,
2441 /*NontrivialTypeSourceInfo=*/true);
2442 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002443 TemplateId->RAngleLoc);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002444 ConsumeToken();
2445 return false;
2446 }
2447
2448 Result.setConstructorTemplateId(TemplateId);
2449 ConsumeToken();
2450 return false;
2451 }
2452
Douglas Gregor7861a802009-11-03 01:35:08 +00002453 // We have already parsed a template-id; consume the annotation token as
2454 // our unqualified-id.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002455 Result.setTemplateId(TemplateId);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002456 TemplateKWLoc = TemplateId->TemplateKWLoc;
Douglas Gregor7861a802009-11-03 01:35:08 +00002457 ConsumeToken();
2458 return false;
2459 }
2460
2461 // unqualified-id:
2462 // operator-function-id
2463 // conversion-function-id
2464 if (Tok.is(tok::kw_operator)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00002465 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor7861a802009-11-03 01:35:08 +00002466 return true;
2467
Alexis Hunted0530f2009-11-28 08:58:14 +00002468 // If we have an operator-function-id or a literal-operator-id and the next
2469 // token is a '<', we may have a
Douglas Gregor71395fa2009-11-04 00:56:37 +00002470 //
2471 // template-id:
2472 // operator-function-id < template-argument-list[opt] >
Alexis Hunted0530f2009-11-28 08:58:14 +00002473 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2474 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002475 (TemplateSpecified || Tok.is(tok::less)))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002476 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00002477 nullptr, SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002478 EnteringContext, ObjectType,
2479 Result, TemplateSpecified);
Craig Topper161e4db2014-05-21 06:02:52 +00002480
Douglas Gregor7861a802009-11-03 01:35:08 +00002481 return false;
2482 }
2483
David Blaikiebbafb8a2012-03-11 07:00:24 +00002484 if (getLangOpts().CPlusPlus &&
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002485 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002486 // C++ [expr.unary.op]p10:
2487 // There is an ambiguity in the unary-expression ~X(), where X is a
2488 // class-name. The ambiguity is resolved in favor of treating ~ as a
2489 // unary complement rather than treating ~X as referring to a destructor.
2490
2491 // Parse the '~'.
2492 SourceLocation TildeLoc = ConsumeToken();
David Blaikieecd8a942011-12-08 16:13:53 +00002493
2494 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2495 DeclSpec DS(AttrFactory);
2496 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2497 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2498 Result.setDestructorName(TildeLoc, Type, EndLoc);
2499 return false;
2500 }
2501 return true;
2502 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002503
2504 // Parse the class-name.
2505 if (Tok.isNot(tok::identifier)) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002506 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00002507 return true;
2508 }
2509
Richard Smithefa6f732014-09-06 02:06:12 +00002510 // If the user wrote ~T::T, correct it to T::~T.
Richard Smith64e033f2015-01-15 00:48:52 +00002511 DeclaratorScopeObj DeclScopeObj(*this, SS);
Richard Smithefa6f732014-09-06 02:06:12 +00002512 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2513 if (SS.isSet()) {
2514 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2515 SS.clear();
2516 }
2517 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2518 return true;
2519 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon)) {
2520 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2521 return true;
2522 }
2523
2524 // Recover as if the tilde had been written before the identifier.
2525 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2526 << FixItHint::CreateRemoval(TildeLoc)
2527 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
Richard Smith64e033f2015-01-15 00:48:52 +00002528
2529 // Temporarily enter the scope for the rest of this function.
2530 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2531 DeclScopeObj.EnterDeclaratorScope();
Richard Smithefa6f732014-09-06 02:06:12 +00002532 }
2533
Douglas Gregor7861a802009-11-03 01:35:08 +00002534 // Parse the class-name (or template-name in a simple-template-id).
2535 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2536 SourceLocation ClassNameLoc = ConsumeToken();
Richard Smithefa6f732014-09-06 02:06:12 +00002537
Douglas Gregorb22ee882010-05-05 05:58:24 +00002538 if (TemplateSpecified || Tok.is(tok::less)) {
John McCallba7bf592010-08-24 05:47:05 +00002539 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002540 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2541 ClassName, ClassNameLoc,
2542 EnteringContext, ObjectType,
2543 Result, TemplateSpecified);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002544 }
Richard Smithefa6f732014-09-06 02:06:12 +00002545
Douglas Gregor7861a802009-11-03 01:35:08 +00002546 // Note that this is a destructor name.
John McCallba7bf592010-08-24 05:47:05 +00002547 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2548 ClassNameLoc, getCurScope(),
2549 SS, ObjectType,
2550 EnteringContext);
Douglas Gregorfe17d252010-02-16 19:09:40 +00002551 if (!Ty)
Douglas Gregor7861a802009-11-03 01:35:08 +00002552 return true;
Douglas Gregorfe17d252010-02-16 19:09:40 +00002553
Douglas Gregor7861a802009-11-03 01:35:08 +00002554 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002555 return false;
2556 }
2557
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002558 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002559 << getLangOpts().CPlusPlus;
Douglas Gregor7861a802009-11-03 01:35:08 +00002560 return true;
2561}
2562
Sebastian Redlbd150f42008-11-21 19:14:01 +00002563/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2564/// memory in a typesafe manner and call constructors.
Mike Stump11289f42009-09-09 15:08:12 +00002565///
Chris Lattner109faf22009-01-04 21:25:24 +00002566/// This method is called to parse the new expression after the optional :: has
2567/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2568/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002569///
2570/// new-expression:
2571/// '::'[opt] 'new' new-placement[opt] new-type-id
2572/// new-initializer[opt]
2573/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2574/// new-initializer[opt]
2575///
2576/// new-placement:
2577/// '(' expression-list ')'
2578///
Sebastian Redl351bb782008-12-02 14:43:59 +00002579/// new-type-id:
2580/// type-specifier-seq new-declarator[opt]
Douglas Gregora3a020a2011-04-15 19:40:02 +00002581/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redl351bb782008-12-02 14:43:59 +00002582///
2583/// new-declarator:
2584/// ptr-operator new-declarator[opt]
2585/// direct-new-declarator
2586///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002587/// new-initializer:
2588/// '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00002589/// [C++0x] braced-init-list
Sebastian Redlbd150f42008-11-21 19:14:01 +00002590///
John McCalldadc5752010-08-24 06:29:42 +00002591ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002592Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2593 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2594 ConsumeToken(); // Consume 'new'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002595
2596 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2597 // second form of new-expression. It can't be a new-type-id.
2598
Benjamin Kramerf0623432012-08-23 22:51:59 +00002599 ExprVector PlacementArgs;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002600 SourceLocation PlacementLParen, PlacementRParen;
2601
Douglas Gregorf2753b32010-07-13 15:54:32 +00002602 SourceRange TypeIdParens;
John McCall084e83d2011-03-24 11:26:52 +00002603 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +00002604 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002605 if (Tok.is(tok::l_paren)) {
2606 // If it turns out to be a placement, we change the type location.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002607 BalancedDelimiterTracker T(*this, tok::l_paren);
2608 T.consumeOpen();
2609 PlacementLParen = T.getOpenLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002610 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002611 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002612 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002613 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002614
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002615 T.consumeClose();
2616 PlacementRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002617 if (PlacementRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002618 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002619 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002620 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002621
Sebastian Redl351bb782008-12-02 14:43:59 +00002622 if (PlacementArgs.empty()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002623 // Reset the placement locations. There was no placement.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002624 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002625 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002626 } else {
2627 // We still need the type.
2628 if (Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002629 BalancedDelimiterTracker T(*this, tok::l_paren);
2630 T.consumeOpen();
Douglas Gregora3a020a2011-04-15 19:40:02 +00002631 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002632 ParseSpecifierQualifierList(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002633 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002634 ParseDeclarator(DeclaratorInfo);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002635 T.consumeClose();
2636 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002637 } else {
Douglas Gregora3a020a2011-04-15 19:40:02 +00002638 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002639 if (ParseCXXTypeSpecifierSeq(DS))
2640 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002641 else {
2642 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002643 ParseDeclaratorInternal(DeclaratorInfo,
2644 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002645 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002646 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002647 }
2648 } else {
Sebastian Redl351bb782008-12-02 14:43:59 +00002649 // A new-type-id is a simplified type-id, where essentially the
2650 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregora3a020a2011-04-15 19:40:02 +00002651 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002652 if (ParseCXXTypeSpecifierSeq(DS))
2653 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002654 else {
2655 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002656 ParseDeclaratorInternal(DeclaratorInfo,
2657 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002658 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002659 }
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002660 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002661 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002662 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002663 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002664
Sebastian Redl6047f072012-02-16 12:22:20 +00002665 ExprResult Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002666
2667 if (Tok.is(tok::l_paren)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00002668 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002669 ExprVector ConstructorArgs;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002670 BalancedDelimiterTracker T(*this, tok::l_paren);
2671 T.consumeOpen();
2672 ConstructorLParen = T.getOpenLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002673 if (Tok.isNot(tok::r_paren)) {
2674 CommaLocsTy CommaLocs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002675 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2676 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
2677 DeclaratorInfo).get();
2678 Actions.CodeCompleteConstructor(getCurScope(),
2679 TypeRep.get()->getCanonicalTypeInternal(),
2680 DeclaratorInfo.getLocEnd(),
2681 ConstructorArgs);
2682 })) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002683 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002684 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002685 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002686 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002687 T.consumeClose();
2688 ConstructorRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002689 if (ConstructorRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002690 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002691 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002692 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002693 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2694 ConstructorRParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002695 ConstructorArgs);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002696 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002697 Diag(Tok.getLocation(),
2698 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl6047f072012-02-16 12:22:20 +00002699 Initializer = ParseBraceInitializer();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002700 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002701 if (Initializer.isInvalid())
2702 return Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002703
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002704 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002705 PlacementArgs, PlacementRParen,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002706 TypeIdParens, DeclaratorInfo, Initializer.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002707}
2708
Sebastian Redlbd150f42008-11-21 19:14:01 +00002709/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2710/// passed to ParseDeclaratorInternal.
2711///
2712/// direct-new-declarator:
2713/// '[' expression ']'
2714/// direct-new-declarator '[' constant-expression ']'
2715///
Chris Lattner109faf22009-01-04 21:25:24 +00002716void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002717 // Parse the array dimensions.
2718 bool first = true;
2719 while (Tok.is(tok::l_square)) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002720 // An array-size expression can't start with a lambda.
2721 if (CheckProhibitedCXX11Attribute())
2722 continue;
2723
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002724 BalancedDelimiterTracker T(*this, tok::l_square);
2725 T.consumeOpen();
2726
John McCalldadc5752010-08-24 06:29:42 +00002727 ExprResult Size(first ? ParseExpression()
Sebastian Redl59b5e512008-12-11 21:36:32 +00002728 : ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002729 if (Size.isInvalid()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002730 // Recover
Alexey Bataevee6507d2013-11-18 08:17:37 +00002731 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002732 return;
2733 }
2734 first = false;
2735
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002736 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00002737
Bill Wendling44426052012-12-20 19:22:21 +00002738 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002739 ParsedAttributes Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002740 MaybeParseCXX11Attributes(Attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002741
John McCall084e83d2011-03-24 11:26:52 +00002742 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall53fa7142010-12-24 02:08:15 +00002743 /*static=*/false, /*star=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002744 Size.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002745 T.getOpenLocation(),
2746 T.getCloseLocation()),
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002747 Attrs, T.getCloseLocation());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002748
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002749 if (T.getCloseLocation().isInvalid())
Sebastian Redlbd150f42008-11-21 19:14:01 +00002750 return;
2751 }
2752}
2753
2754/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2755/// This ambiguity appears in the syntax of the C++ new operator.
2756///
2757/// new-expression:
2758/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2759/// new-initializer[opt]
2760///
2761/// new-placement:
2762/// '(' expression-list ')'
2763///
John McCall37ad5512010-08-23 06:44:23 +00002764bool Parser::ParseExpressionListOrTypeId(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002765 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner109faf22009-01-04 21:25:24 +00002766 Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002767 // The '(' was already consumed.
2768 if (isTypeIdInParens()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00002769 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002770 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002771 ParseDeclarator(D);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002772 return D.isInvalidType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002773 }
2774
2775 // It's not a type, it has to be an expression list.
2776 // Discard the comma locations - ActOnCXXNew has enough parameters.
2777 CommaLocsTy CommaLocs;
2778 return ParseExpressionList(PlacementArgs, CommaLocs);
2779}
2780
2781/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2782/// to free memory allocated by new.
2783///
Chris Lattner109faf22009-01-04 21:25:24 +00002784/// This method is called to parse the 'delete' expression after the optional
2785/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2786/// and "Start" is its location. Otherwise, "Start" is the location of the
2787/// 'delete' token.
2788///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002789/// delete-expression:
2790/// '::'[opt] 'delete' cast-expression
2791/// '::'[opt] 'delete' '[' ']' cast-expression
John McCalldadc5752010-08-24 06:29:42 +00002792ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002793Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2794 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2795 ConsumeToken(); // Consume 'delete'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002796
2797 // Array delete?
2798 bool ArrayDelete = false;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002799 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith10c60722012-08-09 19:01:51 +00002800 // C++11 [expr.delete]p1:
2801 // Whenever the delete keyword is followed by empty square brackets, it
2802 // shall be interpreted as [array delete].
2803 // [Footnote: A lambda expression with a lambda-introducer that consists
2804 // of empty square brackets can follow the delete keyword if
2805 // the lambda expression is enclosed in parentheses.]
2806 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2807 // lambda-introducer.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002808 ArrayDelete = true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002809 BalancedDelimiterTracker T(*this, tok::l_square);
2810
2811 T.consumeOpen();
2812 T.consumeClose();
2813 if (T.getCloseLocation().isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00002814 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002815 }
2816
John McCalldadc5752010-08-24 06:29:42 +00002817 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002818 if (Operand.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002819 return Operand;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002820
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002821 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002822}
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002823
Douglas Gregor29c42f22012-02-24 07:38:34 +00002824static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2825 switch (kind) {
2826 default: llvm_unreachable("Not a known type trait");
Alp Toker95e7ff22014-01-01 05:57:51 +00002827#define TYPE_TRAIT_1(Spelling, Name, Key) \
2828case tok::kw_ ## Spelling: return UTT_ ## Name;
Alp Tokercbb90342013-12-13 20:49:58 +00002829#define TYPE_TRAIT_2(Spelling, Name, Key) \
2830case tok::kw_ ## Spelling: return BTT_ ## Name;
2831#include "clang/Basic/TokenKinds.def"
Alp Toker40f9b1c2013-12-12 21:23:03 +00002832#define TYPE_TRAIT_N(Spelling, Name, Key) \
2833 case tok::kw_ ## Spelling: return TT_ ## Name;
2834#include "clang/Basic/TokenKinds.def"
Douglas Gregor29c42f22012-02-24 07:38:34 +00002835 }
2836}
2837
John Wiegley6242b6a2011-04-28 00:16:57 +00002838static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2839 switch(kind) {
2840 default: llvm_unreachable("Not a known binary type trait");
2841 case tok::kw___array_rank: return ATT_ArrayRank;
2842 case tok::kw___array_extent: return ATT_ArrayExtent;
2843 }
2844}
2845
John Wiegleyf9f65842011-04-25 06:54:41 +00002846static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2847 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002848 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegleyf9f65842011-04-25 06:54:41 +00002849 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2850 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2851 }
2852}
2853
Alp Toker40f9b1c2013-12-12 21:23:03 +00002854static unsigned TypeTraitArity(tok::TokenKind kind) {
2855 switch (kind) {
2856 default: llvm_unreachable("Not a known type trait");
2857#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2858#include "clang/Basic/TokenKinds.def"
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002859 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002860}
2861
Douglas Gregor29c42f22012-02-24 07:38:34 +00002862/// \brief Parse the built-in type-trait pseudo-functions that allow
2863/// implementation of the TR1/C++11 type traits templates.
2864///
2865/// primary-expression:
Alp Toker40f9b1c2013-12-12 21:23:03 +00002866/// unary-type-trait '(' type-id ')'
2867/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor29c42f22012-02-24 07:38:34 +00002868/// type-trait '(' type-id-seq ')'
2869///
2870/// type-id-seq:
2871/// type-id ...[opt] type-id-seq[opt]
2872///
2873ExprResult Parser::ParseTypeTrait() {
Alp Toker40f9b1c2013-12-12 21:23:03 +00002874 tok::TokenKind Kind = Tok.getKind();
2875 unsigned Arity = TypeTraitArity(Kind);
2876
Douglas Gregor29c42f22012-02-24 07:38:34 +00002877 SourceLocation Loc = ConsumeToken();
2878
2879 BalancedDelimiterTracker Parens(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002880 if (Parens.expectAndConsume())
Douglas Gregor29c42f22012-02-24 07:38:34 +00002881 return ExprError();
2882
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002883 SmallVector<ParsedType, 2> Args;
Douglas Gregor29c42f22012-02-24 07:38:34 +00002884 do {
2885 // Parse the next type.
2886 TypeResult Ty = ParseTypeName();
2887 if (Ty.isInvalid()) {
2888 Parens.skipToEnd();
2889 return ExprError();
2890 }
2891
2892 // Parse the ellipsis, if present.
2893 if (Tok.is(tok::ellipsis)) {
2894 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2895 if (Ty.isInvalid()) {
2896 Parens.skipToEnd();
2897 return ExprError();
2898 }
2899 }
2900
2901 // Add this type to the list of arguments.
2902 Args.push_back(Ty.get());
Alp Tokera3ebe6e2013-12-17 14:12:37 +00002903 } while (TryConsumeToken(tok::comma));
2904
Douglas Gregor29c42f22012-02-24 07:38:34 +00002905 if (Parens.consumeClose())
2906 return ExprError();
Alp Toker40f9b1c2013-12-12 21:23:03 +00002907
2908 SourceLocation EndLoc = Parens.getCloseLocation();
2909
2910 if (Arity && Args.size() != Arity) {
2911 Diag(EndLoc, diag::err_type_trait_arity)
2912 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
2913 return ExprError();
2914 }
2915
2916 if (!Arity && Args.empty()) {
2917 Diag(EndLoc, diag::err_type_trait_arity)
2918 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
2919 return ExprError();
2920 }
2921
Alp Toker88f64e62013-12-13 21:19:30 +00002922 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
Douglas Gregor29c42f22012-02-24 07:38:34 +00002923}
2924
John Wiegley6242b6a2011-04-28 00:16:57 +00002925/// ParseArrayTypeTrait - Parse the built-in array type-trait
2926/// pseudo-functions.
2927///
2928/// primary-expression:
2929/// [Embarcadero] '__array_rank' '(' type-id ')'
2930/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2931///
2932ExprResult Parser::ParseArrayTypeTrait() {
2933 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2934 SourceLocation Loc = ConsumeToken();
2935
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002936 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002937 if (T.expectAndConsume())
John Wiegley6242b6a2011-04-28 00:16:57 +00002938 return ExprError();
2939
2940 TypeResult Ty = ParseTypeName();
2941 if (Ty.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002942 SkipUntil(tok::comma, StopAtSemi);
2943 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00002944 return ExprError();
2945 }
2946
2947 switch (ATT) {
2948 case ATT_ArrayRank: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002949 T.consumeClose();
Craig Topper161e4db2014-05-21 06:02:52 +00002950 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002951 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00002952 }
2953 case ATT_ArrayExtent: {
Alp Toker383d2c42014-01-01 03:08:43 +00002954 if (ExpectAndConsume(tok::comma)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002955 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00002956 return ExprError();
2957 }
2958
2959 ExprResult DimExpr = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002960 T.consumeClose();
John Wiegley6242b6a2011-04-28 00:16:57 +00002961
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002962 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2963 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00002964 }
John Wiegley6242b6a2011-04-28 00:16:57 +00002965 }
David Blaikiee4d798f2012-01-20 21:50:17 +00002966 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley6242b6a2011-04-28 00:16:57 +00002967}
2968
John Wiegleyf9f65842011-04-25 06:54:41 +00002969/// ParseExpressionTrait - Parse built-in expression-trait
2970/// pseudo-functions like __is_lvalue_expr( xxx ).
2971///
2972/// primary-expression:
2973/// [Embarcadero] expression-trait '(' expression ')'
2974///
2975ExprResult Parser::ParseExpressionTrait() {
2976 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2977 SourceLocation Loc = ConsumeToken();
2978
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002979 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002980 if (T.expectAndConsume())
John Wiegleyf9f65842011-04-25 06:54:41 +00002981 return ExprError();
2982
2983 ExprResult Expr = ParseExpression();
2984
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002985 T.consumeClose();
John Wiegleyf9f65842011-04-25 06:54:41 +00002986
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002987 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2988 T.getCloseLocation());
John Wiegleyf9f65842011-04-25 06:54:41 +00002989}
2990
2991
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002992/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2993/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2994/// based on the context past the parens.
John McCalldadc5752010-08-24 06:29:42 +00002995ExprResult
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002996Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallba7bf592010-08-24 05:47:05 +00002997 ParsedType &CastTy,
Richard Smith87e11a42014-05-15 02:43:47 +00002998 BalancedDelimiterTracker &Tracker,
2999 ColonProtectionRAIIObject &ColonProt) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003000 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003001 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3002 assert(isTypeIdInParens() && "Not a type-id!");
3003
John McCalldadc5752010-08-24 06:29:42 +00003004 ExprResult Result(true);
John McCallba7bf592010-08-24 05:47:05 +00003005 CastTy = ParsedType();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003006
3007 // We need to disambiguate a very ugly part of the C++ syntax:
3008 //
3009 // (T())x; - type-id
3010 // (T())*x; - type-id
3011 // (T())/x; - expression
3012 // (T()); - expression
3013 //
3014 // The bad news is that we cannot use the specialized tentative parser, since
3015 // it can only verify that the thing inside the parens can be parsed as
3016 // type-id, it is not useful for determining the context past the parens.
3017 //
3018 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidis24ad6922009-05-22 15:12:46 +00003019 // making any unnecessary Action calls.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003020 //
3021 // It uses a scheme similar to parsing inline methods. The parenthesized
3022 // tokens are cached, the context that follows is determined (possibly by
3023 // parsing a cast-expression), and then we re-introduce the cached tokens
3024 // into the token stream and parse them appropriately.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003025
Mike Stump11289f42009-09-09 15:08:12 +00003026 ParenParseOption ParseAs;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003027 CachedTokens Toks;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003028
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003029 // Store the tokens of the parentheses. We will parse them after we determine
3030 // the context that follows them.
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +00003031 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003032 // We didn't find the ')' we expected.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003033 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003034 return ExprError();
3035 }
3036
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003037 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003038 ParseAs = CompoundLiteral;
3039 } else {
3040 bool NotCastExpr;
Eli Friedmancf7530f2009-05-25 19:41:42 +00003041 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3042 NotCastExpr = true;
3043 } else {
3044 // Try parsing the cast-expression that may follow.
3045 // If it is not a cast-expression, NotCastExpr will be true and no token
3046 // will be consumed.
Richard Smith87e11a42014-05-15 02:43:47 +00003047 ColonProt.restore();
Eli Friedmancf7530f2009-05-25 19:41:42 +00003048 Result = ParseCastExpression(false/*isUnaryExpression*/,
3049 false/*isAddressofOperand*/,
John McCallba7bf592010-08-24 05:47:05 +00003050 NotCastExpr,
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003051 // type-id has priority.
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00003052 IsTypeCast);
Eli Friedmancf7530f2009-05-25 19:41:42 +00003053 }
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003054
3055 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3056 // an expression.
3057 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003058 }
3059
Mike Stump11289f42009-09-09 15:08:12 +00003060 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003061 Toks.push_back(Tok);
3062 // Re-enter the stored parenthesized tokens into the token stream, so we may
3063 // parse them now.
3064 PP.EnterTokenStream(Toks.data(), Toks.size(),
3065 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
3066 // Drop the current token and bring the first cached one. It's the same token
3067 // as when we entered this function.
3068 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003069
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003070 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003071 // Parse the type declarator.
3072 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003073 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
Richard Smith87e11a42014-05-15 02:43:47 +00003074 {
3075 ColonProtectionRAIIObject InnerColonProtection(*this);
3076 ParseSpecifierQualifierList(DS);
3077 ParseDeclarator(DeclaratorInfo);
3078 }
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003079
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003080 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003081 Tracker.consumeClose();
Richard Smith87e11a42014-05-15 02:43:47 +00003082 ColonProt.restore();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003083
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003084 if (ParseAs == CompoundLiteral) {
3085 ExprType = CompoundLiteral;
Richard Smithaba8b362014-05-15 02:51:15 +00003086 if (DeclaratorInfo.isInvalidType())
3087 return ExprError();
3088
3089 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Richard Smith87e11a42014-05-15 02:43:47 +00003090 return ParseCompoundLiteralExpression(Ty.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003091 Tracker.getOpenLocation(),
3092 Tracker.getCloseLocation());
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003093 }
Mike Stump11289f42009-09-09 15:08:12 +00003094
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003095 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3096 assert(ParseAs == CastExpr);
3097
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003098 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003099 return ExprError();
3100
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003101 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003102 if (!Result.isInvalid())
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003103 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3104 DeclaratorInfo, CastTy,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003105 Tracker.getCloseLocation(), Result.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003106 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003107 }
Mike Stump11289f42009-09-09 15:08:12 +00003108
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003109 // Not a compound literal, and not followed by a cast-expression.
3110 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003111
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003112 ExprType = SimpleExpr;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003113 Result = ParseExpression();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003114 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003115 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003116 Tok.getLocation(), Result.get());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003117
3118 // Match the ')'.
3119 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003120 SkipUntil(tok::r_paren, StopAtSemi);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003121 return ExprError();
3122 }
Mike Stump11289f42009-09-09 15:08:12 +00003123
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003124 Tracker.consumeClose();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003125 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003126}