blob: 8abd6969c0f0dab33e9dafbf5d67404d9d3839f9 [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;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000689 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000690 if (DiagID) {
691 Diag(Tok, DiagID.getValue());
David Majnemer234b8182015-01-12 03:36:37 +0000692 SkipUntil(tok::r_square, StopAtSemi);
693 SkipUntil(tok::l_brace, StopAtSemi);
694 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000695 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000696 }
697
698 return ParseLambdaExpressionAfterIntroducer(Intro);
699}
700
701/// TryParseLambdaExpression - Use lookahead and potentially tentative
702/// parsing to determine if we are looking at a C++0x lambda expression, and parse
703/// it if we are.
704///
705/// If we are not looking at a lambda expression, returns ExprError().
706ExprResult Parser::TryParseLambdaExpression() {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000707 assert(getLangOpts().CPlusPlus11
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000708 && Tok.is(tok::l_square)
709 && "Not at the start of a possible lambda expression.");
710
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000711 const Token Next = NextToken();
712 if (Next.is(tok::eof)) // Nothing else to lookup here...
713 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000714
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000715 const Token After = GetLookAheadToken(2);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000716 // If lookahead indicates this is a lambda...
717 if (Next.is(tok::r_square) || // []
718 Next.is(tok::equal) || // [=
719 (Next.is(tok::amp) && // [&] or [&,
720 (After.is(tok::r_square) ||
721 After.is(tok::comma))) ||
722 (Next.is(tok::identifier) && // [identifier]
723 After.is(tok::r_square))) {
724 return ParseLambdaExpression();
725 }
726
Eli Friedmanc7c97142012-01-04 02:40:39 +0000727 // If lookahead indicates an ObjC message send...
728 // [identifier identifier
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000729 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000730 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000731 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000732
Eli Friedmanc7c97142012-01-04 02:40:39 +0000733 // Here, we're stuck: lambda introducers and Objective-C message sends are
734 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
735 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
736 // writing two routines to parse a lambda introducer, just try to parse
737 // a lambda introducer first, and fall back if that fails.
738 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000739 LambdaIntroducer Intro;
740 if (TryParseLambdaIntroducer(Intro))
Eli Friedmanc7c97142012-01-04 02:40:39 +0000741 return ExprEmpty();
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000742
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000743 return ParseLambdaExpressionAfterIntroducer(Intro);
744}
745
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000746/// Parse a lambda introducer.
Richard Smithf44d2a82013-05-21 22:21:19 +0000747/// \param Intro A LambdaIntroducer filled in with information about the
748/// contents of the lambda-introducer.
749/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
750/// message send and a lambda expression. In this mode, we will
751/// sometimes skip the initializers for init-captures and not fully
752/// populate \p Intro. This flag will be set to \c true if we do so.
753/// \return A DiagnosticID if it hit something unexpected. The location for
Malcolm Parsonsffd21d32017-01-11 11:23:22 +0000754/// the diagnostic is that of the current token.
Richard Smithf44d2a82013-05-21 22:21:19 +0000755Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
756 bool *SkippedInits) {
David Blaikie05785d12013-02-20 22:23:23 +0000757 typedef Optional<unsigned> DiagResult;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000758
759 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000760 BalancedDelimiterTracker T(*this, tok::l_square);
761 T.consumeOpen();
762
763 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000764
765 bool first = true;
766
767 // Parse capture-default.
768 if (Tok.is(tok::amp) &&
769 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
770 Intro.Default = LCD_ByRef;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000771 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000772 first = false;
773 } else if (Tok.is(tok::equal)) {
774 Intro.Default = LCD_ByCopy;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000775 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000776 first = false;
777 }
778
779 while (Tok.isNot(tok::r_square)) {
780 if (!first) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000781 if (Tok.isNot(tok::comma)) {
Douglas Gregor721b14d2012-07-31 00:50:07 +0000782 // Provide a completion for a lambda introducer here. Except
783 // in Objective-C, where this is Almost Surely meant to be a message
784 // send. In that case, fail here and let the ObjC message
785 // expression parser perform the completion.
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000786 if (Tok.is(tok::code_completion) &&
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000787 !(getLangOpts().ObjC && Intro.Default == LCD_None &&
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000788 !Intro.Captures.empty())) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000789 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
Douglas Gregord8c61782012-02-15 15:34:24 +0000790 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000791 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000792 break;
793 }
794
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000795 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregord8c61782012-02-15 15:34:24 +0000796 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000797 ConsumeToken();
798 }
799
Douglas Gregord8c61782012-02-15 15:34:24 +0000800 if (Tok.is(tok::code_completion)) {
801 // If we're in Objective-C++ and we have a bare '[', then this is more
802 // likely to be a message receiver.
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000803 if (getLangOpts().ObjC && first)
Douglas Gregord8c61782012-02-15 15:34:24 +0000804 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
805 else
Fangrui Song6907ce22018-07-30 19:24:48 +0000806 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
Douglas Gregord8c61782012-02-15 15:34:24 +0000807 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000808 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000809 break;
810 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000811
Douglas Gregord8c61782012-02-15 15:34:24 +0000812 first = false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000813
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000814 // Parse capture.
815 LambdaCaptureKind Kind = LCK_ByCopy;
Richard Smith42b10572015-11-11 01:36:17 +0000816 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000817 SourceLocation Loc;
Craig Topper161e4db2014-05-21 06:02:52 +0000818 IdentifierInfo *Id = nullptr;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000819 SourceLocation EllipsisLoc;
Richard Smith21b3ab42013-05-09 21:36:41 +0000820 ExprResult Init;
Alexander Shaposhnikov832f49b2018-07-16 07:23:47 +0000821 SourceLocation LocStart = Tok.getLocation();
Faisal Validc6b5962016-03-21 09:25:37 +0000822
823 if (Tok.is(tok::star)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000824 Loc = ConsumeToken();
Faisal Validc6b5962016-03-21 09:25:37 +0000825 if (Tok.is(tok::kw_this)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000826 ConsumeToken();
827 Kind = LCK_StarThis;
Faisal Validc6b5962016-03-21 09:25:37 +0000828 } else {
829 return DiagResult(diag::err_expected_star_this_capture);
830 }
831 } else if (Tok.is(tok::kw_this)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000832 Kind = LCK_This;
833 Loc = ConsumeToken();
834 } else {
835 if (Tok.is(tok::amp)) {
836 Kind = LCK_ByRef;
837 ConsumeToken();
Douglas Gregord8c61782012-02-15 15:34:24 +0000838
839 if (Tok.is(tok::code_completion)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000840 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
Douglas Gregord8c61782012-02-15 15:34:24 +0000841 /*AfterAmpersand=*/true);
Alp Toker1c583cc2014-05-02 03:43:14 +0000842 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000843 break;
844 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000845 }
846
847 if (Tok.is(tok::identifier)) {
848 Id = Tok.getIdentifierInfo();
849 Loc = ConsumeToken();
850 } else if (Tok.is(tok::kw_this)) {
851 // FIXME: If we want to suggest a fixit here, will need to return more
852 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
853 // Clear()ed to prevent emission in case of tentative parsing?
854 return DiagResult(diag::err_this_captured_by_reference);
855 } else {
856 return DiagResult(diag::err_expected_capture);
857 }
Richard Smith21b3ab42013-05-09 21:36:41 +0000858
859 if (Tok.is(tok::l_paren)) {
860 BalancedDelimiterTracker Parens(*this, tok::l_paren);
861 Parens.consumeOpen();
862
Richard Smith42b10572015-11-11 01:36:17 +0000863 InitKind = LambdaCaptureInitKind::DirectInit;
864
Richard Smith21b3ab42013-05-09 21:36:41 +0000865 ExprVector Exprs;
866 CommaLocsTy Commas;
Richard Smithf44d2a82013-05-21 22:21:19 +0000867 if (SkippedInits) {
868 Parens.skipToEnd();
869 *SkippedInits = true;
870 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith21b3ab42013-05-09 21:36:41 +0000871 Parens.skipToEnd();
872 Init = ExprError();
873 } else {
874 Parens.consumeClose();
875 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
876 Parens.getCloseLocation(),
877 Exprs);
878 }
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000879 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000880 // Each lambda init-capture forms its own full expression, which clears
881 // Actions.MaybeODRUseExprs. So create an expression evaluation context
882 // to save the necessary state, and restore it later.
Faisal Valid143a0c2017-04-01 21:30:49 +0000883 EnterExpressionEvaluationContext EC(
884 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith42b10572015-11-11 01:36:17 +0000885
886 if (TryConsumeToken(tok::equal))
887 InitKind = LambdaCaptureInitKind::CopyInit;
888 else
889 InitKind = LambdaCaptureInitKind::ListInit;
Richard Smith21b3ab42013-05-09 21:36:41 +0000890
Richard Smith215f4232015-02-11 02:41:33 +0000891 if (!SkippedInits) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000892 Init = ParseInitializer();
Richard Smith215f4232015-02-11 02:41:33 +0000893 } else if (Tok.is(tok::l_brace)) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000894 BalancedDelimiterTracker Braces(*this, tok::l_brace);
895 Braces.consumeOpen();
896 Braces.skipToEnd();
897 *SkippedInits = true;
898 } else {
899 // We're disambiguating this:
900 //
901 // [..., x = expr
902 //
903 // We need to find the end of the following expression in order to
Richard Smith9e2f0a42014-04-13 04:31:48 +0000904 // determine whether this is an Obj-C message send's receiver, a
905 // C99 designator, or a lambda init-capture.
Richard Smithf44d2a82013-05-21 22:21:19 +0000906 //
907 // Parse the expression to find where it ends, and annotate it back
908 // onto the tokens. We would have parsed this expression the same way
909 // in either case: both the RHS of an init-capture and the RHS of an
910 // assignment expression are parsed as an initializer-clause, and in
911 // neither case can anything be added to the scope between the '[' and
912 // here.
913 //
914 // FIXME: This is horrible. Adding a mechanism to skip an expression
915 // would be much cleaner.
916 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
917 // that instead. (And if we see a ':' with no matching '?', we can
918 // classify this as an Obj-C message send.)
919 SourceLocation StartLoc = Tok.getLocation();
920 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
921 Init = ParseInitializer();
Akira Hatanaka51e60f92016-12-20 02:11:29 +0000922 if (!Init.isInvalid())
923 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
Richard Smithf44d2a82013-05-21 22:21:19 +0000924
925 if (Tok.getLocation() != StartLoc) {
926 // Back out the lexing of the token after the initializer.
927 PP.RevertCachedTokens(1);
928
929 // Replace the consumed tokens with an appropriate annotation.
930 Tok.setLocation(StartLoc);
931 Tok.setKind(tok::annot_primary_expr);
932 setExprAnnotation(Tok, Init);
933 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
934 PP.AnnotateCachedTokens(Tok);
935
936 // Consume the annotated initializer.
Richard Smithaf3b3252017-05-18 19:21:48 +0000937 ConsumeAnnotationToken();
Richard Smithf44d2a82013-05-21 22:21:19 +0000938 }
939 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000940 } else
941 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000942 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000943 // If this is an init capture, process the initialization expression
944 // right away. For lambda init-captures such as the following:
945 // const int x = 10;
946 // auto L = [i = x+1](int a) {
947 // return [j = x+2,
948 // &k = x](char b) { };
949 // };
950 // keep in mind that each lambda init-capture has to have:
951 // - its initialization expression executed in the context
952 // of the enclosing/parent decl-context.
953 // - but the variable itself has to be 'injected' into the
954 // decl-context of its lambda's call-operator (which has
955 // not yet been created).
956 // Each init-expression is a full-expression that has to get
957 // Sema-analyzed (for capturing etc.) before its lambda's
958 // call-operator's decl-context, scope & scopeinfo are pushed on their
959 // respective stacks. Thus if any variable is odr-used in the init-capture
960 // it will correctly get captured in the enclosing lambda, if one exists.
961 // The init-variables above are created later once the lambdascope and
962 // call-operators decl-context is pushed onto its respective stack.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000963
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000964 // Since the lambda init-capture's initializer expression occurs in the
965 // context of the enclosing function or lambda, therefore we can not wait
966 // till a lambda scope has been pushed on before deciding whether the
967 // variable needs to be captured. We also need to process all
968 // lvalue-to-rvalue conversions and discarded-value conversions,
969 // so that we can avoid capturing certain constant variables.
970 // For e.g.,
971 // void test() {
972 // const int x = 10;
973 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
974 // return [y = x](int i) { <-- don't capture by enclosing lambda
975 // return y;
976 // }
977 // };
Richard Smithbdb84f32016-07-22 23:36:59 +0000978 // }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000979 // If x was not const, the second use would require 'L' to capture, and
980 // that would be an error.
981
Richard Smith42b10572015-11-11 01:36:17 +0000982 ParsedType InitCaptureType;
Volodymyr Sapsaib0f1aae2017-08-22 17:55:19 +0000983 if (!Init.isInvalid())
984 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000985 if (Init.isUsable()) {
986 // Get the pointer and store it in an lvalue, so we can use it as an
987 // out argument.
988 Expr *InitExpr = Init.get();
989 // This performs any lvalue-to-rvalue conversions if necessary, which
990 // can affect what gets captured in the containing decl-context.
Richard Smith42b10572015-11-11 01:36:17 +0000991 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
992 Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000993 Init = InitExpr;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000994 }
Alexander Shaposhnikov832f49b2018-07-16 07:23:47 +0000995
996 SourceLocation LocEnd = PrevTokLocation;
997
Richard Smith42b10572015-11-11 01:36:17 +0000998 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
Alexander Shaposhnikov832f49b2018-07-16 07:23:47 +0000999 InitCaptureType, SourceRange(LocStart, LocEnd));
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001000 }
1001
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001002 T.consumeClose();
1003 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001004 return DiagResult();
1005}
1006
Douglas Gregord8c61782012-02-15 15:34:24 +00001007/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001008///
1009/// Returns true if it hit something unexpected.
1010bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
Jan Korous06aa2af2017-11-06 17:42:17 +00001011 {
1012 bool SkippedInits = false;
1013 TentativeParsingAction PA1(*this);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001014
Jan Korous06aa2af2017-11-06 17:42:17 +00001015 if (ParseLambdaIntroducer(Intro, &SkippedInits)) {
1016 PA1.Revert();
1017 return true;
1018 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001019
Jan Korous06aa2af2017-11-06 17:42:17 +00001020 if (!SkippedInits) {
1021 PA1.Commit();
1022 return false;
1023 }
1024
1025 PA1.Revert();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001026 }
1027
Jan Korous06aa2af2017-11-06 17:42:17 +00001028 // Try to parse it again, but this time parse the init-captures too.
1029 Intro = LambdaIntroducer();
1030 TentativeParsingAction PA2(*this);
1031
1032 if (!ParseLambdaIntroducer(Intro)) {
1033 PA2.Commit();
Richard Smithf44d2a82013-05-21 22:21:19 +00001034 return false;
1035 }
1036
Jan Korous06aa2af2017-11-06 17:42:17 +00001037 PA2.Revert();
1038 return true;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001039}
1040
Faisal Valia734ab92016-03-26 16:11:37 +00001041static void
1042tryConsumeMutableOrConstexprToken(Parser &P, SourceLocation &MutableLoc,
1043 SourceLocation &ConstexprLoc,
1044 SourceLocation &DeclEndLoc) {
1045 assert(MutableLoc.isInvalid());
1046 assert(ConstexprLoc.isInvalid());
1047 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1048 // to the final of those locations. Emit an error if we have multiple
1049 // copies of those keywords and recover.
1050
1051 while (true) {
1052 switch (P.getCurToken().getKind()) {
1053 case tok::kw_mutable: {
1054 if (MutableLoc.isValid()) {
1055 P.Diag(P.getCurToken().getLocation(),
1056 diag::err_lambda_decl_specifier_repeated)
1057 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1058 }
1059 MutableLoc = P.ConsumeToken();
1060 DeclEndLoc = MutableLoc;
1061 break /*switch*/;
1062 }
1063 case tok::kw_constexpr:
1064 if (ConstexprLoc.isValid()) {
1065 P.Diag(P.getCurToken().getLocation(),
1066 diag::err_lambda_decl_specifier_repeated)
1067 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1068 }
1069 ConstexprLoc = P.ConsumeToken();
1070 DeclEndLoc = ConstexprLoc;
1071 break /*switch*/;
1072 default:
1073 return;
1074 }
1075 }
1076}
1077
1078static void
1079addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1080 DeclSpec &DS) {
1081 if (ConstexprLoc.isValid()) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001082 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
Richard Smithb115e5d2017-08-13 23:37:29 +00001083 ? diag::ext_constexpr_on_lambda_cxx17
Faisal Valia734ab92016-03-26 16:11:37 +00001084 : diag::warn_cxx14_compat_constexpr_on_lambda);
1085 const char *PrevSpec = nullptr;
1086 unsigned DiagID = 0;
1087 DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
1088 assert(PrevSpec == nullptr && DiagID == 0 &&
1089 "Constexpr cannot have been set previously!");
1090 }
1091}
1092
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001093/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1094/// expression.
1095ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1096 LambdaIntroducer &Intro) {
Eli Friedmanc7c97142012-01-04 02:40:39 +00001097 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1098 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1099
1100 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1101 "lambda expression parsing");
1102
Fangrui Song6907ce22018-07-30 19:24:48 +00001103
Faisal Vali2b391ab2013-09-26 19:54:12 +00001104
Richard Smith21b3ab42013-05-09 21:36:41 +00001105 // FIXME: Call into Actions to add any init-capture declarations to the
1106 // scope while parsing the lambda-declarator and compound-statement.
1107
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001108 // Parse lambda-declarator[opt].
1109 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00001110 Declarator D(DS, DeclaratorContext::LambdaExprContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001111 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001112 Actions.PushLambdaScope();
1113
1114 ParsedAttributes Attr(AttrFactory);
1115 SourceLocation DeclLoc = Tok.getLocation();
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001116 if (getLangOpts().CUDA) {
1117 // In CUDA code, GNU attributes are allowed to appear immediately after the
1118 // "[...]", even if there is no "(...)" before the lambda body.
Justin Lebar0139a5d2016-09-30 19:55:48 +00001119 MaybeParseGNUAttributes(D);
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001120 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001121
Justin Lebare46ea722016-09-30 19:55:55 +00001122 // Helper to emit a warning if we see a CUDA host/device/global attribute
1123 // after '(...)'. nvcc doesn't accept this.
1124 auto WarnIfHasCUDATargetAttr = [&] {
1125 if (getLangOpts().CUDA)
Erich Keanee891aa92018-07-13 15:07:47 +00001126 for (const ParsedAttr &A : Attr)
1127 if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1128 A.getKind() == ParsedAttr::AT_CUDAHost ||
1129 A.getKind() == ParsedAttr::AT_CUDAGlobal)
Erich Keanec480f302018-07-12 21:09:05 +00001130 Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
1131 << A.getName()->getName();
Justin Lebare46ea722016-09-30 19:55:55 +00001132 };
1133
Hamza Sood8205a812019-05-04 10:49:46 +00001134 // FIXME: Consider allowing this as an extension for GCC compatibiblity.
1135 const bool HasExplicitTemplateParams = Tok.is(tok::less);
1136 ParseScope TemplateParamScope(this, Scope::TemplateParamScope,
1137 /*EnteredScope=*/HasExplicitTemplateParams);
1138 if (HasExplicitTemplateParams) {
1139 Diag(Tok, getLangOpts().CPlusPlus2a
1140 ? diag::warn_cxx17_compat_lambda_template_parameter_list
1141 : diag::ext_lambda_template_parameter_list);
1142
1143 SmallVector<NamedDecl*, 4> TemplateParams;
1144 SourceLocation LAngleLoc, RAngleLoc;
1145 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
1146 TemplateParams, LAngleLoc, RAngleLoc)) {
1147 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1148 return ExprError();
1149 }
1150
1151 if (TemplateParams.empty()) {
1152 Diag(RAngleLoc,
1153 diag::err_lambda_template_parameter_list_empty);
1154 } else {
1155 Actions.ActOnLambdaExplicitTemplateParameterList(
1156 LAngleLoc, TemplateParams, RAngleLoc);
1157 ++CurTemplateDepthTracker;
1158 }
1159 }
1160
David Majnemere01c4662015-01-09 05:10:55 +00001161 TypeResult TrailingReturnType;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001162 if (Tok.is(tok::l_paren)) {
1163 ParseScope PrototypeScope(this,
1164 Scope::FunctionPrototypeScope |
Richard Smithe233fbf2013-01-28 22:42:45 +00001165 Scope::FunctionDeclarationScope |
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001166 Scope::DeclScope);
1167
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001168 BalancedDelimiterTracker T(*this, tok::l_paren);
1169 T.consumeOpen();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001170 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001171
1172 // Parse parameter-declaration-clause.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001173 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001174 SourceLocation EllipsisLoc;
Fangrui Song6907ce22018-07-30 19:24:48 +00001175
Faisal Vali2b391ab2013-09-26 19:54:12 +00001176 if (Tok.isNot(tok::r_paren)) {
Hamza Sood8205a812019-05-04 10:49:46 +00001177 Actions.RecordParsingTemplateParameterDepth(
1178 CurTemplateDepthTracker.getOriginalDepth());
1179
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001180 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
Hamza Sood8205a812019-05-04 10:49:46 +00001181
Fangrui Song6907ce22018-07-30 19:24:48 +00001182 // For a generic lambda, each 'auto' within the parameter declaration
Faisal Vali2b391ab2013-09-26 19:54:12 +00001183 // clause creates a template type parameter, so increment the depth.
Hamza Sood8205a812019-05-04 10:49:46 +00001184 // If we've parsed any explicit template parameters, then the depth will
1185 // have already been incremented. So we make sure that at most a single
1186 // depth level is added.
Fangrui Song6907ce22018-07-30 19:24:48 +00001187 if (Actions.getCurGenericLambda())
Hamza Sood8205a812019-05-04 10:49:46 +00001188 CurTemplateDepthTracker.setAddedDepth(1);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001189 }
Hamza Sood8205a812019-05-04 10:49:46 +00001190
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001191 T.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001192 SourceLocation RParenLoc = T.getCloseLocation();
Justin Lebar0139a5d2016-09-30 19:55:48 +00001193 SourceLocation DeclEndLoc = RParenLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001194
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001195 // GNU-style attributes must be parsed before the mutable specifier to be
1196 // compatible with GCC.
1197 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1198
David Majnemerbda86322015-02-04 08:22:46 +00001199 // MSVC-style attributes must be parsed before the mutable specifier to be
1200 // compatible with MSVC.
Aaron Ballman068aa512015-05-20 20:58:33 +00001201 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
David Majnemerbda86322015-02-04 08:22:46 +00001202
Faisal Valia734ab92016-03-26 16:11:37 +00001203 // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001204 SourceLocation MutableLoc;
Faisal Valia734ab92016-03-26 16:11:37 +00001205 SourceLocation ConstexprLoc;
1206 tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
1207 DeclEndLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001208
Faisal Valia734ab92016-03-26 16:11:37 +00001209 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001210
1211 // Parse exception-specification[opt].
1212 ExceptionSpecificationType ESpecType = EST_None;
1213 SourceRange ESpecRange;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001214 SmallVector<ParsedType, 2> DynamicExceptions;
1215 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001216 ExprResult NoexceptExpr;
Richard Smith0b3a4622014-11-13 20:01:57 +00001217 CachedTokens *ExceptionSpecTokens;
1218 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1219 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00001220 DynamicExceptions,
1221 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00001222 NoexceptExpr,
1223 ExceptionSpecTokens);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001224
1225 if (ESpecType != EST_None)
1226 DeclEndLoc = ESpecRange.getEnd();
1227
1228 // Parse attribute-specifier[opt].
Richard Smith89645bc2013-01-02 12:01:23 +00001229 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001230
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001231 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1232
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001233 // Parse trailing-return-type[opt].
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001234 if (Tok.is(tok::arrow)) {
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001235 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001236 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00001237 TrailingReturnType =
1238 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001239 if (Range.getEnd().isValid())
1240 DeclEndLoc = Range.getEnd();
1241 }
1242
1243 PrototypeScope.Exit();
1244
Justin Lebare46ea722016-09-30 19:55:55 +00001245 WarnIfHasCUDATargetAttr();
1246
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001247 SourceLocation NoLoc;
Erich Keanec480f302018-07-12 21:09:05 +00001248 D.AddTypeInfo(DeclaratorChunk::getFunction(
1249 /*hasProto=*/true,
1250 /*isAmbiguous=*/false, LParenLoc, ParamInfo.data(),
1251 ParamInfo.size(), EllipsisLoc, RParenLoc,
Erich Keanec480f302018-07-12 21:09:05 +00001252 /*RefQualifierIsLValueRef=*/true,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00001253 /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType,
Erich Keanec480f302018-07-12 21:09:05 +00001254 ESpecRange, DynamicExceptions.data(),
1255 DynamicExceptionRanges.data(), DynamicExceptions.size(),
1256 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1257 /*ExceptionSpecTokens*/ nullptr,
1258 /*DeclsInPrototype=*/None, LParenLoc, FunLocalRangeEnd, D,
1259 TrailingReturnType),
1260 std::move(Attr), DeclEndLoc);
Faisal Valia734ab92016-03-26 16:11:37 +00001261 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1262 tok::kw_constexpr) ||
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001263 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1264 // It's common to forget that one needs '()' before 'mutable', an attribute
1265 // specifier, or the result type. Deal with this.
1266 unsigned TokKind = 0;
1267 switch (Tok.getKind()) {
1268 case tok::kw_mutable: TokKind = 0; break;
1269 case tok::arrow: TokKind = 1; break;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001270 case tok::kw___attribute:
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001271 case tok::l_square: TokKind = 2; break;
Faisal Valia734ab92016-03-26 16:11:37 +00001272 case tok::kw_constexpr: TokKind = 3; break;
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001273 default: llvm_unreachable("Unknown token kind");
1274 }
1275
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001276 Diag(Tok, diag::err_lambda_missing_parens)
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001277 << TokKind
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001278 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
Justin Lebar0139a5d2016-09-30 19:55:48 +00001279 SourceLocation DeclEndLoc = DeclLoc;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001280
1281 // GNU-style attributes must be parsed before the mutable specifier to be
1282 // compatible with GCC.
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001283 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1284
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001285 // Parse 'mutable', if it's there.
1286 SourceLocation MutableLoc;
1287 if (Tok.is(tok::kw_mutable)) {
1288 MutableLoc = ConsumeToken();
1289 DeclEndLoc = MutableLoc;
1290 }
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001291
1292 // Parse attribute-specifier[opt].
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001293 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1294
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001295 // Parse the return type, if there is one.
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001296 if (Tok.is(tok::arrow)) {
1297 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00001298 TrailingReturnType =
1299 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001300 if (Range.getEnd().isValid())
David Majnemere01c4662015-01-09 05:10:55 +00001301 DeclEndLoc = Range.getEnd();
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001302 }
1303
Justin Lebare46ea722016-09-30 19:55:55 +00001304 WarnIfHasCUDATargetAttr();
1305
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001306 SourceLocation NoLoc;
Erich Keanec480f302018-07-12 21:09:05 +00001307 D.AddTypeInfo(DeclaratorChunk::getFunction(
1308 /*hasProto=*/true,
1309 /*isAmbiguous=*/false,
1310 /*LParenLoc=*/NoLoc,
1311 /*Params=*/nullptr,
1312 /*NumParams=*/0,
1313 /*EllipsisLoc=*/NoLoc,
1314 /*RParenLoc=*/NoLoc,
Erich Keanec480f302018-07-12 21:09:05 +00001315 /*RefQualifierIsLValueRef=*/true,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00001316 /*RefQualifierLoc=*/NoLoc, MutableLoc, EST_None,
Erich Keanec480f302018-07-12 21:09:05 +00001317 /*ESpecRange=*/SourceRange(),
1318 /*Exceptions=*/nullptr,
1319 /*ExceptionRanges=*/nullptr,
1320 /*NumExceptions=*/0,
1321 /*NoexceptExpr=*/nullptr,
1322 /*ExceptionSpecTokens=*/nullptr,
1323 /*DeclsInPrototype=*/None, DeclLoc, DeclEndLoc, D,
1324 TrailingReturnType),
1325 std::move(Attr), DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001326 }
1327
Eli Friedman4817cf72012-01-06 03:05:34 +00001328 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1329 // it.
Momchil Velikov57c681f2017-08-10 15:43:06 +00001330 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1331 Scope::CompoundStmtScope;
Douglas Gregorb8389972012-02-21 22:51:27 +00001332 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman4817cf72012-01-06 03:05:34 +00001333
Eli Friedman71c80552012-01-05 03:35:19 +00001334 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1335
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001336 // Parse compound-statement.
Eli Friedmanc7c97142012-01-04 02:40:39 +00001337 if (!Tok.is(tok::l_brace)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001338 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmanc7c97142012-01-04 02:40:39 +00001339 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1340 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001341 }
1342
Eli Friedmanc7c97142012-01-04 02:40:39 +00001343 StmtResult Stmt(ParseCompoundStatementBody());
1344 BodyScope.Exit();
Hamza Sood8205a812019-05-04 10:49:46 +00001345 TemplateParamScope.Exit();
Eli Friedmanc7c97142012-01-04 02:40:39 +00001346
David Majnemere01c4662015-01-09 05:10:55 +00001347 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001348 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
David Majnemere01c4662015-01-09 05:10:55 +00001349
Eli Friedman898caf82012-01-04 02:46:53 +00001350 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1351 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001352}
1353
Chris Lattner29375652006-12-04 18:06:35 +00001354/// ParseCXXCasts - This handles the various ways to cast expressions to another
1355/// type.
1356///
1357/// postfix-expression: [C++ 5.2p1]
1358/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1359/// 'static_cast' '<' type-name '>' '(' expression ')'
1360/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1361/// 'const_cast' '<' type-name '>' '(' expression ')'
1362///
John McCalldadc5752010-08-24 06:29:42 +00001363ExprResult Parser::ParseCXXCasts() {
Chris Lattner29375652006-12-04 18:06:35 +00001364 tok::TokenKind Kind = Tok.getKind();
Craig Topper161e4db2014-05-21 06:02:52 +00001365 const char *CastName = nullptr; // For error messages
Chris Lattner29375652006-12-04 18:06:35 +00001366
1367 switch (Kind) {
David Blaikieaa347f92011-09-23 20:26:49 +00001368 default: llvm_unreachable("Unknown C++ cast!");
Chris Lattner29375652006-12-04 18:06:35 +00001369 case tok::kw_const_cast: CastName = "const_cast"; break;
1370 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1371 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1372 case tok::kw_static_cast: CastName = "static_cast"; break;
1373 }
1374
1375 SourceLocation OpLoc = ConsumeToken();
1376 SourceLocation LAngleBracketLoc = Tok.getLocation();
1377
Richard Smith55858492011-04-14 21:45:45 +00001378 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1379 // diagnose error, suggest fix, and recover parsing.
Richard Smith62e66302012-08-20 17:37:52 +00001380 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1381 Token Next = NextToken();
1382 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1383 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1384 }
Richard Smith55858492011-04-14 21:45:45 +00001385
Chris Lattner29375652006-12-04 18:06:35 +00001386 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redld65cea82008-12-11 22:51:44 +00001387 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001388
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001389 // Parse the common declaration-specifiers piece.
1390 DeclSpec DS(AttrFactory);
1391 ParseSpecifierQualifierList(DS);
1392
1393 // Parse the abstract-declarator, if present.
Faisal Vali421b2d12017-12-29 05:41:00 +00001394 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001395 ParseDeclarator(DeclaratorInfo);
1396
Chris Lattner29375652006-12-04 18:06:35 +00001397 SourceLocation RAngleBracketLoc = Tok.getLocation();
1398
Alp Toker383d2c42014-01-01 03:08:43 +00001399 if (ExpectAndConsume(tok::greater))
Alp Tokerec543272013-12-24 09:48:30 +00001400 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
Chris Lattner29375652006-12-04 18:06:35 +00001401
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001402 BalancedDelimiterTracker T(*this, tok::l_paren);
Chris Lattner29375652006-12-04 18:06:35 +00001403
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001404 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001405 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001406
John McCalldadc5752010-08-24 06:29:42 +00001407 ExprResult Result = ParseExpression();
Mike Stump11289f42009-09-09 15:08:12 +00001408
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001409 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001410 T.consumeClose();
Chris Lattner29375652006-12-04 18:06:35 +00001411
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001412 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregore200adc2008-10-27 19:41:14 +00001413 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001414 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor220cac52009-02-18 17:45:20 +00001415 RAngleBracketLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00001416 T.getOpenLocation(), Result.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001417 T.getCloseLocation());
Chris Lattner29375652006-12-04 18:06:35 +00001418
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001419 return Result;
Chris Lattner29375652006-12-04 18:06:35 +00001420}
Bill Wendling4073ed52007-02-13 01:51:42 +00001421
Sebastian Redlc4704762008-11-11 11:37:55 +00001422/// ParseCXXTypeid - This handles the C++ typeid expression.
1423///
1424/// postfix-expression: [C++ 5.2p1]
1425/// 'typeid' '(' expression ')'
1426/// 'typeid' '(' type-id ')'
1427///
John McCalldadc5752010-08-24 06:29:42 +00001428ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc4704762008-11-11 11:37:55 +00001429 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1430
1431 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001432 SourceLocation LParenLoc, RParenLoc;
1433 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc4704762008-11-11 11:37:55 +00001434
1435 // typeid expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001436 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redld65cea82008-12-11 22:51:44 +00001437 return ExprError();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001438 LParenLoc = T.getOpenLocation();
Sebastian Redlc4704762008-11-11 11:37:55 +00001439
John McCalldadc5752010-08-24 06:29:42 +00001440 ExprResult Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001441
Richard Smith4f605af2012-08-18 00:55:03 +00001442 // C++0x [expr.typeid]p3:
1443 // When typeid is applied to an expression other than an lvalue of a
1444 // polymorphic class type [...] The expression is an unevaluated
1445 // operand (Clause 5).
1446 //
1447 // Note that we can't tell whether the expression is an lvalue of a
1448 // polymorphic class type until after we've parsed the expression; we
1449 // speculatively assume the subexpression is unevaluated, and fix it up
1450 // later.
1451 //
1452 // We enter the unevaluated context before trying to determine whether we
1453 // have a type-id, because the tentative parse logic will try to resolve
1454 // names, and must treat them as unevaluated.
Faisal Valid143a0c2017-04-01 21:30:49 +00001455 EnterExpressionEvaluationContext Unevaluated(
1456 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1457 Sema::ReuseLambdaContextDecl);
Richard Smith4f605af2012-08-18 00:55:03 +00001458
Sebastian Redlc4704762008-11-11 11:37:55 +00001459 if (isTypeIdInParens()) {
Douglas Gregor220cac52009-02-18 17:45:20 +00001460 TypeResult Ty = ParseTypeName();
Sebastian Redlc4704762008-11-11 11:37:55 +00001461
1462 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001463 T.consumeClose();
1464 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001465 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00001466 return ExprError();
Sebastian Redlc4704762008-11-11 11:37:55 +00001467
1468 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallba7bf592010-08-24 05:47:05 +00001469 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001470 } else {
1471 Result = ParseExpression();
1472
1473 // Match the ')'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001474 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001475 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc4704762008-11-11 11:37:55 +00001476 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001477 T.consumeClose();
1478 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001479 if (RParenLoc.isInvalid())
1480 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00001481
Sebastian Redlc4704762008-11-11 11:37:55 +00001482 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001483 Result.get(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001484 }
1485 }
1486
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001487 return Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001488}
1489
Francois Pichet9f4f2072010-09-08 12:20:18 +00001490/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1491///
1492/// '__uuidof' '(' expression ')'
1493/// '__uuidof' '(' type-id ')'
1494///
1495ExprResult Parser::ParseCXXUuidof() {
1496 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1497
1498 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001499 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001500
1501 // __uuidof expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001502 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet9f4f2072010-09-08 12:20:18 +00001503 return ExprError();
1504
1505 ExprResult Result;
1506
1507 if (isTypeIdInParens()) {
1508 TypeResult Ty = ParseTypeName();
1509
1510 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001511 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001512
1513 if (Ty.isInvalid())
1514 return ExprError();
1515
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001516 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
Fangrui Song6907ce22018-07-30 19:24:48 +00001517 Ty.get().getAsOpaquePtr(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001518 T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001519 } else {
Faisal Valid143a0c2017-04-01 21:30:49 +00001520 EnterExpressionEvaluationContext Unevaluated(
1521 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001522 Result = ParseExpression();
1523
1524 // Match the ')'.
1525 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001526 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001527 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001528 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001529
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001530 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1531 /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001532 Result.get(), T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001533 }
1534 }
1535
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001536 return Result;
Francois Pichet9f4f2072010-09-08 12:20:18 +00001537}
1538
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001539/// Parse a C++ pseudo-destructor expression after the base,
Douglas Gregore610ada2010-02-24 18:44:31 +00001540/// . or -> operator, and nested-name-specifier have already been
1541/// parsed.
1542///
1543/// postfix-expression: [C++ 5.2]
1544/// postfix-expression . pseudo-destructor-name
1545/// postfix-expression -> pseudo-destructor-name
1546///
Fangrui Song6907ce22018-07-30 19:24:48 +00001547/// pseudo-destructor-name:
1548/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1549/// ::[opt] nested-name-specifier template simple-template-id ::
1550/// ~type-name
Douglas Gregore610ada2010-02-24 18:44:31 +00001551/// ::[opt] nested-name-specifier[opt] ~type-name
Fangrui Song6907ce22018-07-30 19:24:48 +00001552///
1553ExprResult
Craig Toppera2c51532014-10-30 05:30:05 +00001554Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00001555 tok::TokenKind OpKind,
1556 CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +00001557 ParsedType ObjectType) {
Douglas Gregore610ada2010-02-24 18:44:31 +00001558 // We're parsing either a pseudo-destructor-name or a dependent
1559 // member access that has the same form as a
1560 // pseudo-destructor-name. We parse both in the same way and let
1561 // the action model sort them out.
1562 //
1563 // Note that the ::[opt] nested-name-specifier[opt] has already
1564 // been parsed, and if there was a simple-template-id, it has
1565 // been coalesced into a template-id annotation token.
1566 UnqualifiedId FirstTypeName;
1567 SourceLocation CCLoc;
1568 if (Tok.is(tok::identifier)) {
1569 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1570 ConsumeToken();
1571 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1572 CCLoc = ConsumeToken();
1573 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001574 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1575 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregore610ada2010-02-24 18:44:31 +00001576 FirstTypeName.setTemplateId(
1577 (TemplateIdAnnotation *)Tok.getAnnotationValue());
Richard Smithaf3b3252017-05-18 19:21:48 +00001578 ConsumeAnnotationToken();
Douglas Gregore610ada2010-02-24 18:44:31 +00001579 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1580 CCLoc = ConsumeToken();
1581 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001582 FirstTypeName.setIdentifier(nullptr, SourceLocation());
Douglas Gregore610ada2010-02-24 18:44:31 +00001583 }
1584
1585 // Parse the tilde.
1586 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1587 SourceLocation TildeLoc = ConsumeToken();
David Blaikie1d578782011-12-16 16:03:09 +00001588
1589 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1590 DeclSpec DS(AttrFactory);
Benjamin Kramer198e0832011-12-18 12:18:02 +00001591 ParseDecltypeSpecifier(DS);
Faisal Vali090da2d2018-01-01 18:23:28 +00001592 if (DS.getTypeSpecType() == TST_error)
David Blaikie1d578782011-12-16 16:03:09 +00001593 return ExprError();
David Majnemerced8bdf2015-02-25 17:36:15 +00001594 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1595 TildeLoc, DS);
David Blaikie1d578782011-12-16 16:03:09 +00001596 }
1597
Douglas Gregore610ada2010-02-24 18:44:31 +00001598 if (!Tok.is(tok::identifier)) {
1599 Diag(Tok, diag::err_destructor_tilde_identifier);
1600 return ExprError();
1601 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001602
Douglas Gregore610ada2010-02-24 18:44:31 +00001603 // Parse the second type.
1604 UnqualifiedId SecondTypeName;
1605 IdentifierInfo *Name = Tok.getIdentifierInfo();
1606 SourceLocation NameLoc = ConsumeToken();
1607 SecondTypeName.setIdentifier(Name, NameLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001608
Douglas Gregore610ada2010-02-24 18:44:31 +00001609 // If there is a '<', the second type name is a template-id. Parse
1610 // it as such.
1611 if (Tok.is(tok::less) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +00001612 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1613 Name, NameLoc,
1614 false, ObjectType, SecondTypeName,
1615 /*AssumeTemplateName=*/true))
Douglas Gregore610ada2010-02-24 18:44:31 +00001616 return ExprError();
1617
David Majnemerced8bdf2015-02-25 17:36:15 +00001618 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1619 SS, FirstTypeName, CCLoc, TildeLoc,
1620 SecondTypeName);
Douglas Gregore610ada2010-02-24 18:44:31 +00001621}
1622
Bill Wendling4073ed52007-02-13 01:51:42 +00001623/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1624///
1625/// boolean-literal: [C++ 2.13.5]
1626/// 'true'
1627/// 'false'
John McCalldadc5752010-08-24 06:29:42 +00001628ExprResult Parser::ParseCXXBoolLiteral() {
Bill Wendling4073ed52007-02-13 01:51:42 +00001629 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001630 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Bill Wendling4073ed52007-02-13 01:51:42 +00001631}
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001632
1633/// ParseThrowExpression - This handles the C++ throw expression.
1634///
1635/// throw-expression: [C++ 15]
1636/// 'throw' assignment-expression[opt]
John McCalldadc5752010-08-24 06:29:42 +00001637ExprResult Parser::ParseThrowExpression() {
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001638 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001639 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redld65cea82008-12-11 22:51:44 +00001640
Chris Lattner65dd8432008-04-06 06:02:23 +00001641 // If the current token isn't the start of an assignment-expression,
1642 // then the expression is not present. This handles things like:
1643 // "C ? throw : (void)42", which is crazy but legal.
1644 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1645 case tok::semi:
1646 case tok::r_paren:
1647 case tok::r_square:
1648 case tok::r_brace:
1649 case tok::colon:
1650 case tok::comma:
Craig Topper161e4db2014-05-21 06:02:52 +00001651 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001652
Chris Lattner65dd8432008-04-06 06:02:23 +00001653 default:
John McCalldadc5752010-08-24 06:29:42 +00001654 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001655 if (Expr.isInvalid()) return Expr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001656 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
Chris Lattner65dd8432008-04-06 06:02:23 +00001657 }
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001658}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001659
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001660/// Parse the C++ Coroutines co_yield expression.
Richard Smith0e304ea2015-10-22 04:46:14 +00001661///
1662/// co_yield-expression:
1663/// 'co_yield' assignment-expression[opt]
1664ExprResult Parser::ParseCoyieldExpression() {
1665 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1666
1667 SourceLocation Loc = ConsumeToken();
Richard Smithae3d1472015-11-20 22:47:10 +00001668 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1669 : ParseAssignmentExpression();
Richard Smithcfd53b42015-10-22 06:13:50 +00001670 if (!Expr.isInvalid())
Richard Smith9f690bd2015-10-27 06:02:45 +00001671 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
Richard Smith0e304ea2015-10-22 04:46:14 +00001672 return Expr;
1673}
1674
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001675/// ParseCXXThis - This handles the C++ 'this' pointer.
1676///
1677/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1678/// a non-lvalue expression whose value is the address of the object for which
1679/// the function is called.
John McCalldadc5752010-08-24 06:29:42 +00001680ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001681 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1682 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001683 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001684}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001685
1686/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1687/// Can be interpreted either as function-style casting ("int(x)")
1688/// or class type construction ("ClassType(x,y,z)")
1689/// or creation of a value-initialized type ("int()").
Sebastian Redl3da34892011-06-05 12:23:16 +00001690/// See [C++ 5.2.3].
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001691///
1692/// postfix-expression: [C++ 5.2p1]
Sebastian Redl3da34892011-06-05 12:23:16 +00001693/// simple-type-specifier '(' expression-list[opt] ')'
1694/// [C++0x] simple-type-specifier braced-init-list
1695/// typename-specifier '(' expression-list[opt] ')'
1696/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001697///
Richard Smith600b5262017-01-26 20:40:47 +00001698/// In C++1z onwards, the type specifier can also be a template-name.
John McCalldadc5752010-08-24 06:29:42 +00001699ExprResult
Sebastian Redld65cea82008-12-11 22:51:44 +00001700Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Faisal Vali421b2d12017-12-29 05:41:00 +00001701 Declarator DeclaratorInfo(DS, DeclaratorContext::FunctionalCastContext);
John McCallba7bf592010-08-24 05:47:05 +00001702 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001703
Sebastian Redl3da34892011-06-05 12:23:16 +00001704 assert((Tok.is(tok::l_paren) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001705 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redl3da34892011-06-05 12:23:16 +00001706 && "Expected '(' or '{'!");
Douglas Gregor94a32472011-01-11 00:33:19 +00001707
Sebastian Redl3da34892011-06-05 12:23:16 +00001708 if (Tok.is(tok::l_brace)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001709 ExprResult Init = ParseBraceInitializer();
1710 if (Init.isInvalid())
1711 return Init;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001712 Expr *InitList = Init.get();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001713 return Actions.ActOnCXXTypeConstructExpr(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001714 TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001715 InitList->getEndLoc(), /*ListInitialization=*/true);
Sebastian Redl3da34892011-06-05 12:23:16 +00001716 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001717 BalancedDelimiterTracker T(*this, tok::l_paren);
1718 T.consumeOpen();
Sebastian Redl3da34892011-06-05 12:23:16 +00001719
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00001720 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1721
Benjamin Kramerf0623432012-08-23 22:51:59 +00001722 ExprVector Exprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00001723 CommaLocsTy CommaLocs;
1724
Ilya Biryukovff2a9972019-02-26 11:01:50 +00001725 auto RunSignatureHelp = [&]() {
1726 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
1727 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
1728 DS.getEndLoc(), Exprs, T.getOpenLocation());
1729 CalledSignatureHelp = true;
1730 return PreferredType;
1731 };
1732
Sebastian Redl3da34892011-06-05 12:23:16 +00001733 if (Tok.isNot(tok::r_paren)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00001734 if (ParseExpressionList(Exprs, CommaLocs, [&] {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00001735 PreferredType.enterFunctionArgument(Tok.getLocation(),
1736 RunSignatureHelp);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001737 })) {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00001738 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1739 RunSignatureHelp();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001740 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00001741 return ExprError();
1742 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001743 }
Sebastian Redl3da34892011-06-05 12:23:16 +00001744
1745 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001746 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00001747
1748 // TypeRep could be null, if it references an invalid typedef.
1749 if (!TypeRep)
1750 return ExprError();
1751
1752 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1753 "Unexpected number of commas!");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001754 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1755 Exprs, T.getCloseLocation(),
1756 /*ListInitialization=*/false);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001757 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001758}
1759
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001760/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001761///
1762/// condition:
1763/// expression
1764/// type-specifier-seq declarator '=' assignment-expression
Richard Smith2a15b742012-02-22 06:49:09 +00001765/// [C++11] type-specifier-seq declarator '=' initializer-clause
1766/// [C++11] type-specifier-seq declarator braced-init-list
Zhihao Yuanc81f4532017-12-07 07:03:15 +00001767/// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1768/// brace-or-equal-initializer
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001769/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1770/// '=' assignment-expression
1771///
Richard Smithc7a05a92016-06-29 21:17:59 +00001772/// In C++1z, a condition may in some contexts be preceded by an
1773/// optional init-statement. This function will parse that too.
1774///
1775/// \param InitStmt If non-null, an init-statement is permitted, and if present
1776/// will be parsed and stored here.
1777///
Douglas Gregore60e41a2010-05-06 17:25:47 +00001778/// \param Loc The location of the start of the statement that requires this
1779/// condition, e.g., the "for" in a for loop.
1780///
Richard Smith8baa5002018-09-28 18:44:09 +00001781/// \param FRI If non-null, a for range declaration is permitted, and if
1782/// present will be parsed and stored here, and a null result will be returned.
1783///
Richard Smith03a4aa32016-06-23 19:02:52 +00001784/// \returns The parsed condition.
Richard Smithc7a05a92016-06-29 21:17:59 +00001785Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1786 SourceLocation Loc,
Richard Smith8baa5002018-09-28 18:44:09 +00001787 Sema::ConditionKind CK,
1788 ForRangeInfo *FRI) {
Richard Smithbf5bcf22018-06-26 23:20:26 +00001789 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00001790 PreferredType.enterCondition(Actions, Tok.getLocation());
Richard Smithbf5bcf22018-06-26 23:20:26 +00001791
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001792 if (Tok.is(tok::code_completion)) {
John McCallfaf5fb42010-08-26 23:41:50 +00001793 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001794 cutOffParsing();
Richard Smith03a4aa32016-06-23 19:02:52 +00001795 return Sema::ConditionError();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001796 }
1797
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001798 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001799 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001800
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001801 const auto WarnOnInit = [this, &CK] {
1802 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
1803 ? diag::warn_cxx14_compat_init_statement
1804 : diag::ext_init_statement)
1805 << (CK == Sema::ConditionKind::Switch);
1806 };
1807
Richard Smithc7a05a92016-06-29 21:17:59 +00001808 // Determine what kind of thing we have.
Richard Smith8baa5002018-09-28 18:44:09 +00001809 switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
Richard Smithc7a05a92016-06-29 21:17:59 +00001810 case ConditionOrInitStatement::Expression: {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001811 ProhibitAttributes(attrs);
1812
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001813 // We can have an empty expression here.
1814 // if (; true);
1815 if (InitStmt && Tok.is(tok::semi)) {
1816 WarnOnInit();
Roman Lebedev377748f2018-11-20 18:59:05 +00001817 SourceLocation SemiLoc = Tok.getLocation();
1818 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
1819 Diag(SemiLoc, diag::warn_empty_init_statement)
1820 << (CK == Sema::ConditionKind::Switch)
1821 << FixItHint::CreateRemoval(SemiLoc);
1822 }
1823 ConsumeToken();
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001824 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
1825 return ParseCXXCondition(nullptr, Loc, CK);
1826 }
1827
Douglas Gregore60e41a2010-05-06 17:25:47 +00001828 // Parse the expression.
Richard Smith03a4aa32016-06-23 19:02:52 +00001829 ExprResult Expr = ParseExpression(); // expression
1830 if (Expr.isInvalid())
1831 return Sema::ConditionError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00001832
Richard Smithc7a05a92016-06-29 21:17:59 +00001833 if (InitStmt && Tok.is(tok::semi)) {
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001834 WarnOnInit();
Richard Smithc7a05a92016-06-29 21:17:59 +00001835 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1836 ConsumeToken();
1837 return ParseCXXCondition(nullptr, Loc, CK);
1838 }
1839
Richard Smith03a4aa32016-06-23 19:02:52 +00001840 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001841 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001842
Richard Smithc7a05a92016-06-29 21:17:59 +00001843 case ConditionOrInitStatement::InitStmtDecl: {
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001844 WarnOnInit();
Richard Smithc7a05a92016-06-29 21:17:59 +00001845 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Faisal Vali421b2d12017-12-29 05:41:00 +00001846 DeclGroupPtrTy DG =
1847 ParseSimpleDeclaration(DeclaratorContext::InitStmtContext, DeclEnd,
1848 attrs, /*RequireSemi=*/true);
Richard Smithc7a05a92016-06-29 21:17:59 +00001849 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1850 return ParseCXXCondition(nullptr, Loc, CK);
1851 }
1852
Richard Smith8baa5002018-09-28 18:44:09 +00001853 case ConditionOrInitStatement::ForRangeDecl: {
1854 assert(FRI && "should not parse a for range declaration here");
1855 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1856 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1857 DeclaratorContext::ForContext, DeclEnd, attrs, false, FRI);
1858 FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1859 return Sema::ConditionResult();
1860 }
1861
Richard Smithc7a05a92016-06-29 21:17:59 +00001862 case ConditionOrInitStatement::ConditionDecl:
1863 case ConditionOrInitStatement::Error:
1864 break;
1865 }
1866
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001867 // type-specifier-seq
John McCall084e83d2011-03-24 11:26:52 +00001868 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +00001869 DS.takeAttributesFrom(attrs);
Faisal Vali7db85c52017-12-31 00:06:40 +00001870 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001871
1872 // declarator
Faisal Vali421b2d12017-12-29 05:41:00 +00001873 Declarator DeclaratorInfo(DS, DeclaratorContext::ConditionContext);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001874 ParseDeclarator(DeclaratorInfo);
1875
1876 // simple-asm-expr[opt]
1877 if (Tok.is(tok::kw_asm)) {
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001878 SourceLocation Loc;
John McCalldadc5752010-08-24 06:29:42 +00001879 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001880 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001881 SkipUntil(tok::semi, StopAtSemi);
Richard Smith03a4aa32016-06-23 19:02:52 +00001882 return Sema::ConditionError();
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001883 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001884 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001885 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001886 }
1887
1888 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001889 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001890
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001891 // Type-check the declaration itself.
Fangrui Song6907ce22018-07-30 19:24:48 +00001892 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall53fa7142010-12-24 02:08:15 +00001893 DeclaratorInfo);
Richard Smith03a4aa32016-06-23 19:02:52 +00001894 if (Dcl.isInvalid())
1895 return Sema::ConditionError();
1896 Decl *DeclOut = Dcl.get();
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001897
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001898 // '=' assignment-expression
Richard Trieuc64d3232012-01-18 22:54:52 +00001899 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith2a15b742012-02-22 06:49:09 +00001900 bool CopyInitialization = isTokenEqualOrEqualTypo();
1901 if (CopyInitialization)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001902 ConsumeToken();
Richard Smith2a15b742012-02-22 06:49:09 +00001903
1904 ExprResult InitExpr = ExprError();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001905 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith2a15b742012-02-22 06:49:09 +00001906 Diag(Tok.getLocation(),
1907 diag::warn_cxx98_compat_generalized_initializer_lists);
1908 InitExpr = ParseBraceInitializer();
1909 } else if (CopyInitialization) {
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00001910 PreferredType.enterVariableInit(Tok.getLocation(), DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001911 InitExpr = ParseAssignmentExpression();
1912 } else if (Tok.is(tok::l_paren)) {
1913 // This was probably an attempt to initialize the variable.
1914 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001915 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith2a15b742012-02-22 06:49:09 +00001916 RParen = ConsumeParen();
Richard Smith03a4aa32016-06-23 19:02:52 +00001917 Diag(DeclOut->getLocation(),
Richard Smith2a15b742012-02-22 06:49:09 +00001918 diag::err_expected_init_in_condition_lparen)
1919 << SourceRange(LParen, RParen);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001920 } else {
Richard Smith03a4aa32016-06-23 19:02:52 +00001921 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001922 }
Richard Smith2a15b742012-02-22 06:49:09 +00001923
1924 if (!InitExpr.isInvalid())
Richard Smith3beb7c62017-01-12 02:27:38 +00001925 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
Richard Smith27d807c2013-04-30 13:56:41 +00001926 else
1927 Actions.ActOnInitializerError(DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001928
Richard Smithb2bc2e62011-02-21 20:05:19 +00001929 Actions.FinalizeDeclaration(DeclOut);
Richard Smith03a4aa32016-06-23 19:02:52 +00001930 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001931}
1932
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001933/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1934/// This should only be called when the current token is known to be part of
1935/// simple-type-specifier.
1936///
1937/// simple-type-specifier:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001938/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001939/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1940/// char
1941/// wchar_t
1942/// bool
1943/// short
1944/// int
1945/// long
1946/// signed
1947/// unsigned
1948/// float
1949/// double
1950/// void
1951/// [GNU] typeof-specifier
1952/// [C++0x] auto [TODO]
1953///
1954/// type-name:
1955/// class-name
1956/// enum-name
1957/// typedef-name
1958///
1959void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1960 DS.SetRangeStart(Tok.getLocation());
1961 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +00001962 unsigned DiagID;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001963 SourceLocation Loc = Tok.getLocation();
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001964 const clang::PrintingPolicy &Policy =
1965 Actions.getASTContext().getPrintingPolicy();
Mike Stump11289f42009-09-09 15:08:12 +00001966
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001967 switch (Tok.getKind()) {
Chris Lattner45ddec32009-01-05 00:13:00 +00001968 case tok::identifier: // foo::bar
1969 case tok::coloncolon: // ::foo::bar
David Blaikie83d382b2011-09-23 05:06:16 +00001970 llvm_unreachable("Annotation token should already be formed!");
Mike Stump11289f42009-09-09 15:08:12 +00001971 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001972 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner45ddec32009-01-05 00:13:00 +00001973
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001974 // type-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00001975 case tok::annot_typename: {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001976 if (getTypeAnnotation(Tok))
1977 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001978 getTypeAnnotation(Tok), Policy);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001979 else
1980 DS.SetTypeSpecError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001981
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001982 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00001983 ConsumeAnnotationToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00001984
Craig Topper25122412015-11-15 03:32:11 +00001985 DS.Finish(Actions, Policy);
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001986 return;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001987 }
Mike Stump11289f42009-09-09 15:08:12 +00001988
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001989 // builtin types
1990 case tok::kw_short:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001991 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001992 break;
1993 case tok::kw_long:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001994 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001995 break;
Francois Pichet84133e42011-04-28 01:59:37 +00001996 case tok::kw___int64:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001997 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00001998 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001999 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00002000 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002001 break;
2002 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00002003 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002004 break;
2005 case tok::kw_void:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002006 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002007 break;
2008 case tok::kw_char:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002009 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002010 break;
2011 case tok::kw_int:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002012 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002013 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00002014 case tok::kw___int128:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002015 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00002016 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002017 case tok::kw_half:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002018 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002019 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002020 case tok::kw_float:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002021 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002022 break;
2023 case tok::kw_double:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002024 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002025 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002026 case tok::kw__Float16:
2027 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
2028 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002029 case tok::kw___float128:
2030 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
2031 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002032 case tok::kw_wchar_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002033 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002034 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00002035 case tok::kw_char8_t:
2036 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
2037 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002038 case tok::kw_char16_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002039 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002040 break;
2041 case tok::kw_char32_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002042 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002043 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002044 case tok::kw_bool:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002045 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002046 break;
Anastasia Stulova2c4730d2019-02-15 12:07:57 +00002047#define GENERIC_IMAGE_TYPE(ImgType, Id) \
2048 case tok::kw_##ImgType##_t: \
2049 DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \
2050 Policy); \
2051 break;
2052#include "clang/Basic/OpenCLImageTypes.def"
2053
David Blaikie25896afb2012-01-24 05:47:35 +00002054 case tok::annot_decltype:
2055 case tok::kw_decltype:
2056 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
Craig Topper25122412015-11-15 03:32:11 +00002057 return DS.Finish(Actions, Policy);
Mike Stump11289f42009-09-09 15:08:12 +00002058
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002059 // GNU typeof support.
2060 case tok::kw_typeof:
2061 ParseTypeofSpecifier(DS);
Craig Topper25122412015-11-15 03:32:11 +00002062 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002063 return;
2064 }
Richard Smithaf3b3252017-05-18 19:21:48 +00002065 ConsumeAnyToken();
2066 DS.SetRangeEnd(PrevTokLocation);
Craig Topper25122412015-11-15 03:32:11 +00002067 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002068}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002069
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002070/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2071/// [dcl.name]), which is a non-empty sequence of type-specifiers,
2072/// e.g., "const short int". Note that the DeclSpec is *not* finished
2073/// by parsing the type-specifier-seq, because these sequences are
2074/// typically followed by some form of declarator. Returns true and
2075/// emits diagnostics if this is not a type-specifier-seq, false
2076/// otherwise.
2077///
2078/// type-specifier-seq: [C++ 8.1]
2079/// type-specifier type-specifier-seq[opt]
2080///
2081bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Faisal Vali7db85c52017-12-31 00:06:40 +00002082 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
Craig Topper25122412015-11-15 03:32:11 +00002083 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002084 return false;
2085}
2086
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002087/// Finish parsing a C++ unqualified-id that is a template-id of
Fangrui Song6907ce22018-07-30 19:24:48 +00002088/// some form.
Douglas Gregor7861a802009-11-03 01:35:08 +00002089///
2090/// This routine is invoked when a '<' is encountered after an identifier or
2091/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2092/// whether the unqualified-id is actually a template-id. This routine will
2093/// then parse the template arguments and form the appropriate template-id to
2094/// return to the caller.
2095///
2096/// \param SS the nested-name-specifier that precedes this template-id, if
2097/// we're actually parsing a qualified-id.
2098///
2099/// \param Name for constructor and destructor names, this is the actual
2100/// identifier that may be a template-name.
2101///
Fangrui Song6907ce22018-07-30 19:24:48 +00002102/// \param NameLoc the location of the class-name in a constructor or
Douglas Gregor7861a802009-11-03 01:35:08 +00002103/// destructor.
2104///
Fangrui Song6907ce22018-07-30 19:24:48 +00002105/// \param EnteringContext whether we're entering the scope of the
Douglas Gregor7861a802009-11-03 01:35:08 +00002106/// nested-name-specifier.
2107///
Douglas Gregor127ea592009-11-03 21:24:04 +00002108/// \param ObjectType if this unqualified-id occurs within a member access
2109/// expression, the type of the base object whose member is being accessed.
2110///
Douglas Gregor7861a802009-11-03 01:35:08 +00002111/// \param Id as input, describes the template-name or operator-function-id
2112/// that precedes the '<'. If template arguments were parsed successfully,
2113/// will be updated with the template-id.
Fangrui Song6907ce22018-07-30 19:24:48 +00002114///
Douglas Gregore610ada2010-02-24 18:44:31 +00002115/// \param AssumeTemplateId When true, this routine will assume that the name
Fangrui Song6907ce22018-07-30 19:24:48 +00002116/// refers to a template without performing name lookup to verify.
Douglas Gregore610ada2010-02-24 18:44:31 +00002117///
Douglas Gregor7861a802009-11-03 01:35:08 +00002118/// \returns true if a parse error occurred, false otherwise.
2119bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002120 SourceLocation TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002121 IdentifierInfo *Name,
2122 SourceLocation NameLoc,
2123 bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002124 ParsedType ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00002125 UnqualifiedId &Id,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002126 bool AssumeTemplateId) {
Richard Smithc08b6932018-04-27 02:00:13 +00002127 assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
2128
Douglas Gregor7861a802009-11-03 01:35:08 +00002129 TemplateTy Template;
2130 TemplateNameKind TNK = TNK_Non_template;
2131 switch (Id.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00002132 case UnqualifiedIdKind::IK_Identifier:
2133 case UnqualifiedIdKind::IK_OperatorFunctionId:
2134 case UnqualifiedIdKind::IK_LiteralOperatorId:
Douglas Gregore610ada2010-02-24 18:44:31 +00002135 if (AssumeTemplateId) {
Richard Smithfd3dae02017-01-20 00:20:39 +00002136 // We defer the injected-class-name checks until we've found whether
2137 // this template-id is used to form a nested-name-specifier or not.
2138 TNK = Actions.ActOnDependentTemplateName(
2139 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2140 Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002141 if (TNK == TNK_Non_template)
2142 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00002143 } else {
2144 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002145 TNK = Actions.isTemplateName(getCurScope(), SS,
2146 TemplateKWLoc.isValid(), Id,
2147 ObjectType, EnteringContext, Template,
Douglas Gregor786123d2010-05-21 23:18:07 +00002148 MemberOfUnknownSpecialization);
Richard Smithb23c5e82019-05-09 03:31:27 +00002149 // If lookup found nothing but we're assuming that this is a template
2150 // name, double-check that makes sense syntactically before committing
2151 // to it.
2152 if (TNK == TNK_Undeclared_template &&
2153 isTemplateArgumentList(0) == TPResult::False)
2154 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00002155
Douglas Gregor786123d2010-05-21 23:18:07 +00002156 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
Richard Smithb23c5e82019-05-09 03:31:27 +00002157 ObjectType && isTemplateArgumentList(0) == TPResult::True) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002158 // We have something like t->getAs<T>(), where getAs is a
Douglas Gregor786123d2010-05-21 23:18:07 +00002159 // member of an unknown specialization. However, this will only
2160 // parse correctly as a template, so suggest the keyword 'template'
2161 // before 'getAs' and treat this as a dependent template name.
2162 std::string Name;
Faisal Vali2ab8c152017-12-30 04:15:27 +00002163 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
Douglas Gregor786123d2010-05-21 23:18:07 +00002164 Name = Id.Identifier->getName();
2165 else {
2166 Name = "operator ";
Faisal Vali2ab8c152017-12-30 04:15:27 +00002167 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
Douglas Gregor786123d2010-05-21 23:18:07 +00002168 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2169 else
2170 Name += Id.Identifier->getName();
2171 }
2172 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2173 << Name
2174 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Richard Smithfd3dae02017-01-20 00:20:39 +00002175 TNK = Actions.ActOnDependentTemplateName(
2176 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2177 Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002178 if (TNK == TNK_Non_template)
Fangrui Song6907ce22018-07-30 19:24:48 +00002179 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00002180 }
2181 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002182 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002183
Faisal Vali2ab8c152017-12-30 04:15:27 +00002184 case UnqualifiedIdKind::IK_ConstructorName: {
Douglas Gregor3cf81312009-11-03 23:16:33 +00002185 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002186 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002187 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002188 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002189 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002190 EnteringContext, Template,
2191 MemberOfUnknownSpecialization);
Douglas Gregor7861a802009-11-03 01:35:08 +00002192 break;
2193 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002194
Faisal Vali2ab8c152017-12-30 04:15:27 +00002195 case UnqualifiedIdKind::IK_DestructorName: {
Douglas Gregor3cf81312009-11-03 23:16:33 +00002196 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002197 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002198 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002199 if (ObjectType) {
Richard Smithfd3dae02017-01-20 00:20:39 +00002200 TNK = Actions.ActOnDependentTemplateName(
2201 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2202 EnteringContext, Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002203 if (TNK == TNK_Non_template)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002204 return true;
2205 } else {
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002206 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002207 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002208 EnteringContext, Template,
2209 MemberOfUnknownSpecialization);
Fangrui Song6907ce22018-07-30 19:24:48 +00002210
John McCallba7bf592010-08-24 05:47:05 +00002211 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002212 Diag(NameLoc, diag::err_destructor_template_id)
2213 << Name << SS.getRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00002214 return true;
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002215 }
2216 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002217 break;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002218 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002219
Douglas Gregor7861a802009-11-03 01:35:08 +00002220 default:
2221 return false;
2222 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002223
Douglas Gregor7861a802009-11-03 01:35:08 +00002224 if (TNK == TNK_Non_template)
2225 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00002226
Douglas Gregor7861a802009-11-03 01:35:08 +00002227 // Parse the enclosed template argument list.
2228 SourceLocation LAngleLoc, RAngleLoc;
2229 TemplateArgList TemplateArgs;
Richard Smithc08b6932018-04-27 02:00:13 +00002230 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
2231 RAngleLoc))
Douglas Gregor7861a802009-11-03 01:35:08 +00002232 return true;
Richard Smithc08b6932018-04-27 02:00:13 +00002233
Faisal Vali2ab8c152017-12-30 04:15:27 +00002234 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2235 Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2236 Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002237 // Form a parsed representation of the template-id to be stored in the
2238 // UnqualifiedId.
Douglas Gregor7861a802009-11-03 01:35:08 +00002239
Richard Smith72bfbd82013-12-04 00:28:23 +00002240 // FIXME: Store name for literal operator too.
Faisal Vali43caf672017-05-23 01:07:12 +00002241 IdentifierInfo *TemplateII =
Faisal Vali2ab8c152017-12-30 04:15:27 +00002242 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2243 : nullptr;
2244 OverloadedOperatorKind OpKind =
2245 Id.getKind() == UnqualifiedIdKind::IK_Identifier
2246 ? OO_None
2247 : Id.OperatorFunctionId.Operator;
Douglas Gregor7861a802009-11-03 01:35:08 +00002248
Faisal Vali43caf672017-05-23 01:07:12 +00002249 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2250 SS, TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2251 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
2252
Douglas Gregor7861a802009-11-03 01:35:08 +00002253 Id.setTemplateId(TemplateId);
2254 return false;
2255 }
2256
2257 // Bundle the template arguments together.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002258 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnara4244b432012-01-27 08:46:19 +00002259
Douglas Gregor7861a802009-11-03 01:35:08 +00002260 // Constructor and destructor names.
Richard Smithb23c5e82019-05-09 03:31:27 +00002261 TypeResult Type = Actions.ActOnTemplateIdType(
2262 getCurScope(), SS, TemplateKWLoc, Template, Name, NameLoc, LAngleLoc,
2263 TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true);
Douglas Gregor7861a802009-11-03 01:35:08 +00002264 if (Type.isInvalid())
2265 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002266
Faisal Vali2ab8c152017-12-30 04:15:27 +00002267 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
Douglas Gregor7861a802009-11-03 01:35:08 +00002268 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2269 else
2270 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00002271
Douglas Gregor7861a802009-11-03 01:35:08 +00002272 return false;
2273}
2274
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002275/// Parse an operator-function-id or conversion-function-id as part
Douglas Gregor71395fa2009-11-04 00:56:37 +00002276/// of a C++ unqualified-id.
2277///
2278/// This routine is responsible only for parsing the operator-function-id or
2279/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor7861a802009-11-03 01:35:08 +00002280///
2281/// \code
Douglas Gregor7861a802009-11-03 01:35:08 +00002282/// operator-function-id: [C++ 13.5]
2283/// 'operator' operator
2284///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002285/// operator: one of
Douglas Gregor7861a802009-11-03 01:35:08 +00002286/// new delete new[] delete[]
2287/// + - * / % ^ & | ~
2288/// ! = < > += -= *= /= %=
2289/// ^= &= |= << >> >>= <<= == !=
2290/// <= >= && || ++ -- , ->* ->
Richard Smithd30b23d2017-12-01 02:13:10 +00002291/// () [] <=>
Douglas Gregor7861a802009-11-03 01:35:08 +00002292///
2293/// conversion-function-id: [C++ 12.3.2]
2294/// operator conversion-type-id
2295///
2296/// conversion-type-id:
2297/// type-specifier-seq conversion-declarator[opt]
2298///
2299/// conversion-declarator:
2300/// ptr-operator conversion-declarator[opt]
2301/// \endcode
2302///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002303/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor7861a802009-11-03 01:35:08 +00002304/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2305///
Fangrui Song6907ce22018-07-30 19:24:48 +00002306/// \param EnteringContext whether we are entering the scope of the
Douglas Gregor7861a802009-11-03 01:35:08 +00002307/// nested-name-specifier.
2308///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002309/// \param ObjectType if this unqualified-id occurs within a member access
2310/// expression, the type of the base object whose member is being accessed.
2311///
2312/// \param Result on a successful parse, contains the parsed unqualified-id.
2313///
2314/// \returns true if parsing fails, false otherwise.
2315bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002316 ParsedType ObjectType,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002317 UnqualifiedId &Result) {
2318 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
Fangrui Song6907ce22018-07-30 19:24:48 +00002319
Douglas Gregor71395fa2009-11-04 00:56:37 +00002320 // Consume the 'operator' keyword.
2321 SourceLocation KeywordLoc = ConsumeToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00002322
Douglas Gregor71395fa2009-11-04 00:56:37 +00002323 // Determine what kind of operator name we have.
2324 unsigned SymbolIdx = 0;
2325 SourceLocation SymbolLocations[3];
2326 OverloadedOperatorKind Op = OO_None;
2327 switch (Tok.getKind()) {
2328 case tok::kw_new:
2329 case tok::kw_delete: {
2330 bool isNew = Tok.getKind() == tok::kw_new;
2331 // Consume the 'new' or 'delete'.
2332 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002333 // Check for array new/delete.
2334 if (Tok.is(tok::l_square) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002335 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002336 // Consume the '[' and ']'.
2337 BalancedDelimiterTracker T(*this, tok::l_square);
2338 T.consumeOpen();
2339 T.consumeClose();
2340 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002341 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002342
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002343 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2344 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002345 Op = isNew? OO_Array_New : OO_Array_Delete;
2346 } else {
2347 Op = isNew? OO_New : OO_Delete;
2348 }
2349 break;
2350 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002351
Douglas Gregor71395fa2009-11-04 00:56:37 +00002352#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2353 case tok::Token: \
2354 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2355 Op = OO_##Name; \
2356 break;
2357#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2358#include "clang/Basic/OperatorKinds.def"
Fangrui Song6907ce22018-07-30 19:24:48 +00002359
Douglas Gregor71395fa2009-11-04 00:56:37 +00002360 case tok::l_paren: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002361 // Consume the '(' and ')'.
2362 BalancedDelimiterTracker T(*this, tok::l_paren);
2363 T.consumeOpen();
2364 T.consumeClose();
2365 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002366 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002367
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002368 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2369 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002370 Op = OO_Call;
2371 break;
2372 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002373
Douglas Gregor71395fa2009-11-04 00:56:37 +00002374 case tok::l_square: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002375 // Consume the '[' and ']'.
2376 BalancedDelimiterTracker T(*this, tok::l_square);
2377 T.consumeOpen();
2378 T.consumeClose();
2379 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002380 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002381
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002382 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2383 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002384 Op = OO_Subscript;
2385 break;
2386 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002387
Douglas Gregor71395fa2009-11-04 00:56:37 +00002388 case tok::code_completion: {
2389 // Code completion for the operator name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002390 Actions.CodeCompleteOperatorName(getCurScope());
Fangrui Song6907ce22018-07-30 19:24:48 +00002391 cutOffParsing();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002392 // Don't try to parse any further.
2393 return true;
2394 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002395
Douglas Gregor71395fa2009-11-04 00:56:37 +00002396 default:
2397 break;
2398 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002399
Douglas Gregor71395fa2009-11-04 00:56:37 +00002400 if (Op != OO_None) {
2401 // We have parsed an operator-function-id.
2402 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2403 return false;
2404 }
Alexis Hunt34458502009-11-28 04:44:28 +00002405
2406 // Parse a literal-operator-id.
2407 //
Richard Smith6f212062012-10-20 08:41:10 +00002408 // literal-operator-id: C++11 [over.literal]
2409 // operator string-literal identifier
2410 // operator user-defined-string-literal
Alexis Hunt34458502009-11-28 04:44:28 +00002411
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002412 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002413 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Alexis Hunt34458502009-11-28 04:44:28 +00002414
Richard Smith7d182a72012-03-08 23:06:02 +00002415 SourceLocation DiagLoc;
2416 unsigned DiagId = 0;
2417
2418 // We're past translation phase 6, so perform string literal concatenation
2419 // before checking for "".
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002420 SmallVector<Token, 4> Toks;
2421 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith7d182a72012-03-08 23:06:02 +00002422 while (isTokenStringLiteral()) {
2423 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smith6f212062012-10-20 08:41:10 +00002424 // C++11 [over.literal]p1:
2425 // The string-literal or user-defined-string-literal in a
2426 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith7d182a72012-03-08 23:06:02 +00002427 DiagLoc = Tok.getLocation();
2428 DiagId = diag::err_literal_operator_string_prefix;
2429 }
2430 Toks.push_back(Tok);
2431 TokLocs.push_back(ConsumeStringToken());
2432 }
2433
Craig Topper9d5583e2014-06-26 04:58:39 +00002434 StringLiteralParser Literal(Toks, PP);
Richard Smith7d182a72012-03-08 23:06:02 +00002435 if (Literal.hadError)
2436 return true;
2437
2438 // Grab the literal operator's suffix, which will be either the next token
2439 // or a ud-suffix from the string literal.
Craig Topper161e4db2014-05-21 06:02:52 +00002440 IdentifierInfo *II = nullptr;
Richard Smith7d182a72012-03-08 23:06:02 +00002441 SourceLocation SuffixLoc;
2442 if (!Literal.getUDSuffix().empty()) {
2443 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2444 SuffixLoc =
2445 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2446 Literal.getUDSuffixOffset(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002447 PP.getSourceManager(), getLangOpts());
Richard Smith7d182a72012-03-08 23:06:02 +00002448 } else if (Tok.is(tok::identifier)) {
2449 II = Tok.getIdentifierInfo();
2450 SuffixLoc = ConsumeToken();
2451 TokLocs.push_back(SuffixLoc);
2452 } else {
Alp Tokerec543272013-12-24 09:48:30 +00002453 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexis Hunt34458502009-11-28 04:44:28 +00002454 return true;
2455 }
2456
Richard Smith7d182a72012-03-08 23:06:02 +00002457 // The string literal must be empty.
2458 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smith6f212062012-10-20 08:41:10 +00002459 // C++11 [over.literal]p1:
2460 // The string-literal or user-defined-string-literal in a
2461 // literal-operator-id shall [...] contain no characters
2462 // other than the implicit terminating '\0'.
Richard Smith7d182a72012-03-08 23:06:02 +00002463 DiagLoc = TokLocs.front();
2464 DiagId = diag::err_literal_operator_string_not_empty;
2465 }
2466
2467 if (DiagId) {
2468 // This isn't a valid literal-operator-id, but we think we know
2469 // what the user meant. Tell them what they should have written.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002470 SmallString<32> Str;
Richard Smithe87aeb32015-10-08 00:17:59 +00002471 Str += "\"\"";
Richard Smith7d182a72012-03-08 23:06:02 +00002472 Str += II->getName();
2473 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2474 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2475 }
2476
2477 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Richard Smithd091dc12013-12-05 00:58:33 +00002478
2479 return Actions.checkLiteralOperatorId(SS, Result);
Alexis Hunt34458502009-11-28 04:44:28 +00002480 }
Richard Smithd091dc12013-12-05 00:58:33 +00002481
Douglas Gregor71395fa2009-11-04 00:56:37 +00002482 // Parse a conversion-function-id.
2483 //
2484 // conversion-function-id: [C++ 12.3.2]
2485 // operator conversion-type-id
2486 //
2487 // conversion-type-id:
2488 // type-specifier-seq conversion-declarator[opt]
2489 //
2490 // conversion-declarator:
2491 // ptr-operator conversion-declarator[opt]
Fangrui Song6907ce22018-07-30 19:24:48 +00002492
Douglas Gregor71395fa2009-11-04 00:56:37 +00002493 // Parse the type-specifier-seq.
John McCall084e83d2011-03-24 11:26:52 +00002494 DeclSpec DS(AttrFactory);
Douglas Gregora25d65d2009-11-20 22:03:38 +00002495 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregor71395fa2009-11-04 00:56:37 +00002496 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002497
Douglas Gregor71395fa2009-11-04 00:56:37 +00002498 // Parse the conversion-declarator, which is merely a sequence of
2499 // ptr-operators.
Faisal Vali421b2d12017-12-29 05:41:00 +00002500 Declarator D(DS, DeclaratorContext::ConversionIdContext);
Craig Topper161e4db2014-05-21 06:02:52 +00002501 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2502
Douglas Gregor71395fa2009-11-04 00:56:37 +00002503 // Finish up the type.
John McCallfaf5fb42010-08-26 23:41:50 +00002504 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002505 if (Ty.isInvalid())
2506 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002507
Douglas Gregor71395fa2009-11-04 00:56:37 +00002508 // Note that this is a conversion-function-id.
Fangrui Song6907ce22018-07-30 19:24:48 +00002509 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
Douglas Gregor71395fa2009-11-04 00:56:37 +00002510 D.getSourceRange().getEnd());
Fangrui Song6907ce22018-07-30 19:24:48 +00002511 return false;
Douglas Gregor71395fa2009-11-04 00:56:37 +00002512}
2513
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002514/// Parse a C++ unqualified-id (or a C identifier), which describes the
Douglas Gregor71395fa2009-11-04 00:56:37 +00002515/// name of an entity.
2516///
2517/// \code
2518/// unqualified-id: [C++ expr.prim.general]
2519/// identifier
2520/// operator-function-id
2521/// conversion-function-id
2522/// [C++0x] literal-operator-id [TODO]
2523/// ~ class-name
2524/// template-id
2525///
2526/// \endcode
2527///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002528/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor71395fa2009-11-04 00:56:37 +00002529/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2530///
Fangrui Song6907ce22018-07-30 19:24:48 +00002531/// \param EnteringContext whether we are entering the scope of the
Douglas Gregor71395fa2009-11-04 00:56:37 +00002532/// nested-name-specifier.
2533///
Douglas Gregor7861a802009-11-03 01:35:08 +00002534/// \param AllowDestructorName whether we allow parsing of a destructor name.
2535///
2536/// \param AllowConstructorName whether we allow parsing a constructor name.
2537///
Richard Smith35845152017-02-07 01:37:30 +00002538/// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2539///
Douglas Gregor127ea592009-11-03 21:24:04 +00002540/// \param ObjectType if this unqualified-id occurs within a member access
2541/// expression, the type of the base object whose member is being accessed.
2542///
Douglas Gregor7861a802009-11-03 01:35:08 +00002543/// \param Result on a successful parse, contains the parsed unqualified-id.
2544///
2545/// \returns true if parsing fails, false otherwise.
2546bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2547 bool AllowDestructorName,
2548 bool AllowConstructorName,
Richard Smith35845152017-02-07 01:37:30 +00002549 bool AllowDeductionGuide,
John McCallba7bf592010-08-24 05:47:05 +00002550 ParsedType ObjectType,
Richard Smithc08b6932018-04-27 02:00:13 +00002551 SourceLocation *TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002552 UnqualifiedId &Result) {
Richard Smithc08b6932018-04-27 02:00:13 +00002553 if (TemplateKWLoc)
2554 *TemplateKWLoc = SourceLocation();
Douglas Gregorb22ee882010-05-05 05:58:24 +00002555
2556 // Handle 'A::template B'. This is for template-ids which have not
2557 // already been annotated by ParseOptionalCXXScopeSpecifier().
2558 bool TemplateSpecified = false;
Richard Smithc08b6932018-04-27 02:00:13 +00002559 if (Tok.is(tok::kw_template)) {
2560 if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2561 TemplateSpecified = true;
2562 *TemplateKWLoc = ConsumeToken();
2563 } else {
2564 SourceLocation TemplateLoc = ConsumeToken();
2565 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2566 << FixItHint::CreateRemoval(TemplateLoc);
2567 }
Douglas Gregorb22ee882010-05-05 05:58:24 +00002568 }
2569
Douglas Gregor7861a802009-11-03 01:35:08 +00002570 // unqualified-id:
2571 // identifier
2572 // template-id (when it hasn't already been annotated)
2573 if (Tok.is(tok::identifier)) {
2574 // Consume the identifier.
2575 IdentifierInfo *Id = Tok.getIdentifierInfo();
2576 SourceLocation IdLoc = ConsumeToken();
2577
David Blaikiebbafb8a2012-03-11 07:00:24 +00002578 if (!getLangOpts().CPlusPlus) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002579 // If we're not in C++, only identifiers matter. Record the
2580 // identifier and return.
2581 Result.setIdentifier(Id, IdLoc);
2582 return false;
2583 }
2584
Richard Smith35845152017-02-07 01:37:30 +00002585 ParsedTemplateTy TemplateName;
Fangrui Song6907ce22018-07-30 19:24:48 +00002586 if (AllowConstructorName &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002587 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002588 // We have parsed a constructor name.
Richard Smith69bc9aa2018-06-22 19:50:19 +00002589 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2590 EnteringContext);
Richard Smith715ee072018-06-20 21:58:20 +00002591 if (!Ty)
2592 return true;
Abramo Bagnara4244b432012-01-27 08:46:19 +00002593 Result.setConstructorName(Ty, IdLoc, IdLoc);
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002594 } else if (getLangOpts().CPlusPlus17 &&
Richard Smith35845152017-02-07 01:37:30 +00002595 AllowDeductionGuide && SS.isEmpty() &&
2596 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2597 &TemplateName)) {
2598 // We have parsed a template-name naming a deduction guide.
2599 Result.setDeductionGuideName(TemplateName, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002600 } else {
2601 // We have parsed an identifier.
Fangrui Song6907ce22018-07-30 19:24:48 +00002602 Result.setIdentifier(Id, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002603 }
2604
2605 // If the next token is a '<', we may have a template.
Richard Smithc08b6932018-04-27 02:00:13 +00002606 TemplateTy Template;
2607 if (Tok.is(tok::less))
2608 return ParseUnqualifiedIdTemplateId(
2609 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2610 EnteringContext, ObjectType, Result, TemplateSpecified);
2611 else if (TemplateSpecified &&
2612 Actions.ActOnDependentTemplateName(
2613 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2614 EnteringContext, Template,
2615 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2616 return true;
2617
Douglas Gregor7861a802009-11-03 01:35:08 +00002618 return false;
2619 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002620
Douglas Gregor7861a802009-11-03 01:35:08 +00002621 // unqualified-id:
2622 // template-id (already parsed and annotated)
2623 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00002624 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002625
Fangrui Song6907ce22018-07-30 19:24:48 +00002626 // If the template-name names the current class, then this is a constructor
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002627 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002628 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002629 if (SS.isSet()) {
2630 // C++ [class.qual]p2 specifies that a qualified template-name
2631 // is taken as the constructor name where a constructor can be
2632 // declared. Thus, the template arguments are extraneous, so
2633 // complain about them and remove them entirely.
Fangrui Song6907ce22018-07-30 19:24:48 +00002634 Diag(TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002635 diag::err_out_of_line_constructor_template_id)
2636 << TemplateId->Name
Douglas Gregora771f462010-03-31 17:46:05 +00002637 << FixItHint::CreateRemoval(
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002638 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Richard Smith715ee072018-06-20 21:58:20 +00002639 ParsedType Ty = Actions.getConstructorName(
Richard Smith69bc9aa2018-06-22 19:50:19 +00002640 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2641 EnteringContext);
Richard Smith715ee072018-06-20 21:58:20 +00002642 if (!Ty)
2643 return true;
Abramo Bagnara4244b432012-01-27 08:46:19 +00002644 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002645 TemplateId->RAngleLoc);
Richard Smithaf3b3252017-05-18 19:21:48 +00002646 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002647 return false;
2648 }
2649
2650 Result.setConstructorTemplateId(TemplateId);
Richard Smithaf3b3252017-05-18 19:21:48 +00002651 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002652 return false;
2653 }
2654
Douglas Gregor7861a802009-11-03 01:35:08 +00002655 // We have already parsed a template-id; consume the annotation token as
2656 // our unqualified-id.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002657 Result.setTemplateId(TemplateId);
Richard Smithc08b6932018-04-27 02:00:13 +00002658 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2659 if (TemplateLoc.isValid()) {
2660 if (TemplateKWLoc && (ObjectType || SS.isSet()))
2661 *TemplateKWLoc = TemplateLoc;
2662 else
2663 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2664 << FixItHint::CreateRemoval(TemplateLoc);
2665 }
Richard Smithaf3b3252017-05-18 19:21:48 +00002666 ConsumeAnnotationToken();
Douglas Gregor7861a802009-11-03 01:35:08 +00002667 return false;
2668 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002669
Douglas Gregor7861a802009-11-03 01:35:08 +00002670 // unqualified-id:
2671 // operator-function-id
2672 // conversion-function-id
2673 if (Tok.is(tok::kw_operator)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00002674 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor7861a802009-11-03 01:35:08 +00002675 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002676
Alexis Hunted0530f2009-11-28 08:58:14 +00002677 // If we have an operator-function-id or a literal-operator-id and the next
2678 // token is a '<', we may have a
Fangrui Song6907ce22018-07-30 19:24:48 +00002679 //
Douglas Gregor71395fa2009-11-04 00:56:37 +00002680 // template-id:
2681 // operator-function-id < template-argument-list[opt] >
Richard Smithc08b6932018-04-27 02:00:13 +00002682 TemplateTy Template;
Faisal Vali2ab8c152017-12-30 04:15:27 +00002683 if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2684 Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
Richard Smithc08b6932018-04-27 02:00:13 +00002685 Tok.is(tok::less))
2686 return ParseUnqualifiedIdTemplateId(
2687 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2688 SourceLocation(), EnteringContext, ObjectType, Result,
2689 TemplateSpecified);
2690 else if (TemplateSpecified &&
2691 Actions.ActOnDependentTemplateName(
2692 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2693 EnteringContext, Template,
2694 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2695 return true;
Craig Topper161e4db2014-05-21 06:02:52 +00002696
Douglas Gregor7861a802009-11-03 01:35:08 +00002697 return false;
2698 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002699
2700 if (getLangOpts().CPlusPlus &&
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002701 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002702 // C++ [expr.unary.op]p10:
Fangrui Song6907ce22018-07-30 19:24:48 +00002703 // There is an ambiguity in the unary-expression ~X(), where X is a
2704 // class-name. The ambiguity is resolved in favor of treating ~ as a
Douglas Gregor7861a802009-11-03 01:35:08 +00002705 // unary complement rather than treating ~X as referring to a destructor.
Fangrui Song6907ce22018-07-30 19:24:48 +00002706
Douglas Gregor7861a802009-11-03 01:35:08 +00002707 // Parse the '~'.
2708 SourceLocation TildeLoc = ConsumeToken();
David Blaikieecd8a942011-12-08 16:13:53 +00002709
2710 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2711 DeclSpec DS(AttrFactory);
2712 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Richard Smithef2cd8f2017-02-08 20:39:08 +00002713 if (ParsedType Type =
2714 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
David Blaikieecd8a942011-12-08 16:13:53 +00002715 Result.setDestructorName(TildeLoc, Type, EndLoc);
2716 return false;
2717 }
2718 return true;
2719 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002720
Douglas Gregor7861a802009-11-03 01:35:08 +00002721 // Parse the class-name.
2722 if (Tok.isNot(tok::identifier)) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002723 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00002724 return true;
2725 }
2726
Richard Smithefa6f732014-09-06 02:06:12 +00002727 // If the user wrote ~T::T, correct it to T::~T.
Richard Smith64e033f2015-01-15 00:48:52 +00002728 DeclaratorScopeObj DeclScopeObj(*this, SS);
Nico Weber10d02b52015-02-02 04:18:38 +00002729 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
Nico Weberf9e37be2015-01-30 16:53:11 +00002730 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2731 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2732 // it will confuse this recovery logic.
2733 ColonProtectionRAIIObject ColonRAII(*this, false);
2734
Richard Smithefa6f732014-09-06 02:06:12 +00002735 if (SS.isSet()) {
2736 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2737 SS.clear();
2738 }
2739 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2740 return true;
Nico Weber7f8ec522015-02-02 05:33:50 +00002741 if (SS.isNotEmpty())
David Blaikieefdccaa2016-01-15 23:43:34 +00002742 ObjectType = nullptr;
Nico Weberd0045862015-01-30 04:05:15 +00002743 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
Benjamin Kramer3012e592015-03-29 14:35:39 +00002744 !SS.isSet()) {
Richard Smithefa6f732014-09-06 02:06:12 +00002745 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2746 return true;
2747 }
2748
2749 // Recover as if the tilde had been written before the identifier.
2750 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2751 << FixItHint::CreateRemoval(TildeLoc)
2752 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
Richard Smith64e033f2015-01-15 00:48:52 +00002753
2754 // Temporarily enter the scope for the rest of this function.
2755 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2756 DeclScopeObj.EnterDeclaratorScope();
Richard Smithefa6f732014-09-06 02:06:12 +00002757 }
2758
Douglas Gregor7861a802009-11-03 01:35:08 +00002759 // Parse the class-name (or template-name in a simple-template-id).
2760 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2761 SourceLocation ClassNameLoc = ConsumeToken();
Richard Smithefa6f732014-09-06 02:06:12 +00002762
Richard Smithc08b6932018-04-27 02:00:13 +00002763 if (Tok.is(tok::less)) {
David Blaikieefdccaa2016-01-15 23:43:34 +00002764 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
Richard Smithc08b6932018-04-27 02:00:13 +00002765 return ParseUnqualifiedIdTemplateId(
2766 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
2767 ClassNameLoc, EnteringContext, ObjectType, Result, TemplateSpecified);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002768 }
Richard Smithefa6f732014-09-06 02:06:12 +00002769
Douglas Gregor7861a802009-11-03 01:35:08 +00002770 // Note that this is a destructor name.
Fangrui Song6907ce22018-07-30 19:24:48 +00002771 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
John McCallba7bf592010-08-24 05:47:05 +00002772 ClassNameLoc, getCurScope(),
2773 SS, ObjectType,
2774 EnteringContext);
Douglas Gregorfe17d252010-02-16 19:09:40 +00002775 if (!Ty)
Douglas Gregor7861a802009-11-03 01:35:08 +00002776 return true;
Douglas Gregorfe17d252010-02-16 19:09:40 +00002777
Douglas Gregor7861a802009-11-03 01:35:08 +00002778 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002779 return false;
2780 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002781
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002782 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002783 << getLangOpts().CPlusPlus;
Douglas Gregor7861a802009-11-03 01:35:08 +00002784 return true;
2785}
2786
Sebastian Redlbd150f42008-11-21 19:14:01 +00002787/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2788/// memory in a typesafe manner and call constructors.
Mike Stump11289f42009-09-09 15:08:12 +00002789///
Chris Lattner109faf22009-01-04 21:25:24 +00002790/// This method is called to parse the new expression after the optional :: has
2791/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2792/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002793///
2794/// new-expression:
2795/// '::'[opt] 'new' new-placement[opt] new-type-id
2796/// new-initializer[opt]
2797/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2798/// new-initializer[opt]
2799///
2800/// new-placement:
2801/// '(' expression-list ')'
2802///
Sebastian Redl351bb782008-12-02 14:43:59 +00002803/// new-type-id:
2804/// type-specifier-seq new-declarator[opt]
Douglas Gregora3a020a2011-04-15 19:40:02 +00002805/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redl351bb782008-12-02 14:43:59 +00002806///
2807/// new-declarator:
2808/// ptr-operator new-declarator[opt]
2809/// direct-new-declarator
2810///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002811/// new-initializer:
2812/// '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00002813/// [C++0x] braced-init-list
Sebastian Redlbd150f42008-11-21 19:14:01 +00002814///
John McCalldadc5752010-08-24 06:29:42 +00002815ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002816Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2817 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2818 ConsumeToken(); // Consume 'new'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002819
2820 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2821 // second form of new-expression. It can't be a new-type-id.
2822
Benjamin Kramerf0623432012-08-23 22:51:59 +00002823 ExprVector PlacementArgs;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002824 SourceLocation PlacementLParen, PlacementRParen;
2825
Douglas Gregorf2753b32010-07-13 15:54:32 +00002826 SourceRange TypeIdParens;
John McCall084e83d2011-03-24 11:26:52 +00002827 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00002828 Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNewContext);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002829 if (Tok.is(tok::l_paren)) {
2830 // If it turns out to be a placement, we change the type location.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002831 BalancedDelimiterTracker T(*this, tok::l_paren);
2832 T.consumeOpen();
2833 PlacementLParen = T.getOpenLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002834 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002835 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002836 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002837 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002838
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002839 T.consumeClose();
2840 PlacementRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002841 if (PlacementRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002842 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002843 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002844 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002845
Sebastian Redl351bb782008-12-02 14:43:59 +00002846 if (PlacementArgs.empty()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002847 // Reset the placement locations. There was no placement.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002848 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002849 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002850 } else {
2851 // We still need the type.
2852 if (Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002853 BalancedDelimiterTracker T(*this, tok::l_paren);
2854 T.consumeOpen();
Douglas Gregora3a020a2011-04-15 19:40:02 +00002855 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002856 ParseSpecifierQualifierList(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002857 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002858 ParseDeclarator(DeclaratorInfo);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002859 T.consumeClose();
2860 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002861 } else {
Douglas Gregora3a020a2011-04-15 19:40:02 +00002862 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002863 if (ParseCXXTypeSpecifierSeq(DS))
2864 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002865 else {
2866 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002867 ParseDeclaratorInternal(DeclaratorInfo,
2868 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002869 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002870 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002871 }
2872 } else {
Sebastian Redl351bb782008-12-02 14:43:59 +00002873 // A new-type-id is a simplified type-id, where essentially the
2874 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregora3a020a2011-04-15 19:40:02 +00002875 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002876 if (ParseCXXTypeSpecifierSeq(DS))
2877 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002878 else {
2879 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002880 ParseDeclaratorInternal(DeclaratorInfo,
2881 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002882 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002883 }
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002884 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002885 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002886 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002887 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002888
Sebastian Redl6047f072012-02-16 12:22:20 +00002889 ExprResult Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002890
2891 if (Tok.is(tok::l_paren)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00002892 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002893 ExprVector ConstructorArgs;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002894 BalancedDelimiterTracker T(*this, tok::l_paren);
2895 T.consumeOpen();
2896 ConstructorLParen = T.getOpenLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002897 if (Tok.isNot(tok::r_paren)) {
2898 CommaLocsTy CommaLocs;
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002899 auto RunSignatureHelp = [&]() {
2900 ParsedType TypeRep =
2901 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
2902 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2903 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
2904 DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
2905 CalledSignatureHelp = true;
2906 return PreferredType;
2907 };
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002908 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002909 PreferredType.enterFunctionArgument(Tok.getLocation(),
2910 RunSignatureHelp);
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002911 })) {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002912 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
2913 RunSignatureHelp();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002914 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002915 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002916 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002917 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002918 T.consumeClose();
2919 ConstructorRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002920 if (ConstructorRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002921 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002922 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002923 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002924 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2925 ConstructorRParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002926 ConstructorArgs);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002927 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002928 Diag(Tok.getLocation(),
2929 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl6047f072012-02-16 12:22:20 +00002930 Initializer = ParseBraceInitializer();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002931 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002932 if (Initializer.isInvalid())
2933 return Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002934
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002935 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002936 PlacementArgs, PlacementRParen,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002937 TypeIdParens, DeclaratorInfo, Initializer.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002938}
2939
Sebastian Redlbd150f42008-11-21 19:14:01 +00002940/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2941/// passed to ParseDeclaratorInternal.
2942///
2943/// direct-new-declarator:
Richard Smithb9fb1212019-05-06 03:47:15 +00002944/// '[' expression[opt] ']'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002945/// direct-new-declarator '[' constant-expression ']'
2946///
Chris Lattner109faf22009-01-04 21:25:24 +00002947void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002948 // Parse the array dimensions.
Richard Smithb9fb1212019-05-06 03:47:15 +00002949 bool First = true;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002950 while (Tok.is(tok::l_square)) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002951 // An array-size expression can't start with a lambda.
2952 if (CheckProhibitedCXX11Attribute())
2953 continue;
2954
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002955 BalancedDelimiterTracker T(*this, tok::l_square);
2956 T.consumeOpen();
2957
Richard Smithb9fb1212019-05-06 03:47:15 +00002958 ExprResult Size =
2959 First ? (Tok.is(tok::r_square) ? ExprResult() : ParseExpression())
2960 : ParseConstantExpression();
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002961 if (Size.isInvalid()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002962 // Recover
Alexey Bataevee6507d2013-11-18 08:17:37 +00002963 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002964 return;
2965 }
Richard Smithb9fb1212019-05-06 03:47:15 +00002966 First = false;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002967
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002968 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00002969
Bill Wendling44426052012-12-20 19:22:21 +00002970 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002971 ParsedAttributes Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002972 MaybeParseCXX11Attributes(Attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002973
John McCall084e83d2011-03-24 11:26:52 +00002974 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall53fa7142010-12-24 02:08:15 +00002975 /*static=*/false, /*star=*/false,
Erich Keanec480f302018-07-12 21:09:05 +00002976 Size.get(), T.getOpenLocation(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002977 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00002978 std::move(Attrs), T.getCloseLocation());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002979
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002980 if (T.getCloseLocation().isInvalid())
Sebastian Redlbd150f42008-11-21 19:14:01 +00002981 return;
2982 }
2983}
2984
2985/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2986/// This ambiguity appears in the syntax of the C++ new operator.
2987///
2988/// new-expression:
2989/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2990/// new-initializer[opt]
2991///
2992/// new-placement:
2993/// '(' expression-list ')'
2994///
John McCall37ad5512010-08-23 06:44:23 +00002995bool Parser::ParseExpressionListOrTypeId(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002996 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner109faf22009-01-04 21:25:24 +00002997 Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002998 // The '(' was already consumed.
2999 if (isTypeIdInParens()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00003000 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00003001 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00003002 ParseDeclarator(D);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00003003 return D.isInvalidType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003004 }
3005
3006 // It's not a type, it has to be an expression list.
3007 // Discard the comma locations - ActOnCXXNew has enough parameters.
3008 CommaLocsTy CommaLocs;
3009 return ParseExpressionList(PlacementArgs, CommaLocs);
3010}
3011
3012/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
3013/// to free memory allocated by new.
3014///
Chris Lattner109faf22009-01-04 21:25:24 +00003015/// This method is called to parse the 'delete' expression after the optional
3016/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
3017/// and "Start" is its location. Otherwise, "Start" is the location of the
3018/// 'delete' token.
3019///
Sebastian Redlbd150f42008-11-21 19:14:01 +00003020/// delete-expression:
3021/// '::'[opt] 'delete' cast-expression
3022/// '::'[opt] 'delete' '[' ']' cast-expression
John McCalldadc5752010-08-24 06:29:42 +00003023ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00003024Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
3025 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
3026 ConsumeToken(); // Consume 'delete'
Sebastian Redlbd150f42008-11-21 19:14:01 +00003027
3028 // Array delete?
3029 bool ArrayDelete = false;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003030 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith10c60722012-08-09 19:01:51 +00003031 // C++11 [expr.delete]p1:
3032 // Whenever the delete keyword is followed by empty square brackets, it
3033 // shall be interpreted as [array delete].
3034 // [Footnote: A lambda expression with a lambda-introducer that consists
3035 // of empty square brackets can follow the delete keyword if
3036 // the lambda expression is enclosed in parentheses.]
3037 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
3038 // lambda-introducer.
Sebastian Redlbd150f42008-11-21 19:14:01 +00003039 ArrayDelete = true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003040 BalancedDelimiterTracker T(*this, tok::l_square);
3041
3042 T.consumeOpen();
3043 T.consumeClose();
3044 if (T.getCloseLocation().isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00003045 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003046 }
3047
John McCalldadc5752010-08-24 06:29:42 +00003048 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00003049 if (Operand.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003050 return Operand;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003051
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003052 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00003053}
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003054
Douglas Gregor29c42f22012-02-24 07:38:34 +00003055static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
3056 switch (kind) {
3057 default: llvm_unreachable("Not a known type trait");
Alp Toker95e7ff22014-01-01 05:57:51 +00003058#define TYPE_TRAIT_1(Spelling, Name, Key) \
3059case tok::kw_ ## Spelling: return UTT_ ## Name;
Alp Tokercbb90342013-12-13 20:49:58 +00003060#define TYPE_TRAIT_2(Spelling, Name, Key) \
3061case tok::kw_ ## Spelling: return BTT_ ## Name;
3062#include "clang/Basic/TokenKinds.def"
Alp Toker40f9b1c2013-12-12 21:23:03 +00003063#define TYPE_TRAIT_N(Spelling, Name, Key) \
3064 case tok::kw_ ## Spelling: return TT_ ## Name;
3065#include "clang/Basic/TokenKinds.def"
Douglas Gregor29c42f22012-02-24 07:38:34 +00003066 }
3067}
3068
John Wiegley6242b6a2011-04-28 00:16:57 +00003069static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
3070 switch(kind) {
3071 default: llvm_unreachable("Not a known binary type trait");
3072 case tok::kw___array_rank: return ATT_ArrayRank;
3073 case tok::kw___array_extent: return ATT_ArrayExtent;
3074 }
3075}
3076
John Wiegleyf9f65842011-04-25 06:54:41 +00003077static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
3078 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003079 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegleyf9f65842011-04-25 06:54:41 +00003080 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
3081 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
3082 }
3083}
3084
Alp Toker40f9b1c2013-12-12 21:23:03 +00003085static unsigned TypeTraitArity(tok::TokenKind kind) {
3086 switch (kind) {
3087 default: llvm_unreachable("Not a known type trait");
3088#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
3089#include "clang/Basic/TokenKinds.def"
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003090 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003091}
3092
Fangrui Song6907ce22018-07-30 19:24:48 +00003093/// Parse the built-in type-trait pseudo-functions that allow
Douglas Gregor29c42f22012-02-24 07:38:34 +00003094/// implementation of the TR1/C++11 type traits templates.
3095///
3096/// primary-expression:
Alp Toker40f9b1c2013-12-12 21:23:03 +00003097/// unary-type-trait '(' type-id ')'
3098/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor29c42f22012-02-24 07:38:34 +00003099/// type-trait '(' type-id-seq ')'
3100///
3101/// type-id-seq:
3102/// type-id ...[opt] type-id-seq[opt]
3103///
3104ExprResult Parser::ParseTypeTrait() {
Alp Toker40f9b1c2013-12-12 21:23:03 +00003105 tok::TokenKind Kind = Tok.getKind();
3106 unsigned Arity = TypeTraitArity(Kind);
3107
Douglas Gregor29c42f22012-02-24 07:38:34 +00003108 SourceLocation Loc = ConsumeToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00003109
Douglas Gregor29c42f22012-02-24 07:38:34 +00003110 BalancedDelimiterTracker Parens(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003111 if (Parens.expectAndConsume())
Douglas Gregor29c42f22012-02-24 07:38:34 +00003112 return ExprError();
3113
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003114 SmallVector<ParsedType, 2> Args;
Douglas Gregor29c42f22012-02-24 07:38:34 +00003115 do {
3116 // Parse the next type.
3117 TypeResult Ty = ParseTypeName();
3118 if (Ty.isInvalid()) {
3119 Parens.skipToEnd();
3120 return ExprError();
3121 }
3122
3123 // Parse the ellipsis, if present.
3124 if (Tok.is(tok::ellipsis)) {
3125 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3126 if (Ty.isInvalid()) {
3127 Parens.skipToEnd();
3128 return ExprError();
3129 }
3130 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003131
Douglas Gregor29c42f22012-02-24 07:38:34 +00003132 // Add this type to the list of arguments.
3133 Args.push_back(Ty.get());
Alp Tokera3ebe6e2013-12-17 14:12:37 +00003134 } while (TryConsumeToken(tok::comma));
3135
Douglas Gregor29c42f22012-02-24 07:38:34 +00003136 if (Parens.consumeClose())
3137 return ExprError();
Alp Toker40f9b1c2013-12-12 21:23:03 +00003138
3139 SourceLocation EndLoc = Parens.getCloseLocation();
3140
3141 if (Arity && Args.size() != Arity) {
3142 Diag(EndLoc, diag::err_type_trait_arity)
3143 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3144 return ExprError();
3145 }
3146
3147 if (!Arity && Args.empty()) {
3148 Diag(EndLoc, diag::err_type_trait_arity)
3149 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3150 return ExprError();
3151 }
3152
Alp Toker88f64e62013-12-13 21:19:30 +00003153 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
Douglas Gregor29c42f22012-02-24 07:38:34 +00003154}
3155
John Wiegley6242b6a2011-04-28 00:16:57 +00003156/// ParseArrayTypeTrait - Parse the built-in array type-trait
3157/// pseudo-functions.
3158///
3159/// primary-expression:
3160/// [Embarcadero] '__array_rank' '(' type-id ')'
3161/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3162///
3163ExprResult Parser::ParseArrayTypeTrait() {
3164 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3165 SourceLocation Loc = ConsumeToken();
3166
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003167 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003168 if (T.expectAndConsume())
John Wiegley6242b6a2011-04-28 00:16:57 +00003169 return ExprError();
3170
3171 TypeResult Ty = ParseTypeName();
3172 if (Ty.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003173 SkipUntil(tok::comma, StopAtSemi);
3174 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003175 return ExprError();
3176 }
3177
3178 switch (ATT) {
3179 case ATT_ArrayRank: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003180 T.consumeClose();
Craig Topper161e4db2014-05-21 06:02:52 +00003181 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003182 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003183 }
3184 case ATT_ArrayExtent: {
Alp Toker383d2c42014-01-01 03:08:43 +00003185 if (ExpectAndConsume(tok::comma)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003186 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003187 return ExprError();
3188 }
3189
3190 ExprResult DimExpr = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003191 T.consumeClose();
John Wiegley6242b6a2011-04-28 00:16:57 +00003192
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003193 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3194 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003195 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003196 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003197 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley6242b6a2011-04-28 00:16:57 +00003198}
3199
John Wiegleyf9f65842011-04-25 06:54:41 +00003200/// ParseExpressionTrait - Parse built-in expression-trait
3201/// pseudo-functions like __is_lvalue_expr( xxx ).
3202///
3203/// primary-expression:
3204/// [Embarcadero] expression-trait '(' expression ')'
3205///
3206ExprResult Parser::ParseExpressionTrait() {
3207 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3208 SourceLocation Loc = ConsumeToken();
3209
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003210 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003211 if (T.expectAndConsume())
John Wiegleyf9f65842011-04-25 06:54:41 +00003212 return ExprError();
3213
3214 ExprResult Expr = ParseExpression();
3215
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003216 T.consumeClose();
John Wiegleyf9f65842011-04-25 06:54:41 +00003217
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003218 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3219 T.getCloseLocation());
John Wiegleyf9f65842011-04-25 06:54:41 +00003220}
3221
3222
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003223/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3224/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3225/// based on the context past the parens.
John McCalldadc5752010-08-24 06:29:42 +00003226ExprResult
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003227Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallba7bf592010-08-24 05:47:05 +00003228 ParsedType &CastTy,
Richard Smith87e11a42014-05-15 02:43:47 +00003229 BalancedDelimiterTracker &Tracker,
3230 ColonProtectionRAIIObject &ColonProt) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003231 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003232 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3233 assert(isTypeIdInParens() && "Not a type-id!");
3234
John McCalldadc5752010-08-24 06:29:42 +00003235 ExprResult Result(true);
David Blaikieefdccaa2016-01-15 23:43:34 +00003236 CastTy = nullptr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003237
3238 // We need to disambiguate a very ugly part of the C++ syntax:
3239 //
3240 // (T())x; - type-id
3241 // (T())*x; - type-id
3242 // (T())/x; - expression
3243 // (T()); - expression
3244 //
3245 // The bad news is that we cannot use the specialized tentative parser, since
3246 // it can only verify that the thing inside the parens can be parsed as
3247 // type-id, it is not useful for determining the context past the parens.
3248 //
3249 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidis24ad6922009-05-22 15:12:46 +00003250 // making any unnecessary Action calls.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003251 //
3252 // It uses a scheme similar to parsing inline methods. The parenthesized
3253 // tokens are cached, the context that follows is determined (possibly by
3254 // parsing a cast-expression), and then we re-introduce the cached tokens
3255 // into the token stream and parse them appropriately.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003256
Mike Stump11289f42009-09-09 15:08:12 +00003257 ParenParseOption ParseAs;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003258 CachedTokens Toks;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003259
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003260 // Store the tokens of the parentheses. We will parse them after we determine
3261 // the context that follows them.
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +00003262 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003263 // We didn't find the ')' we expected.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003264 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003265 return ExprError();
3266 }
3267
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003268 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003269 ParseAs = CompoundLiteral;
3270 } else {
3271 bool NotCastExpr;
Eli Friedmancf7530f2009-05-25 19:41:42 +00003272 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3273 NotCastExpr = true;
3274 } else {
3275 // Try parsing the cast-expression that may follow.
3276 // If it is not a cast-expression, NotCastExpr will be true and no token
3277 // will be consumed.
Richard Smith87e11a42014-05-15 02:43:47 +00003278 ColonProt.restore();
Eli Friedmancf7530f2009-05-25 19:41:42 +00003279 Result = ParseCastExpression(false/*isUnaryExpression*/,
3280 false/*isAddressofOperand*/,
John McCallba7bf592010-08-24 05:47:05 +00003281 NotCastExpr,
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003282 // type-id has priority.
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00003283 IsTypeCast);
Eli Friedmancf7530f2009-05-25 19:41:42 +00003284 }
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003285
3286 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3287 // an expression.
3288 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003289 }
3290
Alexey Bataev703a93c2016-02-04 04:22:09 +00003291 // Create a fake EOF to mark end of Toks buffer.
3292 Token AttrEnd;
3293 AttrEnd.startToken();
3294 AttrEnd.setKind(tok::eof);
3295 AttrEnd.setLocation(Tok.getLocation());
3296 AttrEnd.setEofData(Toks.data());
3297 Toks.push_back(AttrEnd);
3298
Mike Stump11289f42009-09-09 15:08:12 +00003299 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003300 Toks.push_back(Tok);
3301 // Re-enter the stored parenthesized tokens into the token stream, so we may
3302 // parse them now.
Ilya Biryukov929af672019-05-17 09:32:05 +00003303 PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true,
3304 /*IsReinject*/ true);
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003305 // Drop the current token and bring the first cached one. It's the same token
3306 // as when we entered this function.
3307 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003308
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003309 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003310 // Parse the type declarator.
3311 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00003312 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Richard Smith87e11a42014-05-15 02:43:47 +00003313 {
3314 ColonProtectionRAIIObject InnerColonProtection(*this);
3315 ParseSpecifierQualifierList(DS);
3316 ParseDeclarator(DeclaratorInfo);
3317 }
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003318
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003319 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003320 Tracker.consumeClose();
Richard Smith87e11a42014-05-15 02:43:47 +00003321 ColonProt.restore();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003322
Alexey Bataev703a93c2016-02-04 04:22:09 +00003323 // Consume EOF marker for Toks buffer.
3324 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3325 ConsumeAnyToken();
3326
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003327 if (ParseAs == CompoundLiteral) {
3328 ExprType = CompoundLiteral;
Richard Smithaba8b362014-05-15 02:51:15 +00003329 if (DeclaratorInfo.isInvalidType())
3330 return ExprError();
3331
3332 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Richard Smith87e11a42014-05-15 02:43:47 +00003333 return ParseCompoundLiteralExpression(Ty.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003334 Tracker.getOpenLocation(),
3335 Tracker.getCloseLocation());
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003336 }
Mike Stump11289f42009-09-09 15:08:12 +00003337
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003338 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3339 assert(ParseAs == CastExpr);
3340
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003341 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003342 return ExprError();
3343
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003344 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003345 if (!Result.isInvalid())
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003346 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3347 DeclaratorInfo, CastTy,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003348 Tracker.getCloseLocation(), Result.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003349 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003350 }
Mike Stump11289f42009-09-09 15:08:12 +00003351
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003352 // Not a compound literal, and not followed by a cast-expression.
3353 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003354
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003355 ExprType = SimpleExpr;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003356 Result = ParseExpression();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003357 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Fangrui Song6907ce22018-07-30 19:24:48 +00003358 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003359 Tok.getLocation(), Result.get());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003360
3361 // Match the ')'.
3362 if (Result.isInvalid()) {
Alexey Bataev703a93c2016-02-04 04:22:09 +00003363 while (Tok.isNot(tok::eof))
3364 ConsumeAnyToken();
3365 assert(Tok.getEofData() == AttrEnd.getEofData());
3366 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003367 return ExprError();
3368 }
Mike Stump11289f42009-09-09 15:08:12 +00003369
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003370 Tracker.consumeClose();
Alexey Bataev703a93c2016-02-04 04:22:09 +00003371 // Consume EOF marker for Toks buffer.
3372 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3373 ConsumeAnyToken();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003374 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003375}