clang API Documentation

Parser.h

Go to the documentation of this file.
00001 //===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the Parser interface.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_CLANG_PARSE_PARSER_H
00015 #define LLVM_CLANG_PARSE_PARSER_H
00016 
00017 #include "clang/Basic/Specifiers.h"
00018 #include "clang/Lex/Preprocessor.h"
00019 #include "clang/Parse/Action.h"
00020 #include "clang/Parse/DeclSpec.h"
00021 #include "llvm/ADT/OwningPtr.h"
00022 #include <stack>
00023 #include <list>
00024 
00025 namespace clang {
00026   class AttributeList;
00027   struct CXX0XAttributeList;
00028   class PragmaHandler;
00029   class Scope;
00030   class DiagnosticBuilder;
00031   class Parser;
00032   class PragmaUnusedHandler;
00033   class ColonProtectionRAIIObject;
00034 
00035 /// PrettyStackTraceParserEntry - If a crash happens while the parser is active,
00036 /// an entry is printed for it.
00037 class PrettyStackTraceParserEntry : public llvm::PrettyStackTraceEntry {
00038   const Parser &P;
00039 public:
00040   PrettyStackTraceParserEntry(const Parser &p) : P(p) {}
00041   virtual void print(llvm::raw_ostream &OS) const;
00042 };
00043 
00044 
00045 /// Parser - This implements a parser for the C family of languages.  After
00046 /// parsing units of the grammar, productions are invoked to handle whatever has
00047 /// been read.
00048 ///
00049 class Parser {
00050   friend class PragmaUnusedHandler;
00051   friend class ColonProtectionRAIIObject;
00052   PrettyStackTraceParserEntry CrashInfo;
00053 
00054   Preprocessor &PP;
00055 
00056   /// Tok - The current token we are peeking ahead.  All parsing methods assume
00057   /// that this is valid.
00058   Token Tok;
00059 
00060   // PrevTokLocation - The location of the token we previously
00061   // consumed. This token is used for diagnostics where we expected to
00062   // see a token following another token (e.g., the ';' at the end of
00063   // a statement).
00064   SourceLocation PrevTokLocation;
00065 
00066   unsigned short ParenCount, BracketCount, BraceCount;
00067 
00068   /// Actions - These are the callbacks we invoke as we parse various constructs
00069   /// in the file.  This refers to the common base class between MinimalActions
00070   /// and SemaActions for those uses that don't matter.
00071   Action &Actions;
00072 
00073   Scope *CurScope;
00074   Diagnostic &Diags;
00075 
00076   /// ScopeCache - Cache scopes to reduce malloc traffic.
00077   enum { ScopeCacheSize = 16 };
00078   unsigned NumCachedScopes;
00079   Scope *ScopeCache[ScopeCacheSize];
00080 
00081   /// Ident_super - IdentifierInfo for "super", to support fast
00082   /// comparison.
00083   IdentifierInfo *Ident_super;
00084   /// Ident_vector and Ident_pixel - cached IdentifierInfo's for
00085   /// "vector" and "pixel" fast comparison.  Only present if
00086   /// AltiVec enabled.
00087   IdentifierInfo *Ident_vector;
00088   IdentifierInfo *Ident_pixel;
00089 
00090   llvm::OwningPtr<PragmaHandler> PackHandler;
00091   llvm::OwningPtr<PragmaHandler> UnusedHandler;
00092   llvm::OwningPtr<PragmaHandler> WeakHandler;
00093   llvm::OwningPtr<clang::CommentHandler> CommentHandler;
00094 
00095   /// Whether the '>' token acts as an operator or not. This will be
00096   /// true except when we are parsing an expression within a C++
00097   /// template argument list, where the '>' closes the template
00098   /// argument list.
00099   bool GreaterThanIsOperator;
00100   
00101   /// ColonIsSacred - When this is false, we aggressively try to recover from
00102   /// code like "foo : bar" as if it were a typo for "foo :: bar".  This is not
00103   /// safe in case statements and a few other things.  This is managed by the
00104   /// ColonProtectionRAIIObject RAII object.
00105   bool ColonIsSacred;
00106 
00107   /// The "depth" of the template parameters currently being parsed.
00108   unsigned TemplateParameterDepth;
00109 
00110 public:
00111   Parser(Preprocessor &PP, Action &Actions);
00112   ~Parser();
00113 
00114   const LangOptions &getLang() const { return PP.getLangOptions(); }
00115   const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); }
00116   Preprocessor &getPreprocessor() const { return PP; }
00117   Action &getActions() const { return Actions; }
00118 
00119   const Token &getCurToken() const { return Tok; }
00120 
00121   // Type forwarding.  All of these are statically 'void*', but they may all be
00122   // different actual classes based on the actions in place.
00123   typedef Action::ExprTy ExprTy;
00124   typedef Action::StmtTy StmtTy;
00125   typedef Action::DeclPtrTy DeclPtrTy;
00126   typedef Action::DeclGroupPtrTy DeclGroupPtrTy;
00127   typedef Action::TypeTy TypeTy;
00128   typedef Action::BaseTy BaseTy;
00129   typedef Action::MemInitTy MemInitTy;
00130   typedef Action::CXXScopeTy CXXScopeTy;
00131   typedef Action::TemplateParamsTy TemplateParamsTy;
00132   typedef Action::TemplateTy TemplateTy;
00133 
00134   typedef llvm::SmallVector<TemplateParamsTy *, 4> TemplateParameterLists;
00135 
00136   typedef Action::ExprResult        ExprResult;
00137   typedef Action::StmtResult        StmtResult;
00138   typedef Action::BaseResult        BaseResult;
00139   typedef Action::MemInitResult     MemInitResult;
00140   typedef Action::TypeResult        TypeResult;
00141 
00142   typedef Action::OwningExprResult OwningExprResult;
00143   typedef Action::OwningStmtResult OwningStmtResult;
00144 
00145   typedef Action::ExprArg ExprArg;
00146   typedef Action::MultiStmtArg MultiStmtArg;
00147   typedef Action::FullExprArg FullExprArg;
00148 
00149   /// Adorns a ExprResult with Actions to make it an OwningExprResult
00150   OwningExprResult Owned(ExprResult res) {
00151     return OwningExprResult(Actions, res);
00152   }
00153   /// Adorns a StmtResult with Actions to make it an OwningStmtResult
00154   OwningStmtResult Owned(StmtResult res) {
00155     return OwningStmtResult(Actions, res);
00156   }
00157 
00158   OwningExprResult ExprError() { return OwningExprResult(Actions, true); }
00159   OwningStmtResult StmtError() { return OwningStmtResult(Actions, true); }
00160 
00161   OwningExprResult ExprError(const DiagnosticBuilder &) { return ExprError(); }
00162   OwningStmtResult StmtError(const DiagnosticBuilder &) { return StmtError(); }
00163 
00164   OwningExprResult ExprEmpty() { return OwningExprResult(Actions, false); }
00165 
00166   // Parsing methods.
00167 
00168   /// ParseTranslationUnit - All in one method that initializes parses, and
00169   /// shuts down the parser.
00170   void ParseTranslationUnit();
00171 
00172   /// Initialize - Warm up the parser.
00173   ///
00174   void Initialize();
00175 
00176   /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if
00177   /// the EOF was encountered.
00178   bool ParseTopLevelDecl(DeclGroupPtrTy &Result);
00179 
00180   DeclGroupPtrTy RetrievePendingObjCImpDecl();
00181 
00182 private:
00183   //===--------------------------------------------------------------------===//
00184   // Low-Level token peeking and consumption methods.
00185   //
00186 
00187   /// isTokenParen - Return true if the cur token is '(' or ')'.
00188   bool isTokenParen() const {
00189     return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren;
00190   }
00191   /// isTokenBracket - Return true if the cur token is '[' or ']'.
00192   bool isTokenBracket() const {
00193     return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square;
00194   }
00195   /// isTokenBrace - Return true if the cur token is '{' or '}'.
00196   bool isTokenBrace() const {
00197     return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace;
00198   }
00199 
00200   /// isTokenStringLiteral - True if this token is a string-literal.
00201   ///
00202   bool isTokenStringLiteral() const {
00203     return Tok.getKind() == tok::string_literal ||
00204            Tok.getKind() == tok::wide_string_literal;
00205   }
00206 
00207   /// ConsumeToken - Consume the current 'peek token' and lex the next one.
00208   /// This does not work with all kinds of tokens: strings and specific other
00209   /// tokens must be consumed with custom methods below.  This returns the
00210   /// location of the consumed token.
00211   SourceLocation ConsumeToken() {
00212     assert(!isTokenStringLiteral() && !isTokenParen() && !isTokenBracket() &&
00213            !isTokenBrace() &&
00214            "Should consume special tokens with Consume*Token");
00215     PrevTokLocation = Tok.getLocation();
00216     PP.Lex(Tok);
00217     return PrevTokLocation;
00218   }
00219 
00220   /// ConsumeAnyToken - Dispatch to the right Consume* method based on the
00221   /// current token type.  This should only be used in cases where the type of
00222   /// the token really isn't known, e.g. in error recovery.
00223   SourceLocation ConsumeAnyToken() {
00224     if (isTokenParen())
00225       return ConsumeParen();
00226     else if (isTokenBracket())
00227       return ConsumeBracket();
00228     else if (isTokenBrace())
00229       return ConsumeBrace();
00230     else if (isTokenStringLiteral())
00231       return ConsumeStringToken();
00232     else
00233       return ConsumeToken();
00234   }
00235 
00236   /// ConsumeParen - This consume method keeps the paren count up-to-date.
00237   ///
00238   SourceLocation ConsumeParen() {
00239     assert(isTokenParen() && "wrong consume method");
00240     if (Tok.getKind() == tok::l_paren)
00241       ++ParenCount;
00242     else if (ParenCount)
00243       --ParenCount;       // Don't let unbalanced )'s drive the count negative.
00244     PrevTokLocation = Tok.getLocation();
00245     PP.Lex(Tok);
00246     return PrevTokLocation;
00247   }
00248 
00249   /// ConsumeBracket - This consume method keeps the bracket count up-to-date.
00250   ///
00251   SourceLocation ConsumeBracket() {
00252     assert(isTokenBracket() && "wrong consume method");
00253     if (Tok.getKind() == tok::l_square)
00254       ++BracketCount;
00255     else if (BracketCount)
00256       --BracketCount;     // Don't let unbalanced ]'s drive the count negative.
00257 
00258     PrevTokLocation = Tok.getLocation();
00259     PP.Lex(Tok);
00260     return PrevTokLocation;
00261   }
00262 
00263   /// ConsumeBrace - This consume method keeps the brace count up-to-date.
00264   ///
00265   SourceLocation ConsumeBrace() {
00266     assert(isTokenBrace() && "wrong consume method");
00267     if (Tok.getKind() == tok::l_brace)
00268       ++BraceCount;
00269     else if (BraceCount)
00270       --BraceCount;     // Don't let unbalanced }'s drive the count negative.
00271 
00272     PrevTokLocation = Tok.getLocation();
00273     PP.Lex(Tok);
00274     return PrevTokLocation;
00275   }
00276 
00277   /// ConsumeStringToken - Consume the current 'peek token', lexing a new one
00278   /// and returning the token kind.  This method is specific to strings, as it
00279   /// handles string literal concatenation, as per C99 5.1.1.2, translation
00280   /// phase #6.
00281   SourceLocation ConsumeStringToken() {
00282     assert(isTokenStringLiteral() &&
00283            "Should only consume string literals with this method");
00284     PrevTokLocation = Tok.getLocation();
00285     PP.Lex(Tok);
00286     return PrevTokLocation;
00287   }
00288 
00289   /// GetLookAheadToken - This peeks ahead N tokens and returns that token
00290   /// without consuming any tokens.  LookAhead(0) returns 'Tok', LookAhead(1)
00291   /// returns the token after Tok, etc.
00292   ///
00293   /// Note that this differs from the Preprocessor's LookAhead method, because
00294   /// the Parser always has one token lexed that the preprocessor doesn't.
00295   ///
00296   const Token &GetLookAheadToken(unsigned N) {
00297     if (N == 0 || Tok.is(tok::eof)) return Tok;
00298     return PP.LookAhead(N-1);
00299   }
00300 
00301   /// NextToken - This peeks ahead one token and returns it without
00302   /// consuming it.
00303   const Token &NextToken() {
00304     return PP.LookAhead(0);
00305   }
00306 
00307   /// TryAnnotateTypeOrScopeToken - If the current token position is on a
00308   /// typename (possibly qualified in C++) or a C++ scope specifier not followed
00309   /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens
00310   /// with a single annotation token representing the typename or C++ scope
00311   /// respectively.
00312   /// This simplifies handling of C++ scope specifiers and allows efficient
00313   /// backtracking without the need to re-parse and resolve nested-names and
00314   /// typenames.
00315   /// It will mainly be called when we expect to treat identifiers as typenames
00316   /// (if they are typenames). For example, in C we do not expect identifiers
00317   /// inside expressions to be treated as typenames so it will not be called
00318   /// for expressions in C.
00319   ///
00320   /// This returns true if the token was annotated.
00321   bool TryAnnotateTypeOrScopeToken(bool EnteringContext = false);
00322 
00323   /// TryAnnotateCXXScopeToken - Like TryAnnotateTypeOrScopeToken but
00324   /// only annotates C++ scope specifiers.  This returns true if there
00325   /// was an unrecoverable error.
00326   bool TryAnnotateCXXScopeToken(bool EnteringContext = false);
00327 
00328   /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens,
00329   /// replacing them with the non-context-sensitive keywords.  This returns
00330   /// true if the token was replaced.
00331   bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc,
00332                        const char *&PrevSpec, unsigned &DiagID,
00333                        bool &isInvalid) {
00334     if (!getLang().AltiVec ||
00335         (Tok.getIdentifierInfo() != Ident_vector &&
00336          Tok.getIdentifierInfo() != Ident_pixel))
00337       return false;
00338     
00339     return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid);
00340   }
00341 
00342   /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector
00343   /// identifier token, replacing it with the non-context-sensitive __vector.
00344   /// This returns true if the token was replaced.
00345   bool TryAltiVecVectorToken() {
00346     if (!getLang().AltiVec ||
00347         Tok.getIdentifierInfo() != Ident_vector) return false;
00348     return TryAltiVecVectorTokenOutOfLine();
00349   }
00350   
00351   bool TryAltiVecVectorTokenOutOfLine();
00352   bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc,
00353                                 const char *&PrevSpec, unsigned &DiagID,
00354                                 bool &isInvalid);
00355     
00356   /// TentativeParsingAction - An object that is used as a kind of "tentative
00357   /// parsing transaction". It gets instantiated to mark the token position and
00358   /// after the token consumption is done, Commit() or Revert() is called to
00359   /// either "commit the consumed tokens" or revert to the previously marked
00360   /// token position. Example:
00361   ///
00362   ///   TentativeParsingAction TPA(*this);
00363   ///   ConsumeToken();
00364   ///   ....
00365   ///   TPA.Revert();
00366   ///
00367   class TentativeParsingAction {
00368     Parser &P;
00369     Token PrevTok;
00370     bool isActive;
00371 
00372   public:
00373     explicit TentativeParsingAction(Parser& p) : P(p) {
00374       PrevTok = P.Tok;
00375       P.PP.EnableBacktrackAtThisPos();
00376       isActive = true;
00377     }
00378     void Commit() {
00379       assert(isActive && "Parsing action was finished!");
00380       P.PP.CommitBacktrackedTokens();
00381       isActive = false;
00382     }
00383     void Revert() {
00384       assert(isActive && "Parsing action was finished!");
00385       P.PP.Backtrack();
00386       P.Tok = PrevTok;
00387       isActive = false;
00388     }
00389     ~TentativeParsingAction() {
00390       assert(!isActive && "Forgot to call Commit or Revert!");
00391     }
00392   };
00393 
00394 
00395   /// MatchRHSPunctuation - For punctuation with a LHS and RHS (e.g. '['/']'),
00396   /// this helper function matches and consumes the specified RHS token if
00397   /// present.  If not present, it emits the specified diagnostic indicating
00398   /// that the parser failed to match the RHS of the token at LHSLoc.  LHSName
00399   /// should be the name of the unmatched LHS token.  This returns the location
00400   /// of the consumed token.
00401   SourceLocation MatchRHSPunctuation(tok::TokenKind RHSTok,
00402                                      SourceLocation LHSLoc);
00403 
00404   /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the
00405   /// input.  If so, it is consumed and false is returned.
00406   ///
00407   /// If the input is malformed, this emits the specified diagnostic.  Next, if
00408   /// SkipToTok is specified, it calls SkipUntil(SkipToTok).  Finally, true is
00409   /// returned.
00410   bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag,
00411                         const char *DiagMsg = "",
00412                         tok::TokenKind SkipToTok = tok::unknown);
00413 
00414   //===--------------------------------------------------------------------===//
00415   // Scope manipulation
00416 
00417   /// ParseScope - Introduces a new scope for parsing. The kind of
00418   /// scope is determined by ScopeFlags. Objects of this type should
00419   /// be created on the stack to coincide with the position where the
00420   /// parser enters the new scope, and this object's constructor will
00421   /// create that new scope. Similarly, once the object is destroyed
00422   /// the parser will exit the scope.
00423   class ParseScope {
00424     Parser *Self;
00425     ParseScope(const ParseScope&); // do not implement
00426     ParseScope& operator=(const ParseScope&); // do not implement
00427 
00428   public:
00429     // ParseScope - Construct a new object to manage a scope in the
00430     // parser Self where the new Scope is created with the flags
00431     // ScopeFlags, but only when ManageScope is true (the default). If
00432     // ManageScope is false, this object does nothing.
00433     ParseScope(Parser *Self, unsigned ScopeFlags, bool ManageScope = true)
00434       : Self(Self) {
00435       if (ManageScope)
00436         Self->EnterScope(ScopeFlags);
00437       else
00438         this->Self = 0;
00439     }
00440 
00441     // Exit - Exit the scope associated with this object now, rather
00442     // than waiting until the object is destroyed.
00443     void Exit() {
00444       if (Self) {
00445         Self->ExitScope();
00446         Self = 0;
00447       }
00448     }
00449 
00450     ~ParseScope() {
00451       Exit();
00452     }
00453   };
00454 
00455   /// EnterScope - Start a new scope.
00456   void EnterScope(unsigned ScopeFlags);
00457 
00458   /// ExitScope - Pop a scope off the scope stack.
00459   void ExitScope();
00460 
00461   //===--------------------------------------------------------------------===//
00462   // Diagnostic Emission and Error recovery.
00463 
00464   DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
00465   DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID);
00466 
00467   void SuggestParentheses(SourceLocation Loc, unsigned DK,
00468                           SourceRange ParenRange);
00469 
00470   /// SkipUntil - Read tokens until we get to the specified token, then consume
00471   /// it (unless DontConsume is true).  Because we cannot guarantee that the
00472   /// token will ever occur, this skips to the next token, or to some likely
00473   /// good stopping point.  If StopAtSemi is true, skipping will stop at a ';'
00474   /// character.
00475   ///
00476   /// If SkipUntil finds the specified token, it returns true, otherwise it
00477   /// returns false.
00478   bool SkipUntil(tok::TokenKind T, bool StopAtSemi = true,
00479                  bool DontConsume = false) {
00480     return SkipUntil(&T, 1, StopAtSemi, DontConsume);
00481   }
00482   bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, bool StopAtSemi = true,
00483                  bool DontConsume = false) {
00484     tok::TokenKind TokArray[] = {T1, T2};
00485     return SkipUntil(TokArray, 2, StopAtSemi, DontConsume);
00486   }
00487   bool SkipUntil(const tok::TokenKind *Toks, unsigned NumToks,
00488                  bool StopAtSemi = true, bool DontConsume = false);
00489 
00490   //===--------------------------------------------------------------------===//
00491   // Lexing and parsing of C++ inline methods.
00492 
00493   struct LexedMethod {
00494     Action::DeclPtrTy D;
00495     CachedTokens Toks;
00496 
00497     /// \brief Whether this member function had an associated template
00498     /// scope. When true, D is a template declaration.
00499     /// othewise, it is a member function declaration.
00500     bool TemplateScope;
00501 
00502     explicit LexedMethod(Action::DeclPtrTy MD) : D(MD), TemplateScope(false) {}
00503   };
00504 
00505   /// LateParsedDefaultArgument - Keeps track of a parameter that may
00506   /// have a default argument that cannot be parsed yet because it
00507   /// occurs within a member function declaration inside the class
00508   /// (C++ [class.mem]p2).
00509   struct LateParsedDefaultArgument {
00510     explicit LateParsedDefaultArgument(Action::DeclPtrTy P,
00511                                        CachedTokens *Toks = 0)
00512       : Param(P), Toks(Toks) { }
00513 
00514     /// Param - The parameter declaration for this parameter.
00515     Action::DeclPtrTy Param;
00516 
00517     /// Toks - The sequence of tokens that comprises the default
00518     /// argument expression, not including the '=' or the terminating
00519     /// ')' or ','. This will be NULL for parameters that have no
00520     /// default argument.
00521     CachedTokens *Toks;
00522   };
00523 
00524   /// LateParsedMethodDeclaration - A method declaration inside a class that
00525   /// contains at least one entity whose parsing needs to be delayed
00526   /// until the class itself is completely-defined, such as a default
00527   /// argument (C++ [class.mem]p2).
00528   struct LateParsedMethodDeclaration {
00529     explicit LateParsedMethodDeclaration(Action::DeclPtrTy M)
00530       : Method(M), TemplateScope(false) { }
00531 
00532     /// Method - The method declaration.
00533     Action::DeclPtrTy Method;
00534 
00535     /// \brief Whether this member function had an associated template
00536     /// scope. When true, D is a template declaration.
00537     /// othewise, it is a member function declaration.
00538     bool TemplateScope;
00539 
00540     /// DefaultArgs - Contains the parameters of the function and
00541     /// their default arguments. At least one of the parameters will
00542     /// have a default argument, but all of the parameters of the
00543     /// method will be stored so that they can be reintroduced into
00544     /// scope at the appropriate times.
00545     llvm::SmallVector<LateParsedDefaultArgument, 8> DefaultArgs;
00546   };
00547 
00548   /// LateParsedMethodDecls - During parsing of a top (non-nested) C++
00549   /// class, its method declarations that contain parts that won't be
00550   /// parsed until after the definiton is completed (C++ [class.mem]p2),
00551   /// the method declarations will be stored here with the tokens that
00552   /// will be parsed to create those entities.
00553   typedef std::list<LateParsedMethodDeclaration> LateParsedMethodDecls;
00554 
00555   /// LexedMethodsForTopClass - During parsing of a top (non-nested) C++ class,
00556   /// its inline method definitions and the inline method definitions of its
00557   /// nested classes are lexed and stored here.
00558   typedef std::list<LexedMethod> LexedMethodsForTopClass;
00559 
00560   /// \brief Representation of a class that has been parsed, including
00561   /// any member function declarations or definitions that need to be
00562   /// parsed after the corresponding top-level class is complete.
00563   struct ParsingClass {
00564     ParsingClass(DeclPtrTy TagOrTemplate, bool TopLevelClass)
00565       : TopLevelClass(TopLevelClass), TemplateScope(false),
00566         TagOrTemplate(TagOrTemplate) { }
00567 
00568     /// \brief Whether this is a "top-level" class, meaning that it is
00569     /// not nested within another class.
00570     bool TopLevelClass : 1;
00571 
00572     /// \brief Whether this class had an associated template
00573     /// scope. When true, TagOrTemplate is a template declaration;
00574     /// othewise, it is a tag declaration.
00575     bool TemplateScope : 1;
00576 
00577     /// \brief The class or class template whose definition we are parsing.
00578     DeclPtrTy TagOrTemplate;
00579 
00580     /// MethodDecls - Method declarations that contain pieces whose
00581     /// parsing will be delayed until the class is fully defined.
00582     LateParsedMethodDecls MethodDecls;
00583 
00584     /// MethodDefs - Methods whose definitions will be parsed once the
00585     /// class has been fully defined.
00586     LexedMethodsForTopClass MethodDefs;
00587 
00588     /// \brief Nested classes inside this class.
00589     llvm::SmallVector<ParsingClass*, 4> NestedClasses;
00590   };
00591 
00592   /// \brief The stack of classes that is currently being
00593   /// parsed. Nested and local classes will be pushed onto this stack
00594   /// when they are parsed, and removed afterward.
00595   std::stack<ParsingClass *> ClassStack;
00596 
00597   ParsingClass &getCurrentClass() {
00598     assert(!ClassStack.empty() && "No lexed method stacks!");
00599     return *ClassStack.top();
00600   }
00601 
00602   /// \brief RAII object used to inform the actions that we're
00603   /// currently parsing a declaration.  This is active when parsing a
00604   /// variable's initializer, but not when parsing the body of a
00605   /// class or function definition.
00606   class ParsingDeclRAIIObject {
00607     Action &Actions;
00608     Action::ParsingDeclStackState State;
00609     bool Popped;
00610     
00611   public:
00612     ParsingDeclRAIIObject(Parser &P) : Actions(P.Actions) {
00613       push();
00614     }
00615 
00616     ~ParsingDeclRAIIObject() {
00617       abort();
00618     }
00619 
00620     /// Resets the RAII object for a new declaration.
00621     void reset() {
00622       abort();
00623       push();
00624     }
00625 
00626     /// Signals that the context was completed without an appropriate
00627     /// declaration being parsed.
00628     void abort() {
00629       pop(DeclPtrTy());
00630     }
00631 
00632     void complete(DeclPtrTy D) {
00633       assert(!Popped && "ParsingDeclaration has already been popped!");
00634       pop(D);
00635     }
00636 
00637   private:
00638     void push() {
00639       State = Actions.PushParsingDeclaration();
00640       Popped = false;
00641     }
00642 
00643     void pop(DeclPtrTy D) {
00644       if (!Popped) {
00645         Actions.PopParsingDeclaration(State, D);
00646         Popped = true;
00647       }
00648     }
00649   };
00650 
00651   /// A class for parsing a DeclSpec.
00652   class ParsingDeclSpec : public DeclSpec {
00653     ParsingDeclRAIIObject ParsingRAII;
00654 
00655   public:
00656     ParsingDeclSpec(Parser &P) : ParsingRAII(P) {
00657     }
00658 
00659     void complete(DeclPtrTy D) {
00660       ParsingRAII.complete(D);
00661     }
00662 
00663     void abort() {
00664       ParsingRAII.abort();
00665     }
00666   };
00667 
00668   /// A class for parsing a declarator.
00669   class ParsingDeclarator : public Declarator {
00670     ParsingDeclRAIIObject ParsingRAII;
00671 
00672   public:
00673     ParsingDeclarator(Parser &P, const ParsingDeclSpec &DS, TheContext C)
00674       : Declarator(DS, C), ParsingRAII(P) {
00675     }
00676 
00677     const ParsingDeclSpec &getDeclSpec() const {
00678       return static_cast<const ParsingDeclSpec&>(Declarator::getDeclSpec());
00679     }
00680 
00681     ParsingDeclSpec &getMutableDeclSpec() const {
00682       return const_cast<ParsingDeclSpec&>(getDeclSpec());
00683     }
00684 
00685     void clear() {
00686       Declarator::clear();
00687       ParsingRAII.reset();
00688     }
00689 
00690     void complete(DeclPtrTy D) {
00691       ParsingRAII.complete(D);
00692     }
00693   };
00694 
00695   /// \brief RAII object used to
00696   class ParsingClassDefinition {
00697     Parser &P;
00698     bool Popped;
00699 
00700   public:
00701     ParsingClassDefinition(Parser &P, DeclPtrTy TagOrTemplate, bool TopLevelClass)
00702       : P(P), Popped(false) {
00703       P.PushParsingClass(TagOrTemplate, TopLevelClass);
00704     }
00705 
00706     /// \brief Pop this class of the stack.
00707     void Pop() {
00708       assert(!Popped && "Nested class has already been popped");
00709       Popped = true;
00710       P.PopParsingClass();
00711     }
00712 
00713     ~ParsingClassDefinition() {
00714       if (!Popped)
00715         P.PopParsingClass();
00716     }
00717   };
00718 
00719   /// \brief Contains information about any template-specific
00720   /// information that has been parsed prior to parsing declaration
00721   /// specifiers.
00722   struct ParsedTemplateInfo {
00723     ParsedTemplateInfo()
00724       : Kind(NonTemplate), TemplateParams(0), TemplateLoc() { }
00725 
00726     ParsedTemplateInfo(TemplateParameterLists *TemplateParams,
00727                        bool isSpecialization,
00728                        bool lastParameterListWasEmpty = false)
00729       : Kind(isSpecialization? ExplicitSpecialization : Template),
00730         TemplateParams(TemplateParams), 
00731         LastParameterListWasEmpty(lastParameterListWasEmpty) { }
00732 
00733     explicit ParsedTemplateInfo(SourceLocation ExternLoc,
00734                                 SourceLocation TemplateLoc)
00735       : Kind(ExplicitInstantiation), TemplateParams(0),
00736         ExternLoc(ExternLoc), TemplateLoc(TemplateLoc),
00737         LastParameterListWasEmpty(false){ }
00738 
00739     /// \brief The kind of template we are parsing.
00740     enum {
00741       /// \brief We are not parsing a template at all.
00742       NonTemplate = 0,
00743       /// \brief We are parsing a template declaration.
00744       Template,
00745       /// \brief We are parsing an explicit specialization.
00746       ExplicitSpecialization,
00747       /// \brief We are parsing an explicit instantiation.
00748       ExplicitInstantiation
00749     } Kind;
00750 
00751     /// \brief The template parameter lists, for template declarations
00752     /// and explicit specializations.
00753     TemplateParameterLists *TemplateParams;
00754 
00755     /// \brief The location of the 'extern' keyword, if any, for an explicit
00756     /// instantiation
00757     SourceLocation ExternLoc;
00758 
00759     /// \brief The location of the 'template' keyword, for an explicit
00760     /// instantiation.
00761     SourceLocation TemplateLoc;
00762     
00763     /// \brief Whether the last template parameter list was empty.
00764     bool LastParameterListWasEmpty;
00765   };
00766 
00767   void PushParsingClass(DeclPtrTy TagOrTemplate, bool TopLevelClass);
00768   void DeallocateParsedClasses(ParsingClass *Class);
00769   void PopParsingClass();
00770 
00771   DeclPtrTy ParseCXXInlineMethodDef(AccessSpecifier AS, Declarator &D,
00772                                     const ParsedTemplateInfo &TemplateInfo);
00773   void ParseLexedMethodDeclarations(ParsingClass &Class);
00774   void ParseLexedMethodDefs(ParsingClass &Class);
00775   bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2,
00776                             CachedTokens &Toks,
00777                             tok::TokenKind EarlyAbortIf = tok::unknown,
00778                             bool ConsumeFinalToken = true);
00779 
00780   //===--------------------------------------------------------------------===//
00781   // C99 6.9: External Definitions.
00782   DeclGroupPtrTy ParseExternalDeclaration(CXX0XAttributeList Attr);
00783   bool isDeclarationAfterDeclarator();
00784   bool isStartOfFunctionDefinition();
00785   DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(AttributeList *Attr,
00786             AccessSpecifier AS = AS_none);
00787   DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(ParsingDeclSpec &DS,
00788                                                   AttributeList *Attr,
00789                                                   AccessSpecifier AS = AS_none);
00790   
00791   DeclPtrTy ParseFunctionDefinition(ParsingDeclarator &D,
00792                  const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
00793   void ParseKNRParamDeclarations(Declarator &D);
00794   // EndLoc, if non-NULL, is filled with the location of the last token of
00795   // the simple-asm.
00796   OwningExprResult ParseSimpleAsm(SourceLocation *EndLoc = 0);
00797   OwningExprResult ParseAsmStringLiteral();
00798 
00799   // Objective-C External Declarations
00800   DeclPtrTy ParseObjCAtDirectives();
00801   DeclPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc);
00802   DeclPtrTy ParseObjCAtInterfaceDeclaration(SourceLocation atLoc,
00803                                           AttributeList *prefixAttrs = 0);
00804   void ParseObjCClassInstanceVariables(DeclPtrTy interfaceDecl,
00805                                        tok::ObjCKeywordKind visibility,
00806                                        SourceLocation atLoc);
00807   bool ParseObjCProtocolReferences(llvm::SmallVectorImpl<Action::DeclPtrTy> &P,
00808                                    llvm::SmallVectorImpl<SourceLocation> &PLocs,
00809                                    bool WarnOnDeclarations,
00810                                    SourceLocation &LAngleLoc,
00811                                    SourceLocation &EndProtoLoc);
00812   void ParseObjCInterfaceDeclList(DeclPtrTy interfaceDecl,
00813                                   tok::ObjCKeywordKind contextKey);
00814   DeclPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc,
00815                                            AttributeList *prefixAttrs = 0);
00816 
00817   DeclPtrTy ObjCImpDecl;
00818   llvm::SmallVector<DeclPtrTy, 4> PendingObjCImpDecl;
00819 
00820   DeclPtrTy ParseObjCAtImplementationDeclaration(SourceLocation atLoc);
00821   DeclPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd);
00822   DeclPtrTy ParseObjCAtAliasDeclaration(SourceLocation atLoc);
00823   DeclPtrTy ParseObjCPropertySynthesize(SourceLocation atLoc);
00824   DeclPtrTy ParseObjCPropertyDynamic(SourceLocation atLoc);
00825 
00826   IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation);
00827   // Definitions for Objective-c context sensitive keywords recognition.
00828   enum ObjCTypeQual {
00829     objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref,
00830     objc_NumQuals
00831   };
00832   IdentifierInfo *ObjCTypeQuals[objc_NumQuals];
00833 
00834   bool isTokIdentifier_in() const;
00835 
00836   TypeTy *ParseObjCTypeName(ObjCDeclSpec &DS);
00837   void ParseObjCMethodRequirement();
00838   DeclPtrTy ParseObjCMethodPrototype(DeclPtrTy classOrCat,
00839             tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword);
00840   DeclPtrTy ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType,
00841                                 DeclPtrTy classDecl,
00842             tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword);
00843   void ParseObjCPropertyAttribute(ObjCDeclSpec &DS, DeclPtrTy ClassDecl,
00844                                   DeclPtrTy *Methods, unsigned NumMethods);
00845 
00846   DeclPtrTy ParseObjCMethodDefinition();
00847 
00848   //===--------------------------------------------------------------------===//
00849   // C99 6.5: Expressions.
00850 
00851   OwningExprResult ParseExpression();
00852   OwningExprResult ParseConstantExpression();
00853   // Expr that doesn't include commas.
00854   OwningExprResult ParseAssignmentExpression();
00855 
00856   OwningExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc);
00857 
00858   OwningExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc);
00859 
00860   OwningExprResult ParseRHSOfBinaryExpression(OwningExprResult LHS,
00861                                               unsigned MinPrec);
00862   OwningExprResult ParseCastExpression(bool isUnaryExpression,
00863                                        bool isAddressOfOperand,
00864                                        bool &NotCastExpr,
00865                                        TypeTy *TypeOfCast);
00866   OwningExprResult ParseCastExpression(bool isUnaryExpression,
00867                                        bool isAddressOfOperand = false,
00868                                        TypeTy *TypeOfCast = 0);
00869   OwningExprResult ParsePostfixExpressionSuffix(OwningExprResult LHS);
00870   OwningExprResult ParseSizeofAlignofExpression();
00871   OwningExprResult ParseBuiltinPrimaryExpression();
00872 
00873   OwningExprResult ParseExprAfterTypeofSizeofAlignof(const Token &OpTok,
00874                                                      bool &isCastExpr,
00875                                                      TypeTy *&CastTy,
00876                                                      SourceRange &CastRange);
00877 
00878   static const unsigned ExprListSize = 12;
00879   typedef llvm::SmallVector<ExprTy*, ExprListSize> ExprListTy;
00880   typedef llvm::SmallVector<SourceLocation, ExprListSize> CommaLocsTy;
00881 
00882   /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
00883   bool ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs,
00884                            void (Action::*Completer)(Scope *S, void *Data,
00885                                                      ExprTy **Args,
00886                                                      unsigned NumArgs) = 0,
00887                            void *Data = 0);
00888 
00889   /// ParenParseOption - Control what ParseParenExpression will parse.
00890   enum ParenParseOption {
00891     SimpleExpr,      // Only parse '(' expression ')'
00892     CompoundStmt,    // Also allow '(' compound-statement ')'
00893     CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}'
00894     CastExpr         // Also allow '(' type-name ')' <anything>
00895   };
00896   OwningExprResult ParseParenExpression(ParenParseOption &ExprType,
00897                                         bool stopIfCastExpr,
00898                                         TypeTy *TypeOfCast,
00899                                         TypeTy *&CastTy,
00900                                         SourceLocation &RParenLoc);
00901 
00902   OwningExprResult ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
00903                                                     TypeTy *&CastTy,
00904                                                     SourceLocation LParenLoc,
00905                                                     SourceLocation &RParenLoc);
00906 
00907   OwningExprResult ParseCompoundLiteralExpression(TypeTy *Ty,
00908                                                   SourceLocation LParenLoc,
00909                                                   SourceLocation RParenLoc);
00910 
00911   OwningExprResult ParseStringLiteralExpression();
00912 
00913   //===--------------------------------------------------------------------===//
00914   // C++ Expressions
00915   OwningExprResult ParseCXXIdExpression(bool isAddressOfOperand = false);
00916 
00917   bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
00918                                       TypeTy *ObjectType,
00919                                       bool EnteringContext,
00920                                       bool *MayBePseudoDestructor = 0);
00921 
00922   //===--------------------------------------------------------------------===//
00923   // C++ 5.2p1: C++ Casts
00924   OwningExprResult ParseCXXCasts();
00925 
00926   //===--------------------------------------------------------------------===//
00927   // C++ 5.2p1: C++ Type Identification
00928   OwningExprResult ParseCXXTypeid();
00929 
00930   //===--------------------------------------------------------------------===//
00931   // C++ 5.2.4: C++ Pseudo-Destructor Expressions
00932   OwningExprResult ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
00933                                             tok::TokenKind OpKind,
00934                                             CXXScopeSpec &SS,
00935                                             Action::TypeTy *ObjectType);
00936 
00937   //===--------------------------------------------------------------------===//
00938   // C++ 9.3.2: C++ 'this' pointer
00939   OwningExprResult ParseCXXThis();
00940 
00941   //===--------------------------------------------------------------------===//
00942   // C++ 15: C++ Throw Expression
00943   OwningExprResult ParseThrowExpression();
00944   // EndLoc is filled with the location of the last token of the specification.
00945   bool ParseExceptionSpecification(SourceLocation &EndLoc,
00946                                    llvm::SmallVector<TypeTy*, 2> &Exceptions,
00947                                    llvm::SmallVector<SourceRange, 2> &Ranges,
00948                                    bool &hasAnyExceptionSpec);
00949 
00950   //===--------------------------------------------------------------------===//
00951   // C++ 2.13.5: C++ Boolean Literals
00952   OwningExprResult ParseCXXBoolLiteral();
00953 
00954   //===--------------------------------------------------------------------===//
00955   // C++ 5.2.3: Explicit type conversion (functional notation)
00956   OwningExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS);
00957 
00958   /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
00959   /// This should only be called when the current token is known to be part of
00960   /// simple-type-specifier.
00961   void ParseCXXSimpleTypeSpecifier(DeclSpec &DS);
00962 
00963   bool ParseCXXTypeSpecifierSeq(DeclSpec &DS);
00964 
00965   //===--------------------------------------------------------------------===//
00966   // C++ 5.3.4 and 5.3.5: C++ new and delete
00967   bool ParseExpressionListOrTypeId(ExprListTy &Exprs, Declarator &D);
00968   void ParseDirectNewDeclarator(Declarator &D);
00969   OwningExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start);
00970   OwningExprResult ParseCXXDeleteExpression(bool UseGlobal,
00971                                             SourceLocation Start);
00972 
00973   //===--------------------------------------------------------------------===//
00974   // C++ if/switch/while condition expression.
00975   bool ParseCXXCondition(OwningExprResult &ExprResult, DeclPtrTy &DeclResult);
00976 
00977   //===--------------------------------------------------------------------===//
00978   // C++ types
00979 
00980   //===--------------------------------------------------------------------===//
00981   // C99 6.7.8: Initialization.
00982 
00983   /// ParseInitializer
00984   ///       initializer: [C99 6.7.8]
00985   ///         assignment-expression
00986   ///         '{' ...
00987   OwningExprResult ParseInitializer() {
00988     if (Tok.isNot(tok::l_brace))
00989       return ParseAssignmentExpression();
00990     return ParseBraceInitializer();
00991   }
00992   OwningExprResult ParseBraceInitializer();
00993   OwningExprResult ParseInitializerWithPotentialDesignator();
00994 
00995   //===--------------------------------------------------------------------===//
00996   // clang Expressions
00997 
00998   OwningExprResult ParseBlockLiteralExpression();  // ^{...}
00999 
01000   //===--------------------------------------------------------------------===//
01001   // Objective-C Expressions
01002 
01003   bool isTokObjCMessageIdentifierReceiver() const {
01004     if (!Tok.is(tok::identifier))
01005       return false;
01006 
01007     IdentifierInfo *II = Tok.getIdentifierInfo();
01008     if (Actions.getTypeName(*II, Tok.getLocation(), CurScope))
01009       return true;
01010 
01011     return II == Ident_super;
01012   }
01013 
01014   OwningExprResult ParseObjCAtExpression(SourceLocation AtLocation);
01015   OwningExprResult ParseObjCStringLiteral(SourceLocation AtLoc);
01016   OwningExprResult ParseObjCEncodeExpression(SourceLocation AtLoc);
01017   OwningExprResult ParseObjCSelectorExpression(SourceLocation AtLoc);
01018   OwningExprResult ParseObjCProtocolExpression(SourceLocation AtLoc);
01019   OwningExprResult ParseObjCMessageExpression();
01020   OwningExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc,
01021                                                   SourceLocation NameLoc,
01022                                                   IdentifierInfo *ReceiverName,
01023                                                   ExprArg ReceiverExpr);
01024   OwningExprResult ParseAssignmentExprWithObjCMessageExprStart(
01025       SourceLocation LBracloc, SourceLocation NameLoc,
01026       IdentifierInfo *ReceiverName, ExprArg ReceiverExpr);
01027 
01028   //===--------------------------------------------------------------------===//
01029   // C99 6.8: Statements and Blocks.
01030 
01031   OwningStmtResult ParseStatement() {
01032     return ParseStatementOrDeclaration(true);
01033   }
01034   OwningStmtResult ParseStatementOrDeclaration(bool OnlyStatement = false);
01035   OwningStmtResult ParseLabeledStatement(AttributeList *Attr);
01036   OwningStmtResult ParseCaseStatement(AttributeList *Attr);
01037   OwningStmtResult ParseDefaultStatement(AttributeList *Attr);
01038   OwningStmtResult ParseCompoundStatement(AttributeList *Attr,
01039                                           bool isStmtExpr = false);
01040   OwningStmtResult ParseCompoundStatementBody(bool isStmtExpr = false);
01041   bool ParseParenExprOrCondition(OwningExprResult &ExprResult,
01042                                  DeclPtrTy &DeclResult);
01043   OwningStmtResult ParseIfStatement(AttributeList *Attr);
01044   OwningStmtResult ParseSwitchStatement(AttributeList *Attr);
01045   OwningStmtResult ParseWhileStatement(AttributeList *Attr);
01046   OwningStmtResult ParseDoStatement(AttributeList *Attr);
01047   OwningStmtResult ParseForStatement(AttributeList *Attr);
01048   OwningStmtResult ParseGotoStatement(AttributeList *Attr);
01049   OwningStmtResult ParseContinueStatement(AttributeList *Attr);
01050   OwningStmtResult ParseBreakStatement(AttributeList *Attr);
01051   OwningStmtResult ParseReturnStatement(AttributeList *Attr);
01052   OwningStmtResult ParseAsmStatement(bool &msAsm);
01053   OwningStmtResult FuzzyParseMicrosoftAsmStatement();
01054   bool ParseAsmOperandsOpt(llvm::SmallVectorImpl<IdentifierInfo *> &Names,
01055                            llvm::SmallVectorImpl<ExprTy *> &Constraints,
01056                            llvm::SmallVectorImpl<ExprTy *> &Exprs);
01057 
01058   //===--------------------------------------------------------------------===//
01059   // C++ 6: Statements and Blocks
01060 
01061   OwningStmtResult ParseCXXTryBlock(AttributeList *Attr);
01062   OwningStmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc);
01063   OwningStmtResult ParseCXXCatchBlock();
01064 
01065   //===--------------------------------------------------------------------===//
01066   // Objective-C Statements
01067 
01068   OwningStmtResult ParseObjCAtStatement(SourceLocation atLoc);
01069   OwningStmtResult ParseObjCTryStmt(SourceLocation atLoc);
01070   OwningStmtResult ParseObjCThrowStmt(SourceLocation atLoc);
01071   OwningStmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc);
01072 
01073 
01074   //===--------------------------------------------------------------------===//
01075   // C99 6.7: Declarations.
01076 
01077   /// A context for parsing declaration specifiers.  TODO: flesh this
01078   /// out, there are other significant restrictions on specifiers than
01079   /// would be best implemented in the parser.
01080   enum DeclSpecContext {
01081     DSC_normal, // normal context
01082     DSC_class,  // class context, enables 'friend'
01083     DSC_top_level // top-level/namespace declaration context
01084   };
01085 
01086   DeclGroupPtrTy ParseDeclaration(unsigned Context, SourceLocation &DeclEnd,
01087                                   CXX0XAttributeList Attr);
01088   DeclGroupPtrTy ParseSimpleDeclaration(unsigned Context,
01089                                         SourceLocation &DeclEnd,
01090                                         AttributeList *Attr);
01091   DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context,
01092                                 bool AllowFunctionDefinitions,
01093                                 SourceLocation *DeclEnd = 0);
01094   DeclPtrTy ParseDeclarationAfterDeclarator(Declarator &D,
01095                const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
01096   DeclPtrTy ParseFunctionStatementBody(DeclPtrTy Decl);
01097   DeclPtrTy ParseFunctionTryBlock(DeclPtrTy Decl);
01098 
01099   bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS,
01100                         const ParsedTemplateInfo &TemplateInfo,
01101                         AccessSpecifier AS);
01102   DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context);
01103   void ParseDeclarationSpecifiers(DeclSpec &DS,
01104                 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
01105                                   AccessSpecifier AS = AS_none,
01106                                   DeclSpecContext DSC = DSC_normal);
01107   bool ParseOptionalTypeSpecifier(DeclSpec &DS, bool &isInvalid,
01108                                   const char *&PrevSpec,
01109                                   unsigned &DiagID,
01110                const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
01111                                   bool SuppressDeclarations = false);
01112 
01113   void ParseSpecifierQualifierList(DeclSpec &DS);
01114 
01115   void ParseObjCTypeQualifierList(ObjCDeclSpec &DS);
01116 
01117   void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS,
01118                 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),                          AccessSpecifier AS = AS_none);
01119   void ParseEnumBody(SourceLocation StartLoc, DeclPtrTy TagDecl);
01120   void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType,
01121                             DeclPtrTy TagDecl);
01122 
01123   struct FieldCallback {
01124     virtual DeclPtrTy invoke(FieldDeclarator &Field) = 0;
01125     virtual ~FieldCallback() {}
01126 
01127   private:
01128     virtual void _anchor();
01129   };
01130   struct ObjCPropertyCallback;
01131 
01132   void ParseStructDeclaration(DeclSpec &DS, FieldCallback &Callback);
01133 
01134   bool isDeclarationSpecifier();
01135   bool isTypeSpecifierQualifier();
01136   bool isTypeQualifier() const;
01137   
01138   /// isKnownToBeTypeSpecifier - Return true if we know that the specified token
01139   /// is definitely a type-specifier.  Return false if it isn't part of a type
01140   /// specifier or if we're not sure.
01141   bool isKnownToBeTypeSpecifier(const Token &Tok) const;
01142 
01143   /// isDeclarationStatement - Disambiguates between a declaration or an
01144   /// expression statement, when parsing function bodies.
01145   /// Returns true for declaration, false for expression.
01146   bool isDeclarationStatement() {
01147     if (getLang().CPlusPlus)
01148       return isCXXDeclarationStatement();
01149     return isDeclarationSpecifier();
01150   }
01151 
01152   /// isSimpleDeclaration - Disambiguates between a declaration or an
01153   /// expression, mainly used for the C 'clause-1' or the C++
01154   // 'for-init-statement' part of a 'for' statement.
01155   /// Returns true for declaration, false for expression.
01156   bool isSimpleDeclaration() {
01157     if (getLang().CPlusPlus)
01158       return isCXXSimpleDeclaration();
01159     return isDeclarationSpecifier();
01160   }
01161 
01162   /// \brief Starting with a scope specifier, identifier, or
01163   /// template-id that refers to the current class, determine whether
01164   /// this is a constructor declarator.
01165   bool isConstructorDeclarator();
01166 
01167   /// \brief Specifies the context in which type-id/expression
01168   /// disambiguation will occur.
01169   enum TentativeCXXTypeIdContext {
01170     TypeIdInParens,
01171     TypeIdAsTemplateArgument
01172   };
01173 
01174 
01175   /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know
01176   /// whether the parens contain an expression or a type-id.
01177   /// Returns true for a type-id and false for an expression.
01178   bool isTypeIdInParens(bool &isAmbiguous) {
01179     if (getLang().CPlusPlus)
01180       return isCXXTypeId(TypeIdInParens, isAmbiguous);
01181     isAmbiguous = false;
01182     return isTypeSpecifierQualifier();
01183   }
01184   bool isTypeIdInParens() {
01185     bool isAmbiguous;
01186     return isTypeIdInParens(isAmbiguous);
01187   }
01188 
01189   /// isCXXDeclarationStatement - C++-specialized function that disambiguates
01190   /// between a declaration or an expression statement, when parsing function
01191   /// bodies. Returns true for declaration, false for expression.
01192   bool isCXXDeclarationStatement();
01193 
01194   /// isCXXSimpleDeclaration - C++-specialized function that disambiguates
01195   /// between a simple-declaration or an expression-statement.
01196   /// If during the disambiguation process a parsing error is encountered,
01197   /// the function returns true to let the declaration parsing code handle it.
01198   /// Returns false if the statement is disambiguated as expression.
01199   bool isCXXSimpleDeclaration();
01200 
01201   /// isCXXFunctionDeclarator - Disambiguates between a function declarator or
01202   /// a constructor-style initializer, when parsing declaration statements.
01203   /// Returns true for function declarator and false for constructor-style
01204   /// initializer. If 'warnIfAmbiguous' is true a warning will be emitted to
01205   /// indicate that the parens were disambiguated as function declarator.
01206   /// If during the disambiguation process a parsing error is encountered,
01207   /// the function returns true to let the declaration parsing code handle it.
01208   bool isCXXFunctionDeclarator(bool warnIfAmbiguous);
01209 
01210   /// isCXXConditionDeclaration - Disambiguates between a declaration or an
01211   /// expression for a condition of a if/switch/while/for statement.
01212   /// If during the disambiguation process a parsing error is encountered,
01213   /// the function returns true to let the declaration parsing code handle it.
01214   bool isCXXConditionDeclaration();
01215 
01216   bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous);
01217   bool isCXXTypeId(TentativeCXXTypeIdContext Context) {
01218     bool isAmbiguous;
01219     return isCXXTypeId(Context, isAmbiguous);
01220   }
01221 
01222   /// TPResult - Used as the result value for functions whose purpose is to
01223   /// disambiguate C++ constructs by "tentatively parsing" them.
01224   /// This is a class instead of a simple enum because the implicit enum-to-bool
01225   /// conversions may cause subtle bugs.
01226   class TPResult {
01227     enum Result {
01228       TPR_true,
01229       TPR_false,
01230       TPR_ambiguous,
01231       TPR_error
01232     };
01233     Result Res;
01234     TPResult(Result result) : Res(result) {}
01235   public:
01236     static TPResult True() { return TPR_true; }
01237     static TPResult False() { return TPR_false; }
01238     static TPResult Ambiguous() { return TPR_ambiguous; }
01239     static TPResult Error() { return TPR_error; }
01240 
01241     bool operator==(const TPResult &RHS) const { return Res == RHS.Res; }
01242     bool operator!=(const TPResult &RHS) const { return Res != RHS.Res; }
01243   };
01244 
01245   /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a
01246   /// declaration specifier, TPResult::False() if it is not,
01247   /// TPResult::Ambiguous() if it could be either a decl-specifier or a
01248   /// function-style cast, and TPResult::Error() if a parsing error was
01249   /// encountered.
01250   /// Doesn't consume tokens.
01251   TPResult isCXXDeclarationSpecifier();
01252 
01253   // "Tentative parsing" functions, used for disambiguation. If a parsing error
01254   // is encountered they will return TPResult::Error().
01255   // Returning TPResult::True()/False() indicates that the ambiguity was
01256   // resolved and tentative parsing may stop. TPResult::Ambiguous() indicates
01257   // that more tentative parsing is necessary for disambiguation.
01258   // They all consume tokens, so backtracking should be used after calling them.
01259 
01260   TPResult TryParseDeclarationSpecifier();
01261   TPResult TryParseSimpleDeclaration();
01262   TPResult TryParseTypeofSpecifier();
01263   TPResult TryParseInitDeclaratorList();
01264   TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true);
01265   TPResult TryParseParameterDeclarationClause();
01266   TPResult TryParseFunctionDeclarator();
01267   TPResult TryParseBracketDeclarator();
01268 
01269   TypeResult ParseTypeName(SourceRange *Range = 0);
01270   void ParseBlockId();
01271   // EndLoc, if non-NULL, is filled with the location of the last token of
01272   // the attribute list.
01273   CXX0XAttributeList ParseCXX0XAttributes(SourceLocation *EndLoc = 0);
01274   AttributeList *ParseGNUAttributes(SourceLocation *EndLoc = 0);
01275   AttributeList *ParseMicrosoftDeclSpec(AttributeList* CurrAttr = 0);
01276   AttributeList *ParseMicrosoftTypeAttributes(AttributeList* CurrAttr = 0);
01277   void ParseTypeofSpecifier(DeclSpec &DS);
01278   void ParseDecltypeSpecifier(DeclSpec &DS);
01279   
01280   OwningExprResult ParseCXX0XAlignArgument(SourceLocation Start);
01281 
01282   /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to
01283   /// enter a new C++ declarator scope and exit it when the function is
01284   /// finished.
01285   class DeclaratorScopeObj {
01286     Parser &P;
01287     CXXScopeSpec &SS;
01288     bool EnteredScope;
01289     bool CreatedScope;
01290   public:
01291     DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss)
01292       : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {}
01293 
01294     void EnterDeclaratorScope() {
01295       assert(!EnteredScope && "Already entered the scope!");
01296       assert(SS.isSet() && "C++ scope was not set!");
01297 
01298       CreatedScope = true;
01299       P.EnterScope(0); // Not a decl scope.
01300 
01301       if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.CurScope, SS))
01302         EnteredScope = true;
01303     }
01304 
01305     ~DeclaratorScopeObj() {
01306       if (EnteredScope) {
01307         assert(SS.isSet() && "C++ scope was cleared ?");
01308         P.Actions.ActOnCXXExitDeclaratorScope(P.CurScope, SS);
01309       }
01310       if (CreatedScope)
01311         P.ExitScope();
01312     }
01313   };
01314 
01315   /// ParseDeclarator - Parse and verify a newly-initialized declarator.
01316   void ParseDeclarator(Declarator &D);
01317   /// A function that parses a variant of direct-declarator.
01318   typedef void (Parser::*DirectDeclParseFunction)(Declarator&);
01319   void ParseDeclaratorInternal(Declarator &D,
01320                                DirectDeclParseFunction DirectDeclParser);
01321   void ParseTypeQualifierListOpt(DeclSpec &DS, bool GNUAttributesAllowed = true,
01322                                  bool CXX0XAttributesAllowed = true);
01323   void ParseDirectDeclarator(Declarator &D);
01324   void ParseParenDeclarator(Declarator &D);
01325   void ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D,
01326                                AttributeList *AttrList = 0,
01327                                bool RequiresArg = false);
01328   void ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc,
01329                                              Declarator &D);
01330   void ParseBracketDeclarator(Declarator &D);
01331 
01332   //===--------------------------------------------------------------------===//
01333   // C++ 7: Declarations [dcl.dcl]
01334 
01335   bool isCXX0XAttributeSpecifier(bool FullLookahead = false, 
01336                                  tok::TokenKind *After = 0);
01337   
01338   DeclPtrTy ParseNamespace(unsigned Context, SourceLocation &DeclEnd);
01339   DeclPtrTy ParseLinkage(ParsingDeclSpec &DS, unsigned Context);
01340   DeclPtrTy ParseUsingDirectiveOrDeclaration(unsigned Context,
01341                                              SourceLocation &DeclEnd,
01342                                              CXX0XAttributeList Attrs);
01343   DeclPtrTy ParseUsingDirective(unsigned Context, SourceLocation UsingLoc,
01344                                 SourceLocation &DeclEnd,
01345                                 AttributeList *Attr);
01346   DeclPtrTy ParseUsingDeclaration(unsigned Context, SourceLocation UsingLoc,
01347                                   SourceLocation &DeclEnd,
01348                                   AccessSpecifier AS = AS_none);
01349   DeclPtrTy ParseStaticAssertDeclaration(SourceLocation &DeclEnd);
01350   DeclPtrTy ParseNamespaceAlias(SourceLocation NamespaceLoc,
01351                                 SourceLocation AliasLoc, IdentifierInfo *Alias,
01352                                 SourceLocation &DeclEnd);
01353 
01354   //===--------------------------------------------------------------------===//
01355   // C++ 9: classes [class] and C structs/unions.
01356   TypeResult ParseClassName(SourceLocation &EndLocation,
01357                             const CXXScopeSpec *SS = 0);
01358   void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc,
01359                            DeclSpec &DS,
01360                 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(),
01361                            AccessSpecifier AS = AS_none,
01362                            bool SuppressDeclarations = false);
01363   void ParseCXXMemberSpecification(SourceLocation StartLoc, unsigned TagType,
01364                                    DeclPtrTy TagDecl);
01365   void ParseCXXClassMemberDeclaration(AccessSpecifier AS,
01366                 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo());
01367   void ParseConstructorInitializer(DeclPtrTy ConstructorDecl);
01368   MemInitResult ParseMemInitializer(DeclPtrTy ConstructorDecl);
01369   void HandleMemberFunctionDefaultArgs(Declarator& DeclaratorInfo,
01370                                        DeclPtrTy ThisDecl);
01371 
01372   //===--------------------------------------------------------------------===//
01373   // C++ 10: Derived classes [class.derived]
01374   void ParseBaseClause(DeclPtrTy ClassDecl);
01375   BaseResult ParseBaseSpecifier(DeclPtrTy ClassDecl);
01376   AccessSpecifier getAccessSpecifierIfPresent() const;
01377 
01378   bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, 
01379                                     IdentifierInfo *Name,
01380                                     SourceLocation NameLoc,
01381                                     bool EnteringContext,
01382                                     TypeTy *ObjectType,
01383                                     UnqualifiedId &Id,
01384                                     bool AssumeTemplateId = false);
01385   bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
01386                                   TypeTy *ObjectType,
01387                                   UnqualifiedId &Result);
01388   bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
01389                           bool AllowDestructorName,
01390                           bool AllowConstructorName,
01391                           TypeTy *ObjectType,
01392                           UnqualifiedId &Result);
01393     
01394   //===--------------------------------------------------------------------===//
01395   // C++ 14: Templates [temp]
01396   typedef llvm::SmallVector<DeclPtrTy, 4> TemplateParameterList;
01397 
01398   // C++ 14.1: Template Parameters [temp.param]
01399   DeclPtrTy ParseDeclarationStartingWithTemplate(unsigned Context,
01400                                                  SourceLocation &DeclEnd,
01401                                                  AccessSpecifier AS = AS_none);
01402   DeclPtrTy ParseTemplateDeclarationOrSpecialization(unsigned Context,
01403                                                      SourceLocation &DeclEnd,
01404                                                      AccessSpecifier AS);
01405   DeclPtrTy ParseSingleDeclarationAfterTemplate(
01406                                        unsigned Context,
01407                                        const ParsedTemplateInfo &TemplateInfo,
01408                                        SourceLocation &DeclEnd,
01409                                        AccessSpecifier AS=AS_none);
01410   bool ParseTemplateParameters(unsigned Depth,
01411                                TemplateParameterList &TemplateParams,
01412                                SourceLocation &LAngleLoc,
01413                                SourceLocation &RAngleLoc);
01414   bool ParseTemplateParameterList(unsigned Depth,
01415                                   TemplateParameterList &TemplateParams);
01416   bool isStartOfTemplateTypeParameter();
01417   DeclPtrTy ParseTemplateParameter(unsigned Depth, unsigned Position);
01418   DeclPtrTy ParseTypeParameter(unsigned Depth, unsigned Position);
01419   DeclPtrTy ParseTemplateTemplateParameter(unsigned Depth, unsigned Position);
01420   DeclPtrTy ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position);
01421   // C++ 14.3: Template arguments [temp.arg]
01422   typedef llvm::SmallVector<ParsedTemplateArgument, 16> TemplateArgList;
01423 
01424   bool ParseTemplateIdAfterTemplateName(TemplateTy Template,
01425                                         SourceLocation TemplateNameLoc,
01426                                         const CXXScopeSpec *SS,
01427                                         bool ConsumeLastToken,
01428                                         SourceLocation &LAngleLoc,
01429                                         TemplateArgList &TemplateArgs,
01430                                         SourceLocation &RAngleLoc);
01431 
01432   bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK,
01433                                const CXXScopeSpec *SS,
01434                                UnqualifiedId &TemplateName,
01435                                SourceLocation TemplateKWLoc = SourceLocation(),
01436                                bool AllowTypeAnnotation = true);
01437   void AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS = 0);
01438   bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs);
01439   ParsedTemplateArgument ParseTemplateTemplateArgument();
01440   ParsedTemplateArgument ParseTemplateArgument();
01441   DeclPtrTy ParseExplicitInstantiation(SourceLocation ExternLoc,
01442                                        SourceLocation TemplateLoc,
01443                                        SourceLocation &DeclEnd);
01444 
01445   //===--------------------------------------------------------------------===//
01446   // GNU G++: Type Traits [Type-Traits.html in the GCC manual]
01447   OwningExprResult ParseUnaryTypeTrait();
01448 };
01449 
01450 }  // end namespace clang
01451 
01452 #endif