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