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

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