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