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