blob: cb0fb72c1938b4691e4311146c42052f4d220c1b [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"
23
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
Douglas Gregore861bac2009-08-25 22:51:20 +0000146bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +0000147 ParsedType ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000148 bool EnteringContext,
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000149 bool *MayBePseudoDestructor,
Richard Smith7447af42013-03-26 01:15:19 +0000150 bool IsTypename,
Matthias Gehredc01bb42017-03-17 21:41:20 +0000151 IdentifierInfo **LastII,
152 bool OnlyNamespace) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000153 assert(getLangOpts().CPlusPlus &&
Chris Lattnerb5134c02009-01-05 01:24:05 +0000154 "Call sites of this function should be guarded by checking for C++");
Mike Stump11289f42009-09-09 15:08:12 +0000155
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000156 if (Tok.is(tok::annot_cxxscope)) {
Richard Smith7447af42013-03-26 01:15:19 +0000157 assert(!LastII && "want last identifier but have already annotated scope");
Nico Weberc60aa712015-02-16 22:32:46 +0000158 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
Douglas Gregor869ad452011-02-24 17:54:50 +0000159 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
160 Tok.getAnnotationRange(),
161 SS);
Richard Smithaf3b3252017-05-18 19:21:48 +0000162 ConsumeAnnotationToken();
John McCall1f476a12010-02-26 08:45:28 +0000163 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000164 }
Chris Lattnerf9b2cd42009-01-04 21:14:15 +0000165
Larisse Voufob959c3c2013-08-06 05:49:26 +0000166 if (Tok.is(tok::annot_template_id)) {
167 // If the current token is an annotated template id, it may already have
168 // a scope specifier. Restore it.
169 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
170 SS = TemplateId->SS;
171 }
172
Nico Weberc60aa712015-02-16 22:32:46 +0000173 // Has to happen before any "return false"s in this function.
174 bool CheckForDestructor = false;
175 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
176 CheckForDestructor = true;
177 *MayBePseudoDestructor = false;
178 }
179
Richard Smith7447af42013-03-26 01:15:19 +0000180 if (LastII)
Craig Topper161e4db2014-05-21 06:02:52 +0000181 *LastII = nullptr;
Richard Smith7447af42013-03-26 01:15:19 +0000182
Douglas Gregor7f741122009-02-25 19:37:18 +0000183 bool HasScopeSpecifier = false;
184
Chris Lattner8a7d10d2009-01-05 03:55:46 +0000185 if (Tok.is(tok::coloncolon)) {
186 // ::new and ::delete aren't nested-name-specifiers.
187 tok::TokenKind NextKind = NextToken().getKind();
188 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
189 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000190
David Majnemere8fb28f2014-12-29 19:19:18 +0000191 if (NextKind == tok::l_brace) {
192 // It is invalid to have :: {, consume the scope qualifier and pretend
193 // like we never saw it.
194 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
195 } else {
196 // '::' - Global scope qualifier.
197 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
198 return true;
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000199
David Majnemere8fb28f2014-12-29 19:19:18 +0000200 HasScopeSpecifier = true;
201 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000202 }
203
Nikola Smiljanic67860242014-09-26 00:28:20 +0000204 if (Tok.is(tok::kw___super)) {
205 SourceLocation SuperLoc = ConsumeToken();
206 if (!Tok.is(tok::coloncolon)) {
207 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
208 return true;
209 }
210
211 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
212 }
213
Richard Smitha9d10012014-10-04 01:57:39 +0000214 if (!HasScopeSpecifier &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000215 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikie15a430a2011-12-04 05:04:18 +0000216 DeclSpec DS(AttrFactory);
217 SourceLocation DeclLoc = Tok.getLocation();
218 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000219
220 SourceLocation CCLoc;
Richard Smith3f846bd2017-02-08 19:58:48 +0000221 // Work around a standard defect: 'decltype(auto)::' is not a
222 // nested-name-specifier.
223 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
224 !TryConsumeToken(tok::coloncolon, CCLoc)) {
David Blaikie15a430a2011-12-04 05:04:18 +0000225 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
226 return false;
227 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000228
David Blaikie15a430a2011-12-04 05:04:18 +0000229 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
230 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
231
232 HasScopeSpecifier = true;
233 }
234
Douglas Gregor7f741122009-02-25 19:37:18 +0000235 while (true) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000236 if (HasScopeSpecifier) {
Ilya Biryukovf1822ec2018-12-03 13:29:17 +0000237 if (Tok.is(tok::code_completion)) {
238 // Code completion for a nested-name-specifier, where the code
239 // completion token follows the '::'.
240 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext,
241 ObjectType.get());
242 // 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
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000555ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
556 Token &Replacement) {
557 SourceLocation TemplateKWLoc;
558 UnqualifiedId Name;
559 if (ParseUnqualifiedId(SS,
560 /*EnteringContext=*/false,
561 /*AllowDestructorName=*/false,
562 /*AllowConstructorName=*/false,
Richard Smith35845152017-02-07 01:37:30 +0000563 /*AllowDeductionGuide=*/false,
Richard Smithc08b6932018-04-27 02:00:13 +0000564 /*ObjectType=*/nullptr, &TemplateKWLoc, Name))
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000565 return ExprError();
566
567 // This is only the direct operand of an & operator if it is not
568 // followed by a postfix-expression suffix.
569 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
570 isAddressOfOperand = false;
571
Richard Smithc2dead42018-06-27 01:32:04 +0000572 ExprResult E = Actions.ActOnIdExpression(
573 getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren),
Bruno Ricci70ad3962019-03-25 17:08:51 +0000574 isAddressOfOperand, /*CCC=*/nullptr, /*IsInlineAsmIdentifier=*/false,
Richard Smithc2dead42018-06-27 01:32:04 +0000575 &Replacement);
576 if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less))
577 checkPotentialAngleBracket(E);
578 return E;
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000579}
580
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000581/// ParseCXXIdExpression - Handle id-expression.
582///
583/// id-expression:
584/// unqualified-id
585/// qualified-id
586///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000587/// qualified-id:
588/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
589/// '::' identifier
590/// '::' operator-function-id
Douglas Gregora727cb92009-06-30 22:34:41 +0000591/// '::' template-id
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000592///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000593/// NOTE: The standard specifies that, for qualified-id, the parser does not
594/// expect:
595///
596/// '::' conversion-function-id
597/// '::' '~' class-name
598///
599/// This may cause a slight inconsistency on diagnostics:
600///
601/// class C {};
602/// namespace A {}
603/// void f() {
604/// :: A :: ~ C(); // Some Sema error about using destructor with a
605/// // namespace.
606/// :: ~ C(); // Some Parser error like 'unexpected ~'.
607/// }
608///
609/// We simplify the parser a bit and make it work like:
610///
611/// qualified-id:
612/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
613/// '::' unqualified-id
614///
615/// That way Sema can handle and report similar errors for namespaces and the
616/// global scope.
617///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000618/// The isAddressOfOperand parameter indicates that this id-expression is a
619/// direct operand of the address-of operator. This is, besides member contexts,
620/// the only place where a qualified-id naming a non-static class member may
621/// appear.
622///
John McCalldadc5752010-08-24 06:29:42 +0000623ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000624 // qualified-id:
625 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
626 // '::' unqualified-id
627 //
628 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +0000629 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000630
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000631 Token Replacement;
Nico Weber01a46ad2015-02-15 06:15:40 +0000632 ExprResult Result =
633 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000634 if (Result.isUnset()) {
635 // If the ExprResult is valid but null, then typo correction suggested a
636 // keyword replacement that needs to be reparsed.
637 UnconsumeToken(Replacement);
638 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
639 }
640 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
641 "for a previous keyword suggestion");
642 return Result;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000643}
644
Richard Smith21b3ab42013-05-09 21:36:41 +0000645/// ParseLambdaExpression - Parse a C++11 lambda expression.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000646///
647/// lambda-expression:
648/// lambda-introducer lambda-declarator[opt] compound-statement
Hamza Sood8205a812019-05-04 10:49:46 +0000649/// lambda-introducer '<' template-parameter-list '>'
650/// lambda-declarator[opt] compound-statement
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000651///
652/// lambda-introducer:
653/// '[' lambda-capture[opt] ']'
654///
655/// lambda-capture:
656/// capture-default
657/// capture-list
658/// capture-default ',' capture-list
659///
660/// capture-default:
661/// '&'
662/// '='
663///
664/// capture-list:
665/// capture
666/// capture-list ',' capture
667///
668/// capture:
Richard Smith21b3ab42013-05-09 21:36:41 +0000669/// simple-capture
670/// init-capture [C++1y]
671///
672/// simple-capture:
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000673/// identifier
674/// '&' identifier
675/// 'this'
676///
Richard Smith21b3ab42013-05-09 21:36:41 +0000677/// init-capture: [C++1y]
678/// identifier initializer
679/// '&' identifier initializer
680///
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000681/// lambda-declarator:
682/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
683/// 'mutable'[opt] exception-specification[opt]
684/// trailing-return-type[opt]
685///
686ExprResult Parser::ParseLambdaExpression() {
687 // Parse lambda-introducer.
688 LambdaIntroducer Intro;
Richard Smithe9585062019-05-20 18:01:54 +0000689 if (ParseLambdaIntroducer(Intro)) {
David Majnemer234b8182015-01-12 03:36:37 +0000690 SkipUntil(tok::r_square, StopAtSemi);
691 SkipUntil(tok::l_brace, StopAtSemi);
692 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000693 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000694 }
695
696 return ParseLambdaExpressionAfterIntroducer(Intro);
697}
698
Richard Smithe9585062019-05-20 18:01:54 +0000699/// Use lookahead and potentially tentative parsing to determine if we are
700/// looking at a C++11 lambda expression, and parse it if we are.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000701///
702/// If we are not looking at a lambda expression, returns ExprError().
703ExprResult Parser::TryParseLambdaExpression() {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000704 assert(getLangOpts().CPlusPlus11
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000705 && Tok.is(tok::l_square)
706 && "Not at the start of a possible lambda expression.");
707
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000708 const Token Next = NextToken();
709 if (Next.is(tok::eof)) // Nothing else to lookup here...
710 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000711
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000712 const Token After = GetLookAheadToken(2);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000713 // If lookahead indicates this is a lambda...
714 if (Next.is(tok::r_square) || // []
715 Next.is(tok::equal) || // [=
716 (Next.is(tok::amp) && // [&] or [&,
717 (After.is(tok::r_square) ||
718 After.is(tok::comma))) ||
719 (Next.is(tok::identifier) && // [identifier]
720 After.is(tok::r_square))) {
721 return ParseLambdaExpression();
722 }
723
Eli Friedmanc7c97142012-01-04 02:40:39 +0000724 // If lookahead indicates an ObjC message send...
725 // [identifier identifier
Richard Smithe9585062019-05-20 18:01:54 +0000726 if (Next.is(tok::identifier) && After.is(tok::identifier))
Eli Friedmanc7c97142012-01-04 02:40:39 +0000727 return ExprEmpty();
Fangrui Song6907ce22018-07-30 19:24:48 +0000728
Eli Friedmanc7c97142012-01-04 02:40:39 +0000729 // Here, we're stuck: lambda introducers and Objective-C message sends are
730 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
731 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
732 // writing two routines to parse a lambda introducer, just try to parse
733 // a lambda introducer first, and fall back if that fails.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000734 LambdaIntroducer Intro;
Richard Smithe9585062019-05-20 18:01:54 +0000735 {
736 TentativeParsingAction TPA(*this);
737 LambdaIntroducerTentativeParse Tentative;
738 if (ParseLambdaIntroducer(Intro, &Tentative)) {
739 TPA.Commit();
740 return ExprError();
741 }
742
743 switch (Tentative) {
744 case LambdaIntroducerTentativeParse::Success:
745 TPA.Commit();
746 break;
747
748 case LambdaIntroducerTentativeParse::Incomplete:
749 // Didn't fully parse the lambda-introducer, try again with a
750 // non-tentative parse.
751 TPA.Revert();
752 Intro = LambdaIntroducer();
753 if (ParseLambdaIntroducer(Intro))
754 return ExprError();
755 break;
756
757 case LambdaIntroducerTentativeParse::MessageSend:
758 case LambdaIntroducerTentativeParse::Invalid:
759 // Not a lambda-introducer, might be a message send.
760 TPA.Revert();
761 return ExprEmpty();
762 }
763 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000764
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000765 return ParseLambdaExpressionAfterIntroducer(Intro);
766}
767
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000768/// Parse a lambda introducer.
Richard Smithf44d2a82013-05-21 22:21:19 +0000769/// \param Intro A LambdaIntroducer filled in with information about the
770/// contents of the lambda-introducer.
Richard Smithe9585062019-05-20 18:01:54 +0000771/// \param Tentative If non-null, we are disambiguating between a
772/// lambda-introducer and some other construct. In this mode, we do not
773/// produce any diagnostics or take any other irreversible action unless
774/// we're sure that this is a lambda-expression.
775/// \return \c true if parsing (or disambiguation) failed with a diagnostic and
776/// the caller should bail out / recover.
777bool Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
778 LambdaIntroducerTentativeParse *Tentative) {
779 if (Tentative)
780 *Tentative = LambdaIntroducerTentativeParse::Success;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000781
782 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000783 BalancedDelimiterTracker T(*this, tok::l_square);
784 T.consumeOpen();
785
786 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000787
Richard Smithe9585062019-05-20 18:01:54 +0000788 bool First = true;
789
790 // Produce a diagnostic if we're not tentatively parsing; otherwise track
791 // that our parse has failed.
792 auto Invalid = [&](llvm::function_ref<void()> Action) {
793 if (Tentative) {
794 *Tentative = LambdaIntroducerTentativeParse::Invalid;
795 return false;
796 }
797 Action();
798 return true;
799 };
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000800
801 // Parse capture-default.
802 if (Tok.is(tok::amp) &&
803 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
804 Intro.Default = LCD_ByRef;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000805 Intro.DefaultLoc = ConsumeToken();
Richard Smithe9585062019-05-20 18:01:54 +0000806 First = false;
807 if (!Tok.getIdentifierInfo()) {
808 // This can only be a lambda; no need for tentative parsing any more.
809 // '[[and]]' can still be an attribute, though.
810 Tentative = nullptr;
811 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000812 } else if (Tok.is(tok::equal)) {
813 Intro.Default = LCD_ByCopy;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000814 Intro.DefaultLoc = ConsumeToken();
Richard Smithe9585062019-05-20 18:01:54 +0000815 First = false;
816 Tentative = nullptr;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000817 }
818
819 while (Tok.isNot(tok::r_square)) {
Richard Smithe9585062019-05-20 18:01:54 +0000820 if (!First) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000821 if (Tok.isNot(tok::comma)) {
Douglas Gregor721b14d2012-07-31 00:50:07 +0000822 // Provide a completion for a lambda introducer here. Except
823 // in Objective-C, where this is Almost Surely meant to be a message
824 // send. In that case, fail here and let the ObjC message
825 // expression parser perform the completion.
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000826 if (Tok.is(tok::code_completion) &&
Richard Smithe9585062019-05-20 18:01:54 +0000827 !(getLangOpts().ObjC && Tentative)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000828 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
Douglas Gregord8c61782012-02-15 15:34:24 +0000829 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000830 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000831 break;
832 }
833
Richard Smithe9585062019-05-20 18:01:54 +0000834 return Invalid([&] {
835 Diag(Tok.getLocation(), diag::err_expected_comma_or_rsquare);
836 });
Douglas Gregord8c61782012-02-15 15:34:24 +0000837 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000838 ConsumeToken();
839 }
840
Douglas Gregord8c61782012-02-15 15:34:24 +0000841 if (Tok.is(tok::code_completion)) {
842 // If we're in Objective-C++ and we have a bare '[', then this is more
843 // likely to be a message receiver.
Richard Smithe9585062019-05-20 18:01:54 +0000844 if (getLangOpts().ObjC && Tentative && First)
Douglas Gregord8c61782012-02-15 15:34:24 +0000845 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
846 else
Fangrui Song6907ce22018-07-30 19:24:48 +0000847 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
Douglas Gregord8c61782012-02-15 15:34:24 +0000848 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000849 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000850 break;
851 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000852
Richard Smithe9585062019-05-20 18:01:54 +0000853 First = false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000854
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000855 // Parse capture.
856 LambdaCaptureKind Kind = LCK_ByCopy;
Richard Smith42b10572015-11-11 01:36:17 +0000857 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000858 SourceLocation Loc;
Craig Topper161e4db2014-05-21 06:02:52 +0000859 IdentifierInfo *Id = nullptr;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000860 SourceLocation EllipsisLoc;
Richard Smith21b3ab42013-05-09 21:36:41 +0000861 ExprResult Init;
Alexander Shaposhnikov832f49b2018-07-16 07:23:47 +0000862 SourceLocation LocStart = Tok.getLocation();
Faisal Validc6b5962016-03-21 09:25:37 +0000863
864 if (Tok.is(tok::star)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000865 Loc = ConsumeToken();
Faisal Validc6b5962016-03-21 09:25:37 +0000866 if (Tok.is(tok::kw_this)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000867 ConsumeToken();
868 Kind = LCK_StarThis;
Faisal Validc6b5962016-03-21 09:25:37 +0000869 } else {
Richard Smithe9585062019-05-20 18:01:54 +0000870 return Invalid([&] {
871 Diag(Tok.getLocation(), diag::err_expected_star_this_capture);
872 });
Faisal Validc6b5962016-03-21 09:25:37 +0000873 }
874 } else if (Tok.is(tok::kw_this)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000875 Kind = LCK_This;
876 Loc = ConsumeToken();
877 } else {
878 if (Tok.is(tok::amp)) {
879 Kind = LCK_ByRef;
880 ConsumeToken();
Douglas Gregord8c61782012-02-15 15:34:24 +0000881
882 if (Tok.is(tok::code_completion)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000883 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
Douglas Gregord8c61782012-02-15 15:34:24 +0000884 /*AfterAmpersand=*/true);
Alp Toker1c583cc2014-05-02 03:43:14 +0000885 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000886 break;
887 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000888 }
889
890 if (Tok.is(tok::identifier)) {
891 Id = Tok.getIdentifierInfo();
892 Loc = ConsumeToken();
893 } else if (Tok.is(tok::kw_this)) {
Richard Smithe9585062019-05-20 18:01:54 +0000894 return Invalid([&] {
895 // FIXME: Suggest a fixit here.
896 Diag(Tok.getLocation(), diag::err_this_captured_by_reference);
897 });
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000898 } else {
Richard Smithe9585062019-05-20 18:01:54 +0000899 return Invalid([&] {
900 Diag(Tok.getLocation(), diag::err_expected_capture);
901 });
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000902 }
Richard Smith21b3ab42013-05-09 21:36:41 +0000903
904 if (Tok.is(tok::l_paren)) {
905 BalancedDelimiterTracker Parens(*this, tok::l_paren);
906 Parens.consumeOpen();
907
Richard Smith42b10572015-11-11 01:36:17 +0000908 InitKind = LambdaCaptureInitKind::DirectInit;
909
Richard Smith21b3ab42013-05-09 21:36:41 +0000910 ExprVector Exprs;
911 CommaLocsTy Commas;
Richard Smithe9585062019-05-20 18:01:54 +0000912 if (Tentative) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000913 Parens.skipToEnd();
Richard Smithe9585062019-05-20 18:01:54 +0000914 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
Richard Smithf44d2a82013-05-21 22:21:19 +0000915 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith21b3ab42013-05-09 21:36:41 +0000916 Parens.skipToEnd();
917 Init = ExprError();
918 } else {
919 Parens.consumeClose();
920 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
921 Parens.getCloseLocation(),
922 Exprs);
923 }
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000924 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000925 // Each lambda init-capture forms its own full expression, which clears
926 // Actions.MaybeODRUseExprs. So create an expression evaluation context
927 // to save the necessary state, and restore it later.
Faisal Valid143a0c2017-04-01 21:30:49 +0000928 EnterExpressionEvaluationContext EC(
929 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith42b10572015-11-11 01:36:17 +0000930
931 if (TryConsumeToken(tok::equal))
932 InitKind = LambdaCaptureInitKind::CopyInit;
933 else
934 InitKind = LambdaCaptureInitKind::ListInit;
Richard Smith21b3ab42013-05-09 21:36:41 +0000935
Richard Smithe9585062019-05-20 18:01:54 +0000936 if (!Tentative) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000937 Init = ParseInitializer();
Richard Smith215f4232015-02-11 02:41:33 +0000938 } else if (Tok.is(tok::l_brace)) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000939 BalancedDelimiterTracker Braces(*this, tok::l_brace);
940 Braces.consumeOpen();
941 Braces.skipToEnd();
Richard Smithe9585062019-05-20 18:01:54 +0000942 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
Richard Smithf44d2a82013-05-21 22:21:19 +0000943 } else {
944 // We're disambiguating this:
945 //
946 // [..., x = expr
947 //
948 // We need to find the end of the following expression in order to
Richard Smith9e2f0a42014-04-13 04:31:48 +0000949 // determine whether this is an Obj-C message send's receiver, a
950 // C99 designator, or a lambda init-capture.
Richard Smithf44d2a82013-05-21 22:21:19 +0000951 //
952 // Parse the expression to find where it ends, and annotate it back
953 // onto the tokens. We would have parsed this expression the same way
954 // in either case: both the RHS of an init-capture and the RHS of an
955 // assignment expression are parsed as an initializer-clause, and in
956 // neither case can anything be added to the scope between the '[' and
957 // here.
958 //
959 // FIXME: This is horrible. Adding a mechanism to skip an expression
960 // would be much cleaner.
961 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
962 // that instead. (And if we see a ':' with no matching '?', we can
963 // classify this as an Obj-C message send.)
964 SourceLocation StartLoc = Tok.getLocation();
965 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
966 Init = ParseInitializer();
Akira Hatanaka51e60f92016-12-20 02:11:29 +0000967 if (!Init.isInvalid())
968 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
Richard Smithf44d2a82013-05-21 22:21:19 +0000969
970 if (Tok.getLocation() != StartLoc) {
971 // Back out the lexing of the token after the initializer.
972 PP.RevertCachedTokens(1);
973
974 // Replace the consumed tokens with an appropriate annotation.
975 Tok.setLocation(StartLoc);
976 Tok.setKind(tok::annot_primary_expr);
977 setExprAnnotation(Tok, Init);
978 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
979 PP.AnnotateCachedTokens(Tok);
980
981 // Consume the annotated initializer.
Richard Smithaf3b3252017-05-18 19:21:48 +0000982 ConsumeAnnotationToken();
Richard Smithf44d2a82013-05-21 22:21:19 +0000983 }
984 }
Richard Smithe9585062019-05-20 18:01:54 +0000985 } else {
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000986 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Richard Smithe9585062019-05-20 18:01:54 +0000987 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000988 }
Richard Smithe9585062019-05-20 18:01:54 +0000989
990 // Check if this is a message send before we act on a possible init-capture.
991 if (Tentative && Tok.is(tok::identifier) &&
992 NextToken().isOneOf(tok::colon, tok::r_square)) {
993 // This can only be a message send. We're done with disambiguation.
994 *Tentative = LambdaIntroducerTentativeParse::MessageSend;
995 return false;
996 }
997
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000998 // If this is an init capture, process the initialization expression
999 // right away. For lambda init-captures such as the following:
1000 // const int x = 10;
1001 // auto L = [i = x+1](int a) {
1002 // return [j = x+2,
1003 // &k = x](char b) { };
1004 // };
1005 // keep in mind that each lambda init-capture has to have:
1006 // - its initialization expression executed in the context
1007 // of the enclosing/parent decl-context.
1008 // - but the variable itself has to be 'injected' into the
1009 // decl-context of its lambda's call-operator (which has
1010 // not yet been created).
1011 // Each init-expression is a full-expression that has to get
1012 // Sema-analyzed (for capturing etc.) before its lambda's
1013 // call-operator's decl-context, scope & scopeinfo are pushed on their
1014 // respective stacks. Thus if any variable is odr-used in the init-capture
1015 // it will correctly get captured in the enclosing lambda, if one exists.
1016 // The init-variables above are created later once the lambdascope and
1017 // call-operators decl-context is pushed onto its respective stack.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001018
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001019 // Since the lambda init-capture's initializer expression occurs in the
1020 // context of the enclosing function or lambda, therefore we can not wait
1021 // till a lambda scope has been pushed on before deciding whether the
1022 // variable needs to be captured. We also need to process all
1023 // lvalue-to-rvalue conversions and discarded-value conversions,
1024 // so that we can avoid capturing certain constant variables.
1025 // For e.g.,
1026 // void test() {
1027 // const int x = 10;
1028 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
1029 // return [y = x](int i) { <-- don't capture by enclosing lambda
1030 // return y;
1031 // }
1032 // };
Richard Smithbdb84f32016-07-22 23:36:59 +00001033 // }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001034 // If x was not const, the second use would require 'L' to capture, and
1035 // that would be an error.
1036
Richard Smith42b10572015-11-11 01:36:17 +00001037 ParsedType InitCaptureType;
Richard Smithe9585062019-05-20 18:01:54 +00001038 if (Tentative && Init.isUsable())
1039 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
1040 else if (Init.isUsable()) {
Volodymyr Sapsaib0f1aae2017-08-22 17:55:19 +00001041 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
Richard Smithe9585062019-05-20 18:01:54 +00001042 if (Init.isUsable()) {
1043 // Get the pointer and store it in an lvalue, so we can use it as an
1044 // out argument.
1045 Expr *InitExpr = Init.get();
1046 // This performs any lvalue-to-rvalue conversions if necessary, which
1047 // can affect what gets captured in the containing decl-context.
1048 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
1049 Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
1050 Init = InitExpr;
1051 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001052 }
Alexander Shaposhnikov832f49b2018-07-16 07:23:47 +00001053
1054 SourceLocation LocEnd = PrevTokLocation;
1055
Richard Smith42b10572015-11-11 01:36:17 +00001056 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
Alexander Shaposhnikov832f49b2018-07-16 07:23:47 +00001057 InitCaptureType, SourceRange(LocStart, LocEnd));
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001058 }
1059
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001060 T.consumeClose();
1061 Intro.Range.setEnd(T.getCloseLocation());
Richard Smithe9585062019-05-20 18:01:54 +00001062 return false;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001063}
1064
Faisal Valia734ab92016-03-26 16:11:37 +00001065static void
1066tryConsumeMutableOrConstexprToken(Parser &P, SourceLocation &MutableLoc,
1067 SourceLocation &ConstexprLoc,
1068 SourceLocation &DeclEndLoc) {
1069 assert(MutableLoc.isInvalid());
1070 assert(ConstexprLoc.isInvalid());
1071 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1072 // to the final of those locations. Emit an error if we have multiple
1073 // copies of those keywords and recover.
1074
1075 while (true) {
1076 switch (P.getCurToken().getKind()) {
1077 case tok::kw_mutable: {
1078 if (MutableLoc.isValid()) {
1079 P.Diag(P.getCurToken().getLocation(),
1080 diag::err_lambda_decl_specifier_repeated)
1081 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1082 }
1083 MutableLoc = P.ConsumeToken();
1084 DeclEndLoc = MutableLoc;
1085 break /*switch*/;
1086 }
1087 case tok::kw_constexpr:
1088 if (ConstexprLoc.isValid()) {
1089 P.Diag(P.getCurToken().getLocation(),
1090 diag::err_lambda_decl_specifier_repeated)
1091 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1092 }
1093 ConstexprLoc = P.ConsumeToken();
1094 DeclEndLoc = ConstexprLoc;
1095 break /*switch*/;
1096 default:
1097 return;
1098 }
1099 }
1100}
1101
1102static void
1103addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1104 DeclSpec &DS) {
1105 if (ConstexprLoc.isValid()) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001106 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
Richard Smithb115e5d2017-08-13 23:37:29 +00001107 ? diag::ext_constexpr_on_lambda_cxx17
Faisal Valia734ab92016-03-26 16:11:37 +00001108 : diag::warn_cxx14_compat_constexpr_on_lambda);
1109 const char *PrevSpec = nullptr;
1110 unsigned DiagID = 0;
1111 DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
1112 assert(PrevSpec == nullptr && DiagID == 0 &&
1113 "Constexpr cannot have been set previously!");
1114 }
1115}
1116
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001117/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1118/// expression.
1119ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1120 LambdaIntroducer &Intro) {
Eli Friedmanc7c97142012-01-04 02:40:39 +00001121 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1122 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1123
1124 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1125 "lambda expression parsing");
1126
Fangrui Song6907ce22018-07-30 19:24:48 +00001127
Faisal Vali2b391ab2013-09-26 19:54:12 +00001128
Richard Smith21b3ab42013-05-09 21:36:41 +00001129 // FIXME: Call into Actions to add any init-capture declarations to the
1130 // scope while parsing the lambda-declarator and compound-statement.
1131
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001132 // Parse lambda-declarator[opt].
1133 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00001134 Declarator D(DS, DeclaratorContext::LambdaExprContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001135 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001136 Actions.PushLambdaScope();
1137
1138 ParsedAttributes Attr(AttrFactory);
1139 SourceLocation DeclLoc = Tok.getLocation();
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001140 if (getLangOpts().CUDA) {
1141 // In CUDA code, GNU attributes are allowed to appear immediately after the
1142 // "[...]", even if there is no "(...)" before the lambda body.
Justin Lebar0139a5d2016-09-30 19:55:48 +00001143 MaybeParseGNUAttributes(D);
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001144 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001145
Justin Lebare46ea722016-09-30 19:55:55 +00001146 // Helper to emit a warning if we see a CUDA host/device/global attribute
1147 // after '(...)'. nvcc doesn't accept this.
1148 auto WarnIfHasCUDATargetAttr = [&] {
1149 if (getLangOpts().CUDA)
Erich Keanee891aa92018-07-13 15:07:47 +00001150 for (const ParsedAttr &A : Attr)
1151 if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1152 A.getKind() == ParsedAttr::AT_CUDAHost ||
1153 A.getKind() == ParsedAttr::AT_CUDAGlobal)
Erich Keanec480f302018-07-12 21:09:05 +00001154 Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
1155 << A.getName()->getName();
Justin Lebare46ea722016-09-30 19:55:55 +00001156 };
1157
Hamza Sood8205a812019-05-04 10:49:46 +00001158 // FIXME: Consider allowing this as an extension for GCC compatibiblity.
1159 const bool HasExplicitTemplateParams = Tok.is(tok::less);
1160 ParseScope TemplateParamScope(this, Scope::TemplateParamScope,
1161 /*EnteredScope=*/HasExplicitTemplateParams);
1162 if (HasExplicitTemplateParams) {
1163 Diag(Tok, getLangOpts().CPlusPlus2a
1164 ? diag::warn_cxx17_compat_lambda_template_parameter_list
1165 : diag::ext_lambda_template_parameter_list);
1166
1167 SmallVector<NamedDecl*, 4> TemplateParams;
1168 SourceLocation LAngleLoc, RAngleLoc;
1169 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
1170 TemplateParams, LAngleLoc, RAngleLoc)) {
1171 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1172 return ExprError();
1173 }
1174
1175 if (TemplateParams.empty()) {
1176 Diag(RAngleLoc,
1177 diag::err_lambda_template_parameter_list_empty);
1178 } else {
1179 Actions.ActOnLambdaExplicitTemplateParameterList(
1180 LAngleLoc, TemplateParams, RAngleLoc);
1181 ++CurTemplateDepthTracker;
1182 }
1183 }
1184
David Majnemere01c4662015-01-09 05:10:55 +00001185 TypeResult TrailingReturnType;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001186 if (Tok.is(tok::l_paren)) {
1187 ParseScope PrototypeScope(this,
1188 Scope::FunctionPrototypeScope |
Richard Smithe233fbf2013-01-28 22:42:45 +00001189 Scope::FunctionDeclarationScope |
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001190 Scope::DeclScope);
1191
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001192 BalancedDelimiterTracker T(*this, tok::l_paren);
1193 T.consumeOpen();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001194 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001195
1196 // Parse parameter-declaration-clause.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001197 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001198 SourceLocation EllipsisLoc;
Fangrui Song6907ce22018-07-30 19:24:48 +00001199
Faisal Vali2b391ab2013-09-26 19:54:12 +00001200 if (Tok.isNot(tok::r_paren)) {
Hamza Sood8205a812019-05-04 10:49:46 +00001201 Actions.RecordParsingTemplateParameterDepth(
1202 CurTemplateDepthTracker.getOriginalDepth());
1203
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001204 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
Hamza Sood8205a812019-05-04 10:49:46 +00001205
Fangrui Song6907ce22018-07-30 19:24:48 +00001206 // For a generic lambda, each 'auto' within the parameter declaration
Faisal Vali2b391ab2013-09-26 19:54:12 +00001207 // clause creates a template type parameter, so increment the depth.
Hamza Sood8205a812019-05-04 10:49:46 +00001208 // If we've parsed any explicit template parameters, then the depth will
1209 // have already been incremented. So we make sure that at most a single
1210 // depth level is added.
Fangrui Song6907ce22018-07-30 19:24:48 +00001211 if (Actions.getCurGenericLambda())
Hamza Sood8205a812019-05-04 10:49:46 +00001212 CurTemplateDepthTracker.setAddedDepth(1);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001213 }
Hamza Sood8205a812019-05-04 10:49:46 +00001214
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001215 T.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001216 SourceLocation RParenLoc = T.getCloseLocation();
Justin Lebar0139a5d2016-09-30 19:55:48 +00001217 SourceLocation DeclEndLoc = RParenLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001218
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001219 // GNU-style attributes must be parsed before the mutable specifier to be
1220 // compatible with GCC.
1221 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1222
David Majnemerbda86322015-02-04 08:22:46 +00001223 // MSVC-style attributes must be parsed before the mutable specifier to be
1224 // compatible with MSVC.
Aaron Ballman068aa512015-05-20 20:58:33 +00001225 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
David Majnemerbda86322015-02-04 08:22:46 +00001226
Faisal Valia734ab92016-03-26 16:11:37 +00001227 // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001228 SourceLocation MutableLoc;
Faisal Valia734ab92016-03-26 16:11:37 +00001229 SourceLocation ConstexprLoc;
1230 tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
1231 DeclEndLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001232
Faisal Valia734ab92016-03-26 16:11:37 +00001233 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001234
1235 // Parse exception-specification[opt].
1236 ExceptionSpecificationType ESpecType = EST_None;
1237 SourceRange ESpecRange;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001238 SmallVector<ParsedType, 2> DynamicExceptions;
1239 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001240 ExprResult NoexceptExpr;
Richard Smith0b3a4622014-11-13 20:01:57 +00001241 CachedTokens *ExceptionSpecTokens;
1242 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1243 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00001244 DynamicExceptions,
1245 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00001246 NoexceptExpr,
1247 ExceptionSpecTokens);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001248
1249 if (ESpecType != EST_None)
1250 DeclEndLoc = ESpecRange.getEnd();
1251
1252 // Parse attribute-specifier[opt].
Richard Smith89645bc2013-01-02 12:01:23 +00001253 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001254
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001255 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1256
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001257 // Parse trailing-return-type[opt].
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001258 if (Tok.is(tok::arrow)) {
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001259 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001260 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00001261 TrailingReturnType =
1262 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001263 if (Range.getEnd().isValid())
1264 DeclEndLoc = Range.getEnd();
1265 }
1266
1267 PrototypeScope.Exit();
1268
Justin Lebare46ea722016-09-30 19:55:55 +00001269 WarnIfHasCUDATargetAttr();
1270
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001271 SourceLocation NoLoc;
Erich Keanec480f302018-07-12 21:09:05 +00001272 D.AddTypeInfo(DeclaratorChunk::getFunction(
1273 /*hasProto=*/true,
1274 /*isAmbiguous=*/false, LParenLoc, ParamInfo.data(),
1275 ParamInfo.size(), EllipsisLoc, RParenLoc,
Erich Keanec480f302018-07-12 21:09:05 +00001276 /*RefQualifierIsLValueRef=*/true,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00001277 /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType,
Erich Keanec480f302018-07-12 21:09:05 +00001278 ESpecRange, DynamicExceptions.data(),
1279 DynamicExceptionRanges.data(), DynamicExceptions.size(),
1280 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1281 /*ExceptionSpecTokens*/ nullptr,
1282 /*DeclsInPrototype=*/None, LParenLoc, FunLocalRangeEnd, D,
1283 TrailingReturnType),
1284 std::move(Attr), DeclEndLoc);
Faisal Valia734ab92016-03-26 16:11:37 +00001285 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1286 tok::kw_constexpr) ||
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001287 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1288 // It's common to forget that one needs '()' before 'mutable', an attribute
1289 // specifier, or the result type. Deal with this.
1290 unsigned TokKind = 0;
1291 switch (Tok.getKind()) {
1292 case tok::kw_mutable: TokKind = 0; break;
1293 case tok::arrow: TokKind = 1; break;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001294 case tok::kw___attribute:
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001295 case tok::l_square: TokKind = 2; break;
Faisal Valia734ab92016-03-26 16:11:37 +00001296 case tok::kw_constexpr: TokKind = 3; break;
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001297 default: llvm_unreachable("Unknown token kind");
1298 }
1299
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001300 Diag(Tok, diag::err_lambda_missing_parens)
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001301 << TokKind
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001302 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
Justin Lebar0139a5d2016-09-30 19:55:48 +00001303 SourceLocation DeclEndLoc = DeclLoc;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001304
1305 // GNU-style attributes must be parsed before the mutable specifier to be
1306 // compatible with GCC.
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001307 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1308
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001309 // Parse 'mutable', if it's there.
1310 SourceLocation MutableLoc;
1311 if (Tok.is(tok::kw_mutable)) {
1312 MutableLoc = ConsumeToken();
1313 DeclEndLoc = MutableLoc;
1314 }
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001315
1316 // Parse attribute-specifier[opt].
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001317 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1318
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001319 // Parse the return type, if there is one.
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001320 if (Tok.is(tok::arrow)) {
1321 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00001322 TrailingReturnType =
1323 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001324 if (Range.getEnd().isValid())
David Majnemere01c4662015-01-09 05:10:55 +00001325 DeclEndLoc = Range.getEnd();
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001326 }
1327
Justin Lebare46ea722016-09-30 19:55:55 +00001328 WarnIfHasCUDATargetAttr();
1329
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001330 SourceLocation NoLoc;
Erich Keanec480f302018-07-12 21:09:05 +00001331 D.AddTypeInfo(DeclaratorChunk::getFunction(
1332 /*hasProto=*/true,
1333 /*isAmbiguous=*/false,
1334 /*LParenLoc=*/NoLoc,
1335 /*Params=*/nullptr,
1336 /*NumParams=*/0,
1337 /*EllipsisLoc=*/NoLoc,
1338 /*RParenLoc=*/NoLoc,
Erich Keanec480f302018-07-12 21:09:05 +00001339 /*RefQualifierIsLValueRef=*/true,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00001340 /*RefQualifierLoc=*/NoLoc, MutableLoc, EST_None,
Erich Keanec480f302018-07-12 21:09:05 +00001341 /*ESpecRange=*/SourceRange(),
1342 /*Exceptions=*/nullptr,
1343 /*ExceptionRanges=*/nullptr,
1344 /*NumExceptions=*/0,
1345 /*NoexceptExpr=*/nullptr,
1346 /*ExceptionSpecTokens=*/nullptr,
1347 /*DeclsInPrototype=*/None, DeclLoc, DeclEndLoc, D,
1348 TrailingReturnType),
1349 std::move(Attr), DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001350 }
1351
Eli Friedman4817cf72012-01-06 03:05:34 +00001352 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1353 // it.
Momchil Velikov57c681f2017-08-10 15:43:06 +00001354 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1355 Scope::CompoundStmtScope;
Douglas Gregorb8389972012-02-21 22:51:27 +00001356 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman4817cf72012-01-06 03:05:34 +00001357
Eli Friedman71c80552012-01-05 03:35:19 +00001358 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1359
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001360 // Parse compound-statement.
Eli Friedmanc7c97142012-01-04 02:40:39 +00001361 if (!Tok.is(tok::l_brace)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001362 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmanc7c97142012-01-04 02:40:39 +00001363 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1364 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001365 }
1366
Eli Friedmanc7c97142012-01-04 02:40:39 +00001367 StmtResult Stmt(ParseCompoundStatementBody());
1368 BodyScope.Exit();
Hamza Sood8205a812019-05-04 10:49:46 +00001369 TemplateParamScope.Exit();
Eli Friedmanc7c97142012-01-04 02:40:39 +00001370
David Majnemere01c4662015-01-09 05:10:55 +00001371 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001372 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
David Majnemere01c4662015-01-09 05:10:55 +00001373
Eli Friedman898caf82012-01-04 02:46:53 +00001374 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1375 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001376}
1377
Chris Lattner29375652006-12-04 18:06:35 +00001378/// ParseCXXCasts - This handles the various ways to cast expressions to another
1379/// type.
1380///
1381/// postfix-expression: [C++ 5.2p1]
1382/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1383/// 'static_cast' '<' type-name '>' '(' expression ')'
1384/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1385/// 'const_cast' '<' type-name '>' '(' expression ')'
1386///
John McCalldadc5752010-08-24 06:29:42 +00001387ExprResult Parser::ParseCXXCasts() {
Chris Lattner29375652006-12-04 18:06:35 +00001388 tok::TokenKind Kind = Tok.getKind();
Craig Topper161e4db2014-05-21 06:02:52 +00001389 const char *CastName = nullptr; // For error messages
Chris Lattner29375652006-12-04 18:06:35 +00001390
1391 switch (Kind) {
David Blaikieaa347f92011-09-23 20:26:49 +00001392 default: llvm_unreachable("Unknown C++ cast!");
Chris Lattner29375652006-12-04 18:06:35 +00001393 case tok::kw_const_cast: CastName = "const_cast"; break;
1394 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1395 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1396 case tok::kw_static_cast: CastName = "static_cast"; break;
1397 }
1398
1399 SourceLocation OpLoc = ConsumeToken();
1400 SourceLocation LAngleBracketLoc = Tok.getLocation();
1401
Richard Smith55858492011-04-14 21:45:45 +00001402 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1403 // diagnose error, suggest fix, and recover parsing.
Richard Smith62e66302012-08-20 17:37:52 +00001404 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1405 Token Next = NextToken();
1406 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1407 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1408 }
Richard Smith55858492011-04-14 21:45:45 +00001409
Chris Lattner29375652006-12-04 18:06:35 +00001410 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redld65cea82008-12-11 22:51:44 +00001411 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001412
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001413 // Parse the common declaration-specifiers piece.
1414 DeclSpec DS(AttrFactory);
1415 ParseSpecifierQualifierList(DS);
1416
1417 // Parse the abstract-declarator, if present.
Faisal Vali421b2d12017-12-29 05:41:00 +00001418 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001419 ParseDeclarator(DeclaratorInfo);
1420
Chris Lattner29375652006-12-04 18:06:35 +00001421 SourceLocation RAngleBracketLoc = Tok.getLocation();
1422
Alp Toker383d2c42014-01-01 03:08:43 +00001423 if (ExpectAndConsume(tok::greater))
Alp Tokerec543272013-12-24 09:48:30 +00001424 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
Chris Lattner29375652006-12-04 18:06:35 +00001425
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001426 BalancedDelimiterTracker T(*this, tok::l_paren);
Chris Lattner29375652006-12-04 18:06:35 +00001427
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001428 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001429 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001430
John McCalldadc5752010-08-24 06:29:42 +00001431 ExprResult Result = ParseExpression();
Mike Stump11289f42009-09-09 15:08:12 +00001432
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001433 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001434 T.consumeClose();
Chris Lattner29375652006-12-04 18:06:35 +00001435
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001436 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregore200adc2008-10-27 19:41:14 +00001437 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001438 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor220cac52009-02-18 17:45:20 +00001439 RAngleBracketLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00001440 T.getOpenLocation(), Result.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001441 T.getCloseLocation());
Chris Lattner29375652006-12-04 18:06:35 +00001442
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001443 return Result;
Chris Lattner29375652006-12-04 18:06:35 +00001444}
Bill Wendling4073ed52007-02-13 01:51:42 +00001445
Sebastian Redlc4704762008-11-11 11:37:55 +00001446/// ParseCXXTypeid - This handles the C++ typeid expression.
1447///
1448/// postfix-expression: [C++ 5.2p1]
1449/// 'typeid' '(' expression ')'
1450/// 'typeid' '(' type-id ')'
1451///
John McCalldadc5752010-08-24 06:29:42 +00001452ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc4704762008-11-11 11:37:55 +00001453 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1454
1455 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001456 SourceLocation LParenLoc, RParenLoc;
1457 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc4704762008-11-11 11:37:55 +00001458
1459 // typeid expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001460 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redld65cea82008-12-11 22:51:44 +00001461 return ExprError();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001462 LParenLoc = T.getOpenLocation();
Sebastian Redlc4704762008-11-11 11:37:55 +00001463
John McCalldadc5752010-08-24 06:29:42 +00001464 ExprResult Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001465
Richard Smith4f605af2012-08-18 00:55:03 +00001466 // C++0x [expr.typeid]p3:
1467 // When typeid is applied to an expression other than an lvalue of a
1468 // polymorphic class type [...] The expression is an unevaluated
1469 // operand (Clause 5).
1470 //
1471 // Note that we can't tell whether the expression is an lvalue of a
1472 // polymorphic class type until after we've parsed the expression; we
1473 // speculatively assume the subexpression is unevaluated, and fix it up
1474 // later.
1475 //
1476 // We enter the unevaluated context before trying to determine whether we
1477 // have a type-id, because the tentative parse logic will try to resolve
1478 // names, and must treat them as unevaluated.
Faisal Valid143a0c2017-04-01 21:30:49 +00001479 EnterExpressionEvaluationContext Unevaluated(
1480 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1481 Sema::ReuseLambdaContextDecl);
Richard Smith4f605af2012-08-18 00:55:03 +00001482
Sebastian Redlc4704762008-11-11 11:37:55 +00001483 if (isTypeIdInParens()) {
Douglas Gregor220cac52009-02-18 17:45:20 +00001484 TypeResult Ty = ParseTypeName();
Sebastian Redlc4704762008-11-11 11:37:55 +00001485
1486 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001487 T.consumeClose();
1488 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001489 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00001490 return ExprError();
Sebastian Redlc4704762008-11-11 11:37:55 +00001491
1492 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallba7bf592010-08-24 05:47:05 +00001493 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001494 } else {
1495 Result = ParseExpression();
1496
1497 // Match the ')'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001498 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001499 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc4704762008-11-11 11:37:55 +00001500 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001501 T.consumeClose();
1502 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001503 if (RParenLoc.isInvalid())
1504 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00001505
Sebastian Redlc4704762008-11-11 11:37:55 +00001506 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001507 Result.get(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001508 }
1509 }
1510
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001511 return Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001512}
1513
Francois Pichet9f4f2072010-09-08 12:20:18 +00001514/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1515///
1516/// '__uuidof' '(' expression ')'
1517/// '__uuidof' '(' type-id ')'
1518///
1519ExprResult Parser::ParseCXXUuidof() {
1520 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1521
1522 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001523 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001524
1525 // __uuidof expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001526 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet9f4f2072010-09-08 12:20:18 +00001527 return ExprError();
1528
1529 ExprResult Result;
1530
1531 if (isTypeIdInParens()) {
1532 TypeResult Ty = ParseTypeName();
1533
1534 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001535 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001536
1537 if (Ty.isInvalid())
1538 return ExprError();
1539
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001540 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
Fangrui Song6907ce22018-07-30 19:24:48 +00001541 Ty.get().getAsOpaquePtr(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001542 T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001543 } else {
Faisal Valid143a0c2017-04-01 21:30:49 +00001544 EnterExpressionEvaluationContext Unevaluated(
1545 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001546 Result = ParseExpression();
1547
1548 // Match the ')'.
1549 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001550 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001551 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001552 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001553
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001554 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1555 /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001556 Result.get(), T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001557 }
1558 }
1559
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001560 return Result;
Francois Pichet9f4f2072010-09-08 12:20:18 +00001561}
1562
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001563/// Parse a C++ pseudo-destructor expression after the base,
Douglas Gregore610ada2010-02-24 18:44:31 +00001564/// . or -> operator, and nested-name-specifier have already been
1565/// parsed.
1566///
1567/// postfix-expression: [C++ 5.2]
1568/// postfix-expression . pseudo-destructor-name
1569/// postfix-expression -> pseudo-destructor-name
1570///
Fangrui Song6907ce22018-07-30 19:24:48 +00001571/// pseudo-destructor-name:
1572/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1573/// ::[opt] nested-name-specifier template simple-template-id ::
1574/// ~type-name
Douglas Gregore610ada2010-02-24 18:44:31 +00001575/// ::[opt] nested-name-specifier[opt] ~type-name
Fangrui Song6907ce22018-07-30 19:24:48 +00001576///
1577ExprResult
Craig Toppera2c51532014-10-30 05:30:05 +00001578Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00001579 tok::TokenKind OpKind,
1580 CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +00001581 ParsedType ObjectType) {
Douglas Gregore610ada2010-02-24 18:44:31 +00001582 // We're parsing either a pseudo-destructor-name or a dependent
1583 // member access that has the same form as a
1584 // pseudo-destructor-name. We parse both in the same way and let
1585 // the action model sort them out.
1586 //
1587 // Note that the ::[opt] nested-name-specifier[opt] has already
1588 // been parsed, and if there was a simple-template-id, it has
1589 // been coalesced into a template-id annotation token.
1590 UnqualifiedId FirstTypeName;
1591 SourceLocation CCLoc;
1592 if (Tok.is(tok::identifier)) {
1593 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1594 ConsumeToken();
1595 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1596 CCLoc = ConsumeToken();
1597 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001598 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1599 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregore610ada2010-02-24 18:44:31 +00001600 FirstTypeName.setTemplateId(
1601 (TemplateIdAnnotation *)Tok.getAnnotationValue());
Richard Smithaf3b3252017-05-18 19:21:48 +00001602 ConsumeAnnotationToken();
Douglas Gregore610ada2010-02-24 18:44:31 +00001603 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1604 CCLoc = ConsumeToken();
1605 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001606 FirstTypeName.setIdentifier(nullptr, SourceLocation());
Douglas Gregore610ada2010-02-24 18:44:31 +00001607 }
1608
1609 // Parse the tilde.
1610 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1611 SourceLocation TildeLoc = ConsumeToken();
David Blaikie1d578782011-12-16 16:03:09 +00001612
1613 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1614 DeclSpec DS(AttrFactory);
Benjamin Kramer198e0832011-12-18 12:18:02 +00001615 ParseDecltypeSpecifier(DS);
Faisal Vali090da2d2018-01-01 18:23:28 +00001616 if (DS.getTypeSpecType() == TST_error)
David Blaikie1d578782011-12-16 16:03:09 +00001617 return ExprError();
David Majnemerced8bdf2015-02-25 17:36:15 +00001618 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1619 TildeLoc, DS);
David Blaikie1d578782011-12-16 16:03:09 +00001620 }
1621
Douglas Gregore610ada2010-02-24 18:44:31 +00001622 if (!Tok.is(tok::identifier)) {
1623 Diag(Tok, diag::err_destructor_tilde_identifier);
1624 return ExprError();
1625 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001626
Douglas Gregore610ada2010-02-24 18:44:31 +00001627 // Parse the second type.
1628 UnqualifiedId SecondTypeName;
1629 IdentifierInfo *Name = Tok.getIdentifierInfo();
1630 SourceLocation NameLoc = ConsumeToken();
1631 SecondTypeName.setIdentifier(Name, NameLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001632
Douglas Gregore610ada2010-02-24 18:44:31 +00001633 // If there is a '<', the second type name is a template-id. Parse
1634 // it as such.
1635 if (Tok.is(tok::less) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +00001636 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1637 Name, NameLoc,
1638 false, ObjectType, SecondTypeName,
1639 /*AssumeTemplateName=*/true))
Douglas Gregore610ada2010-02-24 18:44:31 +00001640 return ExprError();
1641
David Majnemerced8bdf2015-02-25 17:36:15 +00001642 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1643 SS, FirstTypeName, CCLoc, TildeLoc,
1644 SecondTypeName);
Douglas Gregore610ada2010-02-24 18:44:31 +00001645}
1646
Bill Wendling4073ed52007-02-13 01:51:42 +00001647/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1648///
1649/// boolean-literal: [C++ 2.13.5]
1650/// 'true'
1651/// 'false'
John McCalldadc5752010-08-24 06:29:42 +00001652ExprResult Parser::ParseCXXBoolLiteral() {
Bill Wendling4073ed52007-02-13 01:51:42 +00001653 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001654 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Bill Wendling4073ed52007-02-13 01:51:42 +00001655}
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001656
1657/// ParseThrowExpression - This handles the C++ throw expression.
1658///
1659/// throw-expression: [C++ 15]
1660/// 'throw' assignment-expression[opt]
John McCalldadc5752010-08-24 06:29:42 +00001661ExprResult Parser::ParseThrowExpression() {
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001662 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001663 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redld65cea82008-12-11 22:51:44 +00001664
Chris Lattner65dd8432008-04-06 06:02:23 +00001665 // If the current token isn't the start of an assignment-expression,
1666 // then the expression is not present. This handles things like:
1667 // "C ? throw : (void)42", which is crazy but legal.
1668 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1669 case tok::semi:
1670 case tok::r_paren:
1671 case tok::r_square:
1672 case tok::r_brace:
1673 case tok::colon:
1674 case tok::comma:
Craig Topper161e4db2014-05-21 06:02:52 +00001675 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001676
Chris Lattner65dd8432008-04-06 06:02:23 +00001677 default:
John McCalldadc5752010-08-24 06:29:42 +00001678 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001679 if (Expr.isInvalid()) return Expr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001680 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
Chris Lattner65dd8432008-04-06 06:02:23 +00001681 }
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001682}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001683
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001684/// Parse the C++ Coroutines co_yield expression.
Richard Smith0e304ea2015-10-22 04:46:14 +00001685///
1686/// co_yield-expression:
1687/// 'co_yield' assignment-expression[opt]
1688ExprResult Parser::ParseCoyieldExpression() {
1689 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1690
1691 SourceLocation Loc = ConsumeToken();
Richard Smithae3d1472015-11-20 22:47:10 +00001692 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1693 : ParseAssignmentExpression();
Richard Smithcfd53b42015-10-22 06:13:50 +00001694 if (!Expr.isInvalid())
Richard Smith9f690bd2015-10-27 06:02:45 +00001695 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
Richard Smith0e304ea2015-10-22 04:46:14 +00001696 return Expr;
1697}
1698
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001699/// ParseCXXThis - This handles the C++ 'this' pointer.
1700///
1701/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1702/// a non-lvalue expression whose value is the address of the object for which
1703/// the function is called.
John McCalldadc5752010-08-24 06:29:42 +00001704ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001705 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1706 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001707 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001708}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001709
1710/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1711/// Can be interpreted either as function-style casting ("int(x)")
1712/// or class type construction ("ClassType(x,y,z)")
1713/// or creation of a value-initialized type ("int()").
Sebastian Redl3da34892011-06-05 12:23:16 +00001714/// See [C++ 5.2.3].
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001715///
1716/// postfix-expression: [C++ 5.2p1]
Sebastian Redl3da34892011-06-05 12:23:16 +00001717/// simple-type-specifier '(' expression-list[opt] ')'
1718/// [C++0x] simple-type-specifier braced-init-list
1719/// typename-specifier '(' expression-list[opt] ')'
1720/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001721///
Richard Smith600b5262017-01-26 20:40:47 +00001722/// In C++1z onwards, the type specifier can also be a template-name.
John McCalldadc5752010-08-24 06:29:42 +00001723ExprResult
Sebastian Redld65cea82008-12-11 22:51:44 +00001724Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Faisal Vali421b2d12017-12-29 05:41:00 +00001725 Declarator DeclaratorInfo(DS, DeclaratorContext::FunctionalCastContext);
John McCallba7bf592010-08-24 05:47:05 +00001726 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001727
Sebastian Redl3da34892011-06-05 12:23:16 +00001728 assert((Tok.is(tok::l_paren) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001729 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redl3da34892011-06-05 12:23:16 +00001730 && "Expected '(' or '{'!");
Douglas Gregor94a32472011-01-11 00:33:19 +00001731
Sebastian Redl3da34892011-06-05 12:23:16 +00001732 if (Tok.is(tok::l_brace)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001733 ExprResult Init = ParseBraceInitializer();
1734 if (Init.isInvalid())
1735 return Init;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001736 Expr *InitList = Init.get();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001737 return Actions.ActOnCXXTypeConstructExpr(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001738 TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001739 InitList->getEndLoc(), /*ListInitialization=*/true);
Sebastian Redl3da34892011-06-05 12:23:16 +00001740 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001741 BalancedDelimiterTracker T(*this, tok::l_paren);
1742 T.consumeOpen();
Sebastian Redl3da34892011-06-05 12:23:16 +00001743
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00001744 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1745
Benjamin Kramerf0623432012-08-23 22:51:59 +00001746 ExprVector Exprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00001747 CommaLocsTy CommaLocs;
1748
Ilya Biryukovff2a9972019-02-26 11:01:50 +00001749 auto RunSignatureHelp = [&]() {
1750 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
1751 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
1752 DS.getEndLoc(), Exprs, T.getOpenLocation());
1753 CalledSignatureHelp = true;
1754 return PreferredType;
1755 };
1756
Sebastian Redl3da34892011-06-05 12:23:16 +00001757 if (Tok.isNot(tok::r_paren)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00001758 if (ParseExpressionList(Exprs, CommaLocs, [&] {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00001759 PreferredType.enterFunctionArgument(Tok.getLocation(),
1760 RunSignatureHelp);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001761 })) {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00001762 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1763 RunSignatureHelp();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001764 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00001765 return ExprError();
1766 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001767 }
Sebastian Redl3da34892011-06-05 12:23:16 +00001768
1769 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001770 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00001771
1772 // TypeRep could be null, if it references an invalid typedef.
1773 if (!TypeRep)
1774 return ExprError();
1775
1776 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1777 "Unexpected number of commas!");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001778 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1779 Exprs, T.getCloseLocation(),
1780 /*ListInitialization=*/false);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001781 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001782}
1783
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001784/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001785///
1786/// condition:
1787/// expression
1788/// type-specifier-seq declarator '=' assignment-expression
Richard Smith2a15b742012-02-22 06:49:09 +00001789/// [C++11] type-specifier-seq declarator '=' initializer-clause
1790/// [C++11] type-specifier-seq declarator braced-init-list
Zhihao Yuanc81f4532017-12-07 07:03:15 +00001791/// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1792/// brace-or-equal-initializer
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001793/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1794/// '=' assignment-expression
1795///
Richard Smithc7a05a92016-06-29 21:17:59 +00001796/// In C++1z, a condition may in some contexts be preceded by an
1797/// optional init-statement. This function will parse that too.
1798///
1799/// \param InitStmt If non-null, an init-statement is permitted, and if present
1800/// will be parsed and stored here.
1801///
Douglas Gregore60e41a2010-05-06 17:25:47 +00001802/// \param Loc The location of the start of the statement that requires this
1803/// condition, e.g., the "for" in a for loop.
1804///
Richard Smith8baa5002018-09-28 18:44:09 +00001805/// \param FRI If non-null, a for range declaration is permitted, and if
1806/// present will be parsed and stored here, and a null result will be returned.
1807///
Richard Smith03a4aa32016-06-23 19:02:52 +00001808/// \returns The parsed condition.
Richard Smithc7a05a92016-06-29 21:17:59 +00001809Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1810 SourceLocation Loc,
Richard Smith8baa5002018-09-28 18:44:09 +00001811 Sema::ConditionKind CK,
1812 ForRangeInfo *FRI) {
Richard Smithbf5bcf22018-06-26 23:20:26 +00001813 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00001814 PreferredType.enterCondition(Actions, Tok.getLocation());
Richard Smithbf5bcf22018-06-26 23:20:26 +00001815
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001816 if (Tok.is(tok::code_completion)) {
John McCallfaf5fb42010-08-26 23:41:50 +00001817 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001818 cutOffParsing();
Richard Smith03a4aa32016-06-23 19:02:52 +00001819 return Sema::ConditionError();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001820 }
1821
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001822 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001823 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001824
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001825 const auto WarnOnInit = [this, &CK] {
1826 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
1827 ? diag::warn_cxx14_compat_init_statement
1828 : diag::ext_init_statement)
1829 << (CK == Sema::ConditionKind::Switch);
1830 };
1831
Richard Smithc7a05a92016-06-29 21:17:59 +00001832 // Determine what kind of thing we have.
Richard Smith8baa5002018-09-28 18:44:09 +00001833 switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
Richard Smithc7a05a92016-06-29 21:17:59 +00001834 case ConditionOrInitStatement::Expression: {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001835 ProhibitAttributes(attrs);
1836
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001837 // We can have an empty expression here.
1838 // if (; true);
1839 if (InitStmt && Tok.is(tok::semi)) {
1840 WarnOnInit();
Roman Lebedev377748f2018-11-20 18:59:05 +00001841 SourceLocation SemiLoc = Tok.getLocation();
1842 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
1843 Diag(SemiLoc, diag::warn_empty_init_statement)
1844 << (CK == Sema::ConditionKind::Switch)
1845 << FixItHint::CreateRemoval(SemiLoc);
1846 }
1847 ConsumeToken();
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001848 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
1849 return ParseCXXCondition(nullptr, Loc, CK);
1850 }
1851
Douglas Gregore60e41a2010-05-06 17:25:47 +00001852 // Parse the expression.
Richard Smith03a4aa32016-06-23 19:02:52 +00001853 ExprResult Expr = ParseExpression(); // expression
1854 if (Expr.isInvalid())
1855 return Sema::ConditionError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00001856
Richard Smithc7a05a92016-06-29 21:17:59 +00001857 if (InitStmt && Tok.is(tok::semi)) {
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001858 WarnOnInit();
Richard Smithc7a05a92016-06-29 21:17:59 +00001859 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1860 ConsumeToken();
1861 return ParseCXXCondition(nullptr, Loc, CK);
1862 }
1863
Richard Smith03a4aa32016-06-23 19:02:52 +00001864 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001865 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001866
Richard Smithc7a05a92016-06-29 21:17:59 +00001867 case ConditionOrInitStatement::InitStmtDecl: {
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001868 WarnOnInit();
Richard Smithc7a05a92016-06-29 21:17:59 +00001869 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Faisal Vali421b2d12017-12-29 05:41:00 +00001870 DeclGroupPtrTy DG =
1871 ParseSimpleDeclaration(DeclaratorContext::InitStmtContext, DeclEnd,
1872 attrs, /*RequireSemi=*/true);
Richard Smithc7a05a92016-06-29 21:17:59 +00001873 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1874 return ParseCXXCondition(nullptr, Loc, CK);
1875 }
1876
Richard Smith8baa5002018-09-28 18:44:09 +00001877 case ConditionOrInitStatement::ForRangeDecl: {
1878 assert(FRI && "should not parse a for range declaration here");
1879 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1880 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1881 DeclaratorContext::ForContext, DeclEnd, attrs, false, FRI);
1882 FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1883 return Sema::ConditionResult();
1884 }
1885
Richard Smithc7a05a92016-06-29 21:17:59 +00001886 case ConditionOrInitStatement::ConditionDecl:
1887 case ConditionOrInitStatement::Error:
1888 break;
1889 }
1890
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001891 // type-specifier-seq
John McCall084e83d2011-03-24 11:26:52 +00001892 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +00001893 DS.takeAttributesFrom(attrs);
Faisal Vali7db85c52017-12-31 00:06:40 +00001894 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001895
1896 // declarator
Faisal Vali421b2d12017-12-29 05:41:00 +00001897 Declarator DeclaratorInfo(DS, DeclaratorContext::ConditionContext);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001898 ParseDeclarator(DeclaratorInfo);
1899
1900 // simple-asm-expr[opt]
1901 if (Tok.is(tok::kw_asm)) {
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001902 SourceLocation Loc;
John McCalldadc5752010-08-24 06:29:42 +00001903 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001904 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001905 SkipUntil(tok::semi, StopAtSemi);
Richard Smith03a4aa32016-06-23 19:02:52 +00001906 return Sema::ConditionError();
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001907 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001908 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001909 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001910 }
1911
1912 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001913 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001914
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001915 // Type-check the declaration itself.
Fangrui Song6907ce22018-07-30 19:24:48 +00001916 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall53fa7142010-12-24 02:08:15 +00001917 DeclaratorInfo);
Richard Smith03a4aa32016-06-23 19:02:52 +00001918 if (Dcl.isInvalid())
1919 return Sema::ConditionError();
1920 Decl *DeclOut = Dcl.get();
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001921
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001922 // '=' assignment-expression
Richard Trieuc64d3232012-01-18 22:54:52 +00001923 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith2a15b742012-02-22 06:49:09 +00001924 bool CopyInitialization = isTokenEqualOrEqualTypo();
1925 if (CopyInitialization)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001926 ConsumeToken();
Richard Smith2a15b742012-02-22 06:49:09 +00001927
1928 ExprResult InitExpr = ExprError();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001929 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith2a15b742012-02-22 06:49:09 +00001930 Diag(Tok.getLocation(),
1931 diag::warn_cxx98_compat_generalized_initializer_lists);
1932 InitExpr = ParseBraceInitializer();
1933 } else if (CopyInitialization) {
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00001934 PreferredType.enterVariableInit(Tok.getLocation(), DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001935 InitExpr = ParseAssignmentExpression();
1936 } else if (Tok.is(tok::l_paren)) {
1937 // This was probably an attempt to initialize the variable.
1938 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001939 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith2a15b742012-02-22 06:49:09 +00001940 RParen = ConsumeParen();
Richard Smith03a4aa32016-06-23 19:02:52 +00001941 Diag(DeclOut->getLocation(),
Richard Smith2a15b742012-02-22 06:49:09 +00001942 diag::err_expected_init_in_condition_lparen)
1943 << SourceRange(LParen, RParen);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001944 } else {
Richard Smith03a4aa32016-06-23 19:02:52 +00001945 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001946 }
Richard Smith2a15b742012-02-22 06:49:09 +00001947
1948 if (!InitExpr.isInvalid())
Richard Smith3beb7c62017-01-12 02:27:38 +00001949 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
Richard Smith27d807c2013-04-30 13:56:41 +00001950 else
1951 Actions.ActOnInitializerError(DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001952
Richard Smithb2bc2e62011-02-21 20:05:19 +00001953 Actions.FinalizeDeclaration(DeclOut);
Richard Smith03a4aa32016-06-23 19:02:52 +00001954 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001955}
1956
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001957/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1958/// This should only be called when the current token is known to be part of
1959/// simple-type-specifier.
1960///
1961/// simple-type-specifier:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001962/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001963/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1964/// char
1965/// wchar_t
1966/// bool
1967/// short
1968/// int
1969/// long
1970/// signed
1971/// unsigned
1972/// float
1973/// double
1974/// void
1975/// [GNU] typeof-specifier
1976/// [C++0x] auto [TODO]
1977///
1978/// type-name:
1979/// class-name
1980/// enum-name
1981/// typedef-name
1982///
1983void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1984 DS.SetRangeStart(Tok.getLocation());
1985 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +00001986 unsigned DiagID;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001987 SourceLocation Loc = Tok.getLocation();
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001988 const clang::PrintingPolicy &Policy =
1989 Actions.getASTContext().getPrintingPolicy();
Mike Stump11289f42009-09-09 15:08:12 +00001990
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001991 switch (Tok.getKind()) {
Chris Lattner45ddec32009-01-05 00:13:00 +00001992 case tok::identifier: // foo::bar
1993 case tok::coloncolon: // ::foo::bar
David Blaikie83d382b2011-09-23 05:06:16 +00001994 llvm_unreachable("Annotation token should already be formed!");
Mike Stump11289f42009-09-09 15:08:12 +00001995 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001996 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner45ddec32009-01-05 00:13:00 +00001997
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001998 // type-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00001999 case tok::annot_typename: {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002000 if (getTypeAnnotation(Tok))
2001 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002002 getTypeAnnotation(Tok), Policy);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002003 else
2004 DS.SetTypeSpecError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002005
Douglas Gregor06e41ae2010-10-21 23:17:00 +00002006 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00002007 ConsumeAnnotationToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00002008
Craig Topper25122412015-11-15 03:32:11 +00002009 DS.Finish(Actions, Policy);
Douglas Gregor06e41ae2010-10-21 23:17:00 +00002010 return;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002011 }
Mike Stump11289f42009-09-09 15:08:12 +00002012
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002013 // builtin types
2014 case tok::kw_short:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002015 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002016 break;
2017 case tok::kw_long:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002018 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002019 break;
Francois Pichet84133e42011-04-28 01:59:37 +00002020 case tok::kw___int64:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002021 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00002022 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002023 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00002024 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002025 break;
2026 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00002027 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002028 break;
2029 case tok::kw_void:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002030 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002031 break;
2032 case tok::kw_char:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002033 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002034 break;
2035 case tok::kw_int:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002036 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002037 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00002038 case tok::kw___int128:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002039 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00002040 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002041 case tok::kw_half:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002042 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002043 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002044 case tok::kw_float:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002045 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002046 break;
2047 case tok::kw_double:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002048 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002049 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002050 case tok::kw__Float16:
2051 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
2052 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002053 case tok::kw___float128:
2054 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
2055 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002056 case tok::kw_wchar_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002057 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002058 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00002059 case tok::kw_char8_t:
2060 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
2061 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002062 case tok::kw_char16_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002063 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002064 break;
2065 case tok::kw_char32_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002066 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002067 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002068 case tok::kw_bool:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002069 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002070 break;
Anastasia Stulova2c4730d2019-02-15 12:07:57 +00002071#define GENERIC_IMAGE_TYPE(ImgType, Id) \
2072 case tok::kw_##ImgType##_t: \
2073 DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \
2074 Policy); \
2075 break;
2076#include "clang/Basic/OpenCLImageTypes.def"
2077
David Blaikie25896afb2012-01-24 05:47:35 +00002078 case tok::annot_decltype:
2079 case tok::kw_decltype:
2080 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
Craig Topper25122412015-11-15 03:32:11 +00002081 return DS.Finish(Actions, Policy);
Mike Stump11289f42009-09-09 15:08:12 +00002082
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002083 // GNU typeof support.
2084 case tok::kw_typeof:
2085 ParseTypeofSpecifier(DS);
Craig Topper25122412015-11-15 03:32:11 +00002086 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002087 return;
2088 }
Richard Smithaf3b3252017-05-18 19:21:48 +00002089 ConsumeAnyToken();
2090 DS.SetRangeEnd(PrevTokLocation);
Craig Topper25122412015-11-15 03:32:11 +00002091 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002092}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002093
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002094/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2095/// [dcl.name]), which is a non-empty sequence of type-specifiers,
2096/// e.g., "const short int". Note that the DeclSpec is *not* finished
2097/// by parsing the type-specifier-seq, because these sequences are
2098/// typically followed by some form of declarator. Returns true and
2099/// emits diagnostics if this is not a type-specifier-seq, false
2100/// otherwise.
2101///
2102/// type-specifier-seq: [C++ 8.1]
2103/// type-specifier type-specifier-seq[opt]
2104///
2105bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Faisal Vali7db85c52017-12-31 00:06:40 +00002106 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
Craig Topper25122412015-11-15 03:32:11 +00002107 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002108 return false;
2109}
2110
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002111/// Finish parsing a C++ unqualified-id that is a template-id of
Fangrui Song6907ce22018-07-30 19:24:48 +00002112/// some form.
Douglas Gregor7861a802009-11-03 01:35:08 +00002113///
2114/// This routine is invoked when a '<' is encountered after an identifier or
2115/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2116/// whether the unqualified-id is actually a template-id. This routine will
2117/// then parse the template arguments and form the appropriate template-id to
2118/// return to the caller.
2119///
2120/// \param SS the nested-name-specifier that precedes this template-id, if
2121/// we're actually parsing a qualified-id.
2122///
2123/// \param Name for constructor and destructor names, this is the actual
2124/// identifier that may be a template-name.
2125///
Fangrui Song6907ce22018-07-30 19:24:48 +00002126/// \param NameLoc the location of the class-name in a constructor or
Douglas Gregor7861a802009-11-03 01:35:08 +00002127/// destructor.
2128///
Fangrui Song6907ce22018-07-30 19:24:48 +00002129/// \param EnteringContext whether we're entering the scope of the
Douglas Gregor7861a802009-11-03 01:35:08 +00002130/// nested-name-specifier.
2131///
Douglas Gregor127ea592009-11-03 21:24:04 +00002132/// \param ObjectType if this unqualified-id occurs within a member access
2133/// expression, the type of the base object whose member is being accessed.
2134///
Douglas Gregor7861a802009-11-03 01:35:08 +00002135/// \param Id as input, describes the template-name or operator-function-id
2136/// that precedes the '<'. If template arguments were parsed successfully,
2137/// will be updated with the template-id.
Fangrui Song6907ce22018-07-30 19:24:48 +00002138///
Douglas Gregore610ada2010-02-24 18:44:31 +00002139/// \param AssumeTemplateId When true, this routine will assume that the name
Fangrui Song6907ce22018-07-30 19:24:48 +00002140/// refers to a template without performing name lookup to verify.
Douglas Gregore610ada2010-02-24 18:44:31 +00002141///
Douglas Gregor7861a802009-11-03 01:35:08 +00002142/// \returns true if a parse error occurred, false otherwise.
2143bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002144 SourceLocation TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002145 IdentifierInfo *Name,
2146 SourceLocation NameLoc,
2147 bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002148 ParsedType ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00002149 UnqualifiedId &Id,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002150 bool AssumeTemplateId) {
Richard Smithc08b6932018-04-27 02:00:13 +00002151 assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
2152
Douglas Gregor7861a802009-11-03 01:35:08 +00002153 TemplateTy Template;
2154 TemplateNameKind TNK = TNK_Non_template;
2155 switch (Id.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00002156 case UnqualifiedIdKind::IK_Identifier:
2157 case UnqualifiedIdKind::IK_OperatorFunctionId:
2158 case UnqualifiedIdKind::IK_LiteralOperatorId:
Douglas Gregore610ada2010-02-24 18:44:31 +00002159 if (AssumeTemplateId) {
Richard Smithfd3dae02017-01-20 00:20:39 +00002160 // We defer the injected-class-name checks until we've found whether
2161 // this template-id is used to form a nested-name-specifier or not.
2162 TNK = Actions.ActOnDependentTemplateName(
2163 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2164 Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002165 if (TNK == TNK_Non_template)
2166 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00002167 } else {
2168 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002169 TNK = Actions.isTemplateName(getCurScope(), SS,
2170 TemplateKWLoc.isValid(), Id,
2171 ObjectType, EnteringContext, Template,
Douglas Gregor786123d2010-05-21 23:18:07 +00002172 MemberOfUnknownSpecialization);
Richard Smithb23c5e82019-05-09 03:31:27 +00002173 // If lookup found nothing but we're assuming that this is a template
2174 // name, double-check that makes sense syntactically before committing
2175 // to it.
2176 if (TNK == TNK_Undeclared_template &&
2177 isTemplateArgumentList(0) == TPResult::False)
2178 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00002179
Douglas Gregor786123d2010-05-21 23:18:07 +00002180 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
Richard Smithb23c5e82019-05-09 03:31:27 +00002181 ObjectType && isTemplateArgumentList(0) == TPResult::True) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002182 // We have something like t->getAs<T>(), where getAs is a
Douglas Gregor786123d2010-05-21 23:18:07 +00002183 // member of an unknown specialization. However, this will only
2184 // parse correctly as a template, so suggest the keyword 'template'
2185 // before 'getAs' and treat this as a dependent template name.
2186 std::string Name;
Faisal Vali2ab8c152017-12-30 04:15:27 +00002187 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
Douglas Gregor786123d2010-05-21 23:18:07 +00002188 Name = Id.Identifier->getName();
2189 else {
2190 Name = "operator ";
Faisal Vali2ab8c152017-12-30 04:15:27 +00002191 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
Douglas Gregor786123d2010-05-21 23:18:07 +00002192 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2193 else
2194 Name += Id.Identifier->getName();
2195 }
2196 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2197 << Name
2198 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Richard Smithfd3dae02017-01-20 00:20:39 +00002199 TNK = Actions.ActOnDependentTemplateName(
2200 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2201 Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002202 if (TNK == TNK_Non_template)
Fangrui Song6907ce22018-07-30 19:24:48 +00002203 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00002204 }
2205 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002206 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002207
Faisal Vali2ab8c152017-12-30 04:15:27 +00002208 case UnqualifiedIdKind::IK_ConstructorName: {
Douglas Gregor3cf81312009-11-03 23:16:33 +00002209 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002210 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002211 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002212 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002213 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002214 EnteringContext, Template,
2215 MemberOfUnknownSpecialization);
Douglas Gregor7861a802009-11-03 01:35:08 +00002216 break;
2217 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002218
Faisal Vali2ab8c152017-12-30 04:15:27 +00002219 case UnqualifiedIdKind::IK_DestructorName: {
Douglas Gregor3cf81312009-11-03 23:16:33 +00002220 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002221 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002222 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002223 if (ObjectType) {
Richard Smithfd3dae02017-01-20 00:20:39 +00002224 TNK = Actions.ActOnDependentTemplateName(
2225 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2226 EnteringContext, Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002227 if (TNK == TNK_Non_template)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002228 return true;
2229 } else {
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002230 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002231 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002232 EnteringContext, Template,
2233 MemberOfUnknownSpecialization);
Fangrui Song6907ce22018-07-30 19:24:48 +00002234
John McCallba7bf592010-08-24 05:47:05 +00002235 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002236 Diag(NameLoc, diag::err_destructor_template_id)
2237 << Name << SS.getRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00002238 return true;
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002239 }
2240 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002241 break;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002242 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002243
Douglas Gregor7861a802009-11-03 01:35:08 +00002244 default:
2245 return false;
2246 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002247
Douglas Gregor7861a802009-11-03 01:35:08 +00002248 if (TNK == TNK_Non_template)
2249 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00002250
Douglas Gregor7861a802009-11-03 01:35:08 +00002251 // Parse the enclosed template argument list.
2252 SourceLocation LAngleLoc, RAngleLoc;
2253 TemplateArgList TemplateArgs;
Richard Smithc08b6932018-04-27 02:00:13 +00002254 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
2255 RAngleLoc))
Douglas Gregor7861a802009-11-03 01:35:08 +00002256 return true;
Richard Smithc08b6932018-04-27 02:00:13 +00002257
Faisal Vali2ab8c152017-12-30 04:15:27 +00002258 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2259 Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2260 Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002261 // Form a parsed representation of the template-id to be stored in the
2262 // UnqualifiedId.
Douglas Gregor7861a802009-11-03 01:35:08 +00002263
Richard Smith72bfbd82013-12-04 00:28:23 +00002264 // FIXME: Store name for literal operator too.
Faisal Vali43caf672017-05-23 01:07:12 +00002265 IdentifierInfo *TemplateII =
Faisal Vali2ab8c152017-12-30 04:15:27 +00002266 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2267 : nullptr;
2268 OverloadedOperatorKind OpKind =
2269 Id.getKind() == UnqualifiedIdKind::IK_Identifier
2270 ? OO_None
2271 : Id.OperatorFunctionId.Operator;
Douglas Gregor7861a802009-11-03 01:35:08 +00002272
Faisal Vali43caf672017-05-23 01:07:12 +00002273 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2274 SS, TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2275 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
2276
Douglas Gregor7861a802009-11-03 01:35:08 +00002277 Id.setTemplateId(TemplateId);
2278 return false;
2279 }
2280
2281 // Bundle the template arguments together.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002282 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnara4244b432012-01-27 08:46:19 +00002283
Douglas Gregor7861a802009-11-03 01:35:08 +00002284 // Constructor and destructor names.
Richard Smithb23c5e82019-05-09 03:31:27 +00002285 TypeResult Type = Actions.ActOnTemplateIdType(
2286 getCurScope(), SS, TemplateKWLoc, Template, Name, NameLoc, LAngleLoc,
2287 TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true);
Douglas Gregor7861a802009-11-03 01:35:08 +00002288 if (Type.isInvalid())
2289 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002290
Faisal Vali2ab8c152017-12-30 04:15:27 +00002291 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
Douglas Gregor7861a802009-11-03 01:35:08 +00002292 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2293 else
2294 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00002295
Douglas Gregor7861a802009-11-03 01:35:08 +00002296 return false;
2297}
2298
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002299/// Parse an operator-function-id or conversion-function-id as part
Douglas Gregor71395fa2009-11-04 00:56:37 +00002300/// of a C++ unqualified-id.
2301///
2302/// This routine is responsible only for parsing the operator-function-id or
2303/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor7861a802009-11-03 01:35:08 +00002304///
2305/// \code
Douglas Gregor7861a802009-11-03 01:35:08 +00002306/// operator-function-id: [C++ 13.5]
2307/// 'operator' operator
2308///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002309/// operator: one of
Douglas Gregor7861a802009-11-03 01:35:08 +00002310/// new delete new[] delete[]
2311/// + - * / % ^ & | ~
2312/// ! = < > += -= *= /= %=
2313/// ^= &= |= << >> >>= <<= == !=
2314/// <= >= && || ++ -- , ->* ->
Richard Smithd30b23d2017-12-01 02:13:10 +00002315/// () [] <=>
Douglas Gregor7861a802009-11-03 01:35:08 +00002316///
2317/// conversion-function-id: [C++ 12.3.2]
2318/// operator conversion-type-id
2319///
2320/// conversion-type-id:
2321/// type-specifier-seq conversion-declarator[opt]
2322///
2323/// conversion-declarator:
2324/// ptr-operator conversion-declarator[opt]
2325/// \endcode
2326///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002327/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor7861a802009-11-03 01:35:08 +00002328/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2329///
Fangrui Song6907ce22018-07-30 19:24:48 +00002330/// \param EnteringContext whether we are entering the scope of the
Douglas Gregor7861a802009-11-03 01:35:08 +00002331/// nested-name-specifier.
2332///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002333/// \param ObjectType if this unqualified-id occurs within a member access
2334/// expression, the type of the base object whose member is being accessed.
2335///
2336/// \param Result on a successful parse, contains the parsed unqualified-id.
2337///
2338/// \returns true if parsing fails, false otherwise.
2339bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002340 ParsedType ObjectType,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002341 UnqualifiedId &Result) {
2342 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
Fangrui Song6907ce22018-07-30 19:24:48 +00002343
Douglas Gregor71395fa2009-11-04 00:56:37 +00002344 // Consume the 'operator' keyword.
2345 SourceLocation KeywordLoc = ConsumeToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00002346
Douglas Gregor71395fa2009-11-04 00:56:37 +00002347 // Determine what kind of operator name we have.
2348 unsigned SymbolIdx = 0;
2349 SourceLocation SymbolLocations[3];
2350 OverloadedOperatorKind Op = OO_None;
2351 switch (Tok.getKind()) {
2352 case tok::kw_new:
2353 case tok::kw_delete: {
2354 bool isNew = Tok.getKind() == tok::kw_new;
2355 // Consume the 'new' or 'delete'.
2356 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002357 // Check for array new/delete.
2358 if (Tok.is(tok::l_square) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002359 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002360 // Consume the '[' and ']'.
2361 BalancedDelimiterTracker T(*this, tok::l_square);
2362 T.consumeOpen();
2363 T.consumeClose();
2364 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002365 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002366
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002367 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2368 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002369 Op = isNew? OO_Array_New : OO_Array_Delete;
2370 } else {
2371 Op = isNew? OO_New : OO_Delete;
2372 }
2373 break;
2374 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002375
Douglas Gregor71395fa2009-11-04 00:56:37 +00002376#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2377 case tok::Token: \
2378 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2379 Op = OO_##Name; \
2380 break;
2381#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2382#include "clang/Basic/OperatorKinds.def"
Fangrui Song6907ce22018-07-30 19:24:48 +00002383
Douglas Gregor71395fa2009-11-04 00:56:37 +00002384 case tok::l_paren: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002385 // Consume the '(' and ')'.
2386 BalancedDelimiterTracker T(*this, tok::l_paren);
2387 T.consumeOpen();
2388 T.consumeClose();
2389 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002390 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002391
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002392 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2393 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002394 Op = OO_Call;
2395 break;
2396 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002397
Douglas Gregor71395fa2009-11-04 00:56:37 +00002398 case tok::l_square: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002399 // Consume the '[' and ']'.
2400 BalancedDelimiterTracker T(*this, tok::l_square);
2401 T.consumeOpen();
2402 T.consumeClose();
2403 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002404 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002405
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002406 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2407 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002408 Op = OO_Subscript;
2409 break;
2410 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002411
Douglas Gregor71395fa2009-11-04 00:56:37 +00002412 case tok::code_completion: {
2413 // Code completion for the operator name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002414 Actions.CodeCompleteOperatorName(getCurScope());
Fangrui Song6907ce22018-07-30 19:24:48 +00002415 cutOffParsing();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002416 // Don't try to parse any further.
2417 return true;
2418 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002419
Douglas Gregor71395fa2009-11-04 00:56:37 +00002420 default:
2421 break;
2422 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002423
Douglas Gregor71395fa2009-11-04 00:56:37 +00002424 if (Op != OO_None) {
2425 // We have parsed an operator-function-id.
2426 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2427 return false;
2428 }
Alexis Hunt34458502009-11-28 04:44:28 +00002429
2430 // Parse a literal-operator-id.
2431 //
Richard Smith6f212062012-10-20 08:41:10 +00002432 // literal-operator-id: C++11 [over.literal]
2433 // operator string-literal identifier
2434 // operator user-defined-string-literal
Alexis Hunt34458502009-11-28 04:44:28 +00002435
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002436 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002437 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Alexis Hunt34458502009-11-28 04:44:28 +00002438
Richard Smith7d182a72012-03-08 23:06:02 +00002439 SourceLocation DiagLoc;
2440 unsigned DiagId = 0;
2441
2442 // We're past translation phase 6, so perform string literal concatenation
2443 // before checking for "".
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002444 SmallVector<Token, 4> Toks;
2445 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith7d182a72012-03-08 23:06:02 +00002446 while (isTokenStringLiteral()) {
2447 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smith6f212062012-10-20 08:41:10 +00002448 // C++11 [over.literal]p1:
2449 // The string-literal or user-defined-string-literal in a
2450 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith7d182a72012-03-08 23:06:02 +00002451 DiagLoc = Tok.getLocation();
2452 DiagId = diag::err_literal_operator_string_prefix;
2453 }
2454 Toks.push_back(Tok);
2455 TokLocs.push_back(ConsumeStringToken());
2456 }
2457
Craig Topper9d5583e2014-06-26 04:58:39 +00002458 StringLiteralParser Literal(Toks, PP);
Richard Smith7d182a72012-03-08 23:06:02 +00002459 if (Literal.hadError)
2460 return true;
2461
2462 // Grab the literal operator's suffix, which will be either the next token
2463 // or a ud-suffix from the string literal.
Craig Topper161e4db2014-05-21 06:02:52 +00002464 IdentifierInfo *II = nullptr;
Richard Smith7d182a72012-03-08 23:06:02 +00002465 SourceLocation SuffixLoc;
2466 if (!Literal.getUDSuffix().empty()) {
2467 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2468 SuffixLoc =
2469 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2470 Literal.getUDSuffixOffset(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002471 PP.getSourceManager(), getLangOpts());
Richard Smith7d182a72012-03-08 23:06:02 +00002472 } else if (Tok.is(tok::identifier)) {
2473 II = Tok.getIdentifierInfo();
2474 SuffixLoc = ConsumeToken();
2475 TokLocs.push_back(SuffixLoc);
2476 } else {
Alp Tokerec543272013-12-24 09:48:30 +00002477 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexis Hunt34458502009-11-28 04:44:28 +00002478 return true;
2479 }
2480
Richard Smith7d182a72012-03-08 23:06:02 +00002481 // The string literal must be empty.
2482 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smith6f212062012-10-20 08:41:10 +00002483 // C++11 [over.literal]p1:
2484 // The string-literal or user-defined-string-literal in a
2485 // literal-operator-id shall [...] contain no characters
2486 // other than the implicit terminating '\0'.
Richard Smith7d182a72012-03-08 23:06:02 +00002487 DiagLoc = TokLocs.front();
2488 DiagId = diag::err_literal_operator_string_not_empty;
2489 }
2490
2491 if (DiagId) {
2492 // This isn't a valid literal-operator-id, but we think we know
2493 // what the user meant. Tell them what they should have written.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002494 SmallString<32> Str;
Richard Smithe87aeb32015-10-08 00:17:59 +00002495 Str += "\"\"";
Richard Smith7d182a72012-03-08 23:06:02 +00002496 Str += II->getName();
2497 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2498 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2499 }
2500
2501 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Richard Smithd091dc12013-12-05 00:58:33 +00002502
2503 return Actions.checkLiteralOperatorId(SS, Result);
Alexis Hunt34458502009-11-28 04:44:28 +00002504 }
Richard Smithd091dc12013-12-05 00:58:33 +00002505
Douglas Gregor71395fa2009-11-04 00:56:37 +00002506 // Parse a conversion-function-id.
2507 //
2508 // conversion-function-id: [C++ 12.3.2]
2509 // operator conversion-type-id
2510 //
2511 // conversion-type-id:
2512 // type-specifier-seq conversion-declarator[opt]
2513 //
2514 // conversion-declarator:
2515 // ptr-operator conversion-declarator[opt]
Fangrui Song6907ce22018-07-30 19:24:48 +00002516
Douglas Gregor71395fa2009-11-04 00:56:37 +00002517 // Parse the type-specifier-seq.
John McCall084e83d2011-03-24 11:26:52 +00002518 DeclSpec DS(AttrFactory);
Douglas Gregora25d65d2009-11-20 22:03:38 +00002519 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregor71395fa2009-11-04 00:56:37 +00002520 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002521
Douglas Gregor71395fa2009-11-04 00:56:37 +00002522 // Parse the conversion-declarator, which is merely a sequence of
2523 // ptr-operators.
Faisal Vali421b2d12017-12-29 05:41:00 +00002524 Declarator D(DS, DeclaratorContext::ConversionIdContext);
Craig Topper161e4db2014-05-21 06:02:52 +00002525 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2526
Douglas Gregor71395fa2009-11-04 00:56:37 +00002527 // Finish up the type.
John McCallfaf5fb42010-08-26 23:41:50 +00002528 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002529 if (Ty.isInvalid())
2530 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002531
Douglas Gregor71395fa2009-11-04 00:56:37 +00002532 // Note that this is a conversion-function-id.
Fangrui Song6907ce22018-07-30 19:24:48 +00002533 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
Douglas Gregor71395fa2009-11-04 00:56:37 +00002534 D.getSourceRange().getEnd());
Fangrui Song6907ce22018-07-30 19:24:48 +00002535 return false;
Douglas Gregor71395fa2009-11-04 00:56:37 +00002536}
2537
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002538/// Parse a C++ unqualified-id (or a C identifier), which describes the
Douglas Gregor71395fa2009-11-04 00:56:37 +00002539/// name of an entity.
2540///
2541/// \code
2542/// unqualified-id: [C++ expr.prim.general]
2543/// identifier
2544/// operator-function-id
2545/// conversion-function-id
2546/// [C++0x] literal-operator-id [TODO]
2547/// ~ class-name
2548/// template-id
2549///
2550/// \endcode
2551///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002552/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor71395fa2009-11-04 00:56:37 +00002553/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2554///
Fangrui Song6907ce22018-07-30 19:24:48 +00002555/// \param EnteringContext whether we are entering the scope of the
Douglas Gregor71395fa2009-11-04 00:56:37 +00002556/// nested-name-specifier.
2557///
Douglas Gregor7861a802009-11-03 01:35:08 +00002558/// \param AllowDestructorName whether we allow parsing of a destructor name.
2559///
2560/// \param AllowConstructorName whether we allow parsing a constructor name.
2561///
Richard Smith35845152017-02-07 01:37:30 +00002562/// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2563///
Douglas Gregor127ea592009-11-03 21:24:04 +00002564/// \param ObjectType if this unqualified-id occurs within a member access
2565/// expression, the type of the base object whose member is being accessed.
2566///
Douglas Gregor7861a802009-11-03 01:35:08 +00002567/// \param Result on a successful parse, contains the parsed unqualified-id.
2568///
2569/// \returns true if parsing fails, false otherwise.
2570bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2571 bool AllowDestructorName,
2572 bool AllowConstructorName,
Richard Smith35845152017-02-07 01:37:30 +00002573 bool AllowDeductionGuide,
John McCallba7bf592010-08-24 05:47:05 +00002574 ParsedType ObjectType,
Richard Smithc08b6932018-04-27 02:00:13 +00002575 SourceLocation *TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002576 UnqualifiedId &Result) {
Richard Smithc08b6932018-04-27 02:00:13 +00002577 if (TemplateKWLoc)
2578 *TemplateKWLoc = SourceLocation();
Douglas Gregorb22ee882010-05-05 05:58:24 +00002579
2580 // Handle 'A::template B'. This is for template-ids which have not
2581 // already been annotated by ParseOptionalCXXScopeSpecifier().
2582 bool TemplateSpecified = false;
Richard Smithc08b6932018-04-27 02:00:13 +00002583 if (Tok.is(tok::kw_template)) {
2584 if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2585 TemplateSpecified = true;
2586 *TemplateKWLoc = ConsumeToken();
2587 } else {
2588 SourceLocation TemplateLoc = ConsumeToken();
2589 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2590 << FixItHint::CreateRemoval(TemplateLoc);
2591 }
Douglas Gregorb22ee882010-05-05 05:58:24 +00002592 }
2593
Douglas Gregor7861a802009-11-03 01:35:08 +00002594 // unqualified-id:
2595 // identifier
2596 // template-id (when it hasn't already been annotated)
2597 if (Tok.is(tok::identifier)) {
2598 // Consume the identifier.
2599 IdentifierInfo *Id = Tok.getIdentifierInfo();
2600 SourceLocation IdLoc = ConsumeToken();
2601
David Blaikiebbafb8a2012-03-11 07:00:24 +00002602 if (!getLangOpts().CPlusPlus) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002603 // If we're not in C++, only identifiers matter. Record the
2604 // identifier and return.
2605 Result.setIdentifier(Id, IdLoc);
2606 return false;
2607 }
2608
Richard Smith35845152017-02-07 01:37:30 +00002609 ParsedTemplateTy TemplateName;
Fangrui Song6907ce22018-07-30 19:24:48 +00002610 if (AllowConstructorName &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002611 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002612 // We have parsed a constructor name.
Richard Smith69bc9aa2018-06-22 19:50:19 +00002613 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2614 EnteringContext);
Richard Smith715ee072018-06-20 21:58:20 +00002615 if (!Ty)
2616 return true;
Abramo Bagnara4244b432012-01-27 08:46:19 +00002617 Result.setConstructorName(Ty, IdLoc, IdLoc);
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002618 } else if (getLangOpts().CPlusPlus17 &&
Richard Smith35845152017-02-07 01:37:30 +00002619 AllowDeductionGuide && SS.isEmpty() &&
2620 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2621 &TemplateName)) {
2622 // We have parsed a template-name naming a deduction guide.
2623 Result.setDeductionGuideName(TemplateName, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002624 } else {
2625 // We have parsed an identifier.
Fangrui Song6907ce22018-07-30 19:24:48 +00002626 Result.setIdentifier(Id, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002627 }
2628
2629 // If the next token is a '<', we may have a template.
Richard Smithc08b6932018-04-27 02:00:13 +00002630 TemplateTy Template;
2631 if (Tok.is(tok::less))
2632 return ParseUnqualifiedIdTemplateId(
2633 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2634 EnteringContext, ObjectType, Result, TemplateSpecified);
2635 else if (TemplateSpecified &&
2636 Actions.ActOnDependentTemplateName(
2637 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2638 EnteringContext, Template,
2639 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2640 return true;
2641
Douglas Gregor7861a802009-11-03 01:35:08 +00002642 return false;
2643 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002644
Douglas Gregor7861a802009-11-03 01:35:08 +00002645 // unqualified-id:
2646 // template-id (already parsed and annotated)
2647 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00002648 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002649
Fangrui Song6907ce22018-07-30 19:24:48 +00002650 // If the template-name names the current class, then this is a constructor
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002651 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002652 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002653 if (SS.isSet()) {
2654 // C++ [class.qual]p2 specifies that a qualified template-name
2655 // is taken as the constructor name where a constructor can be
2656 // declared. Thus, the template arguments are extraneous, so
2657 // complain about them and remove them entirely.
Fangrui Song6907ce22018-07-30 19:24:48 +00002658 Diag(TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002659 diag::err_out_of_line_constructor_template_id)
2660 << TemplateId->Name
Douglas Gregora771f462010-03-31 17:46:05 +00002661 << FixItHint::CreateRemoval(
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002662 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Richard Smith715ee072018-06-20 21:58:20 +00002663 ParsedType Ty = Actions.getConstructorName(
Richard Smith69bc9aa2018-06-22 19:50:19 +00002664 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2665 EnteringContext);
Richard Smith715ee072018-06-20 21:58:20 +00002666 if (!Ty)
2667 return true;
Abramo Bagnara4244b432012-01-27 08:46:19 +00002668 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002669 TemplateId->RAngleLoc);
Richard Smithaf3b3252017-05-18 19:21:48 +00002670 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002671 return false;
2672 }
2673
2674 Result.setConstructorTemplateId(TemplateId);
Richard Smithaf3b3252017-05-18 19:21:48 +00002675 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002676 return false;
2677 }
2678
Douglas Gregor7861a802009-11-03 01:35:08 +00002679 // We have already parsed a template-id; consume the annotation token as
2680 // our unqualified-id.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002681 Result.setTemplateId(TemplateId);
Richard Smithc08b6932018-04-27 02:00:13 +00002682 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2683 if (TemplateLoc.isValid()) {
2684 if (TemplateKWLoc && (ObjectType || SS.isSet()))
2685 *TemplateKWLoc = TemplateLoc;
2686 else
2687 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2688 << FixItHint::CreateRemoval(TemplateLoc);
2689 }
Richard Smithaf3b3252017-05-18 19:21:48 +00002690 ConsumeAnnotationToken();
Douglas Gregor7861a802009-11-03 01:35:08 +00002691 return false;
2692 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002693
Douglas Gregor7861a802009-11-03 01:35:08 +00002694 // unqualified-id:
2695 // operator-function-id
2696 // conversion-function-id
2697 if (Tok.is(tok::kw_operator)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00002698 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor7861a802009-11-03 01:35:08 +00002699 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002700
Alexis Hunted0530f2009-11-28 08:58:14 +00002701 // If we have an operator-function-id or a literal-operator-id and the next
2702 // token is a '<', we may have a
Fangrui Song6907ce22018-07-30 19:24:48 +00002703 //
Douglas Gregor71395fa2009-11-04 00:56:37 +00002704 // template-id:
2705 // operator-function-id < template-argument-list[opt] >
Richard Smithc08b6932018-04-27 02:00:13 +00002706 TemplateTy Template;
Faisal Vali2ab8c152017-12-30 04:15:27 +00002707 if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2708 Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
Richard Smithc08b6932018-04-27 02:00:13 +00002709 Tok.is(tok::less))
2710 return ParseUnqualifiedIdTemplateId(
2711 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2712 SourceLocation(), EnteringContext, ObjectType, Result,
2713 TemplateSpecified);
2714 else if (TemplateSpecified &&
2715 Actions.ActOnDependentTemplateName(
2716 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2717 EnteringContext, Template,
2718 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2719 return true;
Craig Topper161e4db2014-05-21 06:02:52 +00002720
Douglas Gregor7861a802009-11-03 01:35:08 +00002721 return false;
2722 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002723
2724 if (getLangOpts().CPlusPlus &&
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002725 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002726 // C++ [expr.unary.op]p10:
Fangrui Song6907ce22018-07-30 19:24:48 +00002727 // There is an ambiguity in the unary-expression ~X(), where X is a
2728 // class-name. The ambiguity is resolved in favor of treating ~ as a
Douglas Gregor7861a802009-11-03 01:35:08 +00002729 // unary complement rather than treating ~X as referring to a destructor.
Fangrui Song6907ce22018-07-30 19:24:48 +00002730
Douglas Gregor7861a802009-11-03 01:35:08 +00002731 // Parse the '~'.
2732 SourceLocation TildeLoc = ConsumeToken();
David Blaikieecd8a942011-12-08 16:13:53 +00002733
2734 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2735 DeclSpec DS(AttrFactory);
2736 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Richard Smithef2cd8f2017-02-08 20:39:08 +00002737 if (ParsedType Type =
2738 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
David Blaikieecd8a942011-12-08 16:13:53 +00002739 Result.setDestructorName(TildeLoc, Type, EndLoc);
2740 return false;
2741 }
2742 return true;
2743 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002744
Douglas Gregor7861a802009-11-03 01:35:08 +00002745 // Parse the class-name.
2746 if (Tok.isNot(tok::identifier)) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002747 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00002748 return true;
2749 }
2750
Richard Smithefa6f732014-09-06 02:06:12 +00002751 // If the user wrote ~T::T, correct it to T::~T.
Richard Smith64e033f2015-01-15 00:48:52 +00002752 DeclaratorScopeObj DeclScopeObj(*this, SS);
Nico Weber10d02b52015-02-02 04:18:38 +00002753 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
Nico Weberf9e37be2015-01-30 16:53:11 +00002754 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2755 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2756 // it will confuse this recovery logic.
2757 ColonProtectionRAIIObject ColonRAII(*this, false);
2758
Richard Smithefa6f732014-09-06 02:06:12 +00002759 if (SS.isSet()) {
2760 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2761 SS.clear();
2762 }
2763 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2764 return true;
Nico Weber7f8ec522015-02-02 05:33:50 +00002765 if (SS.isNotEmpty())
David Blaikieefdccaa2016-01-15 23:43:34 +00002766 ObjectType = nullptr;
Nico Weberd0045862015-01-30 04:05:15 +00002767 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
Benjamin Kramer3012e592015-03-29 14:35:39 +00002768 !SS.isSet()) {
Richard Smithefa6f732014-09-06 02:06:12 +00002769 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2770 return true;
2771 }
2772
2773 // Recover as if the tilde had been written before the identifier.
2774 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2775 << FixItHint::CreateRemoval(TildeLoc)
2776 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
Richard Smith64e033f2015-01-15 00:48:52 +00002777
2778 // Temporarily enter the scope for the rest of this function.
2779 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2780 DeclScopeObj.EnterDeclaratorScope();
Richard Smithefa6f732014-09-06 02:06:12 +00002781 }
2782
Douglas Gregor7861a802009-11-03 01:35:08 +00002783 // Parse the class-name (or template-name in a simple-template-id).
2784 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2785 SourceLocation ClassNameLoc = ConsumeToken();
Richard Smithefa6f732014-09-06 02:06:12 +00002786
Richard Smithc08b6932018-04-27 02:00:13 +00002787 if (Tok.is(tok::less)) {
David Blaikieefdccaa2016-01-15 23:43:34 +00002788 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
Richard Smithc08b6932018-04-27 02:00:13 +00002789 return ParseUnqualifiedIdTemplateId(
2790 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
2791 ClassNameLoc, EnteringContext, ObjectType, Result, TemplateSpecified);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002792 }
Richard Smithefa6f732014-09-06 02:06:12 +00002793
Douglas Gregor7861a802009-11-03 01:35:08 +00002794 // Note that this is a destructor name.
Fangrui Song6907ce22018-07-30 19:24:48 +00002795 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
John McCallba7bf592010-08-24 05:47:05 +00002796 ClassNameLoc, getCurScope(),
2797 SS, ObjectType,
2798 EnteringContext);
Douglas Gregorfe17d252010-02-16 19:09:40 +00002799 if (!Ty)
Douglas Gregor7861a802009-11-03 01:35:08 +00002800 return true;
Douglas Gregorfe17d252010-02-16 19:09:40 +00002801
Douglas Gregor7861a802009-11-03 01:35:08 +00002802 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002803 return false;
2804 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002805
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002806 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002807 << getLangOpts().CPlusPlus;
Douglas Gregor7861a802009-11-03 01:35:08 +00002808 return true;
2809}
2810
Sebastian Redlbd150f42008-11-21 19:14:01 +00002811/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2812/// memory in a typesafe manner and call constructors.
Mike Stump11289f42009-09-09 15:08:12 +00002813///
Chris Lattner109faf22009-01-04 21:25:24 +00002814/// This method is called to parse the new expression after the optional :: has
2815/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2816/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002817///
2818/// new-expression:
2819/// '::'[opt] 'new' new-placement[opt] new-type-id
2820/// new-initializer[opt]
2821/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2822/// new-initializer[opt]
2823///
2824/// new-placement:
2825/// '(' expression-list ')'
2826///
Sebastian Redl351bb782008-12-02 14:43:59 +00002827/// new-type-id:
2828/// type-specifier-seq new-declarator[opt]
Douglas Gregora3a020a2011-04-15 19:40:02 +00002829/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redl351bb782008-12-02 14:43:59 +00002830///
2831/// new-declarator:
2832/// ptr-operator new-declarator[opt]
2833/// direct-new-declarator
2834///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002835/// new-initializer:
2836/// '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00002837/// [C++0x] braced-init-list
Sebastian Redlbd150f42008-11-21 19:14:01 +00002838///
John McCalldadc5752010-08-24 06:29:42 +00002839ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002840Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2841 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2842 ConsumeToken(); // Consume 'new'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002843
2844 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2845 // second form of new-expression. It can't be a new-type-id.
2846
Benjamin Kramerf0623432012-08-23 22:51:59 +00002847 ExprVector PlacementArgs;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002848 SourceLocation PlacementLParen, PlacementRParen;
2849
Douglas Gregorf2753b32010-07-13 15:54:32 +00002850 SourceRange TypeIdParens;
John McCall084e83d2011-03-24 11:26:52 +00002851 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00002852 Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNewContext);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002853 if (Tok.is(tok::l_paren)) {
2854 // If it turns out to be a placement, we change the type location.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002855 BalancedDelimiterTracker T(*this, tok::l_paren);
2856 T.consumeOpen();
2857 PlacementLParen = T.getOpenLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002858 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002859 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002860 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002861 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002862
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002863 T.consumeClose();
2864 PlacementRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002865 if (PlacementRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002866 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002867 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002868 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002869
Sebastian Redl351bb782008-12-02 14:43:59 +00002870 if (PlacementArgs.empty()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002871 // Reset the placement locations. There was no placement.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002872 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002873 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002874 } else {
2875 // We still need the type.
2876 if (Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002877 BalancedDelimiterTracker T(*this, tok::l_paren);
2878 T.consumeOpen();
Douglas Gregora3a020a2011-04-15 19:40:02 +00002879 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002880 ParseSpecifierQualifierList(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002881 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002882 ParseDeclarator(DeclaratorInfo);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002883 T.consumeClose();
2884 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002885 } else {
Douglas Gregora3a020a2011-04-15 19:40:02 +00002886 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002887 if (ParseCXXTypeSpecifierSeq(DS))
2888 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002889 else {
2890 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002891 ParseDeclaratorInternal(DeclaratorInfo,
2892 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002893 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002894 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002895 }
2896 } else {
Sebastian Redl351bb782008-12-02 14:43:59 +00002897 // A new-type-id is a simplified type-id, where essentially the
2898 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregora3a020a2011-04-15 19:40:02 +00002899 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002900 if (ParseCXXTypeSpecifierSeq(DS))
2901 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002902 else {
2903 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002904 ParseDeclaratorInternal(DeclaratorInfo,
2905 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002906 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002907 }
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002908 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002909 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002910 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002911 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002912
Sebastian Redl6047f072012-02-16 12:22:20 +00002913 ExprResult Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002914
2915 if (Tok.is(tok::l_paren)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00002916 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002917 ExprVector ConstructorArgs;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002918 BalancedDelimiterTracker T(*this, tok::l_paren);
2919 T.consumeOpen();
2920 ConstructorLParen = T.getOpenLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002921 if (Tok.isNot(tok::r_paren)) {
2922 CommaLocsTy CommaLocs;
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002923 auto RunSignatureHelp = [&]() {
2924 ParsedType TypeRep =
2925 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
2926 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2927 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
2928 DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
2929 CalledSignatureHelp = true;
2930 return PreferredType;
2931 };
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002932 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002933 PreferredType.enterFunctionArgument(Tok.getLocation(),
2934 RunSignatureHelp);
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002935 })) {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002936 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
2937 RunSignatureHelp();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002938 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002939 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002940 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002941 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002942 T.consumeClose();
2943 ConstructorRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002944 if (ConstructorRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002945 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002946 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002947 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002948 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2949 ConstructorRParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002950 ConstructorArgs);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002951 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002952 Diag(Tok.getLocation(),
2953 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl6047f072012-02-16 12:22:20 +00002954 Initializer = ParseBraceInitializer();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002955 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002956 if (Initializer.isInvalid())
2957 return Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002958
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002959 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002960 PlacementArgs, PlacementRParen,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002961 TypeIdParens, DeclaratorInfo, Initializer.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002962}
2963
Sebastian Redlbd150f42008-11-21 19:14:01 +00002964/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2965/// passed to ParseDeclaratorInternal.
2966///
2967/// direct-new-declarator:
Richard Smithb9fb1212019-05-06 03:47:15 +00002968/// '[' expression[opt] ']'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002969/// direct-new-declarator '[' constant-expression ']'
2970///
Chris Lattner109faf22009-01-04 21:25:24 +00002971void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002972 // Parse the array dimensions.
Richard Smithb9fb1212019-05-06 03:47:15 +00002973 bool First = true;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002974 while (Tok.is(tok::l_square)) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002975 // An array-size expression can't start with a lambda.
2976 if (CheckProhibitedCXX11Attribute())
2977 continue;
2978
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002979 BalancedDelimiterTracker T(*this, tok::l_square);
2980 T.consumeOpen();
2981
Richard Smithb9fb1212019-05-06 03:47:15 +00002982 ExprResult Size =
2983 First ? (Tok.is(tok::r_square) ? ExprResult() : ParseExpression())
2984 : ParseConstantExpression();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002985 if (Size.isInvalid()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002986 // Recover
Alexey Bataevee6507d2013-11-18 08:17:37 +00002987 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002988 return;
2989 }
Richard Smithb9fb1212019-05-06 03:47:15 +00002990 First = false;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002991
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002992 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00002993
Bill Wendling44426052012-12-20 19:22:21 +00002994 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002995 ParsedAttributes Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002996 MaybeParseCXX11Attributes(Attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002997
John McCall084e83d2011-03-24 11:26:52 +00002998 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall53fa7142010-12-24 02:08:15 +00002999 /*static=*/false, /*star=*/false,
Erich Keanec480f302018-07-12 21:09:05 +00003000 Size.get(), T.getOpenLocation(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003001 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00003002 std::move(Attrs), T.getCloseLocation());
Sebastian Redlbd150f42008-11-21 19:14:01 +00003003
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003004 if (T.getCloseLocation().isInvalid())
Sebastian Redlbd150f42008-11-21 19:14:01 +00003005 return;
3006 }
3007}
3008
3009/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
3010/// This ambiguity appears in the syntax of the C++ new operator.
3011///
3012/// new-expression:
3013/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3014/// new-initializer[opt]
3015///
3016/// new-placement:
3017/// '(' expression-list ')'
3018///
John McCall37ad5512010-08-23 06:44:23 +00003019bool Parser::ParseExpressionListOrTypeId(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003020 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner109faf22009-01-04 21:25:24 +00003021 Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00003022 // The '(' was already consumed.
3023 if (isTypeIdInParens()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00003024 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003025 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00003026 ParseDeclarator(D);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003027 return D.isInvalidType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003028 }
3029
3030 // It's not a type, it has to be an expression list.
3031 // Discard the comma locations - ActOnCXXNew has enough parameters.
3032 CommaLocsTy CommaLocs;
3033 return ParseExpressionList(PlacementArgs, CommaLocs);
3034}
3035
3036/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
3037/// to free memory allocated by new.
3038///
Chris Lattner109faf22009-01-04 21:25:24 +00003039/// This method is called to parse the 'delete' expression after the optional
3040/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
3041/// and "Start" is its location. Otherwise, "Start" is the location of the
3042/// 'delete' token.
3043///
Sebastian Redlbd150f42008-11-21 19:14:01 +00003044/// delete-expression:
3045/// '::'[opt] 'delete' cast-expression
3046/// '::'[opt] 'delete' '[' ']' cast-expression
John McCalldadc5752010-08-24 06:29:42 +00003047ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00003048Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
3049 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
3050 ConsumeToken(); // Consume 'delete'
Sebastian Redlbd150f42008-11-21 19:14:01 +00003051
3052 // Array delete?
3053 bool ArrayDelete = false;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003054 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith10c60722012-08-09 19:01:51 +00003055 // C++11 [expr.delete]p1:
3056 // Whenever the delete keyword is followed by empty square brackets, it
3057 // shall be interpreted as [array delete].
3058 // [Footnote: A lambda expression with a lambda-introducer that consists
3059 // of empty square brackets can follow the delete keyword if
3060 // the lambda expression is enclosed in parentheses.]
Nicolas Lesserf53d1722019-05-19 15:07:58 +00003061
3062 const Token Next = GetLookAheadToken(2);
3063
3064 // Basic lookahead to check if we have a lambda expression.
3065 if (Next.isOneOf(tok::l_brace, tok::less) ||
3066 (Next.is(tok::l_paren) &&
3067 (GetLookAheadToken(3).is(tok::r_paren) ||
3068 (GetLookAheadToken(3).is(tok::identifier) &&
3069 GetLookAheadToken(4).is(tok::identifier))))) {
3070 TentativeParsingAction TPA(*this);
3071 SourceLocation LSquareLoc = Tok.getLocation();
3072 SourceLocation RSquareLoc = NextToken().getLocation();
3073
3074 // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this
3075 // case.
3076 SkipUntil({tok::l_brace, tok::less}, StopBeforeMatch);
3077 SourceLocation RBraceLoc;
3078 bool EmitFixIt = false;
Nicolas Lessere47ae692019-05-19 15:30:00 +00003079 if (Tok.is(tok::l_brace)) {
3080 ConsumeBrace();
Nicolas Lesserf53d1722019-05-19 15:07:58 +00003081 SkipUntil(tok::r_brace, StopBeforeMatch);
3082 RBraceLoc = Tok.getLocation();
3083 EmitFixIt = true;
3084 }
3085
3086 TPA.Revert();
3087
3088 if (EmitFixIt)
3089 Diag(Start, diag::err_lambda_after_delete)
3090 << SourceRange(Start, RSquareLoc)
3091 << FixItHint::CreateInsertion(LSquareLoc, "(")
3092 << FixItHint::CreateInsertion(
3093 Lexer::getLocForEndOfToken(
3094 RBraceLoc, 0, Actions.getSourceManager(), getLangOpts()),
3095 ")");
3096 else
3097 Diag(Start, diag::err_lambda_after_delete)
3098 << SourceRange(Start, RSquareLoc);
3099
3100 // Warn that the non-capturing lambda isn't surrounded by parentheses
3101 // to disambiguate it from 'delete[]'.
3102 ExprResult Lambda = ParseLambdaExpression();
3103 if (Lambda.isInvalid())
3104 return ExprError();
3105
3106 // Evaluate any postfix expressions used on the lambda.
3107 Lambda = ParsePostfixExpressionSuffix(Lambda);
3108 if (Lambda.isInvalid())
3109 return ExprError();
3110 return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
3111 Lambda.get());
3112 }
3113
Sebastian Redlbd150f42008-11-21 19:14:01 +00003114 ArrayDelete = true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003115 BalancedDelimiterTracker T(*this, tok::l_square);
3116
3117 T.consumeOpen();
3118 T.consumeClose();
3119 if (T.getCloseLocation().isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00003120 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003121 }
3122
John McCalldadc5752010-08-24 06:29:42 +00003123 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00003124 if (Operand.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003125 return Operand;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003126
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003127 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00003128}
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003129
Douglas Gregor29c42f22012-02-24 07:38:34 +00003130static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
3131 switch (kind) {
3132 default: llvm_unreachable("Not a known type trait");
Alp Toker95e7ff22014-01-01 05:57:51 +00003133#define TYPE_TRAIT_1(Spelling, Name, Key) \
3134case tok::kw_ ## Spelling: return UTT_ ## Name;
Alp Tokercbb90342013-12-13 20:49:58 +00003135#define TYPE_TRAIT_2(Spelling, Name, Key) \
3136case tok::kw_ ## Spelling: return BTT_ ## Name;
3137#include "clang/Basic/TokenKinds.def"
Alp Toker40f9b1c2013-12-12 21:23:03 +00003138#define TYPE_TRAIT_N(Spelling, Name, Key) \
3139 case tok::kw_ ## Spelling: return TT_ ## Name;
3140#include "clang/Basic/TokenKinds.def"
Douglas Gregor29c42f22012-02-24 07:38:34 +00003141 }
3142}
3143
John Wiegley6242b6a2011-04-28 00:16:57 +00003144static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
3145 switch(kind) {
3146 default: llvm_unreachable("Not a known binary type trait");
3147 case tok::kw___array_rank: return ATT_ArrayRank;
3148 case tok::kw___array_extent: return ATT_ArrayExtent;
3149 }
3150}
3151
John Wiegleyf9f65842011-04-25 06:54:41 +00003152static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
3153 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003154 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegleyf9f65842011-04-25 06:54:41 +00003155 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
3156 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
3157 }
3158}
3159
Alp Toker40f9b1c2013-12-12 21:23:03 +00003160static unsigned TypeTraitArity(tok::TokenKind kind) {
3161 switch (kind) {
3162 default: llvm_unreachable("Not a known type trait");
3163#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
3164#include "clang/Basic/TokenKinds.def"
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003165 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003166}
3167
Fangrui Song6907ce22018-07-30 19:24:48 +00003168/// Parse the built-in type-trait pseudo-functions that allow
Douglas Gregor29c42f22012-02-24 07:38:34 +00003169/// implementation of the TR1/C++11 type traits templates.
3170///
3171/// primary-expression:
Alp Toker40f9b1c2013-12-12 21:23:03 +00003172/// unary-type-trait '(' type-id ')'
3173/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor29c42f22012-02-24 07:38:34 +00003174/// type-trait '(' type-id-seq ')'
3175///
3176/// type-id-seq:
3177/// type-id ...[opt] type-id-seq[opt]
3178///
3179ExprResult Parser::ParseTypeTrait() {
Alp Toker40f9b1c2013-12-12 21:23:03 +00003180 tok::TokenKind Kind = Tok.getKind();
3181 unsigned Arity = TypeTraitArity(Kind);
3182
Douglas Gregor29c42f22012-02-24 07:38:34 +00003183 SourceLocation Loc = ConsumeToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00003184
Douglas Gregor29c42f22012-02-24 07:38:34 +00003185 BalancedDelimiterTracker Parens(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003186 if (Parens.expectAndConsume())
Douglas Gregor29c42f22012-02-24 07:38:34 +00003187 return ExprError();
3188
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003189 SmallVector<ParsedType, 2> Args;
Douglas Gregor29c42f22012-02-24 07:38:34 +00003190 do {
3191 // Parse the next type.
3192 TypeResult Ty = ParseTypeName();
3193 if (Ty.isInvalid()) {
3194 Parens.skipToEnd();
3195 return ExprError();
3196 }
3197
3198 // Parse the ellipsis, if present.
3199 if (Tok.is(tok::ellipsis)) {
3200 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3201 if (Ty.isInvalid()) {
3202 Parens.skipToEnd();
3203 return ExprError();
3204 }
3205 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003206
Douglas Gregor29c42f22012-02-24 07:38:34 +00003207 // Add this type to the list of arguments.
3208 Args.push_back(Ty.get());
Alp Tokera3ebe6e2013-12-17 14:12:37 +00003209 } while (TryConsumeToken(tok::comma));
3210
Douglas Gregor29c42f22012-02-24 07:38:34 +00003211 if (Parens.consumeClose())
3212 return ExprError();
Alp Toker40f9b1c2013-12-12 21:23:03 +00003213
3214 SourceLocation EndLoc = Parens.getCloseLocation();
3215
3216 if (Arity && Args.size() != Arity) {
3217 Diag(EndLoc, diag::err_type_trait_arity)
3218 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3219 return ExprError();
3220 }
3221
3222 if (!Arity && Args.empty()) {
3223 Diag(EndLoc, diag::err_type_trait_arity)
3224 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3225 return ExprError();
3226 }
3227
Alp Toker88f64e62013-12-13 21:19:30 +00003228 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
Douglas Gregor29c42f22012-02-24 07:38:34 +00003229}
3230
John Wiegley6242b6a2011-04-28 00:16:57 +00003231/// ParseArrayTypeTrait - Parse the built-in array type-trait
3232/// pseudo-functions.
3233///
3234/// primary-expression:
3235/// [Embarcadero] '__array_rank' '(' type-id ')'
3236/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3237///
3238ExprResult Parser::ParseArrayTypeTrait() {
3239 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3240 SourceLocation Loc = ConsumeToken();
3241
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003242 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003243 if (T.expectAndConsume())
John Wiegley6242b6a2011-04-28 00:16:57 +00003244 return ExprError();
3245
3246 TypeResult Ty = ParseTypeName();
3247 if (Ty.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003248 SkipUntil(tok::comma, StopAtSemi);
3249 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003250 return ExprError();
3251 }
3252
3253 switch (ATT) {
3254 case ATT_ArrayRank: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003255 T.consumeClose();
Craig Topper161e4db2014-05-21 06:02:52 +00003256 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003257 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003258 }
3259 case ATT_ArrayExtent: {
Alp Toker383d2c42014-01-01 03:08:43 +00003260 if (ExpectAndConsume(tok::comma)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003261 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003262 return ExprError();
3263 }
3264
3265 ExprResult DimExpr = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003266 T.consumeClose();
John Wiegley6242b6a2011-04-28 00:16:57 +00003267
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003268 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3269 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003270 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003271 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003272 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley6242b6a2011-04-28 00:16:57 +00003273}
3274
John Wiegleyf9f65842011-04-25 06:54:41 +00003275/// ParseExpressionTrait - Parse built-in expression-trait
3276/// pseudo-functions like __is_lvalue_expr( xxx ).
3277///
3278/// primary-expression:
3279/// [Embarcadero] expression-trait '(' expression ')'
3280///
3281ExprResult Parser::ParseExpressionTrait() {
3282 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3283 SourceLocation Loc = ConsumeToken();
3284
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003285 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003286 if (T.expectAndConsume())
John Wiegleyf9f65842011-04-25 06:54:41 +00003287 return ExprError();
3288
3289 ExprResult Expr = ParseExpression();
3290
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003291 T.consumeClose();
John Wiegleyf9f65842011-04-25 06:54:41 +00003292
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003293 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3294 T.getCloseLocation());
John Wiegleyf9f65842011-04-25 06:54:41 +00003295}
3296
3297
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003298/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3299/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3300/// based on the context past the parens.
John McCalldadc5752010-08-24 06:29:42 +00003301ExprResult
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003302Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallba7bf592010-08-24 05:47:05 +00003303 ParsedType &CastTy,
Richard Smith87e11a42014-05-15 02:43:47 +00003304 BalancedDelimiterTracker &Tracker,
3305 ColonProtectionRAIIObject &ColonProt) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003306 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003307 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3308 assert(isTypeIdInParens() && "Not a type-id!");
3309
John McCalldadc5752010-08-24 06:29:42 +00003310 ExprResult Result(true);
David Blaikieefdccaa2016-01-15 23:43:34 +00003311 CastTy = nullptr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003312
3313 // We need to disambiguate a very ugly part of the C++ syntax:
3314 //
3315 // (T())x; - type-id
3316 // (T())*x; - type-id
3317 // (T())/x; - expression
3318 // (T()); - expression
3319 //
3320 // The bad news is that we cannot use the specialized tentative parser, since
3321 // it can only verify that the thing inside the parens can be parsed as
3322 // type-id, it is not useful for determining the context past the parens.
3323 //
3324 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidis24ad6922009-05-22 15:12:46 +00003325 // making any unnecessary Action calls.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003326 //
3327 // It uses a scheme similar to parsing inline methods. The parenthesized
3328 // tokens are cached, the context that follows is determined (possibly by
3329 // parsing a cast-expression), and then we re-introduce the cached tokens
3330 // into the token stream and parse them appropriately.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003331
Mike Stump11289f42009-09-09 15:08:12 +00003332 ParenParseOption ParseAs;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003333 CachedTokens Toks;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003334
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003335 // Store the tokens of the parentheses. We will parse them after we determine
3336 // the context that follows them.
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +00003337 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003338 // We didn't find the ')' we expected.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003339 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003340 return ExprError();
3341 }
3342
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003343 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003344 ParseAs = CompoundLiteral;
3345 } else {
3346 bool NotCastExpr;
Eli Friedmancf7530f2009-05-25 19:41:42 +00003347 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3348 NotCastExpr = true;
3349 } else {
3350 // Try parsing the cast-expression that may follow.
3351 // If it is not a cast-expression, NotCastExpr will be true and no token
3352 // will be consumed.
Richard Smith87e11a42014-05-15 02:43:47 +00003353 ColonProt.restore();
Eli Friedmancf7530f2009-05-25 19:41:42 +00003354 Result = ParseCastExpression(false/*isUnaryExpression*/,
3355 false/*isAddressofOperand*/,
John McCallba7bf592010-08-24 05:47:05 +00003356 NotCastExpr,
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003357 // type-id has priority.
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00003358 IsTypeCast);
Eli Friedmancf7530f2009-05-25 19:41:42 +00003359 }
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003360
3361 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3362 // an expression.
3363 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003364 }
3365
Alexey Bataev703a93c2016-02-04 04:22:09 +00003366 // Create a fake EOF to mark end of Toks buffer.
3367 Token AttrEnd;
3368 AttrEnd.startToken();
3369 AttrEnd.setKind(tok::eof);
3370 AttrEnd.setLocation(Tok.getLocation());
3371 AttrEnd.setEofData(Toks.data());
3372 Toks.push_back(AttrEnd);
3373
Mike Stump11289f42009-09-09 15:08:12 +00003374 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003375 Toks.push_back(Tok);
3376 // Re-enter the stored parenthesized tokens into the token stream, so we may
3377 // parse them now.
Ilya Biryukov929af672019-05-17 09:32:05 +00003378 PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true,
3379 /*IsReinject*/ true);
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003380 // Drop the current token and bring the first cached one. It's the same token
3381 // as when we entered this function.
3382 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003383
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003384 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003385 // Parse the type declarator.
3386 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00003387 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Richard Smith87e11a42014-05-15 02:43:47 +00003388 {
3389 ColonProtectionRAIIObject InnerColonProtection(*this);
3390 ParseSpecifierQualifierList(DS);
3391 ParseDeclarator(DeclaratorInfo);
3392 }
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003393
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003394 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003395 Tracker.consumeClose();
Richard Smith87e11a42014-05-15 02:43:47 +00003396 ColonProt.restore();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003397
Alexey Bataev703a93c2016-02-04 04:22:09 +00003398 // Consume EOF marker for Toks buffer.
3399 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3400 ConsumeAnyToken();
3401
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003402 if (ParseAs == CompoundLiteral) {
3403 ExprType = CompoundLiteral;
Richard Smithaba8b362014-05-15 02:51:15 +00003404 if (DeclaratorInfo.isInvalidType())
3405 return ExprError();
3406
3407 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Richard Smith87e11a42014-05-15 02:43:47 +00003408 return ParseCompoundLiteralExpression(Ty.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003409 Tracker.getOpenLocation(),
3410 Tracker.getCloseLocation());
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003411 }
Mike Stump11289f42009-09-09 15:08:12 +00003412
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003413 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3414 assert(ParseAs == CastExpr);
3415
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003416 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003417 return ExprError();
3418
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003419 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003420 if (!Result.isInvalid())
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003421 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3422 DeclaratorInfo, CastTy,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003423 Tracker.getCloseLocation(), Result.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003424 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003425 }
Mike Stump11289f42009-09-09 15:08:12 +00003426
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003427 // Not a compound literal, and not followed by a cast-expression.
3428 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003429
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003430 ExprType = SimpleExpr;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003431 Result = ParseExpression();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003432 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Fangrui Song6907ce22018-07-30 19:24:48 +00003433 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003434 Tok.getLocation(), Result.get());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003435
3436 // Match the ')'.
3437 if (Result.isInvalid()) {
Alexey Bataev703a93c2016-02-04 04:22:09 +00003438 while (Tok.isNot(tok::eof))
3439 ConsumeAnyToken();
3440 assert(Tok.getEofData() == AttrEnd.getEofData());
3441 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003442 return ExprError();
3443 }
Mike Stump11289f42009-09-09 15:08:12 +00003444
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003445 Tracker.consumeClose();
Alexey Bataev703a93c2016-02-04 04:22:09 +00003446 // Consume EOF marker for Toks buffer.
3447 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3448 ConsumeAnyToken();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003449 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003450}