Home | History | Annotate | Download | only in Parse
      1 //===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the Expression parsing implementation for C++.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 #include "clang/AST/ASTContext.h"
     14 #include "RAIIObjectsForParser.h"
     15 #include "clang/AST/DeclTemplate.h"
     16 #include "clang/Basic/PrettyStackTrace.h"
     17 #include "clang/Lex/LiteralSupport.h"
     18 #include "clang/Parse/ParseDiagnostic.h"
     19 #include "clang/Parse/Parser.h"
     20 #include "clang/Sema/DeclSpec.h"
     21 #include "clang/Sema/ParsedTemplate.h"
     22 #include "clang/Sema/Scope.h"
     23 #include "llvm/Support/ErrorHandling.h"
     24 
     25 
     26 using namespace clang;
     27 
     28 static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
     29   switch (Kind) {
     30     // template name
     31     case tok::unknown:             return 0;
     32     // casts
     33     case tok::kw_const_cast:       return 1;
     34     case tok::kw_dynamic_cast:     return 2;
     35     case tok::kw_reinterpret_cast: return 3;
     36     case tok::kw_static_cast:      return 4;
     37     default:
     38       llvm_unreachable("Unknown type for digraph error message.");
     39   }
     40 }
     41 
     42 // Are the two tokens adjacent in the same source file?
     43 bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
     44   SourceManager &SM = PP.getSourceManager();
     45   SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
     46   SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
     47   return FirstEnd == SM.getSpellingLoc(Second.getLocation());
     48 }
     49 
     50 // Suggest fixit for "<::" after a cast.
     51 static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
     52                        Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
     53   // Pull '<:' and ':' off token stream.
     54   if (!AtDigraph)
     55     PP.Lex(DigraphToken);
     56   PP.Lex(ColonToken);
     57 
     58   SourceRange Range;
     59   Range.setBegin(DigraphToken.getLocation());
     60   Range.setEnd(ColonToken.getLocation());
     61   P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
     62       << SelectDigraphErrorMessage(Kind)
     63       << FixItHint::CreateReplacement(Range, "< ::");
     64 
     65   // Update token information to reflect their change in token type.
     66   ColonToken.setKind(tok::coloncolon);
     67   ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
     68   ColonToken.setLength(2);
     69   DigraphToken.setKind(tok::less);
     70   DigraphToken.setLength(1);
     71 
     72   // Push new tokens back to token stream.
     73   PP.EnterToken(ColonToken);
     74   if (!AtDigraph)
     75     PP.EnterToken(DigraphToken);
     76 }
     77 
     78 // Check for '<::' which should be '< ::' instead of '[:' when following
     79 // a template name.
     80 void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
     81                                         bool EnteringContext,
     82                                         IdentifierInfo &II, CXXScopeSpec &SS) {
     83   if (!Next.is(tok::l_square) || Next.getLength() != 2)
     84     return;
     85 
     86   Token SecondToken = GetLookAheadToken(2);
     87   if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
     88     return;
     89 
     90   TemplateTy Template;
     91   UnqualifiedId TemplateName;
     92   TemplateName.setIdentifier(&II, Tok.getLocation());
     93   bool MemberOfUnknownSpecialization;
     94   if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
     95                               TemplateName, ObjectType, EnteringContext,
     96                               Template, MemberOfUnknownSpecialization))
     97     return;
     98 
     99   FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
    100              /*AtDigraph*/false);
    101 }
    102 
    103 /// \brief Emits an error for a left parentheses after a double colon.
    104 ///
    105 /// When a '(' is found after a '::', emit an error.  Attempt to fix the token
    106 /// stream by removing the '(', and the matching ')' if found.
    107 void Parser::CheckForLParenAfterColonColon() {
    108   if (!Tok.is(tok::l_paren))
    109     return;
    110 
    111   Token LParen = Tok;
    112   Token NextTok = GetLookAheadToken(1);
    113   Token StarTok = NextTok;
    114   // Check for (identifier or (*identifier
    115   Token IdentifierTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : StarTok;
    116   if (IdentifierTok.isNot(tok::identifier))
    117     return;
    118   // Eat the '('.
    119   ConsumeParen();
    120   Token RParen;
    121   RParen.setLocation(SourceLocation());
    122   // Do we have a ')' ?
    123   NextTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : GetLookAheadToken(1);
    124   if (NextTok.is(tok::r_paren)) {
    125     RParen = NextTok;
    126     // Eat the '*' if it is present.
    127     if (StarTok.is(tok::star))
    128       ConsumeToken();
    129     // Eat the identifier.
    130     ConsumeToken();
    131     // Add the identifier token back.
    132     PP.EnterToken(IdentifierTok);
    133     // Add the '*' back if it was present.
    134     if (StarTok.is(tok::star))
    135       PP.EnterToken(StarTok);
    136     // Eat the ')'.
    137     ConsumeParen();
    138   }
    139 
    140   Diag(LParen.getLocation(), diag::err_paren_after_colon_colon)
    141       << FixItHint::CreateRemoval(LParen.getLocation())
    142       << FixItHint::CreateRemoval(RParen.getLocation());
    143 }
    144 
    145 /// \brief Parse global scope or nested-name-specifier if present.
    146 ///
    147 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
    148 /// may be preceded by '::'). Note that this routine will not parse ::new or
    149 /// ::delete; it will just leave them in the token stream.
    150 ///
    151 ///       '::'[opt] nested-name-specifier
    152 ///       '::'
    153 ///
    154 ///       nested-name-specifier:
    155 ///         type-name '::'
    156 ///         namespace-name '::'
    157 ///         nested-name-specifier identifier '::'
    158 ///         nested-name-specifier 'template'[opt] simple-template-id '::'
    159 ///
    160 ///
    161 /// \param SS the scope specifier that will be set to the parsed
    162 /// nested-name-specifier (or empty)
    163 ///
    164 /// \param ObjectType if this nested-name-specifier is being parsed following
    165 /// the "." or "->" of a member access expression, this parameter provides the
    166 /// type of the object whose members are being accessed.
    167 ///
    168 /// \param EnteringContext whether we will be entering into the context of
    169 /// the nested-name-specifier after parsing it.
    170 ///
    171 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
    172 /// indicates whether this nested-name-specifier may be part of a
    173 /// pseudo-destructor name. In this case, the flag will be set false
    174 /// if we don't actually end up parsing a destructor name. Moreorover,
    175 /// if we do end up determining that we are parsing a destructor name,
    176 /// the last component of the nested-name-specifier is not parsed as
    177 /// part of the scope specifier.
    178 ///
    179 /// \param IsTypename If \c true, this nested-name-specifier is known to be
    180 /// part of a type name. This is used to improve error recovery.
    181 ///
    182 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
    183 /// filled in with the leading identifier in the last component of the
    184 /// nested-name-specifier, if any.
    185 ///
    186 /// \returns true if there was an error parsing a scope specifier
    187 bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
    188                                             ParsedType ObjectType,
    189                                             bool EnteringContext,
    190                                             bool *MayBePseudoDestructor,
    191                                             bool IsTypename,
    192                                             IdentifierInfo **LastII) {
    193   assert(getLangOpts().CPlusPlus &&
    194          "Call sites of this function should be guarded by checking for C++");
    195 
    196   if (Tok.is(tok::annot_cxxscope)) {
    197     assert(!LastII && "want last identifier but have already annotated scope");
    198     assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
    199     Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
    200                                                  Tok.getAnnotationRange(),
    201                                                  SS);
    202     ConsumeToken();
    203     return false;
    204   }
    205 
    206   if (Tok.is(tok::annot_template_id)) {
    207     // If the current token is an annotated template id, it may already have
    208     // a scope specifier. Restore it.
    209     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
    210     SS = TemplateId->SS;
    211   }
    212 
    213   // Has to happen before any "return false"s in this function.
    214   bool CheckForDestructor = false;
    215   if (MayBePseudoDestructor && *MayBePseudoDestructor) {
    216     CheckForDestructor = true;
    217     *MayBePseudoDestructor = false;
    218   }
    219 
    220   if (LastII)
    221     *LastII = nullptr;
    222 
    223   bool HasScopeSpecifier = false;
    224 
    225   if (Tok.is(tok::coloncolon)) {
    226     // ::new and ::delete aren't nested-name-specifiers.
    227     tok::TokenKind NextKind = NextToken().getKind();
    228     if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
    229       return false;
    230 
    231     if (NextKind == tok::l_brace) {
    232       // It is invalid to have :: {, consume the scope qualifier and pretend
    233       // like we never saw it.
    234       Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
    235     } else {
    236       // '::' - Global scope qualifier.
    237       if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
    238         return true;
    239 
    240       CheckForLParenAfterColonColon();
    241 
    242       HasScopeSpecifier = true;
    243     }
    244   }
    245 
    246   if (Tok.is(tok::kw___super)) {
    247     SourceLocation SuperLoc = ConsumeToken();
    248     if (!Tok.is(tok::coloncolon)) {
    249       Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
    250       return true;
    251     }
    252 
    253     return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
    254   }
    255 
    256   if (!HasScopeSpecifier &&
    257       Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
    258     DeclSpec DS(AttrFactory);
    259     SourceLocation DeclLoc = Tok.getLocation();
    260     SourceLocation EndLoc  = ParseDecltypeSpecifier(DS);
    261 
    262     SourceLocation CCLoc;
    263     if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
    264       AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
    265       return false;
    266     }
    267 
    268     if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
    269       SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
    270 
    271     HasScopeSpecifier = true;
    272   }
    273 
    274   while (true) {
    275     if (HasScopeSpecifier) {
    276       // C++ [basic.lookup.classref]p5:
    277       //   If the qualified-id has the form
    278       //
    279       //       ::class-name-or-namespace-name::...
    280       //
    281       //   the class-name-or-namespace-name is looked up in global scope as a
    282       //   class-name or namespace-name.
    283       //
    284       // To implement this, we clear out the object type as soon as we've
    285       // seen a leading '::' or part of a nested-name-specifier.
    286       ObjectType = nullptr;
    287 
    288       if (Tok.is(tok::code_completion)) {
    289         // Code completion for a nested-name-specifier, where the code
    290         // code completion token follows the '::'.
    291         Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
    292         // Include code completion token into the range of the scope otherwise
    293         // when we try to annotate the scope tokens the dangling code completion
    294         // token will cause assertion in
    295         // Preprocessor::AnnotatePreviousCachedTokens.
    296         SS.setEndLoc(Tok.getLocation());
    297         cutOffParsing();
    298         return true;
    299       }
    300     }
    301 
    302     // nested-name-specifier:
    303     //   nested-name-specifier 'template'[opt] simple-template-id '::'
    304 
    305     // Parse the optional 'template' keyword, then make sure we have
    306     // 'identifier <' after it.
    307     if (Tok.is(tok::kw_template)) {
    308       // If we don't have a scope specifier or an object type, this isn't a
    309       // nested-name-specifier, since they aren't allowed to start with
    310       // 'template'.
    311       if (!HasScopeSpecifier && !ObjectType)
    312         break;
    313 
    314       TentativeParsingAction TPA(*this);
    315       SourceLocation TemplateKWLoc = ConsumeToken();
    316 
    317       UnqualifiedId TemplateName;
    318       if (Tok.is(tok::identifier)) {
    319         // Consume the identifier.
    320         TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
    321         ConsumeToken();
    322       } else if (Tok.is(tok::kw_operator)) {
    323         // We don't need to actually parse the unqualified-id in this case,
    324         // because a simple-template-id cannot start with 'operator', but
    325         // go ahead and parse it anyway for consistency with the case where
    326         // we already annotated the template-id.
    327         if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
    328                                        TemplateName)) {
    329           TPA.Commit();
    330           break;
    331         }
    332 
    333         if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
    334             TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
    335           Diag(TemplateName.getSourceRange().getBegin(),
    336                diag::err_id_after_template_in_nested_name_spec)
    337             << TemplateName.getSourceRange();
    338           TPA.Commit();
    339           break;
    340         }
    341       } else {
    342         TPA.Revert();
    343         break;
    344       }
    345 
    346       // If the next token is not '<', we have a qualified-id that refers
    347       // to a template name, such as T::template apply, but is not a
    348       // template-id.
    349       if (Tok.isNot(tok::less)) {
    350         TPA.Revert();
    351         break;
    352       }
    353 
    354       // Commit to parsing the template-id.
    355       TPA.Commit();
    356       TemplateTy Template;
    357       if (TemplateNameKind TNK
    358           = Actions.ActOnDependentTemplateName(getCurScope(),
    359                                                SS, TemplateKWLoc, TemplateName,
    360                                                ObjectType, EnteringContext,
    361                                                Template)) {
    362         if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
    363                                     TemplateName, false))
    364           return true;
    365       } else
    366         return true;
    367 
    368       continue;
    369     }
    370 
    371     if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
    372       // We have
    373       //
    374       //   template-id '::'
    375       //
    376       // So we need to check whether the template-id is a simple-template-id of
    377       // the right kind (it should name a type or be dependent), and then
    378       // convert it into a type within the nested-name-specifier.
    379       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
    380       if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
    381         *MayBePseudoDestructor = true;
    382         return false;
    383       }
    384 
    385       if (LastII)
    386         *LastII = TemplateId->Name;
    387 
    388       // Consume the template-id token.
    389       ConsumeToken();
    390 
    391       assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
    392       SourceLocation CCLoc = ConsumeToken();
    393 
    394       HasScopeSpecifier = true;
    395 
    396       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
    397                                          TemplateId->NumArgs);
    398 
    399       if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
    400                                               SS,
    401                                               TemplateId->TemplateKWLoc,
    402                                               TemplateId->Template,
    403                                               TemplateId->TemplateNameLoc,
    404                                               TemplateId->LAngleLoc,
    405                                               TemplateArgsPtr,
    406                                               TemplateId->RAngleLoc,
    407                                               CCLoc,
    408                                               EnteringContext)) {
    409         SourceLocation StartLoc
    410           = SS.getBeginLoc().isValid()? SS.getBeginLoc()
    411                                       : TemplateId->TemplateNameLoc;
    412         SS.SetInvalid(SourceRange(StartLoc, CCLoc));
    413       }
    414 
    415       continue;
    416     }
    417 
    418     // The rest of the nested-name-specifier possibilities start with
    419     // tok::identifier.
    420     if (Tok.isNot(tok::identifier))
    421       break;
    422 
    423     IdentifierInfo &II = *Tok.getIdentifierInfo();
    424 
    425     // nested-name-specifier:
    426     //   type-name '::'
    427     //   namespace-name '::'
    428     //   nested-name-specifier identifier '::'
    429     Token Next = NextToken();
    430 
    431     // If we get foo:bar, this is almost certainly a typo for foo::bar.  Recover
    432     // and emit a fixit hint for it.
    433     if (Next.is(tok::colon) && !ColonIsSacred) {
    434       if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
    435                                             Tok.getLocation(),
    436                                             Next.getLocation(), ObjectType,
    437                                             EnteringContext) &&
    438           // If the token after the colon isn't an identifier, it's still an
    439           // error, but they probably meant something else strange so don't
    440           // recover like this.
    441           PP.LookAhead(1).is(tok::identifier)) {
    442         Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
    443           << FixItHint::CreateReplacement(Next.getLocation(), "::");
    444         // Recover as if the user wrote '::'.
    445         Next.setKind(tok::coloncolon);
    446       }
    447     }
    448 
    449     if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
    450       // It is invalid to have :: {, consume the scope qualifier and pretend
    451       // like we never saw it.
    452       Token Identifier = Tok; // Stash away the identifier.
    453       ConsumeToken();         // Eat the identifier, current token is now '::'.
    454       Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
    455           << tok::identifier;
    456       UnconsumeToken(Identifier); // Stick the identifier back.
    457       Next = NextToken();         // Point Next at the '{' token.
    458     }
    459 
    460     if (Next.is(tok::coloncolon)) {
    461       if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
    462           !Actions.isNonTypeNestedNameSpecifier(
    463               getCurScope(), SS, Tok.getLocation(), II, ObjectType)) {
    464         *MayBePseudoDestructor = true;
    465         return false;
    466       }
    467 
    468       if (ColonIsSacred) {
    469         const Token &Next2 = GetLookAheadToken(2);
    470         if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
    471             Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
    472           Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
    473               << Next2.getName()
    474               << FixItHint::CreateReplacement(Next.getLocation(), ":");
    475           Token ColonColon;
    476           PP.Lex(ColonColon);
    477           ColonColon.setKind(tok::colon);
    478           PP.EnterToken(ColonColon);
    479           break;
    480         }
    481       }
    482 
    483       if (LastII)
    484         *LastII = &II;
    485 
    486       // We have an identifier followed by a '::'. Lookup this name
    487       // as the name in a nested-name-specifier.
    488       Token Identifier = Tok;
    489       SourceLocation IdLoc = ConsumeToken();
    490       assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
    491              "NextToken() not working properly!");
    492       Token ColonColon = Tok;
    493       SourceLocation CCLoc = ConsumeToken();
    494 
    495       CheckForLParenAfterColonColon();
    496 
    497       bool IsCorrectedToColon = false;
    498       bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
    499       if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
    500                                               ObjectType, EnteringContext, SS,
    501                                               false, CorrectionFlagPtr)) {
    502         // Identifier is not recognized as a nested name, but we can have
    503         // mistyped '::' instead of ':'.
    504         if (CorrectionFlagPtr && IsCorrectedToColon) {
    505           ColonColon.setKind(tok::colon);
    506           PP.EnterToken(Tok);
    507           PP.EnterToken(ColonColon);
    508           Tok = Identifier;
    509           break;
    510         }
    511         SS.SetInvalid(SourceRange(IdLoc, CCLoc));
    512       }
    513       HasScopeSpecifier = true;
    514       continue;
    515     }
    516 
    517     CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
    518 
    519     // nested-name-specifier:
    520     //   type-name '<'
    521     if (Next.is(tok::less)) {
    522       TemplateTy Template;
    523       UnqualifiedId TemplateName;
    524       TemplateName.setIdentifier(&II, Tok.getLocation());
    525       bool MemberOfUnknownSpecialization;
    526       if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
    527                                               /*hasTemplateKeyword=*/false,
    528                                                         TemplateName,
    529                                                         ObjectType,
    530                                                         EnteringContext,
    531                                                         Template,
    532                                               MemberOfUnknownSpecialization)) {
    533         // We have found a template name, so annotate this token
    534         // with a template-id annotation. We do not permit the
    535         // template-id to be translated into a type annotation,
    536         // because some clients (e.g., the parsing of class template
    537         // specializations) still want to see the original template-id
    538         // token.
    539         ConsumeToken();
    540         if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
    541                                     TemplateName, false))
    542           return true;
    543         continue;
    544       }
    545 
    546       if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
    547           (IsTypename || IsTemplateArgumentList(1))) {
    548         // We have something like t::getAs<T>, where getAs is a
    549         // member of an unknown specialization. However, this will only
    550         // parse correctly as a template, so suggest the keyword 'template'
    551         // before 'getAs' and treat this as a dependent template name.
    552         unsigned DiagID = diag::err_missing_dependent_template_keyword;
    553         if (getLangOpts().MicrosoftExt)
    554           DiagID = diag::warn_missing_dependent_template_keyword;
    555 
    556         Diag(Tok.getLocation(), DiagID)
    557           << II.getName()
    558           << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
    559 
    560         if (TemplateNameKind TNK
    561               = Actions.ActOnDependentTemplateName(getCurScope(),
    562                                                    SS, SourceLocation(),
    563                                                    TemplateName, ObjectType,
    564                                                    EnteringContext, Template)) {
    565           // Consume the identifier.
    566           ConsumeToken();
    567           if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
    568                                       TemplateName, false))
    569             return true;
    570         }
    571         else
    572           return true;
    573 
    574         continue;
    575       }
    576     }
    577 
    578     // We don't have any tokens that form the beginning of a
    579     // nested-name-specifier, so we're done.
    580     break;
    581   }
    582 
    583   // Even if we didn't see any pieces of a nested-name-specifier, we
    584   // still check whether there is a tilde in this position, which
    585   // indicates a potential pseudo-destructor.
    586   if (CheckForDestructor && Tok.is(tok::tilde))
    587     *MayBePseudoDestructor = true;
    588 
    589   return false;
    590 }
    591 
    592 ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
    593                                            Token &Replacement) {
    594   SourceLocation TemplateKWLoc;
    595   UnqualifiedId Name;
    596   if (ParseUnqualifiedId(SS,
    597                          /*EnteringContext=*/false,
    598                          /*AllowDestructorName=*/false,
    599                          /*AllowConstructorName=*/false,
    600                          /*ObjectType=*/nullptr, TemplateKWLoc, Name))
    601     return ExprError();
    602 
    603   // This is only the direct operand of an & operator if it is not
    604   // followed by a postfix-expression suffix.
    605   if (isAddressOfOperand && isPostfixExpressionSuffixStart())
    606     isAddressOfOperand = false;
    607 
    608   return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
    609                                    Tok.is(tok::l_paren), isAddressOfOperand,
    610                                    nullptr, /*IsInlineAsmIdentifier=*/false,
    611                                    &Replacement);
    612 }
    613 
    614 /// ParseCXXIdExpression - Handle id-expression.
    615 ///
    616 ///       id-expression:
    617 ///         unqualified-id
    618 ///         qualified-id
    619 ///
    620 ///       qualified-id:
    621 ///         '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
    622 ///         '::' identifier
    623 ///         '::' operator-function-id
    624 ///         '::' template-id
    625 ///
    626 /// NOTE: The standard specifies that, for qualified-id, the parser does not
    627 /// expect:
    628 ///
    629 ///   '::' conversion-function-id
    630 ///   '::' '~' class-name
    631 ///
    632 /// This may cause a slight inconsistency on diagnostics:
    633 ///
    634 /// class C {};
    635 /// namespace A {}
    636 /// void f() {
    637 ///   :: A :: ~ C(); // Some Sema error about using destructor with a
    638 ///                  // namespace.
    639 ///   :: ~ C(); // Some Parser error like 'unexpected ~'.
    640 /// }
    641 ///
    642 /// We simplify the parser a bit and make it work like:
    643 ///
    644 ///       qualified-id:
    645 ///         '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
    646 ///         '::' unqualified-id
    647 ///
    648 /// That way Sema can handle and report similar errors for namespaces and the
    649 /// global scope.
    650 ///
    651 /// The isAddressOfOperand parameter indicates that this id-expression is a
    652 /// direct operand of the address-of operator. This is, besides member contexts,
    653 /// the only place where a qualified-id naming a non-static class member may
    654 /// appear.
    655 ///
    656 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
    657   // qualified-id:
    658   //   '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
    659   //   '::' unqualified-id
    660   //
    661   CXXScopeSpec SS;
    662   ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
    663 
    664   Token Replacement;
    665   ExprResult Result =
    666       tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
    667   if (Result.isUnset()) {
    668     // If the ExprResult is valid but null, then typo correction suggested a
    669     // keyword replacement that needs to be reparsed.
    670     UnconsumeToken(Replacement);
    671     Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
    672   }
    673   assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
    674                               "for a previous keyword suggestion");
    675   return Result;
    676 }
    677 
    678 /// ParseLambdaExpression - Parse a C++11 lambda expression.
    679 ///
    680 ///       lambda-expression:
    681 ///         lambda-introducer lambda-declarator[opt] compound-statement
    682 ///
    683 ///       lambda-introducer:
    684 ///         '[' lambda-capture[opt] ']'
    685 ///
    686 ///       lambda-capture:
    687 ///         capture-default
    688 ///         capture-list
    689 ///         capture-default ',' capture-list
    690 ///
    691 ///       capture-default:
    692 ///         '&'
    693 ///         '='
    694 ///
    695 ///       capture-list:
    696 ///         capture
    697 ///         capture-list ',' capture
    698 ///
    699 ///       capture:
    700 ///         simple-capture
    701 ///         init-capture     [C++1y]
    702 ///
    703 ///       simple-capture:
    704 ///         identifier
    705 ///         '&' identifier
    706 ///         'this'
    707 ///
    708 ///       init-capture:      [C++1y]
    709 ///         identifier initializer
    710 ///         '&' identifier initializer
    711 ///
    712 ///       lambda-declarator:
    713 ///         '(' parameter-declaration-clause ')' attribute-specifier[opt]
    714 ///           'mutable'[opt] exception-specification[opt]
    715 ///           trailing-return-type[opt]
    716 ///
    717 ExprResult Parser::ParseLambdaExpression() {
    718   // Parse lambda-introducer.
    719   LambdaIntroducer Intro;
    720   Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
    721   if (DiagID) {
    722     Diag(Tok, DiagID.getValue());
    723     SkipUntil(tok::r_square, StopAtSemi);
    724     SkipUntil(tok::l_brace, StopAtSemi);
    725     SkipUntil(tok::r_brace, StopAtSemi);
    726     return ExprError();
    727   }
    728 
    729   return ParseLambdaExpressionAfterIntroducer(Intro);
    730 }
    731 
    732 /// TryParseLambdaExpression - Use lookahead and potentially tentative
    733 /// parsing to determine if we are looking at a C++0x lambda expression, and parse
    734 /// it if we are.
    735 ///
    736 /// If we are not looking at a lambda expression, returns ExprError().
    737 ExprResult Parser::TryParseLambdaExpression() {
    738   assert(getLangOpts().CPlusPlus11
    739          && Tok.is(tok::l_square)
    740          && "Not at the start of a possible lambda expression.");
    741 
    742   const Token Next = NextToken();
    743   if (Next.is(tok::eof)) // Nothing else to lookup here...
    744     return ExprEmpty();
    745 
    746   const Token After = GetLookAheadToken(2);
    747   // If lookahead indicates this is a lambda...
    748   if (Next.is(tok::r_square) ||     // []
    749       Next.is(tok::equal) ||        // [=
    750       (Next.is(tok::amp) &&         // [&] or [&,
    751        (After.is(tok::r_square) ||
    752         After.is(tok::comma))) ||
    753       (Next.is(tok::identifier) &&  // [identifier]
    754        After.is(tok::r_square))) {
    755     return ParseLambdaExpression();
    756   }
    757 
    758   // If lookahead indicates an ObjC message send...
    759   // [identifier identifier
    760   if (Next.is(tok::identifier) && After.is(tok::identifier)) {
    761     return ExprEmpty();
    762   }
    763 
    764   // Here, we're stuck: lambda introducers and Objective-C message sends are
    765   // unambiguous, but it requires arbitrary lookhead.  [a,b,c,d,e,f,g] is a
    766   // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send.  Instead of
    767   // writing two routines to parse a lambda introducer, just try to parse
    768   // a lambda introducer first, and fall back if that fails.
    769   // (TryParseLambdaIntroducer never produces any diagnostic output.)
    770   LambdaIntroducer Intro;
    771   if (TryParseLambdaIntroducer(Intro))
    772     return ExprEmpty();
    773 
    774   return ParseLambdaExpressionAfterIntroducer(Intro);
    775 }
    776 
    777 /// \brief Parse a lambda introducer.
    778 /// \param Intro A LambdaIntroducer filled in with information about the
    779 ///        contents of the lambda-introducer.
    780 /// \param SkippedInits If non-null, we are disambiguating between an Obj-C
    781 ///        message send and a lambda expression. In this mode, we will
    782 ///        sometimes skip the initializers for init-captures and not fully
    783 ///        populate \p Intro. This flag will be set to \c true if we do so.
    784 /// \return A DiagnosticID if it hit something unexpected. The location for
    785 ///         for the diagnostic is that of the current token.
    786 Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
    787                                                  bool *SkippedInits) {
    788   typedef Optional<unsigned> DiagResult;
    789 
    790   assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
    791   BalancedDelimiterTracker T(*this, tok::l_square);
    792   T.consumeOpen();
    793 
    794   Intro.Range.setBegin(T.getOpenLocation());
    795 
    796   bool first = true;
    797 
    798   // Parse capture-default.
    799   if (Tok.is(tok::amp) &&
    800       (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
    801     Intro.Default = LCD_ByRef;
    802     Intro.DefaultLoc = ConsumeToken();
    803     first = false;
    804   } else if (Tok.is(tok::equal)) {
    805     Intro.Default = LCD_ByCopy;
    806     Intro.DefaultLoc = ConsumeToken();
    807     first = false;
    808   }
    809 
    810   while (Tok.isNot(tok::r_square)) {
    811     if (!first) {
    812       if (Tok.isNot(tok::comma)) {
    813         // Provide a completion for a lambda introducer here. Except
    814         // in Objective-C, where this is Almost Surely meant to be a message
    815         // send. In that case, fail here and let the ObjC message
    816         // expression parser perform the completion.
    817         if (Tok.is(tok::code_completion) &&
    818             !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
    819               !Intro.Captures.empty())) {
    820           Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
    821                                                /*AfterAmpersand=*/false);
    822           cutOffParsing();
    823           break;
    824         }
    825 
    826         return DiagResult(diag::err_expected_comma_or_rsquare);
    827       }
    828       ConsumeToken();
    829     }
    830 
    831     if (Tok.is(tok::code_completion)) {
    832       // If we're in Objective-C++ and we have a bare '[', then this is more
    833       // likely to be a message receiver.
    834       if (getLangOpts().ObjC1 && first)
    835         Actions.CodeCompleteObjCMessageReceiver(getCurScope());
    836       else
    837         Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
    838                                              /*AfterAmpersand=*/false);
    839       cutOffParsing();
    840       break;
    841     }
    842 
    843     first = false;
    844 
    845     // Parse capture.
    846     LambdaCaptureKind Kind = LCK_ByCopy;
    847     LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
    848     SourceLocation Loc;
    849     IdentifierInfo *Id = nullptr;
    850     SourceLocation EllipsisLoc;
    851     ExprResult Init;
    852 
    853     if (Tok.is(tok::star)) {
    854       Loc = ConsumeToken();
    855       if (Tok.is(tok::kw_this)) {
    856         ConsumeToken();
    857         Kind = LCK_StarThis;
    858       } else {
    859         return DiagResult(diag::err_expected_star_this_capture);
    860       }
    861     } else if (Tok.is(tok::kw_this)) {
    862       Kind = LCK_This;
    863       Loc = ConsumeToken();
    864     } else {
    865       if (Tok.is(tok::amp)) {
    866         Kind = LCK_ByRef;
    867         ConsumeToken();
    868 
    869         if (Tok.is(tok::code_completion)) {
    870           Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
    871                                                /*AfterAmpersand=*/true);
    872           cutOffParsing();
    873           break;
    874         }
    875       }
    876 
    877       if (Tok.is(tok::identifier)) {
    878         Id = Tok.getIdentifierInfo();
    879         Loc = ConsumeToken();
    880       } else if (Tok.is(tok::kw_this)) {
    881         // FIXME: If we want to suggest a fixit here, will need to return more
    882         // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
    883         // Clear()ed to prevent emission in case of tentative parsing?
    884         return DiagResult(diag::err_this_captured_by_reference);
    885       } else {
    886         return DiagResult(diag::err_expected_capture);
    887       }
    888 
    889       if (Tok.is(tok::l_paren)) {
    890         BalancedDelimiterTracker Parens(*this, tok::l_paren);
    891         Parens.consumeOpen();
    892 
    893         InitKind = LambdaCaptureInitKind::DirectInit;
    894 
    895         ExprVector Exprs;
    896         CommaLocsTy Commas;
    897         if (SkippedInits) {
    898           Parens.skipToEnd();
    899           *SkippedInits = true;
    900         } else if (ParseExpressionList(Exprs, Commas)) {
    901           Parens.skipToEnd();
    902           Init = ExprError();
    903         } else {
    904           Parens.consumeClose();
    905           Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
    906                                             Parens.getCloseLocation(),
    907                                             Exprs);
    908         }
    909       } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
    910         // Each lambda init-capture forms its own full expression, which clears
    911         // Actions.MaybeODRUseExprs. So create an expression evaluation context
    912         // to save the necessary state, and restore it later.
    913         EnterExpressionEvaluationContext EC(Actions,
    914                                             Sema::PotentiallyEvaluated);
    915 
    916         if (TryConsumeToken(tok::equal))
    917           InitKind = LambdaCaptureInitKind::CopyInit;
    918         else
    919           InitKind = LambdaCaptureInitKind::ListInit;
    920 
    921         if (!SkippedInits) {
    922           Init = ParseInitializer();
    923         } else if (Tok.is(tok::l_brace)) {
    924           BalancedDelimiterTracker Braces(*this, tok::l_brace);
    925           Braces.consumeOpen();
    926           Braces.skipToEnd();
    927           *SkippedInits = true;
    928         } else {
    929           // We're disambiguating this:
    930           //
    931           //   [..., x = expr
    932           //
    933           // We need to find the end of the following expression in order to
    934           // determine whether this is an Obj-C message send's receiver, a
    935           // C99 designator, or a lambda init-capture.
    936           //
    937           // Parse the expression to find where it ends, and annotate it back
    938           // onto the tokens. We would have parsed this expression the same way
    939           // in either case: both the RHS of an init-capture and the RHS of an
    940           // assignment expression are parsed as an initializer-clause, and in
    941           // neither case can anything be added to the scope between the '[' and
    942           // here.
    943           //
    944           // FIXME: This is horrible. Adding a mechanism to skip an expression
    945           // would be much cleaner.
    946           // FIXME: If there is a ',' before the next ']' or ':', we can skip to
    947           // that instead. (And if we see a ':' with no matching '?', we can
    948           // classify this as an Obj-C message send.)
    949           SourceLocation StartLoc = Tok.getLocation();
    950           InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
    951           Init = ParseInitializer();
    952 
    953           if (Tok.getLocation() != StartLoc) {
    954             // Back out the lexing of the token after the initializer.
    955             PP.RevertCachedTokens(1);
    956 
    957             // Replace the consumed tokens with an appropriate annotation.
    958             Tok.setLocation(StartLoc);
    959             Tok.setKind(tok::annot_primary_expr);
    960             setExprAnnotation(Tok, Init);
    961             Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
    962             PP.AnnotateCachedTokens(Tok);
    963 
    964             // Consume the annotated initializer.
    965             ConsumeToken();
    966           }
    967         }
    968       } else
    969         TryConsumeToken(tok::ellipsis, EllipsisLoc);
    970     }
    971     // If this is an init capture, process the initialization expression
    972     // right away.  For lambda init-captures such as the following:
    973     // const int x = 10;
    974     //  auto L = [i = x+1](int a) {
    975     //    return [j = x+2,
    976     //           &k = x](char b) { };
    977     //  };
    978     // keep in mind that each lambda init-capture has to have:
    979     //  - its initialization expression executed in the context
    980     //    of the enclosing/parent decl-context.
    981     //  - but the variable itself has to be 'injected' into the
    982     //    decl-context of its lambda's call-operator (which has
    983     //    not yet been created).
    984     // Each init-expression is a full-expression that has to get
    985     // Sema-analyzed (for capturing etc.) before its lambda's
    986     // call-operator's decl-context, scope & scopeinfo are pushed on their
    987     // respective stacks.  Thus if any variable is odr-used in the init-capture
    988     // it will correctly get captured in the enclosing lambda, if one exists.
    989     // The init-variables above are created later once the lambdascope and
    990     // call-operators decl-context is pushed onto its respective stack.
    991 
    992     // Since the lambda init-capture's initializer expression occurs in the
    993     // context of the enclosing function or lambda, therefore we can not wait
    994     // till a lambda scope has been pushed on before deciding whether the
    995     // variable needs to be captured.  We also need to process all
    996     // lvalue-to-rvalue conversions and discarded-value conversions,
    997     // so that we can avoid capturing certain constant variables.
    998     // For e.g.,
    999     //  void test() {
   1000     //   const int x = 10;
   1001     //   auto L = [&z = x](char a) { <-- don't capture by the current lambda
   1002     //     return [y = x](int i) { <-- don't capture by enclosing lambda
   1003     //          return y;
   1004     //     }
   1005     //   };
   1006     // If x was not const, the second use would require 'L' to capture, and
   1007     // that would be an error.
   1008 
   1009     ParsedType InitCaptureType;
   1010     if (Init.isUsable()) {
   1011       // Get the pointer and store it in an lvalue, so we can use it as an
   1012       // out argument.
   1013       Expr *InitExpr = Init.get();
   1014       // This performs any lvalue-to-rvalue conversions if necessary, which
   1015       // can affect what gets captured in the containing decl-context.
   1016       InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
   1017           Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
   1018       Init = InitExpr;
   1019     }
   1020     Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
   1021                      InitCaptureType);
   1022   }
   1023 
   1024   T.consumeClose();
   1025   Intro.Range.setEnd(T.getCloseLocation());
   1026   return DiagResult();
   1027 }
   1028 
   1029 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
   1030 ///
   1031 /// Returns true if it hit something unexpected.
   1032 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
   1033   TentativeParsingAction PA(*this);
   1034 
   1035   bool SkippedInits = false;
   1036   Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
   1037 
   1038   if (DiagID) {
   1039     PA.Revert();
   1040     return true;
   1041   }
   1042 
   1043   if (SkippedInits) {
   1044     // Parse it again, but this time parse the init-captures too.
   1045     PA.Revert();
   1046     Intro = LambdaIntroducer();
   1047     DiagID = ParseLambdaIntroducer(Intro);
   1048     assert(!DiagID && "parsing lambda-introducer failed on reparse");
   1049     return false;
   1050   }
   1051 
   1052   PA.Commit();
   1053   return false;
   1054 }
   1055 
   1056 static void
   1057 tryConsumeMutableOrConstexprToken(Parser &P, SourceLocation &MutableLoc,
   1058                                   SourceLocation &ConstexprLoc,
   1059                                   SourceLocation &DeclEndLoc) {
   1060   assert(MutableLoc.isInvalid());
   1061   assert(ConstexprLoc.isInvalid());
   1062   // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
   1063   // to the final of those locations. Emit an error if we have multiple
   1064   // copies of those keywords and recover.
   1065 
   1066   while (true) {
   1067     switch (P.getCurToken().getKind()) {
   1068     case tok::kw_mutable: {
   1069       if (MutableLoc.isValid()) {
   1070         P.Diag(P.getCurToken().getLocation(),
   1071                diag::err_lambda_decl_specifier_repeated)
   1072             << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
   1073       }
   1074       MutableLoc = P.ConsumeToken();
   1075       DeclEndLoc = MutableLoc;
   1076       break /*switch*/;
   1077     }
   1078     case tok::kw_constexpr:
   1079       if (ConstexprLoc.isValid()) {
   1080         P.Diag(P.getCurToken().getLocation(),
   1081                diag::err_lambda_decl_specifier_repeated)
   1082             << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
   1083       }
   1084       ConstexprLoc = P.ConsumeToken();
   1085       DeclEndLoc = ConstexprLoc;
   1086       break /*switch*/;
   1087     default:
   1088       return;
   1089     }
   1090   }
   1091 }
   1092 
   1093 static void
   1094 addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
   1095                                   DeclSpec &DS) {
   1096   if (ConstexprLoc.isValid()) {
   1097     P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus1z
   1098                              ? diag::ext_constexpr_on_lambda_cxx1z
   1099                              : diag::warn_cxx14_compat_constexpr_on_lambda);
   1100     const char *PrevSpec = nullptr;
   1101     unsigned DiagID = 0;
   1102     DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
   1103     assert(PrevSpec == nullptr && DiagID == 0 &&
   1104            "Constexpr cannot have been set previously!");
   1105   }
   1106 }
   1107 
   1108 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
   1109 /// expression.
   1110 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
   1111                      LambdaIntroducer &Intro) {
   1112   SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
   1113   Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
   1114 
   1115   PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
   1116                                 "lambda expression parsing");
   1117 
   1118 
   1119 
   1120   // FIXME: Call into Actions to add any init-capture declarations to the
   1121   // scope while parsing the lambda-declarator and compound-statement.
   1122 
   1123   // Parse lambda-declarator[opt].
   1124   DeclSpec DS(AttrFactory);
   1125   Declarator D(DS, Declarator::LambdaExprContext);
   1126   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
   1127   Actions.PushLambdaScope();
   1128 
   1129   TypeResult TrailingReturnType;
   1130   if (Tok.is(tok::l_paren)) {
   1131     ParseScope PrototypeScope(this,
   1132                               Scope::FunctionPrototypeScope |
   1133                               Scope::FunctionDeclarationScope |
   1134                               Scope::DeclScope);
   1135 
   1136     SourceLocation DeclEndLoc;
   1137     BalancedDelimiterTracker T(*this, tok::l_paren);
   1138     T.consumeOpen();
   1139     SourceLocation LParenLoc = T.getOpenLocation();
   1140 
   1141     // Parse parameter-declaration-clause.
   1142     ParsedAttributes Attr(AttrFactory);
   1143     SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
   1144     SourceLocation EllipsisLoc;
   1145 
   1146     if (Tok.isNot(tok::r_paren)) {
   1147       Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
   1148       ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
   1149       // For a generic lambda, each 'auto' within the parameter declaration
   1150       // clause creates a template type parameter, so increment the depth.
   1151       if (Actions.getCurGenericLambda())
   1152         ++CurTemplateDepthTracker;
   1153     }
   1154     T.consumeClose();
   1155     SourceLocation RParenLoc = T.getCloseLocation();
   1156     DeclEndLoc = RParenLoc;
   1157 
   1158     // GNU-style attributes must be parsed before the mutable specifier to be
   1159     // compatible with GCC.
   1160     MaybeParseGNUAttributes(Attr, &DeclEndLoc);
   1161 
   1162     // MSVC-style attributes must be parsed before the mutable specifier to be
   1163     // compatible with MSVC.
   1164     MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
   1165 
   1166     // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
   1167     SourceLocation MutableLoc;
   1168     SourceLocation ConstexprLoc;
   1169     tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
   1170                                       DeclEndLoc);
   1171 
   1172     addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
   1173 
   1174     // Parse exception-specification[opt].
   1175     ExceptionSpecificationType ESpecType = EST_None;
   1176     SourceRange ESpecRange;
   1177     SmallVector<ParsedType, 2> DynamicExceptions;
   1178     SmallVector<SourceRange, 2> DynamicExceptionRanges;
   1179     ExprResult NoexceptExpr;
   1180     CachedTokens *ExceptionSpecTokens;
   1181     ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
   1182                                                ESpecRange,
   1183                                                DynamicExceptions,
   1184                                                DynamicExceptionRanges,
   1185                                                NoexceptExpr,
   1186                                                ExceptionSpecTokens);
   1187 
   1188     if (ESpecType != EST_None)
   1189       DeclEndLoc = ESpecRange.getEnd();
   1190 
   1191     // Parse attribute-specifier[opt].
   1192     MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
   1193 
   1194     SourceLocation FunLocalRangeEnd = DeclEndLoc;
   1195 
   1196     // Parse trailing-return-type[opt].
   1197     if (Tok.is(tok::arrow)) {
   1198       FunLocalRangeEnd = Tok.getLocation();
   1199       SourceRange Range;
   1200       TrailingReturnType = ParseTrailingReturnType(Range);
   1201       if (Range.getEnd().isValid())
   1202         DeclEndLoc = Range.getEnd();
   1203     }
   1204 
   1205     PrototypeScope.Exit();
   1206 
   1207     SourceLocation NoLoc;
   1208     D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
   1209                                            /*isAmbiguous=*/false,
   1210                                            LParenLoc,
   1211                                            ParamInfo.data(), ParamInfo.size(),
   1212                                            EllipsisLoc, RParenLoc,
   1213                                            DS.getTypeQualifiers(),
   1214                                            /*RefQualifierIsLValueRef=*/true,
   1215                                            /*RefQualifierLoc=*/NoLoc,
   1216                                            /*ConstQualifierLoc=*/NoLoc,
   1217                                            /*VolatileQualifierLoc=*/NoLoc,
   1218                                            /*RestrictQualifierLoc=*/NoLoc,
   1219                                            MutableLoc,
   1220                                            ESpecType, ESpecRange,
   1221                                            DynamicExceptions.data(),
   1222                                            DynamicExceptionRanges.data(),
   1223                                            DynamicExceptions.size(),
   1224                                            NoexceptExpr.isUsable() ?
   1225                                              NoexceptExpr.get() : nullptr,
   1226                                            /*ExceptionSpecTokens*/nullptr,
   1227                                            LParenLoc, FunLocalRangeEnd, D,
   1228                                            TrailingReturnType),
   1229                   Attr, DeclEndLoc);
   1230   } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
   1231                          tok::kw_constexpr) ||
   1232              (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
   1233     // It's common to forget that one needs '()' before 'mutable', an attribute
   1234     // specifier, or the result type. Deal with this.
   1235     unsigned TokKind = 0;
   1236     switch (Tok.getKind()) {
   1237     case tok::kw_mutable: TokKind = 0; break;
   1238     case tok::arrow: TokKind = 1; break;
   1239     case tok::kw___attribute:
   1240     case tok::l_square: TokKind = 2; break;
   1241     case tok::kw_constexpr: TokKind = 3; break;
   1242     default: llvm_unreachable("Unknown token kind");
   1243     }
   1244 
   1245     Diag(Tok, diag::err_lambda_missing_parens)
   1246       << TokKind
   1247       << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
   1248     SourceLocation DeclLoc = Tok.getLocation();
   1249     SourceLocation DeclEndLoc = DeclLoc;
   1250 
   1251     // GNU-style attributes must be parsed before the mutable specifier to be
   1252     // compatible with GCC.
   1253     ParsedAttributes Attr(AttrFactory);
   1254     MaybeParseGNUAttributes(Attr, &DeclEndLoc);
   1255 
   1256     // Parse 'mutable', if it's there.
   1257     SourceLocation MutableLoc;
   1258     if (Tok.is(tok::kw_mutable)) {
   1259       MutableLoc = ConsumeToken();
   1260       DeclEndLoc = MutableLoc;
   1261     }
   1262 
   1263     // Parse attribute-specifier[opt].
   1264     MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
   1265 
   1266     // Parse the return type, if there is one.
   1267     if (Tok.is(tok::arrow)) {
   1268       SourceRange Range;
   1269       TrailingReturnType = ParseTrailingReturnType(Range);
   1270       if (Range.getEnd().isValid())
   1271         DeclEndLoc = Range.getEnd();
   1272     }
   1273 
   1274     SourceLocation NoLoc;
   1275     D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
   1276                                                /*isAmbiguous=*/false,
   1277                                                /*LParenLoc=*/NoLoc,
   1278                                                /*Params=*/nullptr,
   1279                                                /*NumParams=*/0,
   1280                                                /*EllipsisLoc=*/NoLoc,
   1281                                                /*RParenLoc=*/NoLoc,
   1282                                                /*TypeQuals=*/0,
   1283                                                /*RefQualifierIsLValueRef=*/true,
   1284                                                /*RefQualifierLoc=*/NoLoc,
   1285                                                /*ConstQualifierLoc=*/NoLoc,
   1286                                                /*VolatileQualifierLoc=*/NoLoc,
   1287                                                /*RestrictQualifierLoc=*/NoLoc,
   1288                                                MutableLoc,
   1289                                                EST_None,
   1290                                                /*ESpecRange=*/SourceRange(),
   1291                                                /*Exceptions=*/nullptr,
   1292                                                /*ExceptionRanges=*/nullptr,
   1293                                                /*NumExceptions=*/0,
   1294                                                /*NoexceptExpr=*/nullptr,
   1295                                                /*ExceptionSpecTokens=*/nullptr,
   1296                                                DeclLoc, DeclEndLoc, D,
   1297                                                TrailingReturnType),
   1298                   Attr, DeclEndLoc);
   1299   }
   1300 
   1301 
   1302   // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
   1303   // it.
   1304   unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
   1305   ParseScope BodyScope(this, ScopeFlags);
   1306 
   1307   Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
   1308 
   1309   // Parse compound-statement.
   1310   if (!Tok.is(tok::l_brace)) {
   1311     Diag(Tok, diag::err_expected_lambda_body);
   1312     Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
   1313     return ExprError();
   1314   }
   1315 
   1316   StmtResult Stmt(ParseCompoundStatementBody());
   1317   BodyScope.Exit();
   1318 
   1319   if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
   1320     return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
   1321 
   1322   Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
   1323   return ExprError();
   1324 }
   1325 
   1326 /// ParseCXXCasts - This handles the various ways to cast expressions to another
   1327 /// type.
   1328 ///
   1329 ///       postfix-expression: [C++ 5.2p1]
   1330 ///         'dynamic_cast' '<' type-name '>' '(' expression ')'
   1331 ///         'static_cast' '<' type-name '>' '(' expression ')'
   1332 ///         'reinterpret_cast' '<' type-name '>' '(' expression ')'
   1333 ///         'const_cast' '<' type-name '>' '(' expression ')'
   1334 ///
   1335 ExprResult Parser::ParseCXXCasts() {
   1336   tok::TokenKind Kind = Tok.getKind();
   1337   const char *CastName = nullptr; // For error messages
   1338 
   1339   switch (Kind) {
   1340   default: llvm_unreachable("Unknown C++ cast!");
   1341   case tok::kw_const_cast:       CastName = "const_cast";       break;
   1342   case tok::kw_dynamic_cast:     CastName = "dynamic_cast";     break;
   1343   case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
   1344   case tok::kw_static_cast:      CastName = "static_cast";      break;
   1345   }
   1346 
   1347   SourceLocation OpLoc = ConsumeToken();
   1348   SourceLocation LAngleBracketLoc = Tok.getLocation();
   1349 
   1350   // Check for "<::" which is parsed as "[:".  If found, fix token stream,
   1351   // diagnose error, suggest fix, and recover parsing.
   1352   if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
   1353     Token Next = NextToken();
   1354     if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
   1355       FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
   1356   }
   1357 
   1358   if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
   1359     return ExprError();
   1360 
   1361   // Parse the common declaration-specifiers piece.
   1362   DeclSpec DS(AttrFactory);
   1363   ParseSpecifierQualifierList(DS);
   1364 
   1365   // Parse the abstract-declarator, if present.
   1366   Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
   1367   ParseDeclarator(DeclaratorInfo);
   1368 
   1369   SourceLocation RAngleBracketLoc = Tok.getLocation();
   1370 
   1371   if (ExpectAndConsume(tok::greater))
   1372     return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
   1373 
   1374   SourceLocation LParenLoc, RParenLoc;
   1375   BalancedDelimiterTracker T(*this, tok::l_paren);
   1376 
   1377   if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
   1378     return ExprError();
   1379 
   1380   ExprResult Result = ParseExpression();
   1381 
   1382   // Match the ')'.
   1383   T.consumeClose();
   1384 
   1385   if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
   1386     Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
   1387                                        LAngleBracketLoc, DeclaratorInfo,
   1388                                        RAngleBracketLoc,
   1389                                        T.getOpenLocation(), Result.get(),
   1390                                        T.getCloseLocation());
   1391 
   1392   return Result;
   1393 }
   1394 
   1395 /// ParseCXXTypeid - This handles the C++ typeid expression.
   1396 ///
   1397 ///       postfix-expression: [C++ 5.2p1]
   1398 ///         'typeid' '(' expression ')'
   1399 ///         'typeid' '(' type-id ')'
   1400 ///
   1401 ExprResult Parser::ParseCXXTypeid() {
   1402   assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
   1403 
   1404   SourceLocation OpLoc = ConsumeToken();
   1405   SourceLocation LParenLoc, RParenLoc;
   1406   BalancedDelimiterTracker T(*this, tok::l_paren);
   1407 
   1408   // typeid expressions are always parenthesized.
   1409   if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
   1410     return ExprError();
   1411   LParenLoc = T.getOpenLocation();
   1412 
   1413   ExprResult Result;
   1414 
   1415   // C++0x [expr.typeid]p3:
   1416   //   When typeid is applied to an expression other than an lvalue of a
   1417   //   polymorphic class type [...] The expression is an unevaluated
   1418   //   operand (Clause 5).
   1419   //
   1420   // Note that we can't tell whether the expression is an lvalue of a
   1421   // polymorphic class type until after we've parsed the expression; we
   1422   // speculatively assume the subexpression is unevaluated, and fix it up
   1423   // later.
   1424   //
   1425   // We enter the unevaluated context before trying to determine whether we
   1426   // have a type-id, because the tentative parse logic will try to resolve
   1427   // names, and must treat them as unevaluated.
   1428   EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
   1429                                                Sema::ReuseLambdaContextDecl);
   1430 
   1431   if (isTypeIdInParens()) {
   1432     TypeResult Ty = ParseTypeName();
   1433 
   1434     // Match the ')'.
   1435     T.consumeClose();
   1436     RParenLoc = T.getCloseLocation();
   1437     if (Ty.isInvalid() || RParenLoc.isInvalid())
   1438       return ExprError();
   1439 
   1440     Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
   1441                                     Ty.get().getAsOpaquePtr(), RParenLoc);
   1442   } else {
   1443     Result = ParseExpression();
   1444 
   1445     // Match the ')'.
   1446     if (Result.isInvalid())
   1447       SkipUntil(tok::r_paren, StopAtSemi);
   1448     else {
   1449       T.consumeClose();
   1450       RParenLoc = T.getCloseLocation();
   1451       if (RParenLoc.isInvalid())
   1452         return ExprError();
   1453 
   1454       Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
   1455                                       Result.get(), RParenLoc);
   1456     }
   1457   }
   1458 
   1459   return Result;
   1460 }
   1461 
   1462 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
   1463 ///
   1464 ///         '__uuidof' '(' expression ')'
   1465 ///         '__uuidof' '(' type-id ')'
   1466 ///
   1467 ExprResult Parser::ParseCXXUuidof() {
   1468   assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
   1469 
   1470   SourceLocation OpLoc = ConsumeToken();
   1471   BalancedDelimiterTracker T(*this, tok::l_paren);
   1472 
   1473   // __uuidof expressions are always parenthesized.
   1474   if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
   1475     return ExprError();
   1476 
   1477   ExprResult Result;
   1478 
   1479   if (isTypeIdInParens()) {
   1480     TypeResult Ty = ParseTypeName();
   1481 
   1482     // Match the ')'.
   1483     T.consumeClose();
   1484 
   1485     if (Ty.isInvalid())
   1486       return ExprError();
   1487 
   1488     Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
   1489                                     Ty.get().getAsOpaquePtr(),
   1490                                     T.getCloseLocation());
   1491   } else {
   1492     EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
   1493     Result = ParseExpression();
   1494 
   1495     // Match the ')'.
   1496     if (Result.isInvalid())
   1497       SkipUntil(tok::r_paren, StopAtSemi);
   1498     else {
   1499       T.consumeClose();
   1500 
   1501       Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
   1502                                       /*isType=*/false,
   1503                                       Result.get(), T.getCloseLocation());
   1504     }
   1505   }
   1506 
   1507   return Result;
   1508 }
   1509 
   1510 /// \brief Parse a C++ pseudo-destructor expression after the base,
   1511 /// . or -> operator, and nested-name-specifier have already been
   1512 /// parsed.
   1513 ///
   1514 ///       postfix-expression: [C++ 5.2]
   1515 ///         postfix-expression . pseudo-destructor-name
   1516 ///         postfix-expression -> pseudo-destructor-name
   1517 ///
   1518 ///       pseudo-destructor-name:
   1519 ///         ::[opt] nested-name-specifier[opt] type-name :: ~type-name
   1520 ///         ::[opt] nested-name-specifier template simple-template-id ::
   1521 ///                 ~type-name
   1522 ///         ::[opt] nested-name-specifier[opt] ~type-name
   1523 ///
   1524 ExprResult
   1525 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
   1526                                  tok::TokenKind OpKind,
   1527                                  CXXScopeSpec &SS,
   1528                                  ParsedType ObjectType) {
   1529   // We're parsing either a pseudo-destructor-name or a dependent
   1530   // member access that has the same form as a
   1531   // pseudo-destructor-name. We parse both in the same way and let
   1532   // the action model sort them out.
   1533   //
   1534   // Note that the ::[opt] nested-name-specifier[opt] has already
   1535   // been parsed, and if there was a simple-template-id, it has
   1536   // been coalesced into a template-id annotation token.
   1537   UnqualifiedId FirstTypeName;
   1538   SourceLocation CCLoc;
   1539   if (Tok.is(tok::identifier)) {
   1540     FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
   1541     ConsumeToken();
   1542     assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
   1543     CCLoc = ConsumeToken();
   1544   } else if (Tok.is(tok::annot_template_id)) {
   1545     // FIXME: retrieve TemplateKWLoc from template-id annotation and
   1546     // store it in the pseudo-dtor node (to be used when instantiating it).
   1547     FirstTypeName.setTemplateId(
   1548                               (TemplateIdAnnotation *)Tok.getAnnotationValue());
   1549     ConsumeToken();
   1550     assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
   1551     CCLoc = ConsumeToken();
   1552   } else {
   1553     FirstTypeName.setIdentifier(nullptr, SourceLocation());
   1554   }
   1555 
   1556   // Parse the tilde.
   1557   assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
   1558   SourceLocation TildeLoc = ConsumeToken();
   1559 
   1560   if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
   1561     DeclSpec DS(AttrFactory);
   1562     ParseDecltypeSpecifier(DS);
   1563     if (DS.getTypeSpecType() == TST_error)
   1564       return ExprError();
   1565     return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
   1566                                              TildeLoc, DS);
   1567   }
   1568 
   1569   if (!Tok.is(tok::identifier)) {
   1570     Diag(Tok, diag::err_destructor_tilde_identifier);
   1571     return ExprError();
   1572   }
   1573 
   1574   // Parse the second type.
   1575   UnqualifiedId SecondTypeName;
   1576   IdentifierInfo *Name = Tok.getIdentifierInfo();
   1577   SourceLocation NameLoc = ConsumeToken();
   1578   SecondTypeName.setIdentifier(Name, NameLoc);
   1579 
   1580   // If there is a '<', the second type name is a template-id. Parse
   1581   // it as such.
   1582   if (Tok.is(tok::less) &&
   1583       ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
   1584                                    Name, NameLoc,
   1585                                    false, ObjectType, SecondTypeName,
   1586                                    /*AssumeTemplateName=*/true))
   1587     return ExprError();
   1588 
   1589   return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
   1590                                            SS, FirstTypeName, CCLoc, TildeLoc,
   1591                                            SecondTypeName);
   1592 }
   1593 
   1594 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
   1595 ///
   1596 ///       boolean-literal: [C++ 2.13.5]
   1597 ///         'true'
   1598 ///         'false'
   1599 ExprResult Parser::ParseCXXBoolLiteral() {
   1600   tok::TokenKind Kind = Tok.getKind();
   1601   return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
   1602 }
   1603 
   1604 /// ParseThrowExpression - This handles the C++ throw expression.
   1605 ///
   1606 ///       throw-expression: [C++ 15]
   1607 ///         'throw' assignment-expression[opt]
   1608 ExprResult Parser::ParseThrowExpression() {
   1609   assert(Tok.is(tok::kw_throw) && "Not throw!");
   1610   SourceLocation ThrowLoc = ConsumeToken();           // Eat the throw token.
   1611 
   1612   // If the current token isn't the start of an assignment-expression,
   1613   // then the expression is not present.  This handles things like:
   1614   //   "C ? throw : (void)42", which is crazy but legal.
   1615   switch (Tok.getKind()) {  // FIXME: move this predicate somewhere common.
   1616   case tok::semi:
   1617   case tok::r_paren:
   1618   case tok::r_square:
   1619   case tok::r_brace:
   1620   case tok::colon:
   1621   case tok::comma:
   1622     return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
   1623 
   1624   default:
   1625     ExprResult Expr(ParseAssignmentExpression());
   1626     if (Expr.isInvalid()) return Expr;
   1627     return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
   1628   }
   1629 }
   1630 
   1631 /// \brief Parse the C++ Coroutines co_yield expression.
   1632 ///
   1633 ///       co_yield-expression:
   1634 ///         'co_yield' assignment-expression[opt]
   1635 ExprResult Parser::ParseCoyieldExpression() {
   1636   assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
   1637 
   1638   SourceLocation Loc = ConsumeToken();
   1639   ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
   1640                                          : ParseAssignmentExpression();
   1641   if (!Expr.isInvalid())
   1642     Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
   1643   return Expr;
   1644 }
   1645 
   1646 /// ParseCXXThis - This handles the C++ 'this' pointer.
   1647 ///
   1648 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
   1649 /// a non-lvalue expression whose value is the address of the object for which
   1650 /// the function is called.
   1651 ExprResult Parser::ParseCXXThis() {
   1652   assert(Tok.is(tok::kw_this) && "Not 'this'!");
   1653   SourceLocation ThisLoc = ConsumeToken();
   1654   return Actions.ActOnCXXThis(ThisLoc);
   1655 }
   1656 
   1657 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
   1658 /// Can be interpreted either as function-style casting ("int(x)")
   1659 /// or class type construction ("ClassType(x,y,z)")
   1660 /// or creation of a value-initialized type ("int()").
   1661 /// See [C++ 5.2.3].
   1662 ///
   1663 ///       postfix-expression: [C++ 5.2p1]
   1664 ///         simple-type-specifier '(' expression-list[opt] ')'
   1665 /// [C++0x] simple-type-specifier braced-init-list
   1666 ///         typename-specifier '(' expression-list[opt] ')'
   1667 /// [C++0x] typename-specifier braced-init-list
   1668 ///
   1669 ExprResult
   1670 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
   1671   Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
   1672   ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
   1673 
   1674   assert((Tok.is(tok::l_paren) ||
   1675           (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
   1676          && "Expected '(' or '{'!");
   1677 
   1678   if (Tok.is(tok::l_brace)) {
   1679     ExprResult Init = ParseBraceInitializer();
   1680     if (Init.isInvalid())
   1681       return Init;
   1682     Expr *InitList = Init.get();
   1683     return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
   1684                                              MultiExprArg(&InitList, 1),
   1685                                              SourceLocation());
   1686   } else {
   1687     BalancedDelimiterTracker T(*this, tok::l_paren);
   1688     T.consumeOpen();
   1689 
   1690     ExprVector Exprs;
   1691     CommaLocsTy CommaLocs;
   1692 
   1693     if (Tok.isNot(tok::r_paren)) {
   1694       if (ParseExpressionList(Exprs, CommaLocs, [&] {
   1695             Actions.CodeCompleteConstructor(getCurScope(),
   1696                                       TypeRep.get()->getCanonicalTypeInternal(),
   1697                                             DS.getLocEnd(), Exprs);
   1698          })) {
   1699         SkipUntil(tok::r_paren, StopAtSemi);
   1700         return ExprError();
   1701       }
   1702     }
   1703 
   1704     // Match the ')'.
   1705     T.consumeClose();
   1706 
   1707     // TypeRep could be null, if it references an invalid typedef.
   1708     if (!TypeRep)
   1709       return ExprError();
   1710 
   1711     assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
   1712            "Unexpected number of commas!");
   1713     return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
   1714                                              Exprs,
   1715                                              T.getCloseLocation());
   1716   }
   1717 }
   1718 
   1719 /// ParseCXXCondition - if/switch/while condition expression.
   1720 ///
   1721 ///       condition:
   1722 ///         expression
   1723 ///         type-specifier-seq declarator '=' assignment-expression
   1724 /// [C++11] type-specifier-seq declarator '=' initializer-clause
   1725 /// [C++11] type-specifier-seq declarator braced-init-list
   1726 /// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
   1727 ///             '=' assignment-expression
   1728 ///
   1729 /// In C++1z, a condition may in some contexts be preceded by an
   1730 /// optional init-statement. This function will parse that too.
   1731 ///
   1732 /// \param InitStmt If non-null, an init-statement is permitted, and if present
   1733 /// will be parsed and stored here.
   1734 ///
   1735 /// \param Loc The location of the start of the statement that requires this
   1736 /// condition, e.g., the "for" in a for loop.
   1737 ///
   1738 /// \returns The parsed condition.
   1739 Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
   1740                                                 SourceLocation Loc,
   1741                                                 Sema::ConditionKind CK) {
   1742   if (Tok.is(tok::code_completion)) {
   1743     Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
   1744     cutOffParsing();
   1745     return Sema::ConditionError();
   1746   }
   1747 
   1748   ParsedAttributesWithRange attrs(AttrFactory);
   1749   MaybeParseCXX11Attributes(attrs);
   1750 
   1751   // Determine what kind of thing we have.
   1752   switch (isCXXConditionDeclarationOrInitStatement(InitStmt)) {
   1753   case ConditionOrInitStatement::Expression: {
   1754     ProhibitAttributes(attrs);
   1755 
   1756     // Parse the expression.
   1757     ExprResult Expr = ParseExpression(); // expression
   1758     if (Expr.isInvalid())
   1759       return Sema::ConditionError();
   1760 
   1761     if (InitStmt && Tok.is(tok::semi)) {
   1762       *InitStmt = Actions.ActOnExprStmt(Expr.get());
   1763       ConsumeToken();
   1764       return ParseCXXCondition(nullptr, Loc, CK);
   1765     }
   1766 
   1767     return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
   1768   }
   1769 
   1770   case ConditionOrInitStatement::InitStmtDecl: {
   1771     SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
   1772     DeclGroupPtrTy DG = ParseSimpleDeclaration(
   1773         Declarator::InitStmtContext, DeclEnd, attrs, /*RequireSemi=*/true);
   1774     *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
   1775     return ParseCXXCondition(nullptr, Loc, CK);
   1776   }
   1777 
   1778   case ConditionOrInitStatement::ConditionDecl:
   1779   case ConditionOrInitStatement::Error:
   1780     break;
   1781   }
   1782 
   1783   // type-specifier-seq
   1784   DeclSpec DS(AttrFactory);
   1785   DS.takeAttributesFrom(attrs);
   1786   ParseSpecifierQualifierList(DS, AS_none, DSC_condition);
   1787 
   1788   // declarator
   1789   Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
   1790   ParseDeclarator(DeclaratorInfo);
   1791 
   1792   // simple-asm-expr[opt]
   1793   if (Tok.is(tok::kw_asm)) {
   1794     SourceLocation Loc;
   1795     ExprResult AsmLabel(ParseSimpleAsm(&Loc));
   1796     if (AsmLabel.isInvalid()) {
   1797       SkipUntil(tok::semi, StopAtSemi);
   1798       return Sema::ConditionError();
   1799     }
   1800     DeclaratorInfo.setAsmLabel(AsmLabel.get());
   1801     DeclaratorInfo.SetRangeEnd(Loc);
   1802   }
   1803 
   1804   // If attributes are present, parse them.
   1805   MaybeParseGNUAttributes(DeclaratorInfo);
   1806 
   1807   // Type-check the declaration itself.
   1808   DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
   1809                                                         DeclaratorInfo);
   1810   if (Dcl.isInvalid())
   1811     return Sema::ConditionError();
   1812   Decl *DeclOut = Dcl.get();
   1813 
   1814   // '=' assignment-expression
   1815   // If a '==' or '+=' is found, suggest a fixit to '='.
   1816   bool CopyInitialization = isTokenEqualOrEqualTypo();
   1817   if (CopyInitialization)
   1818     ConsumeToken();
   1819 
   1820   ExprResult InitExpr = ExprError();
   1821   if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
   1822     Diag(Tok.getLocation(),
   1823          diag::warn_cxx98_compat_generalized_initializer_lists);
   1824     InitExpr = ParseBraceInitializer();
   1825   } else if (CopyInitialization) {
   1826     InitExpr = ParseAssignmentExpression();
   1827   } else if (Tok.is(tok::l_paren)) {
   1828     // This was probably an attempt to initialize the variable.
   1829     SourceLocation LParen = ConsumeParen(), RParen = LParen;
   1830     if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
   1831       RParen = ConsumeParen();
   1832     Diag(DeclOut->getLocation(),
   1833          diag::err_expected_init_in_condition_lparen)
   1834       << SourceRange(LParen, RParen);
   1835   } else {
   1836     Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
   1837   }
   1838 
   1839   if (!InitExpr.isInvalid())
   1840     Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization,
   1841                                  DS.containsPlaceholderType());
   1842   else
   1843     Actions.ActOnInitializerError(DeclOut);
   1844 
   1845   Actions.FinalizeDeclaration(DeclOut);
   1846   return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
   1847 }
   1848 
   1849 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
   1850 /// This should only be called when the current token is known to be part of
   1851 /// simple-type-specifier.
   1852 ///
   1853 ///       simple-type-specifier:
   1854 ///         '::'[opt] nested-name-specifier[opt] type-name
   1855 ///         '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
   1856 ///         char
   1857 ///         wchar_t
   1858 ///         bool
   1859 ///         short
   1860 ///         int
   1861 ///         long
   1862 ///         signed
   1863 ///         unsigned
   1864 ///         float
   1865 ///         double
   1866 ///         void
   1867 /// [GNU]   typeof-specifier
   1868 /// [C++0x] auto               [TODO]
   1869 ///
   1870 ///       type-name:
   1871 ///         class-name
   1872 ///         enum-name
   1873 ///         typedef-name
   1874 ///
   1875 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
   1876   DS.SetRangeStart(Tok.getLocation());
   1877   const char *PrevSpec;
   1878   unsigned DiagID;
   1879   SourceLocation Loc = Tok.getLocation();
   1880   const clang::PrintingPolicy &Policy =
   1881       Actions.getASTContext().getPrintingPolicy();
   1882 
   1883   switch (Tok.getKind()) {
   1884   case tok::identifier:   // foo::bar
   1885   case tok::coloncolon:   // ::foo::bar
   1886     llvm_unreachable("Annotation token should already be formed!");
   1887   default:
   1888     llvm_unreachable("Not a simple-type-specifier token!");
   1889 
   1890   // type-name
   1891   case tok::annot_typename: {
   1892     if (getTypeAnnotation(Tok))
   1893       DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
   1894                          getTypeAnnotation(Tok), Policy);
   1895     else
   1896       DS.SetTypeSpecError();
   1897 
   1898     DS.SetRangeEnd(Tok.getAnnotationEndLoc());
   1899     ConsumeToken();
   1900 
   1901     DS.Finish(Actions, Policy);
   1902     return;
   1903   }
   1904 
   1905   // builtin types
   1906   case tok::kw_short:
   1907     DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
   1908     break;
   1909   case tok::kw_long:
   1910     DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
   1911     break;
   1912   case tok::kw___int64:
   1913     DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
   1914     break;
   1915   case tok::kw_signed:
   1916     DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
   1917     break;
   1918   case tok::kw_unsigned:
   1919     DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
   1920     break;
   1921   case tok::kw_void:
   1922     DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
   1923     break;
   1924   case tok::kw_char:
   1925     DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
   1926     break;
   1927   case tok::kw_int:
   1928     DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
   1929     break;
   1930   case tok::kw___int128:
   1931     DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
   1932     break;
   1933   case tok::kw_half:
   1934     DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
   1935     break;
   1936   case tok::kw_float:
   1937     DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
   1938     break;
   1939   case tok::kw_double:
   1940     DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
   1941     break;
   1942   case tok::kw___float128:
   1943     DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
   1944     break;
   1945   case tok::kw_wchar_t:
   1946     DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
   1947     break;
   1948   case tok::kw_char16_t:
   1949     DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
   1950     break;
   1951   case tok::kw_char32_t:
   1952     DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
   1953     break;
   1954   case tok::kw_bool:
   1955     DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
   1956     break;
   1957   case tok::annot_decltype:
   1958   case tok::kw_decltype:
   1959     DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
   1960     return DS.Finish(Actions, Policy);
   1961 
   1962   // GNU typeof support.
   1963   case tok::kw_typeof:
   1964     ParseTypeofSpecifier(DS);
   1965     DS.Finish(Actions, Policy);
   1966     return;
   1967   }
   1968   if (Tok.is(tok::annot_typename))
   1969     DS.SetRangeEnd(Tok.getAnnotationEndLoc());
   1970   else
   1971     DS.SetRangeEnd(Tok.getLocation());
   1972   ConsumeToken();
   1973   DS.Finish(Actions, Policy);
   1974 }
   1975 
   1976 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
   1977 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
   1978 /// e.g., "const short int". Note that the DeclSpec is *not* finished
   1979 /// by parsing the type-specifier-seq, because these sequences are
   1980 /// typically followed by some form of declarator. Returns true and
   1981 /// emits diagnostics if this is not a type-specifier-seq, false
   1982 /// otherwise.
   1983 ///
   1984 ///   type-specifier-seq: [C++ 8.1]
   1985 ///     type-specifier type-specifier-seq[opt]
   1986 ///
   1987 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
   1988   ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
   1989   DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
   1990   return false;
   1991 }
   1992 
   1993 /// \brief Finish parsing a C++ unqualified-id that is a template-id of
   1994 /// some form.
   1995 ///
   1996 /// This routine is invoked when a '<' is encountered after an identifier or
   1997 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
   1998 /// whether the unqualified-id is actually a template-id. This routine will
   1999 /// then parse the template arguments and form the appropriate template-id to
   2000 /// return to the caller.
   2001 ///
   2002 /// \param SS the nested-name-specifier that precedes this template-id, if
   2003 /// we're actually parsing a qualified-id.
   2004 ///
   2005 /// \param Name for constructor and destructor names, this is the actual
   2006 /// identifier that may be a template-name.
   2007 ///
   2008 /// \param NameLoc the location of the class-name in a constructor or
   2009 /// destructor.
   2010 ///
   2011 /// \param EnteringContext whether we're entering the scope of the
   2012 /// nested-name-specifier.
   2013 ///
   2014 /// \param ObjectType if this unqualified-id occurs within a member access
   2015 /// expression, the type of the base object whose member is being accessed.
   2016 ///
   2017 /// \param Id as input, describes the template-name or operator-function-id
   2018 /// that precedes the '<'. If template arguments were parsed successfully,
   2019 /// will be updated with the template-id.
   2020 ///
   2021 /// \param AssumeTemplateId When true, this routine will assume that the name
   2022 /// refers to a template without performing name lookup to verify.
   2023 ///
   2024 /// \returns true if a parse error occurred, false otherwise.
   2025 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
   2026                                           SourceLocation TemplateKWLoc,
   2027                                           IdentifierInfo *Name,
   2028                                           SourceLocation NameLoc,
   2029                                           bool EnteringContext,
   2030                                           ParsedType ObjectType,
   2031                                           UnqualifiedId &Id,
   2032                                           bool AssumeTemplateId) {
   2033   assert((AssumeTemplateId || Tok.is(tok::less)) &&
   2034          "Expected '<' to finish parsing a template-id");
   2035 
   2036   TemplateTy Template;
   2037   TemplateNameKind TNK = TNK_Non_template;
   2038   switch (Id.getKind()) {
   2039   case UnqualifiedId::IK_Identifier:
   2040   case UnqualifiedId::IK_OperatorFunctionId:
   2041   case UnqualifiedId::IK_LiteralOperatorId:
   2042     if (AssumeTemplateId) {
   2043       TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
   2044                                                Id, ObjectType, EnteringContext,
   2045                                                Template);
   2046       if (TNK == TNK_Non_template)
   2047         return true;
   2048     } else {
   2049       bool MemberOfUnknownSpecialization;
   2050       TNK = Actions.isTemplateName(getCurScope(), SS,
   2051                                    TemplateKWLoc.isValid(), Id,
   2052                                    ObjectType, EnteringContext, Template,
   2053                                    MemberOfUnknownSpecialization);
   2054 
   2055       if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
   2056           ObjectType && IsTemplateArgumentList()) {
   2057         // We have something like t->getAs<T>(), where getAs is a
   2058         // member of an unknown specialization. However, this will only
   2059         // parse correctly as a template, so suggest the keyword 'template'
   2060         // before 'getAs' and treat this as a dependent template name.
   2061         std::string Name;
   2062         if (Id.getKind() == UnqualifiedId::IK_Identifier)
   2063           Name = Id.Identifier->getName();
   2064         else {
   2065           Name = "operator ";
   2066           if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
   2067             Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
   2068           else
   2069             Name += Id.Identifier->getName();
   2070         }
   2071         Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
   2072           << Name
   2073           << FixItHint::CreateInsertion(Id.StartLocation, "template ");
   2074         TNK = Actions.ActOnDependentTemplateName(getCurScope(),
   2075                                                  SS, TemplateKWLoc, Id,
   2076                                                  ObjectType, EnteringContext,
   2077                                                  Template);
   2078         if (TNK == TNK_Non_template)
   2079           return true;
   2080       }
   2081     }
   2082     break;
   2083 
   2084   case UnqualifiedId::IK_ConstructorName: {
   2085     UnqualifiedId TemplateName;
   2086     bool MemberOfUnknownSpecialization;
   2087     TemplateName.setIdentifier(Name, NameLoc);
   2088     TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
   2089                                  TemplateName, ObjectType,
   2090                                  EnteringContext, Template,
   2091                                  MemberOfUnknownSpecialization);
   2092     break;
   2093   }
   2094 
   2095   case UnqualifiedId::IK_DestructorName: {
   2096     UnqualifiedId TemplateName;
   2097     bool MemberOfUnknownSpecialization;
   2098     TemplateName.setIdentifier(Name, NameLoc);
   2099     if (ObjectType) {
   2100       TNK = Actions.ActOnDependentTemplateName(getCurScope(),
   2101                                                SS, TemplateKWLoc, TemplateName,
   2102                                                ObjectType, EnteringContext,
   2103                                                Template);
   2104       if (TNK == TNK_Non_template)
   2105         return true;
   2106     } else {
   2107       TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
   2108                                    TemplateName, ObjectType,
   2109                                    EnteringContext, Template,
   2110                                    MemberOfUnknownSpecialization);
   2111 
   2112       if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
   2113         Diag(NameLoc, diag::err_destructor_template_id)
   2114           << Name << SS.getRange();
   2115         return true;
   2116       }
   2117     }
   2118     break;
   2119   }
   2120 
   2121   default:
   2122     return false;
   2123   }
   2124 
   2125   if (TNK == TNK_Non_template)
   2126     return false;
   2127 
   2128   // Parse the enclosed template argument list.
   2129   SourceLocation LAngleLoc, RAngleLoc;
   2130   TemplateArgList TemplateArgs;
   2131   if (Tok.is(tok::less) &&
   2132       ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
   2133                                        SS, true, LAngleLoc,
   2134                                        TemplateArgs,
   2135                                        RAngleLoc))
   2136     return true;
   2137 
   2138   if (Id.getKind() == UnqualifiedId::IK_Identifier ||
   2139       Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
   2140       Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
   2141     // Form a parsed representation of the template-id to be stored in the
   2142     // UnqualifiedId.
   2143     TemplateIdAnnotation *TemplateId
   2144       = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
   2145 
   2146     // FIXME: Store name for literal operator too.
   2147     if (Id.getKind() == UnqualifiedId::IK_Identifier) {
   2148       TemplateId->Name = Id.Identifier;
   2149       TemplateId->Operator = OO_None;
   2150       TemplateId->TemplateNameLoc = Id.StartLocation;
   2151     } else {
   2152       TemplateId->Name = nullptr;
   2153       TemplateId->Operator = Id.OperatorFunctionId.Operator;
   2154       TemplateId->TemplateNameLoc = Id.StartLocation;
   2155     }
   2156 
   2157     TemplateId->SS = SS;
   2158     TemplateId->TemplateKWLoc = TemplateKWLoc;
   2159     TemplateId->Template = Template;
   2160     TemplateId->Kind = TNK;
   2161     TemplateId->LAngleLoc = LAngleLoc;
   2162     TemplateId->RAngleLoc = RAngleLoc;
   2163     ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
   2164     for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
   2165          Arg != ArgEnd; ++Arg)
   2166       Args[Arg] = TemplateArgs[Arg];
   2167 
   2168     Id.setTemplateId(TemplateId);
   2169     return false;
   2170   }
   2171 
   2172   // Bundle the template arguments together.
   2173   ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
   2174 
   2175   // Constructor and destructor names.
   2176   TypeResult Type
   2177     = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
   2178                                   Template, NameLoc,
   2179                                   LAngleLoc, TemplateArgsPtr, RAngleLoc,
   2180                                   /*IsCtorOrDtorName=*/true);
   2181   if (Type.isInvalid())
   2182     return true;
   2183 
   2184   if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
   2185     Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
   2186   else
   2187     Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
   2188 
   2189   return false;
   2190 }
   2191 
   2192 /// \brief Parse an operator-function-id or conversion-function-id as part
   2193 /// of a C++ unqualified-id.
   2194 ///
   2195 /// This routine is responsible only for parsing the operator-function-id or
   2196 /// conversion-function-id; it does not handle template arguments in any way.
   2197 ///
   2198 /// \code
   2199 ///       operator-function-id: [C++ 13.5]
   2200 ///         'operator' operator
   2201 ///
   2202 ///       operator: one of
   2203 ///            new   delete  new[]   delete[]
   2204 ///            +     -    *  /    %  ^    &   |   ~
   2205 ///            !     =    <  >    += -=   *=  /=  %=
   2206 ///            ^=    &=   |= <<   >> >>= <<=  ==  !=
   2207 ///            <=    >=   && ||   ++ --   ,   ->* ->
   2208 ///            ()    []
   2209 ///
   2210 ///       conversion-function-id: [C++ 12.3.2]
   2211 ///         operator conversion-type-id
   2212 ///
   2213 ///       conversion-type-id:
   2214 ///         type-specifier-seq conversion-declarator[opt]
   2215 ///
   2216 ///       conversion-declarator:
   2217 ///         ptr-operator conversion-declarator[opt]
   2218 /// \endcode
   2219 ///
   2220 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
   2221 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
   2222 ///
   2223 /// \param EnteringContext whether we are entering the scope of the
   2224 /// nested-name-specifier.
   2225 ///
   2226 /// \param ObjectType if this unqualified-id occurs within a member access
   2227 /// expression, the type of the base object whose member is being accessed.
   2228 ///
   2229 /// \param Result on a successful parse, contains the parsed unqualified-id.
   2230 ///
   2231 /// \returns true if parsing fails, false otherwise.
   2232 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
   2233                                         ParsedType ObjectType,
   2234                                         UnqualifiedId &Result) {
   2235   assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
   2236 
   2237   // Consume the 'operator' keyword.
   2238   SourceLocation KeywordLoc = ConsumeToken();
   2239 
   2240   // Determine what kind of operator name we have.
   2241   unsigned SymbolIdx = 0;
   2242   SourceLocation SymbolLocations[3];
   2243   OverloadedOperatorKind Op = OO_None;
   2244   switch (Tok.getKind()) {
   2245     case tok::kw_new:
   2246     case tok::kw_delete: {
   2247       bool isNew = Tok.getKind() == tok::kw_new;
   2248       // Consume the 'new' or 'delete'.
   2249       SymbolLocations[SymbolIdx++] = ConsumeToken();
   2250       // Check for array new/delete.
   2251       if (Tok.is(tok::l_square) &&
   2252           (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
   2253         // Consume the '[' and ']'.
   2254         BalancedDelimiterTracker T(*this, tok::l_square);
   2255         T.consumeOpen();
   2256         T.consumeClose();
   2257         if (T.getCloseLocation().isInvalid())
   2258           return true;
   2259 
   2260         SymbolLocations[SymbolIdx++] = T.getOpenLocation();
   2261         SymbolLocations[SymbolIdx++] = T.getCloseLocation();
   2262         Op = isNew? OO_Array_New : OO_Array_Delete;
   2263       } else {
   2264         Op = isNew? OO_New : OO_Delete;
   2265       }
   2266       break;
   2267     }
   2268 
   2269 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
   2270     case tok::Token:                                                     \
   2271       SymbolLocations[SymbolIdx++] = ConsumeToken();                     \
   2272       Op = OO_##Name;                                                    \
   2273       break;
   2274 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
   2275 #include "clang/Basic/OperatorKinds.def"
   2276 
   2277     case tok::l_paren: {
   2278       // Consume the '(' and ')'.
   2279       BalancedDelimiterTracker T(*this, tok::l_paren);
   2280       T.consumeOpen();
   2281       T.consumeClose();
   2282       if (T.getCloseLocation().isInvalid())
   2283         return true;
   2284 
   2285       SymbolLocations[SymbolIdx++] = T.getOpenLocation();
   2286       SymbolLocations[SymbolIdx++] = T.getCloseLocation();
   2287       Op = OO_Call;
   2288       break;
   2289     }
   2290 
   2291     case tok::l_square: {
   2292       // Consume the '[' and ']'.
   2293       BalancedDelimiterTracker T(*this, tok::l_square);
   2294       T.consumeOpen();
   2295       T.consumeClose();
   2296       if (T.getCloseLocation().isInvalid())
   2297         return true;
   2298 
   2299       SymbolLocations[SymbolIdx++] = T.getOpenLocation();
   2300       SymbolLocations[SymbolIdx++] = T.getCloseLocation();
   2301       Op = OO_Subscript;
   2302       break;
   2303     }
   2304 
   2305     case tok::code_completion: {
   2306       // Code completion for the operator name.
   2307       Actions.CodeCompleteOperatorName(getCurScope());
   2308       cutOffParsing();
   2309       // Don't try to parse any further.
   2310       return true;
   2311     }
   2312 
   2313     default:
   2314       break;
   2315   }
   2316 
   2317   if (Op != OO_None) {
   2318     // We have parsed an operator-function-id.
   2319     Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
   2320     return false;
   2321   }
   2322 
   2323   // Parse a literal-operator-id.
   2324   //
   2325   //   literal-operator-id: C++11 [over.literal]
   2326   //     operator string-literal identifier
   2327   //     operator user-defined-string-literal
   2328 
   2329   if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
   2330     Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
   2331 
   2332     SourceLocation DiagLoc;
   2333     unsigned DiagId = 0;
   2334 
   2335     // We're past translation phase 6, so perform string literal concatenation
   2336     // before checking for "".
   2337     SmallVector<Token, 4> Toks;
   2338     SmallVector<SourceLocation, 4> TokLocs;
   2339     while (isTokenStringLiteral()) {
   2340       if (!Tok.is(tok::string_literal) && !DiagId) {
   2341         // C++11 [over.literal]p1:
   2342         //   The string-literal or user-defined-string-literal in a
   2343         //   literal-operator-id shall have no encoding-prefix [...].
   2344         DiagLoc = Tok.getLocation();
   2345         DiagId = diag::err_literal_operator_string_prefix;
   2346       }
   2347       Toks.push_back(Tok);
   2348       TokLocs.push_back(ConsumeStringToken());
   2349     }
   2350 
   2351     StringLiteralParser Literal(Toks, PP);
   2352     if (Literal.hadError)
   2353       return true;
   2354 
   2355     // Grab the literal operator's suffix, which will be either the next token
   2356     // or a ud-suffix from the string literal.
   2357     IdentifierInfo *II = nullptr;
   2358     SourceLocation SuffixLoc;
   2359     if (!Literal.getUDSuffix().empty()) {
   2360       II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
   2361       SuffixLoc =
   2362         Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
   2363                                        Literal.getUDSuffixOffset(),
   2364                                        PP.getSourceManager(), getLangOpts());
   2365     } else if (Tok.is(tok::identifier)) {
   2366       II = Tok.getIdentifierInfo();
   2367       SuffixLoc = ConsumeToken();
   2368       TokLocs.push_back(SuffixLoc);
   2369     } else {
   2370       Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
   2371       return true;
   2372     }
   2373 
   2374     // The string literal must be empty.
   2375     if (!Literal.GetString().empty() || Literal.Pascal) {
   2376       // C++11 [over.literal]p1:
   2377       //   The string-literal or user-defined-string-literal in a
   2378       //   literal-operator-id shall [...] contain no characters
   2379       //   other than the implicit terminating '\0'.
   2380       DiagLoc = TokLocs.front();
   2381       DiagId = diag::err_literal_operator_string_not_empty;
   2382     }
   2383 
   2384     if (DiagId) {
   2385       // This isn't a valid literal-operator-id, but we think we know
   2386       // what the user meant. Tell them what they should have written.
   2387       SmallString<32> Str;
   2388       Str += "\"\"";
   2389       Str += II->getName();
   2390       Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
   2391           SourceRange(TokLocs.front(), TokLocs.back()), Str);
   2392     }
   2393 
   2394     Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
   2395 
   2396     return Actions.checkLiteralOperatorId(SS, Result);
   2397   }
   2398 
   2399   // Parse a conversion-function-id.
   2400   //
   2401   //   conversion-function-id: [C++ 12.3.2]
   2402   //     operator conversion-type-id
   2403   //
   2404   //   conversion-type-id:
   2405   //     type-specifier-seq conversion-declarator[opt]
   2406   //
   2407   //   conversion-declarator:
   2408   //     ptr-operator conversion-declarator[opt]
   2409 
   2410   // Parse the type-specifier-seq.
   2411   DeclSpec DS(AttrFactory);
   2412   if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
   2413     return true;
   2414 
   2415   // Parse the conversion-declarator, which is merely a sequence of
   2416   // ptr-operators.
   2417   Declarator D(DS, Declarator::ConversionIdContext);
   2418   ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
   2419 
   2420   // Finish up the type.
   2421   TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
   2422   if (Ty.isInvalid())
   2423     return true;
   2424 
   2425   // Note that this is a conversion-function-id.
   2426   Result.setConversionFunctionId(KeywordLoc, Ty.get(),
   2427                                  D.getSourceRange().getEnd());
   2428   return false;
   2429 }
   2430 
   2431 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
   2432 /// name of an entity.
   2433 ///
   2434 /// \code
   2435 ///       unqualified-id: [C++ expr.prim.general]
   2436 ///         identifier
   2437 ///         operator-function-id
   2438 ///         conversion-function-id
   2439 /// [C++0x] literal-operator-id [TODO]
   2440 ///         ~ class-name
   2441 ///         template-id
   2442 ///
   2443 /// \endcode
   2444 ///
   2445 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
   2446 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
   2447 ///
   2448 /// \param EnteringContext whether we are entering the scope of the
   2449 /// nested-name-specifier.
   2450 ///
   2451 /// \param AllowDestructorName whether we allow parsing of a destructor name.
   2452 ///
   2453 /// \param AllowConstructorName whether we allow parsing a constructor name.
   2454 ///
   2455 /// \param ObjectType if this unqualified-id occurs within a member access
   2456 /// expression, the type of the base object whose member is being accessed.
   2457 ///
   2458 /// \param Result on a successful parse, contains the parsed unqualified-id.
   2459 ///
   2460 /// \returns true if parsing fails, false otherwise.
   2461 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
   2462                                 bool AllowDestructorName,
   2463                                 bool AllowConstructorName,
   2464                                 ParsedType ObjectType,
   2465                                 SourceLocation& TemplateKWLoc,
   2466                                 UnqualifiedId &Result) {
   2467 
   2468   // Handle 'A::template B'. This is for template-ids which have not
   2469   // already been annotated by ParseOptionalCXXScopeSpecifier().
   2470   bool TemplateSpecified = false;
   2471   if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
   2472       (ObjectType || SS.isSet())) {
   2473     TemplateSpecified = true;
   2474     TemplateKWLoc = ConsumeToken();
   2475   }
   2476 
   2477   // unqualified-id:
   2478   //   identifier
   2479   //   template-id (when it hasn't already been annotated)
   2480   if (Tok.is(tok::identifier)) {
   2481     // Consume the identifier.
   2482     IdentifierInfo *Id = Tok.getIdentifierInfo();
   2483     SourceLocation IdLoc = ConsumeToken();
   2484 
   2485     if (!getLangOpts().CPlusPlus) {
   2486       // If we're not in C++, only identifiers matter. Record the
   2487       // identifier and return.
   2488       Result.setIdentifier(Id, IdLoc);
   2489       return false;
   2490     }
   2491 
   2492     if (AllowConstructorName &&
   2493         Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
   2494       // We have parsed a constructor name.
   2495       ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, false,
   2496                                           false, nullptr,
   2497                                           /*IsCtorOrDtorName=*/true,
   2498                                           /*NonTrivialTypeSourceInfo=*/true);
   2499       Result.setConstructorName(Ty, IdLoc, IdLoc);
   2500     } else {
   2501       // We have parsed an identifier.
   2502       Result.setIdentifier(Id, IdLoc);
   2503     }
   2504 
   2505     // If the next token is a '<', we may have a template.
   2506     if (TemplateSpecified || Tok.is(tok::less))
   2507       return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
   2508                                           EnteringContext, ObjectType,
   2509                                           Result, TemplateSpecified);
   2510 
   2511     return false;
   2512   }
   2513 
   2514   // unqualified-id:
   2515   //   template-id (already parsed and annotated)
   2516   if (Tok.is(tok::annot_template_id)) {
   2517     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
   2518 
   2519     // If the template-name names the current class, then this is a constructor
   2520     if (AllowConstructorName && TemplateId->Name &&
   2521         Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
   2522       if (SS.isSet()) {
   2523         // C++ [class.qual]p2 specifies that a qualified template-name
   2524         // is taken as the constructor name where a constructor can be
   2525         // declared. Thus, the template arguments are extraneous, so
   2526         // complain about them and remove them entirely.
   2527         Diag(TemplateId->TemplateNameLoc,
   2528              diag::err_out_of_line_constructor_template_id)
   2529           << TemplateId->Name
   2530           << FixItHint::CreateRemoval(
   2531                     SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
   2532         ParsedType Ty =
   2533             Actions.getTypeName(*TemplateId->Name, TemplateId->TemplateNameLoc,
   2534                                 getCurScope(), &SS, false, false, nullptr,
   2535                                 /*IsCtorOrDtorName=*/true,
   2536                                 /*NontrivialTypeSourceInfo=*/true);
   2537         Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
   2538                                   TemplateId->RAngleLoc);
   2539         ConsumeToken();
   2540         return false;
   2541       }
   2542 
   2543       Result.setConstructorTemplateId(TemplateId);
   2544       ConsumeToken();
   2545       return false;
   2546     }
   2547 
   2548     // We have already parsed a template-id; consume the annotation token as
   2549     // our unqualified-id.
   2550     Result.setTemplateId(TemplateId);
   2551     TemplateKWLoc = TemplateId->TemplateKWLoc;
   2552     ConsumeToken();
   2553     return false;
   2554   }
   2555 
   2556   // unqualified-id:
   2557   //   operator-function-id
   2558   //   conversion-function-id
   2559   if (Tok.is(tok::kw_operator)) {
   2560     if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
   2561       return true;
   2562 
   2563     // If we have an operator-function-id or a literal-operator-id and the next
   2564     // token is a '<', we may have a
   2565     //
   2566     //   template-id:
   2567     //     operator-function-id < template-argument-list[opt] >
   2568     if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
   2569          Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
   2570         (TemplateSpecified || Tok.is(tok::less)))
   2571       return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
   2572                                           nullptr, SourceLocation(),
   2573                                           EnteringContext, ObjectType,
   2574                                           Result, TemplateSpecified);
   2575 
   2576     return false;
   2577   }
   2578 
   2579   if (getLangOpts().CPlusPlus &&
   2580       (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
   2581     // C++ [expr.unary.op]p10:
   2582     //   There is an ambiguity in the unary-expression ~X(), where X is a
   2583     //   class-name. The ambiguity is resolved in favor of treating ~ as a
   2584     //    unary complement rather than treating ~X as referring to a destructor.
   2585 
   2586     // Parse the '~'.
   2587     SourceLocation TildeLoc = ConsumeToken();
   2588 
   2589     if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
   2590       DeclSpec DS(AttrFactory);
   2591       SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
   2592       if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
   2593         Result.setDestructorName(TildeLoc, Type, EndLoc);
   2594         return false;
   2595       }
   2596       return true;
   2597     }
   2598 
   2599     // Parse the class-name.
   2600     if (Tok.isNot(tok::identifier)) {
   2601       Diag(Tok, diag::err_destructor_tilde_identifier);
   2602       return true;
   2603     }
   2604 
   2605     // If the user wrote ~T::T, correct it to T::~T.
   2606     DeclaratorScopeObj DeclScopeObj(*this, SS);
   2607     if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
   2608       // Don't let ParseOptionalCXXScopeSpecifier() "correct"
   2609       // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
   2610       // it will confuse this recovery logic.
   2611       ColonProtectionRAIIObject ColonRAII(*this, false);
   2612 
   2613       if (SS.isSet()) {
   2614         AnnotateScopeToken(SS, /*NewAnnotation*/true);
   2615         SS.clear();
   2616       }
   2617       if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
   2618         return true;
   2619       if (SS.isNotEmpty())
   2620         ObjectType = nullptr;
   2621       if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
   2622           !SS.isSet()) {
   2623         Diag(TildeLoc, diag::err_destructor_tilde_scope);
   2624         return true;
   2625       }
   2626 
   2627       // Recover as if the tilde had been written before the identifier.
   2628       Diag(TildeLoc, diag::err_destructor_tilde_scope)
   2629         << FixItHint::CreateRemoval(TildeLoc)
   2630         << FixItHint::CreateInsertion(Tok.getLocation(), "~");
   2631 
   2632       // Temporarily enter the scope for the rest of this function.
   2633       if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
   2634         DeclScopeObj.EnterDeclaratorScope();
   2635     }
   2636 
   2637     // Parse the class-name (or template-name in a simple-template-id).
   2638     IdentifierInfo *ClassName = Tok.getIdentifierInfo();
   2639     SourceLocation ClassNameLoc = ConsumeToken();
   2640 
   2641     if (TemplateSpecified || Tok.is(tok::less)) {
   2642       Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
   2643       return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
   2644                                           ClassName, ClassNameLoc,
   2645                                           EnteringContext, ObjectType,
   2646                                           Result, TemplateSpecified);
   2647     }
   2648 
   2649     // Note that this is a destructor name.
   2650     ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
   2651                                               ClassNameLoc, getCurScope(),
   2652                                               SS, ObjectType,
   2653                                               EnteringContext);
   2654     if (!Ty)
   2655       return true;
   2656 
   2657     Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
   2658     return false;
   2659   }
   2660 
   2661   Diag(Tok, diag::err_expected_unqualified_id)
   2662     << getLangOpts().CPlusPlus;
   2663   return true;
   2664 }
   2665 
   2666 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
   2667 /// memory in a typesafe manner and call constructors.
   2668 ///
   2669 /// This method is called to parse the new expression after the optional :: has
   2670 /// been already parsed.  If the :: was present, "UseGlobal" is true and "Start"
   2671 /// is its location.  Otherwise, "Start" is the location of the 'new' token.
   2672 ///
   2673 ///        new-expression:
   2674 ///                   '::'[opt] 'new' new-placement[opt] new-type-id
   2675 ///                                     new-initializer[opt]
   2676 ///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
   2677 ///                                     new-initializer[opt]
   2678 ///
   2679 ///        new-placement:
   2680 ///                   '(' expression-list ')'
   2681 ///
   2682 ///        new-type-id:
   2683 ///                   type-specifier-seq new-declarator[opt]
   2684 /// [GNU]             attributes type-specifier-seq new-declarator[opt]
   2685 ///
   2686 ///        new-declarator:
   2687 ///                   ptr-operator new-declarator[opt]
   2688 ///                   direct-new-declarator
   2689 ///
   2690 ///        new-initializer:
   2691 ///                   '(' expression-list[opt] ')'
   2692 /// [C++0x]           braced-init-list
   2693 ///
   2694 ExprResult
   2695 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
   2696   assert(Tok.is(tok::kw_new) && "expected 'new' token");
   2697   ConsumeToken();   // Consume 'new'
   2698 
   2699   // A '(' now can be a new-placement or the '(' wrapping the type-id in the
   2700   // second form of new-expression. It can't be a new-type-id.
   2701 
   2702   ExprVector PlacementArgs;
   2703   SourceLocation PlacementLParen, PlacementRParen;
   2704 
   2705   SourceRange TypeIdParens;
   2706   DeclSpec DS(AttrFactory);
   2707   Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
   2708   if (Tok.is(tok::l_paren)) {
   2709     // If it turns out to be a placement, we change the type location.
   2710     BalancedDelimiterTracker T(*this, tok::l_paren);
   2711     T.consumeOpen();
   2712     PlacementLParen = T.getOpenLocation();
   2713     if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
   2714       SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
   2715       return ExprError();
   2716     }
   2717 
   2718     T.consumeClose();
   2719     PlacementRParen = T.getCloseLocation();
   2720     if (PlacementRParen.isInvalid()) {
   2721       SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
   2722       return ExprError();
   2723     }
   2724 
   2725     if (PlacementArgs.empty()) {
   2726       // Reset the placement locations. There was no placement.
   2727       TypeIdParens = T.getRange();
   2728       PlacementLParen = PlacementRParen = SourceLocation();
   2729     } else {
   2730       // We still need the type.
   2731       if (Tok.is(tok::l_paren)) {
   2732         BalancedDelimiterTracker T(*this, tok::l_paren);
   2733         T.consumeOpen();
   2734         MaybeParseGNUAttributes(DeclaratorInfo);
   2735         ParseSpecifierQualifierList(DS);
   2736         DeclaratorInfo.SetSourceRange(DS.getSourceRange());
   2737         ParseDeclarator(DeclaratorInfo);
   2738         T.consumeClose();
   2739         TypeIdParens = T.getRange();
   2740       } else {
   2741         MaybeParseGNUAttributes(DeclaratorInfo);
   2742         if (ParseCXXTypeSpecifierSeq(DS))
   2743           DeclaratorInfo.setInvalidType(true);
   2744         else {
   2745           DeclaratorInfo.SetSourceRange(DS.getSourceRange());
   2746           ParseDeclaratorInternal(DeclaratorInfo,
   2747                                   &Parser::ParseDirectNewDeclarator);
   2748         }
   2749       }
   2750     }
   2751   } else {
   2752     // A new-type-id is a simplified type-id, where essentially the
   2753     // direct-declarator is replaced by a direct-new-declarator.
   2754     MaybeParseGNUAttributes(DeclaratorInfo);
   2755     if (ParseCXXTypeSpecifierSeq(DS))
   2756       DeclaratorInfo.setInvalidType(true);
   2757     else {
   2758       DeclaratorInfo.SetSourceRange(DS.getSourceRange());
   2759       ParseDeclaratorInternal(DeclaratorInfo,
   2760                               &Parser::ParseDirectNewDeclarator);
   2761     }
   2762   }
   2763   if (DeclaratorInfo.isInvalidType()) {
   2764     SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
   2765     return ExprError();
   2766   }
   2767 
   2768   ExprResult Initializer;
   2769 
   2770   if (Tok.is(tok::l_paren)) {
   2771     SourceLocation ConstructorLParen, ConstructorRParen;
   2772     ExprVector ConstructorArgs;
   2773     BalancedDelimiterTracker T(*this, tok::l_paren);
   2774     T.consumeOpen();
   2775     ConstructorLParen = T.getOpenLocation();
   2776     if (Tok.isNot(tok::r_paren)) {
   2777       CommaLocsTy CommaLocs;
   2778       if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
   2779             ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
   2780                                                        DeclaratorInfo).get();
   2781             Actions.CodeCompleteConstructor(getCurScope(),
   2782                                       TypeRep.get()->getCanonicalTypeInternal(),
   2783                                             DeclaratorInfo.getLocEnd(),
   2784                                             ConstructorArgs);
   2785       })) {
   2786         SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
   2787         return ExprError();
   2788       }
   2789     }
   2790     T.consumeClose();
   2791     ConstructorRParen = T.getCloseLocation();
   2792     if (ConstructorRParen.isInvalid()) {
   2793       SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
   2794       return ExprError();
   2795     }
   2796     Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
   2797                                              ConstructorRParen,
   2798                                              ConstructorArgs);
   2799   } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
   2800     Diag(Tok.getLocation(),
   2801          diag::warn_cxx98_compat_generalized_initializer_lists);
   2802     Initializer = ParseBraceInitializer();
   2803   }
   2804   if (Initializer.isInvalid())
   2805     return Initializer;
   2806 
   2807   return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
   2808                              PlacementArgs, PlacementRParen,
   2809                              TypeIdParens, DeclaratorInfo, Initializer.get());
   2810 }
   2811 
   2812 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
   2813 /// passed to ParseDeclaratorInternal.
   2814 ///
   2815 ///        direct-new-declarator:
   2816 ///                   '[' expression ']'
   2817 ///                   direct-new-declarator '[' constant-expression ']'
   2818 ///
   2819 void Parser::ParseDirectNewDeclarator(Declarator &D) {
   2820   // Parse the array dimensions.
   2821   bool first = true;
   2822   while (Tok.is(tok::l_square)) {
   2823     // An array-size expression can't start with a lambda.
   2824     if (CheckProhibitedCXX11Attribute())
   2825       continue;
   2826 
   2827     BalancedDelimiterTracker T(*this, tok::l_square);
   2828     T.consumeOpen();
   2829 
   2830     ExprResult Size(first ? ParseExpression()
   2831                                 : ParseConstantExpression());
   2832     if (Size.isInvalid()) {
   2833       // Recover
   2834       SkipUntil(tok::r_square, StopAtSemi);
   2835       return;
   2836     }
   2837     first = false;
   2838 
   2839     T.consumeClose();
   2840 
   2841     // Attributes here appertain to the array type. C++11 [expr.new]p5.
   2842     ParsedAttributes Attrs(AttrFactory);
   2843     MaybeParseCXX11Attributes(Attrs);
   2844 
   2845     D.AddTypeInfo(DeclaratorChunk::getArray(0,
   2846                                             /*static=*/false, /*star=*/false,
   2847                                             Size.get(),
   2848                                             T.getOpenLocation(),
   2849                                             T.getCloseLocation()),
   2850                   Attrs, T.getCloseLocation());
   2851 
   2852     if (T.getCloseLocation().isInvalid())
   2853       return;
   2854   }
   2855 }
   2856 
   2857 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
   2858 /// This ambiguity appears in the syntax of the C++ new operator.
   2859 ///
   2860 ///        new-expression:
   2861 ///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
   2862 ///                                     new-initializer[opt]
   2863 ///
   2864 ///        new-placement:
   2865 ///                   '(' expression-list ')'
   2866 ///
   2867 bool Parser::ParseExpressionListOrTypeId(
   2868                                    SmallVectorImpl<Expr*> &PlacementArgs,
   2869                                          Declarator &D) {
   2870   // The '(' was already consumed.
   2871   if (isTypeIdInParens()) {
   2872     ParseSpecifierQualifierList(D.getMutableDeclSpec());
   2873     D.SetSourceRange(D.getDeclSpec().getSourceRange());
   2874     ParseDeclarator(D);
   2875     return D.isInvalidType();
   2876   }
   2877 
   2878   // It's not a type, it has to be an expression list.
   2879   // Discard the comma locations - ActOnCXXNew has enough parameters.
   2880   CommaLocsTy CommaLocs;
   2881   return ParseExpressionList(PlacementArgs, CommaLocs);
   2882 }
   2883 
   2884 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
   2885 /// to free memory allocated by new.
   2886 ///
   2887 /// This method is called to parse the 'delete' expression after the optional
   2888 /// '::' has been already parsed.  If the '::' was present, "UseGlobal" is true
   2889 /// and "Start" is its location.  Otherwise, "Start" is the location of the
   2890 /// 'delete' token.
   2891 ///
   2892 ///        delete-expression:
   2893 ///                   '::'[opt] 'delete' cast-expression
   2894 ///                   '::'[opt] 'delete' '[' ']' cast-expression
   2895 ExprResult
   2896 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
   2897   assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
   2898   ConsumeToken(); // Consume 'delete'
   2899 
   2900   // Array delete?
   2901   bool ArrayDelete = false;
   2902   if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
   2903     // C++11 [expr.delete]p1:
   2904     //   Whenever the delete keyword is followed by empty square brackets, it
   2905     //   shall be interpreted as [array delete].
   2906     //   [Footnote: A lambda expression with a lambda-introducer that consists
   2907     //              of empty square brackets can follow the delete keyword if
   2908     //              the lambda expression is enclosed in parentheses.]
   2909     // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
   2910     //        lambda-introducer.
   2911     ArrayDelete = true;
   2912     BalancedDelimiterTracker T(*this, tok::l_square);
   2913 
   2914     T.consumeOpen();
   2915     T.consumeClose();
   2916     if (T.getCloseLocation().isInvalid())
   2917       return ExprError();
   2918   }
   2919 
   2920   ExprResult Operand(ParseCastExpression(false));
   2921   if (Operand.isInvalid())
   2922     return Operand;
   2923 
   2924   return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
   2925 }
   2926 
   2927 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
   2928   switch (kind) {
   2929   default: llvm_unreachable("Not a known type trait");
   2930 #define TYPE_TRAIT_1(Spelling, Name, Key) \
   2931 case tok::kw_ ## Spelling: return UTT_ ## Name;
   2932 #define TYPE_TRAIT_2(Spelling, Name, Key) \
   2933 case tok::kw_ ## Spelling: return BTT_ ## Name;
   2934 #include "clang/Basic/TokenKinds.def"
   2935 #define TYPE_TRAIT_N(Spelling, Name, Key) \
   2936   case tok::kw_ ## Spelling: return TT_ ## Name;
   2937 #include "clang/Basic/TokenKinds.def"
   2938   }
   2939 }
   2940 
   2941 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
   2942   switch(kind) {
   2943   default: llvm_unreachable("Not a known binary type trait");
   2944   case tok::kw___array_rank:                 return ATT_ArrayRank;
   2945   case tok::kw___array_extent:               return ATT_ArrayExtent;
   2946   }
   2947 }
   2948 
   2949 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
   2950   switch(kind) {
   2951   default: llvm_unreachable("Not a known unary expression trait.");
   2952   case tok::kw___is_lvalue_expr:             return ET_IsLValueExpr;
   2953   case tok::kw___is_rvalue_expr:             return ET_IsRValueExpr;
   2954   }
   2955 }
   2956 
   2957 static unsigned TypeTraitArity(tok::TokenKind kind) {
   2958   switch (kind) {
   2959     default: llvm_unreachable("Not a known type trait");
   2960 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
   2961 #include "clang/Basic/TokenKinds.def"
   2962   }
   2963 }
   2964 
   2965 /// \brief Parse the built-in type-trait pseudo-functions that allow
   2966 /// implementation of the TR1/C++11 type traits templates.
   2967 ///
   2968 ///       primary-expression:
   2969 ///          unary-type-trait '(' type-id ')'
   2970 ///          binary-type-trait '(' type-id ',' type-id ')'
   2971 ///          type-trait '(' type-id-seq ')'
   2972 ///
   2973 ///       type-id-seq:
   2974 ///          type-id ...[opt] type-id-seq[opt]
   2975 ///
   2976 ExprResult Parser::ParseTypeTrait() {
   2977   tok::TokenKind Kind = Tok.getKind();
   2978   unsigned Arity = TypeTraitArity(Kind);
   2979 
   2980   SourceLocation Loc = ConsumeToken();
   2981 
   2982   BalancedDelimiterTracker Parens(*this, tok::l_paren);
   2983   if (Parens.expectAndConsume())
   2984     return ExprError();
   2985 
   2986   SmallVector<ParsedType, 2> Args;
   2987   do {
   2988     // Parse the next type.
   2989     TypeResult Ty = ParseTypeName();
   2990     if (Ty.isInvalid()) {
   2991       Parens.skipToEnd();
   2992       return ExprError();
   2993     }
   2994 
   2995     // Parse the ellipsis, if present.
   2996     if (Tok.is(tok::ellipsis)) {
   2997       Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
   2998       if (Ty.isInvalid()) {
   2999         Parens.skipToEnd();
   3000         return ExprError();
   3001       }
   3002     }
   3003 
   3004     // Add this type to the list of arguments.
   3005     Args.push_back(Ty.get());
   3006   } while (TryConsumeToken(tok::comma));
   3007 
   3008   if (Parens.consumeClose())
   3009     return ExprError();
   3010 
   3011   SourceLocation EndLoc = Parens.getCloseLocation();
   3012 
   3013   if (Arity && Args.size() != Arity) {
   3014     Diag(EndLoc, diag::err_type_trait_arity)
   3015       << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
   3016     return ExprError();
   3017   }
   3018 
   3019   if (!Arity && Args.empty()) {
   3020     Diag(EndLoc, diag::err_type_trait_arity)
   3021       << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
   3022     return ExprError();
   3023   }
   3024 
   3025   return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
   3026 }
   3027 
   3028 /// ParseArrayTypeTrait - Parse the built-in array type-trait
   3029 /// pseudo-functions.
   3030 ///
   3031 ///       primary-expression:
   3032 /// [Embarcadero]     '__array_rank' '(' type-id ')'
   3033 /// [Embarcadero]     '__array_extent' '(' type-id ',' expression ')'
   3034 ///
   3035 ExprResult Parser::ParseArrayTypeTrait() {
   3036   ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
   3037   SourceLocation Loc = ConsumeToken();
   3038 
   3039   BalancedDelimiterTracker T(*this, tok::l_paren);
   3040   if (T.expectAndConsume())
   3041     return ExprError();
   3042 
   3043   TypeResult Ty = ParseTypeName();
   3044   if (Ty.isInvalid()) {
   3045     SkipUntil(tok::comma, StopAtSemi);
   3046     SkipUntil(tok::r_paren, StopAtSemi);
   3047     return ExprError();
   3048   }
   3049 
   3050   switch (ATT) {
   3051   case ATT_ArrayRank: {
   3052     T.consumeClose();
   3053     return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
   3054                                        T.getCloseLocation());
   3055   }
   3056   case ATT_ArrayExtent: {
   3057     if (ExpectAndConsume(tok::comma)) {
   3058       SkipUntil(tok::r_paren, StopAtSemi);
   3059       return ExprError();
   3060     }
   3061 
   3062     ExprResult DimExpr = ParseExpression();
   3063     T.consumeClose();
   3064 
   3065     return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
   3066                                        T.getCloseLocation());
   3067   }
   3068   }
   3069   llvm_unreachable("Invalid ArrayTypeTrait!");
   3070 }
   3071 
   3072 /// ParseExpressionTrait - Parse built-in expression-trait
   3073 /// pseudo-functions like __is_lvalue_expr( xxx ).
   3074 ///
   3075 ///       primary-expression:
   3076 /// [Embarcadero]     expression-trait '(' expression ')'
   3077 ///
   3078 ExprResult Parser::ParseExpressionTrait() {
   3079   ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
   3080   SourceLocation Loc = ConsumeToken();
   3081 
   3082   BalancedDelimiterTracker T(*this, tok::l_paren);
   3083   if (T.expectAndConsume())
   3084     return ExprError();
   3085 
   3086   ExprResult Expr = ParseExpression();
   3087 
   3088   T.consumeClose();
   3089 
   3090   return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
   3091                                       T.getCloseLocation());
   3092 }
   3093 
   3094 
   3095 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
   3096 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
   3097 /// based on the context past the parens.
   3098 ExprResult
   3099 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
   3100                                          ParsedType &CastTy,
   3101                                          BalancedDelimiterTracker &Tracker,
   3102                                          ColonProtectionRAIIObject &ColonProt) {
   3103   assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
   3104   assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
   3105   assert(isTypeIdInParens() && "Not a type-id!");
   3106 
   3107   ExprResult Result(true);
   3108   CastTy = nullptr;
   3109 
   3110   // We need to disambiguate a very ugly part of the C++ syntax:
   3111   //
   3112   // (T())x;  - type-id
   3113   // (T())*x; - type-id
   3114   // (T())/x; - expression
   3115   // (T());   - expression
   3116   //
   3117   // The bad news is that we cannot use the specialized tentative parser, since
   3118   // it can only verify that the thing inside the parens can be parsed as
   3119   // type-id, it is not useful for determining the context past the parens.
   3120   //
   3121   // The good news is that the parser can disambiguate this part without
   3122   // making any unnecessary Action calls.
   3123   //
   3124   // It uses a scheme similar to parsing inline methods. The parenthesized
   3125   // tokens are cached, the context that follows is determined (possibly by
   3126   // parsing a cast-expression), and then we re-introduce the cached tokens
   3127   // into the token stream and parse them appropriately.
   3128 
   3129   ParenParseOption ParseAs;
   3130   CachedTokens Toks;
   3131 
   3132   // Store the tokens of the parentheses. We will parse them after we determine
   3133   // the context that follows them.
   3134   if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
   3135     // We didn't find the ')' we expected.
   3136     Tracker.consumeClose();
   3137     return ExprError();
   3138   }
   3139 
   3140   if (Tok.is(tok::l_brace)) {
   3141     ParseAs = CompoundLiteral;
   3142   } else {
   3143     bool NotCastExpr;
   3144     if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
   3145       NotCastExpr = true;
   3146     } else {
   3147       // Try parsing the cast-expression that may follow.
   3148       // If it is not a cast-expression, NotCastExpr will be true and no token
   3149       // will be consumed.
   3150       ColonProt.restore();
   3151       Result = ParseCastExpression(false/*isUnaryExpression*/,
   3152                                    false/*isAddressofOperand*/,
   3153                                    NotCastExpr,
   3154                                    // type-id has priority.
   3155                                    IsTypeCast);
   3156     }
   3157 
   3158     // If we parsed a cast-expression, it's really a type-id, otherwise it's
   3159     // an expression.
   3160     ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
   3161   }
   3162 
   3163   // Create a fake EOF to mark end of Toks buffer.
   3164   Token AttrEnd;
   3165   AttrEnd.startToken();
   3166   AttrEnd.setKind(tok::eof);
   3167   AttrEnd.setLocation(Tok.getLocation());
   3168   AttrEnd.setEofData(Toks.data());
   3169   Toks.push_back(AttrEnd);
   3170 
   3171   // The current token should go after the cached tokens.
   3172   Toks.push_back(Tok);
   3173   // Re-enter the stored parenthesized tokens into the token stream, so we may
   3174   // parse them now.
   3175   PP.EnterTokenStream(Toks, true /*DisableMacroExpansion*/);
   3176   // Drop the current token and bring the first cached one. It's the same token
   3177   // as when we entered this function.
   3178   ConsumeAnyToken();
   3179 
   3180   if (ParseAs >= CompoundLiteral) {
   3181     // Parse the type declarator.
   3182     DeclSpec DS(AttrFactory);
   3183     Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
   3184     {
   3185       ColonProtectionRAIIObject InnerColonProtection(*this);
   3186       ParseSpecifierQualifierList(DS);
   3187       ParseDeclarator(DeclaratorInfo);
   3188     }
   3189 
   3190     // Match the ')'.
   3191     Tracker.consumeClose();
   3192     ColonProt.restore();
   3193 
   3194     // Consume EOF marker for Toks buffer.
   3195     assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
   3196     ConsumeAnyToken();
   3197 
   3198     if (ParseAs == CompoundLiteral) {
   3199       ExprType = CompoundLiteral;
   3200       if (DeclaratorInfo.isInvalidType())
   3201         return ExprError();
   3202 
   3203       TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
   3204       return ParseCompoundLiteralExpression(Ty.get(),
   3205                                             Tracker.getOpenLocation(),
   3206                                             Tracker.getCloseLocation());
   3207     }
   3208 
   3209     // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
   3210     assert(ParseAs == CastExpr);
   3211 
   3212     if (DeclaratorInfo.isInvalidType())
   3213       return ExprError();
   3214 
   3215     // Result is what ParseCastExpression returned earlier.
   3216     if (!Result.isInvalid())
   3217       Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
   3218                                     DeclaratorInfo, CastTy,
   3219                                     Tracker.getCloseLocation(), Result.get());
   3220     return Result;
   3221   }
   3222 
   3223   // Not a compound literal, and not followed by a cast-expression.
   3224   assert(ParseAs == SimpleExpr);
   3225 
   3226   ExprType = SimpleExpr;
   3227   Result = ParseExpression();
   3228   if (!Result.isInvalid() && Tok.is(tok::r_paren))
   3229     Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
   3230                                     Tok.getLocation(), Result.get());
   3231 
   3232   // Match the ')'.
   3233   if (Result.isInvalid()) {
   3234     while (Tok.isNot(tok::eof))
   3235       ConsumeAnyToken();
   3236     assert(Tok.getEofData() == AttrEnd.getEofData());
   3237     ConsumeAnyToken();
   3238     return ExprError();
   3239   }
   3240 
   3241   Tracker.consumeClose();
   3242   // Consume EOF marker for Toks buffer.
   3243   assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
   3244   ConsumeAnyToken();
   3245   return Result;
   3246 }
   3247