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