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