blob: c74d103341114e1cef73c8208a2f874f790c7f16 [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),
566 isAddressOfOperand, nullptr, /*IsInlineAsmIdentifier=*/false,
567 &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
641///
642/// lambda-introducer:
643/// '[' lambda-capture[opt] ']'
644///
645/// lambda-capture:
646/// capture-default
647/// capture-list
648/// capture-default ',' capture-list
649///
650/// capture-default:
651/// '&'
652/// '='
653///
654/// capture-list:
655/// capture
656/// capture-list ',' capture
657///
658/// capture:
Richard Smith21b3ab42013-05-09 21:36:41 +0000659/// simple-capture
660/// init-capture [C++1y]
661///
662/// simple-capture:
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000663/// identifier
664/// '&' identifier
665/// 'this'
666///
Richard Smith21b3ab42013-05-09 21:36:41 +0000667/// init-capture: [C++1y]
668/// identifier initializer
669/// '&' identifier initializer
670///
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000671/// lambda-declarator:
672/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
673/// 'mutable'[opt] exception-specification[opt]
674/// trailing-return-type[opt]
675///
676ExprResult Parser::ParseLambdaExpression() {
677 // Parse lambda-introducer.
678 LambdaIntroducer Intro;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000679 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000680 if (DiagID) {
681 Diag(Tok, DiagID.getValue());
David Majnemer234b8182015-01-12 03:36:37 +0000682 SkipUntil(tok::r_square, StopAtSemi);
683 SkipUntil(tok::l_brace, StopAtSemi);
684 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000685 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000686 }
687
688 return ParseLambdaExpressionAfterIntroducer(Intro);
689}
690
691/// TryParseLambdaExpression - Use lookahead and potentially tentative
692/// parsing to determine if we are looking at a C++0x lambda expression, and parse
693/// it if we are.
694///
695/// If we are not looking at a lambda expression, returns ExprError().
696ExprResult Parser::TryParseLambdaExpression() {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000697 assert(getLangOpts().CPlusPlus11
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000698 && Tok.is(tok::l_square)
699 && "Not at the start of a possible lambda expression.");
700
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000701 const Token Next = NextToken();
702 if (Next.is(tok::eof)) // Nothing else to lookup here...
703 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000704
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000705 const Token After = GetLookAheadToken(2);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000706 // If lookahead indicates this is a lambda...
707 if (Next.is(tok::r_square) || // []
708 Next.is(tok::equal) || // [=
709 (Next.is(tok::amp) && // [&] or [&,
710 (After.is(tok::r_square) ||
711 After.is(tok::comma))) ||
712 (Next.is(tok::identifier) && // [identifier]
713 After.is(tok::r_square))) {
714 return ParseLambdaExpression();
715 }
716
Eli Friedmanc7c97142012-01-04 02:40:39 +0000717 // If lookahead indicates an ObjC message send...
718 // [identifier identifier
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000719 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000720 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000721 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000722
Eli Friedmanc7c97142012-01-04 02:40:39 +0000723 // Here, we're stuck: lambda introducers and Objective-C message sends are
724 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
725 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
726 // writing two routines to parse a lambda introducer, just try to parse
727 // a lambda introducer first, and fall back if that fails.
728 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000729 LambdaIntroducer Intro;
730 if (TryParseLambdaIntroducer(Intro))
Eli Friedmanc7c97142012-01-04 02:40:39 +0000731 return ExprEmpty();
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000732
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000733 return ParseLambdaExpressionAfterIntroducer(Intro);
734}
735
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000736/// Parse a lambda introducer.
Richard Smithf44d2a82013-05-21 22:21:19 +0000737/// \param Intro A LambdaIntroducer filled in with information about the
738/// contents of the lambda-introducer.
739/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
740/// message send and a lambda expression. In this mode, we will
741/// sometimes skip the initializers for init-captures and not fully
742/// populate \p Intro. This flag will be set to \c true if we do so.
743/// \return A DiagnosticID if it hit something unexpected. The location for
Malcolm Parsonsffd21d32017-01-11 11:23:22 +0000744/// the diagnostic is that of the current token.
Richard Smithf44d2a82013-05-21 22:21:19 +0000745Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
746 bool *SkippedInits) {
David Blaikie05785d12013-02-20 22:23:23 +0000747 typedef Optional<unsigned> DiagResult;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000748
749 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000750 BalancedDelimiterTracker T(*this, tok::l_square);
751 T.consumeOpen();
752
753 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000754
755 bool first = true;
756
757 // Parse capture-default.
758 if (Tok.is(tok::amp) &&
759 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
760 Intro.Default = LCD_ByRef;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000761 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000762 first = false;
763 } else if (Tok.is(tok::equal)) {
764 Intro.Default = LCD_ByCopy;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000765 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000766 first = false;
767 }
768
769 while (Tok.isNot(tok::r_square)) {
770 if (!first) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000771 if (Tok.isNot(tok::comma)) {
Douglas Gregor721b14d2012-07-31 00:50:07 +0000772 // Provide a completion for a lambda introducer here. Except
773 // in Objective-C, where this is Almost Surely meant to be a message
774 // send. In that case, fail here and let the ObjC message
775 // expression parser perform the completion.
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000776 if (Tok.is(tok::code_completion) &&
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000777 !(getLangOpts().ObjC && Intro.Default == LCD_None &&
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000778 !Intro.Captures.empty())) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000779 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
Douglas Gregord8c61782012-02-15 15:34:24 +0000780 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000781 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000782 break;
783 }
784
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000785 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregord8c61782012-02-15 15:34:24 +0000786 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000787 ConsumeToken();
788 }
789
Douglas Gregord8c61782012-02-15 15:34:24 +0000790 if (Tok.is(tok::code_completion)) {
791 // If we're in Objective-C++ and we have a bare '[', then this is more
792 // likely to be a message receiver.
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000793 if (getLangOpts().ObjC && first)
Douglas Gregord8c61782012-02-15 15:34:24 +0000794 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
795 else
Fangrui Song6907ce22018-07-30 19:24:48 +0000796 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
Douglas Gregord8c61782012-02-15 15:34:24 +0000797 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000798 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000799 break;
800 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000801
Douglas Gregord8c61782012-02-15 15:34:24 +0000802 first = false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000803
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000804 // Parse capture.
805 LambdaCaptureKind Kind = LCK_ByCopy;
Richard Smith42b10572015-11-11 01:36:17 +0000806 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000807 SourceLocation Loc;
Craig Topper161e4db2014-05-21 06:02:52 +0000808 IdentifierInfo *Id = nullptr;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000809 SourceLocation EllipsisLoc;
Richard Smith21b3ab42013-05-09 21:36:41 +0000810 ExprResult Init;
Alexander Shaposhnikov832f49b2018-07-16 07:23:47 +0000811 SourceLocation LocStart = Tok.getLocation();
Faisal Validc6b5962016-03-21 09:25:37 +0000812
813 if (Tok.is(tok::star)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000814 Loc = ConsumeToken();
Faisal Validc6b5962016-03-21 09:25:37 +0000815 if (Tok.is(tok::kw_this)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000816 ConsumeToken();
817 Kind = LCK_StarThis;
Faisal Validc6b5962016-03-21 09:25:37 +0000818 } else {
819 return DiagResult(diag::err_expected_star_this_capture);
820 }
821 } else if (Tok.is(tok::kw_this)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000822 Kind = LCK_This;
823 Loc = ConsumeToken();
824 } else {
825 if (Tok.is(tok::amp)) {
826 Kind = LCK_ByRef;
827 ConsumeToken();
Douglas Gregord8c61782012-02-15 15:34:24 +0000828
829 if (Tok.is(tok::code_completion)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000830 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
Douglas Gregord8c61782012-02-15 15:34:24 +0000831 /*AfterAmpersand=*/true);
Alp Toker1c583cc2014-05-02 03:43:14 +0000832 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000833 break;
834 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000835 }
836
837 if (Tok.is(tok::identifier)) {
838 Id = Tok.getIdentifierInfo();
839 Loc = ConsumeToken();
840 } else if (Tok.is(tok::kw_this)) {
841 // FIXME: If we want to suggest a fixit here, will need to return more
842 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
843 // Clear()ed to prevent emission in case of tentative parsing?
844 return DiagResult(diag::err_this_captured_by_reference);
845 } else {
846 return DiagResult(diag::err_expected_capture);
847 }
Richard Smith21b3ab42013-05-09 21:36:41 +0000848
849 if (Tok.is(tok::l_paren)) {
850 BalancedDelimiterTracker Parens(*this, tok::l_paren);
851 Parens.consumeOpen();
852
Richard Smith42b10572015-11-11 01:36:17 +0000853 InitKind = LambdaCaptureInitKind::DirectInit;
854
Richard Smith21b3ab42013-05-09 21:36:41 +0000855 ExprVector Exprs;
856 CommaLocsTy Commas;
Richard Smithf44d2a82013-05-21 22:21:19 +0000857 if (SkippedInits) {
858 Parens.skipToEnd();
859 *SkippedInits = true;
860 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith21b3ab42013-05-09 21:36:41 +0000861 Parens.skipToEnd();
862 Init = ExprError();
863 } else {
864 Parens.consumeClose();
865 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
866 Parens.getCloseLocation(),
867 Exprs);
868 }
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000869 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000870 // Each lambda init-capture forms its own full expression, which clears
871 // Actions.MaybeODRUseExprs. So create an expression evaluation context
872 // to save the necessary state, and restore it later.
Faisal Valid143a0c2017-04-01 21:30:49 +0000873 EnterExpressionEvaluationContext EC(
874 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith42b10572015-11-11 01:36:17 +0000875
876 if (TryConsumeToken(tok::equal))
877 InitKind = LambdaCaptureInitKind::CopyInit;
878 else
879 InitKind = LambdaCaptureInitKind::ListInit;
Richard Smith21b3ab42013-05-09 21:36:41 +0000880
Richard Smith215f4232015-02-11 02:41:33 +0000881 if (!SkippedInits) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000882 Init = ParseInitializer();
Richard Smith215f4232015-02-11 02:41:33 +0000883 } else if (Tok.is(tok::l_brace)) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000884 BalancedDelimiterTracker Braces(*this, tok::l_brace);
885 Braces.consumeOpen();
886 Braces.skipToEnd();
887 *SkippedInits = true;
888 } else {
889 // We're disambiguating this:
890 //
891 // [..., x = expr
892 //
893 // We need to find the end of the following expression in order to
Richard Smith9e2f0a42014-04-13 04:31:48 +0000894 // determine whether this is an Obj-C message send's receiver, a
895 // C99 designator, or a lambda init-capture.
Richard Smithf44d2a82013-05-21 22:21:19 +0000896 //
897 // Parse the expression to find where it ends, and annotate it back
898 // onto the tokens. We would have parsed this expression the same way
899 // in either case: both the RHS of an init-capture and the RHS of an
900 // assignment expression are parsed as an initializer-clause, and in
901 // neither case can anything be added to the scope between the '[' and
902 // here.
903 //
904 // FIXME: This is horrible. Adding a mechanism to skip an expression
905 // would be much cleaner.
906 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
907 // that instead. (And if we see a ':' with no matching '?', we can
908 // classify this as an Obj-C message send.)
909 SourceLocation StartLoc = Tok.getLocation();
910 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
911 Init = ParseInitializer();
Akira Hatanaka51e60f92016-12-20 02:11:29 +0000912 if (!Init.isInvalid())
913 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
Richard Smithf44d2a82013-05-21 22:21:19 +0000914
915 if (Tok.getLocation() != StartLoc) {
916 // Back out the lexing of the token after the initializer.
917 PP.RevertCachedTokens(1);
918
919 // Replace the consumed tokens with an appropriate annotation.
920 Tok.setLocation(StartLoc);
921 Tok.setKind(tok::annot_primary_expr);
922 setExprAnnotation(Tok, Init);
923 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
924 PP.AnnotateCachedTokens(Tok);
925
926 // Consume the annotated initializer.
Richard Smithaf3b3252017-05-18 19:21:48 +0000927 ConsumeAnnotationToken();
Richard Smithf44d2a82013-05-21 22:21:19 +0000928 }
929 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000930 } else
931 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000932 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000933 // If this is an init capture, process the initialization expression
934 // right away. For lambda init-captures such as the following:
935 // const int x = 10;
936 // auto L = [i = x+1](int a) {
937 // return [j = x+2,
938 // &k = x](char b) { };
939 // };
940 // keep in mind that each lambda init-capture has to have:
941 // - its initialization expression executed in the context
942 // of the enclosing/parent decl-context.
943 // - but the variable itself has to be 'injected' into the
944 // decl-context of its lambda's call-operator (which has
945 // not yet been created).
946 // Each init-expression is a full-expression that has to get
947 // Sema-analyzed (for capturing etc.) before its lambda's
948 // call-operator's decl-context, scope & scopeinfo are pushed on their
949 // respective stacks. Thus if any variable is odr-used in the init-capture
950 // it will correctly get captured in the enclosing lambda, if one exists.
951 // The init-variables above are created later once the lambdascope and
952 // call-operators decl-context is pushed onto its respective stack.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000953
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000954 // Since the lambda init-capture's initializer expression occurs in the
955 // context of the enclosing function or lambda, therefore we can not wait
956 // till a lambda scope has been pushed on before deciding whether the
957 // variable needs to be captured. We also need to process all
958 // lvalue-to-rvalue conversions and discarded-value conversions,
959 // so that we can avoid capturing certain constant variables.
960 // For e.g.,
961 // void test() {
962 // const int x = 10;
963 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
964 // return [y = x](int i) { <-- don't capture by enclosing lambda
965 // return y;
966 // }
967 // };
Richard Smithbdb84f32016-07-22 23:36:59 +0000968 // }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000969 // If x was not const, the second use would require 'L' to capture, and
970 // that would be an error.
971
Richard Smith42b10572015-11-11 01:36:17 +0000972 ParsedType InitCaptureType;
Volodymyr Sapsaib0f1aae2017-08-22 17:55:19 +0000973 if (!Init.isInvalid())
974 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000975 if (Init.isUsable()) {
976 // Get the pointer and store it in an lvalue, so we can use it as an
977 // out argument.
978 Expr *InitExpr = Init.get();
979 // This performs any lvalue-to-rvalue conversions if necessary, which
980 // can affect what gets captured in the containing decl-context.
Richard Smith42b10572015-11-11 01:36:17 +0000981 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
982 Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000983 Init = InitExpr;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000984 }
Alexander Shaposhnikov832f49b2018-07-16 07:23:47 +0000985
986 SourceLocation LocEnd = PrevTokLocation;
987
Richard Smith42b10572015-11-11 01:36:17 +0000988 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
Alexander Shaposhnikov832f49b2018-07-16 07:23:47 +0000989 InitCaptureType, SourceRange(LocStart, LocEnd));
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000990 }
991
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000992 T.consumeClose();
993 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000994 return DiagResult();
995}
996
Douglas Gregord8c61782012-02-15 15:34:24 +0000997/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000998///
999/// Returns true if it hit something unexpected.
1000bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
Jan Korous06aa2af2017-11-06 17:42:17 +00001001 {
1002 bool SkippedInits = false;
1003 TentativeParsingAction PA1(*this);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001004
Jan Korous06aa2af2017-11-06 17:42:17 +00001005 if (ParseLambdaIntroducer(Intro, &SkippedInits)) {
1006 PA1.Revert();
1007 return true;
1008 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001009
Jan Korous06aa2af2017-11-06 17:42:17 +00001010 if (!SkippedInits) {
1011 PA1.Commit();
1012 return false;
1013 }
1014
1015 PA1.Revert();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001016 }
1017
Jan Korous06aa2af2017-11-06 17:42:17 +00001018 // Try to parse it again, but this time parse the init-captures too.
1019 Intro = LambdaIntroducer();
1020 TentativeParsingAction PA2(*this);
1021
1022 if (!ParseLambdaIntroducer(Intro)) {
1023 PA2.Commit();
Richard Smithf44d2a82013-05-21 22:21:19 +00001024 return false;
1025 }
1026
Jan Korous06aa2af2017-11-06 17:42:17 +00001027 PA2.Revert();
1028 return true;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001029}
1030
Faisal Valia734ab92016-03-26 16:11:37 +00001031static void
1032tryConsumeMutableOrConstexprToken(Parser &P, SourceLocation &MutableLoc,
1033 SourceLocation &ConstexprLoc,
1034 SourceLocation &DeclEndLoc) {
1035 assert(MutableLoc.isInvalid());
1036 assert(ConstexprLoc.isInvalid());
1037 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1038 // to the final of those locations. Emit an error if we have multiple
1039 // copies of those keywords and recover.
1040
1041 while (true) {
1042 switch (P.getCurToken().getKind()) {
1043 case tok::kw_mutable: {
1044 if (MutableLoc.isValid()) {
1045 P.Diag(P.getCurToken().getLocation(),
1046 diag::err_lambda_decl_specifier_repeated)
1047 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1048 }
1049 MutableLoc = P.ConsumeToken();
1050 DeclEndLoc = MutableLoc;
1051 break /*switch*/;
1052 }
1053 case tok::kw_constexpr:
1054 if (ConstexprLoc.isValid()) {
1055 P.Diag(P.getCurToken().getLocation(),
1056 diag::err_lambda_decl_specifier_repeated)
1057 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1058 }
1059 ConstexprLoc = P.ConsumeToken();
1060 DeclEndLoc = ConstexprLoc;
1061 break /*switch*/;
1062 default:
1063 return;
1064 }
1065 }
1066}
1067
1068static void
1069addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1070 DeclSpec &DS) {
1071 if (ConstexprLoc.isValid()) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00001072 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
Richard Smithb115e5d2017-08-13 23:37:29 +00001073 ? diag::ext_constexpr_on_lambda_cxx17
Faisal Valia734ab92016-03-26 16:11:37 +00001074 : diag::warn_cxx14_compat_constexpr_on_lambda);
1075 const char *PrevSpec = nullptr;
1076 unsigned DiagID = 0;
1077 DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
1078 assert(PrevSpec == nullptr && DiagID == 0 &&
1079 "Constexpr cannot have been set previously!");
1080 }
1081}
1082
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001083/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1084/// expression.
1085ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1086 LambdaIntroducer &Intro) {
Eli Friedmanc7c97142012-01-04 02:40:39 +00001087 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1088 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1089
1090 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1091 "lambda expression parsing");
1092
Fangrui Song6907ce22018-07-30 19:24:48 +00001093
Faisal Vali2b391ab2013-09-26 19:54:12 +00001094
Richard Smith21b3ab42013-05-09 21:36:41 +00001095 // FIXME: Call into Actions to add any init-capture declarations to the
1096 // scope while parsing the lambda-declarator and compound-statement.
1097
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001098 // Parse lambda-declarator[opt].
1099 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00001100 Declarator D(DS, DeclaratorContext::LambdaExprContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001101 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001102 Actions.PushLambdaScope();
1103
1104 ParsedAttributes Attr(AttrFactory);
1105 SourceLocation DeclLoc = Tok.getLocation();
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001106 if (getLangOpts().CUDA) {
1107 // In CUDA code, GNU attributes are allowed to appear immediately after the
1108 // "[...]", even if there is no "(...)" before the lambda body.
Justin Lebar0139a5d2016-09-30 19:55:48 +00001109 MaybeParseGNUAttributes(D);
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001110 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001111
Justin Lebare46ea722016-09-30 19:55:55 +00001112 // Helper to emit a warning if we see a CUDA host/device/global attribute
1113 // after '(...)'. nvcc doesn't accept this.
1114 auto WarnIfHasCUDATargetAttr = [&] {
1115 if (getLangOpts().CUDA)
Erich Keanee891aa92018-07-13 15:07:47 +00001116 for (const ParsedAttr &A : Attr)
1117 if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1118 A.getKind() == ParsedAttr::AT_CUDAHost ||
1119 A.getKind() == ParsedAttr::AT_CUDAGlobal)
Erich Keanec480f302018-07-12 21:09:05 +00001120 Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
1121 << A.getName()->getName();
Justin Lebare46ea722016-09-30 19:55:55 +00001122 };
1123
David Majnemere01c4662015-01-09 05:10:55 +00001124 TypeResult TrailingReturnType;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001125 if (Tok.is(tok::l_paren)) {
1126 ParseScope PrototypeScope(this,
1127 Scope::FunctionPrototypeScope |
Richard Smithe233fbf2013-01-28 22:42:45 +00001128 Scope::FunctionDeclarationScope |
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001129 Scope::DeclScope);
1130
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001131 BalancedDelimiterTracker T(*this, tok::l_paren);
1132 T.consumeOpen();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001133 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001134
1135 // Parse parameter-declaration-clause.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001136 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001137 SourceLocation EllipsisLoc;
Fangrui Song6907ce22018-07-30 19:24:48 +00001138
Faisal Vali2b391ab2013-09-26 19:54:12 +00001139 if (Tok.isNot(tok::r_paren)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00001140 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001141 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001142 // For a generic lambda, each 'auto' within the parameter declaration
Faisal Vali2b391ab2013-09-26 19:54:12 +00001143 // clause creates a template type parameter, so increment the depth.
Fangrui Song6907ce22018-07-30 19:24:48 +00001144 if (Actions.getCurGenericLambda())
Faisal Vali2b391ab2013-09-26 19:54:12 +00001145 ++CurTemplateDepthTracker;
1146 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001147 T.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001148 SourceLocation RParenLoc = T.getCloseLocation();
Justin Lebar0139a5d2016-09-30 19:55:48 +00001149 SourceLocation DeclEndLoc = RParenLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001150
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001151 // GNU-style attributes must be parsed before the mutable specifier to be
1152 // compatible with GCC.
1153 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1154
David Majnemerbda86322015-02-04 08:22:46 +00001155 // MSVC-style attributes must be parsed before the mutable specifier to be
1156 // compatible with MSVC.
Aaron Ballman068aa512015-05-20 20:58:33 +00001157 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
David Majnemerbda86322015-02-04 08:22:46 +00001158
Faisal Valia734ab92016-03-26 16:11:37 +00001159 // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001160 SourceLocation MutableLoc;
Faisal Valia734ab92016-03-26 16:11:37 +00001161 SourceLocation ConstexprLoc;
1162 tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
1163 DeclEndLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001164
Faisal Valia734ab92016-03-26 16:11:37 +00001165 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001166
1167 // Parse exception-specification[opt].
1168 ExceptionSpecificationType ESpecType = EST_None;
1169 SourceRange ESpecRange;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001170 SmallVector<ParsedType, 2> DynamicExceptions;
1171 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001172 ExprResult NoexceptExpr;
Richard Smith0b3a4622014-11-13 20:01:57 +00001173 CachedTokens *ExceptionSpecTokens;
1174 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1175 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00001176 DynamicExceptions,
1177 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00001178 NoexceptExpr,
1179 ExceptionSpecTokens);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001180
1181 if (ESpecType != EST_None)
1182 DeclEndLoc = ESpecRange.getEnd();
1183
1184 // Parse attribute-specifier[opt].
Richard Smith89645bc2013-01-02 12:01:23 +00001185 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001186
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001187 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1188
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001189 // Parse trailing-return-type[opt].
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001190 if (Tok.is(tok::arrow)) {
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001191 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001192 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00001193 TrailingReturnType =
1194 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001195 if (Range.getEnd().isValid())
1196 DeclEndLoc = Range.getEnd();
1197 }
1198
1199 PrototypeScope.Exit();
1200
Justin Lebare46ea722016-09-30 19:55:55 +00001201 WarnIfHasCUDATargetAttr();
1202
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001203 SourceLocation NoLoc;
Erich Keanec480f302018-07-12 21:09:05 +00001204 D.AddTypeInfo(DeclaratorChunk::getFunction(
1205 /*hasProto=*/true,
1206 /*isAmbiguous=*/false, LParenLoc, ParamInfo.data(),
1207 ParamInfo.size(), EllipsisLoc, RParenLoc,
Erich Keanec480f302018-07-12 21:09:05 +00001208 /*RefQualifierIsLValueRef=*/true,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00001209 /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType,
Erich Keanec480f302018-07-12 21:09:05 +00001210 ESpecRange, DynamicExceptions.data(),
1211 DynamicExceptionRanges.data(), DynamicExceptions.size(),
1212 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1213 /*ExceptionSpecTokens*/ nullptr,
1214 /*DeclsInPrototype=*/None, LParenLoc, FunLocalRangeEnd, D,
1215 TrailingReturnType),
1216 std::move(Attr), DeclEndLoc);
Faisal Valia734ab92016-03-26 16:11:37 +00001217 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1218 tok::kw_constexpr) ||
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001219 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1220 // It's common to forget that one needs '()' before 'mutable', an attribute
1221 // specifier, or the result type. Deal with this.
1222 unsigned TokKind = 0;
1223 switch (Tok.getKind()) {
1224 case tok::kw_mutable: TokKind = 0; break;
1225 case tok::arrow: TokKind = 1; break;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001226 case tok::kw___attribute:
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001227 case tok::l_square: TokKind = 2; break;
Faisal Valia734ab92016-03-26 16:11:37 +00001228 case tok::kw_constexpr: TokKind = 3; break;
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001229 default: llvm_unreachable("Unknown token kind");
1230 }
1231
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001232 Diag(Tok, diag::err_lambda_missing_parens)
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001233 << TokKind
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001234 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
Justin Lebar0139a5d2016-09-30 19:55:48 +00001235 SourceLocation DeclEndLoc = DeclLoc;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001236
1237 // GNU-style attributes must be parsed before the mutable specifier to be
1238 // compatible with GCC.
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001239 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1240
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001241 // Parse 'mutable', if it's there.
1242 SourceLocation MutableLoc;
1243 if (Tok.is(tok::kw_mutable)) {
1244 MutableLoc = ConsumeToken();
1245 DeclEndLoc = MutableLoc;
1246 }
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001247
1248 // Parse attribute-specifier[opt].
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001249 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1250
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001251 // Parse the return type, if there is one.
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001252 if (Tok.is(tok::arrow)) {
1253 SourceRange Range;
Richard Smithe303e352018-02-02 22:24:54 +00001254 TrailingReturnType =
1255 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001256 if (Range.getEnd().isValid())
David Majnemere01c4662015-01-09 05:10:55 +00001257 DeclEndLoc = Range.getEnd();
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001258 }
1259
Justin Lebare46ea722016-09-30 19:55:55 +00001260 WarnIfHasCUDATargetAttr();
1261
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001262 SourceLocation NoLoc;
Erich Keanec480f302018-07-12 21:09:05 +00001263 D.AddTypeInfo(DeclaratorChunk::getFunction(
1264 /*hasProto=*/true,
1265 /*isAmbiguous=*/false,
1266 /*LParenLoc=*/NoLoc,
1267 /*Params=*/nullptr,
1268 /*NumParams=*/0,
1269 /*EllipsisLoc=*/NoLoc,
1270 /*RParenLoc=*/NoLoc,
Erich Keanec480f302018-07-12 21:09:05 +00001271 /*RefQualifierIsLValueRef=*/true,
Anastasia Stulovaa9bc4bd2019-01-09 11:25:09 +00001272 /*RefQualifierLoc=*/NoLoc, MutableLoc, EST_None,
Erich Keanec480f302018-07-12 21:09:05 +00001273 /*ESpecRange=*/SourceRange(),
1274 /*Exceptions=*/nullptr,
1275 /*ExceptionRanges=*/nullptr,
1276 /*NumExceptions=*/0,
1277 /*NoexceptExpr=*/nullptr,
1278 /*ExceptionSpecTokens=*/nullptr,
1279 /*DeclsInPrototype=*/None, DeclLoc, DeclEndLoc, D,
1280 TrailingReturnType),
1281 std::move(Attr), DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001282 }
1283
Eli Friedman4817cf72012-01-06 03:05:34 +00001284 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1285 // it.
Momchil Velikov57c681f2017-08-10 15:43:06 +00001286 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1287 Scope::CompoundStmtScope;
Douglas Gregorb8389972012-02-21 22:51:27 +00001288 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman4817cf72012-01-06 03:05:34 +00001289
Eli Friedman71c80552012-01-05 03:35:19 +00001290 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1291
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001292 // Parse compound-statement.
Eli Friedmanc7c97142012-01-04 02:40:39 +00001293 if (!Tok.is(tok::l_brace)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001294 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmanc7c97142012-01-04 02:40:39 +00001295 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1296 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001297 }
1298
Eli Friedmanc7c97142012-01-04 02:40:39 +00001299 StmtResult Stmt(ParseCompoundStatementBody());
1300 BodyScope.Exit();
1301
David Majnemere01c4662015-01-09 05:10:55 +00001302 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001303 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
David Majnemere01c4662015-01-09 05:10:55 +00001304
Eli Friedman898caf82012-01-04 02:46:53 +00001305 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1306 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001307}
1308
Chris Lattner29375652006-12-04 18:06:35 +00001309/// ParseCXXCasts - This handles the various ways to cast expressions to another
1310/// type.
1311///
1312/// postfix-expression: [C++ 5.2p1]
1313/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1314/// 'static_cast' '<' type-name '>' '(' expression ')'
1315/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1316/// 'const_cast' '<' type-name '>' '(' expression ')'
1317///
John McCalldadc5752010-08-24 06:29:42 +00001318ExprResult Parser::ParseCXXCasts() {
Chris Lattner29375652006-12-04 18:06:35 +00001319 tok::TokenKind Kind = Tok.getKind();
Craig Topper161e4db2014-05-21 06:02:52 +00001320 const char *CastName = nullptr; // For error messages
Chris Lattner29375652006-12-04 18:06:35 +00001321
1322 switch (Kind) {
David Blaikieaa347f92011-09-23 20:26:49 +00001323 default: llvm_unreachable("Unknown C++ cast!");
Chris Lattner29375652006-12-04 18:06:35 +00001324 case tok::kw_const_cast: CastName = "const_cast"; break;
1325 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1326 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1327 case tok::kw_static_cast: CastName = "static_cast"; break;
1328 }
1329
1330 SourceLocation OpLoc = ConsumeToken();
1331 SourceLocation LAngleBracketLoc = Tok.getLocation();
1332
Richard Smith55858492011-04-14 21:45:45 +00001333 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1334 // diagnose error, suggest fix, and recover parsing.
Richard Smith62e66302012-08-20 17:37:52 +00001335 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1336 Token Next = NextToken();
1337 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1338 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1339 }
Richard Smith55858492011-04-14 21:45:45 +00001340
Chris Lattner29375652006-12-04 18:06:35 +00001341 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redld65cea82008-12-11 22:51:44 +00001342 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001343
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001344 // Parse the common declaration-specifiers piece.
1345 DeclSpec DS(AttrFactory);
1346 ParseSpecifierQualifierList(DS);
1347
1348 // Parse the abstract-declarator, if present.
Faisal Vali421b2d12017-12-29 05:41:00 +00001349 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001350 ParseDeclarator(DeclaratorInfo);
1351
Chris Lattner29375652006-12-04 18:06:35 +00001352 SourceLocation RAngleBracketLoc = Tok.getLocation();
1353
Alp Toker383d2c42014-01-01 03:08:43 +00001354 if (ExpectAndConsume(tok::greater))
Alp Tokerec543272013-12-24 09:48:30 +00001355 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
Chris Lattner29375652006-12-04 18:06:35 +00001356
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001357 BalancedDelimiterTracker T(*this, tok::l_paren);
Chris Lattner29375652006-12-04 18:06:35 +00001358
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001359 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001360 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001361
John McCalldadc5752010-08-24 06:29:42 +00001362 ExprResult Result = ParseExpression();
Mike Stump11289f42009-09-09 15:08:12 +00001363
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001364 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001365 T.consumeClose();
Chris Lattner29375652006-12-04 18:06:35 +00001366
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001367 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregore200adc2008-10-27 19:41:14 +00001368 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001369 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor220cac52009-02-18 17:45:20 +00001370 RAngleBracketLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +00001371 T.getOpenLocation(), Result.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001372 T.getCloseLocation());
Chris Lattner29375652006-12-04 18:06:35 +00001373
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001374 return Result;
Chris Lattner29375652006-12-04 18:06:35 +00001375}
Bill Wendling4073ed52007-02-13 01:51:42 +00001376
Sebastian Redlc4704762008-11-11 11:37:55 +00001377/// ParseCXXTypeid - This handles the C++ typeid expression.
1378///
1379/// postfix-expression: [C++ 5.2p1]
1380/// 'typeid' '(' expression ')'
1381/// 'typeid' '(' type-id ')'
1382///
John McCalldadc5752010-08-24 06:29:42 +00001383ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc4704762008-11-11 11:37:55 +00001384 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1385
1386 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001387 SourceLocation LParenLoc, RParenLoc;
1388 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc4704762008-11-11 11:37:55 +00001389
1390 // typeid expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001391 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redld65cea82008-12-11 22:51:44 +00001392 return ExprError();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001393 LParenLoc = T.getOpenLocation();
Sebastian Redlc4704762008-11-11 11:37:55 +00001394
John McCalldadc5752010-08-24 06:29:42 +00001395 ExprResult Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001396
Richard Smith4f605af2012-08-18 00:55:03 +00001397 // C++0x [expr.typeid]p3:
1398 // When typeid is applied to an expression other than an lvalue of a
1399 // polymorphic class type [...] The expression is an unevaluated
1400 // operand (Clause 5).
1401 //
1402 // Note that we can't tell whether the expression is an lvalue of a
1403 // polymorphic class type until after we've parsed the expression; we
1404 // speculatively assume the subexpression is unevaluated, and fix it up
1405 // later.
1406 //
1407 // We enter the unevaluated context before trying to determine whether we
1408 // have a type-id, because the tentative parse logic will try to resolve
1409 // names, and must treat them as unevaluated.
Faisal Valid143a0c2017-04-01 21:30:49 +00001410 EnterExpressionEvaluationContext Unevaluated(
1411 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1412 Sema::ReuseLambdaContextDecl);
Richard Smith4f605af2012-08-18 00:55:03 +00001413
Sebastian Redlc4704762008-11-11 11:37:55 +00001414 if (isTypeIdInParens()) {
Douglas Gregor220cac52009-02-18 17:45:20 +00001415 TypeResult Ty = ParseTypeName();
Sebastian Redlc4704762008-11-11 11:37:55 +00001416
1417 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001418 T.consumeClose();
1419 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001420 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00001421 return ExprError();
Sebastian Redlc4704762008-11-11 11:37:55 +00001422
1423 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallba7bf592010-08-24 05:47:05 +00001424 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001425 } else {
1426 Result = ParseExpression();
1427
1428 // Match the ')'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001429 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001430 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc4704762008-11-11 11:37:55 +00001431 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001432 T.consumeClose();
1433 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001434 if (RParenLoc.isInvalid())
1435 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00001436
Sebastian Redlc4704762008-11-11 11:37:55 +00001437 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001438 Result.get(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001439 }
1440 }
1441
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001442 return Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001443}
1444
Francois Pichet9f4f2072010-09-08 12:20:18 +00001445/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1446///
1447/// '__uuidof' '(' expression ')'
1448/// '__uuidof' '(' type-id ')'
1449///
1450ExprResult Parser::ParseCXXUuidof() {
1451 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1452
1453 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001454 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001455
1456 // __uuidof expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001457 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet9f4f2072010-09-08 12:20:18 +00001458 return ExprError();
1459
1460 ExprResult Result;
1461
1462 if (isTypeIdInParens()) {
1463 TypeResult Ty = ParseTypeName();
1464
1465 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001466 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001467
1468 if (Ty.isInvalid())
1469 return ExprError();
1470
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001471 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
Fangrui Song6907ce22018-07-30 19:24:48 +00001472 Ty.get().getAsOpaquePtr(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001473 T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001474 } else {
Faisal Valid143a0c2017-04-01 21:30:49 +00001475 EnterExpressionEvaluationContext Unevaluated(
1476 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001477 Result = ParseExpression();
1478
1479 // Match the ')'.
1480 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001481 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001482 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001483 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001484
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001485 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1486 /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001487 Result.get(), T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001488 }
1489 }
1490
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001491 return Result;
Francois Pichet9f4f2072010-09-08 12:20:18 +00001492}
1493
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001494/// Parse a C++ pseudo-destructor expression after the base,
Douglas Gregore610ada2010-02-24 18:44:31 +00001495/// . or -> operator, and nested-name-specifier have already been
1496/// parsed.
1497///
1498/// postfix-expression: [C++ 5.2]
1499/// postfix-expression . pseudo-destructor-name
1500/// postfix-expression -> pseudo-destructor-name
1501///
Fangrui Song6907ce22018-07-30 19:24:48 +00001502/// pseudo-destructor-name:
1503/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1504/// ::[opt] nested-name-specifier template simple-template-id ::
1505/// ~type-name
Douglas Gregore610ada2010-02-24 18:44:31 +00001506/// ::[opt] nested-name-specifier[opt] ~type-name
Fangrui Song6907ce22018-07-30 19:24:48 +00001507///
1508ExprResult
Craig Toppera2c51532014-10-30 05:30:05 +00001509Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00001510 tok::TokenKind OpKind,
1511 CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +00001512 ParsedType ObjectType) {
Douglas Gregore610ada2010-02-24 18:44:31 +00001513 // We're parsing either a pseudo-destructor-name or a dependent
1514 // member access that has the same form as a
1515 // pseudo-destructor-name. We parse both in the same way and let
1516 // the action model sort them out.
1517 //
1518 // Note that the ::[opt] nested-name-specifier[opt] has already
1519 // been parsed, and if there was a simple-template-id, it has
1520 // been coalesced into a template-id annotation token.
1521 UnqualifiedId FirstTypeName;
1522 SourceLocation CCLoc;
1523 if (Tok.is(tok::identifier)) {
1524 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1525 ConsumeToken();
1526 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1527 CCLoc = ConsumeToken();
1528 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001529 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1530 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregore610ada2010-02-24 18:44:31 +00001531 FirstTypeName.setTemplateId(
1532 (TemplateIdAnnotation *)Tok.getAnnotationValue());
Richard Smithaf3b3252017-05-18 19:21:48 +00001533 ConsumeAnnotationToken();
Douglas Gregore610ada2010-02-24 18:44:31 +00001534 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1535 CCLoc = ConsumeToken();
1536 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001537 FirstTypeName.setIdentifier(nullptr, SourceLocation());
Douglas Gregore610ada2010-02-24 18:44:31 +00001538 }
1539
1540 // Parse the tilde.
1541 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1542 SourceLocation TildeLoc = ConsumeToken();
David Blaikie1d578782011-12-16 16:03:09 +00001543
1544 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1545 DeclSpec DS(AttrFactory);
Benjamin Kramer198e0832011-12-18 12:18:02 +00001546 ParseDecltypeSpecifier(DS);
Faisal Vali090da2d2018-01-01 18:23:28 +00001547 if (DS.getTypeSpecType() == TST_error)
David Blaikie1d578782011-12-16 16:03:09 +00001548 return ExprError();
David Majnemerced8bdf2015-02-25 17:36:15 +00001549 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1550 TildeLoc, DS);
David Blaikie1d578782011-12-16 16:03:09 +00001551 }
1552
Douglas Gregore610ada2010-02-24 18:44:31 +00001553 if (!Tok.is(tok::identifier)) {
1554 Diag(Tok, diag::err_destructor_tilde_identifier);
1555 return ExprError();
1556 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001557
Douglas Gregore610ada2010-02-24 18:44:31 +00001558 // Parse the second type.
1559 UnqualifiedId SecondTypeName;
1560 IdentifierInfo *Name = Tok.getIdentifierInfo();
1561 SourceLocation NameLoc = ConsumeToken();
1562 SecondTypeName.setIdentifier(Name, NameLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00001563
Douglas Gregore610ada2010-02-24 18:44:31 +00001564 // If there is a '<', the second type name is a template-id. Parse
1565 // it as such.
1566 if (Tok.is(tok::less) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +00001567 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1568 Name, NameLoc,
1569 false, ObjectType, SecondTypeName,
1570 /*AssumeTemplateName=*/true))
Douglas Gregore610ada2010-02-24 18:44:31 +00001571 return ExprError();
1572
David Majnemerced8bdf2015-02-25 17:36:15 +00001573 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1574 SS, FirstTypeName, CCLoc, TildeLoc,
1575 SecondTypeName);
Douglas Gregore610ada2010-02-24 18:44:31 +00001576}
1577
Bill Wendling4073ed52007-02-13 01:51:42 +00001578/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1579///
1580/// boolean-literal: [C++ 2.13.5]
1581/// 'true'
1582/// 'false'
John McCalldadc5752010-08-24 06:29:42 +00001583ExprResult Parser::ParseCXXBoolLiteral() {
Bill Wendling4073ed52007-02-13 01:51:42 +00001584 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001585 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Bill Wendling4073ed52007-02-13 01:51:42 +00001586}
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001587
1588/// ParseThrowExpression - This handles the C++ throw expression.
1589///
1590/// throw-expression: [C++ 15]
1591/// 'throw' assignment-expression[opt]
John McCalldadc5752010-08-24 06:29:42 +00001592ExprResult Parser::ParseThrowExpression() {
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001593 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001594 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redld65cea82008-12-11 22:51:44 +00001595
Chris Lattner65dd8432008-04-06 06:02:23 +00001596 // If the current token isn't the start of an assignment-expression,
1597 // then the expression is not present. This handles things like:
1598 // "C ? throw : (void)42", which is crazy but legal.
1599 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1600 case tok::semi:
1601 case tok::r_paren:
1602 case tok::r_square:
1603 case tok::r_brace:
1604 case tok::colon:
1605 case tok::comma:
Craig Topper161e4db2014-05-21 06:02:52 +00001606 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001607
Chris Lattner65dd8432008-04-06 06:02:23 +00001608 default:
John McCalldadc5752010-08-24 06:29:42 +00001609 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001610 if (Expr.isInvalid()) return Expr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001611 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
Chris Lattner65dd8432008-04-06 06:02:23 +00001612 }
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001613}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001614
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001615/// Parse the C++ Coroutines co_yield expression.
Richard Smith0e304ea2015-10-22 04:46:14 +00001616///
1617/// co_yield-expression:
1618/// 'co_yield' assignment-expression[opt]
1619ExprResult Parser::ParseCoyieldExpression() {
1620 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1621
1622 SourceLocation Loc = ConsumeToken();
Richard Smithae3d1472015-11-20 22:47:10 +00001623 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1624 : ParseAssignmentExpression();
Richard Smithcfd53b42015-10-22 06:13:50 +00001625 if (!Expr.isInvalid())
Richard Smith9f690bd2015-10-27 06:02:45 +00001626 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
Richard Smith0e304ea2015-10-22 04:46:14 +00001627 return Expr;
1628}
1629
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001630/// ParseCXXThis - This handles the C++ 'this' pointer.
1631///
1632/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1633/// a non-lvalue expression whose value is the address of the object for which
1634/// the function is called.
John McCalldadc5752010-08-24 06:29:42 +00001635ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001636 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1637 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001638 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001639}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001640
1641/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1642/// Can be interpreted either as function-style casting ("int(x)")
1643/// or class type construction ("ClassType(x,y,z)")
1644/// or creation of a value-initialized type ("int()").
Sebastian Redl3da34892011-06-05 12:23:16 +00001645/// See [C++ 5.2.3].
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001646///
1647/// postfix-expression: [C++ 5.2p1]
Sebastian Redl3da34892011-06-05 12:23:16 +00001648/// simple-type-specifier '(' expression-list[opt] ')'
1649/// [C++0x] simple-type-specifier braced-init-list
1650/// typename-specifier '(' expression-list[opt] ')'
1651/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001652///
Richard Smith600b5262017-01-26 20:40:47 +00001653/// In C++1z onwards, the type specifier can also be a template-name.
John McCalldadc5752010-08-24 06:29:42 +00001654ExprResult
Sebastian Redld65cea82008-12-11 22:51:44 +00001655Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Faisal Vali421b2d12017-12-29 05:41:00 +00001656 Declarator DeclaratorInfo(DS, DeclaratorContext::FunctionalCastContext);
John McCallba7bf592010-08-24 05:47:05 +00001657 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001658
Sebastian Redl3da34892011-06-05 12:23:16 +00001659 assert((Tok.is(tok::l_paren) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001660 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redl3da34892011-06-05 12:23:16 +00001661 && "Expected '(' or '{'!");
Douglas Gregor94a32472011-01-11 00:33:19 +00001662
Sebastian Redl3da34892011-06-05 12:23:16 +00001663 if (Tok.is(tok::l_brace)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001664 ExprResult Init = ParseBraceInitializer();
1665 if (Init.isInvalid())
1666 return Init;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001667 Expr *InitList = Init.get();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001668 return Actions.ActOnCXXTypeConstructExpr(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001669 TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001670 InitList->getEndLoc(), /*ListInitialization=*/true);
Sebastian Redl3da34892011-06-05 12:23:16 +00001671 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001672 BalancedDelimiterTracker T(*this, tok::l_paren);
1673 T.consumeOpen();
Sebastian Redl3da34892011-06-05 12:23:16 +00001674
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00001675 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1676
Benjamin Kramerf0623432012-08-23 22:51:59 +00001677 ExprVector Exprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00001678 CommaLocsTy CommaLocs;
1679
1680 if (Tok.isNot(tok::r_paren)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00001681 if (ParseExpressionList(Exprs, CommaLocs, [&] {
Ilya Biryukov832c4af2018-09-07 14:04:39 +00001682 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001683 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
Ilya Biryukov2fab2352018-08-30 13:08:03 +00001684 DS.getEndLoc(), Exprs, T.getOpenLocation());
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00001685 CalledSignatureHelp = true;
Ilya Biryukov832c4af2018-09-07 14:04:39 +00001686 Actions.CodeCompleteExpression(getCurScope(), PreferredType);
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001687 })) {
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00001688 if (PP.isCodeCompletionReached() && !CalledSignatureHelp) {
1689 Actions.ProduceConstructorSignatureHelp(
1690 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
1691 DS.getEndLoc(), Exprs, T.getOpenLocation());
1692 CalledSignatureHelp = true;
1693 }
Alexey Bataevee6507d2013-11-18 08:17:37 +00001694 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00001695 return ExprError();
1696 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001697 }
Sebastian Redl3da34892011-06-05 12:23:16 +00001698
1699 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001700 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00001701
1702 // TypeRep could be null, if it references an invalid typedef.
1703 if (!TypeRep)
1704 return ExprError();
1705
1706 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1707 "Unexpected number of commas!");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001708 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1709 Exprs, T.getCloseLocation(),
1710 /*ListInitialization=*/false);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001711 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001712}
1713
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001714/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001715///
1716/// condition:
1717/// expression
1718/// type-specifier-seq declarator '=' assignment-expression
Richard Smith2a15b742012-02-22 06:49:09 +00001719/// [C++11] type-specifier-seq declarator '=' initializer-clause
1720/// [C++11] type-specifier-seq declarator braced-init-list
Zhihao Yuanc81f4532017-12-07 07:03:15 +00001721/// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1722/// brace-or-equal-initializer
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001723/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1724/// '=' assignment-expression
1725///
Richard Smithc7a05a92016-06-29 21:17:59 +00001726/// In C++1z, a condition may in some contexts be preceded by an
1727/// optional init-statement. This function will parse that too.
1728///
1729/// \param InitStmt If non-null, an init-statement is permitted, and if present
1730/// will be parsed and stored here.
1731///
Douglas Gregore60e41a2010-05-06 17:25:47 +00001732/// \param Loc The location of the start of the statement that requires this
1733/// condition, e.g., the "for" in a for loop.
1734///
Richard Smith8baa5002018-09-28 18:44:09 +00001735/// \param FRI If non-null, a for range declaration is permitted, and if
1736/// present will be parsed and stored here, and a null result will be returned.
1737///
Richard Smith03a4aa32016-06-23 19:02:52 +00001738/// \returns The parsed condition.
Richard Smithc7a05a92016-06-29 21:17:59 +00001739Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1740 SourceLocation Loc,
Richard Smith8baa5002018-09-28 18:44:09 +00001741 Sema::ConditionKind CK,
1742 ForRangeInfo *FRI) {
Richard Smithbf5bcf22018-06-26 23:20:26 +00001743 ParenBraceBracketBalancer BalancerRAIIObj(*this);
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00001744 PreferredType.enterCondition(Actions, Tok.getLocation());
Richard Smithbf5bcf22018-06-26 23:20:26 +00001745
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001746 if (Tok.is(tok::code_completion)) {
John McCallfaf5fb42010-08-26 23:41:50 +00001747 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001748 cutOffParsing();
Richard Smith03a4aa32016-06-23 19:02:52 +00001749 return Sema::ConditionError();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001750 }
1751
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001752 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001753 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001754
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001755 const auto WarnOnInit = [this, &CK] {
1756 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
1757 ? diag::warn_cxx14_compat_init_statement
1758 : diag::ext_init_statement)
1759 << (CK == Sema::ConditionKind::Switch);
1760 };
1761
Richard Smithc7a05a92016-06-29 21:17:59 +00001762 // Determine what kind of thing we have.
Richard Smith8baa5002018-09-28 18:44:09 +00001763 switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
Richard Smithc7a05a92016-06-29 21:17:59 +00001764 case ConditionOrInitStatement::Expression: {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001765 ProhibitAttributes(attrs);
1766
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001767 // We can have an empty expression here.
1768 // if (; true);
1769 if (InitStmt && Tok.is(tok::semi)) {
1770 WarnOnInit();
Roman Lebedev377748f2018-11-20 18:59:05 +00001771 SourceLocation SemiLoc = Tok.getLocation();
1772 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
1773 Diag(SemiLoc, diag::warn_empty_init_statement)
1774 << (CK == Sema::ConditionKind::Switch)
1775 << FixItHint::CreateRemoval(SemiLoc);
1776 }
1777 ConsumeToken();
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001778 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
1779 return ParseCXXCondition(nullptr, Loc, CK);
1780 }
1781
Douglas Gregore60e41a2010-05-06 17:25:47 +00001782 // Parse the expression.
Richard Smith03a4aa32016-06-23 19:02:52 +00001783 ExprResult Expr = ParseExpression(); // expression
1784 if (Expr.isInvalid())
1785 return Sema::ConditionError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00001786
Richard Smithc7a05a92016-06-29 21:17:59 +00001787 if (InitStmt && Tok.is(tok::semi)) {
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001788 WarnOnInit();
Richard Smithc7a05a92016-06-29 21:17:59 +00001789 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1790 ConsumeToken();
1791 return ParseCXXCondition(nullptr, Loc, CK);
1792 }
1793
Richard Smith03a4aa32016-06-23 19:02:52 +00001794 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001795 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001796
Richard Smithc7a05a92016-06-29 21:17:59 +00001797 case ConditionOrInitStatement::InitStmtDecl: {
Zhihao Yuan52b5bf82018-03-17 21:42:10 +00001798 WarnOnInit();
Richard Smithc7a05a92016-06-29 21:17:59 +00001799 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
Faisal Vali421b2d12017-12-29 05:41:00 +00001800 DeclGroupPtrTy DG =
1801 ParseSimpleDeclaration(DeclaratorContext::InitStmtContext, DeclEnd,
1802 attrs, /*RequireSemi=*/true);
Richard Smithc7a05a92016-06-29 21:17:59 +00001803 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1804 return ParseCXXCondition(nullptr, Loc, CK);
1805 }
1806
Richard Smith8baa5002018-09-28 18:44:09 +00001807 case ConditionOrInitStatement::ForRangeDecl: {
1808 assert(FRI && "should not parse a for range declaration here");
1809 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1810 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1811 DeclaratorContext::ForContext, DeclEnd, attrs, false, FRI);
1812 FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
1813 return Sema::ConditionResult();
1814 }
1815
Richard Smithc7a05a92016-06-29 21:17:59 +00001816 case ConditionOrInitStatement::ConditionDecl:
1817 case ConditionOrInitStatement::Error:
1818 break;
1819 }
1820
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001821 // type-specifier-seq
John McCall084e83d2011-03-24 11:26:52 +00001822 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +00001823 DS.takeAttributesFrom(attrs);
Faisal Vali7db85c52017-12-31 00:06:40 +00001824 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001825
1826 // declarator
Faisal Vali421b2d12017-12-29 05:41:00 +00001827 Declarator DeclaratorInfo(DS, DeclaratorContext::ConditionContext);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001828 ParseDeclarator(DeclaratorInfo);
1829
1830 // simple-asm-expr[opt]
1831 if (Tok.is(tok::kw_asm)) {
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001832 SourceLocation Loc;
John McCalldadc5752010-08-24 06:29:42 +00001833 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001834 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001835 SkipUntil(tok::semi, StopAtSemi);
Richard Smith03a4aa32016-06-23 19:02:52 +00001836 return Sema::ConditionError();
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001837 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001838 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001839 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001840 }
1841
1842 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001843 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001844
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001845 // Type-check the declaration itself.
Fangrui Song6907ce22018-07-30 19:24:48 +00001846 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall53fa7142010-12-24 02:08:15 +00001847 DeclaratorInfo);
Richard Smith03a4aa32016-06-23 19:02:52 +00001848 if (Dcl.isInvalid())
1849 return Sema::ConditionError();
1850 Decl *DeclOut = Dcl.get();
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001851
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001852 // '=' assignment-expression
Richard Trieuc64d3232012-01-18 22:54:52 +00001853 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith2a15b742012-02-22 06:49:09 +00001854 bool CopyInitialization = isTokenEqualOrEqualTypo();
1855 if (CopyInitialization)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001856 ConsumeToken();
Richard Smith2a15b742012-02-22 06:49:09 +00001857
1858 ExprResult InitExpr = ExprError();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001859 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith2a15b742012-02-22 06:49:09 +00001860 Diag(Tok.getLocation(),
1861 diag::warn_cxx98_compat_generalized_initializer_lists);
1862 InitExpr = ParseBraceInitializer();
1863 } else if (CopyInitialization) {
Ilya Biryukov4f9543b2019-01-31 20:20:32 +00001864 PreferredType.enterVariableInit(Tok.getLocation(), DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001865 InitExpr = ParseAssignmentExpression();
1866 } else if (Tok.is(tok::l_paren)) {
1867 // This was probably an attempt to initialize the variable.
1868 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001869 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith2a15b742012-02-22 06:49:09 +00001870 RParen = ConsumeParen();
Richard Smith03a4aa32016-06-23 19:02:52 +00001871 Diag(DeclOut->getLocation(),
Richard Smith2a15b742012-02-22 06:49:09 +00001872 diag::err_expected_init_in_condition_lparen)
1873 << SourceRange(LParen, RParen);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001874 } else {
Richard Smith03a4aa32016-06-23 19:02:52 +00001875 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001876 }
Richard Smith2a15b742012-02-22 06:49:09 +00001877
1878 if (!InitExpr.isInvalid())
Richard Smith3beb7c62017-01-12 02:27:38 +00001879 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
Richard Smith27d807c2013-04-30 13:56:41 +00001880 else
1881 Actions.ActOnInitializerError(DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001882
Richard Smithb2bc2e62011-02-21 20:05:19 +00001883 Actions.FinalizeDeclaration(DeclOut);
Richard Smith03a4aa32016-06-23 19:02:52 +00001884 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001885}
1886
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001887/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1888/// This should only be called when the current token is known to be part of
1889/// simple-type-specifier.
1890///
1891/// simple-type-specifier:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001892/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001893/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1894/// char
1895/// wchar_t
1896/// bool
1897/// short
1898/// int
1899/// long
1900/// signed
1901/// unsigned
1902/// float
1903/// double
1904/// void
1905/// [GNU] typeof-specifier
1906/// [C++0x] auto [TODO]
1907///
1908/// type-name:
1909/// class-name
1910/// enum-name
1911/// typedef-name
1912///
1913void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1914 DS.SetRangeStart(Tok.getLocation());
1915 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +00001916 unsigned DiagID;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001917 SourceLocation Loc = Tok.getLocation();
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001918 const clang::PrintingPolicy &Policy =
1919 Actions.getASTContext().getPrintingPolicy();
Mike Stump11289f42009-09-09 15:08:12 +00001920
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001921 switch (Tok.getKind()) {
Chris Lattner45ddec32009-01-05 00:13:00 +00001922 case tok::identifier: // foo::bar
1923 case tok::coloncolon: // ::foo::bar
David Blaikie83d382b2011-09-23 05:06:16 +00001924 llvm_unreachable("Annotation token should already be formed!");
Mike Stump11289f42009-09-09 15:08:12 +00001925 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001926 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner45ddec32009-01-05 00:13:00 +00001927
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001928 // type-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00001929 case tok::annot_typename: {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001930 if (getTypeAnnotation(Tok))
1931 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001932 getTypeAnnotation(Tok), Policy);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001933 else
1934 DS.SetTypeSpecError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001935
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001936 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
Richard Smithaf3b3252017-05-18 19:21:48 +00001937 ConsumeAnnotationToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00001938
Craig Topper25122412015-11-15 03:32:11 +00001939 DS.Finish(Actions, Policy);
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001940 return;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001941 }
Mike Stump11289f42009-09-09 15:08:12 +00001942
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001943 // builtin types
1944 case tok::kw_short:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001945 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001946 break;
1947 case tok::kw_long:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001948 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001949 break;
Francois Pichet84133e42011-04-28 01:59:37 +00001950 case tok::kw___int64:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001951 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00001952 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001953 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00001954 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001955 break;
1956 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00001957 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001958 break;
1959 case tok::kw_void:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001960 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001961 break;
1962 case tok::kw_char:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001963 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001964 break;
1965 case tok::kw_int:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001966 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001967 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00001968 case tok::kw___int128:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001969 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00001970 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001971 case tok::kw_half:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001972 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001973 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001974 case tok::kw_float:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001975 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001976 break;
1977 case tok::kw_double:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001978 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001979 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001980 case tok::kw__Float16:
1981 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
1982 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001983 case tok::kw___float128:
1984 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
1985 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001986 case tok::kw_wchar_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001987 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001988 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00001989 case tok::kw_char8_t:
1990 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
1991 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001992 case tok::kw_char16_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001993 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001994 break;
1995 case tok::kw_char32_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001996 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001997 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001998 case tok::kw_bool:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001999 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002000 break;
Anastasia Stulova2c4730d2019-02-15 12:07:57 +00002001#define GENERIC_IMAGE_TYPE(ImgType, Id) \
2002 case tok::kw_##ImgType##_t: \
2003 DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \
2004 Policy); \
2005 break;
2006#include "clang/Basic/OpenCLImageTypes.def"
2007
David Blaikie25896afb2012-01-24 05:47:35 +00002008 case tok::annot_decltype:
2009 case tok::kw_decltype:
2010 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
Craig Topper25122412015-11-15 03:32:11 +00002011 return DS.Finish(Actions, Policy);
Mike Stump11289f42009-09-09 15:08:12 +00002012
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002013 // GNU typeof support.
2014 case tok::kw_typeof:
2015 ParseTypeofSpecifier(DS);
Craig Topper25122412015-11-15 03:32:11 +00002016 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002017 return;
2018 }
Richard Smithaf3b3252017-05-18 19:21:48 +00002019 ConsumeAnyToken();
2020 DS.SetRangeEnd(PrevTokLocation);
Craig Topper25122412015-11-15 03:32:11 +00002021 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00002022}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002023
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002024/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2025/// [dcl.name]), which is a non-empty sequence of type-specifiers,
2026/// e.g., "const short int". Note that the DeclSpec is *not* finished
2027/// by parsing the type-specifier-seq, because these sequences are
2028/// typically followed by some form of declarator. Returns true and
2029/// emits diagnostics if this is not a type-specifier-seq, false
2030/// otherwise.
2031///
2032/// type-specifier-seq: [C++ 8.1]
2033/// type-specifier type-specifier-seq[opt]
2034///
2035bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Faisal Vali7db85c52017-12-31 00:06:40 +00002036 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
Craig Topper25122412015-11-15 03:32:11 +00002037 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002038 return false;
2039}
2040
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002041/// Finish parsing a C++ unqualified-id that is a template-id of
Fangrui Song6907ce22018-07-30 19:24:48 +00002042/// some form.
Douglas Gregor7861a802009-11-03 01:35:08 +00002043///
2044/// This routine is invoked when a '<' is encountered after an identifier or
2045/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2046/// whether the unqualified-id is actually a template-id. This routine will
2047/// then parse the template arguments and form the appropriate template-id to
2048/// return to the caller.
2049///
2050/// \param SS the nested-name-specifier that precedes this template-id, if
2051/// we're actually parsing a qualified-id.
2052///
2053/// \param Name for constructor and destructor names, this is the actual
2054/// identifier that may be a template-name.
2055///
Fangrui Song6907ce22018-07-30 19:24:48 +00002056/// \param NameLoc the location of the class-name in a constructor or
Douglas Gregor7861a802009-11-03 01:35:08 +00002057/// destructor.
2058///
Fangrui Song6907ce22018-07-30 19:24:48 +00002059/// \param EnteringContext whether we're entering the scope of the
Douglas Gregor7861a802009-11-03 01:35:08 +00002060/// nested-name-specifier.
2061///
Douglas Gregor127ea592009-11-03 21:24:04 +00002062/// \param ObjectType if this unqualified-id occurs within a member access
2063/// expression, the type of the base object whose member is being accessed.
2064///
Douglas Gregor7861a802009-11-03 01:35:08 +00002065/// \param Id as input, describes the template-name or operator-function-id
2066/// that precedes the '<'. If template arguments were parsed successfully,
2067/// will be updated with the template-id.
Fangrui Song6907ce22018-07-30 19:24:48 +00002068///
Douglas Gregore610ada2010-02-24 18:44:31 +00002069/// \param AssumeTemplateId When true, this routine will assume that the name
Fangrui Song6907ce22018-07-30 19:24:48 +00002070/// refers to a template without performing name lookup to verify.
Douglas Gregore610ada2010-02-24 18:44:31 +00002071///
Douglas Gregor7861a802009-11-03 01:35:08 +00002072/// \returns true if a parse error occurred, false otherwise.
2073bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002074 SourceLocation TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002075 IdentifierInfo *Name,
2076 SourceLocation NameLoc,
2077 bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002078 ParsedType ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00002079 UnqualifiedId &Id,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002080 bool AssumeTemplateId) {
Richard Smithc08b6932018-04-27 02:00:13 +00002081 assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
2082
Douglas Gregor7861a802009-11-03 01:35:08 +00002083 TemplateTy Template;
2084 TemplateNameKind TNK = TNK_Non_template;
2085 switch (Id.getKind()) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00002086 case UnqualifiedIdKind::IK_Identifier:
2087 case UnqualifiedIdKind::IK_OperatorFunctionId:
2088 case UnqualifiedIdKind::IK_LiteralOperatorId:
Douglas Gregore610ada2010-02-24 18:44:31 +00002089 if (AssumeTemplateId) {
Richard Smithfd3dae02017-01-20 00:20:39 +00002090 // We defer the injected-class-name checks until we've found whether
2091 // this template-id is used to form a nested-name-specifier or not.
2092 TNK = Actions.ActOnDependentTemplateName(
2093 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2094 Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002095 if (TNK == TNK_Non_template)
2096 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00002097 } else {
2098 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002099 TNK = Actions.isTemplateName(getCurScope(), SS,
2100 TemplateKWLoc.isValid(), Id,
2101 ObjectType, EnteringContext, Template,
Douglas Gregor786123d2010-05-21 23:18:07 +00002102 MemberOfUnknownSpecialization);
Fangrui Song6907ce22018-07-30 19:24:48 +00002103
Douglas Gregor786123d2010-05-21 23:18:07 +00002104 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2105 ObjectType && IsTemplateArgumentList()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002106 // We have something like t->getAs<T>(), where getAs is a
Douglas Gregor786123d2010-05-21 23:18:07 +00002107 // member of an unknown specialization. However, this will only
2108 // parse correctly as a template, so suggest the keyword 'template'
2109 // before 'getAs' and treat this as a dependent template name.
2110 std::string Name;
Faisal Vali2ab8c152017-12-30 04:15:27 +00002111 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
Douglas Gregor786123d2010-05-21 23:18:07 +00002112 Name = Id.Identifier->getName();
2113 else {
2114 Name = "operator ";
Faisal Vali2ab8c152017-12-30 04:15:27 +00002115 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
Douglas Gregor786123d2010-05-21 23:18:07 +00002116 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2117 else
2118 Name += Id.Identifier->getName();
2119 }
2120 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2121 << Name
2122 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Richard Smithfd3dae02017-01-20 00:20:39 +00002123 TNK = Actions.ActOnDependentTemplateName(
2124 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2125 Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002126 if (TNK == TNK_Non_template)
Fangrui Song6907ce22018-07-30 19:24:48 +00002127 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00002128 }
2129 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002130 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002131
Faisal Vali2ab8c152017-12-30 04:15:27 +00002132 case UnqualifiedIdKind::IK_ConstructorName: {
Douglas Gregor3cf81312009-11-03 23:16:33 +00002133 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002134 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002135 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002136 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002137 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002138 EnteringContext, Template,
2139 MemberOfUnknownSpecialization);
Douglas Gregor7861a802009-11-03 01:35:08 +00002140 break;
2141 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002142
Faisal Vali2ab8c152017-12-30 04:15:27 +00002143 case UnqualifiedIdKind::IK_DestructorName: {
Douglas Gregor3cf81312009-11-03 23:16:33 +00002144 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002145 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002146 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002147 if (ObjectType) {
Richard Smithfd3dae02017-01-20 00:20:39 +00002148 TNK = Actions.ActOnDependentTemplateName(
2149 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2150 EnteringContext, Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002151 if (TNK == TNK_Non_template)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002152 return true;
2153 } else {
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002154 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002155 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002156 EnteringContext, Template,
2157 MemberOfUnknownSpecialization);
Fangrui Song6907ce22018-07-30 19:24:48 +00002158
John McCallba7bf592010-08-24 05:47:05 +00002159 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002160 Diag(NameLoc, diag::err_destructor_template_id)
2161 << Name << SS.getRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00002162 return true;
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002163 }
2164 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002165 break;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002166 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002167
Douglas Gregor7861a802009-11-03 01:35:08 +00002168 default:
2169 return false;
2170 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002171
Douglas Gregor7861a802009-11-03 01:35:08 +00002172 if (TNK == TNK_Non_template)
2173 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00002174
Douglas Gregor7861a802009-11-03 01:35:08 +00002175 // Parse the enclosed template argument list.
2176 SourceLocation LAngleLoc, RAngleLoc;
2177 TemplateArgList TemplateArgs;
Richard Smithc08b6932018-04-27 02:00:13 +00002178 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
2179 RAngleLoc))
Douglas Gregor7861a802009-11-03 01:35:08 +00002180 return true;
Richard Smithc08b6932018-04-27 02:00:13 +00002181
Faisal Vali2ab8c152017-12-30 04:15:27 +00002182 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2183 Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2184 Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002185 // Form a parsed representation of the template-id to be stored in the
2186 // UnqualifiedId.
Douglas Gregor7861a802009-11-03 01:35:08 +00002187
Richard Smith72bfbd82013-12-04 00:28:23 +00002188 // FIXME: Store name for literal operator too.
Faisal Vali43caf672017-05-23 01:07:12 +00002189 IdentifierInfo *TemplateII =
Faisal Vali2ab8c152017-12-30 04:15:27 +00002190 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2191 : nullptr;
2192 OverloadedOperatorKind OpKind =
2193 Id.getKind() == UnqualifiedIdKind::IK_Identifier
2194 ? OO_None
2195 : Id.OperatorFunctionId.Operator;
Douglas Gregor7861a802009-11-03 01:35:08 +00002196
Faisal Vali43caf672017-05-23 01:07:12 +00002197 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2198 SS, TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2199 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
2200
Douglas Gregor7861a802009-11-03 01:35:08 +00002201 Id.setTemplateId(TemplateId);
2202 return false;
2203 }
2204
2205 // Bundle the template arguments together.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002206 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnara4244b432012-01-27 08:46:19 +00002207
Douglas Gregor7861a802009-11-03 01:35:08 +00002208 // Constructor and destructor names.
John McCallfaf5fb42010-08-26 23:41:50 +00002209 TypeResult Type
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002210 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00002211 Template, Name, NameLoc,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002212 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2213 /*IsCtorOrDtorName=*/true);
Douglas Gregor7861a802009-11-03 01:35:08 +00002214 if (Type.isInvalid())
2215 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002216
Faisal Vali2ab8c152017-12-30 04:15:27 +00002217 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
Douglas Gregor7861a802009-11-03 01:35:08 +00002218 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2219 else
2220 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00002221
Douglas Gregor7861a802009-11-03 01:35:08 +00002222 return false;
2223}
2224
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002225/// Parse an operator-function-id or conversion-function-id as part
Douglas Gregor71395fa2009-11-04 00:56:37 +00002226/// of a C++ unqualified-id.
2227///
2228/// This routine is responsible only for parsing the operator-function-id or
2229/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor7861a802009-11-03 01:35:08 +00002230///
2231/// \code
Douglas Gregor7861a802009-11-03 01:35:08 +00002232/// operator-function-id: [C++ 13.5]
2233/// 'operator' operator
2234///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002235/// operator: one of
Douglas Gregor7861a802009-11-03 01:35:08 +00002236/// new delete new[] delete[]
2237/// + - * / % ^ & | ~
2238/// ! = < > += -= *= /= %=
2239/// ^= &= |= << >> >>= <<= == !=
2240/// <= >= && || ++ -- , ->* ->
Richard Smithd30b23d2017-12-01 02:13:10 +00002241/// () [] <=>
Douglas Gregor7861a802009-11-03 01:35:08 +00002242///
2243/// conversion-function-id: [C++ 12.3.2]
2244/// operator conversion-type-id
2245///
2246/// conversion-type-id:
2247/// type-specifier-seq conversion-declarator[opt]
2248///
2249/// conversion-declarator:
2250/// ptr-operator conversion-declarator[opt]
2251/// \endcode
2252///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002253/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor7861a802009-11-03 01:35:08 +00002254/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2255///
Fangrui Song6907ce22018-07-30 19:24:48 +00002256/// \param EnteringContext whether we are entering the scope of the
Douglas Gregor7861a802009-11-03 01:35:08 +00002257/// nested-name-specifier.
2258///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002259/// \param ObjectType if this unqualified-id occurs within a member access
2260/// expression, the type of the base object whose member is being accessed.
2261///
2262/// \param Result on a successful parse, contains the parsed unqualified-id.
2263///
2264/// \returns true if parsing fails, false otherwise.
2265bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002266 ParsedType ObjectType,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002267 UnqualifiedId &Result) {
2268 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
Fangrui Song6907ce22018-07-30 19:24:48 +00002269
Douglas Gregor71395fa2009-11-04 00:56:37 +00002270 // Consume the 'operator' keyword.
2271 SourceLocation KeywordLoc = ConsumeToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00002272
Douglas Gregor71395fa2009-11-04 00:56:37 +00002273 // Determine what kind of operator name we have.
2274 unsigned SymbolIdx = 0;
2275 SourceLocation SymbolLocations[3];
2276 OverloadedOperatorKind Op = OO_None;
2277 switch (Tok.getKind()) {
2278 case tok::kw_new:
2279 case tok::kw_delete: {
2280 bool isNew = Tok.getKind() == tok::kw_new;
2281 // Consume the 'new' or 'delete'.
2282 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002283 // Check for array new/delete.
2284 if (Tok.is(tok::l_square) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002285 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002286 // Consume the '[' and ']'.
2287 BalancedDelimiterTracker T(*this, tok::l_square);
2288 T.consumeOpen();
2289 T.consumeClose();
2290 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002291 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002292
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002293 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2294 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002295 Op = isNew? OO_Array_New : OO_Array_Delete;
2296 } else {
2297 Op = isNew? OO_New : OO_Delete;
2298 }
2299 break;
2300 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002301
Douglas Gregor71395fa2009-11-04 00:56:37 +00002302#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2303 case tok::Token: \
2304 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2305 Op = OO_##Name; \
2306 break;
2307#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2308#include "clang/Basic/OperatorKinds.def"
Fangrui Song6907ce22018-07-30 19:24:48 +00002309
Douglas Gregor71395fa2009-11-04 00:56:37 +00002310 case tok::l_paren: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002311 // Consume the '(' and ')'.
2312 BalancedDelimiterTracker T(*this, tok::l_paren);
2313 T.consumeOpen();
2314 T.consumeClose();
2315 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002316 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002317
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002318 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2319 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002320 Op = OO_Call;
2321 break;
2322 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002323
Douglas Gregor71395fa2009-11-04 00:56:37 +00002324 case tok::l_square: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002325 // Consume the '[' and ']'.
2326 BalancedDelimiterTracker T(*this, tok::l_square);
2327 T.consumeOpen();
2328 T.consumeClose();
2329 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002330 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002331
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002332 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2333 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002334 Op = OO_Subscript;
2335 break;
2336 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002337
Douglas Gregor71395fa2009-11-04 00:56:37 +00002338 case tok::code_completion: {
2339 // Code completion for the operator name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002340 Actions.CodeCompleteOperatorName(getCurScope());
Fangrui Song6907ce22018-07-30 19:24:48 +00002341 cutOffParsing();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002342 // Don't try to parse any further.
2343 return true;
2344 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002345
Douglas Gregor71395fa2009-11-04 00:56:37 +00002346 default:
2347 break;
2348 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002349
Douglas Gregor71395fa2009-11-04 00:56:37 +00002350 if (Op != OO_None) {
2351 // We have parsed an operator-function-id.
2352 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2353 return false;
2354 }
Alexis Hunt34458502009-11-28 04:44:28 +00002355
2356 // Parse a literal-operator-id.
2357 //
Richard Smith6f212062012-10-20 08:41:10 +00002358 // literal-operator-id: C++11 [over.literal]
2359 // operator string-literal identifier
2360 // operator user-defined-string-literal
Alexis Hunt34458502009-11-28 04:44:28 +00002361
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002362 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002363 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Alexis Hunt34458502009-11-28 04:44:28 +00002364
Richard Smith7d182a72012-03-08 23:06:02 +00002365 SourceLocation DiagLoc;
2366 unsigned DiagId = 0;
2367
2368 // We're past translation phase 6, so perform string literal concatenation
2369 // before checking for "".
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002370 SmallVector<Token, 4> Toks;
2371 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith7d182a72012-03-08 23:06:02 +00002372 while (isTokenStringLiteral()) {
2373 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smith6f212062012-10-20 08:41:10 +00002374 // C++11 [over.literal]p1:
2375 // The string-literal or user-defined-string-literal in a
2376 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith7d182a72012-03-08 23:06:02 +00002377 DiagLoc = Tok.getLocation();
2378 DiagId = diag::err_literal_operator_string_prefix;
2379 }
2380 Toks.push_back(Tok);
2381 TokLocs.push_back(ConsumeStringToken());
2382 }
2383
Craig Topper9d5583e2014-06-26 04:58:39 +00002384 StringLiteralParser Literal(Toks, PP);
Richard Smith7d182a72012-03-08 23:06:02 +00002385 if (Literal.hadError)
2386 return true;
2387
2388 // Grab the literal operator's suffix, which will be either the next token
2389 // or a ud-suffix from the string literal.
Craig Topper161e4db2014-05-21 06:02:52 +00002390 IdentifierInfo *II = nullptr;
Richard Smith7d182a72012-03-08 23:06:02 +00002391 SourceLocation SuffixLoc;
2392 if (!Literal.getUDSuffix().empty()) {
2393 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2394 SuffixLoc =
2395 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2396 Literal.getUDSuffixOffset(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002397 PP.getSourceManager(), getLangOpts());
Richard Smith7d182a72012-03-08 23:06:02 +00002398 } else if (Tok.is(tok::identifier)) {
2399 II = Tok.getIdentifierInfo();
2400 SuffixLoc = ConsumeToken();
2401 TokLocs.push_back(SuffixLoc);
2402 } else {
Alp Tokerec543272013-12-24 09:48:30 +00002403 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexis Hunt34458502009-11-28 04:44:28 +00002404 return true;
2405 }
2406
Richard Smith7d182a72012-03-08 23:06:02 +00002407 // The string literal must be empty.
2408 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smith6f212062012-10-20 08:41:10 +00002409 // C++11 [over.literal]p1:
2410 // The string-literal or user-defined-string-literal in a
2411 // literal-operator-id shall [...] contain no characters
2412 // other than the implicit terminating '\0'.
Richard Smith7d182a72012-03-08 23:06:02 +00002413 DiagLoc = TokLocs.front();
2414 DiagId = diag::err_literal_operator_string_not_empty;
2415 }
2416
2417 if (DiagId) {
2418 // This isn't a valid literal-operator-id, but we think we know
2419 // what the user meant. Tell them what they should have written.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002420 SmallString<32> Str;
Richard Smithe87aeb32015-10-08 00:17:59 +00002421 Str += "\"\"";
Richard Smith7d182a72012-03-08 23:06:02 +00002422 Str += II->getName();
2423 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2424 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2425 }
2426
2427 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Richard Smithd091dc12013-12-05 00:58:33 +00002428
2429 return Actions.checkLiteralOperatorId(SS, Result);
Alexis Hunt34458502009-11-28 04:44:28 +00002430 }
Richard Smithd091dc12013-12-05 00:58:33 +00002431
Douglas Gregor71395fa2009-11-04 00:56:37 +00002432 // Parse a conversion-function-id.
2433 //
2434 // conversion-function-id: [C++ 12.3.2]
2435 // operator conversion-type-id
2436 //
2437 // conversion-type-id:
2438 // type-specifier-seq conversion-declarator[opt]
2439 //
2440 // conversion-declarator:
2441 // ptr-operator conversion-declarator[opt]
Fangrui Song6907ce22018-07-30 19:24:48 +00002442
Douglas Gregor71395fa2009-11-04 00:56:37 +00002443 // Parse the type-specifier-seq.
John McCall084e83d2011-03-24 11:26:52 +00002444 DeclSpec DS(AttrFactory);
Douglas Gregora25d65d2009-11-20 22:03:38 +00002445 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregor71395fa2009-11-04 00:56:37 +00002446 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002447
Douglas Gregor71395fa2009-11-04 00:56:37 +00002448 // Parse the conversion-declarator, which is merely a sequence of
2449 // ptr-operators.
Faisal Vali421b2d12017-12-29 05:41:00 +00002450 Declarator D(DS, DeclaratorContext::ConversionIdContext);
Craig Topper161e4db2014-05-21 06:02:52 +00002451 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2452
Douglas Gregor71395fa2009-11-04 00:56:37 +00002453 // Finish up the type.
John McCallfaf5fb42010-08-26 23:41:50 +00002454 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002455 if (Ty.isInvalid())
2456 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002457
Douglas Gregor71395fa2009-11-04 00:56:37 +00002458 // Note that this is a conversion-function-id.
Fangrui Song6907ce22018-07-30 19:24:48 +00002459 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
Douglas Gregor71395fa2009-11-04 00:56:37 +00002460 D.getSourceRange().getEnd());
Fangrui Song6907ce22018-07-30 19:24:48 +00002461 return false;
Douglas Gregor71395fa2009-11-04 00:56:37 +00002462}
2463
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002464/// Parse a C++ unqualified-id (or a C identifier), which describes the
Douglas Gregor71395fa2009-11-04 00:56:37 +00002465/// name of an entity.
2466///
2467/// \code
2468/// unqualified-id: [C++ expr.prim.general]
2469/// identifier
2470/// operator-function-id
2471/// conversion-function-id
2472/// [C++0x] literal-operator-id [TODO]
2473/// ~ class-name
2474/// template-id
2475///
2476/// \endcode
2477///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002478/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor71395fa2009-11-04 00:56:37 +00002479/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2480///
Fangrui Song6907ce22018-07-30 19:24:48 +00002481/// \param EnteringContext whether we are entering the scope of the
Douglas Gregor71395fa2009-11-04 00:56:37 +00002482/// nested-name-specifier.
2483///
Douglas Gregor7861a802009-11-03 01:35:08 +00002484/// \param AllowDestructorName whether we allow parsing of a destructor name.
2485///
2486/// \param AllowConstructorName whether we allow parsing a constructor name.
2487///
Richard Smith35845152017-02-07 01:37:30 +00002488/// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2489///
Douglas Gregor127ea592009-11-03 21:24:04 +00002490/// \param ObjectType if this unqualified-id occurs within a member access
2491/// expression, the type of the base object whose member is being accessed.
2492///
Douglas Gregor7861a802009-11-03 01:35:08 +00002493/// \param Result on a successful parse, contains the parsed unqualified-id.
2494///
2495/// \returns true if parsing fails, false otherwise.
2496bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2497 bool AllowDestructorName,
2498 bool AllowConstructorName,
Richard Smith35845152017-02-07 01:37:30 +00002499 bool AllowDeductionGuide,
John McCallba7bf592010-08-24 05:47:05 +00002500 ParsedType ObjectType,
Richard Smithc08b6932018-04-27 02:00:13 +00002501 SourceLocation *TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002502 UnqualifiedId &Result) {
Richard Smithc08b6932018-04-27 02:00:13 +00002503 if (TemplateKWLoc)
2504 *TemplateKWLoc = SourceLocation();
Douglas Gregorb22ee882010-05-05 05:58:24 +00002505
2506 // Handle 'A::template B'. This is for template-ids which have not
2507 // already been annotated by ParseOptionalCXXScopeSpecifier().
2508 bool TemplateSpecified = false;
Richard Smithc08b6932018-04-27 02:00:13 +00002509 if (Tok.is(tok::kw_template)) {
2510 if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2511 TemplateSpecified = true;
2512 *TemplateKWLoc = ConsumeToken();
2513 } else {
2514 SourceLocation TemplateLoc = ConsumeToken();
2515 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2516 << FixItHint::CreateRemoval(TemplateLoc);
2517 }
Douglas Gregorb22ee882010-05-05 05:58:24 +00002518 }
2519
Douglas Gregor7861a802009-11-03 01:35:08 +00002520 // unqualified-id:
2521 // identifier
2522 // template-id (when it hasn't already been annotated)
2523 if (Tok.is(tok::identifier)) {
2524 // Consume the identifier.
2525 IdentifierInfo *Id = Tok.getIdentifierInfo();
2526 SourceLocation IdLoc = ConsumeToken();
2527
David Blaikiebbafb8a2012-03-11 07:00:24 +00002528 if (!getLangOpts().CPlusPlus) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002529 // If we're not in C++, only identifiers matter. Record the
2530 // identifier and return.
2531 Result.setIdentifier(Id, IdLoc);
2532 return false;
2533 }
2534
Richard Smith35845152017-02-07 01:37:30 +00002535 ParsedTemplateTy TemplateName;
Fangrui Song6907ce22018-07-30 19:24:48 +00002536 if (AllowConstructorName &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002537 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002538 // We have parsed a constructor name.
Richard Smith69bc9aa2018-06-22 19:50:19 +00002539 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2540 EnteringContext);
Richard Smith715ee072018-06-20 21:58:20 +00002541 if (!Ty)
2542 return true;
Abramo Bagnara4244b432012-01-27 08:46:19 +00002543 Result.setConstructorName(Ty, IdLoc, IdLoc);
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002544 } else if (getLangOpts().CPlusPlus17 &&
Richard Smith35845152017-02-07 01:37:30 +00002545 AllowDeductionGuide && SS.isEmpty() &&
2546 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2547 &TemplateName)) {
2548 // We have parsed a template-name naming a deduction guide.
2549 Result.setDeductionGuideName(TemplateName, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002550 } else {
2551 // We have parsed an identifier.
Fangrui Song6907ce22018-07-30 19:24:48 +00002552 Result.setIdentifier(Id, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002553 }
2554
2555 // If the next token is a '<', we may have a template.
Richard Smithc08b6932018-04-27 02:00:13 +00002556 TemplateTy Template;
2557 if (Tok.is(tok::less))
2558 return ParseUnqualifiedIdTemplateId(
2559 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2560 EnteringContext, ObjectType, Result, TemplateSpecified);
2561 else if (TemplateSpecified &&
2562 Actions.ActOnDependentTemplateName(
2563 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2564 EnteringContext, Template,
2565 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2566 return true;
2567
Douglas Gregor7861a802009-11-03 01:35:08 +00002568 return false;
2569 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002570
Douglas Gregor7861a802009-11-03 01:35:08 +00002571 // unqualified-id:
2572 // template-id (already parsed and annotated)
2573 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00002574 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002575
Fangrui Song6907ce22018-07-30 19:24:48 +00002576 // If the template-name names the current class, then this is a constructor
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002577 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002578 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002579 if (SS.isSet()) {
2580 // C++ [class.qual]p2 specifies that a qualified template-name
2581 // is taken as the constructor name where a constructor can be
2582 // declared. Thus, the template arguments are extraneous, so
2583 // complain about them and remove them entirely.
Fangrui Song6907ce22018-07-30 19:24:48 +00002584 Diag(TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002585 diag::err_out_of_line_constructor_template_id)
2586 << TemplateId->Name
Douglas Gregora771f462010-03-31 17:46:05 +00002587 << FixItHint::CreateRemoval(
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002588 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Richard Smith715ee072018-06-20 21:58:20 +00002589 ParsedType Ty = Actions.getConstructorName(
Richard Smith69bc9aa2018-06-22 19:50:19 +00002590 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2591 EnteringContext);
Richard Smith715ee072018-06-20 21:58:20 +00002592 if (!Ty)
2593 return true;
Abramo Bagnara4244b432012-01-27 08:46:19 +00002594 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002595 TemplateId->RAngleLoc);
Richard Smithaf3b3252017-05-18 19:21:48 +00002596 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002597 return false;
2598 }
2599
2600 Result.setConstructorTemplateId(TemplateId);
Richard Smithaf3b3252017-05-18 19:21:48 +00002601 ConsumeAnnotationToken();
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002602 return false;
2603 }
2604
Douglas Gregor7861a802009-11-03 01:35:08 +00002605 // We have already parsed a template-id; consume the annotation token as
2606 // our unqualified-id.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002607 Result.setTemplateId(TemplateId);
Richard Smithc08b6932018-04-27 02:00:13 +00002608 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2609 if (TemplateLoc.isValid()) {
2610 if (TemplateKWLoc && (ObjectType || SS.isSet()))
2611 *TemplateKWLoc = TemplateLoc;
2612 else
2613 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2614 << FixItHint::CreateRemoval(TemplateLoc);
2615 }
Richard Smithaf3b3252017-05-18 19:21:48 +00002616 ConsumeAnnotationToken();
Douglas Gregor7861a802009-11-03 01:35:08 +00002617 return false;
2618 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002619
Douglas Gregor7861a802009-11-03 01:35:08 +00002620 // unqualified-id:
2621 // operator-function-id
2622 // conversion-function-id
2623 if (Tok.is(tok::kw_operator)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00002624 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor7861a802009-11-03 01:35:08 +00002625 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00002626
Alexis Hunted0530f2009-11-28 08:58:14 +00002627 // If we have an operator-function-id or a literal-operator-id and the next
2628 // token is a '<', we may have a
Fangrui Song6907ce22018-07-30 19:24:48 +00002629 //
Douglas Gregor71395fa2009-11-04 00:56:37 +00002630 // template-id:
2631 // operator-function-id < template-argument-list[opt] >
Richard Smithc08b6932018-04-27 02:00:13 +00002632 TemplateTy Template;
Faisal Vali2ab8c152017-12-30 04:15:27 +00002633 if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2634 Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
Richard Smithc08b6932018-04-27 02:00:13 +00002635 Tok.is(tok::less))
2636 return ParseUnqualifiedIdTemplateId(
2637 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2638 SourceLocation(), EnteringContext, ObjectType, Result,
2639 TemplateSpecified);
2640 else if (TemplateSpecified &&
2641 Actions.ActOnDependentTemplateName(
2642 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2643 EnteringContext, Template,
2644 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2645 return true;
Craig Topper161e4db2014-05-21 06:02:52 +00002646
Douglas Gregor7861a802009-11-03 01:35:08 +00002647 return false;
2648 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002649
2650 if (getLangOpts().CPlusPlus &&
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002651 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002652 // C++ [expr.unary.op]p10:
Fangrui Song6907ce22018-07-30 19:24:48 +00002653 // There is an ambiguity in the unary-expression ~X(), where X is a
2654 // class-name. The ambiguity is resolved in favor of treating ~ as a
Douglas Gregor7861a802009-11-03 01:35:08 +00002655 // unary complement rather than treating ~X as referring to a destructor.
Fangrui Song6907ce22018-07-30 19:24:48 +00002656
Douglas Gregor7861a802009-11-03 01:35:08 +00002657 // Parse the '~'.
2658 SourceLocation TildeLoc = ConsumeToken();
David Blaikieecd8a942011-12-08 16:13:53 +00002659
2660 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2661 DeclSpec DS(AttrFactory);
2662 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Richard Smithef2cd8f2017-02-08 20:39:08 +00002663 if (ParsedType Type =
2664 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
David Blaikieecd8a942011-12-08 16:13:53 +00002665 Result.setDestructorName(TildeLoc, Type, EndLoc);
2666 return false;
2667 }
2668 return true;
2669 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002670
Douglas Gregor7861a802009-11-03 01:35:08 +00002671 // Parse the class-name.
2672 if (Tok.isNot(tok::identifier)) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002673 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00002674 return true;
2675 }
2676
Richard Smithefa6f732014-09-06 02:06:12 +00002677 // If the user wrote ~T::T, correct it to T::~T.
Richard Smith64e033f2015-01-15 00:48:52 +00002678 DeclaratorScopeObj DeclScopeObj(*this, SS);
Nico Weber10d02b52015-02-02 04:18:38 +00002679 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
Nico Weberf9e37be2015-01-30 16:53:11 +00002680 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2681 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2682 // it will confuse this recovery logic.
2683 ColonProtectionRAIIObject ColonRAII(*this, false);
2684
Richard Smithefa6f732014-09-06 02:06:12 +00002685 if (SS.isSet()) {
2686 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2687 SS.clear();
2688 }
2689 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2690 return true;
Nico Weber7f8ec522015-02-02 05:33:50 +00002691 if (SS.isNotEmpty())
David Blaikieefdccaa2016-01-15 23:43:34 +00002692 ObjectType = nullptr;
Nico Weberd0045862015-01-30 04:05:15 +00002693 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
Benjamin Kramer3012e592015-03-29 14:35:39 +00002694 !SS.isSet()) {
Richard Smithefa6f732014-09-06 02:06:12 +00002695 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2696 return true;
2697 }
2698
2699 // Recover as if the tilde had been written before the identifier.
2700 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2701 << FixItHint::CreateRemoval(TildeLoc)
2702 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
Richard Smith64e033f2015-01-15 00:48:52 +00002703
2704 // Temporarily enter the scope for the rest of this function.
2705 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2706 DeclScopeObj.EnterDeclaratorScope();
Richard Smithefa6f732014-09-06 02:06:12 +00002707 }
2708
Douglas Gregor7861a802009-11-03 01:35:08 +00002709 // Parse the class-name (or template-name in a simple-template-id).
2710 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2711 SourceLocation ClassNameLoc = ConsumeToken();
Richard Smithefa6f732014-09-06 02:06:12 +00002712
Richard Smithc08b6932018-04-27 02:00:13 +00002713 if (Tok.is(tok::less)) {
David Blaikieefdccaa2016-01-15 23:43:34 +00002714 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
Richard Smithc08b6932018-04-27 02:00:13 +00002715 return ParseUnqualifiedIdTemplateId(
2716 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
2717 ClassNameLoc, EnteringContext, ObjectType, Result, TemplateSpecified);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002718 }
Richard Smithefa6f732014-09-06 02:06:12 +00002719
Douglas Gregor7861a802009-11-03 01:35:08 +00002720 // Note that this is a destructor name.
Fangrui Song6907ce22018-07-30 19:24:48 +00002721 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
John McCallba7bf592010-08-24 05:47:05 +00002722 ClassNameLoc, getCurScope(),
2723 SS, ObjectType,
2724 EnteringContext);
Douglas Gregorfe17d252010-02-16 19:09:40 +00002725 if (!Ty)
Douglas Gregor7861a802009-11-03 01:35:08 +00002726 return true;
Douglas Gregorfe17d252010-02-16 19:09:40 +00002727
Douglas Gregor7861a802009-11-03 01:35:08 +00002728 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002729 return false;
2730 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002731
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002732 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002733 << getLangOpts().CPlusPlus;
Douglas Gregor7861a802009-11-03 01:35:08 +00002734 return true;
2735}
2736
Sebastian Redlbd150f42008-11-21 19:14:01 +00002737/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2738/// memory in a typesafe manner and call constructors.
Mike Stump11289f42009-09-09 15:08:12 +00002739///
Chris Lattner109faf22009-01-04 21:25:24 +00002740/// This method is called to parse the new expression after the optional :: has
2741/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2742/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002743///
2744/// new-expression:
2745/// '::'[opt] 'new' new-placement[opt] new-type-id
2746/// new-initializer[opt]
2747/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2748/// new-initializer[opt]
2749///
2750/// new-placement:
2751/// '(' expression-list ')'
2752///
Sebastian Redl351bb782008-12-02 14:43:59 +00002753/// new-type-id:
2754/// type-specifier-seq new-declarator[opt]
Douglas Gregora3a020a2011-04-15 19:40:02 +00002755/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redl351bb782008-12-02 14:43:59 +00002756///
2757/// new-declarator:
2758/// ptr-operator new-declarator[opt]
2759/// direct-new-declarator
2760///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002761/// new-initializer:
2762/// '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00002763/// [C++0x] braced-init-list
Sebastian Redlbd150f42008-11-21 19:14:01 +00002764///
John McCalldadc5752010-08-24 06:29:42 +00002765ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002766Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2767 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2768 ConsumeToken(); // Consume 'new'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002769
2770 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2771 // second form of new-expression. It can't be a new-type-id.
2772
Benjamin Kramerf0623432012-08-23 22:51:59 +00002773 ExprVector PlacementArgs;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002774 SourceLocation PlacementLParen, PlacementRParen;
2775
Douglas Gregorf2753b32010-07-13 15:54:32 +00002776 SourceRange TypeIdParens;
John McCall084e83d2011-03-24 11:26:52 +00002777 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00002778 Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNewContext);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002779 if (Tok.is(tok::l_paren)) {
2780 // If it turns out to be a placement, we change the type location.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002781 BalancedDelimiterTracker T(*this, tok::l_paren);
2782 T.consumeOpen();
2783 PlacementLParen = T.getOpenLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002784 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002785 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002786 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002787 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002788
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002789 T.consumeClose();
2790 PlacementRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002791 if (PlacementRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002792 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002793 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002794 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002795
Sebastian Redl351bb782008-12-02 14:43:59 +00002796 if (PlacementArgs.empty()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002797 // Reset the placement locations. There was no placement.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002798 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002799 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002800 } else {
2801 // We still need the type.
2802 if (Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002803 BalancedDelimiterTracker T(*this, tok::l_paren);
2804 T.consumeOpen();
Douglas Gregora3a020a2011-04-15 19:40:02 +00002805 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002806 ParseSpecifierQualifierList(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002807 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002808 ParseDeclarator(DeclaratorInfo);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002809 T.consumeClose();
2810 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002811 } else {
Douglas Gregora3a020a2011-04-15 19:40:02 +00002812 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002813 if (ParseCXXTypeSpecifierSeq(DS))
2814 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002815 else {
2816 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002817 ParseDeclaratorInternal(DeclaratorInfo,
2818 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002819 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002820 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002821 }
2822 } else {
Sebastian Redl351bb782008-12-02 14:43:59 +00002823 // A new-type-id is a simplified type-id, where essentially the
2824 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregora3a020a2011-04-15 19:40:02 +00002825 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002826 if (ParseCXXTypeSpecifierSeq(DS))
2827 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002828 else {
2829 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002830 ParseDeclaratorInternal(DeclaratorInfo,
2831 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002832 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002833 }
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002834 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002835 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002836 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002837 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002838
Sebastian Redl6047f072012-02-16 12:22:20 +00002839 ExprResult Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002840
2841 if (Tok.is(tok::l_paren)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00002842 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002843 ExprVector ConstructorArgs;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002844 BalancedDelimiterTracker T(*this, tok::l_paren);
2845 T.consumeOpen();
2846 ConstructorLParen = T.getOpenLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002847 if (Tok.isNot(tok::r_paren)) {
2848 CommaLocsTy CommaLocs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002849 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002850 ParsedType TypeRep =
2851 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Ilya Biryukov832c4af2018-09-07 14:04:39 +00002852 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002853 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
Ilya Biryukov2fab2352018-08-30 13:08:03 +00002854 DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002855 CalledSignatureHelp = true;
Ilya Biryukov832c4af2018-09-07 14:04:39 +00002856 Actions.CodeCompleteExpression(getCurScope(), PreferredType);
Kadir Cetinkayaa32d2532018-09-10 13:46:28 +00002857 })) {
2858 if (PP.isCodeCompletionReached() && !CalledSignatureHelp) {
2859 ParsedType TypeRep =
2860 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
2861 Actions.ProduceConstructorSignatureHelp(
2862 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
2863 DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
2864 CalledSignatureHelp = true;
2865 }
Alexey Bataevee6507d2013-11-18 08:17:37 +00002866 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002867 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002868 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002869 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002870 T.consumeClose();
2871 ConstructorRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002872 if (ConstructorRParen.isInvalid()) {
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 Redl6047f072012-02-16 12:22:20 +00002876 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2877 ConstructorRParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002878 ConstructorArgs);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002879 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002880 Diag(Tok.getLocation(),
2881 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl6047f072012-02-16 12:22:20 +00002882 Initializer = ParseBraceInitializer();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002883 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002884 if (Initializer.isInvalid())
2885 return Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002886
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002887 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002888 PlacementArgs, PlacementRParen,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002889 TypeIdParens, DeclaratorInfo, Initializer.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002890}
2891
Sebastian Redlbd150f42008-11-21 19:14:01 +00002892/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2893/// passed to ParseDeclaratorInternal.
2894///
2895/// direct-new-declarator:
2896/// '[' expression ']'
2897/// direct-new-declarator '[' constant-expression ']'
2898///
Chris Lattner109faf22009-01-04 21:25:24 +00002899void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002900 // Parse the array dimensions.
2901 bool first = true;
2902 while (Tok.is(tok::l_square)) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002903 // An array-size expression can't start with a lambda.
2904 if (CheckProhibitedCXX11Attribute())
2905 continue;
2906
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002907 BalancedDelimiterTracker T(*this, tok::l_square);
2908 T.consumeOpen();
2909
John McCalldadc5752010-08-24 06:29:42 +00002910 ExprResult Size(first ? ParseExpression()
Sebastian Redl59b5e512008-12-11 21:36:32 +00002911 : ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002912 if (Size.isInvalid()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002913 // Recover
Alexey Bataevee6507d2013-11-18 08:17:37 +00002914 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002915 return;
2916 }
2917 first = false;
2918
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002919 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00002920
Bill Wendling44426052012-12-20 19:22:21 +00002921 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002922 ParsedAttributes Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002923 MaybeParseCXX11Attributes(Attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002924
John McCall084e83d2011-03-24 11:26:52 +00002925 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall53fa7142010-12-24 02:08:15 +00002926 /*static=*/false, /*star=*/false,
Erich Keanec480f302018-07-12 21:09:05 +00002927 Size.get(), T.getOpenLocation(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002928 T.getCloseLocation()),
Erich Keanec480f302018-07-12 21:09:05 +00002929 std::move(Attrs), T.getCloseLocation());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002930
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002931 if (T.getCloseLocation().isInvalid())
Sebastian Redlbd150f42008-11-21 19:14:01 +00002932 return;
2933 }
2934}
2935
2936/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2937/// This ambiguity appears in the syntax of the C++ new operator.
2938///
2939/// new-expression:
2940/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2941/// new-initializer[opt]
2942///
2943/// new-placement:
2944/// '(' expression-list ')'
2945///
John McCall37ad5512010-08-23 06:44:23 +00002946bool Parser::ParseExpressionListOrTypeId(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002947 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner109faf22009-01-04 21:25:24 +00002948 Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002949 // The '(' was already consumed.
2950 if (isTypeIdInParens()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00002951 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002952 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002953 ParseDeclarator(D);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002954 return D.isInvalidType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002955 }
2956
2957 // It's not a type, it has to be an expression list.
2958 // Discard the comma locations - ActOnCXXNew has enough parameters.
2959 CommaLocsTy CommaLocs;
2960 return ParseExpressionList(PlacementArgs, CommaLocs);
2961}
2962
2963/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2964/// to free memory allocated by new.
2965///
Chris Lattner109faf22009-01-04 21:25:24 +00002966/// This method is called to parse the 'delete' expression after the optional
2967/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2968/// and "Start" is its location. Otherwise, "Start" is the location of the
2969/// 'delete' token.
2970///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002971/// delete-expression:
2972/// '::'[opt] 'delete' cast-expression
2973/// '::'[opt] 'delete' '[' ']' cast-expression
John McCalldadc5752010-08-24 06:29:42 +00002974ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002975Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2976 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2977 ConsumeToken(); // Consume 'delete'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002978
2979 // Array delete?
2980 bool ArrayDelete = false;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002981 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith10c60722012-08-09 19:01:51 +00002982 // C++11 [expr.delete]p1:
2983 // Whenever the delete keyword is followed by empty square brackets, it
2984 // shall be interpreted as [array delete].
2985 // [Footnote: A lambda expression with a lambda-introducer that consists
2986 // of empty square brackets can follow the delete keyword if
2987 // the lambda expression is enclosed in parentheses.]
2988 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2989 // lambda-introducer.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002990 ArrayDelete = true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002991 BalancedDelimiterTracker T(*this, tok::l_square);
2992
2993 T.consumeOpen();
2994 T.consumeClose();
2995 if (T.getCloseLocation().isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00002996 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002997 }
2998
John McCalldadc5752010-08-24 06:29:42 +00002999 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00003000 if (Operand.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003001 return Operand;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003002
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003003 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00003004}
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003005
Douglas Gregor29c42f22012-02-24 07:38:34 +00003006static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
3007 switch (kind) {
3008 default: llvm_unreachable("Not a known type trait");
Alp Toker95e7ff22014-01-01 05:57:51 +00003009#define TYPE_TRAIT_1(Spelling, Name, Key) \
3010case tok::kw_ ## Spelling: return UTT_ ## Name;
Alp Tokercbb90342013-12-13 20:49:58 +00003011#define TYPE_TRAIT_2(Spelling, Name, Key) \
3012case tok::kw_ ## Spelling: return BTT_ ## Name;
3013#include "clang/Basic/TokenKinds.def"
Alp Toker40f9b1c2013-12-12 21:23:03 +00003014#define TYPE_TRAIT_N(Spelling, Name, Key) \
3015 case tok::kw_ ## Spelling: return TT_ ## Name;
3016#include "clang/Basic/TokenKinds.def"
Douglas Gregor29c42f22012-02-24 07:38:34 +00003017 }
3018}
3019
John Wiegley6242b6a2011-04-28 00:16:57 +00003020static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
3021 switch(kind) {
3022 default: llvm_unreachable("Not a known binary type trait");
3023 case tok::kw___array_rank: return ATT_ArrayRank;
3024 case tok::kw___array_extent: return ATT_ArrayExtent;
3025 }
3026}
3027
John Wiegleyf9f65842011-04-25 06:54:41 +00003028static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
3029 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003030 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegleyf9f65842011-04-25 06:54:41 +00003031 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
3032 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
3033 }
3034}
3035
Alp Toker40f9b1c2013-12-12 21:23:03 +00003036static unsigned TypeTraitArity(tok::TokenKind kind) {
3037 switch (kind) {
3038 default: llvm_unreachable("Not a known type trait");
3039#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
3040#include "clang/Basic/TokenKinds.def"
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003041 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003042}
3043
Fangrui Song6907ce22018-07-30 19:24:48 +00003044/// Parse the built-in type-trait pseudo-functions that allow
Douglas Gregor29c42f22012-02-24 07:38:34 +00003045/// implementation of the TR1/C++11 type traits templates.
3046///
3047/// primary-expression:
Alp Toker40f9b1c2013-12-12 21:23:03 +00003048/// unary-type-trait '(' type-id ')'
3049/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor29c42f22012-02-24 07:38:34 +00003050/// type-trait '(' type-id-seq ')'
3051///
3052/// type-id-seq:
3053/// type-id ...[opt] type-id-seq[opt]
3054///
3055ExprResult Parser::ParseTypeTrait() {
Alp Toker40f9b1c2013-12-12 21:23:03 +00003056 tok::TokenKind Kind = Tok.getKind();
3057 unsigned Arity = TypeTraitArity(Kind);
3058
Douglas Gregor29c42f22012-02-24 07:38:34 +00003059 SourceLocation Loc = ConsumeToken();
Fangrui Song6907ce22018-07-30 19:24:48 +00003060
Douglas Gregor29c42f22012-02-24 07:38:34 +00003061 BalancedDelimiterTracker Parens(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003062 if (Parens.expectAndConsume())
Douglas Gregor29c42f22012-02-24 07:38:34 +00003063 return ExprError();
3064
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003065 SmallVector<ParsedType, 2> Args;
Douglas Gregor29c42f22012-02-24 07:38:34 +00003066 do {
3067 // Parse the next type.
3068 TypeResult Ty = ParseTypeName();
3069 if (Ty.isInvalid()) {
3070 Parens.skipToEnd();
3071 return ExprError();
3072 }
3073
3074 // Parse the ellipsis, if present.
3075 if (Tok.is(tok::ellipsis)) {
3076 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3077 if (Ty.isInvalid()) {
3078 Parens.skipToEnd();
3079 return ExprError();
3080 }
3081 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003082
Douglas Gregor29c42f22012-02-24 07:38:34 +00003083 // Add this type to the list of arguments.
3084 Args.push_back(Ty.get());
Alp Tokera3ebe6e2013-12-17 14:12:37 +00003085 } while (TryConsumeToken(tok::comma));
3086
Douglas Gregor29c42f22012-02-24 07:38:34 +00003087 if (Parens.consumeClose())
3088 return ExprError();
Alp Toker40f9b1c2013-12-12 21:23:03 +00003089
3090 SourceLocation EndLoc = Parens.getCloseLocation();
3091
3092 if (Arity && Args.size() != Arity) {
3093 Diag(EndLoc, diag::err_type_trait_arity)
3094 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3095 return ExprError();
3096 }
3097
3098 if (!Arity && Args.empty()) {
3099 Diag(EndLoc, diag::err_type_trait_arity)
3100 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3101 return ExprError();
3102 }
3103
Alp Toker88f64e62013-12-13 21:19:30 +00003104 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
Douglas Gregor29c42f22012-02-24 07:38:34 +00003105}
3106
John Wiegley6242b6a2011-04-28 00:16:57 +00003107/// ParseArrayTypeTrait - Parse the built-in array type-trait
3108/// pseudo-functions.
3109///
3110/// primary-expression:
3111/// [Embarcadero] '__array_rank' '(' type-id ')'
3112/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3113///
3114ExprResult Parser::ParseArrayTypeTrait() {
3115 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3116 SourceLocation Loc = ConsumeToken();
3117
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003118 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003119 if (T.expectAndConsume())
John Wiegley6242b6a2011-04-28 00:16:57 +00003120 return ExprError();
3121
3122 TypeResult Ty = ParseTypeName();
3123 if (Ty.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003124 SkipUntil(tok::comma, StopAtSemi);
3125 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003126 return ExprError();
3127 }
3128
3129 switch (ATT) {
3130 case ATT_ArrayRank: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003131 T.consumeClose();
Craig Topper161e4db2014-05-21 06:02:52 +00003132 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003133 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003134 }
3135 case ATT_ArrayExtent: {
Alp Toker383d2c42014-01-01 03:08:43 +00003136 if (ExpectAndConsume(tok::comma)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003137 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003138 return ExprError();
3139 }
3140
3141 ExprResult DimExpr = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003142 T.consumeClose();
John Wiegley6242b6a2011-04-28 00:16:57 +00003143
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003144 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3145 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003146 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003147 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003148 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley6242b6a2011-04-28 00:16:57 +00003149}
3150
John Wiegleyf9f65842011-04-25 06:54:41 +00003151/// ParseExpressionTrait - Parse built-in expression-trait
3152/// pseudo-functions like __is_lvalue_expr( xxx ).
3153///
3154/// primary-expression:
3155/// [Embarcadero] expression-trait '(' expression ')'
3156///
3157ExprResult Parser::ParseExpressionTrait() {
3158 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3159 SourceLocation Loc = ConsumeToken();
3160
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003161 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003162 if (T.expectAndConsume())
John Wiegleyf9f65842011-04-25 06:54:41 +00003163 return ExprError();
3164
3165 ExprResult Expr = ParseExpression();
3166
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003167 T.consumeClose();
John Wiegleyf9f65842011-04-25 06:54:41 +00003168
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003169 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3170 T.getCloseLocation());
John Wiegleyf9f65842011-04-25 06:54:41 +00003171}
3172
3173
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003174/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3175/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3176/// based on the context past the parens.
John McCalldadc5752010-08-24 06:29:42 +00003177ExprResult
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003178Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallba7bf592010-08-24 05:47:05 +00003179 ParsedType &CastTy,
Richard Smith87e11a42014-05-15 02:43:47 +00003180 BalancedDelimiterTracker &Tracker,
3181 ColonProtectionRAIIObject &ColonProt) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003182 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003183 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3184 assert(isTypeIdInParens() && "Not a type-id!");
3185
John McCalldadc5752010-08-24 06:29:42 +00003186 ExprResult Result(true);
David Blaikieefdccaa2016-01-15 23:43:34 +00003187 CastTy = nullptr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003188
3189 // We need to disambiguate a very ugly part of the C++ syntax:
3190 //
3191 // (T())x; - type-id
3192 // (T())*x; - type-id
3193 // (T())/x; - expression
3194 // (T()); - expression
3195 //
3196 // The bad news is that we cannot use the specialized tentative parser, since
3197 // it can only verify that the thing inside the parens can be parsed as
3198 // type-id, it is not useful for determining the context past the parens.
3199 //
3200 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidis24ad6922009-05-22 15:12:46 +00003201 // making any unnecessary Action calls.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003202 //
3203 // It uses a scheme similar to parsing inline methods. The parenthesized
3204 // tokens are cached, the context that follows is determined (possibly by
3205 // parsing a cast-expression), and then we re-introduce the cached tokens
3206 // into the token stream and parse them appropriately.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003207
Mike Stump11289f42009-09-09 15:08:12 +00003208 ParenParseOption ParseAs;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003209 CachedTokens Toks;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003210
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003211 // Store the tokens of the parentheses. We will parse them after we determine
3212 // the context that follows them.
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +00003213 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003214 // We didn't find the ')' we expected.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003215 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003216 return ExprError();
3217 }
3218
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003219 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003220 ParseAs = CompoundLiteral;
3221 } else {
3222 bool NotCastExpr;
Eli Friedmancf7530f2009-05-25 19:41:42 +00003223 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3224 NotCastExpr = true;
3225 } else {
3226 // Try parsing the cast-expression that may follow.
3227 // If it is not a cast-expression, NotCastExpr will be true and no token
3228 // will be consumed.
Richard Smith87e11a42014-05-15 02:43:47 +00003229 ColonProt.restore();
Eli Friedmancf7530f2009-05-25 19:41:42 +00003230 Result = ParseCastExpression(false/*isUnaryExpression*/,
3231 false/*isAddressofOperand*/,
John McCallba7bf592010-08-24 05:47:05 +00003232 NotCastExpr,
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003233 // type-id has priority.
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00003234 IsTypeCast);
Eli Friedmancf7530f2009-05-25 19:41:42 +00003235 }
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003236
3237 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3238 // an expression.
3239 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003240 }
3241
Alexey Bataev703a93c2016-02-04 04:22:09 +00003242 // Create a fake EOF to mark end of Toks buffer.
3243 Token AttrEnd;
3244 AttrEnd.startToken();
3245 AttrEnd.setKind(tok::eof);
3246 AttrEnd.setLocation(Tok.getLocation());
3247 AttrEnd.setEofData(Toks.data());
3248 Toks.push_back(AttrEnd);
3249
Mike Stump11289f42009-09-09 15:08:12 +00003250 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003251 Toks.push_back(Tok);
3252 // Re-enter the stored parenthesized tokens into the token stream, so we may
3253 // parse them now.
David Blaikie2eabcc92016-02-09 18:52:09 +00003254 PP.EnterTokenStream(Toks, true /*DisableMacroExpansion*/);
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003255 // Drop the current token and bring the first cached one. It's the same token
3256 // as when we entered this function.
3257 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003258
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003259 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003260 // Parse the type declarator.
3261 DeclSpec DS(AttrFactory);
Faisal Vali421b2d12017-12-29 05:41:00 +00003262 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
Richard Smith87e11a42014-05-15 02:43:47 +00003263 {
3264 ColonProtectionRAIIObject InnerColonProtection(*this);
3265 ParseSpecifierQualifierList(DS);
3266 ParseDeclarator(DeclaratorInfo);
3267 }
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003268
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003269 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003270 Tracker.consumeClose();
Richard Smith87e11a42014-05-15 02:43:47 +00003271 ColonProt.restore();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003272
Alexey Bataev703a93c2016-02-04 04:22:09 +00003273 // Consume EOF marker for Toks buffer.
3274 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3275 ConsumeAnyToken();
3276
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003277 if (ParseAs == CompoundLiteral) {
3278 ExprType = CompoundLiteral;
Richard Smithaba8b362014-05-15 02:51:15 +00003279 if (DeclaratorInfo.isInvalidType())
3280 return ExprError();
3281
3282 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Richard Smith87e11a42014-05-15 02:43:47 +00003283 return ParseCompoundLiteralExpression(Ty.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003284 Tracker.getOpenLocation(),
3285 Tracker.getCloseLocation());
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003286 }
Mike Stump11289f42009-09-09 15:08:12 +00003287
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003288 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3289 assert(ParseAs == CastExpr);
3290
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003291 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003292 return ExprError();
3293
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003294 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003295 if (!Result.isInvalid())
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003296 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3297 DeclaratorInfo, CastTy,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003298 Tracker.getCloseLocation(), Result.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003299 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003300 }
Mike Stump11289f42009-09-09 15:08:12 +00003301
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003302 // Not a compound literal, and not followed by a cast-expression.
3303 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003304
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003305 ExprType = SimpleExpr;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003306 Result = ParseExpression();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003307 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Fangrui Song6907ce22018-07-30 19:24:48 +00003308 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003309 Tok.getLocation(), Result.get());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003310
3311 // Match the ')'.
3312 if (Result.isInvalid()) {
Alexey Bataev703a93c2016-02-04 04:22:09 +00003313 while (Tok.isNot(tok::eof))
3314 ConsumeAnyToken();
3315 assert(Tok.getEofData() == AttrEnd.getEofData());
3316 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003317 return ExprError();
3318 }
Mike Stump11289f42009-09-09 15:08:12 +00003319
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003320 Tracker.consumeClose();
Alexey Bataev703a93c2016-02-04 04:22:09 +00003321 // Consume EOF marker for Toks buffer.
3322 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3323 ConsumeAnyToken();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003324 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003325}