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