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