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