blob: 77eed54376098981f0789999e090c484c8748244 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner29375652006-12-04 18:06:35 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expression parsing implementation for C++.
10//
11//===----------------------------------------------------------------------===//
Vassil Vassilev11ad3392017-03-23 15:11:07 +000012#include "clang/Parse/Parser.h"
Erik Verbruggen888d52a2014-01-15 09:15:43 +000013#include "clang/AST/ASTContext.h"
Chandler Carruth757fcd62014-03-04 10:05:20 +000014#include "clang/AST/DeclTemplate.h"
Eli Friedmanc7c97142012-01-04 02:40:39 +000015#include "clang/Basic/PrettyStackTrace.h"
Richard Smith7d182a72012-03-08 23:06:02 +000016#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/Parse/ParseDiagnostic.h"
Vassil Vassilev11ad3392017-03-23 15:11:07 +000018#include "clang/Parse/RAIIObjectsForParser.h"
John McCall8b0666c2010-08-20 18:27:03 +000019#include "clang/Sema/DeclSpec.h"
20#include "clang/Sema/ParsedTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Sema/Scope.h"
Douglas Gregor7861a802009-11-03 01:35:08 +000022#include "llvm/Support/ErrorHandling.h"
Richard Smithb2997f52019-05-21 20:10:50 +000023#include <numeric>
Faisal Vali2b391ab2013-09-26 19:54:12 +000024
Chris Lattner29375652006-12-04 18:06:35 +000025using namespace clang;
26
Alp Tokerf990cef2014-01-07 02:35:33 +000027static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
28 switch (Kind) {
29 // template name
30 case tok::unknown: return 0;
31 // casts
32 case tok::kw_const_cast: return 1;
33 case tok::kw_dynamic_cast: return 2;
34 case tok::kw_reinterpret_cast: return 3;
35 case tok::kw_static_cast: return 4;
36 default:
37 llvm_unreachable("Unknown type for digraph error message.");
38 }
39}
40
Richard Smith55858492011-04-14 21:45:45 +000041// Are the two tokens adjacent in the same source file?
Richard Smith7b3f3222012-06-18 06:11:04 +000042bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
Richard Smith55858492011-04-14 21:45:45 +000043 SourceManager &SM = PP.getSourceManager();
44 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000045 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
Richard Smith55858492011-04-14 21:45:45 +000046 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
47}
48
49// Suggest fixit for "<::" after a cast.
50static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
51 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
52 // Pull '<:' and ':' off token stream.
53 if (!AtDigraph)
54 PP.Lex(DigraphToken);
55 PP.Lex(ColonToken);
56
57 SourceRange Range;
58 Range.setBegin(DigraphToken.getLocation());
59 Range.setEnd(ColonToken.getLocation());
60 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
Alp Tokerf990cef2014-01-07 02:35:33 +000061 << SelectDigraphErrorMessage(Kind)
62 << FixItHint::CreateReplacement(Range, "< ::");
Richard Smith55858492011-04-14 21:45:45 +000063
64 // Update token information to reflect their change in token type.
65 ColonToken.setKind(tok::coloncolon);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000066 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
Richard Smith55858492011-04-14 21:45:45 +000067 ColonToken.setLength(2);
68 DigraphToken.setKind(tok::less);
69 DigraphToken.setLength(1);
70
71 // Push new tokens back to token stream.
Ilya Biryukov929af672019-05-17 09:32:05 +000072 PP.EnterToken(ColonToken, /*IsReinject*/ true);
Richard Smith55858492011-04-14 21:45:45 +000073 if (!AtDigraph)
Ilya Biryukov929af672019-05-17 09:32:05 +000074 PP.EnterToken(DigraphToken, /*IsReinject*/ true);
Richard Smith55858492011-04-14 21:45:45 +000075}
76
Richard Trieu01fc0012011-09-19 19:01:00 +000077// Check for '<::' which should be '< ::' instead of '[:' when following
78// a template name.
79void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
80 bool EnteringContext,
81 IdentifierInfo &II, CXXScopeSpec &SS) {
Richard Trieu02e25db2011-09-20 20:03:50 +000082 if (!Next.is(tok::l_square) || Next.getLength() != 2)
Richard Trieu01fc0012011-09-19 19:01:00 +000083 return;
84
85 Token SecondToken = GetLookAheadToken(2);
Richard Smith7b3f3222012-06-18 06:11:04 +000086 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
Richard Trieu01fc0012011-09-19 19:01:00 +000087 return;
88
89 TemplateTy Template;
90 UnqualifiedId TemplateName;
91 TemplateName.setIdentifier(&II, Tok.getLocation());
92 bool MemberOfUnknownSpecialization;
93 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
94 TemplateName, ObjectType, EnteringContext,
95 Template, MemberOfUnknownSpecialization))
96 return;
97
Alp Tokerf990cef2014-01-07 02:35:33 +000098 FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
99 /*AtDigraph*/false);
Richard Trieu01fc0012011-09-19 19:01:00 +0000100}
101
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000102/// Parse global scope or nested-name-specifier if present.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000103///
104/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
Mike Stump11289f42009-09-09 15:08:12 +0000105/// may be preceded by '::'). Note that this routine will not parse ::new or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000106/// ::delete; it will just leave them in the token stream.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000107///
108/// '::'[opt] nested-name-specifier
109/// '::'
110///
111/// nested-name-specifier:
112/// type-name '::'
113/// namespace-name '::'
114/// nested-name-specifier identifier '::'
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000115/// nested-name-specifier 'template'[opt] simple-template-id '::'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000116///
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000117///
Mike Stump11289f42009-09-09 15:08:12 +0000118/// \param SS the scope specifier that will be set to the parsed
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000119/// nested-name-specifier (or empty)
120///
Mike Stump11289f42009-09-09 15:08:12 +0000121/// \param ObjectType if this nested-name-specifier is being parsed following
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000122/// the "." or "->" of a member access expression, this parameter provides the
123/// type of the object whose members are being accessed.
124///
125/// \param EnteringContext whether we will be entering into the context of
126/// the nested-name-specifier after parsing it.
127///
Douglas Gregore610ada2010-02-24 18:44:31 +0000128/// \param MayBePseudoDestructor When non-NULL, points to a flag that
129/// indicates whether this nested-name-specifier may be part of a
130/// pseudo-destructor name. In this case, the flag will be set false
131/// if we don't actually end up parsing a destructor name. Moreorover,
132/// if we do end up determining that we are parsing a destructor name,
133/// the last component of the nested-name-specifier is not parsed as
134/// part of the scope specifier.
Richard Smith7447af42013-03-26 01:15:19 +0000135///
136/// \param IsTypename If \c true, this nested-name-specifier is known to be
137/// part of a type name. This is used to improve error recovery.
138///
139/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
140/// filled in with the leading identifier in the last component of the
141/// nested-name-specifier, if any.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000142///
Matthias Gehredc01bb42017-03-17 21:41:20 +0000143/// \param OnlyNamespace If true, only considers namespaces in lookup.
144///
John McCall1f476a12010-02-26 08:45:28 +0000145/// \returns true if there was an error parsing a scope specifier
Ilya Biryukovd9971d02019-10-28 09:34:21 +0100146bool Parser::ParseOptionalCXXScopeSpecifier(
147 CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext,
148 bool *MayBePseudoDestructor, bool IsTypename, IdentifierInfo **LastII,
149 bool OnlyNamespace, bool InUsingDeclaration) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000150 assert(getLangOpts().CPlusPlus &&
Chris Lattnerb5134c02009-01-05 01:24:05 +0000151 "Call sites of this function should be guarded by checking for C++");
Mike Stump11289f42009-09-09 15:08:12 +0000152
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000153 if (Tok.is(tok::annot_cxxscope)) {
Richard Smith7447af42013-03-26 01:15:19 +0000154 assert(!LastII && "want last identifier but have already annotated scope");
Nico Weberc60aa712015-02-16 22:32:46 +0000155 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
Douglas Gregor869ad452011-02-24 17:54:50 +0000156 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
157 Tok.getAnnotationRange(),
158 SS);
Richard Smithaf3b3252017-05-18 19:21:48 +0000159 ConsumeAnnotationToken();
John McCall1f476a12010-02-26 08:45:28 +0000160 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000161 }
Chris Lattnerf9b2cd42009-01-04 21:14:15 +0000162
Larisse Voufob959c3c2013-08-06 05:49:26 +0000163 if (Tok.is(tok::annot_template_id)) {
164 // If the current token is an annotated template id, it may already have
165 // a scope specifier. Restore it.
166 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
167 SS = TemplateId->SS;
168 }
169
Nico Weberc60aa712015-02-16 22:32:46 +0000170 // Has to happen before any "return false"s in this function.
171 bool CheckForDestructor = false;
172 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
173 CheckForDestructor = true;
174 *MayBePseudoDestructor = false;
175 }
176
Richard Smith7447af42013-03-26 01:15:19 +0000177 if (LastII)
Craig Topper161e4db2014-05-21 06:02:52 +0000178 *LastII = nullptr;
Richard Smith7447af42013-03-26 01:15:19 +0000179
Douglas Gregor7f741122009-02-25 19:37:18 +0000180 bool HasScopeSpecifier = false;
181
Chris Lattner8a7d10d2009-01-05 03:55:46 +0000182 if (Tok.is(tok::coloncolon)) {
183 // ::new and ::delete aren't nested-name-specifiers.
184 tok::TokenKind NextKind = NextToken().getKind();
185 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
186 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000187
David Majnemere8fb28f2014-12-29 19:19:18 +0000188 if (NextKind == tok::l_brace) {
189 // It is invalid to have :: {, consume the scope qualifier and pretend
190 // like we never saw it.
191 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
192 } else {
193 // '::' - Global scope qualifier.
194 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
195 return true;
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000196
David Majnemere8fb28f2014-12-29 19:19:18 +0000197 HasScopeSpecifier = true;
198 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000199 }
200
Nikola Smiljanic67860242014-09-26 00:28:20 +0000201 if (Tok.is(tok::kw___super)) {
202 SourceLocation SuperLoc = ConsumeToken();
203 if (!Tok.is(tok::coloncolon)) {
204 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
205 return true;
206 }
207
208 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
209 }
210
Richard Smitha9d10012014-10-04 01:57:39 +0000211 if (!HasScopeSpecifier &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000212 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikie15a430a2011-12-04 05:04:18 +0000213 DeclSpec DS(AttrFactory);
214 SourceLocation DeclLoc = Tok.getLocation();
215 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000216
217 SourceLocation CCLoc;
Richard Smith3f846bd2017-02-08 19:58:48 +0000218 // Work around a standard defect: 'decltype(auto)::' is not a
219 // nested-name-specifier.
220 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
221 !TryConsumeToken(tok::coloncolon, CCLoc)) {
David Blaikie15a430a2011-12-04 05:04:18 +0000222 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
223 return false;
224 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000225
David Blaikie15a430a2011-12-04 05:04:18 +0000226 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
227 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
228
229 HasScopeSpecifier = true;
230 }
231
Ilya Biryukovb1296fa2019-05-28 15:21:03 +0000232 // Preferred type might change when parsing qualifiers, we need the original.
233 auto SavedType = PreferredType;
Douglas Gregor7f741122009-02-25 19:37:18 +0000234 while (true) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000235 if (HasScopeSpecifier) {
Ilya Biryukovf1822ec2018-12-03 13:29:17 +0000236 if (Tok.is(tok::code_completion)) {
237 // Code completion for a nested-name-specifier, where the code
238 // completion token follows the '::'.
239 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext,
Ilya Biryukovd9971d02019-10-28 09:34:21 +0100240 InUsingDeclaration, ObjectType.get(),
Ilya Biryukovb1296fa2019-05-28 15:21:03 +0000241 SavedType.get(SS.getBeginLoc()));
Ilya Biryukovf1822ec2018-12-03 13:29:17 +0000242 // Include code completion token into the range of the scope otherwise
243 // when we try to annotate the scope tokens the dangling code completion
244 // token will cause assertion in
245 // Preprocessor::AnnotatePreviousCachedTokens.
246 SS.setEndLoc(Tok.getLocation());
247 cutOffParsing();
248 return true;
249 }
250
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000251 // C++ [basic.lookup.classref]p5:
252 // If the qualified-id has the form
Douglas Gregor308047d2009-09-09 00:23:06 +0000253 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000254 // ::class-name-or-namespace-name::...
Douglas Gregor308047d2009-09-09 00:23:06 +0000255 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000256 // the class-name-or-namespace-name is looked up in global scope as a
257 // class-name or namespace-name.
258 //
259 // To implement this, we clear out the object type as soon as we've
260 // seen a leading '::' or part of a nested-name-specifier.
David Blaikieefdccaa2016-01-15 23:43:34 +0000261 ObjectType = nullptr;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000262 }
Mike Stump11289f42009-09-09 15:08:12 +0000263
Douglas Gregor7f741122009-02-25 19:37:18 +0000264 // nested-name-specifier:
Chris Lattner0eed3a62009-06-26 03:47:46 +0000265 // nested-name-specifier 'template'[opt] simple-template-id '::'
266
267 // Parse the optional 'template' keyword, then make sure we have
268 // 'identifier <' after it.
269 if (Tok.is(tok::kw_template)) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000270 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedman2624be42009-08-29 04:08:08 +0000271 // nested-name-specifier, since they aren't allowed to start with
272 // 'template'.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000273 if (!HasScopeSpecifier && !ObjectType)
Eli Friedman2624be42009-08-29 04:08:08 +0000274 break;
275
Douglas Gregor120635b2009-11-11 16:39:34 +0000276 TentativeParsingAction TPA(*this);
Chris Lattner0eed3a62009-06-26 03:47:46 +0000277 SourceLocation TemplateKWLoc = ConsumeToken();
Richard Smithd091dc12013-12-05 00:58:33 +0000278
Douglas Gregor71395fa2009-11-04 00:56:37 +0000279 UnqualifiedId TemplateName;
280 if (Tok.is(tok::identifier)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000281 // Consume the identifier.
Douglas Gregor120635b2009-11-11 16:39:34 +0000282 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregor71395fa2009-11-04 00:56:37 +0000283 ConsumeToken();
284 } else if (Tok.is(tok::kw_operator)) {
Richard Smithd091dc12013-12-05 00:58:33 +0000285 // We don't need to actually parse the unqualified-id in this case,
286 // because a simple-template-id cannot start with 'operator', but
287 // go ahead and parse it anyway for consistency with the case where
288 // we already annotated the template-id.
289 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor120635b2009-11-11 16:39:34 +0000290 TemplateName)) {
291 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000292 break;
Douglas Gregor120635b2009-11-11 16:39:34 +0000293 }
Richard Smithd091dc12013-12-05 00:58:33 +0000294
Faisal Vali2ab8c152017-12-30 04:15:27 +0000295 if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId &&
296 TemplateName.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000297 Diag(TemplateName.getSourceRange().getBegin(),
298 diag::err_id_after_template_in_nested_name_spec)
299 << TemplateName.getSourceRange();
Douglas Gregor120635b2009-11-11 16:39:34 +0000300 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000301 break;
302 }
303 } else {
Douglas Gregor120635b2009-11-11 16:39:34 +0000304 TPA.Revert();
Chris Lattner0eed3a62009-06-26 03:47:46 +0000305 break;
306 }
Mike Stump11289f42009-09-09 15:08:12 +0000307
Douglas Gregor120635b2009-11-11 16:39:34 +0000308 // If the next token is not '<', we have a qualified-id that refers
Fangrui Song6907ce22018-07-30 19:24:48 +0000309 // to a template name, such as T::template apply, but is not a
Douglas Gregor120635b2009-11-11 16:39:34 +0000310 // template-id.
311 if (Tok.isNot(tok::less)) {
312 TPA.Revert();
313 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000314 }
315
Douglas Gregor120635b2009-11-11 16:39:34 +0000316 // Commit to parsing the template-id.
317 TPA.Commit();
Douglas Gregorbb119652010-06-16 23:00:59 +0000318 TemplateTy Template;
Richard Smithfd3dae02017-01-20 00:20:39 +0000319 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
320 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
321 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000322 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
323 TemplateName, false))
Douglas Gregorbb119652010-06-16 23:00:59 +0000324 return true;
325 } else
John McCall1f476a12010-02-26 08:45:28 +0000326 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000327
Chris Lattner0eed3a62009-06-26 03:47:46 +0000328 continue;
329 }
Mike Stump11289f42009-09-09 15:08:12 +0000330
Douglas Gregor7f741122009-02-25 19:37:18 +0000331 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump11289f42009-09-09 15:08:12 +0000332 // We have
Douglas Gregor7f741122009-02-25 19:37:18 +0000333 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000334 // template-id '::'
Douglas Gregor7f741122009-02-25 19:37:18 +0000335 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000336 // So we need to check whether the template-id is a simple-template-id of
337 // the right kind (it should name a type or be dependent), and then
Douglas Gregorb67535d2009-03-31 00:43:58 +0000338 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +0000339 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregore610ada2010-02-24 18:44:31 +0000340 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
341 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000342 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000343 }
344
Richard Smith7447af42013-03-26 01:15:19 +0000345 if (LastII)
346 *LastII = TemplateId->Name;
347
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000348 // Consume the template-id token.
Richard Smithaf3b3252017-05-18 19:21:48 +0000349 ConsumeAnnotationToken();
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000350
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000351 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
352 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000353
David Blaikie8c045bc2011-11-07 03:30:03 +0000354 HasScopeSpecifier = true;
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000355
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000356 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000357 TemplateId->NumArgs);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000358
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000359 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000360 SS,
361 TemplateId->TemplateKWLoc,
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000362 TemplateId->Template,
363 TemplateId->TemplateNameLoc,
364 TemplateId->LAngleLoc,
365 TemplateArgsPtr,
366 TemplateId->RAngleLoc,
367 CCLoc,
368 EnteringContext)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000369 SourceLocation StartLoc
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000370 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
371 : TemplateId->TemplateNameLoc;
372 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner704edfb2009-06-26 03:45:46 +0000373 }
Argyrios Kyrtzidis13935672011-05-03 18:45:38 +0000374
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000375 continue;
Douglas Gregor7f741122009-02-25 19:37:18 +0000376 }
377
Chris Lattnere2355f72009-06-26 03:52:38 +0000378 // The rest of the nested-name-specifier possibilities start with
379 // tok::identifier.
380 if (Tok.isNot(tok::identifier))
381 break;
382
383 IdentifierInfo &II = *Tok.getIdentifierInfo();
384
385 // nested-name-specifier:
386 // type-name '::'
387 // namespace-name '::'
388 // nested-name-specifier identifier '::'
389 Token Next = NextToken();
Serge Pavlovd931b9f2016-08-08 04:02:15 +0000390 Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
391 ObjectType);
392
Chris Lattner1c428032009-12-07 01:36:53 +0000393 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
394 // and emit a fixit hint for it.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000395 if (Next.is(tok::colon) && !ColonIsSacred) {
Serge Pavlovd931b9f2016-08-08 04:02:15 +0000396 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000397 EnteringContext) &&
398 // If the token after the colon isn't an identifier, it's still an
399 // error, but they probably meant something else strange so don't
400 // recover like this.
401 PP.LookAhead(1).is(tok::identifier)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000402 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
Douglas Gregora771f462010-03-31 17:46:05 +0000403 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregor90d554e2010-02-21 18:36:56 +0000404 // Recover as if the user wrote '::'.
405 Next.setKind(tok::coloncolon);
406 }
Chris Lattner1c428032009-12-07 01:36:53 +0000407 }
David Majnemerf58efd92014-12-29 23:12:23 +0000408
409 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
410 // It is invalid to have :: {, consume the scope qualifier and pretend
411 // like we never saw it.
412 Token Identifier = Tok; // Stash away the identifier.
413 ConsumeToken(); // Eat the identifier, current token is now '::'.
David Majnemerec3f49d2014-12-29 23:24:27 +0000414 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
415 << tok::identifier;
David Majnemerf58efd92014-12-29 23:12:23 +0000416 UnconsumeToken(Identifier); // Stick the identifier back.
417 Next = NextToken(); // Point Next at the '{' token.
418 }
419
Chris Lattnere2355f72009-06-26 03:52:38 +0000420 if (Next.is(tok::coloncolon)) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +0000421 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Serge Pavlovd931b9f2016-08-08 04:02:15 +0000422 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, IdInfo)) {
Douglas Gregore610ada2010-02-24 18:44:31 +0000423 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000424 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000425 }
426
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000427 if (ColonIsSacred) {
428 const Token &Next2 = GetLookAheadToken(2);
429 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
430 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
431 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
432 << Next2.getName()
433 << FixItHint::CreateReplacement(Next.getLocation(), ":");
434 Token ColonColon;
435 PP.Lex(ColonColon);
436 ColonColon.setKind(tok::colon);
Ilya Biryukov929af672019-05-17 09:32:05 +0000437 PP.EnterToken(ColonColon, /*IsReinject*/ true);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000438 break;
439 }
440 }
441
Richard Smith7447af42013-03-26 01:15:19 +0000442 if (LastII)
443 *LastII = &II;
444
Chris Lattnere2355f72009-06-26 03:52:38 +0000445 // We have an identifier followed by a '::'. Lookup this name
446 // as the name in a nested-name-specifier.
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000447 Token Identifier = Tok;
Chris Lattnere2355f72009-06-26 03:52:38 +0000448 SourceLocation IdLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000449 assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
Chris Lattner1c428032009-12-07 01:36:53 +0000450 "NextToken() not working properly!");
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000451 Token ColonColon = Tok;
Chris Lattnere2355f72009-06-26 03:52:38 +0000452 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000453
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000454 bool IsCorrectedToColon = false;
Craig Topper161e4db2014-05-21 06:02:52 +0000455 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
Matthias Gehredc01bb42017-03-17 21:41:20 +0000456 if (Actions.ActOnCXXNestedNameSpecifier(
457 getCurScope(), IdInfo, EnteringContext, SS, false,
458 CorrectionFlagPtr, OnlyNamespace)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000459 // Identifier is not recognized as a nested name, but we can have
460 // mistyped '::' instead of ':'.
461 if (CorrectionFlagPtr && IsCorrectedToColon) {
462 ColonColon.setKind(tok::colon);
Ilya Biryukov929af672019-05-17 09:32:05 +0000463 PP.EnterToken(Tok, /*IsReinject*/ true);
464 PP.EnterToken(ColonColon, /*IsReinject*/ true);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000465 Tok = Identifier;
466 break;
467 }
Douglas Gregor90c99722011-02-24 00:17:56 +0000468 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000469 }
470 HasScopeSpecifier = true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000471 continue;
472 }
Mike Stump11289f42009-09-09 15:08:12 +0000473
Richard Trieu01fc0012011-09-19 19:01:00 +0000474 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smith55858492011-04-14 21:45:45 +0000475
Chris Lattnere2355f72009-06-26 03:52:38 +0000476 // nested-name-specifier:
477 // type-name '<'
478 if (Next.is(tok::less)) {
479 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000480 UnqualifiedId TemplateName;
481 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor786123d2010-05-21 23:18:07 +0000482 bool MemberOfUnknownSpecialization;
Fangrui Song6907ce22018-07-30 19:24:48 +0000483 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000484 /*hasTemplateKeyword=*/false,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000485 TemplateName,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000486 ObjectType,
Douglas Gregore861bac2009-08-25 22:51:20 +0000487 EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000488 Template,
489 MemberOfUnknownSpecialization)) {
Richard Smithb23c5e82019-05-09 03:31:27 +0000490 // If lookup didn't find anything, we treat the name as a template-name
491 // anyway. C++20 requires this, and in prior language modes it improves
492 // error recovery. But before we commit to this, check that we actually
493 // have something that looks like a template-argument-list next.
494 if (!IsTypename && TNK == TNK_Undeclared_template &&
495 isTemplateArgumentList(1) == TPResult::False)
496 break;
497
David Blaikie8c045bc2011-11-07 03:30:03 +0000498 // We have found a template name, so annotate this token
Chris Lattnere2355f72009-06-26 03:52:38 +0000499 // with a template-id annotation. We do not permit the
500 // template-id to be translated into a type annotation,
501 // because some clients (e.g., the parsing of class template
502 // specializations) still want to see the original template-id
503 // token.
Douglas Gregor71395fa2009-11-04 00:56:37 +0000504 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000505 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
506 TemplateName, false))
John McCall1f476a12010-02-26 08:45:28 +0000507 return true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000508 continue;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000509 }
510
Fangrui Song6907ce22018-07-30 19:24:48 +0000511 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Richard Smithb23c5e82019-05-09 03:31:27 +0000512 (IsTypename || isTemplateArgumentList(1) == TPResult::True)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000513 // We have something like t::getAs<T>, where getAs is a
Douglas Gregor20c38a72010-05-21 23:43:39 +0000514 // member of an unknown specialization. However, this will only
515 // parse correctly as a template, so suggest the keyword 'template'
516 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000517 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000518 if (getLangOpts().MicrosoftExt)
Francois Pichet93921652011-04-22 08:25:24 +0000519 DiagID = diag::warn_missing_dependent_template_keyword;
Fangrui Song6907ce22018-07-30 19:24:48 +0000520
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000521 Diag(Tok.getLocation(), DiagID)
Douglas Gregor20c38a72010-05-21 23:43:39 +0000522 << II.getName()
523 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
Richard Smithfd3dae02017-01-20 00:20:39 +0000524
525 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
Richard Smith79810042018-05-11 02:43:08 +0000526 getCurScope(), SS, Tok.getLocation(), TemplateName, ObjectType,
Richard Smithfd3dae02017-01-20 00:20:39 +0000527 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
Douglas Gregorbb119652010-06-16 23:00:59 +0000528 // Consume the identifier.
529 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000530 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
531 TemplateName, false))
532 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000533 }
534 else
Fangrui Song6907ce22018-07-30 19:24:48 +0000535 return true;
536
537 continue;
Chris Lattnere2355f72009-06-26 03:52:38 +0000538 }
539 }
540
Douglas Gregor7f741122009-02-25 19:37:18 +0000541 // We don't have any tokens that form the beginning of a
542 // nested-name-specifier, so we're done.
543 break;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000544 }
Mike Stump11289f42009-09-09 15:08:12 +0000545
Douglas Gregore610ada2010-02-24 18:44:31 +0000546 // Even if we didn't see any pieces of a nested-name-specifier, we
547 // still check whether there is a tilde in this position, which
548 // indicates a potential pseudo-destructor.
549 if (CheckForDestructor && Tok.is(tok::tilde))
550 *MayBePseudoDestructor = true;
551
John McCall1f476a12010-02-26 08:45:28 +0000552 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000553}
554
Richard Smith7e8fe672019-10-14 21:53:03 +0000555ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS,
556 bool isAddressOfOperand,
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000557 Token &Replacement) {
Richard Smith7e8fe672019-10-14 21:53:03 +0000558 ExprResult E;
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000559
Richard Smith7e8fe672019-10-14 21:53:03 +0000560 // We may have already annotated this id-expression.
561 switch (Tok.getKind()) {
562 case tok::annot_non_type: {
563 NamedDecl *ND = getNonTypeAnnotation(Tok);
564 SourceLocation Loc = ConsumeAnnotationToken();
565 E = Actions.ActOnNameClassifiedAsNonType(getCurScope(), SS, ND, Loc, Tok);
566 break;
567 }
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000568
Richard Smith7e8fe672019-10-14 21:53:03 +0000569 case tok::annot_non_type_dependent: {
570 IdentifierInfo *II = getIdentifierAnnotation(Tok);
571 SourceLocation Loc = ConsumeAnnotationToken();
572
573 // This is only the direct operand of an & operator if it is not
574 // followed by a postfix-expression suffix.
575 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
576 isAddressOfOperand = false;
577
578 E = Actions.ActOnNameClassifiedAsDependentNonType(SS, II, Loc,
579 isAddressOfOperand);
580 break;
581 }
582
583 case tok::annot_non_type_undeclared: {
584 assert(SS.isEmpty() &&
585 "undeclared non-type annotation should be unqualified");
586 IdentifierInfo *II = getIdentifierAnnotation(Tok);
587 SourceLocation Loc = ConsumeAnnotationToken();
588 E = Actions.ActOnNameClassifiedAsUndeclaredNonType(II, Loc);
589 break;
590 }
591
592 default:
593 SourceLocation TemplateKWLoc;
594 UnqualifiedId Name;
595 if (ParseUnqualifiedId(SS,
596 /*EnteringContext=*/false,
597 /*AllowDestructorName=*/false,
598 /*AllowConstructorName=*/false,
599 /*AllowDeductionGuide=*/false,
600 /*ObjectType=*/nullptr, &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 E = Actions.ActOnIdExpression(
609 getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren),
610 isAddressOfOperand, /*CCC=*/nullptr, /*IsInlineAsmIdentifier=*/false,
611 &Replacement);
612 break;
613 }
614
Richard Smithc2dead42018-06-27 01:32:04 +0000615 if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less))
616 checkPotentialAngleBracket(E);
617 return E;
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000618}
619
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000620/// ParseCXXIdExpression - Handle id-expression.
621///
622/// id-expression:
623/// unqualified-id
624/// qualified-id
625///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000626/// qualified-id:
627/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
628/// '::' identifier
629/// '::' operator-function-id
Douglas Gregora727cb92009-06-30 22:34:41 +0000630/// '::' template-id
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000631///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000632/// NOTE: The standard specifies that, for qualified-id, the parser does not
633/// expect:
634///
635/// '::' conversion-function-id
636/// '::' '~' class-name
637///
638/// This may cause a slight inconsistency on diagnostics:
639///
640/// class C {};
641/// namespace A {}
642/// void f() {
643/// :: A :: ~ C(); // Some Sema error about using destructor with a
644/// // namespace.
645/// :: ~ C(); // Some Parser error like 'unexpected ~'.
646/// }
647///
648/// We simplify the parser a bit and make it work like:
649///
650/// qualified-id:
651/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
652/// '::' unqualified-id
653///
654/// That way Sema can handle and report similar errors for namespaces and the
655/// global scope.
656///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000657/// The isAddressOfOperand parameter indicates that this id-expression is a
658/// direct operand of the address-of operator. This is, besides member contexts,
659/// the only place where a qualified-id naming a non-static class member may
660/// appear.
661///
John McCalldadc5752010-08-24 06:29:42 +0000662ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000663 // qualified-id:
664 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
665 // '::' unqualified-id
666 //
667 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +0000668 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000669
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000670 Token Replacement;
Nico Weber01a46ad2015-02-15 06:15:40 +0000671 ExprResult Result =
672 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000673 if (Result.isUnset()) {
674 // If the ExprResult is valid but null, then typo correction suggested a
675 // keyword replacement that needs to be reparsed.
676 UnconsumeToken(Replacement);
677 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
678 }
679 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
680 "for a previous keyword suggestion");
681 return Result;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000682}
683
Richard Smith21b3ab42013-05-09 21:36:41 +0000684/// ParseLambdaExpression - Parse a C++11 lambda expression.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000685///
686/// lambda-expression:
687/// lambda-introducer lambda-declarator[opt] compound-statement
Hamza Sood8205a812019-05-04 10:49:46 +0000688/// lambda-introducer '<' template-parameter-list '>'
689/// lambda-declarator[opt] compound-statement
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000690///
691/// lambda-introducer:
692/// '[' lambda-capture[opt] ']'
693///
694/// lambda-capture:
695/// capture-default
696/// capture-list
697/// capture-default ',' capture-list
698///
699/// capture-default:
700/// '&'
701/// '='
702///
703/// capture-list:
704/// capture
705/// capture-list ',' capture
706///
707/// capture:
Richard Smith21b3ab42013-05-09 21:36:41 +0000708/// simple-capture
709/// init-capture [C++1y]
710///
711/// simple-capture:
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000712/// identifier
713/// '&' identifier
714/// 'this'
715///
Richard Smith21b3ab42013-05-09 21:36:41 +0000716/// init-capture: [C++1y]
717/// identifier initializer
718/// '&' identifier initializer
719///
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000720/// lambda-declarator:
721/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
722/// 'mutable'[opt] exception-specification[opt]
723/// trailing-return-type[opt]
724///
725ExprResult Parser::ParseLambdaExpression() {
726 // Parse lambda-introducer.
727 LambdaIntroducer Intro;
Richard Smithe9585062019-05-20 18:01:54 +0000728 if (ParseLambdaIntroducer(Intro)) {
David Majnemer234b8182015-01-12 03:36:37 +0000729 SkipUntil(tok::r_square, StopAtSemi);
730 SkipUntil(tok::l_brace, StopAtSemi);
731 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000732 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000733 }
734
735 return ParseLambdaExpressionAfterIntroducer(Intro);
736}
737
Richard Smithe9585062019-05-20 18:01:54 +0000738/// Use lookahead and potentially tentative parsing to determine if we are
739/// looking at a C++11 lambda expression, and parse it if we are.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000740///
741/// If we are not looking at a lambda expression, returns ExprError().
742ExprResult Parser::TryParseLambdaExpression() {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000743 assert(getLangOpts().CPlusPlus11
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000744 && Tok.is(tok::l_square)
745 && "Not at the start of a possible lambda expression.");
746
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000747 const Token Next = NextToken();
748 if (Next.is(tok::eof)) // Nothing else to lookup here...
749 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000750
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000751 const Token After = GetLookAheadToken(2);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000752 // If lookahead indicates this is a lambda...
753 if (Next.is(tok::r_square) || // []
754 Next.is(tok::equal) || // [=
755 (Next.is(tok::amp) && // [&] or [&,
Richard Smithb2997f52019-05-21 20:10:50 +0000756 After.isOneOf(tok::r_square, tok::comma)) ||
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000757 (Next.is(tok::identifier) && // [identifier]
Richard Smithb2997f52019-05-21 20:10:50 +0000758 After.is(tok::r_square)) ||
759 Next.is(tok::ellipsis)) { // [...
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000760 return ParseLambdaExpression();
761 }
762
Eli Friedmanc7c97142012-01-04 02:40:39 +0000763 // If lookahead indicates an ObjC message send...
764 // [identifier identifier
Richard Smithe9585062019-05-20 18:01:54 +0000765 if (Next.is(tok::identifier) && After.is(tok::identifier))
Eli Friedmanc7c97142012-01-04 02:40:39 +0000766 return ExprEmpty();
Fangrui Song6907ce22018-07-30 19:24:48 +0000767
Eli Friedmanc7c97142012-01-04 02:40:39 +0000768 // Here, we're stuck: lambda introducers and Objective-C message sends are
769 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
770 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
771 // writing two routines to parse a lambda introducer, just try to parse
772 // a lambda introducer first, and fall back if that fails.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000773 LambdaIntroducer Intro;
Richard Smithe9585062019-05-20 18:01:54 +0000774 {
775 TentativeParsingAction TPA(*this);
776 LambdaIntroducerTentativeParse Tentative;
777 if (ParseLambdaIntroducer(Intro, &Tentative)) {
778 TPA.Commit();
779 return ExprError();
780 }
781
782 switch (Tentative) {
783 case LambdaIntroducerTentativeParse::Success:
784 TPA.Commit();
785 break;
786
787 case LambdaIntroducerTentativeParse::Incomplete:
788 // Didn't fully parse the lambda-introducer, try again with a
789 // non-tentative parse.
790 TPA.Revert();
791 Intro = LambdaIntroducer();
792 if (ParseLambdaIntroducer(Intro))
793 return ExprError();
794 break;
795
796 case LambdaIntroducerTentativeParse::MessageSend:
797 case LambdaIntroducerTentativeParse::Invalid:
798 // Not a lambda-introducer, might be a message send.
799 TPA.Revert();
800 return ExprEmpty();
801 }
802 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000803
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000804 return ParseLambdaExpressionAfterIntroducer(Intro);
805}
806
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000807/// Parse a lambda introducer.
Richard Smithf44d2a82013-05-21 22:21:19 +0000808/// \param Intro A LambdaIntroducer filled in with information about the
809/// contents of the lambda-introducer.
Richard Smithe9585062019-05-20 18:01:54 +0000810/// \param Tentative If non-null, we are disambiguating between a
811/// lambda-introducer and some other construct. In this mode, we do not
812/// produce any diagnostics or take any other irreversible action unless
813/// we're sure that this is a lambda-expression.
814/// \return \c true if parsing (or disambiguation) failed with a diagnostic and
815/// the caller should bail out / recover.
816bool Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
817 LambdaIntroducerTentativeParse *Tentative) {
818 if (Tentative)
819 *Tentative = LambdaIntroducerTentativeParse::Success;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000820
821 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000822 BalancedDelimiterTracker T(*this, tok::l_square);
823 T.consumeOpen();
824
825 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000826
Richard Smithe9585062019-05-20 18:01:54 +0000827 bool First = true;
828
829 // Produce a diagnostic if we're not tentatively parsing; otherwise track
830 // that our parse has failed.
831 auto Invalid = [&](llvm::function_ref<void()> Action) {
832 if (Tentative) {
833 *Tentative = LambdaIntroducerTentativeParse::Invalid;
834 return false;
835 }
836 Action();
837 return true;
838 };
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000839
Richard Smithb2997f52019-05-21 20:10:50 +0000840 // Perform some irreversible action if this is a non-tentative parse;
841 // otherwise note that our actions were incomplete.
842 auto NonTentativeAction = [&](llvm::function_ref<void()> Action) {
843 if (Tentative)
844 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
845 else
846 Action();
847 };
848
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000849 // Parse capture-default.
850 if (Tok.is(tok::amp) &&
851 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
852 Intro.Default = LCD_ByRef;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000853 Intro.DefaultLoc = ConsumeToken();
Richard Smithe9585062019-05-20 18:01:54 +0000854 First = false;
855 if (!Tok.getIdentifierInfo()) {
856 // This can only be a lambda; no need for tentative parsing any more.
857 // '[[and]]' can still be an attribute, though.
858 Tentative = nullptr;
859 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000860 } else if (Tok.is(tok::equal)) {
861 Intro.Default = LCD_ByCopy;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000862 Intro.DefaultLoc = ConsumeToken();
Richard Smithe9585062019-05-20 18:01:54 +0000863 First = false;
864 Tentative = nullptr;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000865 }
866
867 while (Tok.isNot(tok::r_square)) {
Richard Smithe9585062019-05-20 18:01:54 +0000868 if (!First) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000869 if (Tok.isNot(tok::comma)) {
Douglas Gregor721b14d2012-07-31 00:50:07 +0000870 // Provide a completion for a lambda introducer here. Except
871 // in Objective-C, where this is Almost Surely meant to be a message
872 // send. In that case, fail here and let the ObjC message
873 // expression parser perform the completion.
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000874 if (Tok.is(tok::code_completion) &&
Richard Smithe9585062019-05-20 18:01:54 +0000875 !(getLangOpts().ObjC && Tentative)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000876 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
Douglas Gregord8c61782012-02-15 15:34:24 +0000877 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000878 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000879 break;
880 }
881
Richard Smithe9585062019-05-20 18:01:54 +0000882 return Invalid([&] {
883 Diag(Tok.getLocation(), diag::err_expected_comma_or_rsquare);
884 });
Douglas Gregord8c61782012-02-15 15:34:24 +0000885 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000886 ConsumeToken();
887 }
888
Douglas Gregord8c61782012-02-15 15:34:24 +0000889 if (Tok.is(tok::code_completion)) {
890 // If we're in Objective-C++ and we have a bare '[', then this is more
891 // likely to be a message receiver.
Richard Smithe9585062019-05-20 18:01:54 +0000892 if (getLangOpts().ObjC && Tentative && First)
Douglas Gregord8c61782012-02-15 15:34:24 +0000893 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
894 else
Fangrui Song6907ce22018-07-30 19:24:48 +0000895 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
Douglas Gregord8c61782012-02-15 15:34:24 +0000896 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000897 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000898 break;
899 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000900
Richard Smithe9585062019-05-20 18:01:54 +0000901 First = false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000902
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000903 // Parse capture.
904 LambdaCaptureKind Kind = LCK_ByCopy;
Richard Smith42b10572015-11-11 01:36:17 +0000905 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000906 SourceLocation Loc;
Craig Topper161e4db2014-05-21 06:02:52 +0000907 IdentifierInfo *Id = nullptr;
Richard Smithb2997f52019-05-21 20:10:50 +0000908 SourceLocation EllipsisLocs[4];
Richard Smith21b3ab42013-05-09 21:36:41 +0000909 ExprResult Init;
Alexander Shaposhnikov832f49b2018-07-16 07:23:47 +0000910 SourceLocation LocStart = Tok.getLocation();
Faisal Validc6b5962016-03-21 09:25:37 +0000911
912 if (Tok.is(tok::star)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000913 Loc = ConsumeToken();
Faisal Validc6b5962016-03-21 09:25:37 +0000914 if (Tok.is(tok::kw_this)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000915 ConsumeToken();
916 Kind = LCK_StarThis;
Faisal Validc6b5962016-03-21 09:25:37 +0000917 } else {
Richard Smithe9585062019-05-20 18:01:54 +0000918 return Invalid([&] {
919 Diag(Tok.getLocation(), diag::err_expected_star_this_capture);
920 });
Faisal Validc6b5962016-03-21 09:25:37 +0000921 }
922 } else if (Tok.is(tok::kw_this)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000923 Kind = LCK_This;
924 Loc = ConsumeToken();
925 } else {
Richard Smithb2997f52019-05-21 20:10:50 +0000926 TryConsumeToken(tok::ellipsis, EllipsisLocs[0]);
927
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000928 if (Tok.is(tok::amp)) {
929 Kind = LCK_ByRef;
930 ConsumeToken();
Douglas Gregord8c61782012-02-15 15:34:24 +0000931
932 if (Tok.is(tok::code_completion)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000933 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
Douglas Gregord8c61782012-02-15 15:34:24 +0000934 /*AfterAmpersand=*/true);
Alp Toker1c583cc2014-05-02 03:43:14 +0000935 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000936 break;
937 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000938 }
939
Richard Smithb2997f52019-05-21 20:10:50 +0000940 TryConsumeToken(tok::ellipsis, EllipsisLocs[1]);
941
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000942 if (Tok.is(tok::identifier)) {
943 Id = Tok.getIdentifierInfo();
944 Loc = ConsumeToken();
945 } else if (Tok.is(tok::kw_this)) {
Richard Smithe9585062019-05-20 18:01:54 +0000946 return Invalid([&] {
947 // FIXME: Suggest a fixit here.
948 Diag(Tok.getLocation(), diag::err_this_captured_by_reference);
949 });
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000950 } else {
Richard Smithe9585062019-05-20 18:01:54 +0000951 return Invalid([&] {
952 Diag(Tok.getLocation(), diag::err_expected_capture);
953 });
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000954 }
Richard Smith21b3ab42013-05-09 21:36:41 +0000955
Richard Smithb2997f52019-05-21 20:10:50 +0000956 TryConsumeToken(tok::ellipsis, EllipsisLocs[2]);
957
Richard Smith21b3ab42013-05-09 21:36:41 +0000958 if (Tok.is(tok::l_paren)) {
959 BalancedDelimiterTracker Parens(*this, tok::l_paren);
960 Parens.consumeOpen();
961
Richard Smith42b10572015-11-11 01:36:17 +0000962 InitKind = LambdaCaptureInitKind::DirectInit;
963
Richard Smith21b3ab42013-05-09 21:36:41 +0000964 ExprVector Exprs;
965 CommaLocsTy Commas;
Richard Smithe9585062019-05-20 18:01:54 +0000966 if (Tentative) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000967 Parens.skipToEnd();
Richard Smithe9585062019-05-20 18:01:54 +0000968 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
Richard Smithf44d2a82013-05-21 22:21:19 +0000969 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith21b3ab42013-05-09 21:36:41 +0000970 Parens.skipToEnd();
971 Init = ExprError();
972 } else {
973 Parens.consumeClose();
974 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
975 Parens.getCloseLocation(),
976 Exprs);
977 }
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000978 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000979 // Each lambda init-capture forms its own full expression, which clears
980 // Actions.MaybeODRUseExprs. So create an expression evaluation context
981 // to save the necessary state, and restore it later.
Faisal Valid143a0c2017-04-01 21:30:49 +0000982 EnterExpressionEvaluationContext EC(
983 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith42b10572015-11-11 01:36:17 +0000984
985 if (TryConsumeToken(tok::equal))
986 InitKind = LambdaCaptureInitKind::CopyInit;
987 else
988 InitKind = LambdaCaptureInitKind::ListInit;
Richard Smith21b3ab42013-05-09 21:36:41 +0000989
Richard Smithe9585062019-05-20 18:01:54 +0000990 if (!Tentative) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000991 Init = ParseInitializer();
Richard Smith215f4232015-02-11 02:41:33 +0000992 } else if (Tok.is(tok::l_brace)) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000993 BalancedDelimiterTracker Braces(*this, tok::l_brace);
994 Braces.consumeOpen();
995 Braces.skipToEnd();
Richard Smithe9585062019-05-20 18:01:54 +0000996 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
Richard Smithf44d2a82013-05-21 22:21:19 +0000997 } else {
998 // We're disambiguating this:
999 //
1000 // [..., x = expr
1001 //
1002 // We need to find the end of the following expression in order to
Richard Smith9e2f0a42014-04-13 04:31:48 +00001003 // determine whether this is an Obj-C message send's receiver, a
1004 // C99 designator, or a lambda init-capture.
Richard Smithf44d2a82013-05-21 22:21:19 +00001005 //
1006 // Parse the expression to find where it ends, and annotate it back
1007 // onto the tokens. We would have parsed this expression the same way
1008 // in either case: both the RHS of an init-capture and the RHS of an
1009 // assignment expression are parsed as an initializer-clause, and in
1010 // neither case can anything be added to the scope between the '[' and
1011 // here.
1012 //
1013 // FIXME: This is horrible. Adding a mechanism to skip an expression
1014 // would be much cleaner.
1015 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
1016 // that instead. (And if we see a ':' with no matching '?', we can
1017 // classify this as an Obj-C message send.)
1018 SourceLocation StartLoc = Tok.getLocation();
1019 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
1020 Init = ParseInitializer();
Akira Hatanaka51e60f92016-12-20 02:11:29 +00001021 if (!Init.isInvalid())
1022 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
Richard Smithf44d2a82013-05-21 22:21:19 +00001023
1024 if (Tok.getLocation() != StartLoc) {
1025 // Back out the lexing of the token after the initializer.
1026 PP.RevertCachedTokens(1);
1027
1028 // Replace the consumed tokens with an appropriate annotation.
1029 Tok.setLocation(StartLoc);
1030 Tok.setKind(tok::annot_primary_expr);
1031 setExprAnnotation(Tok, Init);
1032 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
1033 PP.AnnotateCachedTokens(Tok);
1034
1035 // Consume the annotated initializer.
Richard Smithaf3b3252017-05-18 19:21:48 +00001036 ConsumeAnnotationToken();
Richard Smithf44d2a82013-05-21 22:21:19 +00001037 }
1038 }
Richard Smithe9585062019-05-20 18:01:54 +00001039 }
Richard Smithb2997f52019-05-21 20:10:50 +00001040
1041 TryConsumeToken(tok::ellipsis, EllipsisLocs[3]);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001042 }
Richard Smithe9585062019-05-20 18:01:54 +00001043
1044 // Check if this is a message send before we act on a possible init-capture.
1045 if (Tentative && Tok.is(tok::identifier) &&
1046 NextToken().isOneOf(tok::colon, tok::r_square)) {
1047 // This can only be a message send. We're done with disambiguation.
1048 *Tentative = LambdaIntroducerTentativeParse::MessageSend;
1049 return false;
1050 }
1051
Richard Smithb2997f52019-05-21 20:10:50 +00001052 // Ensure that any ellipsis was in the right place.
1053 SourceLocation EllipsisLoc;
1054 if (std::any_of(std::begin(EllipsisLocs), std::end(EllipsisLocs),
1055 [](SourceLocation Loc) { return Loc.isValid(); })) {
1056 // The '...' should appear before the identifier in an init-capture, and
1057 // after the identifier otherwise.
1058 bool InitCapture = InitKind != LambdaCaptureInitKind::NoInit;
1059 SourceLocation *ExpectedEllipsisLoc =
1060 !InitCapture ? &EllipsisLocs[2] :
1061 Kind == LCK_ByRef ? &EllipsisLocs[1] :
1062 &EllipsisLocs[0];
1063 EllipsisLoc = *ExpectedEllipsisLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001064
Richard Smithb2997f52019-05-21 20:10:50 +00001065 unsigned DiagID = 0;
1066 if (EllipsisLoc.isInvalid()) {
1067 DiagID = diag::err_lambda_capture_misplaced_ellipsis;
1068 for (SourceLocation Loc : EllipsisLocs) {
1069 if (Loc.isValid())
1070 EllipsisLoc = Loc;
1071 }
1072 } else {
1073 unsigned NumEllipses = std::accumulate(
1074 std::begin(EllipsisLocs), std::end(EllipsisLocs), 0,
1075 [](int N, SourceLocation Loc) { return N + Loc.isValid(); });
1076 if (NumEllipses > 1)
1077 DiagID = diag::err_lambda_capture_multiple_ellipses;
1078 }
1079 if (DiagID) {
1080 NonTentativeAction([&] {
1081 // Point the diagnostic at the first misplaced ellipsis.
1082 SourceLocation DiagLoc;
1083 for (SourceLocation &Loc : EllipsisLocs) {
1084 if (&Loc != ExpectedEllipsisLoc && Loc.isValid()) {
1085 DiagLoc = Loc;
1086 break;
1087 }
1088 }
1089 assert(DiagLoc.isValid() && "no location for diagnostic");
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001090
Richard Smithb2997f52019-05-21 20:10:50 +00001091 // Issue the diagnostic and produce fixits showing where the ellipsis
1092 // should have been written.
1093 auto &&D = Diag(DiagLoc, DiagID);
1094 if (DiagID == diag::err_lambda_capture_misplaced_ellipsis) {
1095 SourceLocation ExpectedLoc =
1096 InitCapture ? Loc
1097 : Lexer::getLocForEndOfToken(
1098 Loc, 0, PP.getSourceManager(), getLangOpts());
1099 D << InitCapture << FixItHint::CreateInsertion(ExpectedLoc, "...");
1100 }
1101 for (SourceLocation &Loc : EllipsisLocs) {
1102 if (&Loc != ExpectedEllipsisLoc && Loc.isValid())
1103 D << FixItHint::CreateRemoval(Loc);
1104 }
1105 });
1106 }
1107 }
1108
1109 // Process the init-capture initializers now rather than delaying until we
1110 // form the lambda-expression so that they can be handled in the context
1111 // enclosing the lambda-expression, rather than in the context of the
1112 // lambda-expression itself.
Richard Smith42b10572015-11-11 01:36:17 +00001113 ParsedType InitCaptureType;
Richard Smithb2997f52019-05-21 20:10:50 +00001114 if (Init.isUsable())
Volodymyr Sapsaib0f1aae2017-08-22 17:55:19 +00001115 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
Richard Smithb2997f52019-05-21 20:10:50 +00001116 if (Init.isUsable()) {
1117 NonTentativeAction([&] {
Richard Smithe9585062019-05-20 18:01:54 +00001118 // Get the pointer and store it in an lvalue, so we can use it as an
1119 // out argument.
1120 Expr *InitExpr = Init.get();
1121 // This performs any lvalue-to-rvalue conversions if necessary, which
1122 // can affect what gets captured in the containing decl-context.
1123 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
Richard Smithb2997f52019-05-21 20:10:50 +00001124 Loc, Kind == LCK_ByRef, EllipsisLoc, Id, InitKind, InitExpr);
Richard Smithe9585062019-05-20 18:01:54 +00001125 Init = InitExpr;
Richard Smithb2997f52019-05-21 20:10:50 +00001126 });
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001127 }
Alexander Shaposhnikov832f49b2018-07-16 07:23:47 +00001128
1129 SourceLocation LocEnd = PrevTokLocation;
1130
Richard Smith42b10572015-11-11 01:36:17 +00001131 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
Alexander Shaposhnikov832f49b2018-07-16 07:23:47 +00001132 InitCaptureType, SourceRange(LocStart, LocEnd));
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001133 }
1134
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001135 T.consumeClose();
1136 Intro.Range.setEnd(T.getCloseLocation());
Richard Smithe9585062019-05-20 18:01:54 +00001137 return false;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001138}
1139
Gauthier Harnisch796ed032019-06-14 08:56:20 +00001140static void tryConsumeLambdaSpecifierToken(Parser &P,
1141 SourceLocation &MutableLoc,
1142 SourceLocation &ConstexprLoc,
1143 SourceLocation &ConstevalLoc,
1144 SourceLocation &DeclEndLoc) {
Faisal Valia734ab92016-03-26 16:11:37 +00001145 assert(MutableLoc.isInvalid());
1146 assert(ConstexprLoc.isInvalid());
1147 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1148 // to the final of those locations. Emit an error if we have multiple
1149 // copies of those keywords and recover.
1150
1151 while (true) {
1152 switch (P.getCurToken().getKind()) {
1153 case tok::kw_mutable: {
1154 if (MutableLoc.isValid()) {
1155 P.Diag(P.getCurToken().getLocation(),
1156 diag::err_lambda_decl_specifier_repeated)
1157 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1158 }
1159 MutableLoc = P.ConsumeToken();
1160 DeclEndLoc = MutableLoc;
1161 break /*switch*/;
1162 }
1163 case tok::kw_constexpr:
1164 if (ConstexprLoc.isValid()) {
1165 P.Diag(P.getCurToken().getLocation(),
1166 diag::err_lambda_decl_specifier_repeated)
1167 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1168 }
1169 ConstexprLoc = P.ConsumeToken();
1170 DeclEndLoc = ConstexprLoc;
1171 break /*switch*/;
Gauthier Harnisch796ed032019-06-14 08:56:20 +00001172 case tok::kw_consteval:
1173 if (ConstevalLoc.isValid()) {
1174 P.Diag(P.getCurToken().getLocation(),
1175 diag::err_lambda_decl_specifier_repeated)
1176 << 2 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1177 }
1178 ConstevalLoc = P.ConsumeToken();
1179 DeclEndLoc = ConstevalLoc;
1180 break /*switch*/;
Faisal Valia734ab92016-03-26 16:11:37 +00001181 default:
1182 return;
1183 }
1184 }
1185}
1186
1187static void
1188addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1189 DeclSpec &DS) {
1190 if (ConstexprLoc.isValid()) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001191 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
Richard Smithb115e5d2017-08-13 23:37:29 +00001192 ? diag::ext_constexpr_on_lambda_cxx17
Faisal Valia734ab92016-03-26 16:11:37 +00001193 : diag::warn_cxx14_compat_constexpr_on_lambda);
1194 const char *PrevSpec = nullptr;
1195 unsigned DiagID = 0;
Gauthier Harnisch796ed032019-06-14 08:56:20 +00001196 DS.SetConstexprSpec(CSK_constexpr, ConstexprLoc, PrevSpec, DiagID);
Faisal Valia734ab92016-03-26 16:11:37 +00001197 assert(PrevSpec == nullptr && DiagID == 0 &&
1198 "Constexpr cannot have been set previously!");
1199 }
1200}
1201
Gauthier Harnisch796ed032019-06-14 08:56:20 +00001202static void addConstevalToLambdaDeclSpecifier(Parser &P,
1203 SourceLocation ConstevalLoc,
1204 DeclSpec &DS) {
1205 if (ConstevalLoc.isValid()) {
1206 P.Diag(ConstevalLoc, diag::warn_cxx20_compat_consteval);
1207 const char *PrevSpec = nullptr;
1208 unsigned DiagID = 0;
1209 DS.SetConstexprSpec(CSK_consteval, ConstevalLoc, PrevSpec, DiagID);
1210 if (DiagID != 0)
1211 P.Diag(ConstevalLoc, DiagID) << PrevSpec;
1212 }
1213}
1214
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001215/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1216/// expression.
1217ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1218 LambdaIntroducer &Intro) {
Eli Friedmanc7c97142012-01-04 02:40:39 +00001219 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1220 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1221
1222 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1223 "lambda expression parsing");
1224
Fangrui Song6907ce22018-07-30 19:24:48 +00001225
Faisal Vali2b391ab2013-09-26 19:54:12 +00001226
Richard Smith21b3ab42013-05-09 21:36:41 +00001227 // FIXME: Call into Actions to add any init-capture declarations to the
1228 // scope while parsing the lambda-declarator and compound-statement.
1229
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001230 // Parse lambda-declarator[opt].
1231 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00001232 Declarator D(DS, DeclaratorContext::LambdaExprContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001233 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001234 Actions.PushLambdaScope();
1235
1236 ParsedAttributes Attr(AttrFactory);
1237 SourceLocation DeclLoc = Tok.getLocation();
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001238 if (getLangOpts().CUDA) {
1239 // In CUDA code, GNU attributes are allowed to appear immediately after the
1240 // "[...]", even if there is no "(...)" before the lambda body.
Justin Lebar0139a5d2016-09-30 19:55:48 +00001241 MaybeParseGNUAttributes(D);
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001242 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001243
Justin Lebare46ea722016-09-30 19:55:55 +00001244 // Helper to emit a warning if we see a CUDA host/device/global attribute
1245 // after '(...)'. nvcc doesn't accept this.
1246 auto WarnIfHasCUDATargetAttr = [&] {
1247 if (getLangOpts().CUDA)
Erich Keanee891aa92018-07-13 15:07:47 +00001248 for (const ParsedAttr &A : Attr)
1249 if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1250 A.getKind() == ParsedAttr::AT_CUDAHost ||
1251 A.getKind() == ParsedAttr::AT_CUDAGlobal)
Erich Keanec480f302018-07-12 21:09:05 +00001252 Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
Erich Keane6a24e802019-09-13 17:39:31 +00001253 << A.getAttrName()->getName();
Justin Lebare46ea722016-09-30 19:55:55 +00001254 };
1255
Hamza Sood8205a812019-05-04 10:49:46 +00001256 // FIXME: Consider allowing this as an extension for GCC compatibiblity.
1257 const bool HasExplicitTemplateParams = Tok.is(tok::less);
1258 ParseScope TemplateParamScope(this, Scope::TemplateParamScope,
1259 /*EnteredScope=*/HasExplicitTemplateParams);
1260 if (HasExplicitTemplateParams) {
1261 Diag(Tok, getLangOpts().CPlusPlus2a
1262 ? diag::warn_cxx17_compat_lambda_template_parameter_list
1263 : diag::ext_lambda_template_parameter_list);
1264
1265 SmallVector<NamedDecl*, 4> TemplateParams;
1266 SourceLocation LAngleLoc, RAngleLoc;
1267 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
1268 TemplateParams, LAngleLoc, RAngleLoc)) {
1269 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1270 return ExprError();
1271 }
1272
1273 if (TemplateParams.empty()) {
1274 Diag(RAngleLoc,
1275 diag::err_lambda_template_parameter_list_empty);
1276 } else {
1277 Actions.ActOnLambdaExplicitTemplateParameterList(
1278 LAngleLoc, TemplateParams, RAngleLoc);
1279 ++CurTemplateDepthTracker;
1280 }
1281 }
1282
David Majnemere01c4662015-01-09 05:10:55 +00001283 TypeResult TrailingReturnType;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001284 if (Tok.is(tok::l_paren)) {
1285 ParseScope PrototypeScope(this,
1286 Scope::FunctionPrototypeScope |
Richard Smithe233fbf2013-01-28 22:42:45 +00001287 Scope::FunctionDeclarationScope |
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001288 Scope::DeclScope);
1289
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001290 BalancedDelimiterTracker T(*this, tok::l_paren);
1291 T.consumeOpen();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001292 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001293
1294 // Parse parameter-declaration-clause.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001295 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001296 SourceLocation EllipsisLoc;
Fangrui Song6907ce22018-07-30 19:24:48 +00001297
Faisal Vali2b391ab2013-09-26 19:54:12 +00001298 if (Tok.isNot(tok::r_paren)) {
Hamza Sood8205a812019-05-04 10:49:46 +00001299 Actions.RecordParsingTemplateParameterDepth(
1300 CurTemplateDepthTracker.getOriginalDepth());
1301
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001302 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
Hamza Sood8205a812019-05-04 10:49:46 +00001303
Fangrui Song6907ce22018-07-30 19:24:48 +00001304 // For a generic lambda, each 'auto' within the parameter declaration
Faisal Vali2b391ab2013-09-26 19:54:12 +00001305 // clause creates a template type parameter, so increment the depth.
Hamza Sood8205a812019-05-04 10:49:46 +00001306 // If we've parsed any explicit template parameters, then the depth will
1307 // have already been incremented. So we make sure that at most a single
1308 // depth level is added.
Fangrui Song6907ce22018-07-30 19:24:48 +00001309 if (Actions.getCurGenericLambda())
Hamza Sood8205a812019-05-04 10:49:46 +00001310 CurTemplateDepthTracker.setAddedDepth(1);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001311 }
Hamza Sood8205a812019-05-04 10:49:46 +00001312
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001313 T.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001314 SourceLocation RParenLoc = T.getCloseLocation();
Justin Lebar0139a5d2016-09-30 19:55:48 +00001315 SourceLocation DeclEndLoc = RParenLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001316
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001317 // GNU-style attributes must be parsed before the mutable specifier to be
1318 // compatible with GCC.
1319 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1320
David Majnemerbda86322015-02-04 08:22:46 +00001321 // MSVC-style attributes must be parsed before the mutable specifier to be
1322 // compatible with MSVC.
Aaron Ballman068aa512015-05-20 20:58:33 +00001323 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
David Majnemerbda86322015-02-04 08:22:46 +00001324
Gauthier Harnisch796ed032019-06-14 08:56:20 +00001325 // Parse mutable-opt and/or constexpr-opt or consteval-opt, and update the
1326 // DeclEndLoc.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001327 SourceLocation MutableLoc;
Faisal Valia734ab92016-03-26 16:11:37 +00001328 SourceLocation ConstexprLoc;
Gauthier Harnisch796ed032019-06-14 08:56:20 +00001329 SourceLocation ConstevalLoc;
1330 tryConsumeLambdaSpecifierToken(*this, MutableLoc, ConstexprLoc,
1331 ConstevalLoc, DeclEndLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001332
Faisal Valia734ab92016-03-26 16:11:37 +00001333 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
Gauthier Harnisch796ed032019-06-14 08:56:20 +00001334 addConstevalToLambdaDeclSpecifier(*this, ConstevalLoc, DS);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001335 // Parse exception-specification[opt].
1336 ExceptionSpecificationType ESpecType = EST_None;
1337 SourceRange ESpecRange;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001338 SmallVector<ParsedType, 2> DynamicExceptions;
1339 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001340 ExprResult NoexceptExpr;
Richard Smith0b3a4622014-11-13 20:01:57 +00001341 CachedTokens *ExceptionSpecTokens;
1342 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1343 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00001344 DynamicExceptions,
1345 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00001346 NoexceptExpr,
1347 ExceptionSpecTokens);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001348
1349 if (ESpecType != EST_None)
1350 DeclEndLoc = ESpecRange.getEnd();
1351
1352 // Parse attribute-specifier[opt].
Richard Smith89645bc2013-01-02 12:01:23 +00001353 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001354
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001355 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1356
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001357 // Parse trailing-return-type[opt].
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001358 if (Tok.is(tok::arrow)) {
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001359 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001360 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00001361 TrailingReturnType =
1362 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001363 if (Range.getEnd().isValid())
1364 DeclEndLoc = Range.getEnd();
1365 }
1366
1367 PrototypeScope.Exit();
1368
Justin Lebare46ea722016-09-30 19:55:55 +00001369 WarnIfHasCUDATargetAttr();
1370
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001371 SourceLocation NoLoc;
Erich Keanec480f302018-07-12 21:09:05 +00001372 D.AddTypeInfo(DeclaratorChunk::getFunction(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001373 /*HasProto=*/true,
1374 /*IsAmbiguous=*/false, LParenLoc, ParamInfo.data(),
Erich Keanec480f302018-07-12 21:09:05 +00001375 ParamInfo.size(), EllipsisLoc, RParenLoc,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001376 /*RefQualifierIsLvalueRef=*/true,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00001377 /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType,
Erich Keanec480f302018-07-12 21:09:05 +00001378 ESpecRange, DynamicExceptions.data(),
1379 DynamicExceptionRanges.data(), DynamicExceptions.size(),
1380 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1381 /*ExceptionSpecTokens*/ nullptr,
1382 /*DeclsInPrototype=*/None, LParenLoc, FunLocalRangeEnd, D,
1383 TrailingReturnType),
1384 std::move(Attr), DeclEndLoc);
Faisal Valia734ab92016-03-26 16:11:37 +00001385 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
Gauthier Harnisch796ed032019-06-14 08:56:20 +00001386 tok::kw_constexpr, tok::kw_consteval) ||
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001387 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1388 // It's common to forget that one needs '()' before 'mutable', an attribute
1389 // specifier, or the result type. Deal with this.
1390 unsigned TokKind = 0;
1391 switch (Tok.getKind()) {
1392 case tok::kw_mutable: TokKind = 0; break;
1393 case tok::arrow: TokKind = 1; break;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001394 case tok::kw___attribute:
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001395 case tok::l_square: TokKind = 2; break;
Faisal Valia734ab92016-03-26 16:11:37 +00001396 case tok::kw_constexpr: TokKind = 3; break;
Gauthier Harnisch796ed032019-06-14 08:56:20 +00001397 case tok::kw_consteval: TokKind = 4; break;
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001398 default: llvm_unreachable("Unknown token kind");
1399 }
1400
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001401 Diag(Tok, diag::err_lambda_missing_parens)
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001402 << TokKind
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001403 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
Justin Lebar0139a5d2016-09-30 19:55:48 +00001404 SourceLocation DeclEndLoc = DeclLoc;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001405
1406 // GNU-style attributes must be parsed before the mutable specifier to be
1407 // compatible with GCC.
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001408 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1409
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001410 // Parse 'mutable', if it's there.
1411 SourceLocation MutableLoc;
1412 if (Tok.is(tok::kw_mutable)) {
1413 MutableLoc = ConsumeToken();
1414 DeclEndLoc = MutableLoc;
1415 }
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001416
1417 // Parse attribute-specifier[opt].
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001418 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1419
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001420 // Parse the return type, if there is one.
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001421 if (Tok.is(tok::arrow)) {
1422 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00001423 TrailingReturnType =
1424 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001425 if (Range.getEnd().isValid())
David Majnemere01c4662015-01-09 05:10:55 +00001426 DeclEndLoc = Range.getEnd();
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001427 }
1428
Justin Lebare46ea722016-09-30 19:55:55 +00001429 WarnIfHasCUDATargetAttr();
1430
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001431 SourceLocation NoLoc;
Erich Keanec480f302018-07-12 21:09:05 +00001432 D.AddTypeInfo(DeclaratorChunk::getFunction(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001433 /*HasProto=*/true,
1434 /*IsAmbiguous=*/false,
Erich Keanec480f302018-07-12 21:09:05 +00001435 /*LParenLoc=*/NoLoc,
1436 /*Params=*/nullptr,
1437 /*NumParams=*/0,
1438 /*EllipsisLoc=*/NoLoc,
1439 /*RParenLoc=*/NoLoc,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001440 /*RefQualifierIsLvalueRef=*/true,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00001441 /*RefQualifierLoc=*/NoLoc, MutableLoc, EST_None,
Erich Keanec480f302018-07-12 21:09:05 +00001442 /*ESpecRange=*/SourceRange(),
1443 /*Exceptions=*/nullptr,
1444 /*ExceptionRanges=*/nullptr,
1445 /*NumExceptions=*/0,
1446 /*NoexceptExpr=*/nullptr,
1447 /*ExceptionSpecTokens=*/nullptr,
1448 /*DeclsInPrototype=*/None, DeclLoc, DeclEndLoc, D,
1449 TrailingReturnType),
1450 std::move(Attr), DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001451 }
1452
Eli Friedman4817cf72012-01-06 03:05:34 +00001453 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1454 // it.
Momchil Velikov57c681f2017-08-10 15:43:06 +00001455 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1456 Scope::CompoundStmtScope;
Douglas Gregorb8389972012-02-21 22:51:27 +00001457 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman4817cf72012-01-06 03:05:34 +00001458
Eli Friedman71c80552012-01-05 03:35:19 +00001459 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1460
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001461 // Parse compound-statement.
Eli Friedmanc7c97142012-01-04 02:40:39 +00001462 if (!Tok.is(tok::l_brace)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001463 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmanc7c97142012-01-04 02:40:39 +00001464 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1465 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001466 }
1467
Eli Friedmanc7c97142012-01-04 02:40:39 +00001468 StmtResult Stmt(ParseCompoundStatementBody());
1469 BodyScope.Exit();
Hamza Sood8205a812019-05-04 10:49:46 +00001470 TemplateParamScope.Exit();
Eli Friedmanc7c97142012-01-04 02:40:39 +00001471
David Majnemere01c4662015-01-09 05:10:55 +00001472 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001473 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
David Majnemere01c4662015-01-09 05:10:55 +00001474
Eli Friedman898caf82012-01-04 02:46:53 +00001475 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1476 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001477}
1478
Chris Lattner29375652006-12-04 18:06:35 +00001479/// ParseCXXCasts - This handles the various ways to cast expressions to another
1480/// type.
1481///
1482/// postfix-expression: [C++ 5.2p1]
1483/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1484/// 'static_cast' '<' type-name '>' '(' expression ')'
1485/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1486/// 'const_cast' '<' type-name '>' '(' expression ')'
1487///
John McCalldadc5752010-08-24 06:29:42 +00001488ExprResult Parser::ParseCXXCasts() {
Chris Lattner29375652006-12-04 18:06:35 +00001489 tok::TokenKind Kind = Tok.getKind();
Craig Topper161e4db2014-05-21 06:02:52 +00001490 const char *CastName = nullptr; // For error messages
Chris Lattner29375652006-12-04 18:06:35 +00001491
1492 switch (Kind) {
David Blaikieaa347f92011-09-23 20:26:49 +00001493 default: llvm_unreachable("Unknown C++ cast!");
Chris Lattner29375652006-12-04 18:06:35 +00001494 case tok::kw_const_cast: CastName = "const_cast"; break;
1495 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1496 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1497 case tok::kw_static_cast: CastName = "static_cast"; break;
1498 }
1499
1500 SourceLocation OpLoc = ConsumeToken();
1501 SourceLocation LAngleBracketLoc = Tok.getLocation();
1502
Richard Smith55858492011-04-14 21:45:45 +00001503 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1504 // diagnose error, suggest fix, and recover parsing.
Richard Smith62e66302012-08-20 17:37:52 +00001505 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1506 Token Next = NextToken();
1507 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1508 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1509 }
Richard Smith55858492011-04-14 21:45:45 +00001510
Chris Lattner29375652006-12-04 18:06:35 +00001511 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redld65cea82008-12-11 22:51:44 +00001512 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001513
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001514 // Parse the common declaration-specifiers piece.
1515 DeclSpec DS(AttrFactory);
1516 ParseSpecifierQualifierList(DS);
1517
1518 // Parse the abstract-declarator, if present.
Faisal Vali421b2d12017-12-29 05:41:00 +00001519 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001520 ParseDeclarator(DeclaratorInfo);
1521
Chris Lattner29375652006-12-04 18:06:35 +00001522 SourceLocation RAngleBracketLoc = Tok.getLocation();
1523
Alp Toker383d2c42014-01-01 03:08:43 +00001524 if (ExpectAndConsume(tok::greater))
Alp Tokerec543272013-12-24 09:48:30 +00001525 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
Chris Lattner29375652006-12-04 18:06:35 +00001526
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001527 BalancedDelimiterTracker T(*this, tok::l_paren);
Chris Lattner29375652006-12-04 18:06:35 +00001528
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001529 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001530 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001531
John McCalldadc5752010-08-24 06:29:42 +00001532 ExprResult Result = ParseExpression();
Mike Stump11289f42009-09-09 15:08:12 +00001533
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001534 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001535 T.consumeClose();
Chris Lattner29375652006-12-04 18:06:35 +00001536
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001537 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregore200adc2008-10-27 19:41:14 +00001538 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001539 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor220cac52009-02-18 17:45:20 +00001540 RAngleBracketLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00001541 T.getOpenLocation(), Result.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001542 T.getCloseLocation());
Chris Lattner29375652006-12-04 18:06:35 +00001543
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001544 return Result;
Chris Lattner29375652006-12-04 18:06:35 +00001545}
Bill Wendling4073ed52007-02-13 01:51:42 +00001546
Sebastian Redlc4704762008-11-11 11:37:55 +00001547/// ParseCXXTypeid - This handles the C++ typeid expression.
1548///
1549/// postfix-expression: [C++ 5.2p1]
1550/// 'typeid' '(' expression ')'
1551/// 'typeid' '(' type-id ')'
1552///
John McCalldadc5752010-08-24 06:29:42 +00001553ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc4704762008-11-11 11:37:55 +00001554 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1555
1556 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001557 SourceLocation LParenLoc, RParenLoc;
1558 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc4704762008-11-11 11:37:55 +00001559
1560 // typeid expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001561 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redld65cea82008-12-11 22:51:44 +00001562 return ExprError();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001563 LParenLoc = T.getOpenLocation();
Sebastian Redlc4704762008-11-11 11:37:55 +00001564
John McCalldadc5752010-08-24 06:29:42 +00001565 ExprResult Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001566
Richard Smith4f605af2012-08-18 00:55:03 +00001567 // C++0x [expr.typeid]p3:
1568 // When typeid is applied to an expression other than an lvalue of a
1569 // polymorphic class type [...] The expression is an unevaluated
1570 // operand (Clause 5).
1571 //
1572 // Note that we can't tell whether the expression is an lvalue of a
1573 // polymorphic class type until after we've parsed the expression; we
1574 // speculatively assume the subexpression is unevaluated, and fix it up
1575 // later.
1576 //
1577 // We enter the unevaluated context before trying to determine whether we
1578 // have a type-id, because the tentative parse logic will try to resolve
1579 // names, and must treat them as unevaluated.
Faisal Valid143a0c2017-04-01 21:30:49 +00001580 EnterExpressionEvaluationContext Unevaluated(
1581 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1582 Sema::ReuseLambdaContextDecl);
Richard Smith4f605af2012-08-18 00:55:03 +00001583
Sebastian Redlc4704762008-11-11 11:37:55 +00001584 if (isTypeIdInParens()) {
Douglas Gregor220cac52009-02-18 17:45:20 +00001585 TypeResult Ty = ParseTypeName();
Sebastian Redlc4704762008-11-11 11:37:55 +00001586
1587 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001588 T.consumeClose();
1589 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001590 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00001591 return ExprError();
Sebastian Redlc4704762008-11-11 11:37:55 +00001592
1593 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallba7bf592010-08-24 05:47:05 +00001594 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001595 } else {
1596 Result = ParseExpression();
1597
1598 // Match the ')'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001599 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001600 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc4704762008-11-11 11:37:55 +00001601 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001602 T.consumeClose();
1603 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001604 if (RParenLoc.isInvalid())
1605 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00001606
Sebastian Redlc4704762008-11-11 11:37:55 +00001607 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001608 Result.get(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001609 }
1610 }
1611
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001612 return Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001613}
1614
Francois Pichet9f4f2072010-09-08 12:20:18 +00001615/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1616///
1617/// '__uuidof' '(' expression ')'
1618/// '__uuidof' '(' type-id ')'
1619///
1620ExprResult Parser::ParseCXXUuidof() {
1621 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1622
1623 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001624 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001625
1626 // __uuidof expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001627 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet9f4f2072010-09-08 12:20:18 +00001628 return ExprError();
1629
1630 ExprResult Result;
1631
1632 if (isTypeIdInParens()) {
1633 TypeResult Ty = ParseTypeName();
1634
1635 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001636 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001637
1638 if (Ty.isInvalid())
1639 return ExprError();
1640
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001641 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
Fangrui Song6907ce22018-07-30 19:24:48 +00001642 Ty.get().getAsOpaquePtr(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001643 T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001644 } else {
Faisal Valid143a0c2017-04-01 21:30:49 +00001645 EnterExpressionEvaluationContext Unevaluated(
1646 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001647 Result = ParseExpression();
1648
1649 // Match the ')'.
1650 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001651 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001652 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001653 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001654
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001655 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1656 /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001657 Result.get(), T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001658 }
1659 }
1660
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001661 return Result;
Francois Pichet9f4f2072010-09-08 12:20:18 +00001662}
1663
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001664/// Parse a C++ pseudo-destructor expression after the base,
Douglas Gregore610ada2010-02-24 18:44:31 +00001665/// . or -> operator, and nested-name-specifier have already been
1666/// parsed.
1667///
1668/// postfix-expression: [C++ 5.2]
1669/// postfix-expression . pseudo-destructor-name
1670/// postfix-expression -> pseudo-destructor-name
1671///
Fangrui Song6907ce22018-07-30 19:24:48 +00001672/// pseudo-destructor-name:
1673/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1674/// ::[opt] nested-name-specifier template simple-template-id ::
1675/// ~type-name
Douglas Gregore610ada2010-02-24 18:44:31 +00001676/// ::[opt] nested-name-specifier[opt] ~type-name
Fangrui Song6907ce22018-07-30 19:24:48 +00001677///
1678ExprResult
Craig Toppera2c51532014-10-30 05:30:05 +00001679Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00001680 tok::TokenKind OpKind,
1681 CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +00001682 ParsedType ObjectType) {
Douglas Gregore610ada2010-02-24 18:44:31 +00001683 // We're parsing either a pseudo-destructor-name or a dependent
1684 // member access that has the same form as a
1685 // pseudo-destructor-name. We parse both in the same way and let
1686 // the action model sort them out.
1687 //
1688 // Note that the ::[opt] nested-name-specifier[opt] has already
1689 // been parsed, and if there was a simple-template-id, it has
1690 // been coalesced into a template-id annotation token.
1691 UnqualifiedId FirstTypeName;
1692 SourceLocation CCLoc;
1693 if (Tok.is(tok::identifier)) {
1694 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1695 ConsumeToken();
1696 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1697 CCLoc = ConsumeToken();
1698 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001699 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1700 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregore610ada2010-02-24 18:44:31 +00001701 FirstTypeName.setTemplateId(
1702 (TemplateIdAnnotation *)Tok.getAnnotationValue());
Richard Smithaf3b3252017-05-18 19:21:48 +00001703 ConsumeAnnotationToken();
Douglas Gregore610ada2010-02-24 18:44:31 +00001704 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1705 CCLoc = ConsumeToken();
1706 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001707 FirstTypeName.setIdentifier(nullptr, SourceLocation());
Douglas Gregore610ada2010-02-24 18:44:31 +00001708 }
1709
1710 // Parse the tilde.
1711 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1712 SourceLocation TildeLoc = ConsumeToken();
David Blaikie1d578782011-12-16 16:03:09 +00001713
1714 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1715 DeclSpec DS(AttrFactory);
Benjamin Kramer198e0832011-12-18 12:18:02 +00001716 ParseDecltypeSpecifier(DS);
Faisal Vali090da2d2018-01-01 18:23:28 +00001717 if (DS.getTypeSpecType() == TST_error)
David Blaikie1d578782011-12-16 16:03:09 +00001718 return ExprError();
David Majnemerced8bdf2015-02-25 17:36:15 +00001719 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1720 TildeLoc, DS);
David Blaikie1d578782011-12-16 16:03:09 +00001721 }
1722
Douglas Gregore610ada2010-02-24 18:44:31 +00001723 if (!Tok.is(tok::identifier)) {
1724 Diag(Tok, diag::err_destructor_tilde_identifier);
1725 return ExprError();
1726 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001727
Douglas Gregore610ada2010-02-24 18:44:31 +00001728 // Parse the second type.
1729 UnqualifiedId SecondTypeName;
1730 IdentifierInfo *Name = Tok.getIdentifierInfo();
1731 SourceLocation NameLoc = ConsumeToken();
1732 SecondTypeName.setIdentifier(Name, NameLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001733
Douglas Gregore610ada2010-02-24 18:44:31 +00001734 // If there is a '<', the second type name is a template-id. Parse
1735 // it as such.
1736 if (Tok.is(tok::less) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +00001737 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1738 Name, NameLoc,
1739 false, ObjectType, SecondTypeName,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001740 /*AssumeTemplateId=*/true))
Douglas Gregore610ada2010-02-24 18:44:31 +00001741 return ExprError();
1742
David Majnemerced8bdf2015-02-25 17:36:15 +00001743 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1744 SS, FirstTypeName, CCLoc, TildeLoc,
1745 SecondTypeName);
Douglas Gregore610ada2010-02-24 18:44:31 +00001746}
1747
Bill Wendling4073ed52007-02-13 01:51:42 +00001748/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1749///
1750/// boolean-literal: [C++ 2.13.5]
1751/// 'true'
1752/// 'false'
John McCalldadc5752010-08-24 06:29:42 +00001753ExprResult Parser::ParseCXXBoolLiteral() {
Bill Wendling4073ed52007-02-13 01:51:42 +00001754 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001755 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Bill Wendling4073ed52007-02-13 01:51:42 +00001756}
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001757
1758/// ParseThrowExpression - This handles the C++ throw expression.
1759///
1760/// throw-expression: [C++ 15]
1761/// 'throw' assignment-expression[opt]
John McCalldadc5752010-08-24 06:29:42 +00001762ExprResult Parser::ParseThrowExpression() {
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001763 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001764 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redld65cea82008-12-11 22:51:44 +00001765
Chris Lattner65dd8432008-04-06 06:02:23 +00001766 // If the current token isn't the start of an assignment-expression,
1767 // then the expression is not present. This handles things like:
1768 // "C ? throw : (void)42", which is crazy but legal.
1769 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1770 case tok::semi:
1771 case tok::r_paren:
1772 case tok::r_square:
1773 case tok::r_brace:
1774 case tok::colon:
1775 case tok::comma:
Craig Topper161e4db2014-05-21 06:02:52 +00001776 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001777
Chris Lattner65dd8432008-04-06 06:02:23 +00001778 default:
John McCalldadc5752010-08-24 06:29:42 +00001779 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001780 if (Expr.isInvalid()) return Expr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001781 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
Chris Lattner65dd8432008-04-06 06:02:23 +00001782 }
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001783}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001784
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001785/// Parse the C++ Coroutines co_yield expression.
Richard Smith0e304ea2015-10-22 04:46:14 +00001786///
1787/// co_yield-expression:
1788/// 'co_yield' assignment-expression[opt]
1789ExprResult Parser::ParseCoyieldExpression() {
1790 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1791
1792 SourceLocation Loc = ConsumeToken();
Richard Smithae3d1472015-11-20 22:47:10 +00001793 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1794 : ParseAssignmentExpression();
Richard Smithcfd53b42015-10-22 06:13:50 +00001795 if (!Expr.isInvalid())
Richard Smith9f690bd2015-10-27 06:02:45 +00001796 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
Richard Smith0e304ea2015-10-22 04:46:14 +00001797 return Expr;
1798}
1799
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001800/// ParseCXXThis - This handles the C++ 'this' pointer.
1801///
1802/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1803/// a non-lvalue expression whose value is the address of the object for which
1804/// the function is called.
John McCalldadc5752010-08-24 06:29:42 +00001805ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001806 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1807 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001808 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001809}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001810
1811/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1812/// Can be interpreted either as function-style casting ("int(x)")
1813/// or class type construction ("ClassType(x,y,z)")
1814/// or creation of a value-initialized type ("int()").
Sebastian Redl3da34892011-06-05 12:23:16 +00001815/// See [C++ 5.2.3].
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001816///
1817/// postfix-expression: [C++ 5.2p1]
Sebastian Redl3da34892011-06-05 12:23:16 +00001818/// simple-type-specifier '(' expression-list[opt] ')'
1819/// [C++0x] simple-type-specifier braced-init-list
1820/// typename-specifier '(' expression-list[opt] ')'
1821/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001822///
Richard Smith600b5262017-01-26 20:40:47 +00001823/// In C++1z onwards, the type specifier can also be a template-name.
John McCalldadc5752010-08-24 06:29:42 +00001824ExprResult
Sebastian Redld65cea82008-12-11 22:51:44 +00001825Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Faisal Vali421b2d12017-12-29 05:41:00 +00001826 Declarator DeclaratorInfo(DS, DeclaratorContext::FunctionalCastContext);
John McCallba7bf592010-08-24 05:47:05 +00001827 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001828
Sebastian Redl3da34892011-06-05 12:23:16 +00001829 assert((Tok.is(tok::l_paren) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001830 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redl3da34892011-06-05 12:23:16 +00001831 && "Expected '(' or '{'!");
Douglas Gregor94a32472011-01-11 00:33:19 +00001832
Sebastian Redl3da34892011-06-05 12:23:16 +00001833 if (Tok.is(tok::l_brace)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001834 ExprResult Init = ParseBraceInitializer();
1835 if (Init.isInvalid())
1836 return Init;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001837 Expr *InitList = Init.get();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001838 return Actions.ActOnCXXTypeConstructExpr(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001839 TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001840 InitList->getEndLoc(), /*ListInitialization=*/true);
Sebastian Redl3da34892011-06-05 12:23:16 +00001841 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001842 BalancedDelimiterTracker T(*this, tok::l_paren);
1843 T.consumeOpen();
Sebastian Redl3da34892011-06-05 12:23:16 +00001844
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00001845 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1846
Benjamin Kramerf0623432012-08-23 22:51:59 +00001847 ExprVector Exprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00001848 CommaLocsTy CommaLocs;
1849
Ilya Biryukovff2a9972019-02-26 11:01:50 +00001850 auto RunSignatureHelp = [&]() {
1851 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
1852 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
1853 DS.getEndLoc(), Exprs, T.getOpenLocation());
1854 CalledSignatureHelp = true;
1855 return PreferredType;
1856 };
1857
Sebastian Redl3da34892011-06-05 12:23:16 +00001858 if (Tok.isNot(tok::r_paren)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00001859 if (ParseExpressionList(Exprs, CommaLocs, [&] {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00001860 PreferredType.enterFunctionArgument(Tok.getLocation(),
1861 RunSignatureHelp);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001862 })) {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00001863 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1864 RunSignatureHelp();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001865 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00001866 return ExprError();
1867 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001868 }
Sebastian Redl3da34892011-06-05 12:23:16 +00001869
1870 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001871 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00001872
1873 // TypeRep could be null, if it references an invalid typedef.
1874 if (!TypeRep)
1875 return ExprError();
1876
1877 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1878 "Unexpected number of commas!");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001879 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1880 Exprs, T.getCloseLocation(),
1881 /*ListInitialization=*/false);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001882 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001883}
1884
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001885/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001886///
1887/// condition:
1888/// expression
1889/// type-specifier-seq declarator '=' assignment-expression
Richard Smith2a15b742012-02-22 06:49:09 +00001890/// [C++11] type-specifier-seq declarator '=' initializer-clause
1891/// [C++11] type-specifier-seq declarator braced-init-list
Zhihao Yuanc81f4532017-12-07 07:03:15 +00001892/// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1893/// brace-or-equal-initializer
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001894/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1895/// '=' assignment-expression
1896///
Richard Smithc7a05a92016-06-29 21:17:59 +00001897/// In C++1z, a condition may in some contexts be preceded by an
1898/// optional init-statement. This function will parse that too.
1899///
1900/// \param InitStmt If non-null, an init-statement is permitted, and if present
1901/// will be parsed and stored here.
1902///
Douglas Gregore60e41a2010-05-06 17:25:47 +00001903/// \param Loc The location of the start of the statement that requires this
1904/// condition, e.g., the "for" in a for loop.
1905///
Richard Smith8baa5002018-09-28 18:44:09 +00001906/// \param FRI If non-null, a for range declaration is permitted, and if
1907/// present will be parsed and stored here, and a null result will be returned.
1908///
Richard Smith03a4aa32016-06-23 19:02:52 +00001909/// \returns The parsed condition.
Richard Smithc7a05a92016-06-29 21:17:59 +00001910Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1911 SourceLocation Loc,
Richard Smith8baa5002018-09-28 18:44:09 +00001912 Sema::ConditionKind CK,
1913 ForRangeInfo *FRI) {
Richard Smithbf5bcf22018-06-26 23:20:26 +00001914 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00001915 PreferredType.enterCondition(Actions, Tok.getLocation());
Richard Smithbf5bcf22018-06-26 23:20:26 +00001916
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001917 if (Tok.is(tok::code_completion)) {
John McCallfaf5fb42010-08-26 23:41:50 +00001918 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001919 cutOffParsing();
Richard Smith03a4aa32016-06-23 19:02:52 +00001920 return Sema::ConditionError();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001921 }
1922
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001923 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001924 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001925
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001926 const auto WarnOnInit = [this, &CK] {
1927 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
1928 ? diag::warn_cxx14_compat_init_statement
1929 : diag::ext_init_statement)
1930 << (CK == Sema::ConditionKind::Switch);
1931 };
1932
Richard Smithc7a05a92016-06-29 21:17:59 +00001933 // Determine what kind of thing we have.
Richard Smith8baa5002018-09-28 18:44:09 +00001934 switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
Richard Smithc7a05a92016-06-29 21:17:59 +00001935 case ConditionOrInitStatement::Expression: {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001936 ProhibitAttributes(attrs);
1937
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001938 // We can have an empty expression here.
1939 // if (; true);
1940 if (InitStmt && Tok.is(tok::semi)) {
1941 WarnOnInit();
Roman Lebedev377748f2018-11-20 18:59:05 +00001942 SourceLocation SemiLoc = Tok.getLocation();
1943 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
1944 Diag(SemiLoc, diag::warn_empty_init_statement)
1945 << (CK == Sema::ConditionKind::Switch)
1946 << FixItHint::CreateRemoval(SemiLoc);
1947 }
1948 ConsumeToken();
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001949 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
1950 return ParseCXXCondition(nullptr, Loc, CK);
1951 }
1952
Douglas Gregore60e41a2010-05-06 17:25:47 +00001953 // Parse the expression.
Richard Smith03a4aa32016-06-23 19:02:52 +00001954 ExprResult Expr = ParseExpression(); // expression
1955 if (Expr.isInvalid())
1956 return Sema::ConditionError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00001957
Richard Smithc7a05a92016-06-29 21:17:59 +00001958 if (InitStmt && Tok.is(tok::semi)) {
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001959 WarnOnInit();
Richard Smithc7a05a92016-06-29 21:17:59 +00001960 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1961 ConsumeToken();
1962 return ParseCXXCondition(nullptr, Loc, CK);
1963 }
1964
Richard Smith03a4aa32016-06-23 19:02:52 +00001965 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001966 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001967
Richard Smithc7a05a92016-06-29 21:17:59 +00001968 case ConditionOrInitStatement::InitStmtDecl: {
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001969 WarnOnInit();
Richard Smithc7a05a92016-06-29 21:17:59 +00001970 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Faisal Vali421b2d12017-12-29 05:41:00 +00001971 DeclGroupPtrTy DG =
1972 ParseSimpleDeclaration(DeclaratorContext::InitStmtContext, DeclEnd,
1973 attrs, /*RequireSemi=*/true);
Richard Smithc7a05a92016-06-29 21:17:59 +00001974 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1975 return ParseCXXCondition(nullptr, Loc, CK);
1976 }
1977
Richard Smith8baa5002018-09-28 18:44:09 +00001978 case ConditionOrInitStatement::ForRangeDecl: {
1979 assert(FRI && "should not parse a for range declaration here");
1980 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1981 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1982 DeclaratorContext::ForContext, DeclEnd, attrs, false, FRI);
1983 FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1984 return Sema::ConditionResult();
1985 }
1986
Richard Smithc7a05a92016-06-29 21:17:59 +00001987 case ConditionOrInitStatement::ConditionDecl:
1988 case ConditionOrInitStatement::Error:
1989 break;
1990 }
1991
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001992 // type-specifier-seq
John McCall084e83d2011-03-24 11:26:52 +00001993 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +00001994 DS.takeAttributesFrom(attrs);
Faisal Vali7db85c52017-12-31 00:06:40 +00001995 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001996
1997 // declarator
Faisal Vali421b2d12017-12-29 05:41:00 +00001998 Declarator DeclaratorInfo(DS, DeclaratorContext::ConditionContext);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001999 ParseDeclarator(DeclaratorInfo);
2000
2001 // simple-asm-expr[opt]
2002 if (Tok.is(tok::kw_asm)) {
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002003 SourceLocation Loc;
John McCalldadc5752010-08-24 06:29:42 +00002004 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002005 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002006 SkipUntil(tok::semi, StopAtSemi);
Richard Smith03a4aa32016-06-23 19:02:52 +00002007 return Sema::ConditionError();
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00002008 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002009 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002010 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00002011 }
2012
2013 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00002014 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00002015
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00002016 // Type-check the declaration itself.
Fangrui Song6907ce22018-07-30 19:24:48 +00002017 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall53fa7142010-12-24 02:08:15 +00002018 DeclaratorInfo);
Richard Smith03a4aa32016-06-23 19:02:52 +00002019 if (Dcl.isInvalid())
2020 return Sema::ConditionError();
2021 Decl *DeclOut = Dcl.get();
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00002022
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00002023 // '=' assignment-expression
Richard Trieuc64d3232012-01-18 22:54:52 +00002024 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith2a15b742012-02-22 06:49:09 +00002025 bool CopyInitialization = isTokenEqualOrEqualTypo();
2026 if (CopyInitialization)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00002027 ConsumeToken();
Richard Smith2a15b742012-02-22 06:49:09 +00002028
2029 ExprResult InitExpr = ExprError();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002030 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith2a15b742012-02-22 06:49:09 +00002031 Diag(Tok.getLocation(),
2032 diag::warn_cxx98_compat_generalized_initializer_lists);
2033 InitExpr = ParseBraceInitializer();
2034 } else if (CopyInitialization) {
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00002035 PreferredType.enterVariableInit(Tok.getLocation(), DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00002036 InitExpr = ParseAssignmentExpression();
2037 } else if (Tok.is(tok::l_paren)) {
2038 // This was probably an attempt to initialize the variable.
2039 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataevee6507d2013-11-18 08:17:37 +00002040 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith2a15b742012-02-22 06:49:09 +00002041 RParen = ConsumeParen();
Richard Smith03a4aa32016-06-23 19:02:52 +00002042 Diag(DeclOut->getLocation(),
Richard Smith2a15b742012-02-22 06:49:09 +00002043 diag::err_expected_init_in_condition_lparen)
2044 << SourceRange(LParen, RParen);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00002045 } else {
Richard Smith03a4aa32016-06-23 19:02:52 +00002046 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00002047 }
Richard Smith2a15b742012-02-22 06:49:09 +00002048
2049 if (!InitExpr.isInvalid())
Richard Smith3beb7c62017-01-12 02:27:38 +00002050 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
Richard Smith27d807c2013-04-30 13:56:41 +00002051 else
2052 Actions.ActOnInitializerError(DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00002053
Richard Smithb2bc2e62011-02-21 20:05:19 +00002054 Actions.FinalizeDeclaration(DeclOut);
Richard Smith03a4aa32016-06-23 19:02:52 +00002055 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00002056}
2057
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002058/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
2059/// This should only be called when the current token is known to be part of
2060/// simple-type-specifier.
2061///
2062/// simple-type-specifier:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00002063/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002064/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
2065/// char
2066/// wchar_t
2067/// bool
2068/// short
2069/// int
2070/// long
2071/// signed
2072/// unsigned
2073/// float
2074/// double
2075/// void
2076/// [GNU] typeof-specifier
2077/// [C++0x] auto [TODO]
2078///
2079/// type-name:
2080/// class-name
2081/// enum-name
2082/// typedef-name
2083///
2084void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
2085 DS.SetRangeStart(Tok.getLocation());
2086 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +00002087 unsigned DiagID;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002088 SourceLocation Loc = Tok.getLocation();
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002089 const clang::PrintingPolicy &Policy =
2090 Actions.getASTContext().getPrintingPolicy();
Mike Stump11289f42009-09-09 15:08:12 +00002091
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002092 switch (Tok.getKind()) {
Chris Lattner45ddec32009-01-05 00:13:00 +00002093 case tok::identifier: // foo::bar
2094 case tok::coloncolon: // ::foo::bar
David Blaikie83d382b2011-09-23 05:06:16 +00002095 llvm_unreachable("Annotation token should already be formed!");
Mike Stump11289f42009-09-09 15:08:12 +00002096 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002097 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner45ddec32009-01-05 00:13:00 +00002098
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002099 // type-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00002100 case tok::annot_typename: {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002101 if (getTypeAnnotation(Tok))
2102 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002103 getTypeAnnotation(Tok), Policy);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002104 else
2105 DS.SetTypeSpecError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002106
Douglas Gregor06e41ae2010-10-21 23:17:00 +00002107 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00002108 ConsumeAnnotationToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00002109
Craig Topper25122412015-11-15 03:32:11 +00002110 DS.Finish(Actions, Policy);
Douglas Gregor06e41ae2010-10-21 23:17:00 +00002111 return;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002112 }
Mike Stump11289f42009-09-09 15:08:12 +00002113
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002114 // builtin types
2115 case tok::kw_short:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002116 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002117 break;
2118 case tok::kw_long:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002119 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002120 break;
Francois Pichet84133e42011-04-28 01:59:37 +00002121 case tok::kw___int64:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002122 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00002123 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002124 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00002125 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002126 break;
2127 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00002128 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002129 break;
2130 case tok::kw_void:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002131 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002132 break;
2133 case tok::kw_char:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002134 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002135 break;
2136 case tok::kw_int:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002137 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002138 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00002139 case tok::kw___int128:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002140 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00002141 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002142 case tok::kw_half:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002143 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002144 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002145 case tok::kw_float:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002146 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002147 break;
2148 case tok::kw_double:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002149 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002150 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002151 case tok::kw__Float16:
2152 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
2153 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002154 case tok::kw___float128:
2155 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
2156 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002157 case tok::kw_wchar_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002158 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002159 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00002160 case tok::kw_char8_t:
2161 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
2162 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002163 case tok::kw_char16_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002164 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002165 break;
2166 case tok::kw_char32_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002167 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002168 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002169 case tok::kw_bool:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002170 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002171 break;
Anastasia Stulova2c4730d2019-02-15 12:07:57 +00002172#define GENERIC_IMAGE_TYPE(ImgType, Id) \
2173 case tok::kw_##ImgType##_t: \
2174 DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \
2175 Policy); \
2176 break;
2177#include "clang/Basic/OpenCLImageTypes.def"
2178
David Blaikie25896afb2012-01-24 05:47:35 +00002179 case tok::annot_decltype:
2180 case tok::kw_decltype:
2181 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
Craig Topper25122412015-11-15 03:32:11 +00002182 return DS.Finish(Actions, Policy);
Mike Stump11289f42009-09-09 15:08:12 +00002183
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002184 // GNU typeof support.
2185 case tok::kw_typeof:
2186 ParseTypeofSpecifier(DS);
Craig Topper25122412015-11-15 03:32:11 +00002187 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002188 return;
2189 }
Richard Smithaf3b3252017-05-18 19:21:48 +00002190 ConsumeAnyToken();
2191 DS.SetRangeEnd(PrevTokLocation);
Craig Topper25122412015-11-15 03:32:11 +00002192 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002193}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002194
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002195/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2196/// [dcl.name]), which is a non-empty sequence of type-specifiers,
2197/// e.g., "const short int". Note that the DeclSpec is *not* finished
2198/// by parsing the type-specifier-seq, because these sequences are
2199/// typically followed by some form of declarator. Returns true and
2200/// emits diagnostics if this is not a type-specifier-seq, false
2201/// otherwise.
2202///
2203/// type-specifier-seq: [C++ 8.1]
2204/// type-specifier type-specifier-seq[opt]
2205///
2206bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Faisal Vali7db85c52017-12-31 00:06:40 +00002207 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
Craig Topper25122412015-11-15 03:32:11 +00002208 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002209 return false;
2210}
2211
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002212/// Finish parsing a C++ unqualified-id that is a template-id of
Fangrui Song6907ce22018-07-30 19:24:48 +00002213/// some form.
Douglas Gregor7861a802009-11-03 01:35:08 +00002214///
2215/// This routine is invoked when a '<' is encountered after an identifier or
2216/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2217/// whether the unqualified-id is actually a template-id. This routine will
2218/// then parse the template arguments and form the appropriate template-id to
2219/// return to the caller.
2220///
2221/// \param SS the nested-name-specifier that precedes this template-id, if
2222/// we're actually parsing a qualified-id.
2223///
2224/// \param Name for constructor and destructor names, this is the actual
2225/// identifier that may be a template-name.
2226///
Fangrui Song6907ce22018-07-30 19:24:48 +00002227/// \param NameLoc the location of the class-name in a constructor or
Douglas Gregor7861a802009-11-03 01:35:08 +00002228/// destructor.
2229///
Fangrui Song6907ce22018-07-30 19:24:48 +00002230/// \param EnteringContext whether we're entering the scope of the
Douglas Gregor7861a802009-11-03 01:35:08 +00002231/// nested-name-specifier.
2232///
Douglas Gregor127ea592009-11-03 21:24:04 +00002233/// \param ObjectType if this unqualified-id occurs within a member access
2234/// expression, the type of the base object whose member is being accessed.
2235///
Douglas Gregor7861a802009-11-03 01:35:08 +00002236/// \param Id as input, describes the template-name or operator-function-id
2237/// that precedes the '<'. If template arguments were parsed successfully,
2238/// will be updated with the template-id.
Fangrui Song6907ce22018-07-30 19:24:48 +00002239///
Douglas Gregore610ada2010-02-24 18:44:31 +00002240/// \param AssumeTemplateId When true, this routine will assume that the name
Fangrui Song6907ce22018-07-30 19:24:48 +00002241/// refers to a template without performing name lookup to verify.
Douglas Gregore610ada2010-02-24 18:44:31 +00002242///
Douglas Gregor7861a802009-11-03 01:35:08 +00002243/// \returns true if a parse error occurred, false otherwise.
2244bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002245 SourceLocation TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002246 IdentifierInfo *Name,
2247 SourceLocation NameLoc,
2248 bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002249 ParsedType ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00002250 UnqualifiedId &Id,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002251 bool AssumeTemplateId) {
Richard Smithc08b6932018-04-27 02:00:13 +00002252 assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
2253
Douglas Gregor7861a802009-11-03 01:35:08 +00002254 TemplateTy Template;
2255 TemplateNameKind TNK = TNK_Non_template;
2256 switch (Id.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00002257 case UnqualifiedIdKind::IK_Identifier:
2258 case UnqualifiedIdKind::IK_OperatorFunctionId:
2259 case UnqualifiedIdKind::IK_LiteralOperatorId:
Douglas Gregore610ada2010-02-24 18:44:31 +00002260 if (AssumeTemplateId) {
Richard Smithfd3dae02017-01-20 00:20:39 +00002261 // We defer the injected-class-name checks until we've found whether
2262 // this template-id is used to form a nested-name-specifier or not.
2263 TNK = Actions.ActOnDependentTemplateName(
2264 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2265 Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002266 if (TNK == TNK_Non_template)
2267 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00002268 } else {
2269 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002270 TNK = Actions.isTemplateName(getCurScope(), SS,
2271 TemplateKWLoc.isValid(), Id,
2272 ObjectType, EnteringContext, Template,
Douglas Gregor786123d2010-05-21 23:18:07 +00002273 MemberOfUnknownSpecialization);
Richard Smithb23c5e82019-05-09 03:31:27 +00002274 // If lookup found nothing but we're assuming that this is a template
2275 // name, double-check that makes sense syntactically before committing
2276 // to it.
2277 if (TNK == TNK_Undeclared_template &&
2278 isTemplateArgumentList(0) == TPResult::False)
2279 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00002280
Douglas Gregor786123d2010-05-21 23:18:07 +00002281 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
Richard Smithb23c5e82019-05-09 03:31:27 +00002282 ObjectType && isTemplateArgumentList(0) == TPResult::True) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002283 // We have something like t->getAs<T>(), where getAs is a
Douglas Gregor786123d2010-05-21 23:18:07 +00002284 // member of an unknown specialization. However, this will only
2285 // parse correctly as a template, so suggest the keyword 'template'
2286 // before 'getAs' and treat this as a dependent template name.
2287 std::string Name;
Faisal Vali2ab8c152017-12-30 04:15:27 +00002288 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
Douglas Gregor786123d2010-05-21 23:18:07 +00002289 Name = Id.Identifier->getName();
2290 else {
2291 Name = "operator ";
Faisal Vali2ab8c152017-12-30 04:15:27 +00002292 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
Douglas Gregor786123d2010-05-21 23:18:07 +00002293 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2294 else
2295 Name += Id.Identifier->getName();
2296 }
2297 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2298 << Name
2299 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Richard Smithfd3dae02017-01-20 00:20:39 +00002300 TNK = Actions.ActOnDependentTemplateName(
2301 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2302 Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002303 if (TNK == TNK_Non_template)
Fangrui Song6907ce22018-07-30 19:24:48 +00002304 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00002305 }
2306 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002307 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002308
Faisal Vali2ab8c152017-12-30 04:15:27 +00002309 case UnqualifiedIdKind::IK_ConstructorName: {
Douglas Gregor3cf81312009-11-03 23:16:33 +00002310 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002311 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002312 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002313 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002314 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002315 EnteringContext, Template,
2316 MemberOfUnknownSpecialization);
Douglas Gregor7861a802009-11-03 01:35:08 +00002317 break;
2318 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002319
Faisal Vali2ab8c152017-12-30 04:15:27 +00002320 case UnqualifiedIdKind::IK_DestructorName: {
Douglas Gregor3cf81312009-11-03 23:16:33 +00002321 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002322 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002323 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002324 if (ObjectType) {
Richard Smithfd3dae02017-01-20 00:20:39 +00002325 TNK = Actions.ActOnDependentTemplateName(
2326 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2327 EnteringContext, Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002328 if (TNK == TNK_Non_template)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002329 return true;
2330 } else {
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002331 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002332 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002333 EnteringContext, Template,
2334 MemberOfUnknownSpecialization);
Fangrui Song6907ce22018-07-30 19:24:48 +00002335
John McCallba7bf592010-08-24 05:47:05 +00002336 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002337 Diag(NameLoc, diag::err_destructor_template_id)
2338 << Name << SS.getRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00002339 return true;
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002340 }
2341 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002342 break;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002343 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002344
Douglas Gregor7861a802009-11-03 01:35:08 +00002345 default:
2346 return false;
2347 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002348
Douglas Gregor7861a802009-11-03 01:35:08 +00002349 if (TNK == TNK_Non_template)
2350 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00002351
Douglas Gregor7861a802009-11-03 01:35:08 +00002352 // Parse the enclosed template argument list.
2353 SourceLocation LAngleLoc, RAngleLoc;
2354 TemplateArgList TemplateArgs;
Richard Smithc08b6932018-04-27 02:00:13 +00002355 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
2356 RAngleLoc))
Douglas Gregor7861a802009-11-03 01:35:08 +00002357 return true;
Richard Smithc08b6932018-04-27 02:00:13 +00002358
Faisal Vali2ab8c152017-12-30 04:15:27 +00002359 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2360 Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2361 Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002362 // Form a parsed representation of the template-id to be stored in the
2363 // UnqualifiedId.
Douglas Gregor7861a802009-11-03 01:35:08 +00002364
Richard Smith72bfbd82013-12-04 00:28:23 +00002365 // FIXME: Store name for literal operator too.
Faisal Vali43caf672017-05-23 01:07:12 +00002366 IdentifierInfo *TemplateII =
Faisal Vali2ab8c152017-12-30 04:15:27 +00002367 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2368 : nullptr;
2369 OverloadedOperatorKind OpKind =
2370 Id.getKind() == UnqualifiedIdKind::IK_Identifier
2371 ? OO_None
2372 : Id.OperatorFunctionId.Operator;
Douglas Gregor7861a802009-11-03 01:35:08 +00002373
Faisal Vali43caf672017-05-23 01:07:12 +00002374 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2375 SS, TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2376 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
2377
Douglas Gregor7861a802009-11-03 01:35:08 +00002378 Id.setTemplateId(TemplateId);
2379 return false;
2380 }
2381
2382 // Bundle the template arguments together.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002383 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnara4244b432012-01-27 08:46:19 +00002384
Douglas Gregor7861a802009-11-03 01:35:08 +00002385 // Constructor and destructor names.
Richard Smithb23c5e82019-05-09 03:31:27 +00002386 TypeResult Type = Actions.ActOnTemplateIdType(
2387 getCurScope(), SS, TemplateKWLoc, Template, Name, NameLoc, LAngleLoc,
2388 TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true);
Douglas Gregor7861a802009-11-03 01:35:08 +00002389 if (Type.isInvalid())
2390 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002391
Faisal Vali2ab8c152017-12-30 04:15:27 +00002392 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
Douglas Gregor7861a802009-11-03 01:35:08 +00002393 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2394 else
2395 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00002396
Douglas Gregor7861a802009-11-03 01:35:08 +00002397 return false;
2398}
2399
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002400/// Parse an operator-function-id or conversion-function-id as part
Douglas Gregor71395fa2009-11-04 00:56:37 +00002401/// of a C++ unqualified-id.
2402///
2403/// This routine is responsible only for parsing the operator-function-id or
2404/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor7861a802009-11-03 01:35:08 +00002405///
2406/// \code
Douglas Gregor7861a802009-11-03 01:35:08 +00002407/// operator-function-id: [C++ 13.5]
2408/// 'operator' operator
2409///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002410/// operator: one of
Douglas Gregor7861a802009-11-03 01:35:08 +00002411/// new delete new[] delete[]
2412/// + - * / % ^ & | ~
2413/// ! = < > += -= *= /= %=
2414/// ^= &= |= << >> >>= <<= == !=
2415/// <= >= && || ++ -- , ->* ->
Richard Smithd30b23d2017-12-01 02:13:10 +00002416/// () [] <=>
Douglas Gregor7861a802009-11-03 01:35:08 +00002417///
2418/// conversion-function-id: [C++ 12.3.2]
2419/// operator conversion-type-id
2420///
2421/// conversion-type-id:
2422/// type-specifier-seq conversion-declarator[opt]
2423///
2424/// conversion-declarator:
2425/// ptr-operator conversion-declarator[opt]
2426/// \endcode
2427///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002428/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor7861a802009-11-03 01:35:08 +00002429/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2430///
Fangrui Song6907ce22018-07-30 19:24:48 +00002431/// \param EnteringContext whether we are entering the scope of the
Douglas Gregor7861a802009-11-03 01:35:08 +00002432/// nested-name-specifier.
2433///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002434/// \param ObjectType if this unqualified-id occurs within a member access
2435/// expression, the type of the base object whose member is being accessed.
2436///
2437/// \param Result on a successful parse, contains the parsed unqualified-id.
2438///
2439/// \returns true if parsing fails, false otherwise.
2440bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002441 ParsedType ObjectType,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002442 UnqualifiedId &Result) {
2443 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
Fangrui Song6907ce22018-07-30 19:24:48 +00002444
Douglas Gregor71395fa2009-11-04 00:56:37 +00002445 // Consume the 'operator' keyword.
2446 SourceLocation KeywordLoc = ConsumeToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00002447
Douglas Gregor71395fa2009-11-04 00:56:37 +00002448 // Determine what kind of operator name we have.
2449 unsigned SymbolIdx = 0;
2450 SourceLocation SymbolLocations[3];
2451 OverloadedOperatorKind Op = OO_None;
2452 switch (Tok.getKind()) {
2453 case tok::kw_new:
2454 case tok::kw_delete: {
2455 bool isNew = Tok.getKind() == tok::kw_new;
2456 // Consume the 'new' or 'delete'.
2457 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002458 // Check for array new/delete.
2459 if (Tok.is(tok::l_square) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002460 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002461 // Consume the '[' and ']'.
2462 BalancedDelimiterTracker T(*this, tok::l_square);
2463 T.consumeOpen();
2464 T.consumeClose();
2465 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002466 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002467
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002468 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2469 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002470 Op = isNew? OO_Array_New : OO_Array_Delete;
2471 } else {
2472 Op = isNew? OO_New : OO_Delete;
2473 }
2474 break;
2475 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002476
Douglas Gregor71395fa2009-11-04 00:56:37 +00002477#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2478 case tok::Token: \
2479 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2480 Op = OO_##Name; \
2481 break;
2482#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2483#include "clang/Basic/OperatorKinds.def"
Fangrui Song6907ce22018-07-30 19:24:48 +00002484
Douglas Gregor71395fa2009-11-04 00:56:37 +00002485 case tok::l_paren: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002486 // Consume the '(' and ')'.
2487 BalancedDelimiterTracker T(*this, tok::l_paren);
2488 T.consumeOpen();
2489 T.consumeClose();
2490 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002491 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002492
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002493 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2494 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002495 Op = OO_Call;
2496 break;
2497 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002498
Douglas Gregor71395fa2009-11-04 00:56:37 +00002499 case tok::l_square: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002500 // Consume the '[' and ']'.
2501 BalancedDelimiterTracker T(*this, tok::l_square);
2502 T.consumeOpen();
2503 T.consumeClose();
2504 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002505 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002506
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002507 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2508 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002509 Op = OO_Subscript;
2510 break;
2511 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002512
Douglas Gregor71395fa2009-11-04 00:56:37 +00002513 case tok::code_completion: {
2514 // Code completion for the operator name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002515 Actions.CodeCompleteOperatorName(getCurScope());
Fangrui Song6907ce22018-07-30 19:24:48 +00002516 cutOffParsing();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002517 // Don't try to parse any further.
2518 return true;
2519 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002520
Douglas Gregor71395fa2009-11-04 00:56:37 +00002521 default:
2522 break;
2523 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002524
Douglas Gregor71395fa2009-11-04 00:56:37 +00002525 if (Op != OO_None) {
2526 // We have parsed an operator-function-id.
2527 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2528 return false;
2529 }
Alexis Hunt34458502009-11-28 04:44:28 +00002530
2531 // Parse a literal-operator-id.
2532 //
Richard Smith6f212062012-10-20 08:41:10 +00002533 // literal-operator-id: C++11 [over.literal]
2534 // operator string-literal identifier
2535 // operator user-defined-string-literal
Alexis Hunt34458502009-11-28 04:44:28 +00002536
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002537 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002538 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Alexis Hunt34458502009-11-28 04:44:28 +00002539
Richard Smith7d182a72012-03-08 23:06:02 +00002540 SourceLocation DiagLoc;
2541 unsigned DiagId = 0;
2542
2543 // We're past translation phase 6, so perform string literal concatenation
2544 // before checking for "".
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002545 SmallVector<Token, 4> Toks;
2546 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith7d182a72012-03-08 23:06:02 +00002547 while (isTokenStringLiteral()) {
2548 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smith6f212062012-10-20 08:41:10 +00002549 // C++11 [over.literal]p1:
2550 // The string-literal or user-defined-string-literal in a
2551 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith7d182a72012-03-08 23:06:02 +00002552 DiagLoc = Tok.getLocation();
2553 DiagId = diag::err_literal_operator_string_prefix;
2554 }
2555 Toks.push_back(Tok);
2556 TokLocs.push_back(ConsumeStringToken());
2557 }
2558
Craig Topper9d5583e2014-06-26 04:58:39 +00002559 StringLiteralParser Literal(Toks, PP);
Richard Smith7d182a72012-03-08 23:06:02 +00002560 if (Literal.hadError)
2561 return true;
2562
2563 // Grab the literal operator's suffix, which will be either the next token
2564 // or a ud-suffix from the string literal.
Craig Topper161e4db2014-05-21 06:02:52 +00002565 IdentifierInfo *II = nullptr;
Richard Smith7d182a72012-03-08 23:06:02 +00002566 SourceLocation SuffixLoc;
2567 if (!Literal.getUDSuffix().empty()) {
2568 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2569 SuffixLoc =
2570 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2571 Literal.getUDSuffixOffset(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002572 PP.getSourceManager(), getLangOpts());
Richard Smith7d182a72012-03-08 23:06:02 +00002573 } else if (Tok.is(tok::identifier)) {
2574 II = Tok.getIdentifierInfo();
2575 SuffixLoc = ConsumeToken();
2576 TokLocs.push_back(SuffixLoc);
2577 } else {
Alp Tokerec543272013-12-24 09:48:30 +00002578 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexis Hunt34458502009-11-28 04:44:28 +00002579 return true;
2580 }
2581
Richard Smith7d182a72012-03-08 23:06:02 +00002582 // The string literal must be empty.
2583 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smith6f212062012-10-20 08:41:10 +00002584 // C++11 [over.literal]p1:
2585 // The string-literal or user-defined-string-literal in a
2586 // literal-operator-id shall [...] contain no characters
2587 // other than the implicit terminating '\0'.
Richard Smith7d182a72012-03-08 23:06:02 +00002588 DiagLoc = TokLocs.front();
2589 DiagId = diag::err_literal_operator_string_not_empty;
2590 }
2591
2592 if (DiagId) {
2593 // This isn't a valid literal-operator-id, but we think we know
2594 // what the user meant. Tell them what they should have written.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002595 SmallString<32> Str;
Richard Smithe87aeb32015-10-08 00:17:59 +00002596 Str += "\"\"";
Richard Smith7d182a72012-03-08 23:06:02 +00002597 Str += II->getName();
2598 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2599 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2600 }
2601
2602 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Richard Smithd091dc12013-12-05 00:58:33 +00002603
2604 return Actions.checkLiteralOperatorId(SS, Result);
Alexis Hunt34458502009-11-28 04:44:28 +00002605 }
Richard Smithd091dc12013-12-05 00:58:33 +00002606
Douglas Gregor71395fa2009-11-04 00:56:37 +00002607 // Parse a conversion-function-id.
2608 //
2609 // conversion-function-id: [C++ 12.3.2]
2610 // operator conversion-type-id
2611 //
2612 // conversion-type-id:
2613 // type-specifier-seq conversion-declarator[opt]
2614 //
2615 // conversion-declarator:
2616 // ptr-operator conversion-declarator[opt]
Fangrui Song6907ce22018-07-30 19:24:48 +00002617
Douglas Gregor71395fa2009-11-04 00:56:37 +00002618 // Parse the type-specifier-seq.
John McCall084e83d2011-03-24 11:26:52 +00002619 DeclSpec DS(AttrFactory);
Douglas Gregora25d65d2009-11-20 22:03:38 +00002620 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregor71395fa2009-11-04 00:56:37 +00002621 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002622
Douglas Gregor71395fa2009-11-04 00:56:37 +00002623 // Parse the conversion-declarator, which is merely a sequence of
2624 // ptr-operators.
Faisal Vali421b2d12017-12-29 05:41:00 +00002625 Declarator D(DS, DeclaratorContext::ConversionIdContext);
Craig Topper161e4db2014-05-21 06:02:52 +00002626 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2627
Douglas Gregor71395fa2009-11-04 00:56:37 +00002628 // Finish up the type.
John McCallfaf5fb42010-08-26 23:41:50 +00002629 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002630 if (Ty.isInvalid())
2631 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002632
Douglas Gregor71395fa2009-11-04 00:56:37 +00002633 // Note that this is a conversion-function-id.
Fangrui Song6907ce22018-07-30 19:24:48 +00002634 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
Douglas Gregor71395fa2009-11-04 00:56:37 +00002635 D.getSourceRange().getEnd());
Fangrui Song6907ce22018-07-30 19:24:48 +00002636 return false;
Douglas Gregor71395fa2009-11-04 00:56:37 +00002637}
2638
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002639/// Parse a C++ unqualified-id (or a C identifier), which describes the
Douglas Gregor71395fa2009-11-04 00:56:37 +00002640/// name of an entity.
2641///
2642/// \code
2643/// unqualified-id: [C++ expr.prim.general]
2644/// identifier
2645/// operator-function-id
2646/// conversion-function-id
2647/// [C++0x] literal-operator-id [TODO]
2648/// ~ class-name
2649/// template-id
2650///
2651/// \endcode
2652///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002653/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor71395fa2009-11-04 00:56:37 +00002654/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2655///
Fangrui Song6907ce22018-07-30 19:24:48 +00002656/// \param EnteringContext whether we are entering the scope of the
Douglas Gregor71395fa2009-11-04 00:56:37 +00002657/// nested-name-specifier.
2658///
Douglas Gregor7861a802009-11-03 01:35:08 +00002659/// \param AllowDestructorName whether we allow parsing of a destructor name.
2660///
2661/// \param AllowConstructorName whether we allow parsing a constructor name.
2662///
Richard Smith35845152017-02-07 01:37:30 +00002663/// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2664///
Douglas Gregor127ea592009-11-03 21:24:04 +00002665/// \param ObjectType if this unqualified-id occurs within a member access
2666/// expression, the type of the base object whose member is being accessed.
2667///
Douglas Gregor7861a802009-11-03 01:35:08 +00002668/// \param Result on a successful parse, contains the parsed unqualified-id.
2669///
2670/// \returns true if parsing fails, false otherwise.
2671bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2672 bool AllowDestructorName,
2673 bool AllowConstructorName,
Richard Smith35845152017-02-07 01:37:30 +00002674 bool AllowDeductionGuide,
John McCallba7bf592010-08-24 05:47:05 +00002675 ParsedType ObjectType,
Richard Smithc08b6932018-04-27 02:00:13 +00002676 SourceLocation *TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002677 UnqualifiedId &Result) {
Richard Smithc08b6932018-04-27 02:00:13 +00002678 if (TemplateKWLoc)
2679 *TemplateKWLoc = SourceLocation();
Douglas Gregorb22ee882010-05-05 05:58:24 +00002680
2681 // Handle 'A::template B'. This is for template-ids which have not
2682 // already been annotated by ParseOptionalCXXScopeSpecifier().
2683 bool TemplateSpecified = false;
Richard Smithc08b6932018-04-27 02:00:13 +00002684 if (Tok.is(tok::kw_template)) {
2685 if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2686 TemplateSpecified = true;
2687 *TemplateKWLoc = ConsumeToken();
2688 } else {
2689 SourceLocation TemplateLoc = ConsumeToken();
2690 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2691 << FixItHint::CreateRemoval(TemplateLoc);
2692 }
Douglas Gregorb22ee882010-05-05 05:58:24 +00002693 }
2694
Douglas Gregor7861a802009-11-03 01:35:08 +00002695 // unqualified-id:
2696 // identifier
2697 // template-id (when it hasn't already been annotated)
2698 if (Tok.is(tok::identifier)) {
2699 // Consume the identifier.
2700 IdentifierInfo *Id = Tok.getIdentifierInfo();
2701 SourceLocation IdLoc = ConsumeToken();
2702
David Blaikiebbafb8a2012-03-11 07:00:24 +00002703 if (!getLangOpts().CPlusPlus) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002704 // If we're not in C++, only identifiers matter. Record the
2705 // identifier and return.
2706 Result.setIdentifier(Id, IdLoc);
2707 return false;
2708 }
2709
Richard Smith35845152017-02-07 01:37:30 +00002710 ParsedTemplateTy TemplateName;
Fangrui Song6907ce22018-07-30 19:24:48 +00002711 if (AllowConstructorName &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002712 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002713 // We have parsed a constructor name.
Richard Smith69bc9aa2018-06-22 19:50:19 +00002714 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2715 EnteringContext);
Richard Smith715ee072018-06-20 21:58:20 +00002716 if (!Ty)
2717 return true;
Abramo Bagnara4244b432012-01-27 08:46:19 +00002718 Result.setConstructorName(Ty, IdLoc, IdLoc);
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002719 } else if (getLangOpts().CPlusPlus17 &&
Richard Smith35845152017-02-07 01:37:30 +00002720 AllowDeductionGuide && SS.isEmpty() &&
2721 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2722 &TemplateName)) {
2723 // We have parsed a template-name naming a deduction guide.
2724 Result.setDeductionGuideName(TemplateName, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002725 } else {
2726 // We have parsed an identifier.
Fangrui Song6907ce22018-07-30 19:24:48 +00002727 Result.setIdentifier(Id, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002728 }
2729
2730 // If the next token is a '<', we may have a template.
Richard Smithc08b6932018-04-27 02:00:13 +00002731 TemplateTy Template;
2732 if (Tok.is(tok::less))
2733 return ParseUnqualifiedIdTemplateId(
2734 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2735 EnteringContext, ObjectType, Result, TemplateSpecified);
2736 else if (TemplateSpecified &&
2737 Actions.ActOnDependentTemplateName(
2738 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2739 EnteringContext, Template,
2740 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2741 return true;
2742
Douglas Gregor7861a802009-11-03 01:35:08 +00002743 return false;
2744 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002745
Douglas Gregor7861a802009-11-03 01:35:08 +00002746 // unqualified-id:
2747 // template-id (already parsed and annotated)
2748 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00002749 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002750
Fangrui Song6907ce22018-07-30 19:24:48 +00002751 // If the template-name names the current class, then this is a constructor
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002752 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002753 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002754 if (SS.isSet()) {
2755 // C++ [class.qual]p2 specifies that a qualified template-name
2756 // is taken as the constructor name where a constructor can be
2757 // declared. Thus, the template arguments are extraneous, so
2758 // complain about them and remove them entirely.
Fangrui Song6907ce22018-07-30 19:24:48 +00002759 Diag(TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002760 diag::err_out_of_line_constructor_template_id)
2761 << TemplateId->Name
Douglas Gregora771f462010-03-31 17:46:05 +00002762 << FixItHint::CreateRemoval(
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002763 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Richard Smith715ee072018-06-20 21:58:20 +00002764 ParsedType Ty = Actions.getConstructorName(
Richard Smith69bc9aa2018-06-22 19:50:19 +00002765 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2766 EnteringContext);
Richard Smith715ee072018-06-20 21:58:20 +00002767 if (!Ty)
2768 return true;
Abramo Bagnara4244b432012-01-27 08:46:19 +00002769 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002770 TemplateId->RAngleLoc);
Richard Smithaf3b3252017-05-18 19:21:48 +00002771 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002772 return false;
2773 }
2774
2775 Result.setConstructorTemplateId(TemplateId);
Richard Smithaf3b3252017-05-18 19:21:48 +00002776 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002777 return false;
2778 }
2779
Douglas Gregor7861a802009-11-03 01:35:08 +00002780 // We have already parsed a template-id; consume the annotation token as
2781 // our unqualified-id.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002782 Result.setTemplateId(TemplateId);
Richard Smithc08b6932018-04-27 02:00:13 +00002783 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2784 if (TemplateLoc.isValid()) {
2785 if (TemplateKWLoc && (ObjectType || SS.isSet()))
2786 *TemplateKWLoc = TemplateLoc;
2787 else
2788 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2789 << FixItHint::CreateRemoval(TemplateLoc);
2790 }
Richard Smithaf3b3252017-05-18 19:21:48 +00002791 ConsumeAnnotationToken();
Douglas Gregor7861a802009-11-03 01:35:08 +00002792 return false;
2793 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002794
Douglas Gregor7861a802009-11-03 01:35:08 +00002795 // unqualified-id:
2796 // operator-function-id
2797 // conversion-function-id
2798 if (Tok.is(tok::kw_operator)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00002799 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor7861a802009-11-03 01:35:08 +00002800 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002801
Alexis Hunted0530f2009-11-28 08:58:14 +00002802 // If we have an operator-function-id or a literal-operator-id and the next
2803 // token is a '<', we may have a
Fangrui Song6907ce22018-07-30 19:24:48 +00002804 //
Douglas Gregor71395fa2009-11-04 00:56:37 +00002805 // template-id:
2806 // operator-function-id < template-argument-list[opt] >
Richard Smithc08b6932018-04-27 02:00:13 +00002807 TemplateTy Template;
Faisal Vali2ab8c152017-12-30 04:15:27 +00002808 if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2809 Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
Richard Smithc08b6932018-04-27 02:00:13 +00002810 Tok.is(tok::less))
2811 return ParseUnqualifiedIdTemplateId(
2812 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2813 SourceLocation(), EnteringContext, ObjectType, Result,
2814 TemplateSpecified);
2815 else if (TemplateSpecified &&
2816 Actions.ActOnDependentTemplateName(
2817 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2818 EnteringContext, Template,
2819 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2820 return true;
Craig Topper161e4db2014-05-21 06:02:52 +00002821
Douglas Gregor7861a802009-11-03 01:35:08 +00002822 return false;
2823 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002824
2825 if (getLangOpts().CPlusPlus &&
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002826 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002827 // C++ [expr.unary.op]p10:
Fangrui Song6907ce22018-07-30 19:24:48 +00002828 // There is an ambiguity in the unary-expression ~X(), where X is a
2829 // class-name. The ambiguity is resolved in favor of treating ~ as a
Douglas Gregor7861a802009-11-03 01:35:08 +00002830 // unary complement rather than treating ~X as referring to a destructor.
Fangrui Song6907ce22018-07-30 19:24:48 +00002831
Douglas Gregor7861a802009-11-03 01:35:08 +00002832 // Parse the '~'.
2833 SourceLocation TildeLoc = ConsumeToken();
David Blaikieecd8a942011-12-08 16:13:53 +00002834
2835 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2836 DeclSpec DS(AttrFactory);
2837 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Richard Smithef2cd8f2017-02-08 20:39:08 +00002838 if (ParsedType Type =
2839 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
David Blaikieecd8a942011-12-08 16:13:53 +00002840 Result.setDestructorName(TildeLoc, Type, EndLoc);
2841 return false;
2842 }
2843 return true;
2844 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002845
Douglas Gregor7861a802009-11-03 01:35:08 +00002846 // Parse the class-name.
2847 if (Tok.isNot(tok::identifier)) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002848 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00002849 return true;
2850 }
2851
Richard Smithefa6f732014-09-06 02:06:12 +00002852 // If the user wrote ~T::T, correct it to T::~T.
Richard Smith64e033f2015-01-15 00:48:52 +00002853 DeclaratorScopeObj DeclScopeObj(*this, SS);
Nico Weber10d02b52015-02-02 04:18:38 +00002854 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
Nico Weberf9e37be2015-01-30 16:53:11 +00002855 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2856 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2857 // it will confuse this recovery logic.
2858 ColonProtectionRAIIObject ColonRAII(*this, false);
2859
Richard Smithefa6f732014-09-06 02:06:12 +00002860 if (SS.isSet()) {
2861 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2862 SS.clear();
2863 }
2864 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2865 return true;
Nico Weber7f8ec522015-02-02 05:33:50 +00002866 if (SS.isNotEmpty())
David Blaikieefdccaa2016-01-15 23:43:34 +00002867 ObjectType = nullptr;
Nico Weberd0045862015-01-30 04:05:15 +00002868 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
Benjamin Kramer3012e592015-03-29 14:35:39 +00002869 !SS.isSet()) {
Richard Smithefa6f732014-09-06 02:06:12 +00002870 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2871 return true;
2872 }
2873
2874 // Recover as if the tilde had been written before the identifier.
2875 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2876 << FixItHint::CreateRemoval(TildeLoc)
2877 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
Richard Smith64e033f2015-01-15 00:48:52 +00002878
2879 // Temporarily enter the scope for the rest of this function.
2880 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2881 DeclScopeObj.EnterDeclaratorScope();
Richard Smithefa6f732014-09-06 02:06:12 +00002882 }
2883
Douglas Gregor7861a802009-11-03 01:35:08 +00002884 // Parse the class-name (or template-name in a simple-template-id).
2885 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2886 SourceLocation ClassNameLoc = ConsumeToken();
Richard Smithefa6f732014-09-06 02:06:12 +00002887
Richard Smithc08b6932018-04-27 02:00:13 +00002888 if (Tok.is(tok::less)) {
David Blaikieefdccaa2016-01-15 23:43:34 +00002889 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
Richard Smithc08b6932018-04-27 02:00:13 +00002890 return ParseUnqualifiedIdTemplateId(
2891 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
2892 ClassNameLoc, EnteringContext, ObjectType, Result, TemplateSpecified);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002893 }
Richard Smithefa6f732014-09-06 02:06:12 +00002894
Douglas Gregor7861a802009-11-03 01:35:08 +00002895 // Note that this is a destructor name.
Fangrui Song6907ce22018-07-30 19:24:48 +00002896 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
John McCallba7bf592010-08-24 05:47:05 +00002897 ClassNameLoc, getCurScope(),
2898 SS, ObjectType,
2899 EnteringContext);
Douglas Gregorfe17d252010-02-16 19:09:40 +00002900 if (!Ty)
Douglas Gregor7861a802009-11-03 01:35:08 +00002901 return true;
Douglas Gregorfe17d252010-02-16 19:09:40 +00002902
Douglas Gregor7861a802009-11-03 01:35:08 +00002903 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002904 return false;
2905 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002906
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002907 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002908 << getLangOpts().CPlusPlus;
Douglas Gregor7861a802009-11-03 01:35:08 +00002909 return true;
2910}
2911
Sebastian Redlbd150f42008-11-21 19:14:01 +00002912/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2913/// memory in a typesafe manner and call constructors.
Mike Stump11289f42009-09-09 15:08:12 +00002914///
Chris Lattner109faf22009-01-04 21:25:24 +00002915/// This method is called to parse the new expression after the optional :: has
2916/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2917/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002918///
2919/// new-expression:
2920/// '::'[opt] 'new' new-placement[opt] new-type-id
2921/// new-initializer[opt]
2922/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2923/// new-initializer[opt]
2924///
2925/// new-placement:
2926/// '(' expression-list ')'
2927///
Sebastian Redl351bb782008-12-02 14:43:59 +00002928/// new-type-id:
2929/// type-specifier-seq new-declarator[opt]
Douglas Gregora3a020a2011-04-15 19:40:02 +00002930/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redl351bb782008-12-02 14:43:59 +00002931///
2932/// new-declarator:
2933/// ptr-operator new-declarator[opt]
2934/// direct-new-declarator
2935///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002936/// new-initializer:
2937/// '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00002938/// [C++0x] braced-init-list
Sebastian Redlbd150f42008-11-21 19:14:01 +00002939///
John McCalldadc5752010-08-24 06:29:42 +00002940ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002941Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2942 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2943 ConsumeToken(); // Consume 'new'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002944
2945 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2946 // second form of new-expression. It can't be a new-type-id.
2947
Benjamin Kramerf0623432012-08-23 22:51:59 +00002948 ExprVector PlacementArgs;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002949 SourceLocation PlacementLParen, PlacementRParen;
2950
Douglas Gregorf2753b32010-07-13 15:54:32 +00002951 SourceRange TypeIdParens;
John McCall084e83d2011-03-24 11:26:52 +00002952 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00002953 Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNewContext);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002954 if (Tok.is(tok::l_paren)) {
2955 // If it turns out to be a placement, we change the type location.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002956 BalancedDelimiterTracker T(*this, tok::l_paren);
2957 T.consumeOpen();
2958 PlacementLParen = T.getOpenLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002959 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002960 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002961 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002962 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002963
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002964 T.consumeClose();
2965 PlacementRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002966 if (PlacementRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002967 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002968 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002969 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002970
Sebastian Redl351bb782008-12-02 14:43:59 +00002971 if (PlacementArgs.empty()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002972 // Reset the placement locations. There was no placement.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002973 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002974 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002975 } else {
2976 // We still need the type.
2977 if (Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002978 BalancedDelimiterTracker T(*this, tok::l_paren);
2979 T.consumeOpen();
Douglas Gregora3a020a2011-04-15 19:40:02 +00002980 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002981 ParseSpecifierQualifierList(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002982 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002983 ParseDeclarator(DeclaratorInfo);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002984 T.consumeClose();
2985 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002986 } else {
Douglas Gregora3a020a2011-04-15 19:40:02 +00002987 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002988 if (ParseCXXTypeSpecifierSeq(DS))
2989 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002990 else {
2991 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002992 ParseDeclaratorInternal(DeclaratorInfo,
2993 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002994 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002995 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002996 }
2997 } else {
Sebastian Redl351bb782008-12-02 14:43:59 +00002998 // A new-type-id is a simplified type-id, where essentially the
2999 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregora3a020a2011-04-15 19:40:02 +00003000 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00003001 if (ParseCXXTypeSpecifierSeq(DS))
3002 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003003 else {
3004 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00003005 ParseDeclaratorInternal(DeclaratorInfo,
3006 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003007 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003008 }
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003009 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003010 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00003011 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00003012 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003013
Sebastian Redl6047f072012-02-16 12:22:20 +00003014 ExprResult Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003015
3016 if (Tok.is(tok::l_paren)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00003017 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramerf0623432012-08-23 22:51:59 +00003018 ExprVector ConstructorArgs;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003019 BalancedDelimiterTracker T(*this, tok::l_paren);
3020 T.consumeOpen();
3021 ConstructorLParen = T.getOpenLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003022 if (Tok.isNot(tok::r_paren)) {
3023 CommaLocsTy CommaLocs;
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003024 auto RunSignatureHelp = [&]() {
3025 ParsedType TypeRep =
3026 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
3027 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
3028 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
3029 DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
3030 CalledSignatureHelp = true;
3031 return PreferredType;
3032 };
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003033 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003034 PreferredType.enterFunctionArgument(Tok.getLocation(),
3035 RunSignatureHelp);
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00003036 })) {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00003037 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3038 RunSignatureHelp();
Alexey Bataevee6507d2013-11-18 08:17:37 +00003039 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00003040 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00003041 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003042 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003043 T.consumeClose();
3044 ConstructorRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00003045 if (ConstructorRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003046 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00003047 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00003048 }
Sebastian Redl6047f072012-02-16 12:22:20 +00003049 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
3050 ConstructorRParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003051 ConstructorArgs);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003052 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00003053 Diag(Tok.getLocation(),
3054 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl6047f072012-02-16 12:22:20 +00003055 Initializer = ParseBraceInitializer();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003056 }
Sebastian Redl6047f072012-02-16 12:22:20 +00003057 if (Initializer.isInvalid())
3058 return Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003059
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003060 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003061 PlacementArgs, PlacementRParen,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003062 TypeIdParens, DeclaratorInfo, Initializer.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00003063}
3064
Sebastian Redlbd150f42008-11-21 19:14:01 +00003065/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
3066/// passed to ParseDeclaratorInternal.
3067///
3068/// direct-new-declarator:
Richard Smithb9fb1212019-05-06 03:47:15 +00003069/// '[' expression[opt] ']'
Sebastian Redlbd150f42008-11-21 19:14:01 +00003070/// direct-new-declarator '[' constant-expression ']'
3071///
Chris Lattner109faf22009-01-04 21:25:24 +00003072void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00003073 // Parse the array dimensions.
Richard Smithb9fb1212019-05-06 03:47:15 +00003074 bool First = true;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003075 while (Tok.is(tok::l_square)) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003076 // An array-size expression can't start with a lambda.
3077 if (CheckProhibitedCXX11Attribute())
3078 continue;
3079
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003080 BalancedDelimiterTracker T(*this, tok::l_square);
3081 T.consumeOpen();
3082
Richard Smithb9fb1212019-05-06 03:47:15 +00003083 ExprResult Size =
3084 First ? (Tok.is(tok::r_square) ? ExprResult() : ParseExpression())
3085 : ParseConstantExpression();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00003086 if (Size.isInvalid()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00003087 // Recover
Alexey Bataevee6507d2013-11-18 08:17:37 +00003088 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redlbd150f42008-11-21 19:14:01 +00003089 return;
3090 }
Richard Smithb9fb1212019-05-06 03:47:15 +00003091 First = false;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003092
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003093 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00003094
Bill Wendling44426052012-12-20 19:22:21 +00003095 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003096 ParsedAttributes Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00003097 MaybeParseCXX11Attributes(Attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003098
John McCall084e83d2011-03-24 11:26:52 +00003099 D.AddTypeInfo(DeclaratorChunk::getArray(0,
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003100 /*isStatic=*/false, /*isStar=*/false,
Erich Keanec480f302018-07-12 21:09:05 +00003101 Size.get(), T.getOpenLocation(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003102 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00003103 std::move(Attrs), T.getCloseLocation());
Sebastian Redlbd150f42008-11-21 19:14:01 +00003104
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003105 if (T.getCloseLocation().isInvalid())
Sebastian Redlbd150f42008-11-21 19:14:01 +00003106 return;
3107 }
3108}
3109
3110/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
3111/// This ambiguity appears in the syntax of the C++ new operator.
3112///
3113/// new-expression:
3114/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3115/// new-initializer[opt]
3116///
3117/// new-placement:
3118/// '(' expression-list ')'
3119///
John McCall37ad5512010-08-23 06:44:23 +00003120bool Parser::ParseExpressionListOrTypeId(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003121 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner109faf22009-01-04 21:25:24 +00003122 Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00003123 // The '(' was already consumed.
3124 if (isTypeIdInParens()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00003125 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003126 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00003127 ParseDeclarator(D);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003128 return D.isInvalidType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003129 }
3130
3131 // It's not a type, it has to be an expression list.
3132 // Discard the comma locations - ActOnCXXNew has enough parameters.
3133 CommaLocsTy CommaLocs;
3134 return ParseExpressionList(PlacementArgs, CommaLocs);
3135}
3136
3137/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
3138/// to free memory allocated by new.
3139///
Chris Lattner109faf22009-01-04 21:25:24 +00003140/// This method is called to parse the 'delete' expression after the optional
3141/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
3142/// and "Start" is its location. Otherwise, "Start" is the location of the
3143/// 'delete' token.
3144///
Sebastian Redlbd150f42008-11-21 19:14:01 +00003145/// delete-expression:
3146/// '::'[opt] 'delete' cast-expression
3147/// '::'[opt] 'delete' '[' ']' cast-expression
John McCalldadc5752010-08-24 06:29:42 +00003148ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00003149Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
3150 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
3151 ConsumeToken(); // Consume 'delete'
Sebastian Redlbd150f42008-11-21 19:14:01 +00003152
3153 // Array delete?
3154 bool ArrayDelete = false;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003155 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith10c60722012-08-09 19:01:51 +00003156 // C++11 [expr.delete]p1:
3157 // Whenever the delete keyword is followed by empty square brackets, it
3158 // shall be interpreted as [array delete].
3159 // [Footnote: A lambda expression with a lambda-introducer that consists
3160 // of empty square brackets can follow the delete keyword if
3161 // the lambda expression is enclosed in parentheses.]
Nicolas Lesserf53d1722019-05-19 15:07:58 +00003162
3163 const Token Next = GetLookAheadToken(2);
3164
3165 // Basic lookahead to check if we have a lambda expression.
3166 if (Next.isOneOf(tok::l_brace, tok::less) ||
3167 (Next.is(tok::l_paren) &&
3168 (GetLookAheadToken(3).is(tok::r_paren) ||
3169 (GetLookAheadToken(3).is(tok::identifier) &&
3170 GetLookAheadToken(4).is(tok::identifier))))) {
3171 TentativeParsingAction TPA(*this);
3172 SourceLocation LSquareLoc = Tok.getLocation();
3173 SourceLocation RSquareLoc = NextToken().getLocation();
3174
3175 // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this
3176 // case.
3177 SkipUntil({tok::l_brace, tok::less}, StopBeforeMatch);
3178 SourceLocation RBraceLoc;
3179 bool EmitFixIt = false;
Nicolas Lessere47ae692019-05-19 15:30:00 +00003180 if (Tok.is(tok::l_brace)) {
3181 ConsumeBrace();
Nicolas Lesserf53d1722019-05-19 15:07:58 +00003182 SkipUntil(tok::r_brace, StopBeforeMatch);
3183 RBraceLoc = Tok.getLocation();
3184 EmitFixIt = true;
3185 }
3186
3187 TPA.Revert();
3188
3189 if (EmitFixIt)
3190 Diag(Start, diag::err_lambda_after_delete)
3191 << SourceRange(Start, RSquareLoc)
3192 << FixItHint::CreateInsertion(LSquareLoc, "(")
3193 << FixItHint::CreateInsertion(
3194 Lexer::getLocForEndOfToken(
3195 RBraceLoc, 0, Actions.getSourceManager(), getLangOpts()),
3196 ")");
3197 else
3198 Diag(Start, diag::err_lambda_after_delete)
3199 << SourceRange(Start, RSquareLoc);
3200
3201 // Warn that the non-capturing lambda isn't surrounded by parentheses
3202 // to disambiguate it from 'delete[]'.
3203 ExprResult Lambda = ParseLambdaExpression();
3204 if (Lambda.isInvalid())
3205 return ExprError();
3206
3207 // Evaluate any postfix expressions used on the lambda.
3208 Lambda = ParsePostfixExpressionSuffix(Lambda);
3209 if (Lambda.isInvalid())
3210 return ExprError();
3211 return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
3212 Lambda.get());
3213 }
3214
Sebastian Redlbd150f42008-11-21 19:14:01 +00003215 ArrayDelete = true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003216 BalancedDelimiterTracker T(*this, tok::l_square);
3217
3218 T.consumeOpen();
3219 T.consumeClose();
3220 if (T.getCloseLocation().isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00003221 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003222 }
3223
John McCalldadc5752010-08-24 06:29:42 +00003224 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00003225 if (Operand.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003226 return Operand;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003227
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003228 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00003229}
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003230
Douglas Gregor29c42f22012-02-24 07:38:34 +00003231static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
3232 switch (kind) {
3233 default: llvm_unreachable("Not a known type trait");
Alp Toker95e7ff22014-01-01 05:57:51 +00003234#define TYPE_TRAIT_1(Spelling, Name, Key) \
3235case tok::kw_ ## Spelling: return UTT_ ## Name;
Alp Tokercbb90342013-12-13 20:49:58 +00003236#define TYPE_TRAIT_2(Spelling, Name, Key) \
3237case tok::kw_ ## Spelling: return BTT_ ## Name;
3238#include "clang/Basic/TokenKinds.def"
Alp Toker40f9b1c2013-12-12 21:23:03 +00003239#define TYPE_TRAIT_N(Spelling, Name, Key) \
3240 case tok::kw_ ## Spelling: return TT_ ## Name;
3241#include "clang/Basic/TokenKinds.def"
Douglas Gregor29c42f22012-02-24 07:38:34 +00003242 }
3243}
3244
John Wiegley6242b6a2011-04-28 00:16:57 +00003245static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
3246 switch(kind) {
3247 default: llvm_unreachable("Not a known binary type trait");
3248 case tok::kw___array_rank: return ATT_ArrayRank;
3249 case tok::kw___array_extent: return ATT_ArrayExtent;
3250 }
3251}
3252
John Wiegleyf9f65842011-04-25 06:54:41 +00003253static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
3254 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003255 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegleyf9f65842011-04-25 06:54:41 +00003256 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
3257 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
3258 }
3259}
3260
Alp Toker40f9b1c2013-12-12 21:23:03 +00003261static unsigned TypeTraitArity(tok::TokenKind kind) {
3262 switch (kind) {
3263 default: llvm_unreachable("Not a known type trait");
3264#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
3265#include "clang/Basic/TokenKinds.def"
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003266 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003267}
3268
Fangrui Song6907ce22018-07-30 19:24:48 +00003269/// Parse the built-in type-trait pseudo-functions that allow
Douglas Gregor29c42f22012-02-24 07:38:34 +00003270/// implementation of the TR1/C++11 type traits templates.
3271///
3272/// primary-expression:
Alp Toker40f9b1c2013-12-12 21:23:03 +00003273/// unary-type-trait '(' type-id ')'
3274/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor29c42f22012-02-24 07:38:34 +00003275/// type-trait '(' type-id-seq ')'
3276///
3277/// type-id-seq:
3278/// type-id ...[opt] type-id-seq[opt]
3279///
3280ExprResult Parser::ParseTypeTrait() {
Alp Toker40f9b1c2013-12-12 21:23:03 +00003281 tok::TokenKind Kind = Tok.getKind();
3282 unsigned Arity = TypeTraitArity(Kind);
3283
Douglas Gregor29c42f22012-02-24 07:38:34 +00003284 SourceLocation Loc = ConsumeToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00003285
Douglas Gregor29c42f22012-02-24 07:38:34 +00003286 BalancedDelimiterTracker Parens(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003287 if (Parens.expectAndConsume())
Douglas Gregor29c42f22012-02-24 07:38:34 +00003288 return ExprError();
3289
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003290 SmallVector<ParsedType, 2> Args;
Douglas Gregor29c42f22012-02-24 07:38:34 +00003291 do {
3292 // Parse the next type.
3293 TypeResult Ty = ParseTypeName();
3294 if (Ty.isInvalid()) {
3295 Parens.skipToEnd();
3296 return ExprError();
3297 }
3298
3299 // Parse the ellipsis, if present.
3300 if (Tok.is(tok::ellipsis)) {
3301 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3302 if (Ty.isInvalid()) {
3303 Parens.skipToEnd();
3304 return ExprError();
3305 }
3306 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003307
Douglas Gregor29c42f22012-02-24 07:38:34 +00003308 // Add this type to the list of arguments.
3309 Args.push_back(Ty.get());
Alp Tokera3ebe6e2013-12-17 14:12:37 +00003310 } while (TryConsumeToken(tok::comma));
3311
Douglas Gregor29c42f22012-02-24 07:38:34 +00003312 if (Parens.consumeClose())
3313 return ExprError();
Alp Toker40f9b1c2013-12-12 21:23:03 +00003314
3315 SourceLocation EndLoc = Parens.getCloseLocation();
3316
3317 if (Arity && Args.size() != Arity) {
3318 Diag(EndLoc, diag::err_type_trait_arity)
3319 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3320 return ExprError();
3321 }
3322
3323 if (!Arity && Args.empty()) {
3324 Diag(EndLoc, diag::err_type_trait_arity)
3325 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3326 return ExprError();
3327 }
3328
Alp Toker88f64e62013-12-13 21:19:30 +00003329 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
Douglas Gregor29c42f22012-02-24 07:38:34 +00003330}
3331
John Wiegley6242b6a2011-04-28 00:16:57 +00003332/// ParseArrayTypeTrait - Parse the built-in array type-trait
3333/// pseudo-functions.
3334///
3335/// primary-expression:
3336/// [Embarcadero] '__array_rank' '(' type-id ')'
3337/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3338///
3339ExprResult Parser::ParseArrayTypeTrait() {
3340 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3341 SourceLocation Loc = ConsumeToken();
3342
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003343 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003344 if (T.expectAndConsume())
John Wiegley6242b6a2011-04-28 00:16:57 +00003345 return ExprError();
3346
3347 TypeResult Ty = ParseTypeName();
3348 if (Ty.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003349 SkipUntil(tok::comma, StopAtSemi);
3350 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003351 return ExprError();
3352 }
3353
3354 switch (ATT) {
3355 case ATT_ArrayRank: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003356 T.consumeClose();
Craig Topper161e4db2014-05-21 06:02:52 +00003357 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003358 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003359 }
3360 case ATT_ArrayExtent: {
Alp Toker383d2c42014-01-01 03:08:43 +00003361 if (ExpectAndConsume(tok::comma)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003362 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003363 return ExprError();
3364 }
3365
3366 ExprResult DimExpr = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003367 T.consumeClose();
John Wiegley6242b6a2011-04-28 00:16:57 +00003368
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003369 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3370 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003371 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003372 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003373 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley6242b6a2011-04-28 00:16:57 +00003374}
3375
John Wiegleyf9f65842011-04-25 06:54:41 +00003376/// ParseExpressionTrait - Parse built-in expression-trait
3377/// pseudo-functions like __is_lvalue_expr( xxx ).
3378///
3379/// primary-expression:
3380/// [Embarcadero] expression-trait '(' expression ')'
3381///
3382ExprResult Parser::ParseExpressionTrait() {
3383 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3384 SourceLocation Loc = ConsumeToken();
3385
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003386 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003387 if (T.expectAndConsume())
John Wiegleyf9f65842011-04-25 06:54:41 +00003388 return ExprError();
3389
3390 ExprResult Expr = ParseExpression();
3391
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003392 T.consumeClose();
John Wiegleyf9f65842011-04-25 06:54:41 +00003393
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003394 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3395 T.getCloseLocation());
John Wiegleyf9f65842011-04-25 06:54:41 +00003396}
3397
3398
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003399/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3400/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3401/// based on the context past the parens.
John McCalldadc5752010-08-24 06:29:42 +00003402ExprResult
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003403Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallba7bf592010-08-24 05:47:05 +00003404 ParsedType &CastTy,
Richard Smith87e11a42014-05-15 02:43:47 +00003405 BalancedDelimiterTracker &Tracker,
3406 ColonProtectionRAIIObject &ColonProt) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003407 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003408 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3409 assert(isTypeIdInParens() && "Not a type-id!");
3410
John McCalldadc5752010-08-24 06:29:42 +00003411 ExprResult Result(true);
David Blaikieefdccaa2016-01-15 23:43:34 +00003412 CastTy = nullptr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003413
3414 // We need to disambiguate a very ugly part of the C++ syntax:
3415 //
3416 // (T())x; - type-id
3417 // (T())*x; - type-id
3418 // (T())/x; - expression
3419 // (T()); - expression
3420 //
3421 // The bad news is that we cannot use the specialized tentative parser, since
3422 // it can only verify that the thing inside the parens can be parsed as
3423 // type-id, it is not useful for determining the context past the parens.
3424 //
3425 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidis24ad6922009-05-22 15:12:46 +00003426 // making any unnecessary Action calls.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003427 //
3428 // It uses a scheme similar to parsing inline methods. The parenthesized
3429 // tokens are cached, the context that follows is determined (possibly by
3430 // parsing a cast-expression), and then we re-introduce the cached tokens
3431 // into the token stream and parse them appropriately.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003432
Mike Stump11289f42009-09-09 15:08:12 +00003433 ParenParseOption ParseAs;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003434 CachedTokens Toks;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003435
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003436 // Store the tokens of the parentheses. We will parse them after we determine
3437 // the context that follows them.
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +00003438 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003439 // We didn't find the ')' we expected.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003440 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003441 return ExprError();
3442 }
3443
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003444 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003445 ParseAs = CompoundLiteral;
3446 } else {
3447 bool NotCastExpr;
Eli Friedmancf7530f2009-05-25 19:41:42 +00003448 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3449 NotCastExpr = true;
3450 } else {
3451 // Try parsing the cast-expression that may follow.
3452 // If it is not a cast-expression, NotCastExpr will be true and no token
3453 // will be consumed.
Richard Smith87e11a42014-05-15 02:43:47 +00003454 ColonProt.restore();
Eli Friedmancf7530f2009-05-25 19:41:42 +00003455 Result = ParseCastExpression(false/*isUnaryExpression*/,
3456 false/*isAddressofOperand*/,
John McCallba7bf592010-08-24 05:47:05 +00003457 NotCastExpr,
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003458 // type-id has priority.
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00003459 IsTypeCast);
Eli Friedmancf7530f2009-05-25 19:41:42 +00003460 }
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003461
3462 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3463 // an expression.
3464 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003465 }
3466
Alexey Bataev703a93c2016-02-04 04:22:09 +00003467 // Create a fake EOF to mark end of Toks buffer.
3468 Token AttrEnd;
3469 AttrEnd.startToken();
3470 AttrEnd.setKind(tok::eof);
3471 AttrEnd.setLocation(Tok.getLocation());
3472 AttrEnd.setEofData(Toks.data());
3473 Toks.push_back(AttrEnd);
3474
Mike Stump11289f42009-09-09 15:08:12 +00003475 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003476 Toks.push_back(Tok);
3477 // Re-enter the stored parenthesized tokens into the token stream, so we may
3478 // parse them now.
Ilya Biryukov929af672019-05-17 09:32:05 +00003479 PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true,
3480 /*IsReinject*/ true);
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003481 // Drop the current token and bring the first cached one. It's the same token
3482 // as when we entered this function.
3483 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003484
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003485 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003486 // Parse the type declarator.
3487 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00003488 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Richard Smith87e11a42014-05-15 02:43:47 +00003489 {
3490 ColonProtectionRAIIObject InnerColonProtection(*this);
3491 ParseSpecifierQualifierList(DS);
3492 ParseDeclarator(DeclaratorInfo);
3493 }
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003494
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003495 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003496 Tracker.consumeClose();
Richard Smith87e11a42014-05-15 02:43:47 +00003497 ColonProt.restore();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003498
Alexey Bataev703a93c2016-02-04 04:22:09 +00003499 // Consume EOF marker for Toks buffer.
3500 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3501 ConsumeAnyToken();
3502
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003503 if (ParseAs == CompoundLiteral) {
3504 ExprType = CompoundLiteral;
Richard Smithaba8b362014-05-15 02:51:15 +00003505 if (DeclaratorInfo.isInvalidType())
3506 return ExprError();
3507
3508 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Richard Smith87e11a42014-05-15 02:43:47 +00003509 return ParseCompoundLiteralExpression(Ty.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003510 Tracker.getOpenLocation(),
3511 Tracker.getCloseLocation());
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003512 }
Mike Stump11289f42009-09-09 15:08:12 +00003513
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003514 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3515 assert(ParseAs == CastExpr);
3516
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003517 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003518 return ExprError();
3519
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003520 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003521 if (!Result.isInvalid())
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003522 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3523 DeclaratorInfo, CastTy,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003524 Tracker.getCloseLocation(), Result.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003525 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003526 }
Mike Stump11289f42009-09-09 15:08:12 +00003527
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003528 // Not a compound literal, and not followed by a cast-expression.
3529 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003530
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003531 ExprType = SimpleExpr;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003532 Result = ParseExpression();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003533 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Fangrui Song6907ce22018-07-30 19:24:48 +00003534 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003535 Tok.getLocation(), Result.get());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003536
3537 // Match the ')'.
3538 if (Result.isInvalid()) {
Alexey Bataev703a93c2016-02-04 04:22:09 +00003539 while (Tok.isNot(tok::eof))
3540 ConsumeAnyToken();
3541 assert(Tok.getEofData() == AttrEnd.getEofData());
3542 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003543 return ExprError();
3544 }
Mike Stump11289f42009-09-09 15:08:12 +00003545
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003546 Tracker.consumeClose();
Alexey Bataev703a93c2016-02-04 04:22:09 +00003547 // Consume EOF marker for Toks buffer.
3548 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3549 ConsumeAnyToken();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003550 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003551}
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00003552
3553/// Parse a __builtin_bit_cast(T, E).
3554ExprResult Parser::ParseBuiltinBitCast() {
3555 SourceLocation KWLoc = ConsumeToken();
3556
3557 BalancedDelimiterTracker T(*this, tok::l_paren);
3558 if (T.expectAndConsume(diag::err_expected_lparen_after, "__builtin_bit_cast"))
3559 return ExprError();
3560
3561 // Parse the common declaration-specifiers piece.
3562 DeclSpec DS(AttrFactory);
3563 ParseSpecifierQualifierList(DS);
3564
3565 // Parse the abstract-declarator, if present.
3566 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
3567 ParseDeclarator(DeclaratorInfo);
3568
3569 if (ExpectAndConsume(tok::comma)) {
3570 Diag(Tok.getLocation(), diag::err_expected) << tok::comma;
3571 SkipUntil(tok::r_paren, StopAtSemi);
3572 return ExprError();
3573 }
3574
3575 ExprResult Operand = ParseExpression();
3576
3577 if (T.consumeClose())
3578 return ExprError();
3579
3580 if (Operand.isInvalid() || DeclaratorInfo.isInvalidType())
3581 return ExprError();
3582
3583 return Actions.ActOnBuiltinBitCastExpr(KWLoc, DeclaratorInfo, Operand,
3584 T.getCloseLocation());
3585}