1 //===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the Expression parsing implementation for C++.
11 //===----------------------------------------------------------------------===//
12 #include "clang/Parse/Parser.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/Basic/PrettyStackTrace.h"
18 #include "clang/Lex/LiteralSupport.h"
19 #include "clang/Parse/ParseDiagnostic.h"
20 #include "clang/Parse/RAIIObjectsForParser.h"
21 #include "clang/Sema/DeclSpec.h"
22 #include "clang/Sema/ParsedTemplate.h"
23 #include "clang/Sema/Scope.h"
24 #include "llvm/Support/ErrorHandling.h"
27 using namespace clang;
29 static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
32 case tok::unknown: return 0;
34 case tok::kw_const_cast: return 1;
35 case tok::kw_dynamic_cast: return 2;
36 case tok::kw_reinterpret_cast: return 3;
37 case tok::kw_static_cast: return 4;
39 llvm_unreachable("Unknown type for digraph error message.");
43 // Are the two tokens adjacent in the same source file?
44 bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
45 SourceManager &SM = PP.getSourceManager();
46 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
47 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
48 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
51 // Suggest fixit for "<::" after a cast.
52 static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
53 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
54 // Pull '<:' and ':' off token stream.
60 Range.setBegin(DigraphToken.getLocation());
61 Range.setEnd(ColonToken.getLocation());
62 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
63 << SelectDigraphErrorMessage(Kind)
64 << FixItHint::CreateReplacement(Range, "< ::");
66 // Update token information to reflect their change in token type.
67 ColonToken.setKind(tok::coloncolon);
68 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
69 ColonToken.setLength(2);
70 DigraphToken.setKind(tok::less);
71 DigraphToken.setLength(1);
73 // Push new tokens back to token stream.
74 PP.EnterToken(ColonToken, /*IsReinject*/ true);
76 PP.EnterToken(DigraphToken, /*IsReinject*/ true);
79 // Check for '<::' which should be '< ::' instead of '[:' when following
81 void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
83 IdentifierInfo &II, CXXScopeSpec &SS) {
84 if (!Next.is(tok::l_square) || Next.getLength() != 2)
87 Token SecondToken = GetLookAheadToken(2);
88 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
92 UnqualifiedId TemplateName;
93 TemplateName.setIdentifier(&II, Tok.getLocation());
94 bool MemberOfUnknownSpecialization;
95 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
96 TemplateName, ObjectType, EnteringContext,
97 Template, MemberOfUnknownSpecialization))
100 FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
104 /// Parse global scope or nested-name-specifier if present.
106 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
107 /// may be preceded by '::'). Note that this routine will not parse ::new or
108 /// ::delete; it will just leave them in the token stream.
110 /// '::'[opt] nested-name-specifier
113 /// nested-name-specifier:
115 /// namespace-name '::'
116 /// nested-name-specifier identifier '::'
117 /// nested-name-specifier 'template'[opt] simple-template-id '::'
120 /// \param SS the scope specifier that will be set to the parsed
121 /// nested-name-specifier (or empty)
123 /// \param ObjectType if this nested-name-specifier is being parsed following
124 /// the "." or "->" of a member access expression, this parameter provides the
125 /// type of the object whose members are being accessed.
127 /// \param EnteringContext whether we will be entering into the context of
128 /// the nested-name-specifier after parsing it.
130 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
131 /// indicates whether this nested-name-specifier may be part of a
132 /// pseudo-destructor name. In this case, the flag will be set false
133 /// if we don't actually end up parsing a destructor name. Moreorover,
134 /// if we do end up determining that we are parsing a destructor name,
135 /// the last component of the nested-name-specifier is not parsed as
136 /// part of the scope specifier.
138 /// \param IsTypename If \c true, this nested-name-specifier is known to be
139 /// part of a type name. This is used to improve error recovery.
141 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
142 /// filled in with the leading identifier in the last component of the
143 /// nested-name-specifier, if any.
145 /// \param OnlyNamespace If true, only considers namespaces in lookup.
148 /// \returns true if there was an error parsing a scope specifier
149 bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
150 ParsedType ObjectType,
151 bool EnteringContext,
152 bool *MayBePseudoDestructor,
154 IdentifierInfo **LastII,
156 bool InUsingDeclaration) {
157 assert(getLangOpts().CPlusPlus &&
158 "Call sites of this function should be guarded by checking for C++");
160 if (Tok.is(tok::annot_cxxscope)) {
161 assert(!LastII && "want last identifier but have already annotated scope");
162 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
163 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
164 Tok.getAnnotationRange(),
166 ConsumeAnnotationToken();
170 // Has to happen before any "return false"s in this function.
171 bool CheckForDestructor = false;
172 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
173 CheckForDestructor = true;
174 *MayBePseudoDestructor = false;
180 bool HasScopeSpecifier = false;
182 if (Tok.is(tok::coloncolon)) {
183 // ::new and ::delete aren't nested-name-specifiers.
184 tok::TokenKind NextKind = NextToken().getKind();
185 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
188 if (NextKind == tok::l_brace) {
189 // It is invalid to have :: {, consume the scope qualifier and pretend
190 // like we never saw it.
191 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
193 // '::' - Global scope qualifier.
194 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
197 HasScopeSpecifier = true;
201 if (Tok.is(tok::kw___super)) {
202 SourceLocation SuperLoc = ConsumeToken();
203 if (!Tok.is(tok::coloncolon)) {
204 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
208 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
211 if (!HasScopeSpecifier &&
212 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
213 DeclSpec DS(AttrFactory);
214 SourceLocation DeclLoc = Tok.getLocation();
215 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
217 SourceLocation CCLoc;
218 // Work around a standard defect: 'decltype(auto)::' is not a
219 // nested-name-specifier.
220 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
221 !TryConsumeToken(tok::coloncolon, CCLoc)) {
222 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
226 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
227 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
229 HasScopeSpecifier = true;
232 // Preferred type might change when parsing qualifiers, we need the original.
233 auto SavedType = PreferredType;
235 if (HasScopeSpecifier) {
236 if (Tok.is(tok::code_completion)) {
237 // Code completion for a nested-name-specifier, where the code
238 // completion token follows the '::'.
239 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext,
240 InUsingDeclaration, ObjectType.get(),
241 SavedType.get(SS.getBeginLoc()));
242 // Include code completion token into the range of the scope otherwise
243 // when we try to annotate the scope tokens the dangling code completion
244 // token will cause assertion in
245 // Preprocessor::AnnotatePreviousCachedTokens.
246 SS.setEndLoc(Tok.getLocation());
251 // C++ [basic.lookup.classref]p5:
252 // If the qualified-id has the form
254 // ::class-name-or-namespace-name::...
256 // the class-name-or-namespace-name is looked up in global scope as a
257 // class-name or namespace-name.
259 // To implement this, we clear out the object type as soon as we've
260 // seen a leading '::' or part of a nested-name-specifier.
261 ObjectType = nullptr;
264 // nested-name-specifier:
265 // nested-name-specifier 'template'[opt] simple-template-id '::'
267 // Parse the optional 'template' keyword, then make sure we have
268 // 'identifier <' after it.
269 if (Tok.is(tok::kw_template)) {
270 // If we don't have a scope specifier or an object type, this isn't a
271 // nested-name-specifier, since they aren't allowed to start with
273 if (!HasScopeSpecifier && !ObjectType)
276 TentativeParsingAction TPA(*this);
277 SourceLocation TemplateKWLoc = ConsumeToken();
279 UnqualifiedId TemplateName;
280 if (Tok.is(tok::identifier)) {
281 // Consume the identifier.
282 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
284 } else if (Tok.is(tok::kw_operator)) {
285 // We don't need to actually parse the unqualified-id in this case,
286 // because a simple-template-id cannot start with 'operator', but
287 // go ahead and parse it anyway for consistency with the case where
288 // we already annotated the template-id.
289 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
295 if (TemplateName.getKind() != UnqualifiedIdKind::IK_OperatorFunctionId &&
296 TemplateName.getKind() != UnqualifiedIdKind::IK_LiteralOperatorId) {
297 Diag(TemplateName.getSourceRange().getBegin(),
298 diag::err_id_after_template_in_nested_name_spec)
299 << TemplateName.getSourceRange();
308 // If the next token is not '<', we have a qualified-id that refers
309 // to a template name, such as T::template apply, but is not a
311 if (Tok.isNot(tok::less)) {
316 // Commit to parsing the template-id.
319 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
320 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
321 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
322 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
323 TemplateName, false))
331 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
336 // So we need to check whether the template-id is a simple-template-id of
337 // the right kind (it should name a type or be dependent), and then
338 // convert it into a type within the nested-name-specifier.
339 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
340 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
341 *MayBePseudoDestructor = true;
346 *LastII = TemplateId->Name;
348 // Consume the template-id token.
349 ConsumeAnnotationToken();
351 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
352 SourceLocation CCLoc = ConsumeToken();
354 HasScopeSpecifier = true;
356 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
357 TemplateId->NumArgs);
359 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
361 TemplateId->TemplateKWLoc,
362 TemplateId->Template,
363 TemplateId->TemplateNameLoc,
364 TemplateId->LAngleLoc,
366 TemplateId->RAngleLoc,
369 SourceLocation StartLoc
370 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
371 : TemplateId->TemplateNameLoc;
372 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
378 // The rest of the nested-name-specifier possibilities start with
380 if (Tok.isNot(tok::identifier))
383 IdentifierInfo &II = *Tok.getIdentifierInfo();
385 // nested-name-specifier:
387 // namespace-name '::'
388 // nested-name-specifier identifier '::'
389 Token Next = NextToken();
390 Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
393 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
394 // and emit a fixit hint for it.
395 if (Next.is(tok::colon) && !ColonIsSacred) {
396 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
398 // If the token after the colon isn't an identifier, it's still an
399 // error, but they probably meant something else strange so don't
400 // recover like this.
401 PP.LookAhead(1).is(tok::identifier)) {
402 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
403 << FixItHint::CreateReplacement(Next.getLocation(), "::");
404 // Recover as if the user wrote '::'.
405 Next.setKind(tok::coloncolon);
409 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
410 // It is invalid to have :: {, consume the scope qualifier and pretend
411 // like we never saw it.
412 Token Identifier = Tok; // Stash away the identifier.
413 ConsumeToken(); // Eat the identifier, current token is now '::'.
414 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
416 UnconsumeToken(Identifier); // Stick the identifier back.
417 Next = NextToken(); // Point Next at the '{' token.
420 if (Next.is(tok::coloncolon)) {
421 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
422 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, IdInfo)) {
423 *MayBePseudoDestructor = true;
428 const Token &Next2 = GetLookAheadToken(2);
429 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
430 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
431 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
433 << FixItHint::CreateReplacement(Next.getLocation(), ":");
436 ColonColon.setKind(tok::colon);
437 PP.EnterToken(ColonColon, /*IsReinject*/ true);
445 // We have an identifier followed by a '::'. Lookup this name
446 // as the name in a nested-name-specifier.
447 Token Identifier = Tok;
448 SourceLocation IdLoc = ConsumeToken();
449 assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
450 "NextToken() not working properly!");
451 Token ColonColon = Tok;
452 SourceLocation CCLoc = ConsumeToken();
454 bool IsCorrectedToColon = false;
455 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
456 if (Actions.ActOnCXXNestedNameSpecifier(
457 getCurScope(), IdInfo, EnteringContext, SS, false,
458 CorrectionFlagPtr, OnlyNamespace)) {
459 // Identifier is not recognized as a nested name, but we can have
460 // mistyped '::' instead of ':'.
461 if (CorrectionFlagPtr && IsCorrectedToColon) {
462 ColonColon.setKind(tok::colon);
463 PP.EnterToken(Tok, /*IsReinject*/ true);
464 PP.EnterToken(ColonColon, /*IsReinject*/ true);
468 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
470 HasScopeSpecifier = true;
474 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
476 // nested-name-specifier:
478 if (Next.is(tok::less)) {
481 UnqualifiedId TemplateName;
482 TemplateName.setIdentifier(&II, Tok.getLocation());
483 bool MemberOfUnknownSpecialization;
484 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
485 /*hasTemplateKeyword=*/false,
490 MemberOfUnknownSpecialization)) {
491 // If lookup didn't find anything, we treat the name as a template-name
492 // anyway. C++20 requires this, and in prior language modes it improves
493 // error recovery. But before we commit to this, check that we actually
494 // have something that looks like a template-argument-list next.
495 if (!IsTypename && TNK == TNK_Undeclared_template &&
496 isTemplateArgumentList(1) == TPResult::False)
499 // We have found a template name, so annotate this token
500 // with a template-id annotation. We do not permit the
501 // template-id to be translated into a type annotation,
502 // because some clients (e.g., the parsing of class template
503 // specializations) still want to see the original template-id
504 // token, and it might not be a type at all (e.g. a concept name in a
507 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
508 TemplateName, false))
513 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
514 (IsTypename || isTemplateArgumentList(1) == TPResult::True)) {
515 // We have something like t::getAs<T>, where getAs is a
516 // member of an unknown specialization. However, this will only
517 // parse correctly as a template, so suggest the keyword 'template'
518 // before 'getAs' and treat this as a dependent template name.
519 unsigned DiagID = diag::err_missing_dependent_template_keyword;
520 if (getLangOpts().MicrosoftExt)
521 DiagID = diag::warn_missing_dependent_template_keyword;
523 Diag(Tok.getLocation(), DiagID)
525 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
527 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
528 getCurScope(), SS, Tok.getLocation(), TemplateName, ObjectType,
529 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
530 // Consume the identifier.
532 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
533 TemplateName, false))
543 // We don't have any tokens that form the beginning of a
544 // nested-name-specifier, so we're done.
548 // Even if we didn't see any pieces of a nested-name-specifier, we
549 // still check whether there is a tilde in this position, which
550 // indicates a potential pseudo-destructor.
551 if (CheckForDestructor && Tok.is(tok::tilde))
552 *MayBePseudoDestructor = true;
557 ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS,
558 bool isAddressOfOperand,
559 Token &Replacement) {
562 // We may have already annotated this id-expression.
563 switch (Tok.getKind()) {
564 case tok::annot_non_type: {
565 NamedDecl *ND = getNonTypeAnnotation(Tok);
566 SourceLocation Loc = ConsumeAnnotationToken();
567 E = Actions.ActOnNameClassifiedAsNonType(getCurScope(), SS, ND, Loc, Tok);
571 case tok::annot_non_type_dependent: {
572 IdentifierInfo *II = getIdentifierAnnotation(Tok);
573 SourceLocation Loc = ConsumeAnnotationToken();
575 // This is only the direct operand of an & operator if it is not
576 // followed by a postfix-expression suffix.
577 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
578 isAddressOfOperand = false;
580 E = Actions.ActOnNameClassifiedAsDependentNonType(SS, II, Loc,
585 case tok::annot_non_type_undeclared: {
586 assert(SS.isEmpty() &&
587 "undeclared non-type annotation should be unqualified");
588 IdentifierInfo *II = getIdentifierAnnotation(Tok);
589 SourceLocation Loc = ConsumeAnnotationToken();
590 E = Actions.ActOnNameClassifiedAsUndeclaredNonType(II, Loc);
595 SourceLocation TemplateKWLoc;
597 if (ParseUnqualifiedId(SS,
598 /*EnteringContext=*/false,
599 /*AllowDestructorName=*/false,
600 /*AllowConstructorName=*/false,
601 /*AllowDeductionGuide=*/false,
602 /*ObjectType=*/nullptr, &TemplateKWLoc, Name))
605 // This is only the direct operand of an & operator if it is not
606 // followed by a postfix-expression suffix.
607 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
608 isAddressOfOperand = false;
610 E = Actions.ActOnIdExpression(
611 getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren),
612 isAddressOfOperand, /*CCC=*/nullptr, /*IsInlineAsmIdentifier=*/false,
617 if (!E.isInvalid() && !E.isUnset() && Tok.is(tok::less))
618 checkPotentialAngleBracket(E);
622 /// ParseCXXIdExpression - Handle id-expression.
629 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
631 /// '::' operator-function-id
634 /// NOTE: The standard specifies that, for qualified-id, the parser does not
637 /// '::' conversion-function-id
638 /// '::' '~' class-name
640 /// This may cause a slight inconsistency on diagnostics:
645 /// :: A :: ~ C(); // Some Sema error about using destructor with a
647 /// :: ~ C(); // Some Parser error like 'unexpected ~'.
650 /// We simplify the parser a bit and make it work like:
653 /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
654 /// '::' unqualified-id
656 /// That way Sema can handle and report similar errors for namespaces and the
659 /// The isAddressOfOperand parameter indicates that this id-expression is a
660 /// direct operand of the address-of operator. This is, besides member contexts,
661 /// the only place where a qualified-id naming a non-static class member may
664 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
666 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
667 // '::' unqualified-id
670 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
674 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
675 if (Result.isUnset()) {
676 // If the ExprResult is valid but null, then typo correction suggested a
677 // keyword replacement that needs to be reparsed.
678 UnconsumeToken(Replacement);
679 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
681 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
682 "for a previous keyword suggestion");
686 /// ParseLambdaExpression - Parse a C++11 lambda expression.
688 /// lambda-expression:
689 /// lambda-introducer lambda-declarator[opt] compound-statement
690 /// lambda-introducer '<' template-parameter-list '>'
691 /// lambda-declarator[opt] compound-statement
693 /// lambda-introducer:
694 /// '[' lambda-capture[opt] ']'
699 /// capture-default ',' capture-list
707 /// capture-list ',' capture
711 /// init-capture [C++1y]
718 /// init-capture: [C++1y]
719 /// identifier initializer
720 /// '&' identifier initializer
722 /// lambda-declarator:
723 /// '(' parameter-declaration-clause ')' attribute-specifier[opt]
724 /// 'mutable'[opt] exception-specification[opt]
725 /// trailing-return-type[opt]
727 ExprResult Parser::ParseLambdaExpression() {
728 // Parse lambda-introducer.
729 LambdaIntroducer Intro;
730 if (ParseLambdaIntroducer(Intro)) {
731 SkipUntil(tok::r_square, StopAtSemi);
732 SkipUntil(tok::l_brace, StopAtSemi);
733 SkipUntil(tok::r_brace, StopAtSemi);
737 return ParseLambdaExpressionAfterIntroducer(Intro);
740 /// Use lookahead and potentially tentative parsing to determine if we are
741 /// looking at a C++11 lambda expression, and parse it if we are.
743 /// If we are not looking at a lambda expression, returns ExprError().
744 ExprResult Parser::TryParseLambdaExpression() {
745 assert(getLangOpts().CPlusPlus11
746 && Tok.is(tok::l_square)
747 && "Not at the start of a possible lambda expression.");
749 const Token Next = NextToken();
750 if (Next.is(tok::eof)) // Nothing else to lookup here...
753 const Token After = GetLookAheadToken(2);
754 // If lookahead indicates this is a lambda...
755 if (Next.is(tok::r_square) || // []
756 Next.is(tok::equal) || // [=
757 (Next.is(tok::amp) && // [&] or [&,
758 After.isOneOf(tok::r_square, tok::comma)) ||
759 (Next.is(tok::identifier) && // [identifier]
760 After.is(tok::r_square)) ||
761 Next.is(tok::ellipsis)) { // [...
762 return ParseLambdaExpression();
765 // If lookahead indicates an ObjC message send...
766 // [identifier identifier
767 if (Next.is(tok::identifier) && After.is(tok::identifier))
770 // Here, we're stuck: lambda introducers and Objective-C message sends are
771 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
772 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
773 // writing two routines to parse a lambda introducer, just try to parse
774 // a lambda introducer first, and fall back if that fails.
775 LambdaIntroducer Intro;
777 TentativeParsingAction TPA(*this);
778 LambdaIntroducerTentativeParse Tentative;
779 if (ParseLambdaIntroducer(Intro, &Tentative)) {
785 case LambdaIntroducerTentativeParse::Success:
789 case LambdaIntroducerTentativeParse::Incomplete:
790 // Didn't fully parse the lambda-introducer, try again with a
791 // non-tentative parse.
793 Intro = LambdaIntroducer();
794 if (ParseLambdaIntroducer(Intro))
798 case LambdaIntroducerTentativeParse::MessageSend:
799 case LambdaIntroducerTentativeParse::Invalid:
800 // Not a lambda-introducer, might be a message send.
806 return ParseLambdaExpressionAfterIntroducer(Intro);
809 /// Parse a lambda introducer.
810 /// \param Intro A LambdaIntroducer filled in with information about the
811 /// contents of the lambda-introducer.
812 /// \param Tentative If non-null, we are disambiguating between a
813 /// lambda-introducer and some other construct. In this mode, we do not
814 /// produce any diagnostics or take any other irreversible action unless
815 /// we're sure that this is a lambda-expression.
816 /// \return \c true if parsing (or disambiguation) failed with a diagnostic and
817 /// the caller should bail out / recover.
818 bool Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
819 LambdaIntroducerTentativeParse *Tentative) {
821 *Tentative = LambdaIntroducerTentativeParse::Success;
823 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
824 BalancedDelimiterTracker T(*this, tok::l_square);
827 Intro.Range.setBegin(T.getOpenLocation());
831 // Produce a diagnostic if we're not tentatively parsing; otherwise track
832 // that our parse has failed.
833 auto Invalid = [&](llvm::function_ref<void()> Action) {
835 *Tentative = LambdaIntroducerTentativeParse::Invalid;
842 // Perform some irreversible action if this is a non-tentative parse;
843 // otherwise note that our actions were incomplete.
844 auto NonTentativeAction = [&](llvm::function_ref<void()> Action) {
846 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
851 // Parse capture-default.
852 if (Tok.is(tok::amp) &&
853 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
854 Intro.Default = LCD_ByRef;
855 Intro.DefaultLoc = ConsumeToken();
857 if (!Tok.getIdentifierInfo()) {
858 // This can only be a lambda; no need for tentative parsing any more.
859 // '[[and]]' can still be an attribute, though.
862 } else if (Tok.is(tok::equal)) {
863 Intro.Default = LCD_ByCopy;
864 Intro.DefaultLoc = ConsumeToken();
869 while (Tok.isNot(tok::r_square)) {
871 if (Tok.isNot(tok::comma)) {
872 // Provide a completion for a lambda introducer here. Except
873 // in Objective-C, where this is Almost Surely meant to be a message
874 // send. In that case, fail here and let the ObjC message
875 // expression parser perform the completion.
876 if (Tok.is(tok::code_completion) &&
877 !(getLangOpts().ObjC && Tentative)) {
878 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
879 /*AfterAmpersand=*/false);
885 Diag(Tok.getLocation(), diag::err_expected_comma_or_rsquare);
891 if (Tok.is(tok::code_completion)) {
892 // If we're in Objective-C++ and we have a bare '[', then this is more
893 // likely to be a message receiver.
894 if (getLangOpts().ObjC && Tentative && First)
895 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
897 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
898 /*AfterAmpersand=*/false);
906 LambdaCaptureKind Kind = LCK_ByCopy;
907 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
909 IdentifierInfo *Id = nullptr;
910 SourceLocation EllipsisLocs[4];
912 SourceLocation LocStart = Tok.getLocation();
914 if (Tok.is(tok::star)) {
915 Loc = ConsumeToken();
916 if (Tok.is(tok::kw_this)) {
921 Diag(Tok.getLocation(), diag::err_expected_star_this_capture);
924 } else if (Tok.is(tok::kw_this)) {
926 Loc = ConsumeToken();
928 TryConsumeToken(tok::ellipsis, EllipsisLocs[0]);
930 if (Tok.is(tok::amp)) {
934 if (Tok.is(tok::code_completion)) {
935 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
936 /*AfterAmpersand=*/true);
942 TryConsumeToken(tok::ellipsis, EllipsisLocs[1]);
944 if (Tok.is(tok::identifier)) {
945 Id = Tok.getIdentifierInfo();
946 Loc = ConsumeToken();
947 } else if (Tok.is(tok::kw_this)) {
949 // FIXME: Suggest a fixit here.
950 Diag(Tok.getLocation(), diag::err_this_captured_by_reference);
954 Diag(Tok.getLocation(), diag::err_expected_capture);
958 TryConsumeToken(tok::ellipsis, EllipsisLocs[2]);
960 if (Tok.is(tok::l_paren)) {
961 BalancedDelimiterTracker Parens(*this, tok::l_paren);
962 Parens.consumeOpen();
964 InitKind = LambdaCaptureInitKind::DirectInit;
970 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
971 } else if (ParseExpressionList(Exprs, Commas)) {
975 Parens.consumeClose();
976 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
977 Parens.getCloseLocation(),
980 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
981 // Each lambda init-capture forms its own full expression, which clears
982 // Actions.MaybeODRUseExprs. So create an expression evaluation context
983 // to save the necessary state, and restore it later.
984 EnterExpressionEvaluationContext EC(
985 Actions, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
987 if (TryConsumeToken(tok::equal))
988 InitKind = LambdaCaptureInitKind::CopyInit;
990 InitKind = LambdaCaptureInitKind::ListInit;
993 Init = ParseInitializer();
994 } else if (Tok.is(tok::l_brace)) {
995 BalancedDelimiterTracker Braces(*this, tok::l_brace);
996 Braces.consumeOpen();
998 *Tentative = LambdaIntroducerTentativeParse::Incomplete;
1000 // We're disambiguating this:
1004 // We need to find the end of the following expression in order to
1005 // determine whether this is an Obj-C message send's receiver, a
1006 // C99 designator, or a lambda init-capture.
1008 // Parse the expression to find where it ends, and annotate it back
1009 // onto the tokens. We would have parsed this expression the same way
1010 // in either case: both the RHS of an init-capture and the RHS of an
1011 // assignment expression are parsed as an initializer-clause, and in
1012 // neither case can anything be added to the scope between the '[' and
1015 // FIXME: This is horrible. Adding a mechanism to skip an expression
1016 // would be much cleaner.
1017 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
1018 // that instead. (And if we see a ':' with no matching '?', we can
1019 // classify this as an Obj-C message send.)
1020 SourceLocation StartLoc = Tok.getLocation();
1021 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
1022 Init = ParseInitializer();
1023 if (!Init.isInvalid())
1024 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
1026 if (Tok.getLocation() != StartLoc) {
1027 // Back out the lexing of the token after the initializer.
1028 PP.RevertCachedTokens(1);
1030 // Replace the consumed tokens with an appropriate annotation.
1031 Tok.setLocation(StartLoc);
1032 Tok.setKind(tok::annot_primary_expr);
1033 setExprAnnotation(Tok, Init);
1034 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
1035 PP.AnnotateCachedTokens(Tok);
1037 // Consume the annotated initializer.
1038 ConsumeAnnotationToken();
1043 TryConsumeToken(tok::ellipsis, EllipsisLocs[3]);
1046 // Check if this is a message send before we act on a possible init-capture.
1047 if (Tentative && Tok.is(tok::identifier) &&
1048 NextToken().isOneOf(tok::colon, tok::r_square)) {
1049 // This can only be a message send. We're done with disambiguation.
1050 *Tentative = LambdaIntroducerTentativeParse::MessageSend;
1054 // Ensure that any ellipsis was in the right place.
1055 SourceLocation EllipsisLoc;
1056 if (std::any_of(std::begin(EllipsisLocs), std::end(EllipsisLocs),
1057 [](SourceLocation Loc) { return Loc.isValid(); })) {
1058 // The '...' should appear before the identifier in an init-capture, and
1059 // after the identifier otherwise.
1060 bool InitCapture = InitKind != LambdaCaptureInitKind::NoInit;
1061 SourceLocation *ExpectedEllipsisLoc =
1062 !InitCapture ? &EllipsisLocs[2] :
1063 Kind == LCK_ByRef ? &EllipsisLocs[1] :
1065 EllipsisLoc = *ExpectedEllipsisLoc;
1067 unsigned DiagID = 0;
1068 if (EllipsisLoc.isInvalid()) {
1069 DiagID = diag::err_lambda_capture_misplaced_ellipsis;
1070 for (SourceLocation Loc : EllipsisLocs) {
1075 unsigned NumEllipses = std::accumulate(
1076 std::begin(EllipsisLocs), std::end(EllipsisLocs), 0,
1077 [](int N, SourceLocation Loc) { return N + Loc.isValid(); });
1078 if (NumEllipses > 1)
1079 DiagID = diag::err_lambda_capture_multiple_ellipses;
1082 NonTentativeAction([&] {
1083 // Point the diagnostic at the first misplaced ellipsis.
1084 SourceLocation DiagLoc;
1085 for (SourceLocation &Loc : EllipsisLocs) {
1086 if (&Loc != ExpectedEllipsisLoc && Loc.isValid()) {
1091 assert(DiagLoc.isValid() && "no location for diagnostic");
1093 // Issue the diagnostic and produce fixits showing where the ellipsis
1094 // should have been written.
1095 auto &&D = Diag(DiagLoc, DiagID);
1096 if (DiagID == diag::err_lambda_capture_misplaced_ellipsis) {
1097 SourceLocation ExpectedLoc =
1099 : Lexer::getLocForEndOfToken(
1100 Loc, 0, PP.getSourceManager(), getLangOpts());
1101 D << InitCapture << FixItHint::CreateInsertion(ExpectedLoc, "...");
1103 for (SourceLocation &Loc : EllipsisLocs) {
1104 if (&Loc != ExpectedEllipsisLoc && Loc.isValid())
1105 D << FixItHint::CreateRemoval(Loc);
1111 // Process the init-capture initializers now rather than delaying until we
1112 // form the lambda-expression so that they can be handled in the context
1113 // enclosing the lambda-expression, rather than in the context of the
1114 // lambda-expression itself.
1115 ParsedType InitCaptureType;
1116 if (Init.isUsable())
1117 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
1118 if (Init.isUsable()) {
1119 NonTentativeAction([&] {
1120 // Get the pointer and store it in an lvalue, so we can use it as an
1122 Expr *InitExpr = Init.get();
1123 // This performs any lvalue-to-rvalue conversions if necessary, which
1124 // can affect what gets captured in the containing decl-context.
1125 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
1126 Loc, Kind == LCK_ByRef, EllipsisLoc, Id, InitKind, InitExpr);
1131 SourceLocation LocEnd = PrevTokLocation;
1133 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
1134 InitCaptureType, SourceRange(LocStart, LocEnd));
1138 Intro.Range.setEnd(T.getCloseLocation());
1142 static void tryConsumeLambdaSpecifierToken(Parser &P,
1143 SourceLocation &MutableLoc,
1144 SourceLocation &ConstexprLoc,
1145 SourceLocation &ConstevalLoc,
1146 SourceLocation &DeclEndLoc) {
1147 assert(MutableLoc.isInvalid());
1148 assert(ConstexprLoc.isInvalid());
1149 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1150 // to the final of those locations. Emit an error if we have multiple
1151 // copies of those keywords and recover.
1154 switch (P.getCurToken().getKind()) {
1155 case tok::kw_mutable: {
1156 if (MutableLoc.isValid()) {
1157 P.Diag(P.getCurToken().getLocation(),
1158 diag::err_lambda_decl_specifier_repeated)
1159 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1161 MutableLoc = P.ConsumeToken();
1162 DeclEndLoc = MutableLoc;
1165 case tok::kw_constexpr:
1166 if (ConstexprLoc.isValid()) {
1167 P.Diag(P.getCurToken().getLocation(),
1168 diag::err_lambda_decl_specifier_repeated)
1169 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1171 ConstexprLoc = P.ConsumeToken();
1172 DeclEndLoc = ConstexprLoc;
1174 case tok::kw_consteval:
1175 if (ConstevalLoc.isValid()) {
1176 P.Diag(P.getCurToken().getLocation(),
1177 diag::err_lambda_decl_specifier_repeated)
1178 << 2 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1180 ConstevalLoc = P.ConsumeToken();
1181 DeclEndLoc = ConstevalLoc;
1190 addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1192 if (ConstexprLoc.isValid()) {
1193 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus17
1194 ? diag::ext_constexpr_on_lambda_cxx17
1195 : diag::warn_cxx14_compat_constexpr_on_lambda);
1196 const char *PrevSpec = nullptr;
1197 unsigned DiagID = 0;
1198 DS.SetConstexprSpec(CSK_constexpr, ConstexprLoc, PrevSpec, DiagID);
1199 assert(PrevSpec == nullptr && DiagID == 0 &&
1200 "Constexpr cannot have been set previously!");
1204 static void addConstevalToLambdaDeclSpecifier(Parser &P,
1205 SourceLocation ConstevalLoc,
1207 if (ConstevalLoc.isValid()) {
1208 P.Diag(ConstevalLoc, diag::warn_cxx20_compat_consteval);
1209 const char *PrevSpec = nullptr;
1210 unsigned DiagID = 0;
1211 DS.SetConstexprSpec(CSK_consteval, ConstevalLoc, PrevSpec, DiagID);
1213 P.Diag(ConstevalLoc, DiagID) << PrevSpec;
1217 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1219 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1220 LambdaIntroducer &Intro) {
1221 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1222 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1224 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1225 "lambda expression parsing");
1229 // FIXME: Call into Actions to add any init-capture declarations to the
1230 // scope while parsing the lambda-declarator and compound-statement.
1232 // Parse lambda-declarator[opt].
1233 DeclSpec DS(AttrFactory);
1234 Declarator D(DS, DeclaratorContext::LambdaExprContext);
1235 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1236 Actions.PushLambdaScope();
1238 ParsedAttributes Attr(AttrFactory);
1239 SourceLocation DeclLoc = Tok.getLocation();
1240 if (getLangOpts().CUDA) {
1241 // In CUDA code, GNU attributes are allowed to appear immediately after the
1242 // "[...]", even if there is no "(...)" before the lambda body.
1243 MaybeParseGNUAttributes(D);
1246 // Helper to emit a warning if we see a CUDA host/device/global attribute
1247 // after '(...)'. nvcc doesn't accept this.
1248 auto WarnIfHasCUDATargetAttr = [&] {
1249 if (getLangOpts().CUDA)
1250 for (const ParsedAttr &A : Attr)
1251 if (A.getKind() == ParsedAttr::AT_CUDADevice ||
1252 A.getKind() == ParsedAttr::AT_CUDAHost ||
1253 A.getKind() == ParsedAttr::AT_CUDAGlobal)
1254 Diag(A.getLoc(), diag::warn_cuda_attr_lambda_position)
1255 << A.getAttrName()->getName();
1258 // FIXME: Consider allowing this as an extension for GCC compatibiblity.
1259 const bool HasExplicitTemplateParams = Tok.is(tok::less);
1260 ParseScope TemplateParamScope(this, Scope::TemplateParamScope,
1261 /*EnteredScope=*/HasExplicitTemplateParams);
1262 if (HasExplicitTemplateParams) {
1263 Diag(Tok, getLangOpts().CPlusPlus2a
1264 ? diag::warn_cxx17_compat_lambda_template_parameter_list
1265 : diag::ext_lambda_template_parameter_list);
1267 SmallVector<NamedDecl*, 4> TemplateParams;
1268 SourceLocation LAngleLoc, RAngleLoc;
1269 if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(),
1270 TemplateParams, LAngleLoc, RAngleLoc)) {
1271 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1275 if (TemplateParams.empty()) {
1277 diag::err_lambda_template_parameter_list_empty);
1279 Actions.ActOnLambdaExplicitTemplateParameterList(
1280 LAngleLoc, TemplateParams, RAngleLoc);
1281 ++CurTemplateDepthTracker;
1285 TypeResult TrailingReturnType;
1286 if (Tok.is(tok::l_paren)) {
1287 ParseScope PrototypeScope(this,
1288 Scope::FunctionPrototypeScope |
1289 Scope::FunctionDeclarationScope |
1292 BalancedDelimiterTracker T(*this, tok::l_paren);
1294 SourceLocation LParenLoc = T.getOpenLocation();
1296 // Parse parameter-declaration-clause.
1297 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
1298 SourceLocation EllipsisLoc;
1300 if (Tok.isNot(tok::r_paren)) {
1301 Actions.RecordParsingTemplateParameterDepth(
1302 CurTemplateDepthTracker.getOriginalDepth());
1304 ParseParameterDeclarationClause(D.getContext(), Attr, ParamInfo,
1306 // For a generic lambda, each 'auto' within the parameter declaration
1307 // clause creates a template type parameter, so increment the depth.
1308 // If we've parsed any explicit template parameters, then the depth will
1309 // have already been incremented. So we make sure that at most a single
1310 // depth level is added.
1311 if (Actions.getCurGenericLambda())
1312 CurTemplateDepthTracker.setAddedDepth(1);
1316 SourceLocation RParenLoc = T.getCloseLocation();
1317 SourceLocation DeclEndLoc = RParenLoc;
1319 // GNU-style attributes must be parsed before the mutable specifier to be
1320 // compatible with GCC.
1321 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1323 // MSVC-style attributes must be parsed before the mutable specifier to be
1324 // compatible with MSVC.
1325 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
1327 // Parse mutable-opt and/or constexpr-opt or consteval-opt, and update the
1329 SourceLocation MutableLoc;
1330 SourceLocation ConstexprLoc;
1331 SourceLocation ConstevalLoc;
1332 tryConsumeLambdaSpecifierToken(*this, MutableLoc, ConstexprLoc,
1333 ConstevalLoc, DeclEndLoc);
1335 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
1336 addConstevalToLambdaDeclSpecifier(*this, ConstevalLoc, DS);
1337 // Parse exception-specification[opt].
1338 ExceptionSpecificationType ESpecType = EST_None;
1339 SourceRange ESpecRange;
1340 SmallVector<ParsedType, 2> DynamicExceptions;
1341 SmallVector<SourceRange, 2> DynamicExceptionRanges;
1342 ExprResult NoexceptExpr;
1343 CachedTokens *ExceptionSpecTokens;
1344 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1347 DynamicExceptionRanges,
1349 ExceptionSpecTokens);
1351 if (ESpecType != EST_None)
1352 DeclEndLoc = ESpecRange.getEnd();
1354 // Parse attribute-specifier[opt].
1355 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1357 // Parse OpenCL addr space attribute.
1358 if (Tok.isOneOf(tok::kw___private, tok::kw___global, tok::kw___local,
1359 tok::kw___constant, tok::kw___generic)) {
1360 ParseOpenCLQualifiers(DS.getAttributes());
1364 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1366 // Parse trailing-return-type[opt].
1367 if (Tok.is(tok::arrow)) {
1368 FunLocalRangeEnd = Tok.getLocation();
1370 TrailingReturnType =
1371 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1372 if (Range.getEnd().isValid())
1373 DeclEndLoc = Range.getEnd();
1376 SourceLocation NoLoc;
1377 D.AddTypeInfo(DeclaratorChunk::getFunction(
1379 /*IsAmbiguous=*/false, LParenLoc, ParamInfo.data(),
1380 ParamInfo.size(), EllipsisLoc, RParenLoc,
1381 /*RefQualifierIsLvalueRef=*/true,
1382 /*RefQualifierLoc=*/NoLoc, MutableLoc, ESpecType,
1383 ESpecRange, DynamicExceptions.data(),
1384 DynamicExceptionRanges.data(), DynamicExceptions.size(),
1385 NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr,
1386 /*ExceptionSpecTokens*/ nullptr,
1387 /*DeclsInPrototype=*/None, LParenLoc, FunLocalRangeEnd, D,
1388 TrailingReturnType, &DS),
1389 std::move(Attr), DeclEndLoc);
1391 // Parse requires-clause[opt].
1392 if (Tok.is(tok::kw_requires))
1393 ParseTrailingRequiresClause(D);
1395 PrototypeScope.Exit();
1397 WarnIfHasCUDATargetAttr();
1398 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1399 tok::kw_constexpr, tok::kw_consteval,
1400 tok::kw___private, tok::kw___global, tok::kw___local,
1401 tok::kw___constant, tok::kw___generic,
1402 tok::kw_requires) ||
1403 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1404 // It's common to forget that one needs '()' before 'mutable', an attribute
1405 // specifier, the result type, or the requires clause. Deal with this.
1406 unsigned TokKind = 0;
1407 switch (Tok.getKind()) {
1408 case tok::kw_mutable: TokKind = 0; break;
1409 case tok::arrow: TokKind = 1; break;
1410 case tok::kw___attribute:
1411 case tok::kw___private:
1412 case tok::kw___global:
1413 case tok::kw___local:
1414 case tok::kw___constant:
1415 case tok::kw___generic:
1416 case tok::l_square: TokKind = 2; break;
1417 case tok::kw_constexpr: TokKind = 3; break;
1418 case tok::kw_consteval: TokKind = 4; break;
1419 case tok::kw_requires: TokKind = 5; break;
1420 default: llvm_unreachable("Unknown token kind");
1423 Diag(Tok, diag::err_lambda_missing_parens)
1425 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1426 SourceLocation DeclEndLoc = DeclLoc;
1428 // GNU-style attributes must be parsed before the mutable specifier to be
1429 // compatible with GCC.
1430 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1432 // Parse 'mutable', if it's there.
1433 SourceLocation MutableLoc;
1434 if (Tok.is(tok::kw_mutable)) {
1435 MutableLoc = ConsumeToken();
1436 DeclEndLoc = MutableLoc;
1439 // Parse attribute-specifier[opt].
1440 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1442 // Parse the return type, if there is one.
1443 if (Tok.is(tok::arrow)) {
1445 TrailingReturnType =
1446 ParseTrailingReturnType(Range, /*MayBeFollowedByDirectInit*/ false);
1447 if (Range.getEnd().isValid())
1448 DeclEndLoc = Range.getEnd();
1451 SourceLocation NoLoc;
1452 D.AddTypeInfo(DeclaratorChunk::getFunction(
1454 /*IsAmbiguous=*/false,
1455 /*LParenLoc=*/NoLoc,
1458 /*EllipsisLoc=*/NoLoc,
1459 /*RParenLoc=*/NoLoc,
1460 /*RefQualifierIsLvalueRef=*/true,
1461 /*RefQualifierLoc=*/NoLoc, MutableLoc, EST_None,
1462 /*ESpecRange=*/SourceRange(),
1463 /*Exceptions=*/nullptr,
1464 /*ExceptionRanges=*/nullptr,
1465 /*NumExceptions=*/0,
1466 /*NoexceptExpr=*/nullptr,
1467 /*ExceptionSpecTokens=*/nullptr,
1468 /*DeclsInPrototype=*/None, DeclLoc, DeclEndLoc, D,
1469 TrailingReturnType),
1470 std::move(Attr), DeclEndLoc);
1472 // Parse the requires-clause, if present.
1473 if (Tok.is(tok::kw_requires))
1474 ParseTrailingRequiresClause(D);
1476 WarnIfHasCUDATargetAttr();
1479 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1481 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope |
1482 Scope::CompoundStmtScope;
1483 ParseScope BodyScope(this, ScopeFlags);
1485 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1487 // Parse compound-statement.
1488 if (!Tok.is(tok::l_brace)) {
1489 Diag(Tok, diag::err_expected_lambda_body);
1490 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1494 StmtResult Stmt(ParseCompoundStatementBody());
1496 TemplateParamScope.Exit();
1498 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
1499 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
1501 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1505 /// ParseCXXCasts - This handles the various ways to cast expressions to another
1508 /// postfix-expression: [C++ 5.2p1]
1509 /// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1510 /// 'static_cast' '<' type-name '>' '(' expression ')'
1511 /// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1512 /// 'const_cast' '<' type-name '>' '(' expression ')'
1514 ExprResult Parser::ParseCXXCasts() {
1515 tok::TokenKind Kind = Tok.getKind();
1516 const char *CastName = nullptr; // For error messages
1519 default: llvm_unreachable("Unknown C++ cast!");
1520 case tok::kw_const_cast: CastName = "const_cast"; break;
1521 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1522 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1523 case tok::kw_static_cast: CastName = "static_cast"; break;
1526 SourceLocation OpLoc = ConsumeToken();
1527 SourceLocation LAngleBracketLoc = Tok.getLocation();
1529 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1530 // diagnose error, suggest fix, and recover parsing.
1531 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1532 Token Next = NextToken();
1533 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1534 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1537 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
1540 // Parse the common declaration-specifiers piece.
1541 DeclSpec DS(AttrFactory);
1542 ParseSpecifierQualifierList(DS);
1544 // Parse the abstract-declarator, if present.
1545 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
1546 ParseDeclarator(DeclaratorInfo);
1548 SourceLocation RAngleBracketLoc = Tok.getLocation();
1550 if (ExpectAndConsume(tok::greater))
1551 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
1553 BalancedDelimiterTracker T(*this, tok::l_paren);
1555 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
1558 ExprResult Result = ParseExpression();
1563 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
1564 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
1565 LAngleBracketLoc, DeclaratorInfo,
1567 T.getOpenLocation(), Result.get(),
1568 T.getCloseLocation());
1573 /// ParseCXXTypeid - This handles the C++ typeid expression.
1575 /// postfix-expression: [C++ 5.2p1]
1576 /// 'typeid' '(' expression ')'
1577 /// 'typeid' '(' type-id ')'
1579 ExprResult Parser::ParseCXXTypeid() {
1580 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1582 SourceLocation OpLoc = ConsumeToken();
1583 SourceLocation LParenLoc, RParenLoc;
1584 BalancedDelimiterTracker T(*this, tok::l_paren);
1586 // typeid expressions are always parenthesized.
1587 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
1589 LParenLoc = T.getOpenLocation();
1593 // C++0x [expr.typeid]p3:
1594 // When typeid is applied to an expression other than an lvalue of a
1595 // polymorphic class type [...] The expression is an unevaluated
1596 // operand (Clause 5).
1598 // Note that we can't tell whether the expression is an lvalue of a
1599 // polymorphic class type until after we've parsed the expression; we
1600 // speculatively assume the subexpression is unevaluated, and fix it up
1603 // We enter the unevaluated context before trying to determine whether we
1604 // have a type-id, because the tentative parse logic will try to resolve
1605 // names, and must treat them as unevaluated.
1606 EnterExpressionEvaluationContext Unevaluated(
1607 Actions, Sema::ExpressionEvaluationContext::Unevaluated,
1608 Sema::ReuseLambdaContextDecl);
1610 if (isTypeIdInParens()) {
1611 TypeResult Ty = ParseTypeName();
1615 RParenLoc = T.getCloseLocation();
1616 if (Ty.isInvalid() || RParenLoc.isInvalid())
1619 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
1620 Ty.get().getAsOpaquePtr(), RParenLoc);
1622 Result = ParseExpression();
1625 if (Result.isInvalid())
1626 SkipUntil(tok::r_paren, StopAtSemi);
1629 RParenLoc = T.getCloseLocation();
1630 if (RParenLoc.isInvalid())
1633 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
1634 Result.get(), RParenLoc);
1641 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1643 /// '__uuidof' '(' expression ')'
1644 /// '__uuidof' '(' type-id ')'
1646 ExprResult Parser::ParseCXXUuidof() {
1647 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1649 SourceLocation OpLoc = ConsumeToken();
1650 BalancedDelimiterTracker T(*this, tok::l_paren);
1652 // __uuidof expressions are always parenthesized.
1653 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
1658 if (isTypeIdInParens()) {
1659 TypeResult Ty = ParseTypeName();
1667 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1668 Ty.get().getAsOpaquePtr(),
1669 T.getCloseLocation());
1671 EnterExpressionEvaluationContext Unevaluated(
1672 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1673 Result = ParseExpression();
1676 if (Result.isInvalid())
1677 SkipUntil(tok::r_paren, StopAtSemi);
1681 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1683 Result.get(), T.getCloseLocation());
1690 /// Parse a C++ pseudo-destructor expression after the base,
1691 /// . or -> operator, and nested-name-specifier have already been
1694 /// postfix-expression: [C++ 5.2]
1695 /// postfix-expression . pseudo-destructor-name
1696 /// postfix-expression -> pseudo-destructor-name
1698 /// pseudo-destructor-name:
1699 /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1700 /// ::[opt] nested-name-specifier template simple-template-id ::
1702 /// ::[opt] nested-name-specifier[opt] ~type-name
1705 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
1706 tok::TokenKind OpKind,
1708 ParsedType ObjectType) {
1709 // We're parsing either a pseudo-destructor-name or a dependent
1710 // member access that has the same form as a
1711 // pseudo-destructor-name. We parse both in the same way and let
1712 // the action model sort them out.
1714 // Note that the ::[opt] nested-name-specifier[opt] has already
1715 // been parsed, and if there was a simple-template-id, it has
1716 // been coalesced into a template-id annotation token.
1717 UnqualifiedId FirstTypeName;
1718 SourceLocation CCLoc;
1719 if (Tok.is(tok::identifier)) {
1720 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1722 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1723 CCLoc = ConsumeToken();
1724 } else if (Tok.is(tok::annot_template_id)) {
1725 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1726 // store it in the pseudo-dtor node (to be used when instantiating it).
1727 FirstTypeName.setTemplateId(
1728 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1729 ConsumeAnnotationToken();
1730 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1731 CCLoc = ConsumeToken();
1733 FirstTypeName.setIdentifier(nullptr, SourceLocation());
1737 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1738 SourceLocation TildeLoc = ConsumeToken();
1740 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1741 DeclSpec DS(AttrFactory);
1742 ParseDecltypeSpecifier(DS);
1743 if (DS.getTypeSpecType() == TST_error)
1745 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1749 if (!Tok.is(tok::identifier)) {
1750 Diag(Tok, diag::err_destructor_tilde_identifier);
1754 // Parse the second type.
1755 UnqualifiedId SecondTypeName;
1756 IdentifierInfo *Name = Tok.getIdentifierInfo();
1757 SourceLocation NameLoc = ConsumeToken();
1758 SecondTypeName.setIdentifier(Name, NameLoc);
1760 // If there is a '<', the second type name is a template-id. Parse
1762 if (Tok.is(tok::less) &&
1763 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1765 false, ObjectType, SecondTypeName,
1766 /*AssumeTemplateId=*/true))
1769 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1770 SS, FirstTypeName, CCLoc, TildeLoc,
1774 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1776 /// boolean-literal: [C++ 2.13.5]
1779 ExprResult Parser::ParseCXXBoolLiteral() {
1780 tok::TokenKind Kind = Tok.getKind();
1781 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
1784 /// ParseThrowExpression - This handles the C++ throw expression.
1786 /// throw-expression: [C++ 15]
1787 /// 'throw' assignment-expression[opt]
1788 ExprResult Parser::ParseThrowExpression() {
1789 assert(Tok.is(tok::kw_throw) && "Not throw!");
1790 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
1792 // If the current token isn't the start of an assignment-expression,
1793 // then the expression is not present. This handles things like:
1794 // "C ? throw : (void)42", which is crazy but legal.
1795 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1802 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
1805 ExprResult Expr(ParseAssignmentExpression());
1806 if (Expr.isInvalid()) return Expr;
1807 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
1811 /// Parse the C++ Coroutines co_yield expression.
1813 /// co_yield-expression:
1814 /// 'co_yield' assignment-expression[opt]
1815 ExprResult Parser::ParseCoyieldExpression() {
1816 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1818 SourceLocation Loc = ConsumeToken();
1819 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1820 : ParseAssignmentExpression();
1821 if (!Expr.isInvalid())
1822 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
1826 /// ParseCXXThis - This handles the C++ 'this' pointer.
1828 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1829 /// a non-lvalue expression whose value is the address of the object for which
1830 /// the function is called.
1831 ExprResult Parser::ParseCXXThis() {
1832 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1833 SourceLocation ThisLoc = ConsumeToken();
1834 return Actions.ActOnCXXThis(ThisLoc);
1837 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1838 /// Can be interpreted either as function-style casting ("int(x)")
1839 /// or class type construction ("ClassType(x,y,z)")
1840 /// or creation of a value-initialized type ("int()").
1841 /// See [C++ 5.2.3].
1843 /// postfix-expression: [C++ 5.2p1]
1844 /// simple-type-specifier '(' expression-list[opt] ')'
1845 /// [C++0x] simple-type-specifier braced-init-list
1846 /// typename-specifier '(' expression-list[opt] ')'
1847 /// [C++0x] typename-specifier braced-init-list
1849 /// In C++1z onwards, the type specifier can also be a template-name.
1851 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
1852 Declarator DeclaratorInfo(DS, DeclaratorContext::FunctionalCastContext);
1853 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
1855 assert((Tok.is(tok::l_paren) ||
1856 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
1857 && "Expected '(' or '{'!");
1859 if (Tok.is(tok::l_brace)) {
1860 ExprResult Init = ParseBraceInitializer();
1861 if (Init.isInvalid())
1863 Expr *InitList = Init.get();
1864 return Actions.ActOnCXXTypeConstructExpr(
1865 TypeRep, InitList->getBeginLoc(), MultiExprArg(&InitList, 1),
1866 InitList->getEndLoc(), /*ListInitialization=*/true);
1868 BalancedDelimiterTracker T(*this, tok::l_paren);
1871 PreferredType.enterTypeCast(Tok.getLocation(), TypeRep.get());
1874 CommaLocsTy CommaLocs;
1876 auto RunSignatureHelp = [&]() {
1877 QualType PreferredType;
1879 PreferredType = Actions.ProduceConstructorSignatureHelp(
1880 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
1881 DS.getEndLoc(), Exprs, T.getOpenLocation());
1882 CalledSignatureHelp = true;
1883 return PreferredType;
1886 if (Tok.isNot(tok::r_paren)) {
1887 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1888 PreferredType.enterFunctionArgument(Tok.getLocation(),
1891 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
1893 SkipUntil(tok::r_paren, StopAtSemi);
1901 // TypeRep could be null, if it references an invalid typedef.
1905 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1906 "Unexpected number of commas!");
1907 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1908 Exprs, T.getCloseLocation(),
1909 /*ListInitialization=*/false);
1913 /// ParseCXXCondition - if/switch/while condition expression.
1917 /// type-specifier-seq declarator '=' assignment-expression
1918 /// [C++11] type-specifier-seq declarator '=' initializer-clause
1919 /// [C++11] type-specifier-seq declarator braced-init-list
1920 /// [Clang] type-specifier-seq ref-qualifier[opt] '[' identifier-list ']'
1921 /// brace-or-equal-initializer
1922 /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1923 /// '=' assignment-expression
1925 /// In C++1z, a condition may in some contexts be preceded by an
1926 /// optional init-statement. This function will parse that too.
1928 /// \param InitStmt If non-null, an init-statement is permitted, and if present
1929 /// will be parsed and stored here.
1931 /// \param Loc The location of the start of the statement that requires this
1932 /// condition, e.g., the "for" in a for loop.
1934 /// \param FRI If non-null, a for range declaration is permitted, and if
1935 /// present will be parsed and stored here, and a null result will be returned.
1937 /// \returns The parsed condition.
1938 Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1940 Sema::ConditionKind CK,
1941 ForRangeInfo *FRI) {
1942 ParenBraceBracketBalancer BalancerRAIIObj(*this);
1943 PreferredType.enterCondition(Actions, Tok.getLocation());
1945 if (Tok.is(tok::code_completion)) {
1946 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
1948 return Sema::ConditionError();
1951 ParsedAttributesWithRange attrs(AttrFactory);
1952 MaybeParseCXX11Attributes(attrs);
1954 const auto WarnOnInit = [this, &CK] {
1955 Diag(Tok.getLocation(), getLangOpts().CPlusPlus17
1956 ? diag::warn_cxx14_compat_init_statement
1957 : diag::ext_init_statement)
1958 << (CK == Sema::ConditionKind::Switch);
1961 // Determine what kind of thing we have.
1962 switch (isCXXConditionDeclarationOrInitStatement(InitStmt, FRI)) {
1963 case ConditionOrInitStatement::Expression: {
1964 ProhibitAttributes(attrs);
1966 // We can have an empty expression here.
1968 if (InitStmt && Tok.is(tok::semi)) {
1970 SourceLocation SemiLoc = Tok.getLocation();
1971 if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID()) {
1972 Diag(SemiLoc, diag::warn_empty_init_statement)
1973 << (CK == Sema::ConditionKind::Switch)
1974 << FixItHint::CreateRemoval(SemiLoc);
1977 *InitStmt = Actions.ActOnNullStmt(SemiLoc);
1978 return ParseCXXCondition(nullptr, Loc, CK);
1981 // Parse the expression.
1982 ExprResult Expr = ParseExpression(); // expression
1983 if (Expr.isInvalid())
1984 return Sema::ConditionError();
1986 if (InitStmt && Tok.is(tok::semi)) {
1988 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1990 return ParseCXXCondition(nullptr, Loc, CK);
1993 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
1996 case ConditionOrInitStatement::InitStmtDecl: {
1998 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2000 ParseSimpleDeclaration(DeclaratorContext::InitStmtContext, DeclEnd,
2001 attrs, /*RequireSemi=*/true);
2002 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
2003 return ParseCXXCondition(nullptr, Loc, CK);
2006 case ConditionOrInitStatement::ForRangeDecl: {
2007 assert(FRI && "should not parse a for range declaration here");
2008 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
2009 DeclGroupPtrTy DG = ParseSimpleDeclaration(
2010 DeclaratorContext::ForContext, DeclEnd, attrs, false, FRI);
2011 FRI->LoopVar = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
2012 return Sema::ConditionResult();
2015 case ConditionOrInitStatement::ConditionDecl:
2016 case ConditionOrInitStatement::Error:
2020 // type-specifier-seq
2021 DeclSpec DS(AttrFactory);
2022 DS.takeAttributesFrom(attrs);
2023 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_condition);
2026 Declarator DeclaratorInfo(DS, DeclaratorContext::ConditionContext);
2027 ParseDeclarator(DeclaratorInfo);
2029 // simple-asm-expr[opt]
2030 if (Tok.is(tok::kw_asm)) {
2032 ExprResult AsmLabel(ParseSimpleAsm(/*ForAsmLabel*/ true, &Loc));
2033 if (AsmLabel.isInvalid()) {
2034 SkipUntil(tok::semi, StopAtSemi);
2035 return Sema::ConditionError();
2037 DeclaratorInfo.setAsmLabel(AsmLabel.get());
2038 DeclaratorInfo.SetRangeEnd(Loc);
2041 // If attributes are present, parse them.
2042 MaybeParseGNUAttributes(DeclaratorInfo);
2044 // Type-check the declaration itself.
2045 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
2047 if (Dcl.isInvalid())
2048 return Sema::ConditionError();
2049 Decl *DeclOut = Dcl.get();
2051 // '=' assignment-expression
2052 // If a '==' or '+=' is found, suggest a fixit to '='.
2053 bool CopyInitialization = isTokenEqualOrEqualTypo();
2054 if (CopyInitialization)
2057 ExprResult InitExpr = ExprError();
2058 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2059 Diag(Tok.getLocation(),
2060 diag::warn_cxx98_compat_generalized_initializer_lists);
2061 InitExpr = ParseBraceInitializer();
2062 } else if (CopyInitialization) {
2063 PreferredType.enterVariableInit(Tok.getLocation(), DeclOut);
2064 InitExpr = ParseAssignmentExpression();
2065 } else if (Tok.is(tok::l_paren)) {
2066 // This was probably an attempt to initialize the variable.
2067 SourceLocation LParen = ConsumeParen(), RParen = LParen;
2068 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
2069 RParen = ConsumeParen();
2070 Diag(DeclOut->getLocation(),
2071 diag::err_expected_init_in_condition_lparen)
2072 << SourceRange(LParen, RParen);
2074 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
2077 if (!InitExpr.isInvalid())
2078 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
2080 Actions.ActOnInitializerError(DeclOut);
2082 Actions.FinalizeDeclaration(DeclOut);
2083 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
2086 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
2087 /// This should only be called when the current token is known to be part of
2088 /// simple-type-specifier.
2090 /// simple-type-specifier:
2091 /// '::'[opt] nested-name-specifier[opt] type-name
2092 /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
2104 /// [GNU] typeof-specifier
2105 /// [C++0x] auto [TODO]
2112 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
2113 DS.SetRangeStart(Tok.getLocation());
2114 const char *PrevSpec;
2116 SourceLocation Loc = Tok.getLocation();
2117 const clang::PrintingPolicy &Policy =
2118 Actions.getASTContext().getPrintingPolicy();
2120 switch (Tok.getKind()) {
2121 case tok::identifier: // foo::bar
2122 case tok::coloncolon: // ::foo::bar
2123 llvm_unreachable("Annotation token should already be formed!");
2125 llvm_unreachable("Not a simple-type-specifier token!");
2128 case tok::annot_typename: {
2129 if (getTypeAnnotation(Tok))
2130 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
2131 getTypeAnnotation(Tok), Policy);
2133 DS.SetTypeSpecError();
2135 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
2136 ConsumeAnnotationToken();
2138 DS.Finish(Actions, Policy);
2144 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
2147 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
2149 case tok::kw___int64:
2150 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
2152 case tok::kw_signed:
2153 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
2155 case tok::kw_unsigned:
2156 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
2159 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
2162 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
2165 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
2167 case tok::kw___int128:
2168 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
2171 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
2174 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
2176 case tok::kw_double:
2177 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
2179 case tok::kw__Float16:
2180 DS.SetTypeSpecType(DeclSpec::TST_float16, Loc, PrevSpec, DiagID, Policy);
2182 case tok::kw___float128:
2183 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
2185 case tok::kw_wchar_t:
2186 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
2188 case tok::kw_char8_t:
2189 DS.SetTypeSpecType(DeclSpec::TST_char8, Loc, PrevSpec, DiagID, Policy);
2191 case tok::kw_char16_t:
2192 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
2194 case tok::kw_char32_t:
2195 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
2198 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
2200 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
2201 case tok::kw_##ImgType##_t: \
2202 DS.SetTypeSpecType(DeclSpec::TST_##ImgType##_t, Loc, PrevSpec, DiagID, \
2205 #include "clang/Basic/OpenCLImageTypes.def"
2207 case tok::annot_decltype:
2208 case tok::kw_decltype:
2209 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
2210 return DS.Finish(Actions, Policy);
2212 // GNU typeof support.
2213 case tok::kw_typeof:
2214 ParseTypeofSpecifier(DS);
2215 DS.Finish(Actions, Policy);
2219 DS.SetRangeEnd(PrevTokLocation);
2220 DS.Finish(Actions, Policy);
2223 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
2224 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
2225 /// e.g., "const short int". Note that the DeclSpec is *not* finished
2226 /// by parsing the type-specifier-seq, because these sequences are
2227 /// typically followed by some form of declarator. Returns true and
2228 /// emits diagnostics if this is not a type-specifier-seq, false
2231 /// type-specifier-seq: [C++ 8.1]
2232 /// type-specifier type-specifier-seq[opt]
2234 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
2235 ParseSpecifierQualifierList(DS, AS_none, DeclSpecContext::DSC_type_specifier);
2236 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
2240 /// Finish parsing a C++ unqualified-id that is a template-id of
2243 /// This routine is invoked when a '<' is encountered after an identifier or
2244 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
2245 /// whether the unqualified-id is actually a template-id. This routine will
2246 /// then parse the template arguments and form the appropriate template-id to
2247 /// return to the caller.
2249 /// \param SS the nested-name-specifier that precedes this template-id, if
2250 /// we're actually parsing a qualified-id.
2252 /// \param Name for constructor and destructor names, this is the actual
2253 /// identifier that may be a template-name.
2255 /// \param NameLoc the location of the class-name in a constructor or
2258 /// \param EnteringContext whether we're entering the scope of the
2259 /// nested-name-specifier.
2261 /// \param ObjectType if this unqualified-id occurs within a member access
2262 /// expression, the type of the base object whose member is being accessed.
2264 /// \param Id as input, describes the template-name or operator-function-id
2265 /// that precedes the '<'. If template arguments were parsed successfully,
2266 /// will be updated with the template-id.
2268 /// \param AssumeTemplateId When true, this routine will assume that the name
2269 /// refers to a template without performing name lookup to verify.
2271 /// \returns true if a parse error occurred, false otherwise.
2272 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
2273 SourceLocation TemplateKWLoc,
2274 IdentifierInfo *Name,
2275 SourceLocation NameLoc,
2276 bool EnteringContext,
2277 ParsedType ObjectType,
2279 bool AssumeTemplateId) {
2280 assert(Tok.is(tok::less) && "Expected '<' to finish parsing a template-id");
2282 TemplateTy Template;
2283 TemplateNameKind TNK = TNK_Non_template;
2284 switch (Id.getKind()) {
2285 case UnqualifiedIdKind::IK_Identifier:
2286 case UnqualifiedIdKind::IK_OperatorFunctionId:
2287 case UnqualifiedIdKind::IK_LiteralOperatorId:
2288 if (AssumeTemplateId) {
2289 // We defer the injected-class-name checks until we've found whether
2290 // this template-id is used to form a nested-name-specifier or not.
2291 TNK = Actions.ActOnDependentTemplateName(
2292 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2293 Template, /*AllowInjectedClassName*/ true);
2294 if (TNK == TNK_Non_template)
2297 bool MemberOfUnknownSpecialization;
2298 TNK = Actions.isTemplateName(getCurScope(), SS,
2299 TemplateKWLoc.isValid(), Id,
2300 ObjectType, EnteringContext, Template,
2301 MemberOfUnknownSpecialization);
2302 // If lookup found nothing but we're assuming that this is a template
2303 // name, double-check that makes sense syntactically before committing
2305 if (TNK == TNK_Undeclared_template &&
2306 isTemplateArgumentList(0) == TPResult::False)
2309 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2310 ObjectType && isTemplateArgumentList(0) == TPResult::True) {
2311 // We have something like t->getAs<T>(), where getAs is a
2312 // member of an unknown specialization. However, this will only
2313 // parse correctly as a template, so suggest the keyword 'template'
2314 // before 'getAs' and treat this as a dependent template name.
2316 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier)
2317 Name = Id.Identifier->getName();
2320 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId)
2321 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2323 Name += Id.Identifier->getName();
2325 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2327 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
2328 TNK = Actions.ActOnDependentTemplateName(
2329 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2330 Template, /*AllowInjectedClassName*/ true);
2331 if (TNK == TNK_Non_template)
2337 case UnqualifiedIdKind::IK_ConstructorName: {
2338 UnqualifiedId TemplateName;
2339 bool MemberOfUnknownSpecialization;
2340 TemplateName.setIdentifier(Name, NameLoc);
2341 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2342 TemplateName, ObjectType,
2343 EnteringContext, Template,
2344 MemberOfUnknownSpecialization);
2348 case UnqualifiedIdKind::IK_DestructorName: {
2349 UnqualifiedId TemplateName;
2350 bool MemberOfUnknownSpecialization;
2351 TemplateName.setIdentifier(Name, NameLoc);
2353 TNK = Actions.ActOnDependentTemplateName(
2354 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2355 EnteringContext, Template, /*AllowInjectedClassName*/ true);
2356 if (TNK == TNK_Non_template)
2359 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2360 TemplateName, ObjectType,
2361 EnteringContext, Template,
2362 MemberOfUnknownSpecialization);
2364 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
2365 Diag(NameLoc, diag::err_destructor_template_id)
2366 << Name << SS.getRange();
2377 if (TNK == TNK_Non_template)
2380 // Parse the enclosed template argument list.
2381 SourceLocation LAngleLoc, RAngleLoc;
2382 TemplateArgList TemplateArgs;
2383 if (ParseTemplateIdAfterTemplateName(true, LAngleLoc, TemplateArgs,
2387 if (Id.getKind() == UnqualifiedIdKind::IK_Identifier ||
2388 Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2389 Id.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) {
2390 // Form a parsed representation of the template-id to be stored in the
2393 // FIXME: Store name for literal operator too.
2394 IdentifierInfo *TemplateII =
2395 Id.getKind() == UnqualifiedIdKind::IK_Identifier ? Id.Identifier
2397 OverloadedOperatorKind OpKind =
2398 Id.getKind() == UnqualifiedIdKind::IK_Identifier
2400 : Id.OperatorFunctionId.Operator;
2402 TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Create(
2403 TemplateKWLoc, Id.StartLocation, TemplateII, OpKind, Template, TNK,
2404 LAngleLoc, RAngleLoc, TemplateArgs, TemplateIds);
2406 Id.setTemplateId(TemplateId);
2410 // Bundle the template arguments together.
2411 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
2413 // Constructor and destructor names.
2414 TypeResult Type = Actions.ActOnTemplateIdType(
2415 getCurScope(), SS, TemplateKWLoc, Template, Name, NameLoc, LAngleLoc,
2416 TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true);
2417 if (Type.isInvalid())
2420 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
2421 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2423 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2428 /// Parse an operator-function-id or conversion-function-id as part
2429 /// of a C++ unqualified-id.
2431 /// This routine is responsible only for parsing the operator-function-id or
2432 /// conversion-function-id; it does not handle template arguments in any way.
2435 /// operator-function-id: [C++ 13.5]
2436 /// 'operator' operator
2438 /// operator: one of
2439 /// new delete new[] delete[]
2440 /// + - * / % ^ & | ~
2441 /// ! = < > += -= *= /= %=
2442 /// ^= &= |= << >> >>= <<= == !=
2443 /// <= >= && || ++ -- , ->* ->
2446 /// conversion-function-id: [C++ 12.3.2]
2447 /// operator conversion-type-id
2449 /// conversion-type-id:
2450 /// type-specifier-seq conversion-declarator[opt]
2452 /// conversion-declarator:
2453 /// ptr-operator conversion-declarator[opt]
2456 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2457 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2459 /// \param EnteringContext whether we are entering the scope of the
2460 /// nested-name-specifier.
2462 /// \param ObjectType if this unqualified-id occurs within a member access
2463 /// expression, the type of the base object whose member is being accessed.
2465 /// \param Result on a successful parse, contains the parsed unqualified-id.
2467 /// \returns true if parsing fails, false otherwise.
2468 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
2469 ParsedType ObjectType,
2470 UnqualifiedId &Result) {
2471 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2473 // Consume the 'operator' keyword.
2474 SourceLocation KeywordLoc = ConsumeToken();
2476 // Determine what kind of operator name we have.
2477 unsigned SymbolIdx = 0;
2478 SourceLocation SymbolLocations[3];
2479 OverloadedOperatorKind Op = OO_None;
2480 switch (Tok.getKind()) {
2482 case tok::kw_delete: {
2483 bool isNew = Tok.getKind() == tok::kw_new;
2484 // Consume the 'new' or 'delete'.
2485 SymbolLocations[SymbolIdx++] = ConsumeToken();
2486 // Check for array new/delete.
2487 if (Tok.is(tok::l_square) &&
2488 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
2489 // Consume the '[' and ']'.
2490 BalancedDelimiterTracker T(*this, tok::l_square);
2493 if (T.getCloseLocation().isInvalid())
2496 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2497 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2498 Op = isNew? OO_Array_New : OO_Array_Delete;
2500 Op = isNew? OO_New : OO_Delete;
2505 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2507 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2510 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2511 #include "clang/Basic/OperatorKinds.def"
2513 case tok::l_paren: {
2514 // Consume the '(' and ')'.
2515 BalancedDelimiterTracker T(*this, tok::l_paren);
2518 if (T.getCloseLocation().isInvalid())
2521 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2522 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2527 case tok::l_square: {
2528 // Consume the '[' and ']'.
2529 BalancedDelimiterTracker T(*this, tok::l_square);
2532 if (T.getCloseLocation().isInvalid())
2535 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2536 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
2541 case tok::code_completion: {
2542 // Code completion for the operator name.
2543 Actions.CodeCompleteOperatorName(getCurScope());
2545 // Don't try to parse any further.
2553 if (Op != OO_None) {
2554 // We have parsed an operator-function-id.
2555 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2559 // Parse a literal-operator-id.
2561 // literal-operator-id: C++11 [over.literal]
2562 // operator string-literal identifier
2563 // operator user-defined-string-literal
2565 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
2566 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
2568 SourceLocation DiagLoc;
2569 unsigned DiagId = 0;
2571 // We're past translation phase 6, so perform string literal concatenation
2572 // before checking for "".
2573 SmallVector<Token, 4> Toks;
2574 SmallVector<SourceLocation, 4> TokLocs;
2575 while (isTokenStringLiteral()) {
2576 if (!Tok.is(tok::string_literal) && !DiagId) {
2577 // C++11 [over.literal]p1:
2578 // The string-literal or user-defined-string-literal in a
2579 // literal-operator-id shall have no encoding-prefix [...].
2580 DiagLoc = Tok.getLocation();
2581 DiagId = diag::err_literal_operator_string_prefix;
2583 Toks.push_back(Tok);
2584 TokLocs.push_back(ConsumeStringToken());
2587 StringLiteralParser Literal(Toks, PP);
2588 if (Literal.hadError)
2591 // Grab the literal operator's suffix, which will be either the next token
2592 // or a ud-suffix from the string literal.
2593 IdentifierInfo *II = nullptr;
2594 SourceLocation SuffixLoc;
2595 if (!Literal.getUDSuffix().empty()) {
2596 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2598 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2599 Literal.getUDSuffixOffset(),
2600 PP.getSourceManager(), getLangOpts());
2601 } else if (Tok.is(tok::identifier)) {
2602 II = Tok.getIdentifierInfo();
2603 SuffixLoc = ConsumeToken();
2604 TokLocs.push_back(SuffixLoc);
2606 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
2610 // The string literal must be empty.
2611 if (!Literal.GetString().empty() || Literal.Pascal) {
2612 // C++11 [over.literal]p1:
2613 // The string-literal or user-defined-string-literal in a
2614 // literal-operator-id shall [...] contain no characters
2615 // other than the implicit terminating '\0'.
2616 DiagLoc = TokLocs.front();
2617 DiagId = diag::err_literal_operator_string_not_empty;
2621 // This isn't a valid literal-operator-id, but we think we know
2622 // what the user meant. Tell them what they should have written.
2623 SmallString<32> Str;
2625 Str += II->getName();
2626 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2627 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2630 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
2632 return Actions.checkLiteralOperatorId(SS, Result);
2635 // Parse a conversion-function-id.
2637 // conversion-function-id: [C++ 12.3.2]
2638 // operator conversion-type-id
2640 // conversion-type-id:
2641 // type-specifier-seq conversion-declarator[opt]
2643 // conversion-declarator:
2644 // ptr-operator conversion-declarator[opt]
2646 // Parse the type-specifier-seq.
2647 DeclSpec DS(AttrFactory);
2648 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
2651 // Parse the conversion-declarator, which is merely a sequence of
2653 Declarator D(DS, DeclaratorContext::ConversionIdContext);
2654 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2656 // Finish up the type.
2657 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
2661 // Note that this is a conversion-function-id.
2662 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2663 D.getSourceRange().getEnd());
2667 /// Parse a C++ unqualified-id (or a C identifier), which describes the
2668 /// name of an entity.
2671 /// unqualified-id: [C++ expr.prim.general]
2673 /// operator-function-id
2674 /// conversion-function-id
2675 /// [C++0x] literal-operator-id [TODO]
2681 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
2682 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
2684 /// \param EnteringContext whether we are entering the scope of the
2685 /// nested-name-specifier.
2687 /// \param AllowDestructorName whether we allow parsing of a destructor name.
2689 /// \param AllowConstructorName whether we allow parsing a constructor name.
2691 /// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2693 /// \param ObjectType if this unqualified-id occurs within a member access
2694 /// expression, the type of the base object whose member is being accessed.
2696 /// \param Result on a successful parse, contains the parsed unqualified-id.
2698 /// \returns true if parsing fails, false otherwise.
2699 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2700 bool AllowDestructorName,
2701 bool AllowConstructorName,
2702 bool AllowDeductionGuide,
2703 ParsedType ObjectType,
2704 SourceLocation *TemplateKWLoc,
2705 UnqualifiedId &Result) {
2707 *TemplateKWLoc = SourceLocation();
2709 // Handle 'A::template B'. This is for template-ids which have not
2710 // already been annotated by ParseOptionalCXXScopeSpecifier().
2711 bool TemplateSpecified = false;
2712 if (Tok.is(tok::kw_template)) {
2713 if (TemplateKWLoc && (ObjectType || SS.isSet())) {
2714 TemplateSpecified = true;
2715 *TemplateKWLoc = ConsumeToken();
2717 SourceLocation TemplateLoc = ConsumeToken();
2718 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2719 << FixItHint::CreateRemoval(TemplateLoc);
2725 // template-id (when it hasn't already been annotated)
2726 if (Tok.is(tok::identifier)) {
2727 // Consume the identifier.
2728 IdentifierInfo *Id = Tok.getIdentifierInfo();
2729 SourceLocation IdLoc = ConsumeToken();
2731 if (!getLangOpts().CPlusPlus) {
2732 // If we're not in C++, only identifiers matter. Record the
2733 // identifier and return.
2734 Result.setIdentifier(Id, IdLoc);
2738 ParsedTemplateTy TemplateName;
2739 if (AllowConstructorName &&
2740 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
2741 // We have parsed a constructor name.
2742 ParsedType Ty = Actions.getConstructorName(*Id, IdLoc, getCurScope(), SS,
2746 Result.setConstructorName(Ty, IdLoc, IdLoc);
2747 } else if (getLangOpts().CPlusPlus17 &&
2748 AllowDeductionGuide && SS.isEmpty() &&
2749 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2751 // We have parsed a template-name naming a deduction guide.
2752 Result.setDeductionGuideName(TemplateName, IdLoc);
2754 // We have parsed an identifier.
2755 Result.setIdentifier(Id, IdLoc);
2758 // If the next token is a '<', we may have a template.
2759 TemplateTy Template;
2760 if (Tok.is(tok::less))
2761 return ParseUnqualifiedIdTemplateId(
2762 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), Id, IdLoc,
2763 EnteringContext, ObjectType, Result, TemplateSpecified);
2764 else if (TemplateSpecified &&
2765 Actions.ActOnDependentTemplateName(
2766 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2767 EnteringContext, Template,
2768 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2775 // template-id (already parsed and annotated)
2776 if (Tok.is(tok::annot_template_id)) {
2777 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
2779 // If the template-name names the current class, then this is a constructor
2780 if (AllowConstructorName && TemplateId->Name &&
2781 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
2783 // C++ [class.qual]p2 specifies that a qualified template-name
2784 // is taken as the constructor name where a constructor can be
2785 // declared. Thus, the template arguments are extraneous, so
2786 // complain about them and remove them entirely.
2787 Diag(TemplateId->TemplateNameLoc,
2788 diag::err_out_of_line_constructor_template_id)
2790 << FixItHint::CreateRemoval(
2791 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
2792 ParsedType Ty = Actions.getConstructorName(
2793 *TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), SS,
2797 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
2798 TemplateId->RAngleLoc);
2799 ConsumeAnnotationToken();
2803 Result.setConstructorTemplateId(TemplateId);
2804 ConsumeAnnotationToken();
2808 // We have already parsed a template-id; consume the annotation token as
2809 // our unqualified-id.
2810 Result.setTemplateId(TemplateId);
2811 SourceLocation TemplateLoc = TemplateId->TemplateKWLoc;
2812 if (TemplateLoc.isValid()) {
2813 if (TemplateKWLoc && (ObjectType || SS.isSet()))
2814 *TemplateKWLoc = TemplateLoc;
2816 Diag(TemplateLoc, diag::err_unexpected_template_in_unqualified_id)
2817 << FixItHint::CreateRemoval(TemplateLoc);
2819 ConsumeAnnotationToken();
2824 // operator-function-id
2825 // conversion-function-id
2826 if (Tok.is(tok::kw_operator)) {
2827 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
2830 // If we have an operator-function-id or a literal-operator-id and the next
2831 // token is a '<', we may have a
2834 // operator-function-id < template-argument-list[opt] >
2835 TemplateTy Template;
2836 if ((Result.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId ||
2837 Result.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) &&
2839 return ParseUnqualifiedIdTemplateId(
2840 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), nullptr,
2841 SourceLocation(), EnteringContext, ObjectType, Result,
2843 else if (TemplateSpecified &&
2844 Actions.ActOnDependentTemplateName(
2845 getCurScope(), SS, *TemplateKWLoc, Result, ObjectType,
2846 EnteringContext, Template,
2847 /*AllowInjectedClassName*/ true) == TNK_Non_template)
2853 if (getLangOpts().CPlusPlus &&
2854 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
2855 // C++ [expr.unary.op]p10:
2856 // There is an ambiguity in the unary-expression ~X(), where X is a
2857 // class-name. The ambiguity is resolved in favor of treating ~ as a
2858 // unary complement rather than treating ~X as referring to a destructor.
2861 SourceLocation TildeLoc = ConsumeToken();
2863 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2864 DeclSpec DS(AttrFactory);
2865 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2866 if (ParsedType Type =
2867 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
2868 Result.setDestructorName(TildeLoc, Type, EndLoc);
2874 // Parse the class-name.
2875 if (Tok.isNot(tok::identifier)) {
2876 Diag(Tok, diag::err_destructor_tilde_identifier);
2880 // If the user wrote ~T::T, correct it to T::~T.
2881 DeclaratorScopeObj DeclScopeObj(*this, SS);
2882 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2883 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2884 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2885 // it will confuse this recovery logic.
2886 ColonProtectionRAIIObject ColonRAII(*this, false);
2889 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2892 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2894 if (SS.isNotEmpty())
2895 ObjectType = nullptr;
2896 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2898 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2902 // Recover as if the tilde had been written before the identifier.
2903 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2904 << FixItHint::CreateRemoval(TildeLoc)
2905 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2907 // Temporarily enter the scope for the rest of this function.
2908 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2909 DeclScopeObj.EnterDeclaratorScope();
2912 // Parse the class-name (or template-name in a simple-template-id).
2913 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2914 SourceLocation ClassNameLoc = ConsumeToken();
2916 if (Tok.is(tok::less)) {
2917 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
2918 return ParseUnqualifiedIdTemplateId(
2919 SS, TemplateKWLoc ? *TemplateKWLoc : SourceLocation(), ClassName,
2920 ClassNameLoc, EnteringContext, ObjectType, Result, TemplateSpecified);
2923 // Note that this is a destructor name.
2924 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2925 ClassNameLoc, getCurScope(),
2931 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
2935 Diag(Tok, diag::err_expected_unqualified_id)
2936 << getLangOpts().CPlusPlus;
2940 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2941 /// memory in a typesafe manner and call constructors.
2943 /// This method is called to parse the new expression after the optional :: has
2944 /// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2945 /// is its location. Otherwise, "Start" is the location of the 'new' token.
2948 /// '::'[opt] 'new' new-placement[opt] new-type-id
2949 /// new-initializer[opt]
2950 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2951 /// new-initializer[opt]
2954 /// '(' expression-list ')'
2957 /// type-specifier-seq new-declarator[opt]
2958 /// [GNU] attributes type-specifier-seq new-declarator[opt]
2961 /// ptr-operator new-declarator[opt]
2962 /// direct-new-declarator
2964 /// new-initializer:
2965 /// '(' expression-list[opt] ')'
2966 /// [C++0x] braced-init-list
2969 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2970 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2971 ConsumeToken(); // Consume 'new'
2973 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2974 // second form of new-expression. It can't be a new-type-id.
2976 ExprVector PlacementArgs;
2977 SourceLocation PlacementLParen, PlacementRParen;
2979 SourceRange TypeIdParens;
2980 DeclSpec DS(AttrFactory);
2981 Declarator DeclaratorInfo(DS, DeclaratorContext::CXXNewContext);
2982 if (Tok.is(tok::l_paren)) {
2983 // If it turns out to be a placement, we change the type location.
2984 BalancedDelimiterTracker T(*this, tok::l_paren);
2986 PlacementLParen = T.getOpenLocation();
2987 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2988 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2993 PlacementRParen = T.getCloseLocation();
2994 if (PlacementRParen.isInvalid()) {
2995 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
2999 if (PlacementArgs.empty()) {
3000 // Reset the placement locations. There was no placement.
3001 TypeIdParens = T.getRange();
3002 PlacementLParen = PlacementRParen = SourceLocation();
3004 // We still need the type.
3005 if (Tok.is(tok::l_paren)) {
3006 BalancedDelimiterTracker T(*this, tok::l_paren);
3008 MaybeParseGNUAttributes(DeclaratorInfo);
3009 ParseSpecifierQualifierList(DS);
3010 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3011 ParseDeclarator(DeclaratorInfo);
3013 TypeIdParens = T.getRange();
3015 MaybeParseGNUAttributes(DeclaratorInfo);
3016 if (ParseCXXTypeSpecifierSeq(DS))
3017 DeclaratorInfo.setInvalidType(true);
3019 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3020 ParseDeclaratorInternal(DeclaratorInfo,
3021 &Parser::ParseDirectNewDeclarator);
3026 // A new-type-id is a simplified type-id, where essentially the
3027 // direct-declarator is replaced by a direct-new-declarator.
3028 MaybeParseGNUAttributes(DeclaratorInfo);
3029 if (ParseCXXTypeSpecifierSeq(DS))
3030 DeclaratorInfo.setInvalidType(true);
3032 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
3033 ParseDeclaratorInternal(DeclaratorInfo,
3034 &Parser::ParseDirectNewDeclarator);
3037 if (DeclaratorInfo.isInvalidType()) {
3038 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3042 ExprResult Initializer;
3044 if (Tok.is(tok::l_paren)) {
3045 SourceLocation ConstructorLParen, ConstructorRParen;
3046 ExprVector ConstructorArgs;
3047 BalancedDelimiterTracker T(*this, tok::l_paren);
3049 ConstructorLParen = T.getOpenLocation();
3050 if (Tok.isNot(tok::r_paren)) {
3051 CommaLocsTy CommaLocs;
3052 auto RunSignatureHelp = [&]() {
3053 ParsedType TypeRep =
3054 Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
3055 assert(TypeRep && "invalid types should be handled before");
3056 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
3057 getCurScope(), TypeRep.get()->getCanonicalTypeInternal(),
3058 DeclaratorInfo.getEndLoc(), ConstructorArgs, ConstructorLParen);
3059 CalledSignatureHelp = true;
3060 return PreferredType;
3062 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
3063 PreferredType.enterFunctionArgument(Tok.getLocation(),
3066 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
3068 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3073 ConstructorRParen = T.getCloseLocation();
3074 if (ConstructorRParen.isInvalid()) {
3075 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
3078 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
3081 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
3082 Diag(Tok.getLocation(),
3083 diag::warn_cxx98_compat_generalized_initializer_lists);
3084 Initializer = ParseBraceInitializer();
3086 if (Initializer.isInvalid())
3089 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
3090 PlacementArgs, PlacementRParen,
3091 TypeIdParens, DeclaratorInfo, Initializer.get());
3094 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
3095 /// passed to ParseDeclaratorInternal.
3097 /// direct-new-declarator:
3098 /// '[' expression[opt] ']'
3099 /// direct-new-declarator '[' constant-expression ']'
3101 void Parser::ParseDirectNewDeclarator(Declarator &D) {
3102 // Parse the array dimensions.
3104 while (Tok.is(tok::l_square)) {
3105 // An array-size expression can't start with a lambda.
3106 if (CheckProhibitedCXX11Attribute())
3109 BalancedDelimiterTracker T(*this, tok::l_square);
3113 First ? (Tok.is(tok::r_square) ? ExprResult() : ParseExpression())
3114 : ParseConstantExpression();
3115 if (Size.isInvalid()) {
3117 SkipUntil(tok::r_square, StopAtSemi);
3124 // Attributes here appertain to the array type. C++11 [expr.new]p5.
3125 ParsedAttributes Attrs(AttrFactory);
3126 MaybeParseCXX11Attributes(Attrs);
3128 D.AddTypeInfo(DeclaratorChunk::getArray(0,
3129 /*isStatic=*/false, /*isStar=*/false,
3130 Size.get(), T.getOpenLocation(),
3131 T.getCloseLocation()),
3132 std::move(Attrs), T.getCloseLocation());
3134 if (T.getCloseLocation().isInvalid())
3139 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
3140 /// This ambiguity appears in the syntax of the C++ new operator.
3143 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
3144 /// new-initializer[opt]
3147 /// '(' expression-list ')'
3149 bool Parser::ParseExpressionListOrTypeId(
3150 SmallVectorImpl<Expr*> &PlacementArgs,
3152 // The '(' was already consumed.
3153 if (isTypeIdInParens()) {
3154 ParseSpecifierQualifierList(D.getMutableDeclSpec());
3155 D.SetSourceRange(D.getDeclSpec().getSourceRange());
3157 return D.isInvalidType();
3160 // It's not a type, it has to be an expression list.
3161 // Discard the comma locations - ActOnCXXNew has enough parameters.
3162 CommaLocsTy CommaLocs;
3163 return ParseExpressionList(PlacementArgs, CommaLocs);
3166 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
3167 /// to free memory allocated by new.
3169 /// This method is called to parse the 'delete' expression after the optional
3170 /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
3171 /// and "Start" is its location. Otherwise, "Start" is the location of the
3174 /// delete-expression:
3175 /// '::'[opt] 'delete' cast-expression
3176 /// '::'[opt] 'delete' '[' ']' cast-expression
3178 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
3179 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
3180 ConsumeToken(); // Consume 'delete'
3183 bool ArrayDelete = false;
3184 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
3185 // C++11 [expr.delete]p1:
3186 // Whenever the delete keyword is followed by empty square brackets, it
3187 // shall be interpreted as [array delete].
3188 // [Footnote: A lambda expression with a lambda-introducer that consists
3189 // of empty square brackets can follow the delete keyword if
3190 // the lambda expression is enclosed in parentheses.]
3192 const Token Next = GetLookAheadToken(2);
3194 // Basic lookahead to check if we have a lambda expression.
3195 if (Next.isOneOf(tok::l_brace, tok::less) ||
3196 (Next.is(tok::l_paren) &&
3197 (GetLookAheadToken(3).is(tok::r_paren) ||
3198 (GetLookAheadToken(3).is(tok::identifier) &&
3199 GetLookAheadToken(4).is(tok::identifier))))) {
3200 TentativeParsingAction TPA(*this);
3201 SourceLocation LSquareLoc = Tok.getLocation();
3202 SourceLocation RSquareLoc = NextToken().getLocation();
3204 // SkipUntil can't skip pairs of </*...*/>; don't emit a FixIt in this
3206 SkipUntil({tok::l_brace, tok::less}, StopBeforeMatch);
3207 SourceLocation RBraceLoc;
3208 bool EmitFixIt = false;
3209 if (Tok.is(tok::l_brace)) {
3211 SkipUntil(tok::r_brace, StopBeforeMatch);
3212 RBraceLoc = Tok.getLocation();
3219 Diag(Start, diag::err_lambda_after_delete)
3220 << SourceRange(Start, RSquareLoc)
3221 << FixItHint::CreateInsertion(LSquareLoc, "(")
3222 << FixItHint::CreateInsertion(
3223 Lexer::getLocForEndOfToken(
3224 RBraceLoc, 0, Actions.getSourceManager(), getLangOpts()),
3227 Diag(Start, diag::err_lambda_after_delete)
3228 << SourceRange(Start, RSquareLoc);
3230 // Warn that the non-capturing lambda isn't surrounded by parentheses
3231 // to disambiguate it from 'delete[]'.
3232 ExprResult Lambda = ParseLambdaExpression();
3233 if (Lambda.isInvalid())
3236 // Evaluate any postfix expressions used on the lambda.
3237 Lambda = ParsePostfixExpressionSuffix(Lambda);
3238 if (Lambda.isInvalid())
3240 return Actions.ActOnCXXDelete(Start, UseGlobal, /*ArrayForm=*/false,
3245 BalancedDelimiterTracker T(*this, tok::l_square);
3249 if (T.getCloseLocation().isInvalid())
3253 ExprResult Operand(ParseCastExpression(AnyCastExpr));
3254 if (Operand.isInvalid())
3257 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
3260 /// ParseRequiresExpression - Parse a C++2a requires-expression.
3261 /// C++2a [expr.prim.req]p1
3262 /// A requires-expression provides a concise way to express requirements on
3263 /// template arguments. A requirement is one that can be checked by name
3264 /// lookup (6.4) or by checking properties of types and expressions.
3266 /// requires-expression:
3267 /// 'requires' requirement-parameter-list[opt] requirement-body
3269 /// requirement-parameter-list:
3270 /// '(' parameter-declaration-clause[opt] ')'
3272 /// requirement-body:
3273 /// '{' requirement-seq '}'
3275 /// requirement-seq:
3277 /// requirement-seq requirement
3280 /// simple-requirement
3281 /// type-requirement
3282 /// compound-requirement
3283 /// nested-requirement
3284 ExprResult Parser::ParseRequiresExpression() {
3285 assert(Tok.is(tok::kw_requires) && "Expected 'requires' keyword");
3286 SourceLocation RequiresKWLoc = ConsumeToken(); // Consume 'requires'
3288 llvm::SmallVector<ParmVarDecl *, 2> LocalParameterDecls;
3289 if (Tok.is(tok::l_paren)) {
3290 // requirement parameter list is present.
3291 ParseScope LocalParametersScope(this, Scope::FunctionPrototypeScope |
3293 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3294 Parens.consumeOpen();
3295 if (!Tok.is(tok::r_paren)) {
3296 ParsedAttributes FirstArgAttrs(getAttrFactory());
3297 SourceLocation EllipsisLoc;
3298 llvm::SmallVector<DeclaratorChunk::ParamInfo, 2> LocalParameters;
3299 DiagnosticErrorTrap Trap(Diags);
3300 ParseParameterDeclarationClause(DeclaratorContext::RequiresExprContext,
3301 FirstArgAttrs, LocalParameters,
3303 if (EllipsisLoc.isValid())
3304 Diag(EllipsisLoc, diag::err_requires_expr_parameter_list_ellipsis);
3305 for (auto &ParamInfo : LocalParameters)
3306 LocalParameterDecls.push_back(cast<ParmVarDecl>(ParamInfo.Param));
3307 if (Trap.hasErrorOccurred())
3308 SkipUntil(tok::r_paren, StopBeforeMatch);
3310 Parens.consumeClose();
3313 BalancedDelimiterTracker Braces(*this, tok::l_brace);
3314 if (Braces.expectAndConsume())
3317 // Start of requirement list
3318 llvm::SmallVector<concepts::Requirement *, 2> Requirements;
3320 // C++2a [expr.prim.req]p2
3321 // Expressions appearing within a requirement-body are unevaluated operands.
3322 EnterExpressionEvaluationContext Ctx(
3323 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
3325 ParseScope BodyScope(this, Scope::DeclScope);
3326 RequiresExprBodyDecl *Body = Actions.ActOnStartRequiresExpr(
3327 RequiresKWLoc, LocalParameterDecls, getCurScope());
3329 if (Tok.is(tok::r_brace)) {
3330 // Grammar does not allow an empty body.
3331 // requirement-body:
3332 // { requirement-seq }
3335 // requirement-seq requirement
3336 Diag(Tok, diag::err_empty_requires_expr);
3337 // Continue anyway and produce a requires expr with no requirements.
3339 while (!Tok.is(tok::r_brace)) {
3340 switch (Tok.getKind()) {
3341 case tok::l_brace: {
3342 // Compound requirement
3343 // C++ [expr.prim.req.compound]
3344 // compound-requirement:
3345 // '{' expression '}' 'noexcept'[opt]
3346 // return-type-requirement[opt] ';'
3347 // return-type-requirement:
3348 // trailing-return-type
3349 // '->' cv-qualifier-seq[opt] constrained-parameter
3350 // cv-qualifier-seq[opt] abstract-declarator[opt]
3351 BalancedDelimiterTracker ExprBraces(*this, tok::l_brace);
3352 ExprBraces.consumeOpen();
3353 ExprResult Expression =
3354 Actions.CorrectDelayedTyposInExpr(ParseExpression());
3355 if (!Expression.isUsable()) {
3356 ExprBraces.skipToEnd();
3357 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3360 if (ExprBraces.consumeClose())
3361 ExprBraces.skipToEnd();
3363 concepts::Requirement *Req = nullptr;
3364 SourceLocation NoexceptLoc;
3365 TryConsumeToken(tok::kw_noexcept, NoexceptLoc);
3366 if (Tok.is(tok::semi)) {
3367 Req = Actions.ActOnCompoundRequirement(Expression.get(), NoexceptLoc);
3369 Requirements.push_back(Req);
3372 if (!TryConsumeToken(tok::arrow))
3373 // User probably forgot the arrow, remind them and try to continue.
3374 Diag(Tok, diag::err_requires_expr_missing_arrow)
3375 << FixItHint::CreateInsertion(Tok.getLocation(), "->");
3376 // Try to parse a 'type-constraint'
3377 if (TryAnnotateTypeConstraint()) {
3378 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3381 if (!isTypeConstraintAnnotation()) {
3382 Diag(Tok, diag::err_requires_expr_expected_type_constraint);
3383 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3387 if (Tok.is(tok::annot_cxxscope)) {
3388 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
3389 Tok.getAnnotationRange(),
3391 ConsumeAnnotationToken();
3394 Req = Actions.ActOnCompoundRequirement(
3395 Expression.get(), NoexceptLoc, SS, takeTemplateIdAnnotation(Tok),
3396 TemplateParameterDepth);
3397 ConsumeAnnotationToken();
3399 Requirements.push_back(Req);
3403 bool PossibleRequiresExprInSimpleRequirement = false;
3404 if (Tok.is(tok::kw_requires)) {
3405 auto IsNestedRequirement = [&] {
3406 RevertingTentativeParsingAction TPA(*this);
3407 ConsumeToken(); // 'requires'
3408 if (Tok.is(tok::l_brace))
3409 // This is a requires expression
3411 // requires { t++; };
3415 if (Tok.is(tok::l_paren)) {
3416 // This might be the parameter list of a requires expression
3418 auto Res = TryParseParameterDeclarationClause();
3419 if (Res != TPResult::False) {
3420 // Skip to the closing parenthesis
3421 // FIXME: Don't traverse these tokens twice (here and in
3422 // TryParseParameterDeclarationClause).
3424 while (Depth != 0) {
3425 if (Tok.is(tok::l_paren))
3427 else if (Tok.is(tok::r_paren))
3435 // requires (int x) ?
3438 if (Tok.is(tok::l_brace))
3440 // ^ - a requires expression as a
3441 // simple-requirement.
3447 if (IsNestedRequirement()) {
3449 // Nested requirement
3450 // C++ [expr.prim.req.nested]
3451 // nested-requirement:
3452 // 'requires' constraint-expression ';'
3453 ExprResult ConstraintExpr =
3454 Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression());
3455 if (ConstraintExpr.isInvalid() || !ConstraintExpr.isUsable()) {
3456 SkipUntil(tok::semi, tok::r_brace,
3457 SkipUntilFlags::StopBeforeMatch);
3461 Actions.ActOnNestedRequirement(ConstraintExpr.get()))
3462 Requirements.push_back(Req);
3464 SkipUntil(tok::semi, tok::r_brace,
3465 SkipUntilFlags::StopBeforeMatch);
3470 PossibleRequiresExprInSimpleRequirement = true;
3471 } else if (Tok.is(tok::kw_typename)) {
3472 // This might be 'typename T::value_type;' (a type requirement) or
3473 // 'typename T::value_type{};' (a simple requirement).
3474 TentativeParsingAction TPA(*this);
3476 // We need to consume the typename to allow 'requires { typename a; }'
3477 SourceLocation TypenameKWLoc = ConsumeToken();
3478 if (TryAnnotateCXXScopeToken()) {
3480 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3484 if (Tok.is(tok::annot_cxxscope)) {
3485 Actions.RestoreNestedNameSpecifierAnnotation(
3486 Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS);
3487 ConsumeAnnotationToken();
3490 if (Tok.isOneOf(tok::identifier, tok::annot_template_id) &&
3491 !NextToken().isOneOf(tok::l_brace, tok::l_paren)) {
3493 SourceLocation NameLoc = Tok.getLocation();
3494 IdentifierInfo *II = nullptr;
3495 TemplateIdAnnotation *TemplateId = nullptr;
3496 if (Tok.is(tok::identifier)) {
3497 II = Tok.getIdentifierInfo();
3500 TemplateId = takeTemplateIdAnnotation(Tok);
3501 ConsumeAnnotationToken();
3504 if (auto *Req = Actions.ActOnTypeRequirement(TypenameKWLoc, SS,
3507 Requirements.push_back(Req);
3513 // Simple requirement
3514 // C++ [expr.prim.req.simple]
3515 // simple-requirement:
3517 SourceLocation StartLoc = Tok.getLocation();
3518 ExprResult Expression =
3519 Actions.CorrectDelayedTyposInExpr(ParseExpression());
3520 if (!Expression.isUsable()) {
3521 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3524 if (!Expression.isInvalid() && PossibleRequiresExprInSimpleRequirement)
3525 Diag(StartLoc, diag::warn_requires_expr_in_simple_requirement)
3526 << FixItHint::CreateInsertion(StartLoc, "requires");
3527 if (auto *Req = Actions.ActOnSimpleRequirement(Expression.get()))
3528 Requirements.push_back(Req);
3530 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3533 // User may have tried to put some compound requirement stuff here
3534 if (Tok.is(tok::kw_noexcept)) {
3535 Diag(Tok, diag::err_requires_expr_simple_requirement_noexcept)
3536 << FixItHint::CreateInsertion(StartLoc, "{")
3537 << FixItHint::CreateInsertion(Tok.getLocation(), "}");
3538 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3544 if (ExpectAndConsumeSemi(diag::err_expected_semi_requirement)) {
3545 SkipUntil(tok::semi, tok::r_brace, SkipUntilFlags::StopBeforeMatch);
3546 TryConsumeToken(tok::semi);
3550 if (Requirements.empty()) {
3551 // Don't emit an empty requires expr here to avoid confusing the user with
3552 // other diagnostics quoting an empty requires expression they never
3554 Braces.consumeClose();
3555 Actions.ActOnFinishRequiresExpr();
3559 Braces.consumeClose();
3560 Actions.ActOnFinishRequiresExpr();
3561 return Actions.ActOnRequiresExpr(RequiresKWLoc, Body, LocalParameterDecls,
3562 Requirements, Braces.getCloseLocation());
3565 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
3567 default: llvm_unreachable("Not a known type trait");
3568 #define TYPE_TRAIT_1(Spelling, Name, Key) \
3569 case tok::kw_ ## Spelling: return UTT_ ## Name;
3570 #define TYPE_TRAIT_2(Spelling, Name, Key) \
3571 case tok::kw_ ## Spelling: return BTT_ ## Name;
3572 #include "clang/Basic/TokenKinds.def"
3573 #define TYPE_TRAIT_N(Spelling, Name, Key) \
3574 case tok::kw_ ## Spelling: return TT_ ## Name;
3575 #include "clang/Basic/TokenKinds.def"
3579 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
3581 default: llvm_unreachable("Not a known binary type trait");
3582 case tok::kw___array_rank: return ATT_ArrayRank;
3583 case tok::kw___array_extent: return ATT_ArrayExtent;
3587 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
3589 default: llvm_unreachable("Not a known unary expression trait.");
3590 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
3591 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
3595 static unsigned TypeTraitArity(tok::TokenKind kind) {
3597 default: llvm_unreachable("Not a known type trait");
3598 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
3599 #include "clang/Basic/TokenKinds.def"
3603 /// Parse the built-in type-trait pseudo-functions that allow
3604 /// implementation of the TR1/C++11 type traits templates.
3606 /// primary-expression:
3607 /// unary-type-trait '(' type-id ')'
3608 /// binary-type-trait '(' type-id ',' type-id ')'
3609 /// type-trait '(' type-id-seq ')'
3612 /// type-id ...[opt] type-id-seq[opt]
3614 ExprResult Parser::ParseTypeTrait() {
3615 tok::TokenKind Kind = Tok.getKind();
3616 unsigned Arity = TypeTraitArity(Kind);
3618 SourceLocation Loc = ConsumeToken();
3620 BalancedDelimiterTracker Parens(*this, tok::l_paren);
3621 if (Parens.expectAndConsume())
3624 SmallVector<ParsedType, 2> Args;
3626 // Parse the next type.
3627 TypeResult Ty = ParseTypeName();
3628 if (Ty.isInvalid()) {
3633 // Parse the ellipsis, if present.
3634 if (Tok.is(tok::ellipsis)) {
3635 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
3636 if (Ty.isInvalid()) {
3642 // Add this type to the list of arguments.
3643 Args.push_back(Ty.get());
3644 } while (TryConsumeToken(tok::comma));
3646 if (Parens.consumeClose())
3649 SourceLocation EndLoc = Parens.getCloseLocation();
3651 if (Arity && Args.size() != Arity) {
3652 Diag(EndLoc, diag::err_type_trait_arity)
3653 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3657 if (!Arity && Args.empty()) {
3658 Diag(EndLoc, diag::err_type_trait_arity)
3659 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3663 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
3666 /// ParseArrayTypeTrait - Parse the built-in array type-trait
3667 /// pseudo-functions.
3669 /// primary-expression:
3670 /// [Embarcadero] '__array_rank' '(' type-id ')'
3671 /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3673 ExprResult Parser::ParseArrayTypeTrait() {
3674 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3675 SourceLocation Loc = ConsumeToken();
3677 BalancedDelimiterTracker T(*this, tok::l_paren);
3678 if (T.expectAndConsume())
3681 TypeResult Ty = ParseTypeName();
3682 if (Ty.isInvalid()) {
3683 SkipUntil(tok::comma, StopAtSemi);
3684 SkipUntil(tok::r_paren, StopAtSemi);
3689 case ATT_ArrayRank: {
3691 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
3692 T.getCloseLocation());
3694 case ATT_ArrayExtent: {
3695 if (ExpectAndConsume(tok::comma)) {
3696 SkipUntil(tok::r_paren, StopAtSemi);
3700 ExprResult DimExpr = ParseExpression();
3703 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3704 T.getCloseLocation());
3707 llvm_unreachable("Invalid ArrayTypeTrait!");
3710 /// ParseExpressionTrait - Parse built-in expression-trait
3711 /// pseudo-functions like __is_lvalue_expr( xxx ).
3713 /// primary-expression:
3714 /// [Embarcadero] expression-trait '(' expression ')'
3716 ExprResult Parser::ParseExpressionTrait() {
3717 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3718 SourceLocation Loc = ConsumeToken();
3720 BalancedDelimiterTracker T(*this, tok::l_paren);
3721 if (T.expectAndConsume())
3724 ExprResult Expr = ParseExpression();
3728 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3729 T.getCloseLocation());
3733 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3734 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3735 /// based on the context past the parens.
3737 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
3739 BalancedDelimiterTracker &Tracker,
3740 ColonProtectionRAIIObject &ColonProt) {
3741 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
3742 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3743 assert(isTypeIdInParens() && "Not a type-id!");
3745 ExprResult Result(true);
3748 // We need to disambiguate a very ugly part of the C++ syntax:
3750 // (T())x; - type-id
3751 // (T())*x; - type-id
3752 // (T())/x; - expression
3753 // (T()); - expression
3755 // The bad news is that we cannot use the specialized tentative parser, since
3756 // it can only verify that the thing inside the parens can be parsed as
3757 // type-id, it is not useful for determining the context past the parens.
3759 // The good news is that the parser can disambiguate this part without
3760 // making any unnecessary Action calls.
3762 // It uses a scheme similar to parsing inline methods. The parenthesized
3763 // tokens are cached, the context that follows is determined (possibly by
3764 // parsing a cast-expression), and then we re-introduce the cached tokens
3765 // into the token stream and parse them appropriately.
3767 ParenParseOption ParseAs;
3770 // Store the tokens of the parentheses. We will parse them after we determine
3771 // the context that follows them.
3772 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
3773 // We didn't find the ')' we expected.
3774 Tracker.consumeClose();
3778 if (Tok.is(tok::l_brace)) {
3779 ParseAs = CompoundLiteral;
3782 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3785 // Try parsing the cast-expression that may follow.
3786 // If it is not a cast-expression, NotCastExpr will be true and no token
3787 // will be consumed.
3788 ColonProt.restore();
3789 Result = ParseCastExpression(AnyCastExpr,
3790 false/*isAddressofOperand*/,
3792 // type-id has priority.
3796 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3798 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
3801 // Create a fake EOF to mark end of Toks buffer.
3803 AttrEnd.startToken();
3804 AttrEnd.setKind(tok::eof);
3805 AttrEnd.setLocation(Tok.getLocation());
3806 AttrEnd.setEofData(Toks.data());
3807 Toks.push_back(AttrEnd);
3809 // The current token should go after the cached tokens.
3810 Toks.push_back(Tok);
3811 // Re-enter the stored parenthesized tokens into the token stream, so we may
3813 PP.EnterTokenStream(Toks, /*DisableMacroExpansion*/ true,
3814 /*IsReinject*/ true);
3815 // Drop the current token and bring the first cached one. It's the same token
3816 // as when we entered this function.
3819 if (ParseAs >= CompoundLiteral) {
3820 // Parse the type declarator.
3821 DeclSpec DS(AttrFactory);
3822 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
3824 ColonProtectionRAIIObject InnerColonProtection(*this);
3825 ParseSpecifierQualifierList(DS);
3826 ParseDeclarator(DeclaratorInfo);
3830 Tracker.consumeClose();
3831 ColonProt.restore();
3833 // Consume EOF marker for Toks buffer.
3834 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3837 if (ParseAs == CompoundLiteral) {
3838 ExprType = CompoundLiteral;
3839 if (DeclaratorInfo.isInvalidType())
3842 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3843 return ParseCompoundLiteralExpression(Ty.get(),
3844 Tracker.getOpenLocation(),
3845 Tracker.getCloseLocation());
3848 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3849 assert(ParseAs == CastExpr);
3851 if (DeclaratorInfo.isInvalidType())
3854 // Result is what ParseCastExpression returned earlier.
3855 if (!Result.isInvalid())
3856 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3857 DeclaratorInfo, CastTy,
3858 Tracker.getCloseLocation(), Result.get());
3862 // Not a compound literal, and not followed by a cast-expression.
3863 assert(ParseAs == SimpleExpr);
3865 ExprType = SimpleExpr;
3866 Result = ParseExpression();
3867 if (!Result.isInvalid() && Tok.is(tok::r_paren))
3868 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3869 Tok.getLocation(), Result.get());
3872 if (Result.isInvalid()) {
3873 while (Tok.isNot(tok::eof))
3875 assert(Tok.getEofData() == AttrEnd.getEofData());
3880 Tracker.consumeClose();
3881 // Consume EOF marker for Toks buffer.
3882 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3887 /// Parse a __builtin_bit_cast(T, E).
3888 ExprResult Parser::ParseBuiltinBitCast() {
3889 SourceLocation KWLoc = ConsumeToken();
3891 BalancedDelimiterTracker T(*this, tok::l_paren);
3892 if (T.expectAndConsume(diag::err_expected_lparen_after, "__builtin_bit_cast"))
3895 // Parse the common declaration-specifiers piece.
3896 DeclSpec DS(AttrFactory);
3897 ParseSpecifierQualifierList(DS);
3899 // Parse the abstract-declarator, if present.
3900 Declarator DeclaratorInfo(DS, DeclaratorContext::TypeNameContext);
3901 ParseDeclarator(DeclaratorInfo);
3903 if (ExpectAndConsume(tok::comma)) {
3904 Diag(Tok.getLocation(), diag::err_expected) << tok::comma;
3905 SkipUntil(tok::r_paren, StopAtSemi);
3909 ExprResult Operand = ParseExpression();
3911 if (T.consumeClose())
3914 if (Operand.isInvalid() || DeclaratorInfo.isInvalidType())
3917 return Actions.ActOnBuiltinBitCastExpr(KWLoc, DeclaratorInfo, Operand,
3918 T.getCloseLocation());