brintos

brintos / llvm-project-archived public Read only

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