clang 19.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"
20#include "clang/Parse/Parser.h"
22#include "clang/Sema/DeclSpec.h"
25#include "clang/Sema/Scope.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/ErrorHandling.h"
29#include <numeric>
30
31using namespace clang;
32
34 switch (Kind) {
35 // template name
36 case tok::unknown: return 0;
37 // casts
38 case tok::kw_addrspace_cast: return 1;
39 case tok::kw_const_cast: return 2;
40 case tok::kw_dynamic_cast: return 3;
41 case tok::kw_reinterpret_cast: return 4;
42 case tok::kw_static_cast: return 5;
43 default:
44 llvm_unreachable("Unknown type for digraph error message.");
45 }
46}
47
48// Are the two tokens adjacent in the same source file?
49bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
51 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
52 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
53 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
54}
55
56// Suggest fixit for "<::" after a cast.
57static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
58 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
59 // Pull '<:' and ':' off token stream.
60 if (!AtDigraph)
61 PP.Lex(DigraphToken);
62 PP.Lex(ColonToken);
63
65 Range.setBegin(DigraphToken.getLocation());
66 Range.setEnd(ColonToken.getLocation());
67 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
70
71 // Update token information to reflect their change in token type.
72 ColonToken.setKind(tok::coloncolon);
73 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
74 ColonToken.setLength(2);
75 DigraphToken.setKind(tok::less);
76 DigraphToken.setLength(1);
77
78 // Push new tokens back to token stream.
79 PP.EnterToken(ColonToken, /*IsReinject*/ true);
80 if (!AtDigraph)
81 PP.EnterToken(DigraphToken, /*IsReinject*/ true);
82}
83
84// Check for '<::' which should be '< ::' instead of '[:' when following
85// a template name.
86void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
87 bool EnteringContext,
89 if (!Next.is(tok::l_square) || Next.getLength() != 2)
90 return;
91
92 Token SecondToken = GetLookAheadToken(2);
93 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
94 return;
95
96 TemplateTy Template;
98 TemplateName.setIdentifier(&II, Tok.getLocation());
99 bool MemberOfUnknownSpecialization;
100 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
101 TemplateName, ObjectType, EnteringContext,
102 Template, MemberOfUnknownSpecialization))
103 return;
104
105 FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
106 /*AtDigraph*/false);
107}
108
109/// Parse global scope or nested-name-specifier if present.
110///
111/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
112/// may be preceded by '::'). Note that this routine will not parse ::new or
113/// ::delete; it will just leave them in the token stream.
114///
115/// '::'[opt] nested-name-specifier
116/// '::'
117///
118/// nested-name-specifier:
119/// type-name '::'
120/// namespace-name '::'
121/// nested-name-specifier identifier '::'
122/// nested-name-specifier 'template'[opt] simple-template-id '::'
123///
124///
125/// \param SS the scope specifier that will be set to the parsed
126/// nested-name-specifier (or empty)
127///
128/// \param ObjectType if this nested-name-specifier is being parsed following
129/// the "." or "->" of a member access expression, this parameter provides the
130/// type of the object whose members are being accessed.
131///
132/// \param ObjectHadErrors if this unqualified-id occurs within a member access
133/// expression, indicates whether the original subexpressions had any errors.
134/// When true, diagnostics for missing 'template' keyword will be supressed.
135///
136/// \param EnteringContext whether we will be entering into the context of
137/// the nested-name-specifier after parsing it.
138///
139/// \param MayBePseudoDestructor When non-NULL, points to a flag that
140/// indicates whether this nested-name-specifier may be part of a
141/// pseudo-destructor name. In this case, the flag will be set false
142/// if we don't actually end up parsing a destructor name. Moreover,
143/// if we do end up determining that we are parsing a destructor name,
144/// the last component of the nested-name-specifier is not parsed as
145/// part of the scope specifier.
146///
147/// \param IsTypename If \c true, this nested-name-specifier is known to be
148/// part of a type name. This is used to improve error recovery.
149///
150/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
151/// filled in with the leading identifier in the last component of the
152/// nested-name-specifier, if any.
153///
154/// \param OnlyNamespace If true, only considers namespaces in lookup.
155///
156///
157/// \returns true if there was an error parsing a scope specifier
158bool Parser::ParseOptionalCXXScopeSpecifier(
159 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors,
160 bool EnteringContext, bool *MayBePseudoDestructor, bool IsTypename,
161 const IdentifierInfo **LastII, bool OnlyNamespace,
162 bool InUsingDeclaration) {
163 assert(getLangOpts().CPlusPlus &&
164 "Call sites of this function should be guarded by checking for C++");
165
166 if (Tok.is(tok::annot_cxxscope)) {
167 assert(!LastII && "want last identifier but have already annotated scope");
168 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
170 Tok.getAnnotationRange(),
171 SS);
172 ConsumeAnnotationToken();
173 return false;
174 }
175
176 // Has to happen before any "return false"s in this function.
177 bool CheckForDestructor = false;
178 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
179 CheckForDestructor = true;
180 *MayBePseudoDestructor = false;
181 }
182
183 if (LastII)
184 *LastII = nullptr;
185
186 bool HasScopeSpecifier = false;
187
188 if (Tok.is(tok::coloncolon)) {
189 // ::new and ::delete aren't nested-name-specifiers.
190 tok::TokenKind NextKind = NextToken().getKind();
191 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
192 return false;
193
194 if (NextKind == tok::l_brace) {
195 // It is invalid to have :: {, consume the scope qualifier and pretend
196 // like we never saw it.
197 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
198 } else {
199 // '::' - Global scope qualifier.
201 return true;
202
203 HasScopeSpecifier = true;
204 }
205 }
206
207 if (Tok.is(tok::kw___super)) {
208 SourceLocation SuperLoc = ConsumeToken();
209 if (!Tok.is(tok::coloncolon)) {
210 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
211 return true;
212 }
213
214 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
215 }
216
217 if (!HasScopeSpecifier &&
218 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
219 DeclSpec DS(AttrFactory);
220 SourceLocation DeclLoc = Tok.getLocation();
221 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
222
223 SourceLocation CCLoc;
224 // Work around a standard defect: 'decltype(auto)::' is not a
225 // nested-name-specifier.
226 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
227 !TryConsumeToken(tok::coloncolon, CCLoc)) {
228 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
229 return false;
230 }
231
232 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
233 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
234
235 HasScopeSpecifier = true;
236 }
237
238 else if (!HasScopeSpecifier && Tok.is(tok::identifier) &&
239 GetLookAheadToken(1).is(tok::ellipsis) &&
240 GetLookAheadToken(2).is(tok::l_square)) {
241 SourceLocation Start = Tok.getLocation();
242 DeclSpec DS(AttrFactory);
243 SourceLocation CCLoc;
244 SourceLocation EndLoc = ParsePackIndexingType(DS);
245 if (DS.getTypeSpecType() == DeclSpec::TST_error)
246 return false;
247
249 DS.getRepAsType().get(), DS.getPackIndexingExpr(), DS.getBeginLoc(),
250 DS.getEllipsisLoc());
251
252 if (Type.isNull())
253 return false;
254
255 if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
256 AnnotateExistingIndexedTypeNamePack(ParsedType::make(Type), Start,
257 EndLoc);
258 return false;
259 }
260 if (Actions.ActOnCXXNestedNameSpecifierIndexedPack(SS, DS, CCLoc,
261 std::move(Type)))
262 SS.SetInvalid(SourceRange(Start, CCLoc));
263 HasScopeSpecifier = true;
264 }
265
266 // Preferred type might change when parsing qualifiers, we need the original.
267 auto SavedType = PreferredType;
268 while (true) {
269 if (HasScopeSpecifier) {
270 if (Tok.is(tok::code_completion)) {
271 cutOffParsing();
272 // Code completion for a nested-name-specifier, where the code
273 // completion token follows the '::'.
275 getCurScope(), SS, EnteringContext, InUsingDeclaration,
276 ObjectType.get(), SavedType.get(SS.getBeginLoc()));
277 // Include code completion token into the range of the scope otherwise
278 // when we try to annotate the scope tokens the dangling code completion
279 // token will cause assertion in
280 // Preprocessor::AnnotatePreviousCachedTokens.
281 SS.setEndLoc(Tok.getLocation());
282 return true;
283 }
284
285 // C++ [basic.lookup.classref]p5:
286 // If the qualified-id has the form
287 //
288 // ::class-name-or-namespace-name::...
289 //
290 // the class-name-or-namespace-name is looked up in global scope as a
291 // class-name or namespace-name.
292 //
293 // To implement this, we clear out the object type as soon as we've
294 // seen a leading '::' or part of a nested-name-specifier.
295 ObjectType = nullptr;
296 }
297
298 // nested-name-specifier:
299 // nested-name-specifier 'template'[opt] simple-template-id '::'
300
301 // Parse the optional 'template' keyword, then make sure we have
302 // 'identifier <' after it.
303 if (Tok.is(tok::kw_template)) {
304 // If we don't have a scope specifier or an object type, this isn't a
305 // nested-name-specifier, since they aren't allowed to start with
306 // 'template'.
307 if (!HasScopeSpecifier && !ObjectType)
308 break;
309
310 TentativeParsingAction TPA(*this);
311 SourceLocation TemplateKWLoc = ConsumeToken();
312
314 if (Tok.is(tok::identifier)) {
315 // Consume the identifier.
316 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
317 ConsumeToken();
318 } else if (Tok.is(tok::kw_operator)) {
319 // We don't need to actually parse the unqualified-id in this case,
320 // because a simple-template-id cannot start with 'operator', but
321 // go ahead and parse it anyway for consistency with the case where
322 // we already annotated the template-id.
323 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
324 TemplateName)) {
325 TPA.Commit();
326 break;
327 }
328
331 Diag(TemplateName.getSourceRange().getBegin(),
332 diag::err_id_after_template_in_nested_name_spec)
333 << TemplateName.getSourceRange();
334 TPA.Commit();
335 break;
336 }
337 } else {
338 TPA.Revert();
339 break;
340 }
341
342 // If the next token is not '<', we have a qualified-id that refers
343 // to a template name, such as T::template apply, but is not a
344 // template-id.
345 if (Tok.isNot(tok::less)) {
346 TPA.Revert();
347 break;
348 }
349
350 // Commit to parsing the template-id.
351 TPA.Commit();
352 TemplateTy Template;
354 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
355 EnteringContext, Template, /*AllowInjectedClassName*/ true);
356 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
357 TemplateName, false))
358 return true;
359
360 continue;
361 }
362
363 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
364 // We have
365 //
366 // template-id '::'
367 //
368 // So we need to check whether the template-id is a simple-template-id of
369 // the right kind (it should name a type or be dependent), and then
370 // convert it into a type within the nested-name-specifier.
371 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
372 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
373 *MayBePseudoDestructor = true;
374 return false;
375 }
376
377 if (LastII)
378 *LastII = TemplateId->Name;
379
380 // Consume the template-id token.
381 ConsumeAnnotationToken();
382
383 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
385
386 HasScopeSpecifier = true;
387
388 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
389 TemplateId->NumArgs);
390
391 if (TemplateId->isInvalid() ||
393 SS,
394 TemplateId->TemplateKWLoc,
395 TemplateId->Template,
396 TemplateId->TemplateNameLoc,
397 TemplateId->LAngleLoc,
398 TemplateArgsPtr,
399 TemplateId->RAngleLoc,
400 CCLoc,
401 EnteringContext)) {
402 SourceLocation StartLoc
403 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
404 : TemplateId->TemplateNameLoc;
405 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
406 }
407
408 continue;
409 }
410
411 switch (Tok.getKind()) {
412#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
413#include "clang/Basic/TransformTypeTraits.def"
414 if (!NextToken().is(tok::l_paren)) {
415 Tok.setKind(tok::identifier);
416 Diag(Tok, diag::ext_keyword_as_ident)
417 << Tok.getIdentifierInfo()->getName() << 0;
418 continue;
419 }
420 [[fallthrough]];
421 default:
422 break;
423 }
424
425 // The rest of the nested-name-specifier possibilities start with
426 // tok::identifier.
427 if (Tok.isNot(tok::identifier))
428 break;
429
431
432 // nested-name-specifier:
433 // type-name '::'
434 // namespace-name '::'
435 // nested-name-specifier identifier '::'
436 Token Next = NextToken();
437 Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
438 ObjectType);
439
440 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
441 // and emit a fixit hint for it.
442 if (Next.is(tok::colon) && !ColonIsSacred) {
443 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
444 EnteringContext) &&
445 // If the token after the colon isn't an identifier, it's still an
446 // error, but they probably meant something else strange so don't
447 // recover like this.
448 PP.LookAhead(1).is(tok::identifier)) {
449 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
450 << FixItHint::CreateReplacement(Next.getLocation(), "::");
451 // Recover as if the user wrote '::'.
452 Next.setKind(tok::coloncolon);
453 }
454 }
455
456 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
457 // It is invalid to have :: {, consume the scope qualifier and pretend
458 // like we never saw it.
459 Token Identifier = Tok; // Stash away the identifier.
460 ConsumeToken(); // Eat the identifier, current token is now '::'.
461 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
462 << tok::identifier;
463 UnconsumeToken(Identifier); // Stick the identifier back.
464 Next = NextToken(); // Point Next at the '{' token.
465 }
466
467 if (Next.is(tok::coloncolon)) {
468 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
469 *MayBePseudoDestructor = true;
470 return false;
471 }
472
473 if (ColonIsSacred) {
474 const Token &Next2 = GetLookAheadToken(2);
475 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
476 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
477 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
478 << Next2.getName()
479 << FixItHint::CreateReplacement(Next.getLocation(), ":");
480 Token ColonColon;
481 PP.Lex(ColonColon);
482 ColonColon.setKind(tok::colon);
483 PP.EnterToken(ColonColon, /*IsReinject*/ true);
484 break;
485 }
486 }
487
488 if (LastII)
489 *LastII = &II;
490
491 // We have an identifier followed by a '::'. Lookup this name
492 // as the name in a nested-name-specifier.
493 Token Identifier = Tok;
495 assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
496 "NextToken() not working properly!");
497 Token ColonColon = Tok;
499
500 bool IsCorrectedToColon = false;
501 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
502 if (Actions.ActOnCXXNestedNameSpecifier(
503 getCurScope(), IdInfo, EnteringContext, SS, CorrectionFlagPtr,
504 OnlyNamespace)) {
505 // Identifier is not recognized as a nested name, but we can have
506 // mistyped '::' instead of ':'.
507 if (CorrectionFlagPtr && IsCorrectedToColon) {
508 ColonColon.setKind(tok::colon);
509 PP.EnterToken(Tok, /*IsReinject*/ true);
510 PP.EnterToken(ColonColon, /*IsReinject*/ true);
511 Tok = Identifier;
512 break;
513 }
514 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
515 }
516 HasScopeSpecifier = true;
517 continue;
518 }
519
520 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
521
522 // nested-name-specifier:
523 // type-name '<'
524 if (Next.is(tok::less)) {
525
526 TemplateTy Template;
528 TemplateName.setIdentifier(&II, Tok.getLocation());
529 bool MemberOfUnknownSpecialization;
530 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
531 /*hasTemplateKeyword=*/false,
533 ObjectType,
534 EnteringContext,
535 Template,
536 MemberOfUnknownSpecialization)) {
537 // If lookup didn't find anything, we treat the name as a template-name
538 // anyway. C++20 requires this, and in prior language modes it improves
539 // error recovery. But before we commit to this, check that we actually
540 // have something that looks like a template-argument-list next.
541 if (!IsTypename && TNK == TNK_Undeclared_template &&
542 isTemplateArgumentList(1) == TPResult::False)
543 break;
544
545 // We have found a template name, so annotate this token
546 // with a template-id annotation. We do not permit the
547 // template-id to be translated into a type annotation,
548 // because some clients (e.g., the parsing of class template
549 // specializations) still want to see the original template-id
550 // token, and it might not be a type at all (e.g. a concept name in a
551 // type-constraint).
552 ConsumeToken();
553 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
554 TemplateName, false))
555 return true;
556 continue;
557 }
558
559 if (MemberOfUnknownSpecialization && (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) {
607 ExprResult E;
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
627 E = Actions.ActOnNameClassifiedAsDependentNonType(SS, II, Loc,
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 Actions.ActOnLambdaClosureQualifiers(Intro, MutableLoc);
1584
1585 if (HasParentheses && Tok.is(tok::kw_requires))
1586 ParseTrailingRequiresClause(D);
1587 }
1588
1589 // Emit a warning if we see a CUDA host/device/global attribute
1590 // after '(...)'. nvcc doesn't accept this.
1591 if (getLangOpts().CUDA) {
1592 for (const ParsedAttr &A : Attributes)
1593 if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1594 A.getKind() == ParsedAttr::AT_CUDAHost ||
1595 A.getKind() == ParsedAttr::AT_CUDAGlobal)
1596 Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
1597 << A.getAttrName()->getName();
1598 }
1599
1600 Prototype.Exit();
1601
1602 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1603 // it.
1604 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1606 ParseScope BodyScope(this, ScopeFlags);
1607
1608 Actions.ActOnStartOfLambdaDefinition(Intro, D, DS);
1609
1610 // Parse compound-statement.
1611 if (!Tok.is(tok::l_brace)) {
1612 Diag(Tok, diag::err_expected_lambda_body);
1613 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1614 return ExprError();
1615 }
1616
1617 StmtResult Stmt(ParseCompoundStatementBody());
1618 BodyScope.Exit();
1619 TemplateParamScope.Exit();
1620 LambdaScope.Exit();
1621
1622 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid() &&
1623 !D.isInvalidType())
1624 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get());
1625
1626 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1627 return ExprError();
1628}
1629
1630/// ParseCXXCasts - This handles the various ways to cast expressions to another
1631/// type.
1632///
1633/// postfix-expression: [C++ 5.2p1]
1634/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1635/// 'static_cast' '<' type-name '>' '(' expression ')'
1636/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1637/// 'const_cast' '<' type-name '>' '(' expression ')'
1638///
1639/// C++ for OpenCL s2.3.1 adds:
1640/// 'addrspace_cast' '<' type-name '>' '(' expression ')'
1641ExprResult Parser::ParseCXXCasts() {
1642 tok::TokenKind Kind = Tok.getKind();
1643 const char *CastName = nullptr; // For error messages
1644
1645 switch (Kind) {
1646 default: llvm_unreachable("Unknown C++ cast!");
1647 case tok::kw_addrspace_cast: CastName = "addrspace_cast"; break;
1648 case tok::kw_const_cast: CastName = "const_cast"; break;
1649 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1650 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1651 case tok::kw_static_cast: CastName = "static_cast"; break;
1652 }
1653
1654 SourceLocation OpLoc = ConsumeToken();
1655 SourceLocation LAngleBracketLoc = Tok.getLocation();
1656
1657 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1658 // diagnose error, suggest fix, and recover parsing.
1659 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1660 Token Next = NextToken();
1661 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1662 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1663 }
1664
1665 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1666 return ExprError();
1667
1668 // Parse the common declaration-specifiers piece.
1669 DeclSpec DS(AttrFactory);
1670 ParseSpecifierQualifierList(DS, /*AccessSpecifier=*/AS_none,
1671 DeclSpecContext::DSC_type_specifier);
1672
1673 // Parse the abstract-declarator, if present.
1674 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1676 ParseDeclarator(DeclaratorInfo);
1677
1678 SourceLocation RAngleBracketLoc = Tok.getLocation();
1679
1680 if (ExpectAndConsume(tok::greater))
1681 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1682
1683 BalancedDelimiterTracker T(*this, tok::l_paren);
1684
1685 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1686 return ExprError();
1687
1689
1690 // Match the ')'.
1691 T.consumeClose();
1692
1693 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1694 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1695 LAngleBracketLoc, DeclaratorInfo,
1696 RAngleBracketLoc,
1697 T.getOpenLocation(), Result.get(),
1698 T.getCloseLocation());
1699
1700 return Result;
1701}
1702
1703/// ParseCXXTypeid - This handles the C++ typeid expression.
1704///
1705/// postfix-expression: [C++ 5.2p1]
1706/// 'typeid' '(' expression ')'
1707/// 'typeid' '(' type-id ')'
1708///
1709ExprResult Parser::ParseCXXTypeid() {
1710 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1711
1712 SourceLocation OpLoc = ConsumeToken();
1713 SourceLocation LParenLoc, RParenLoc;
1714 BalancedDelimiterTracker T(*this, tok::l_paren);
1715
1716 // typeid expressions are always parenthesized.
1717 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1718 return ExprError();
1719 LParenLoc = T.getOpenLocation();
1720
1722
1723 // C++0x [expr.typeid]p3:
1724 // When typeid is applied to an expression other than an lvalue of a
1725 // polymorphic class type [...] The expression is an unevaluated
1726 // operand (Clause 5).
1727 //
1728 // Note that we can't tell whether the expression is an lvalue of a
1729 // polymorphic class type until after we've parsed the expression; we
1730 // speculatively assume the subexpression is unevaluated, and fix it up
1731 // later.
1732 //
1733 // We enter the unevaluated context before trying to determine whether we
1734 // have a type-id, because the tentative parse logic will try to resolve
1735 // names, and must treat them as unevaluated.
1739
1740 if (isTypeIdInParens()) {
1742
1743 // Match the ')'.
1744 T.consumeClose();
1745 RParenLoc = T.getCloseLocation();
1746 if (Ty.isInvalid() || RParenLoc.isInvalid())
1747 return ExprError();
1748
1749 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1750 Ty.get().getAsOpaquePtr(), RParenLoc);
1751 } else {
1753
1754 // Match the ')'.
1755 if (Result.isInvalid())
1756 SkipUntil(tok::r_paren, StopAtSemi);
1757 else {
1758 T.consumeClose();
1759 RParenLoc = T.getCloseLocation();
1760 if (RParenLoc.isInvalid())
1761 return ExprError();
1762
1763 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1764 Result.get(), RParenLoc);
1765 }
1766 }
1767
1768 return Result;
1769}
1770
1771/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1772///
1773/// '__uuidof' '(' expression ')'
1774/// '__uuidof' '(' type-id ')'
1775///
1776ExprResult Parser::ParseCXXUuidof() {
1777 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1778
1779 SourceLocation OpLoc = ConsumeToken();
1780 BalancedDelimiterTracker T(*this, tok::l_paren);
1781
1782 // __uuidof expressions are always parenthesized.
1783 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1784 return ExprError();
1785
1787
1788 if (isTypeIdInParens()) {
1790
1791 // Match the ')'.
1792 T.consumeClose();
1793
1794 if (Ty.isInvalid())
1795 return ExprError();
1796
1797 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1798 Ty.get().getAsOpaquePtr(),
1799 T.getCloseLocation());
1800 } else {
1804
1805 // Match the ')'.
1806 if (Result.isInvalid())
1807 SkipUntil(tok::r_paren, StopAtSemi);
1808 else {
1809 T.consumeClose();
1810
1811 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1812 /*isType=*/false,
1813 Result.get(), T.getCloseLocation());
1814 }
1815 }
1816
1817 return Result;
1818}
1819
1820/// Parse a C++ pseudo-destructor expression after the base,
1821/// . or -> operator, and nested-name-specifier have already been
1822/// parsed. We're handling this fragment of the grammar:
1823///
1824/// postfix-expression: [C++2a expr.post]
1825/// postfix-expression . template[opt] id-expression
1826/// postfix-expression -> template[opt] id-expression
1827///
1828/// id-expression:
1829/// qualified-id
1830/// unqualified-id
1831///
1832/// qualified-id:
1833/// nested-name-specifier template[opt] unqualified-id
1834///
1835/// nested-name-specifier:
1836/// type-name ::
1837/// decltype-specifier :: FIXME: not implemented, but probably only
1838/// allowed in C++ grammar by accident
1839/// nested-name-specifier identifier ::
1840/// nested-name-specifier template[opt] simple-template-id ::
1841/// [...]
1842///
1843/// unqualified-id:
1844/// ~ type-name
1845/// ~ decltype-specifier
1846/// [...]
1847///
1848/// ... where the all but the last component of the nested-name-specifier
1849/// has already been parsed, and the base expression is not of a non-dependent
1850/// class type.
1852Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1853 tok::TokenKind OpKind,
1854 CXXScopeSpec &SS,
1855 ParsedType ObjectType) {
1856 // If the last component of the (optional) nested-name-specifier is
1857 // template[opt] simple-template-id, it has already been annotated.
1858 UnqualifiedId FirstTypeName;
1859 SourceLocation CCLoc;
1860 if (Tok.is(tok::identifier)) {
1861 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1862 ConsumeToken();
1863 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1864 CCLoc = ConsumeToken();
1865 } else if (Tok.is(tok::annot_template_id)) {
1866 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1867 // FIXME: Carry on and build an AST representation for tooling.
1868 if (TemplateId->isInvalid())
1869 return ExprError();
1870 FirstTypeName.setTemplateId(TemplateId);
1871 ConsumeAnnotationToken();
1872 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1873 CCLoc = ConsumeToken();
1874 } else {
1875 assert(SS.isEmpty() && "missing last component of nested name specifier");
1876 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1877 }
1878
1879 // Parse the tilde.
1880 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1881 SourceLocation TildeLoc = ConsumeToken();
1882
1883 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid()) {
1884 DeclSpec DS(AttrFactory);
1885 ParseDecltypeSpecifier(DS);
1886 if (DS.getTypeSpecType() == TST_error)
1887 return ExprError();
1888 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1889 TildeLoc, DS);
1890 }
1891
1892 if (!Tok.is(tok::identifier)) {
1893 Diag(Tok, diag::err_destructor_tilde_identifier);
1894 return ExprError();
1895 }
1896
1897 // pack-index-specifier
1898 if (GetLookAheadToken(1).is(tok::ellipsis) &&
1899 GetLookAheadToken(2).is(tok::l_square)) {
1900 DeclSpec DS(AttrFactory);
1901 ParsePackIndexingType(DS);
1902 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1903 TildeLoc, DS);
1904 }
1905
1906 // Parse the second type.
1907 UnqualifiedId SecondTypeName;
1908 IdentifierInfo *Name = Tok.getIdentifierInfo();
1909 SourceLocation NameLoc = ConsumeToken();
1910 SecondTypeName.setIdentifier(Name, NameLoc);
1911
1912 // If there is a '<', the second type name is a template-id. Parse
1913 // it as such.
1914 //
1915 // FIXME: This is not a context in which a '<' is assumed to start a template
1916 // argument list. This affects examples such as
1917 // void f(auto *p) { p->~X<int>(); }
1918 // ... but there's no ambiguity, and nowhere to write 'template' in such an
1919 // example, so we accept it anyway.
1920 if (Tok.is(tok::less) &&
1921 ParseUnqualifiedIdTemplateId(
1922 SS, ObjectType, Base && Base->containsErrors(), SourceLocation(),
1923 Name, NameLoc, false, SecondTypeName,
1924 /*AssumeTemplateId=*/true))
1925 return ExprError();
1926
1927 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1928 SS, FirstTypeName, CCLoc, TildeLoc,
1929 SecondTypeName);
1930}
1931
1932/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1933///
1934/// boolean-literal: [C++ 2.13.5]
1935/// 'true'
1936/// 'false'
1937ExprResult Parser::ParseCXXBoolLiteral() {
1938 tok::TokenKind Kind = Tok.getKind();
1939 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1940}
1941
1942/// ParseThrowExpression - This handles the C++ throw expression.
1943///
1944/// throw-expression: [C++ 15]
1945/// 'throw' assignment-expression[opt]
1946ExprResult Parser::ParseThrowExpression() {
1947 assert(Tok.is(tok::kw_throw) && "Not throw!");
1948 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1949
1950 // If the current token isn't the start of an assignment-expression,
1951 // then the expression is not present. This handles things like:
1952 // "C ? throw : (void)42", which is crazy but legal.
1953 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1954 case tok::semi:
1955 case tok::r_paren:
1956 case tok::r_square:
1957 case tok::r_brace:
1958 case tok::colon:
1959 case tok::comma:
1960 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1961
1962 default:
1964 if (Expr.isInvalid()) return Expr;
1965 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1966 }
1967}
1968
1969/// Parse the C++ Coroutines co_yield expression.
1970///
1971/// co_yield-expression:
1972/// 'co_yield' assignment-expression[opt]
1973ExprResult Parser::ParseCoyieldExpression() {
1974 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1975
1977 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1979 if (!Expr.isInvalid())
1980 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1981 return Expr;
1982}
1983
1984/// ParseCXXThis - This handles the C++ 'this' pointer.
1985///
1986/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1987/// a non-lvalue expression whose value is the address of the object for which
1988/// the function is called.
1989ExprResult Parser::ParseCXXThis() {
1990 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1991 SourceLocation ThisLoc = ConsumeToken();
1992 return Actions.ActOnCXXThis(ThisLoc);
1993}
1994
1995/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1996/// Can be interpreted either as function-style casting ("int(x)")
1997/// or class type construction ("ClassType(x,y,z)")
1998/// or creation of a value-initialized type ("int()").
1999/// See [C++ 5.2.3].
2000///
2001/// postfix-expression: [C++ 5.2p1]
2002/// simple-type-specifier '(' expression-list[opt] ')'
2003/// [C++0x] simple-type-specifier braced-init-list
2004/// typename-specifier '(' expression-list[opt] ')'
2005/// [C++0x] typename-specifier braced-init-list
2006///
2007/// In C++1z onwards, the type specifier can also be a template-name.
2009Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
2010 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
2012 ParsedType TypeRep = Actions.ActOnTypeName(DeclaratorInfo).get();
2013
2014 assert((Tok.is(tok::l_paren) ||
2015 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
2016 && "Expected '(' or '{'!");
2017
2018 if (Tok.is(tok::l_brace)) {
2019 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
2020 ExprResult Init = ParseBraceInitializer();
2021 if (Init.isInvalid())
2022 return Init;
2023 Expr *InitList = Init.get();
2024 return Actions.ActOnCXXTypeConstructExpr(
2025 TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
2026 InitList->getEndLoc(), /*ListInitialization=*/true);
2027 } else {
2028 BalancedDelimiterTracker T(*this, tok::l_paren);
2029 T.consumeOpen();
2030
2031 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
2032
2033 ExprVector Exprs;
2034
2035 auto RunSignatureHelp = [&]() {
2036 QualType PreferredType;
2037 if (TypeRep)
2038 PreferredType =
2040 TypeRep.get()->getCanonicalTypeInternal(), DS.getEndLoc(),
2041 Exprs, T.getOpenLocation(), /*Braced=*/false);
2042 CalledSignatureHelp = true;
2043 return PreferredType;
2044 };
2045
2046 if (Tok.isNot(tok::r_paren)) {
2047 if (ParseExpressionList(Exprs, [&] {
2048 PreferredType.enterFunctionArgument(Tok.getLocation(),
2049 RunSignatureHelp);
2050 })) {
2051 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
2052 RunSignatureHelp();
2053 SkipUntil(tok::r_paren, StopAtSemi);
2054 return ExprError();
2055 }
2056 }
2057
2058 // Match the ')'.
2059 T.consumeClose();
2060
2061 // TypeRep could be null, if it references an invalid typedef.
2062 if (!TypeRep)
2063 return ExprError();
2064
2065 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
2066 Exprs, T.getCloseLocation(),
2067 /*ListInitialization=*/false);
2068 }
2069}
2070
2072Parser::ParseAliasDeclarationInInitStatement(DeclaratorContext Context,
2073 ParsedAttributes &Attrs) {
2074 assert(Tok.is(tok::kw_using) && "Expected using");
2075 assert((Context == DeclaratorContext::ForInit ||
2077 "Unexpected Declarator Context");
2078 DeclGroupPtrTy DG;
2079 SourceLocation DeclStart = ConsumeToken(), DeclEnd;
2080
2081 DG = ParseUsingDeclaration(Context, {}, DeclStart, DeclEnd, Attrs, AS_none);
2082 if (!DG)
2083 return DG;
2084
2085 Diag(DeclStart, !getLangOpts().CPlusPlus23
2086 ? diag::ext_alias_in_init_statement
2087 : diag::warn_cxx20_alias_in_init_statement)
2088 << SourceRange(DeclStart, DeclEnd);
2089
2090 return DG;
2091}
2092
2093/// ParseCXXCondition - if/switch/while condition expression.
2094///
2095/// condition:
2096/// expression
2097/// type-specifier-seq declarator '=' assignment-expression
2098/// [C++11] type-specifier-seq declarator '=' initializer-clause
2099/// [C++11] type-specifier-seq declarator braced-init-list
2100/// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
2101/// brace-or-equal-initializer
2102/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
2103/// '=' assignment-expression
2104///
2105/// In C++1z, a condition may in some contexts be preceded by an
2106/// optional init-statement. This function will parse that too.
2107///
2108/// \param InitStmt If non-null, an init-statement is permitted, and if present
2109/// will be parsed and stored here.
2110///
2111/// \param Loc The location of the start of the statement that requires this
2112/// condition, e.g., the "for" in a for loop.
2113///
2114/// \param MissingOK Whether an empty condition is acceptable here. Otherwise
2115/// it is considered an error to be recovered from.
2116///
2117/// \param FRI If non-null, a for range declaration is permitted, and if
2118/// present will be parsed and stored here, and a null result will be returned.
2119///
2120/// \param EnterForConditionScope If true, enter a continue/break scope at the
2121/// appropriate moment for a 'for' loop.
2122///
2123/// \returns The parsed condition.
2125Parser::ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc,
2126 Sema::ConditionKind CK, bool MissingOK,
2127 ForRangeInfo *FRI, bool EnterForConditionScope) {
2128 // Helper to ensure we always enter a continue/break scope if requested.
2129 struct ForConditionScopeRAII {
2130 Scope *S;
2131 void enter(bool IsConditionVariable) {
2132 if (S) {
2134 S->setIsConditionVarScope(IsConditionVariable);
2135 }
2136 }
2137 ~ForConditionScopeRAII() {
2138 if (S)
2139 S->setIsConditionVarScope(false);
2140 }
2141 } ForConditionScope{EnterForConditionScope ? getCurScope() : nullptr};
2142
2143 ParenBraceBracketBalancer BalancerRAIIObj(*this);
2144 PreferredType.enterCondition(Actions, Tok.getLocation());
2145
2146 if (Tok.is(tok::code_completion)) {
2147 cutOffParsing();
2150 return Sema::ConditionError();
2151 }
2152
2153 ParsedAttributes attrs(AttrFactory);
2154 MaybeParseCXX11Attributes(attrs);
2155
2156 const auto WarnOnInit = [this, &CK] {
2158 ? diag::warn_cxx14_compat_init_statement
2159 : diag::ext_init_statement)
2160 << (CK == Sema::ConditionKind::Switch);
2161 };
2162
2163 // Determine what kind of thing we have.
2164 switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
2165 case ConditionOrInitStatement::Expression: {
2166 // If this is a for loop, we're entering its condition.
2167 ForConditionScope.enter(/*IsConditionVariable=*/false);
2168
2169 ProhibitAttributes(attrs);
2170
2171 // We can have an empty expression here.
2172 // if (; true);
2173 if (InitStmt && Tok.is(tok::semi)) {
2174 WarnOnInit();
2175 SourceLocation SemiLoc = Tok.getLocation();
2176 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
2177 Diag(SemiLoc, diag::warn_empty_init_statement)
2179 << FixItHint::CreateRemoval(SemiLoc);
2180 }
2181 ConsumeToken();
2182 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
2183 return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
2184 }
2185
2186 // Parse the expression.
2187 ExprResult Expr = ParseExpression(); // expression
2188 if (Expr.isInvalid())
2189 return Sema::ConditionError();
2190
2191 if (InitStmt && Tok.is(tok::semi)) {
2192 WarnOnInit();
2193 *InitStmt = Actions.ActOnExprStmt(Expr.get());
2194 ConsumeToken();
2195 return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
2196 }
2197
2198 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK,
2199 MissingOK);
2200 }
2201
2202 case ConditionOrInitStatement::InitStmtDecl: {
2203 WarnOnInit();
2204 DeclGroupPtrTy DG;
2205 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2206 if (Tok.is(tok::kw_using))
2207 DG = ParseAliasDeclarationInInitStatement(
2209 else {
2210 ParsedAttributes DeclSpecAttrs(AttrFactory);
2211 DG = ParseSimpleDeclaration(DeclaratorContext::SelectionInit, DeclEnd,
2212 attrs, DeclSpecAttrs, /*RequireSemi=*/true);
2213 }
2214 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
2215 return ParseCXXCondition(nullptr, Loc, CK, MissingOK);
2216 }
2217
2218 case ConditionOrInitStatement::ForRangeDecl: {
2219 // This is 'for (init-stmt; for-range-decl : range-expr)'.
2220 // We're not actually in a for loop yet, so 'break' and 'continue' aren't
2221 // permitted here.
2222 assert(FRI && "should not parse a for range declaration here");
2223 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2224 ParsedAttributes DeclSpecAttrs(AttrFactory);
2225 DeclGroupPtrTy DG = ParseSimpleDeclaration(
2226 DeclaratorContext::ForInit, DeclEnd, attrs, DeclSpecAttrs, false, FRI);
2227 FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
2228 return Sema::ConditionResult();
2229 }
2230
2231 case ConditionOrInitStatement::ConditionDecl:
2232 case ConditionOrInitStatement::Error:
2233 break;
2234 }
2235
2236 // If this is a for loop, we're entering its condition.
2237 ForConditionScope.enter(/*IsConditionVariable=*/true);
2238
2239 // type-specifier-seq
2240 DeclSpec DS(AttrFactory);
2241 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
2242
2243 // declarator
2244 Declarator DeclaratorInfo(DS, attrs, DeclaratorContext::Condition);
2245 ParseDeclarator(DeclaratorInfo);
2246
2247 // simple-asm-expr[opt]
2248 if (Tok.is(tok::kw_asm)) {
2250 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2251 if (AsmLabel.isInvalid()) {
2252 SkipUntil(tok::semi, StopAtSemi);
2253 return Sema::ConditionError();
2254 }
2255 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2256 DeclaratorInfo.SetRangeEnd(Loc);
2257 }
2258
2259 // If attributes are present, parse them.
2260 MaybeParseGNUAttributes(DeclaratorInfo);
2261
2262 // Type-check the declaration itself.
2264 DeclaratorInfo);
2265 if (Dcl.isInvalid())
2266 return Sema::ConditionError();
2267 Decl *DeclOut = Dcl.get();
2268
2269 // '=' assignment-expression
2270 // If a '==' or '+=' is found, suggest a fixit to '='.
2271 bool CopyInitialization = isTokenEqualOrEqualTypo();
2272 if (CopyInitialization)
2273 ConsumeToken();
2274
2275 ExprResult InitExpr = ExprError();
2276 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2277 Diag(Tok.getLocation(),
2278 diag::warn_cxx98_compat_generalized_initializer_lists);
2279 InitExpr = ParseBraceInitializer();
2280 } else if (CopyInitialization) {
2281 PreferredType.enterVariableInit(Tok.getLocation(), DeclOut);
2282 InitExpr = ParseAssignmentExpression();
2283 } else if (Tok.is(tok::l_paren)) {
2284 // This was probably an attempt to initialize the variable.
2285 SourceLocation LParen = ConsumeParen(), RParen = LParen;
2286 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
2287 RParen = ConsumeParen();
2288 Diag(DeclOut->getLocation(),
2289 diag::err_expected_init_in_condition_lparen)
2290 << SourceRange(LParen, RParen);
2291 } else {
2292 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
2293 }
2294
2295 if (!InitExpr.isInvalid())
2296 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
2297 else
2298 Actions.ActOnInitializerError(DeclOut);
2299
2300 Actions.FinalizeDeclaration(DeclOut);
2301 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
2302}
2303
2304/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
2305/// This should only be called when the current token is known to be part of
2306/// simple-type-specifier.
2307///
2308/// simple-type-specifier:
2309/// '::'[opt] nested-name-specifier[opt] type-name
2310/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
2311/// char
2312/// wchar_t
2313/// bool
2314/// short
2315/// int
2316/// long
2317/// signed
2318/// unsigned
2319/// float
2320/// double
2321/// void
2322/// [GNU] typeof-specifier
2323/// [C++0x] auto [TODO]
2324///
2325/// type-name:
2326/// class-name
2327/// enum-name
2328/// typedef-name
2329///
2330void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
2331 DS.SetRangeStart(Tok.getLocation());
2332 const char *PrevSpec;
2333 unsigned DiagID;
2335 const clang::PrintingPolicy &Policy =
2336 Actions.getASTContext().getPrintingPolicy();
2337
2338 switch (Tok.getKind()) {
2339 case tok::identifier: // foo::bar
2340 case tok::coloncolon: // ::foo::bar
2341 llvm_unreachable("Annotation token should already be formed!");
2342 default:
2343 llvm_unreachable("Not a simple-type-specifier token!");
2344
2345 // type-name
2346 case tok::annot_typename: {
2347 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
2348 getTypeAnnotation(Tok), Policy);
2350 ConsumeAnnotationToken();
2351 DS.Finish(Actions, Policy);
2352 return;
2353 }
2354
2355 case tok::kw__ExtInt:
2356 case tok::kw__BitInt: {
2357 DiagnoseBitIntUse(Tok);
2358 ExprResult ER = ParseExtIntegerArgument();
2359 if (ER.isInvalid())
2360 DS.SetTypeSpecError();
2361 else
2362 DS.SetBitIntType(Loc, ER.get(), PrevSpec, DiagID, Policy);
2363
2364 // Do this here because we have already consumed the close paren.
2365 DS.SetRangeEnd(PrevTokLocation);
2366 DS.Finish(Actions, Policy);
2367 return;
2368 }
2369
2370 // builtin types
2371 case tok::kw_short:
2372 DS.SetTypeSpecWidth(TypeSpecifierWidth::Short, Loc, PrevSpec, DiagID,
2373 Policy);
2374 break;
2375 case tok::kw_long:
2376 DS.SetTypeSpecWidth(TypeSpecifierWidth::Long, Loc, PrevSpec, DiagID,
2377 Policy);
2378 break;
2379 case tok::kw___int64:
2381 Policy);
2382 break;
2383 case tok::kw_signed:
2384 DS.SetTypeSpecSign(TypeSpecifierSign::Signed, Loc, PrevSpec, DiagID);
2385 break;
2386 case tok::kw_unsigned:
2387 DS.SetTypeSpecSign(TypeSpecifierSign::Unsigned, Loc, PrevSpec, DiagID);
2388 break;
2389 case tok::kw_void:
2390 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
2391 break;
2392 case tok::kw_auto:
2393 DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID, Policy);
2394 break;
2395 case tok::kw_char:
2396 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
2397 break;
2398 case tok::kw_int:
2399 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
2400 break;
2401 case tok::kw___int128:
2402 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
2403 break;
2404 case tok::kw___bf16:
2405 DS.SetTypeSpecType(DeclSpec::TST_BFloat16, Loc, PrevSpec, DiagID, Policy);
2406 break;
2407 case tok::kw_half:
2408 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
2409 break;
2410 case tok::kw_float:
2411 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
2412 break;
2413 case tok::kw_double:
2414 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
2415 break;
2416 case tok::kw__Float16:
2417 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
2418 break;
2419 case tok::kw___float128:
2420 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
2421 break;
2422 case tok::kw___ibm128:
2423 DS.SetTypeSpecType(DeclSpec::TST_ibm128, Loc, PrevSpec, DiagID, Policy);
2424 break;
2425 case tok::kw_wchar_t:
2426 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
2427 break;
2428 case tok::kw_char8_t:
2429 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
2430 break;
2431 case tok::kw_char16_t:
2432 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
2433 break;
2434 case tok::kw_char32_t:
2435 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
2436 break;
2437 case tok::kw_bool:
2438 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
2439 break;
2440 case tok::kw__Accum:
2441 DS.SetTypeSpecType(DeclSpec::TST_accum, Loc, PrevSpec, DiagID, Policy);
2442 break;
2443 case tok::kw__Fract:
2444 DS.SetTypeSpecType(DeclSpec::TST_fract, Loc, PrevSpec, DiagID, Policy);
2445 break;
2446 case tok::kw__Sat:
2447 DS.SetTypeSpecSat(Loc, PrevSpec, DiagID);
2448 break;
2449#define GENERIC_IMAGE_TYPE(ImgType, Id) \
2450 case tok::kw_##ImgType##_t: \
2451 DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \
2452 Policy); \
2453 break;
2454#include "clang/Basic/OpenCLImageTypes.def"
2455
2456 case tok::annot_decltype:
2457 case tok::kw_decltype:
2458 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
2459 return DS.Finish(Actions, Policy);
2460
2461 case tok::annot_pack_indexing_type:
2462 DS.SetRangeEnd(ParsePackIndexingType(DS));
2463 return DS.Finish(Actions, Policy);
2464
2465 // GNU typeof support.
2466 case tok::kw_typeof:
2467 ParseTypeofSpecifier(DS);
2468 DS.Finish(Actions, Policy);
2469 return;
2470 }
2472 DS.SetRangeEnd(PrevTokLocation);
2473 DS.Finish(Actions, Policy);
2474}
2475
2476/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2477/// [dcl.name]), which is a non-empty sequence of type-specifiers,
2478/// e.g., "const short int". Note that the DeclSpec is *not* finished
2479/// by parsing the type-specifier-seq, because these sequences are
2480/// typically followed by some form of declarator. Returns true and
2481/// emits diagnostics if this is not a type-specifier-seq, false
2482/// otherwise.
2483///
2484/// type-specifier-seq: [C++ 8.1]
2485/// type-specifier type-specifier-seq[opt]
2486///
2487bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS, DeclaratorContext Context) {
2488 ParseSpecifierQualifierList(DS, AS_none,
2489 getDeclSpecContextFromDeclaratorContext(Context));
2490 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
2491 return false;
2492}
2493
2494/// Finish parsing a C++ unqualified-id that is a template-id of
2495/// some form.
2496///
2497/// This routine is invoked when a '<' is encountered after an identifier or
2498/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2499/// whether the unqualified-id is actually a template-id. This routine will
2500/// then parse the template arguments and form the appropriate template-id to
2501/// return to the caller.
2502///
2503/// \param SS the nested-name-specifier that precedes this template-id, if
2504/// we're actually parsing a qualified-id.
2505///
2506/// \param ObjectType if this unqualified-id occurs within a member access
2507/// expression, the type of the base object whose member is being accessed.
2508///
2509/// \param ObjectHadErrors this unqualified-id occurs within a member access
2510/// expression, indicates whether the original subexpressions had any errors.
2511///
2512/// \param Name for constructor and destructor names, this is the actual
2513/// identifier that may be a template-name.
2514///
2515/// \param NameLoc the location of the class-name in a constructor or
2516/// destructor.
2517///
2518/// \param EnteringContext whether we're entering the scope of the
2519/// nested-name-specifier.
2520///
2521/// \param Id as input, describes the template-name or operator-function-id
2522/// that precedes the '<'. If template arguments were parsed successfully,
2523/// will be updated with the template-id.
2524///
2525/// \param AssumeTemplateId When true, this routine will assume that the name
2526/// refers to a template without performing name lookup to verify.
2527///
2528/// \returns true if a parse error occurred, false otherwise.
2529bool Parser::ParseUnqualifiedIdTemplateId(
2530 CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors,
2531 SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc,
2532 bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId) {
2533 assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
2534
2535 TemplateTy Template;
2537 switch (Id.getKind()) {
2541 if (AssumeTemplateId) {
2542 // We defer the injected-class-name checks until we've found whether
2543 // this template-id is used to form a nested-name-specifier or not.
2544 TNK = Actions.ActOnTemplateName(getCurScope(), SS, TemplateKWLoc, Id,
2545 ObjectType, EnteringContext, Template,
2546 /*AllowInjectedClassName*/ true);
2547 } else {
2548 bool MemberOfUnknownSpecialization;
2549 TNK = Actions.isTemplateName(getCurScope(), SS,
2550 TemplateKWLoc.isValid(), Id,
2551 ObjectType, EnteringContext, Template,
2552 MemberOfUnknownSpecialization);
2553 // If lookup found nothing but we're assuming that this is a template
2554 // name, double-check that makes sense syntactically before committing
2555 // to it.
2556 if (TNK == TNK_Undeclared_template &&
2557 isTemplateArgumentList(0) == TPResult::False)
2558 return false;
2559
2560 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2561 ObjectType && isTemplateArgumentList(0) == TPResult::True) {
2562 // If we had errors before, ObjectType can be dependent even without any
2563 // templates, do not report missing template keyword in that case.
2564 if (!ObjectHadErrors) {
2565 // We have something like t->getAs<T>(), where getAs is a
2566 // member of an unknown specialization. However, this will only
2567 // parse correctly as a template, so suggest the keyword 'template'
2568 // before 'getAs' and treat this as a dependent template name.
2569 std::string Name;
2570 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
2571 Name = std::string(Id.Identifier->getName());
2572 else {
2573 Name = "operator ";
2575 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2576 else
2577 Name += Id.Identifier->getName();
2578 }
2579 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2580 << Name
2581 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2582 }
2583 TNK = Actions.ActOnTemplateName(
2584 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2585 Template, /*AllowInjectedClassName*/ true);
2586 } else if (TNK == TNK_Non_template) {
2587 return false;
2588 }
2589 }
2590 break;
2591
2594 bool MemberOfUnknownSpecialization;
2595 TemplateName.setIdentifier(Name, NameLoc);
2596 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2597 TemplateName, ObjectType,
2598 EnteringContext, Template,
2599 MemberOfUnknownSpecialization);
2600 if (TNK == TNK_Non_template)
2601 return false;
2602 break;
2603 }
2604
2607 bool MemberOfUnknownSpecialization;
2608 TemplateName.setIdentifier(Name, NameLoc);
2609 if (ObjectType) {
2610 TNK = Actions.ActOnTemplateName(
2611 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2612 EnteringContext, Template, /*AllowInjectedClassName*/ true);
2613 } else {
2614 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2615 TemplateName, ObjectType,
2616 EnteringContext, Template,
2617 MemberOfUnknownSpecialization);
2618
2619 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2620 Diag(NameLoc, diag::err_destructor_template_id)
2621 << Name << SS.getRange();
2622 // Carry on to parse the template arguments before bailing out.
2623 }
2624 }
2625 break;
2626 }
2627
2628 default:
2629 return false;
2630 }
2631
2632 // Parse the enclosed template argument list.
2633 SourceLocation LAngleLoc, RAngleLoc;
2634 TemplateArgList TemplateArgs;
2635 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs, RAngleLoc,
2636 Template))
2637 return true;
2638
2639 // If this is a non-template, we already issued a diagnostic.
2640 if (TNK == TNK_Non_template)
2641 return true;
2642
2643 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2646 // Form a parsed representation of the template-id to be stored in the
2647 // UnqualifiedId.
2648
2649 // FIXME: Store name for literal operator too.
2650 const IdentifierInfo *TemplateII =
2651 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2652 : nullptr;
2653 OverloadedOperatorKind OpKind =
2655 ? OO_None
2656 : Id.OperatorFunctionId.Operator;
2657
2659 TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2660 LAngleLoc, RAngleLoc, TemplateArgs, /*ArgsInvalid*/false, TemplateIds);
2661
2662 Id.setTemplateId(TemplateId);
2663 return false;
2664 }
2665
2666 // Bundle the template arguments together.
2667 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2668
2669 // Constructor and destructor names.
2671 getCurScope(), SS, TemplateKWLoc, Template, Name, NameLoc, LAngleLoc,
2672 TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true);
2673 if (Type.isInvalid())
2674 return true;
2675
2677 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2678 else
2679 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2680
2681 return false;
2682}
2683
2684/// Parse an operator-function-id or conversion-function-id as part
2685/// of a C++ unqualified-id.
2686///
2687/// This routine is responsible only for parsing the operator-function-id or
2688/// conversion-function-id; it does not handle template arguments in any way.
2689///
2690/// \code
2691/// operator-function-id: [C++ 13.5]
2692/// 'operator' operator
2693///
2694/// operator: one of
2695/// new delete new[] delete[]
2696/// + - * / % ^ & | ~
2697/// ! = < > += -= *= /= %=
2698/// ^= &= |= << >> >>= <<= == !=
2699/// <= >= && || ++ -- , ->* ->
2700/// () [] <=>
2701///
2702/// conversion-function-id: [C++ 12.3.2]
2703/// operator conversion-type-id
2704///
2705/// conversion-type-id:
2706/// type-specifier-seq conversion-declarator[opt]
2707///
2708/// conversion-declarator:
2709/// ptr-operator conversion-declarator[opt]
2710/// \endcode
2711///
2712/// \param SS The nested-name-specifier that preceded this unqualified-id. If
2713/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2714///
2715/// \param EnteringContext whether we are entering the scope of the
2716/// nested-name-specifier.
2717///
2718/// \param ObjectType if this unqualified-id occurs within a member access
2719/// expression, the type of the base object whose member is being accessed.
2720///
2721/// \param Result on a successful parse, contains the parsed unqualified-id.
2722///
2723/// \returns true if parsing fails, false otherwise.
2724bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2725 ParsedType ObjectType,
2727 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2728
2729 // Consume the 'operator' keyword.
2730 SourceLocation KeywordLoc = ConsumeToken();
2731
2732 // Determine what kind of operator name we have.
2733 unsigned SymbolIdx = 0;
2734 SourceLocation SymbolLocations[3];
2736 switch (Tok.getKind()) {
2737 case tok::kw_new:
2738 case tok::kw_delete: {
2739 bool isNew = Tok.getKind() == tok::kw_new;
2740 // Consume the 'new' or 'delete'.
2741 SymbolLocations[SymbolIdx++] = ConsumeToken();
2742 // Check for array new/delete.
2743 if (Tok.is(tok::l_square) &&
2744 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2745 // Consume the '[' and ']'.
2746 BalancedDelimiterTracker T(*this, tok::l_square);
2747 T.consumeOpen();
2748 T.consumeClose();
2749 if (T.getCloseLocation().isInvalid())
2750 return true;
2751
2752 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2753 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2754 Op = isNew? OO_Array_New : OO_Array_Delete;
2755 } else {
2756 Op = isNew? OO_New : OO_Delete;
2757 }
2758 break;
2759 }
2760
2761#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2762 case tok::Token: \
2763 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2764 Op = OO_##Name; \
2765 break;
2766#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2767#include "clang/Basic/OperatorKinds.def"
2768
2769 case tok::l_paren: {
2770 // Consume the '(' and ')'.
2771 BalancedDelimiterTracker T(*this, tok::l_paren);
2772 T.consumeOpen();
2773 T.consumeClose();
2774 if (T.getCloseLocation().isInvalid())
2775 return true;
2776
2777 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2778 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2779 Op = OO_Call;
2780 break;
2781 }
2782
2783 case tok::l_square: {
2784 // Consume the '[' and ']'.
2785 BalancedDelimiterTracker T(*this, tok::l_square);
2786 T.consumeOpen();
2787 T.consumeClose();
2788 if (T.getCloseLocation().isInvalid())
2789 return true;
2790
2791 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2792 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2793 Op = OO_Subscript;
2794 break;
2795 }
2796
2797 case tok::code_completion: {
2798 // Don't try to parse any further.
2799 cutOffParsing();
2800 // Code completion for the operator name.
2802 return true;
2803 }
2804
2805 default:
2806 break;
2807 }
2808
2809 if (Op != OO_None) {
2810 // We have parsed an operator-function-id.
2811 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2812 return false;
2813 }
2814
2815 // Parse a literal-operator-id.
2816 //
2817 // literal-operator-id: C++11 [over.literal]
2818 // operator string-literal identifier
2819 // operator user-defined-string-literal
2820
2821 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2822 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2823
2824 SourceLocation DiagLoc;
2825 unsigned DiagId = 0;
2826
2827 // We're past translation phase 6, so perform string literal concatenation
2828 // before checking for "".
2831 while (isTokenStringLiteral()) {
2832 if (!Tok.is(tok::string_literal) && !DiagId) {
2833 // C++11 [over.literal]p1:
2834 // The string-literal or user-defined-string-literal in a
2835 // literal-operator-id shall have no encoding-prefix [...].
2836 DiagLoc = Tok.getLocation();
2837 DiagId = diag::err_literal_operator_string_prefix;
2838 }
2839 Toks.push_back(Tok);
2840 TokLocs.push_back(ConsumeStringToken());
2841 }
2842
2843 StringLiteralParser Literal(Toks, PP);
2844 if (Literal.hadError)
2845 return true;
2846
2847 // Grab the literal operator's suffix, which will be either the next token
2848 // or a ud-suffix from the string literal.
2849 bool IsUDSuffix = !Literal.getUDSuffix().empty();
2850 IdentifierInfo *II = nullptr;
2851 SourceLocation SuffixLoc;
2852 if (IsUDSuffix) {
2853 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2854 SuffixLoc =
2855 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2856 Literal.getUDSuffixOffset(),
2858 } else if (Tok.is(tok::identifier)) {
2859 II = Tok.getIdentifierInfo();
2860 SuffixLoc = ConsumeToken();
2861 TokLocs.push_back(SuffixLoc);
2862 } else {
2863 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2864 return true;
2865 }
2866
2867 // The string literal must be empty.
2868 if (!Literal.GetString().empty() || Literal.Pascal) {
2869 // C++11 [over.literal]p1:
2870 // The string-literal or user-defined-string-literal in a
2871 // literal-operator-id shall [...] contain no characters
2872 // other than the implicit terminating '\0'.
2873 DiagLoc = TokLocs.front();
2874 DiagId = diag::err_literal_operator_string_not_empty;
2875 }
2876
2877 if (DiagId) {
2878 // This isn't a valid literal-operator-id, but we think we know
2879 // what the user meant. Tell them what they should have written.
2880 SmallString<32> Str;
2881 Str += "\"\"";
2882 Str += II->getName();
2883 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2884 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2885 }
2886
2887 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2888
2889 return Actions.checkLiteralOperatorId(SS, Result, IsUDSuffix);
2890 }
2891
2892 // Parse a conversion-function-id.
2893 //
2894 // conversion-function-id: [C++ 12.3.2]
2895 // operator conversion-type-id
2896 //
2897 // conversion-type-id:
2898 // type-specifier-seq conversion-declarator[opt]
2899 //
2900 // conversion-declarator:
2901 // ptr-operator conversion-declarator[opt]
2902
2903 // Parse the type-specifier-seq.
2904 DeclSpec DS(AttrFactory);
2905 if (ParseCXXTypeSpecifierSeq(
2906 DS, DeclaratorContext::ConversionId)) // FIXME: ObjectType?
2907 return true;
2908
2909 // Parse the conversion-declarator, which is merely a sequence of
2910 // ptr-operators.
2913 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2914
2915 // Finish up the type.
2916 TypeResult Ty = Actions.ActOnTypeName(D);
2917 if (Ty.isInvalid())
2918 return true;
2919
2920 // Note that this is a conversion-function-id.
2921 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2922 D.getSourceRange().getEnd());
2923 return false;
2924}
2925
2926/// Parse a C++ unqualified-id (or a C identifier), which describes the
2927/// name of an entity.
2928///
2929/// \code
2930/// unqualified-id: [C++ expr.prim.general]
2931/// identifier
2932/// operator-function-id
2933/// conversion-function-id
2934/// [C++0x] literal-operator-id [TODO]
2935/// ~ class-name
2936/// template-id
2937///
2938/// \endcode
2939///
2940/// \param SS The nested-name-specifier that preceded this unqualified-id. If
2941/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2942///
2943/// \param ObjectType if this unqualified-id occurs within a member access
2944/// expression, the type of the base object whose member is being accessed.
2945///
2946/// \param ObjectHadErrors if this unqualified-id occurs within a member access
2947/// expression, indicates whether the original subexpressions had any errors.
2948/// When true, diagnostics for missing 'template' keyword will be supressed.
2949///
2950/// \param EnteringContext whether we are entering the scope of the
2951/// nested-name-specifier.
2952///
2953/// \param AllowDestructorName whether we allow parsing of a destructor name.
2954///
2955/// \param AllowConstructorName whether we allow parsing a constructor name.
2956///
2957/// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2958///
2959/// \param Result on a successful parse, contains the parsed unqualified-id.
2960///
2961/// \returns true if parsing fails, false otherwise.
2963 bool ObjectHadErrors, bool EnteringContext,
2964 bool AllowDestructorName,
2965 bool AllowConstructorName,
2966 bool AllowDeductionGuide,
2967 SourceLocation *TemplateKWLoc,
2969 if (TemplateKWLoc)
2970 *TemplateKWLoc = SourceLocation();
2971
2972 // Handle 'A::template B'. This is for template-ids which have not
2973 // already been annotated by ParseOptionalCXXScopeSpecifier().
2974 bool TemplateSpecified = false;
2975 if (Tok.is(tok::kw_template)) {
2976 if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2977 TemplateSpecified = true;
2978 *TemplateKWLoc = ConsumeToken();
2979 } else {
2980 SourceLocation TemplateLoc = ConsumeToken();
2981 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2982 << FixItHint::CreateRemoval(TemplateLoc);
2983 }
2984 }
2985
2986 // unqualified-id:
2987 // identifier
2988 // template-id (when it hasn't already been annotated)
2989 if (Tok.is(tok::identifier)) {
2990 ParseIdentifier:
2991 // Consume the identifier.
2993 SourceLocation IdLoc = ConsumeToken();
2994
2995 if (!getLangOpts().CPlusPlus) {
2996 // If we're not in C++, only identifiers matter. Record the
2997 // identifier and return.
2998 Result.setIdentifier(Id, IdLoc);
2999 return false;
3000 }
3001
3003 if (AllowConstructorName &&
3004 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
3005 // We have parsed a constructor name.
3006 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
3007 EnteringContext);
3008 if (!Ty)
3009 return true;
3010 Result.setConstructorName(Ty, IdLoc, IdLoc);
3011 } else if (getLangOpts().CPlusPlus17 && AllowDeductionGuide &&
3012 SS.isEmpty() &&
3013 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc, SS,
3014 &TemplateName)) {
3015 // We have parsed a template-name naming a deduction guide.
3016 Result.setDeductionGuideName(TemplateName, IdLoc);
3017 } else {
3018 // We have parsed an identifier.
3019 Result.setIdentifier(Id, IdLoc);
3020 }
3021
3022 // If the next token is a '<', we may have a template.
3023 TemplateTy Template;
3024 if (Tok.is(tok::less))
3025 return ParseUnqualifiedIdTemplateId(
3026 SS, ObjectType, ObjectHadErrors,
3027 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
3028 EnteringContext, Result, TemplateSpecified);
3029 else if (TemplateSpecified &&
3030 Actions.ActOnTemplateName(
3031 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
3032 EnteringContext, Template,
3033 /*AllowInjectedClassName*/ true) == TNK_Non_template)
3034 return true;
3035
3036 return false;
3037 }
3038
3039 // unqualified-id:
3040 // template-id (already parsed and annotated)
3041 if (Tok.is(tok::annot_template_id)) {
3042 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
3043
3044 // FIXME: Consider passing invalid template-ids on to callers; they may
3045 // be able to recover better than we can.
3046 if (TemplateId->isInvalid()) {
3047 ConsumeAnnotationToken();
3048 return true;
3049 }
3050
3051 // If the template-name names the current class, then this is a constructor
3052 if (AllowConstructorName && TemplateId->Name &&
3053 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
3054 if (SS.isSet()) {
3055 // C++ [class.qual]p2 specifies that a qualified template-name
3056 // is taken as the constructor name where a constructor can be
3057 // declared. Thus, the template arguments are extraneous, so
3058 // complain about them and remove them entirely.
3059 Diag(TemplateId->TemplateNameLoc,
3060 diag::err_out_of_line_constructor_template_id)
3061 << TemplateId->Name
3063 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
3064 ParsedType Ty = Actions.getConstructorName(
3065 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
3066 EnteringContext);
3067 if (!Ty)
3068 return true;
3069 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
3070 TemplateId->RAngleLoc);
3071 ConsumeAnnotationToken();
3072 return false;
3073 }
3074
3075 Result.setConstructorTemplateId(TemplateId);
3076 ConsumeAnnotationToken();
3077 return false;
3078 }
3079
3080 // We have already parsed a template-id; consume the annotation token as
3081 // our unqualified-id.
3082 Result.setTemplateId(TemplateId);
3083 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
3084 if (TemplateLoc.isValid()) {
3085 if (TemplateKWLoc && (ObjectType || SS.isSet()))
3086 *TemplateKWLoc = TemplateLoc;
3087 else
3088 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
3089 << FixItHint::CreateRemoval(TemplateLoc);
3090 }
3091 ConsumeAnnotationToken();
3092 return false;
3093 }
3094
3095 // unqualified-id:
3096 // operator-function-id
3097 // conversion-function-id
3098 if (Tok.is(tok::kw_operator)) {
3099 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
3100 return true;
3101
3102 // If we have an operator-function-id or a literal-operator-id and the next
3103 // token is a '<', we may have a
3104 //
3105 // template-id:
3106 // operator-function-id < template-argument-list[opt] >
3107 TemplateTy Template;
3110 Tok.is(tok::less))
3111 return ParseUnqualifiedIdTemplateId(
3112 SS, ObjectType, ObjectHadErrors,
3113 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
3114 SourceLocation(), EnteringContext, Result, TemplateSpecified);
3115 else if (TemplateSpecified &&
3116 Actions.ActOnTemplateName(
3117 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
3118 EnteringContext, Template,
3119 /*AllowInjectedClassName*/ true) == TNK_Non_template)
3120 return true;
3121
3122 return false;
3123 }
3124
3125 if (getLangOpts().CPlusPlus &&
3126 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
3127 // C++ [expr.unary.op]p10:
3128 // There is an ambiguity in the unary-expression ~X(), where X is a
3129 // class-name. The ambiguity is resolved in favor of treating ~ as a
3130 // unary complement rather than treating ~X as referring to a destructor.
3131
3132 // Parse the '~'.
3133 SourceLocation TildeLoc = ConsumeToken();
3134
3135 if (TemplateSpecified) {
3136 // C++ [temp.names]p3:
3137 // A name prefixed by the keyword template shall be a template-id [...]
3138 //
3139 // A template-id cannot begin with a '~' token. This would never work
3140 // anyway: x.~A<int>() would specify that the destructor is a template,
3141 // not that 'A' is a template.
3142 //
3143 // FIXME: Suggest replacing the attempted destructor name with a correct
3144 // destructor name and recover. (This is not trivial if this would become
3145 // a pseudo-destructor name).
3146 Diag(*TemplateKWLoc, diag::err_unexpected_template_in_destructor_name)
3147 << Tok.getLocation();
3148 return true;
3149 }
3150
3151 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
3152 DeclSpec DS(AttrFactory);
3153 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
3154 if (ParsedType Type =
3155 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
3156 Result.setDestructorName(TildeLoc, Type, EndLoc);
3157 return false;
3158 }
3159 return true;
3160 }
3161
3162 // Parse the class-name.
3163 if (Tok.isNot(tok::identifier)) {
3164 Diag(Tok, diag::err_destructor_tilde_identifier);
3165 return true;
3166 }
3167
3168 // If the user wrote ~T::T, correct it to T::~T.
3169 DeclaratorScopeObj DeclScopeObj(*this, SS);
3170 if (NextToken().is(tok::coloncolon)) {
3171 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
3172 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
3173 // it will confuse this recovery logic.
3174 ColonProtectionRAIIObject ColonRAII(*this, false);
3175
3176 if (SS.isSet()) {
3177 AnnotateScopeToken(SS, /*NewAnnotation*/true);
3178 SS.clear();
3179 }
3180 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, ObjectHadErrors,
3181 EnteringContext))
3182 return true;
3183 if (SS.isNotEmpty())
3184 ObjectType = nullptr;
3185 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
3186 !SS.isSet()) {
3187 Diag(TildeLoc, diag::err_destructor_tilde_scope);
3188 return true;
3189 }
3190
3191 // Recover as if the tilde had been written before the identifier.
3192 Diag(TildeLoc, diag::err_destructor_tilde_scope)
3193 << FixItHint::CreateRemoval(TildeLoc)
3195
3196 // Temporarily enter the scope for the rest of this function.
3197 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
3198 DeclScopeObj.EnterDeclaratorScope();
3199 }
3200
3201 // Parse the class-name (or template-name in a simple-template-id).
3202 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
3203 SourceLocation ClassNameLoc = ConsumeToken();
3204
3205 if (Tok.is(tok::less)) {
3206 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
3207 return ParseUnqualifiedIdTemplateId(
3208 SS, ObjectType, ObjectHadErrors,
3209 TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
3210 ClassNameLoc, EnteringContext, Result, TemplateSpecified);
3211 }
3212
3213 // Note that this is a destructor name.
3214 ParsedType Ty =
3215 Actions.getDestructorName(*ClassName, ClassNameLoc, getCurScope(), SS,
3216 ObjectType, EnteringContext);
3217 if (!Ty)
3218 return true;
3219
3220 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
3221 return false;
3222 }
3223
3224 switch (Tok.getKind()) {
3225#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
3226#include "clang/Basic/TransformTypeTraits.def"
3227 if (!NextToken().is(tok::l_paren)) {
3228 Tok.setKind(tok::identifier);
3229 Diag(Tok, diag::ext_keyword_as_ident)
3230 << Tok.getIdentifierInfo()->getName() << 0;
3231 goto ParseIdentifier;
3232 }
3233 [[fallthrough]];
3234 default:
3235 Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus;
3236 return true;
3237 }
3238}
3239
3240/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
3241/// memory in a typesafe manner and call constructors.
3242///
3243/// This method is called to parse the new expression after the optional :: has
3244/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
3245/// is its location. Otherwise, "Start" is the location of the 'new' token.
3246///
3247/// new-expression:
3248/// '::'[opt] 'new' new-placement[opt] new-type-id
3249/// new-initializer[opt]
3250/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3251/// new-initializer[opt]
3252///
3253/// new-placement:
3254/// '(' expression-list ')'
3255///
3256/// new-type-id:
3257/// type-specifier-seq new-declarator[opt]
3258/// [GNU] attributes type-specifier-seq new-declarator[opt]
3259///
3260/// new-declarator:
3261/// ptr-operator new-declarator[opt]
3262/// direct-new-declarator
3263///
3264/// new-initializer:
3265/// '(' expression-list[opt] ')'
3266/// [C++0x] braced-init-list
3267///
3269Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
3270 assert(Tok.is(tok::kw_new) && "expected 'new' token");
3271 ConsumeToken(); // Consume 'new'
3272
3273 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
3274 // second form of new-expression. It can't be a new-type-id.
3275
3276 ExprVector PlacementArgs;
3277 SourceLocation PlacementLParen, PlacementRParen;
3278
3279 SourceRange TypeIdParens;
3280 DeclSpec DS(AttrFactory);
3281 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
3283 if (Tok.is(tok::l_paren)) {
3284 // If it turns out to be a placement, we change the type location.
3285 BalancedDelimiterTracker T(*this, tok::l_paren);
3286 T.consumeOpen();
3287 PlacementLParen = T.getOpenLocation();
3288 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
3289 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3290 return ExprError();
3291 }
3292
3293 T.consumeClose();
3294 PlacementRParen = T.getCloseLocation();
3295 if (PlacementRParen.isInvalid()) {
3296 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3297 return ExprError();
3298 }
3299
3300 if (PlacementArgs.empty()) {
3301 // Reset the placement locations. There was no placement.
3302 TypeIdParens = T.getRange();
3303 PlacementLParen = PlacementRParen = SourceLocation();
3304 } else {
3305 // We still need the type.
3306 if (Tok.is(tok::l_paren)) {
3307 BalancedDelimiterTracker T(*this, tok::l_paren);
3308 T.consumeOpen();
3309 MaybeParseGNUAttributes(DeclaratorInfo);
3310 ParseSpecifierQualifierList(DS);
3311 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3312 ParseDeclarator(DeclaratorInfo);
3313 T.consumeClose();
3314 TypeIdParens = T.getRange();
3315 } else {
3316 MaybeParseGNUAttributes(DeclaratorInfo);
3317 if (ParseCXXTypeSpecifierSeq(DS))
3318 DeclaratorInfo.setInvalidType(true);
3319 else {
3320 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3321 ParseDeclaratorInternal(DeclaratorInfo,
3322 &Parser::ParseDirectNewDeclarator);
3323 }
3324 }
3325 }
3326 } else {
3327 // A new-type-id is a simplified type-id, where essentially the
3328 // direct-declarator is replaced by a direct-new-declarator.
3329 MaybeParseGNUAttributes(DeclaratorInfo);
3330 if (ParseCXXTypeSpecifierSeq(DS, DeclaratorContext::CXXNew))
3331 DeclaratorInfo.setInvalidType(true);
3332 else {
3333 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3334 ParseDeclaratorInternal(DeclaratorInfo,
3335 &Parser::ParseDirectNewDeclarator);
3336 }
3337 }
3338 if (DeclaratorInfo.isInvalidType()) {
3339 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3340 return ExprError();
3341 }
3342
3344
3345 if (Tok.is(tok::l_paren)) {
3346 SourceLocation ConstructorLParen, ConstructorRParen;
3347 ExprVector ConstructorArgs;
3348 BalancedDelimiterTracker T(*this, tok::l_paren);
3349 T.consumeOpen();
3350 ConstructorLParen = T.getOpenLocation();
3351 if (Tok.isNot(tok::r_paren)) {
3352 auto RunSignatureHelp = [&]() {
3353 ParsedType TypeRep = Actions.ActOnTypeName(DeclaratorInfo).get();
3354 QualType PreferredType;
3355 // ActOnTypeName might adjust DeclaratorInfo and return a null type even
3356 // the passing DeclaratorInfo is valid, e.g. running SignatureHelp on
3357 // `new decltype(invalid) (^)`.
3358 if (TypeRep)
3359 PreferredType =
3361 TypeRep.get()->getCanonicalTypeInternal(),
3362 DeclaratorInfo.getEndLoc(), ConstructorArgs,
3363 ConstructorLParen,
3364 /*Braced=*/false);
3365 CalledSignatureHelp = true;
3366 return PreferredType;
3367 };
3368 if (ParseExpressionList(ConstructorArgs, [&] {
3369 PreferredType.enterFunctionArgument(Tok.getLocation(),
3370 RunSignatureHelp);
3371 })) {
3372 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3373 RunSignatureHelp();
3374 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3375 return ExprError();
3376 }
3377 }
3378 T.consumeClose();
3379 ConstructorRParen = T.getCloseLocation();
3380 if (ConstructorRParen.isInvalid()) {
3381 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3382 return ExprError();
3383 }
3384 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
3385 ConstructorRParen,
3386 ConstructorArgs);
3387 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
3388 Diag(Tok.getLocation(),
3389 diag::warn_cxx98_compat_generalized_initializer_lists);
3390 Initializer = ParseBraceInitializer();
3391 }
3392 if (Initializer.isInvalid())
3393 return Initializer;
3394
3395 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
3396 PlacementArgs, PlacementRParen,
3397 TypeIdParens, DeclaratorInfo, Initializer.get());
3398}
3399
3400/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
3401/// passed to ParseDeclaratorInternal.
3402///
3403/// direct-new-declarator:
3404/// '[' expression[opt] ']'
3405/// direct-new-declarator '[' constant-expression ']'
3406///
3407void Parser::ParseDirectNewDeclarator(Declarator &D) {
3408 // Parse the array dimensions.
3409 bool First = true;
3410 while (Tok.is(tok::l_square)) {
3411 // An array-size expression can't start with a lambda.
3412 if (CheckProhibitedCXX11Attribute())
3413 continue;
3414
3415 BalancedDelimiterTracker T(*this, tok::l_square);
3416 T.consumeOpen();
3417
3419 First ? (Tok.is(tok::r_square) ? ExprResult() : ParseExpression())
3421 if (Size.isInvalid()) {
3422 // Recover
3423 SkipUntil(tok::r_square, StopAtSemi);
3424 return;
3425 }
3426 First = false;
3427
3428 T.consumeClose();
3429
3430 // Attributes here appertain to the array type. C++11 [expr.new]p5.
3431 ParsedAttributes Attrs(AttrFactory);
3432 MaybeParseCXX11Attributes(Attrs);
3433
3435 /*isStatic=*/false, /*isStar=*/false,
3436 Size.get(), T.getOpenLocation(),
3437 T.getCloseLocation()),
3438 std::move(Attrs), T.getCloseLocation());
3439
3440 if (T.getCloseLocation().isInvalid())
3441 return;
3442 }
3443}
3444
3445/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
3446/// This ambiguity appears in the syntax of the C++ new operator.
3447///
3448/// new-expression:
3449/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3450/// new-initializer[opt]
3451///
3452/// new-placement:
3453/// '(' expression-list ')'
3454///
3455bool Parser::ParseExpressionListOrTypeId(
3456 SmallVectorImpl<Expr*> &PlacementArgs,
3457 Declarator &D) {
3458 // The '(' was already consumed.
3459 if (isTypeIdInParens()) {
3460 ParseSpecifierQualifierList(D.getMutableDeclSpec());
3462 ParseDeclarator(D);
3463 return D.isInvalidType();
3464 }
3465
3466 // It's not a type, it has to be an expression list.
3467 return ParseExpressionList(PlacementArgs);
3468}
3469
3470/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
3471/// to free memory allocated by new.
3472///
3473/// This method is called to parse the 'delete' expression after the optional
3474/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
3475/// and "Start" is its location. Otherwise, "Start" is the location of the
3476/// 'delete' token.
3477///
3478/// delete-expression:
3479/// '::'[opt] 'delete' cast-expression
3480/// '::'[opt] 'delete' '[' ']' cast-expression
3482Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
3483 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
3484 ConsumeToken(); // Consume 'delete'
3485
3486 // Array delete?
3487 bool ArrayDelete = false;
3488 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
3489 // C++11 [expr.delete]p1:
3490 // Whenever the delete keyword is followed by empty square brackets, it
3491 // shall be interpreted as [array delete].
3492 // [Footnote: A lambda expression with a lambda-introducer that consists
3493 // of empty square brackets can follow the delete keyword if
3494 // the lambda expression is enclosed in parentheses.]
3495
3496 const Token Next = GetLookAheadToken(2);
3497
3498 // Basic lookahead to check if we have a lambda expression.
3499 if (Next.isOneOf(tok::l_brace, tok::less) ||
3500 (Next.is(tok::l_paren) &&
3501 (GetLookAheadToken(3).is(tok::r_paren) ||
3502 (GetLookAheadToken(3).is(tok::identifier) &&
3503 GetLookAheadToken(4).is(tok::identifier))))) {
3504 TentativeParsingAction TPA(*this);
3505 SourceLocation LSquareLoc = Tok.getLocation();
3506 SourceLocation RSquareLoc = NextToken().getLocation();
3507
3508 // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this
3509 // case.
3510 SkipUntil({tok::l_brace, tok::less}, StopBeforeMatch);
3511 SourceLocation RBraceLoc;
3512 bool EmitFixIt = false;
3513 if (Tok.is(tok::l_brace)) {
3514 ConsumeBrace();
3515 SkipUntil(tok::r_brace, StopBeforeMatch);
3516 RBraceLoc = Tok.getLocation();
3517 EmitFixIt = true;
3518 }
3519
3520 TPA.Revert();
3521
3522 if (EmitFixIt)
3523 Diag(Start, diag::err_lambda_after_delete)
3524 << SourceRange(Start, RSquareLoc)
3525 << FixItHint::CreateInsertion(LSquareLoc, "(")
3528 RBraceLoc, 0, Actions.getSourceManager(), getLangOpts()),
3529 ")");
3530 else
3531 Diag(Start, diag::err_lambda_after_delete)
3532 << SourceRange(Start, RSquareLoc);
3533
3534 // Warn that the non-capturing lambda isn't surrounded by parentheses
3535 // to disambiguate it from 'delete[]'.
3536 ExprResult Lambda = ParseLambdaExpression();
3537 if (Lambda.isInvalid())
3538 return ExprError();
3539
3540 // Evaluate any postfix expressions used on the lambda.
3541 Lambda = ParsePostfixExpressionSuffix(Lambda);
3542 if (Lambda.isInvalid())
3543 return ExprError();
3544 return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
3545 Lambda.get());
3546 }
3547
3548 ArrayDelete = true;
3549 BalancedDelimiterTracker T(*this, tok::l_square);
3550
3551 T.consumeOpen();
3552 T.consumeClose();
3553 if (T.getCloseLocation().isInvalid())
3554 return ExprError();
3555 }
3556
3557 ExprResult Operand(ParseCastExpression(AnyCastExpr));
3558 if (Operand.isInvalid())
3559 return Operand;
3560
3561 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
3562}
3563
3564/// ParseRequiresExpression - Parse a C++2a requires-expression.
3565/// C++2a [expr.prim.req]p1
3566/// A requires-expression provides a concise way to express requirements on
3567/// template arguments. A requirement is one that can be checked by name
3568/// lookup (6.4) or by checking properties of types and expressions.
3569///
3570/// requires-expression:
3571/// 'requires' requirement-parameter-list[opt] requirement-body
3572///
3573/// requirement-parameter-list:
3574/// '(' parameter-declaration-clause[opt] ')'
3575///
3576/// requirement-body:
3577/// '{' requirement-seq '}'
3578///
3579/// requirement-seq:
3580/// requirement
3581/// requirement-seq requirement
3582///
3583/// requirement:
3584/// simple-requirement
3585/// type-requirement
3586/// compound-requirement
3587/// nested-requirement
3588ExprResult Parser::ParseRequiresExpression() {
3589 assert(Tok.is(tok::kw_requires) && "Expected 'requires' keyword");
3590 SourceLocation RequiresKWLoc = ConsumeToken(); // Consume 'requires'
3591
3592 llvm::SmallVector<ParmVarDecl *, 2> LocalParameterDecls;
3593 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3594 if (Tok.is(tok::l_paren)) {
3595 // requirement parameter list is present.
3596 ParseScope LocalParametersScope(this, Scope::FunctionPrototypeScope |
3598 Parens.consumeOpen();
3599 if (!Tok.is(tok::r_paren)) {
3600 ParsedAttributes FirstArgAttrs(getAttrFactory());
3601 SourceLocation EllipsisLoc;
3603 ParseParameterDeclarationClause(DeclaratorContext::RequiresExpr,
3604 FirstArgAttrs, LocalParameters,
3605 EllipsisLoc);
3606 if (EllipsisLoc.isValid())
3607 Diag(EllipsisLoc, diag::err_requires_expr_parameter_list_ellipsis);
3608 for (auto &ParamInfo : LocalParameters)
3609 LocalParameterDecls.push_back(cast<ParmVarDecl>(ParamInfo.Param));
3610 }
3611 Parens.consumeClose();
3612 }
3613
3614 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3615 if (Braces.expectAndConsume())
3616 return ExprError();
3617
3618 // Start of requirement list
3620
3621 // C++2a [expr.prim.req]p2
3622 // Expressions appearing within a requirement-body are unevaluated operands.
3625
3626 ParseScope BodyScope(this, Scope::DeclScope);
3627 // Create a separate diagnostic pool for RequiresExprBodyDecl.
3628 // Dependent diagnostics are attached to this Decl and non-depenedent
3629 // diagnostics are surfaced after this parse.
3632 RequiresKWLoc, LocalParameterDecls, getCurScope());
3633
3634 if (Tok.is(tok::r_brace)) {
3635 // Grammar does not allow an empty body.
3636 // requirement-body:
3637 // { requirement-seq }
3638 // requirement-seq:
3639 // requirement
3640 // requirement-seq requirement
3641 Diag(Tok, diag::err_empty_requires_expr);
3642 // Continue anyway and produce a requires expr with no requirements.
3643 } else {
3644 while (!Tok.is(tok::r_brace)) {
3645 switch (Tok.getKind()) {
3646 case tok::l_brace: {
3647 // Compound requirement
3648 // C++ [expr.prim.req.compound]
3649 // compound-requirement:
3650 // '{' expression '}' 'noexcept'[opt]
3651 // return-type-requirement[opt] ';'
3652 // return-type-requirement:
3653 // trailing-return-type
3654 // '->' cv-qualifier-seq[opt] constrained-parameter
3655 // cv-qualifier-seq[opt] abstract-declarator[opt]
3656 BalancedDelimiterTracker ExprBraces(*this, tok::l_brace);
3657 ExprBraces.consumeOpen();
3660 if (!Expression.isUsable()) {
3661 ExprBraces.skipToEnd();
3662 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3663 break;
3664 }
3665 if (ExprBraces.consumeClose())
3666 ExprBraces.skipToEnd();
3667
3668 concepts::Requirement *Req = nullptr;
3669 SourceLocation NoexceptLoc;
3670 TryConsumeToken(tok::kw_noexcept, NoexceptLoc);
3671 if (Tok.is(tok::semi)) {
3672 Req = Actions.ActOnCompoundRequirement(Expression.get(), NoexceptLoc);
3673 if (Req)
3674 Requirements.push_back(Req);
3675 break;
3676 }
3677 if (!TryConsumeToken(tok::arrow))
3678 // User probably forgot the arrow, remind them and try to continue.
3679 Diag(Tok, diag::err_requires_expr_missing_arrow)
3681 // Try to parse a 'type-constraint'
3682 if (TryAnnotateTypeConstraint()) {
3683 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3684 break;
3685 }
3686 if (!isTypeConstraintAnnotation()) {
3687 Diag(Tok, diag::err_requires_expr_expected_type_constraint);
3688 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3689 break;
3690 }
3691 CXXScopeSpec SS;
3692 if (Tok.is(tok::annot_cxxscope)) {
3694 Tok.getAnnotationRange(),
3695 SS);
3696 ConsumeAnnotationToken();
3697 }
3698
3699 Req = Actions.ActOnCompoundRequirement(
3700 Expression.get(), NoexceptLoc, SS, takeTemplateIdAnnotation(Tok),
3701 TemplateParameterDepth);
3702 ConsumeAnnotationToken();
3703 if (Req)
3704 Requirements.push_back(Req);
3705 break;
3706 }
3707 default: {
3708 bool PossibleRequiresExprInSimpleRequirement = false;
3709 if (Tok.is(tok::kw_requires)) {
3710 auto IsNestedRequirement = [&] {
3711 RevertingTentativeParsingAction TPA(*this);
3712 ConsumeToken(); // 'requires'
3713 if (Tok.is(tok::l_brace))
3714 // This is a requires expression
3715 // requires (T t) {
3716 // requires { t++; };
3717 // ... ^
3718 // }
3719 return false;
3720 if (Tok.is(tok::l_paren)) {
3721 // This might be the parameter list of a requires expression
3722 ConsumeParen();
3723 auto Res = TryParseParameterDeclarationClause();
3724 if (Res != TPResult::False) {
3725 // Skip to the closing parenthesis
3726 unsigned Depth = 1;
3727 while (Depth != 0) {
3728 bool FoundParen = SkipUntil(tok::l_paren, tok::r_paren,
3730 if (!FoundParen)
3731 break;
3732 if (Tok.is(tok::l_paren))
3733 Depth++;
3734 else if (Tok.is(tok::r_paren))
3735 Depth--;
3737 }
3738 // requires (T t) {
3739 // requires () ?
3740 // ... ^
3741 // - OR -
3742 // requires (int x) ?
3743 // ... ^
3744 // }
3745 if (Tok.is(tok::l_brace))
3746 // requires (...) {
3747 // ^ - a requires expression as a
3748 // simple-requirement.
3749 return false;
3750 }
3751 }
3752 return true;
3753 };
3754 if (IsNestedRequirement()) {
3755 ConsumeToken();
3756 // Nested requirement
3757 // C++ [expr.prim.req.nested]
3758 // nested-requirement:
3759 // 'requires' constraint-expression ';'
3760 ExprResult ConstraintExpr =
3762 if (ConstraintExpr.isInvalid() || !ConstraintExpr.isUsable()) {
3763 SkipUntil(tok::semi, tok::r_brace,
3765 break;
3766 }
3767 if (auto *Req =
3768 Actions.ActOnNestedRequirement(ConstraintExpr.get()))
3769 Requirements.push_back(Req);
3770 else {
3771 SkipUntil(tok::semi, tok::r_brace,
3773 break;
3774 }
3775 break;
3776 } else
3777 PossibleRequiresExprInSimpleRequirement = true;
3778 } else if (Tok.is(tok::kw_typename)) {
3779 // This might be 'typename T::value_type;' (a type requirement) or
3780 // 'typename T::value_type{};' (a simple requirement).
3781 TentativeParsingAction TPA(*this);
3782
3783 // We need to consume the typename to allow 'requires { typename a; }'
3784 SourceLocation TypenameKWLoc = ConsumeToken();
3786 TPA.Commit();
3787 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3788 break;
3789 }
3790 CXXScopeSpec SS;
3791 if (Tok.is(tok::annot_cxxscope)) {
3793 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3794 ConsumeAnnotationToken();
3795 }
3796
3797 if (Tok.isOneOf(tok::identifier, tok::annot_template_id) &&
3798 !NextToken().isOneOf(tok::l_brace, tok::l_paren)) {
3799 TPA.Commit();
3800 SourceLocation NameLoc = Tok.getLocation();
3801 IdentifierInfo *II = nullptr;
3802 TemplateIdAnnotation *TemplateId = nullptr;
3803 if (Tok.is(tok::identifier)) {
3804 II = Tok.getIdentifierInfo();
3805 ConsumeToken();
3806 } else {
3807 TemplateId = takeTemplateIdAnnotation(Tok);
3808 ConsumeAnnotationToken();
3809 if (TemplateId->isInvalid())
3810 break;
3811 }
3812
3813 if (auto *Req = Actions.ActOnTypeRequirement(TypenameKWLoc, SS,
3814 NameLoc, II,
3815 TemplateId)) {
3816 Requirements.push_back(Req);
3817 }
3818 break;
3819 }
3820 TPA.Revert();
3821 }
3822 // Simple requirement
3823 // C++ [expr.prim.req.simple]
3824 // simple-requirement:
3825 // expression ';'
3826 SourceLocation StartLoc = Tok.getLocation();
3829 if (!Expression.isUsable()) {
3830 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3831 break;
3832 }
3833 if (!Expression.isInvalid() && PossibleRequiresExprInSimpleRequirement)
3834 Diag(StartLoc, diag::err_requires_expr_in_simple_requirement)
3835 << FixItHint::CreateInsertion(StartLoc, "requires");
3836 if (auto *Req = Actions.ActOnSimpleRequirement(Expression.get()))
3837 Requirements.push_back(Req);
3838 else {
3839 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3840 break;
3841 }
3842 // User may have tried to put some compound requirement stuff here
3843 if (Tok.is(tok::kw_noexcept)) {
3844 Diag(Tok, diag::err_requires_expr_simple_requirement_noexcept)
3845 << FixItHint::CreateInsertion(StartLoc, "{")
3847 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3848 break;
3849 }
3850 break;
3851 }
3852 }
3853 if (ExpectAndConsumeSemi(diag::err_expected_semi_requirement)) {
3854 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3855 TryConsumeToken(tok::semi);
3856 break;
3857 }
3858 }
3859 if (Requirements.empty()) {
3860 // Don't emit an empty requires expr here to avoid confusing the user with
3861 // other diagnostics quoting an empty requires expression they never
3862 // wrote.
3863 Braces.consumeClose();
3864 Actions.ActOnFinishRequiresExpr();
3865 return ExprError();
3866 }
3867 }
3868 Braces.consumeClose();
3869 Actions.ActOnFinishRequiresExpr();
3870 ParsingBodyDecl.complete(Body);
3871 return Actions.ActOnRequiresExpr(
3872 RequiresKWLoc, Body, Parens.getOpenLocation(), LocalParameterDecls,
3873 Parens.getCloseLocation(), Requirements, Braces.getCloseLocation());
3874}
3875
3877 switch (kind) {
3878 default: llvm_unreachable("Not a known type trait");
3879#define TYPE_TRAIT_1(Spelling, Name, Key) \
3880case tok::kw_ ## Spelling: return UTT_ ## Name;
3881#define TYPE_TRAIT_2(Spelling, Name, Key) \
3882case tok::kw_ ## Spelling: return BTT_ ## Name;
3883#include "clang/Basic/TokenKinds.def"
3884#define TYPE_TRAIT_N(Spelling, Name, Key) \
3885 case tok::kw_ ## Spelling: return TT_ ## Name;
3886#include "clang/Basic/TokenKinds.def"
3887 }
3888}
3889
3891 switch (kind) {
3892 default:
3893 llvm_unreachable("Not a known array type trait");
3894#define ARRAY_TYPE_TRAIT(Spelling, Name, Key) \
3895 case tok::kw_##Spelling: \
3896 return ATT_##Name;
3897#include "clang/Basic/TokenKinds.def"
3898 }
3899}
3900
3902 switch (kind) {
3903 default:
3904 llvm_unreachable("Not a known unary expression trait.");
3905#define EXPRESSION_TRAIT(Spelling, Name, Key) \
3906 case tok::kw_##Spelling: \
3907 return ET_##Name;
3908#include "clang/Basic/TokenKinds.def"
3909 }
3910}
3911
3912/// Parse the built-in type-trait pseudo-functions that allow
3913/// implementation of the TR1/C++11 type traits templates.
3914///
3915/// primary-expression:
3916/// unary-type-trait '(' type-id ')'
3917/// binary-type-trait '(' type-id ',' type-id ')'
3918/// type-trait '(' type-id-seq ')'
3919///
3920/// type-id-seq:
3921/// type-id ...[opt] type-id-seq[opt]
3922///
3923ExprResult Parser::ParseTypeTrait() {
3924 tok::TokenKind Kind = Tok.getKind();
3925
3927
3928 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3929 if (Parens.expectAndConsume())
3930 return ExprError();
3931
3933 do {
3934 // Parse the next type.
3935 TypeResult Ty = ParseTypeName(/*SourceRange=*/nullptr,
3939 if (Ty.isInvalid()) {
3940 Parens.skipToEnd();
3941 return ExprError();
3942 }
3943
3944 // Parse the ellipsis, if present.
3945 if (Tok.is(tok::ellipsis)) {
3946 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3947 if (Ty.isInvalid()) {
3948 Parens.skipToEnd();
3949 return ExprError();
3950 }
3951 }
3952
3953 // Add this type to the list of arguments.
3954 Args.push_back(Ty.get());
3955 } while (TryConsumeToken(tok::comma));
3956
3957 if (Parens.consumeClose())
3958 return ExprError();
3959
3960 SourceLocation EndLoc = Parens.getCloseLocation();
3961
3962 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3963}
3964
3965/// ParseArrayTypeTrait - Parse the built-in array type-trait
3966/// pseudo-functions.
3967///
3968/// primary-expression:
3969/// [Embarcadero] '__array_rank' '(' type-id ')'
3970/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3971///
3972ExprResult Parser::ParseArrayTypeTrait() {
3975
3976 BalancedDelimiterTracker T(*this, tok::l_paren);
3977 if (T.expectAndConsume())
3978 return ExprError();
3979
3980 TypeResult Ty = ParseTypeName(/*SourceRange=*/nullptr,
3982 if (Ty.isInvalid()) {
3983 SkipUntil(tok::comma, StopAtSemi);
3984 SkipUntil(tok::r_paren, StopAtSemi);
3985 return ExprError();
3986 }
3987
3988 switch (ATT) {
3989 case ATT_ArrayRank: {
3990 T.consumeClose();
3991 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3992 T.getCloseLocation());
3993 }
3994 case ATT_ArrayExtent: {
3995 if (ExpectAndConsume(tok::comma)) {
3996 SkipUntil(tok::r_paren, StopAtSemi);
3997 return ExprError();
3998 }
3999
4000 ExprResult DimExpr = ParseExpression();
4001 T.consumeClose();
4002
4003 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
4004 T.getCloseLocation());
4005 }
4006 }
4007 llvm_unreachable("Invalid ArrayTypeTrait!");
4008}
4009
4010/// ParseExpressionTrait - Parse built-in expression-trait
4011/// pseudo-functions like __is_lvalue_expr( xxx ).
4012///
4013/// primary-expression:
4014/// [Embarcadero] expression-trait '(' expression ')'
4015///
4016ExprResult Parser::ParseExpressionTrait() {
4019
4020 BalancedDelimiterTracker T(*this, tok::l_paren);
4021 if (T.expectAndConsume())
4022 return ExprError();
4023
4025
4026 T.consumeClose();
4027
4028 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
4029 T.getCloseLocation());
4030}
4031
4032
4033/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
4034/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
4035/// based on the context past the parens.
4037Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
4038 ParsedType &CastTy,
4039 BalancedDelimiterTracker &Tracker,
4040 ColonProtectionRAIIObject &ColonProt) {
4041 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
4042 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
4043 assert(isTypeIdInParens() && "Not a type-id!");
4044
4045 ExprResult Result(true);
4046 CastTy = nullptr;
4047
4048 // We need to disambiguate a very ugly part of the C++ syntax:
4049 //
4050 // (T())x; - type-id
4051 // (T())*x; - type-id
4052 // (T())/x; - expression
4053 // (T()); - expression
4054 //
4055 // The bad news is that we cannot use the specialized tentative parser, since
4056 // it can only verify that the thing inside the parens can be parsed as
4057 // type-id, it is not useful for determining the context past the parens.
4058 //
4059 // The good news is that the parser can disambiguate this part without
4060 // making any unnecessary Action calls.
4061 //
4062 // It uses a scheme similar to parsing inline methods. The parenthesized
4063 // tokens are cached, the context that follows is determined (possibly by
4064 // parsing a cast-expression), and then we re-introduce the cached tokens
4065 // into the token stream and parse them appropriately.
4066
4067 ParenParseOption ParseAs;
4068 CachedTokens Toks;
4069
4070 // Store the tokens of the parentheses. We will parse them after we determine
4071 // the context that follows them.
4072 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
4073 // We didn't find the ')' we expected.
4074 Tracker.consumeClose();
4075 return ExprError();
4076 }
4077
4078 if (Tok.is(tok::l_brace)) {
4079 ParseAs = CompoundLiteral;
4080 } else {
4081 bool NotCastExpr;
4082 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
4083 NotCastExpr = true;
4084 } else {
4085 // Try parsing the cast-expression that may follow.
4086 // If it is not a cast-expression, NotCastExpr will be true and no token
4087 // will be consumed.
4088 ColonProt.restore();
4089 Result = ParseCastExpression(AnyCastExpr,
4090 false/*isAddressofOperand*/,
4091 NotCastExpr,
4092 // type-id has priority.
4093 IsTypeCast);
4094 }
4095
4096 // If we parsed a cast-expression, it's really a type-id, otherwise it's
4097 // an expression.
4098 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
4099 }
4100
4101 // Create a fake EOF to mark end of Toks buffer.
4102 Token AttrEnd;
4103 AttrEnd.startToken();
4104 AttrEnd.setKind(tok::eof);
4105 AttrEnd.setLocation(Tok.getLocation());
4106 AttrEnd.setEofData(Toks.data());
4107 Toks.push_back(AttrEnd);
4108
4109 // The current token should go after the cached tokens.
4110 Toks.push_back(Tok);
4111 // Re-enter the stored parenthesized tokens into the token stream, so we may
4112 // parse them now.
4113 PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true,
4114 /*IsReinject*/ true);
4115 // Drop the current token and bring the first cached one. It's the same token
4116 // as when we entered this function.
4118
4119 if (ParseAs >= CompoundLiteral) {
4120 // Parse the type declarator.
4121 DeclSpec DS(AttrFactory);
4122 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
4124 {
4125 ColonProtectionRAIIObject InnerColonProtection(*this);
4126 ParseSpecifierQualifierList(DS);
4127 ParseDeclarator(DeclaratorInfo);
4128 }
4129
4130 // Match the ')'.
4131 Tracker.consumeClose();
4132 ColonProt.restore();
4133
4134 // Consume EOF marker for Toks buffer.
4135 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
4137
4138 if (ParseAs == CompoundLiteral) {
4139 ExprType = CompoundLiteral;
4140 if (DeclaratorInfo.isInvalidType())
4141 return ExprError();
4142
4143 TypeResult Ty = Actions.ActOnTypeName(DeclaratorInfo);
4144 return ParseCompoundLiteralExpression(Ty.get(),
4145 Tracker.getOpenLocation(),
4146 Tracker.getCloseLocation());
4147 }
4148
4149 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
4150 assert(ParseAs == CastExpr);
4151
4152 if (DeclaratorInfo.isInvalidType())
4153 return ExprError();
4154
4155 // Result is what ParseCastExpression returned earlier.
4156 if (!Result.isInvalid())
4157 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
4158 DeclaratorInfo, CastTy,
4159 Tracker.getCloseLocation(), Result.get());
4160 return Result;
4161 }
4162
4163 // Not a compound literal, and not followed by a cast-expression.
4164 assert(ParseAs == SimpleExpr);
4165
4166 ExprType = SimpleExpr;
4168 if (!Result.isInvalid() && Tok.is(tok::r_paren))
4169 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
4170 Tok.getLocation(), Result.get());
4171
4172 // Match the ')'.
4173 if (Result.isInvalid()) {
4174 while (Tok.isNot(tok::eof))
4176 assert(Tok.getEofData() == AttrEnd.getEofData());
4178 return ExprError();
4179 }
4180
4181 Tracker.consumeClose();
4182 // Consume EOF marker for Toks buffer.
4183 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
4185 return Result;
4186}
4187
4188/// Parse a __builtin_bit_cast(T, E).
4189ExprResult Parser::ParseBuiltinBitCast() {
4190 SourceLocation KWLoc = ConsumeToken();
4191
4192 BalancedDelimiterTracker T(*this, tok::l_paren);
4193 if (T.expectAndConsume(diag::err_expected_lparen_after, "__builtin_bit_cast"))
4194 return ExprError();
4195
4196 // Parse the common declaration-specifiers piece.
4197 DeclSpec DS(AttrFactory);
4198 ParseSpecifierQualifierList(DS);
4199
4200 // Parse the abstract-declarator, if present.
4201 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
4203 ParseDeclarator(DeclaratorInfo);
4204
4205 if (ExpectAndConsume(tok::comma)) {
4206 Diag(Tok.getLocation(), diag::err_expected) << tok::comma;
4207 SkipUntil(tok::r_paren, StopAtSemi);
4208 return ExprError();
4209 }
4210
4212
4213 if (T.consumeClose())
4214 return ExprError();
4215
4216 if (Operand.isInvalid() || DeclaratorInfo.isInvalidType())
4217 return ExprError();
4218
4219 return Actions.ActOnBuiltinBitCastExpr(KWLoc, DeclaratorInfo, Operand,
4220 T.getCloseLocation());
4221}
Defines the clang::ASTContext interface.
int Id
Definition: ASTDiff.cpp:190
StringRef P
#define SM(sm)
Definition: Cuda.cpp:83
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
StringRef Identifier
Definition: Format.cpp:2983
static void addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc, DeclSpec &DS)
static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken, Token &ColonToken, tok::TokenKind Kind, bool AtDigraph)
static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind)
static void tryConsumeLambdaSpecifierToken(Parser &P, SourceLocation &MutableLoc, SourceLocation &StaticLoc, SourceLocation &ConstexprLoc, SourceLocation &ConstevalLoc, SourceLocation &DeclEndLoc)
static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind)
static void addConstevalToLambdaDeclSpecifier(Parser &P, SourceLocation ConstevalLoc, DeclSpec &DS)
static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind)
static void DiagnoseStaticSpecifierRestrictions(Parser &P, SourceLocation StaticLoc, SourceLocation MutableLoc, const LambdaIntroducer &Intro)
static int SelectDigraphErrorMessage(tok::TokenKind Kind)
static void addStaticToLambdaDeclSpecifier(Parser &P, SourceLocation StaticLoc, DeclSpec &DS)
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
static constexpr bool isOneOf()
This file declares facilities that support code completion.
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
Defines the clang::TokenKind enum and support functions.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:697
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:3483
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:573
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:641
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:1128
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:717
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:856
bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID)
Definition: DeclSpec.cpp:880
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:571
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:706
bool SetBitIntType(SourceLocation KWLoc, Expr *BitWidth, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:967
static const TST TST_double
Definition: DeclSpec.h:291
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:705
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 "_Imaginary" (...
Definition: DeclSpec.cpp:1150
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:959
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:325
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:744
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:445
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1900
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2047
void SetSourceRange(SourceRange R)
Definition: DeclSpec.h:2086
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition: DeclSpec.h:2353
bool isInvalidType() const
Definition: DeclSpec.h:2714
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:2054
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:545
AttributeFactory & getAttrFactory()
Definition: Parser.h:496
static TypeResult getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition: Parser.h:874
ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-or-expression.
Definition: ParseExpr.cpp:380
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:933
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition: Parser.h:573
ExprResult ParseConstantExpression()
Definition: ParseExpr.cpp:233
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:553
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition: Parser.h:510
Scope * getCurScope() const
Definition: Parser.h:499
OpaquePtr< TemplateName > TemplateTy
Definition: Parser.h:511
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:1291
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast=NotTypeCast)
Parse an expr that doesn't include (top-level) commas.
Definition: ParseExpr.cpp:169
const LangOptions & getLangOpts() const
Definition: Parser.h:492
ExprResult ParseExpression(TypeCastState isTypeCast=NotTypeCast)
Simple precedence-based parser for binary/ternary operators.
Definition: ParseExpr.cpp:132
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition: Parser.h:1272
@ StopAtSemi
Stop skipping at semicolon.
Definition: Parser.h:1270
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:869
ExprResult ParseConstraintExpression()
Parse a constraint-expression.
Definition: ParseExpr.cpp:266
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:128
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:940
Represents the body of a requires-expression.
Definition: DeclCXX.h:2029
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:5830
@ 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:2694
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.
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:14737
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:517
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:7999
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)
ActOnCXXThrow - Parse throw expressions.
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition: Sema.cpp:2391
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:1269
ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, ExprResult Operand, SourceLocation RParenLoc)
Definition: SemaCast.cpp:384
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:20292
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2150
SemaCodeCompletion & CodeCompletion()
Definition: Sema.h:988
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:5194
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:275
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)
ActOnCXXNew - Parsed a C++ 'new' expression.
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:4194
SourceManager & getSourceManager() const
Definition: Sema.h:515
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:504
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:7065
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:13959
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:1250
TypeResult ActOnTypeName(Declarator &D)
Definition: SemaType.cpp:6369
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:2157
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:7825
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:9450
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:13438
ParsedType getConstructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext)
Definition: SemaExprCXX.cpp:95
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:1259
concepts::Requirement * ActOnNestedRequirement(Expr *Constraint)
static ConditionResult ConditionError()
Definition: Sema.h:5817
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:202
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:1813
QualType getCanonicalTypeInternal() const
Definition: Type.h:2936
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1025
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition: DeclSpec.h:1113
bool isValid() const
Determine whether this unqualified-id refers to a valid name.
Definition: DeclSpec.h:1101
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.
@ 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:101
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:60
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus17
Definition: LangStandard.h:58
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:2824
@ CopyInit
[a = b], [a = {b}]
DeclaratorContext
Definition: DeclSpec.h:1850
@ 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_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:124
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:1695
Represents a complete lambda introducer.
Definition: DeclSpec.h:2832
bool hasLambdaCapture() const
Definition: DeclSpec.h:2861
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:2866
SourceLocation DefaultLoc
Definition: DeclSpec.h:2855
LambdaCaptureDefault Default
Definition: DeclSpec.h:2856
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:2368
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.