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