clang API Documentation

ParseExprCXX.cpp
Go to the documentation of this file.
00001 //===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Expression parsing implementation for C++.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 #include "clang/AST/ASTContext.h"
00014 #include "RAIIObjectsForParser.h"
00015 #include "clang/AST/DeclTemplate.h"
00016 #include "clang/Basic/PrettyStackTrace.h"
00017 #include "clang/Lex/LiteralSupport.h"
00018 #include "clang/Parse/ParseDiagnostic.h"
00019 #include "clang/Parse/Parser.h"
00020 #include "clang/Sema/DeclSpec.h"
00021 #include "clang/Sema/ParsedTemplate.h"
00022 #include "clang/Sema/Scope.h"
00023 #include "llvm/Support/ErrorHandling.h"
00024 
00025 
00026 using namespace clang;
00027 
00028 static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
00029   switch (Kind) {
00030     // template name
00031     case tok::unknown:             return 0;
00032     // casts
00033     case tok::kw_const_cast:       return 1;
00034     case tok::kw_dynamic_cast:     return 2;
00035     case tok::kw_reinterpret_cast: return 3;
00036     case tok::kw_static_cast:      return 4;
00037     default:
00038       llvm_unreachable("Unknown type for digraph error message.");
00039   }
00040 }
00041 
00042 // Are the two tokens adjacent in the same source file?
00043 bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
00044   SourceManager &SM = PP.getSourceManager();
00045   SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
00046   SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
00047   return FirstEnd == SM.getSpellingLoc(Second.getLocation());
00048 }
00049 
00050 // Suggest fixit for "<::" after a cast.
00051 static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
00052                        Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
00053   // Pull '<:' and ':' off token stream.
00054   if (!AtDigraph)
00055     PP.Lex(DigraphToken);
00056   PP.Lex(ColonToken);
00057 
00058   SourceRange Range;
00059   Range.setBegin(DigraphToken.getLocation());
00060   Range.setEnd(ColonToken.getLocation());
00061   P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
00062       << SelectDigraphErrorMessage(Kind)
00063       << FixItHint::CreateReplacement(Range, "< ::");
00064 
00065   // Update token information to reflect their change in token type.
00066   ColonToken.setKind(tok::coloncolon);
00067   ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
00068   ColonToken.setLength(2);
00069   DigraphToken.setKind(tok::less);
00070   DigraphToken.setLength(1);
00071 
00072   // Push new tokens back to token stream.
00073   PP.EnterToken(ColonToken);
00074   if (!AtDigraph)
00075     PP.EnterToken(DigraphToken);
00076 }
00077 
00078 // Check for '<::' which should be '< ::' instead of '[:' when following
00079 // a template name.
00080 void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
00081                                         bool EnteringContext,
00082                                         IdentifierInfo &II, CXXScopeSpec &SS) {
00083   if (!Next.is(tok::l_square) || Next.getLength() != 2)
00084     return;
00085 
00086   Token SecondToken = GetLookAheadToken(2);
00087   if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
00088     return;
00089 
00090   TemplateTy Template;
00091   UnqualifiedId TemplateName;
00092   TemplateName.setIdentifier(&II, Tok.getLocation());
00093   bool MemberOfUnknownSpecialization;
00094   if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
00095                               TemplateName, ObjectType, EnteringContext,
00096                               Template, MemberOfUnknownSpecialization))
00097     return;
00098 
00099   FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
00100              /*AtDigraph*/false);
00101 }
00102 
00103 /// \brief Emits an error for a left parentheses after a double colon.
00104 ///
00105 /// When a '(' is found after a '::', emit an error.  Attempt to fix the token
00106 /// stream by removing the '(', and the matching ')' if found.
00107 void Parser::CheckForLParenAfterColonColon() {
00108   if (!Tok.is(tok::l_paren))
00109     return;
00110 
00111   SourceLocation l_parenLoc = ConsumeParen(), r_parenLoc;
00112   Token Tok1 = getCurToken();
00113   if (!Tok1.is(tok::identifier) && !Tok1.is(tok::star))
00114     return;
00115 
00116   if (Tok1.is(tok::identifier)) {
00117     Token Tok2 = GetLookAheadToken(1);
00118     if (Tok2.is(tok::r_paren)) {
00119       ConsumeToken();
00120       PP.EnterToken(Tok1);
00121       r_parenLoc = ConsumeParen();
00122     }
00123   } else if (Tok1.is(tok::star)) {
00124     Token Tok2 = GetLookAheadToken(1);
00125     if (Tok2.is(tok::identifier)) {
00126       Token Tok3 = GetLookAheadToken(2);
00127       if (Tok3.is(tok::r_paren)) {
00128         ConsumeToken();
00129         ConsumeToken();
00130         PP.EnterToken(Tok2);
00131         PP.EnterToken(Tok1);
00132         r_parenLoc = ConsumeParen();
00133       }
00134     }
00135   }
00136 
00137   Diag(l_parenLoc, diag::err_paren_after_colon_colon)
00138       << FixItHint::CreateRemoval(l_parenLoc)
00139       << FixItHint::CreateRemoval(r_parenLoc);
00140 }
00141 
00142 /// \brief Parse global scope or nested-name-specifier if present.
00143 ///
00144 /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
00145 /// may be preceded by '::'). Note that this routine will not parse ::new or
00146 /// ::delete; it will just leave them in the token stream.
00147 ///
00148 ///       '::'[opt] nested-name-specifier
00149 ///       '::'
00150 ///
00151 ///       nested-name-specifier:
00152 ///         type-name '::'
00153 ///         namespace-name '::'
00154 ///         nested-name-specifier identifier '::'
00155 ///         nested-name-specifier 'template'[opt] simple-template-id '::'
00156 ///
00157 ///
00158 /// \param SS the scope specifier that will be set to the parsed
00159 /// nested-name-specifier (or empty)
00160 ///
00161 /// \param ObjectType if this nested-name-specifier is being parsed following
00162 /// the "." or "->" of a member access expression, this parameter provides the
00163 /// type of the object whose members are being accessed.
00164 ///
00165 /// \param EnteringContext whether we will be entering into the context of
00166 /// the nested-name-specifier after parsing it.
00167 ///
00168 /// \param MayBePseudoDestructor When non-NULL, points to a flag that
00169 /// indicates whether this nested-name-specifier may be part of a
00170 /// pseudo-destructor name. In this case, the flag will be set false
00171 /// if we don't actually end up parsing a destructor name. Moreorover,
00172 /// if we do end up determining that we are parsing a destructor name,
00173 /// the last component of the nested-name-specifier is not parsed as
00174 /// part of the scope specifier.
00175 ///
00176 /// \param IsTypename If \c true, this nested-name-specifier is known to be
00177 /// part of a type name. This is used to improve error recovery.
00178 ///
00179 /// \param LastII When non-NULL, points to an IdentifierInfo* that will be
00180 /// filled in with the leading identifier in the last component of the
00181 /// nested-name-specifier, if any.
00182 ///
00183 /// \returns true if there was an error parsing a scope specifier
00184 bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
00185                                             ParsedType ObjectType,
00186                                             bool EnteringContext,
00187                                             bool *MayBePseudoDestructor,
00188                                             bool IsTypename,
00189                                             IdentifierInfo **LastII) {
00190   assert(getLangOpts().CPlusPlus &&
00191          "Call sites of this function should be guarded by checking for C++");
00192 
00193   if (Tok.is(tok::annot_cxxscope)) {
00194     assert(!LastII && "want last identifier but have already annotated scope");
00195     Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
00196                                                  Tok.getAnnotationRange(),
00197                                                  SS);
00198     ConsumeToken();
00199     return false;
00200   }
00201 
00202   if (Tok.is(tok::annot_template_id)) {
00203     // If the current token is an annotated template id, it may already have
00204     // a scope specifier. Restore it.
00205     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
00206     SS = TemplateId->SS;
00207   }
00208 
00209   if (LastII)
00210     *LastII = nullptr;
00211 
00212   bool HasScopeSpecifier = false;
00213 
00214   if (Tok.is(tok::coloncolon)) {
00215     // ::new and ::delete aren't nested-name-specifiers.
00216     tok::TokenKind NextKind = NextToken().getKind();
00217     if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
00218       return false;
00219 
00220     // '::' - Global scope qualifier.
00221     if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
00222       return true;
00223 
00224     CheckForLParenAfterColonColon();
00225 
00226     HasScopeSpecifier = true;
00227   }
00228 
00229   if (Tok.is(tok::kw___super)) {
00230     SourceLocation SuperLoc = ConsumeToken();
00231     if (!Tok.is(tok::coloncolon)) {
00232       Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
00233       return true;
00234     }
00235 
00236     return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
00237   }
00238 
00239   bool CheckForDestructor = false;
00240   if (MayBePseudoDestructor && *MayBePseudoDestructor) {
00241     CheckForDestructor = true;
00242     *MayBePseudoDestructor = false;
00243   }
00244 
00245   if (!HasScopeSpecifier &&
00246       (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))) {
00247     DeclSpec DS(AttrFactory);
00248     SourceLocation DeclLoc = Tok.getLocation();
00249     SourceLocation EndLoc  = ParseDecltypeSpecifier(DS);
00250 
00251     SourceLocation CCLoc;
00252     if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
00253       AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
00254       return false;
00255     }
00256 
00257     if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
00258       SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
00259 
00260     HasScopeSpecifier = true;
00261   }
00262 
00263   while (true) {
00264     if (HasScopeSpecifier) {
00265       // C++ [basic.lookup.classref]p5:
00266       //   If the qualified-id has the form
00267       //
00268       //       ::class-name-or-namespace-name::...
00269       //
00270       //   the class-name-or-namespace-name is looked up in global scope as a
00271       //   class-name or namespace-name.
00272       //
00273       // To implement this, we clear out the object type as soon as we've
00274       // seen a leading '::' or part of a nested-name-specifier.
00275       ObjectType = ParsedType();
00276       
00277       if (Tok.is(tok::code_completion)) {
00278         // Code completion for a nested-name-specifier, where the code
00279         // code completion token follows the '::'.
00280         Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
00281         // Include code completion token into the range of the scope otherwise
00282         // when we try to annotate the scope tokens the dangling code completion
00283         // token will cause assertion in
00284         // Preprocessor::AnnotatePreviousCachedTokens.
00285         SS.setEndLoc(Tok.getLocation());
00286         cutOffParsing();
00287         return true;
00288       }
00289     }
00290 
00291     // nested-name-specifier:
00292     //   nested-name-specifier 'template'[opt] simple-template-id '::'
00293 
00294     // Parse the optional 'template' keyword, then make sure we have
00295     // 'identifier <' after it.
00296     if (Tok.is(tok::kw_template)) {
00297       // If we don't have a scope specifier or an object type, this isn't a
00298       // nested-name-specifier, since they aren't allowed to start with
00299       // 'template'.
00300       if (!HasScopeSpecifier && !ObjectType)
00301         break;
00302 
00303       TentativeParsingAction TPA(*this);
00304       SourceLocation TemplateKWLoc = ConsumeToken();
00305 
00306       UnqualifiedId TemplateName;
00307       if (Tok.is(tok::identifier)) {
00308         // Consume the identifier.
00309         TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
00310         ConsumeToken();
00311       } else if (Tok.is(tok::kw_operator)) {
00312         // We don't need to actually parse the unqualified-id in this case,
00313         // because a simple-template-id cannot start with 'operator', but
00314         // go ahead and parse it anyway for consistency with the case where
00315         // we already annotated the template-id.
00316         if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
00317                                        TemplateName)) {
00318           TPA.Commit();
00319           break;
00320         }
00321 
00322         if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
00323             TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
00324           Diag(TemplateName.getSourceRange().getBegin(),
00325                diag::err_id_after_template_in_nested_name_spec)
00326             << TemplateName.getSourceRange();
00327           TPA.Commit();
00328           break;
00329         }
00330       } else {
00331         TPA.Revert();
00332         break;
00333       }
00334 
00335       // If the next token is not '<', we have a qualified-id that refers
00336       // to a template name, such as T::template apply, but is not a 
00337       // template-id.
00338       if (Tok.isNot(tok::less)) {
00339         TPA.Revert();
00340         break;
00341       }        
00342       
00343       // Commit to parsing the template-id.
00344       TPA.Commit();
00345       TemplateTy Template;
00346       if (TemplateNameKind TNK
00347           = Actions.ActOnDependentTemplateName(getCurScope(),
00348                                                SS, TemplateKWLoc, TemplateName,
00349                                                ObjectType, EnteringContext,
00350                                                Template)) {
00351         if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
00352                                     TemplateName, false))
00353           return true;
00354       } else
00355         return true;
00356 
00357       continue;
00358     }
00359 
00360     if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
00361       // We have
00362       //
00363       //   template-id '::'
00364       //
00365       // So we need to check whether the template-id is a simple-template-id of
00366       // the right kind (it should name a type or be dependent), and then
00367       // convert it into a type within the nested-name-specifier.
00368       TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
00369       if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
00370         *MayBePseudoDestructor = true;
00371         return false;
00372       }
00373 
00374       if (LastII)
00375         *LastII = TemplateId->Name;
00376 
00377       // Consume the template-id token.
00378       ConsumeToken();
00379 
00380       assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
00381       SourceLocation CCLoc = ConsumeToken();
00382 
00383       HasScopeSpecifier = true;
00384 
00385       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
00386                                          TemplateId->NumArgs);
00387 
00388       if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
00389                                               SS,
00390                                               TemplateId->TemplateKWLoc,
00391                                               TemplateId->Template,
00392                                               TemplateId->TemplateNameLoc,
00393                                               TemplateId->LAngleLoc,
00394                                               TemplateArgsPtr,
00395                                               TemplateId->RAngleLoc,
00396                                               CCLoc,
00397                                               EnteringContext)) {
00398         SourceLocation StartLoc 
00399           = SS.getBeginLoc().isValid()? SS.getBeginLoc()
00400                                       : TemplateId->TemplateNameLoc;
00401         SS.SetInvalid(SourceRange(StartLoc, CCLoc));
00402       }
00403 
00404       continue;
00405     }
00406 
00407     // The rest of the nested-name-specifier possibilities start with
00408     // tok::identifier.
00409     if (Tok.isNot(tok::identifier))
00410       break;
00411 
00412     IdentifierInfo &II = *Tok.getIdentifierInfo();
00413 
00414     // nested-name-specifier:
00415     //   type-name '::'
00416     //   namespace-name '::'
00417     //   nested-name-specifier identifier '::'
00418     Token Next = NextToken();
00419     
00420     // If we get foo:bar, this is almost certainly a typo for foo::bar.  Recover
00421     // and emit a fixit hint for it.
00422     if (Next.is(tok::colon) && !ColonIsSacred) {
00423       if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II, 
00424                                             Tok.getLocation(), 
00425                                             Next.getLocation(), ObjectType,
00426                                             EnteringContext) &&
00427           // If the token after the colon isn't an identifier, it's still an
00428           // error, but they probably meant something else strange so don't
00429           // recover like this.
00430           PP.LookAhead(1).is(tok::identifier)) {
00431         Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
00432           << FixItHint::CreateReplacement(Next.getLocation(), "::");
00433         // Recover as if the user wrote '::'.
00434         Next.setKind(tok::coloncolon);
00435       }
00436     }
00437     
00438     if (Next.is(tok::coloncolon)) {
00439       if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
00440           !Actions.isNonTypeNestedNameSpecifier(
00441               getCurScope(), SS, Tok.getLocation(), II, ObjectType)) {
00442         *MayBePseudoDestructor = true;
00443         return false;
00444       }
00445 
00446       if (ColonIsSacred) {
00447         const Token &Next2 = GetLookAheadToken(2);
00448         if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
00449             Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
00450           Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
00451               << Next2.getName()
00452               << FixItHint::CreateReplacement(Next.getLocation(), ":");
00453           Token ColonColon;
00454           PP.Lex(ColonColon);
00455           ColonColon.setKind(tok::colon);
00456           PP.EnterToken(ColonColon);
00457           break;
00458         }
00459       }
00460 
00461       if (LastII)
00462         *LastII = &II;
00463 
00464       // We have an identifier followed by a '::'. Lookup this name
00465       // as the name in a nested-name-specifier.
00466       Token Identifier = Tok;
00467       SourceLocation IdLoc = ConsumeToken();
00468       assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
00469              "NextToken() not working properly!");
00470       Token ColonColon = Tok;
00471       SourceLocation CCLoc = ConsumeToken();
00472 
00473       CheckForLParenAfterColonColon();
00474 
00475       bool IsCorrectedToColon = false;
00476       bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
00477       if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
00478                                               ObjectType, EnteringContext, SS,
00479                                               false, CorrectionFlagPtr)) {
00480         // Identifier is not recognized as a nested name, but we can have
00481         // mistyped '::' instead of ':'.
00482         if (CorrectionFlagPtr && IsCorrectedToColon) {
00483           ColonColon.setKind(tok::colon);
00484           PP.EnterToken(Tok);
00485           PP.EnterToken(ColonColon);
00486           Tok = Identifier;
00487           break;
00488         }
00489         SS.SetInvalid(SourceRange(IdLoc, CCLoc));
00490       }
00491       HasScopeSpecifier = true;
00492       continue;
00493     }
00494 
00495     CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
00496 
00497     // nested-name-specifier:
00498     //   type-name '<'
00499     if (Next.is(tok::less)) {
00500       TemplateTy Template;
00501       UnqualifiedId TemplateName;
00502       TemplateName.setIdentifier(&II, Tok.getLocation());
00503       bool MemberOfUnknownSpecialization;
00504       if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS, 
00505                                               /*hasTemplateKeyword=*/false,
00506                                                         TemplateName,
00507                                                         ObjectType,
00508                                                         EnteringContext,
00509                                                         Template,
00510                                               MemberOfUnknownSpecialization)) {
00511         // We have found a template name, so annotate this token
00512         // with a template-id annotation. We do not permit the
00513         // template-id to be translated into a type annotation,
00514         // because some clients (e.g., the parsing of class template
00515         // specializations) still want to see the original template-id
00516         // token.
00517         ConsumeToken();
00518         if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
00519                                     TemplateName, false))
00520           return true;
00521         continue;
00522       }
00523 
00524       if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) && 
00525           (IsTypename || IsTemplateArgumentList(1))) {
00526         // We have something like t::getAs<T>, where getAs is a 
00527         // member of an unknown specialization. However, this will only
00528         // parse correctly as a template, so suggest the keyword 'template'
00529         // before 'getAs' and treat this as a dependent template name.
00530         unsigned DiagID = diag::err_missing_dependent_template_keyword;
00531         if (getLangOpts().MicrosoftExt)
00532           DiagID = diag::warn_missing_dependent_template_keyword;
00533         
00534         Diag(Tok.getLocation(), DiagID)
00535           << II.getName()
00536           << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
00537         
00538         if (TemplateNameKind TNK 
00539               = Actions.ActOnDependentTemplateName(getCurScope(), 
00540                                                    SS, SourceLocation(),
00541                                                    TemplateName, ObjectType,
00542                                                    EnteringContext, Template)) {
00543           // Consume the identifier.
00544           ConsumeToken();
00545           if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
00546                                       TemplateName, false))
00547             return true;
00548         }
00549         else
00550           return true;     
00551                 
00552         continue;        
00553       }
00554     }
00555 
00556     // We don't have any tokens that form the beginning of a
00557     // nested-name-specifier, so we're done.
00558     break;
00559   }
00560 
00561   // Even if we didn't see any pieces of a nested-name-specifier, we
00562   // still check whether there is a tilde in this position, which
00563   // indicates a potential pseudo-destructor.
00564   if (CheckForDestructor && Tok.is(tok::tilde))
00565     *MayBePseudoDestructor = true;
00566 
00567   return false;
00568 }
00569 
00570 /// ParseCXXIdExpression - Handle id-expression.
00571 ///
00572 ///       id-expression:
00573 ///         unqualified-id
00574 ///         qualified-id
00575 ///
00576 ///       qualified-id:
00577 ///         '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
00578 ///         '::' identifier
00579 ///         '::' operator-function-id
00580 ///         '::' template-id
00581 ///
00582 /// NOTE: The standard specifies that, for qualified-id, the parser does not
00583 /// expect:
00584 ///
00585 ///   '::' conversion-function-id
00586 ///   '::' '~' class-name
00587 ///
00588 /// This may cause a slight inconsistency on diagnostics:
00589 ///
00590 /// class C {};
00591 /// namespace A {}
00592 /// void f() {
00593 ///   :: A :: ~ C(); // Some Sema error about using destructor with a
00594 ///                  // namespace.
00595 ///   :: ~ C(); // Some Parser error like 'unexpected ~'.
00596 /// }
00597 ///
00598 /// We simplify the parser a bit and make it work like:
00599 ///
00600 ///       qualified-id:
00601 ///         '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
00602 ///         '::' unqualified-id
00603 ///
00604 /// That way Sema can handle and report similar errors for namespaces and the
00605 /// global scope.
00606 ///
00607 /// The isAddressOfOperand parameter indicates that this id-expression is a
00608 /// direct operand of the address-of operator. This is, besides member contexts,
00609 /// the only place where a qualified-id naming a non-static class member may
00610 /// appear.
00611 ///
00612 ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
00613   // qualified-id:
00614   //   '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
00615   //   '::' unqualified-id
00616   //
00617   CXXScopeSpec SS;
00618   ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
00619 
00620   SourceLocation TemplateKWLoc;
00621   UnqualifiedId Name;
00622   if (ParseUnqualifiedId(SS,
00623                          /*EnteringContext=*/false,
00624                          /*AllowDestructorName=*/false,
00625                          /*AllowConstructorName=*/false,
00626                          /*ObjectType=*/ ParsedType(),
00627                          TemplateKWLoc,
00628                          Name))
00629     return ExprError();
00630 
00631   // This is only the direct operand of an & operator if it is not
00632   // followed by a postfix-expression suffix.
00633   if (isAddressOfOperand && isPostfixExpressionSuffixStart())
00634     isAddressOfOperand = false;
00635 
00636   return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
00637                                    Tok.is(tok::l_paren), isAddressOfOperand);
00638 }
00639 
00640 /// ParseLambdaExpression - Parse a C++11 lambda expression.
00641 ///
00642 ///       lambda-expression:
00643 ///         lambda-introducer lambda-declarator[opt] compound-statement
00644 ///
00645 ///       lambda-introducer:
00646 ///         '[' lambda-capture[opt] ']'
00647 ///
00648 ///       lambda-capture:
00649 ///         capture-default
00650 ///         capture-list
00651 ///         capture-default ',' capture-list
00652 ///
00653 ///       capture-default:
00654 ///         '&'
00655 ///         '='
00656 ///
00657 ///       capture-list:
00658 ///         capture
00659 ///         capture-list ',' capture
00660 ///
00661 ///       capture:
00662 ///         simple-capture
00663 ///         init-capture     [C++1y]
00664 ///
00665 ///       simple-capture:
00666 ///         identifier
00667 ///         '&' identifier
00668 ///         'this'
00669 ///
00670 ///       init-capture:      [C++1y]
00671 ///         identifier initializer
00672 ///         '&' identifier initializer
00673 ///
00674 ///       lambda-declarator:
00675 ///         '(' parameter-declaration-clause ')' attribute-specifier[opt]
00676 ///           'mutable'[opt] exception-specification[opt]
00677 ///           trailing-return-type[opt]
00678 ///
00679 ExprResult Parser::ParseLambdaExpression() {
00680   // Parse lambda-introducer.
00681   LambdaIntroducer Intro;
00682   Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
00683   if (DiagID) {
00684     Diag(Tok, DiagID.getValue());
00685     SkipUntil(tok::r_square, StopAtSemi);
00686     SkipUntil(tok::l_brace, StopAtSemi);
00687     SkipUntil(tok::r_brace, StopAtSemi);
00688     return ExprError();
00689   }
00690 
00691   return ParseLambdaExpressionAfterIntroducer(Intro);
00692 }
00693 
00694 /// TryParseLambdaExpression - Use lookahead and potentially tentative
00695 /// parsing to determine if we are looking at a C++0x lambda expression, and parse
00696 /// it if we are.
00697 ///
00698 /// If we are not looking at a lambda expression, returns ExprError().
00699 ExprResult Parser::TryParseLambdaExpression() {
00700   assert(getLangOpts().CPlusPlus11
00701          && Tok.is(tok::l_square)
00702          && "Not at the start of a possible lambda expression.");
00703 
00704   const Token Next = NextToken(), After = GetLookAheadToken(2);
00705 
00706   // If lookahead indicates this is a lambda...
00707   if (Next.is(tok::r_square) ||     // []
00708       Next.is(tok::equal) ||        // [=
00709       (Next.is(tok::amp) &&         // [&] or [&,
00710        (After.is(tok::r_square) ||
00711         After.is(tok::comma))) ||
00712       (Next.is(tok::identifier) &&  // [identifier]
00713        After.is(tok::r_square))) {
00714     return ParseLambdaExpression();
00715   }
00716 
00717   // If lookahead indicates an ObjC message send...
00718   // [identifier identifier
00719   if (Next.is(tok::identifier) && After.is(tok::identifier)) {
00720     return ExprEmpty();
00721   }
00722  
00723   // Here, we're stuck: lambda introducers and Objective-C message sends are
00724   // unambiguous, but it requires arbitrary lookhead.  [a,b,c,d,e,f,g] is a
00725   // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send.  Instead of
00726   // writing two routines to parse a lambda introducer, just try to parse
00727   // a lambda introducer first, and fall back if that fails.
00728   // (TryParseLambdaIntroducer never produces any diagnostic output.)
00729   LambdaIntroducer Intro;
00730   if (TryParseLambdaIntroducer(Intro))
00731     return ExprEmpty();
00732 
00733   return ParseLambdaExpressionAfterIntroducer(Intro);
00734 }
00735 
00736 /// \brief Parse a lambda introducer.
00737 /// \param Intro A LambdaIntroducer filled in with information about the
00738 ///        contents of the lambda-introducer.
00739 /// \param SkippedInits If non-null, we are disambiguating between an Obj-C
00740 ///        message send and a lambda expression. In this mode, we will
00741 ///        sometimes skip the initializers for init-captures and not fully
00742 ///        populate \p Intro. This flag will be set to \c true if we do so.
00743 /// \return A DiagnosticID if it hit something unexpected. The location for
00744 ///         for the diagnostic is that of the current token.
00745 Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
00746                                                  bool *SkippedInits) {
00747   typedef Optional<unsigned> DiagResult;
00748 
00749   assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
00750   BalancedDelimiterTracker T(*this, tok::l_square);
00751   T.consumeOpen();
00752 
00753   Intro.Range.setBegin(T.getOpenLocation());
00754 
00755   bool first = true;
00756 
00757   // Parse capture-default.
00758   if (Tok.is(tok::amp) &&
00759       (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
00760     Intro.Default = LCD_ByRef;
00761     Intro.DefaultLoc = ConsumeToken();
00762     first = false;
00763   } else if (Tok.is(tok::equal)) {
00764     Intro.Default = LCD_ByCopy;
00765     Intro.DefaultLoc = ConsumeToken();
00766     first = false;
00767   }
00768 
00769   while (Tok.isNot(tok::r_square)) {
00770     if (!first) {
00771       if (Tok.isNot(tok::comma)) {
00772         // Provide a completion for a lambda introducer here. Except
00773         // in Objective-C, where this is Almost Surely meant to be a message
00774         // send. In that case, fail here and let the ObjC message
00775         // expression parser perform the completion.
00776         if (Tok.is(tok::code_completion) &&
00777             !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
00778               !Intro.Captures.empty())) {
00779           Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, 
00780                                                /*AfterAmpersand=*/false);
00781           cutOffParsing();
00782           break;
00783         }
00784 
00785         return DiagResult(diag::err_expected_comma_or_rsquare);
00786       }
00787       ConsumeToken();
00788     }
00789 
00790     if (Tok.is(tok::code_completion)) {
00791       // If we're in Objective-C++ and we have a bare '[', then this is more
00792       // likely to be a message receiver.
00793       if (getLangOpts().ObjC1 && first)
00794         Actions.CodeCompleteObjCMessageReceiver(getCurScope());
00795       else
00796         Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, 
00797                                              /*AfterAmpersand=*/false);
00798       cutOffParsing();
00799       break;
00800     }
00801 
00802     first = false;
00803     
00804     // Parse capture.
00805     LambdaCaptureKind Kind = LCK_ByCopy;
00806     SourceLocation Loc;
00807     IdentifierInfo *Id = nullptr;
00808     SourceLocation EllipsisLoc;
00809     ExprResult Init;
00810     
00811     if (Tok.is(tok::kw_this)) {
00812       Kind = LCK_This;
00813       Loc = ConsumeToken();
00814     } else {
00815       if (Tok.is(tok::amp)) {
00816         Kind = LCK_ByRef;
00817         ConsumeToken();
00818 
00819         if (Tok.is(tok::code_completion)) {
00820           Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, 
00821                                                /*AfterAmpersand=*/true);
00822           cutOffParsing();
00823           break;
00824         }
00825       }
00826 
00827       if (Tok.is(tok::identifier)) {
00828         Id = Tok.getIdentifierInfo();
00829         Loc = ConsumeToken();
00830       } else if (Tok.is(tok::kw_this)) {
00831         // FIXME: If we want to suggest a fixit here, will need to return more
00832         // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
00833         // Clear()ed to prevent emission in case of tentative parsing?
00834         return DiagResult(diag::err_this_captured_by_reference);
00835       } else {
00836         return DiagResult(diag::err_expected_capture);
00837       }
00838 
00839       if (Tok.is(tok::l_paren)) {
00840         BalancedDelimiterTracker Parens(*this, tok::l_paren);
00841         Parens.consumeOpen();
00842 
00843         ExprVector Exprs;
00844         CommaLocsTy Commas;
00845         if (SkippedInits) {
00846           Parens.skipToEnd();
00847           *SkippedInits = true;
00848         } else if (ParseExpressionList(Exprs, Commas)) {
00849           Parens.skipToEnd();
00850           Init = ExprError();
00851         } else {
00852           Parens.consumeClose();
00853           Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
00854                                             Parens.getCloseLocation(),
00855                                             Exprs);
00856         }
00857       } else if (Tok.is(tok::l_brace) || Tok.is(tok::equal)) {
00858         // Each lambda init-capture forms its own full expression, which clears
00859         // Actions.MaybeODRUseExprs. So create an expression evaluation context
00860         // to save the necessary state, and restore it later.
00861         EnterExpressionEvaluationContext EC(Actions,
00862                                             Sema::PotentiallyEvaluated);
00863         TryConsumeToken(tok::equal);
00864 
00865         if (!SkippedInits)
00866           Init = ParseInitializer();
00867         else if (Tok.is(tok::l_brace)) {
00868           BalancedDelimiterTracker Braces(*this, tok::l_brace);
00869           Braces.consumeOpen();
00870           Braces.skipToEnd();
00871           *SkippedInits = true;
00872         } else {
00873           // We're disambiguating this:
00874           //
00875           //   [..., x = expr
00876           //
00877           // We need to find the end of the following expression in order to
00878           // determine whether this is an Obj-C message send's receiver, a
00879           // C99 designator, or a lambda init-capture.
00880           //
00881           // Parse the expression to find where it ends, and annotate it back
00882           // onto the tokens. We would have parsed this expression the same way
00883           // in either case: both the RHS of an init-capture and the RHS of an
00884           // assignment expression are parsed as an initializer-clause, and in
00885           // neither case can anything be added to the scope between the '[' and
00886           // here.
00887           //
00888           // FIXME: This is horrible. Adding a mechanism to skip an expression
00889           // would be much cleaner.
00890           // FIXME: If there is a ',' before the next ']' or ':', we can skip to
00891           // that instead. (And if we see a ':' with no matching '?', we can
00892           // classify this as an Obj-C message send.)
00893           SourceLocation StartLoc = Tok.getLocation();
00894           InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
00895           Init = ParseInitializer();
00896 
00897           if (Tok.getLocation() != StartLoc) {
00898             // Back out the lexing of the token after the initializer.
00899             PP.RevertCachedTokens(1);
00900 
00901             // Replace the consumed tokens with an appropriate annotation.
00902             Tok.setLocation(StartLoc);
00903             Tok.setKind(tok::annot_primary_expr);
00904             setExprAnnotation(Tok, Init);
00905             Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
00906             PP.AnnotateCachedTokens(Tok);
00907 
00908             // Consume the annotated initializer.
00909             ConsumeToken();
00910           }
00911         }
00912       } else
00913         TryConsumeToken(tok::ellipsis, EllipsisLoc);
00914     }
00915     // If this is an init capture, process the initialization expression
00916     // right away.  For lambda init-captures such as the following:
00917     // const int x = 10;
00918     //  auto L = [i = x+1](int a) {
00919     //    return [j = x+2,
00920     //           &k = x](char b) { };
00921     //  };
00922     // keep in mind that each lambda init-capture has to have:
00923     //  - its initialization expression executed in the context
00924     //    of the enclosing/parent decl-context.
00925     //  - but the variable itself has to be 'injected' into the
00926     //    decl-context of its lambda's call-operator (which has
00927     //    not yet been created).
00928     // Each init-expression is a full-expression that has to get
00929     // Sema-analyzed (for capturing etc.) before its lambda's
00930     // call-operator's decl-context, scope & scopeinfo are pushed on their
00931     // respective stacks.  Thus if any variable is odr-used in the init-capture
00932     // it will correctly get captured in the enclosing lambda, if one exists.
00933     // The init-variables above are created later once the lambdascope and
00934     // call-operators decl-context is pushed onto its respective stack.
00935 
00936     // Since the lambda init-capture's initializer expression occurs in the
00937     // context of the enclosing function or lambda, therefore we can not wait
00938     // till a lambda scope has been pushed on before deciding whether the
00939     // variable needs to be captured.  We also need to process all
00940     // lvalue-to-rvalue conversions and discarded-value conversions,
00941     // so that we can avoid capturing certain constant variables.
00942     // For e.g.,
00943     //  void test() {
00944     //   const int x = 10;
00945     //   auto L = [&z = x](char a) { <-- don't capture by the current lambda
00946     //     return [y = x](int i) { <-- don't capture by enclosing lambda
00947     //          return y;
00948     //     }
00949     //   };
00950     // If x was not const, the second use would require 'L' to capture, and
00951     // that would be an error.
00952 
00953     ParsedType InitCaptureParsedType;
00954     if (Init.isUsable()) {
00955       // Get the pointer and store it in an lvalue, so we can use it as an
00956       // out argument.
00957       Expr *InitExpr = Init.get();
00958       // This performs any lvalue-to-rvalue conversions if necessary, which
00959       // can affect what gets captured in the containing decl-context.
00960       QualType InitCaptureType = Actions.performLambdaInitCaptureInitialization(
00961         Loc, Kind == LCK_ByRef, Id, InitExpr);
00962       Init = InitExpr;
00963       InitCaptureParsedType.set(InitCaptureType);
00964     }
00965     Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init, InitCaptureParsedType);
00966   }
00967 
00968   T.consumeClose();
00969   Intro.Range.setEnd(T.getCloseLocation());
00970   return DiagResult();
00971 }
00972 
00973 /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
00974 ///
00975 /// Returns true if it hit something unexpected.
00976 bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
00977   TentativeParsingAction PA(*this);
00978 
00979   bool SkippedInits = false;
00980   Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
00981 
00982   if (DiagID) {
00983     PA.Revert();
00984     return true;
00985   }
00986 
00987   if (SkippedInits) {
00988     // Parse it again, but this time parse the init-captures too.
00989     PA.Revert();
00990     Intro = LambdaIntroducer();
00991     DiagID = ParseLambdaIntroducer(Intro);
00992     assert(!DiagID && "parsing lambda-introducer failed on reparse");
00993     return false;
00994   }
00995 
00996   PA.Commit();
00997   return false;
00998 }
00999 
01000 /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
01001 /// expression.
01002 ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
01003                      LambdaIntroducer &Intro) {
01004   SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
01005   Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
01006 
01007   PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
01008                                 "lambda expression parsing");
01009 
01010  
01011 
01012   // FIXME: Call into Actions to add any init-capture declarations to the
01013   // scope while parsing the lambda-declarator and compound-statement.
01014 
01015   // Parse lambda-declarator[opt].
01016   DeclSpec DS(AttrFactory);
01017   Declarator D(DS, Declarator::LambdaExprContext);
01018   TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
01019   Actions.PushLambdaScope();    
01020 
01021   if (Tok.is(tok::l_paren)) {
01022     ParseScope PrototypeScope(this,
01023                               Scope::FunctionPrototypeScope |
01024                               Scope::FunctionDeclarationScope |
01025                               Scope::DeclScope);
01026 
01027     SourceLocation DeclEndLoc;
01028     BalancedDelimiterTracker T(*this, tok::l_paren);
01029     T.consumeOpen();
01030     SourceLocation LParenLoc = T.getOpenLocation();
01031 
01032     // Parse parameter-declaration-clause.
01033     ParsedAttributes Attr(AttrFactory);
01034     SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
01035     SourceLocation EllipsisLoc;
01036     
01037     if (Tok.isNot(tok::r_paren)) {
01038       Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
01039       ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
01040       // For a generic lambda, each 'auto' within the parameter declaration 
01041       // clause creates a template type parameter, so increment the depth.
01042       if (Actions.getCurGenericLambda()) 
01043         ++CurTemplateDepthTracker;
01044     }
01045     T.consumeClose();
01046     SourceLocation RParenLoc = T.getCloseLocation();
01047     DeclEndLoc = RParenLoc;
01048 
01049     // GNU-style attributes must be parsed before the mutable specifier to be
01050     // compatible with GCC.
01051     MaybeParseGNUAttributes(Attr, &DeclEndLoc);
01052 
01053     // Parse 'mutable'[opt].
01054     SourceLocation MutableLoc;
01055     if (TryConsumeToken(tok::kw_mutable, MutableLoc))
01056       DeclEndLoc = MutableLoc;
01057 
01058     // Parse exception-specification[opt].
01059     ExceptionSpecificationType ESpecType = EST_None;
01060     SourceRange ESpecRange;
01061     SmallVector<ParsedType, 2> DynamicExceptions;
01062     SmallVector<SourceRange, 2> DynamicExceptionRanges;
01063     ExprResult NoexceptExpr;
01064     CachedTokens *ExceptionSpecTokens;
01065     ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
01066                                                ESpecRange,
01067                                                DynamicExceptions,
01068                                                DynamicExceptionRanges,
01069                                                NoexceptExpr,
01070                                                ExceptionSpecTokens);
01071 
01072     if (ESpecType != EST_None)
01073       DeclEndLoc = ESpecRange.getEnd();
01074 
01075     // Parse attribute-specifier[opt].
01076     MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
01077 
01078     SourceLocation FunLocalRangeEnd = DeclEndLoc;
01079 
01080     // Parse trailing-return-type[opt].
01081     TypeResult TrailingReturnType;
01082     if (Tok.is(tok::arrow)) {
01083       FunLocalRangeEnd = Tok.getLocation();
01084       SourceRange Range;
01085       TrailingReturnType = ParseTrailingReturnType(Range);
01086       if (Range.getEnd().isValid())
01087         DeclEndLoc = Range.getEnd();
01088     }
01089 
01090     PrototypeScope.Exit();
01091 
01092     SourceLocation NoLoc;
01093     D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
01094                                            /*isAmbiguous=*/false,
01095                                            LParenLoc,
01096                                            ParamInfo.data(), ParamInfo.size(),
01097                                            EllipsisLoc, RParenLoc,
01098                                            DS.getTypeQualifiers(),
01099                                            /*RefQualifierIsLValueRef=*/true,
01100                                            /*RefQualifierLoc=*/NoLoc,
01101                                            /*ConstQualifierLoc=*/NoLoc,
01102                                            /*VolatileQualifierLoc=*/NoLoc,
01103                                            /*RestrictQualifierLoc=*/NoLoc,
01104                                            MutableLoc,
01105                                            ESpecType, ESpecRange.getBegin(),
01106                                            DynamicExceptions.data(),
01107                                            DynamicExceptionRanges.data(),
01108                                            DynamicExceptions.size(),
01109                                            NoexceptExpr.isUsable() ?
01110                                              NoexceptExpr.get() : nullptr,
01111                                            /*ExceptionSpecTokens*/nullptr,
01112                                            LParenLoc, FunLocalRangeEnd, D,
01113                                            TrailingReturnType),
01114                   Attr, DeclEndLoc);
01115   } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow) ||
01116              Tok.is(tok::kw___attribute) ||
01117              (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
01118     // It's common to forget that one needs '()' before 'mutable', an attribute
01119     // specifier, or the result type. Deal with this.
01120     unsigned TokKind = 0;
01121     switch (Tok.getKind()) {
01122     case tok::kw_mutable: TokKind = 0; break;
01123     case tok::arrow: TokKind = 1; break;
01124     case tok::kw___attribute:
01125     case tok::l_square: TokKind = 2; break;
01126     default: llvm_unreachable("Unknown token kind");
01127     }
01128 
01129     Diag(Tok, diag::err_lambda_missing_parens)
01130       << TokKind
01131       << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
01132     SourceLocation DeclLoc = Tok.getLocation();
01133     SourceLocation DeclEndLoc = DeclLoc;
01134 
01135     // GNU-style attributes must be parsed before the mutable specifier to be
01136     // compatible with GCC.
01137     ParsedAttributes Attr(AttrFactory);
01138     MaybeParseGNUAttributes(Attr, &DeclEndLoc);
01139 
01140     // Parse 'mutable', if it's there.
01141     SourceLocation MutableLoc;
01142     if (Tok.is(tok::kw_mutable)) {
01143       MutableLoc = ConsumeToken();
01144       DeclEndLoc = MutableLoc;
01145     }
01146 
01147     // Parse attribute-specifier[opt].
01148     MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
01149 
01150     // Parse the return type, if there is one.
01151     TypeResult TrailingReturnType;
01152     if (Tok.is(tok::arrow)) {
01153       SourceRange Range;
01154       TrailingReturnType = ParseTrailingReturnType(Range);
01155       if (Range.getEnd().isValid())
01156         DeclEndLoc = Range.getEnd();      
01157     }
01158 
01159     SourceLocation NoLoc;
01160     D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
01161                                                /*isAmbiguous=*/false,
01162                                                /*LParenLoc=*/NoLoc,
01163                                                /*Params=*/nullptr,
01164                                                /*NumParams=*/0,
01165                                                /*EllipsisLoc=*/NoLoc,
01166                                                /*RParenLoc=*/NoLoc,
01167                                                /*TypeQuals=*/0,
01168                                                /*RefQualifierIsLValueRef=*/true,
01169                                                /*RefQualifierLoc=*/NoLoc,
01170                                                /*ConstQualifierLoc=*/NoLoc,
01171                                                /*VolatileQualifierLoc=*/NoLoc,
01172                                                /*RestrictQualifierLoc=*/NoLoc,
01173                                                MutableLoc,
01174                                                EST_None,
01175                                                /*ESpecLoc=*/NoLoc,
01176                                                /*Exceptions=*/nullptr,
01177                                                /*ExceptionRanges=*/nullptr,
01178                                                /*NumExceptions=*/0,
01179                                                /*NoexceptExpr=*/nullptr,
01180                                                /*ExceptionSpecTokens=*/nullptr,
01181                                                DeclLoc, DeclEndLoc, D,
01182                                                TrailingReturnType),
01183                   Attr, DeclEndLoc);
01184   }
01185   
01186 
01187   // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
01188   // it.
01189   unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
01190   ParseScope BodyScope(this, ScopeFlags);
01191 
01192   Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
01193 
01194   // Parse compound-statement.
01195   if (!Tok.is(tok::l_brace)) {
01196     Diag(Tok, diag::err_expected_lambda_body);
01197     Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
01198     return ExprError();
01199   }
01200 
01201   StmtResult Stmt(ParseCompoundStatementBody());
01202   BodyScope.Exit();
01203 
01204   if (!Stmt.isInvalid())
01205     return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
01206  
01207   Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
01208   return ExprError();
01209 }
01210 
01211 /// ParseCXXCasts - This handles the various ways to cast expressions to another
01212 /// type.
01213 ///
01214 ///       postfix-expression: [C++ 5.2p1]
01215 ///         'dynamic_cast' '<' type-name '>' '(' expression ')'
01216 ///         'static_cast' '<' type-name '>' '(' expression ')'
01217 ///         'reinterpret_cast' '<' type-name '>' '(' expression ')'
01218 ///         'const_cast' '<' type-name '>' '(' expression ')'
01219 ///
01220 ExprResult Parser::ParseCXXCasts() {
01221   tok::TokenKind Kind = Tok.getKind();
01222   const char *CastName = nullptr; // For error messages
01223 
01224   switch (Kind) {
01225   default: llvm_unreachable("Unknown C++ cast!");
01226   case tok::kw_const_cast:       CastName = "const_cast";       break;
01227   case tok::kw_dynamic_cast:     CastName = "dynamic_cast";     break;
01228   case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
01229   case tok::kw_static_cast:      CastName = "static_cast";      break;
01230   }
01231 
01232   SourceLocation OpLoc = ConsumeToken();
01233   SourceLocation LAngleBracketLoc = Tok.getLocation();
01234 
01235   // Check for "<::" which is parsed as "[:".  If found, fix token stream,
01236   // diagnose error, suggest fix, and recover parsing.
01237   if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
01238     Token Next = NextToken();
01239     if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
01240       FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
01241   }
01242 
01243   if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
01244     return ExprError();
01245 
01246   // Parse the common declaration-specifiers piece.
01247   DeclSpec DS(AttrFactory);
01248   ParseSpecifierQualifierList(DS);
01249 
01250   // Parse the abstract-declarator, if present.
01251   Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
01252   ParseDeclarator(DeclaratorInfo);
01253 
01254   SourceLocation RAngleBracketLoc = Tok.getLocation();
01255 
01256   if (ExpectAndConsume(tok::greater))
01257     return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
01258 
01259   SourceLocation LParenLoc, RParenLoc;
01260   BalancedDelimiterTracker T(*this, tok::l_paren);
01261 
01262   if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
01263     return ExprError();
01264 
01265   ExprResult Result = ParseExpression();
01266 
01267   // Match the ')'.
01268   T.consumeClose();
01269 
01270   if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
01271     Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
01272                                        LAngleBracketLoc, DeclaratorInfo,
01273                                        RAngleBracketLoc,
01274                                        T.getOpenLocation(), Result.get(), 
01275                                        T.getCloseLocation());
01276 
01277   return Result;
01278 }
01279 
01280 /// ParseCXXTypeid - This handles the C++ typeid expression.
01281 ///
01282 ///       postfix-expression: [C++ 5.2p1]
01283 ///         'typeid' '(' expression ')'
01284 ///         'typeid' '(' type-id ')'
01285 ///
01286 ExprResult Parser::ParseCXXTypeid() {
01287   assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
01288 
01289   SourceLocation OpLoc = ConsumeToken();
01290   SourceLocation LParenLoc, RParenLoc;
01291   BalancedDelimiterTracker T(*this, tok::l_paren);
01292 
01293   // typeid expressions are always parenthesized.
01294   if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
01295     return ExprError();
01296   LParenLoc = T.getOpenLocation();
01297 
01298   ExprResult Result;
01299 
01300   // C++0x [expr.typeid]p3:
01301   //   When typeid is applied to an expression other than an lvalue of a
01302   //   polymorphic class type [...] The expression is an unevaluated
01303   //   operand (Clause 5).
01304   //
01305   // Note that we can't tell whether the expression is an lvalue of a
01306   // polymorphic class type until after we've parsed the expression; we
01307   // speculatively assume the subexpression is unevaluated, and fix it up
01308   // later.
01309   //
01310   // We enter the unevaluated context before trying to determine whether we
01311   // have a type-id, because the tentative parse logic will try to resolve
01312   // names, and must treat them as unevaluated.
01313   EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
01314                                                Sema::ReuseLambdaContextDecl);
01315 
01316   if (isTypeIdInParens()) {
01317     TypeResult Ty = ParseTypeName();
01318 
01319     // Match the ')'.
01320     T.consumeClose();
01321     RParenLoc = T.getCloseLocation();
01322     if (Ty.isInvalid() || RParenLoc.isInvalid())
01323       return ExprError();
01324 
01325     Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
01326                                     Ty.get().getAsOpaquePtr(), RParenLoc);
01327   } else {
01328     Result = ParseExpression();
01329 
01330     // Match the ')'.
01331     if (Result.isInvalid())
01332       SkipUntil(tok::r_paren, StopAtSemi);
01333     else {
01334       T.consumeClose();
01335       RParenLoc = T.getCloseLocation();
01336       if (RParenLoc.isInvalid())
01337         return ExprError();
01338 
01339       Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
01340                                       Result.get(), RParenLoc);
01341     }
01342   }
01343 
01344   return Result;
01345 }
01346 
01347 /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
01348 ///
01349 ///         '__uuidof' '(' expression ')'
01350 ///         '__uuidof' '(' type-id ')'
01351 ///
01352 ExprResult Parser::ParseCXXUuidof() {
01353   assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
01354 
01355   SourceLocation OpLoc = ConsumeToken();
01356   BalancedDelimiterTracker T(*this, tok::l_paren);
01357 
01358   // __uuidof expressions are always parenthesized.
01359   if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
01360     return ExprError();
01361 
01362   ExprResult Result;
01363 
01364   if (isTypeIdInParens()) {
01365     TypeResult Ty = ParseTypeName();
01366 
01367     // Match the ')'.
01368     T.consumeClose();
01369 
01370     if (Ty.isInvalid())
01371       return ExprError();
01372 
01373     Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
01374                                     Ty.get().getAsOpaquePtr(), 
01375                                     T.getCloseLocation());
01376   } else {
01377     EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
01378     Result = ParseExpression();
01379 
01380     // Match the ')'.
01381     if (Result.isInvalid())
01382       SkipUntil(tok::r_paren, StopAtSemi);
01383     else {
01384       T.consumeClose();
01385 
01386       Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
01387                                       /*isType=*/false,
01388                                       Result.get(), T.getCloseLocation());
01389     }
01390   }
01391 
01392   return Result;
01393 }
01394 
01395 /// \brief Parse a C++ pseudo-destructor expression after the base,
01396 /// . or -> operator, and nested-name-specifier have already been
01397 /// parsed.
01398 ///
01399 ///       postfix-expression: [C++ 5.2]
01400 ///         postfix-expression . pseudo-destructor-name
01401 ///         postfix-expression -> pseudo-destructor-name
01402 ///
01403 ///       pseudo-destructor-name: 
01404 ///         ::[opt] nested-name-specifier[opt] type-name :: ~type-name 
01405 ///         ::[opt] nested-name-specifier template simple-template-id :: 
01406 ///                 ~type-name 
01407 ///         ::[opt] nested-name-specifier[opt] ~type-name
01408 ///       
01409 ExprResult 
01410 Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
01411                                  tok::TokenKind OpKind,
01412                                  CXXScopeSpec &SS,
01413                                  ParsedType ObjectType) {
01414   // We're parsing either a pseudo-destructor-name or a dependent
01415   // member access that has the same form as a
01416   // pseudo-destructor-name. We parse both in the same way and let
01417   // the action model sort them out.
01418   //
01419   // Note that the ::[opt] nested-name-specifier[opt] has already
01420   // been parsed, and if there was a simple-template-id, it has
01421   // been coalesced into a template-id annotation token.
01422   UnqualifiedId FirstTypeName;
01423   SourceLocation CCLoc;
01424   if (Tok.is(tok::identifier)) {
01425     FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
01426     ConsumeToken();
01427     assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
01428     CCLoc = ConsumeToken();
01429   } else if (Tok.is(tok::annot_template_id)) {
01430     // FIXME: retrieve TemplateKWLoc from template-id annotation and
01431     // store it in the pseudo-dtor node (to be used when instantiating it).
01432     FirstTypeName.setTemplateId(
01433                               (TemplateIdAnnotation *)Tok.getAnnotationValue());
01434     ConsumeToken();
01435     assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
01436     CCLoc = ConsumeToken();
01437   } else {
01438     FirstTypeName.setIdentifier(nullptr, SourceLocation());
01439   }
01440 
01441   // Parse the tilde.
01442   assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
01443   SourceLocation TildeLoc = ConsumeToken();
01444 
01445   if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
01446     DeclSpec DS(AttrFactory);
01447     ParseDecltypeSpecifier(DS);
01448     if (DS.getTypeSpecType() == TST_error)
01449       return ExprError();
01450     return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, 
01451                                              OpKind, TildeLoc, DS, 
01452                                              Tok.is(tok::l_paren));
01453   }
01454 
01455   if (!Tok.is(tok::identifier)) {
01456     Diag(Tok, diag::err_destructor_tilde_identifier);
01457     return ExprError();
01458   }
01459   
01460   // Parse the second type.
01461   UnqualifiedId SecondTypeName;
01462   IdentifierInfo *Name = Tok.getIdentifierInfo();
01463   SourceLocation NameLoc = ConsumeToken();
01464   SecondTypeName.setIdentifier(Name, NameLoc);
01465   
01466   // If there is a '<', the second type name is a template-id. Parse
01467   // it as such.
01468   if (Tok.is(tok::less) &&
01469       ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
01470                                    Name, NameLoc,
01471                                    false, ObjectType, SecondTypeName,
01472                                    /*AssumeTemplateName=*/true))
01473     return ExprError();
01474 
01475   return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
01476                                            OpLoc, OpKind,
01477                                            SS, FirstTypeName, CCLoc,
01478                                            TildeLoc, SecondTypeName,
01479                                            Tok.is(tok::l_paren));
01480 }
01481 
01482 /// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
01483 ///
01484 ///       boolean-literal: [C++ 2.13.5]
01485 ///         'true'
01486 ///         'false'
01487 ExprResult Parser::ParseCXXBoolLiteral() {
01488   tok::TokenKind Kind = Tok.getKind();
01489   return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
01490 }
01491 
01492 /// ParseThrowExpression - This handles the C++ throw expression.
01493 ///
01494 ///       throw-expression: [C++ 15]
01495 ///         'throw' assignment-expression[opt]
01496 ExprResult Parser::ParseThrowExpression() {
01497   assert(Tok.is(tok::kw_throw) && "Not throw!");
01498   SourceLocation ThrowLoc = ConsumeToken();           // Eat the throw token.
01499 
01500   // If the current token isn't the start of an assignment-expression,
01501   // then the expression is not present.  This handles things like:
01502   //   "C ? throw : (void)42", which is crazy but legal.
01503   switch (Tok.getKind()) {  // FIXME: move this predicate somewhere common.
01504   case tok::semi:
01505   case tok::r_paren:
01506   case tok::r_square:
01507   case tok::r_brace:
01508   case tok::colon:
01509   case tok::comma:
01510     return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
01511 
01512   default:
01513     ExprResult Expr(ParseAssignmentExpression());
01514     if (Expr.isInvalid()) return Expr;
01515     return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
01516   }
01517 }
01518 
01519 /// ParseCXXThis - This handles the C++ 'this' pointer.
01520 ///
01521 /// C++ 9.3.2: In the body of a non-static member function, the keyword this is
01522 /// a non-lvalue expression whose value is the address of the object for which
01523 /// the function is called.
01524 ExprResult Parser::ParseCXXThis() {
01525   assert(Tok.is(tok::kw_this) && "Not 'this'!");
01526   SourceLocation ThisLoc = ConsumeToken();
01527   return Actions.ActOnCXXThis(ThisLoc);
01528 }
01529 
01530 /// ParseCXXTypeConstructExpression - Parse construction of a specified type.
01531 /// Can be interpreted either as function-style casting ("int(x)")
01532 /// or class type construction ("ClassType(x,y,z)")
01533 /// or creation of a value-initialized type ("int()").
01534 /// See [C++ 5.2.3].
01535 ///
01536 ///       postfix-expression: [C++ 5.2p1]
01537 ///         simple-type-specifier '(' expression-list[opt] ')'
01538 /// [C++0x] simple-type-specifier braced-init-list
01539 ///         typename-specifier '(' expression-list[opt] ')'
01540 /// [C++0x] typename-specifier braced-init-list
01541 ///
01542 ExprResult
01543 Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
01544   Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
01545   ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
01546 
01547   assert((Tok.is(tok::l_paren) ||
01548           (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
01549          && "Expected '(' or '{'!");
01550 
01551   if (Tok.is(tok::l_brace)) {
01552     ExprResult Init = ParseBraceInitializer();
01553     if (Init.isInvalid())
01554       return Init;
01555     Expr *InitList = Init.get();
01556     return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
01557                                              MultiExprArg(&InitList, 1),
01558                                              SourceLocation());
01559   } else {
01560     BalancedDelimiterTracker T(*this, tok::l_paren);
01561     T.consumeOpen();
01562 
01563     ExprVector Exprs;
01564     CommaLocsTy CommaLocs;
01565 
01566     if (Tok.isNot(tok::r_paren)) {
01567       if (ParseExpressionList(Exprs, CommaLocs)) {
01568         SkipUntil(tok::r_paren, StopAtSemi);
01569         return ExprError();
01570       }
01571     }
01572 
01573     // Match the ')'.
01574     T.consumeClose();
01575 
01576     // TypeRep could be null, if it references an invalid typedef.
01577     if (!TypeRep)
01578       return ExprError();
01579 
01580     assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
01581            "Unexpected number of commas!");
01582     return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(), 
01583                                              Exprs,
01584                                              T.getCloseLocation());
01585   }
01586 }
01587 
01588 /// ParseCXXCondition - if/switch/while condition expression.
01589 ///
01590 ///       condition:
01591 ///         expression
01592 ///         type-specifier-seq declarator '=' assignment-expression
01593 /// [C++11] type-specifier-seq declarator '=' initializer-clause
01594 /// [C++11] type-specifier-seq declarator braced-init-list
01595 /// [GNU]   type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
01596 ///             '=' assignment-expression
01597 ///
01598 /// \param ExprOut if the condition was parsed as an expression, the parsed
01599 /// expression.
01600 ///
01601 /// \param DeclOut if the condition was parsed as a declaration, the parsed
01602 /// declaration.
01603 ///
01604 /// \param Loc The location of the start of the statement that requires this
01605 /// condition, e.g., the "for" in a for loop.
01606 ///
01607 /// \param ConvertToBoolean Whether the condition expression should be
01608 /// converted to a boolean value.
01609 ///
01610 /// \returns true if there was a parsing, false otherwise.
01611 bool Parser::ParseCXXCondition(ExprResult &ExprOut,
01612                                Decl *&DeclOut,
01613                                SourceLocation Loc,
01614                                bool ConvertToBoolean) {
01615   if (Tok.is(tok::code_completion)) {
01616     Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
01617     cutOffParsing();
01618     return true;
01619   }
01620 
01621   ParsedAttributesWithRange attrs(AttrFactory);
01622   MaybeParseCXX11Attributes(attrs);
01623 
01624   if (!isCXXConditionDeclaration()) {
01625     ProhibitAttributes(attrs);
01626 
01627     // Parse the expression.
01628     ExprOut = ParseExpression(); // expression
01629     DeclOut = nullptr;
01630     if (ExprOut.isInvalid())
01631       return true;
01632 
01633     // If required, convert to a boolean value.
01634     if (ConvertToBoolean)
01635       ExprOut
01636         = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
01637     return ExprOut.isInvalid();
01638   }
01639 
01640   // type-specifier-seq
01641   DeclSpec DS(AttrFactory);
01642   DS.takeAttributesFrom(attrs);
01643   ParseSpecifierQualifierList(DS);
01644 
01645   // declarator
01646   Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
01647   ParseDeclarator(DeclaratorInfo);
01648 
01649   // simple-asm-expr[opt]
01650   if (Tok.is(tok::kw_asm)) {
01651     SourceLocation Loc;
01652     ExprResult AsmLabel(ParseSimpleAsm(&Loc));
01653     if (AsmLabel.isInvalid()) {
01654       SkipUntil(tok::semi, StopAtSemi);
01655       return true;
01656     }
01657     DeclaratorInfo.setAsmLabel(AsmLabel.get());
01658     DeclaratorInfo.SetRangeEnd(Loc);
01659   }
01660 
01661   // If attributes are present, parse them.
01662   MaybeParseGNUAttributes(DeclaratorInfo);
01663 
01664   // Type-check the declaration itself.
01665   DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(), 
01666                                                         DeclaratorInfo);
01667   DeclOut = Dcl.get();
01668   ExprOut = ExprError();
01669 
01670   // '=' assignment-expression
01671   // If a '==' or '+=' is found, suggest a fixit to '='.
01672   bool CopyInitialization = isTokenEqualOrEqualTypo();
01673   if (CopyInitialization)
01674     ConsumeToken();
01675 
01676   ExprResult InitExpr = ExprError();
01677   if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
01678     Diag(Tok.getLocation(),
01679          diag::warn_cxx98_compat_generalized_initializer_lists);
01680     InitExpr = ParseBraceInitializer();
01681   } else if (CopyInitialization) {
01682     InitExpr = ParseAssignmentExpression();
01683   } else if (Tok.is(tok::l_paren)) {
01684     // This was probably an attempt to initialize the variable.
01685     SourceLocation LParen = ConsumeParen(), RParen = LParen;
01686     if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
01687       RParen = ConsumeParen();
01688     Diag(DeclOut ? DeclOut->getLocation() : LParen,
01689          diag::err_expected_init_in_condition_lparen)
01690       << SourceRange(LParen, RParen);
01691   } else {
01692     Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
01693          diag::err_expected_init_in_condition);
01694   }
01695 
01696   if (!InitExpr.isInvalid())
01697     Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization,
01698                                  DS.containsPlaceholderType());
01699   else
01700     Actions.ActOnInitializerError(DeclOut);
01701 
01702   // FIXME: Build a reference to this declaration? Convert it to bool?
01703   // (This is currently handled by Sema).
01704 
01705   Actions.FinalizeDeclaration(DeclOut);
01706   
01707   return false;
01708 }
01709 
01710 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
01711 /// This should only be called when the current token is known to be part of
01712 /// simple-type-specifier.
01713 ///
01714 ///       simple-type-specifier:
01715 ///         '::'[opt] nested-name-specifier[opt] type-name
01716 ///         '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
01717 ///         char
01718 ///         wchar_t
01719 ///         bool
01720 ///         short
01721 ///         int
01722 ///         long
01723 ///         signed
01724 ///         unsigned
01725 ///         float
01726 ///         double
01727 ///         void
01728 /// [GNU]   typeof-specifier
01729 /// [C++0x] auto               [TODO]
01730 ///
01731 ///       type-name:
01732 ///         class-name
01733 ///         enum-name
01734 ///         typedef-name
01735 ///
01736 void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
01737   DS.SetRangeStart(Tok.getLocation());
01738   const char *PrevSpec;
01739   unsigned DiagID;
01740   SourceLocation Loc = Tok.getLocation();
01741   const clang::PrintingPolicy &Policy =
01742       Actions.getASTContext().getPrintingPolicy();
01743 
01744   switch (Tok.getKind()) {
01745   case tok::identifier:   // foo::bar
01746   case tok::coloncolon:   // ::foo::bar
01747     llvm_unreachable("Annotation token should already be formed!");
01748   default:
01749     llvm_unreachable("Not a simple-type-specifier token!");
01750 
01751   // type-name
01752   case tok::annot_typename: {
01753     if (getTypeAnnotation(Tok))
01754       DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
01755                          getTypeAnnotation(Tok), Policy);
01756     else
01757       DS.SetTypeSpecError();
01758     
01759     DS.SetRangeEnd(Tok.getAnnotationEndLoc());
01760     ConsumeToken();
01761     
01762     // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
01763     // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
01764     // Objective-C interface.  If we don't have Objective-C or a '<', this is
01765     // just a normal reference to a typedef name.
01766     if (Tok.is(tok::less) && getLangOpts().ObjC1)
01767       ParseObjCProtocolQualifiers(DS);
01768     
01769     DS.Finish(Diags, PP, Policy);
01770     return;
01771   }
01772 
01773   // builtin types
01774   case tok::kw_short:
01775     DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
01776     break;
01777   case tok::kw_long:
01778     DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
01779     break;
01780   case tok::kw___int64:
01781     DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
01782     break;
01783   case tok::kw_signed:
01784     DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
01785     break;
01786   case tok::kw_unsigned:
01787     DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
01788     break;
01789   case tok::kw_void:
01790     DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
01791     break;
01792   case tok::kw_char:
01793     DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
01794     break;
01795   case tok::kw_int:
01796     DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
01797     break;
01798   case tok::kw___int128:
01799     DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
01800     break;
01801   case tok::kw_half:
01802     DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
01803     break;
01804   case tok::kw_float:
01805     DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
01806     break;
01807   case tok::kw_double:
01808     DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
01809     break;
01810   case tok::kw_wchar_t:
01811     DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
01812     break;
01813   case tok::kw_char16_t:
01814     DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
01815     break;
01816   case tok::kw_char32_t:
01817     DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
01818     break;
01819   case tok::kw_bool:
01820     DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
01821     break;
01822   case tok::annot_decltype:
01823   case tok::kw_decltype:
01824     DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
01825     return DS.Finish(Diags, PP, Policy);
01826 
01827   // GNU typeof support.
01828   case tok::kw_typeof:
01829     ParseTypeofSpecifier(DS);
01830     DS.Finish(Diags, PP, Policy);
01831     return;
01832   }
01833   if (Tok.is(tok::annot_typename))
01834     DS.SetRangeEnd(Tok.getAnnotationEndLoc());
01835   else
01836     DS.SetRangeEnd(Tok.getLocation());
01837   ConsumeToken();
01838   DS.Finish(Diags, PP, Policy);
01839 }
01840 
01841 /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
01842 /// [dcl.name]), which is a non-empty sequence of type-specifiers,
01843 /// e.g., "const short int". Note that the DeclSpec is *not* finished
01844 /// by parsing the type-specifier-seq, because these sequences are
01845 /// typically followed by some form of declarator. Returns true and
01846 /// emits diagnostics if this is not a type-specifier-seq, false
01847 /// otherwise.
01848 ///
01849 ///   type-specifier-seq: [C++ 8.1]
01850 ///     type-specifier type-specifier-seq[opt]
01851 ///
01852 bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
01853   ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
01854   DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy());
01855   return false;
01856 }
01857 
01858 /// \brief Finish parsing a C++ unqualified-id that is a template-id of
01859 /// some form. 
01860 ///
01861 /// This routine is invoked when a '<' is encountered after an identifier or
01862 /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
01863 /// whether the unqualified-id is actually a template-id. This routine will
01864 /// then parse the template arguments and form the appropriate template-id to
01865 /// return to the caller.
01866 ///
01867 /// \param SS the nested-name-specifier that precedes this template-id, if
01868 /// we're actually parsing a qualified-id.
01869 ///
01870 /// \param Name for constructor and destructor names, this is the actual
01871 /// identifier that may be a template-name.
01872 ///
01873 /// \param NameLoc the location of the class-name in a constructor or 
01874 /// destructor.
01875 ///
01876 /// \param EnteringContext whether we're entering the scope of the 
01877 /// nested-name-specifier.
01878 ///
01879 /// \param ObjectType if this unqualified-id occurs within a member access
01880 /// expression, the type of the base object whose member is being accessed.
01881 ///
01882 /// \param Id as input, describes the template-name or operator-function-id
01883 /// that precedes the '<'. If template arguments were parsed successfully,
01884 /// will be updated with the template-id.
01885 /// 
01886 /// \param AssumeTemplateId When true, this routine will assume that the name
01887 /// refers to a template without performing name lookup to verify. 
01888 ///
01889 /// \returns true if a parse error occurred, false otherwise.
01890 bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
01891                                           SourceLocation TemplateKWLoc,
01892                                           IdentifierInfo *Name,
01893                                           SourceLocation NameLoc,
01894                                           bool EnteringContext,
01895                                           ParsedType ObjectType,
01896                                           UnqualifiedId &Id,
01897                                           bool AssumeTemplateId) {
01898   assert((AssumeTemplateId || Tok.is(tok::less)) &&
01899          "Expected '<' to finish parsing a template-id");
01900   
01901   TemplateTy Template;
01902   TemplateNameKind TNK = TNK_Non_template;
01903   switch (Id.getKind()) {
01904   case UnqualifiedId::IK_Identifier:
01905   case UnqualifiedId::IK_OperatorFunctionId:
01906   case UnqualifiedId::IK_LiteralOperatorId:
01907     if (AssumeTemplateId) {
01908       TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
01909                                                Id, ObjectType, EnteringContext,
01910                                                Template);
01911       if (TNK == TNK_Non_template)
01912         return true;
01913     } else {
01914       bool MemberOfUnknownSpecialization;
01915       TNK = Actions.isTemplateName(getCurScope(), SS,
01916                                    TemplateKWLoc.isValid(), Id,
01917                                    ObjectType, EnteringContext, Template,
01918                                    MemberOfUnknownSpecialization);
01919       
01920       if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
01921           ObjectType && IsTemplateArgumentList()) {
01922         // We have something like t->getAs<T>(), where getAs is a 
01923         // member of an unknown specialization. However, this will only
01924         // parse correctly as a template, so suggest the keyword 'template'
01925         // before 'getAs' and treat this as a dependent template name.
01926         std::string Name;
01927         if (Id.getKind() == UnqualifiedId::IK_Identifier)
01928           Name = Id.Identifier->getName();
01929         else {
01930           Name = "operator ";
01931           if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
01932             Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
01933           else
01934             Name += Id.Identifier->getName();
01935         }
01936         Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
01937           << Name
01938           << FixItHint::CreateInsertion(Id.StartLocation, "template ");
01939         TNK = Actions.ActOnDependentTemplateName(getCurScope(),
01940                                                  SS, TemplateKWLoc, Id,
01941                                                  ObjectType, EnteringContext,
01942                                                  Template);
01943         if (TNK == TNK_Non_template)
01944           return true;              
01945       }
01946     }
01947     break;
01948       
01949   case UnqualifiedId::IK_ConstructorName: {
01950     UnqualifiedId TemplateName;
01951     bool MemberOfUnknownSpecialization;
01952     TemplateName.setIdentifier(Name, NameLoc);
01953     TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
01954                                  TemplateName, ObjectType, 
01955                                  EnteringContext, Template,
01956                                  MemberOfUnknownSpecialization);
01957     break;
01958   }
01959       
01960   case UnqualifiedId::IK_DestructorName: {
01961     UnqualifiedId TemplateName;
01962     bool MemberOfUnknownSpecialization;
01963     TemplateName.setIdentifier(Name, NameLoc);
01964     if (ObjectType) {
01965       TNK = Actions.ActOnDependentTemplateName(getCurScope(),
01966                                                SS, TemplateKWLoc, TemplateName,
01967                                                ObjectType, EnteringContext,
01968                                                Template);
01969       if (TNK == TNK_Non_template)
01970         return true;
01971     } else {
01972       TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
01973                                    TemplateName, ObjectType, 
01974                                    EnteringContext, Template,
01975                                    MemberOfUnknownSpecialization);
01976       
01977       if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
01978         Diag(NameLoc, diag::err_destructor_template_id)
01979           << Name << SS.getRange();
01980         return true;        
01981       }
01982     }
01983     break;
01984   }
01985       
01986   default:
01987     return false;
01988   }
01989   
01990   if (TNK == TNK_Non_template)
01991     return false;
01992   
01993   // Parse the enclosed template argument list.
01994   SourceLocation LAngleLoc, RAngleLoc;
01995   TemplateArgList TemplateArgs;
01996   if (Tok.is(tok::less) &&
01997       ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
01998                                        SS, true, LAngleLoc,
01999                                        TemplateArgs,
02000                                        RAngleLoc))
02001     return true;
02002   
02003   if (Id.getKind() == UnqualifiedId::IK_Identifier ||
02004       Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
02005       Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
02006     // Form a parsed representation of the template-id to be stored in the
02007     // UnqualifiedId.
02008     TemplateIdAnnotation *TemplateId
02009       = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
02010 
02011     // FIXME: Store name for literal operator too.
02012     if (Id.getKind() == UnqualifiedId::IK_Identifier) {
02013       TemplateId->Name = Id.Identifier;
02014       TemplateId->Operator = OO_None;
02015       TemplateId->TemplateNameLoc = Id.StartLocation;
02016     } else {
02017       TemplateId->Name = nullptr;
02018       TemplateId->Operator = Id.OperatorFunctionId.Operator;
02019       TemplateId->TemplateNameLoc = Id.StartLocation;
02020     }
02021 
02022     TemplateId->SS = SS;
02023     TemplateId->TemplateKWLoc = TemplateKWLoc;
02024     TemplateId->Template = Template;
02025     TemplateId->Kind = TNK;
02026     TemplateId->LAngleLoc = LAngleLoc;
02027     TemplateId->RAngleLoc = RAngleLoc;
02028     ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
02029     for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); 
02030          Arg != ArgEnd; ++Arg)
02031       Args[Arg] = TemplateArgs[Arg];
02032     
02033     Id.setTemplateId(TemplateId);
02034     return false;
02035   }
02036 
02037   // Bundle the template arguments together.
02038   ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
02039 
02040   // Constructor and destructor names.
02041   TypeResult Type
02042     = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
02043                                   Template, NameLoc,
02044                                   LAngleLoc, TemplateArgsPtr, RAngleLoc,
02045                                   /*IsCtorOrDtorName=*/true);
02046   if (Type.isInvalid())
02047     return true;
02048   
02049   if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
02050     Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
02051   else
02052     Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
02053   
02054   return false;
02055 }
02056 
02057 /// \brief Parse an operator-function-id or conversion-function-id as part
02058 /// of a C++ unqualified-id.
02059 ///
02060 /// This routine is responsible only for parsing the operator-function-id or
02061 /// conversion-function-id; it does not handle template arguments in any way.
02062 ///
02063 /// \code
02064 ///       operator-function-id: [C++ 13.5]
02065 ///         'operator' operator
02066 ///
02067 ///       operator: one of
02068 ///            new   delete  new[]   delete[]
02069 ///            +     -    *  /    %  ^    &   |   ~
02070 ///            !     =    <  >    += -=   *=  /=  %=
02071 ///            ^=    &=   |= <<   >> >>= <<=  ==  !=
02072 ///            <=    >=   && ||   ++ --   ,   ->* ->
02073 ///            ()    []
02074 ///
02075 ///       conversion-function-id: [C++ 12.3.2]
02076 ///         operator conversion-type-id
02077 ///
02078 ///       conversion-type-id:
02079 ///         type-specifier-seq conversion-declarator[opt]
02080 ///
02081 ///       conversion-declarator:
02082 ///         ptr-operator conversion-declarator[opt]
02083 /// \endcode
02084 ///
02085 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
02086 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
02087 ///
02088 /// \param EnteringContext whether we are entering the scope of the 
02089 /// nested-name-specifier.
02090 ///
02091 /// \param ObjectType if this unqualified-id occurs within a member access
02092 /// expression, the type of the base object whose member is being accessed.
02093 ///
02094 /// \param Result on a successful parse, contains the parsed unqualified-id.
02095 ///
02096 /// \returns true if parsing fails, false otherwise.
02097 bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
02098                                         ParsedType ObjectType,
02099                                         UnqualifiedId &Result) {
02100   assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
02101   
02102   // Consume the 'operator' keyword.
02103   SourceLocation KeywordLoc = ConsumeToken();
02104   
02105   // Determine what kind of operator name we have.
02106   unsigned SymbolIdx = 0;
02107   SourceLocation SymbolLocations[3];
02108   OverloadedOperatorKind Op = OO_None;
02109   switch (Tok.getKind()) {
02110     case tok::kw_new:
02111     case tok::kw_delete: {
02112       bool isNew = Tok.getKind() == tok::kw_new;
02113       // Consume the 'new' or 'delete'.
02114       SymbolLocations[SymbolIdx++] = ConsumeToken();
02115       // Check for array new/delete.
02116       if (Tok.is(tok::l_square) &&
02117           (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
02118         // Consume the '[' and ']'.
02119         BalancedDelimiterTracker T(*this, tok::l_square);
02120         T.consumeOpen();
02121         T.consumeClose();
02122         if (T.getCloseLocation().isInvalid())
02123           return true;
02124         
02125         SymbolLocations[SymbolIdx++] = T.getOpenLocation();
02126         SymbolLocations[SymbolIdx++] = T.getCloseLocation();
02127         Op = isNew? OO_Array_New : OO_Array_Delete;
02128       } else {
02129         Op = isNew? OO_New : OO_Delete;
02130       }
02131       break;
02132     }
02133       
02134 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
02135     case tok::Token:                                                     \
02136       SymbolLocations[SymbolIdx++] = ConsumeToken();                     \
02137       Op = OO_##Name;                                                    \
02138       break;
02139 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
02140 #include "clang/Basic/OperatorKinds.def"
02141       
02142     case tok::l_paren: {
02143       // Consume the '(' and ')'.
02144       BalancedDelimiterTracker T(*this, tok::l_paren);
02145       T.consumeOpen();
02146       T.consumeClose();
02147       if (T.getCloseLocation().isInvalid())
02148         return true;
02149       
02150       SymbolLocations[SymbolIdx++] = T.getOpenLocation();
02151       SymbolLocations[SymbolIdx++] = T.getCloseLocation();
02152       Op = OO_Call;
02153       break;
02154     }
02155       
02156     case tok::l_square: {
02157       // Consume the '[' and ']'.
02158       BalancedDelimiterTracker T(*this, tok::l_square);
02159       T.consumeOpen();
02160       T.consumeClose();
02161       if (T.getCloseLocation().isInvalid())
02162         return true;
02163       
02164       SymbolLocations[SymbolIdx++] = T.getOpenLocation();
02165       SymbolLocations[SymbolIdx++] = T.getCloseLocation();
02166       Op = OO_Subscript;
02167       break;
02168     }
02169       
02170     case tok::code_completion: {
02171       // Code completion for the operator name.
02172       Actions.CodeCompleteOperatorName(getCurScope());
02173       cutOffParsing();      
02174       // Don't try to parse any further.
02175       return true;
02176     }
02177       
02178     default:
02179       break;
02180   }
02181   
02182   if (Op != OO_None) {
02183     // We have parsed an operator-function-id.
02184     Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
02185     return false;
02186   }
02187 
02188   // Parse a literal-operator-id.
02189   //
02190   //   literal-operator-id: C++11 [over.literal]
02191   //     operator string-literal identifier
02192   //     operator user-defined-string-literal
02193 
02194   if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
02195     Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
02196 
02197     SourceLocation DiagLoc;
02198     unsigned DiagId = 0;
02199 
02200     // We're past translation phase 6, so perform string literal concatenation
02201     // before checking for "".
02202     SmallVector<Token, 4> Toks;
02203     SmallVector<SourceLocation, 4> TokLocs;
02204     while (isTokenStringLiteral()) {
02205       if (!Tok.is(tok::string_literal) && !DiagId) {
02206         // C++11 [over.literal]p1:
02207         //   The string-literal or user-defined-string-literal in a
02208         //   literal-operator-id shall have no encoding-prefix [...].
02209         DiagLoc = Tok.getLocation();
02210         DiagId = diag::err_literal_operator_string_prefix;
02211       }
02212       Toks.push_back(Tok);
02213       TokLocs.push_back(ConsumeStringToken());
02214     }
02215 
02216     StringLiteralParser Literal(Toks, PP);
02217     if (Literal.hadError)
02218       return true;
02219 
02220     // Grab the literal operator's suffix, which will be either the next token
02221     // or a ud-suffix from the string literal.
02222     IdentifierInfo *II = nullptr;
02223     SourceLocation SuffixLoc;
02224     if (!Literal.getUDSuffix().empty()) {
02225       II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
02226       SuffixLoc =
02227         Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
02228                                        Literal.getUDSuffixOffset(),
02229                                        PP.getSourceManager(), getLangOpts());
02230     } else if (Tok.is(tok::identifier)) {
02231       II = Tok.getIdentifierInfo();
02232       SuffixLoc = ConsumeToken();
02233       TokLocs.push_back(SuffixLoc);
02234     } else {
02235       Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
02236       return true;
02237     }
02238 
02239     // The string literal must be empty.
02240     if (!Literal.GetString().empty() || Literal.Pascal) {
02241       // C++11 [over.literal]p1:
02242       //   The string-literal or user-defined-string-literal in a
02243       //   literal-operator-id shall [...] contain no characters
02244       //   other than the implicit terminating '\0'.
02245       DiagLoc = TokLocs.front();
02246       DiagId = diag::err_literal_operator_string_not_empty;
02247     }
02248 
02249     if (DiagId) {
02250       // This isn't a valid literal-operator-id, but we think we know
02251       // what the user meant. Tell them what they should have written.
02252       SmallString<32> Str;
02253       Str += "\"\" ";
02254       Str += II->getName();
02255       Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
02256           SourceRange(TokLocs.front(), TokLocs.back()), Str);
02257     }
02258 
02259     Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
02260 
02261     return Actions.checkLiteralOperatorId(SS, Result);
02262   }
02263 
02264   // Parse a conversion-function-id.
02265   //
02266   //   conversion-function-id: [C++ 12.3.2]
02267   //     operator conversion-type-id
02268   //
02269   //   conversion-type-id:
02270   //     type-specifier-seq conversion-declarator[opt]
02271   //
02272   //   conversion-declarator:
02273   //     ptr-operator conversion-declarator[opt]
02274   
02275   // Parse the type-specifier-seq.
02276   DeclSpec DS(AttrFactory);
02277   if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
02278     return true;
02279   
02280   // Parse the conversion-declarator, which is merely a sequence of
02281   // ptr-operators.
02282   Declarator D(DS, Declarator::ConversionIdContext);
02283   ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
02284 
02285   // Finish up the type.
02286   TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
02287   if (Ty.isInvalid())
02288     return true;
02289   
02290   // Note that this is a conversion-function-id.
02291   Result.setConversionFunctionId(KeywordLoc, Ty.get(), 
02292                                  D.getSourceRange().getEnd());
02293   return false;  
02294 }
02295 
02296 /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
02297 /// name of an entity.
02298 ///
02299 /// \code
02300 ///       unqualified-id: [C++ expr.prim.general]
02301 ///         identifier
02302 ///         operator-function-id
02303 ///         conversion-function-id
02304 /// [C++0x] literal-operator-id [TODO]
02305 ///         ~ class-name
02306 ///         template-id
02307 ///
02308 /// \endcode
02309 ///
02310 /// \param SS The nested-name-specifier that preceded this unqualified-id. If
02311 /// non-empty, then we are parsing the unqualified-id of a qualified-id.
02312 ///
02313 /// \param EnteringContext whether we are entering the scope of the 
02314 /// nested-name-specifier.
02315 ///
02316 /// \param AllowDestructorName whether we allow parsing of a destructor name.
02317 ///
02318 /// \param AllowConstructorName whether we allow parsing a constructor name.
02319 ///
02320 /// \param ObjectType if this unqualified-id occurs within a member access
02321 /// expression, the type of the base object whose member is being accessed.
02322 ///
02323 /// \param Result on a successful parse, contains the parsed unqualified-id.
02324 ///
02325 /// \returns true if parsing fails, false otherwise.
02326 bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
02327                                 bool AllowDestructorName,
02328                                 bool AllowConstructorName,
02329                                 ParsedType ObjectType,
02330                                 SourceLocation& TemplateKWLoc,
02331                                 UnqualifiedId &Result) {
02332 
02333   // Handle 'A::template B'. This is for template-ids which have not
02334   // already been annotated by ParseOptionalCXXScopeSpecifier().
02335   bool TemplateSpecified = false;
02336   if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
02337       (ObjectType || SS.isSet())) {
02338     TemplateSpecified = true;
02339     TemplateKWLoc = ConsumeToken();
02340   }
02341 
02342   // unqualified-id:
02343   //   identifier
02344   //   template-id (when it hasn't already been annotated)
02345   if (Tok.is(tok::identifier)) {
02346     // Consume the identifier.
02347     IdentifierInfo *Id = Tok.getIdentifierInfo();
02348     SourceLocation IdLoc = ConsumeToken();
02349 
02350     if (!getLangOpts().CPlusPlus) {
02351       // If we're not in C++, only identifiers matter. Record the
02352       // identifier and return.
02353       Result.setIdentifier(Id, IdLoc);
02354       return false;
02355     }
02356 
02357     if (AllowConstructorName && 
02358         Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
02359       // We have parsed a constructor name.
02360       ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
02361                                           &SS, false, false,
02362                                           ParsedType(),
02363                                           /*IsCtorOrDtorName=*/true,
02364                                           /*NonTrivialTypeSourceInfo=*/true);
02365       Result.setConstructorName(Ty, IdLoc, IdLoc);
02366     } else {
02367       // We have parsed an identifier.
02368       Result.setIdentifier(Id, IdLoc);      
02369     }
02370 
02371     // If the next token is a '<', we may have a template.
02372     if (TemplateSpecified || Tok.is(tok::less))
02373       return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
02374                                           EnteringContext, ObjectType,
02375                                           Result, TemplateSpecified);
02376     
02377     return false;
02378   }
02379   
02380   // unqualified-id:
02381   //   template-id (already parsed and annotated)
02382   if (Tok.is(tok::annot_template_id)) {
02383     TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
02384 
02385     // If the template-name names the current class, then this is a constructor 
02386     if (AllowConstructorName && TemplateId->Name &&
02387         Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
02388       if (SS.isSet()) {
02389         // C++ [class.qual]p2 specifies that a qualified template-name
02390         // is taken as the constructor name where a constructor can be
02391         // declared. Thus, the template arguments are extraneous, so
02392         // complain about them and remove them entirely.
02393         Diag(TemplateId->TemplateNameLoc, 
02394              diag::err_out_of_line_constructor_template_id)
02395           << TemplateId->Name
02396           << FixItHint::CreateRemoval(
02397                     SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
02398         ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
02399                                             TemplateId->TemplateNameLoc,
02400                                             getCurScope(),
02401                                             &SS, false, false,
02402                                             ParsedType(),
02403                                             /*IsCtorOrDtorName=*/true,
02404                                             /*NontrivialTypeSourceInfo=*/true);
02405         Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
02406                                   TemplateId->RAngleLoc);
02407         ConsumeToken();
02408         return false;
02409       }
02410 
02411       Result.setConstructorTemplateId(TemplateId);
02412       ConsumeToken();
02413       return false;
02414     }
02415 
02416     // We have already parsed a template-id; consume the annotation token as
02417     // our unqualified-id.
02418     Result.setTemplateId(TemplateId);
02419     TemplateKWLoc = TemplateId->TemplateKWLoc;
02420     ConsumeToken();
02421     return false;
02422   }
02423   
02424   // unqualified-id:
02425   //   operator-function-id
02426   //   conversion-function-id
02427   if (Tok.is(tok::kw_operator)) {
02428     if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
02429       return true;
02430     
02431     // If we have an operator-function-id or a literal-operator-id and the next
02432     // token is a '<', we may have a
02433     // 
02434     //   template-id:
02435     //     operator-function-id < template-argument-list[opt] >
02436     if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
02437          Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
02438         (TemplateSpecified || Tok.is(tok::less)))
02439       return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
02440                                           nullptr, SourceLocation(),
02441                                           EnteringContext, ObjectType,
02442                                           Result, TemplateSpecified);
02443 
02444     return false;
02445   }
02446   
02447   if (getLangOpts().CPlusPlus && 
02448       (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
02449     // C++ [expr.unary.op]p10:
02450     //   There is an ambiguity in the unary-expression ~X(), where X is a 
02451     //   class-name. The ambiguity is resolved in favor of treating ~ as a 
02452     //    unary complement rather than treating ~X as referring to a destructor.
02453     
02454     // Parse the '~'.
02455     SourceLocation TildeLoc = ConsumeToken();
02456 
02457     if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
02458       DeclSpec DS(AttrFactory);
02459       SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
02460       if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
02461         Result.setDestructorName(TildeLoc, Type, EndLoc);
02462         return false;
02463       }
02464       return true;
02465     }
02466     
02467     // Parse the class-name.
02468     if (Tok.isNot(tok::identifier)) {
02469       Diag(Tok, diag::err_destructor_tilde_identifier);
02470       return true;
02471     }
02472 
02473     // If the user wrote ~T::T, correct it to T::~T.
02474     if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
02475       if (SS.isSet()) {
02476         AnnotateScopeToken(SS, /*NewAnnotation*/true);
02477         SS.clear();
02478       }
02479       if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
02480         return true;
02481       if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon)) {
02482         Diag(TildeLoc, diag::err_destructor_tilde_scope);
02483         return true;
02484       }
02485 
02486       // Recover as if the tilde had been written before the identifier.
02487       Diag(TildeLoc, diag::err_destructor_tilde_scope)
02488         << FixItHint::CreateRemoval(TildeLoc)
02489         << FixItHint::CreateInsertion(Tok.getLocation(), "~");
02490     }
02491 
02492     // Parse the class-name (or template-name in a simple-template-id).
02493     IdentifierInfo *ClassName = Tok.getIdentifierInfo();
02494     SourceLocation ClassNameLoc = ConsumeToken();
02495 
02496     if (TemplateSpecified || Tok.is(tok::less)) {
02497       Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
02498       return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
02499                                           ClassName, ClassNameLoc,
02500                                           EnteringContext, ObjectType,
02501                                           Result, TemplateSpecified);
02502     }
02503 
02504     // Note that this is a destructor name.
02505     ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName, 
02506                                               ClassNameLoc, getCurScope(),
02507                                               SS, ObjectType,
02508                                               EnteringContext);
02509     if (!Ty)
02510       return true;
02511 
02512     Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
02513     return false;
02514   }
02515   
02516   Diag(Tok, diag::err_expected_unqualified_id)
02517     << getLangOpts().CPlusPlus;
02518   return true;
02519 }
02520 
02521 /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
02522 /// memory in a typesafe manner and call constructors.
02523 ///
02524 /// This method is called to parse the new expression after the optional :: has
02525 /// been already parsed.  If the :: was present, "UseGlobal" is true and "Start"
02526 /// is its location.  Otherwise, "Start" is the location of the 'new' token.
02527 ///
02528 ///        new-expression:
02529 ///                   '::'[opt] 'new' new-placement[opt] new-type-id
02530 ///                                     new-initializer[opt]
02531 ///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
02532 ///                                     new-initializer[opt]
02533 ///
02534 ///        new-placement:
02535 ///                   '(' expression-list ')'
02536 ///
02537 ///        new-type-id:
02538 ///                   type-specifier-seq new-declarator[opt]
02539 /// [GNU]             attributes type-specifier-seq new-declarator[opt]
02540 ///
02541 ///        new-declarator:
02542 ///                   ptr-operator new-declarator[opt]
02543 ///                   direct-new-declarator
02544 ///
02545 ///        new-initializer:
02546 ///                   '(' expression-list[opt] ')'
02547 /// [C++0x]           braced-init-list
02548 ///
02549 ExprResult
02550 Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
02551   assert(Tok.is(tok::kw_new) && "expected 'new' token");
02552   ConsumeToken();   // Consume 'new'
02553 
02554   // A '(' now can be a new-placement or the '(' wrapping the type-id in the
02555   // second form of new-expression. It can't be a new-type-id.
02556 
02557   ExprVector PlacementArgs;
02558   SourceLocation PlacementLParen, PlacementRParen;
02559 
02560   SourceRange TypeIdParens;
02561   DeclSpec DS(AttrFactory);
02562   Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
02563   if (Tok.is(tok::l_paren)) {
02564     // If it turns out to be a placement, we change the type location.
02565     BalancedDelimiterTracker T(*this, tok::l_paren);
02566     T.consumeOpen();
02567     PlacementLParen = T.getOpenLocation();
02568     if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
02569       SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
02570       return ExprError();
02571     }
02572 
02573     T.consumeClose();
02574     PlacementRParen = T.getCloseLocation();
02575     if (PlacementRParen.isInvalid()) {
02576       SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
02577       return ExprError();
02578     }
02579 
02580     if (PlacementArgs.empty()) {
02581       // Reset the placement locations. There was no placement.
02582       TypeIdParens = T.getRange();
02583       PlacementLParen = PlacementRParen = SourceLocation();
02584     } else {
02585       // We still need the type.
02586       if (Tok.is(tok::l_paren)) {
02587         BalancedDelimiterTracker T(*this, tok::l_paren);
02588         T.consumeOpen();
02589         MaybeParseGNUAttributes(DeclaratorInfo);
02590         ParseSpecifierQualifierList(DS);
02591         DeclaratorInfo.SetSourceRange(DS.getSourceRange());
02592         ParseDeclarator(DeclaratorInfo);
02593         T.consumeClose();
02594         TypeIdParens = T.getRange();
02595       } else {
02596         MaybeParseGNUAttributes(DeclaratorInfo);
02597         if (ParseCXXTypeSpecifierSeq(DS))
02598           DeclaratorInfo.setInvalidType(true);
02599         else {
02600           DeclaratorInfo.SetSourceRange(DS.getSourceRange());
02601           ParseDeclaratorInternal(DeclaratorInfo,
02602                                   &Parser::ParseDirectNewDeclarator);
02603         }
02604       }
02605     }
02606   } else {
02607     // A new-type-id is a simplified type-id, where essentially the
02608     // direct-declarator is replaced by a direct-new-declarator.
02609     MaybeParseGNUAttributes(DeclaratorInfo);
02610     if (ParseCXXTypeSpecifierSeq(DS))
02611       DeclaratorInfo.setInvalidType(true);
02612     else {
02613       DeclaratorInfo.SetSourceRange(DS.getSourceRange());
02614       ParseDeclaratorInternal(DeclaratorInfo,
02615                               &Parser::ParseDirectNewDeclarator);
02616     }
02617   }
02618   if (DeclaratorInfo.isInvalidType()) {
02619     SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
02620     return ExprError();
02621   }
02622 
02623   ExprResult Initializer;
02624 
02625   if (Tok.is(tok::l_paren)) {
02626     SourceLocation ConstructorLParen, ConstructorRParen;
02627     ExprVector ConstructorArgs;
02628     BalancedDelimiterTracker T(*this, tok::l_paren);
02629     T.consumeOpen();
02630     ConstructorLParen = T.getOpenLocation();
02631     if (Tok.isNot(tok::r_paren)) {
02632       CommaLocsTy CommaLocs;
02633       if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
02634         SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
02635         return ExprError();
02636       }
02637     }
02638     T.consumeClose();
02639     ConstructorRParen = T.getCloseLocation();
02640     if (ConstructorRParen.isInvalid()) {
02641       SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
02642       return ExprError();
02643     }
02644     Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
02645                                              ConstructorRParen,
02646                                              ConstructorArgs);
02647   } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
02648     Diag(Tok.getLocation(),
02649          diag::warn_cxx98_compat_generalized_initializer_lists);
02650     Initializer = ParseBraceInitializer();
02651   }
02652   if (Initializer.isInvalid())
02653     return Initializer;
02654 
02655   return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
02656                              PlacementArgs, PlacementRParen,
02657                              TypeIdParens, DeclaratorInfo, Initializer.get());
02658 }
02659 
02660 /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
02661 /// passed to ParseDeclaratorInternal.
02662 ///
02663 ///        direct-new-declarator:
02664 ///                   '[' expression ']'
02665 ///                   direct-new-declarator '[' constant-expression ']'
02666 ///
02667 void Parser::ParseDirectNewDeclarator(Declarator &D) {
02668   // Parse the array dimensions.
02669   bool first = true;
02670   while (Tok.is(tok::l_square)) {
02671     // An array-size expression can't start with a lambda.
02672     if (CheckProhibitedCXX11Attribute())
02673       continue;
02674 
02675     BalancedDelimiterTracker T(*this, tok::l_square);
02676     T.consumeOpen();
02677 
02678     ExprResult Size(first ? ParseExpression()
02679                                 : ParseConstantExpression());
02680     if (Size.isInvalid()) {
02681       // Recover
02682       SkipUntil(tok::r_square, StopAtSemi);
02683       return;
02684     }
02685     first = false;
02686 
02687     T.consumeClose();
02688 
02689     // Attributes here appertain to the array type. C++11 [expr.new]p5.
02690     ParsedAttributes Attrs(AttrFactory);
02691     MaybeParseCXX11Attributes(Attrs);
02692 
02693     D.AddTypeInfo(DeclaratorChunk::getArray(0,
02694                                             /*static=*/false, /*star=*/false,
02695                                             Size.get(),
02696                                             T.getOpenLocation(),
02697                                             T.getCloseLocation()),
02698                   Attrs, T.getCloseLocation());
02699 
02700     if (T.getCloseLocation().isInvalid())
02701       return;
02702   }
02703 }
02704 
02705 /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
02706 /// This ambiguity appears in the syntax of the C++ new operator.
02707 ///
02708 ///        new-expression:
02709 ///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
02710 ///                                     new-initializer[opt]
02711 ///
02712 ///        new-placement:
02713 ///                   '(' expression-list ')'
02714 ///
02715 bool Parser::ParseExpressionListOrTypeId(
02716                                    SmallVectorImpl<Expr*> &PlacementArgs,
02717                                          Declarator &D) {
02718   // The '(' was already consumed.
02719   if (isTypeIdInParens()) {
02720     ParseSpecifierQualifierList(D.getMutableDeclSpec());
02721     D.SetSourceRange(D.getDeclSpec().getSourceRange());
02722     ParseDeclarator(D);
02723     return D.isInvalidType();
02724   }
02725 
02726   // It's not a type, it has to be an expression list.
02727   // Discard the comma locations - ActOnCXXNew has enough parameters.
02728   CommaLocsTy CommaLocs;
02729   return ParseExpressionList(PlacementArgs, CommaLocs);
02730 }
02731 
02732 /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
02733 /// to free memory allocated by new.
02734 ///
02735 /// This method is called to parse the 'delete' expression after the optional
02736 /// '::' has been already parsed.  If the '::' was present, "UseGlobal" is true
02737 /// and "Start" is its location.  Otherwise, "Start" is the location of the
02738 /// 'delete' token.
02739 ///
02740 ///        delete-expression:
02741 ///                   '::'[opt] 'delete' cast-expression
02742 ///                   '::'[opt] 'delete' '[' ']' cast-expression
02743 ExprResult
02744 Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
02745   assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
02746   ConsumeToken(); // Consume 'delete'
02747 
02748   // Array delete?
02749   bool ArrayDelete = false;
02750   if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
02751     // C++11 [expr.delete]p1:
02752     //   Whenever the delete keyword is followed by empty square brackets, it
02753     //   shall be interpreted as [array delete].
02754     //   [Footnote: A lambda expression with a lambda-introducer that consists
02755     //              of empty square brackets can follow the delete keyword if
02756     //              the lambda expression is enclosed in parentheses.]
02757     // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
02758     //        lambda-introducer.
02759     ArrayDelete = true;
02760     BalancedDelimiterTracker T(*this, tok::l_square);
02761 
02762     T.consumeOpen();
02763     T.consumeClose();
02764     if (T.getCloseLocation().isInvalid())
02765       return ExprError();
02766   }
02767 
02768   ExprResult Operand(ParseCastExpression(false));
02769   if (Operand.isInvalid())
02770     return Operand;
02771 
02772   return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
02773 }
02774 
02775 static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
02776   switch (kind) {
02777   default: llvm_unreachable("Not a known type trait");
02778 #define TYPE_TRAIT_1(Spelling, Name, Key) \
02779 case tok::kw_ ## Spelling: return UTT_ ## Name;
02780 #define TYPE_TRAIT_2(Spelling, Name, Key) \
02781 case tok::kw_ ## Spelling: return BTT_ ## Name;
02782 #include "clang/Basic/TokenKinds.def"
02783 #define TYPE_TRAIT_N(Spelling, Name, Key) \
02784   case tok::kw_ ## Spelling: return TT_ ## Name;
02785 #include "clang/Basic/TokenKinds.def"
02786   }
02787 }
02788 
02789 static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
02790   switch(kind) {
02791   default: llvm_unreachable("Not a known binary type trait");
02792   case tok::kw___array_rank:                 return ATT_ArrayRank;
02793   case tok::kw___array_extent:               return ATT_ArrayExtent;
02794   }
02795 }
02796 
02797 static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
02798   switch(kind) {
02799   default: llvm_unreachable("Not a known unary expression trait.");
02800   case tok::kw___is_lvalue_expr:             return ET_IsLValueExpr;
02801   case tok::kw___is_rvalue_expr:             return ET_IsRValueExpr;
02802   }
02803 }
02804 
02805 static unsigned TypeTraitArity(tok::TokenKind kind) {
02806   switch (kind) {
02807     default: llvm_unreachable("Not a known type trait");
02808 #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
02809 #include "clang/Basic/TokenKinds.def"
02810   }
02811 }
02812 
02813 /// \brief Parse the built-in type-trait pseudo-functions that allow 
02814 /// implementation of the TR1/C++11 type traits templates.
02815 ///
02816 ///       primary-expression:
02817 ///          unary-type-trait '(' type-id ')'
02818 ///          binary-type-trait '(' type-id ',' type-id ')'
02819 ///          type-trait '(' type-id-seq ')'
02820 ///
02821 ///       type-id-seq:
02822 ///          type-id ...[opt] type-id-seq[opt]
02823 ///
02824 ExprResult Parser::ParseTypeTrait() {
02825   tok::TokenKind Kind = Tok.getKind();
02826   unsigned Arity = TypeTraitArity(Kind);
02827 
02828   SourceLocation Loc = ConsumeToken();
02829   
02830   BalancedDelimiterTracker Parens(*this, tok::l_paren);
02831   if (Parens.expectAndConsume())
02832     return ExprError();
02833 
02834   SmallVector<ParsedType, 2> Args;
02835   do {
02836     // Parse the next type.
02837     TypeResult Ty = ParseTypeName();
02838     if (Ty.isInvalid()) {
02839       Parens.skipToEnd();
02840       return ExprError();
02841     }
02842 
02843     // Parse the ellipsis, if present.
02844     if (Tok.is(tok::ellipsis)) {
02845       Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
02846       if (Ty.isInvalid()) {
02847         Parens.skipToEnd();
02848         return ExprError();
02849       }
02850     }
02851     
02852     // Add this type to the list of arguments.
02853     Args.push_back(Ty.get());
02854   } while (TryConsumeToken(tok::comma));
02855 
02856   if (Parens.consumeClose())
02857     return ExprError();
02858 
02859   SourceLocation EndLoc = Parens.getCloseLocation();
02860 
02861   if (Arity && Args.size() != Arity) {
02862     Diag(EndLoc, diag::err_type_trait_arity)
02863       << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
02864     return ExprError();
02865   }
02866 
02867   if (!Arity && Args.empty()) {
02868     Diag(EndLoc, diag::err_type_trait_arity)
02869       << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
02870     return ExprError();
02871   }
02872 
02873   return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
02874 }
02875 
02876 /// ParseArrayTypeTrait - Parse the built-in array type-trait
02877 /// pseudo-functions.
02878 ///
02879 ///       primary-expression:
02880 /// [Embarcadero]     '__array_rank' '(' type-id ')'
02881 /// [Embarcadero]     '__array_extent' '(' type-id ',' expression ')'
02882 ///
02883 ExprResult Parser::ParseArrayTypeTrait() {
02884   ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
02885   SourceLocation Loc = ConsumeToken();
02886 
02887   BalancedDelimiterTracker T(*this, tok::l_paren);
02888   if (T.expectAndConsume())
02889     return ExprError();
02890 
02891   TypeResult Ty = ParseTypeName();
02892   if (Ty.isInvalid()) {
02893     SkipUntil(tok::comma, StopAtSemi);
02894     SkipUntil(tok::r_paren, StopAtSemi);
02895     return ExprError();
02896   }
02897 
02898   switch (ATT) {
02899   case ATT_ArrayRank: {
02900     T.consumeClose();
02901     return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
02902                                        T.getCloseLocation());
02903   }
02904   case ATT_ArrayExtent: {
02905     if (ExpectAndConsume(tok::comma)) {
02906       SkipUntil(tok::r_paren, StopAtSemi);
02907       return ExprError();
02908     }
02909 
02910     ExprResult DimExpr = ParseExpression();
02911     T.consumeClose();
02912 
02913     return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
02914                                        T.getCloseLocation());
02915   }
02916   }
02917   llvm_unreachable("Invalid ArrayTypeTrait!");
02918 }
02919 
02920 /// ParseExpressionTrait - Parse built-in expression-trait
02921 /// pseudo-functions like __is_lvalue_expr( xxx ).
02922 ///
02923 ///       primary-expression:
02924 /// [Embarcadero]     expression-trait '(' expression ')'
02925 ///
02926 ExprResult Parser::ParseExpressionTrait() {
02927   ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
02928   SourceLocation Loc = ConsumeToken();
02929 
02930   BalancedDelimiterTracker T(*this, tok::l_paren);
02931   if (T.expectAndConsume())
02932     return ExprError();
02933 
02934   ExprResult Expr = ParseExpression();
02935 
02936   T.consumeClose();
02937 
02938   return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
02939                                       T.getCloseLocation());
02940 }
02941 
02942 
02943 /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
02944 /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
02945 /// based on the context past the parens.
02946 ExprResult
02947 Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
02948                                          ParsedType &CastTy,
02949                                          BalancedDelimiterTracker &Tracker,
02950                                          ColonProtectionRAIIObject &ColonProt) {
02951   assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
02952   assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
02953   assert(isTypeIdInParens() && "Not a type-id!");
02954 
02955   ExprResult Result(true);
02956   CastTy = ParsedType();
02957 
02958   // We need to disambiguate a very ugly part of the C++ syntax:
02959   //
02960   // (T())x;  - type-id
02961   // (T())*x; - type-id
02962   // (T())/x; - expression
02963   // (T());   - expression
02964   //
02965   // The bad news is that we cannot use the specialized tentative parser, since
02966   // it can only verify that the thing inside the parens can be parsed as
02967   // type-id, it is not useful for determining the context past the parens.
02968   //
02969   // The good news is that the parser can disambiguate this part without
02970   // making any unnecessary Action calls.
02971   //
02972   // It uses a scheme similar to parsing inline methods. The parenthesized
02973   // tokens are cached, the context that follows is determined (possibly by
02974   // parsing a cast-expression), and then we re-introduce the cached tokens
02975   // into the token stream and parse them appropriately.
02976 
02977   ParenParseOption ParseAs;
02978   CachedTokens Toks;
02979 
02980   // Store the tokens of the parentheses. We will parse them after we determine
02981   // the context that follows them.
02982   if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
02983     // We didn't find the ')' we expected.
02984     Tracker.consumeClose();
02985     return ExprError();
02986   }
02987 
02988   if (Tok.is(tok::l_brace)) {
02989     ParseAs = CompoundLiteral;
02990   } else {
02991     bool NotCastExpr;
02992     if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
02993       NotCastExpr = true;
02994     } else {
02995       // Try parsing the cast-expression that may follow.
02996       // If it is not a cast-expression, NotCastExpr will be true and no token
02997       // will be consumed.
02998       ColonProt.restore();
02999       Result = ParseCastExpression(false/*isUnaryExpression*/,
03000                                    false/*isAddressofOperand*/,
03001                                    NotCastExpr,
03002                                    // type-id has priority.
03003                                    IsTypeCast);
03004     }
03005 
03006     // If we parsed a cast-expression, it's really a type-id, otherwise it's
03007     // an expression.
03008     ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
03009   }
03010 
03011   // The current token should go after the cached tokens.
03012   Toks.push_back(Tok);
03013   // Re-enter the stored parenthesized tokens into the token stream, so we may
03014   // parse them now.
03015   PP.EnterTokenStream(Toks.data(), Toks.size(),
03016                       true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
03017   // Drop the current token and bring the first cached one. It's the same token
03018   // as when we entered this function.
03019   ConsumeAnyToken();
03020 
03021   if (ParseAs >= CompoundLiteral) {
03022     // Parse the type declarator.
03023     DeclSpec DS(AttrFactory);
03024     Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
03025     {
03026       ColonProtectionRAIIObject InnerColonProtection(*this);
03027       ParseSpecifierQualifierList(DS);
03028       ParseDeclarator(DeclaratorInfo);
03029     }
03030 
03031     // Match the ')'.
03032     Tracker.consumeClose();
03033     ColonProt.restore();
03034 
03035     if (ParseAs == CompoundLiteral) {
03036       ExprType = CompoundLiteral;
03037       if (DeclaratorInfo.isInvalidType())
03038         return ExprError();
03039 
03040       TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
03041       return ParseCompoundLiteralExpression(Ty.get(),
03042                                             Tracker.getOpenLocation(),
03043                                             Tracker.getCloseLocation());
03044     }
03045 
03046     // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
03047     assert(ParseAs == CastExpr);
03048 
03049     if (DeclaratorInfo.isInvalidType())
03050       return ExprError();
03051 
03052     // Result is what ParseCastExpression returned earlier.
03053     if (!Result.isInvalid())
03054       Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
03055                                     DeclaratorInfo, CastTy,
03056                                     Tracker.getCloseLocation(), Result.get());
03057     return Result;
03058   }
03059 
03060   // Not a compound literal, and not followed by a cast-expression.
03061   assert(ParseAs == SimpleExpr);
03062 
03063   ExprType = SimpleExpr;
03064   Result = ParseExpression();
03065   if (!Result.isInvalid() && Tok.is(tok::r_paren))
03066     Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(), 
03067                                     Tok.getLocation(), Result.get());
03068 
03069   // Match the ')'.
03070   if (Result.isInvalid()) {
03071     SkipUntil(tok::r_paren, StopAtSemi);
03072     return ExprError();
03073   }
03074 
03075   Tracker.consumeClose();
03076   return Result;
03077 }