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

source code of clang/lib/Parse/ParseExprCXX.cpp