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