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