blob: ed9f75d7b4de2c036f64bc411cc7558af6c82b10 [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;
Benjamin Kramerd503c1c2015-03-08 18:11:59 +0000121 RParen.setLocation(SourceLocation());
David Majnemer6ca445e2014-12-17 01:39:22 +0000122 // Do we have a ')' ?
123 NextTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : GetLookAheadToken(1);
124 if (NextTok.is(tok::r_paren)) {
125 RParen = NextTok;
126 // Eat the '*' if it is present.
127 if (StarTok.is(tok::star))
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000128 ConsumeToken();
David Majnemer6ca445e2014-12-17 01:39:22 +0000129 // Eat the identifier.
130 ConsumeToken();
131 // Add the identifier token back.
132 PP.EnterToken(IdentifierTok);
133 // Add the '*' back if it was present.
134 if (StarTok.is(tok::star))
135 PP.EnterToken(StarTok);
136 // Eat the ')'.
137 ConsumeParen();
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000138 }
139
David Majnemer6ca445e2014-12-17 01:39:22 +0000140 Diag(LParen.getLocation(), diag::err_paren_after_colon_colon)
141 << FixItHint::CreateRemoval(LParen.getLocation())
142 << FixItHint::CreateRemoval(RParen.getLocation());
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000143}
144
Mike Stump11289f42009-09-09 15:08:12 +0000145/// \brief Parse global scope or nested-name-specifier if present.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000146///
147/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
Mike Stump11289f42009-09-09 15:08:12 +0000148/// may be preceded by '::'). Note that this routine will not parse ::new or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000149/// ::delete; it will just leave them in the token stream.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000150///
151/// '::'[opt] nested-name-specifier
152/// '::'
153///
154/// nested-name-specifier:
155/// type-name '::'
156/// namespace-name '::'
157/// nested-name-specifier identifier '::'
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000158/// nested-name-specifier 'template'[opt] simple-template-id '::'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000159///
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000160///
Mike Stump11289f42009-09-09 15:08:12 +0000161/// \param SS the scope specifier that will be set to the parsed
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000162/// nested-name-specifier (or empty)
163///
Mike Stump11289f42009-09-09 15:08:12 +0000164/// \param ObjectType if this nested-name-specifier is being parsed following
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000165/// the "." or "->" of a member access expression, this parameter provides the
166/// type of the object whose members are being accessed.
167///
168/// \param EnteringContext whether we will be entering into the context of
169/// the nested-name-specifier after parsing it.
170///
Douglas Gregore610ada2010-02-24 18:44:31 +0000171/// \param MayBePseudoDestructor When non-NULL, points to a flag that
172/// indicates whether this nested-name-specifier may be part of a
173/// pseudo-destructor name. In this case, the flag will be set false
174/// if we don't actually end up parsing a destructor name. Moreorover,
175/// if we do end up determining that we are parsing a destructor name,
176/// the last component of the nested-name-specifier is not parsed as
177/// part of the scope specifier.
Richard Smith7447af42013-03-26 01:15:19 +0000178///
179/// \param IsTypename If \c true, this nested-name-specifier is known to be
180/// part of a type name. This is used to improve error recovery.
181///
182/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
183/// filled in with the leading identifier in the last component of the
184/// nested-name-specifier, if any.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000185///
John McCall1f476a12010-02-26 08:45:28 +0000186/// \returns true if there was an error parsing a scope specifier
Douglas Gregore861bac2009-08-25 22:51:20 +0000187bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +0000188 ParsedType ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000189 bool EnteringContext,
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000190 bool *MayBePseudoDestructor,
Richard Smith7447af42013-03-26 01:15:19 +0000191 bool IsTypename,
192 IdentifierInfo **LastII) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000193 assert(getLangOpts().CPlusPlus &&
Chris Lattnerb5134c02009-01-05 01:24:05 +0000194 "Call sites of this function should be guarded by checking for C++");
Mike Stump11289f42009-09-09 15:08:12 +0000195
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000196 if (Tok.is(tok::annot_cxxscope)) {
Richard Smith7447af42013-03-26 01:15:19 +0000197 assert(!LastII && "want last identifier but have already annotated scope");
Nico Weberc60aa712015-02-16 22:32:46 +0000198 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
Douglas Gregor869ad452011-02-24 17:54:50 +0000199 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
200 Tok.getAnnotationRange(),
201 SS);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000202 ConsumeToken();
John McCall1f476a12010-02-26 08:45:28 +0000203 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000204 }
Chris Lattnerf9b2cd42009-01-04 21:14:15 +0000205
Larisse Voufob959c3c2013-08-06 05:49:26 +0000206 if (Tok.is(tok::annot_template_id)) {
207 // If the current token is an annotated template id, it may already have
208 // a scope specifier. Restore it.
209 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
210 SS = TemplateId->SS;
211 }
212
Nico Weberc60aa712015-02-16 22:32:46 +0000213 // Has to happen before any "return false"s in this function.
214 bool CheckForDestructor = false;
215 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
216 CheckForDestructor = true;
217 *MayBePseudoDestructor = false;
218 }
219
Richard Smith7447af42013-03-26 01:15:19 +0000220 if (LastII)
Craig Topper161e4db2014-05-21 06:02:52 +0000221 *LastII = nullptr;
Richard Smith7447af42013-03-26 01:15:19 +0000222
Douglas Gregor7f741122009-02-25 19:37:18 +0000223 bool HasScopeSpecifier = false;
224
Chris Lattner8a7d10d2009-01-05 03:55:46 +0000225 if (Tok.is(tok::coloncolon)) {
226 // ::new and ::delete aren't nested-name-specifiers.
227 tok::TokenKind NextKind = NextToken().getKind();
228 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
229 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000230
David Majnemere8fb28f2014-12-29 19:19:18 +0000231 if (NextKind == tok::l_brace) {
232 // It is invalid to have :: {, consume the scope qualifier and pretend
233 // like we never saw it.
234 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
235 } else {
236 // '::' - Global scope qualifier.
237 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
238 return true;
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000239
David Majnemere8fb28f2014-12-29 19:19:18 +0000240 CheckForLParenAfterColonColon();
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000241
David Majnemere8fb28f2014-12-29 19:19:18 +0000242 HasScopeSpecifier = true;
243 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000244 }
245
Nikola Smiljanic67860242014-09-26 00:28:20 +0000246 if (Tok.is(tok::kw___super)) {
247 SourceLocation SuperLoc = ConsumeToken();
248 if (!Tok.is(tok::coloncolon)) {
249 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
250 return true;
251 }
252
253 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
254 }
255
Richard Smitha9d10012014-10-04 01:57:39 +0000256 if (!HasScopeSpecifier &&
257 (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))) {
David Blaikie15a430a2011-12-04 05:04:18 +0000258 DeclSpec DS(AttrFactory);
259 SourceLocation DeclLoc = Tok.getLocation();
260 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000261
262 SourceLocation CCLoc;
263 if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
David Blaikie15a430a2011-12-04 05:04:18 +0000264 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
265 return false;
266 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000267
David Blaikie15a430a2011-12-04 05:04:18 +0000268 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
269 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
270
271 HasScopeSpecifier = true;
272 }
273
Douglas Gregor7f741122009-02-25 19:37:18 +0000274 while (true) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000275 if (HasScopeSpecifier) {
276 // C++ [basic.lookup.classref]p5:
277 // If the qualified-id has the form
Douglas Gregor308047d2009-09-09 00:23:06 +0000278 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000279 // ::class-name-or-namespace-name::...
Douglas Gregor308047d2009-09-09 00:23:06 +0000280 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000281 // the class-name-or-namespace-name is looked up in global scope as a
282 // class-name or namespace-name.
283 //
284 // To implement this, we clear out the object type as soon as we've
285 // seen a leading '::' or part of a nested-name-specifier.
John McCallba7bf592010-08-24 05:47:05 +0000286 ObjectType = ParsedType();
Douglas Gregor2436e712009-09-17 21:32:03 +0000287
288 if (Tok.is(tok::code_completion)) {
289 // Code completion for a nested-name-specifier, where the code
290 // code completion token follows the '::'.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000291 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
Argyrios Kyrtzidis7d94c922011-04-23 01:04:12 +0000292 // Include code completion token into the range of the scope otherwise
293 // when we try to annotate the scope tokens the dangling code completion
294 // token will cause assertion in
295 // Preprocessor::AnnotatePreviousCachedTokens.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000296 SS.setEndLoc(Tok.getLocation());
297 cutOffParsing();
298 return true;
Douglas Gregor2436e712009-09-17 21:32:03 +0000299 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000300 }
Mike Stump11289f42009-09-09 15:08:12 +0000301
Douglas Gregor7f741122009-02-25 19:37:18 +0000302 // nested-name-specifier:
Chris Lattner0eed3a62009-06-26 03:47:46 +0000303 // nested-name-specifier 'template'[opt] simple-template-id '::'
304
305 // Parse the optional 'template' keyword, then make sure we have
306 // 'identifier <' after it.
307 if (Tok.is(tok::kw_template)) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000308 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedman2624be42009-08-29 04:08:08 +0000309 // nested-name-specifier, since they aren't allowed to start with
310 // 'template'.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000311 if (!HasScopeSpecifier && !ObjectType)
Eli Friedman2624be42009-08-29 04:08:08 +0000312 break;
313
Douglas Gregor120635b2009-11-11 16:39:34 +0000314 TentativeParsingAction TPA(*this);
Chris Lattner0eed3a62009-06-26 03:47:46 +0000315 SourceLocation TemplateKWLoc = ConsumeToken();
Richard Smithd091dc12013-12-05 00:58:33 +0000316
Douglas Gregor71395fa2009-11-04 00:56:37 +0000317 UnqualifiedId TemplateName;
318 if (Tok.is(tok::identifier)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000319 // Consume the identifier.
Douglas Gregor120635b2009-11-11 16:39:34 +0000320 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregor71395fa2009-11-04 00:56:37 +0000321 ConsumeToken();
322 } else if (Tok.is(tok::kw_operator)) {
Richard Smithd091dc12013-12-05 00:58:33 +0000323 // We don't need to actually parse the unqualified-id in this case,
324 // because a simple-template-id cannot start with 'operator', but
325 // go ahead and parse it anyway for consistency with the case where
326 // we already annotated the template-id.
327 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor120635b2009-11-11 16:39:34 +0000328 TemplateName)) {
329 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000330 break;
Douglas Gregor120635b2009-11-11 16:39:34 +0000331 }
Richard Smithd091dc12013-12-05 00:58:33 +0000332
Alexis Hunted0530f2009-11-28 08:58:14 +0000333 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
334 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000335 Diag(TemplateName.getSourceRange().getBegin(),
336 diag::err_id_after_template_in_nested_name_spec)
337 << TemplateName.getSourceRange();
Douglas Gregor120635b2009-11-11 16:39:34 +0000338 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000339 break;
340 }
341 } else {
Douglas Gregor120635b2009-11-11 16:39:34 +0000342 TPA.Revert();
Chris Lattner0eed3a62009-06-26 03:47:46 +0000343 break;
344 }
Mike Stump11289f42009-09-09 15:08:12 +0000345
Douglas Gregor120635b2009-11-11 16:39:34 +0000346 // If the next token is not '<', we have a qualified-id that refers
347 // to a template name, such as T::template apply, but is not a
348 // template-id.
349 if (Tok.isNot(tok::less)) {
350 TPA.Revert();
351 break;
352 }
353
354 // Commit to parsing the template-id.
355 TPA.Commit();
Douglas Gregorbb119652010-06-16 23:00:59 +0000356 TemplateTy Template;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000357 if (TemplateNameKind TNK
358 = Actions.ActOnDependentTemplateName(getCurScope(),
359 SS, TemplateKWLoc, TemplateName,
360 ObjectType, EnteringContext,
361 Template)) {
362 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
363 TemplateName, false))
Douglas Gregorbb119652010-06-16 23:00:59 +0000364 return true;
365 } else
John McCall1f476a12010-02-26 08:45:28 +0000366 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000367
Chris Lattner0eed3a62009-06-26 03:47:46 +0000368 continue;
369 }
Mike Stump11289f42009-09-09 15:08:12 +0000370
Douglas Gregor7f741122009-02-25 19:37:18 +0000371 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump11289f42009-09-09 15:08:12 +0000372 // We have
Douglas Gregor7f741122009-02-25 19:37:18 +0000373 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000374 // template-id '::'
Douglas Gregor7f741122009-02-25 19:37:18 +0000375 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000376 // So we need to check whether the template-id is a simple-template-id of
377 // the right kind (it should name a type or be dependent), and then
Douglas Gregorb67535d2009-03-31 00:43:58 +0000378 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +0000379 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregore610ada2010-02-24 18:44:31 +0000380 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
381 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000382 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000383 }
384
Richard Smith7447af42013-03-26 01:15:19 +0000385 if (LastII)
386 *LastII = TemplateId->Name;
387
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000388 // Consume the template-id token.
389 ConsumeToken();
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000390
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000391 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
392 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000393
David Blaikie8c045bc2011-11-07 03:30:03 +0000394 HasScopeSpecifier = true;
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000395
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000396 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000397 TemplateId->NumArgs);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000398
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000399 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000400 SS,
401 TemplateId->TemplateKWLoc,
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000402 TemplateId->Template,
403 TemplateId->TemplateNameLoc,
404 TemplateId->LAngleLoc,
405 TemplateArgsPtr,
406 TemplateId->RAngleLoc,
407 CCLoc,
408 EnteringContext)) {
409 SourceLocation StartLoc
410 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
411 : TemplateId->TemplateNameLoc;
412 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner704edfb2009-06-26 03:45:46 +0000413 }
Argyrios Kyrtzidis13935672011-05-03 18:45:38 +0000414
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000415 continue;
Douglas Gregor7f741122009-02-25 19:37:18 +0000416 }
417
Chris Lattnere2355f72009-06-26 03:52:38 +0000418 // The rest of the nested-name-specifier possibilities start with
419 // tok::identifier.
420 if (Tok.isNot(tok::identifier))
421 break;
422
423 IdentifierInfo &II = *Tok.getIdentifierInfo();
424
425 // nested-name-specifier:
426 // type-name '::'
427 // namespace-name '::'
428 // nested-name-specifier identifier '::'
429 Token Next = NextToken();
Chris Lattner1c428032009-12-07 01:36:53 +0000430
431 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
432 // and emit a fixit hint for it.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000433 if (Next.is(tok::colon) && !ColonIsSacred) {
Douglas Gregor90c99722011-02-24 00:17:56 +0000434 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
435 Tok.getLocation(),
436 Next.getLocation(), ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000437 EnteringContext) &&
438 // If the token after the colon isn't an identifier, it's still an
439 // error, but they probably meant something else strange so don't
440 // recover like this.
441 PP.LookAhead(1).is(tok::identifier)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000442 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
Douglas Gregora771f462010-03-31 17:46:05 +0000443 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregor90d554e2010-02-21 18:36:56 +0000444 // Recover as if the user wrote '::'.
445 Next.setKind(tok::coloncolon);
446 }
Chris Lattner1c428032009-12-07 01:36:53 +0000447 }
David Majnemerf58efd92014-12-29 23:12:23 +0000448
449 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
450 // It is invalid to have :: {, consume the scope qualifier and pretend
451 // like we never saw it.
452 Token Identifier = Tok; // Stash away the identifier.
453 ConsumeToken(); // Eat the identifier, current token is now '::'.
David Majnemerec3f49d2014-12-29 23:24:27 +0000454 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
455 << tok::identifier;
David Majnemerf58efd92014-12-29 23:12:23 +0000456 UnconsumeToken(Identifier); // Stick the identifier back.
457 Next = NextToken(); // Point Next at the '{' token.
458 }
459
Chris Lattnere2355f72009-06-26 03:52:38 +0000460 if (Next.is(tok::coloncolon)) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +0000461 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Nico Weber61281fa2014-07-26 22:15:25 +0000462 !Actions.isNonTypeNestedNameSpecifier(
463 getCurScope(), SS, Tok.getLocation(), II, ObjectType)) {
Douglas Gregore610ada2010-02-24 18:44:31 +0000464 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000465 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000466 }
467
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000468 if (ColonIsSacred) {
469 const Token &Next2 = GetLookAheadToken(2);
470 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
471 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
472 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
473 << Next2.getName()
474 << FixItHint::CreateReplacement(Next.getLocation(), ":");
475 Token ColonColon;
476 PP.Lex(ColonColon);
477 ColonColon.setKind(tok::colon);
478 PP.EnterToken(ColonColon);
479 break;
480 }
481 }
482
Richard Smith7447af42013-03-26 01:15:19 +0000483 if (LastII)
484 *LastII = &II;
485
Chris Lattnere2355f72009-06-26 03:52:38 +0000486 // We have an identifier followed by a '::'. Lookup this name
487 // as the name in a nested-name-specifier.
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000488 Token Identifier = Tok;
Chris Lattnere2355f72009-06-26 03:52:38 +0000489 SourceLocation IdLoc = ConsumeToken();
Chris Lattner1c428032009-12-07 01:36:53 +0000490 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
491 "NextToken() not working properly!");
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000492 Token ColonColon = Tok;
Chris Lattnere2355f72009-06-26 03:52:38 +0000493 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000494
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000495 CheckForLParenAfterColonColon();
496
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000497 bool IsCorrectedToColon = false;
Craig Topper161e4db2014-05-21 06:02:52 +0000498 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
Douglas Gregor90c99722011-02-24 00:17:56 +0000499 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000500 ObjectType, EnteringContext, SS,
501 false, CorrectionFlagPtr)) {
502 // Identifier is not recognized as a nested name, but we can have
503 // mistyped '::' instead of ':'.
504 if (CorrectionFlagPtr && IsCorrectedToColon) {
505 ColonColon.setKind(tok::colon);
506 PP.EnterToken(Tok);
507 PP.EnterToken(ColonColon);
508 Tok = Identifier;
509 break;
510 }
Douglas Gregor90c99722011-02-24 00:17:56 +0000511 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000512 }
513 HasScopeSpecifier = true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000514 continue;
515 }
Mike Stump11289f42009-09-09 15:08:12 +0000516
Richard Trieu01fc0012011-09-19 19:01:00 +0000517 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smith55858492011-04-14 21:45:45 +0000518
Chris Lattnere2355f72009-06-26 03:52:38 +0000519 // nested-name-specifier:
520 // type-name '<'
521 if (Next.is(tok::less)) {
522 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000523 UnqualifiedId TemplateName;
524 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor786123d2010-05-21 23:18:07 +0000525 bool MemberOfUnknownSpecialization;
Douglas Gregor0be31a22010-07-02 17:43:08 +0000526 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000527 /*hasTemplateKeyword=*/false,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000528 TemplateName,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000529 ObjectType,
Douglas Gregore861bac2009-08-25 22:51:20 +0000530 EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000531 Template,
532 MemberOfUnknownSpecialization)) {
David Blaikie8c045bc2011-11-07 03:30:03 +0000533 // We have found a template name, so annotate this token
Chris Lattnere2355f72009-06-26 03:52:38 +0000534 // with a template-id annotation. We do not permit the
535 // template-id to be translated into a type annotation,
536 // because some clients (e.g., the parsing of class template
537 // specializations) still want to see the original template-id
538 // token.
Douglas Gregor71395fa2009-11-04 00:56:37 +0000539 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000540 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
541 TemplateName, false))
John McCall1f476a12010-02-26 08:45:28 +0000542 return true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000543 continue;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000544 }
545
Douglas Gregor20c38a72010-05-21 23:43:39 +0000546 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000547 (IsTypename || IsTemplateArgumentList(1))) {
Douglas Gregor20c38a72010-05-21 23:43:39 +0000548 // We have something like t::getAs<T>, where getAs is a
549 // member of an unknown specialization. However, this will only
550 // parse correctly as a template, so suggest the keyword 'template'
551 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000552 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000553 if (getLangOpts().MicrosoftExt)
Francois Pichet93921652011-04-22 08:25:24 +0000554 DiagID = diag::warn_missing_dependent_template_keyword;
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000555
556 Diag(Tok.getLocation(), DiagID)
Douglas Gregor20c38a72010-05-21 23:43:39 +0000557 << II.getName()
558 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
559
Douglas Gregorbb119652010-06-16 23:00:59 +0000560 if (TemplateNameKind TNK
Douglas Gregor0be31a22010-07-02 17:43:08 +0000561 = Actions.ActOnDependentTemplateName(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000562 SS, SourceLocation(),
Douglas Gregorbb119652010-06-16 23:00:59 +0000563 TemplateName, ObjectType,
564 EnteringContext, Template)) {
565 // Consume the identifier.
566 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000567 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
568 TemplateName, false))
569 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000570 }
571 else
Douglas Gregor20c38a72010-05-21 23:43:39 +0000572 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000573
Douglas Gregor20c38a72010-05-21 23:43:39 +0000574 continue;
Chris Lattnere2355f72009-06-26 03:52:38 +0000575 }
576 }
577
Douglas Gregor7f741122009-02-25 19:37:18 +0000578 // We don't have any tokens that form the beginning of a
579 // nested-name-specifier, so we're done.
580 break;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000581 }
Mike Stump11289f42009-09-09 15:08:12 +0000582
Douglas Gregore610ada2010-02-24 18:44:31 +0000583 // Even if we didn't see any pieces of a nested-name-specifier, we
584 // still check whether there is a tilde in this position, which
585 // indicates a potential pseudo-destructor.
586 if (CheckForDestructor && Tok.is(tok::tilde))
587 *MayBePseudoDestructor = true;
588
John McCall1f476a12010-02-26 08:45:28 +0000589 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000590}
591
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000592ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
593 Token &Replacement) {
594 SourceLocation TemplateKWLoc;
595 UnqualifiedId Name;
596 if (ParseUnqualifiedId(SS,
597 /*EnteringContext=*/false,
598 /*AllowDestructorName=*/false,
599 /*AllowConstructorName=*/false,
600 /*ObjectType=*/ParsedType(), TemplateKWLoc, Name))
601 return ExprError();
602
603 // This is only the direct operand of an & operator if it is not
604 // followed by a postfix-expression suffix.
605 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
606 isAddressOfOperand = false;
607
608 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
609 Tok.is(tok::l_paren), isAddressOfOperand,
610 nullptr, /*IsInlineAsmIdentifier=*/false,
611 &Replacement);
612}
613
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000614/// ParseCXXIdExpression - Handle id-expression.
615///
616/// id-expression:
617/// unqualified-id
618/// qualified-id
619///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000620/// qualified-id:
621/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
622/// '::' identifier
623/// '::' operator-function-id
Douglas Gregora727cb92009-06-30 22:34:41 +0000624/// '::' template-id
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000625///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000626/// NOTE: The standard specifies that, for qualified-id, the parser does not
627/// expect:
628///
629/// '::' conversion-function-id
630/// '::' '~' class-name
631///
632/// This may cause a slight inconsistency on diagnostics:
633///
634/// class C {};
635/// namespace A {}
636/// void f() {
637/// :: A :: ~ C(); // Some Sema error about using destructor with a
638/// // namespace.
639/// :: ~ C(); // Some Parser error like 'unexpected ~'.
640/// }
641///
642/// We simplify the parser a bit and make it work like:
643///
644/// qualified-id:
645/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
646/// '::' unqualified-id
647///
648/// That way Sema can handle and report similar errors for namespaces and the
649/// global scope.
650///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000651/// The isAddressOfOperand parameter indicates that this id-expression is a
652/// direct operand of the address-of operator. This is, besides member contexts,
653/// the only place where a qualified-id naming a non-static class member may
654/// appear.
655///
John McCalldadc5752010-08-24 06:29:42 +0000656ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000657 // qualified-id:
658 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
659 // '::' unqualified-id
660 //
661 CXXScopeSpec SS;
Douglas Gregordf593fb2011-11-07 17:33:42 +0000662 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000663
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000664 Token Replacement;
Nico Weber01a46ad2015-02-15 06:15:40 +0000665 ExprResult Result =
666 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000667 if (Result.isUnset()) {
668 // If the ExprResult is valid but null, then typo correction suggested a
669 // keyword replacement that needs to be reparsed.
670 UnconsumeToken(Replacement);
671 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
672 }
673 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
674 "for a previous keyword suggestion");
675 return Result;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000676}
677
Richard Smith21b3ab42013-05-09 21:36:41 +0000678/// ParseLambdaExpression - Parse a C++11 lambda expression.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000679///
680/// lambda-expression:
681/// lambda-introducer lambda-declarator[opt] compound-statement
682///
683/// lambda-introducer:
684/// '[' lambda-capture[opt] ']'
685///
686/// lambda-capture:
687/// capture-default
688/// capture-list
689/// capture-default ',' capture-list
690///
691/// capture-default:
692/// '&'
693/// '='
694///
695/// capture-list:
696/// capture
697/// capture-list ',' capture
698///
699/// capture:
Richard Smith21b3ab42013-05-09 21:36:41 +0000700/// simple-capture
701/// init-capture [C++1y]
702///
703/// simple-capture:
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000704/// identifier
705/// '&' identifier
706/// 'this'
707///
Richard Smith21b3ab42013-05-09 21:36:41 +0000708/// init-capture: [C++1y]
709/// identifier initializer
710/// '&' identifier initializer
711///
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000712/// lambda-declarator:
713/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
714/// 'mutable'[opt] exception-specification[opt]
715/// trailing-return-type[opt]
716///
717ExprResult Parser::ParseLambdaExpression() {
718 // Parse lambda-introducer.
719 LambdaIntroducer Intro;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000720 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000721 if (DiagID) {
722 Diag(Tok, DiagID.getValue());
David Majnemer234b8182015-01-12 03:36:37 +0000723 SkipUntil(tok::r_square, StopAtSemi);
724 SkipUntil(tok::l_brace, StopAtSemi);
725 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000726 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000727 }
728
729 return ParseLambdaExpressionAfterIntroducer(Intro);
730}
731
732/// TryParseLambdaExpression - Use lookahead and potentially tentative
733/// parsing to determine if we are looking at a C++0x lambda expression, and parse
734/// it if we are.
735///
736/// If we are not looking at a lambda expression, returns ExprError().
737ExprResult Parser::TryParseLambdaExpression() {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000738 assert(getLangOpts().CPlusPlus11
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000739 && Tok.is(tok::l_square)
740 && "Not at the start of a possible lambda expression.");
741
742 const Token Next = NextToken(), After = GetLookAheadToken(2);
743
744 // If lookahead indicates this is a lambda...
745 if (Next.is(tok::r_square) || // []
746 Next.is(tok::equal) || // [=
747 (Next.is(tok::amp) && // [&] or [&,
748 (After.is(tok::r_square) ||
749 After.is(tok::comma))) ||
750 (Next.is(tok::identifier) && // [identifier]
751 After.is(tok::r_square))) {
752 return ParseLambdaExpression();
753 }
754
Eli Friedmanc7c97142012-01-04 02:40:39 +0000755 // If lookahead indicates an ObjC message send...
756 // [identifier identifier
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000757 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000758 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000759 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000760
Eli Friedmanc7c97142012-01-04 02:40:39 +0000761 // Here, we're stuck: lambda introducers and Objective-C message sends are
762 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
763 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
764 // writing two routines to parse a lambda introducer, just try to parse
765 // a lambda introducer first, and fall back if that fails.
766 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000767 LambdaIntroducer Intro;
768 if (TryParseLambdaIntroducer(Intro))
Eli Friedmanc7c97142012-01-04 02:40:39 +0000769 return ExprEmpty();
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000770
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000771 return ParseLambdaExpressionAfterIntroducer(Intro);
772}
773
Richard Smithf44d2a82013-05-21 22:21:19 +0000774/// \brief Parse a lambda introducer.
775/// \param Intro A LambdaIntroducer filled in with information about the
776/// contents of the lambda-introducer.
777/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
778/// message send and a lambda expression. In this mode, we will
779/// sometimes skip the initializers for init-captures and not fully
780/// populate \p Intro. This flag will be set to \c true if we do so.
781/// \return A DiagnosticID if it hit something unexpected. The location for
782/// for the diagnostic is that of the current token.
783Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
784 bool *SkippedInits) {
David Blaikie05785d12013-02-20 22:23:23 +0000785 typedef Optional<unsigned> DiagResult;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000786
787 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000788 BalancedDelimiterTracker T(*this, tok::l_square);
789 T.consumeOpen();
790
791 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000792
793 bool first = true;
794
795 // Parse capture-default.
796 if (Tok.is(tok::amp) &&
797 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
798 Intro.Default = LCD_ByRef;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000799 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000800 first = false;
801 } else if (Tok.is(tok::equal)) {
802 Intro.Default = LCD_ByCopy;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000803 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000804 first = false;
805 }
806
807 while (Tok.isNot(tok::r_square)) {
808 if (!first) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000809 if (Tok.isNot(tok::comma)) {
Douglas Gregor721b14d2012-07-31 00:50:07 +0000810 // Provide a completion for a lambda introducer here. Except
811 // in Objective-C, where this is Almost Surely meant to be a message
812 // send. In that case, fail here and let the ObjC message
813 // expression parser perform the completion.
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000814 if (Tok.is(tok::code_completion) &&
815 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
816 !Intro.Captures.empty())) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000817 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
818 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000819 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000820 break;
821 }
822
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000823 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregord8c61782012-02-15 15:34:24 +0000824 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000825 ConsumeToken();
826 }
827
Douglas Gregord8c61782012-02-15 15:34:24 +0000828 if (Tok.is(tok::code_completion)) {
829 // If we're in Objective-C++ and we have a bare '[', then this is more
830 // likely to be a message receiver.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000831 if (getLangOpts().ObjC1 && first)
Douglas Gregord8c61782012-02-15 15:34:24 +0000832 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
833 else
834 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
835 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000836 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000837 break;
838 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000839
Douglas Gregord8c61782012-02-15 15:34:24 +0000840 first = false;
841
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000842 // Parse capture.
843 LambdaCaptureKind Kind = LCK_ByCopy;
844 SourceLocation Loc;
Craig Topper161e4db2014-05-21 06:02:52 +0000845 IdentifierInfo *Id = nullptr;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000846 SourceLocation EllipsisLoc;
Richard Smith21b3ab42013-05-09 21:36:41 +0000847 ExprResult Init;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000848
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000849 if (Tok.is(tok::kw_this)) {
850 Kind = LCK_This;
851 Loc = ConsumeToken();
852 } else {
853 if (Tok.is(tok::amp)) {
854 Kind = LCK_ByRef;
855 ConsumeToken();
Douglas Gregord8c61782012-02-15 15:34:24 +0000856
857 if (Tok.is(tok::code_completion)) {
858 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
859 /*AfterAmpersand=*/true);
Alp Toker1c583cc2014-05-02 03:43:14 +0000860 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000861 break;
862 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000863 }
864
865 if (Tok.is(tok::identifier)) {
866 Id = Tok.getIdentifierInfo();
867 Loc = ConsumeToken();
868 } else if (Tok.is(tok::kw_this)) {
869 // FIXME: If we want to suggest a fixit here, will need to return more
870 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
871 // Clear()ed to prevent emission in case of tentative parsing?
872 return DiagResult(diag::err_this_captured_by_reference);
873 } else {
874 return DiagResult(diag::err_expected_capture);
875 }
Richard Smith21b3ab42013-05-09 21:36:41 +0000876
877 if (Tok.is(tok::l_paren)) {
878 BalancedDelimiterTracker Parens(*this, tok::l_paren);
879 Parens.consumeOpen();
880
881 ExprVector Exprs;
882 CommaLocsTy Commas;
Richard Smithf44d2a82013-05-21 22:21:19 +0000883 if (SkippedInits) {
884 Parens.skipToEnd();
885 *SkippedInits = true;
886 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith21b3ab42013-05-09 21:36:41 +0000887 Parens.skipToEnd();
888 Init = ExprError();
889 } else {
890 Parens.consumeClose();
891 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
892 Parens.getCloseLocation(),
893 Exprs);
894 }
895 } else if (Tok.is(tok::l_brace) || Tok.is(tok::equal)) {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000896 // Each lambda init-capture forms its own full expression, which clears
897 // Actions.MaybeODRUseExprs. So create an expression evaluation context
898 // to save the necessary state, and restore it later.
899 EnterExpressionEvaluationContext EC(Actions,
900 Sema::PotentiallyEvaluated);
Richard Smith215f4232015-02-11 02:41:33 +0000901 bool HadEquals = TryConsumeToken(tok::equal);
Richard Smith21b3ab42013-05-09 21:36:41 +0000902
Richard Smith215f4232015-02-11 02:41:33 +0000903 if (!SkippedInits) {
904 // Warn on constructs that will change meaning when we implement N3922
905 if (!HadEquals && Tok.is(tok::l_brace)) {
906 Diag(Tok, diag::warn_init_capture_direct_list_init)
907 << FixItHint::CreateInsertion(Tok.getLocation(), "=");
908 }
Richard Smithf44d2a82013-05-21 22:21:19 +0000909 Init = ParseInitializer();
Richard Smith215f4232015-02-11 02:41:33 +0000910 } else if (Tok.is(tok::l_brace)) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000911 BalancedDelimiterTracker Braces(*this, tok::l_brace);
912 Braces.consumeOpen();
913 Braces.skipToEnd();
914 *SkippedInits = true;
915 } else {
916 // We're disambiguating this:
917 //
918 // [..., x = expr
919 //
920 // We need to find the end of the following expression in order to
Richard Smith9e2f0a42014-04-13 04:31:48 +0000921 // determine whether this is an Obj-C message send's receiver, a
922 // C99 designator, or a lambda init-capture.
Richard Smithf44d2a82013-05-21 22:21:19 +0000923 //
924 // Parse the expression to find where it ends, and annotate it back
925 // onto the tokens. We would have parsed this expression the same way
926 // in either case: both the RHS of an init-capture and the RHS of an
927 // assignment expression are parsed as an initializer-clause, and in
928 // neither case can anything be added to the scope between the '[' and
929 // here.
930 //
931 // FIXME: This is horrible. Adding a mechanism to skip an expression
932 // would be much cleaner.
933 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
934 // that instead. (And if we see a ':' with no matching '?', we can
935 // classify this as an Obj-C message send.)
936 SourceLocation StartLoc = Tok.getLocation();
937 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
938 Init = ParseInitializer();
939
940 if (Tok.getLocation() != StartLoc) {
941 // Back out the lexing of the token after the initializer.
942 PP.RevertCachedTokens(1);
943
944 // Replace the consumed tokens with an appropriate annotation.
945 Tok.setLocation(StartLoc);
946 Tok.setKind(tok::annot_primary_expr);
947 setExprAnnotation(Tok, Init);
948 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
949 PP.AnnotateCachedTokens(Tok);
950
951 // Consume the annotated initializer.
952 ConsumeToken();
953 }
954 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000955 } else
956 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000957 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000958 // If this is an init capture, process the initialization expression
959 // right away. For lambda init-captures such as the following:
960 // const int x = 10;
961 // auto L = [i = x+1](int a) {
962 // return [j = x+2,
963 // &k = x](char b) { };
964 // };
965 // keep in mind that each lambda init-capture has to have:
966 // - its initialization expression executed in the context
967 // of the enclosing/parent decl-context.
968 // - but the variable itself has to be 'injected' into the
969 // decl-context of its lambda's call-operator (which has
970 // not yet been created).
971 // Each init-expression is a full-expression that has to get
972 // Sema-analyzed (for capturing etc.) before its lambda's
973 // call-operator's decl-context, scope & scopeinfo are pushed on their
974 // respective stacks. Thus if any variable is odr-used in the init-capture
975 // it will correctly get captured in the enclosing lambda, if one exists.
976 // The init-variables above are created later once the lambdascope and
977 // call-operators decl-context is pushed onto its respective stack.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000978
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000979 // Since the lambda init-capture's initializer expression occurs in the
980 // context of the enclosing function or lambda, therefore we can not wait
981 // till a lambda scope has been pushed on before deciding whether the
982 // variable needs to be captured. We also need to process all
983 // lvalue-to-rvalue conversions and discarded-value conversions,
984 // so that we can avoid capturing certain constant variables.
985 // For e.g.,
986 // void test() {
987 // const int x = 10;
988 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
989 // return [y = x](int i) { <-- don't capture by enclosing lambda
990 // return y;
991 // }
992 // };
993 // If x was not const, the second use would require 'L' to capture, and
994 // that would be an error.
995
996 ParsedType InitCaptureParsedType;
997 if (Init.isUsable()) {
998 // Get the pointer and store it in an lvalue, so we can use it as an
999 // out argument.
1000 Expr *InitExpr = Init.get();
1001 // This performs any lvalue-to-rvalue conversions if necessary, which
1002 // can affect what gets captured in the containing decl-context.
1003 QualType InitCaptureType = Actions.performLambdaInitCaptureInitialization(
1004 Loc, Kind == LCK_ByRef, Id, InitExpr);
1005 Init = InitExpr;
1006 InitCaptureParsedType.set(InitCaptureType);
1007 }
1008 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init, InitCaptureParsedType);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001009 }
1010
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001011 T.consumeClose();
1012 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001013 return DiagResult();
1014}
1015
Douglas Gregord8c61782012-02-15 15:34:24 +00001016/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001017///
1018/// Returns true if it hit something unexpected.
1019bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
1020 TentativeParsingAction PA(*this);
1021
Richard Smithf44d2a82013-05-21 22:21:19 +00001022 bool SkippedInits = false;
1023 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001024
1025 if (DiagID) {
1026 PA.Revert();
1027 return true;
1028 }
1029
Richard Smithf44d2a82013-05-21 22:21:19 +00001030 if (SkippedInits) {
1031 // Parse it again, but this time parse the init-captures too.
1032 PA.Revert();
1033 Intro = LambdaIntroducer();
1034 DiagID = ParseLambdaIntroducer(Intro);
1035 assert(!DiagID && "parsing lambda-introducer failed on reparse");
1036 return false;
1037 }
1038
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001039 PA.Commit();
1040 return false;
1041}
1042
1043/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1044/// expression.
1045ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1046 LambdaIntroducer &Intro) {
Eli Friedmanc7c97142012-01-04 02:40:39 +00001047 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1048 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1049
1050 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1051 "lambda expression parsing");
1052
Faisal Vali2b391ab2013-09-26 19:54:12 +00001053
1054
Richard Smith21b3ab42013-05-09 21:36:41 +00001055 // FIXME: Call into Actions to add any init-capture declarations to the
1056 // scope while parsing the lambda-declarator and compound-statement.
1057
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001058 // Parse lambda-declarator[opt].
1059 DeclSpec DS(AttrFactory);
Eli Friedman36d12942012-01-04 04:41:38 +00001060 Declarator D(DS, Declarator::LambdaExprContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001061 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1062 Actions.PushLambdaScope();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001063
David Majnemere01c4662015-01-09 05:10:55 +00001064 TypeResult TrailingReturnType;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001065 if (Tok.is(tok::l_paren)) {
1066 ParseScope PrototypeScope(this,
1067 Scope::FunctionPrototypeScope |
Richard Smithe233fbf2013-01-28 22:42:45 +00001068 Scope::FunctionDeclarationScope |
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001069 Scope::DeclScope);
1070
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001071 SourceLocation DeclEndLoc;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001072 BalancedDelimiterTracker T(*this, tok::l_paren);
1073 T.consumeOpen();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001074 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001075
1076 // Parse parameter-declaration-clause.
1077 ParsedAttributes Attr(AttrFactory);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001078 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001079 SourceLocation EllipsisLoc;
Faisal Vali2b391ab2013-09-26 19:54:12 +00001080
1081 if (Tok.isNot(tok::r_paren)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00001082 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001083 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001084 // For a generic lambda, each 'auto' within the parameter declaration
1085 // clause creates a template type parameter, so increment the depth.
1086 if (Actions.getCurGenericLambda())
1087 ++CurTemplateDepthTracker;
1088 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001089 T.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001090 SourceLocation RParenLoc = T.getCloseLocation();
1091 DeclEndLoc = RParenLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001092
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001093 // GNU-style attributes must be parsed before the mutable specifier to be
1094 // compatible with GCC.
1095 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1096
David Majnemerbda86322015-02-04 08:22:46 +00001097 // MSVC-style attributes must be parsed before the mutable specifier to be
1098 // compatible with MSVC.
Aaron Ballman068aa512015-05-20 20:58:33 +00001099 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
David Majnemerbda86322015-02-04 08:22:46 +00001100
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001101 // Parse 'mutable'[opt].
1102 SourceLocation MutableLoc;
Alp Toker094e5212014-01-05 03:27:11 +00001103 if (TryConsumeToken(tok::kw_mutable, MutableLoc))
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001104 DeclEndLoc = MutableLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001105
1106 // Parse exception-specification[opt].
1107 ExceptionSpecificationType ESpecType = EST_None;
1108 SourceRange ESpecRange;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001109 SmallVector<ParsedType, 2> DynamicExceptions;
1110 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001111 ExprResult NoexceptExpr;
Richard Smith0b3a4622014-11-13 20:01:57 +00001112 CachedTokens *ExceptionSpecTokens;
1113 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1114 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00001115 DynamicExceptions,
1116 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00001117 NoexceptExpr,
1118 ExceptionSpecTokens);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001119
1120 if (ESpecType != EST_None)
1121 DeclEndLoc = ESpecRange.getEnd();
1122
1123 // Parse attribute-specifier[opt].
Richard Smith89645bc2013-01-02 12:01:23 +00001124 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001125
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001126 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1127
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001128 // Parse trailing-return-type[opt].
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001129 if (Tok.is(tok::arrow)) {
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001130 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001131 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001132 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001133 if (Range.getEnd().isValid())
1134 DeclEndLoc = Range.getEnd();
1135 }
1136
1137 PrototypeScope.Exit();
1138
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001139 SourceLocation NoLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001140 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001141 /*isAmbiguous=*/false,
1142 LParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001143 ParamInfo.data(), ParamInfo.size(),
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001144 EllipsisLoc, RParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001145 DS.getTypeQualifiers(),
1146 /*RefQualifierIsLValueRef=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001147 /*RefQualifierLoc=*/NoLoc,
1148 /*ConstQualifierLoc=*/NoLoc,
1149 /*VolatileQualifierLoc=*/NoLoc,
Hal Finkel23a07392014-10-20 17:32:04 +00001150 /*RestrictQualifierLoc=*/NoLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001151 MutableLoc,
1152 ESpecType, ESpecRange.getBegin(),
1153 DynamicExceptions.data(),
1154 DynamicExceptionRanges.data(),
1155 DynamicExceptions.size(),
1156 NoexceptExpr.isUsable() ?
Craig Topper161e4db2014-05-21 06:02:52 +00001157 NoexceptExpr.get() : nullptr,
Richard Smith0b3a4622014-11-13 20:01:57 +00001158 /*ExceptionSpecTokens*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001159 LParenLoc, FunLocalRangeEnd, D,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001160 TrailingReturnType),
1161 Attr, DeclEndLoc);
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001162 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow) ||
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001163 Tok.is(tok::kw___attribute) ||
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001164 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1165 // It's common to forget that one needs '()' before 'mutable', an attribute
1166 // specifier, or the result type. Deal with this.
1167 unsigned TokKind = 0;
1168 switch (Tok.getKind()) {
1169 case tok::kw_mutable: TokKind = 0; break;
1170 case tok::arrow: TokKind = 1; break;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001171 case tok::kw___attribute:
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001172 case tok::l_square: TokKind = 2; break;
1173 default: llvm_unreachable("Unknown token kind");
1174 }
1175
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001176 Diag(Tok, diag::err_lambda_missing_parens)
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001177 << TokKind
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001178 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1179 SourceLocation DeclLoc = Tok.getLocation();
1180 SourceLocation DeclEndLoc = DeclLoc;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001181
1182 // GNU-style attributes must be parsed before the mutable specifier to be
1183 // compatible with GCC.
1184 ParsedAttributes Attr(AttrFactory);
1185 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1186
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001187 // Parse 'mutable', if it's there.
1188 SourceLocation MutableLoc;
1189 if (Tok.is(tok::kw_mutable)) {
1190 MutableLoc = ConsumeToken();
1191 DeclEndLoc = MutableLoc;
1192 }
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001193
1194 // Parse attribute-specifier[opt].
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001195 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1196
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001197 // Parse the return type, if there is one.
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001198 if (Tok.is(tok::arrow)) {
1199 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001200 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001201 if (Range.getEnd().isValid())
David Majnemere01c4662015-01-09 05:10:55 +00001202 DeclEndLoc = Range.getEnd();
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001203 }
1204
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001205 SourceLocation NoLoc;
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001206 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001207 /*isAmbiguous=*/false,
1208 /*LParenLoc=*/NoLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00001209 /*Params=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001210 /*NumParams=*/0,
1211 /*EllipsisLoc=*/NoLoc,
1212 /*RParenLoc=*/NoLoc,
1213 /*TypeQuals=*/0,
1214 /*RefQualifierIsLValueRef=*/true,
1215 /*RefQualifierLoc=*/NoLoc,
1216 /*ConstQualifierLoc=*/NoLoc,
1217 /*VolatileQualifierLoc=*/NoLoc,
Hal Finkel23a07392014-10-20 17:32:04 +00001218 /*RestrictQualifierLoc=*/NoLoc,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001219 MutableLoc,
1220 EST_None,
1221 /*ESpecLoc=*/NoLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00001222 /*Exceptions=*/nullptr,
1223 /*ExceptionRanges=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001224 /*NumExceptions=*/0,
Craig Topper161e4db2014-05-21 06:02:52 +00001225 /*NoexceptExpr=*/nullptr,
Richard Smith0b3a4622014-11-13 20:01:57 +00001226 /*ExceptionSpecTokens=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001227 DeclLoc, DeclEndLoc, D,
1228 TrailingReturnType),
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001229 Attr, DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001230 }
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001231
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001232
Eli Friedman4817cf72012-01-06 03:05:34 +00001233 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1234 // it.
Douglas Gregorb8389972012-02-21 22:51:27 +00001235 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
Douglas Gregorb8389972012-02-21 22:51:27 +00001236 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman4817cf72012-01-06 03:05:34 +00001237
Eli Friedman71c80552012-01-05 03:35:19 +00001238 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1239
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001240 // Parse compound-statement.
Eli Friedmanc7c97142012-01-04 02:40:39 +00001241 if (!Tok.is(tok::l_brace)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001242 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmanc7c97142012-01-04 02:40:39 +00001243 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1244 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001245 }
1246
Eli Friedmanc7c97142012-01-04 02:40:39 +00001247 StmtResult Stmt(ParseCompoundStatementBody());
1248 BodyScope.Exit();
1249
David Majnemere01c4662015-01-09 05:10:55 +00001250 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001251 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
David Majnemere01c4662015-01-09 05:10:55 +00001252
Eli Friedman898caf82012-01-04 02:46:53 +00001253 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1254 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001255}
1256
Chris Lattner29375652006-12-04 18:06:35 +00001257/// ParseCXXCasts - This handles the various ways to cast expressions to another
1258/// type.
1259///
1260/// postfix-expression: [C++ 5.2p1]
1261/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1262/// 'static_cast' '<' type-name '>' '(' expression ')'
1263/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1264/// 'const_cast' '<' type-name '>' '(' expression ')'
1265///
John McCalldadc5752010-08-24 06:29:42 +00001266ExprResult Parser::ParseCXXCasts() {
Chris Lattner29375652006-12-04 18:06:35 +00001267 tok::TokenKind Kind = Tok.getKind();
Craig Topper161e4db2014-05-21 06:02:52 +00001268 const char *CastName = nullptr; // For error messages
Chris Lattner29375652006-12-04 18:06:35 +00001269
1270 switch (Kind) {
David Blaikieaa347f92011-09-23 20:26:49 +00001271 default: llvm_unreachable("Unknown C++ cast!");
Chris Lattner29375652006-12-04 18:06:35 +00001272 case tok::kw_const_cast: CastName = "const_cast"; break;
1273 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1274 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1275 case tok::kw_static_cast: CastName = "static_cast"; break;
1276 }
1277
1278 SourceLocation OpLoc = ConsumeToken();
1279 SourceLocation LAngleBracketLoc = Tok.getLocation();
1280
Richard Smith55858492011-04-14 21:45:45 +00001281 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1282 // diagnose error, suggest fix, and recover parsing.
Richard Smith62e66302012-08-20 17:37:52 +00001283 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1284 Token Next = NextToken();
1285 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1286 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1287 }
Richard Smith55858492011-04-14 21:45:45 +00001288
Chris Lattner29375652006-12-04 18:06:35 +00001289 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redld65cea82008-12-11 22:51:44 +00001290 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001291
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001292 // Parse the common declaration-specifiers piece.
1293 DeclSpec DS(AttrFactory);
1294 ParseSpecifierQualifierList(DS);
1295
1296 // Parse the abstract-declarator, if present.
1297 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1298 ParseDeclarator(DeclaratorInfo);
1299
Chris Lattner29375652006-12-04 18:06:35 +00001300 SourceLocation RAngleBracketLoc = Tok.getLocation();
1301
Alp Toker383d2c42014-01-01 03:08:43 +00001302 if (ExpectAndConsume(tok::greater))
Alp Tokerec543272013-12-24 09:48:30 +00001303 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
Chris Lattner29375652006-12-04 18:06:35 +00001304
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001305 SourceLocation LParenLoc, RParenLoc;
1306 BalancedDelimiterTracker T(*this, tok::l_paren);
Chris Lattner29375652006-12-04 18:06:35 +00001307
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001308 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001309 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001310
John McCalldadc5752010-08-24 06:29:42 +00001311 ExprResult Result = ParseExpression();
Mike Stump11289f42009-09-09 15:08:12 +00001312
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001313 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001314 T.consumeClose();
Chris Lattner29375652006-12-04 18:06:35 +00001315
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001316 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregore200adc2008-10-27 19:41:14 +00001317 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001318 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor220cac52009-02-18 17:45:20 +00001319 RAngleBracketLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001320 T.getOpenLocation(), Result.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001321 T.getCloseLocation());
Chris Lattner29375652006-12-04 18:06:35 +00001322
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001323 return Result;
Chris Lattner29375652006-12-04 18:06:35 +00001324}
Bill Wendling4073ed52007-02-13 01:51:42 +00001325
Sebastian Redlc4704762008-11-11 11:37:55 +00001326/// ParseCXXTypeid - This handles the C++ typeid expression.
1327///
1328/// postfix-expression: [C++ 5.2p1]
1329/// 'typeid' '(' expression ')'
1330/// 'typeid' '(' type-id ')'
1331///
John McCalldadc5752010-08-24 06:29:42 +00001332ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc4704762008-11-11 11:37:55 +00001333 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1334
1335 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001336 SourceLocation LParenLoc, RParenLoc;
1337 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc4704762008-11-11 11:37:55 +00001338
1339 // typeid expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001340 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redld65cea82008-12-11 22:51:44 +00001341 return ExprError();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001342 LParenLoc = T.getOpenLocation();
Sebastian Redlc4704762008-11-11 11:37:55 +00001343
John McCalldadc5752010-08-24 06:29:42 +00001344 ExprResult Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001345
Richard Smith4f605af2012-08-18 00:55:03 +00001346 // C++0x [expr.typeid]p3:
1347 // When typeid is applied to an expression other than an lvalue of a
1348 // polymorphic class type [...] The expression is an unevaluated
1349 // operand (Clause 5).
1350 //
1351 // Note that we can't tell whether the expression is an lvalue of a
1352 // polymorphic class type until after we've parsed the expression; we
1353 // speculatively assume the subexpression is unevaluated, and fix it up
1354 // later.
1355 //
1356 // We enter the unevaluated context before trying to determine whether we
1357 // have a type-id, because the tentative parse logic will try to resolve
1358 // names, and must treat them as unevaluated.
Eli Friedman15681d62012-09-26 04:34:21 +00001359 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1360 Sema::ReuseLambdaContextDecl);
Richard Smith4f605af2012-08-18 00:55:03 +00001361
Sebastian Redlc4704762008-11-11 11:37:55 +00001362 if (isTypeIdInParens()) {
Douglas Gregor220cac52009-02-18 17:45:20 +00001363 TypeResult Ty = ParseTypeName();
Sebastian Redlc4704762008-11-11 11:37:55 +00001364
1365 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001366 T.consumeClose();
1367 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001368 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00001369 return ExprError();
Sebastian Redlc4704762008-11-11 11:37:55 +00001370
1371 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallba7bf592010-08-24 05:47:05 +00001372 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001373 } else {
1374 Result = ParseExpression();
1375
1376 // Match the ')'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001377 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001378 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc4704762008-11-11 11:37:55 +00001379 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001380 T.consumeClose();
1381 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001382 if (RParenLoc.isInvalid())
1383 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00001384
Sebastian Redlc4704762008-11-11 11:37:55 +00001385 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001386 Result.get(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001387 }
1388 }
1389
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001390 return Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001391}
1392
Francois Pichet9f4f2072010-09-08 12:20:18 +00001393/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1394///
1395/// '__uuidof' '(' expression ')'
1396/// '__uuidof' '(' type-id ')'
1397///
1398ExprResult Parser::ParseCXXUuidof() {
1399 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1400
1401 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001402 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001403
1404 // __uuidof expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001405 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet9f4f2072010-09-08 12:20:18 +00001406 return ExprError();
1407
1408 ExprResult Result;
1409
1410 if (isTypeIdInParens()) {
1411 TypeResult Ty = ParseTypeName();
1412
1413 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001414 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001415
1416 if (Ty.isInvalid())
1417 return ExprError();
1418
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001419 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1420 Ty.get().getAsOpaquePtr(),
1421 T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001422 } else {
1423 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1424 Result = ParseExpression();
1425
1426 // Match the ')'.
1427 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001428 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001429 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001430 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001431
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001432 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1433 /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001434 Result.get(), T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001435 }
1436 }
1437
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001438 return Result;
Francois Pichet9f4f2072010-09-08 12:20:18 +00001439}
1440
Douglas Gregore610ada2010-02-24 18:44:31 +00001441/// \brief Parse a C++ pseudo-destructor expression after the base,
1442/// . or -> operator, and nested-name-specifier have already been
1443/// parsed.
1444///
1445/// postfix-expression: [C++ 5.2]
1446/// postfix-expression . pseudo-destructor-name
1447/// postfix-expression -> pseudo-destructor-name
1448///
1449/// pseudo-destructor-name:
1450/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1451/// ::[opt] nested-name-specifier template simple-template-id ::
1452/// ~type-name
1453/// ::[opt] nested-name-specifier[opt] ~type-name
1454///
John McCalldadc5752010-08-24 06:29:42 +00001455ExprResult
Craig Toppera2c51532014-10-30 05:30:05 +00001456Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00001457 tok::TokenKind OpKind,
1458 CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +00001459 ParsedType ObjectType) {
Douglas Gregore610ada2010-02-24 18:44:31 +00001460 // We're parsing either a pseudo-destructor-name or a dependent
1461 // member access that has the same form as a
1462 // pseudo-destructor-name. We parse both in the same way and let
1463 // the action model sort them out.
1464 //
1465 // Note that the ::[opt] nested-name-specifier[opt] has already
1466 // been parsed, and if there was a simple-template-id, it has
1467 // been coalesced into a template-id annotation token.
1468 UnqualifiedId FirstTypeName;
1469 SourceLocation CCLoc;
1470 if (Tok.is(tok::identifier)) {
1471 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1472 ConsumeToken();
1473 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1474 CCLoc = ConsumeToken();
1475 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001476 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1477 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregore610ada2010-02-24 18:44:31 +00001478 FirstTypeName.setTemplateId(
1479 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1480 ConsumeToken();
1481 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1482 CCLoc = ConsumeToken();
1483 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001484 FirstTypeName.setIdentifier(nullptr, SourceLocation());
Douglas Gregore610ada2010-02-24 18:44:31 +00001485 }
1486
1487 // Parse the tilde.
1488 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1489 SourceLocation TildeLoc = ConsumeToken();
David Blaikie1d578782011-12-16 16:03:09 +00001490
1491 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1492 DeclSpec DS(AttrFactory);
Benjamin Kramer198e0832011-12-18 12:18:02 +00001493 ParseDecltypeSpecifier(DS);
David Blaikie1d578782011-12-16 16:03:09 +00001494 if (DS.getTypeSpecType() == TST_error)
1495 return ExprError();
David Majnemerced8bdf2015-02-25 17:36:15 +00001496 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1497 TildeLoc, DS);
David Blaikie1d578782011-12-16 16:03:09 +00001498 }
1499
Douglas Gregore610ada2010-02-24 18:44:31 +00001500 if (!Tok.is(tok::identifier)) {
1501 Diag(Tok, diag::err_destructor_tilde_identifier);
1502 return ExprError();
1503 }
1504
1505 // Parse the second type.
1506 UnqualifiedId SecondTypeName;
1507 IdentifierInfo *Name = Tok.getIdentifierInfo();
1508 SourceLocation NameLoc = ConsumeToken();
1509 SecondTypeName.setIdentifier(Name, NameLoc);
1510
1511 // If there is a '<', the second type name is a template-id. Parse
1512 // it as such.
1513 if (Tok.is(tok::less) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +00001514 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1515 Name, NameLoc,
1516 false, ObjectType, SecondTypeName,
1517 /*AssumeTemplateName=*/true))
Douglas Gregore610ada2010-02-24 18:44:31 +00001518 return ExprError();
1519
David Majnemerced8bdf2015-02-25 17:36:15 +00001520 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1521 SS, FirstTypeName, CCLoc, TildeLoc,
1522 SecondTypeName);
Douglas Gregore610ada2010-02-24 18:44:31 +00001523}
1524
Bill Wendling4073ed52007-02-13 01:51:42 +00001525/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1526///
1527/// boolean-literal: [C++ 2.13.5]
1528/// 'true'
1529/// 'false'
John McCalldadc5752010-08-24 06:29:42 +00001530ExprResult Parser::ParseCXXBoolLiteral() {
Bill Wendling4073ed52007-02-13 01:51:42 +00001531 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001532 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Bill Wendling4073ed52007-02-13 01:51:42 +00001533}
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001534
1535/// ParseThrowExpression - This handles the C++ throw expression.
1536///
1537/// throw-expression: [C++ 15]
1538/// 'throw' assignment-expression[opt]
John McCalldadc5752010-08-24 06:29:42 +00001539ExprResult Parser::ParseThrowExpression() {
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001540 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001541 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redld65cea82008-12-11 22:51:44 +00001542
Chris Lattner65dd8432008-04-06 06:02:23 +00001543 // If the current token isn't the start of an assignment-expression,
1544 // then the expression is not present. This handles things like:
1545 // "C ? throw : (void)42", which is crazy but legal.
1546 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1547 case tok::semi:
1548 case tok::r_paren:
1549 case tok::r_square:
1550 case tok::r_brace:
1551 case tok::colon:
1552 case tok::comma:
Craig Topper161e4db2014-05-21 06:02:52 +00001553 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001554
Chris Lattner65dd8432008-04-06 06:02:23 +00001555 default:
John McCalldadc5752010-08-24 06:29:42 +00001556 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001557 if (Expr.isInvalid()) return Expr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001558 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
Chris Lattner65dd8432008-04-06 06:02:23 +00001559 }
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001560}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001561
1562/// ParseCXXThis - This handles the C++ 'this' pointer.
1563///
1564/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1565/// a non-lvalue expression whose value is the address of the object for which
1566/// the function is called.
John McCalldadc5752010-08-24 06:29:42 +00001567ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001568 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1569 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001570 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001571}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001572
1573/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1574/// Can be interpreted either as function-style casting ("int(x)")
1575/// or class type construction ("ClassType(x,y,z)")
1576/// or creation of a value-initialized type ("int()").
Sebastian Redl3da34892011-06-05 12:23:16 +00001577/// See [C++ 5.2.3].
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001578///
1579/// postfix-expression: [C++ 5.2p1]
Sebastian Redl3da34892011-06-05 12:23:16 +00001580/// simple-type-specifier '(' expression-list[opt] ')'
1581/// [C++0x] simple-type-specifier braced-init-list
1582/// typename-specifier '(' expression-list[opt] ')'
1583/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001584///
John McCalldadc5752010-08-24 06:29:42 +00001585ExprResult
Sebastian Redld65cea82008-12-11 22:51:44 +00001586Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001587 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
John McCallba7bf592010-08-24 05:47:05 +00001588 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001589
Sebastian Redl3da34892011-06-05 12:23:16 +00001590 assert((Tok.is(tok::l_paren) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001591 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redl3da34892011-06-05 12:23:16 +00001592 && "Expected '(' or '{'!");
Douglas Gregor94a32472011-01-11 00:33:19 +00001593
Sebastian Redl3da34892011-06-05 12:23:16 +00001594 if (Tok.is(tok::l_brace)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001595 ExprResult Init = ParseBraceInitializer();
1596 if (Init.isInvalid())
1597 return Init;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001598 Expr *InitList = Init.get();
Sebastian Redld74dd492012-02-12 18:41:05 +00001599 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1600 MultiExprArg(&InitList, 1),
1601 SourceLocation());
Sebastian Redl3da34892011-06-05 12:23:16 +00001602 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001603 BalancedDelimiterTracker T(*this, tok::l_paren);
1604 T.consumeOpen();
Sebastian Redl3da34892011-06-05 12:23:16 +00001605
Benjamin Kramerf0623432012-08-23 22:51:59 +00001606 ExprVector Exprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00001607 CommaLocsTy CommaLocs;
1608
1609 if (Tok.isNot(tok::r_paren)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00001610 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1611 Actions.CodeCompleteConstructor(getCurScope(),
1612 TypeRep.get()->getCanonicalTypeInternal(),
1613 DS.getLocEnd(), Exprs);
1614 })) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001615 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00001616 return ExprError();
1617 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001618 }
Sebastian Redl3da34892011-06-05 12:23:16 +00001619
1620 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001621 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00001622
1623 // TypeRep could be null, if it references an invalid typedef.
1624 if (!TypeRep)
1625 return ExprError();
1626
1627 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1628 "Unexpected number of commas!");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001629 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001630 Exprs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001631 T.getCloseLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001632 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001633}
1634
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001635/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001636///
1637/// condition:
1638/// expression
1639/// type-specifier-seq declarator '=' assignment-expression
Richard Smith2a15b742012-02-22 06:49:09 +00001640/// [C++11] type-specifier-seq declarator '=' initializer-clause
1641/// [C++11] type-specifier-seq declarator braced-init-list
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001642/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1643/// '=' assignment-expression
1644///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001645/// \param ExprOut if the condition was parsed as an expression, the parsed
1646/// expression.
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001647///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001648/// \param DeclOut if the condition was parsed as a declaration, the parsed
1649/// declaration.
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001650///
Douglas Gregore60e41a2010-05-06 17:25:47 +00001651/// \param Loc The location of the start of the statement that requires this
1652/// condition, e.g., the "for" in a for loop.
1653///
1654/// \param ConvertToBoolean Whether the condition expression should be
1655/// converted to a boolean value.
1656///
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001657/// \returns true if there was a parsing, false otherwise.
John McCalldadc5752010-08-24 06:29:42 +00001658bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1659 Decl *&DeclOut,
Douglas Gregore60e41a2010-05-06 17:25:47 +00001660 SourceLocation Loc,
1661 bool ConvertToBoolean) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001662 if (Tok.is(tok::code_completion)) {
John McCallfaf5fb42010-08-26 23:41:50 +00001663 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001664 cutOffParsing();
1665 return true;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001666 }
1667
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001668 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001669 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001670
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001671 if (!isCXXConditionDeclaration()) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001672 ProhibitAttributes(attrs);
1673
Douglas Gregore60e41a2010-05-06 17:25:47 +00001674 // Parse the expression.
John McCalldadc5752010-08-24 06:29:42 +00001675 ExprOut = ParseExpression(); // expression
Craig Topper161e4db2014-05-21 06:02:52 +00001676 DeclOut = nullptr;
John McCalldadc5752010-08-24 06:29:42 +00001677 if (ExprOut.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001678 return true;
1679
1680 // If required, convert to a boolean value.
1681 if (ConvertToBoolean)
John McCalldadc5752010-08-24 06:29:42 +00001682 ExprOut
1683 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1684 return ExprOut.isInvalid();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001685 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001686
1687 // type-specifier-seq
John McCall084e83d2011-03-24 11:26:52 +00001688 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +00001689 DS.takeAttributesFrom(attrs);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001690 ParseSpecifierQualifierList(DS);
1691
1692 // declarator
1693 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1694 ParseDeclarator(DeclaratorInfo);
1695
1696 // simple-asm-expr[opt]
1697 if (Tok.is(tok::kw_asm)) {
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001698 SourceLocation Loc;
John McCalldadc5752010-08-24 06:29:42 +00001699 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001700 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001701 SkipUntil(tok::semi, StopAtSemi);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001702 return true;
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001703 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001704 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001705 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001706 }
1707
1708 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001709 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001710
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001711 // Type-check the declaration itself.
John McCalldadc5752010-08-24 06:29:42 +00001712 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall53fa7142010-12-24 02:08:15 +00001713 DeclaratorInfo);
John McCalldadc5752010-08-24 06:29:42 +00001714 DeclOut = Dcl.get();
1715 ExprOut = ExprError();
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001716
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001717 // '=' assignment-expression
Richard Trieuc64d3232012-01-18 22:54:52 +00001718 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith2a15b742012-02-22 06:49:09 +00001719 bool CopyInitialization = isTokenEqualOrEqualTypo();
1720 if (CopyInitialization)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001721 ConsumeToken();
Richard Smith2a15b742012-02-22 06:49:09 +00001722
1723 ExprResult InitExpr = ExprError();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001724 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith2a15b742012-02-22 06:49:09 +00001725 Diag(Tok.getLocation(),
1726 diag::warn_cxx98_compat_generalized_initializer_lists);
1727 InitExpr = ParseBraceInitializer();
1728 } else if (CopyInitialization) {
1729 InitExpr = ParseAssignmentExpression();
1730 } else if (Tok.is(tok::l_paren)) {
1731 // This was probably an attempt to initialize the variable.
1732 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001733 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith2a15b742012-02-22 06:49:09 +00001734 RParen = ConsumeParen();
1735 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1736 diag::err_expected_init_in_condition_lparen)
1737 << SourceRange(LParen, RParen);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001738 } else {
Richard Smith2a15b742012-02-22 06:49:09 +00001739 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1740 diag::err_expected_init_in_condition);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001741 }
Richard Smith2a15b742012-02-22 06:49:09 +00001742
1743 if (!InitExpr.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001744 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization,
Richard Smith74aeef52013-04-26 16:15:35 +00001745 DS.containsPlaceholderType());
Richard Smith27d807c2013-04-30 13:56:41 +00001746 else
1747 Actions.ActOnInitializerError(DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001748
Douglas Gregore60e41a2010-05-06 17:25:47 +00001749 // FIXME: Build a reference to this declaration? Convert it to bool?
1750 // (This is currently handled by Sema).
Richard Smithb2bc2e62011-02-21 20:05:19 +00001751
1752 Actions.FinalizeDeclaration(DeclOut);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001753
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001754 return false;
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001755}
1756
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001757/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1758/// This should only be called when the current token is known to be part of
1759/// simple-type-specifier.
1760///
1761/// simple-type-specifier:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001762/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001763/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1764/// char
1765/// wchar_t
1766/// bool
1767/// short
1768/// int
1769/// long
1770/// signed
1771/// unsigned
1772/// float
1773/// double
1774/// void
1775/// [GNU] typeof-specifier
1776/// [C++0x] auto [TODO]
1777///
1778/// type-name:
1779/// class-name
1780/// enum-name
1781/// typedef-name
1782///
1783void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1784 DS.SetRangeStart(Tok.getLocation());
1785 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +00001786 unsigned DiagID;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001787 SourceLocation Loc = Tok.getLocation();
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001788 const clang::PrintingPolicy &Policy =
1789 Actions.getASTContext().getPrintingPolicy();
Mike Stump11289f42009-09-09 15:08:12 +00001790
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001791 switch (Tok.getKind()) {
Chris Lattner45ddec32009-01-05 00:13:00 +00001792 case tok::identifier: // foo::bar
1793 case tok::coloncolon: // ::foo::bar
David Blaikie83d382b2011-09-23 05:06:16 +00001794 llvm_unreachable("Annotation token should already be formed!");
Mike Stump11289f42009-09-09 15:08:12 +00001795 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001796 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner45ddec32009-01-05 00:13:00 +00001797
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001798 // type-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00001799 case tok::annot_typename: {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001800 if (getTypeAnnotation(Tok))
1801 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001802 getTypeAnnotation(Tok), Policy);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001803 else
1804 DS.SetTypeSpecError();
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001805
1806 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1807 ConsumeToken();
1808
1809 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1810 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1811 // Objective-C interface. If we don't have Objective-C or a '<', this is
1812 // just a normal reference to a typedef name.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001813 if (Tok.is(tok::less) && getLangOpts().ObjC1)
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001814 ParseObjCProtocolQualifiers(DS);
1815
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001816 DS.Finish(Diags, PP, Policy);
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001817 return;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001818 }
Mike Stump11289f42009-09-09 15:08:12 +00001819
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001820 // builtin types
1821 case tok::kw_short:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001822 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001823 break;
1824 case tok::kw_long:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001825 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001826 break;
Francois Pichet84133e42011-04-28 01:59:37 +00001827 case tok::kw___int64:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001828 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00001829 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001830 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00001831 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001832 break;
1833 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00001834 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001835 break;
1836 case tok::kw_void:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001837 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001838 break;
1839 case tok::kw_char:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001840 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001841 break;
1842 case tok::kw_int:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001843 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001844 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00001845 case tok::kw___int128:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001846 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00001847 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001848 case tok::kw_half:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001849 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001850 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001851 case tok::kw_float:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001852 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001853 break;
1854 case tok::kw_double:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001855 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001856 break;
1857 case tok::kw_wchar_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001858 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001859 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001860 case tok::kw_char16_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001861 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001862 break;
1863 case tok::kw_char32_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001864 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001865 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001866 case tok::kw_bool:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001867 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001868 break;
David Blaikie25896afb2012-01-24 05:47:35 +00001869 case tok::annot_decltype:
1870 case tok::kw_decltype:
1871 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001872 return DS.Finish(Diags, PP, Policy);
Mike Stump11289f42009-09-09 15:08:12 +00001873
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001874 // GNU typeof support.
1875 case tok::kw_typeof:
1876 ParseTypeofSpecifier(DS);
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001877 DS.Finish(Diags, PP, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001878 return;
1879 }
Chris Lattnera8a3f732009-01-06 05:06:21 +00001880 if (Tok.is(tok::annot_typename))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001881 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1882 else
1883 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001884 ConsumeToken();
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001885 DS.Finish(Diags, PP, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001886}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001887
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001888/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1889/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1890/// e.g., "const short int". Note that the DeclSpec is *not* finished
1891/// by parsing the type-specifier-seq, because these sequences are
1892/// typically followed by some form of declarator. Returns true and
1893/// emits diagnostics if this is not a type-specifier-seq, false
1894/// otherwise.
1895///
1896/// type-specifier-seq: [C++ 8.1]
1897/// type-specifier type-specifier-seq[opt]
1898///
1899bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Richard Smithc5b05522012-03-12 07:56:15 +00001900 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001901 DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001902 return false;
1903}
1904
Douglas Gregor7861a802009-11-03 01:35:08 +00001905/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1906/// some form.
1907///
1908/// This routine is invoked when a '<' is encountered after an identifier or
1909/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1910/// whether the unqualified-id is actually a template-id. This routine will
1911/// then parse the template arguments and form the appropriate template-id to
1912/// return to the caller.
1913///
1914/// \param SS the nested-name-specifier that precedes this template-id, if
1915/// we're actually parsing a qualified-id.
1916///
1917/// \param Name for constructor and destructor names, this is the actual
1918/// identifier that may be a template-name.
1919///
1920/// \param NameLoc the location of the class-name in a constructor or
1921/// destructor.
1922///
1923/// \param EnteringContext whether we're entering the scope of the
1924/// nested-name-specifier.
1925///
Douglas Gregor127ea592009-11-03 21:24:04 +00001926/// \param ObjectType if this unqualified-id occurs within a member access
1927/// expression, the type of the base object whose member is being accessed.
1928///
Douglas Gregor7861a802009-11-03 01:35:08 +00001929/// \param Id as input, describes the template-name or operator-function-id
1930/// that precedes the '<'. If template arguments were parsed successfully,
1931/// will be updated with the template-id.
1932///
Douglas Gregore610ada2010-02-24 18:44:31 +00001933/// \param AssumeTemplateId When true, this routine will assume that the name
1934/// refers to a template without performing name lookup to verify.
1935///
Douglas Gregor7861a802009-11-03 01:35:08 +00001936/// \returns true if a parse error occurred, false otherwise.
1937bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001938 SourceLocation TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00001939 IdentifierInfo *Name,
1940 SourceLocation NameLoc,
1941 bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00001942 ParsedType ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00001943 UnqualifiedId &Id,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001944 bool AssumeTemplateId) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00001945 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1946 "Expected '<' to finish parsing a template-id");
Douglas Gregor7861a802009-11-03 01:35:08 +00001947
1948 TemplateTy Template;
1949 TemplateNameKind TNK = TNK_Non_template;
1950 switch (Id.getKind()) {
1951 case UnqualifiedId::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +00001952 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunted0530f2009-11-28 08:58:14 +00001953 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregore610ada2010-02-24 18:44:31 +00001954 if (AssumeTemplateId) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001955 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00001956 Id, ObjectType, EnteringContext,
1957 Template);
1958 if (TNK == TNK_Non_template)
1959 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00001960 } else {
1961 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001962 TNK = Actions.isTemplateName(getCurScope(), SS,
1963 TemplateKWLoc.isValid(), Id,
1964 ObjectType, EnteringContext, Template,
Douglas Gregor786123d2010-05-21 23:18:07 +00001965 MemberOfUnknownSpecialization);
1966
1967 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1968 ObjectType && IsTemplateArgumentList()) {
1969 // We have something like t->getAs<T>(), where getAs is a
1970 // member of an unknown specialization. However, this will only
1971 // parse correctly as a template, so suggest the keyword 'template'
1972 // before 'getAs' and treat this as a dependent template name.
1973 std::string Name;
1974 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1975 Name = Id.Identifier->getName();
1976 else {
1977 Name = "operator ";
1978 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1979 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1980 else
1981 Name += Id.Identifier->getName();
1982 }
1983 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1984 << Name
1985 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Abramo Bagnara7945c982012-01-27 09:46:47 +00001986 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1987 SS, TemplateKWLoc, Id,
1988 ObjectType, EnteringContext,
1989 Template);
Douglas Gregorbb119652010-06-16 23:00:59 +00001990 if (TNK == TNK_Non_template)
Douglas Gregor786123d2010-05-21 23:18:07 +00001991 return true;
1992 }
1993 }
Douglas Gregor7861a802009-11-03 01:35:08 +00001994 break;
1995
Douglas Gregor3cf81312009-11-03 23:16:33 +00001996 case UnqualifiedId::IK_ConstructorName: {
1997 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00001998 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001999 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002000 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2001 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002002 EnteringContext, Template,
2003 MemberOfUnknownSpecialization);
Douglas Gregor7861a802009-11-03 01:35:08 +00002004 break;
2005 }
2006
Douglas Gregor3cf81312009-11-03 23:16:33 +00002007 case UnqualifiedId::IK_DestructorName: {
2008 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002009 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002010 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002011 if (ObjectType) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00002012 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
2013 SS, TemplateKWLoc, TemplateName,
2014 ObjectType, EnteringContext,
2015 Template);
Douglas Gregorbb119652010-06-16 23:00:59 +00002016 if (TNK == TNK_Non_template)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002017 return true;
2018 } else {
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002019 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2020 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002021 EnteringContext, Template,
2022 MemberOfUnknownSpecialization);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002023
John McCallba7bf592010-08-24 05:47:05 +00002024 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002025 Diag(NameLoc, diag::err_destructor_template_id)
2026 << Name << SS.getRange();
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002027 return true;
2028 }
2029 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002030 break;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002031 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002032
2033 default:
2034 return false;
2035 }
2036
2037 if (TNK == TNK_Non_template)
2038 return false;
2039
2040 // Parse the enclosed template argument list.
2041 SourceLocation LAngleLoc, RAngleLoc;
2042 TemplateArgList TemplateArgs;
Douglas Gregorb22ee882010-05-05 05:58:24 +00002043 if (Tok.is(tok::less) &&
2044 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
Douglas Gregore7c20652011-03-02 00:47:37 +00002045 SS, true, LAngleLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002046 TemplateArgs,
Douglas Gregor7861a802009-11-03 01:35:08 +00002047 RAngleLoc))
2048 return true;
2049
2050 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
Alexis Hunted0530f2009-11-28 08:58:14 +00002051 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2052 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002053 // Form a parsed representation of the template-id to be stored in the
2054 // UnqualifiedId.
2055 TemplateIdAnnotation *TemplateId
Benjamin Kramer1e6b6062012-04-14 12:14:03 +00002056 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor7861a802009-11-03 01:35:08 +00002057
Richard Smith72bfbd82013-12-04 00:28:23 +00002058 // FIXME: Store name for literal operator too.
Douglas Gregor7861a802009-11-03 01:35:08 +00002059 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
2060 TemplateId->Name = Id.Identifier;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002061 TemplateId->Operator = OO_None;
Douglas Gregor7861a802009-11-03 01:35:08 +00002062 TemplateId->TemplateNameLoc = Id.StartLocation;
2063 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00002064 TemplateId->Name = nullptr;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002065 TemplateId->Operator = Id.OperatorFunctionId.Operator;
2066 TemplateId->TemplateNameLoc = Id.StartLocation;
Douglas Gregor7861a802009-11-03 01:35:08 +00002067 }
2068
Douglas Gregore7c20652011-03-02 00:47:37 +00002069 TemplateId->SS = SS;
Benjamin Kramer807c2db2012-02-19 23:37:39 +00002070 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall3e56fd42010-08-23 07:28:44 +00002071 TemplateId->Template = Template;
Douglas Gregor7861a802009-11-03 01:35:08 +00002072 TemplateId->Kind = TNK;
2073 TemplateId->LAngleLoc = LAngleLoc;
2074 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002075 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
Douglas Gregor7861a802009-11-03 01:35:08 +00002076 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002077 Arg != ArgEnd; ++Arg)
Douglas Gregor7861a802009-11-03 01:35:08 +00002078 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor7861a802009-11-03 01:35:08 +00002079
2080 Id.setTemplateId(TemplateId);
2081 return false;
2082 }
2083
2084 // Bundle the template arguments together.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002085 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnara4244b432012-01-27 08:46:19 +00002086
Douglas Gregor7861a802009-11-03 01:35:08 +00002087 // Constructor and destructor names.
John McCallfaf5fb42010-08-26 23:41:50 +00002088 TypeResult Type
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002089 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2090 Template, NameLoc,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002091 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2092 /*IsCtorOrDtorName=*/true);
Douglas Gregor7861a802009-11-03 01:35:08 +00002093 if (Type.isInvalid())
2094 return true;
2095
2096 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2097 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2098 else
2099 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2100
2101 return false;
2102}
2103
Douglas Gregor71395fa2009-11-04 00:56:37 +00002104/// \brief Parse an operator-function-id or conversion-function-id as part
2105/// of a C++ unqualified-id.
2106///
2107/// This routine is responsible only for parsing the operator-function-id or
2108/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor7861a802009-11-03 01:35:08 +00002109///
2110/// \code
Douglas Gregor7861a802009-11-03 01:35:08 +00002111/// operator-function-id: [C++ 13.5]
2112/// 'operator' operator
2113///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002114/// operator: one of
Douglas Gregor7861a802009-11-03 01:35:08 +00002115/// new delete new[] delete[]
2116/// + - * / % ^ & | ~
2117/// ! = < > += -= *= /= %=
2118/// ^= &= |= << >> >>= <<= == !=
2119/// <= >= && || ++ -- , ->* ->
2120/// () []
2121///
2122/// conversion-function-id: [C++ 12.3.2]
2123/// operator conversion-type-id
2124///
2125/// conversion-type-id:
2126/// type-specifier-seq conversion-declarator[opt]
2127///
2128/// conversion-declarator:
2129/// ptr-operator conversion-declarator[opt]
2130/// \endcode
2131///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002132/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor7861a802009-11-03 01:35:08 +00002133/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2134///
2135/// \param EnteringContext whether we are entering the scope of the
2136/// nested-name-specifier.
2137///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002138/// \param ObjectType if this unqualified-id occurs within a member access
2139/// expression, the type of the base object whose member is being accessed.
2140///
2141/// \param Result on a successful parse, contains the parsed unqualified-id.
2142///
2143/// \returns true if parsing fails, false otherwise.
2144bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002145 ParsedType ObjectType,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002146 UnqualifiedId &Result) {
2147 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2148
2149 // Consume the 'operator' keyword.
2150 SourceLocation KeywordLoc = ConsumeToken();
2151
2152 // Determine what kind of operator name we have.
2153 unsigned SymbolIdx = 0;
2154 SourceLocation SymbolLocations[3];
2155 OverloadedOperatorKind Op = OO_None;
2156 switch (Tok.getKind()) {
2157 case tok::kw_new:
2158 case tok::kw_delete: {
2159 bool isNew = Tok.getKind() == tok::kw_new;
2160 // Consume the 'new' or 'delete'.
2161 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002162 // Check for array new/delete.
2163 if (Tok.is(tok::l_square) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002164 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002165 // Consume the '[' and ']'.
2166 BalancedDelimiterTracker T(*this, tok::l_square);
2167 T.consumeOpen();
2168 T.consumeClose();
2169 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002170 return true;
2171
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002172 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2173 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002174 Op = isNew? OO_Array_New : OO_Array_Delete;
2175 } else {
2176 Op = isNew? OO_New : OO_Delete;
2177 }
2178 break;
2179 }
2180
2181#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2182 case tok::Token: \
2183 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2184 Op = OO_##Name; \
2185 break;
2186#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2187#include "clang/Basic/OperatorKinds.def"
2188
2189 case tok::l_paren: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002190 // Consume the '(' and ')'.
2191 BalancedDelimiterTracker T(*this, tok::l_paren);
2192 T.consumeOpen();
2193 T.consumeClose();
2194 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002195 return true;
2196
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002197 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2198 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002199 Op = OO_Call;
2200 break;
2201 }
2202
2203 case tok::l_square: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002204 // Consume the '[' and ']'.
2205 BalancedDelimiterTracker T(*this, tok::l_square);
2206 T.consumeOpen();
2207 T.consumeClose();
2208 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002209 return true;
2210
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002211 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2212 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002213 Op = OO_Subscript;
2214 break;
2215 }
2216
2217 case tok::code_completion: {
2218 // Code completion for the operator name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002219 Actions.CodeCompleteOperatorName(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002220 cutOffParsing();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002221 // Don't try to parse any further.
2222 return true;
2223 }
2224
2225 default:
2226 break;
2227 }
2228
2229 if (Op != OO_None) {
2230 // We have parsed an operator-function-id.
2231 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2232 return false;
2233 }
Alexis Hunt34458502009-11-28 04:44:28 +00002234
2235 // Parse a literal-operator-id.
2236 //
Richard Smith6f212062012-10-20 08:41:10 +00002237 // literal-operator-id: C++11 [over.literal]
2238 // operator string-literal identifier
2239 // operator user-defined-string-literal
Alexis Hunt34458502009-11-28 04:44:28 +00002240
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002241 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002242 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Alexis Hunt34458502009-11-28 04:44:28 +00002243
Richard Smith7d182a72012-03-08 23:06:02 +00002244 SourceLocation DiagLoc;
2245 unsigned DiagId = 0;
2246
2247 // We're past translation phase 6, so perform string literal concatenation
2248 // before checking for "".
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002249 SmallVector<Token, 4> Toks;
2250 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith7d182a72012-03-08 23:06:02 +00002251 while (isTokenStringLiteral()) {
2252 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smith6f212062012-10-20 08:41:10 +00002253 // C++11 [over.literal]p1:
2254 // The string-literal or user-defined-string-literal in a
2255 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith7d182a72012-03-08 23:06:02 +00002256 DiagLoc = Tok.getLocation();
2257 DiagId = diag::err_literal_operator_string_prefix;
2258 }
2259 Toks.push_back(Tok);
2260 TokLocs.push_back(ConsumeStringToken());
2261 }
2262
Craig Topper9d5583e2014-06-26 04:58:39 +00002263 StringLiteralParser Literal(Toks, PP);
Richard Smith7d182a72012-03-08 23:06:02 +00002264 if (Literal.hadError)
2265 return true;
2266
2267 // Grab the literal operator's suffix, which will be either the next token
2268 // or a ud-suffix from the string literal.
Craig Topper161e4db2014-05-21 06:02:52 +00002269 IdentifierInfo *II = nullptr;
Richard Smith7d182a72012-03-08 23:06:02 +00002270 SourceLocation SuffixLoc;
2271 if (!Literal.getUDSuffix().empty()) {
2272 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2273 SuffixLoc =
2274 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2275 Literal.getUDSuffixOffset(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002276 PP.getSourceManager(), getLangOpts());
Richard Smith7d182a72012-03-08 23:06:02 +00002277 } else if (Tok.is(tok::identifier)) {
2278 II = Tok.getIdentifierInfo();
2279 SuffixLoc = ConsumeToken();
2280 TokLocs.push_back(SuffixLoc);
2281 } else {
Alp Tokerec543272013-12-24 09:48:30 +00002282 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexis Hunt34458502009-11-28 04:44:28 +00002283 return true;
2284 }
2285
Richard Smith7d182a72012-03-08 23:06:02 +00002286 // The string literal must be empty.
2287 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smith6f212062012-10-20 08:41:10 +00002288 // C++11 [over.literal]p1:
2289 // The string-literal or user-defined-string-literal in a
2290 // literal-operator-id shall [...] contain no characters
2291 // other than the implicit terminating '\0'.
Richard Smith7d182a72012-03-08 23:06:02 +00002292 DiagLoc = TokLocs.front();
2293 DiagId = diag::err_literal_operator_string_not_empty;
2294 }
2295
2296 if (DiagId) {
2297 // This isn't a valid literal-operator-id, but we think we know
2298 // what the user meant. Tell them what they should have written.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002299 SmallString<32> Str;
Richard Smith7d182a72012-03-08 23:06:02 +00002300 Str += "\"\" ";
2301 Str += II->getName();
2302 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2303 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2304 }
2305
2306 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Richard Smithd091dc12013-12-05 00:58:33 +00002307
2308 return Actions.checkLiteralOperatorId(SS, Result);
Alexis Hunt34458502009-11-28 04:44:28 +00002309 }
Richard Smithd091dc12013-12-05 00:58:33 +00002310
Douglas Gregor71395fa2009-11-04 00:56:37 +00002311 // Parse a conversion-function-id.
2312 //
2313 // conversion-function-id: [C++ 12.3.2]
2314 // operator conversion-type-id
2315 //
2316 // conversion-type-id:
2317 // type-specifier-seq conversion-declarator[opt]
2318 //
2319 // conversion-declarator:
2320 // ptr-operator conversion-declarator[opt]
2321
2322 // Parse the type-specifier-seq.
John McCall084e83d2011-03-24 11:26:52 +00002323 DeclSpec DS(AttrFactory);
Douglas Gregora25d65d2009-11-20 22:03:38 +00002324 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregor71395fa2009-11-04 00:56:37 +00002325 return true;
2326
2327 // Parse the conversion-declarator, which is merely a sequence of
2328 // ptr-operators.
Richard Smith01518fa2013-05-04 01:26:46 +00002329 Declarator D(DS, Declarator::ConversionIdContext);
Craig Topper161e4db2014-05-21 06:02:52 +00002330 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2331
Douglas Gregor71395fa2009-11-04 00:56:37 +00002332 // Finish up the type.
John McCallfaf5fb42010-08-26 23:41:50 +00002333 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002334 if (Ty.isInvalid())
2335 return true;
2336
2337 // Note that this is a conversion-function-id.
2338 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2339 D.getSourceRange().getEnd());
2340 return false;
2341}
2342
2343/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2344/// name of an entity.
2345///
2346/// \code
2347/// unqualified-id: [C++ expr.prim.general]
2348/// identifier
2349/// operator-function-id
2350/// conversion-function-id
2351/// [C++0x] literal-operator-id [TODO]
2352/// ~ class-name
2353/// template-id
2354///
2355/// \endcode
2356///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002357/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor71395fa2009-11-04 00:56:37 +00002358/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2359///
2360/// \param EnteringContext whether we are entering the scope of the
2361/// nested-name-specifier.
2362///
Douglas Gregor7861a802009-11-03 01:35:08 +00002363/// \param AllowDestructorName whether we allow parsing of a destructor name.
2364///
2365/// \param AllowConstructorName whether we allow parsing a constructor name.
2366///
Douglas Gregor127ea592009-11-03 21:24:04 +00002367/// \param ObjectType if this unqualified-id occurs within a member access
2368/// expression, the type of the base object whose member is being accessed.
2369///
Douglas Gregor7861a802009-11-03 01:35:08 +00002370/// \param Result on a successful parse, contains the parsed unqualified-id.
2371///
2372/// \returns true if parsing fails, false otherwise.
2373bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2374 bool AllowDestructorName,
2375 bool AllowConstructorName,
John McCallba7bf592010-08-24 05:47:05 +00002376 ParsedType ObjectType,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002377 SourceLocation& TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002378 UnqualifiedId &Result) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00002379
2380 // Handle 'A::template B'. This is for template-ids which have not
2381 // already been annotated by ParseOptionalCXXScopeSpecifier().
2382 bool TemplateSpecified = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002383 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002384 (ObjectType || SS.isSet())) {
2385 TemplateSpecified = true;
2386 TemplateKWLoc = ConsumeToken();
2387 }
2388
Douglas Gregor7861a802009-11-03 01:35:08 +00002389 // unqualified-id:
2390 // identifier
2391 // template-id (when it hasn't already been annotated)
2392 if (Tok.is(tok::identifier)) {
2393 // Consume the identifier.
2394 IdentifierInfo *Id = Tok.getIdentifierInfo();
2395 SourceLocation IdLoc = ConsumeToken();
2396
David Blaikiebbafb8a2012-03-11 07:00:24 +00002397 if (!getLangOpts().CPlusPlus) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002398 // If we're not in C++, only identifiers matter. Record the
2399 // identifier and return.
2400 Result.setIdentifier(Id, IdLoc);
2401 return false;
2402 }
2403
Douglas Gregor7861a802009-11-03 01:35:08 +00002404 if (AllowConstructorName &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002405 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002406 // We have parsed a constructor name.
Abramo Bagnara4244b432012-01-27 08:46:19 +00002407 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2408 &SS, false, false,
2409 ParsedType(),
2410 /*IsCtorOrDtorName=*/true,
2411 /*NonTrivialTypeSourceInfo=*/true);
2412 Result.setConstructorName(Ty, IdLoc, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002413 } else {
2414 // We have parsed an identifier.
2415 Result.setIdentifier(Id, IdLoc);
2416 }
2417
2418 // If the next token is a '<', we may have a template.
Douglas Gregorb22ee882010-05-05 05:58:24 +00002419 if (TemplateSpecified || Tok.is(tok::less))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002420 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2421 EnteringContext, ObjectType,
2422 Result, TemplateSpecified);
Douglas Gregor7861a802009-11-03 01:35:08 +00002423
2424 return false;
2425 }
2426
2427 // unqualified-id:
2428 // template-id (already parsed and annotated)
2429 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00002430 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002431
2432 // If the template-name names the current class, then this is a constructor
2433 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002434 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002435 if (SS.isSet()) {
2436 // C++ [class.qual]p2 specifies that a qualified template-name
2437 // is taken as the constructor name where a constructor can be
2438 // declared. Thus, the template arguments are extraneous, so
2439 // complain about them and remove them entirely.
2440 Diag(TemplateId->TemplateNameLoc,
2441 diag::err_out_of_line_constructor_template_id)
2442 << TemplateId->Name
Douglas Gregora771f462010-03-31 17:46:05 +00002443 << FixItHint::CreateRemoval(
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002444 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Abramo Bagnara4244b432012-01-27 08:46:19 +00002445 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2446 TemplateId->TemplateNameLoc,
2447 getCurScope(),
2448 &SS, false, false,
2449 ParsedType(),
2450 /*IsCtorOrDtorName=*/true,
2451 /*NontrivialTypeSourceInfo=*/true);
2452 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002453 TemplateId->RAngleLoc);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002454 ConsumeToken();
2455 return false;
2456 }
2457
2458 Result.setConstructorTemplateId(TemplateId);
2459 ConsumeToken();
2460 return false;
2461 }
2462
Douglas Gregor7861a802009-11-03 01:35:08 +00002463 // We have already parsed a template-id; consume the annotation token as
2464 // our unqualified-id.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002465 Result.setTemplateId(TemplateId);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002466 TemplateKWLoc = TemplateId->TemplateKWLoc;
Douglas Gregor7861a802009-11-03 01:35:08 +00002467 ConsumeToken();
2468 return false;
2469 }
2470
2471 // unqualified-id:
2472 // operator-function-id
2473 // conversion-function-id
2474 if (Tok.is(tok::kw_operator)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00002475 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor7861a802009-11-03 01:35:08 +00002476 return true;
2477
Alexis Hunted0530f2009-11-28 08:58:14 +00002478 // If we have an operator-function-id or a literal-operator-id and the next
2479 // token is a '<', we may have a
Douglas Gregor71395fa2009-11-04 00:56:37 +00002480 //
2481 // template-id:
2482 // operator-function-id < template-argument-list[opt] >
Alexis Hunted0530f2009-11-28 08:58:14 +00002483 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2484 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002485 (TemplateSpecified || Tok.is(tok::less)))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002486 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00002487 nullptr, SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002488 EnteringContext, ObjectType,
2489 Result, TemplateSpecified);
Craig Topper161e4db2014-05-21 06:02:52 +00002490
Douglas Gregor7861a802009-11-03 01:35:08 +00002491 return false;
2492 }
2493
David Blaikiebbafb8a2012-03-11 07:00:24 +00002494 if (getLangOpts().CPlusPlus &&
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002495 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002496 // C++ [expr.unary.op]p10:
2497 // There is an ambiguity in the unary-expression ~X(), where X is a
2498 // class-name. The ambiguity is resolved in favor of treating ~ as a
2499 // unary complement rather than treating ~X as referring to a destructor.
2500
2501 // Parse the '~'.
2502 SourceLocation TildeLoc = ConsumeToken();
David Blaikieecd8a942011-12-08 16:13:53 +00002503
2504 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2505 DeclSpec DS(AttrFactory);
2506 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2507 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2508 Result.setDestructorName(TildeLoc, Type, EndLoc);
2509 return false;
2510 }
2511 return true;
2512 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002513
2514 // Parse the class-name.
2515 if (Tok.isNot(tok::identifier)) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002516 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00002517 return true;
2518 }
2519
Richard Smithefa6f732014-09-06 02:06:12 +00002520 // If the user wrote ~T::T, correct it to T::~T.
Richard Smith64e033f2015-01-15 00:48:52 +00002521 DeclaratorScopeObj DeclScopeObj(*this, SS);
Nico Weber10d02b52015-02-02 04:18:38 +00002522 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
Nico Weberf9e37be2015-01-30 16:53:11 +00002523 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2524 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2525 // it will confuse this recovery logic.
2526 ColonProtectionRAIIObject ColonRAII(*this, false);
2527
Richard Smithefa6f732014-09-06 02:06:12 +00002528 if (SS.isSet()) {
2529 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2530 SS.clear();
2531 }
2532 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2533 return true;
Nico Weber7f8ec522015-02-02 05:33:50 +00002534 if (SS.isNotEmpty())
2535 ObjectType = ParsedType();
Nico Weberd0045862015-01-30 04:05:15 +00002536 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
Benjamin Kramer3012e592015-03-29 14:35:39 +00002537 !SS.isSet()) {
Richard Smithefa6f732014-09-06 02:06:12 +00002538 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2539 return true;
2540 }
2541
2542 // Recover as if the tilde had been written before the identifier.
2543 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2544 << FixItHint::CreateRemoval(TildeLoc)
2545 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
Richard Smith64e033f2015-01-15 00:48:52 +00002546
2547 // Temporarily enter the scope for the rest of this function.
2548 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2549 DeclScopeObj.EnterDeclaratorScope();
Richard Smithefa6f732014-09-06 02:06:12 +00002550 }
2551
Douglas Gregor7861a802009-11-03 01:35:08 +00002552 // Parse the class-name (or template-name in a simple-template-id).
2553 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2554 SourceLocation ClassNameLoc = ConsumeToken();
Richard Smithefa6f732014-09-06 02:06:12 +00002555
Douglas Gregorb22ee882010-05-05 05:58:24 +00002556 if (TemplateSpecified || Tok.is(tok::less)) {
John McCallba7bf592010-08-24 05:47:05 +00002557 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002558 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2559 ClassName, ClassNameLoc,
2560 EnteringContext, ObjectType,
2561 Result, TemplateSpecified);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002562 }
Richard Smithefa6f732014-09-06 02:06:12 +00002563
Douglas Gregor7861a802009-11-03 01:35:08 +00002564 // Note that this is a destructor name.
John McCallba7bf592010-08-24 05:47:05 +00002565 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2566 ClassNameLoc, getCurScope(),
2567 SS, ObjectType,
2568 EnteringContext);
Douglas Gregorfe17d252010-02-16 19:09:40 +00002569 if (!Ty)
Douglas Gregor7861a802009-11-03 01:35:08 +00002570 return true;
Douglas Gregorfe17d252010-02-16 19:09:40 +00002571
Douglas Gregor7861a802009-11-03 01:35:08 +00002572 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002573 return false;
2574 }
2575
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002576 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002577 << getLangOpts().CPlusPlus;
Douglas Gregor7861a802009-11-03 01:35:08 +00002578 return true;
2579}
2580
Sebastian Redlbd150f42008-11-21 19:14:01 +00002581/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2582/// memory in a typesafe manner and call constructors.
Mike Stump11289f42009-09-09 15:08:12 +00002583///
Chris Lattner109faf22009-01-04 21:25:24 +00002584/// This method is called to parse the new expression after the optional :: has
2585/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2586/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002587///
2588/// new-expression:
2589/// '::'[opt] 'new' new-placement[opt] new-type-id
2590/// new-initializer[opt]
2591/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2592/// new-initializer[opt]
2593///
2594/// new-placement:
2595/// '(' expression-list ')'
2596///
Sebastian Redl351bb782008-12-02 14:43:59 +00002597/// new-type-id:
2598/// type-specifier-seq new-declarator[opt]
Douglas Gregora3a020a2011-04-15 19:40:02 +00002599/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redl351bb782008-12-02 14:43:59 +00002600///
2601/// new-declarator:
2602/// ptr-operator new-declarator[opt]
2603/// direct-new-declarator
2604///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002605/// new-initializer:
2606/// '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00002607/// [C++0x] braced-init-list
Sebastian Redlbd150f42008-11-21 19:14:01 +00002608///
John McCalldadc5752010-08-24 06:29:42 +00002609ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002610Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2611 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2612 ConsumeToken(); // Consume 'new'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002613
2614 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2615 // second form of new-expression. It can't be a new-type-id.
2616
Benjamin Kramerf0623432012-08-23 22:51:59 +00002617 ExprVector PlacementArgs;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002618 SourceLocation PlacementLParen, PlacementRParen;
2619
Douglas Gregorf2753b32010-07-13 15:54:32 +00002620 SourceRange TypeIdParens;
John McCall084e83d2011-03-24 11:26:52 +00002621 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +00002622 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002623 if (Tok.is(tok::l_paren)) {
2624 // If it turns out to be a placement, we change the type location.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002625 BalancedDelimiterTracker T(*this, tok::l_paren);
2626 T.consumeOpen();
2627 PlacementLParen = T.getOpenLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002628 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002629 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002630 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002631 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002632
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002633 T.consumeClose();
2634 PlacementRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002635 if (PlacementRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002636 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002637 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002638 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002639
Sebastian Redl351bb782008-12-02 14:43:59 +00002640 if (PlacementArgs.empty()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002641 // Reset the placement locations. There was no placement.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002642 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002643 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002644 } else {
2645 // We still need the type.
2646 if (Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002647 BalancedDelimiterTracker T(*this, tok::l_paren);
2648 T.consumeOpen();
Douglas Gregora3a020a2011-04-15 19:40:02 +00002649 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002650 ParseSpecifierQualifierList(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002651 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002652 ParseDeclarator(DeclaratorInfo);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002653 T.consumeClose();
2654 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002655 } else {
Douglas Gregora3a020a2011-04-15 19:40:02 +00002656 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002657 if (ParseCXXTypeSpecifierSeq(DS))
2658 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002659 else {
2660 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002661 ParseDeclaratorInternal(DeclaratorInfo,
2662 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002663 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002664 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002665 }
2666 } else {
Sebastian Redl351bb782008-12-02 14:43:59 +00002667 // A new-type-id is a simplified type-id, where essentially the
2668 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregora3a020a2011-04-15 19:40:02 +00002669 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002670 if (ParseCXXTypeSpecifierSeq(DS))
2671 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002672 else {
2673 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002674 ParseDeclaratorInternal(DeclaratorInfo,
2675 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002676 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002677 }
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002678 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002679 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002680 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002681 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002682
Sebastian Redl6047f072012-02-16 12:22:20 +00002683 ExprResult Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002684
2685 if (Tok.is(tok::l_paren)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00002686 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002687 ExprVector ConstructorArgs;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002688 BalancedDelimiterTracker T(*this, tok::l_paren);
2689 T.consumeOpen();
2690 ConstructorLParen = T.getOpenLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002691 if (Tok.isNot(tok::r_paren)) {
2692 CommaLocsTy CommaLocs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002693 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2694 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
2695 DeclaratorInfo).get();
2696 Actions.CodeCompleteConstructor(getCurScope(),
2697 TypeRep.get()->getCanonicalTypeInternal(),
2698 DeclaratorInfo.getLocEnd(),
2699 ConstructorArgs);
2700 })) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002701 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002702 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002703 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002704 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002705 T.consumeClose();
2706 ConstructorRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002707 if (ConstructorRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002708 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002709 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002710 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002711 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2712 ConstructorRParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002713 ConstructorArgs);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002714 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002715 Diag(Tok.getLocation(),
2716 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl6047f072012-02-16 12:22:20 +00002717 Initializer = ParseBraceInitializer();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002718 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002719 if (Initializer.isInvalid())
2720 return Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002721
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002722 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002723 PlacementArgs, PlacementRParen,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002724 TypeIdParens, DeclaratorInfo, Initializer.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002725}
2726
Sebastian Redlbd150f42008-11-21 19:14:01 +00002727/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2728/// passed to ParseDeclaratorInternal.
2729///
2730/// direct-new-declarator:
2731/// '[' expression ']'
2732/// direct-new-declarator '[' constant-expression ']'
2733///
Chris Lattner109faf22009-01-04 21:25:24 +00002734void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002735 // Parse the array dimensions.
2736 bool first = true;
2737 while (Tok.is(tok::l_square)) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002738 // An array-size expression can't start with a lambda.
2739 if (CheckProhibitedCXX11Attribute())
2740 continue;
2741
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002742 BalancedDelimiterTracker T(*this, tok::l_square);
2743 T.consumeOpen();
2744
John McCalldadc5752010-08-24 06:29:42 +00002745 ExprResult Size(first ? ParseExpression()
Sebastian Redl59b5e512008-12-11 21:36:32 +00002746 : ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002747 if (Size.isInvalid()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002748 // Recover
Alexey Bataevee6507d2013-11-18 08:17:37 +00002749 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002750 return;
2751 }
2752 first = false;
2753
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002754 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00002755
Bill Wendling44426052012-12-20 19:22:21 +00002756 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002757 ParsedAttributes Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002758 MaybeParseCXX11Attributes(Attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002759
John McCall084e83d2011-03-24 11:26:52 +00002760 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall53fa7142010-12-24 02:08:15 +00002761 /*static=*/false, /*star=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002762 Size.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002763 T.getOpenLocation(),
2764 T.getCloseLocation()),
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002765 Attrs, T.getCloseLocation());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002766
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002767 if (T.getCloseLocation().isInvalid())
Sebastian Redlbd150f42008-11-21 19:14:01 +00002768 return;
2769 }
2770}
2771
2772/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2773/// This ambiguity appears in the syntax of the C++ new operator.
2774///
2775/// new-expression:
2776/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2777/// new-initializer[opt]
2778///
2779/// new-placement:
2780/// '(' expression-list ')'
2781///
John McCall37ad5512010-08-23 06:44:23 +00002782bool Parser::ParseExpressionListOrTypeId(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002783 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner109faf22009-01-04 21:25:24 +00002784 Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002785 // The '(' was already consumed.
2786 if (isTypeIdInParens()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00002787 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002788 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002789 ParseDeclarator(D);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002790 return D.isInvalidType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002791 }
2792
2793 // It's not a type, it has to be an expression list.
2794 // Discard the comma locations - ActOnCXXNew has enough parameters.
2795 CommaLocsTy CommaLocs;
2796 return ParseExpressionList(PlacementArgs, CommaLocs);
2797}
2798
2799/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2800/// to free memory allocated by new.
2801///
Chris Lattner109faf22009-01-04 21:25:24 +00002802/// This method is called to parse the 'delete' expression after the optional
2803/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2804/// and "Start" is its location. Otherwise, "Start" is the location of the
2805/// 'delete' token.
2806///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002807/// delete-expression:
2808/// '::'[opt] 'delete' cast-expression
2809/// '::'[opt] 'delete' '[' ']' cast-expression
John McCalldadc5752010-08-24 06:29:42 +00002810ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002811Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2812 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2813 ConsumeToken(); // Consume 'delete'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002814
2815 // Array delete?
2816 bool ArrayDelete = false;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002817 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith10c60722012-08-09 19:01:51 +00002818 // C++11 [expr.delete]p1:
2819 // Whenever the delete keyword is followed by empty square brackets, it
2820 // shall be interpreted as [array delete].
2821 // [Footnote: A lambda expression with a lambda-introducer that consists
2822 // of empty square brackets can follow the delete keyword if
2823 // the lambda expression is enclosed in parentheses.]
2824 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2825 // lambda-introducer.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002826 ArrayDelete = true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002827 BalancedDelimiterTracker T(*this, tok::l_square);
2828
2829 T.consumeOpen();
2830 T.consumeClose();
2831 if (T.getCloseLocation().isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00002832 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002833 }
2834
John McCalldadc5752010-08-24 06:29:42 +00002835 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002836 if (Operand.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002837 return Operand;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002838
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002839 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002840}
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002841
Douglas Gregor29c42f22012-02-24 07:38:34 +00002842static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2843 switch (kind) {
2844 default: llvm_unreachable("Not a known type trait");
Alp Toker95e7ff22014-01-01 05:57:51 +00002845#define TYPE_TRAIT_1(Spelling, Name, Key) \
2846case tok::kw_ ## Spelling: return UTT_ ## Name;
Alp Tokercbb90342013-12-13 20:49:58 +00002847#define TYPE_TRAIT_2(Spelling, Name, Key) \
2848case tok::kw_ ## Spelling: return BTT_ ## Name;
2849#include "clang/Basic/TokenKinds.def"
Alp Toker40f9b1c2013-12-12 21:23:03 +00002850#define TYPE_TRAIT_N(Spelling, Name, Key) \
2851 case tok::kw_ ## Spelling: return TT_ ## Name;
2852#include "clang/Basic/TokenKinds.def"
Douglas Gregor29c42f22012-02-24 07:38:34 +00002853 }
2854}
2855
John Wiegley6242b6a2011-04-28 00:16:57 +00002856static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2857 switch(kind) {
2858 default: llvm_unreachable("Not a known binary type trait");
2859 case tok::kw___array_rank: return ATT_ArrayRank;
2860 case tok::kw___array_extent: return ATT_ArrayExtent;
2861 }
2862}
2863
John Wiegleyf9f65842011-04-25 06:54:41 +00002864static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2865 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002866 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegleyf9f65842011-04-25 06:54:41 +00002867 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2868 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2869 }
2870}
2871
Alp Toker40f9b1c2013-12-12 21:23:03 +00002872static unsigned TypeTraitArity(tok::TokenKind kind) {
2873 switch (kind) {
2874 default: llvm_unreachable("Not a known type trait");
2875#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2876#include "clang/Basic/TokenKinds.def"
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002877 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002878}
2879
Douglas Gregor29c42f22012-02-24 07:38:34 +00002880/// \brief Parse the built-in type-trait pseudo-functions that allow
2881/// implementation of the TR1/C++11 type traits templates.
2882///
2883/// primary-expression:
Alp Toker40f9b1c2013-12-12 21:23:03 +00002884/// unary-type-trait '(' type-id ')'
2885/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor29c42f22012-02-24 07:38:34 +00002886/// type-trait '(' type-id-seq ')'
2887///
2888/// type-id-seq:
2889/// type-id ...[opt] type-id-seq[opt]
2890///
2891ExprResult Parser::ParseTypeTrait() {
Alp Toker40f9b1c2013-12-12 21:23:03 +00002892 tok::TokenKind Kind = Tok.getKind();
2893 unsigned Arity = TypeTraitArity(Kind);
2894
Douglas Gregor29c42f22012-02-24 07:38:34 +00002895 SourceLocation Loc = ConsumeToken();
2896
2897 BalancedDelimiterTracker Parens(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002898 if (Parens.expectAndConsume())
Douglas Gregor29c42f22012-02-24 07:38:34 +00002899 return ExprError();
2900
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002901 SmallVector<ParsedType, 2> Args;
Douglas Gregor29c42f22012-02-24 07:38:34 +00002902 do {
2903 // Parse the next type.
2904 TypeResult Ty = ParseTypeName();
2905 if (Ty.isInvalid()) {
2906 Parens.skipToEnd();
2907 return ExprError();
2908 }
2909
2910 // Parse the ellipsis, if present.
2911 if (Tok.is(tok::ellipsis)) {
2912 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2913 if (Ty.isInvalid()) {
2914 Parens.skipToEnd();
2915 return ExprError();
2916 }
2917 }
2918
2919 // Add this type to the list of arguments.
2920 Args.push_back(Ty.get());
Alp Tokera3ebe6e2013-12-17 14:12:37 +00002921 } while (TryConsumeToken(tok::comma));
2922
Douglas Gregor29c42f22012-02-24 07:38:34 +00002923 if (Parens.consumeClose())
2924 return ExprError();
Alp Toker40f9b1c2013-12-12 21:23:03 +00002925
2926 SourceLocation EndLoc = Parens.getCloseLocation();
2927
2928 if (Arity && Args.size() != Arity) {
2929 Diag(EndLoc, diag::err_type_trait_arity)
2930 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
2931 return ExprError();
2932 }
2933
2934 if (!Arity && Args.empty()) {
2935 Diag(EndLoc, diag::err_type_trait_arity)
2936 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
2937 return ExprError();
2938 }
2939
Alp Toker88f64e62013-12-13 21:19:30 +00002940 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
Douglas Gregor29c42f22012-02-24 07:38:34 +00002941}
2942
John Wiegley6242b6a2011-04-28 00:16:57 +00002943/// ParseArrayTypeTrait - Parse the built-in array type-trait
2944/// pseudo-functions.
2945///
2946/// primary-expression:
2947/// [Embarcadero] '__array_rank' '(' type-id ')'
2948/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2949///
2950ExprResult Parser::ParseArrayTypeTrait() {
2951 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2952 SourceLocation Loc = ConsumeToken();
2953
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002954 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002955 if (T.expectAndConsume())
John Wiegley6242b6a2011-04-28 00:16:57 +00002956 return ExprError();
2957
2958 TypeResult Ty = ParseTypeName();
2959 if (Ty.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002960 SkipUntil(tok::comma, StopAtSemi);
2961 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00002962 return ExprError();
2963 }
2964
2965 switch (ATT) {
2966 case ATT_ArrayRank: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002967 T.consumeClose();
Craig Topper161e4db2014-05-21 06:02:52 +00002968 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002969 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00002970 }
2971 case ATT_ArrayExtent: {
Alp Toker383d2c42014-01-01 03:08:43 +00002972 if (ExpectAndConsume(tok::comma)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002973 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00002974 return ExprError();
2975 }
2976
2977 ExprResult DimExpr = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002978 T.consumeClose();
John Wiegley6242b6a2011-04-28 00:16:57 +00002979
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002980 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2981 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00002982 }
John Wiegley6242b6a2011-04-28 00:16:57 +00002983 }
David Blaikiee4d798f2012-01-20 21:50:17 +00002984 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley6242b6a2011-04-28 00:16:57 +00002985}
2986
John Wiegleyf9f65842011-04-25 06:54:41 +00002987/// ParseExpressionTrait - Parse built-in expression-trait
2988/// pseudo-functions like __is_lvalue_expr( xxx ).
2989///
2990/// primary-expression:
2991/// [Embarcadero] expression-trait '(' expression ')'
2992///
2993ExprResult Parser::ParseExpressionTrait() {
2994 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2995 SourceLocation Loc = ConsumeToken();
2996
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002997 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002998 if (T.expectAndConsume())
John Wiegleyf9f65842011-04-25 06:54:41 +00002999 return ExprError();
3000
3001 ExprResult Expr = ParseExpression();
3002
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003003 T.consumeClose();
John Wiegleyf9f65842011-04-25 06:54:41 +00003004
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003005 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3006 T.getCloseLocation());
John Wiegleyf9f65842011-04-25 06:54:41 +00003007}
3008
3009
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003010/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3011/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3012/// based on the context past the parens.
John McCalldadc5752010-08-24 06:29:42 +00003013ExprResult
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003014Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallba7bf592010-08-24 05:47:05 +00003015 ParsedType &CastTy,
Richard Smith87e11a42014-05-15 02:43:47 +00003016 BalancedDelimiterTracker &Tracker,
3017 ColonProtectionRAIIObject &ColonProt) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003018 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003019 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3020 assert(isTypeIdInParens() && "Not a type-id!");
3021
John McCalldadc5752010-08-24 06:29:42 +00003022 ExprResult Result(true);
John McCallba7bf592010-08-24 05:47:05 +00003023 CastTy = ParsedType();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003024
3025 // We need to disambiguate a very ugly part of the C++ syntax:
3026 //
3027 // (T())x; - type-id
3028 // (T())*x; - type-id
3029 // (T())/x; - expression
3030 // (T()); - expression
3031 //
3032 // The bad news is that we cannot use the specialized tentative parser, since
3033 // it can only verify that the thing inside the parens can be parsed as
3034 // type-id, it is not useful for determining the context past the parens.
3035 //
3036 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidis24ad6922009-05-22 15:12:46 +00003037 // making any unnecessary Action calls.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003038 //
3039 // It uses a scheme similar to parsing inline methods. The parenthesized
3040 // tokens are cached, the context that follows is determined (possibly by
3041 // parsing a cast-expression), and then we re-introduce the cached tokens
3042 // into the token stream and parse them appropriately.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003043
Mike Stump11289f42009-09-09 15:08:12 +00003044 ParenParseOption ParseAs;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003045 CachedTokens Toks;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003046
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003047 // Store the tokens of the parentheses. We will parse them after we determine
3048 // the context that follows them.
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +00003049 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003050 // We didn't find the ')' we expected.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003051 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003052 return ExprError();
3053 }
3054
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003055 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003056 ParseAs = CompoundLiteral;
3057 } else {
3058 bool NotCastExpr;
Eli Friedmancf7530f2009-05-25 19:41:42 +00003059 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3060 NotCastExpr = true;
3061 } else {
3062 // Try parsing the cast-expression that may follow.
3063 // If it is not a cast-expression, NotCastExpr will be true and no token
3064 // will be consumed.
Richard Smith87e11a42014-05-15 02:43:47 +00003065 ColonProt.restore();
Eli Friedmancf7530f2009-05-25 19:41:42 +00003066 Result = ParseCastExpression(false/*isUnaryExpression*/,
3067 false/*isAddressofOperand*/,
John McCallba7bf592010-08-24 05:47:05 +00003068 NotCastExpr,
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003069 // type-id has priority.
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00003070 IsTypeCast);
Eli Friedmancf7530f2009-05-25 19:41:42 +00003071 }
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003072
3073 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3074 // an expression.
3075 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003076 }
3077
Mike Stump11289f42009-09-09 15:08:12 +00003078 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003079 Toks.push_back(Tok);
3080 // Re-enter the stored parenthesized tokens into the token stream, so we may
3081 // parse them now.
3082 PP.EnterTokenStream(Toks.data(), Toks.size(),
3083 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
3084 // Drop the current token and bring the first cached one. It's the same token
3085 // as when we entered this function.
3086 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003087
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003088 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003089 // Parse the type declarator.
3090 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003091 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
Richard Smith87e11a42014-05-15 02:43:47 +00003092 {
3093 ColonProtectionRAIIObject InnerColonProtection(*this);
3094 ParseSpecifierQualifierList(DS);
3095 ParseDeclarator(DeclaratorInfo);
3096 }
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003097
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003098 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003099 Tracker.consumeClose();
Richard Smith87e11a42014-05-15 02:43:47 +00003100 ColonProt.restore();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003101
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003102 if (ParseAs == CompoundLiteral) {
3103 ExprType = CompoundLiteral;
Richard Smithaba8b362014-05-15 02:51:15 +00003104 if (DeclaratorInfo.isInvalidType())
3105 return ExprError();
3106
3107 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Richard Smith87e11a42014-05-15 02:43:47 +00003108 return ParseCompoundLiteralExpression(Ty.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003109 Tracker.getOpenLocation(),
3110 Tracker.getCloseLocation());
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003111 }
Mike Stump11289f42009-09-09 15:08:12 +00003112
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003113 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3114 assert(ParseAs == CastExpr);
3115
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003116 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003117 return ExprError();
3118
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003119 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003120 if (!Result.isInvalid())
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003121 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3122 DeclaratorInfo, CastTy,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003123 Tracker.getCloseLocation(), Result.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003124 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003125 }
Mike Stump11289f42009-09-09 15:08:12 +00003126
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003127 // Not a compound literal, and not followed by a cast-expression.
3128 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003129
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003130 ExprType = SimpleExpr;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003131 Result = ParseExpression();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003132 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003133 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003134 Tok.getLocation(), Result.get());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003135
3136 // Match the ')'.
3137 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003138 SkipUntil(tok::r_paren, StopAtSemi);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003139 return ExprError();
3140 }
Mike Stump11289f42009-09-09 15:08:12 +00003141
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003142 Tracker.consumeClose();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003143 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003144}