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