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