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