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