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