Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Parse/ParseExprCXX.cpp
Warning:line 2097, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ParseExprCXX.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Parse -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Parse -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Parse/ParseExprCXX.cpp
1//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expression parsing implementation for C++.
10//
11//===----------------------------------------------------------------------===//
12#include "clang/AST/ASTContext.h"
13#include "clang/AST/Decl.h"
14#include "clang/AST/DeclTemplate.h"
15#include "clang/AST/ExprCXX.h"
16#include "clang/Basic/PrettyStackTrace.h"
17#include "clang/Basic/TokenKinds.h"
18#include "clang/Lex/LiteralSupport.h"
19#include "clang/Parse/ParseDiagnostic.h"
20#include "clang/Parse/Parser.h"
21#include "clang/Parse/RAIIObjectsForParser.h"
22#include "clang/Sema/DeclSpec.h"
23#include "clang/Sema/ParsedTemplate.h"
24#include "clang/Sema/Scope.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/ErrorHandling.h"
27#include <numeric>
28
29using namespace clang;
30
31static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
32 switch (Kind) {
33 // template name
34 case tok::unknown: return 0;
35 // casts
36 case tok::kw_addrspace_cast: return 1;
37 case tok::kw_const_cast: return 2;
38 case tok::kw_dynamic_cast: return 3;
39 case tok::kw_reinterpret_cast: return 4;
40 case tok::kw_static_cast: return 5;
41 default:
42 llvm_unreachable("Unknown type for digraph error message.")::llvm::llvm_unreachable_internal("Unknown type for digraph error message."
, "clang/lib/Parse/ParseExprCXX.cpp", 42)
;
43 }
44}
45
46// Are the two tokens adjacent in the same source file?
47bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
48 SourceManager &SM = PP.getSourceManager();
49 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
50 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
51 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
52}
53
54// Suggest fixit for "<::" after a cast.
55static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
56 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
57 // Pull '<:' and ':' off token stream.
58 if (!AtDigraph)
59 PP.Lex(DigraphToken);
60 PP.Lex(ColonToken);
61
62 SourceRange Range;
63 Range.setBegin(DigraphToken.getLocation());
64 Range.setEnd(ColonToken.getLocation());
65 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
66 << SelectDigraphErrorMessage(Kind)
67 << FixItHint::CreateReplacement(Range, "< ::");
68
69 // Update token information to reflect their change in token type.
70 ColonToken.setKind(tok::coloncolon);
71 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
72 ColonToken.setLength(2);
73 DigraphToken.setKind(tok::less);
74 DigraphToken.setLength(1);
75
76 // Push new tokens back to token stream.
77 PP.EnterToken(ColonToken, /*IsReinject*/ true);
78 if (!AtDigraph)
79 PP.EnterToken(DigraphToken, /*IsReinject*/ true);
80}
81
82// Check for '<::' which should be '< ::' instead of '[:' when following
83// a template name.
84void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
85 bool EnteringContext,
86 IdentifierInfo &II, CXXScopeSpec &SS) {
87 if (!Next.is(tok::l_square) || Next.getLength() != 2)
88 return;
89
90 Token SecondToken = GetLookAheadToken(2);
91 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
92 return;
93
94 TemplateTy Template;
95 UnqualifiedId TemplateName;
96 TemplateName.setIdentifier(&II, Tok.getLocation());
97 bool MemberOfUnknownSpecialization;
98 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
99 TemplateName, ObjectType, EnteringContext,
100 Template, MemberOfUnknownSpecialization))
101 return;
102
103 FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
104 /*AtDigraph*/false);
105}
106
107/// Parse global scope or nested-name-specifier if present.
108///
109/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
110/// may be preceded by '::'). Note that this routine will not parse ::new or
111/// ::delete; it will just leave them in the token stream.
112///
113/// '::'[opt] nested-name-specifier
114/// '::'
115///
116/// nested-name-specifier:
117/// type-name '::'
118/// namespace-name '::'
119/// nested-name-specifier identifier '::'
120/// nested-name-specifier 'template'[opt] simple-template-id '::'
121///
122///
123/// \param SS the scope specifier that will be set to the parsed
124/// nested-name-specifier (or empty)
125///
126/// \param ObjectType if this nested-name-specifier is being parsed following
127/// the "." or "->" of a member access expression, this parameter provides the
128/// type of the object whose members are being accessed.
129///
130/// \param ObjectHadErrors if this unqualified-id occurs within a member access
131/// expression, indicates whether the original subexpressions had any errors.
132/// When true, diagnostics for missing 'template' keyword will be supressed.
133///
134/// \param EnteringContext whether we will be entering into the context of
135/// the nested-name-specifier after parsing it.
136///
137/// \param MayBePseudoDestructor When non-NULL, points to a flag that
138/// indicates whether this nested-name-specifier may be part of a
139/// pseudo-destructor name. In this case, the flag will be set false
140/// if we don't actually end up parsing a destructor name. Moreover,
141/// if we do end up determining that we are parsing a destructor name,
142/// the last component of the nested-name-specifier is not parsed as
143/// part of the scope specifier.
144///
145/// \param IsTypename If \c true, this nested-name-specifier is known to be
146/// part of a type name. This is used to improve error recovery.
147///
148/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
149/// filled in with the leading identifier in the last component of the
150/// nested-name-specifier, if any.
151///
152/// \param OnlyNamespace If true, only considers namespaces in lookup.
153///
154///
155/// \returns true if there was an error parsing a scope specifier
156bool Parser::ParseOptionalCXXScopeSpecifier(
157 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors,
158 bool EnteringContext, bool *MayBePseudoDestructor, bool IsTypename,
159 IdentifierInfo **LastII, bool OnlyNamespace, bool InUsingDeclaration) {
160 assert(getLangOpts().CPlusPlus &&(static_cast <bool> (getLangOpts().CPlusPlus &&
"Call sites of this function should be guarded by checking for C++"
) ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Call sites of this function should be guarded by checking for C++\""
, "clang/lib/Parse/ParseExprCXX.cpp", 161, __extension__ __PRETTY_FUNCTION__
))
161 "Call sites of this function should be guarded by checking for C++")(static_cast <bool> (getLangOpts().CPlusPlus &&
"Call sites of this function should be guarded by checking for C++"
) ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Call sites of this function should be guarded by checking for C++\""
, "clang/lib/Parse/ParseExprCXX.cpp", 161, __extension__ __PRETTY_FUNCTION__
))
;
162
163 if (Tok.is(tok::annot_cxxscope)) {
164 assert(!LastII && "want last identifier but have already annotated scope")(static_cast <bool> (!LastII && "want last identifier but have already annotated scope"
) ? void (0) : __assert_fail ("!LastII && \"want last identifier but have already annotated scope\""
, "clang/lib/Parse/ParseExprCXX.cpp", 164, __extension__ __PRETTY_FUNCTION__
))
;
165 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope")(static_cast <bool> (!MayBePseudoDestructor && "unexpected annot_cxxscope"
) ? void (0) : __assert_fail ("!MayBePseudoDestructor && \"unexpected annot_cxxscope\""
, "clang/lib/Parse/ParseExprCXX.cpp", 165, __extension__ __PRETTY_FUNCTION__
))
;
166 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
167 Tok.getAnnotationRange(),
168 SS);
169 ConsumeAnnotationToken();
170 return false;
171 }
172
173 // 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
180 if (LastII)
181 *LastII = nullptr;
182
183 bool HasScopeSpecifier = false;
184
185 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;
190
191 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;
199
200 HasScopeSpecifier = true;
201 }
202 }
203
204 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
214 if (!HasScopeSpecifier &&
215 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
216 DeclSpec DS(AttrFactory);
217 SourceLocation DeclLoc = Tok.getLocation();
218 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
219
220 SourceLocation CCLoc;
221 // 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)) {
225 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
226 return false;
227 }
228
229 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
230 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
231
232 HasScopeSpecifier = true;
233 }
234
235 // Preferred type might change when parsing qualifiers, we need the original.
236 auto SavedType = PreferredType;
237 while (true) {
238 if (HasScopeSpecifier) {
239 if (Tok.is(tok::code_completion)) {
240 cutOffParsing();
241 // Code completion for a nested-name-specifier, where the code
242 // completion token follows the '::'.
243 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext,
244 InUsingDeclaration, ObjectType.get(),
245 SavedType.get(SS.getBeginLoc()));
246 // Include code completion token into the range of the scope otherwise
247 // when we try to annotate the scope tokens the dangling code completion
248 // token will cause assertion in
249 // Preprocessor::AnnotatePreviousCachedTokens.
250 SS.setEndLoc(Tok.getLocation());
251 return true;
252 }
253
254 // C++ [basic.lookup.classref]p5:
255 // If the qualified-id has the form
256 //
257 // ::class-name-or-namespace-name::...
258 //
259 // the class-name-or-namespace-name is looked up in global scope as a
260 // class-name or namespace-name.
261 //
262 // To implement this, we clear out the object type as soon as we've
263 // seen a leading '::' or part of a nested-name-specifier.
264 ObjectType = nullptr;
265 }
266
267 // nested-name-specifier:
268 // nested-name-specifier 'template'[opt] simple-template-id '::'
269
270 // Parse the optional 'template' keyword, then make sure we have
271 // 'identifier <' after it.
272 if (Tok.is(tok::kw_template)) {
273 // If we don't have a scope specifier or an object type, this isn't a
274 // nested-name-specifier, since they aren't allowed to start with
275 // 'template'.
276 if (!HasScopeSpecifier && !ObjectType)
277 break;
278
279 TentativeParsingAction TPA(*this);
280 SourceLocation TemplateKWLoc = ConsumeToken();
281
282 UnqualifiedId TemplateName;
283 if (Tok.is(tok::identifier)) {
284 // Consume the identifier.
285 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
286 ConsumeToken();
287 } else if (Tok.is(tok::kw_operator)) {
288 // We don't need to actually parse the unqualified-id in this case,
289 // because a simple-template-id cannot start with 'operator', but
290 // go ahead and parse it anyway for consistency with the case where
291 // we already annotated the template-id.
292 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
293 TemplateName)) {
294 TPA.Commit();
295 break;
296 }
297
298 if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId &&
299 TemplateName.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId) {
300 Diag(TemplateName.getSourceRange().getBegin(),
301 diag::err_id_after_template_in_nested_name_spec)
302 << TemplateName.getSourceRange();
303 TPA.Commit();
304 break;
305 }
306 } else {
307 TPA.Revert();
308 break;
309 }
310
311 // If the next token is not '<', we have a qualified-id that refers
312 // to a template name, such as T::template apply, but is not a
313 // template-id.
314 if (Tok.isNot(tok::less)) {
315 TPA.Revert();
316 break;
317 }
318
319 // Commit to parsing the template-id.
320 TPA.Commit();
321 TemplateTy Template;
322 TemplateNameKind TNK = Actions.ActOnTemplateName(
323 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
324 EnteringContext, Template, /*AllowInjectedClassName*/ true);
325 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
326 TemplateName, false))
327 return true;
328
329 continue;
330 }
331
332 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
333 // We have
334 //
335 // template-id '::'
336 //
337 // So we need to check whether the template-id is a simple-template-id of
338 // the right kind (it should name a type or be dependent), and then
339 // convert it into a type within the nested-name-specifier.
340 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
341 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
342 *MayBePseudoDestructor = true;
343 return false;
344 }
345
346 if (LastII)
347 *LastII = TemplateId->Name;
348
349 // Consume the template-id token.
350 ConsumeAnnotationToken();
351
352 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!")(static_cast <bool> (Tok.is(tok::coloncolon) &&
"NextToken() not working properly!") ? void (0) : __assert_fail
("Tok.is(tok::coloncolon) && \"NextToken() not working properly!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 352, __extension__ __PRETTY_FUNCTION__
))
;
353 SourceLocation CCLoc = ConsumeToken();
354
355 HasScopeSpecifier = true;
356
357 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
358 TemplateId->NumArgs);
359
360 if (TemplateId->isInvalid() ||
361 Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
362 SS,
363 TemplateId->TemplateKWLoc,
364 TemplateId->Template,
365 TemplateId->TemplateNameLoc,
366 TemplateId->LAngleLoc,
367 TemplateArgsPtr,
368 TemplateId->RAngleLoc,
369 CCLoc,
370 EnteringContext)) {
371 SourceLocation StartLoc
372 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
373 : TemplateId->TemplateNameLoc;
374 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
375 }
376
377 continue;
378 }
379
380 // The rest of the nested-name-specifier possibilities start with
381 // tok::identifier.
382 if (Tok.isNot(tok::identifier))
383 break;
384
385 IdentifierInfo &II = *Tok.getIdentifierInfo();
386
387 // nested-name-specifier:
388 // type-name '::'
389 // namespace-name '::'
390 // nested-name-specifier identifier '::'
391 Token Next = NextToken();
392 Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
393 ObjectType);
394
395 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
396 // and emit a fixit hint for it.
397 if (Next.is(tok::colon) && !ColonIsSacred) {
398 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
399 EnteringContext) &&
400 // If the token after the colon isn't an identifier, it's still an
401 // error, but they probably meant something else strange so don't
402 // recover like this.
403 PP.LookAhead(1).is(tok::identifier)) {
404 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
405 << FixItHint::CreateReplacement(Next.getLocation(), "::");
406 // Recover as if the user wrote '::'.
407 Next.setKind(tok::coloncolon);
408 }
409 }
410
411 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
412 // It is invalid to have :: {, consume the scope qualifier and pretend
413 // like we never saw it.
414 Token Identifier = Tok; // Stash away the identifier.
415 ConsumeToken(); // Eat the identifier, current token is now '::'.
416 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
417 << tok::identifier;
418 UnconsumeToken(Identifier); // Stick the identifier back.
419 Next = NextToken(); // Point Next at the '{' token.
420 }
421
422 if (Next.is(tok::coloncolon)) {
423 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
424 *MayBePseudoDestructor = true;
425 return false;
426 }
427
428 if (ColonIsSacred) {
429 const Token &Next2 = GetLookAheadToken(2);
430 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
431 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
432 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
433 << Next2.getName()
434 << FixItHint::CreateReplacement(Next.getLocation(), ":");
435 Token ColonColon;
436 PP.Lex(ColonColon);
437 ColonColon.setKind(tok::colon);
438 PP.EnterToken(ColonColon, /*IsReinject*/ true);
439 break;
440 }
441 }
442
443 if (LastII)
444 *LastII = &II;
445
446 // We have an identifier followed by a '::'. Lookup this name
447 // as the name in a nested-name-specifier.
448 Token Identifier = Tok;
449 SourceLocation IdLoc = ConsumeToken();
450 assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&(static_cast <bool> (Tok.isOneOf(tok::coloncolon, tok::
colon) && "NextToken() not working properly!") ? void
(0) : __assert_fail ("Tok.isOneOf(tok::coloncolon, tok::colon) && \"NextToken() not working properly!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 451, __extension__ __PRETTY_FUNCTION__
))
451 "NextToken() not working properly!")(static_cast <bool> (Tok.isOneOf(tok::coloncolon, tok::
colon) && "NextToken() not working properly!") ? void
(0) : __assert_fail ("Tok.isOneOf(tok::coloncolon, tok::colon) && \"NextToken() not working properly!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 451, __extension__ __PRETTY_FUNCTION__
))
;
452 Token ColonColon = Tok;
453 SourceLocation CCLoc = ConsumeToken();
454
455 bool IsCorrectedToColon = false;
456 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
457 if (Actions.ActOnCXXNestedNameSpecifier(
458 getCurScope(), IdInfo, EnteringContext, SS, CorrectionFlagPtr,
459 OnlyNamespace)) {
460 // Identifier is not recognized as a nested name, but we can have
461 // mistyped '::' instead of ':'.
462 if (CorrectionFlagPtr && IsCorrectedToColon) {
463 ColonColon.setKind(tok::colon);
464 PP.EnterToken(Tok, /*IsReinject*/ true);
465 PP.EnterToken(ColonColon, /*IsReinject*/ true);
466 Tok = Identifier;
467 break;
468 }
469 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
470 }
471 HasScopeSpecifier = true;
472 continue;
473 }
474
475 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
476
477 // nested-name-specifier:
478 // type-name '<'
479 if (Next.is(tok::less)) {
480
481 TemplateTy Template;
482 UnqualifiedId TemplateName;
483 TemplateName.setIdentifier(&II, Tok.getLocation());
484 bool MemberOfUnknownSpecialization;
485 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
486 /*hasTemplateKeyword=*/false,
487 TemplateName,
488 ObjectType,
489 EnteringContext,
490 Template,
491 MemberOfUnknownSpecialization)) {
492 // If lookup didn't find anything, we treat the name as a template-name
493 // anyway. C++20 requires this, and in prior language modes it improves
494 // error recovery. But before we commit to this, check that we actually
495 // have something that looks like a template-argument-list next.
496 if (!IsTypename && TNK == TNK_Undeclared_template &&
497 isTemplateArgumentList(1) == TPResult::False)
498 break;
499
500 // We have found a template name, so annotate this token
501 // with a template-id annotation. We do not permit the
502 // template-id to be translated into a type annotation,
503 // because some clients (e.g., the parsing of class template
504 // specializations) still want to see the original template-id
505 // token, and it might not be a type at all (e.g. a concept name in a
506 // type-constraint).
507 ConsumeToken();
508 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
509 TemplateName, false))
510 return true;
511 continue;
512 }
513
514 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
515 (IsTypename || isTemplateArgumentList(1) == TPResult::True)) {
516 // If we had errors before, ObjectType can be dependent even without any
517 // templates. Do not report missing template keyword in that case.
518 if (!ObjectHadErrors) {
519 // We have something like t::getAs<T>, where getAs is a
520 // member of an unknown specialization. However, this will only
521 // parse correctly as a template, so suggest the keyword 'template'
522 // before 'getAs' and treat this as a dependent template name.
523 unsigned DiagID = diag::err_missing_dependent_template_keyword;
524 if (getLangOpts().MicrosoftExt)
525 DiagID = diag::warn_missing_dependent_template_keyword;
526
527 Diag(Tok.getLocation(), DiagID)
528 << II.getName()
529 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
530 }
531
532 SourceLocation TemplateNameLoc = ConsumeToken();
533
534 TemplateNameKind TNK = Actions.ActOnTemplateName(
535 getCurScope(), SS, TemplateNameLoc, TemplateName, ObjectType,
536 EnteringContext, Template, /*AllowInjectedClassName*/ true);
537 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
538 TemplateName, false))
539 return true;
540
541 continue;
542 }
543 }
544
545 // We don't have any tokens that form the beginning of a
546 // nested-name-specifier, so we're done.
547 break;
548 }
549
550 // Even if we didn't see any pieces of a nested-name-specifier, we
551 // still check whether there is a tilde in this position, which
552 // indicates a potential pseudo-destructor.
553 if (CheckForDestructor && !HasScopeSpecifier && Tok.is(tok::tilde))
554 *MayBePseudoDestructor = true;
555
556 return false;
557}
558
559ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS,
560 bool isAddressOfOperand,
561 Token &Replacement) {
562 ExprResult E;
563
564 // We may have already annotated this id-expression.
565 switch (Tok.getKind()) {
566 case tok::annot_non_type: {
567 NamedDecl *ND = getNonTypeAnnotation(Tok);
568 SourceLocation Loc = ConsumeAnnotationToken();
569 E = Actions.ActOnNameClassifiedAsNonType(getCurScope(), SS, ND, Loc, Tok);
570 break;
571 }
572
573 case tok::annot_non_type_dependent: {
574 IdentifierInfo *II = getIdentifierAnnotation(Tok);
575 SourceLocation Loc = ConsumeAnnotationToken();
576
577 // This is only the direct operand of an & operator if it is not
578 // followed by a postfix-expression suffix.
579 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
580 isAddressOfOperand = false;
581
582 E = Actions.ActOnNameClassifiedAsDependentNonType(SS, II, Loc,
583 isAddressOfOperand);
584 break;
585 }
586
587 case tok::annot_non_type_undeclared: {
588 assert(SS.isEmpty() &&(static_cast <bool> (SS.isEmpty() && "undeclared non-type annotation should be unqualified"
) ? void (0) : __assert_fail ("SS.isEmpty() && \"undeclared non-type annotation should be unqualified\""
, "clang/lib/Parse/ParseExprCXX.cpp", 589, __extension__ __PRETTY_FUNCTION__
))
589 "undeclared non-type annotation should be unqualified")(static_cast <bool> (SS.isEmpty() && "undeclared non-type annotation should be unqualified"
) ? void (0) : __assert_fail ("SS.isEmpty() && \"undeclared non-type annotation should be unqualified\""
, "clang/lib/Parse/ParseExprCXX.cpp", 589, __extension__ __PRETTY_FUNCTION__
))
;
590 IdentifierInfo *II = getIdentifierAnnotation(Tok);
591 SourceLocation Loc = ConsumeAnnotationToken();
592 E = Actions.ActOnNameClassifiedAsUndeclaredNonType(II, Loc);
593 break;
594 }
595
596 default:
597 SourceLocation TemplateKWLoc;
598 UnqualifiedId Name;
599 if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
600 /*ObjectHadErrors=*/false,
601 /*EnteringContext=*/false,
602 /*AllowDestructorName=*/false,
603 /*AllowConstructorName=*/false,
604 /*AllowDeductionGuide=*/false, &TemplateKWLoc, Name))
605 return ExprError();
606
607 // This is only the direct operand of an & operator if it is not
608 // followed by a postfix-expression suffix.
609 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
610 isAddressOfOperand = false;
611
612 E = Actions.ActOnIdExpression(
613 getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren),
614 isAddressOfOperand, /*CCC=*/nullptr, /*IsInlineAsmIdentifier=*/false,
615 &Replacement);
616 break;
617 }
618
619 if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less))
620 checkPotentialAngleBracket(E);
621 return E;
622}
623
624/// ParseCXXIdExpression - Handle id-expression.
625///
626/// id-expression:
627/// unqualified-id
628/// qualified-id
629///
630/// qualified-id:
631/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
632/// '::' identifier
633/// '::' operator-function-id
634/// '::' template-id
635///
636/// NOTE: The standard specifies that, for qualified-id, the parser does not
637/// expect:
638///
639/// '::' conversion-function-id
640/// '::' '~' class-name
641///
642/// This may cause a slight inconsistency on diagnostics:
643///
644/// class C {};
645/// namespace A {}
646/// void f() {
647/// :: A :: ~ C(); // Some Sema error about using destructor with a
648/// // namespace.
649/// :: ~ C(); // Some Parser error like 'unexpected ~'.
650/// }
651///
652/// We simplify the parser a bit and make it work like:
653///
654/// qualified-id:
655/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
656/// '::' unqualified-id
657///
658/// That way Sema can handle and report similar errors for namespaces and the
659/// global scope.
660///
661/// The isAddressOfOperand parameter indicates that this id-expression is a
662/// direct operand of the address-of operator. This is, besides member contexts,
663/// the only place where a qualified-id naming a non-static class member may
664/// appear.
665///
666ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
667 // qualified-id:
668 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
669 // '::' unqualified-id
670 //
671 CXXScopeSpec SS;
672 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
673 /*ObjectHasErrors=*/false,
674 /*EnteringContext=*/false);
675
676 Token Replacement;
677 ExprResult Result =
678 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
679 if (Result.isUnset()) {
680 // If the ExprResult is valid but null, then typo correction suggested a
681 // keyword replacement that needs to be reparsed.
682 UnconsumeToken(Replacement);
683 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
684 }
685 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "(static_cast <bool> (!Result.isUnset() && "Typo correction suggested a keyword replacement "
"for a previous keyword suggestion") ? void (0) : __assert_fail
("!Result.isUnset() && \"Typo correction suggested a keyword replacement \" \"for a previous keyword suggestion\""
, "clang/lib/Parse/ParseExprCXX.cpp", 686, __extension__ __PRETTY_FUNCTION__
))
686 "for a previous keyword suggestion")(static_cast <bool> (!Result.isUnset() && "Typo correction suggested a keyword replacement "
"for a previous keyword suggestion") ? void (0) : __assert_fail
("!Result.isUnset() && \"Typo correction suggested a keyword replacement \" \"for a previous keyword suggestion\""
, "clang/lib/Parse/ParseExprCXX.cpp", 686, __extension__ __PRETTY_FUNCTION__
))
;
687 return Result;
688}
689
690/// ParseLambdaExpression - Parse a C++11 lambda expression.
691///
692/// lambda-expression:
693/// lambda-introducer lambda-declarator compound-statement
694/// lambda-introducer '<' template-parameter-list '>'
695/// requires-clause[opt] lambda-declarator compound-statement
696///
697/// lambda-introducer:
698/// '[' lambda-capture[opt] ']'
699///
700/// lambda-capture:
701/// capture-default
702/// capture-list
703/// capture-default ',' capture-list
704///
705/// capture-default:
706/// '&'
707/// '='
708///
709/// capture-list:
710/// capture
711/// capture-list ',' capture
712///
713/// capture:
714/// simple-capture
715/// init-capture [C++1y]
716///
717/// simple-capture:
718/// identifier
719/// '&' identifier
720/// 'this'
721///
722/// init-capture: [C++1y]
723/// identifier initializer
724/// '&' identifier initializer
725///
726/// lambda-declarator:
727/// lambda-specifiers [C++2b]
728/// '(' parameter-declaration-clause ')' lambda-specifiers
729/// requires-clause[opt]
730///
731/// lambda-specifiers:
732/// decl-specifier-seq[opt] noexcept-specifier[opt]
733/// attribute-specifier-seq[opt] trailing-return-type[opt]
734///
735ExprResult Parser::ParseLambdaExpression() {
736 // Parse lambda-introducer.
737 LambdaIntroducer Intro;
738 if (ParseLambdaIntroducer(Intro)) {
739 SkipUntil(tok::r_square, StopAtSemi);
740 SkipUntil(tok::l_brace, StopAtSemi);
741 SkipUntil(tok::r_brace, StopAtSemi);
742 return ExprError();
743 }
744
745 return ParseLambdaExpressionAfterIntroducer(Intro);
746}
747
748/// Use lookahead and potentially tentative parsing to determine if we are
749/// looking at a C++11 lambda expression, and parse it if we are.
750///
751/// If we are not looking at a lambda expression, returns ExprError().
752ExprResult Parser::TryParseLambdaExpression() {
753 assert(getLangOpts().CPlusPlus11(static_cast <bool> (getLangOpts().CPlusPlus11 &&
Tok.is(tok::l_square) && "Not at the start of a possible lambda expression."
) ? void (0) : __assert_fail ("getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) && \"Not at the start of a possible lambda expression.\""
, "clang/lib/Parse/ParseExprCXX.cpp", 755, __extension__ __PRETTY_FUNCTION__
))
754 && Tok.is(tok::l_square)(static_cast <bool> (getLangOpts().CPlusPlus11 &&
Tok.is(tok::l_square) && "Not at the start of a possible lambda expression."
) ? void (0) : __assert_fail ("getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) && \"Not at the start of a possible lambda expression.\""
, "clang/lib/Parse/ParseExprCXX.cpp", 755, __extension__ __PRETTY_FUNCTION__
))
755 && "Not at the start of a possible lambda expression.")(static_cast <bool> (getLangOpts().CPlusPlus11 &&
Tok.is(tok::l_square) && "Not at the start of a possible lambda expression."
) ? void (0) : __assert_fail ("getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) && \"Not at the start of a possible lambda expression.\""
, "clang/lib/Parse/ParseExprCXX.cpp", 755, __extension__ __PRETTY_FUNCTION__
))
;
756
757 const Token Next = NextToken();
758 if (Next.is(tok::eof)) // Nothing else to lookup here...
759 return ExprEmpty();
760
761 const Token After = GetLookAheadToken(2);
762 // If lookahead indicates this is a lambda...
763 if (Next.is(tok::r_square) || // []
764 Next.is(tok::equal) || // [=
765 (Next.is(tok::amp) && // [&] or [&,
766 After.isOneOf(tok::r_square, tok::comma)) ||
767 (Next.is(tok::identifier) && // [identifier]
768 After.is(tok::r_square)) ||
769 Next.is(tok::ellipsis)) { // [...
770 return ParseLambdaExpression();
771 }
772
773 // If lookahead indicates an ObjC message send...
774 // [identifier identifier
775 if (Next.is(tok::identifier) && After.is(tok::identifier))
776 return ExprEmpty();
777
778 // Here, we're stuck: lambda introducers and Objective-C message sends are
779 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
780 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
781 // writing two routines to parse a lambda introducer, just try to parse
782 // a lambda introducer first, and fall back if that fails.
783 LambdaIntroducer Intro;
784 {
785 TentativeParsingAction TPA(*this);
786 LambdaIntroducerTentativeParse Tentative;
787 if (ParseLambdaIntroducer(Intro, &Tentative)) {
788 TPA.Commit();
789 return ExprError();
790 }
791
792 switch (Tentative) {
793 case LambdaIntroducerTentativeParse::Success:
794 TPA.Commit();
795 break;
796
797 case LambdaIntroducerTentativeParse::Incomplete:
798 // Didn't fully parse the lambda-introducer, try again with a
799 // non-tentative parse.
800 TPA.Revert();
801 Intro = LambdaIntroducer();
802 if (ParseLambdaIntroducer(Intro))
803 return ExprError();
804 break;
805
806 case LambdaIntroducerTentativeParse::MessageSend:
807 case LambdaIntroducerTentativeParse::Invalid:
808 // Not a lambda-introducer, might be a message send.
809 TPA.Revert();
810 return ExprEmpty();
811 }
812 }
813
814 return ParseLambdaExpressionAfterIntroducer(Intro);
815}
816
817/// Parse a lambda introducer.
818/// \param Intro A LambdaIntroducer filled in with information about the
819/// contents of the lambda-introducer.
820/// \param Tentative If non-null, we are disambiguating between a
821/// lambda-introducer and some other construct. In this mode, we do not
822/// produce any diagnostics or take any other irreversible action unless
823/// we're sure that this is a lambda-expression.
824/// \return \c true if parsing (or disambiguation) failed with a diagnostic and
825/// the caller should bail out / recover.
826bool Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
827 LambdaIntroducerTentativeParse *Tentative) {
828 if (Tentative)
829 *Tentative = LambdaIntroducerTentativeParse::Success;
830
831 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.")(static_cast <bool> (Tok.is(tok::l_square) && "Lambda expressions begin with '['."
) ? void (0) : __assert_fail ("Tok.is(tok::l_square) && \"Lambda expressions begin with '['.\""
, "clang/lib/Parse/ParseExprCXX.cpp", 831, __extension__ __PRETTY_FUNCTION__
))
;
832 BalancedDelimiterTracker T(*this, tok::l_square);
833 T.consumeOpen();
834
835 Intro.Range.setBegin(T.getOpenLocation());
836
837 bool First = true;
838
839 // Produce a diagnostic if we're not tentatively parsing; otherwise track
840 // that our parse has failed.
841 auto Invalid = [&](llvm::function_ref<void()> Action) {
842 if (Tentative) {
843 *Tentative = LambdaIntroducerTentativeParse::Invalid;
844 return false;
845 }
846 Action();
847 return true;
848 };
849
850 // Perform some irreversible action if this is a non-tentative parse;
851 // otherwise note that our actions were incomplete.
852 auto NonTentativeAction = [&](llvm::function_ref<void()> Action) {
853 if (Tentative)
854 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
855 else
856 Action();
857 };
858
859 // Parse capture-default.
860 if (Tok.is(tok::amp) &&
861 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
862 Intro.Default = LCD_ByRef;
863 Intro.DefaultLoc = ConsumeToken();
864 First = false;
865 if (!Tok.getIdentifierInfo()) {
866 // This can only be a lambda; no need for tentative parsing any more.
867 // '[[and]]' can still be an attribute, though.
868 Tentative = nullptr;
869 }
870 } else if (Tok.is(tok::equal)) {
871 Intro.Default = LCD_ByCopy;
872 Intro.DefaultLoc = ConsumeToken();
873 First = false;
874 Tentative = nullptr;
875 }
876
877 while (Tok.isNot(tok::r_square)) {
878 if (!First) {
879 if (Tok.isNot(tok::comma)) {
880 // Provide a completion for a lambda introducer here. Except
881 // in Objective-C, where this is Almost Surely meant to be a message
882 // send. In that case, fail here and let the ObjC message
883 // expression parser perform the completion.
884 if (Tok.is(tok::code_completion) &&
885 !(getLangOpts().ObjC && Tentative)) {
886 cutOffParsing();
887 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
888 /*AfterAmpersand=*/false);
889 break;
890 }
891
892 return Invalid([&] {
893 Diag(Tok.getLocation(), diag::err_expected_comma_or_rsquare);
894 });
895 }
896 ConsumeToken();
897 }
898
899 if (Tok.is(tok::code_completion)) {
900 cutOffParsing();
901 // If we're in Objective-C++ and we have a bare '[', then this is more
902 // likely to be a message receiver.
903 if (getLangOpts().ObjC && Tentative && First)
904 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
905 else
906 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
907 /*AfterAmpersand=*/false);
908 break;
909 }
910
911 First = false;
912
913 // Parse capture.
914 LambdaCaptureKind Kind = LCK_ByCopy;
915 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
916 SourceLocation Loc;
917 IdentifierInfo *Id = nullptr;
918 SourceLocation EllipsisLocs[4];
919 ExprResult Init;
920 SourceLocation LocStart = Tok.getLocation();
921
922 if (Tok.is(tok::star)) {
923 Loc = ConsumeToken();
924 if (Tok.is(tok::kw_this)) {
925 ConsumeToken();
926 Kind = LCK_StarThis;
927 } else {
928 return Invalid([&] {
929 Diag(Tok.getLocation(), diag::err_expected_star_this_capture);
930 });
931 }
932 } else if (Tok.is(tok::kw_this)) {
933 Kind = LCK_This;
934 Loc = ConsumeToken();
935 } else if (Tok.isOneOf(tok::amp, tok::equal) &&
936 NextToken().isOneOf(tok::comma, tok::r_square) &&
937 Intro.Default == LCD_None) {
938 // We have a lone "&" or "=" which is either a misplaced capture-default
939 // or the start of a capture (in the "&" case) with the rest of the
940 // capture missing. Both are an error but a misplaced capture-default
941 // is more likely if we don't already have a capture default.
942 return Invalid(
943 [&] { Diag(Tok.getLocation(), diag::err_capture_default_first); });
944 } else {
945 TryConsumeToken(tok::ellipsis, EllipsisLocs[0]);
946
947 if (Tok.is(tok::amp)) {
948 Kind = LCK_ByRef;
949 ConsumeToken();
950
951 if (Tok.is(tok::code_completion)) {
952 cutOffParsing();
953 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
954 /*AfterAmpersand=*/true);
955 break;
956 }
957 }
958
959 TryConsumeToken(tok::ellipsis, EllipsisLocs[1]);
960
961 if (Tok.is(tok::identifier)) {
962 Id = Tok.getIdentifierInfo();
963 Loc = ConsumeToken();
964 } else if (Tok.is(tok::kw_this)) {
965 return Invalid([&] {
966 // FIXME: Suggest a fixit here.
967 Diag(Tok.getLocation(), diag::err_this_captured_by_reference);
968 });
969 } else {
970 return Invalid([&] {
971 Diag(Tok.getLocation(), diag::err_expected_capture);
972 });
973 }
974
975 TryConsumeToken(tok::ellipsis, EllipsisLocs[2]);
976
977 if (Tok.is(tok::l_paren)) {
978 BalancedDelimiterTracker Parens(*this, tok::l_paren);
979 Parens.consumeOpen();
980
981 InitKind = LambdaCaptureInitKind::DirectInit;
982
983 ExprVector Exprs;
984 CommaLocsTy Commas;
985 if (Tentative) {
986 Parens.skipToEnd();
987 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
988 } else if (ParseExpressionList(Exprs, Commas)) {
989 Parens.skipToEnd();
990 Init = ExprError();
991 } else {
992 Parens.consumeClose();
993 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
994 Parens.getCloseLocation(),
995 Exprs);
996 }
997 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
998 // Each lambda init-capture forms its own full expression, which clears
999 // Actions.MaybeODRUseExprs. So create an expression evaluation context
1000 // to save the necessary state, and restore it later.
1001 EnterExpressionEvaluationContext EC(
1002 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1003
1004 if (TryConsumeToken(tok::equal))
1005 InitKind = LambdaCaptureInitKind::CopyInit;
1006 else
1007 InitKind = LambdaCaptureInitKind::ListInit;
1008
1009 if (!Tentative) {
1010 Init = ParseInitializer();
1011 } else if (Tok.is(tok::l_brace)) {
1012 BalancedDelimiterTracker Braces(*this, tok::l_brace);
1013 Braces.consumeOpen();
1014 Braces.skipToEnd();
1015 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
1016 } else {
1017 // We're disambiguating this:
1018 //
1019 // [..., x = expr
1020 //
1021 // We need to find the end of the following expression in order to
1022 // determine whether this is an Obj-C message send's receiver, a
1023 // C99 designator, or a lambda init-capture.
1024 //
1025 // Parse the expression to find where it ends, and annotate it back
1026 // onto the tokens. We would have parsed this expression the same way
1027 // in either case: both the RHS of an init-capture and the RHS of an
1028 // assignment expression are parsed as an initializer-clause, and in
1029 // neither case can anything be added to the scope between the '[' and
1030 // here.
1031 //
1032 // FIXME: This is horrible. Adding a mechanism to skip an expression
1033 // would be much cleaner.
1034 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
1035 // that instead. (And if we see a ':' with no matching '?', we can
1036 // classify this as an Obj-C message send.)
1037 SourceLocation StartLoc = Tok.getLocation();
1038 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
1039 Init = ParseInitializer();
1040 if (!Init.isInvalid())
1041 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
1042
1043 if (Tok.getLocation() != StartLoc) {
1044 // Back out the lexing of the token after the initializer.
1045 PP.RevertCachedTokens(1);
1046
1047 // Replace the consumed tokens with an appropriate annotation.
1048 Tok.setLocation(StartLoc);
1049 Tok.setKind(tok::annot_primary_expr);
1050 setExprAnnotation(Tok, Init);
1051 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
1052 PP.AnnotateCachedTokens(Tok);
1053
1054 // Consume the annotated initializer.
1055 ConsumeAnnotationToken();
1056 }
1057 }
1058 }
1059
1060 TryConsumeToken(tok::ellipsis, EllipsisLocs[3]);
1061 }
1062
1063 // Check if this is a message send before we act on a possible init-capture.
1064 if (Tentative && Tok.is(tok::identifier) &&
1065 NextToken().isOneOf(tok::colon, tok::r_square)) {
1066 // This can only be a message send. We're done with disambiguation.
1067 *Tentative = LambdaIntroducerTentativeParse::MessageSend;
1068 return false;
1069 }
1070
1071 // Ensure that any ellipsis was in the right place.
1072 SourceLocation EllipsisLoc;
1073 if (llvm::any_of(EllipsisLocs,
1074 [](SourceLocation Loc) { return Loc.isValid(); })) {
1075 // The '...' should appear before the identifier in an init-capture, and
1076 // after the identifier otherwise.
1077 bool InitCapture = InitKind != LambdaCaptureInitKind::NoInit;
1078 SourceLocation *ExpectedEllipsisLoc =
1079 !InitCapture ? &EllipsisLocs[2] :
1080 Kind == LCK_ByRef ? &EllipsisLocs[1] :
1081 &EllipsisLocs[0];
1082 EllipsisLoc = *ExpectedEllipsisLoc;
1083
1084 unsigned DiagID = 0;
1085 if (EllipsisLoc.isInvalid()) {
1086 DiagID = diag::err_lambda_capture_misplaced_ellipsis;
1087 for (SourceLocation Loc : EllipsisLocs) {
1088 if (Loc.isValid())
1089 EllipsisLoc = Loc;
1090 }
1091 } else {
1092 unsigned NumEllipses = std::accumulate(
1093 std::begin(EllipsisLocs), std::end(EllipsisLocs), 0,
1094 [](int N, SourceLocation Loc) { return N + Loc.isValid(); });
1095 if (NumEllipses > 1)
1096 DiagID = diag::err_lambda_capture_multiple_ellipses;
1097 }
1098 if (DiagID) {
1099 NonTentativeAction([&] {
1100 // Point the diagnostic at the first misplaced ellipsis.
1101 SourceLocation DiagLoc;
1102 for (SourceLocation &Loc : EllipsisLocs) {
1103 if (&Loc != ExpectedEllipsisLoc && Loc.isValid()) {
1104 DiagLoc = Loc;
1105 break;
1106 }
1107 }
1108 assert(DiagLoc.isValid() && "no location for diagnostic")(static_cast <bool> (DiagLoc.isValid() && "no location for diagnostic"
) ? void (0) : __assert_fail ("DiagLoc.isValid() && \"no location for diagnostic\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1108, __extension__ __PRETTY_FUNCTION__
))
;
1109
1110 // Issue the diagnostic and produce fixits showing where the ellipsis
1111 // should have been written.
1112 auto &&D = Diag(DiagLoc, DiagID);
1113 if (DiagID == diag::err_lambda_capture_misplaced_ellipsis) {
1114 SourceLocation ExpectedLoc =
1115 InitCapture ? Loc
1116 : Lexer::getLocForEndOfToken(
1117 Loc, 0, PP.getSourceManager(), getLangOpts());
1118 D << InitCapture << FixItHint::CreateInsertion(ExpectedLoc, "...");
1119 }
1120 for (SourceLocation &Loc : EllipsisLocs) {
1121 if (&Loc != ExpectedEllipsisLoc && Loc.isValid())
1122 D << FixItHint::CreateRemoval(Loc);
1123 }
1124 });
1125 }
1126 }
1127
1128 // Process the init-capture initializers now rather than delaying until we
1129 // form the lambda-expression so that they can be handled in the context
1130 // enclosing the lambda-expression, rather than in the context of the
1131 // lambda-expression itself.
1132 ParsedType InitCaptureType;
1133 if (Init.isUsable())
1134 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
1135 if (Init.isUsable()) {
1136 NonTentativeAction([&] {
1137 // Get the pointer and store it in an lvalue, so we can use it as an
1138 // out argument.
1139 Expr *InitExpr = Init.get();
1140 // This performs any lvalue-to-rvalue conversions if necessary, which
1141 // can affect what gets captured in the containing decl-context.
1142 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
1143 Loc, Kind == LCK_ByRef, EllipsisLoc, Id, InitKind, InitExpr);
1144 Init = InitExpr;
1145 });
1146 }
1147
1148 SourceLocation LocEnd = PrevTokLocation;
1149
1150 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
1151 InitCaptureType, SourceRange(LocStart, LocEnd));
1152 }
1153
1154 T.consumeClose();
1155 Intro.Range.setEnd(T.getCloseLocation());
1156 return false;
1157}
1158
1159static void tryConsumeLambdaSpecifierToken(Parser &P,
1160 SourceLocation &MutableLoc,
1161 SourceLocation &StaticLoc,
1162 SourceLocation &ConstexprLoc,
1163 SourceLocation &ConstevalLoc,
1164 SourceLocation &DeclEndLoc) {
1165 assert(MutableLoc.isInvalid())(static_cast <bool> (MutableLoc.isInvalid()) ? void (0)
: __assert_fail ("MutableLoc.isInvalid()", "clang/lib/Parse/ParseExprCXX.cpp"
, 1165, __extension__ __PRETTY_FUNCTION__))
;
1166 assert(StaticLoc.isInvalid())(static_cast <bool> (StaticLoc.isInvalid()) ? void (0) :
__assert_fail ("StaticLoc.isInvalid()", "clang/lib/Parse/ParseExprCXX.cpp"
, 1166, __extension__ __PRETTY_FUNCTION__))
;
1167 assert(ConstexprLoc.isInvalid())(static_cast <bool> (ConstexprLoc.isInvalid()) ? void (
0) : __assert_fail ("ConstexprLoc.isInvalid()", "clang/lib/Parse/ParseExprCXX.cpp"
, 1167, __extension__ __PRETTY_FUNCTION__))
;
1168 assert(ConstevalLoc.isInvalid())(static_cast <bool> (ConstevalLoc.isInvalid()) ? void (
0) : __assert_fail ("ConstevalLoc.isInvalid()", "clang/lib/Parse/ParseExprCXX.cpp"
, 1168, __extension__ __PRETTY_FUNCTION__))
;
1169 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1170 // to the final of those locations. Emit an error if we have multiple
1171 // copies of those keywords and recover.
1172
1173 auto ConsumeLocation = [&P, &DeclEndLoc](SourceLocation &SpecifierLoc,
1174 int DiagIndex) {
1175 if (SpecifierLoc.isValid()) {
1176 P.Diag(P.getCurToken().getLocation(),
1177 diag::err_lambda_decl_specifier_repeated)
1178 << DiagIndex
1179 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1180 }
1181 SpecifierLoc = P.ConsumeToken();
1182 DeclEndLoc = SpecifierLoc;
1183 };
1184
1185 while (true) {
1186 switch (P.getCurToken().getKind()) {
1187 case tok::kw_mutable:
1188 ConsumeLocation(MutableLoc, 0);
1189 break;
1190 case tok::kw_static:
1191 ConsumeLocation(StaticLoc, 1);
1192 break;
1193 case tok::kw_constexpr:
1194 ConsumeLocation(ConstexprLoc, 2);
1195 break;
1196 case tok::kw_consteval:
1197 ConsumeLocation(ConstevalLoc, 3);
1198 break;
1199 default:
1200 return;
1201 }
1202 }
1203}
1204
1205static void addStaticToLambdaDeclSpecifier(Parser &P, SourceLocation StaticLoc,
1206 DeclSpec &DS) {
1207 if (StaticLoc.isValid()) {
1208 P.Diag(StaticLoc, !P.getLangOpts().CPlusPlus2b
1209 ? diag::err_static_lambda
1210 : diag::warn_cxx20_compat_static_lambda);
1211 const char *PrevSpec = nullptr;
1212 unsigned DiagID = 0;
1213 DS.SetStorageClassSpec(P.getActions(), DeclSpec::SCS_static, StaticLoc,
1214 PrevSpec, DiagID,
1215 P.getActions().getASTContext().getPrintingPolicy());
1216 assert(PrevSpec == nullptr && DiagID == 0 &&(static_cast <bool> (PrevSpec == nullptr && DiagID
== 0 && "Static cannot have been set previously!") ?
void (0) : __assert_fail ("PrevSpec == nullptr && DiagID == 0 && \"Static cannot have been set previously!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1217, __extension__ __PRETTY_FUNCTION__
))
1217 "Static cannot have been set previously!")(static_cast <bool> (PrevSpec == nullptr && DiagID
== 0 && "Static cannot have been set previously!") ?
void (0) : __assert_fail ("PrevSpec == nullptr && DiagID == 0 && \"Static cannot have been set previously!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1217, __extension__ __PRETTY_FUNCTION__
))
;
1218 }
1219}
1220
1221static void
1222addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1223 DeclSpec &DS) {
1224 if (ConstexprLoc.isValid()) {
1225 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
1226 ? diag::ext_constexpr_on_lambda_cxx17
1227 : diag::warn_cxx14_compat_constexpr_on_lambda);
1228 const char *PrevSpec = nullptr;
1229 unsigned DiagID = 0;
1230 DS.SetConstexprSpec(ConstexprSpecKind::Constexpr, ConstexprLoc, PrevSpec,
1231 DiagID);
1232 assert(PrevSpec == nullptr && DiagID == 0 &&(static_cast <bool> (PrevSpec == nullptr && DiagID
== 0 && "Constexpr cannot have been set previously!"
) ? void (0) : __assert_fail ("PrevSpec == nullptr && DiagID == 0 && \"Constexpr cannot have been set previously!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1233, __extension__ __PRETTY_FUNCTION__
))
1233 "Constexpr cannot have been set previously!")(static_cast <bool> (PrevSpec == nullptr && DiagID
== 0 && "Constexpr cannot have been set previously!"
) ? void (0) : __assert_fail ("PrevSpec == nullptr && DiagID == 0 && \"Constexpr cannot have been set previously!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1233, __extension__ __PRETTY_FUNCTION__
))
;
1234 }
1235}
1236
1237static void addConstevalToLambdaDeclSpecifier(Parser &P,
1238 SourceLocation ConstevalLoc,
1239 DeclSpec &DS) {
1240 if (ConstevalLoc.isValid()) {
1241 P.Diag(ConstevalLoc, diag::warn_cxx20_compat_consteval);
1242 const char *PrevSpec = nullptr;
1243 unsigned DiagID = 0;
1244 DS.SetConstexprSpec(ConstexprSpecKind::Consteval, ConstevalLoc, PrevSpec,
1245 DiagID);
1246 if (DiagID != 0)
1247 P.Diag(ConstevalLoc, DiagID) << PrevSpec;
1248 }
1249}
1250
1251static void DiagnoseStaticSpecifierRestrictions(Parser &P,
1252 SourceLocation StaticLoc,
1253 SourceLocation MutableLoc,
1254 const LambdaIntroducer &Intro) {
1255 if (StaticLoc.isInvalid())
1256 return;
1257
1258 // [expr.prim.lambda.general] p4
1259 // The lambda-specifier-seq shall not contain both mutable and static.
1260 // If the lambda-specifier-seq contains static, there shall be no
1261 // lambda-capture.
1262 if (MutableLoc.isValid())
1263 P.Diag(StaticLoc, diag::err_static_mutable_lambda);
1264 if (Intro.hasLambdaCapture()) {
1265 P.Diag(StaticLoc, diag::err_static_lambda_captures);
1266 }
1267}
1268
1269/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1270/// expression.
1271ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1272 LambdaIntroducer &Intro) {
1273 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1274 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1275
1276 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1277 "lambda expression parsing");
1278
1279
1280
1281 // FIXME: Call into Actions to add any init-capture declarations to the
1282 // scope while parsing the lambda-declarator and compound-statement.
1283
1284 // Parse lambda-declarator[opt].
1285 DeclSpec DS(AttrFactory);
1286 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::LambdaExpr);
1287 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1288 Actions.PushLambdaScope();
1289
1290 ParsedAttributes Attr(AttrFactory);
1291 if (getLangOpts().CUDA) {
1292 // In CUDA code, GNU attributes are allowed to appear immediately after the
1293 // "[...]", even if there is no "(...)" before the lambda body.
1294 MaybeParseGNUAttributes(D);
1295 }
1296
1297 // Helper to emit a warning if we see a CUDA host/device/global attribute
1298 // after '(...)'. nvcc doesn't accept this.
1299 auto WarnIfHasCUDATargetAttr = [&] {
1300 if (getLangOpts().CUDA)
1301 for (const ParsedAttr &A : Attr)
1302 if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1303 A.getKind() == ParsedAttr::AT_CUDAHost ||
1304 A.getKind() == ParsedAttr::AT_CUDAGlobal)
1305 Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
1306 << A.getAttrName()->getName();
1307 };
1308
1309 MultiParseScope TemplateParamScope(*this);
1310 if (Tok.is(tok::less)) {
1311 Diag(Tok, getLangOpts().CPlusPlus20
1312 ? diag::warn_cxx17_compat_lambda_template_parameter_list
1313 : diag::ext_lambda_template_parameter_list);
1314
1315 SmallVector<NamedDecl*, 4> TemplateParams;
1316 SourceLocation LAngleLoc, RAngleLoc;
1317 if (ParseTemplateParameters(TemplateParamScope,
1318 CurTemplateDepthTracker.getDepth(),
1319 TemplateParams, LAngleLoc, RAngleLoc)) {
1320 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1321 return ExprError();
1322 }
1323
1324 if (TemplateParams.empty()) {
1325 Diag(RAngleLoc,
1326 diag::err_lambda_template_parameter_list_empty);
1327 } else {
1328 ExprResult RequiresClause;
1329 if (TryConsumeToken(tok::kw_requires)) {
1330 RequiresClause =
1331 Actions.ActOnRequiresClause(ParseConstraintLogicalOrExpression(
1332 /*IsTrailingRequiresClause=*/false));
1333 if (RequiresClause.isInvalid())
1334 SkipUntil({tok::l_brace, tok::l_paren}, StopAtSemi | StopBeforeMatch);
1335 }
1336
1337 Actions.ActOnLambdaExplicitTemplateParameterList(
1338 LAngleLoc, TemplateParams, RAngleLoc, RequiresClause);
1339 ++CurTemplateDepthTracker;
1340 }
1341 }
1342
1343 // Implement WG21 P2173, which allows attributes immediately before the
1344 // lambda declarator and applies them to the corresponding function operator
1345 // or operator template declaration. We accept this as a conforming extension
1346 // in all language modes that support lambdas.
1347 if (isCXX11AttributeSpecifier()) {
1348 Diag(Tok, getLangOpts().CPlusPlus2b
1349 ? diag::warn_cxx20_compat_decl_attrs_on_lambda
1350 : diag::ext_decl_attrs_on_lambda);
1351 MaybeParseCXX11Attributes(D);
1352 }
1353
1354 TypeResult TrailingReturnType;
1355 SourceLocation TrailingReturnTypeLoc;
1356
1357 auto ParseLambdaSpecifiers =
1358 [&](SourceLocation LParenLoc, SourceLocation RParenLoc,
1359 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo,
1360 SourceLocation EllipsisLoc) {
1361 SourceLocation DeclEndLoc = RParenLoc;
1362
1363 // GNU-style attributes must be parsed before the mutable specifier to
1364 // be compatible with GCC. MSVC-style attributes must be parsed before
1365 // the mutable specifier to be compatible with MSVC.
1366 MaybeParseAttributes(PAKM_GNU | PAKM_Declspec, Attr);
1367
1368 // Parse lambda specifiers and update the DeclEndLoc.
1369 SourceLocation MutableLoc;
1370 SourceLocation StaticLoc;
1371 SourceLocation ConstexprLoc;
1372 SourceLocation ConstevalLoc;
1373 tryConsumeLambdaSpecifierToken(*this, MutableLoc, StaticLoc,
1374 ConstexprLoc, ConstevalLoc, DeclEndLoc);
1375
1376 DiagnoseStaticSpecifierRestrictions(*this, StaticLoc, MutableLoc,
1377 Intro);
1378
1379 addStaticToLambdaDeclSpecifier(*this, StaticLoc, DS);
1380 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1381 addConstevalToLambdaDeclSpecifier(*this, ConstevalLoc, DS);
1382 // Parse exception-specification[opt].
1383 ExceptionSpecificationType ESpecType = EST_None;
1384 SourceRange ESpecRange;
1385 SmallVector<ParsedType, 2> DynamicExceptions;
1386 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1387 ExprResult NoexceptExpr;
1388 CachedTokens *ExceptionSpecTokens;
1389 ESpecType = tryParseExceptionSpecification(
1390 /*Delayed=*/false, ESpecRange, DynamicExceptions,
1391 DynamicExceptionRanges, NoexceptExpr, ExceptionSpecTokens);
1392
1393 if (ESpecType != EST_None)
1394 DeclEndLoc = ESpecRange.getEnd();
1395
1396 // Parse attribute-specifier[opt].
1397 if (MaybeParseCXX11Attributes(Attr))
1398 DeclEndLoc = Attr.Range.getEnd();
1399
1400 // Parse OpenCL addr space attribute.
1401 if (Tok.isOneOf(tok::kw___private, tok::kw___global, tok::kw___local,
1402 tok::kw___constant, tok::kw___generic)) {
1403 ParseOpenCLQualifiers(DS.getAttributes());
1404 ConsumeToken();
1405 }
1406
1407 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1408
1409 // Parse trailing-return-type[opt].
1410 if (Tok.is(tok::arrow)) {
1411 FunLocalRangeEnd = Tok.getLocation();
1412 SourceRange Range;
1413 TrailingReturnType = ParseTrailingReturnType(
1414 Range, /*MayBeFollowedByDirectInit*/ false);
1415 TrailingReturnTypeLoc = Range.getBegin();
1416 if (Range.getEnd().isValid())
1417 DeclEndLoc = Range.getEnd();
1418 }
1419
1420 SourceLocation NoLoc;
1421 D.AddTypeInfo(
1422 DeclaratorChunk::getFunction(
1423 /*HasProto=*/true,
1424 /*IsAmbiguous=*/false, LParenLoc, ParamInfo.data(),
1425 ParamInfo.size(), EllipsisLoc, RParenLoc,
1426 /*RefQualifierIsLvalueRef=*/true,
1427 /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType, ESpecRange,
1428 DynamicExceptions.data(), DynamicExceptionRanges.data(),
1429 DynamicExceptions.size(),
1430 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1431 /*ExceptionSpecTokens*/ nullptr,
1432 /*DeclsInPrototype=*/None, LParenLoc, FunLocalRangeEnd, D,
1433 TrailingReturnType, TrailingReturnTypeLoc, &DS),
1434 std::move(Attr), DeclEndLoc);
1435 };
1436
1437 if (Tok.is(tok::l_paren)) {
1438 ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope |
1439 Scope::FunctionDeclarationScope |
1440 Scope::DeclScope);
1441
1442 BalancedDelimiterTracker T(*this, tok::l_paren);
1443 T.consumeOpen();
1444 SourceLocation LParenLoc = T.getOpenLocation();
1445
1446 // Parse parameter-declaration-clause.
1447 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1448 SourceLocation EllipsisLoc;
1449
1450 if (Tok.isNot(tok::r_paren)) {
1451 Actions.RecordParsingTemplateParameterDepth(
1452 CurTemplateDepthTracker.getOriginalDepth());
1453
1454 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
1455 // For a generic lambda, each 'auto' within the parameter declaration
1456 // clause creates a template type parameter, so increment the depth.
1457 // If we've parsed any explicit template parameters, then the depth will
1458 // have already been incremented. So we make sure that at most a single
1459 // depth level is added.
1460 if (Actions.getCurGenericLambda())
1461 CurTemplateDepthTracker.setAddedDepth(1);
1462 }
1463
1464 T.consumeClose();
1465
1466 // Parse lambda-specifiers.
1467 ParseLambdaSpecifiers(LParenLoc, /*DeclEndLoc=*/T.getCloseLocation(),
1468 ParamInfo, EllipsisLoc);
1469
1470 // Parse requires-clause[opt].
1471 if (Tok.is(tok::kw_requires))
1472 ParseTrailingRequiresClause(D);
1473 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1474 tok::kw_constexpr, tok::kw_consteval, tok::kw_static,
1475 tok::kw___private, tok::kw___global, tok::kw___local,
1476 tok::kw___constant, tok::kw___generic,
1477 tok::kw_requires, tok::kw_noexcept) ||
1478 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1479 if (!getLangOpts().CPlusPlus2b)
1480 // It's common to forget that one needs '()' before 'mutable', an
1481 // attribute specifier, the result type, or the requires clause. Deal with
1482 // this.
1483 Diag(Tok, diag::ext_lambda_missing_parens)
1484 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1485
1486 SourceLocation NoLoc;
1487 // Parse lambda-specifiers.
1488 std::vector<DeclaratorChunk::ParamInfo> EmptyParamInfo;
1489 ParseLambdaSpecifiers(/*LParenLoc=*/NoLoc, /*RParenLoc=*/NoLoc,
1490 EmptyParamInfo, /*EllipsisLoc=*/NoLoc);
1491 }
1492
1493 WarnIfHasCUDATargetAttr();
1494
1495 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1496 // it.
1497 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1498 Scope::CompoundStmtScope;
1499 ParseScope BodyScope(this, ScopeFlags);
1500
1501 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1502
1503 // Parse compound-statement.
1504 if (!Tok.is(tok::l_brace)) {
1505 Diag(Tok, diag::err_expected_lambda_body);
1506 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1507 return ExprError();
1508 }
1509
1510 StmtResult Stmt(ParseCompoundStatementBody());
1511 BodyScope.Exit();
1512 TemplateParamScope.Exit();
1513
1514 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1515 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1516
1517 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1518 return ExprError();
1519}
1520
1521/// ParseCXXCasts - This handles the various ways to cast expressions to another
1522/// type.
1523///
1524/// postfix-expression: [C++ 5.2p1]
1525/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1526/// 'static_cast' '<' type-name '>' '(' expression ')'
1527/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1528/// 'const_cast' '<' type-name '>' '(' expression ')'
1529///
1530/// C++ for OpenCL s2.3.1 adds:
1531/// 'addrspace_cast' '<' type-name '>' '(' expression ')'
1532ExprResult Parser::ParseCXXCasts() {
1533 tok::TokenKind Kind = Tok.getKind();
1534 const char *CastName = nullptr; // For error messages
1535
1536 switch (Kind) {
1537 default: llvm_unreachable("Unknown C++ cast!")::llvm::llvm_unreachable_internal("Unknown C++ cast!", "clang/lib/Parse/ParseExprCXX.cpp"
, 1537)
;
1538 case tok::kw_addrspace_cast: CastName = "addrspace_cast"; break;
1539 case tok::kw_const_cast: CastName = "const_cast"; break;
1540 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1541 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1542 case tok::kw_static_cast: CastName = "static_cast"; break;
1543 }
1544
1545 SourceLocation OpLoc = ConsumeToken();
1546 SourceLocation LAngleBracketLoc = Tok.getLocation();
1547
1548 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1549 // diagnose error, suggest fix, and recover parsing.
1550 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1551 Token Next = NextToken();
1552 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1553 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1554 }
1555
1556 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1557 return ExprError();
1558
1559 // Parse the common declaration-specifiers piece.
1560 DeclSpec DS(AttrFactory);
1561 ParseSpecifierQualifierList(DS, /*AccessSpecifier=*/AS_none,
1562 DeclSpecContext::DSC_type_specifier);
1563
1564 // Parse the abstract-declarator, if present.
1565 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1566 DeclaratorContext::TypeName);
1567 ParseDeclarator(DeclaratorInfo);
1568
1569 SourceLocation RAngleBracketLoc = Tok.getLocation();
1570
1571 if (ExpectAndConsume(tok::greater))
1572 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1573
1574 BalancedDelimiterTracker T(*this, tok::l_paren);
1575
1576 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1577 return ExprError();
1578
1579 ExprResult Result = ParseExpression();
1580
1581 // Match the ')'.
1582 T.consumeClose();
1583
1584 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1585 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1586 LAngleBracketLoc, DeclaratorInfo,
1587 RAngleBracketLoc,
1588 T.getOpenLocation(), Result.get(),
1589 T.getCloseLocation());
1590
1591 return Result;
1592}
1593
1594/// ParseCXXTypeid - This handles the C++ typeid expression.
1595///
1596/// postfix-expression: [C++ 5.2p1]
1597/// 'typeid' '(' expression ')'
1598/// 'typeid' '(' type-id ')'
1599///
1600ExprResult Parser::ParseCXXTypeid() {
1601 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!")(static_cast <bool> (Tok.is(tok::kw_typeid) && "Not 'typeid'!"
) ? void (0) : __assert_fail ("Tok.is(tok::kw_typeid) && \"Not 'typeid'!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1601, __extension__ __PRETTY_FUNCTION__
))
;
1602
1603 SourceLocation OpLoc = ConsumeToken();
1604 SourceLocation LParenLoc, RParenLoc;
1605 BalancedDelimiterTracker T(*this, tok::l_paren);
1606
1607 // typeid expressions are always parenthesized.
1608 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1609 return ExprError();
1610 LParenLoc = T.getOpenLocation();
1611
1612 ExprResult Result;
1613
1614 // C++0x [expr.typeid]p3:
1615 // When typeid is applied to an expression other than an lvalue of a
1616 // polymorphic class type [...] The expression is an unevaluated
1617 // operand (Clause 5).
1618 //
1619 // Note that we can't tell whether the expression is an lvalue of a
1620 // polymorphic class type until after we've parsed the expression; we
1621 // speculatively assume the subexpression is unevaluated, and fix it up
1622 // later.
1623 //
1624 // We enter the unevaluated context before trying to determine whether we
1625 // have a type-id, because the tentative parse logic will try to resolve
1626 // names, and must treat them as unevaluated.
1627 EnterExpressionEvaluationContext Unevaluated(
1628 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1629 Sema::ReuseLambdaContextDecl);
1630
1631 if (isTypeIdInParens()) {
1632 TypeResult Ty = ParseTypeName();
1633
1634 // Match the ')'.
1635 T.consumeClose();
1636 RParenLoc = T.getCloseLocation();
1637 if (Ty.isInvalid() || RParenLoc.isInvalid())
1638 return ExprError();
1639
1640 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1641 Ty.get().getAsOpaquePtr(), RParenLoc);
1642 } else {
1643 Result = ParseExpression();
1644
1645 // Match the ')'.
1646 if (Result.isInvalid())
1647 SkipUntil(tok::r_paren, StopAtSemi);
1648 else {
1649 T.consumeClose();
1650 RParenLoc = T.getCloseLocation();
1651 if (RParenLoc.isInvalid())
1652 return ExprError();
1653
1654 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1655 Result.get(), RParenLoc);
1656 }
1657 }
1658
1659 return Result;
1660}
1661
1662/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1663///
1664/// '__uuidof' '(' expression ')'
1665/// '__uuidof' '(' type-id ')'
1666///
1667ExprResult Parser::ParseCXXUuidof() {
1668 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!")(static_cast <bool> (Tok.is(tok::kw___uuidof) &&
"Not '__uuidof'!") ? void (0) : __assert_fail ("Tok.is(tok::kw___uuidof) && \"Not '__uuidof'!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1668, __extension__ __PRETTY_FUNCTION__
))
;
1669
1670 SourceLocation OpLoc = ConsumeToken();
1671 BalancedDelimiterTracker T(*this, tok::l_paren);
1672
1673 // __uuidof expressions are always parenthesized.
1674 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1675 return ExprError();
1676
1677 ExprResult Result;
1678
1679 if (isTypeIdInParens()) {
1680 TypeResult Ty = ParseTypeName();
1681
1682 // Match the ')'.
1683 T.consumeClose();
1684
1685 if (Ty.isInvalid())
1686 return ExprError();
1687
1688 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1689 Ty.get().getAsOpaquePtr(),
1690 T.getCloseLocation());
1691 } else {
1692 EnterExpressionEvaluationContext Unevaluated(
1693 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1694 Result = ParseExpression();
1695
1696 // Match the ')'.
1697 if (Result.isInvalid())
1698 SkipUntil(tok::r_paren, StopAtSemi);
1699 else {
1700 T.consumeClose();
1701
1702 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1703 /*isType=*/false,
1704 Result.get(), T.getCloseLocation());
1705 }
1706 }
1707
1708 return Result;
1709}
1710
1711/// Parse a C++ pseudo-destructor expression after the base,
1712/// . or -> operator, and nested-name-specifier have already been
1713/// parsed. We're handling this fragment of the grammar:
1714///
1715/// postfix-expression: [C++2a expr.post]
1716/// postfix-expression . template[opt] id-expression
1717/// postfix-expression -> template[opt] id-expression
1718///
1719/// id-expression:
1720/// qualified-id
1721/// unqualified-id
1722///
1723/// qualified-id:
1724/// nested-name-specifier template[opt] unqualified-id
1725///
1726/// nested-name-specifier:
1727/// type-name ::
1728/// decltype-specifier :: FIXME: not implemented, but probably only
1729/// allowed in C++ grammar by accident
1730/// nested-name-specifier identifier ::
1731/// nested-name-specifier template[opt] simple-template-id ::
1732/// [...]
1733///
1734/// unqualified-id:
1735/// ~ type-name
1736/// ~ decltype-specifier
1737/// [...]
1738///
1739/// ... where the all but the last component of the nested-name-specifier
1740/// has already been parsed, and the base expression is not of a non-dependent
1741/// class type.
1742ExprResult
1743Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1744 tok::TokenKind OpKind,
1745 CXXScopeSpec &SS,
1746 ParsedType ObjectType) {
1747 // If the last component of the (optional) nested-name-specifier is
1748 // template[opt] simple-template-id, it has already been annotated.
1749 UnqualifiedId FirstTypeName;
1750 SourceLocation CCLoc;
1751 if (Tok.is(tok::identifier)) {
1752 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1753 ConsumeToken();
1754 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail")(static_cast <bool> (Tok.is(tok::coloncolon) &&
"ParseOptionalCXXScopeSpecifier fail") ? void (0) : __assert_fail
("Tok.is(tok::coloncolon) &&\"ParseOptionalCXXScopeSpecifier fail\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1754, __extension__ __PRETTY_FUNCTION__
))
;
1755 CCLoc = ConsumeToken();
1756 } else if (Tok.is(tok::annot_template_id)) {
1757 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1758 // FIXME: Carry on and build an AST representation for tooling.
1759 if (TemplateId->isInvalid())
1760 return ExprError();
1761 FirstTypeName.setTemplateId(TemplateId);
1762 ConsumeAnnotationToken();
1763 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail")(static_cast <bool> (Tok.is(tok::coloncolon) &&
"ParseOptionalCXXScopeSpecifier fail") ? void (0) : __assert_fail
("Tok.is(tok::coloncolon) &&\"ParseOptionalCXXScopeSpecifier fail\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1763, __extension__ __PRETTY_FUNCTION__
))
;
1764 CCLoc = ConsumeToken();
1765 } else {
1766 assert(SS.isEmpty() && "missing last component of nested name specifier")(static_cast <bool> (SS.isEmpty() && "missing last component of nested name specifier"
) ? void (0) : __assert_fail ("SS.isEmpty() && \"missing last component of nested name specifier\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1766, __extension__ __PRETTY_FUNCTION__
))
;
1767 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1768 }
1769
1770 // Parse the tilde.
1771 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail")(static_cast <bool> (Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail"
) ? void (0) : __assert_fail ("Tok.is(tok::tilde) && \"ParseOptionalCXXScopeSpecifier fail\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1771, __extension__ __PRETTY_FUNCTION__
))
;
1772 SourceLocation TildeLoc = ConsumeToken();
1773
1774 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid()) {
1775 DeclSpec DS(AttrFactory);
1776 ParseDecltypeSpecifier(DS);
1777 if (DS.getTypeSpecType() == TST_error)
1778 return ExprError();
1779 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1780 TildeLoc, DS);
1781 }
1782
1783 if (!Tok.is(tok::identifier)) {
1784 Diag(Tok, diag::err_destructor_tilde_identifier);
1785 return ExprError();
1786 }
1787
1788 // Parse the second type.
1789 UnqualifiedId SecondTypeName;
1790 IdentifierInfo *Name = Tok.getIdentifierInfo();
1791 SourceLocation NameLoc = ConsumeToken();
1792 SecondTypeName.setIdentifier(Name, NameLoc);
1793
1794 // If there is a '<', the second type name is a template-id. Parse
1795 // it as such.
1796 //
1797 // FIXME: This is not a context in which a '<' is assumed to start a template
1798 // argument list. This affects examples such as
1799 // void f(auto *p) { p->~X<int>(); }
1800 // ... but there's no ambiguity, and nowhere to write 'template' in such an
1801 // example, so we accept it anyway.
1802 if (Tok.is(tok::less) &&
1803 ParseUnqualifiedIdTemplateId(
1804 SS, ObjectType, Base && Base->containsErrors(), SourceLocation(),
1805 Name, NameLoc, false, SecondTypeName,
1806 /*AssumeTemplateId=*/true))
1807 return ExprError();
1808
1809 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1810 SS, FirstTypeName, CCLoc, TildeLoc,
1811 SecondTypeName);
1812}
1813
1814/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1815///
1816/// boolean-literal: [C++ 2.13.5]
1817/// 'true'
1818/// 'false'
1819ExprResult Parser::ParseCXXBoolLiteral() {
1820 tok::TokenKind Kind = Tok.getKind();
1821 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1822}
1823
1824/// ParseThrowExpression - This handles the C++ throw expression.
1825///
1826/// throw-expression: [C++ 15]
1827/// 'throw' assignment-expression[opt]
1828ExprResult Parser::ParseThrowExpression() {
1829 assert(Tok.is(tok::kw_throw) && "Not throw!")(static_cast <bool> (Tok.is(tok::kw_throw) && "Not throw!"
) ? void (0) : __assert_fail ("Tok.is(tok::kw_throw) && \"Not throw!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1829, __extension__ __PRETTY_FUNCTION__
))
;
1830 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1831
1832 // If the current token isn't the start of an assignment-expression,
1833 // then the expression is not present. This handles things like:
1834 // "C ? throw : (void)42", which is crazy but legal.
1835 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1836 case tok::semi:
1837 case tok::r_paren:
1838 case tok::r_square:
1839 case tok::r_brace:
1840 case tok::colon:
1841 case tok::comma:
1842 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1843
1844 default:
1845 ExprResult Expr(ParseAssignmentExpression());
1846 if (Expr.isInvalid()) return Expr;
1847 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1848 }
1849}
1850
1851/// Parse the C++ Coroutines co_yield expression.
1852///
1853/// co_yield-expression:
1854/// 'co_yield' assignment-expression[opt]
1855ExprResult Parser::ParseCoyieldExpression() {
1856 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!")(static_cast <bool> (Tok.is(tok::kw_co_yield) &&
"Not co_yield!") ? void (0) : __assert_fail ("Tok.is(tok::kw_co_yield) && \"Not co_yield!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1856, __extension__ __PRETTY_FUNCTION__
))
;
1857
1858 SourceLocation Loc = ConsumeToken();
1859 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1860 : ParseAssignmentExpression();
1861 if (!Expr.isInvalid())
1862 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1863 return Expr;
1864}
1865
1866/// ParseCXXThis - This handles the C++ 'this' pointer.
1867///
1868/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1869/// a non-lvalue expression whose value is the address of the object for which
1870/// the function is called.
1871ExprResult Parser::ParseCXXThis() {
1872 assert(Tok.is(tok::kw_this) && "Not 'this'!")(static_cast <bool> (Tok.is(tok::kw_this) && "Not 'this'!"
) ? void (0) : __assert_fail ("Tok.is(tok::kw_this) && \"Not 'this'!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1872, __extension__ __PRETTY_FUNCTION__
))
;
1873 SourceLocation ThisLoc = ConsumeToken();
1874 return Actions.ActOnCXXThis(ThisLoc);
1875}
1876
1877/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1878/// Can be interpreted either as function-style casting ("int(x)")
1879/// or class type construction ("ClassType(x,y,z)")
1880/// or creation of a value-initialized type ("int()").
1881/// See [C++ 5.2.3].
1882///
1883/// postfix-expression: [C++ 5.2p1]
1884/// simple-type-specifier '(' expression-list[opt] ')'
1885/// [C++0x] simple-type-specifier braced-init-list
1886/// typename-specifier '(' expression-list[opt] ')'
1887/// [C++0x] typename-specifier braced-init-list
1888///
1889/// In C++1z onwards, the type specifier can also be a template-name.
1890ExprResult
1891Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1892 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1893 DeclaratorContext::FunctionalCast);
1894 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1895
1896 assert((Tok.is(tok::l_paren) ||(static_cast <bool> ((Tok.is(tok::l_paren) || (getLangOpts
().CPlusPlus11 && Tok.is(tok::l_brace))) && "Expected '(' or '{'!"
) ? void (0) : __assert_fail ("(Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) && \"Expected '(' or '{'!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1898, __extension__ __PRETTY_FUNCTION__
))
1897 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))(static_cast <bool> ((Tok.is(tok::l_paren) || (getLangOpts
().CPlusPlus11 && Tok.is(tok::l_brace))) && "Expected '(' or '{'!"
) ? void (0) : __assert_fail ("(Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) && \"Expected '(' or '{'!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1898, __extension__ __PRETTY_FUNCTION__
))
1898 && "Expected '(' or '{'!")(static_cast <bool> ((Tok.is(tok::l_paren) || (getLangOpts
().CPlusPlus11 && Tok.is(tok::l_brace))) && "Expected '(' or '{'!"
) ? void (0) : __assert_fail ("(Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) && \"Expected '(' or '{'!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1898, __extension__ __PRETTY_FUNCTION__
))
;
1899
1900 if (Tok.is(tok::l_brace)) {
1901 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1902 ExprResult Init = ParseBraceInitializer();
1903 if (Init.isInvalid())
1904 return Init;
1905 Expr *InitList = Init.get();
1906 return Actions.ActOnCXXTypeConstructExpr(
1907 TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
1908 InitList->getEndLoc(), /*ListInitialization=*/true);
1909 } else {
1910 BalancedDelimiterTracker T(*this, tok::l_paren);
1911 T.consumeOpen();
1912
1913 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1914
1915 ExprVector Exprs;
1916 CommaLocsTy CommaLocs;
1917
1918 auto RunSignatureHelp = [&]() {
1919 QualType PreferredType;
1920 if (TypeRep)
1921 PreferredType = Actions.ProduceConstructorSignatureHelp(
1922 TypeRep.get()->getCanonicalTypeInternal(), DS.getEndLoc(), Exprs,
1923 T.getOpenLocation(), /*Braced=*/false);
1924 CalledSignatureHelp = true;
1925 return PreferredType;
1926 };
1927
1928 if (Tok.isNot(tok::r_paren)) {
1929 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1930 PreferredType.enterFunctionArgument(Tok.getLocation(),
1931 RunSignatureHelp);
1932 })) {
1933 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1934 RunSignatureHelp();
1935 SkipUntil(tok::r_paren, StopAtSemi);
1936 return ExprError();
1937 }
1938 }
1939
1940 // Match the ')'.
1941 T.consumeClose();
1942
1943 // TypeRep could be null, if it references an invalid typedef.
1944 if (!TypeRep)
1945 return ExprError();
1946
1947 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&(static_cast <bool> ((Exprs.size() == 0 || Exprs.size()
-1 == CommaLocs.size())&& "Unexpected number of commas!"
) ? void (0) : __assert_fail ("(Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&& \"Unexpected number of commas!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1948, __extension__ __PRETTY_FUNCTION__
))
1948 "Unexpected number of commas!")(static_cast <bool> ((Exprs.size() == 0 || Exprs.size()
-1 == CommaLocs.size())&& "Unexpected number of commas!"
) ? void (0) : __assert_fail ("(Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&& \"Unexpected number of commas!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1948, __extension__ __PRETTY_FUNCTION__
))
;
1949 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1950 Exprs, T.getCloseLocation(),
1951 /*ListInitialization=*/false);
1952 }
1953}
1954
1955Parser::DeclGroupPtrTy
1956Parser::ParseAliasDeclarationInInitStatement(DeclaratorContext Context,
1957 ParsedAttributes &Attrs) {
1958 assert(Tok.is(tok::kw_using) && "Expected using")(static_cast <bool> (Tok.is(tok::kw_using) && "Expected using"
) ? void (0) : __assert_fail ("Tok.is(tok::kw_using) && \"Expected using\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1958, __extension__ __PRETTY_FUNCTION__
))
;
1959 assert((Context == DeclaratorContext::ForInit ||(static_cast <bool> ((Context == DeclaratorContext::ForInit
|| Context == DeclaratorContext::SelectionInit) && "Unexpected Declarator Context"
) ? void (0) : __assert_fail ("(Context == DeclaratorContext::ForInit || Context == DeclaratorContext::SelectionInit) && \"Unexpected Declarator Context\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1961, __extension__ __PRETTY_FUNCTION__
))
1960 Context == DeclaratorContext::SelectionInit) &&(static_cast <bool> ((Context == DeclaratorContext::ForInit
|| Context == DeclaratorContext::SelectionInit) && "Unexpected Declarator Context"
) ? void (0) : __assert_fail ("(Context == DeclaratorContext::ForInit || Context == DeclaratorContext::SelectionInit) && \"Unexpected Declarator Context\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1961, __extension__ __PRETTY_FUNCTION__
))
1961 "Unexpected Declarator Context")(static_cast <bool> ((Context == DeclaratorContext::ForInit
|| Context == DeclaratorContext::SelectionInit) && "Unexpected Declarator Context"
) ? void (0) : __assert_fail ("(Context == DeclaratorContext::ForInit || Context == DeclaratorContext::SelectionInit) && \"Unexpected Declarator Context\""
, "clang/lib/Parse/ParseExprCXX.cpp", 1961, __extension__ __PRETTY_FUNCTION__
))
;
1962 DeclGroupPtrTy DG;
1963 SourceLocation DeclStart = ConsumeToken(), DeclEnd;
1964
1965 DG = ParseUsingDeclaration(Context, {}, DeclStart, DeclEnd, Attrs, AS_none);
1966 if (!DG)
1967 return DG;
1968
1969 Diag(DeclStart, !getLangOpts().CPlusPlus2b
1970 ? diag::ext_alias_in_init_statement
1971 : diag::warn_cxx20_alias_in_init_statement)
1972 << SourceRange(DeclStart, DeclEnd);
1973
1974 return DG;
1975}
1976
1977/// ParseCXXCondition - if/switch/while condition expression.
1978///
1979/// condition:
1980/// expression
1981/// type-specifier-seq declarator '=' assignment-expression
1982/// [C++11] type-specifier-seq declarator '=' initializer-clause
1983/// [C++11] type-specifier-seq declarator braced-init-list
1984/// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1985/// brace-or-equal-initializer
1986/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1987/// '=' assignment-expression
1988///
1989/// In C++1z, a condition may in some contexts be preceded by an
1990/// optional init-statement. This function will parse that too.
1991///
1992/// \param InitStmt If non-null, an init-statement is permitted, and if present
1993/// will be parsed and stored here.
1994///
1995/// \param Loc The location of the start of the statement that requires this
1996/// condition, e.g., the "for" in a for loop.
1997///
1998/// \param MissingOK Whether an empty condition is acceptable here. Otherwise
1999/// it is considered an error to be recovered from.
2000///
2001/// \param FRI If non-null, a for range declaration is permitted, and if
2002/// present will be parsed and stored here, and a null result will be returned.
2003///
2004/// \param EnterForConditionScope If true, enter a continue/break scope at the
2005/// appropriate moment for a 'for' loop.
2006///
2007/// \returns The parsed condition.
2008Sema::ConditionResult
2009Parser::ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc,
2010 Sema::ConditionKind CK, bool MissingOK,
2011 ForRangeInfo *FRI, bool EnterForConditionScope) {
2012 // Helper to ensure we always enter a continue/break scope if requested.
2013 struct ForConditionScopeRAII {
2014 Scope *S;
2015 void enter(bool IsConditionVariable) {
2016 if (S) {
2017 S->AddFlags(Scope::BreakScope | Scope::ContinueScope);
2018 S->setIsConditionVarScope(IsConditionVariable);
2019 }
2020 }
2021 ~ForConditionScopeRAII() {
2022 if (S)
2023 S->setIsConditionVarScope(false);
2024 }
2025 } ForConditionScope{EnterForConditionScope
7.1
'EnterForConditionScope' is false
? getCurScope() : nullptr};
1
Assuming 'EnterForConditionScope' is false
2
'?' condition is false
8
'?' condition is false
2026
2027 ParenBraceBracketBalancer BalancerRAIIObj(*this);
2028 PreferredType.enterCondition(Actions, Tok.getLocation());
2029
2030 if (Tok.is(tok::code_completion)) {
3
Taking false branch
9
Taking false branch
2031 cutOffParsing();
2032 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
2033 return Sema::ConditionError();
2034 }
2035
2036 ParsedAttributes attrs(AttrFactory);
2037 MaybeParseCXX11Attributes(attrs);
2038
2039 const auto WarnOnInit = [this, &CK] {
2040 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
2041 ? diag::warn_cxx14_compat_init_statement
2042 : diag::ext_init_statement)
2043 << (CK == Sema::ConditionKind::Switch);
2044 };
2045
2046 // Determine what kind of thing we have.
2047 switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
4
Control jumps to 'case InitStmtDecl:' at line 2085
10
Control jumps to 'case InitStmtDecl:' at line 2085
2048 case ConditionOrInitStatement::Expression: {
2049 // If this is a for loop, we're entering its condition.
2050 ForConditionScope.enter(/*IsConditionVariable=*/false);
2051
2052 ProhibitAttributes(attrs);
2053
2054 // We can have an empty expression here.
2055 // if (; true);
2056 if (InitStmt && Tok.is(tok::semi)) {
2057 WarnOnInit();
2058 SourceLocation SemiLoc = Tok.getLocation();
2059 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
2060 Diag(SemiLoc, diag::warn_empty_init_statement)
2061 << (CK == Sema::ConditionKind::Switch)
2062 << FixItHint::CreateRemoval(SemiLoc);
2063 }
2064 ConsumeToken();
2065 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
2066 return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
2067 }
2068
2069 // Parse the expression.
2070 ExprResult Expr = ParseExpression(); // expression
2071 if (Expr.isInvalid())
2072 return Sema::ConditionError();
2073
2074 if (InitStmt && Tok.is(tok::semi)) {
2075 WarnOnInit();
2076 *InitStmt = Actions.ActOnExprStmt(Expr.get());
2077 ConsumeToken();
2078 return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
2079 }
2080
2081 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK,
2082 MissingOK);
2083 }
2084
2085 case ConditionOrInitStatement::InitStmtDecl: {
2086 WarnOnInit();
2087 DeclGroupPtrTy DG;
2088 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2089 if (Tok.is(tok::kw_using))
5
Taking false branch
11
Taking true branch
2090 DG = ParseAliasDeclarationInInitStatement(
2091 DeclaratorContext::SelectionInit, attrs);
2092 else {
2093 ParsedAttributes DeclSpecAttrs(AttrFactory);
2094 DG = ParseSimpleDeclaration(DeclaratorContext::SelectionInit, DeclEnd,
2095 attrs, DeclSpecAttrs, /*RequireSemi=*/true);
2096 }
2097 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
12
Called C++ object pointer is null
2098 return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
6
Passing null pointer value via 1st parameter 'InitStmt'
7
Calling 'Parser::ParseCXXCondition'
2099 }
2100
2101 case ConditionOrInitStatement::ForRangeDecl: {
2102 // This is 'for (init-stmt; for-range-decl : range-expr)'.
2103 // We're not actually in a for loop yet, so 'break' and 'continue' aren't
2104 // permitted here.
2105 assert(FRI && "should not parse a for range declaration here")(static_cast <bool> (FRI && "should not parse a for range declaration here"
) ? void (0) : __assert_fail ("FRI && \"should not parse a for range declaration here\""
, "clang/lib/Parse/ParseExprCXX.cpp", 2105, __extension__ __PRETTY_FUNCTION__
))
;
2106 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2107 ParsedAttributes DeclSpecAttrs(AttrFactory);
2108 DeclGroupPtrTy DG = ParseSimpleDeclaration(
2109 DeclaratorContext::ForInit, DeclEnd, attrs, DeclSpecAttrs, false, FRI);
2110 FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
2111 assert((FRI->ColonLoc.isValid() || !DG) &&(static_cast <bool> ((FRI->ColonLoc.isValid() || !DG
) && "cannot find for range declaration") ? void (0) :
__assert_fail ("(FRI->ColonLoc.isValid() || !DG) && \"cannot find for range declaration\""
, "clang/lib/Parse/ParseExprCXX.cpp", 2112, __extension__ __PRETTY_FUNCTION__
))
2112 "cannot find for range declaration")(static_cast <bool> ((FRI->ColonLoc.isValid() || !DG
) && "cannot find for range declaration") ? void (0) :
__assert_fail ("(FRI->ColonLoc.isValid() || !DG) && \"cannot find for range declaration\""
, "clang/lib/Parse/ParseExprCXX.cpp", 2112, __extension__ __PRETTY_FUNCTION__
))
;
2113 return Sema::ConditionResult();
2114 }
2115
2116 case ConditionOrInitStatement::ConditionDecl:
2117 case ConditionOrInitStatement::Error:
2118 break;
2119 }
2120
2121 // If this is a for loop, we're entering its condition.
2122 ForConditionScope.enter(/*IsConditionVariable=*/true);
2123
2124 // type-specifier-seq
2125 DeclSpec DS(AttrFactory);
2126 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
2127
2128 // declarator
2129 Declarator DeclaratorInfo(DS, attrs, DeclaratorContext::Condition);
2130 ParseDeclarator(DeclaratorInfo);
2131
2132 // simple-asm-expr[opt]
2133 if (Tok.is(tok::kw_asm)) {
2134 SourceLocation Loc;
2135 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2136 if (AsmLabel.isInvalid()) {
2137 SkipUntil(tok::semi, StopAtSemi);
2138 return Sema::ConditionError();
2139 }
2140 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2141 DeclaratorInfo.SetRangeEnd(Loc);
2142 }
2143
2144 // If attributes are present, parse them.
2145 MaybeParseGNUAttributes(DeclaratorInfo);
2146
2147 // Type-check the declaration itself.
2148 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
2149 DeclaratorInfo);
2150 if (Dcl.isInvalid())
2151 return Sema::ConditionError();
2152 Decl *DeclOut = Dcl.get();
2153
2154 // '=' assignment-expression
2155 // If a '==' or '+=' is found, suggest a fixit to '='.
2156 bool CopyInitialization = isTokenEqualOrEqualTypo();
2157 if (CopyInitialization)
2158 ConsumeToken();
2159
2160 ExprResult InitExpr = ExprError();
2161 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2162 Diag(Tok.getLocation(),
2163 diag::warn_cxx98_compat_generalized_initializer_lists);
2164 InitExpr = ParseBraceInitializer();
2165 } else if (CopyInitialization) {
2166 PreferredType.enterVariableInit(Tok.getLocation(), DeclOut);
2167 InitExpr = ParseAssignmentExpression();
2168 } else if (Tok.is(tok::l_paren)) {
2169 // This was probably an attempt to initialize the variable.
2170 SourceLocation LParen = ConsumeParen(), RParen = LParen;
2171 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
2172 RParen = ConsumeParen();
2173 Diag(DeclOut->getLocation(),
2174 diag::err_expected_init_in_condition_lparen)
2175 << SourceRange(LParen, RParen);
2176 } else {
2177 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
2178 }
2179
2180 if (!InitExpr.isInvalid())
2181 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
2182 else
2183 Actions.ActOnInitializerError(DeclOut);
2184
2185 Actions.FinalizeDeclaration(DeclOut);
2186 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
2187}
2188
2189/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
2190/// This should only be called when the current token is known to be part of
2191/// simple-type-specifier.
2192///
2193/// simple-type-specifier:
2194/// '::'[opt] nested-name-specifier[opt] type-name
2195/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
2196/// char
2197/// wchar_t
2198/// bool
2199/// short
2200/// int
2201/// long
2202/// signed
2203/// unsigned
2204/// float
2205/// double
2206/// void
2207/// [GNU] typeof-specifier
2208/// [C++0x] auto [TODO]
2209///
2210/// type-name:
2211/// class-name
2212/// enum-name
2213/// typedef-name
2214///
2215void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
2216 DS.SetRangeStart(Tok.getLocation());
2217 const char *PrevSpec;
2218 unsigned DiagID;
2219 SourceLocation Loc = Tok.getLocation();
2220 const clang::PrintingPolicy &Policy =
2221 Actions.getASTContext().getPrintingPolicy();
2222
2223 switch (Tok.getKind()) {
2224 case tok::identifier: // foo::bar
2225 case tok::coloncolon: // ::foo::bar
2226 llvm_unreachable("Annotation token should already be formed!")::llvm::llvm_unreachable_internal("Annotation token should already be formed!"
, "clang/lib/Parse/ParseExprCXX.cpp", 2226)
;
2227 default:
2228 llvm_unreachable("Not a simple-type-specifier token!")::llvm::llvm_unreachable_internal("Not a simple-type-specifier token!"
, "clang/lib/Parse/ParseExprCXX.cpp", 2228)
;
2229
2230 // type-name
2231 case tok::annot_typename: {
2232 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
2233 getTypeAnnotation(Tok), Policy);
2234 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2235 ConsumeAnnotationToken();
2236
2237 DS.Finish(Actions, Policy);
2238 return;
2239 }
2240
2241 case tok::kw__ExtInt:
2242 case tok::kw__BitInt: {
2243 DiagnoseBitIntUse(Tok);
2244 ExprResult ER = ParseExtIntegerArgument();
2245 if (ER.isInvalid())
2246 DS.SetTypeSpecError();
2247 else
2248 DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
2249
2250 // Do this here because we have already consumed the close paren.
2251 DS.SetRangeEnd(PrevTokLocation);
2252 DS.Finish(Actions, Policy);
2253 return;
2254 }
2255
2256 // builtin types
2257 case tok::kw_short:
2258 DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec, DiagID,
2259 Policy);
2260 break;
2261 case tok::kw_long:
2262 DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec, DiagID,
2263 Policy);
2264 break;
2265 case tok::kw___int64:
2266 DS.SetTypeSpecWidth(TypeSpecifierWidth::LongLong, Loc, PrevSpec, DiagID,
2267 Policy);
2268 break;
2269 case tok::kw_signed:
2270 DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
2271 break;
2272 case tok::kw_unsigned:
2273 DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec, DiagID);
2274 break;
2275 case tok::kw_void:
2276 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
2277 break;
2278 case tok::kw_auto:
2279 DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID, Policy);
2280 break;
2281 case tok::kw_char:
2282 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
2283 break;
2284 case tok::kw_int:
2285 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
2286 break;
2287 case tok::kw___int128:
2288 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
2289 break;
2290 case tok::kw___bf16:
2291 DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec, DiagID, Policy);
2292 break;
2293 case tok::kw_half:
2294 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
2295 break;
2296 case tok::kw_float:
2297 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
2298 break;
2299 case tok::kw_double:
2300 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
2301 break;
2302 case tok::kw__Float16:
2303 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
2304 break;
2305 case tok::kw___float128:
2306 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
2307 break;
2308 case tok::kw___ibm128:
2309 DS.SetTypeSpecType(DeclSpec::TST_ibm128, Loc, PrevSpec, DiagID, Policy);
2310 break;
2311 case tok::kw_wchar_t:
2312 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
2313 break;
2314 case tok::kw_char8_t:
2315 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
2316 break;
2317 case tok::kw_char16_t:
2318 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
2319 break;
2320 case tok::kw_char32_t:
2321 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
2322 break;
2323 case tok::kw_bool:
2324 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
2325 break;
2326#define GENERIC_IMAGE_TYPE(ImgType, Id) \
2327 case tok::kw_##ImgType##_t: \
2328 DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \
2329 Policy); \
2330 break;
2331#include "clang/Basic/OpenCLImageTypes.def"
2332
2333 case tok::annot_decltype:
2334 case tok::kw_decltype:
2335 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
2336 return DS.Finish(Actions, Policy);
2337
2338 // GNU typeof support.
2339 case tok::kw_typeof:
2340 ParseTypeofSpecifier(DS);
2341 DS.Finish(Actions, Policy);
2342 return;
2343 }
2344 ConsumeAnyToken();
2345 DS.SetRangeEnd(PrevTokLocation);
2346 DS.Finish(Actions, Policy);
2347}
2348
2349/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2350/// [dcl.name]), which is a non-empty sequence of type-specifiers,
2351/// e.g., "const short int". Note that the DeclSpec is *not* finished
2352/// by parsing the type-specifier-seq, because these sequences are
2353/// typically followed by some form of declarator. Returns true and
2354/// emits diagnostics if this is not a type-specifier-seq, false
2355/// otherwise.
2356///
2357/// type-specifier-seq: [C++ 8.1]
2358/// type-specifier type-specifier-seq[opt]
2359///
2360bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS, DeclaratorContext Context) {
2361 ParseSpecifierQualifierList(DS, AS_none,
2362 getDeclSpecContextFromDeclaratorContext(Context));
2363 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
2364 return false;
2365}
2366
2367/// Finish parsing a C++ unqualified-id that is a template-id of
2368/// some form.
2369///
2370/// This routine is invoked when a '<' is encountered after an identifier or
2371/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2372/// whether the unqualified-id is actually a template-id. This routine will
2373/// then parse the template arguments and form the appropriate template-id to
2374/// return to the caller.
2375///
2376/// \param SS the nested-name-specifier that precedes this template-id, if
2377/// we're actually parsing a qualified-id.
2378///
2379/// \param ObjectType if this unqualified-id occurs within a member access
2380/// expression, the type of the base object whose member is being accessed.
2381///
2382/// \param ObjectHadErrors this unqualified-id occurs within a member access
2383/// expression, indicates whether the original subexpressions had any errors.
2384///
2385/// \param Name for constructor and destructor names, this is the actual
2386/// identifier that may be a template-name.
2387///
2388/// \param NameLoc the location of the class-name in a constructor or
2389/// destructor.
2390///
2391/// \param EnteringContext whether we're entering the scope of the
2392/// nested-name-specifier.
2393///
2394/// \param Id as input, describes the template-name or operator-function-id
2395/// that precedes the '<'. If template arguments were parsed successfully,
2396/// will be updated with the template-id.
2397///
2398/// \param AssumeTemplateId When true, this routine will assume that the name
2399/// refers to a template without performing name lookup to verify.
2400///
2401/// \returns true if a parse error occurred, false otherwise.
2402bool Parser::ParseUnqualifiedIdTemplateId(
2403 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors,
2404 SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc,
2405 bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId) {
2406 assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id")(static_cast <bool> (Tok.is(tok::less) && "Expected '<' to finish parsing a template-id"
) ? void (0) : __assert_fail ("Tok.is(tok::less) && \"Expected '<' to finish parsing a template-id\""
, "clang/lib/Parse/ParseExprCXX.cpp", 2406, __extension__ __PRETTY_FUNCTION__
))
;
2407
2408 TemplateTy Template;
2409 TemplateNameKind TNK = TNK_Non_template;
2410 switch (Id.getKind()) {
2411 case UnqualifiedIdKind::IK_Identifier:
2412 case UnqualifiedIdKind::IK_OperatorFunctionId:
2413 case UnqualifiedIdKind::IK_LiteralOperatorId:
2414 if (AssumeTemplateId) {
2415 // We defer the injected-class-name checks until we've found whether
2416 // this template-id is used to form a nested-name-specifier or not.
2417 TNK = Actions.ActOnTemplateName(getCurScope(), SS, TemplateKWLoc, Id,
2418 ObjectType, EnteringContext, Template,
2419 /*AllowInjectedClassName*/ true);
2420 } else {
2421 bool MemberOfUnknownSpecialization;
2422 TNK = Actions.isTemplateName(getCurScope(), SS,
2423 TemplateKWLoc.isValid(), Id,
2424 ObjectType, EnteringContext, Template,
2425 MemberOfUnknownSpecialization);
2426 // If lookup found nothing but we're assuming that this is a template
2427 // name, double-check that makes sense syntactically before committing
2428 // to it.
2429 if (TNK == TNK_Undeclared_template &&
2430 isTemplateArgumentList(0) == TPResult::False)
2431 return false;
2432
2433 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2434 ObjectType && isTemplateArgumentList(0) == TPResult::True) {
2435 // If we had errors before, ObjectType can be dependent even without any
2436 // templates, do not report missing template keyword in that case.
2437 if (!ObjectHadErrors) {
2438 // We have something like t->getAs<T>(), where getAs is a
2439 // member of an unknown specialization. However, this will only
2440 // parse correctly as a template, so suggest the keyword 'template'
2441 // before 'getAs' and treat this as a dependent template name.
2442 std::string Name;
2443 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
2444 Name = std::string(Id.Identifier->getName());
2445 else {
2446 Name = "operator ";
2447 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
2448 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2449 else
2450 Name += Id.Identifier->getName();
2451 }
2452 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2453 << Name
2454 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2455 }
2456 TNK = Actions.ActOnTemplateName(
2457 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2458 Template, /*AllowInjectedClassName*/ true);
2459 } else if (TNK == TNK_Non_template) {
2460 return false;
2461 }
2462 }
2463 break;
2464
2465 case UnqualifiedIdKind::IK_ConstructorName: {
2466 UnqualifiedId TemplateName;
2467 bool MemberOfUnknownSpecialization;
2468 TemplateName.setIdentifier(Name, NameLoc);
2469 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2470 TemplateName, ObjectType,
2471 EnteringContext, Template,
2472 MemberOfUnknownSpecialization);
2473 if (TNK == TNK_Non_template)
2474 return false;
2475 break;
2476 }
2477
2478 case UnqualifiedIdKind::IK_DestructorName: {
2479 UnqualifiedId TemplateName;
2480 bool MemberOfUnknownSpecialization;
2481 TemplateName.setIdentifier(Name, NameLoc);
2482 if (ObjectType) {
2483 TNK = Actions.ActOnTemplateName(
2484 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2485 EnteringContext, Template, /*AllowInjectedClassName*/ true);
2486 } else {
2487 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2488 TemplateName, ObjectType,
2489 EnteringContext, Template,
2490 MemberOfUnknownSpecialization);
2491
2492 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2493 Diag(NameLoc, diag::err_destructor_template_id)
2494 << Name << SS.getRange();
2495 // Carry on to parse the template arguments before bailing out.
2496 }
2497 }
2498 break;
2499 }
2500
2501 default:
2502 return false;
2503 }
2504
2505 // Parse the enclosed template argument list.
2506 SourceLocation LAngleLoc, RAngleLoc;
2507 TemplateArgList TemplateArgs;
2508 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs, RAngleLoc,
2509 Template))
2510 return true;
2511
2512 // If this is a non-template, we already issued a diagnostic.
2513 if (TNK == TNK_Non_template)
2514 return true;
2515
2516 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2517 Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2518 Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
2519 // Form a parsed representation of the template-id to be stored in the
2520 // UnqualifiedId.
2521
2522 // FIXME: Store name for literal operator too.
2523 IdentifierInfo *TemplateII =
2524 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2525 : nullptr;
2526 OverloadedOperatorKind OpKind =
2527 Id.getKind() == UnqualifiedIdKind::IK_Identifier
2528 ? OO_None
2529 : Id.OperatorFunctionId.Operator;
2530
2531 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2532 TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2533 LAngleLoc, RAngleLoc, TemplateArgs, /*ArgsInvalid*/false, TemplateIds);
2534
2535 Id.setTemplateId(TemplateId);
2536 return false;
2537 }
2538
2539 // Bundle the template arguments together.
2540 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2541
2542 // Constructor and destructor names.
2543 TypeResult Type = Actions.ActOnTemplateIdType(
2544 getCurScope(), SS, TemplateKWLoc, Template, Name, NameLoc, LAngleLoc,
2545 TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true);
2546 if (Type.isInvalid())
2547 return true;
2548
2549 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
2550 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2551 else
2552 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2553
2554 return false;
2555}
2556
2557/// Parse an operator-function-id or conversion-function-id as part
2558/// of a C++ unqualified-id.
2559///
2560/// This routine is responsible only for parsing the operator-function-id or
2561/// conversion-function-id; it does not handle template arguments in any way.
2562///
2563/// \code
2564/// operator-function-id: [C++ 13.5]
2565/// 'operator' operator
2566///
2567/// operator: one of
2568/// new delete new[] delete[]
2569/// + - * / % ^ & | ~
2570/// ! = < > += -= *= /= %=
2571/// ^= &= |= << >> >>= <<= == !=
2572/// <= >= && || ++ -- , ->* ->
2573/// () [] <=>
2574///
2575/// conversion-function-id: [C++ 12.3.2]
2576/// operator conversion-type-id
2577///
2578/// conversion-type-id:
2579/// type-specifier-seq conversion-declarator[opt]
2580///
2581/// conversion-declarator:
2582/// ptr-operator conversion-declarator[opt]
2583/// \endcode
2584///
2585/// \param SS The nested-name-specifier that preceded this unqualified-id. If
2586/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2587///
2588/// \param EnteringContext whether we are entering the scope of the
2589/// nested-name-specifier.
2590///
2591/// \param ObjectType if this unqualified-id occurs within a member access
2592/// expression, the type of the base object whose member is being accessed.
2593///
2594/// \param Result on a successful parse, contains the parsed unqualified-id.
2595///
2596/// \returns true if parsing fails, false otherwise.
2597bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2598 ParsedType ObjectType,
2599 UnqualifiedId &Result) {
2600 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword")(static_cast <bool> (Tok.is(tok::kw_operator) &&
"Expected 'operator' keyword") ? void (0) : __assert_fail ("Tok.is(tok::kw_operator) && \"Expected 'operator' keyword\""
, "clang/lib/Parse/ParseExprCXX.cpp", 2600, __extension__ __PRETTY_FUNCTION__
))
;
2601
2602 // Consume the 'operator' keyword.
2603 SourceLocation KeywordLoc = ConsumeToken();
2604
2605 // Determine what kind of operator name we have.
2606 unsigned SymbolIdx = 0;
2607 SourceLocation SymbolLocations[3];
2608 OverloadedOperatorKind Op = OO_None;
2609 switch (Tok.getKind()) {
2610 case tok::kw_new:
2611 case tok::kw_delete: {
2612 bool isNew = Tok.getKind() == tok::kw_new;
2613 // Consume the 'new' or 'delete'.
2614 SymbolLocations[SymbolIdx++] = ConsumeToken();
2615 // Check for array new/delete.
2616 if (Tok.is(tok::l_square) &&
2617 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2618 // Consume the '[' and ']'.
2619 BalancedDelimiterTracker T(*this, tok::l_square);
2620 T.consumeOpen();
2621 T.consumeClose();
2622 if (T.getCloseLocation().isInvalid())
2623 return true;
2624
2625 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2626 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2627 Op = isNew? OO_Array_New : OO_Array_Delete;
2628 } else {
2629 Op = isNew? OO_New : OO_Delete;
2630 }
2631 break;
2632 }
2633
2634#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2635 case tok::Token: \
2636 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2637 Op = OO_##Name; \
2638 break;
2639#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2640#include "clang/Basic/OperatorKinds.def"
2641
2642 case tok::l_paren: {
2643 // Consume the '(' and ')'.
2644 BalancedDelimiterTracker T(*this, tok::l_paren);
2645 T.consumeOpen();
2646 T.consumeClose();
2647 if (T.getCloseLocation().isInvalid())
2648 return true;
2649
2650 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2651 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2652 Op = OO_Call;
2653 break;
2654 }
2655
2656 case tok::l_square: {
2657 // Consume the '[' and ']'.
2658 BalancedDelimiterTracker T(*this, tok::l_square);
2659 T.consumeOpen();
2660 T.consumeClose();
2661 if (T.getCloseLocation().isInvalid())
2662 return true;
2663
2664 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2665 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2666 Op = OO_Subscript;
2667 break;
2668 }
2669
2670 case tok::code_completion: {
2671 // Don't try to parse any further.
2672 cutOffParsing();
2673 // Code completion for the operator name.
2674 Actions.CodeCompleteOperatorName(getCurScope());
2675 return true;
2676 }
2677
2678 default:
2679 break;
2680 }
2681
2682 if (Op != OO_None) {
2683 // We have parsed an operator-function-id.
2684 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2685 return false;
2686 }
2687
2688 // Parse a literal-operator-id.
2689 //
2690 // literal-operator-id: C++11 [over.literal]
2691 // operator string-literal identifier
2692 // operator user-defined-string-literal
2693
2694 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2695 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2696
2697 SourceLocation DiagLoc;
2698 unsigned DiagId = 0;
2699
2700 // We're past translation phase 6, so perform string literal concatenation
2701 // before checking for "".
2702 SmallVector<Token, 4> Toks;
2703 SmallVector<SourceLocation, 4> TokLocs;
2704 while (isTokenStringLiteral()) {
2705 if (!Tok.is(tok::string_literal) && !DiagId) {
2706 // C++11 [over.literal]p1:
2707 // The string-literal or user-defined-string-literal in a
2708 // literal-operator-id shall have no encoding-prefix [...].
2709 DiagLoc = Tok.getLocation();
2710 DiagId = diag::err_literal_operator_string_prefix;
2711 }
2712 Toks.push_back(Tok);
2713 TokLocs.push_back(ConsumeStringToken());
2714 }
2715
2716 StringLiteralParser Literal(Toks, PP);
2717 if (Literal.hadError)
2718 return true;
2719
2720 // Grab the literal operator's suffix, which will be either the next token
2721 // or a ud-suffix from the string literal.
2722 bool IsUDSuffix = !Literal.getUDSuffix().empty();
2723 IdentifierInfo *II = nullptr;
2724 SourceLocation SuffixLoc;
2725 if (IsUDSuffix) {
2726 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2727 SuffixLoc =
2728 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2729 Literal.getUDSuffixOffset(),
2730 PP.getSourceManager(), getLangOpts());
2731 } else if (Tok.is(tok::identifier)) {
2732 II = Tok.getIdentifierInfo();
2733 SuffixLoc = ConsumeToken();
2734 TokLocs.push_back(SuffixLoc);
2735 } else {
2736 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2737 return true;
2738 }
2739
2740 // The string literal must be empty.
2741 if (!Literal.GetString().empty() || Literal.Pascal) {
2742 // C++11 [over.literal]p1:
2743 // The string-literal or user-defined-string-literal in a
2744 // literal-operator-id shall [...] contain no characters
2745 // other than the implicit terminating '\0'.
2746 DiagLoc = TokLocs.front();
2747 DiagId = diag::err_literal_operator_string_not_empty;
2748 }
2749
2750 if (DiagId) {
2751 // This isn't a valid literal-operator-id, but we think we know
2752 // what the user meant. Tell them what they should have written.
2753 SmallString<32> Str;
2754 Str += "\"\"";
2755 Str += II->getName();
2756 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2757 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2758 }
2759
2760 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2761
2762 return Actions.checkLiteralOperatorId(SS, Result, IsUDSuffix);
2763 }
2764
2765 // Parse a conversion-function-id.
2766 //
2767 // conversion-function-id: [C++ 12.3.2]
2768 // operator conversion-type-id
2769 //
2770 // conversion-type-id:
2771 // type-specifier-seq conversion-declarator[opt]
2772 //
2773 // conversion-declarator:
2774 // ptr-operator conversion-declarator[opt]
2775
2776 // Parse the type-specifier-seq.
2777 DeclSpec DS(AttrFactory);
2778 if (ParseCXXTypeSpecifierSeq(
2779 DS, DeclaratorContext::ConversionId)) // FIXME: ObjectType?
2780 return true;
2781
2782 // Parse the conversion-declarator, which is merely a sequence of
2783 // ptr-operators.
2784 Declarator D(DS, ParsedAttributesView::none(),
2785 DeclaratorContext::ConversionId);
2786 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2787
2788 // Finish up the type.
2789 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2790 if (Ty.isInvalid())
2791 return true;
2792
2793 // Note that this is a conversion-function-id.
2794 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2795 D.getSourceRange().getEnd());
2796 return false;
2797}
2798
2799/// Parse a C++ unqualified-id (or a C identifier), which describes the
2800/// name of an entity.
2801///
2802/// \code
2803/// unqualified-id: [C++ expr.prim.general]
2804/// identifier
2805/// operator-function-id
2806/// conversion-function-id
2807/// [C++0x] literal-operator-id [TODO]
2808/// ~ class-name
2809/// template-id
2810///
2811/// \endcode
2812///
2813/// \param SS The nested-name-specifier that preceded this unqualified-id. If
2814/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2815///
2816/// \param ObjectType if this unqualified-id occurs within a member access
2817/// expression, the type of the base object whose member is being accessed.
2818///
2819/// \param ObjectHadErrors if this unqualified-id occurs within a member access
2820/// expression, indicates whether the original subexpressions had any errors.
2821/// When true, diagnostics for missing 'template' keyword will be supressed.
2822///
2823/// \param EnteringContext whether we are entering the scope of the
2824/// nested-name-specifier.
2825///
2826/// \param AllowDestructorName whether we allow parsing of a destructor name.
2827///
2828/// \param AllowConstructorName whether we allow parsing a constructor name.
2829///
2830/// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2831///
2832/// \param Result on a successful parse, contains the parsed unqualified-id.
2833///
2834/// \returns true if parsing fails, false otherwise.
2835bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType,
2836 bool ObjectHadErrors, bool EnteringContext,
2837 bool AllowDestructorName,
2838 bool AllowConstructorName,
2839 bool AllowDeductionGuide,
2840 SourceLocation *TemplateKWLoc,
2841 UnqualifiedId &Result) {
2842 if (TemplateKWLoc)
2843 *TemplateKWLoc = SourceLocation();
2844
2845 // Handle 'A::template B'. This is for template-ids which have not
2846 // already been annotated by ParseOptionalCXXScopeSpecifier().
2847 bool TemplateSpecified = false;
2848 if (Tok.is(tok::kw_template)) {
2849 if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2850 TemplateSpecified = true;
2851 *TemplateKWLoc = ConsumeToken();
2852 } else {
2853 SourceLocation TemplateLoc = ConsumeToken();
2854 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2855 << FixItHint::CreateRemoval(TemplateLoc);
2856 }
2857 }
2858
2859 // unqualified-id:
2860 // identifier
2861 // template-id (when it hasn't already been annotated)
2862 if (Tok.is(tok::identifier)) {
2863 ParseIdentifier:
2864 // Consume the identifier.
2865 IdentifierInfo *Id = Tok.getIdentifierInfo();
2866 SourceLocation IdLoc = ConsumeToken();
2867
2868 if (!getLangOpts().CPlusPlus) {
2869 // If we're not in C++, only identifiers matter. Record the
2870 // identifier and return.
2871 Result.setIdentifier(Id, IdLoc);
2872 return false;
2873 }
2874
2875 ParsedTemplateTy TemplateName;
2876 if (AllowConstructorName &&
2877 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2878 // We have parsed a constructor name.
2879 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2880 EnteringContext);
2881 if (!Ty)
2882 return true;
2883 Result.setConstructorName(Ty, IdLoc, IdLoc);
2884 } else if (getLangOpts().CPlusPlus17 &&
2885 AllowDeductionGuide && SS.isEmpty() &&
2886 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2887 &TemplateName)) {
2888 // We have parsed a template-name naming a deduction guide.
2889 Result.setDeductionGuideName(TemplateName, IdLoc);
2890 } else {
2891 // We have parsed an identifier.
2892 Result.setIdentifier(Id, IdLoc);
2893 }
2894
2895 // If the next token is a '<', we may have a template.
2896 TemplateTy Template;
2897 if (Tok.is(tok::less))
2898 return ParseUnqualifiedIdTemplateId(
2899 SS, ObjectType, ObjectHadErrors,
2900 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2901 EnteringContext, Result, TemplateSpecified);
2902 else if (TemplateSpecified &&
2903 Actions.ActOnTemplateName(
2904 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2905 EnteringContext, Template,
2906 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2907 return true;
2908
2909 return false;
2910 }
2911
2912 // unqualified-id:
2913 // template-id (already parsed and annotated)
2914 if (Tok.is(tok::annot_template_id)) {
2915 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2916
2917 // FIXME: Consider passing invalid template-ids on to callers; they may
2918 // be able to recover better than we can.
2919 if (TemplateId->isInvalid()) {
2920 ConsumeAnnotationToken();
2921 return true;
2922 }
2923
2924 // If the template-name names the current class, then this is a constructor
2925 if (AllowConstructorName && TemplateId->Name &&
2926 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2927 if (SS.isSet()) {
2928 // C++ [class.qual]p2 specifies that a qualified template-name
2929 // is taken as the constructor name where a constructor can be
2930 // declared. Thus, the template arguments are extraneous, so
2931 // complain about them and remove them entirely.
2932 Diag(TemplateId->TemplateNameLoc,
2933 diag::err_out_of_line_constructor_template_id)
2934 << TemplateId->Name
2935 << FixItHint::CreateRemoval(
2936 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2937 ParsedType Ty = Actions.getConstructorName(
2938 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2939 EnteringContext);
2940 if (!Ty)
2941 return true;
2942 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2943 TemplateId->RAngleLoc);
2944 ConsumeAnnotationToken();
2945 return false;
2946 }
2947
2948 Result.setConstructorTemplateId(TemplateId);
2949 ConsumeAnnotationToken();
2950 return false;
2951 }
2952
2953 // We have already parsed a template-id; consume the annotation token as
2954 // our unqualified-id.
2955 Result.setTemplateId(TemplateId);
2956 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2957 if (TemplateLoc.isValid()) {
2958 if (TemplateKWLoc && (ObjectType || SS.isSet()))
2959 *TemplateKWLoc = TemplateLoc;
2960 else
2961 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2962 << FixItHint::CreateRemoval(TemplateLoc);
2963 }
2964 ConsumeAnnotationToken();
2965 return false;
2966 }
2967
2968 // unqualified-id:
2969 // operator-function-id
2970 // conversion-function-id
2971 if (Tok.is(tok::kw_operator)) {
2972 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2973 return true;
2974
2975 // If we have an operator-function-id or a literal-operator-id and the next
2976 // token is a '<', we may have a
2977 //
2978 // template-id:
2979 // operator-function-id < template-argument-list[opt] >
2980 TemplateTy Template;
2981 if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2982 Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
2983 Tok.is(tok::less))
2984 return ParseUnqualifiedIdTemplateId(
2985 SS, ObjectType, ObjectHadErrors,
2986 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2987 SourceLocation(), EnteringContext, Result, TemplateSpecified);
2988 else if (TemplateSpecified &&
2989 Actions.ActOnTemplateName(
2990 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2991 EnteringContext, Template,
2992 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2993 return true;
2994
2995 return false;
2996 }
2997
2998 if (getLangOpts().CPlusPlus &&
2999 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
3000 // C++ [expr.unary.op]p10:
3001 // There is an ambiguity in the unary-expression ~X(), where X is a
3002 // class-name. The ambiguity is resolved in favor of treating ~ as a
3003 // unary complement rather than treating ~X as referring to a destructor.
3004
3005 // Parse the '~'.
3006 SourceLocation TildeLoc = ConsumeToken();
3007
3008 if (TemplateSpecified) {
3009 // C++ [temp.names]p3:
3010 // A name prefixed by the keyword template shall be a template-id [...]
3011 //
3012 // A template-id cannot begin with a '~' token. This would never work
3013 // anyway: x.~A<int>() would specify that the destructor is a template,
3014 // not that 'A' is a template.
3015 //
3016 // FIXME: Suggest replacing the attempted destructor name with a correct
3017 // destructor name and recover. (This is not trivial if this would become
3018 // a pseudo-destructor name).
3019 Diag(*TemplateKWLoc, diag::err_unexpected_template_in_destructor_name)
3020 << Tok.getLocation();
3021 return true;
3022 }
3023
3024 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
3025 DeclSpec DS(AttrFactory);
3026 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
3027 if (ParsedType Type =
3028 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
3029 Result.setDestructorName(TildeLoc, Type, EndLoc);
3030 return false;
3031 }
3032 return true;
3033 }
3034
3035 // Parse the class-name.
3036 if (Tok.isNot(tok::identifier)) {
3037 Diag(Tok, diag::err_destructor_tilde_identifier);
3038 return true;
3039 }
3040
3041 // If the user wrote ~T::T, correct it to T::~T.
3042 DeclaratorScopeObj DeclScopeObj(*this, SS);
3043 if (NextToken().is(tok::coloncolon)) {
3044 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
3045 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
3046 // it will confuse this recovery logic.
3047 ColonProtectionRAIIObject ColonRAII(*this, false);
3048
3049 if (SS.isSet()) {
3050 AnnotateScopeToken(SS, /*NewAnnotation*/true);
3051 SS.clear();
3052 }
3053 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, ObjectHadErrors,
3054 EnteringContext))
3055 return true;
3056 if (SS.isNotEmpty())
3057 ObjectType = nullptr;
3058 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
3059 !SS.isSet()) {
3060 Diag(TildeLoc, diag::err_destructor_tilde_scope);
3061 return true;
3062 }
3063
3064 // Recover as if the tilde had been written before the identifier.
3065 Diag(TildeLoc, diag::err_destructor_tilde_scope)
3066 << FixItHint::CreateRemoval(TildeLoc)
3067 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
3068
3069 // Temporarily enter the scope for the rest of this function.
3070 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
3071 DeclScopeObj.EnterDeclaratorScope();
3072 }
3073
3074 // Parse the class-name (or template-name in a simple-template-id).
3075 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
3076 SourceLocation ClassNameLoc = ConsumeToken();
3077
3078 if (Tok.is(tok::less)) {
3079 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
3080 return ParseUnqualifiedIdTemplateId(
3081 SS, ObjectType, ObjectHadErrors,
3082 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
3083 ClassNameLoc, EnteringContext, Result, TemplateSpecified);
3084 }
3085
3086 // Note that this is a destructor name.
3087 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
3088 ClassNameLoc, getCurScope(),
3089 SS, ObjectType,
3090 EnteringContext);
3091 if (!Ty)
3092 return true;
3093
3094 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
3095 return false;
3096 }
3097
3098 switch (Tok.getKind()) {
3099#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
3100#include "clang/Basic/TransformTypeTraits.def"
3101 if (!NextToken().is(tok::l_paren)) {
3102 Tok.setKind(tok::identifier);
3103 Diag(Tok, diag::ext_keyword_as_ident)
3104 << Tok.getIdentifierInfo()->getName() << 0;
3105 goto ParseIdentifier;
3106 }
3107 [[fallthrough]];
3108 default:
3109 Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus;
3110 return true;
3111 }
3112}
3113
3114/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
3115/// memory in a typesafe manner and call constructors.
3116///
3117/// This method is called to parse the new expression after the optional :: has
3118/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
3119/// is its location. Otherwise, "Start" is the location of the 'new' token.
3120///
3121/// new-expression:
3122/// '::'[opt] 'new' new-placement[opt] new-type-id
3123/// new-initializer[opt]
3124/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3125/// new-initializer[opt]
3126///
3127/// new-placement:
3128/// '(' expression-list ')'
3129///
3130/// new-type-id:
3131/// type-specifier-seq new-declarator[opt]
3132/// [GNU] attributes type-specifier-seq new-declarator[opt]
3133///
3134/// new-declarator:
3135/// ptr-operator new-declarator[opt]
3136/// direct-new-declarator
3137///
3138/// new-initializer:
3139/// '(' expression-list[opt] ')'
3140/// [C++0x] braced-init-list
3141///
3142ExprResult
3143Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
3144 assert(Tok.is(tok::kw_new) && "expected 'new' token")(static_cast <bool> (Tok.is(tok::kw_new) && "expected 'new' token"
) ? void (0) : __assert_fail ("Tok.is(tok::kw_new) && \"expected 'new' token\""
, "clang/lib/Parse/ParseExprCXX.cpp", 3144, __extension__ __PRETTY_FUNCTION__
))
;
3145 ConsumeToken(); // Consume 'new'
3146
3147 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
3148 // second form of new-expression. It can't be a new-type-id.
3149
3150 ExprVector PlacementArgs;
3151 SourceLocation PlacementLParen, PlacementRParen;
3152
3153 SourceRange TypeIdParens;
3154 DeclSpec DS(AttrFactory);
3155 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
3156 DeclaratorContext::CXXNew);
3157 if (Tok.is(tok::l_paren)) {
3158 // If it turns out to be a placement, we change the type location.
3159 BalancedDelimiterTracker T(*this, tok::l_paren);
3160 T.consumeOpen();
3161 PlacementLParen = T.getOpenLocation();
3162 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
3163 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3164 return ExprError();
3165 }
3166
3167 T.consumeClose();
3168 PlacementRParen = T.getCloseLocation();
3169 if (PlacementRParen.isInvalid()) {
3170 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3171 return ExprError();
3172 }
3173
3174 if (PlacementArgs.empty()) {
3175 // Reset the placement locations. There was no placement.
3176 TypeIdParens = T.getRange();
3177 PlacementLParen = PlacementRParen = SourceLocation();
3178 } else {
3179 // We still need the type.
3180 if (Tok.is(tok::l_paren)) {
3181 BalancedDelimiterTracker T(*this, tok::l_paren);
3182 T.consumeOpen();
3183 MaybeParseGNUAttributes(DeclaratorInfo);
3184 ParseSpecifierQualifierList(DS);
3185 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3186 ParseDeclarator(DeclaratorInfo);
3187 T.consumeClose();
3188 TypeIdParens = T.getRange();
3189 } else {
3190 MaybeParseGNUAttributes(DeclaratorInfo);
3191 if (ParseCXXTypeSpecifierSeq(DS))
3192 DeclaratorInfo.setInvalidType(true);
3193 else {
3194 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3195 ParseDeclaratorInternal(DeclaratorInfo,
3196 &Parser::ParseDirectNewDeclarator);
3197 }
3198 }
3199 }
3200 } else {
3201 // A new-type-id is a simplified type-id, where essentially the
3202 // direct-declarator is replaced by a direct-new-declarator.
3203 MaybeParseGNUAttributes(DeclaratorInfo);
3204 if (ParseCXXTypeSpecifierSeq(DS))
3205 DeclaratorInfo.setInvalidType(true);
3206 else {
3207 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3208 ParseDeclaratorInternal(DeclaratorInfo,
3209 &Parser::ParseDirectNewDeclarator);
3210 }
3211 }
3212 if (DeclaratorInfo.isInvalidType()) {
3213 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3214 return ExprError();
3215 }
3216
3217 ExprResult Initializer;
3218
3219 if (Tok.is(tok::l_paren)) {
3220 SourceLocation ConstructorLParen, ConstructorRParen;
3221 ExprVector ConstructorArgs;
3222 BalancedDelimiterTracker T(*this, tok::l_paren);
3223 T.consumeOpen();
3224 ConstructorLParen = T.getOpenLocation();
3225 if (Tok.isNot(tok::r_paren)) {
3226 CommaLocsTy CommaLocs;
3227 auto RunSignatureHelp = [&]() {
3228 ParsedType TypeRep =
3229 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
3230 QualType PreferredType;
3231 // ActOnTypeName might adjust DeclaratorInfo and return a null type even
3232 // the passing DeclaratorInfo is valid, e.g. running SignatureHelp on
3233 // `new decltype(invalid) (^)`.
3234 if (TypeRep)
3235 PreferredType = Actions.ProduceConstructorSignatureHelp(
3236 TypeRep.get()->getCanonicalTypeInternal(),
3237 DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen,
3238 /*Braced=*/false);
3239 CalledSignatureHelp = true;
3240 return PreferredType;
3241 };
3242 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
3243 PreferredType.enterFunctionArgument(Tok.getLocation(),
3244 RunSignatureHelp);
3245 })) {
3246 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3247 RunSignatureHelp();
3248 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3249 return ExprError();
3250 }
3251 }
3252 T.consumeClose();
3253 ConstructorRParen = T.getCloseLocation();
3254 if (ConstructorRParen.isInvalid()) {
3255 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3256 return ExprError();
3257 }
3258 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
3259 ConstructorRParen,
3260 ConstructorArgs);
3261 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
3262 Diag(Tok.getLocation(),
3263 diag::warn_cxx98_compat_generalized_initializer_lists);
3264 Initializer = ParseBraceInitializer();
3265 }
3266 if (Initializer.isInvalid())
3267 return Initializer;
3268
3269 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
3270 PlacementArgs, PlacementRParen,
3271 TypeIdParens, DeclaratorInfo, Initializer.get());
3272}
3273
3274/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
3275/// passed to ParseDeclaratorInternal.
3276///
3277/// direct-new-declarator:
3278/// '[' expression[opt] ']'
3279/// direct-new-declarator '[' constant-expression ']'
3280///
3281void Parser::ParseDirectNewDeclarator(Declarator &D) {
3282 // Parse the array dimensions.
3283 bool First = true;
3284 while (Tok.is(tok::l_square)) {
3285 // An array-size expression can't start with a lambda.
3286 if (CheckProhibitedCXX11Attribute())
3287 continue;
3288
3289 BalancedDelimiterTracker T(*this, tok::l_square);
3290 T.consumeOpen();
3291
3292 ExprResult Size =
3293 First ? (Tok.is(tok::r_square) ? ExprResult() : ParseExpression())
3294 : ParseConstantExpression();
3295 if (Size.isInvalid()) {
3296 // Recover
3297 SkipUntil(tok::r_square, StopAtSemi);
3298 return;
3299 }
3300 First = false;
3301
3302 T.consumeClose();
3303
3304 // Attributes here appertain to the array type. C++11 [expr.new]p5.
3305 ParsedAttributes Attrs(AttrFactory);
3306 MaybeParseCXX11Attributes(Attrs);
3307
3308 D.AddTypeInfo(DeclaratorChunk::getArray(0,
3309 /*isStatic=*/false, /*isStar=*/false,
3310 Size.get(), T.getOpenLocation(),
3311 T.getCloseLocation()),
3312 std::move(Attrs), T.getCloseLocation());
3313
3314 if (T.getCloseLocation().isInvalid())
3315 return;
3316 }
3317}
3318
3319/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
3320/// This ambiguity appears in the syntax of the C++ new operator.
3321///
3322/// new-expression:
3323/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3324/// new-initializer[opt]
3325///
3326/// new-placement:
3327/// '(' expression-list ')'
3328///
3329bool Parser::ParseExpressionListOrTypeId(
3330 SmallVectorImpl<Expr*> &PlacementArgs,
3331 Declarator &D) {
3332 // The '(' was already consumed.
3333 if (isTypeIdInParens()) {
3334 ParseSpecifierQualifierList(D.getMutableDeclSpec());
3335 D.SetSourceRange(D.getDeclSpec().getSourceRange());
3336 ParseDeclarator(D);
3337 return D.isInvalidType();
3338 }
3339
3340 // It's not a type, it has to be an expression list.
3341 // Discard the comma locations - ActOnCXXNew has enough parameters.
3342 CommaLocsTy CommaLocs;
3343 return ParseExpressionList(PlacementArgs, CommaLocs);
3344}
3345
3346/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
3347/// to free memory allocated by new.
3348///
3349/// This method is called to parse the 'delete' expression after the optional
3350/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
3351/// and "Start" is its location. Otherwise, "Start" is the location of the
3352/// 'delete' token.
3353///
3354/// delete-expression:
3355/// '::'[opt] 'delete' cast-expression
3356/// '::'[opt] 'delete' '[' ']' cast-expression
3357ExprResult
3358Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
3359 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword")(static_cast <bool> (Tok.is(tok::kw_delete) && "Expected 'delete' keyword"
) ? void (0) : __assert_fail ("Tok.is(tok::kw_delete) && \"Expected 'delete' keyword\""
, "clang/lib/Parse/ParseExprCXX.cpp", 3359, __extension__ __PRETTY_FUNCTION__
))
;
3360 ConsumeToken(); // Consume 'delete'
3361
3362 // Array delete?
3363 bool ArrayDelete = false;
3364 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
3365 // C++11 [expr.delete]p1:
3366 // Whenever the delete keyword is followed by empty square brackets, it
3367 // shall be interpreted as [array delete].
3368 // [Footnote: A lambda expression with a lambda-introducer that consists
3369 // of empty square brackets can follow the delete keyword if
3370 // the lambda expression is enclosed in parentheses.]
3371
3372 const Token Next = GetLookAheadToken(2);
3373
3374 // Basic lookahead to check if we have a lambda expression.
3375 if (Next.isOneOf(tok::l_brace, tok::less) ||
3376 (Next.is(tok::l_paren) &&
3377 (GetLookAheadToken(3).is(tok::r_paren) ||
3378 (GetLookAheadToken(3).is(tok::identifier) &&
3379 GetLookAheadToken(4).is(tok::identifier))))) {
3380 TentativeParsingAction TPA(*this);
3381 SourceLocation LSquareLoc = Tok.getLocation();
3382 SourceLocation RSquareLoc = NextToken().getLocation();
3383
3384 // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this
3385 // case.
3386 SkipUntil({tok::l_brace, tok::less}, StopBeforeMatch);
3387 SourceLocation RBraceLoc;
3388 bool EmitFixIt = false;
3389 if (Tok.is(tok::l_brace)) {
3390 ConsumeBrace();
3391 SkipUntil(tok::r_brace, StopBeforeMatch);
3392 RBraceLoc = Tok.getLocation();
3393 EmitFixIt = true;
3394 }
3395
3396 TPA.Revert();
3397
3398 if (EmitFixIt)
3399 Diag(Start, diag::err_lambda_after_delete)
3400 << SourceRange(Start, RSquareLoc)
3401 << FixItHint::CreateInsertion(LSquareLoc, "(")
3402 << FixItHint::CreateInsertion(
3403 Lexer::getLocForEndOfToken(
3404 RBraceLoc, 0, Actions.getSourceManager(), getLangOpts()),
3405 ")");
3406 else
3407 Diag(Start, diag::err_lambda_after_delete)
3408 << SourceRange(Start, RSquareLoc);
3409
3410 // Warn that the non-capturing lambda isn't surrounded by parentheses
3411 // to disambiguate it from 'delete[]'.
3412 ExprResult Lambda = ParseLambdaExpression();
3413 if (Lambda.isInvalid())
3414 return ExprError();
3415
3416 // Evaluate any postfix expressions used on the lambda.
3417 Lambda = ParsePostfixExpressionSuffix(Lambda);
3418 if (Lambda.isInvalid())
3419 return ExprError();
3420 return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
3421 Lambda.get());
3422 }
3423
3424 ArrayDelete = true;
3425 BalancedDelimiterTracker T(*this, tok::l_square);
3426
3427 T.consumeOpen();
3428 T.consumeClose();
3429 if (T.getCloseLocation().isInvalid())
3430 return ExprError();
3431 }
3432
3433 ExprResult Operand(ParseCastExpression(AnyCastExpr));
3434 if (Operand.isInvalid())
3435 return Operand;
3436
3437 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
3438}
3439
3440/// ParseRequiresExpression - Parse a C++2a requires-expression.
3441/// C++2a [expr.prim.req]p1
3442/// A requires-expression provides a concise way to express requirements on
3443/// template arguments. A requirement is one that can be checked by name
3444/// lookup (6.4) or by checking properties of types and expressions.
3445///
3446/// requires-expression:
3447/// 'requires' requirement-parameter-list[opt] requirement-body
3448///
3449/// requirement-parameter-list:
3450/// '(' parameter-declaration-clause[opt] ')'
3451///
3452/// requirement-body:
3453/// '{' requirement-seq '}'
3454///
3455/// requirement-seq:
3456/// requirement
3457/// requirement-seq requirement
3458///
3459/// requirement:
3460/// simple-requirement
3461/// type-requirement
3462/// compound-requirement
3463/// nested-requirement
3464ExprResult Parser::ParseRequiresExpression() {
3465 assert(Tok.is(tok::kw_requires) && "Expected 'requires' keyword")(static_cast <bool> (Tok.is(tok::kw_requires) &&
"Expected 'requires' keyword") ? void (0) : __assert_fail ("Tok.is(tok::kw_requires) && \"Expected 'requires' keyword\""
, "clang/lib/Parse/ParseExprCXX.cpp", 3465, __extension__ __PRETTY_FUNCTION__
))
;
3466 SourceLocation RequiresKWLoc = ConsumeToken(); // Consume 'requires'
3467
3468 llvm::SmallVector<ParmVarDecl *, 2> LocalParameterDecls;
3469 if (Tok.is(tok::l_paren)) {
3470 // requirement parameter list is present.
3471 ParseScope LocalParametersScope(this, Scope::FunctionPrototypeScope |
3472 Scope::DeclScope);
3473 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3474 Parens.consumeOpen();
3475 if (!Tok.is(tok::r_paren)) {
3476 ParsedAttributes FirstArgAttrs(getAttrFactory());
3477 SourceLocation EllipsisLoc;
3478 llvm::SmallVector<DeclaratorChunk::ParamInfo, 2> LocalParameters;
3479 ParseParameterDeclarationClause(DeclaratorContext::RequiresExpr,
3480 FirstArgAttrs, LocalParameters,
3481 EllipsisLoc);
3482 if (EllipsisLoc.isValid())
3483 Diag(EllipsisLoc, diag::err_requires_expr_parameter_list_ellipsis);
3484 for (auto &ParamInfo : LocalParameters)
3485 LocalParameterDecls.push_back(cast<ParmVarDecl>(ParamInfo.Param));
3486 }
3487 Parens.consumeClose();
3488 }
3489
3490 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3491 if (Braces.expectAndConsume())
3492 return ExprError();
3493
3494 // Start of requirement list
3495 llvm::SmallVector<concepts::Requirement *, 2> Requirements;
3496
3497 // C++2a [expr.prim.req]p2
3498 // Expressions appearing within a requirement-body are unevaluated operands.
3499 EnterExpressionEvaluationContext Ctx(
3500 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
3501
3502 ParseScope BodyScope(this, Scope::DeclScope);
3503 RequiresExprBodyDecl *Body = Actions.ActOnStartRequiresExpr(
3504 RequiresKWLoc, LocalParameterDecls, getCurScope());
3505
3506 if (Tok.is(tok::r_brace)) {
3507 // Grammar does not allow an empty body.
3508 // requirement-body:
3509 // { requirement-seq }
3510 // requirement-seq:
3511 // requirement
3512 // requirement-seq requirement
3513 Diag(Tok, diag::err_empty_requires_expr);
3514 // Continue anyway and produce a requires expr with no requirements.
3515 } else {
3516 while (!Tok.is(tok::r_brace)) {
3517 switch (Tok.getKind()) {
3518 case tok::l_brace: {
3519 // Compound requirement
3520 // C++ [expr.prim.req.compound]
3521 // compound-requirement:
3522 // '{' expression '}' 'noexcept'[opt]
3523 // return-type-requirement[opt] ';'
3524 // return-type-requirement:
3525 // trailing-return-type
3526 // '->' cv-qualifier-seq[opt] constrained-parameter
3527 // cv-qualifier-seq[opt] abstract-declarator[opt]
3528 BalancedDelimiterTracker ExprBraces(*this, tok::l_brace);
3529 ExprBraces.consumeOpen();
3530 ExprResult Expression =
3531 Actions.CorrectDelayedTyposInExpr(ParseExpression());
3532 if (!Expression.isUsable()) {
3533 ExprBraces.skipToEnd();
3534 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3535 break;
3536 }
3537 if (ExprBraces.consumeClose())
3538 ExprBraces.skipToEnd();
3539
3540 concepts::Requirement *Req = nullptr;
3541 SourceLocation NoexceptLoc;
3542 TryConsumeToken(tok::kw_noexcept, NoexceptLoc);
3543 if (Tok.is(tok::semi)) {
3544 Req = Actions.ActOnCompoundRequirement(Expression.get(), NoexceptLoc);
3545 if (Req)
3546 Requirements.push_back(Req);
3547 break;
3548 }
3549 if (!TryConsumeToken(tok::arrow))
3550 // User probably forgot the arrow, remind them and try to continue.
3551 Diag(Tok, diag::err_requires_expr_missing_arrow)
3552 << FixItHint::CreateInsertion(Tok.getLocation(), "->");
3553 // Try to parse a 'type-constraint'
3554 if (TryAnnotateTypeConstraint()) {
3555 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3556 break;
3557 }
3558 if (!isTypeConstraintAnnotation()) {
3559 Diag(Tok, diag::err_requires_expr_expected_type_constraint);
3560 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3561 break;
3562 }
3563 CXXScopeSpec SS;
3564 if (Tok.is(tok::annot_cxxscope)) {
3565 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3566 Tok.getAnnotationRange(),
3567 SS);
3568 ConsumeAnnotationToken();
3569 }
3570
3571 Req = Actions.ActOnCompoundRequirement(
3572 Expression.get(), NoexceptLoc, SS, takeTemplateIdAnnotation(Tok),
3573 TemplateParameterDepth);
3574 ConsumeAnnotationToken();
3575 if (Req)
3576 Requirements.push_back(Req);
3577 break;
3578 }
3579 default: {
3580 bool PossibleRequiresExprInSimpleRequirement = false;
3581 if (Tok.is(tok::kw_requires)) {
3582 auto IsNestedRequirement = [&] {
3583 RevertingTentativeParsingAction TPA(*this);
3584 ConsumeToken(); // 'requires'
3585 if (Tok.is(tok::l_brace))
3586 // This is a requires expression
3587 // requires (T t) {
3588 // requires { t++; };
3589 // ... ^
3590 // }
3591 return false;
3592 if (Tok.is(tok::l_paren)) {
3593 // This might be the parameter list of a requires expression
3594 ConsumeParen();
3595 auto Res = TryParseParameterDeclarationClause();
3596 if (Res != TPResult::False) {
3597 // Skip to the closing parenthesis
3598 // FIXME: Don't traverse these tokens twice (here and in
3599 // TryParseParameterDeclarationClause).
3600 unsigned Depth = 1;
3601 while (Depth != 0) {
3602 if (Tok.is(tok::l_paren))
3603 Depth++;
3604 else if (Tok.is(tok::r_paren))
3605 Depth--;
3606 ConsumeAnyToken();
3607 }
3608 // requires (T t) {
3609 // requires () ?
3610 // ... ^
3611 // - OR -
3612 // requires (int x) ?
3613 // ... ^
3614 // }
3615 if (Tok.is(tok::l_brace))
3616 // requires (...) {
3617 // ^ - a requires expression as a
3618 // simple-requirement.
3619 return false;
3620 }
3621 }
3622 return true;
3623 };
3624 if (IsNestedRequirement()) {
3625 ConsumeToken();
3626 // Nested requirement
3627 // C++ [expr.prim.req.nested]
3628 // nested-requirement:
3629 // 'requires' constraint-expression ';'
3630 ExprResult ConstraintExpr =
3631 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
3632 if (ConstraintExpr.isInvalid() || !ConstraintExpr.isUsable()) {
3633 SkipUntil(tok::semi, tok::r_brace,
3634 SkipUntilFlags::StopBeforeMatch);
3635 break;
3636 }
3637 if (auto *Req =
3638 Actions.ActOnNestedRequirement(ConstraintExpr.get()))
3639 Requirements.push_back(Req);
3640 else {
3641 SkipUntil(tok::semi, tok::r_brace,
3642 SkipUntilFlags::StopBeforeMatch);
3643 break;
3644 }
3645 break;
3646 } else
3647 PossibleRequiresExprInSimpleRequirement = true;
3648 } else if (Tok.is(tok::kw_typename)) {
3649 // This might be 'typename T::value_type;' (a type requirement) or
3650 // 'typename T::value_type{};' (a simple requirement).
3651 TentativeParsingAction TPA(*this);
3652
3653 // We need to consume the typename to allow 'requires { typename a; }'
3654 SourceLocation TypenameKWLoc = ConsumeToken();
3655 if (TryAnnotateOptionalCXXScopeToken()) {
3656 TPA.Commit();
3657 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3658 break;
3659 }
3660 CXXScopeSpec SS;
3661 if (Tok.is(tok::annot_cxxscope)) {
3662 Actions.RestoreNestedNameSpecifierAnnotation(
3663 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3664 ConsumeAnnotationToken();
3665 }
3666
3667 if (Tok.isOneOf(tok::identifier, tok::annot_template_id) &&
3668 !NextToken().isOneOf(tok::l_brace, tok::l_paren)) {
3669 TPA.Commit();
3670 SourceLocation NameLoc = Tok.getLocation();
3671 IdentifierInfo *II = nullptr;
3672 TemplateIdAnnotation *TemplateId = nullptr;
3673 if (Tok.is(tok::identifier)) {
3674 II = Tok.getIdentifierInfo();
3675 ConsumeToken();
3676 } else {
3677 TemplateId = takeTemplateIdAnnotation(Tok);
3678 ConsumeAnnotationToken();
3679 if (TemplateId->isInvalid())
3680 break;
3681 }
3682
3683 if (auto *Req = Actions.ActOnTypeRequirement(TypenameKWLoc, SS,
3684 NameLoc, II,
3685 TemplateId)) {
3686 Requirements.push_back(Req);
3687 }
3688 break;
3689 }
3690 TPA.Revert();
3691 }
3692 // Simple requirement
3693 // C++ [expr.prim.req.simple]
3694 // simple-requirement:
3695 // expression ';'
3696 SourceLocation StartLoc = Tok.getLocation();
3697 ExprResult Expression =
3698 Actions.CorrectDelayedTyposInExpr(ParseExpression());
3699 if (!Expression.isUsable()) {
3700 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3701 break;
3702 }
3703 if (!Expression.isInvalid() && PossibleRequiresExprInSimpleRequirement)
3704 Diag(StartLoc, diag::err_requires_expr_in_simple_requirement)
3705 << FixItHint::CreateInsertion(StartLoc, "requires");
3706 if (auto *Req = Actions.ActOnSimpleRequirement(Expression.get()))
3707 Requirements.push_back(Req);
3708 else {
3709 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3710 break;
3711 }
3712 // User may have tried to put some compound requirement stuff here
3713 if (Tok.is(tok::kw_noexcept)) {
3714 Diag(Tok, diag::err_requires_expr_simple_requirement_noexcept)
3715 << FixItHint::CreateInsertion(StartLoc, "{")
3716 << FixItHint::CreateInsertion(Tok.getLocation(), "}");
3717 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3718 break;
3719 }
3720 break;
3721 }
3722 }
3723 if (ExpectAndConsumeSemi(diag::err_expected_semi_requirement)) {
3724 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3725 TryConsumeToken(tok::semi);
3726 break;
3727 }
3728 }
3729 if (Requirements.empty()) {
3730 // Don't emit an empty requires expr here to avoid confusing the user with
3731 // other diagnostics quoting an empty requires expression they never
3732 // wrote.
3733 Braces.consumeClose();
3734 Actions.ActOnFinishRequiresExpr();
3735 return ExprError();
3736 }
3737 }
3738 Braces.consumeClose();
3739 Actions.ActOnFinishRequiresExpr();
3740 return Actions.ActOnRequiresExpr(RequiresKWLoc, Body, LocalParameterDecls,
3741 Requirements, Braces.getCloseLocation());
3742}
3743
3744static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
3745 switch (kind) {
3746 default: llvm_unreachable("Not a known type trait")::llvm::llvm_unreachable_internal("Not a known type trait", "clang/lib/Parse/ParseExprCXX.cpp"
, 3746)
;
3747#define TYPE_TRAIT_1(Spelling, Name, Key) \
3748case tok::kw_ ## Spelling: return UTT_ ## Name;
3749#define TYPE_TRAIT_2(Spelling, Name, Key) \
3750case tok::kw_ ## Spelling: return BTT_ ## Name;
3751#include "clang/Basic/TokenKinds.def"
3752#define TYPE_TRAIT_N(Spelling, Name, Key) \
3753 case tok::kw_ ## Spelling: return TT_ ## Name;
3754#include "clang/Basic/TokenKinds.def"
3755 }
3756}
3757
3758static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
3759 switch (kind) {
3760 default:
3761 llvm_unreachable("Not a known array type trait")::llvm::llvm_unreachable_internal("Not a known array type trait"
, "clang/lib/Parse/ParseExprCXX.cpp", 3761)
;
3762#define ARRAY_TYPE_TRAIT(Spelling, Name, Key) \
3763 case tok::kw_##Spelling: \
3764 return ATT_##Name;
3765#include "clang/Basic/TokenKinds.def"
3766 }
3767}
3768
3769static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
3770 switch (kind) {
3771 default:
3772 llvm_unreachable("Not a known unary expression trait.")::llvm::llvm_unreachable_internal("Not a known unary expression trait."
, "clang/lib/Parse/ParseExprCXX.cpp", 3772)
;
3773#define EXPRESSION_TRAIT(Spelling, Name, Key) \
3774 case tok::kw_##Spelling: \
3775 return ET_##Name;
3776#include "clang/Basic/TokenKinds.def"
3777 }
3778}
3779
3780/// Parse the built-in type-trait pseudo-functions that allow
3781/// implementation of the TR1/C++11 type traits templates.
3782///
3783/// primary-expression:
3784/// unary-type-trait '(' type-id ')'
3785/// binary-type-trait '(' type-id ',' type-id ')'
3786/// type-trait '(' type-id-seq ')'
3787///
3788/// type-id-seq:
3789/// type-id ...[opt] type-id-seq[opt]
3790///
3791ExprResult Parser::ParseTypeTrait() {
3792 tok::TokenKind Kind = Tok.getKind();
3793
3794 SourceLocation Loc = ConsumeToken();
3795
3796 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3797 if (Parens.expectAndConsume())
3798 return ExprError();
3799
3800 SmallVector<ParsedType, 2> Args;
3801 do {
3802 // Parse the next type.
3803 TypeResult Ty = ParseTypeName();
3804 if (Ty.isInvalid()) {
3805 Parens.skipToEnd();
3806 return ExprError();
3807 }
3808
3809 // Parse the ellipsis, if present.
3810 if (Tok.is(tok::ellipsis)) {
3811 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3812 if (Ty.isInvalid()) {
3813 Parens.skipToEnd();
3814 return ExprError();
3815 }
3816 }
3817
3818 // Add this type to the list of arguments.
3819 Args.push_back(Ty.get());
3820 } while (TryConsumeToken(tok::comma));
3821
3822 if (Parens.consumeClose())
3823 return ExprError();
3824
3825 SourceLocation EndLoc = Parens.getCloseLocation();
3826
3827 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3828}
3829
3830/// ParseArrayTypeTrait - Parse the built-in array type-trait
3831/// pseudo-functions.
3832///
3833/// primary-expression:
3834/// [Embarcadero] '__array_rank' '(' type-id ')'
3835/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3836///
3837ExprResult Parser::ParseArrayTypeTrait() {
3838 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3839 SourceLocation Loc = ConsumeToken();
3840
3841 BalancedDelimiterTracker T(*this, tok::l_paren);
3842 if (T.expectAndConsume())
3843 return ExprError();
3844
3845 TypeResult Ty = ParseTypeName();
3846 if (Ty.isInvalid()) {
3847 SkipUntil(tok::comma, StopAtSemi);
3848 SkipUntil(tok::r_paren, StopAtSemi);
3849 return ExprError();
3850 }
3851
3852 switch (ATT) {
3853 case ATT_ArrayRank: {
3854 T.consumeClose();
3855 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3856 T.getCloseLocation());
3857 }
3858 case ATT_ArrayExtent: {
3859 if (ExpectAndConsume(tok::comma)) {
3860 SkipUntil(tok::r_paren, StopAtSemi);
3861 return ExprError();
3862 }
3863
3864 ExprResult DimExpr = ParseExpression();
3865 T.consumeClose();
3866
3867 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3868 T.getCloseLocation());
3869 }
3870 }
3871 llvm_unreachable("Invalid ArrayTypeTrait!")::llvm::llvm_unreachable_internal("Invalid ArrayTypeTrait!", "clang/lib/Parse/ParseExprCXX.cpp"
, 3871)
;
3872}
3873
3874/// ParseExpressionTrait - Parse built-in expression-trait
3875/// pseudo-functions like __is_lvalue_expr( xxx ).
3876///
3877/// primary-expression:
3878/// [Embarcadero] expression-trait '(' expression ')'
3879///
3880ExprResult Parser::ParseExpressionTrait() {
3881 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3882 SourceLocation Loc = ConsumeToken();
3883
3884 BalancedDelimiterTracker T(*this, tok::l_paren);
3885 if (T.expectAndConsume())
3886 return ExprError();
3887
3888 ExprResult Expr = ParseExpression();
3889
3890 T.consumeClose();
3891
3892 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3893 T.getCloseLocation());
3894}
3895
3896
3897/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3898/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3899/// based on the context past the parens.
3900ExprResult
3901Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3902 ParsedType &CastTy,
3903 BalancedDelimiterTracker &Tracker,
3904 ColonProtectionRAIIObject &ColonProt) {
3905 assert(getLangOpts().CPlusPlus && "Should only be called for C++!")(static_cast <bool> (getLangOpts().CPlusPlus &&
"Should only be called for C++!") ? void (0) : __assert_fail
("getLangOpts().CPlusPlus && \"Should only be called for C++!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 3905, __extension__ __PRETTY_FUNCTION__
))
;
3906 assert(ExprType == CastExpr && "Compound literals are not ambiguous!")(static_cast <bool> (ExprType == CastExpr && "Compound literals are not ambiguous!"
) ? void (0) : __assert_fail ("ExprType == CastExpr && \"Compound literals are not ambiguous!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 3906, __extension__ __PRETTY_FUNCTION__
))
;
3907 assert(isTypeIdInParens() && "Not a type-id!")(static_cast <bool> (isTypeIdInParens() && "Not a type-id!"
) ? void (0) : __assert_fail ("isTypeIdInParens() && \"Not a type-id!\""
, "clang/lib/Parse/ParseExprCXX.cpp", 3907, __extension__ __PRETTY_FUNCTION__
))
;
3908
3909 ExprResult Result(true);
3910 CastTy = nullptr;
3911
3912 // We need to disambiguate a very ugly part of the C++ syntax:
3913 //
3914 // (T())x; - type-id
3915 // (T())*x; - type-id
3916 // (T())/x; - expression
3917 // (T()); - expression
3918 //
3919 // The bad news is that we cannot use the specialized tentative parser, since
3920 // it can only verify that the thing inside the parens can be parsed as
3921 // type-id, it is not useful for determining the context past the parens.
3922 //
3923 // The good news is that the parser can disambiguate this part without
3924 // making any unnecessary Action calls.
3925 //
3926 // It uses a scheme similar to parsing inline methods. The parenthesized
3927 // tokens are cached, the context that follows is determined (possibly by
3928 // parsing a cast-expression), and then we re-introduce the cached tokens
3929 // into the token stream and parse them appropriately.
3930
3931 ParenParseOption ParseAs;
3932 CachedTokens Toks;
3933
3934 // Store the tokens of the parentheses. We will parse them after we determine
3935 // the context that follows them.
3936 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3937 // We didn't find the ')' we expected.
3938 Tracker.consumeClose();
3939 return ExprError();
3940 }
3941
3942 if (Tok.is(tok::l_brace)) {
3943 ParseAs = CompoundLiteral;
3944 } else {
3945 bool NotCastExpr;
3946 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3947 NotCastExpr = true;
3948 } else {
3949 // Try parsing the cast-expression that may follow.
3950 // If it is not a cast-expression, NotCastExpr will be true and no token
3951 // will be consumed.
3952 ColonProt.restore();
3953 Result = ParseCastExpression(AnyCastExpr,
3954 false/*isAddressofOperand*/,
3955 NotCastExpr,
3956 // type-id has priority.
3957 IsTypeCast);
3958 }
3959
3960 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3961 // an expression.
3962 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3963 }
3964
3965 // Create a fake EOF to mark end of Toks buffer.
3966 Token AttrEnd;
3967 AttrEnd.startToken();
3968 AttrEnd.setKind(tok::eof);
3969 AttrEnd.setLocation(Tok.getLocation());
3970 AttrEnd.setEofData(Toks.data());
3971 Toks.push_back(AttrEnd);
3972
3973 // The current token should go after the cached tokens.
3974 Toks.push_back(Tok);
3975 // Re-enter the stored parenthesized tokens into the token stream, so we may
3976 // parse them now.
3977 PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true,
3978 /*IsReinject*/ true);
3979 // Drop the current token and bring the first cached one. It's the same token
3980 // as when we entered this function.
3981 ConsumeAnyToken();
3982
3983 if (ParseAs >= CompoundLiteral) {
3984 // Parse the type declarator.
3985 DeclSpec DS(AttrFactory);
3986 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
3987 DeclaratorContext::TypeName);
3988 {
3989 ColonProtectionRAIIObject InnerColonProtection(*this);
3990 ParseSpecifierQualifierList(DS);
3991 ParseDeclarator(DeclaratorInfo);
3992 }
3993
3994 // Match the ')'.
3995 Tracker.consumeClose();
3996 ColonProt.restore();
3997
3998 // Consume EOF marker for Toks buffer.
3999 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())(static_cast <bool> (Tok.is(tok::eof) && Tok.getEofData
() == AttrEnd.getEofData()) ? void (0) : __assert_fail ("Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData()"
, "clang/lib/Parse/ParseExprCXX.cpp", 3999, __extension__ __PRETTY_FUNCTION__
))
;
4000 ConsumeAnyToken();
4001
4002 if (ParseAs == CompoundLiteral) {
4003 ExprType = CompoundLiteral;
4004 if (DeclaratorInfo.isInvalidType())
4005 return ExprError();
4006
4007 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
4008 return ParseCompoundLiteralExpression(Ty.get(),
4009 Tracker.getOpenLocation(),
4010 Tracker.getCloseLocation());
4011 }
4012
4013 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
4014 assert(ParseAs == CastExpr)(static_cast <bool> (ParseAs == CastExpr) ? void (0) : __assert_fail
("ParseAs == CastExpr", "clang/lib/Parse/ParseExprCXX.cpp", 4014
, __extension__ __PRETTY_FUNCTION__))
;
4015
4016 if (DeclaratorInfo.isInvalidType())
4017 return ExprError();
4018
4019 // Result is what ParseCastExpression returned earlier.
4020 if (!Result.isInvalid())
4021 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
4022 DeclaratorInfo, CastTy,
4023 Tracker.getCloseLocation(), Result.get());
4024 return Result;
4025 }
4026
4027 // Not a compound literal, and not followed by a cast-expression.
4028 assert(ParseAs == SimpleExpr)(static_cast <bool> (ParseAs == SimpleExpr) ? void (0) :
__assert_fail ("ParseAs == SimpleExpr", "clang/lib/Parse/ParseExprCXX.cpp"
, 4028, __extension__ __PRETTY_FUNCTION__))
;
4029
4030 ExprType = SimpleExpr;
4031 Result = ParseExpression();
4032 if (!Result.isInvalid() && Tok.is(tok::r_paren))
4033 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
4034 Tok.getLocation(), Result.get());
4035
4036 // Match the ')'.
4037 if (Result.isInvalid()) {
4038 while (Tok.isNot(tok::eof))
4039 ConsumeAnyToken();
4040 assert(Tok.getEofData() == AttrEnd.getEofData())(static_cast <bool> (Tok.getEofData() == AttrEnd.getEofData
()) ? void (0) : __assert_fail ("Tok.getEofData() == AttrEnd.getEofData()"
, "clang/lib/Parse/ParseExprCXX.cpp", 4040, __extension__ __PRETTY_FUNCTION__
))
;
4041 ConsumeAnyToken();
4042 return ExprError();
4043 }
4044
4045 Tracker.consumeClose();
4046 // Consume EOF marker for Toks buffer.
4047 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData())(static_cast <bool> (Tok.is(tok::eof) && Tok.getEofData
() == AttrEnd.getEofData()) ? void (0) : __assert_fail ("Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData()"
, "clang/lib/Parse/ParseExprCXX.cpp", 4047, __extension__ __PRETTY_FUNCTION__
))
;
4048 ConsumeAnyToken();
4049 return Result;
4050}
4051
4052/// Parse a __builtin_bit_cast(T, E).
4053ExprResult Parser::ParseBuiltinBitCast() {
4054 SourceLocation KWLoc = ConsumeToken();
4055
4056 BalancedDelimiterTracker T(*this, tok::l_paren);
4057 if (T.expectAndConsume(diag::err_expected_lparen_after, "__builtin_bit_cast"))
4058 return ExprError();
4059
4060 // Parse the common declaration-specifiers piece.
4061 DeclSpec DS(AttrFactory);
4062 ParseSpecifierQualifierList(DS);
4063
4064 // Parse the abstract-declarator, if present.
4065 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
4066 DeclaratorContext::TypeName);
4067 ParseDeclarator(DeclaratorInfo);
4068
4069 if (ExpectAndConsume(tok::comma)) {
4070 Diag(Tok.getLocation(), diag::err_expected) << tok::comma;
4071 SkipUntil(tok::r_paren, StopAtSemi);
4072 return ExprError();
4073 }
4074
4075 ExprResult Operand = ParseExpression();
4076
4077 if (T.consumeClose())
4078 return ExprError();
4079
4080 if (Operand.isInvalid() || DeclaratorInfo.isInvalidType())
4081 return ExprError();
4082
4083 return Actions.ActOnBuiltinBitCastExpr(KWLoc, DeclaratorInfo, Operand,
4084 T.getCloseLocation());
4085}