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