Home | History | Annotate | Download | only in Parse
      1 //===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 //  This file defines the Parser interface.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_CLANG_PARSE_PARSER_H
     15 #define LLVM_CLANG_PARSE_PARSER_H
     16 
     17 #include "clang/Basic/OperatorPrecedence.h"
     18 #include "clang/Basic/Specifiers.h"
     19 #include "clang/Lex/CodeCompletionHandler.h"
     20 #include "clang/Lex/Preprocessor.h"
     21 #include "clang/Sema/DeclSpec.h"
     22 #include "clang/Sema/Sema.h"
     23 #include "llvm/ADT/OwningPtr.h"
     24 #include "llvm/ADT/SmallVector.h"
     25 #include "llvm/Support/Compiler.h"
     26 #include "llvm/Support/PrettyStackTrace.h"
     27 #include "llvm/Support/SaveAndRestore.h"
     28 #include <stack>
     29 
     30 namespace clang {
     31   class PragmaHandler;
     32   class Scope;
     33   class BalancedDelimiterTracker;
     34   class CorrectionCandidateCallback;
     35   class DeclGroupRef;
     36   class DiagnosticBuilder;
     37   class Parser;
     38   class ParsingDeclRAIIObject;
     39   class ParsingDeclSpec;
     40   class ParsingDeclarator;
     41   class ParsingFieldDeclarator;
     42   class PragmaUnusedHandler;
     43   class ColonProtectionRAIIObject;
     44   class InMessageExpressionRAIIObject;
     45   class PoisonSEHIdentifiersRAIIObject;
     46   class VersionTuple;
     47 
     48 /// Parser - This implements a parser for the C family of languages.  After
     49 /// parsing units of the grammar, productions are invoked to handle whatever has
     50 /// been read.
     51 ///
     52 class Parser : public CodeCompletionHandler {
     53   friend class PragmaUnusedHandler;
     54   friend class ColonProtectionRAIIObject;
     55   friend class InMessageExpressionRAIIObject;
     56   friend class PoisonSEHIdentifiersRAIIObject;
     57   friend class ObjCDeclContextSwitch;
     58   friend class ParenBraceBracketBalancer;
     59   friend class BalancedDelimiterTracker;
     60 
     61   Preprocessor &PP;
     62 
     63   /// Tok - The current token we are peeking ahead.  All parsing methods assume
     64   /// that this is valid.
     65   Token Tok;
     66 
     67   // PrevTokLocation - The location of the token we previously
     68   // consumed. This token is used for diagnostics where we expected to
     69   // see a token following another token (e.g., the ';' at the end of
     70   // a statement).
     71   SourceLocation PrevTokLocation;
     72 
     73   unsigned short ParenCount, BracketCount, BraceCount;
     74 
     75   /// Actions - These are the callbacks we invoke as we parse various constructs
     76   /// in the file.
     77   Sema &Actions;
     78 
     79   DiagnosticsEngine &Diags;
     80 
     81   /// ScopeCache - Cache scopes to reduce malloc traffic.
     82   enum { ScopeCacheSize = 16 };
     83   unsigned NumCachedScopes;
     84   Scope *ScopeCache[ScopeCacheSize];
     85 
     86   /// Identifiers used for SEH handling in Borland. These are only
     87   /// allowed in particular circumstances
     88   // __except block
     89   IdentifierInfo *Ident__exception_code,
     90                  *Ident___exception_code,
     91                  *Ident_GetExceptionCode;
     92   // __except filter expression
     93   IdentifierInfo *Ident__exception_info,
     94                  *Ident___exception_info,
     95                  *Ident_GetExceptionInfo;
     96   // __finally
     97   IdentifierInfo *Ident__abnormal_termination,
     98                  *Ident___abnormal_termination,
     99                  *Ident_AbnormalTermination;
    100 
    101   /// Contextual keywords for Microsoft extensions.
    102   IdentifierInfo *Ident__except;
    103 
    104   /// Ident_super - IdentifierInfo for "super", to support fast
    105   /// comparison.
    106   IdentifierInfo *Ident_super;
    107   /// Ident_vector and Ident_pixel - cached IdentifierInfo's for
    108   /// "vector" and "pixel" fast comparison.  Only present if
    109   /// AltiVec enabled.
    110   IdentifierInfo *Ident_vector;
    111   IdentifierInfo *Ident_pixel;
    112 
    113   /// Objective-C contextual keywords.
    114   mutable IdentifierInfo *Ident_instancetype;
    115 
    116   /// \brief Identifier for "introduced".
    117   IdentifierInfo *Ident_introduced;
    118 
    119   /// \brief Identifier for "deprecated".
    120   IdentifierInfo *Ident_deprecated;
    121 
    122   /// \brief Identifier for "obsoleted".
    123   IdentifierInfo *Ident_obsoleted;
    124 
    125   /// \brief Identifier for "unavailable".
    126   IdentifierInfo *Ident_unavailable;
    127 
    128   /// \brief Identifier for "message".
    129   IdentifierInfo *Ident_message;
    130 
    131   /// C++0x contextual keywords.
    132   mutable IdentifierInfo *Ident_final;
    133   mutable IdentifierInfo *Ident_override;
    134 
    135   // C++ type trait keywords that have can be reverted to identifiers and
    136   // still used as type traits.
    137   llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertableTypeTraits;
    138 
    139   OwningPtr<PragmaHandler> AlignHandler;
    140   OwningPtr<PragmaHandler> GCCVisibilityHandler;
    141   OwningPtr<PragmaHandler> OptionsHandler;
    142   OwningPtr<PragmaHandler> PackHandler;
    143   OwningPtr<PragmaHandler> MSStructHandler;
    144   OwningPtr<PragmaHandler> UnusedHandler;
    145   OwningPtr<PragmaHandler> WeakHandler;
    146   OwningPtr<PragmaHandler> RedefineExtnameHandler;
    147   OwningPtr<PragmaHandler> FPContractHandler;
    148   OwningPtr<PragmaHandler> OpenCLExtensionHandler;
    149   OwningPtr<CommentHandler> CommentSemaHandler;
    150 
    151   /// Whether the '>' token acts as an operator or not. This will be
    152   /// true except when we are parsing an expression within a C++
    153   /// template argument list, where the '>' closes the template
    154   /// argument list.
    155   bool GreaterThanIsOperator;
    156 
    157   /// ColonIsSacred - When this is false, we aggressively try to recover from
    158   /// code like "foo : bar" as if it were a typo for "foo :: bar".  This is not
    159   /// safe in case statements and a few other things.  This is managed by the
    160   /// ColonProtectionRAIIObject RAII object.
    161   bool ColonIsSacred;
    162 
    163   /// \brief When true, we are directly inside an Objective-C messsage
    164   /// send expression.
    165   ///
    166   /// This is managed by the \c InMessageExpressionRAIIObject class, and
    167   /// should not be set directly.
    168   bool InMessageExpression;
    169 
    170   /// The "depth" of the template parameters currently being parsed.
    171   unsigned TemplateParameterDepth;
    172 
    173   /// Factory object for creating AttributeList objects.
    174   AttributeFactory AttrFactory;
    175 
    176   /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a
    177   /// top-level declaration is finished.
    178   SmallVector<TemplateIdAnnotation *, 16> TemplateIds;
    179 
    180   /// \brief Identifiers which have been declared within a tentative parse.
    181   SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers;
    182 
    183   IdentifierInfo *getSEHExceptKeyword();
    184 
    185   /// True if we are within an Objective-C container while parsing C-like decls.
    186   ///
    187   /// This is necessary because Sema thinks we have left the container
    188   /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will
    189   /// be NULL.
    190   bool ParsingInObjCContainer;
    191 
    192   bool SkipFunctionBodies;
    193 
    194 public:
    195   Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies);
    196   ~Parser();
    197 
    198   const LangOptions &getLangOpts() const { return PP.getLangOpts(); }
    199   const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
    200   Preprocessor &getPreprocessor() const { return PP; }
    201   Sema &getActions() const { return Actions; }
    202   AttributeFactory &getAttrFactory() { return AttrFactory; }
    203 
    204   const Token &getCurToken() const { return Tok; }
    205   Scope *getCurScope() const { return Actions.getCurScope(); }
    206 
    207   Decl  *getObjCDeclContext() const { return Actions.getObjCDeclContext(); }
    208 
    209   // Type forwarding.  All of these are statically 'void*', but they may all be
    210   // different actual classes based on the actions in place.
    211   typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
    212   typedef OpaquePtr<TemplateName> TemplateTy;
    213 
    214   typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists;
    215 
    216   typedef clang::ExprResult        ExprResult;
    217   typedef clang::StmtResult        StmtResult;
    218   typedef clang::BaseResult        BaseResult;
    219   typedef clang::MemInitResult     MemInitResult;
    220   typedef clang::TypeResult        TypeResult;
    221 
    222   typedef Expr *ExprArg;
    223   typedef llvm::MutableArrayRef<Stmt*> MultiStmtArg;
    224   typedef Sema::FullExprArg FullExprArg;
    225 
    226   ExprResult ExprError() { return ExprResult(true); }
    227   StmtResult StmtError() { return StmtResult(true); }
    228 
    229   ExprResult ExprError(const DiagnosticBuilder &) { return ExprError(); }
    230   StmtResult StmtError(const DiagnosticBuilder &) { return StmtError(); }
    231 
    232   ExprResult ExprEmpty() { return ExprResult(false); }
    233 
    234   // Parsing methods.
    235 
    236   /// Initialize - Warm up the parser.
    237   ///
    238   void Initialize();
    239 
    240   /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
    241   /// the EOF was encountered.
    242   bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
    243 
    244   /// ConsumeToken - Consume the current 'peek token' and lex the next one.
    245   /// This does not work with all kinds of tokens: strings and specific other
    246   /// tokens must be consumed with custom methods below.  This returns the
    247   /// location of the consumed token.
    248   SourceLocation ConsumeToken() {
    249     assert(!isTokenStringLiteral() && !isTokenParen() && !isTokenBracket() &&
    250            !isTokenBrace() &&
    251            "Should consume special tokens with Consume*Token");
    252 
    253     if (Tok.is(tok::code_completion))
    254       return handleUnexpectedCodeCompletionToken();
    255 
    256     PrevTokLocation = Tok.getLocation();
    257     PP.Lex(Tok);
    258     return PrevTokLocation;
    259   }
    260 
    261 private:
    262   //===--------------------------------------------------------------------===//
    263   // Low-Level token peeking and consumption methods.
    264   //
    265 
    266   /// isTokenParen - Return true if the cur token is '(' or ')'.
    267   bool isTokenParen() const {
    268     return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
    269   }
    270   /// isTokenBracket - Return true if the cur token is '[' or ']'.
    271   bool isTokenBracket() const {
    272     return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
    273   }
    274   /// isTokenBrace - Return true if the cur token is '{' or '}'.
    275   bool isTokenBrace() const {
    276     return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
    277   }
    278 
    279   /// isTokenStringLiteral - True if this token is a string-literal.
    280   ///
    281   bool isTokenStringLiteral() const {
    282     return tok::isStringLiteral(Tok.getKind());
    283   }
    284 
    285   /// \brief Returns true if the current token is '=' or is a type of '='.
    286   /// For typos, give a fixit to '='
    287   bool isTokenEqualOrEqualTypo();
    288 
    289   /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
    290   /// current token type.  This should only be used in cases where the type of
    291   /// the token really isn't known, e.g. in error recovery.
    292   SourceLocation ConsumeAnyToken() {
    293     if (isTokenParen())
    294       return ConsumeParen();
    295     else if (isTokenBracket())
    296       return ConsumeBracket();
    297     else if (isTokenBrace())
    298       return ConsumeBrace();
    299     else if (isTokenStringLiteral())
    300       return ConsumeStringToken();
    301     else
    302       return ConsumeToken();
    303   }
    304 
    305   /// ConsumeParen - This consume method keeps the paren count up-to-date.
    306   ///
    307   SourceLocation ConsumeParen() {
    308     assert(isTokenParen() && "wrong consume method");
    309     if (Tok.getKind() == tok::l_paren)
    310       ++ParenCount;
    311     else if (ParenCount)
    312       --ParenCount;       // Don't let unbalanced )'s drive the count negative.
    313     PrevTokLocation = Tok.getLocation();
    314     PP.Lex(Tok);
    315     return PrevTokLocation;
    316   }
    317 
    318   /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
    319   ///
    320   SourceLocation ConsumeBracket() {
    321     assert(isTokenBracket() && "wrong consume method");
    322     if (Tok.getKind() == tok::l_square)
    323       ++BracketCount;
    324     else if (BracketCount)
    325       --BracketCount;     // Don't let unbalanced ]'s drive the count negative.
    326 
    327     PrevTokLocation = Tok.getLocation();
    328     PP.Lex(Tok);
    329     return PrevTokLocation;
    330   }
    331 
    332   /// ConsumeBrace - This consume method keeps the brace count up-to-date.
    333   ///
    334   SourceLocation ConsumeBrace() {
    335     assert(isTokenBrace() && "wrong consume method");
    336     if (Tok.getKind() == tok::l_brace)
    337       ++BraceCount;
    338     else if (BraceCount)
    339       --BraceCount;     // Don't let unbalanced }'s drive the count negative.
    340 
    341     PrevTokLocation = Tok.getLocation();
    342     PP.Lex(Tok);
    343     return PrevTokLocation;
    344   }
    345 
    346   /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
    347   /// and returning the token kind.  This method is specific to strings, as it
    348   /// handles string literal concatenation, as per C99 5.1.1.2, translation
    349   /// phase #6.
    350   SourceLocation ConsumeStringToken() {
    351     assert(isTokenStringLiteral() &&
    352            "Should only consume string literals with this method");
    353     PrevTokLocation = Tok.getLocation();
    354     PP.Lex(Tok);
    355     return PrevTokLocation;
    356   }
    357 
    358   /// \brief Consume the current code-completion token.
    359   ///
    360   /// This routine should be called to consume the code-completion token once
    361   /// a code-completion action has already been invoked.
    362   SourceLocation ConsumeCodeCompletionToken() {
    363     assert(Tok.is(tok::code_completion));
    364     PrevTokLocation = Tok.getLocation();
    365     PP.Lex(Tok);
    366     return PrevTokLocation;
    367   }
    368 
    369   ///\ brief When we are consuming a code-completion token without having
    370   /// matched specific position in the grammar, provide code-completion results
    371   /// based on context.
    372   ///
    373   /// \returns the source location of the code-completion token.
    374   SourceLocation handleUnexpectedCodeCompletionToken();
    375 
    376   /// \brief Abruptly cut off parsing; mainly used when we have reached the
    377   /// code-completion point.
    378   void cutOffParsing() {
    379     PP.setCodeCompletionReached();
    380     // Cut off parsing by acting as if we reached the end-of-file.
    381     Tok.setKind(tok::eof);
    382   }
    383 
    384   /// \brief Handle the annotation token produced for #pragma unused(...)
    385   void HandlePragmaUnused();
    386 
    387   /// \brief Handle the annotation token produced for
    388   /// #pragma GCC visibility...
    389   void HandlePragmaVisibility();
    390 
    391   /// \brief Handle the annotation token produced for
    392   /// #pragma pack...
    393   void HandlePragmaPack();
    394 
    395   /// \brief Handle the annotation token produced for
    396   /// #pragma ms_struct...
    397   void HandlePragmaMSStruct();
    398 
    399   /// \brief Handle the annotation token produced for
    400   /// #pragma align...
    401   void HandlePragmaAlign();
    402 
    403   /// \brief Handle the annotation token produced for
    404   /// #pragma weak id...
    405   void HandlePragmaWeak();
    406 
    407   /// \brief Handle the annotation token produced for
    408   /// #pragma weak id = id...
    409   void HandlePragmaWeakAlias();
    410 
    411   /// \brief Handle the annotation token produced for
    412   /// #pragma redefine_extname...
    413   void HandlePragmaRedefineExtname();
    414 
    415   /// \brief Handle the annotation token produced for
    416   /// #pragma STDC FP_CONTRACT...
    417   void HandlePragmaFPContract();
    418 
    419   /// \brief Handle the annotation token produced for
    420   /// #pragma OPENCL EXTENSION...
    421   void HandlePragmaOpenCLExtension();
    422 
    423   /// GetLookAheadToken - This peeks ahead N tokens and returns that token
    424   /// without consuming any tokens.  LookAhead(0) returns 'Tok', LookAhead(1)
    425   /// returns the token after Tok, etc.
    426   ///
    427   /// Note that this differs from the Preprocessor's LookAhead method, because
    428   /// the Parser always has one token lexed that the preprocessor doesn't.
    429   ///
    430   const Token &GetLookAheadToken(unsigned N) {
    431     if (N == 0 || Tok.is(tok::eof)) return Tok;
    432     return PP.LookAhead(N-1);
    433   }
    434 
    435 public:
    436   /// NextToken - This peeks ahead one token and returns it without
    437   /// consuming it.
    438   const Token &NextToken() {
    439     return PP.LookAhead(0);
    440   }
    441 
    442   /// getTypeAnnotation - Read a parsed type out of an annotation token.
    443   static ParsedType getTypeAnnotation(Token &Tok) {
    444     return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
    445   }
    446 
    447 private:
    448   static void setTypeAnnotation(Token &Tok, ParsedType T) {
    449     Tok.setAnnotationValue(T.getAsOpaquePtr());
    450   }
    451 
    452   /// \brief Read an already-translated primary expression out of an annotation
    453   /// token.
    454   static ExprResult getExprAnnotation(Token &Tok) {
    455     if (Tok.getAnnotationValue())
    456       return ExprResult((Expr *)Tok.getAnnotationValue());
    457 
    458     return ExprResult(true);
    459   }
    460 
    461   /// \brief Set the primary expression corresponding to the given annotation
    462   /// token.
    463   static void setExprAnnotation(Token &Tok, ExprResult ER) {
    464     if (ER.isInvalid())
    465       Tok.setAnnotationValue(0);
    466     else
    467       Tok.setAnnotationValue(ER.get());
    468   }
    469 
    470 public:
    471   // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to
    472   // find a type name by attempting typo correction.
    473   bool TryAnnotateTypeOrScopeToken(bool EnteringContext = false,
    474                                    bool NeedType = false);
    475   bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext,
    476                                                  bool NeedType,
    477                                                  CXXScopeSpec &SS,
    478                                                  bool IsNewScope);
    479   bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
    480 
    481 private:
    482   enum AnnotatedNameKind {
    483     /// Annotation has failed and emitted an error.
    484     ANK_Error,
    485     /// The identifier is a tentatively-declared name.
    486     ANK_TentativeDecl,
    487     /// The identifier is a template name. FIXME: Add an annotation for that.
    488     ANK_TemplateName,
    489     /// The identifier can't be resolved.
    490     ANK_Unresolved,
    491     /// Annotation was successful.
    492     ANK_Success
    493   };
    494   AnnotatedNameKind TryAnnotateName(bool IsAddressOfOperand,
    495                                     CorrectionCandidateCallback *CCC = 0);
    496 
    497   /// Push a tok::annot_cxxscope token onto the token stream.
    498   void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation);
    499 
    500   /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
    501   /// replacing them with the non-context-sensitive keywords.  This returns
    502   /// true if the token was replaced.
    503   bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
    504                        const char *&PrevSpec, unsigned &DiagID,
    505                        bool &isInvalid) {
    506     if (!getLangOpts().AltiVec ||
    507         (Tok.getIdentifierInfo() != Ident_vector &&
    508          Tok.getIdentifierInfo() != Ident_pixel))
    509       return false;
    510 
    511     return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
    512   }
    513 
    514   /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
    515   /// identifier token, replacing it with the non-context-sensitive __vector.
    516   /// This returns true if the token was replaced.
    517   bool TryAltiVecVectorToken() {
    518     if (!getLangOpts().AltiVec ||
    519         Tok.getIdentifierInfo() != Ident_vector) return false;
    520     return TryAltiVecVectorTokenOutOfLine();
    521   }
    522 
    523   bool TryAltiVecVectorTokenOutOfLine();
    524   bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
    525                                 const char *&PrevSpec, unsigned &DiagID,
    526                                 bool &isInvalid);
    527 
    528   /// \brief Get the TemplateIdAnnotation from the token.
    529   TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok);
    530 
    531   /// TentativeParsingAction - An object that is used as a kind of "tentative
    532   /// parsing transaction". It gets instantiated to mark the token position and
    533   /// after the token consumption is done, Commit() or Revert() is called to
    534   /// either "commit the consumed tokens" or revert to the previously marked
    535   /// token position. Example:
    536   ///
    537   ///   TentativeParsingAction TPA(*this);
    538   ///   ConsumeToken();
    539   ///   ....
    540   ///   TPA.Revert();
    541   ///
    542   class TentativeParsingAction {
    543     Parser &P;
    544     Token PrevTok;
    545     size_t PrevTentativelyDeclaredIdentifierCount;
    546     unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount;
    547     bool isActive;
    548 
    549   public:
    550     explicit TentativeParsingAction(Parser& p) : P(p) {
    551       PrevTok = P.Tok;
    552       PrevTentativelyDeclaredIdentifierCount =
    553           P.TentativelyDeclaredIdentifiers.size();
    554       PrevParenCount = P.ParenCount;
    555       PrevBracketCount = P.BracketCount;
    556       PrevBraceCount = P.BraceCount;
    557       P.PP.EnableBacktrackAtThisPos();
    558       isActive = true;
    559     }
    560     void Commit() {
    561       assert(isActive && "Parsing action was finished!");
    562       P.TentativelyDeclaredIdentifiers.resize(
    563           PrevTentativelyDeclaredIdentifierCount);
    564       P.PP.CommitBacktrackedTokens();
    565       isActive = false;
    566     }
    567     void Revert() {
    568       assert(isActive && "Parsing action was finished!");
    569       P.PP.Backtrack();
    570       P.Tok = PrevTok;
    571       P.TentativelyDeclaredIdentifiers.resize(
    572           PrevTentativelyDeclaredIdentifierCount);
    573       P.ParenCount = PrevParenCount;
    574       P.BracketCount = PrevBracketCount;
    575       P.BraceCount = PrevBraceCount;
    576       isActive = false;
    577     }
    578     ~TentativeParsingAction() {
    579       assert(!isActive && "Forgot to call Commit or Revert!");
    580     }
    581   };
    582 
    583   /// ObjCDeclContextSwitch - An object used to switch context from
    584   /// an objective-c decl context to its enclosing decl context and
    585   /// back.
    586   class ObjCDeclContextSwitch {
    587     Parser &P;
    588     Decl *DC;
    589     SaveAndRestore<bool> WithinObjCContainer;
    590   public:
    591     explicit ObjCDeclContextSwitch(Parser &p)
    592       : P(p), DC(p.getObjCDeclContext()),
    593         WithinObjCContainer(P.ParsingInObjCContainer, DC != 0) {
    594       if (DC)
    595         P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC));
    596     }
    597     ~ObjCDeclContextSwitch() {
    598       if (DC)
    599         P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC));
    600     }
    601   };
    602 
    603   /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
    604   /// input.  If so, it is consumed and false is returned.
    605   ///
    606   /// If the input is malformed, this emits the specified diagnostic.  Next, if
    607   /// SkipToTok is specified, it calls SkipUntil(SkipToTok).  Finally, true is
    608   /// returned.
    609   bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag,
    610                         const char *DiagMsg = "",
    611                         tok::TokenKind SkipToTok = tok::unknown);
    612 
    613   /// \brief The parser expects a semicolon and, if present, will consume it.
    614   ///
    615   /// If the next token is not a semicolon, this emits the specified diagnostic,
    616   /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior
    617   /// to the semicolon, consumes that extra token.
    618   bool ExpectAndConsumeSemi(unsigned DiagID);
    619 
    620   /// \brief The kind of extra semi diagnostic to emit.
    621   enum ExtraSemiKind {
    622     OutsideFunction = 0,
    623     InsideStruct = 1,
    624     InstanceVariableList = 2,
    625     AfterMemberFunctionDefinition = 3
    626   };
    627 
    628   /// \brief Consume any extra semi-colons until the end of the line.
    629   void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified);
    630 
    631 public:
    632   //===--------------------------------------------------------------------===//
    633   // Scope manipulation
    634 
    635   /// ParseScope - Introduces a new scope for parsing. The kind of
    636   /// scope is determined by ScopeFlags. Objects of this type should
    637   /// be created on the stack to coincide with the position where the
    638   /// parser enters the new scope, and this object's constructor will
    639   /// create that new scope. Similarly, once the object is destroyed
    640   /// the parser will exit the scope.
    641   class ParseScope {
    642     Parser *Self;
    643     ParseScope(const ParseScope &) LLVM_DELETED_FUNCTION;
    644     void operator=(const ParseScope &) LLVM_DELETED_FUNCTION;
    645 
    646   public:
    647     // ParseScope - Construct a new object to manage a scope in the
    648     // parser Self where the new Scope is created with the flags
    649     // ScopeFlags, but only when ManageScope is true (the default). If
    650     // ManageScope is false, this object does nothing.
    651     ParseScope(Parser *Self, unsigned ScopeFlags, bool ManageScope = true)
    652       : Self(Self) {
    653       if (ManageScope)
    654         Self->EnterScope(ScopeFlags);
    655       else
    656         this->Self = 0;
    657     }
    658 
    659     // Exit - Exit the scope associated with this object now, rather
    660     // than waiting until the object is destroyed.
    661     void Exit() {
    662       if (Self) {
    663         Self->ExitScope();
    664         Self = 0;
    665       }
    666     }
    667 
    668     ~ParseScope() {
    669       Exit();
    670     }
    671   };
    672 
    673   /// EnterScope - Start a new scope.
    674   void EnterScope(unsigned ScopeFlags);
    675 
    676   /// ExitScope - Pop a scope off the scope stack.
    677   void ExitScope();
    678 
    679 private:
    680   /// \brief RAII object used to modify the scope flags for the current scope.
    681   class ParseScopeFlags {
    682     Scope *CurScope;
    683     unsigned OldFlags;
    684     ParseScopeFlags(const ParseScopeFlags &) LLVM_DELETED_FUNCTION;
    685     void operator=(const ParseScopeFlags &) LLVM_DELETED_FUNCTION;
    686 
    687   public:
    688     ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true);
    689     ~ParseScopeFlags();
    690   };
    691 
    692   //===--------------------------------------------------------------------===//
    693   // Diagnostic Emission and Error recovery.
    694 
    695 public:
    696   DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
    697   DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
    698   DiagnosticBuilder Diag(unsigned DiagID) {
    699     return Diag(Tok, DiagID);
    700   }
    701 
    702 private:
    703   void SuggestParentheses(SourceLocation Loc, unsigned DK,
    704                           SourceRange ParenRange);
    705   void CheckNestedObjCContexts(SourceLocation AtLoc);
    706 
    707 public:
    708   /// SkipUntil - Read tokens until we get to the specified token, then consume
    709   /// it (unless DontConsume is true).  Because we cannot guarantee that the
    710   /// token will ever occur, this skips to the next token, or to some likely
    711   /// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
    712   /// character.
    713   ///
    714   /// If SkipUntil finds the specified token, it returns true, otherwise it
    715   /// returns false.
    716   bool SkipUntil(tok::TokenKind T, bool StopAtSemi = true,
    717                  bool DontConsume = false, bool StopAtCodeCompletion = false) {
    718     return SkipUntil(llvm::makeArrayRef(T), StopAtSemi, DontConsume,
    719                      StopAtCodeCompletion);
    720   }
    721   bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, bool StopAtSemi = true,
    722                  bool DontConsume = false, bool StopAtCodeCompletion = false) {
    723     tok::TokenKind TokArray[] = {T1, T2};
    724     return SkipUntil(TokArray, StopAtSemi, DontConsume,StopAtCodeCompletion);
    725   }
    726   bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3,
    727                  bool StopAtSemi = true, bool DontConsume = false,
    728                  bool StopAtCodeCompletion = false) {
    729     tok::TokenKind TokArray[] = {T1, T2, T3};
    730     return SkipUntil(TokArray, StopAtSemi, DontConsume,StopAtCodeCompletion);
    731   }
    732   bool SkipUntil(ArrayRef<tok::TokenKind> Toks, bool StopAtSemi = true,
    733                  bool DontConsume = false, bool StopAtCodeCompletion = false);
    734 
    735   /// SkipMalformedDecl - Read tokens until we get to some likely good stopping
    736   /// point for skipping past a simple-declaration.
    737   void SkipMalformedDecl();
    738 
    739 private:
    740   //===--------------------------------------------------------------------===//
    741   // Lexing and parsing of C++ inline methods.
    742 
    743   struct ParsingClass;
    744 
    745   /// [class.mem]p1: "... the class is regarded as complete within
    746   /// - function bodies
    747   /// - default arguments
    748   /// - exception-specifications (TODO: C++0x)
    749   /// - and brace-or-equal-initializers for non-static data members
    750   /// (including such things in nested classes)."
    751   /// LateParsedDeclarations build the tree of those elements so they can
    752   /// be parsed after parsing the top-level class.
    753   class LateParsedDeclaration {
    754   public:
    755     virtual ~LateParsedDeclaration();
    756 
    757     virtual void ParseLexedMethodDeclarations();
    758     virtual void ParseLexedMemberInitializers();
    759     virtual void ParseLexedMethodDefs();
    760     virtual void ParseLexedAttributes();
    761   };
    762 
    763   /// Inner node of the LateParsedDeclaration tree that parses
    764   /// all its members recursively.
    765   class LateParsedClass : public LateParsedDeclaration {
    766   public:
    767     LateParsedClass(Parser *P, ParsingClass *C);
    768     virtual ~LateParsedClass();
    769 
    770     virtual void ParseLexedMethodDeclarations();
    771     virtual void ParseLexedMemberInitializers();
    772     virtual void ParseLexedMethodDefs();
    773     virtual void ParseLexedAttributes();
    774 
    775   private:
    776     Parser *Self;
    777     ParsingClass *Class;
    778   };
    779 
    780   /// Contains the lexed tokens of an attribute with arguments that
    781   /// may reference member variables and so need to be parsed at the
    782   /// end of the class declaration after parsing all other member
    783   /// member declarations.
    784   /// FIXME: Perhaps we should change the name of LateParsedDeclaration to
    785   /// LateParsedTokens.
    786   struct LateParsedAttribute : public LateParsedDeclaration {
    787     Parser *Self;
    788     CachedTokens Toks;
    789     IdentifierInfo &AttrName;
    790     SourceLocation AttrNameLoc;
    791     SmallVector<Decl*, 2> Decls;
    792 
    793     explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name,
    794                                  SourceLocation Loc)
    795       : Self(P), AttrName(Name), AttrNameLoc(Loc) {}
    796 
    797     virtual void ParseLexedAttributes();
    798 
    799     void addDecl(Decl *D) { Decls.push_back(D); }
    800   };
    801 
    802   // A list of late-parsed attributes.  Used by ParseGNUAttributes.
    803   class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> {
    804   public:
    805     LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { }
    806 
    807     bool parseSoon() { return ParseSoon; }
    808 
    809   private:
    810     bool ParseSoon;  // Are we planning to parse these shortly after creation?
    811   };
    812 
    813   /// Contains the lexed tokens of a member function definition
    814   /// which needs to be parsed at the end of the class declaration
    815   /// after parsing all other member declarations.
    816   struct LexedMethod : public LateParsedDeclaration {
    817     Parser *Self;
    818     Decl *D;
    819     CachedTokens Toks;
    820 
    821     /// \brief Whether this member function had an associated template
    822     /// scope. When true, D is a template declaration.
    823     /// otherwise, it is a member function declaration.
    824     bool TemplateScope;
    825 
    826     explicit LexedMethod(Parser* P, Decl *MD)
    827       : Self(P), D(MD), TemplateScope(false) {}
    828 
    829     virtual void ParseLexedMethodDefs();
    830   };
    831 
    832   /// LateParsedDefaultArgument - Keeps track of a parameter that may
    833   /// have a default argument that cannot be parsed yet because it
    834   /// occurs within a member function declaration inside the class
    835   /// (C++ [class.mem]p2).
    836   struct LateParsedDefaultArgument {
    837     explicit LateParsedDefaultArgument(Decl *P,
    838                                        CachedTokens *Toks = 0)
    839       : Param(P), Toks(Toks) { }
    840 
    841     /// Param - The parameter declaration for this parameter.
    842     Decl *Param;
    843 
    844     /// Toks - The sequence of tokens that comprises the default
    845     /// argument expression, not including the '=' or the terminating
    846     /// ')' or ','. This will be NULL for parameters that have no
    847     /// default argument.
    848     CachedTokens *Toks;
    849   };
    850 
    851   /// LateParsedMethodDeclaration - A method declaration inside a class that
    852   /// contains at least one entity whose parsing needs to be delayed
    853   /// until the class itself is completely-defined, such as a default
    854   /// argument (C++ [class.mem]p2).
    855   struct LateParsedMethodDeclaration : public LateParsedDeclaration {
    856     explicit LateParsedMethodDeclaration(Parser *P, Decl *M)
    857       : Self(P), Method(M), TemplateScope(false), ExceptionSpecTokens(0) { }
    858 
    859     virtual void ParseLexedMethodDeclarations();
    860 
    861     Parser* Self;
    862 
    863     /// Method - The method declaration.
    864     Decl *Method;
    865 
    866     /// \brief Whether this member function had an associated template
    867     /// scope. When true, D is a template declaration.
    868     /// othewise, it is a member function declaration.
    869     bool TemplateScope;
    870 
    871     /// DefaultArgs - Contains the parameters of the function and
    872     /// their default arguments. At least one of the parameters will
    873     /// have a default argument, but all of the parameters of the
    874     /// method will be stored so that they can be reintroduced into
    875     /// scope at the appropriate times.
    876     SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
    877 
    878     /// \brief The set of tokens that make up an exception-specification that
    879     /// has not yet been parsed.
    880     CachedTokens *ExceptionSpecTokens;
    881   };
    882 
    883   /// LateParsedMemberInitializer - An initializer for a non-static class data
    884   /// member whose parsing must to be delayed until the class is completely
    885   /// defined (C++11 [class.mem]p2).
    886   struct LateParsedMemberInitializer : public LateParsedDeclaration {
    887     LateParsedMemberInitializer(Parser *P, Decl *FD)
    888       : Self(P), Field(FD) { }
    889 
    890     virtual void ParseLexedMemberInitializers();
    891 
    892     Parser *Self;
    893 
    894     /// Field - The field declaration.
    895     Decl *Field;
    896 
    897     /// CachedTokens - The sequence of tokens that comprises the initializer,
    898     /// including any leading '='.
    899     CachedTokens Toks;
    900   };
    901 
    902   /// LateParsedDeclarationsContainer - During parsing of a top (non-nested)
    903   /// C++ class, its method declarations that contain parts that won't be
    904   /// parsed until after the definition is completed (C++ [class.mem]p2),
    905   /// the method declarations and possibly attached inline definitions
    906   /// will be stored here with the tokens that will be parsed to create those
    907   /// entities.
    908   typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer;
    909 
    910   /// \brief Representation of a class that has been parsed, including
    911   /// any member function declarations or definitions that need to be
    912   /// parsed after the corresponding top-level class is complete.
    913   struct ParsingClass {
    914     ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface)
    915       : TopLevelClass(TopLevelClass), TemplateScope(false),
    916         IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { }
    917 
    918     /// \brief Whether this is a "top-level" class, meaning that it is
    919     /// not nested within another class.
    920     bool TopLevelClass : 1;
    921 
    922     /// \brief Whether this class had an associated template
    923     /// scope. When true, TagOrTemplate is a template declaration;
    924     /// othewise, it is a tag declaration.
    925     bool TemplateScope : 1;
    926 
    927     /// \brief Whether this class is an __interface.
    928     bool IsInterface : 1;
    929 
    930     /// \brief The class or class template whose definition we are parsing.
    931     Decl *TagOrTemplate;
    932 
    933     /// LateParsedDeclarations - Method declarations, inline definitions and
    934     /// nested classes that contain pieces whose parsing will be delayed until
    935     /// the top-level class is fully defined.
    936     LateParsedDeclarationsContainer LateParsedDeclarations;
    937   };
    938 
    939   /// \brief The stack of classes that is currently being
    940   /// parsed. Nested and local classes will be pushed onto this stack
    941   /// when they are parsed, and removed afterward.
    942   std::stack<ParsingClass *> ClassStack;
    943 
    944   ParsingClass &getCurrentClass() {
    945     assert(!ClassStack.empty() && "No lexed method stacks!");
    946     return *ClassStack.top();
    947   }
    948 
    949   /// \brief RAII object used to manage the parsing of a class definition.
    950   class ParsingClassDefinition {
    951     Parser &P;
    952     bool Popped;
    953     Sema::ParsingClassState State;
    954 
    955   public:
    956     ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass,
    957                            bool IsInterface)
    958       : P(P), Popped(false),
    959         State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) {
    960     }
    961 
    962     /// \brief Pop this class of the stack.
    963     void Pop() {
    964       assert(!Popped && "Nested class has already been popped");
    965       Popped = true;
    966       P.PopParsingClass(State);
    967     }
    968 
    969     ~ParsingClassDefinition() {
    970       if (!Popped)
    971         P.PopParsingClass(State);
    972     }
    973   };
    974 
    975   /// \brief Contains information about any template-specific
    976   /// information that has been parsed prior to parsing declaration
    977   /// specifiers.
    978   struct ParsedTemplateInfo {
    979     ParsedTemplateInfo()
    980       : Kind(NonTemplate), TemplateParams(0), TemplateLoc() { }
    981 
    982     ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
    983                        bool isSpecialization,
    984                        bool lastParameterListWasEmpty = false)
    985       : Kind(isSpecialization? ExplicitSpecialization : Template),
    986         TemplateParams(TemplateParams),
    987         LastParameterListWasEmpty(lastParameterListWasEmpty) { }
    988 
    989     explicit ParsedTemplateInfo(SourceLocation ExternLoc,
    990                                 SourceLocation TemplateLoc)
    991       : Kind(ExplicitInstantiation), TemplateParams(0),
    992         ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
    993         LastParameterListWasEmpty(false){ }
    994 
    995     /// \brief The kind of template we are parsing.
    996     enum {
    997       /// \brief We are not parsing a template at all.
    998       NonTemplate = 0,
    999       /// \brief We are parsing a template declaration.
   1000       Template,
   1001       /// \brief We are parsing an explicit specialization.
   1002       ExplicitSpecialization,
   1003       /// \brief We are parsing an explicit instantiation.
   1004       ExplicitInstantiation
   1005     } Kind;
   1006 
   1007     /// \brief The template parameter lists, for template declarations
   1008     /// and explicit specializations.
   1009     TemplateParameterLists *TemplateParams;
   1010 
   1011     /// \brief The location of the 'extern' keyword, if any, for an explicit
   1012     /// instantiation
   1013     SourceLocation ExternLoc;
   1014 
   1015     /// \brief The location of the 'template' keyword, for an explicit
   1016     /// instantiation.
   1017     SourceLocation TemplateLoc;
   1018 
   1019     /// \brief Whether the last template parameter list was empty.
   1020     bool LastParameterListWasEmpty;
   1021 
   1022     SourceRange getSourceRange() const LLVM_READONLY;
   1023   };
   1024 
   1025   /// \brief Contains a late templated function.
   1026   /// Will be parsed at the end of the translation unit.
   1027   struct LateParsedTemplatedFunction {
   1028     explicit LateParsedTemplatedFunction(Decl *MD)
   1029       : D(MD) {}
   1030 
   1031     CachedTokens Toks;
   1032 
   1033     /// \brief The template function declaration to be late parsed.
   1034     Decl *D;
   1035   };
   1036 
   1037   void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
   1038   void ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT);
   1039   typedef llvm::DenseMap<const FunctionDecl*, LateParsedTemplatedFunction*>
   1040     LateParsedTemplateMapT;
   1041   LateParsedTemplateMapT LateParsedTemplateMap;
   1042 
   1043   static void LateTemplateParserCallback(void *P, const FunctionDecl *FD);
   1044   void LateTemplateParser(const FunctionDecl *FD);
   1045 
   1046   Sema::ParsingClassState
   1047   PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface);
   1048   void DeallocateParsedClasses(ParsingClass *Class);
   1049   void PopParsingClass(Sema::ParsingClassState);
   1050 
   1051   NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS,
   1052                                 AttributeList *AccessAttrs,
   1053                                 ParsingDeclarator &D,
   1054                                 const ParsedTemplateInfo &TemplateInfo,
   1055                                 const VirtSpecifiers& VS,
   1056                                 FunctionDefinitionKind DefinitionKind,
   1057                                 ExprResult& Init);
   1058   void ParseCXXNonStaticMemberInitializer(Decl *VarD);
   1059   void ParseLexedAttributes(ParsingClass &Class);
   1060   void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D,
   1061                                bool EnterScope, bool OnDefinition);
   1062   void ParseLexedAttribute(LateParsedAttribute &LA,
   1063                            bool EnterScope, bool OnDefinition);
   1064   void ParseLexedMethodDeclarations(ParsingClass &Class);
   1065   void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM);
   1066   void ParseLexedMethodDefs(ParsingClass &Class);
   1067   void ParseLexedMethodDef(LexedMethod &LM);
   1068   void ParseLexedMemberInitializers(ParsingClass &Class);
   1069   void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI);
   1070   void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod);
   1071   bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks);
   1072   bool ConsumeAndStoreUntil(tok::TokenKind T1,
   1073                             CachedTokens &Toks,
   1074                             bool StopAtSemi = true,
   1075                             bool ConsumeFinalToken = true) {
   1076     return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken);
   1077   }
   1078   bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
   1079                             CachedTokens &Toks,
   1080                             bool StopAtSemi = true,
   1081                             bool ConsumeFinalToken = true);
   1082 
   1083   //===--------------------------------------------------------------------===//
   1084   // C99 6.9: External Definitions.
   1085   struct ParsedAttributesWithRange : ParsedAttributes {
   1086     ParsedAttributesWithRange(AttributeFactory &factory)
   1087       : ParsedAttributes(factory) {}
   1088 
   1089     SourceRange Range;
   1090   };
   1091 
   1092   DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs,
   1093                                           ParsingDeclSpec *DS = 0);
   1094   bool isDeclarationAfterDeclarator();
   1095   bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator);
   1096   DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(
   1097                                                   ParsedAttributesWithRange &attrs,
   1098                                                   ParsingDeclSpec *DS = 0,
   1099                                                   AccessSpecifier AS = AS_none);
   1100   DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs,
   1101                                                 ParsingDeclSpec &DS,
   1102                                                 AccessSpecifier AS);
   1103 
   1104   Decl *ParseFunctionDefinition(ParsingDeclarator &D,
   1105                  const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
   1106                  LateParsedAttrList *LateParsedAttrs = 0);
   1107   void ParseKNRParamDeclarations(Declarator &D);
   1108   // EndLoc, if non-NULL, is filled with the location of the last token of
   1109   // the simple-asm.
   1110   ExprResult ParseSimpleAsm(SourceLocation *EndLoc = 0);
   1111   ExprResult ParseAsmStringLiteral();
   1112 
   1113   // Objective-C External Declarations
   1114   DeclGroupPtrTy ParseObjCAtDirectives();
   1115   DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
   1116   Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc,
   1117                                         ParsedAttributes &prefixAttrs);
   1118   void ParseObjCClassInstanceVariables(Decl *interfaceDecl,
   1119                                        tok::ObjCKeywordKind visibility,
   1120                                        SourceLocation atLoc);
   1121   bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P,
   1122                                    SmallVectorImpl<SourceLocation> &PLocs,
   1123                                    bool WarnOnDeclarations,
   1124                                    SourceLocation &LAngleLoc,
   1125                                    SourceLocation &EndProtoLoc);
   1126   bool ParseObjCProtocolQualifiers(DeclSpec &DS);
   1127   void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey,
   1128                                   Decl *CDecl);
   1129   DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
   1130                                                 ParsedAttributes &prefixAttrs);
   1131 
   1132   struct ObjCImplParsingDataRAII {
   1133     Parser &P;
   1134     Decl *Dcl;
   1135     bool HasCFunction;
   1136     typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer;
   1137     LateParsedObjCMethodContainer LateParsedObjCMethods;
   1138 
   1139     ObjCImplParsingDataRAII(Parser &parser, Decl *D)
   1140       : P(parser), Dcl(D), HasCFunction(false) {
   1141       P.CurParsedObjCImpl = this;
   1142       Finished = false;
   1143     }
   1144     ~ObjCImplParsingDataRAII();
   1145 
   1146     void finish(SourceRange AtEnd);
   1147     bool isFinished() const { return Finished; }
   1148 
   1149   private:
   1150     bool Finished;
   1151   };
   1152   ObjCImplParsingDataRAII *CurParsedObjCImpl;
   1153   void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl);
   1154 
   1155   DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc);
   1156   DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
   1157   Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc);
   1158   Decl *ParseObjCPropertySynthesize(SourceLocation atLoc);
   1159   Decl *ParseObjCPropertyDynamic(SourceLocation atLoc);
   1160 
   1161   IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
   1162   // Definitions for Objective-c context sensitive keywords recognition.
   1163   enum ObjCTypeQual {
   1164     objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
   1165     objc_NumQuals
   1166   };
   1167   IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
   1168 
   1169   bool isTokIdentifier_in() const;
   1170 
   1171   ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx,
   1172                                ParsedAttributes *ParamAttrs);
   1173   void ParseObjCMethodRequirement();
   1174   Decl *ParseObjCMethodPrototype(
   1175             tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
   1176             bool MethodDefinition = true);
   1177   Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
   1178             tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword,
   1179             bool MethodDefinition=true);
   1180   void ParseObjCPropertyAttribute(ObjCDeclSpec &DS);
   1181 
   1182   Decl *ParseObjCMethodDefinition();
   1183 
   1184 public:
   1185   //===--------------------------------------------------------------------===//
   1186   // C99 6.5: Expressions.
   1187 
   1188   /// TypeCastState - State whether an expression is or may be a type cast.
   1189   enum TypeCastState {
   1190     NotTypeCast = 0,
   1191     MaybeTypeCast,
   1192     IsTypeCast
   1193   };
   1194 
   1195   ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast);
   1196   ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast);
   1197   // Expr that doesn't include commas.
   1198   ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast);
   1199 
   1200 private:
   1201   ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
   1202 
   1203   ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
   1204 
   1205   ExprResult ParseRHSOfBinaryExpression(ExprResult LHS,
   1206                                         prec::Level MinPrec);
   1207   ExprResult ParseCastExpression(bool isUnaryExpression,
   1208                                  bool isAddressOfOperand,
   1209                                  bool &NotCastExpr,
   1210                                  TypeCastState isTypeCast);
   1211   ExprResult ParseCastExpression(bool isUnaryExpression,
   1212                                  bool isAddressOfOperand = false,
   1213                                  TypeCastState isTypeCast = NotTypeCast);
   1214 
   1215   /// Returns true if the next token cannot start an expression.
   1216   bool isNotExpressionStart();
   1217 
   1218   /// Returns true if the next token would start a postfix-expression
   1219   /// suffix.
   1220   bool isPostfixExpressionSuffixStart() {
   1221     tok::TokenKind K = Tok.getKind();
   1222     return (K == tok::l_square || K == tok::l_paren ||
   1223             K == tok::period || K == tok::arrow ||
   1224             K == tok::plusplus || K == tok::minusminus);
   1225   }
   1226 
   1227   ExprResult ParsePostfixExpressionSuffix(ExprResult LHS);
   1228   ExprResult ParseUnaryExprOrTypeTraitExpression();
   1229   ExprResult ParseBuiltinPrimaryExpression();
   1230 
   1231   ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
   1232                                                      bool &isCastExpr,
   1233                                                      ParsedType &CastTy,
   1234                                                      SourceRange &CastRange);
   1235 
   1236   typedef SmallVector<Expr*, 20> ExprListTy;
   1237   typedef SmallVector<SourceLocation, 20> CommaLocsTy;
   1238 
   1239   /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
   1240   bool ParseExpressionList(SmallVectorImpl<Expr*> &Exprs,
   1241                            SmallVectorImpl<SourceLocation> &CommaLocs,
   1242                            void (Sema::*Completer)(Scope *S,
   1243                                                    Expr *Data,
   1244                                                    ArrayRef<Expr *> Args) = 0,
   1245                            Expr *Data = 0);
   1246 
   1247   /// ParenParseOption - Control what ParseParenExpression will parse.
   1248   enum ParenParseOption {
   1249     SimpleExpr,      // Only parse '(' expression ')'
   1250     CompoundStmt,    // Also allow '(' compound-statement ')'
   1251     CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
   1252     CastExpr         // Also allow '(' type-name ')' <anything>
   1253   };
   1254   ExprResult ParseParenExpression(ParenParseOption &ExprType,
   1255                                         bool stopIfCastExpr,
   1256                                         bool isTypeCast,
   1257                                         ParsedType &CastTy,
   1258                                         SourceLocation &RParenLoc);
   1259 
   1260   ExprResult ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
   1261                                             ParsedType &CastTy,
   1262                                             BalancedDelimiterTracker &Tracker);
   1263   ExprResult ParseCompoundLiteralExpression(ParsedType Ty,
   1264                                                   SourceLocation LParenLoc,
   1265                                                   SourceLocation RParenLoc);
   1266 
   1267   ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
   1268 
   1269   ExprResult ParseGenericSelectionExpression();
   1270 
   1271   ExprResult ParseObjCBoolLiteral();
   1272 
   1273   //===--------------------------------------------------------------------===//
   1274   // C++ Expressions
   1275   ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
   1276 
   1277   bool areTokensAdjacent(const Token &A, const Token &B);
   1278 
   1279   void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr,
   1280                                   bool EnteringContext, IdentifierInfo &II,
   1281                                   CXXScopeSpec &SS);
   1282 
   1283   bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
   1284                                       ParsedType ObjectType,
   1285                                       bool EnteringContext,
   1286                                       bool *MayBePseudoDestructor = 0,
   1287                                       bool IsTypename = false);
   1288 
   1289   void CheckForLParenAfterColonColon();
   1290 
   1291   //===--------------------------------------------------------------------===//
   1292   // C++0x 5.1.2: Lambda expressions
   1293 
   1294   // [...] () -> type {...}
   1295   ExprResult ParseLambdaExpression();
   1296   ExprResult TryParseLambdaExpression();
   1297   Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro);
   1298   bool TryParseLambdaIntroducer(LambdaIntroducer &Intro);
   1299   ExprResult ParseLambdaExpressionAfterIntroducer(
   1300                LambdaIntroducer &Intro);
   1301 
   1302   //===--------------------------------------------------------------------===//
   1303   // C++ 5.2p1: C++ Casts
   1304   ExprResult ParseCXXCasts();
   1305 
   1306   //===--------------------------------------------------------------------===//
   1307   // C++ 5.2p1: C++ Type Identification
   1308   ExprResult ParseCXXTypeid();
   1309 
   1310   //===--------------------------------------------------------------------===//
   1311   //  C++ : Microsoft __uuidof Expression
   1312   ExprResult ParseCXXUuidof();
   1313 
   1314   //===--------------------------------------------------------------------===//
   1315   // C++ 5.2.4: C++ Pseudo-Destructor Expressions
   1316   ExprResult ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
   1317                                             tok::TokenKind OpKind,
   1318                                             CXXScopeSpec &SS,
   1319                                             ParsedType ObjectType);
   1320 
   1321   //===--------------------------------------------------------------------===//
   1322   // C++ 9.3.2: C++ 'this' pointer
   1323   ExprResult ParseCXXThis();
   1324 
   1325   //===--------------------------------------------------------------------===//
   1326   // C++ 15: C++ Throw Expression
   1327   ExprResult ParseThrowExpression();
   1328 
   1329   ExceptionSpecificationType tryParseExceptionSpecification(
   1330                     SourceRange &SpecificationRange,
   1331                     SmallVectorImpl<ParsedType> &DynamicExceptions,
   1332                     SmallVectorImpl<SourceRange> &DynamicExceptionRanges,
   1333                     ExprResult &NoexceptExpr);
   1334 
   1335   // EndLoc is filled with the location of the last token of the specification.
   1336   ExceptionSpecificationType ParseDynamicExceptionSpecification(
   1337                                   SourceRange &SpecificationRange,
   1338                                   SmallVectorImpl<ParsedType> &Exceptions,
   1339                                   SmallVectorImpl<SourceRange> &Ranges);
   1340 
   1341   //===--------------------------------------------------------------------===//
   1342   // C++0x 8: Function declaration trailing-return-type
   1343   TypeResult ParseTrailingReturnType(SourceRange &Range);
   1344 
   1345   //===--------------------------------------------------------------------===//
   1346   // C++ 2.13.5: C++ Boolean Literals
   1347   ExprResult ParseCXXBoolLiteral();
   1348 
   1349   //===--------------------------------------------------------------------===//
   1350   // C++ 5.2.3: Explicit type conversion (functional notation)
   1351   ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
   1352 
   1353   /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
   1354   /// This should only be called when the current token is known to be part of
   1355   /// simple-type-specifier.
   1356   void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
   1357 
   1358   bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
   1359 
   1360   //===--------------------------------------------------------------------===//
   1361   // C++ 5.3.4 and 5.3.5: C++ new and delete
   1362   bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs,
   1363                                    Declarator &D);
   1364   void ParseDirectNewDeclarator(Declarator &D);
   1365   ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
   1366   ExprResult ParseCXXDeleteExpression(bool UseGlobal,
   1367                                             SourceLocation Start);
   1368 
   1369   //===--------------------------------------------------------------------===//
   1370   // C++ if/switch/while condition expression.
   1371   bool ParseCXXCondition(ExprResult &ExprResult, Decl *&DeclResult,
   1372                          SourceLocation Loc, bool ConvertToBoolean);
   1373 
   1374   //===--------------------------------------------------------------------===//
   1375   // C++ types
   1376 
   1377   //===--------------------------------------------------------------------===//
   1378   // C99 6.7.8: Initialization.
   1379 
   1380   /// ParseInitializer
   1381   ///       initializer: [C99 6.7.8]
   1382   ///         assignment-expression
   1383   ///         '{' ...
   1384   ExprResult ParseInitializer() {
   1385     if (Tok.isNot(tok::l_brace))
   1386       return ParseAssignmentExpression();
   1387     return ParseBraceInitializer();
   1388   }
   1389   bool MayBeDesignationStart();
   1390   ExprResult ParseBraceInitializer();
   1391   ExprResult ParseInitializerWithPotentialDesignator();
   1392 
   1393   //===--------------------------------------------------------------------===//
   1394   // clang Expressions
   1395 
   1396   ExprResult ParseBlockLiteralExpression();  // ^{...}
   1397 
   1398   //===--------------------------------------------------------------------===//
   1399   // Objective-C Expressions
   1400   ExprResult ParseObjCAtExpression(SourceLocation AtLocation);
   1401   ExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
   1402   ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc);
   1403   ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc);
   1404   ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue);
   1405   ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc);
   1406   ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc);
   1407   ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc);
   1408   ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
   1409   ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
   1410   ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
   1411   bool isSimpleObjCMessageExpression();
   1412   ExprResult ParseObjCMessageExpression();
   1413   ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
   1414                                             SourceLocation SuperLoc,
   1415                                             ParsedType ReceiverType,
   1416                                             ExprArg ReceiverExpr);
   1417   ExprResult ParseAssignmentExprWithObjCMessageExprStart(
   1418       SourceLocation LBracloc, SourceLocation SuperLoc,
   1419       ParsedType ReceiverType, ExprArg ReceiverExpr);
   1420   bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr);
   1421 
   1422   //===--------------------------------------------------------------------===//
   1423   // C99 6.8: Statements and Blocks.
   1424 
   1425   /// A SmallVector of statements, with stack size 32 (as that is the only one
   1426   /// used.)
   1427   typedef SmallVector<Stmt*, 32> StmtVector;
   1428   /// A SmallVector of expressions, with stack size 12 (the maximum used.)
   1429   typedef SmallVector<Expr*, 12> ExprVector;
   1430   /// A SmallVector of types.
   1431   typedef SmallVector<ParsedType, 12> TypeVector;
   1432 
   1433   StmtResult ParseStatement(SourceLocation *TrailingElseLoc = 0) {
   1434     StmtVector Stmts;
   1435     return ParseStatementOrDeclaration(Stmts, true, TrailingElseLoc);
   1436   }
   1437   StmtResult ParseStatementOrDeclaration(StmtVector &Stmts,
   1438                                          bool OnlyStatement,
   1439                                          SourceLocation *TrailingElseLoc = 0);
   1440   StmtResult ParseStatementOrDeclarationAfterAttributes(
   1441                                          StmtVector &Stmts,
   1442                                          bool OnlyStatement,
   1443                                          SourceLocation *TrailingElseLoc,
   1444                                          ParsedAttributesWithRange &Attrs);
   1445   StmtResult ParseExprStatement();
   1446   StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs);
   1447   StmtResult ParseCaseStatement(bool MissingCase = false,
   1448                                 ExprResult Expr = ExprResult());
   1449   StmtResult ParseDefaultStatement();
   1450   StmtResult ParseCompoundStatement(bool isStmtExpr = false);
   1451   StmtResult ParseCompoundStatement(bool isStmtExpr,
   1452                                     unsigned ScopeFlags);
   1453   void ParseCompoundStatementLeadingPragmas();
   1454   StmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
   1455   bool ParseParenExprOrCondition(ExprResult &ExprResult,
   1456                                  Decl *&DeclResult,
   1457                                  SourceLocation Loc,
   1458                                  bool ConvertToBoolean);
   1459   StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc);
   1460   StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc);
   1461   StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc);
   1462   StmtResult ParseDoStatement();
   1463   StmtResult ParseForStatement(SourceLocation *TrailingElseLoc);
   1464   StmtResult ParseGotoStatement();
   1465   StmtResult ParseContinueStatement();
   1466   StmtResult ParseBreakStatement();
   1467   StmtResult ParseReturnStatement();
   1468   StmtResult ParseAsmStatement(bool &msAsm);
   1469   StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc);
   1470 
   1471   /// \brief Describes the behavior that should be taken for an __if_exists
   1472   /// block.
   1473   enum IfExistsBehavior {
   1474     /// \brief Parse the block; this code is always used.
   1475     IEB_Parse,
   1476     /// \brief Skip the block entirely; this code is never used.
   1477     IEB_Skip,
   1478     /// \brief Parse the block as a dependent block, which may be used in
   1479     /// some template instantiations but not others.
   1480     IEB_Dependent
   1481   };
   1482 
   1483   /// \brief Describes the condition of a Microsoft __if_exists or
   1484   /// __if_not_exists block.
   1485   struct IfExistsCondition {
   1486     /// \brief The location of the initial keyword.
   1487     SourceLocation KeywordLoc;
   1488     /// \brief Whether this is an __if_exists block (rather than an
   1489     /// __if_not_exists block).
   1490     bool IsIfExists;
   1491 
   1492     /// \brief Nested-name-specifier preceding the name.
   1493     CXXScopeSpec SS;
   1494 
   1495     /// \brief The name we're looking for.
   1496     UnqualifiedId Name;
   1497 
   1498     /// \brief The behavior of this __if_exists or __if_not_exists block
   1499     /// should.
   1500     IfExistsBehavior Behavior;
   1501   };
   1502 
   1503   bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result);
   1504   void ParseMicrosoftIfExistsStatement(StmtVector &Stmts);
   1505   void ParseMicrosoftIfExistsExternalDeclaration();
   1506   void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType,
   1507                                               AccessSpecifier& CurAS);
   1508   bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs,
   1509                                               bool &InitExprsOk);
   1510   bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
   1511                            SmallVectorImpl<Expr *> &Constraints,
   1512                            SmallVectorImpl<Expr *> &Exprs);
   1513 
   1514   //===--------------------------------------------------------------------===//
   1515   // C++ 6: Statements and Blocks
   1516 
   1517   StmtResult ParseCXXTryBlock();
   1518   StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false);
   1519   StmtResult ParseCXXCatchBlock(bool FnCatch = false);
   1520 
   1521   //===--------------------------------------------------------------------===//
   1522   // MS: SEH Statements and Blocks
   1523 
   1524   StmtResult ParseSEHTryBlock();
   1525   StmtResult ParseSEHTryBlockCommon(SourceLocation Loc);
   1526   StmtResult ParseSEHExceptBlock(SourceLocation Loc);
   1527   StmtResult ParseSEHFinallyBlock(SourceLocation Loc);
   1528 
   1529   //===--------------------------------------------------------------------===//
   1530   // Objective-C Statements
   1531 
   1532   StmtResult ParseObjCAtStatement(SourceLocation atLoc);
   1533   StmtResult ParseObjCTryStmt(SourceLocation atLoc);
   1534   StmtResult ParseObjCThrowStmt(SourceLocation atLoc);
   1535   StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
   1536   StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc);
   1537 
   1538 
   1539   //===--------------------------------------------------------------------===//
   1540   // C99 6.7: Declarations.
   1541 
   1542   /// A context for parsing declaration specifiers.  TODO: flesh this
   1543   /// out, there are other significant restrictions on specifiers than
   1544   /// would be best implemented in the parser.
   1545   enum DeclSpecContext {
   1546     DSC_normal, // normal context
   1547     DSC_class,  // class context, enables 'friend'
   1548     DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list
   1549     DSC_trailing, // C++11 trailing-type-specifier in a trailing return type
   1550     DSC_top_level // top-level/namespace declaration context
   1551   };
   1552 
   1553   /// Information on a C++0x for-range-initializer found while parsing a
   1554   /// declaration which turns out to be a for-range-declaration.
   1555   struct ForRangeInit {
   1556     SourceLocation ColonLoc;
   1557     ExprResult RangeExpr;
   1558 
   1559     bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); }
   1560   };
   1561 
   1562   DeclGroupPtrTy ParseDeclaration(StmtVector &Stmts,
   1563                                   unsigned Context, SourceLocation &DeclEnd,
   1564                                   ParsedAttributesWithRange &attrs);
   1565   DeclGroupPtrTy ParseSimpleDeclaration(StmtVector &Stmts,
   1566                                         unsigned Context,
   1567                                         SourceLocation &DeclEnd,
   1568                                         ParsedAttributesWithRange &attrs,
   1569                                         bool RequireSemi,
   1570                                         ForRangeInit *FRI = 0);
   1571   bool MightBeDeclarator(unsigned Context);
   1572   DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
   1573                                 bool AllowFunctionDefinitions,
   1574                                 SourceLocation *DeclEnd = 0,
   1575                                 ForRangeInit *FRI = 0);
   1576   Decl *ParseDeclarationAfterDeclarator(Declarator &D,
   1577                const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
   1578   bool ParseAsmAttributesAfterDeclarator(Declarator &D);
   1579   Decl *ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D,
   1580                const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
   1581   Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope);
   1582   Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope);
   1583 
   1584   /// \brief When in code-completion, skip parsing of the function/method body
   1585   /// unless the body contains the code-completion point.
   1586   ///
   1587   /// \returns true if the function body was skipped.
   1588   bool trySkippingFunctionBody();
   1589 
   1590   bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
   1591                         const ParsedTemplateInfo &TemplateInfo,
   1592                         AccessSpecifier AS, DeclSpecContext DSC,
   1593                         ParsedAttributesWithRange &Attrs);
   1594   DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
   1595   void ParseDeclarationSpecifiers(DeclSpec &DS,
   1596                 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
   1597                                   AccessSpecifier AS = AS_none,
   1598                                   DeclSpecContext DSC = DSC_normal,
   1599                                   LateParsedAttrList *LateAttrs = 0);
   1600 
   1601   void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none,
   1602                                    DeclSpecContext DSC = DSC_normal);
   1603 
   1604   void ParseObjCTypeQualifierList(ObjCDeclSpec &DS,
   1605                                   Declarator::TheContext Context);
   1606 
   1607   void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
   1608                           const ParsedTemplateInfo &TemplateInfo,
   1609                           AccessSpecifier AS, DeclSpecContext DSC);
   1610   void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl);
   1611   void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
   1612                             Decl *TagDecl);
   1613 
   1614   struct FieldCallback {
   1615     virtual void invoke(ParsingFieldDeclarator &Field) = 0;
   1616     virtual ~FieldCallback() {}
   1617 
   1618   private:
   1619     virtual void _anchor();
   1620   };
   1621   struct ObjCPropertyCallback;
   1622 
   1623   void ParseStructDeclaration(ParsingDeclSpec &DS, FieldCallback &Callback);
   1624 
   1625   bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false);
   1626   bool isTypeSpecifierQualifier();
   1627   bool isTypeQualifier() const;
   1628 
   1629   /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
   1630   /// is definitely a type-specifier.  Return false if it isn't part of a type
   1631   /// specifier or if we're not sure.
   1632   bool isKnownToBeTypeSpecifier(const Token &Tok) const;
   1633 
   1634   /// \brief Return true if we know that we are definitely looking at a
   1635   /// decl-specifier, and isn't part of an expression such as a function-style
   1636   /// cast. Return false if it's no a decl-specifier, or we're not sure.
   1637   bool isKnownToBeDeclarationSpecifier() {
   1638     if (getLangOpts().CPlusPlus)
   1639       return isCXXDeclarationSpecifier() == TPResult::True();
   1640     return isDeclarationSpecifier(true);
   1641   }
   1642 
   1643   /// isDeclarationStatement - Disambiguates between a declaration or an
   1644   /// expression statement, when parsing function bodies.
   1645   /// Returns true for declaration, false for expression.
   1646   bool isDeclarationStatement() {
   1647     if (getLangOpts().CPlusPlus)
   1648       return isCXXDeclarationStatement();
   1649     return isDeclarationSpecifier(true);
   1650   }
   1651 
   1652   /// isForInitDeclaration - Disambiguates between a declaration or an
   1653   /// expression in the context of the C 'clause-1' or the C++
   1654   // 'for-init-statement' part of a 'for' statement.
   1655   /// Returns true for declaration, false for expression.
   1656   bool isForInitDeclaration() {
   1657     if (getLangOpts().CPlusPlus)
   1658       return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true);
   1659     return isDeclarationSpecifier(true);
   1660   }
   1661 
   1662   /// \brief Determine whether we are currently at the start of an Objective-C
   1663   /// class message that appears to be missing the open bracket '['.
   1664   bool isStartOfObjCClassMessageMissingOpenBracket();
   1665 
   1666   /// \brief Starting with a scope specifier, identifier, or
   1667   /// template-id that refers to the current class, determine whether
   1668   /// this is a constructor declarator.
   1669   bool isConstructorDeclarator();
   1670 
   1671   /// \brief Specifies the context in which type-id/expression
   1672   /// disambiguation will occur.
   1673   enum TentativeCXXTypeIdContext {
   1674     TypeIdInParens,
   1675     TypeIdAsTemplateArgument
   1676   };
   1677 
   1678 
   1679   /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
   1680   /// whether the parens contain an expression or a type-id.
   1681   /// Returns true for a type-id and false for an expression.
   1682   bool isTypeIdInParens(bool &isAmbiguous) {
   1683     if (getLangOpts().CPlusPlus)
   1684       return isCXXTypeId(TypeIdInParens, isAmbiguous);
   1685     isAmbiguous = false;
   1686     return isTypeSpecifierQualifier();
   1687   }
   1688   bool isTypeIdInParens() {
   1689     bool isAmbiguous;
   1690     return isTypeIdInParens(isAmbiguous);
   1691   }
   1692 
   1693   /// isCXXDeclarationStatement - C++-specialized function that disambiguates
   1694   /// between a declaration or an expression statement, when parsing function
   1695   /// bodies. Returns true for declaration, false for expression.
   1696   bool isCXXDeclarationStatement();
   1697 
   1698   /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
   1699   /// between a simple-declaration or an expression-statement.
   1700   /// If during the disambiguation process a parsing error is encountered,
   1701   /// the function returns true to let the declaration parsing code handle it.
   1702   /// Returns false if the statement is disambiguated as expression.
   1703   bool isCXXSimpleDeclaration(bool AllowForRangeDecl);
   1704 
   1705   /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
   1706   /// a constructor-style initializer, when parsing declaration statements.
   1707   /// Returns true for function declarator and false for constructor-style
   1708   /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration
   1709   /// might be a constructor-style initializer.
   1710   /// If during the disambiguation process a parsing error is encountered,
   1711   /// the function returns true to let the declaration parsing code handle it.
   1712   bool isCXXFunctionDeclarator(bool *IsAmbiguous = 0);
   1713 
   1714   /// isCXXConditionDeclaration - Disambiguates between a declaration or an
   1715   /// expression for a condition of a if/switch/while/for statement.
   1716   /// If during the disambiguation process a parsing error is encountered,
   1717   /// the function returns true to let the declaration parsing code handle it.
   1718   bool isCXXConditionDeclaration();
   1719 
   1720   bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
   1721   bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
   1722     bool isAmbiguous;
   1723     return isCXXTypeId(Context, isAmbiguous);
   1724   }
   1725 
   1726   /// TPResult - Used as the result value for functions whose purpose is to
   1727   /// disambiguate C++ constructs by "tentatively parsing" them.
   1728   /// This is a class instead of a simple enum because the implicit enum-to-bool
   1729   /// conversions may cause subtle bugs.
   1730   class TPResult {
   1731     enum Result {
   1732       TPR_true,
   1733       TPR_false,
   1734       TPR_ambiguous,
   1735       TPR_error
   1736     };
   1737     Result Res;
   1738     TPResult(Result result) : Res(result) {}
   1739   public:
   1740     static TPResult True() { return TPR_true; }
   1741     static TPResult False() { return TPR_false; }
   1742     static TPResult Ambiguous() { return TPR_ambiguous; }
   1743     static TPResult Error() { return TPR_error; }
   1744 
   1745     bool operator==(const TPResult &RHS) const { return Res == RHS.Res; }
   1746     bool operator!=(const TPResult &RHS) const { return Res != RHS.Res; }
   1747   };
   1748 
   1749   /// \brief Based only on the given token kind, determine whether we know that
   1750   /// we're at the start of an expression or a type-specifier-seq (which may
   1751   /// be an expression, in C++).
   1752   ///
   1753   /// This routine does not attempt to resolve any of the trick cases, e.g.,
   1754   /// those involving lookup of identifiers.
   1755   ///
   1756   /// \returns \c TPR_true if this token starts an expression, \c TPR_false if
   1757   /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot
   1758   /// tell.
   1759   TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind);
   1760 
   1761   /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a
   1762   /// declaration specifier, TPResult::False() if it is not,
   1763   /// TPResult::Ambiguous() if it could be either a decl-specifier or a
   1764   /// function-style cast, and TPResult::Error() if a parsing error was
   1765   /// encountered. If it could be a braced C++11 function-style cast, returns
   1766   /// BracedCastResult.
   1767   /// Doesn't consume tokens.
   1768   TPResult
   1769   isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False(),
   1770                             bool *HasMissingTypename = 0);
   1771 
   1772   /// \brief Determine whether an identifier has been tentatively declared as a
   1773   /// non-type. Such tentative declarations should not be found to name a type
   1774   /// during a tentative parse, but also should not be annotated as a non-type.
   1775   bool isTentativelyDeclared(IdentifierInfo *II);
   1776 
   1777   // "Tentative parsing" functions, used for disambiguation. If a parsing error
   1778   // is encountered they will return TPResult::Error().
   1779   // Returning TPResult::True()/False() indicates that the ambiguity was
   1780   // resolved and tentative parsing may stop. TPResult::Ambiguous() indicates
   1781   // that more tentative parsing is necessary for disambiguation.
   1782   // They all consume tokens, so backtracking should be used after calling them.
   1783 
   1784   TPResult TryParseDeclarationSpecifier(bool *HasMissingTypename = 0);
   1785   TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl);
   1786   TPResult TryParseTypeofSpecifier();
   1787   TPResult TryParseProtocolQualifiers();
   1788   TPResult TryParseInitDeclaratorList();
   1789   TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
   1790   TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = 0);
   1791   TPResult TryParseFunctionDeclarator();
   1792   TPResult TryParseBracketDeclarator();
   1793 
   1794 public:
   1795   TypeResult ParseTypeName(SourceRange *Range = 0,
   1796                            Declarator::TheContext Context
   1797                              = Declarator::TypeNameContext,
   1798                            AccessSpecifier AS = AS_none,
   1799                            Decl **OwnedType = 0,
   1800                            ParsedAttributes *Attrs = 0);
   1801 
   1802 private:
   1803   void ParseBlockId(SourceLocation CaretLoc);
   1804 
   1805   // Check for the start of a C++11 attribute-specifier-seq in a context where
   1806   // an attribute is not allowed.
   1807   bool CheckProhibitedCXX11Attribute() {
   1808     assert(Tok.is(tok::l_square));
   1809     if (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))
   1810       return false;
   1811     return DiagnoseProhibitedCXX11Attribute();
   1812   }
   1813   bool DiagnoseProhibitedCXX11Attribute();
   1814   void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
   1815                                     SourceLocation CorrectLocation) {
   1816     if (!getLangOpts().CPlusPlus11)
   1817       return;
   1818     if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) &&
   1819         Tok.isNot(tok::kw_alignas))
   1820       return;
   1821     DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation);
   1822   }
   1823   void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs,
   1824                                        SourceLocation CorrectLocation);
   1825 
   1826   void ProhibitAttributes(ParsedAttributesWithRange &attrs) {
   1827     if (!attrs.Range.isValid()) return;
   1828     DiagnoseProhibitedAttributes(attrs);
   1829     attrs.clear();
   1830   }
   1831   void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs);
   1832 
   1833   // Forbid C++11 attributes that appear on certain syntactic
   1834   // locations which standard permits but we don't supported yet,
   1835   // for example, attributes appertain to decl specifiers.
   1836   void ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs);
   1837 
   1838   void MaybeParseGNUAttributes(Declarator &D,
   1839                                LateParsedAttrList *LateAttrs = 0) {
   1840     if (Tok.is(tok::kw___attribute)) {
   1841       ParsedAttributes attrs(AttrFactory);
   1842       SourceLocation endLoc;
   1843       ParseGNUAttributes(attrs, &endLoc, LateAttrs);
   1844       D.takeAttributes(attrs, endLoc);
   1845     }
   1846   }
   1847   void MaybeParseGNUAttributes(ParsedAttributes &attrs,
   1848                                SourceLocation *endLoc = 0,
   1849                                LateParsedAttrList *LateAttrs = 0) {
   1850     if (Tok.is(tok::kw___attribute))
   1851       ParseGNUAttributes(attrs, endLoc, LateAttrs);
   1852   }
   1853   void ParseGNUAttributes(ParsedAttributes &attrs,
   1854                           SourceLocation *endLoc = 0,
   1855                           LateParsedAttrList *LateAttrs = 0);
   1856   void ParseGNUAttributeArgs(IdentifierInfo *AttrName,
   1857                              SourceLocation AttrNameLoc,
   1858                              ParsedAttributes &Attrs,
   1859                              SourceLocation *EndLoc,
   1860                              IdentifierInfo *ScopeName,
   1861                              SourceLocation ScopeLoc,
   1862                              AttributeList::Syntax Syntax);
   1863 
   1864   void MaybeParseCXX11Attributes(Declarator &D) {
   1865     if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
   1866       ParsedAttributesWithRange attrs(AttrFactory);
   1867       SourceLocation endLoc;
   1868       ParseCXX11Attributes(attrs, &endLoc);
   1869       D.takeAttributes(attrs, endLoc);
   1870     }
   1871   }
   1872   void MaybeParseCXX11Attributes(ParsedAttributes &attrs,
   1873                                  SourceLocation *endLoc = 0) {
   1874     if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) {
   1875       ParsedAttributesWithRange attrsWithRange(AttrFactory);
   1876       ParseCXX11Attributes(attrsWithRange, endLoc);
   1877       attrs.takeAllFrom(attrsWithRange);
   1878     }
   1879   }
   1880   void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs,
   1881                                  SourceLocation *endLoc = 0,
   1882                                  bool OuterMightBeMessageSend = false) {
   1883     if (getLangOpts().CPlusPlus11 &&
   1884         isCXX11AttributeSpecifier(false, OuterMightBeMessageSend))
   1885       ParseCXX11Attributes(attrs, endLoc);
   1886   }
   1887 
   1888   void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs,
   1889                                     SourceLocation *EndLoc = 0);
   1890   void ParseCXX11Attributes(ParsedAttributesWithRange &attrs,
   1891                             SourceLocation *EndLoc = 0);
   1892 
   1893   IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc);
   1894 
   1895   void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs,
   1896                                      SourceLocation *endLoc = 0) {
   1897     if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square))
   1898       ParseMicrosoftAttributes(attrs, endLoc);
   1899   }
   1900   void ParseMicrosoftAttributes(ParsedAttributes &attrs,
   1901                                 SourceLocation *endLoc = 0);
   1902   void ParseMicrosoftDeclSpec(ParsedAttributes &Attrs);
   1903   bool IsSimpleMicrosoftDeclSpec(IdentifierInfo *Ident);
   1904   void ParseComplexMicrosoftDeclSpec(IdentifierInfo *Ident,
   1905                                      SourceLocation Loc,
   1906                                      ParsedAttributes &Attrs);
   1907   void ParseMicrosoftDeclSpecWithSingleArg(IdentifierInfo *AttrName,
   1908                                            SourceLocation AttrNameLoc,
   1909                                            ParsedAttributes &Attrs);
   1910   void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs);
   1911   void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs);
   1912   void ParseBorlandTypeAttributes(ParsedAttributes &attrs);
   1913   void ParseOpenCLAttributes(ParsedAttributes &attrs);
   1914   void ParseOpenCLQualifiers(DeclSpec &DS);
   1915 
   1916   VersionTuple ParseVersionTuple(SourceRange &Range);
   1917   void ParseAvailabilityAttribute(IdentifierInfo &Availability,
   1918                                   SourceLocation AvailabilityLoc,
   1919                                   ParsedAttributes &attrs,
   1920                                   SourceLocation *endLoc);
   1921 
   1922   bool IsThreadSafetyAttribute(StringRef AttrName);
   1923   void ParseThreadSafetyAttribute(IdentifierInfo &AttrName,
   1924                                   SourceLocation AttrNameLoc,
   1925                                   ParsedAttributes &Attrs,
   1926                                   SourceLocation *EndLoc);
   1927 
   1928   void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName,
   1929                                         SourceLocation AttrNameLoc,
   1930                                         ParsedAttributes &Attrs,
   1931                                         SourceLocation *EndLoc);
   1932 
   1933   void ParseTypeofSpecifier(DeclSpec &DS);
   1934   SourceLocation ParseDecltypeSpecifier(DeclSpec &DS);
   1935   void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS,
   1936                                          SourceLocation StartLoc,
   1937                                          SourceLocation EndLoc);
   1938   void ParseUnderlyingTypeSpecifier(DeclSpec &DS);
   1939   void ParseAtomicSpecifier(DeclSpec &DS);
   1940 
   1941   ExprResult ParseAlignArgument(SourceLocation Start,
   1942                                 SourceLocation &EllipsisLoc);
   1943   void ParseAlignmentSpecifier(ParsedAttributes &Attrs,
   1944                                SourceLocation *endLoc = 0);
   1945 
   1946   VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const;
   1947   VirtSpecifiers::Specifier isCXX11VirtSpecifier() const {
   1948     return isCXX11VirtSpecifier(Tok);
   1949   }
   1950   void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface);
   1951 
   1952   bool isCXX11FinalKeyword() const;
   1953 
   1954   /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
   1955   /// enter a new C++ declarator scope and exit it when the function is
   1956   /// finished.
   1957   class DeclaratorScopeObj {
   1958     Parser &P;
   1959     CXXScopeSpec &SS;
   1960     bool EnteredScope;
   1961     bool CreatedScope;
   1962   public:
   1963     DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
   1964       : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
   1965 
   1966     void EnterDeclaratorScope() {
   1967       assert(!EnteredScope && "Already entered the scope!");
   1968       assert(SS.isSet() && "C++ scope was not set!");
   1969 
   1970       CreatedScope = true;
   1971       P.EnterScope(0); // Not a decl scope.
   1972 
   1973       if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS))
   1974         EnteredScope = true;
   1975     }
   1976 
   1977     ~DeclaratorScopeObj() {
   1978       if (EnteredScope) {
   1979         assert(SS.isSet() && "C++ scope was cleared ?");
   1980         P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS);
   1981       }
   1982       if (CreatedScope)
   1983         P.ExitScope();
   1984     }
   1985   };
   1986 
   1987   /// ParseDeclarator - Parse and verify a newly-initialized declarator.
   1988   void ParseDeclarator(Declarator &D);
   1989   /// A function that parses a variant of direct-declarator.
   1990   typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
   1991   void ParseDeclaratorInternal(Declarator &D,
   1992                                DirectDeclParseFunction DirectDeclParser);
   1993 
   1994   void ParseTypeQualifierListOpt(DeclSpec &DS, bool GNUAttributesAllowed = true,
   1995                                  bool CXX11AttributesAllowed = true);
   1996   void ParseDirectDeclarator(Declarator &D);
   1997   void ParseParenDeclarator(Declarator &D);
   1998   void ParseFunctionDeclarator(Declarator &D,
   1999                                ParsedAttributes &attrs,
   2000                                BalancedDelimiterTracker &Tracker,
   2001                                bool IsAmbiguous,
   2002                                bool RequiresArg = false);
   2003   bool isFunctionDeclaratorIdentifierList();
   2004   void ParseFunctionDeclaratorIdentifierList(
   2005          Declarator &D,
   2006          SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo);
   2007   void ParseParameterDeclarationClause(
   2008          Declarator &D,
   2009          ParsedAttributes &attrs,
   2010          SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo,
   2011          SourceLocation &EllipsisLoc);
   2012   void ParseBracketDeclarator(Declarator &D);
   2013 
   2014   //===--------------------------------------------------------------------===//
   2015   // C++ 7: Declarations [dcl.dcl]
   2016 
   2017   /// The kind of attribute specifier we have found.
   2018   enum CXX11AttributeKind {
   2019     /// This is not an attribute specifier.
   2020     CAK_NotAttributeSpecifier,
   2021     /// This should be treated as an attribute-specifier.
   2022     CAK_AttributeSpecifier,
   2023     /// The next tokens are '[[', but this is not an attribute-specifier. This
   2024     /// is ill-formed by C++11 [dcl.attr.grammar]p6.
   2025     CAK_InvalidAttributeSpecifier
   2026   };
   2027   CXX11AttributeKind
   2028   isCXX11AttributeSpecifier(bool Disambiguate = false,
   2029                             bool OuterMightBeMessageSend = false);
   2030 
   2031   Decl *ParseNamespace(unsigned Context, SourceLocation &DeclEnd,
   2032                        SourceLocation InlineLoc = SourceLocation());
   2033   void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc,
   2034                            std::vector<IdentifierInfo*>& Ident,
   2035                            std::vector<SourceLocation>& NamespaceLoc,
   2036                            unsigned int index, SourceLocation& InlineLoc,
   2037                            ParsedAttributes& attrs,
   2038                            BalancedDelimiterTracker &Tracker);
   2039   Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
   2040   Decl *ParseUsingDirectiveOrDeclaration(unsigned Context,
   2041                                          const ParsedTemplateInfo &TemplateInfo,
   2042                                          SourceLocation &DeclEnd,
   2043                                          ParsedAttributesWithRange &attrs,
   2044                                          Decl **OwnedType = 0);
   2045   Decl *ParseUsingDirective(unsigned Context,
   2046                             SourceLocation UsingLoc,
   2047                             SourceLocation &DeclEnd,
   2048                             ParsedAttributes &attrs);
   2049   Decl *ParseUsingDeclaration(unsigned Context,
   2050                               const ParsedTemplateInfo &TemplateInfo,
   2051                               SourceLocation UsingLoc,
   2052                               SourceLocation &DeclEnd,
   2053                               AccessSpecifier AS = AS_none,
   2054                               Decl **OwnedType = 0);
   2055   Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
   2056   Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc,
   2057                             SourceLocation AliasLoc, IdentifierInfo *Alias,
   2058                             SourceLocation &DeclEnd);
   2059 
   2060   //===--------------------------------------------------------------------===//
   2061   // C++ 9: classes [class] and C structs/unions.
   2062   bool isValidAfterTypeSpecifier(bool CouldBeBitfield);
   2063   void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
   2064                            DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo,
   2065                            AccessSpecifier AS, bool EnteringContext,
   2066                            DeclSpecContext DSC,
   2067                            ParsedAttributesWithRange &Attributes);
   2068   void ParseCXXMemberSpecification(SourceLocation StartLoc,
   2069                                    SourceLocation AttrFixitLoc,
   2070                                    ParsedAttributesWithRange &Attrs,
   2071                                    unsigned TagType,
   2072                                    Decl *TagDecl);
   2073   ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction,
   2074                                        SourceLocation &EqualLoc);
   2075   void ParseCXXClassMemberDeclaration(AccessSpecifier AS, AttributeList *Attr,
   2076                 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
   2077                                  ParsingDeclRAIIObject *DiagsFromTParams = 0);
   2078   void ParseConstructorInitializer(Decl *ConstructorDecl);
   2079   MemInitResult ParseMemInitializer(Decl *ConstructorDecl);
   2080   void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo,
   2081                                       Decl *ThisDecl);
   2082 
   2083   //===--------------------------------------------------------------------===//
   2084   // C++ 10: Derived classes [class.derived]
   2085   TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc,
   2086                                     SourceLocation &EndLocation);
   2087   void ParseBaseClause(Decl *ClassDecl);
   2088   BaseResult ParseBaseSpecifier(Decl *ClassDecl);
   2089   AccessSpecifier getAccessSpecifierIfPresent() const;
   2090 
   2091   bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
   2092                                     SourceLocation TemplateKWLoc,
   2093                                     IdentifierInfo *Name,
   2094                                     SourceLocation NameLoc,
   2095                                     bool EnteringContext,
   2096                                     ParsedType ObjectType,
   2097                                     UnqualifiedId &Id,
   2098                                     bool AssumeTemplateId);
   2099   bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
   2100                                   ParsedType ObjectType,
   2101                                   UnqualifiedId &Result);
   2102 
   2103 public:
   2104   bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
   2105                           bool AllowDestructorName,
   2106                           bool AllowConstructorName,
   2107                           ParsedType ObjectType,
   2108                           SourceLocation& TemplateKWLoc,
   2109                           UnqualifiedId &Result);
   2110 
   2111 private:
   2112   //===--------------------------------------------------------------------===//
   2113   // C++ 14: Templates [temp]
   2114 
   2115   // C++ 14.1: Template Parameters [temp.param]
   2116   Decl *ParseDeclarationStartingWithTemplate(unsigned Context,
   2117                                              SourceLocation &DeclEnd,
   2118                                              AccessSpecifier AS = AS_none,
   2119                                              AttributeList *AccessAttrs = 0);
   2120   Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context,
   2121                                                  SourceLocation &DeclEnd,
   2122                                                  AccessSpecifier AS,
   2123                                                  AttributeList *AccessAttrs);
   2124   Decl *ParseSingleDeclarationAfterTemplate(
   2125                                        unsigned Context,
   2126                                        const ParsedTemplateInfo &TemplateInfo,
   2127                                        ParsingDeclRAIIObject &DiagsFromParams,
   2128                                        SourceLocation &DeclEnd,
   2129                                        AccessSpecifier AS=AS_none,
   2130                                        AttributeList *AccessAttrs = 0);
   2131   bool ParseTemplateParameters(unsigned Depth,
   2132                                SmallVectorImpl<Decl*> &TemplateParams,
   2133                                SourceLocation &LAngleLoc,
   2134                                SourceLocation &RAngleLoc);
   2135   bool ParseTemplateParameterList(unsigned Depth,
   2136                                   SmallVectorImpl<Decl*> &TemplateParams);
   2137   bool isStartOfTemplateTypeParameter();
   2138   Decl *ParseTemplateParameter(unsigned Depth, unsigned Position);
   2139   Decl *ParseTypeParameter(unsigned Depth, unsigned Position);
   2140   Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
   2141   Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
   2142   // C++ 14.3: Template arguments [temp.arg]
   2143   typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
   2144 
   2145   bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc,
   2146                                       bool ConsumeLastToken);
   2147   bool ParseTemplateIdAfterTemplateName(TemplateTy Template,
   2148                                         SourceLocation TemplateNameLoc,
   2149                                         const CXXScopeSpec &SS,
   2150                                         bool ConsumeLastToken,
   2151                                         SourceLocation &LAngleLoc,
   2152                                         TemplateArgList &TemplateArgs,
   2153                                         SourceLocation &RAngleLoc);
   2154 
   2155   bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
   2156                                CXXScopeSpec &SS,
   2157                                SourceLocation TemplateKWLoc,
   2158                                UnqualifiedId &TemplateName,
   2159                                bool AllowTypeAnnotation = true);
   2160   void AnnotateTemplateIdTokenAsType();
   2161   bool IsTemplateArgumentList(unsigned Skip = 0);
   2162   bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
   2163   ParsedTemplateArgument ParseTemplateTemplateArgument();
   2164   ParsedTemplateArgument ParseTemplateArgument();
   2165   Decl *ParseExplicitInstantiation(unsigned Context,
   2166                                    SourceLocation ExternLoc,
   2167                                    SourceLocation TemplateLoc,
   2168                                    SourceLocation &DeclEnd,
   2169                                    AccessSpecifier AS = AS_none);
   2170 
   2171   //===--------------------------------------------------------------------===//
   2172   // Modules
   2173   DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc);
   2174 
   2175   //===--------------------------------------------------------------------===//
   2176   // GNU G++: Type Traits [Type-Traits.html in the GCC manual]
   2177   ExprResult ParseUnaryTypeTrait();
   2178   ExprResult ParseBinaryTypeTrait();
   2179   ExprResult ParseTypeTrait();
   2180 
   2181   //===--------------------------------------------------------------------===//
   2182   // Embarcadero: Arary and Expression Traits
   2183   ExprResult ParseArrayTypeTrait();
   2184   ExprResult ParseExpressionTrait();
   2185 
   2186   //===--------------------------------------------------------------------===//
   2187   // Preprocessor code-completion pass-through
   2188   virtual void CodeCompleteDirective(bool InConditional);
   2189   virtual void CodeCompleteInConditionalExclusion();
   2190   virtual void CodeCompleteMacroName(bool IsDefinition);
   2191   virtual void CodeCompletePreprocessorExpression();
   2192   virtual void CodeCompleteMacroArgument(IdentifierInfo *Macro,
   2193                                          MacroInfo *MacroInfo,
   2194                                          unsigned ArgumentIndex);
   2195   virtual void CodeCompleteNaturalLanguage();
   2196 };
   2197 
   2198 }  // end namespace clang
   2199 
   2200 #endif
   2201