blob: 87a6b4df8f812a378413266fe61e077a65e6d269 [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.
72 PP.EnterToken(ColonToken);
73 if (!AtDigraph)
74 PP.EnterToken(DigraphToken);
75}
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);
437 PP.EnterToken(ColonColon);
438 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);
463 PP.EnterToken(Tok);
464 PP.EnterToken(ColonColon);
465 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)) {
David Blaikie8c045bc2011-11-07 03:30:03 +0000490 // We have found a template name, so annotate this token
Chris Lattnere2355f72009-06-26 03:52:38 +0000491 // with a template-id annotation. We do not permit the
492 // template-id to be translated into a type annotation,
493 // because some clients (e.g., the parsing of class template
494 // specializations) still want to see the original template-id
495 // token.
Douglas Gregor71395fa2009-11-04 00:56:37 +0000496 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000497 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
498 TemplateName, false))
John McCall1f476a12010-02-26 08:45:28 +0000499 return true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000500 continue;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000501 }
502
Fangrui Song6907ce22018-07-30 19:24:48 +0000503 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000504 (IsTypename || IsTemplateArgumentList(1))) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000505 // We have something like t::getAs<T>, where getAs is a
Douglas Gregor20c38a72010-05-21 23:43:39 +0000506 // member of an unknown specialization. However, this will only
507 // parse correctly as a template, so suggest the keyword 'template'
508 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000509 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000510 if (getLangOpts().MicrosoftExt)
Francois Pichet93921652011-04-22 08:25:24 +0000511 DiagID = diag::warn_missing_dependent_template_keyword;
Fangrui Song6907ce22018-07-30 19:24:48 +0000512
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000513 Diag(Tok.getLocation(), DiagID)
Douglas Gregor20c38a72010-05-21 23:43:39 +0000514 << II.getName()
515 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
Richard Smithfd3dae02017-01-20 00:20:39 +0000516
517 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
Richard Smith79810042018-05-11 02:43:08 +0000518 getCurScope(), SS, Tok.getLocation(), TemplateName, ObjectType,
Richard Smithfd3dae02017-01-20 00:20:39 +0000519 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
Douglas Gregorbb119652010-06-16 23:00:59 +0000520 // Consume the identifier.
521 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000522 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
523 TemplateName, false))
524 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000525 }
526 else
Fangrui Song6907ce22018-07-30 19:24:48 +0000527 return true;
528
529 continue;
Chris Lattnere2355f72009-06-26 03:52:38 +0000530 }
531 }
532
Douglas Gregor7f741122009-02-25 19:37:18 +0000533 // We don't have any tokens that form the beginning of a
534 // nested-name-specifier, so we're done.
535 break;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000536 }
Mike Stump11289f42009-09-09 15:08:12 +0000537
Douglas Gregore610ada2010-02-24 18:44:31 +0000538 // Even if we didn't see any pieces of a nested-name-specifier, we
539 // still check whether there is a tilde in this position, which
540 // indicates a potential pseudo-destructor.
541 if (CheckForDestructor && Tok.is(tok::tilde))
542 *MayBePseudoDestructor = true;
543
John McCall1f476a12010-02-26 08:45:28 +0000544 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000545}
546
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000547ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
548 Token &Replacement) {
549 SourceLocation TemplateKWLoc;
550 UnqualifiedId Name;
551 if (ParseUnqualifiedId(SS,
552 /*EnteringContext=*/false,
553 /*AllowDestructorName=*/false,
554 /*AllowConstructorName=*/false,
Richard Smith35845152017-02-07 01:37:30 +0000555 /*AllowDeductionGuide=*/false,
Richard Smithc08b6932018-04-27 02:00:13 +0000556 /*ObjectType=*/nullptr, &TemplateKWLoc, Name))
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000557 return ExprError();
558
559 // This is only the direct operand of an & operator if it is not
560 // followed by a postfix-expression suffix.
561 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
562 isAddressOfOperand = false;
563
Richard Smithc2dead42018-06-27 01:32:04 +0000564 ExprResult E = Actions.ActOnIdExpression(
565 getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren),
Bruno Ricci70ad3962019-03-25 17:08:51 +0000566 isAddressOfOperand, /*CCC=*/nullptr, /*IsInlineAsmIdentifier=*/false,
Richard Smithc2dead42018-06-27 01:32:04 +0000567 &Replacement);
568 if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less))
569 checkPotentialAngleBracket(E);
570 return E;
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000571}
572
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000573/// ParseCXXIdExpression - Handle id-expression.
574///
575/// id-expression:
576/// unqualified-id
577/// qualified-id
578///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000579/// qualified-id:
580/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
581/// '::' identifier
582/// '::' operator-function-id
Douglas Gregora727cb92009-06-30 22:34:41 +0000583/// '::' template-id
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000584///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000585/// NOTE: The standard specifies that, for qualified-id, the parser does not
586/// expect:
587///
588/// '::' conversion-function-id
589/// '::' '~' class-name
590///
591/// This may cause a slight inconsistency on diagnostics:
592///
593/// class C {};
594/// namespace A {}
595/// void f() {
596/// :: A :: ~ C(); // Some Sema error about using destructor with a
597/// // namespace.
598/// :: ~ C(); // Some Parser error like 'unexpected ~'.
599/// }
600///
601/// We simplify the parser a bit and make it work like:
602///
603/// qualified-id:
604/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
605/// '::' unqualified-id
606///
607/// That way Sema can handle and report similar errors for namespaces and the
608/// global scope.
609///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000610/// The isAddressOfOperand parameter indicates that this id-expression is a
611/// direct operand of the address-of operator. This is, besides member contexts,
612/// the only place where a qualified-id naming a non-static class member may
613/// appear.
614///
John McCalldadc5752010-08-24 06:29:42 +0000615ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000616 // qualified-id:
617 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
618 // '::' unqualified-id
619 //
620 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +0000621 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000622
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000623 Token Replacement;
Nico Weber01a46ad2015-02-15 06:15:40 +0000624 ExprResult Result =
625 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000626 if (Result.isUnset()) {
627 // If the ExprResult is valid but null, then typo correction suggested a
628 // keyword replacement that needs to be reparsed.
629 UnconsumeToken(Replacement);
630 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
631 }
632 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
633 "for a previous keyword suggestion");
634 return Result;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000635}
636
Richard Smith21b3ab42013-05-09 21:36:41 +0000637/// ParseLambdaExpression - Parse a C++11 lambda expression.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000638///
639/// lambda-expression:
640/// lambda-introducer lambda-declarator[opt] compound-statement
Hamza Sood8205a812019-05-04 10:49:46 +0000641/// lambda-introducer '<' template-parameter-list '>'
642/// lambda-declarator[opt] compound-statement
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000643///
644/// lambda-introducer:
645/// '[' lambda-capture[opt] ']'
646///
647/// lambda-capture:
648/// capture-default
649/// capture-list
650/// capture-default ',' capture-list
651///
652/// capture-default:
653/// '&'
654/// '='
655///
656/// capture-list:
657/// capture
658/// capture-list ',' capture
659///
660/// capture:
Richard Smith21b3ab42013-05-09 21:36:41 +0000661/// simple-capture
662/// init-capture [C++1y]
663///
664/// simple-capture:
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000665/// identifier
666/// '&' identifier
667/// 'this'
668///
Richard Smith21b3ab42013-05-09 21:36:41 +0000669/// init-capture: [C++1y]
670/// identifier initializer
671/// '&' identifier initializer
672///
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000673/// lambda-declarator:
674/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
675/// 'mutable'[opt] exception-specification[opt]
676/// trailing-return-type[opt]
677///
678ExprResult Parser::ParseLambdaExpression() {
679 // Parse lambda-introducer.
680 LambdaIntroducer Intro;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000681 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000682 if (DiagID) {
683 Diag(Tok, DiagID.getValue());
David Majnemer234b8182015-01-12 03:36:37 +0000684 SkipUntil(tok::r_square, StopAtSemi);
685 SkipUntil(tok::l_brace, StopAtSemi);
686 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000687 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000688 }
689
690 return ParseLambdaExpressionAfterIntroducer(Intro);
691}
692
693/// TryParseLambdaExpression - Use lookahead and potentially tentative
694/// parsing to determine if we are looking at a C++0x lambda expression, and parse
695/// it if we are.
696///
697/// If we are not looking at a lambda expression, returns ExprError().
698ExprResult Parser::TryParseLambdaExpression() {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000699 assert(getLangOpts().CPlusPlus11
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000700 && Tok.is(tok::l_square)
701 && "Not at the start of a possible lambda expression.");
702
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000703 const Token Next = NextToken();
704 if (Next.is(tok::eof)) // Nothing else to lookup here...
705 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000706
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000707 const Token After = GetLookAheadToken(2);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000708 // If lookahead indicates this is a lambda...
709 if (Next.is(tok::r_square) || // []
710 Next.is(tok::equal) || // [=
711 (Next.is(tok::amp) && // [&] or [&,
712 (After.is(tok::r_square) ||
713 After.is(tok::comma))) ||
714 (Next.is(tok::identifier) && // [identifier]
715 After.is(tok::r_square))) {
716 return ParseLambdaExpression();
717 }
718
Eli Friedmanc7c97142012-01-04 02:40:39 +0000719 // If lookahead indicates an ObjC message send...
720 // [identifier identifier
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000721 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000722 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000723 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000724
Eli Friedmanc7c97142012-01-04 02:40:39 +0000725 // Here, we're stuck: lambda introducers and Objective-C message sends are
726 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
727 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
728 // writing two routines to parse a lambda introducer, just try to parse
729 // a lambda introducer first, and fall back if that fails.
730 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000731 LambdaIntroducer Intro;
732 if (TryParseLambdaIntroducer(Intro))
Eli Friedmanc7c97142012-01-04 02:40:39 +0000733 return ExprEmpty();
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000734
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000735 return ParseLambdaExpressionAfterIntroducer(Intro);
736}
737
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000738/// Parse a lambda introducer.
Richard Smithf44d2a82013-05-21 22:21:19 +0000739/// \param Intro A LambdaIntroducer filled in with information about the
740/// contents of the lambda-introducer.
741/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
742/// message send and a lambda expression. In this mode, we will
743/// sometimes skip the initializers for init-captures and not fully
744/// populate \p Intro. This flag will be set to \c true if we do so.
745/// \return A DiagnosticID if it hit something unexpected. The location for
Malcolm Parsonsffd21d32017-01-11 11:23:22 +0000746/// the diagnostic is that of the current token.
Richard Smithf44d2a82013-05-21 22:21:19 +0000747Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
748 bool *SkippedInits) {
David Blaikie05785d12013-02-20 22:23:23 +0000749 typedef Optional<unsigned> DiagResult;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000750
751 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000752 BalancedDelimiterTracker T(*this, tok::l_square);
753 T.consumeOpen();
754
755 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000756
757 bool first = true;
758
759 // Parse capture-default.
760 if (Tok.is(tok::amp) &&
761 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
762 Intro.Default = LCD_ByRef;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000763 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000764 first = false;
765 } else if (Tok.is(tok::equal)) {
766 Intro.Default = LCD_ByCopy;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000767 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000768 first = false;
769 }
770
771 while (Tok.isNot(tok::r_square)) {
772 if (!first) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000773 if (Tok.isNot(tok::comma)) {
Douglas Gregor721b14d2012-07-31 00:50:07 +0000774 // Provide a completion for a lambda introducer here. Except
775 // in Objective-C, where this is Almost Surely meant to be a message
776 // send. In that case, fail here and let the ObjC message
777 // expression parser perform the completion.
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000778 if (Tok.is(tok::code_completion) &&
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000779 !(getLangOpts().ObjC && Intro.Default == LCD_None &&
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000780 !Intro.Captures.empty())) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000781 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
Douglas Gregord8c61782012-02-15 15:34:24 +0000782 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000783 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000784 break;
785 }
786
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000787 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregord8c61782012-02-15 15:34:24 +0000788 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000789 ConsumeToken();
790 }
791
Douglas Gregord8c61782012-02-15 15:34:24 +0000792 if (Tok.is(tok::code_completion)) {
793 // If we're in Objective-C++ and we have a bare '[', then this is more
794 // likely to be a message receiver.
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000795 if (getLangOpts().ObjC && first)
Douglas Gregord8c61782012-02-15 15:34:24 +0000796 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
797 else
Fangrui Song6907ce22018-07-30 19:24:48 +0000798 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
Douglas Gregord8c61782012-02-15 15:34:24 +0000799 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000800 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000801 break;
802 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000803
Douglas Gregord8c61782012-02-15 15:34:24 +0000804 first = false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000805
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000806 // Parse capture.
807 LambdaCaptureKind Kind = LCK_ByCopy;
Richard Smith42b10572015-11-11 01:36:17 +0000808 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000809 SourceLocation Loc;
Craig Topper161e4db2014-05-21 06:02:52 +0000810 IdentifierInfo *Id = nullptr;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000811 SourceLocation EllipsisLoc;
Richard Smith21b3ab42013-05-09 21:36:41 +0000812 ExprResult Init;
Alexander Shaposhnikov832f49b2018-07-16 07:23:47 +0000813 SourceLocation LocStart = Tok.getLocation();
Faisal Validc6b5962016-03-21 09:25:37 +0000814
815 if (Tok.is(tok::star)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000816 Loc = ConsumeToken();
Faisal Validc6b5962016-03-21 09:25:37 +0000817 if (Tok.is(tok::kw_this)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000818 ConsumeToken();
819 Kind = LCK_StarThis;
Faisal Validc6b5962016-03-21 09:25:37 +0000820 } else {
821 return DiagResult(diag::err_expected_star_this_capture);
822 }
823 } else if (Tok.is(tok::kw_this)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000824 Kind = LCK_This;
825 Loc = ConsumeToken();
826 } else {
827 if (Tok.is(tok::amp)) {
828 Kind = LCK_ByRef;
829 ConsumeToken();
Douglas Gregord8c61782012-02-15 15:34:24 +0000830
831 if (Tok.is(tok::code_completion)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000832 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
Douglas Gregord8c61782012-02-15 15:34:24 +0000833 /*AfterAmpersand=*/true);
Alp Toker1c583cc2014-05-02 03:43:14 +0000834 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000835 break;
836 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000837 }
838
839 if (Tok.is(tok::identifier)) {
840 Id = Tok.getIdentifierInfo();
841 Loc = ConsumeToken();
842 } else if (Tok.is(tok::kw_this)) {
843 // FIXME: If we want to suggest a fixit here, will need to return more
844 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
845 // Clear()ed to prevent emission in case of tentative parsing?
846 return DiagResult(diag::err_this_captured_by_reference);
847 } else {
848 return DiagResult(diag::err_expected_capture);
849 }
Richard Smith21b3ab42013-05-09 21:36:41 +0000850
851 if (Tok.is(tok::l_paren)) {
852 BalancedDelimiterTracker Parens(*this, tok::l_paren);
853 Parens.consumeOpen();
854
Richard Smith42b10572015-11-11 01:36:17 +0000855 InitKind = LambdaCaptureInitKind::DirectInit;
856
Richard Smith21b3ab42013-05-09 21:36:41 +0000857 ExprVector Exprs;
858 CommaLocsTy Commas;
Richard Smithf44d2a82013-05-21 22:21:19 +0000859 if (SkippedInits) {
860 Parens.skipToEnd();
861 *SkippedInits = true;
862 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith21b3ab42013-05-09 21:36:41 +0000863 Parens.skipToEnd();
864 Init = ExprError();
865 } else {
866 Parens.consumeClose();
867 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
868 Parens.getCloseLocation(),
869 Exprs);
870 }
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000871 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000872 // Each lambda init-capture forms its own full expression, which clears
873 // Actions.MaybeODRUseExprs. So create an expression evaluation context
874 // to save the necessary state, and restore it later.
Faisal Valid143a0c2017-04-01 21:30:49 +0000875 EnterExpressionEvaluationContext EC(
876 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith42b10572015-11-11 01:36:17 +0000877
878 if (TryConsumeToken(tok::equal))
879 InitKind = LambdaCaptureInitKind::CopyInit;
880 else
881 InitKind = LambdaCaptureInitKind::ListInit;
Richard Smith21b3ab42013-05-09 21:36:41 +0000882
Richard Smith215f4232015-02-11 02:41:33 +0000883 if (!SkippedInits) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000884 Init = ParseInitializer();
Richard Smith215f4232015-02-11 02:41:33 +0000885 } else if (Tok.is(tok::l_brace)) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000886 BalancedDelimiterTracker Braces(*this, tok::l_brace);
887 Braces.consumeOpen();
888 Braces.skipToEnd();
889 *SkippedInits = true;
890 } else {
891 // We're disambiguating this:
892 //
893 // [..., x = expr
894 //
895 // We need to find the end of the following expression in order to
Richard Smith9e2f0a42014-04-13 04:31:48 +0000896 // determine whether this is an Obj-C message send's receiver, a
897 // C99 designator, or a lambda init-capture.
Richard Smithf44d2a82013-05-21 22:21:19 +0000898 //
899 // Parse the expression to find where it ends, and annotate it back
900 // onto the tokens. We would have parsed this expression the same way
901 // in either case: both the RHS of an init-capture and the RHS of an
902 // assignment expression are parsed as an initializer-clause, and in
903 // neither case can anything be added to the scope between the '[' and
904 // here.
905 //
906 // FIXME: This is horrible. Adding a mechanism to skip an expression
907 // would be much cleaner.
908 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
909 // that instead. (And if we see a ':' with no matching '?', we can
910 // classify this as an Obj-C message send.)
911 SourceLocation StartLoc = Tok.getLocation();
912 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
913 Init = ParseInitializer();
Akira Hatanaka51e60f92016-12-20 02:11:29 +0000914 if (!Init.isInvalid())
915 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
Richard Smithf44d2a82013-05-21 22:21:19 +0000916
917 if (Tok.getLocation() != StartLoc) {
918 // Back out the lexing of the token after the initializer.
919 PP.RevertCachedTokens(1);
920
921 // Replace the consumed tokens with an appropriate annotation.
922 Tok.setLocation(StartLoc);
923 Tok.setKind(tok::annot_primary_expr);
924 setExprAnnotation(Tok, Init);
925 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
926 PP.AnnotateCachedTokens(Tok);
927
928 // Consume the annotated initializer.
Richard Smithaf3b3252017-05-18 19:21:48 +0000929 ConsumeAnnotationToken();
Richard Smithf44d2a82013-05-21 22:21:19 +0000930 }
931 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000932 } else
933 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000934 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000935 // If this is an init capture, process the initialization expression
936 // right away. For lambda init-captures such as the following:
937 // const int x = 10;
938 // auto L = [i = x+1](int a) {
939 // return [j = x+2,
940 // &k = x](char b) { };
941 // };
942 // keep in mind that each lambda init-capture has to have:
943 // - its initialization expression executed in the context
944 // of the enclosing/parent decl-context.
945 // - but the variable itself has to be 'injected' into the
946 // decl-context of its lambda's call-operator (which has
947 // not yet been created).
948 // Each init-expression is a full-expression that has to get
949 // Sema-analyzed (for capturing etc.) before its lambda's
950 // call-operator's decl-context, scope & scopeinfo are pushed on their
951 // respective stacks. Thus if any variable is odr-used in the init-capture
952 // it will correctly get captured in the enclosing lambda, if one exists.
953 // The init-variables above are created later once the lambdascope and
954 // call-operators decl-context is pushed onto its respective stack.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000955
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000956 // Since the lambda init-capture's initializer expression occurs in the
957 // context of the enclosing function or lambda, therefore we can not wait
958 // till a lambda scope has been pushed on before deciding whether the
959 // variable needs to be captured. We also need to process all
960 // lvalue-to-rvalue conversions and discarded-value conversions,
961 // so that we can avoid capturing certain constant variables.
962 // For e.g.,
963 // void test() {
964 // const int x = 10;
965 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
966 // return [y = x](int i) { <-- don't capture by enclosing lambda
967 // return y;
968 // }
969 // };
Richard Smithbdb84f32016-07-22 23:36:59 +0000970 // }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000971 // If x was not const, the second use would require 'L' to capture, and
972 // that would be an error.
973
Richard Smith42b10572015-11-11 01:36:17 +0000974 ParsedType InitCaptureType;
Volodymyr Sapsaib0f1aae2017-08-22 17:55:19 +0000975 if (!Init.isInvalid())
976 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000977 if (Init.isUsable()) {
978 // Get the pointer and store it in an lvalue, so we can use it as an
979 // out argument.
980 Expr *InitExpr = Init.get();
981 // This performs any lvalue-to-rvalue conversions if necessary, which
982 // can affect what gets captured in the containing decl-context.
Richard Smith42b10572015-11-11 01:36:17 +0000983 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
984 Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000985 Init = InitExpr;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000986 }
Alexander Shaposhnikov832f49b2018-07-16 07:23:47 +0000987
988 SourceLocation LocEnd = PrevTokLocation;
989
Richard Smith42b10572015-11-11 01:36:17 +0000990 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
Alexander Shaposhnikov832f49b2018-07-16 07:23:47 +0000991 InitCaptureType, SourceRange(LocStart, LocEnd));
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000992 }
993
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000994 T.consumeClose();
995 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000996 return DiagResult();
997}
998
Douglas Gregord8c61782012-02-15 15:34:24 +0000999/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001000///
1001/// Returns true if it hit something unexpected.
1002bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
Jan Korous06aa2af2017-11-06 17:42:17 +00001003 {
1004 bool SkippedInits = false;
1005 TentativeParsingAction PA1(*this);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001006
Jan Korous06aa2af2017-11-06 17:42:17 +00001007 if (ParseLambdaIntroducer(Intro, &SkippedInits)) {
1008 PA1.Revert();
1009 return true;
1010 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001011
Jan Korous06aa2af2017-11-06 17:42:17 +00001012 if (!SkippedInits) {
1013 PA1.Commit();
1014 return false;
1015 }
1016
1017 PA1.Revert();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001018 }
1019
Jan Korous06aa2af2017-11-06 17:42:17 +00001020 // Try to parse it again, but this time parse the init-captures too.
1021 Intro = LambdaIntroducer();
1022 TentativeParsingAction PA2(*this);
1023
1024 if (!ParseLambdaIntroducer(Intro)) {
1025 PA2.Commit();
Richard Smithf44d2a82013-05-21 22:21:19 +00001026 return false;
1027 }
1028
Jan Korous06aa2af2017-11-06 17:42:17 +00001029 PA2.Revert();
1030 return true;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001031}
1032
Faisal Valia734ab92016-03-26 16:11:37 +00001033static void
1034tryConsumeMutableOrConstexprToken(Parser &P, SourceLocation &MutableLoc,
1035 SourceLocation &ConstexprLoc,
1036 SourceLocation &DeclEndLoc) {
1037 assert(MutableLoc.isInvalid());
1038 assert(ConstexprLoc.isInvalid());
1039 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1040 // to the final of those locations. Emit an error if we have multiple
1041 // copies of those keywords and recover.
1042
1043 while (true) {
1044 switch (P.getCurToken().getKind()) {
1045 case tok::kw_mutable: {
1046 if (MutableLoc.isValid()) {
1047 P.Diag(P.getCurToken().getLocation(),
1048 diag::err_lambda_decl_specifier_repeated)
1049 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1050 }
1051 MutableLoc = P.ConsumeToken();
1052 DeclEndLoc = MutableLoc;
1053 break /*switch*/;
1054 }
1055 case tok::kw_constexpr:
1056 if (ConstexprLoc.isValid()) {
1057 P.Diag(P.getCurToken().getLocation(),
1058 diag::err_lambda_decl_specifier_repeated)
1059 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1060 }
1061 ConstexprLoc = P.ConsumeToken();
1062 DeclEndLoc = ConstexprLoc;
1063 break /*switch*/;
1064 default:
1065 return;
1066 }
1067 }
1068}
1069
1070static void
1071addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1072 DeclSpec &DS) {
1073 if (ConstexprLoc.isValid()) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001074 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
Richard Smithb115e5d2017-08-13 23:37:29 +00001075 ? diag::ext_constexpr_on_lambda_cxx17
Faisal Valia734ab92016-03-26 16:11:37 +00001076 : diag::warn_cxx14_compat_constexpr_on_lambda);
1077 const char *PrevSpec = nullptr;
1078 unsigned DiagID = 0;
1079 DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
1080 assert(PrevSpec == nullptr && DiagID == 0 &&
1081 "Constexpr cannot have been set previously!");
1082 }
1083}
1084
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001085/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1086/// expression.
1087ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1088 LambdaIntroducer &Intro) {
Eli Friedmanc7c97142012-01-04 02:40:39 +00001089 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1090 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1091
1092 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1093 "lambda expression parsing");
1094
Fangrui Song6907ce22018-07-30 19:24:48 +00001095
Faisal Vali2b391ab2013-09-26 19:54:12 +00001096
Richard Smith21b3ab42013-05-09 21:36:41 +00001097 // FIXME: Call into Actions to add any init-capture declarations to the
1098 // scope while parsing the lambda-declarator and compound-statement.
1099
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001100 // Parse lambda-declarator[opt].
1101 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00001102 Declarator D(DS, DeclaratorContext::LambdaExprContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001103 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001104 Actions.PushLambdaScope();
1105
1106 ParsedAttributes Attr(AttrFactory);
1107 SourceLocation DeclLoc = Tok.getLocation();
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001108 if (getLangOpts().CUDA) {
1109 // In CUDA code, GNU attributes are allowed to appear immediately after the
1110 // "[...]", even if there is no "(...)" before the lambda body.
Justin Lebar0139a5d2016-09-30 19:55:48 +00001111 MaybeParseGNUAttributes(D);
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001112 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001113
Justin Lebare46ea722016-09-30 19:55:55 +00001114 // Helper to emit a warning if we see a CUDA host/device/global attribute
1115 // after '(...)'. nvcc doesn't accept this.
1116 auto WarnIfHasCUDATargetAttr = [&] {
1117 if (getLangOpts().CUDA)
Erich Keanee891aa92018-07-13 15:07:47 +00001118 for (const ParsedAttr &A : Attr)
1119 if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1120 A.getKind() == ParsedAttr::AT_CUDAHost ||
1121 A.getKind() == ParsedAttr::AT_CUDAGlobal)
Erich Keanec480f302018-07-12 21:09:05 +00001122 Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
1123 << A.getName()->getName();
Justin Lebare46ea722016-09-30 19:55:55 +00001124 };
1125
Hamza Sood8205a812019-05-04 10:49:46 +00001126 // FIXME: Consider allowing this as an extension for GCC compatibiblity.
1127 const bool HasExplicitTemplateParams = Tok.is(tok::less);
1128 ParseScope TemplateParamScope(this, Scope::TemplateParamScope,
1129 /*EnteredScope=*/HasExplicitTemplateParams);
1130 if (HasExplicitTemplateParams) {
1131 Diag(Tok, getLangOpts().CPlusPlus2a
1132 ? diag::warn_cxx17_compat_lambda_template_parameter_list
1133 : diag::ext_lambda_template_parameter_list);
1134
1135 SmallVector<NamedDecl*, 4> TemplateParams;
1136 SourceLocation LAngleLoc, RAngleLoc;
1137 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
1138 TemplateParams, LAngleLoc, RAngleLoc)) {
1139 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1140 return ExprError();
1141 }
1142
1143 if (TemplateParams.empty()) {
1144 Diag(RAngleLoc,
1145 diag::err_lambda_template_parameter_list_empty);
1146 } else {
1147 Actions.ActOnLambdaExplicitTemplateParameterList(
1148 LAngleLoc, TemplateParams, RAngleLoc);
1149 ++CurTemplateDepthTracker;
1150 }
1151 }
1152
David Majnemere01c4662015-01-09 05:10:55 +00001153 TypeResult TrailingReturnType;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001154 if (Tok.is(tok::l_paren)) {
1155 ParseScope PrototypeScope(this,
1156 Scope::FunctionPrototypeScope |
Richard Smithe233fbf2013-01-28 22:42:45 +00001157 Scope::FunctionDeclarationScope |
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001158 Scope::DeclScope);
1159
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001160 BalancedDelimiterTracker T(*this, tok::l_paren);
1161 T.consumeOpen();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001162 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001163
1164 // Parse parameter-declaration-clause.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001165 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001166 SourceLocation EllipsisLoc;
Fangrui Song6907ce22018-07-30 19:24:48 +00001167
Faisal Vali2b391ab2013-09-26 19:54:12 +00001168 if (Tok.isNot(tok::r_paren)) {
Hamza Sood8205a812019-05-04 10:49:46 +00001169 Actions.RecordParsingTemplateParameterDepth(
1170 CurTemplateDepthTracker.getOriginalDepth());
1171
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001172 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
Hamza Sood8205a812019-05-04 10:49:46 +00001173
Fangrui Song6907ce22018-07-30 19:24:48 +00001174 // For a generic lambda, each 'auto' within the parameter declaration
Faisal Vali2b391ab2013-09-26 19:54:12 +00001175 // clause creates a template type parameter, so increment the depth.
Hamza Sood8205a812019-05-04 10:49:46 +00001176 // If we've parsed any explicit template parameters, then the depth will
1177 // have already been incremented. So we make sure that at most a single
1178 // depth level is added.
Fangrui Song6907ce22018-07-30 19:24:48 +00001179 if (Actions.getCurGenericLambda())
Hamza Sood8205a812019-05-04 10:49:46 +00001180 CurTemplateDepthTracker.setAddedDepth(1);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001181 }
Hamza Sood8205a812019-05-04 10:49:46 +00001182
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001183 T.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001184 SourceLocation RParenLoc = T.getCloseLocation();
Justin Lebar0139a5d2016-09-30 19:55:48 +00001185 SourceLocation DeclEndLoc = RParenLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001186
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001187 // GNU-style attributes must be parsed before the mutable specifier to be
1188 // compatible with GCC.
1189 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1190
David Majnemerbda86322015-02-04 08:22:46 +00001191 // MSVC-style attributes must be parsed before the mutable specifier to be
1192 // compatible with MSVC.
Aaron Ballman068aa512015-05-20 20:58:33 +00001193 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
David Majnemerbda86322015-02-04 08:22:46 +00001194
Faisal Valia734ab92016-03-26 16:11:37 +00001195 // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001196 SourceLocation MutableLoc;
Faisal Valia734ab92016-03-26 16:11:37 +00001197 SourceLocation ConstexprLoc;
1198 tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
1199 DeclEndLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001200
Faisal Valia734ab92016-03-26 16:11:37 +00001201 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001202
1203 // Parse exception-specification[opt].
1204 ExceptionSpecificationType ESpecType = EST_None;
1205 SourceRange ESpecRange;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001206 SmallVector<ParsedType, 2> DynamicExceptions;
1207 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001208 ExprResult NoexceptExpr;
Richard Smith0b3a4622014-11-13 20:01:57 +00001209 CachedTokens *ExceptionSpecTokens;
1210 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1211 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00001212 DynamicExceptions,
1213 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00001214 NoexceptExpr,
1215 ExceptionSpecTokens);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001216
1217 if (ESpecType != EST_None)
1218 DeclEndLoc = ESpecRange.getEnd();
1219
1220 // Parse attribute-specifier[opt].
Richard Smith89645bc2013-01-02 12:01:23 +00001221 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001222
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001223 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1224
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001225 // Parse trailing-return-type[opt].
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001226 if (Tok.is(tok::arrow)) {
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001227 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001228 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00001229 TrailingReturnType =
1230 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001231 if (Range.getEnd().isValid())
1232 DeclEndLoc = Range.getEnd();
1233 }
1234
1235 PrototypeScope.Exit();
1236
Justin Lebare46ea722016-09-30 19:55:55 +00001237 WarnIfHasCUDATargetAttr();
1238
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001239 SourceLocation NoLoc;
Erich Keanec480f302018-07-12 21:09:05 +00001240 D.AddTypeInfo(DeclaratorChunk::getFunction(
1241 /*hasProto=*/true,
1242 /*isAmbiguous=*/false, LParenLoc, ParamInfo.data(),
1243 ParamInfo.size(), EllipsisLoc, RParenLoc,
Erich Keanec480f302018-07-12 21:09:05 +00001244 /*RefQualifierIsLValueRef=*/true,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00001245 /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType,
Erich Keanec480f302018-07-12 21:09:05 +00001246 ESpecRange, DynamicExceptions.data(),
1247 DynamicExceptionRanges.data(), DynamicExceptions.size(),
1248 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1249 /*ExceptionSpecTokens*/ nullptr,
1250 /*DeclsInPrototype=*/None, LParenLoc, FunLocalRangeEnd, D,
1251 TrailingReturnType),
1252 std::move(Attr), DeclEndLoc);
Faisal Valia734ab92016-03-26 16:11:37 +00001253 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1254 tok::kw_constexpr) ||
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001255 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1256 // It's common to forget that one needs '()' before 'mutable', an attribute
1257 // specifier, or the result type. Deal with this.
1258 unsigned TokKind = 0;
1259 switch (Tok.getKind()) {
1260 case tok::kw_mutable: TokKind = 0; break;
1261 case tok::arrow: TokKind = 1; break;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001262 case tok::kw___attribute:
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001263 case tok::l_square: TokKind = 2; break;
Faisal Valia734ab92016-03-26 16:11:37 +00001264 case tok::kw_constexpr: TokKind = 3; break;
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001265 default: llvm_unreachable("Unknown token kind");
1266 }
1267
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001268 Diag(Tok, diag::err_lambda_missing_parens)
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001269 << TokKind
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001270 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
Justin Lebar0139a5d2016-09-30 19:55:48 +00001271 SourceLocation DeclEndLoc = DeclLoc;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001272
1273 // GNU-style attributes must be parsed before the mutable specifier to be
1274 // compatible with GCC.
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001275 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1276
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001277 // Parse 'mutable', if it's there.
1278 SourceLocation MutableLoc;
1279 if (Tok.is(tok::kw_mutable)) {
1280 MutableLoc = ConsumeToken();
1281 DeclEndLoc = MutableLoc;
1282 }
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001283
1284 // Parse attribute-specifier[opt].
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001285 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1286
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001287 // Parse the return type, if there is one.
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001288 if (Tok.is(tok::arrow)) {
1289 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00001290 TrailingReturnType =
1291 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001292 if (Range.getEnd().isValid())
David Majnemere01c4662015-01-09 05:10:55 +00001293 DeclEndLoc = Range.getEnd();
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001294 }
1295
Justin Lebare46ea722016-09-30 19:55:55 +00001296 WarnIfHasCUDATargetAttr();
1297
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001298 SourceLocation NoLoc;
Erich Keanec480f302018-07-12 21:09:05 +00001299 D.AddTypeInfo(DeclaratorChunk::getFunction(
1300 /*hasProto=*/true,
1301 /*isAmbiguous=*/false,
1302 /*LParenLoc=*/NoLoc,
1303 /*Params=*/nullptr,
1304 /*NumParams=*/0,
1305 /*EllipsisLoc=*/NoLoc,
1306 /*RParenLoc=*/NoLoc,
Erich Keanec480f302018-07-12 21:09:05 +00001307 /*RefQualifierIsLValueRef=*/true,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00001308 /*RefQualifierLoc=*/NoLoc, MutableLoc, EST_None,
Erich Keanec480f302018-07-12 21:09:05 +00001309 /*ESpecRange=*/SourceRange(),
1310 /*Exceptions=*/nullptr,
1311 /*ExceptionRanges=*/nullptr,
1312 /*NumExceptions=*/0,
1313 /*NoexceptExpr=*/nullptr,
1314 /*ExceptionSpecTokens=*/nullptr,
1315 /*DeclsInPrototype=*/None, DeclLoc, DeclEndLoc, D,
1316 TrailingReturnType),
1317 std::move(Attr), DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001318 }
1319
Eli Friedman4817cf72012-01-06 03:05:34 +00001320 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1321 // it.
Momchil Velikov57c681f2017-08-10 15:43:06 +00001322 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1323 Scope::CompoundStmtScope;
Douglas Gregorb8389972012-02-21 22:51:27 +00001324 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman4817cf72012-01-06 03:05:34 +00001325
Eli Friedman71c80552012-01-05 03:35:19 +00001326 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1327
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001328 // Parse compound-statement.
Eli Friedmanc7c97142012-01-04 02:40:39 +00001329 if (!Tok.is(tok::l_brace)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001330 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmanc7c97142012-01-04 02:40:39 +00001331 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1332 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001333 }
1334
Eli Friedmanc7c97142012-01-04 02:40:39 +00001335 StmtResult Stmt(ParseCompoundStatementBody());
1336 BodyScope.Exit();
Hamza Sood8205a812019-05-04 10:49:46 +00001337 TemplateParamScope.Exit();
Eli Friedmanc7c97142012-01-04 02:40:39 +00001338
David Majnemere01c4662015-01-09 05:10:55 +00001339 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001340 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
David Majnemere01c4662015-01-09 05:10:55 +00001341
Eli Friedman898caf82012-01-04 02:46:53 +00001342 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1343 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001344}
1345
Chris Lattner29375652006-12-04 18:06:35 +00001346/// ParseCXXCasts - This handles the various ways to cast expressions to another
1347/// type.
1348///
1349/// postfix-expression: [C++ 5.2p1]
1350/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1351/// 'static_cast' '<' type-name '>' '(' expression ')'
1352/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1353/// 'const_cast' '<' type-name '>' '(' expression ')'
1354///
John McCalldadc5752010-08-24 06:29:42 +00001355ExprResult Parser::ParseCXXCasts() {
Chris Lattner29375652006-12-04 18:06:35 +00001356 tok::TokenKind Kind = Tok.getKind();
Craig Topper161e4db2014-05-21 06:02:52 +00001357 const char *CastName = nullptr; // For error messages
Chris Lattner29375652006-12-04 18:06:35 +00001358
1359 switch (Kind) {
David Blaikieaa347f92011-09-23 20:26:49 +00001360 default: llvm_unreachable("Unknown C++ cast!");
Chris Lattner29375652006-12-04 18:06:35 +00001361 case tok::kw_const_cast: CastName = "const_cast"; break;
1362 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1363 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1364 case tok::kw_static_cast: CastName = "static_cast"; break;
1365 }
1366
1367 SourceLocation OpLoc = ConsumeToken();
1368 SourceLocation LAngleBracketLoc = Tok.getLocation();
1369
Richard Smith55858492011-04-14 21:45:45 +00001370 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1371 // diagnose error, suggest fix, and recover parsing.
Richard Smith62e66302012-08-20 17:37:52 +00001372 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1373 Token Next = NextToken();
1374 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1375 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1376 }
Richard Smith55858492011-04-14 21:45:45 +00001377
Chris Lattner29375652006-12-04 18:06:35 +00001378 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redld65cea82008-12-11 22:51:44 +00001379 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001380
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001381 // Parse the common declaration-specifiers piece.
1382 DeclSpec DS(AttrFactory);
1383 ParseSpecifierQualifierList(DS);
1384
1385 // Parse the abstract-declarator, if present.
Faisal Vali421b2d12017-12-29 05:41:00 +00001386 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001387 ParseDeclarator(DeclaratorInfo);
1388
Chris Lattner29375652006-12-04 18:06:35 +00001389 SourceLocation RAngleBracketLoc = Tok.getLocation();
1390
Alp Toker383d2c42014-01-01 03:08:43 +00001391 if (ExpectAndConsume(tok::greater))
Alp Tokerec543272013-12-24 09:48:30 +00001392 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
Chris Lattner29375652006-12-04 18:06:35 +00001393
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001394 BalancedDelimiterTracker T(*this, tok::l_paren);
Chris Lattner29375652006-12-04 18:06:35 +00001395
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001396 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001397 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001398
John McCalldadc5752010-08-24 06:29:42 +00001399 ExprResult Result = ParseExpression();
Mike Stump11289f42009-09-09 15:08:12 +00001400
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001401 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001402 T.consumeClose();
Chris Lattner29375652006-12-04 18:06:35 +00001403
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001404 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregore200adc2008-10-27 19:41:14 +00001405 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001406 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor220cac52009-02-18 17:45:20 +00001407 RAngleBracketLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00001408 T.getOpenLocation(), Result.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001409 T.getCloseLocation());
Chris Lattner29375652006-12-04 18:06:35 +00001410
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001411 return Result;
Chris Lattner29375652006-12-04 18:06:35 +00001412}
Bill Wendling4073ed52007-02-13 01:51:42 +00001413
Sebastian Redlc4704762008-11-11 11:37:55 +00001414/// ParseCXXTypeid - This handles the C++ typeid expression.
1415///
1416/// postfix-expression: [C++ 5.2p1]
1417/// 'typeid' '(' expression ')'
1418/// 'typeid' '(' type-id ')'
1419///
John McCalldadc5752010-08-24 06:29:42 +00001420ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc4704762008-11-11 11:37:55 +00001421 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1422
1423 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001424 SourceLocation LParenLoc, RParenLoc;
1425 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc4704762008-11-11 11:37:55 +00001426
1427 // typeid expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001428 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redld65cea82008-12-11 22:51:44 +00001429 return ExprError();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001430 LParenLoc = T.getOpenLocation();
Sebastian Redlc4704762008-11-11 11:37:55 +00001431
John McCalldadc5752010-08-24 06:29:42 +00001432 ExprResult Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001433
Richard Smith4f605af2012-08-18 00:55:03 +00001434 // C++0x [expr.typeid]p3:
1435 // When typeid is applied to an expression other than an lvalue of a
1436 // polymorphic class type [...] The expression is an unevaluated
1437 // operand (Clause 5).
1438 //
1439 // Note that we can't tell whether the expression is an lvalue of a
1440 // polymorphic class type until after we've parsed the expression; we
1441 // speculatively assume the subexpression is unevaluated, and fix it up
1442 // later.
1443 //
1444 // We enter the unevaluated context before trying to determine whether we
1445 // have a type-id, because the tentative parse logic will try to resolve
1446 // names, and must treat them as unevaluated.
Faisal Valid143a0c2017-04-01 21:30:49 +00001447 EnterExpressionEvaluationContext Unevaluated(
1448 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1449 Sema::ReuseLambdaContextDecl);
Richard Smith4f605af2012-08-18 00:55:03 +00001450
Sebastian Redlc4704762008-11-11 11:37:55 +00001451 if (isTypeIdInParens()) {
Douglas Gregor220cac52009-02-18 17:45:20 +00001452 TypeResult Ty = ParseTypeName();
Sebastian Redlc4704762008-11-11 11:37:55 +00001453
1454 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001455 T.consumeClose();
1456 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001457 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00001458 return ExprError();
Sebastian Redlc4704762008-11-11 11:37:55 +00001459
1460 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallba7bf592010-08-24 05:47:05 +00001461 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001462 } else {
1463 Result = ParseExpression();
1464
1465 // Match the ')'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001466 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001467 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc4704762008-11-11 11:37:55 +00001468 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001469 T.consumeClose();
1470 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001471 if (RParenLoc.isInvalid())
1472 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00001473
Sebastian Redlc4704762008-11-11 11:37:55 +00001474 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001475 Result.get(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001476 }
1477 }
1478
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001479 return Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001480}
1481
Francois Pichet9f4f2072010-09-08 12:20:18 +00001482/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1483///
1484/// '__uuidof' '(' expression ')'
1485/// '__uuidof' '(' type-id ')'
1486///
1487ExprResult Parser::ParseCXXUuidof() {
1488 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1489
1490 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001491 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001492
1493 // __uuidof expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001494 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet9f4f2072010-09-08 12:20:18 +00001495 return ExprError();
1496
1497 ExprResult Result;
1498
1499 if (isTypeIdInParens()) {
1500 TypeResult Ty = ParseTypeName();
1501
1502 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001503 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001504
1505 if (Ty.isInvalid())
1506 return ExprError();
1507
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001508 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
Fangrui Song6907ce22018-07-30 19:24:48 +00001509 Ty.get().getAsOpaquePtr(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001510 T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001511 } else {
Faisal Valid143a0c2017-04-01 21:30:49 +00001512 EnterExpressionEvaluationContext Unevaluated(
1513 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001514 Result = ParseExpression();
1515
1516 // Match the ')'.
1517 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001518 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001519 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001520 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001521
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001522 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1523 /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001524 Result.get(), T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001525 }
1526 }
1527
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001528 return Result;
Francois Pichet9f4f2072010-09-08 12:20:18 +00001529}
1530
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001531/// Parse a C++ pseudo-destructor expression after the base,
Douglas Gregore610ada2010-02-24 18:44:31 +00001532/// . or -> operator, and nested-name-specifier have already been
1533/// parsed.
1534///
1535/// postfix-expression: [C++ 5.2]
1536/// postfix-expression . pseudo-destructor-name
1537/// postfix-expression -> pseudo-destructor-name
1538///
Fangrui Song6907ce22018-07-30 19:24:48 +00001539/// pseudo-destructor-name:
1540/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1541/// ::[opt] nested-name-specifier template simple-template-id ::
1542/// ~type-name
Douglas Gregore610ada2010-02-24 18:44:31 +00001543/// ::[opt] nested-name-specifier[opt] ~type-name
Fangrui Song6907ce22018-07-30 19:24:48 +00001544///
1545ExprResult
Craig Toppera2c51532014-10-30 05:30:05 +00001546Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00001547 tok::TokenKind OpKind,
1548 CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +00001549 ParsedType ObjectType) {
Douglas Gregore610ada2010-02-24 18:44:31 +00001550 // We're parsing either a pseudo-destructor-name or a dependent
1551 // member access that has the same form as a
1552 // pseudo-destructor-name. We parse both in the same way and let
1553 // the action model sort them out.
1554 //
1555 // Note that the ::[opt] nested-name-specifier[opt] has already
1556 // been parsed, and if there was a simple-template-id, it has
1557 // been coalesced into a template-id annotation token.
1558 UnqualifiedId FirstTypeName;
1559 SourceLocation CCLoc;
1560 if (Tok.is(tok::identifier)) {
1561 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1562 ConsumeToken();
1563 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1564 CCLoc = ConsumeToken();
1565 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001566 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1567 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregore610ada2010-02-24 18:44:31 +00001568 FirstTypeName.setTemplateId(
1569 (TemplateIdAnnotation *)Tok.getAnnotationValue());
Richard Smithaf3b3252017-05-18 19:21:48 +00001570 ConsumeAnnotationToken();
Douglas Gregore610ada2010-02-24 18:44:31 +00001571 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1572 CCLoc = ConsumeToken();
1573 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001574 FirstTypeName.setIdentifier(nullptr, SourceLocation());
Douglas Gregore610ada2010-02-24 18:44:31 +00001575 }
1576
1577 // Parse the tilde.
1578 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1579 SourceLocation TildeLoc = ConsumeToken();
David Blaikie1d578782011-12-16 16:03:09 +00001580
1581 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1582 DeclSpec DS(AttrFactory);
Benjamin Kramer198e0832011-12-18 12:18:02 +00001583 ParseDecltypeSpecifier(DS);
Faisal Vali090da2d2018-01-01 18:23:28 +00001584 if (DS.getTypeSpecType() == TST_error)
David Blaikie1d578782011-12-16 16:03:09 +00001585 return ExprError();
David Majnemerced8bdf2015-02-25 17:36:15 +00001586 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1587 TildeLoc, DS);
David Blaikie1d578782011-12-16 16:03:09 +00001588 }
1589
Douglas Gregore610ada2010-02-24 18:44:31 +00001590 if (!Tok.is(tok::identifier)) {
1591 Diag(Tok, diag::err_destructor_tilde_identifier);
1592 return ExprError();
1593 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001594
Douglas Gregore610ada2010-02-24 18:44:31 +00001595 // Parse the second type.
1596 UnqualifiedId SecondTypeName;
1597 IdentifierInfo *Name = Tok.getIdentifierInfo();
1598 SourceLocation NameLoc = ConsumeToken();
1599 SecondTypeName.setIdentifier(Name, NameLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001600
Douglas Gregore610ada2010-02-24 18:44:31 +00001601 // If there is a '<', the second type name is a template-id. Parse
1602 // it as such.
1603 if (Tok.is(tok::less) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +00001604 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1605 Name, NameLoc,
1606 false, ObjectType, SecondTypeName,
1607 /*AssumeTemplateName=*/true))
Douglas Gregore610ada2010-02-24 18:44:31 +00001608 return ExprError();
1609
David Majnemerced8bdf2015-02-25 17:36:15 +00001610 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1611 SS, FirstTypeName, CCLoc, TildeLoc,
1612 SecondTypeName);
Douglas Gregore610ada2010-02-24 18:44:31 +00001613}
1614
Bill Wendling4073ed52007-02-13 01:51:42 +00001615/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1616///
1617/// boolean-literal: [C++ 2.13.5]
1618/// 'true'
1619/// 'false'
John McCalldadc5752010-08-24 06:29:42 +00001620ExprResult Parser::ParseCXXBoolLiteral() {
Bill Wendling4073ed52007-02-13 01:51:42 +00001621 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001622 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Bill Wendling4073ed52007-02-13 01:51:42 +00001623}
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001624
1625/// ParseThrowExpression - This handles the C++ throw expression.
1626///
1627/// throw-expression: [C++ 15]
1628/// 'throw' assignment-expression[opt]
John McCalldadc5752010-08-24 06:29:42 +00001629ExprResult Parser::ParseThrowExpression() {
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001630 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001631 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redld65cea82008-12-11 22:51:44 +00001632
Chris Lattner65dd8432008-04-06 06:02:23 +00001633 // If the current token isn't the start of an assignment-expression,
1634 // then the expression is not present. This handles things like:
1635 // "C ? throw : (void)42", which is crazy but legal.
1636 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1637 case tok::semi:
1638 case tok::r_paren:
1639 case tok::r_square:
1640 case tok::r_brace:
1641 case tok::colon:
1642 case tok::comma:
Craig Topper161e4db2014-05-21 06:02:52 +00001643 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001644
Chris Lattner65dd8432008-04-06 06:02:23 +00001645 default:
John McCalldadc5752010-08-24 06:29:42 +00001646 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001647 if (Expr.isInvalid()) return Expr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001648 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
Chris Lattner65dd8432008-04-06 06:02:23 +00001649 }
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001650}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001651
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001652/// Parse the C++ Coroutines co_yield expression.
Richard Smith0e304ea2015-10-22 04:46:14 +00001653///
1654/// co_yield-expression:
1655/// 'co_yield' assignment-expression[opt]
1656ExprResult Parser::ParseCoyieldExpression() {
1657 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1658
1659 SourceLocation Loc = ConsumeToken();
Richard Smithae3d1472015-11-20 22:47:10 +00001660 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1661 : ParseAssignmentExpression();
Richard Smithcfd53b42015-10-22 06:13:50 +00001662 if (!Expr.isInvalid())
Richard Smith9f690bd2015-10-27 06:02:45 +00001663 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
Richard Smith0e304ea2015-10-22 04:46:14 +00001664 return Expr;
1665}
1666
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001667/// ParseCXXThis - This handles the C++ 'this' pointer.
1668///
1669/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1670/// a non-lvalue expression whose value is the address of the object for which
1671/// the function is called.
John McCalldadc5752010-08-24 06:29:42 +00001672ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001673 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1674 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001675 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001676}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001677
1678/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1679/// Can be interpreted either as function-style casting ("int(x)")
1680/// or class type construction ("ClassType(x,y,z)")
1681/// or creation of a value-initialized type ("int()").
Sebastian Redl3da34892011-06-05 12:23:16 +00001682/// See [C++ 5.2.3].
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001683///
1684/// postfix-expression: [C++ 5.2p1]
Sebastian Redl3da34892011-06-05 12:23:16 +00001685/// simple-type-specifier '(' expression-list[opt] ')'
1686/// [C++0x] simple-type-specifier braced-init-list
1687/// typename-specifier '(' expression-list[opt] ')'
1688/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001689///
Richard Smith600b5262017-01-26 20:40:47 +00001690/// In C++1z onwards, the type specifier can also be a template-name.
John McCalldadc5752010-08-24 06:29:42 +00001691ExprResult
Sebastian Redld65cea82008-12-11 22:51:44 +00001692Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Faisal Vali421b2d12017-12-29 05:41:00 +00001693 Declarator DeclaratorInfo(DS, DeclaratorContext::FunctionalCastContext);
John McCallba7bf592010-08-24 05:47:05 +00001694 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001695
Sebastian Redl3da34892011-06-05 12:23:16 +00001696 assert((Tok.is(tok::l_paren) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001697 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redl3da34892011-06-05 12:23:16 +00001698 && "Expected '(' or '{'!");
Douglas Gregor94a32472011-01-11 00:33:19 +00001699
Sebastian Redl3da34892011-06-05 12:23:16 +00001700 if (Tok.is(tok::l_brace)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001701 ExprResult Init = ParseBraceInitializer();
1702 if (Init.isInvalid())
1703 return Init;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001704 Expr *InitList = Init.get();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001705 return Actions.ActOnCXXTypeConstructExpr(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001706 TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001707 InitList->getEndLoc(), /*ListInitialization=*/true);
Sebastian Redl3da34892011-06-05 12:23:16 +00001708 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001709 BalancedDelimiterTracker T(*this, tok::l_paren);
1710 T.consumeOpen();
Sebastian Redl3da34892011-06-05 12:23:16 +00001711
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00001712 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1713
Benjamin Kramerf0623432012-08-23 22:51:59 +00001714 ExprVector Exprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00001715 CommaLocsTy CommaLocs;
1716
Ilya Biryukovff2a9972019-02-26 11:01:50 +00001717 auto RunSignatureHelp = [&]() {
1718 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
1719 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
1720 DS.getEndLoc(), Exprs, T.getOpenLocation());
1721 CalledSignatureHelp = true;
1722 return PreferredType;
1723 };
1724
Sebastian Redl3da34892011-06-05 12:23:16 +00001725 if (Tok.isNot(tok::r_paren)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00001726 if (ParseExpressionList(Exprs, CommaLocs, [&] {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00001727 PreferredType.enterFunctionArgument(Tok.getLocation(),
1728 RunSignatureHelp);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001729 })) {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00001730 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1731 RunSignatureHelp();
Alexey Bataevee6507d2013-11-18 08:17:37 +00001732 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00001733 return ExprError();
1734 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001735 }
Sebastian Redl3da34892011-06-05 12:23:16 +00001736
1737 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001738 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00001739
1740 // TypeRep could be null, if it references an invalid typedef.
1741 if (!TypeRep)
1742 return ExprError();
1743
1744 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1745 "Unexpected number of commas!");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001746 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1747 Exprs, T.getCloseLocation(),
1748 /*ListInitialization=*/false);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001749 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001750}
1751
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001752/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001753///
1754/// condition:
1755/// expression
1756/// type-specifier-seq declarator '=' assignment-expression
Richard Smith2a15b742012-02-22 06:49:09 +00001757/// [C++11] type-specifier-seq declarator '=' initializer-clause
1758/// [C++11] type-specifier-seq declarator braced-init-list
Zhihao Yuanc81f4532017-12-07 07:03:15 +00001759/// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1760/// brace-or-equal-initializer
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001761/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1762/// '=' assignment-expression
1763///
Richard Smithc7a05a92016-06-29 21:17:59 +00001764/// In C++1z, a condition may in some contexts be preceded by an
1765/// optional init-statement. This function will parse that too.
1766///
1767/// \param InitStmt If non-null, an init-statement is permitted, and if present
1768/// will be parsed and stored here.
1769///
Douglas Gregore60e41a2010-05-06 17:25:47 +00001770/// \param Loc The location of the start of the statement that requires this
1771/// condition, e.g., the "for" in a for loop.
1772///
Richard Smith8baa5002018-09-28 18:44:09 +00001773/// \param FRI If non-null, a for range declaration is permitted, and if
1774/// present will be parsed and stored here, and a null result will be returned.
1775///
Richard Smith03a4aa32016-06-23 19:02:52 +00001776/// \returns The parsed condition.
Richard Smithc7a05a92016-06-29 21:17:59 +00001777Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1778 SourceLocation Loc,
Richard Smith8baa5002018-09-28 18:44:09 +00001779 Sema::ConditionKind CK,
1780 ForRangeInfo *FRI) {
Richard Smithbf5bcf22018-06-26 23:20:26 +00001781 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00001782 PreferredType.enterCondition(Actions, Tok.getLocation());
Richard Smithbf5bcf22018-06-26 23:20:26 +00001783
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001784 if (Tok.is(tok::code_completion)) {
John McCallfaf5fb42010-08-26 23:41:50 +00001785 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001786 cutOffParsing();
Richard Smith03a4aa32016-06-23 19:02:52 +00001787 return Sema::ConditionError();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001788 }
1789
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001790 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001791 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001792
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001793 const auto WarnOnInit = [this, &CK] {
1794 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
1795 ? diag::warn_cxx14_compat_init_statement
1796 : diag::ext_init_statement)
1797 << (CK == Sema::ConditionKind::Switch);
1798 };
1799
Richard Smithc7a05a92016-06-29 21:17:59 +00001800 // Determine what kind of thing we have.
Richard Smith8baa5002018-09-28 18:44:09 +00001801 switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
Richard Smithc7a05a92016-06-29 21:17:59 +00001802 case ConditionOrInitStatement::Expression: {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001803 ProhibitAttributes(attrs);
1804
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001805 // We can have an empty expression here.
1806 // if (; true);
1807 if (InitStmt && Tok.is(tok::semi)) {
1808 WarnOnInit();
Roman Lebedev377748f2018-11-20 18:59:05 +00001809 SourceLocation SemiLoc = Tok.getLocation();
1810 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
1811 Diag(SemiLoc, diag::warn_empty_init_statement)
1812 << (CK == Sema::ConditionKind::Switch)
1813 << FixItHint::CreateRemoval(SemiLoc);
1814 }
1815 ConsumeToken();
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001816 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
1817 return ParseCXXCondition(nullptr, Loc, CK);
1818 }
1819
Douglas Gregore60e41a2010-05-06 17:25:47 +00001820 // Parse the expression.
Richard Smith03a4aa32016-06-23 19:02:52 +00001821 ExprResult Expr = ParseExpression(); // expression
1822 if (Expr.isInvalid())
1823 return Sema::ConditionError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00001824
Richard Smithc7a05a92016-06-29 21:17:59 +00001825 if (InitStmt && Tok.is(tok::semi)) {
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001826 WarnOnInit();
Richard Smithc7a05a92016-06-29 21:17:59 +00001827 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1828 ConsumeToken();
1829 return ParseCXXCondition(nullptr, Loc, CK);
1830 }
1831
Richard Smith03a4aa32016-06-23 19:02:52 +00001832 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001833 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001834
Richard Smithc7a05a92016-06-29 21:17:59 +00001835 case ConditionOrInitStatement::InitStmtDecl: {
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001836 WarnOnInit();
Richard Smithc7a05a92016-06-29 21:17:59 +00001837 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Faisal Vali421b2d12017-12-29 05:41:00 +00001838 DeclGroupPtrTy DG =
1839 ParseSimpleDeclaration(DeclaratorContext::InitStmtContext, DeclEnd,
1840 attrs, /*RequireSemi=*/true);
Richard Smithc7a05a92016-06-29 21:17:59 +00001841 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1842 return ParseCXXCondition(nullptr, Loc, CK);
1843 }
1844
Richard Smith8baa5002018-09-28 18:44:09 +00001845 case ConditionOrInitStatement::ForRangeDecl: {
1846 assert(FRI && "should not parse a for range declaration here");
1847 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1848 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1849 DeclaratorContext::ForContext, DeclEnd, attrs, false, FRI);
1850 FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1851 return Sema::ConditionResult();
1852 }
1853
Richard Smithc7a05a92016-06-29 21:17:59 +00001854 case ConditionOrInitStatement::ConditionDecl:
1855 case ConditionOrInitStatement::Error:
1856 break;
1857 }
1858
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001859 // type-specifier-seq
John McCall084e83d2011-03-24 11:26:52 +00001860 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +00001861 DS.takeAttributesFrom(attrs);
Faisal Vali7db85c52017-12-31 00:06:40 +00001862 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001863
1864 // declarator
Faisal Vali421b2d12017-12-29 05:41:00 +00001865 Declarator DeclaratorInfo(DS, DeclaratorContext::ConditionContext);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001866 ParseDeclarator(DeclaratorInfo);
1867
1868 // simple-asm-expr[opt]
1869 if (Tok.is(tok::kw_asm)) {
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001870 SourceLocation Loc;
John McCalldadc5752010-08-24 06:29:42 +00001871 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001872 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001873 SkipUntil(tok::semi, StopAtSemi);
Richard Smith03a4aa32016-06-23 19:02:52 +00001874 return Sema::ConditionError();
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001875 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001876 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001877 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001878 }
1879
1880 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001881 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001882
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001883 // Type-check the declaration itself.
Fangrui Song6907ce22018-07-30 19:24:48 +00001884 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall53fa7142010-12-24 02:08:15 +00001885 DeclaratorInfo);
Richard Smith03a4aa32016-06-23 19:02:52 +00001886 if (Dcl.isInvalid())
1887 return Sema::ConditionError();
1888 Decl *DeclOut = Dcl.get();
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001889
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001890 // '=' assignment-expression
Richard Trieuc64d3232012-01-18 22:54:52 +00001891 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith2a15b742012-02-22 06:49:09 +00001892 bool CopyInitialization = isTokenEqualOrEqualTypo();
1893 if (CopyInitialization)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001894 ConsumeToken();
Richard Smith2a15b742012-02-22 06:49:09 +00001895
1896 ExprResult InitExpr = ExprError();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001897 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith2a15b742012-02-22 06:49:09 +00001898 Diag(Tok.getLocation(),
1899 diag::warn_cxx98_compat_generalized_initializer_lists);
1900 InitExpr = ParseBraceInitializer();
1901 } else if (CopyInitialization) {
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00001902 PreferredType.enterVariableInit(Tok.getLocation(), DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001903 InitExpr = ParseAssignmentExpression();
1904 } else if (Tok.is(tok::l_paren)) {
1905 // This was probably an attempt to initialize the variable.
1906 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001907 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith2a15b742012-02-22 06:49:09 +00001908 RParen = ConsumeParen();
Richard Smith03a4aa32016-06-23 19:02:52 +00001909 Diag(DeclOut->getLocation(),
Richard Smith2a15b742012-02-22 06:49:09 +00001910 diag::err_expected_init_in_condition_lparen)
1911 << SourceRange(LParen, RParen);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001912 } else {
Richard Smith03a4aa32016-06-23 19:02:52 +00001913 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001914 }
Richard Smith2a15b742012-02-22 06:49:09 +00001915
1916 if (!InitExpr.isInvalid())
Richard Smith3beb7c62017-01-12 02:27:38 +00001917 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
Richard Smith27d807c2013-04-30 13:56:41 +00001918 else
1919 Actions.ActOnInitializerError(DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001920
Richard Smithb2bc2e62011-02-21 20:05:19 +00001921 Actions.FinalizeDeclaration(DeclOut);
Richard Smith03a4aa32016-06-23 19:02:52 +00001922 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001923}
1924
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001925/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1926/// This should only be called when the current token is known to be part of
1927/// simple-type-specifier.
1928///
1929/// simple-type-specifier:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001930/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001931/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1932/// char
1933/// wchar_t
1934/// bool
1935/// short
1936/// int
1937/// long
1938/// signed
1939/// unsigned
1940/// float
1941/// double
1942/// void
1943/// [GNU] typeof-specifier
1944/// [C++0x] auto [TODO]
1945///
1946/// type-name:
1947/// class-name
1948/// enum-name
1949/// typedef-name
1950///
1951void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1952 DS.SetRangeStart(Tok.getLocation());
1953 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +00001954 unsigned DiagID;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001955 SourceLocation Loc = Tok.getLocation();
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001956 const clang::PrintingPolicy &Policy =
1957 Actions.getASTContext().getPrintingPolicy();
Mike Stump11289f42009-09-09 15:08:12 +00001958
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001959 switch (Tok.getKind()) {
Chris Lattner45ddec32009-01-05 00:13:00 +00001960 case tok::identifier: // foo::bar
1961 case tok::coloncolon: // ::foo::bar
David Blaikie83d382b2011-09-23 05:06:16 +00001962 llvm_unreachable("Annotation token should already be formed!");
Mike Stump11289f42009-09-09 15:08:12 +00001963 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001964 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner45ddec32009-01-05 00:13:00 +00001965
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001966 // type-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00001967 case tok::annot_typename: {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001968 if (getTypeAnnotation(Tok))
1969 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001970 getTypeAnnotation(Tok), Policy);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001971 else
1972 DS.SetTypeSpecError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001973
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001974 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00001975 ConsumeAnnotationToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00001976
Craig Topper25122412015-11-15 03:32:11 +00001977 DS.Finish(Actions, Policy);
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001978 return;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001979 }
Mike Stump11289f42009-09-09 15:08:12 +00001980
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001981 // builtin types
1982 case tok::kw_short:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001983 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001984 break;
1985 case tok::kw_long:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001986 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001987 break;
Francois Pichet84133e42011-04-28 01:59:37 +00001988 case tok::kw___int64:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001989 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00001990 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001991 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00001992 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001993 break;
1994 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00001995 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001996 break;
1997 case tok::kw_void:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001998 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001999 break;
2000 case tok::kw_char:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002001 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002002 break;
2003 case tok::kw_int:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002004 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002005 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00002006 case tok::kw___int128:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002007 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00002008 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002009 case tok::kw_half:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002010 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002011 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002012 case tok::kw_float:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002013 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002014 break;
2015 case tok::kw_double:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002016 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002017 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002018 case tok::kw__Float16:
2019 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
2020 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002021 case tok::kw___float128:
2022 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
2023 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002024 case tok::kw_wchar_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002025 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002026 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00002027 case tok::kw_char8_t:
2028 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
2029 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002030 case tok::kw_char16_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002031 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002032 break;
2033 case tok::kw_char32_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002034 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00002035 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002036 case tok::kw_bool:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00002037 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002038 break;
Anastasia Stulova2c4730d2019-02-15 12:07:57 +00002039#define GENERIC_IMAGE_TYPE(ImgType, Id) \
2040 case tok::kw_##ImgType##_t: \
2041 DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \
2042 Policy); \
2043 break;
2044#include "clang/Basic/OpenCLImageTypes.def"
2045
David Blaikie25896afb2012-01-24 05:47:35 +00002046 case tok::annot_decltype:
2047 case tok::kw_decltype:
2048 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
Craig Topper25122412015-11-15 03:32:11 +00002049 return DS.Finish(Actions, Policy);
Mike Stump11289f42009-09-09 15:08:12 +00002050
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002051 // GNU typeof support.
2052 case tok::kw_typeof:
2053 ParseTypeofSpecifier(DS);
Craig Topper25122412015-11-15 03:32:11 +00002054 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002055 return;
2056 }
Richard Smithaf3b3252017-05-18 19:21:48 +00002057 ConsumeAnyToken();
2058 DS.SetRangeEnd(PrevTokLocation);
Craig Topper25122412015-11-15 03:32:11 +00002059 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002060}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002061
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002062/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2063/// [dcl.name]), which is a non-empty sequence of type-specifiers,
2064/// e.g., "const short int". Note that the DeclSpec is *not* finished
2065/// by parsing the type-specifier-seq, because these sequences are
2066/// typically followed by some form of declarator. Returns true and
2067/// emits diagnostics if this is not a type-specifier-seq, false
2068/// otherwise.
2069///
2070/// type-specifier-seq: [C++ 8.1]
2071/// type-specifier type-specifier-seq[opt]
2072///
2073bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Faisal Vali7db85c52017-12-31 00:06:40 +00002074 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
Craig Topper25122412015-11-15 03:32:11 +00002075 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002076 return false;
2077}
2078
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002079/// Finish parsing a C++ unqualified-id that is a template-id of
Fangrui Song6907ce22018-07-30 19:24:48 +00002080/// some form.
Douglas Gregor7861a802009-11-03 01:35:08 +00002081///
2082/// This routine is invoked when a '<' is encountered after an identifier or
2083/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2084/// whether the unqualified-id is actually a template-id. This routine will
2085/// then parse the template arguments and form the appropriate template-id to
2086/// return to the caller.
2087///
2088/// \param SS the nested-name-specifier that precedes this template-id, if
2089/// we're actually parsing a qualified-id.
2090///
2091/// \param Name for constructor and destructor names, this is the actual
2092/// identifier that may be a template-name.
2093///
Fangrui Song6907ce22018-07-30 19:24:48 +00002094/// \param NameLoc the location of the class-name in a constructor or
Douglas Gregor7861a802009-11-03 01:35:08 +00002095/// destructor.
2096///
Fangrui Song6907ce22018-07-30 19:24:48 +00002097/// \param EnteringContext whether we're entering the scope of the
Douglas Gregor7861a802009-11-03 01:35:08 +00002098/// nested-name-specifier.
2099///
Douglas Gregor127ea592009-11-03 21:24:04 +00002100/// \param ObjectType if this unqualified-id occurs within a member access
2101/// expression, the type of the base object whose member is being accessed.
2102///
Douglas Gregor7861a802009-11-03 01:35:08 +00002103/// \param Id as input, describes the template-name or operator-function-id
2104/// that precedes the '<'. If template arguments were parsed successfully,
2105/// will be updated with the template-id.
Fangrui Song6907ce22018-07-30 19:24:48 +00002106///
Douglas Gregore610ada2010-02-24 18:44:31 +00002107/// \param AssumeTemplateId When true, this routine will assume that the name
Fangrui Song6907ce22018-07-30 19:24:48 +00002108/// refers to a template without performing name lookup to verify.
Douglas Gregore610ada2010-02-24 18:44:31 +00002109///
Douglas Gregor7861a802009-11-03 01:35:08 +00002110/// \returns true if a parse error occurred, false otherwise.
2111bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002112 SourceLocation TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002113 IdentifierInfo *Name,
2114 SourceLocation NameLoc,
2115 bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002116 ParsedType ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00002117 UnqualifiedId &Id,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002118 bool AssumeTemplateId) {
Richard Smithc08b6932018-04-27 02:00:13 +00002119 assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
2120
Douglas Gregor7861a802009-11-03 01:35:08 +00002121 TemplateTy Template;
2122 TemplateNameKind TNK = TNK_Non_template;
2123 switch (Id.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00002124 case UnqualifiedIdKind::IK_Identifier:
2125 case UnqualifiedIdKind::IK_OperatorFunctionId:
2126 case UnqualifiedIdKind::IK_LiteralOperatorId:
Douglas Gregore610ada2010-02-24 18:44:31 +00002127 if (AssumeTemplateId) {
Richard Smithfd3dae02017-01-20 00:20:39 +00002128 // We defer the injected-class-name checks until we've found whether
2129 // this template-id is used to form a nested-name-specifier or not.
2130 TNK = Actions.ActOnDependentTemplateName(
2131 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2132 Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002133 if (TNK == TNK_Non_template)
2134 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00002135 } else {
2136 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002137 TNK = Actions.isTemplateName(getCurScope(), SS,
2138 TemplateKWLoc.isValid(), Id,
2139 ObjectType, EnteringContext, Template,
Douglas Gregor786123d2010-05-21 23:18:07 +00002140 MemberOfUnknownSpecialization);
Fangrui Song6907ce22018-07-30 19:24:48 +00002141
Douglas Gregor786123d2010-05-21 23:18:07 +00002142 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2143 ObjectType && IsTemplateArgumentList()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002144 // We have something like t->getAs<T>(), where getAs is a
Douglas Gregor786123d2010-05-21 23:18:07 +00002145 // member of an unknown specialization. However, this will only
2146 // parse correctly as a template, so suggest the keyword 'template'
2147 // before 'getAs' and treat this as a dependent template name.
2148 std::string Name;
Faisal Vali2ab8c152017-12-30 04:15:27 +00002149 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
Douglas Gregor786123d2010-05-21 23:18:07 +00002150 Name = Id.Identifier->getName();
2151 else {
2152 Name = "operator ";
Faisal Vali2ab8c152017-12-30 04:15:27 +00002153 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
Douglas Gregor786123d2010-05-21 23:18:07 +00002154 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2155 else
2156 Name += Id.Identifier->getName();
2157 }
2158 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2159 << Name
2160 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Richard Smithfd3dae02017-01-20 00:20:39 +00002161 TNK = Actions.ActOnDependentTemplateName(
2162 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2163 Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002164 if (TNK == TNK_Non_template)
Fangrui Song6907ce22018-07-30 19:24:48 +00002165 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00002166 }
2167 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002168 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002169
Faisal Vali2ab8c152017-12-30 04:15:27 +00002170 case UnqualifiedIdKind::IK_ConstructorName: {
Douglas Gregor3cf81312009-11-03 23:16:33 +00002171 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002172 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002173 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002174 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002175 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002176 EnteringContext, Template,
2177 MemberOfUnknownSpecialization);
Douglas Gregor7861a802009-11-03 01:35:08 +00002178 break;
2179 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002180
Faisal Vali2ab8c152017-12-30 04:15:27 +00002181 case UnqualifiedIdKind::IK_DestructorName: {
Douglas Gregor3cf81312009-11-03 23:16:33 +00002182 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002183 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002184 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002185 if (ObjectType) {
Richard Smithfd3dae02017-01-20 00:20:39 +00002186 TNK = Actions.ActOnDependentTemplateName(
2187 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2188 EnteringContext, Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002189 if (TNK == TNK_Non_template)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002190 return true;
2191 } else {
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002192 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002193 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002194 EnteringContext, Template,
2195 MemberOfUnknownSpecialization);
Fangrui Song6907ce22018-07-30 19:24:48 +00002196
John McCallba7bf592010-08-24 05:47:05 +00002197 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002198 Diag(NameLoc, diag::err_destructor_template_id)
2199 << Name << SS.getRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00002200 return true;
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002201 }
2202 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002203 break;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002204 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002205
Douglas Gregor7861a802009-11-03 01:35:08 +00002206 default:
2207 return false;
2208 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002209
Douglas Gregor7861a802009-11-03 01:35:08 +00002210 if (TNK == TNK_Non_template)
2211 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00002212
Douglas Gregor7861a802009-11-03 01:35:08 +00002213 // Parse the enclosed template argument list.
2214 SourceLocation LAngleLoc, RAngleLoc;
2215 TemplateArgList TemplateArgs;
Richard Smithc08b6932018-04-27 02:00:13 +00002216 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
2217 RAngleLoc))
Douglas Gregor7861a802009-11-03 01:35:08 +00002218 return true;
Richard Smithc08b6932018-04-27 02:00:13 +00002219
Faisal Vali2ab8c152017-12-30 04:15:27 +00002220 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2221 Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2222 Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002223 // Form a parsed representation of the template-id to be stored in the
2224 // UnqualifiedId.
Douglas Gregor7861a802009-11-03 01:35:08 +00002225
Richard Smith72bfbd82013-12-04 00:28:23 +00002226 // FIXME: Store name for literal operator too.
Faisal Vali43caf672017-05-23 01:07:12 +00002227 IdentifierInfo *TemplateII =
Faisal Vali2ab8c152017-12-30 04:15:27 +00002228 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2229 : nullptr;
2230 OverloadedOperatorKind OpKind =
2231 Id.getKind() == UnqualifiedIdKind::IK_Identifier
2232 ? OO_None
2233 : Id.OperatorFunctionId.Operator;
Douglas Gregor7861a802009-11-03 01:35:08 +00002234
Faisal Vali43caf672017-05-23 01:07:12 +00002235 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2236 SS, TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2237 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
2238
Douglas Gregor7861a802009-11-03 01:35:08 +00002239 Id.setTemplateId(TemplateId);
2240 return false;
2241 }
2242
2243 // Bundle the template arguments together.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002244 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnara4244b432012-01-27 08:46:19 +00002245
Douglas Gregor7861a802009-11-03 01:35:08 +00002246 // Constructor and destructor names.
John McCallfaf5fb42010-08-26 23:41:50 +00002247 TypeResult Type
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002248 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00002249 Template, Name, NameLoc,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002250 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2251 /*IsCtorOrDtorName=*/true);
Douglas Gregor7861a802009-11-03 01:35:08 +00002252 if (Type.isInvalid())
2253 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002254
Faisal Vali2ab8c152017-12-30 04:15:27 +00002255 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
Douglas Gregor7861a802009-11-03 01:35:08 +00002256 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2257 else
2258 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00002259
Douglas Gregor7861a802009-11-03 01:35:08 +00002260 return false;
2261}
2262
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002263/// Parse an operator-function-id or conversion-function-id as part
Douglas Gregor71395fa2009-11-04 00:56:37 +00002264/// of a C++ unqualified-id.
2265///
2266/// This routine is responsible only for parsing the operator-function-id or
2267/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor7861a802009-11-03 01:35:08 +00002268///
2269/// \code
Douglas Gregor7861a802009-11-03 01:35:08 +00002270/// operator-function-id: [C++ 13.5]
2271/// 'operator' operator
2272///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002273/// operator: one of
Douglas Gregor7861a802009-11-03 01:35:08 +00002274/// new delete new[] delete[]
2275/// + - * / % ^ & | ~
2276/// ! = < > += -= *= /= %=
2277/// ^= &= |= << >> >>= <<= == !=
2278/// <= >= && || ++ -- , ->* ->
Richard Smithd30b23d2017-12-01 02:13:10 +00002279/// () [] <=>
Douglas Gregor7861a802009-11-03 01:35:08 +00002280///
2281/// conversion-function-id: [C++ 12.3.2]
2282/// operator conversion-type-id
2283///
2284/// conversion-type-id:
2285/// type-specifier-seq conversion-declarator[opt]
2286///
2287/// conversion-declarator:
2288/// ptr-operator conversion-declarator[opt]
2289/// \endcode
2290///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002291/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor7861a802009-11-03 01:35:08 +00002292/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2293///
Fangrui Song6907ce22018-07-30 19:24:48 +00002294/// \param EnteringContext whether we are entering the scope of the
Douglas Gregor7861a802009-11-03 01:35:08 +00002295/// nested-name-specifier.
2296///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002297/// \param ObjectType if this unqualified-id occurs within a member access
2298/// expression, the type of the base object whose member is being accessed.
2299///
2300/// \param Result on a successful parse, contains the parsed unqualified-id.
2301///
2302/// \returns true if parsing fails, false otherwise.
2303bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002304 ParsedType ObjectType,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002305 UnqualifiedId &Result) {
2306 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
Fangrui Song6907ce22018-07-30 19:24:48 +00002307
Douglas Gregor71395fa2009-11-04 00:56:37 +00002308 // Consume the 'operator' keyword.
2309 SourceLocation KeywordLoc = ConsumeToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00002310
Douglas Gregor71395fa2009-11-04 00:56:37 +00002311 // Determine what kind of operator name we have.
2312 unsigned SymbolIdx = 0;
2313 SourceLocation SymbolLocations[3];
2314 OverloadedOperatorKind Op = OO_None;
2315 switch (Tok.getKind()) {
2316 case tok::kw_new:
2317 case tok::kw_delete: {
2318 bool isNew = Tok.getKind() == tok::kw_new;
2319 // Consume the 'new' or 'delete'.
2320 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002321 // Check for array new/delete.
2322 if (Tok.is(tok::l_square) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002323 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002324 // Consume the '[' and ']'.
2325 BalancedDelimiterTracker T(*this, tok::l_square);
2326 T.consumeOpen();
2327 T.consumeClose();
2328 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002329 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002330
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002331 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2332 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002333 Op = isNew? OO_Array_New : OO_Array_Delete;
2334 } else {
2335 Op = isNew? OO_New : OO_Delete;
2336 }
2337 break;
2338 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002339
Douglas Gregor71395fa2009-11-04 00:56:37 +00002340#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2341 case tok::Token: \
2342 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2343 Op = OO_##Name; \
2344 break;
2345#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2346#include "clang/Basic/OperatorKinds.def"
Fangrui Song6907ce22018-07-30 19:24:48 +00002347
Douglas Gregor71395fa2009-11-04 00:56:37 +00002348 case tok::l_paren: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002349 // Consume the '(' and ')'.
2350 BalancedDelimiterTracker T(*this, tok::l_paren);
2351 T.consumeOpen();
2352 T.consumeClose();
2353 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002354 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002355
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002356 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2357 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002358 Op = OO_Call;
2359 break;
2360 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002361
Douglas Gregor71395fa2009-11-04 00:56:37 +00002362 case tok::l_square: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002363 // Consume the '[' and ']'.
2364 BalancedDelimiterTracker T(*this, tok::l_square);
2365 T.consumeOpen();
2366 T.consumeClose();
2367 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002368 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002369
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002370 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2371 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002372 Op = OO_Subscript;
2373 break;
2374 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002375
Douglas Gregor71395fa2009-11-04 00:56:37 +00002376 case tok::code_completion: {
2377 // Code completion for the operator name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002378 Actions.CodeCompleteOperatorName(getCurScope());
Fangrui Song6907ce22018-07-30 19:24:48 +00002379 cutOffParsing();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002380 // Don't try to parse any further.
2381 return true;
2382 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002383
Douglas Gregor71395fa2009-11-04 00:56:37 +00002384 default:
2385 break;
2386 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002387
Douglas Gregor71395fa2009-11-04 00:56:37 +00002388 if (Op != OO_None) {
2389 // We have parsed an operator-function-id.
2390 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2391 return false;
2392 }
Alexis Hunt34458502009-11-28 04:44:28 +00002393
2394 // Parse a literal-operator-id.
2395 //
Richard Smith6f212062012-10-20 08:41:10 +00002396 // literal-operator-id: C++11 [over.literal]
2397 // operator string-literal identifier
2398 // operator user-defined-string-literal
Alexis Hunt34458502009-11-28 04:44:28 +00002399
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002400 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002401 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Alexis Hunt34458502009-11-28 04:44:28 +00002402
Richard Smith7d182a72012-03-08 23:06:02 +00002403 SourceLocation DiagLoc;
2404 unsigned DiagId = 0;
2405
2406 // We're past translation phase 6, so perform string literal concatenation
2407 // before checking for "".
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002408 SmallVector<Token, 4> Toks;
2409 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith7d182a72012-03-08 23:06:02 +00002410 while (isTokenStringLiteral()) {
2411 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smith6f212062012-10-20 08:41:10 +00002412 // C++11 [over.literal]p1:
2413 // The string-literal or user-defined-string-literal in a
2414 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith7d182a72012-03-08 23:06:02 +00002415 DiagLoc = Tok.getLocation();
2416 DiagId = diag::err_literal_operator_string_prefix;
2417 }
2418 Toks.push_back(Tok);
2419 TokLocs.push_back(ConsumeStringToken());
2420 }
2421
Craig Topper9d5583e2014-06-26 04:58:39 +00002422 StringLiteralParser Literal(Toks, PP);
Richard Smith7d182a72012-03-08 23:06:02 +00002423 if (Literal.hadError)
2424 return true;
2425
2426 // Grab the literal operator's suffix, which will be either the next token
2427 // or a ud-suffix from the string literal.
Craig Topper161e4db2014-05-21 06:02:52 +00002428 IdentifierInfo *II = nullptr;
Richard Smith7d182a72012-03-08 23:06:02 +00002429 SourceLocation SuffixLoc;
2430 if (!Literal.getUDSuffix().empty()) {
2431 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2432 SuffixLoc =
2433 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2434 Literal.getUDSuffixOffset(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002435 PP.getSourceManager(), getLangOpts());
Richard Smith7d182a72012-03-08 23:06:02 +00002436 } else if (Tok.is(tok::identifier)) {
2437 II = Tok.getIdentifierInfo();
2438 SuffixLoc = ConsumeToken();
2439 TokLocs.push_back(SuffixLoc);
2440 } else {
Alp Tokerec543272013-12-24 09:48:30 +00002441 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexis Hunt34458502009-11-28 04:44:28 +00002442 return true;
2443 }
2444
Richard Smith7d182a72012-03-08 23:06:02 +00002445 // The string literal must be empty.
2446 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smith6f212062012-10-20 08:41:10 +00002447 // C++11 [over.literal]p1:
2448 // The string-literal or user-defined-string-literal in a
2449 // literal-operator-id shall [...] contain no characters
2450 // other than the implicit terminating '\0'.
Richard Smith7d182a72012-03-08 23:06:02 +00002451 DiagLoc = TokLocs.front();
2452 DiagId = diag::err_literal_operator_string_not_empty;
2453 }
2454
2455 if (DiagId) {
2456 // This isn't a valid literal-operator-id, but we think we know
2457 // what the user meant. Tell them what they should have written.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002458 SmallString<32> Str;
Richard Smithe87aeb32015-10-08 00:17:59 +00002459 Str += "\"\"";
Richard Smith7d182a72012-03-08 23:06:02 +00002460 Str += II->getName();
2461 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2462 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2463 }
2464
2465 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Richard Smithd091dc12013-12-05 00:58:33 +00002466
2467 return Actions.checkLiteralOperatorId(SS, Result);
Alexis Hunt34458502009-11-28 04:44:28 +00002468 }
Richard Smithd091dc12013-12-05 00:58:33 +00002469
Douglas Gregor71395fa2009-11-04 00:56:37 +00002470 // Parse a conversion-function-id.
2471 //
2472 // conversion-function-id: [C++ 12.3.2]
2473 // operator conversion-type-id
2474 //
2475 // conversion-type-id:
2476 // type-specifier-seq conversion-declarator[opt]
2477 //
2478 // conversion-declarator:
2479 // ptr-operator conversion-declarator[opt]
Fangrui Song6907ce22018-07-30 19:24:48 +00002480
Douglas Gregor71395fa2009-11-04 00:56:37 +00002481 // Parse the type-specifier-seq.
John McCall084e83d2011-03-24 11:26:52 +00002482 DeclSpec DS(AttrFactory);
Douglas Gregora25d65d2009-11-20 22:03:38 +00002483 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregor71395fa2009-11-04 00:56:37 +00002484 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002485
Douglas Gregor71395fa2009-11-04 00:56:37 +00002486 // Parse the conversion-declarator, which is merely a sequence of
2487 // ptr-operators.
Faisal Vali421b2d12017-12-29 05:41:00 +00002488 Declarator D(DS, DeclaratorContext::ConversionIdContext);
Craig Topper161e4db2014-05-21 06:02:52 +00002489 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2490
Douglas Gregor71395fa2009-11-04 00:56:37 +00002491 // Finish up the type.
John McCallfaf5fb42010-08-26 23:41:50 +00002492 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002493 if (Ty.isInvalid())
2494 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002495
Douglas Gregor71395fa2009-11-04 00:56:37 +00002496 // Note that this is a conversion-function-id.
Fangrui Song6907ce22018-07-30 19:24:48 +00002497 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
Douglas Gregor71395fa2009-11-04 00:56:37 +00002498 D.getSourceRange().getEnd());
Fangrui Song6907ce22018-07-30 19:24:48 +00002499 return false;
Douglas Gregor71395fa2009-11-04 00:56:37 +00002500}
2501
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002502/// Parse a C++ unqualified-id (or a C identifier), which describes the
Douglas Gregor71395fa2009-11-04 00:56:37 +00002503/// name of an entity.
2504///
2505/// \code
2506/// unqualified-id: [C++ expr.prim.general]
2507/// identifier
2508/// operator-function-id
2509/// conversion-function-id
2510/// [C++0x] literal-operator-id [TODO]
2511/// ~ class-name
2512/// template-id
2513///
2514/// \endcode
2515///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002516/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor71395fa2009-11-04 00:56:37 +00002517/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2518///
Fangrui Song6907ce22018-07-30 19:24:48 +00002519/// \param EnteringContext whether we are entering the scope of the
Douglas Gregor71395fa2009-11-04 00:56:37 +00002520/// nested-name-specifier.
2521///
Douglas Gregor7861a802009-11-03 01:35:08 +00002522/// \param AllowDestructorName whether we allow parsing of a destructor name.
2523///
2524/// \param AllowConstructorName whether we allow parsing a constructor name.
2525///
Richard Smith35845152017-02-07 01:37:30 +00002526/// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2527///
Douglas Gregor127ea592009-11-03 21:24:04 +00002528/// \param ObjectType if this unqualified-id occurs within a member access
2529/// expression, the type of the base object whose member is being accessed.
2530///
Douglas Gregor7861a802009-11-03 01:35:08 +00002531/// \param Result on a successful parse, contains the parsed unqualified-id.
2532///
2533/// \returns true if parsing fails, false otherwise.
2534bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2535 bool AllowDestructorName,
2536 bool AllowConstructorName,
Richard Smith35845152017-02-07 01:37:30 +00002537 bool AllowDeductionGuide,
John McCallba7bf592010-08-24 05:47:05 +00002538 ParsedType ObjectType,
Richard Smithc08b6932018-04-27 02:00:13 +00002539 SourceLocation *TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002540 UnqualifiedId &Result) {
Richard Smithc08b6932018-04-27 02:00:13 +00002541 if (TemplateKWLoc)
2542 *TemplateKWLoc = SourceLocation();
Douglas Gregorb22ee882010-05-05 05:58:24 +00002543
2544 // Handle 'A::template B'. This is for template-ids which have not
2545 // already been annotated by ParseOptionalCXXScopeSpecifier().
2546 bool TemplateSpecified = false;
Richard Smithc08b6932018-04-27 02:00:13 +00002547 if (Tok.is(tok::kw_template)) {
2548 if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2549 TemplateSpecified = true;
2550 *TemplateKWLoc = ConsumeToken();
2551 } else {
2552 SourceLocation TemplateLoc = ConsumeToken();
2553 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2554 << FixItHint::CreateRemoval(TemplateLoc);
2555 }
Douglas Gregorb22ee882010-05-05 05:58:24 +00002556 }
2557
Douglas Gregor7861a802009-11-03 01:35:08 +00002558 // unqualified-id:
2559 // identifier
2560 // template-id (when it hasn't already been annotated)
2561 if (Tok.is(tok::identifier)) {
2562 // Consume the identifier.
2563 IdentifierInfo *Id = Tok.getIdentifierInfo();
2564 SourceLocation IdLoc = ConsumeToken();
2565
David Blaikiebbafb8a2012-03-11 07:00:24 +00002566 if (!getLangOpts().CPlusPlus) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002567 // If we're not in C++, only identifiers matter. Record the
2568 // identifier and return.
2569 Result.setIdentifier(Id, IdLoc);
2570 return false;
2571 }
2572
Richard Smith35845152017-02-07 01:37:30 +00002573 ParsedTemplateTy TemplateName;
Fangrui Song6907ce22018-07-30 19:24:48 +00002574 if (AllowConstructorName &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002575 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002576 // We have parsed a constructor name.
Richard Smith69bc9aa2018-06-22 19:50:19 +00002577 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2578 EnteringContext);
Richard Smith715ee072018-06-20 21:58:20 +00002579 if (!Ty)
2580 return true;
Abramo Bagnara4244b432012-01-27 08:46:19 +00002581 Result.setConstructorName(Ty, IdLoc, IdLoc);
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002582 } else if (getLangOpts().CPlusPlus17 &&
Richard Smith35845152017-02-07 01:37:30 +00002583 AllowDeductionGuide && SS.isEmpty() &&
2584 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2585 &TemplateName)) {
2586 // We have parsed a template-name naming a deduction guide.
2587 Result.setDeductionGuideName(TemplateName, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002588 } else {
2589 // We have parsed an identifier.
Fangrui Song6907ce22018-07-30 19:24:48 +00002590 Result.setIdentifier(Id, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002591 }
2592
2593 // If the next token is a '<', we may have a template.
Richard Smithc08b6932018-04-27 02:00:13 +00002594 TemplateTy Template;
2595 if (Tok.is(tok::less))
2596 return ParseUnqualifiedIdTemplateId(
2597 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2598 EnteringContext, ObjectType, Result, TemplateSpecified);
2599 else if (TemplateSpecified &&
2600 Actions.ActOnDependentTemplateName(
2601 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2602 EnteringContext, Template,
2603 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2604 return true;
2605
Douglas Gregor7861a802009-11-03 01:35:08 +00002606 return false;
2607 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002608
Douglas Gregor7861a802009-11-03 01:35:08 +00002609 // unqualified-id:
2610 // template-id (already parsed and annotated)
2611 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00002612 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002613
Fangrui Song6907ce22018-07-30 19:24:48 +00002614 // If the template-name names the current class, then this is a constructor
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002615 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002616 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002617 if (SS.isSet()) {
2618 // C++ [class.qual]p2 specifies that a qualified template-name
2619 // is taken as the constructor name where a constructor can be
2620 // declared. Thus, the template arguments are extraneous, so
2621 // complain about them and remove them entirely.
Fangrui Song6907ce22018-07-30 19:24:48 +00002622 Diag(TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002623 diag::err_out_of_line_constructor_template_id)
2624 << TemplateId->Name
Douglas Gregora771f462010-03-31 17:46:05 +00002625 << FixItHint::CreateRemoval(
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002626 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Richard Smith715ee072018-06-20 21:58:20 +00002627 ParsedType Ty = Actions.getConstructorName(
Richard Smith69bc9aa2018-06-22 19:50:19 +00002628 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2629 EnteringContext);
Richard Smith715ee072018-06-20 21:58:20 +00002630 if (!Ty)
2631 return true;
Abramo Bagnara4244b432012-01-27 08:46:19 +00002632 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002633 TemplateId->RAngleLoc);
Richard Smithaf3b3252017-05-18 19:21:48 +00002634 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002635 return false;
2636 }
2637
2638 Result.setConstructorTemplateId(TemplateId);
Richard Smithaf3b3252017-05-18 19:21:48 +00002639 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002640 return false;
2641 }
2642
Douglas Gregor7861a802009-11-03 01:35:08 +00002643 // We have already parsed a template-id; consume the annotation token as
2644 // our unqualified-id.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002645 Result.setTemplateId(TemplateId);
Richard Smithc08b6932018-04-27 02:00:13 +00002646 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2647 if (TemplateLoc.isValid()) {
2648 if (TemplateKWLoc && (ObjectType || SS.isSet()))
2649 *TemplateKWLoc = TemplateLoc;
2650 else
2651 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2652 << FixItHint::CreateRemoval(TemplateLoc);
2653 }
Richard Smithaf3b3252017-05-18 19:21:48 +00002654 ConsumeAnnotationToken();
Douglas Gregor7861a802009-11-03 01:35:08 +00002655 return false;
2656 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002657
Douglas Gregor7861a802009-11-03 01:35:08 +00002658 // unqualified-id:
2659 // operator-function-id
2660 // conversion-function-id
2661 if (Tok.is(tok::kw_operator)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00002662 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor7861a802009-11-03 01:35:08 +00002663 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002664
Alexis Hunted0530f2009-11-28 08:58:14 +00002665 // If we have an operator-function-id or a literal-operator-id and the next
2666 // token is a '<', we may have a
Fangrui Song6907ce22018-07-30 19:24:48 +00002667 //
Douglas Gregor71395fa2009-11-04 00:56:37 +00002668 // template-id:
2669 // operator-function-id < template-argument-list[opt] >
Richard Smithc08b6932018-04-27 02:00:13 +00002670 TemplateTy Template;
Faisal Vali2ab8c152017-12-30 04:15:27 +00002671 if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2672 Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
Richard Smithc08b6932018-04-27 02:00:13 +00002673 Tok.is(tok::less))
2674 return ParseUnqualifiedIdTemplateId(
2675 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2676 SourceLocation(), EnteringContext, ObjectType, Result,
2677 TemplateSpecified);
2678 else if (TemplateSpecified &&
2679 Actions.ActOnDependentTemplateName(
2680 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2681 EnteringContext, Template,
2682 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2683 return true;
Craig Topper161e4db2014-05-21 06:02:52 +00002684
Douglas Gregor7861a802009-11-03 01:35:08 +00002685 return false;
2686 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002687
2688 if (getLangOpts().CPlusPlus &&
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002689 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002690 // C++ [expr.unary.op]p10:
Fangrui Song6907ce22018-07-30 19:24:48 +00002691 // There is an ambiguity in the unary-expression ~X(), where X is a
2692 // class-name. The ambiguity is resolved in favor of treating ~ as a
Douglas Gregor7861a802009-11-03 01:35:08 +00002693 // unary complement rather than treating ~X as referring to a destructor.
Fangrui Song6907ce22018-07-30 19:24:48 +00002694
Douglas Gregor7861a802009-11-03 01:35:08 +00002695 // Parse the '~'.
2696 SourceLocation TildeLoc = ConsumeToken();
David Blaikieecd8a942011-12-08 16:13:53 +00002697
2698 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2699 DeclSpec DS(AttrFactory);
2700 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Richard Smithef2cd8f2017-02-08 20:39:08 +00002701 if (ParsedType Type =
2702 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
David Blaikieecd8a942011-12-08 16:13:53 +00002703 Result.setDestructorName(TildeLoc, Type, EndLoc);
2704 return false;
2705 }
2706 return true;
2707 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002708
Douglas Gregor7861a802009-11-03 01:35:08 +00002709 // Parse the class-name.
2710 if (Tok.isNot(tok::identifier)) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002711 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00002712 return true;
2713 }
2714
Richard Smithefa6f732014-09-06 02:06:12 +00002715 // If the user wrote ~T::T, correct it to T::~T.
Richard Smith64e033f2015-01-15 00:48:52 +00002716 DeclaratorScopeObj DeclScopeObj(*this, SS);
Nico Weber10d02b52015-02-02 04:18:38 +00002717 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
Nico Weberf9e37be2015-01-30 16:53:11 +00002718 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2719 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2720 // it will confuse this recovery logic.
2721 ColonProtectionRAIIObject ColonRAII(*this, false);
2722
Richard Smithefa6f732014-09-06 02:06:12 +00002723 if (SS.isSet()) {
2724 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2725 SS.clear();
2726 }
2727 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2728 return true;
Nico Weber7f8ec522015-02-02 05:33:50 +00002729 if (SS.isNotEmpty())
David Blaikieefdccaa2016-01-15 23:43:34 +00002730 ObjectType = nullptr;
Nico Weberd0045862015-01-30 04:05:15 +00002731 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
Benjamin Kramer3012e592015-03-29 14:35:39 +00002732 !SS.isSet()) {
Richard Smithefa6f732014-09-06 02:06:12 +00002733 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2734 return true;
2735 }
2736
2737 // Recover as if the tilde had been written before the identifier.
2738 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2739 << FixItHint::CreateRemoval(TildeLoc)
2740 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
Richard Smith64e033f2015-01-15 00:48:52 +00002741
2742 // Temporarily enter the scope for the rest of this function.
2743 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2744 DeclScopeObj.EnterDeclaratorScope();
Richard Smithefa6f732014-09-06 02:06:12 +00002745 }
2746
Douglas Gregor7861a802009-11-03 01:35:08 +00002747 // Parse the class-name (or template-name in a simple-template-id).
2748 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2749 SourceLocation ClassNameLoc = ConsumeToken();
Richard Smithefa6f732014-09-06 02:06:12 +00002750
Richard Smithc08b6932018-04-27 02:00:13 +00002751 if (Tok.is(tok::less)) {
David Blaikieefdccaa2016-01-15 23:43:34 +00002752 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
Richard Smithc08b6932018-04-27 02:00:13 +00002753 return ParseUnqualifiedIdTemplateId(
2754 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
2755 ClassNameLoc, EnteringContext, ObjectType, Result, TemplateSpecified);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002756 }
Richard Smithefa6f732014-09-06 02:06:12 +00002757
Douglas Gregor7861a802009-11-03 01:35:08 +00002758 // Note that this is a destructor name.
Fangrui Song6907ce22018-07-30 19:24:48 +00002759 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
John McCallba7bf592010-08-24 05:47:05 +00002760 ClassNameLoc, getCurScope(),
2761 SS, ObjectType,
2762 EnteringContext);
Douglas Gregorfe17d252010-02-16 19:09:40 +00002763 if (!Ty)
Douglas Gregor7861a802009-11-03 01:35:08 +00002764 return true;
Douglas Gregorfe17d252010-02-16 19:09:40 +00002765
Douglas Gregor7861a802009-11-03 01:35:08 +00002766 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002767 return false;
2768 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002769
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002770 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002771 << getLangOpts().CPlusPlus;
Douglas Gregor7861a802009-11-03 01:35:08 +00002772 return true;
2773}
2774
Sebastian Redlbd150f42008-11-21 19:14:01 +00002775/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2776/// memory in a typesafe manner and call constructors.
Mike Stump11289f42009-09-09 15:08:12 +00002777///
Chris Lattner109faf22009-01-04 21:25:24 +00002778/// This method is called to parse the new expression after the optional :: has
2779/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2780/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002781///
2782/// new-expression:
2783/// '::'[opt] 'new' new-placement[opt] new-type-id
2784/// new-initializer[opt]
2785/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2786/// new-initializer[opt]
2787///
2788/// new-placement:
2789/// '(' expression-list ')'
2790///
Sebastian Redl351bb782008-12-02 14:43:59 +00002791/// new-type-id:
2792/// type-specifier-seq new-declarator[opt]
Douglas Gregora3a020a2011-04-15 19:40:02 +00002793/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redl351bb782008-12-02 14:43:59 +00002794///
2795/// new-declarator:
2796/// ptr-operator new-declarator[opt]
2797/// direct-new-declarator
2798///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002799/// new-initializer:
2800/// '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00002801/// [C++0x] braced-init-list
Sebastian Redlbd150f42008-11-21 19:14:01 +00002802///
John McCalldadc5752010-08-24 06:29:42 +00002803ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002804Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2805 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2806 ConsumeToken(); // Consume 'new'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002807
2808 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2809 // second form of new-expression. It can't be a new-type-id.
2810
Benjamin Kramerf0623432012-08-23 22:51:59 +00002811 ExprVector PlacementArgs;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002812 SourceLocation PlacementLParen, PlacementRParen;
2813
Douglas Gregorf2753b32010-07-13 15:54:32 +00002814 SourceRange TypeIdParens;
John McCall084e83d2011-03-24 11:26:52 +00002815 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00002816 Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNewContext);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002817 if (Tok.is(tok::l_paren)) {
2818 // If it turns out to be a placement, we change the type location.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002819 BalancedDelimiterTracker T(*this, tok::l_paren);
2820 T.consumeOpen();
2821 PlacementLParen = T.getOpenLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002822 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002823 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002824 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002825 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002826
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002827 T.consumeClose();
2828 PlacementRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002829 if (PlacementRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002830 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002831 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002832 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002833
Sebastian Redl351bb782008-12-02 14:43:59 +00002834 if (PlacementArgs.empty()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002835 // Reset the placement locations. There was no placement.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002836 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002837 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002838 } else {
2839 // We still need the type.
2840 if (Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002841 BalancedDelimiterTracker T(*this, tok::l_paren);
2842 T.consumeOpen();
Douglas Gregora3a020a2011-04-15 19:40:02 +00002843 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002844 ParseSpecifierQualifierList(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002845 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002846 ParseDeclarator(DeclaratorInfo);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002847 T.consumeClose();
2848 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002849 } else {
Douglas Gregora3a020a2011-04-15 19:40:02 +00002850 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002851 if (ParseCXXTypeSpecifierSeq(DS))
2852 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002853 else {
2854 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002855 ParseDeclaratorInternal(DeclaratorInfo,
2856 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002857 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002858 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002859 }
2860 } else {
Sebastian Redl351bb782008-12-02 14:43:59 +00002861 // A new-type-id is a simplified type-id, where essentially the
2862 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregora3a020a2011-04-15 19:40:02 +00002863 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002864 if (ParseCXXTypeSpecifierSeq(DS))
2865 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002866 else {
2867 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002868 ParseDeclaratorInternal(DeclaratorInfo,
2869 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002870 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002871 }
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002872 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002873 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002874 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002875 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002876
Sebastian Redl6047f072012-02-16 12:22:20 +00002877 ExprResult Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002878
2879 if (Tok.is(tok::l_paren)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00002880 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002881 ExprVector ConstructorArgs;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002882 BalancedDelimiterTracker T(*this, tok::l_paren);
2883 T.consumeOpen();
2884 ConstructorLParen = T.getOpenLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002885 if (Tok.isNot(tok::r_paren)) {
2886 CommaLocsTy CommaLocs;
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002887 auto RunSignatureHelp = [&]() {
2888 ParsedType TypeRep =
2889 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
2890 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
2891 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
2892 DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
2893 CalledSignatureHelp = true;
2894 return PreferredType;
2895 };
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002896 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002897 PreferredType.enterFunctionArgument(Tok.getLocation(),
2898 RunSignatureHelp);
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002899 })) {
Ilya Biryukovff2a9972019-02-26 11:01:50 +00002900 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
2901 RunSignatureHelp();
Alexey Bataevee6507d2013-11-18 08:17:37 +00002902 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002903 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002904 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002905 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002906 T.consumeClose();
2907 ConstructorRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002908 if (ConstructorRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002909 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002910 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002911 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002912 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2913 ConstructorRParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002914 ConstructorArgs);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002915 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002916 Diag(Tok.getLocation(),
2917 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl6047f072012-02-16 12:22:20 +00002918 Initializer = ParseBraceInitializer();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002919 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002920 if (Initializer.isInvalid())
2921 return Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002922
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002923 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002924 PlacementArgs, PlacementRParen,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002925 TypeIdParens, DeclaratorInfo, Initializer.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002926}
2927
Sebastian Redlbd150f42008-11-21 19:14:01 +00002928/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2929/// passed to ParseDeclaratorInternal.
2930///
2931/// direct-new-declarator:
2932/// '[' expression ']'
2933/// direct-new-declarator '[' constant-expression ']'
2934///
Chris Lattner109faf22009-01-04 21:25:24 +00002935void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002936 // Parse the array dimensions.
2937 bool first = true;
2938 while (Tok.is(tok::l_square)) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002939 // An array-size expression can't start with a lambda.
2940 if (CheckProhibitedCXX11Attribute())
2941 continue;
2942
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002943 BalancedDelimiterTracker T(*this, tok::l_square);
2944 T.consumeOpen();
2945
John McCalldadc5752010-08-24 06:29:42 +00002946 ExprResult Size(first ? ParseExpression()
Sebastian Redl59b5e512008-12-11 21:36:32 +00002947 : ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002948 if (Size.isInvalid()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002949 // Recover
Alexey Bataevee6507d2013-11-18 08:17:37 +00002950 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002951 return;
2952 }
2953 first = false;
2954
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002955 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00002956
Bill Wendling44426052012-12-20 19:22:21 +00002957 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002958 ParsedAttributes Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002959 MaybeParseCXX11Attributes(Attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002960
John McCall084e83d2011-03-24 11:26:52 +00002961 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall53fa7142010-12-24 02:08:15 +00002962 /*static=*/false, /*star=*/false,
Erich Keanec480f302018-07-12 21:09:05 +00002963 Size.get(), T.getOpenLocation(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002964 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00002965 std::move(Attrs), T.getCloseLocation());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002966
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002967 if (T.getCloseLocation().isInvalid())
Sebastian Redlbd150f42008-11-21 19:14:01 +00002968 return;
2969 }
2970}
2971
2972/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2973/// This ambiguity appears in the syntax of the C++ new operator.
2974///
2975/// new-expression:
2976/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2977/// new-initializer[opt]
2978///
2979/// new-placement:
2980/// '(' expression-list ')'
2981///
John McCall37ad5512010-08-23 06:44:23 +00002982bool Parser::ParseExpressionListOrTypeId(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002983 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner109faf22009-01-04 21:25:24 +00002984 Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002985 // The '(' was already consumed.
2986 if (isTypeIdInParens()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00002987 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002988 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002989 ParseDeclarator(D);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002990 return D.isInvalidType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002991 }
2992
2993 // It's not a type, it has to be an expression list.
2994 // Discard the comma locations - ActOnCXXNew has enough parameters.
2995 CommaLocsTy CommaLocs;
2996 return ParseExpressionList(PlacementArgs, CommaLocs);
2997}
2998
2999/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
3000/// to free memory allocated by new.
3001///
Chris Lattner109faf22009-01-04 21:25:24 +00003002/// This method is called to parse the 'delete' expression after the optional
3003/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
3004/// and "Start" is its location. Otherwise, "Start" is the location of the
3005/// 'delete' token.
3006///
Sebastian Redlbd150f42008-11-21 19:14:01 +00003007/// delete-expression:
3008/// '::'[opt] 'delete' cast-expression
3009/// '::'[opt] 'delete' '[' ']' cast-expression
John McCalldadc5752010-08-24 06:29:42 +00003010ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00003011Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
3012 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
3013 ConsumeToken(); // Consume 'delete'
Sebastian Redlbd150f42008-11-21 19:14:01 +00003014
3015 // Array delete?
3016 bool ArrayDelete = false;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00003017 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith10c60722012-08-09 19:01:51 +00003018 // C++11 [expr.delete]p1:
3019 // Whenever the delete keyword is followed by empty square brackets, it
3020 // shall be interpreted as [array delete].
3021 // [Footnote: A lambda expression with a lambda-introducer that consists
3022 // of empty square brackets can follow the delete keyword if
3023 // the lambda expression is enclosed in parentheses.]
3024 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
3025 // lambda-introducer.
Sebastian Redlbd150f42008-11-21 19:14:01 +00003026 ArrayDelete = true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003027 BalancedDelimiterTracker T(*this, tok::l_square);
3028
3029 T.consumeOpen();
3030 T.consumeClose();
3031 if (T.getCloseLocation().isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00003032 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003033 }
3034
John McCalldadc5752010-08-24 06:29:42 +00003035 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00003036 if (Operand.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003037 return Operand;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003038
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003039 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00003040}
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003041
Douglas Gregor29c42f22012-02-24 07:38:34 +00003042static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
3043 switch (kind) {
3044 default: llvm_unreachable("Not a known type trait");
Alp Toker95e7ff22014-01-01 05:57:51 +00003045#define TYPE_TRAIT_1(Spelling, Name, Key) \
3046case tok::kw_ ## Spelling: return UTT_ ## Name;
Alp Tokercbb90342013-12-13 20:49:58 +00003047#define TYPE_TRAIT_2(Spelling, Name, Key) \
3048case tok::kw_ ## Spelling: return BTT_ ## Name;
3049#include "clang/Basic/TokenKinds.def"
Alp Toker40f9b1c2013-12-12 21:23:03 +00003050#define TYPE_TRAIT_N(Spelling, Name, Key) \
3051 case tok::kw_ ## Spelling: return TT_ ## Name;
3052#include "clang/Basic/TokenKinds.def"
Douglas Gregor29c42f22012-02-24 07:38:34 +00003053 }
3054}
3055
John Wiegley6242b6a2011-04-28 00:16:57 +00003056static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
3057 switch(kind) {
3058 default: llvm_unreachable("Not a known binary type trait");
3059 case tok::kw___array_rank: return ATT_ArrayRank;
3060 case tok::kw___array_extent: return ATT_ArrayExtent;
3061 }
3062}
3063
John Wiegleyf9f65842011-04-25 06:54:41 +00003064static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
3065 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003066 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegleyf9f65842011-04-25 06:54:41 +00003067 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
3068 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
3069 }
3070}
3071
Alp Toker40f9b1c2013-12-12 21:23:03 +00003072static unsigned TypeTraitArity(tok::TokenKind kind) {
3073 switch (kind) {
3074 default: llvm_unreachable("Not a known type trait");
3075#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
3076#include "clang/Basic/TokenKinds.def"
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003077 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003078}
3079
Fangrui Song6907ce22018-07-30 19:24:48 +00003080/// Parse the built-in type-trait pseudo-functions that allow
Douglas Gregor29c42f22012-02-24 07:38:34 +00003081/// implementation of the TR1/C++11 type traits templates.
3082///
3083/// primary-expression:
Alp Toker40f9b1c2013-12-12 21:23:03 +00003084/// unary-type-trait '(' type-id ')'
3085/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor29c42f22012-02-24 07:38:34 +00003086/// type-trait '(' type-id-seq ')'
3087///
3088/// type-id-seq:
3089/// type-id ...[opt] type-id-seq[opt]
3090///
3091ExprResult Parser::ParseTypeTrait() {
Alp Toker40f9b1c2013-12-12 21:23:03 +00003092 tok::TokenKind Kind = Tok.getKind();
3093 unsigned Arity = TypeTraitArity(Kind);
3094
Douglas Gregor29c42f22012-02-24 07:38:34 +00003095 SourceLocation Loc = ConsumeToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00003096
Douglas Gregor29c42f22012-02-24 07:38:34 +00003097 BalancedDelimiterTracker Parens(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003098 if (Parens.expectAndConsume())
Douglas Gregor29c42f22012-02-24 07:38:34 +00003099 return ExprError();
3100
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003101 SmallVector<ParsedType, 2> Args;
Douglas Gregor29c42f22012-02-24 07:38:34 +00003102 do {
3103 // Parse the next type.
3104 TypeResult Ty = ParseTypeName();
3105 if (Ty.isInvalid()) {
3106 Parens.skipToEnd();
3107 return ExprError();
3108 }
3109
3110 // Parse the ellipsis, if present.
3111 if (Tok.is(tok::ellipsis)) {
3112 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3113 if (Ty.isInvalid()) {
3114 Parens.skipToEnd();
3115 return ExprError();
3116 }
3117 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003118
Douglas Gregor29c42f22012-02-24 07:38:34 +00003119 // Add this type to the list of arguments.
3120 Args.push_back(Ty.get());
Alp Tokera3ebe6e2013-12-17 14:12:37 +00003121 } while (TryConsumeToken(tok::comma));
3122
Douglas Gregor29c42f22012-02-24 07:38:34 +00003123 if (Parens.consumeClose())
3124 return ExprError();
Alp Toker40f9b1c2013-12-12 21:23:03 +00003125
3126 SourceLocation EndLoc = Parens.getCloseLocation();
3127
3128 if (Arity && Args.size() != Arity) {
3129 Diag(EndLoc, diag::err_type_trait_arity)
3130 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3131 return ExprError();
3132 }
3133
3134 if (!Arity && Args.empty()) {
3135 Diag(EndLoc, diag::err_type_trait_arity)
3136 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3137 return ExprError();
3138 }
3139
Alp Toker88f64e62013-12-13 21:19:30 +00003140 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
Douglas Gregor29c42f22012-02-24 07:38:34 +00003141}
3142
John Wiegley6242b6a2011-04-28 00:16:57 +00003143/// ParseArrayTypeTrait - Parse the built-in array type-trait
3144/// pseudo-functions.
3145///
3146/// primary-expression:
3147/// [Embarcadero] '__array_rank' '(' type-id ')'
3148/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3149///
3150ExprResult Parser::ParseArrayTypeTrait() {
3151 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3152 SourceLocation Loc = ConsumeToken();
3153
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003154 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003155 if (T.expectAndConsume())
John Wiegley6242b6a2011-04-28 00:16:57 +00003156 return ExprError();
3157
3158 TypeResult Ty = ParseTypeName();
3159 if (Ty.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003160 SkipUntil(tok::comma, StopAtSemi);
3161 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003162 return ExprError();
3163 }
3164
3165 switch (ATT) {
3166 case ATT_ArrayRank: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003167 T.consumeClose();
Craig Topper161e4db2014-05-21 06:02:52 +00003168 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003169 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003170 }
3171 case ATT_ArrayExtent: {
Alp Toker383d2c42014-01-01 03:08:43 +00003172 if (ExpectAndConsume(tok::comma)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003173 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003174 return ExprError();
3175 }
3176
3177 ExprResult DimExpr = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003178 T.consumeClose();
John Wiegley6242b6a2011-04-28 00:16:57 +00003179
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003180 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3181 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003182 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003183 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003184 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley6242b6a2011-04-28 00:16:57 +00003185}
3186
John Wiegleyf9f65842011-04-25 06:54:41 +00003187/// ParseExpressionTrait - Parse built-in expression-trait
3188/// pseudo-functions like __is_lvalue_expr( xxx ).
3189///
3190/// primary-expression:
3191/// [Embarcadero] expression-trait '(' expression ')'
3192///
3193ExprResult Parser::ParseExpressionTrait() {
3194 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3195 SourceLocation Loc = ConsumeToken();
3196
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003197 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003198 if (T.expectAndConsume())
John Wiegleyf9f65842011-04-25 06:54:41 +00003199 return ExprError();
3200
3201 ExprResult Expr = ParseExpression();
3202
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003203 T.consumeClose();
John Wiegleyf9f65842011-04-25 06:54:41 +00003204
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003205 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3206 T.getCloseLocation());
John Wiegleyf9f65842011-04-25 06:54:41 +00003207}
3208
3209
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003210/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3211/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3212/// based on the context past the parens.
John McCalldadc5752010-08-24 06:29:42 +00003213ExprResult
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003214Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallba7bf592010-08-24 05:47:05 +00003215 ParsedType &CastTy,
Richard Smith87e11a42014-05-15 02:43:47 +00003216 BalancedDelimiterTracker &Tracker,
3217 ColonProtectionRAIIObject &ColonProt) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003218 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003219 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3220 assert(isTypeIdInParens() && "Not a type-id!");
3221
John McCalldadc5752010-08-24 06:29:42 +00003222 ExprResult Result(true);
David Blaikieefdccaa2016-01-15 23:43:34 +00003223 CastTy = nullptr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003224
3225 // We need to disambiguate a very ugly part of the C++ syntax:
3226 //
3227 // (T())x; - type-id
3228 // (T())*x; - type-id
3229 // (T())/x; - expression
3230 // (T()); - expression
3231 //
3232 // The bad news is that we cannot use the specialized tentative parser, since
3233 // it can only verify that the thing inside the parens can be parsed as
3234 // type-id, it is not useful for determining the context past the parens.
3235 //
3236 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidis24ad6922009-05-22 15:12:46 +00003237 // making any unnecessary Action calls.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003238 //
3239 // It uses a scheme similar to parsing inline methods. The parenthesized
3240 // tokens are cached, the context that follows is determined (possibly by
3241 // parsing a cast-expression), and then we re-introduce the cached tokens
3242 // into the token stream and parse them appropriately.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003243
Mike Stump11289f42009-09-09 15:08:12 +00003244 ParenParseOption ParseAs;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003245 CachedTokens Toks;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003246
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003247 // Store the tokens of the parentheses. We will parse them after we determine
3248 // the context that follows them.
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +00003249 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003250 // We didn't find the ')' we expected.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003251 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003252 return ExprError();
3253 }
3254
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003255 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003256 ParseAs = CompoundLiteral;
3257 } else {
3258 bool NotCastExpr;
Eli Friedmancf7530f2009-05-25 19:41:42 +00003259 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3260 NotCastExpr = true;
3261 } else {
3262 // Try parsing the cast-expression that may follow.
3263 // If it is not a cast-expression, NotCastExpr will be true and no token
3264 // will be consumed.
Richard Smith87e11a42014-05-15 02:43:47 +00003265 ColonProt.restore();
Eli Friedmancf7530f2009-05-25 19:41:42 +00003266 Result = ParseCastExpression(false/*isUnaryExpression*/,
3267 false/*isAddressofOperand*/,
John McCallba7bf592010-08-24 05:47:05 +00003268 NotCastExpr,
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003269 // type-id has priority.
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00003270 IsTypeCast);
Eli Friedmancf7530f2009-05-25 19:41:42 +00003271 }
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003272
3273 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3274 // an expression.
3275 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003276 }
3277
Alexey Bataev703a93c2016-02-04 04:22:09 +00003278 // Create a fake EOF to mark end of Toks buffer.
3279 Token AttrEnd;
3280 AttrEnd.startToken();
3281 AttrEnd.setKind(tok::eof);
3282 AttrEnd.setLocation(Tok.getLocation());
3283 AttrEnd.setEofData(Toks.data());
3284 Toks.push_back(AttrEnd);
3285
Mike Stump11289f42009-09-09 15:08:12 +00003286 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003287 Toks.push_back(Tok);
3288 // Re-enter the stored parenthesized tokens into the token stream, so we may
3289 // parse them now.
David Blaikie2eabcc92016-02-09 18:52:09 +00003290 PP.EnterTokenStream(Toks, true /*DisableMacroExpansion*/);
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003291 // Drop the current token and bring the first cached one. It's the same token
3292 // as when we entered this function.
3293 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003294
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003295 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003296 // Parse the type declarator.
3297 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00003298 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Richard Smith87e11a42014-05-15 02:43:47 +00003299 {
3300 ColonProtectionRAIIObject InnerColonProtection(*this);
3301 ParseSpecifierQualifierList(DS);
3302 ParseDeclarator(DeclaratorInfo);
3303 }
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003304
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003305 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003306 Tracker.consumeClose();
Richard Smith87e11a42014-05-15 02:43:47 +00003307 ColonProt.restore();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003308
Alexey Bataev703a93c2016-02-04 04:22:09 +00003309 // Consume EOF marker for Toks buffer.
3310 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3311 ConsumeAnyToken();
3312
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003313 if (ParseAs == CompoundLiteral) {
3314 ExprType = CompoundLiteral;
Richard Smithaba8b362014-05-15 02:51:15 +00003315 if (DeclaratorInfo.isInvalidType())
3316 return ExprError();
3317
3318 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Richard Smith87e11a42014-05-15 02:43:47 +00003319 return ParseCompoundLiteralExpression(Ty.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003320 Tracker.getOpenLocation(),
3321 Tracker.getCloseLocation());
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003322 }
Mike Stump11289f42009-09-09 15:08:12 +00003323
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003324 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3325 assert(ParseAs == CastExpr);
3326
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003327 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003328 return ExprError();
3329
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003330 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003331 if (!Result.isInvalid())
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003332 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3333 DeclaratorInfo, CastTy,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003334 Tracker.getCloseLocation(), Result.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003335 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003336 }
Mike Stump11289f42009-09-09 15:08:12 +00003337
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003338 // Not a compound literal, and not followed by a cast-expression.
3339 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003340
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003341 ExprType = SimpleExpr;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003342 Result = ParseExpression();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003343 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Fangrui Song6907ce22018-07-30 19:24:48 +00003344 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003345 Tok.getLocation(), Result.get());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003346
3347 // Match the ')'.
3348 if (Result.isInvalid()) {
Alexey Bataev703a93c2016-02-04 04:22:09 +00003349 while (Tok.isNot(tok::eof))
3350 ConsumeAnyToken();
3351 assert(Tok.getEofData() == AttrEnd.getEofData());
3352 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003353 return ExprError();
3354 }
Mike Stump11289f42009-09-09 15:08:12 +00003355
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003356 Tracker.consumeClose();
Alexey Bataev703a93c2016-02-04 04:22:09 +00003357 // Consume EOF marker for Toks buffer.
3358 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3359 ConsumeAnyToken();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003360 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003361}