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/Lex/CodeCompletionHandler.h" 00020 #include "clang/Sema/Sema.h" 00021 #include "clang/Sema/DeclSpec.h" 00022 #include "llvm/ADT/OwningPtr.h" 00023 #include "llvm/ADT/SmallVector.h" 00024 #include "llvm/Support/Compiler.h" 00025 #include "llvm/Support/PrettyStackTrace.h" 00026 #include <stack> 00027 00028 namespace clang { 00029 class PragmaHandler; 00030 class Scope; 00031 class DeclGroupRef; 00032 class DiagnosticBuilder; 00033 class Parser; 00034 class ParsingDeclRAIIObject; 00035 class ParsingDeclSpec; 00036 class ParsingDeclarator; 00037 class PragmaUnusedHandler; 00038 class ColonProtectionRAIIObject; 00039 class InMessageExpressionRAIIObject; 00040 class PoisonSEHIdentifiersRAIIObject; 00041 class VersionTuple; 00042 00043 /// PrettyStackTraceParserEntry - If a crash happens while the parser is active, 00044 /// an entry is printed for it. 00045 class PrettyStackTraceParserEntry : public llvm::PrettyStackTraceEntry { 00046 const Parser &P; 00047 public: 00048 PrettyStackTraceParserEntry(const Parser &p) : P(p) {} 00049 virtual void print(raw_ostream &OS) const; 00050 }; 00051 00052 /// PrecedenceLevels - These are precedences for the binary/ternary 00053 /// operators in the C99 grammar. These have been named to relate 00054 /// with the C99 grammar productions. Low precedences numbers bind 00055 /// more weakly than high numbers. 00056 namespace prec { 00057 enum Level { 00058 Unknown = 0, // Not binary operator. 00059 Comma = 1, // , 00060 Assignment = 2, // =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |= 00061 Conditional = 3, // ? 00062 LogicalOr = 4, // || 00063 LogicalAnd = 5, // && 00064 InclusiveOr = 6, // | 00065 ExclusiveOr = 7, // ^ 00066 And = 8, // & 00067 Equality = 9, // ==, != 00068 Relational = 10, // >=, <=, >, < 00069 Shift = 11, // <<, >> 00070 Additive = 12, // -, + 00071 Multiplicative = 13, // *, /, % 00072 PointerToMember = 14 // .*, ->* 00073 }; 00074 } 00075 00076 /// Parser - This implements a parser for the C family of languages. After 00077 /// parsing units of the grammar, productions are invoked to handle whatever has 00078 /// been read. 00079 /// 00080 class Parser : public CodeCompletionHandler { 00081 friend class PragmaUnusedHandler; 00082 friend class ColonProtectionRAIIObject; 00083 friend class InMessageExpressionRAIIObject; 00084 friend class PoisonSEHIdentifiersRAIIObject; 00085 friend class ParenBraceBracketBalancer; 00086 00087 Preprocessor &PP; 00088 00089 /// Tok - The current token we are peeking ahead. All parsing methods assume 00090 /// that this is valid. 00091 Token Tok; 00092 00093 // PrevTokLocation - The location of the token we previously 00094 // consumed. This token is used for diagnostics where we expected to 00095 // see a token following another token (e.g., the ';' at the end of 00096 // a statement). 00097 SourceLocation PrevTokLocation; 00098 00099 unsigned short ParenCount, BracketCount, BraceCount; 00100 00101 /// Actions - These are the callbacks we invoke as we parse various constructs 00102 /// in the file. 00103 Sema &Actions; 00104 00105 DiagnosticsEngine &Diags; 00106 00107 /// ScopeCache - Cache scopes to reduce malloc traffic. 00108 enum { ScopeCacheSize = 16 }; 00109 unsigned NumCachedScopes; 00110 Scope *ScopeCache[ScopeCacheSize]; 00111 00112 /// Identifiers used for SEH handling in Borland. These are only 00113 /// allowed in particular circumstances 00114 // __except block 00115 IdentifierInfo *Ident__exception_code, 00116 *Ident___exception_code, 00117 *Ident_GetExceptionCode; 00118 // __except filter expression 00119 IdentifierInfo *Ident__exception_info, 00120 *Ident___exception_info, 00121 *Ident_GetExceptionInfo; 00122 // __finally 00123 IdentifierInfo *Ident__abnormal_termination, 00124 *Ident___abnormal_termination, 00125 *Ident_AbnormalTermination; 00126 00127 /// Contextual keywords for Microsoft extensions. 00128 IdentifierInfo *Ident__except; 00129 00130 /// Ident_super - IdentifierInfo for "super", to support fast 00131 /// comparison. 00132 IdentifierInfo *Ident_super; 00133 /// Ident_vector and Ident_pixel - cached IdentifierInfo's for 00134 /// "vector" and "pixel" fast comparison. Only present if 00135 /// AltiVec enabled. 00136 IdentifierInfo *Ident_vector; 00137 IdentifierInfo *Ident_pixel; 00138 00139 /// Objective-C contextual keywords. 00140 mutable IdentifierInfo *Ident_instancetype; 00141 00142 /// \brief Identifier for "introduced". 00143 IdentifierInfo *Ident_introduced; 00144 00145 /// \brief Identifier for "deprecated". 00146 IdentifierInfo *Ident_deprecated; 00147 00148 /// \brief Identifier for "obsoleted". 00149 IdentifierInfo *Ident_obsoleted; 00150 00151 /// \brief Identifier for "unavailable". 00152 IdentifierInfo *Ident_unavailable; 00153 00154 /// \brief Identifier for "message". 00155 IdentifierInfo *Ident_message; 00156 00157 /// C++0x contextual keywords. 00158 mutable IdentifierInfo *Ident_final; 00159 mutable IdentifierInfo *Ident_override; 00160 00161 OwningPtr<PragmaHandler> AlignHandler; 00162 OwningPtr<PragmaHandler> GCCVisibilityHandler; 00163 OwningPtr<PragmaHandler> OptionsHandler; 00164 OwningPtr<PragmaHandler> PackHandler; 00165 OwningPtr<PragmaHandler> MSStructHandler; 00166 OwningPtr<PragmaHandler> UnusedHandler; 00167 OwningPtr<PragmaHandler> WeakHandler; 00168 OwningPtr<PragmaHandler> RedefineExtnameHandler; 00169 OwningPtr<PragmaHandler> FPContractHandler; 00170 OwningPtr<PragmaHandler> OpenCLExtensionHandler; 00171 00172 /// Whether the '>' token acts as an operator or not. This will be 00173 /// true except when we are parsing an expression within a C++ 00174 /// template argument list, where the '>' closes the template 00175 /// argument list. 00176 bool GreaterThanIsOperator; 00177 00178 /// ColonIsSacred - When this is false, we aggressively try to recover from 00179 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not 00180 /// safe in case statements and a few other things. This is managed by the 00181 /// ColonProtectionRAIIObject RAII object. 00182 bool ColonIsSacred; 00183 00184 /// \brief When true, we are directly inside an Objective-C messsage 00185 /// send expression. 00186 /// 00187 /// This is managed by the \c InMessageExpressionRAIIObject class, and 00188 /// should not be set directly. 00189 bool InMessageExpression; 00190 00191 /// The "depth" of the template parameters currently being parsed. 00192 unsigned TemplateParameterDepth; 00193 00194 /// Factory object for creating AttributeList objects. 00195 AttributeFactory AttrFactory; 00196 00197 /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a 00198 /// top-level declaration is finished. 00199 SmallVector<TemplateIdAnnotation *, 16> TemplateIds; 00200 00201 IdentifierInfo *getSEHExceptKeyword(); 00202 00203 bool SkipFunctionBodies; 00204 00205 public: 00206 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies); 00207 ~Parser(); 00208 00209 const LangOptions &getLangOpts() const { return PP.getLangOpts(); } 00210 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } 00211 Preprocessor &getPreprocessor() const { return PP; } 00212 Sema &getActions() const { return Actions; } 00213 AttributeFactory &getAttrFactory() { return AttrFactory; } 00214 00215 const Token &getCurToken() const { return Tok; } 00216 Scope *getCurScope() const { return Actions.getCurScope(); } 00217 00218 Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); } 00219 00220 // Type forwarding. All of these are statically 'void*', but they may all be 00221 // different actual classes based on the actions in place. 00222 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; 00223 typedef OpaquePtr<TemplateName> TemplateTy; 00224 00225 typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists; 00226 00227 typedef clang::ExprResult ExprResult; 00228 typedef clang::StmtResult StmtResult; 00229 typedef clang::BaseResult BaseResult; 00230 typedef clang::MemInitResult MemInitResult; 00231 typedef clang::TypeResult TypeResult; 00232 00233 typedef Expr *ExprArg; 00234 typedef ASTMultiPtr<Stmt*> MultiStmtArg; 00235 typedef Sema::FullExprArg FullExprArg; 00236 00237 /// Adorns a ExprResult with Actions to make it an ExprResult 00238 ExprResult Owned(ExprResult res) { 00239 return ExprResult(res); 00240 } 00241 /// Adorns a StmtResult with Actions to make it an StmtResult 00242 StmtResult Owned(StmtResult res) { 00243 return StmtResult(res); 00244 } 00245 00246 ExprResult ExprError() { return ExprResult(true); } 00247 StmtResult StmtError() { return StmtResult(true); } 00248 00249 ExprResult ExprError(const DiagnosticBuilder &) { return ExprError(); } 00250 StmtResult StmtError(const DiagnosticBuilder &) { return StmtError(); } 00251 00252 ExprResult ExprEmpty() { return ExprResult(false); } 00253 00254 // Parsing methods. 00255 00256 /// ParseTranslationUnit - All in one method that initializes parses, and 00257 /// shuts down the parser. 00258 void ParseTranslationUnit(); 00259 00260 /// Initialize - Warm up the parser. 00261 /// 00262 void Initialize(); 00263 00264 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if 00265 /// the EOF was encountered. 00266 bool ParseTopLevelDecl(DeclGroupPtrTy &Result); 00267 00268 private: 00269 //===--------------------------------------------------------------------===// 00270 // Low-Level token peeking and consumption methods. 00271 // 00272 00273 /// isTokenParen - Return true if the cur token is '(' or ')'. 00274 bool isTokenParen() const { 00275 return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren; 00276 } 00277 /// isTokenBracket - Return true if the cur token is '[' or ']'. 00278 bool isTokenBracket() const { 00279 return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square; 00280 } 00281 /// isTokenBrace - Return true if the cur token is '{' or '}'. 00282 bool isTokenBrace() const { 00283 return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace; 00284 } 00285 00286 /// isTokenStringLiteral - True if this token is a string-literal. 00287 /// 00288 bool isTokenStringLiteral() const { 00289 return Tok.getKind() == tok::string_literal || 00290 Tok.getKind() == tok::wide_string_literal || 00291 Tok.getKind() == tok::utf8_string_literal || 00292 Tok.getKind() == tok::utf16_string_literal || 00293 Tok.getKind() == tok::utf32_string_literal; 00294 } 00295 00296 /// \brief Returns true if the current token is '=' or is a type of '='. 00297 /// For typos, give a fixit to '=' 00298 bool isTokenEqualOrEqualTypo(); 00299 00300 /// ConsumeToken - Consume the current 'peek token' and lex the next one. 00301 /// This does not work with all kinds of tokens: strings and specific other 00302 /// tokens must be consumed with custom methods below. This returns the 00303 /// location of the consumed token. 00304 SourceLocation ConsumeToken() { 00305 assert(!isTokenStringLiteral() && !isTokenParen() && !isTokenBracket() && 00306 !isTokenBrace() && 00307 "Should consume special tokens with Consume*Token"); 00308 00309 if (Tok.is(tok::code_completion)) 00310 return handleUnexpectedCodeCompletionToken(); 00311 00312 PrevTokLocation = Tok.getLocation(); 00313 PP.Lex(Tok); 00314 return PrevTokLocation; 00315 } 00316 00317 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the 00318 /// current token type. This should only be used in cases where the type of 00319 /// the token really isn't known, e.g. in error recovery. 00320 SourceLocation ConsumeAnyToken() { 00321 if (isTokenParen()) 00322 return ConsumeParen(); 00323 else if (isTokenBracket()) 00324 return ConsumeBracket(); 00325 else if (isTokenBrace()) 00326 return ConsumeBrace(); 00327 else if (isTokenStringLiteral()) 00328 return ConsumeStringToken(); 00329 else 00330 return ConsumeToken(); 00331 } 00332 00333 /// ConsumeParen - This consume method keeps the paren count up-to-date. 00334 /// 00335 SourceLocation ConsumeParen() { 00336 assert(isTokenParen() && "wrong consume method"); 00337 if (Tok.getKind() == tok::l_paren) 00338 ++ParenCount; 00339 else if (ParenCount) 00340 --ParenCount; // Don't let unbalanced )'s drive the count negative. 00341 PrevTokLocation = Tok.getLocation(); 00342 PP.Lex(Tok); 00343 return PrevTokLocation; 00344 } 00345 00346 /// ConsumeBracket - This consume method keeps the bracket count up-to-date. 00347 /// 00348 SourceLocation ConsumeBracket() { 00349 assert(isTokenBracket() && "wrong consume method"); 00350 if (Tok.getKind() == tok::l_square) 00351 ++BracketCount; 00352 else if (BracketCount) 00353 --BracketCount; // Don't let unbalanced ]'s drive the count negative. 00354 00355 PrevTokLocation = Tok.getLocation(); 00356 PP.Lex(Tok); 00357 return PrevTokLocation; 00358 } 00359 00360 /// ConsumeBrace - This consume method keeps the brace count up-to-date. 00361 /// 00362 SourceLocation ConsumeBrace() { 00363 assert(isTokenBrace() && "wrong consume method"); 00364 if (Tok.getKind() == tok::l_brace) 00365 ++BraceCount; 00366 else if (BraceCount) 00367 --BraceCount; // Don't let unbalanced }'s drive the count negative. 00368 00369 PrevTokLocation = Tok.getLocation(); 00370 PP.Lex(Tok); 00371 return PrevTokLocation; 00372 } 00373 00374 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one 00375 /// and returning the token kind. This method is specific to strings, as it 00376 /// handles string literal concatenation, as per C99 5.1.1.2, translation 00377 /// phase #6. 00378 SourceLocation ConsumeStringToken() { 00379 assert(isTokenStringLiteral() && 00380 "Should only consume string literals with this method"); 00381 PrevTokLocation = Tok.getLocation(); 00382 PP.Lex(Tok); 00383 return PrevTokLocation; 00384 } 00385 00386 /// \brief Consume the current code-completion token. 00387 /// 00388 /// This routine should be called to consume the code-completion token once 00389 /// a code-completion action has already been invoked. 00390 SourceLocation ConsumeCodeCompletionToken() { 00391 assert(Tok.is(tok::code_completion)); 00392 PrevTokLocation = Tok.getLocation(); 00393 PP.Lex(Tok); 00394 return PrevTokLocation; 00395 } 00396 00397 ///\ brief When we are consuming a code-completion token without having 00398 /// matched specific position in the grammar, provide code-completion results 00399 /// based on context. 00400 /// 00401 /// \returns the source location of the code-completion token. 00402 SourceLocation handleUnexpectedCodeCompletionToken(); 00403 00404 /// \brief Abruptly cut off parsing; mainly used when we have reached the 00405 /// code-completion point. 00406 void cutOffParsing() { 00407 PP.setCodeCompletionReached(); 00408 // Cut off parsing by acting as if we reached the end-of-file. 00409 Tok.setKind(tok::eof); 00410 } 00411 00412 /// \brief Handle the annotation token produced for #pragma unused(...) 00413 void HandlePragmaUnused(); 00414 00415 /// \brief Handle the annotation token produced for 00416 /// #pragma GCC visibility... 00417 void HandlePragmaVisibility(); 00418 00419 /// \brief Handle the annotation token produced for 00420 /// #pragma pack... 00421 void HandlePragmaPack(); 00422 00423 /// GetLookAheadToken - This peeks ahead N tokens and returns that token 00424 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) 00425 /// returns the token after Tok, etc. 00426 /// 00427 /// Note that this differs from the Preprocessor's LookAhead method, because 00428 /// the Parser always has one token lexed that the preprocessor doesn't. 00429 /// 00430 const Token &GetLookAheadToken(unsigned N) { 00431 if (N == 0 || Tok.is(tok::eof)) return Tok; 00432 return PP.LookAhead(N-1); 00433 } 00434 00435 /// NextToken - This peeks ahead one token and returns it without 00436 /// consuming it. 00437 const Token &NextToken() { 00438 return PP.LookAhead(0); 00439 } 00440 00441 /// \brief RAII class that helps handle the parsing of an open/close delimiter 00442 /// pair, such as braces { ... } or parentheses ( ... ). 00443 class BalancedDelimiterTracker { 00444 Parser& P; 00445 tok::TokenKind Kind, Close; 00446 SourceLocation (Parser::*Consumer)(); 00447 SourceLocation LOpen, LClose; 00448 00449 unsigned short &getDepth() { 00450 switch (Kind) { 00451 case tok::l_brace: return P.BraceCount; 00452 case tok::l_square: return P.BracketCount; 00453 case tok::l_paren: return P.ParenCount; 00454 default: llvm_unreachable("Wrong token kind"); 00455 } 00456 } 00457 00458 enum { MaxDepth = 512 }; 00459 00460 bool diagnoseOverflow(); 00461 bool diagnoseMissingClose(); 00462 00463 public: 00464 BalancedDelimiterTracker(Parser& p, tok::TokenKind k) : P(p), Kind(k) { 00465 switch (Kind) { 00466 default: llvm_unreachable("Unexpected balanced token"); 00467 case tok::l_brace: 00468 Close = tok::r_brace; 00469 Consumer = &Parser::ConsumeBrace; 00470 break; 00471 case tok::l_paren: 00472 Close = tok::r_paren; 00473 Consumer = &Parser::ConsumeParen; 00474 break; 00475 00476 case tok::l_square: 00477 Close = tok::r_square; 00478 Consumer = &Parser::ConsumeBracket; 00479 break; 00480 } 00481 } 00482 00483 SourceLocation getOpenLocation() const { return LOpen; } 00484 SourceLocation getCloseLocation() const { return LClose; } 00485 SourceRange getRange() const { return SourceRange(LOpen, LClose); } 00486 00487 bool consumeOpen() { 00488 if (!P.Tok.is(Kind)) 00489 return true; 00490 00491 if (getDepth() < MaxDepth) { 00492 LOpen = (P.*Consumer)(); 00493 return false; 00494 } 00495 00496 return diagnoseOverflow(); 00497 } 00498 00499 bool expectAndConsume(unsigned DiagID, 00500 const char *Msg = "", 00501 tok::TokenKind SkipToTok = tok::unknown); 00502 bool consumeClose() { 00503 if (P.Tok.is(Close)) { 00504 LClose = (P.*Consumer)(); 00505 return false; 00506 } 00507 00508 return diagnoseMissingClose(); 00509 } 00510 void skipToEnd(); 00511 }; 00512 00513 /// getTypeAnnotation - Read a parsed type out of an annotation token. 00514 static ParsedType getTypeAnnotation(Token &Tok) { 00515 return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue()); 00516 } 00517 00518 static void setTypeAnnotation(Token &Tok, ParsedType T) { 00519 Tok.setAnnotationValue(T.getAsOpaquePtr()); 00520 } 00521 00522 /// \brief Read an already-translated primary expression out of an annotation 00523 /// token. 00524 static ExprResult getExprAnnotation(Token &Tok) { 00525 if (Tok.getAnnotationValue()) 00526 return ExprResult((Expr *)Tok.getAnnotationValue()); 00527 00528 return ExprResult(true); 00529 } 00530 00531 /// \brief Set the primary expression corresponding to the given annotation 00532 /// token. 00533 static void setExprAnnotation(Token &Tok, ExprResult ER) { 00534 if (ER.isInvalid()) 00535 Tok.setAnnotationValue(0); 00536 else 00537 Tok.setAnnotationValue(ER.get()); 00538 } 00539 00540 // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to 00541 // find a type name by attempting typo correction. 00542 bool TryAnnotateTypeOrScopeToken(bool EnteringContext = false, 00543 bool NeedType = false); 00544 bool TryAnnotateCXXScopeToken(bool EnteringContext = false); 00545 00546 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens, 00547 /// replacing them with the non-context-sensitive keywords. This returns 00548 /// true if the token was replaced. 00549 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, 00550 const char *&PrevSpec, unsigned &DiagID, 00551 bool &isInvalid) { 00552 if (!getLangOpts().AltiVec || 00553 (Tok.getIdentifierInfo() != Ident_vector && 00554 Tok.getIdentifierInfo() != Ident_pixel)) 00555 return false; 00556 00557 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid); 00558 } 00559 00560 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector 00561 /// identifier token, replacing it with the non-context-sensitive __vector. 00562 /// This returns true if the token was replaced. 00563 bool TryAltiVecVectorToken() { 00564 if (!getLangOpts().AltiVec || 00565 Tok.getIdentifierInfo() != Ident_vector) return false; 00566 return TryAltiVecVectorTokenOutOfLine(); 00567 } 00568 00569 bool TryAltiVecVectorTokenOutOfLine(); 00570 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, 00571 const char *&PrevSpec, unsigned &DiagID, 00572 bool &isInvalid); 00573 00574 /// \brief Get the TemplateIdAnnotation from the token. 00575 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok); 00576 00577 /// TentativeParsingAction - An object that is used as a kind of "tentative 00578 /// parsing transaction". It gets instantiated to mark the token position and 00579 /// after the token consumption is done, Commit() or Revert() is called to 00580 /// either "commit the consumed tokens" or revert to the previously marked 00581 /// token position. Example: 00582 /// 00583 /// TentativeParsingAction TPA(*this); 00584 /// ConsumeToken(); 00585 /// .... 00586 /// TPA.Revert(); 00587 /// 00588 class TentativeParsingAction { 00589 Parser &P; 00590 Token PrevTok; 00591 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount; 00592 bool isActive; 00593 00594 public: 00595 explicit TentativeParsingAction(Parser& p) : P(p) { 00596 PrevTok = P.Tok; 00597 PrevParenCount = P.ParenCount; 00598 PrevBracketCount = P.BracketCount; 00599 PrevBraceCount = P.BraceCount; 00600 P.PP.EnableBacktrackAtThisPos(); 00601 isActive = true; 00602 } 00603 void Commit() { 00604 assert(isActive && "Parsing action was finished!"); 00605 P.PP.CommitBacktrackedTokens(); 00606 isActive = false; 00607 } 00608 void Revert() { 00609 assert(isActive && "Parsing action was finished!"); 00610 P.PP.Backtrack(); 00611 P.Tok = PrevTok; 00612 P.ParenCount = PrevParenCount; 00613 P.BracketCount = PrevBracketCount; 00614 P.BraceCount = PrevBraceCount; 00615 isActive = false; 00616 } 00617 ~TentativeParsingAction() { 00618 assert(!isActive && "Forgot to call Commit or Revert!"); 00619 } 00620 }; 00621 00622 /// ObjCDeclContextSwitch - An object used to switch context from 00623 /// an objective-c decl context to its enclosing decl context and 00624 /// back. 00625 class ObjCDeclContextSwitch { 00626 Parser &P; 00627 Decl *DC; 00628 public: 00629 explicit ObjCDeclContextSwitch(Parser &p) : P(p), 00630 DC(p.getObjCDeclContext()) { 00631 if (DC) 00632 P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC)); 00633 } 00634 ~ObjCDeclContextSwitch() { 00635 if (DC) 00636 P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC)); 00637 } 00638 }; 00639 00640 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the 00641 /// input. If so, it is consumed and false is returned. 00642 /// 00643 /// If the input is malformed, this emits the specified diagnostic. Next, if 00644 /// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is 00645 /// returned. 00646 bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag, 00647 const char *DiagMsg = "", 00648 tok::TokenKind SkipToTok = tok::unknown); 00649 00650 /// \brief The parser expects a semicolon and, if present, will consume it. 00651 /// 00652 /// If the next token is not a semicolon, this emits the specified diagnostic, 00653 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior 00654 /// to the semicolon, consumes that extra token. 00655 bool ExpectAndConsumeSemi(unsigned DiagID); 00656 00657 /// \brief The kind of extra semi diagnostic to emit. 00658 enum ExtraSemiKind { 00659 OutsideFunction = 0, 00660 InsideStruct = 1, 00661 InstanceVariableList = 2, 00662 AfterDefinition = 3 00663 }; 00664 00665 /// \brief Consume any extra semi-colons until the end of the line. 00666 void ConsumeExtraSemi(ExtraSemiKind Kind, const char* DiagMsg = ""); 00667 00668 //===--------------------------------------------------------------------===// 00669 // Scope manipulation 00670 00671 /// ParseScope - Introduces a new scope for parsing. The kind of 00672 /// scope is determined by ScopeFlags. Objects of this type should 00673 /// be created on the stack to coincide with the position where the 00674 /// parser enters the new scope, and this object's constructor will 00675 /// create that new scope. Similarly, once the object is destroyed 00676 /// the parser will exit the scope. 00677 class ParseScope { 00678 Parser *Self; 00679 ParseScope(const ParseScope&); // do not implement 00680 ParseScope& operator=(const ParseScope&); // do not implement 00681 00682 public: 00683 // ParseScope - Construct a new object to manage a scope in the 00684 // parser Self where the new Scope is created with the flags 00685 // ScopeFlags, but only when ManageScope is true (the default). If 00686 // ManageScope is false, this object does nothing. 00687 ParseScope(Parser *Self, unsigned ScopeFlags, bool ManageScope = true) 00688 : Self(Self) { 00689 if (ManageScope) 00690 Self->EnterScope(ScopeFlags); 00691 else 00692 this->Self = 0; 00693 } 00694 00695 // Exit - Exit the scope associated with this object now, rather 00696 // than waiting until the object is destroyed. 00697 void Exit() { 00698 if (Self) { 00699 Self->ExitScope(); 00700 Self = 0; 00701 } 00702 } 00703 00704 ~ParseScope() { 00705 Exit(); 00706 } 00707 }; 00708 00709 /// EnterScope - Start a new scope. 00710 void EnterScope(unsigned ScopeFlags); 00711 00712 /// ExitScope - Pop a scope off the scope stack. 00713 void ExitScope(); 00714 00715 /// \brief RAII object used to modify the scope flags for the current scope. 00716 class ParseScopeFlags { 00717 Scope *CurScope; 00718 unsigned OldFlags; 00719 ParseScopeFlags(const ParseScopeFlags &); // do not implement 00720 void operator=(const ParseScopeFlags &); // do not implement 00721 00722 public: 00723 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true); 00724 ~ParseScopeFlags(); 00725 }; 00726 00727 //===--------------------------------------------------------------------===// 00728 // Diagnostic Emission and Error recovery. 00729 00730 public: 00731 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); 00732 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); 00733 00734 private: 00735 void SuggestParentheses(SourceLocation Loc, unsigned DK, 00736 SourceRange ParenRange); 00737 void CheckNestedObjCContexts(SourceLocation AtLoc); 00738 00739 /// SkipUntil - Read tokens until we get to the specified token, then consume 00740 /// it (unless DontConsume is true). Because we cannot guarantee that the 00741 /// token will ever occur, this skips to the next token, or to some likely 00742 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';' 00743 /// character. 00744 /// 00745 /// If SkipUntil finds the specified token, it returns true, otherwise it 00746 /// returns false. 00747 bool SkipUntil(tok::TokenKind T, bool StopAtSemi = true, 00748 bool DontConsume = false, bool StopAtCodeCompletion = false) { 00749 return SkipUntil(llvm::makeArrayRef(T), StopAtSemi, DontConsume, 00750 StopAtCodeCompletion); 00751 } 00752 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, bool StopAtSemi = true, 00753 bool DontConsume = false, bool StopAtCodeCompletion = false) { 00754 tok::TokenKind TokArray[] = {T1, T2}; 00755 return SkipUntil(TokArray, StopAtSemi, DontConsume,StopAtCodeCompletion); 00756 } 00757 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, 00758 bool StopAtSemi = true, bool DontConsume = false, 00759 bool StopAtCodeCompletion = false) { 00760 tok::TokenKind TokArray[] = {T1, T2, T3}; 00761 return SkipUntil(TokArray, StopAtSemi, DontConsume,StopAtCodeCompletion); 00762 } 00763 bool SkipUntil(ArrayRef<tok::TokenKind> Toks, bool StopAtSemi = true, 00764 bool DontConsume = false, bool StopAtCodeCompletion = false); 00765 00766 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping 00767 /// point for skipping past a simple-declaration. 00768 void SkipMalformedDecl(); 00769 00770 //===--------------------------------------------------------------------===// 00771 // Lexing and parsing of C++ inline methods. 00772 00773 struct ParsingClass; 00774 00775 /// [class.mem]p1: "... the class is regarded as complete within 00776 /// - function bodies 00777 /// - default arguments 00778 /// - exception-specifications (TODO: C++0x) 00779 /// - and brace-or-equal-initializers for non-static data members 00780 /// (including such things in nested classes)." 00781 /// LateParsedDeclarations build the tree of those elements so they can 00782 /// be parsed after parsing the top-level class. 00783 class LateParsedDeclaration { 00784 public: 00785 virtual ~LateParsedDeclaration(); 00786 00787 virtual void ParseLexedMethodDeclarations(); 00788 virtual void ParseLexedMemberInitializers(); 00789 virtual void ParseLexedMethodDefs(); 00790 virtual void ParseLexedAttributes(); 00791 }; 00792 00793 /// Inner node of the LateParsedDeclaration tree that parses 00794 /// all its members recursively. 00795 class LateParsedClass : public LateParsedDeclaration { 00796 public: 00797 LateParsedClass(Parser *P, ParsingClass *C); 00798 virtual ~LateParsedClass(); 00799 00800 virtual void ParseLexedMethodDeclarations(); 00801 virtual void ParseLexedMemberInitializers(); 00802 virtual void ParseLexedMethodDefs(); 00803 virtual void ParseLexedAttributes(); 00804 00805 private: 00806 Parser *Self; 00807 ParsingClass *Class; 00808 }; 00809 00810 /// Contains the lexed tokens of an attribute with arguments that 00811 /// may reference member variables and so need to be parsed at the 00812 /// end of the class declaration after parsing all other member 00813 /// member declarations. 00814 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to 00815 /// LateParsedTokens. 00816 struct LateParsedAttribute : public LateParsedDeclaration { 00817 Parser *Self; 00818 CachedTokens Toks; 00819 IdentifierInfo &AttrName; 00820 SourceLocation AttrNameLoc; 00821 SmallVector<Decl*, 2> Decls; 00822 00823 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name, 00824 SourceLocation Loc) 00825 : Self(P), AttrName(Name), AttrNameLoc(Loc) {} 00826 00827 virtual void ParseLexedAttributes(); 00828 00829 void addDecl(Decl *D) { Decls.push_back(D); } 00830 }; 00831 00832 /// A list of late parsed attributes. Used by ParseGNUAttributes. 00833 typedef llvm::SmallVector<LateParsedAttribute*, 2> LateParsedAttrList; 00834 00835 00836 /// Contains the lexed tokens of a member function definition 00837 /// which needs to be parsed at the end of the class declaration 00838 /// after parsing all other member declarations. 00839 struct LexedMethod : public LateParsedDeclaration { 00840 Parser *Self; 00841 Decl *D; 00842 CachedTokens Toks; 00843 00844 /// \brief Whether this member function had an associated template 00845 /// scope. When true, D is a template declaration. 00846 /// othewise, it is a member function declaration. 00847 bool TemplateScope; 00848 00849 explicit LexedMethod(Parser* P, Decl *MD) 00850 : Self(P), D(MD), TemplateScope(false) {} 00851 00852 virtual void ParseLexedMethodDefs(); 00853 }; 00854 00855 /// LateParsedDefaultArgument - Keeps track of a parameter that may 00856 /// have a default argument that cannot be parsed yet because it 00857 /// occurs within a member function declaration inside the class 00858 /// (C++ [class.mem]p2). 00859 struct LateParsedDefaultArgument { 00860 explicit LateParsedDefaultArgument(Decl *P, 00861 CachedTokens *Toks = 0) 00862 : Param(P), Toks(Toks) { } 00863 00864 /// Param - The parameter declaration for this parameter. 00865 Decl *Param; 00866 00867 /// Toks - The sequence of tokens that comprises the default 00868 /// argument expression, not including the '=' or the terminating 00869 /// ')' or ','. This will be NULL for parameters that have no 00870 /// default argument. 00871 CachedTokens *Toks; 00872 }; 00873 00874 /// LateParsedMethodDeclaration - A method declaration inside a class that 00875 /// contains at least one entity whose parsing needs to be delayed 00876 /// until the class itself is completely-defined, such as a default 00877 /// argument (C++ [class.mem]p2). 00878 struct LateParsedMethodDeclaration : public LateParsedDeclaration { 00879 explicit LateParsedMethodDeclaration(Parser *P, Decl *M) 00880 : Self(P), Method(M), TemplateScope(false), ExceptionSpecTokens(0) { } 00881 00882 virtual void ParseLexedMethodDeclarations(); 00883 00884 Parser* Self; 00885 00886 /// Method - The method declaration. 00887 Decl *Method; 00888 00889 /// \brief Whether this member function had an associated template 00890 /// scope. When true, D is a template declaration. 00891 /// othewise, it is a member function declaration. 00892 bool TemplateScope; 00893 00894 /// DefaultArgs - Contains the parameters of the function and 00895 /// their default arguments. At least one of the parameters will 00896 /// have a default argument, but all of the parameters of the 00897 /// method will be stored so that they can be reintroduced into 00898 /// scope at the appropriate times. 00899 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; 00900 00901 /// \brief The set of tokens that make up an exception-specification that 00902 /// has not yet been parsed. 00903 CachedTokens *ExceptionSpecTokens; 00904 }; 00905 00906 /// LateParsedMemberInitializer - An initializer for a non-static class data 00907 /// member whose parsing must to be delayed until the class is completely 00908 /// defined (C++11 [class.mem]p2). 00909 struct LateParsedMemberInitializer : public LateParsedDeclaration { 00910 LateParsedMemberInitializer(Parser *P, Decl *FD) 00911 : Self(P), Field(FD) { } 00912 00913 virtual void ParseLexedMemberInitializers(); 00914 00915 Parser *Self; 00916 00917 /// Field - The field declaration. 00918 Decl *Field; 00919 00920 /// CachedTokens - The sequence of tokens that comprises the initializer, 00921 /// including any leading '='. 00922 CachedTokens Toks; 00923 }; 00924 00925 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested) 00926 /// C++ class, its method declarations that contain parts that won't be 00927 /// parsed until after the definition is completed (C++ [class.mem]p2), 00928 /// the method declarations and possibly attached inline definitions 00929 /// will be stored here with the tokens that will be parsed to create those 00930 /// entities. 00931 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer; 00932 00933 /// \brief Representation of a class that has been parsed, including 00934 /// any member function declarations or definitions that need to be 00935 /// parsed after the corresponding top-level class is complete. 00936 struct ParsingClass { 00937 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass) 00938 : TopLevelClass(TopLevelClass), TemplateScope(false), 00939 TagOrTemplate(TagOrTemplate) { } 00940 00941 /// \brief Whether this is a "top-level" class, meaning that it is 00942 /// not nested within another class. 00943 bool TopLevelClass : 1; 00944 00945 /// \brief Whether this class had an associated template 00946 /// scope. When true, TagOrTemplate is a template declaration; 00947 /// othewise, it is a tag declaration. 00948 bool TemplateScope : 1; 00949 00950 /// \brief The class or class template whose definition we are parsing. 00951 Decl *TagOrTemplate; 00952 00953 /// LateParsedDeclarations - Method declarations, inline definitions and 00954 /// nested classes that contain pieces whose parsing will be delayed until 00955 /// the top-level class is fully defined. 00956 LateParsedDeclarationsContainer LateParsedDeclarations; 00957 }; 00958 00959 /// \brief The stack of classes that is currently being 00960 /// parsed. Nested and local classes will be pushed onto this stack 00961 /// when they are parsed, and removed afterward. 00962 std::stack<ParsingClass *> ClassStack; 00963 00964 ParsingClass &getCurrentClass() { 00965 assert(!ClassStack.empty() && "No lexed method stacks!"); 00966 return *ClassStack.top(); 00967 } 00968 00969 /// \brief RAII object used to manage the parsing of a class definition. 00970 class ParsingClassDefinition { 00971 Parser &P; 00972 bool Popped; 00973 Sema::ParsingClassState State; 00974 00975 public: 00976 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass) 00977 : P(P), Popped(false), 00978 State(P.PushParsingClass(TagOrTemplate, TopLevelClass)) { 00979 } 00980 00981 /// \brief Pop this class of the stack. 00982 void Pop() { 00983 assert(!Popped && "Nested class has already been popped"); 00984 Popped = true; 00985 P.PopParsingClass(State); 00986 } 00987 00988 ~ParsingClassDefinition() { 00989 if (!Popped) 00990 P.PopParsingClass(State); 00991 } 00992 }; 00993 00994 /// \brief Contains information about any template-specific 00995 /// information that has been parsed prior to parsing declaration 00996 /// specifiers. 00997 struct ParsedTemplateInfo { 00998 ParsedTemplateInfo() 00999 : Kind(NonTemplate), TemplateParams(0), TemplateLoc() { } 01000 01001 ParsedTemplateInfo(TemplateParameterLists *TemplateParams, 01002 bool isSpecialization, 01003 bool lastParameterListWasEmpty = false) 01004 : Kind(isSpecialization? ExplicitSpecialization : Template), 01005 TemplateParams(TemplateParams), 01006 LastParameterListWasEmpty(lastParameterListWasEmpty) { } 01007 01008 explicit ParsedTemplateInfo(SourceLocation ExternLoc, 01009 SourceLocation TemplateLoc) 01010 : Kind(ExplicitInstantiation), TemplateParams(0), 01011 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc), 01012 LastParameterListWasEmpty(false){ } 01013 01014 /// \brief The kind of template we are parsing. 01015 enum { 01016 /// \brief We are not parsing a template at all. 01017 NonTemplate = 0, 01018 /// \brief We are parsing a template declaration. 01019 Template, 01020 /// \brief We are parsing an explicit specialization. 01021 ExplicitSpecialization, 01022 /// \brief We are parsing an explicit instantiation. 01023 ExplicitInstantiation 01024 } Kind; 01025 01026 /// \brief The template parameter lists, for template declarations 01027 /// and explicit specializations. 01028 TemplateParameterLists *TemplateParams; 01029 01030 /// \brief The location of the 'extern' keyword, if any, for an explicit 01031 /// instantiation 01032 SourceLocation ExternLoc; 01033 01034 /// \brief The location of the 'template' keyword, for an explicit 01035 /// instantiation. 01036 SourceLocation TemplateLoc; 01037 01038 /// \brief Whether the last template parameter list was empty. 01039 bool LastParameterListWasEmpty; 01040 01041 SourceRange getSourceRange() const LLVM_READONLY; 01042 }; 01043 01044 /// \brief Contains a late templated function. 01045 /// Will be parsed at the end of the translation unit. 01046 struct LateParsedTemplatedFunction { 01047 explicit LateParsedTemplatedFunction(Decl *MD) 01048 : D(MD) {} 01049 01050 CachedTokens Toks; 01051 01052 /// \brief The template function declaration to be late parsed. 01053 Decl *D; 01054 }; 01055 01056 void LexTemplateFunctionForLateParsing(CachedTokens &Toks); 01057 void ParseLateTemplatedFuncDef(LateParsedTemplatedFunction &LMT); 01058 typedef llvm::DenseMap<const FunctionDecl*, LateParsedTemplatedFunction*> 01059 LateParsedTemplateMapT; 01060 LateParsedTemplateMapT LateParsedTemplateMap; 01061 01062 static void LateTemplateParserCallback(void *P, const FunctionDecl *FD); 01063 void LateTemplateParser(const FunctionDecl *FD); 01064 01065 Sema::ParsingClassState 01066 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass); 01067 void DeallocateParsedClasses(ParsingClass *Class); 01068 void PopParsingClass(Sema::ParsingClassState); 01069 01070 Decl *ParseCXXInlineMethodDef(AccessSpecifier AS, AttributeList *AccessAttrs, 01071 ParsingDeclarator &D, 01072 const ParsedTemplateInfo &TemplateInfo, 01073 const VirtSpecifiers& VS, 01074 FunctionDefinitionKind DefinitionKind, 01075 ExprResult& Init); 01076 void ParseCXXNonStaticMemberInitializer(Decl *VarD); 01077 void ParseLexedAttributes(ParsingClass &Class); 01078 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, 01079 bool EnterScope, bool OnDefinition); 01080 void ParseLexedAttribute(LateParsedAttribute &LA, 01081 bool EnterScope, bool OnDefinition); 01082 void ParseLexedMethodDeclarations(ParsingClass &Class); 01083 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM); 01084 void ParseLexedMethodDefs(ParsingClass &Class); 01085 void ParseLexedMethodDef(LexedMethod &LM); 01086 void ParseLexedMemberInitializers(ParsingClass &Class); 01087 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI); 01088 Decl *ParseLexedObjCMethodDefs(LexedMethod &LM); 01089 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks); 01090 bool ConsumeAndStoreUntil(tok::TokenKind T1, 01091 CachedTokens &Toks, 01092 bool StopAtSemi = true, 01093 bool ConsumeFinalToken = true) { 01094 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken); 01095 } 01096 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, 01097 CachedTokens &Toks, 01098 bool StopAtSemi = true, 01099 bool ConsumeFinalToken = true); 01100 01101 //===--------------------------------------------------------------------===// 01102 // C99 6.9: External Definitions. 01103 struct ParsedAttributesWithRange : ParsedAttributes { 01104 ParsedAttributesWithRange(AttributeFactory &factory) 01105 : ParsedAttributes(factory) {} 01106 01107 SourceRange Range; 01108 }; 01109 01110 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs, 01111 ParsingDeclSpec *DS = 0); 01112 bool isDeclarationAfterDeclarator(); 01113 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator); 01114 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(ParsedAttributes &attrs, 01115 AccessSpecifier AS = AS_none); 01116 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition(ParsingDeclSpec &DS, 01117 AccessSpecifier AS = AS_none); 01118 01119 Decl *ParseFunctionDefinition(ParsingDeclarator &D, 01120 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), 01121 LateParsedAttrList *LateParsedAttrs = 0); 01122 void ParseKNRParamDeclarations(Declarator &D); 01123 // EndLoc, if non-NULL, is filled with the location of the last token of 01124 // the simple-asm. 01125 ExprResult ParseSimpleAsm(SourceLocation *EndLoc = 0); 01126 ExprResult ParseAsmStringLiteral(); 01127 01128 // Objective-C External Declarations 01129 DeclGroupPtrTy ParseObjCAtDirectives(); 01130 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); 01131 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, 01132 ParsedAttributes &prefixAttrs); 01133 void ParseObjCClassInstanceVariables(Decl *interfaceDecl, 01134 tok::ObjCKeywordKind visibility, 01135 SourceLocation atLoc); 01136 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P, 01137 SmallVectorImpl<SourceLocation> &PLocs, 01138 bool WarnOnDeclarations, 01139 SourceLocation &LAngleLoc, 01140 SourceLocation &EndProtoLoc); 01141 bool ParseObjCProtocolQualifiers(DeclSpec &DS); 01142 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, 01143 Decl *CDecl); 01144 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, 01145 ParsedAttributes &prefixAttrs); 01146 01147 struct ObjCImplParsingDataRAII { 01148 Parser &P; 01149 Decl *Dcl; 01150 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer; 01151 LateParsedObjCMethodContainer LateParsedObjCMethods; 01152 01153 ObjCImplParsingDataRAII(Parser &parser, Decl *D) 01154 : P(parser), Dcl(D) { 01155 P.CurParsedObjCImpl = this; 01156 Finished = false; 01157 } 01158 ~ObjCImplParsingDataRAII(); 01159 01160 void finish(SourceRange AtEnd); 01161 bool isFinished() const { return Finished; } 01162 01163 private: 01164 bool Finished; 01165 }; 01166 ObjCImplParsingDataRAII *CurParsedObjCImpl; 01167 01168 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc); 01169 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd); 01170 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc); 01171 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc); 01172 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc); 01173 01174 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); 01175 // Definitions for Objective-c context sensitive keywords recognition. 01176 enum ObjCTypeQual { 01177 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, 01178 objc_NumQuals 01179 }; 01180 IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; 01181 01182 bool isTokIdentifier_in() const; 01183 01184 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx, 01185 ParsedAttributes *ParamAttrs); 01186 void ParseObjCMethodRequirement(); 01187 Decl *ParseObjCMethodPrototype( 01188 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, 01189 bool MethodDefinition = true); 01190 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, 01191 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, 01192 bool MethodDefinition=true); 01193 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); 01194 01195 Decl *ParseObjCMethodDefinition(); 01196 01197 //===--------------------------------------------------------------------===// 01198 // C99 6.5: Expressions. 01199 01200 /// TypeCastState - State whether an expression is or may be a type cast. 01201 enum TypeCastState { 01202 NotTypeCast = 0, 01203 MaybeTypeCast, 01204 IsTypeCast 01205 }; 01206 01207 ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast); 01208 ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast); 01209 // Expr that doesn't include commas. 01210 ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); 01211 01212 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); 01213 01214 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); 01215 01216 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, 01217 prec::Level MinPrec); 01218 ExprResult ParseCastExpression(bool isUnaryExpression, 01219 bool isAddressOfOperand, 01220 bool &NotCastExpr, 01221 TypeCastState isTypeCast); 01222 ExprResult ParseCastExpression(bool isUnaryExpression, 01223 bool isAddressOfOperand = false, 01224 TypeCastState isTypeCast = NotTypeCast); 01225 01226 /// Returns true if the next token would start a postfix-expression 01227 /// suffix. 01228 bool isPostfixExpressionSuffixStart() { 01229 tok::TokenKind K = Tok.getKind(); 01230 return (K == tok::l_square || K == tok::l_paren || 01231 K == tok::period || K == tok::arrow || 01232 K == tok::plusplus || K == tok::minusminus); 01233 } 01234 01235 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS); 01236 ExprResult ParseUnaryExprOrTypeTraitExpression(); 01237 ExprResult ParseBuiltinPrimaryExpression(); 01238 01239 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, 01240 bool &isCastExpr, 01241 ParsedType &CastTy, 01242 SourceRange &CastRange); 01243 01244 typedef SmallVector<Expr*, 20> ExprListTy; 01245 typedef SmallVector<SourceLocation, 20> CommaLocsTy; 01246 01247 /// ParseExpressionList - Used for C/C++ (argument-)expression-list. 01248 bool ParseExpressionList(SmallVectorImpl<Expr*> &Exprs, 01249 SmallVectorImpl<SourceLocation> &CommaLocs, 01250 void (Sema::*Completer)(Scope *S, 01251 Expr *Data, 01252 llvm::ArrayRef<Expr *> Args) = 0, 01253 Expr *Data = 0); 01254 01255 /// ParenParseOption - Control what ParseParenExpression will parse. 01256 enum ParenParseOption { 01257 SimpleExpr, // Only parse '(' expression ')' 01258 CompoundStmt, // Also allow '(' compound-statement ')' 01259 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' 01260 CastExpr // Also allow '(' type-name ')' <anything> 01261 }; 01262 ExprResult ParseParenExpression(ParenParseOption &ExprType, 01263 bool stopIfCastExpr, 01264 bool isTypeCast, 01265 ParsedType &CastTy, 01266 SourceLocation &RParenLoc); 01267 01268 ExprResult ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, 01269 ParsedType &CastTy, 01270 BalancedDelimiterTracker &Tracker); 01271 ExprResult ParseCompoundLiteralExpression(ParsedType Ty, 01272 SourceLocation LParenLoc, 01273 SourceLocation RParenLoc); 01274 01275 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); 01276 01277 ExprResult ParseGenericSelectionExpression(); 01278 01279 ExprResult ParseObjCBoolLiteral(); 01280 01281 //===--------------------------------------------------------------------===// 01282 // C++ Expressions 01283 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); 01284 01285 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr, 01286 bool EnteringContext, IdentifierInfo &II, 01287 CXXScopeSpec &SS); 01288 01289 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, 01290 ParsedType ObjectType, 01291 bool EnteringContext, 01292 bool *MayBePseudoDestructor = 0, 01293 bool IsTypename = false); 01294 01295 //===--------------------------------------------------------------------===// 01296 // C++0x 5.1.2: Lambda expressions 01297 01298 // [...] () -> type {...} 01299 ExprResult ParseLambdaExpression(); 01300 ExprResult TryParseLambdaExpression(); 01301 llvm::Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro); 01302 bool TryParseLambdaIntroducer(LambdaIntroducer &Intro); 01303 ExprResult ParseLambdaExpressionAfterIntroducer( 01304 LambdaIntroducer &Intro); 01305 01306 //===--------------------------------------------------------------------===// 01307 // C++ 5.2p1: C++ Casts 01308 ExprResult ParseCXXCasts(); 01309 01310 //===--------------------------------------------------------------------===// 01311 // C++ 5.2p1: C++ Type Identification 01312 ExprResult ParseCXXTypeid(); 01313 01314 //===--------------------------------------------------------------------===// 01315 // C++ : Microsoft __uuidof Expression 01316 ExprResult ParseCXXUuidof(); 01317 01318 //===--------------------------------------------------------------------===// 01319 // C++ 5.2.4: C++ Pseudo-Destructor Expressions 01320 ExprResult ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc, 01321 tok::TokenKind OpKind, 01322 CXXScopeSpec &SS, 01323 ParsedType ObjectType); 01324 01325 //===--------------------------------------------------------------------===// 01326 // C++ 9.3.2: C++ 'this' pointer 01327 ExprResult ParseCXXThis(); 01328 01329 //===--------------------------------------------------------------------===// 01330 // C++ 15: C++ Throw Expression 01331 ExprResult ParseThrowExpression(); 01332 01333 ExceptionSpecificationType tryParseExceptionSpecification( 01334 SourceRange &SpecificationRange, 01335 SmallVectorImpl<ParsedType> &DynamicExceptions, 01336 SmallVectorImpl<SourceRange> &DynamicExceptionRanges, 01337 ExprResult &NoexceptExpr); 01338 01339 // EndLoc is filled with the location of the last token of the specification. 01340 ExceptionSpecificationType ParseDynamicExceptionSpecification( 01341 SourceRange &SpecificationRange, 01342 SmallVectorImpl<ParsedType> &Exceptions, 01343 SmallVectorImpl<SourceRange> &Ranges); 01344 01345 //===--------------------------------------------------------------------===// 01346 // C++0x 8: Function declaration trailing-return-type 01347 TypeResult ParseTrailingReturnType(SourceRange &Range); 01348 01349 //===--------------------------------------------------------------------===// 01350 // C++ 2.13.5: C++ Boolean Literals 01351 ExprResult ParseCXXBoolLiteral(); 01352 01353 //===--------------------------------------------------------------------===// 01354 // C++ 5.2.3: Explicit type conversion (functional notation) 01355 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); 01356 01357 bool isCXXSimpleTypeSpecifier() const; 01358 01359 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. 01360 /// This should only be called when the current token is known to be part of 01361 /// simple-type-specifier. 01362 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); 01363 01364 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS); 01365 01366 //===--------------------------------------------------------------------===// 01367 // C++ 5.3.4 and 5.3.5: C++ new and delete 01368 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs, 01369 Declarator &D); 01370 void ParseDirectNewDeclarator(Declarator &D); 01371 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); 01372 ExprResult ParseCXXDeleteExpression(bool UseGlobal, 01373 SourceLocation Start); 01374 01375 //===--------------------------------------------------------------------===// 01376 // C++ if/switch/while condition expression. 01377 bool ParseCXXCondition(ExprResult &ExprResult, Decl *&DeclResult, 01378 SourceLocation Loc, bool ConvertToBoolean); 01379 01380 //===--------------------------------------------------------------------===// 01381 // C++ types 01382 01383 //===--------------------------------------------------------------------===// 01384 // C99 6.7.8: Initialization. 01385 01386 /// ParseInitializer 01387 /// initializer: [C99 6.7.8] 01388 /// assignment-expression 01389 /// '{' ... 01390 ExprResult ParseInitializer() { 01391 if (Tok.isNot(tok::l_brace)) 01392 return ParseAssignmentExpression(); 01393 return ParseBraceInitializer(); 01394 } 01395 bool MayBeDesignationStart(); 01396 ExprResult ParseBraceInitializer(); 01397 ExprResult ParseInitializerWithPotentialDesignator(); 01398 01399 //===--------------------------------------------------------------------===// 01400 // clang Expressions 01401 01402 ExprResult ParseBlockLiteralExpression(); // ^{...} 01403 01404 //===--------------------------------------------------------------------===// 01405 // Objective-C Expressions 01406 ExprResult ParseObjCAtExpression(SourceLocation AtLocation); 01407 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc); 01408 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc); 01409 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc); 01410 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue); 01411 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc); 01412 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc); 01413 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc); 01414 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); 01415 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); 01416 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); 01417 bool isSimpleObjCMessageExpression(); 01418 ExprResult ParseObjCMessageExpression(); 01419 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, 01420 SourceLocation SuperLoc, 01421 ParsedType ReceiverType, 01422 ExprArg ReceiverExpr); 01423 ExprResult ParseAssignmentExprWithObjCMessageExprStart( 01424 SourceLocation LBracloc, SourceLocation SuperLoc, 01425 ParsedType ReceiverType, ExprArg ReceiverExpr); 01426 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr); 01427 01428 //===--------------------------------------------------------------------===// 01429 // C99 6.8: Statements and Blocks. 01430 01431 StmtResult ParseStatement(SourceLocation *TrailingElseLoc = 0) { 01432 StmtVector Stmts(Actions); 01433 return ParseStatementOrDeclaration(Stmts, true, TrailingElseLoc); 01434 } 01435 StmtResult ParseStatementOrDeclaration(StmtVector &Stmts, 01436 bool OnlyStatement, 01437 SourceLocation *TrailingElseLoc = 0); 01438 StmtResult ParseStatementOrDeclarationAfterAttributes( 01439 StmtVector &Stmts, 01440 bool OnlyStatement, 01441 SourceLocation *TrailingElseLoc, 01442 ParsedAttributesWithRange &Attrs); 01443 StmtResult ParseExprStatement(); 01444 StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs); 01445 StmtResult ParseCaseStatement(bool MissingCase = false, 01446 ExprResult Expr = ExprResult()); 01447 StmtResult ParseDefaultStatement(); 01448 StmtResult ParseCompoundStatement(bool isStmtExpr = false); 01449 StmtResult ParseCompoundStatement(bool isStmtExpr, 01450 unsigned ScopeFlags); 01451 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false); 01452 bool ParseParenExprOrCondition(ExprResult &ExprResult, 01453 Decl *&DeclResult, 01454 SourceLocation Loc, 01455 bool ConvertToBoolean); 01456 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc); 01457 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc); 01458 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc); 01459 StmtResult ParseDoStatement(); 01460 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc); 01461 StmtResult ParseGotoStatement(); 01462 StmtResult ParseContinueStatement(); 01463 StmtResult ParseBreakStatement(); 01464 StmtResult ParseReturnStatement(); 01465 StmtResult ParseAsmStatement(bool &msAsm); 01466 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc); 01467 01468 /// \brief Describes the behavior that should be taken for an __if_exists 01469 /// block. 01470 enum IfExistsBehavior { 01471 /// \brief Parse the block; this code is always used. 01472 IEB_Parse, 01473 /// \brief Skip the block entirely; this code is never used. 01474 IEB_Skip, 01475 /// \brief Parse the block as a dependent block, which may be used in 01476 /// some template instantiations but not others. 01477 IEB_Dependent 01478 }; 01479 01480 /// \brief Describes the condition of a Microsoft __if_exists or 01481 /// __if_not_exists block. 01482 struct IfExistsCondition { 01483 /// \brief The location of the initial keyword. 01484 SourceLocation KeywordLoc; 01485 /// \brief Whether this is an __if_exists block (rather than an 01486 /// __if_not_exists block). 01487 bool IsIfExists; 01488 01489 /// \brief Nested-name-specifier preceding the name. 01490 CXXScopeSpec SS; 01491 01492 /// \brief The name we're looking for. 01493 UnqualifiedId Name; 01494 01495 /// \brief The behavior of this __if_exists or __if_not_exists block 01496 /// should. 01497 IfExistsBehavior Behavior; 01498 }; 01499 01500 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result); 01501 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts); 01502 void ParseMicrosoftIfExistsExternalDeclaration(); 01503 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, 01504 AccessSpecifier& CurAS); 01505 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, 01506 bool &InitExprsOk); 01507 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, 01508 SmallVectorImpl<Expr *> &Constraints, 01509 SmallVectorImpl<Expr *> &Exprs); 01510 01511 //===--------------------------------------------------------------------===// 01512 // C++ 6: Statements and Blocks 01513 01514 StmtResult ParseCXXTryBlock(); 01515 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc); 01516 StmtResult ParseCXXCatchBlock(); 01517 01518 //===--------------------------------------------------------------------===// 01519 // MS: SEH Statements and Blocks 01520 01521 StmtResult ParseSEHTryBlock(); 01522 StmtResult ParseSEHTryBlockCommon(SourceLocation Loc); 01523 StmtResult ParseSEHExceptBlock(SourceLocation Loc); 01524 StmtResult ParseSEHFinallyBlock(SourceLocation Loc); 01525 01526 //===--------------------------------------------------------------------===// 01527 // Objective-C Statements 01528 01529 StmtResult ParseObjCAtStatement(SourceLocation atLoc); 01530 StmtResult ParseObjCTryStmt(SourceLocation atLoc); 01531 StmtResult ParseObjCThrowStmt(SourceLocation atLoc); 01532 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); 01533 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc); 01534 01535 01536 //===--------------------------------------------------------------------===// 01537 // C99 6.7: Declarations. 01538 01539 /// A context for parsing declaration specifiers. TODO: flesh this 01540 /// out, there are other significant restrictions on specifiers than 01541 /// would be best implemented in the parser. 01542 enum DeclSpecContext { 01543 DSC_normal, // normal context 01544 DSC_class, // class context, enables 'friend' 01545 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list 01546 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type 01547 DSC_top_level // top-level/namespace declaration context 01548 }; 01549 01550 /// Information on a C++0x for-range-initializer found while parsing a 01551 /// declaration which turns out to be a for-range-declaration. 01552 struct ForRangeInit { 01553 SourceLocation ColonLoc; 01554 ExprResult RangeExpr; 01555 01556 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); } 01557 }; 01558 01559 DeclGroupPtrTy ParseDeclaration(StmtVector &Stmts, 01560 unsigned Context, SourceLocation &DeclEnd, 01561 ParsedAttributesWithRange &attrs); 01562 DeclGroupPtrTy ParseSimpleDeclaration(StmtVector &Stmts, 01563 unsigned Context, 01564 SourceLocation &DeclEnd, 01565 ParsedAttributes &attrs, 01566 bool RequireSemi, 01567 ForRangeInit *FRI = 0); 01568 bool MightBeDeclarator(unsigned Context); 01569 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context, 01570 bool AllowFunctionDefinitions, 01571 SourceLocation *DeclEnd = 0, 01572 ForRangeInit *FRI = 0); 01573 Decl *ParseDeclarationAfterDeclarator(Declarator &D, 01574 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); 01575 bool ParseAsmAttributesAfterDeclarator(Declarator &D); 01576 Decl *ParseDeclarationAfterDeclaratorAndAttributes(Declarator &D, 01577 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); 01578 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope); 01579 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope); 01580 01581 /// \brief When in code-completion, skip parsing of the function/method body 01582 /// unless the body contains the code-completion point. 01583 /// 01584 /// \returns true if the function body was skipped. 01585 bool trySkippingFunctionBody(); 01586 01587 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, 01588 const ParsedTemplateInfo &TemplateInfo, 01589 AccessSpecifier AS, DeclSpecContext DSC); 01590 DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context); 01591 void ParseDeclarationSpecifiers(DeclSpec &DS, 01592 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), 01593 AccessSpecifier AS = AS_none, 01594 DeclSpecContext DSC = DSC_normal, 01595 LateParsedAttrList *LateAttrs = 0); 01596 01597 void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none, 01598 DeclSpecContext DSC = DSC_normal); 01599 01600 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, 01601 Declarator::TheContext Context); 01602 01603 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, 01604 const ParsedTemplateInfo &TemplateInfo, 01605 AccessSpecifier AS, DeclSpecContext DSC); 01606 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl); 01607 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType, 01608 Decl *TagDecl); 01609 01610 struct FieldCallback { 01611 virtual Decl *invoke(FieldDeclarator &Field) = 0; 01612 virtual ~FieldCallback() {} 01613 01614 private: 01615 virtual void _anchor(); 01616 }; 01617 struct ObjCPropertyCallback; 01618 01619 void ParseStructDeclaration(DeclSpec &DS, FieldCallback &Callback); 01620 01621 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false); 01622 bool isTypeSpecifierQualifier(); 01623 bool isTypeQualifier() const; 01624 01625 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token 01626 /// is definitely a type-specifier. Return false if it isn't part of a type 01627 /// specifier or if we're not sure. 01628 bool isKnownToBeTypeSpecifier(const Token &Tok) const; 01629 01630 /// isDeclarationStatement - Disambiguates between a declaration or an 01631 /// expression statement, when parsing function bodies. 01632 /// Returns true for declaration, false for expression. 01633 bool isDeclarationStatement() { 01634 if (getLangOpts().CPlusPlus) 01635 return isCXXDeclarationStatement(); 01636 return isDeclarationSpecifier(true); 01637 } 01638 01639 /// isForInitDeclaration - Disambiguates between a declaration or an 01640 /// expression in the context of the C 'clause-1' or the C++ 01641 // 'for-init-statement' part of a 'for' statement. 01642 /// Returns true for declaration, false for expression. 01643 bool isForInitDeclaration() { 01644 if (getLangOpts().CPlusPlus) 01645 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true); 01646 return isDeclarationSpecifier(true); 01647 } 01648 01649 /// \brief Determine whether we are currently at the start of an Objective-C 01650 /// class message that appears to be missing the open bracket '['. 01651 bool isStartOfObjCClassMessageMissingOpenBracket(); 01652 01653 /// \brief Starting with a scope specifier, identifier, or 01654 /// template-id that refers to the current class, determine whether 01655 /// this is a constructor declarator. 01656 bool isConstructorDeclarator(); 01657 01658 /// \brief Specifies the context in which type-id/expression 01659 /// disambiguation will occur. 01660 enum TentativeCXXTypeIdContext { 01661 TypeIdInParens, 01662 TypeIdAsTemplateArgument 01663 }; 01664 01665 01666 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know 01667 /// whether the parens contain an expression or a type-id. 01668 /// Returns true for a type-id and false for an expression. 01669 bool isTypeIdInParens(bool &isAmbiguous) { 01670 if (getLangOpts().CPlusPlus) 01671 return isCXXTypeId(TypeIdInParens, isAmbiguous); 01672 isAmbiguous = false; 01673 return isTypeSpecifierQualifier(); 01674 } 01675 bool isTypeIdInParens() { 01676 bool isAmbiguous; 01677 return isTypeIdInParens(isAmbiguous); 01678 } 01679 01680 /// isCXXDeclarationStatement - C++-specialized function that disambiguates 01681 /// between a declaration or an expression statement, when parsing function 01682 /// bodies. Returns true for declaration, false for expression. 01683 bool isCXXDeclarationStatement(); 01684 01685 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates 01686 /// between a simple-declaration or an expression-statement. 01687 /// If during the disambiguation process a parsing error is encountered, 01688 /// the function returns true to let the declaration parsing code handle it. 01689 /// Returns false if the statement is disambiguated as expression. 01690 bool isCXXSimpleDeclaration(bool AllowForRangeDecl); 01691 01692 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or 01693 /// a constructor-style initializer, when parsing declaration statements. 01694 /// Returns true for function declarator and false for constructor-style 01695 /// initializer. If 'warnIfAmbiguous' is true a warning will be emitted to 01696 /// indicate that the parens were disambiguated as function declarator. 01697 /// If during the disambiguation process a parsing error is encountered, 01698 /// the function returns true to let the declaration parsing code handle it. 01699 bool isCXXFunctionDeclarator(bool warnIfAmbiguous); 01700 01701 /// isCXXConditionDeclaration - Disambiguates between a declaration or an 01702 /// expression for a condition of a if/switch/while/for statement. 01703 /// If during the disambiguation process a parsing error is encountered, 01704 /// the function returns true to let the declaration parsing code handle it. 01705 bool isCXXConditionDeclaration(); 01706 01707 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous); 01708 bool isCXXTypeId(TentativeCXXTypeIdContext Context) { 01709 bool isAmbiguous; 01710 return isCXXTypeId(Context, isAmbiguous); 01711 } 01712 01713 /// TPResult - Used as the result value for functions whose purpose is to 01714 /// disambiguate C++ constructs by "tentatively parsing" them. 01715 /// This is a class instead of a simple enum because the implicit enum-to-bool 01716 /// conversions may cause subtle bugs. 01717 class TPResult { 01718 enum Result { 01719 TPR_true, 01720 TPR_false, 01721 TPR_ambiguous, 01722 TPR_error 01723 }; 01724 Result Res; 01725 TPResult(Result result) : Res(result) {} 01726 public: 01727 static TPResult True() { return TPR_true; } 01728 static TPResult False() { return TPR_false; } 01729 static TPResult Ambiguous() { return TPR_ambiguous; } 01730 static TPResult Error() { return TPR_error; } 01731 01732 bool operator==(const TPResult &RHS) const { return Res == RHS.Res; } 01733 bool operator!=(const TPResult &RHS) const { return Res != RHS.Res; } 01734 }; 01735 01736 /// \brief Based only on the given token kind, determine whether we know that 01737 /// we're at the start of an expression or a type-specifier-seq (which may 01738 /// be an expression, in C++). 01739 /// 01740 /// This routine does not attempt to resolve any of the trick cases, e.g., 01741 /// those involving lookup of identifiers. 01742 /// 01743 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if 01744 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot 01745 /// tell. 01746 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind); 01747 01748 /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a 01749 /// declaration specifier, TPResult::False() if it is not, 01750 /// TPResult::Ambiguous() if it could be either a decl-specifier or a 01751 /// function-style cast, and TPResult::Error() if a parsing error was 01752 /// encountered. If it could be a braced C++11 function-style cast, returns 01753 /// BracedCastResult. 01754 /// Doesn't consume tokens. 01755 TPResult 01756 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False(), 01757 bool *HasMissingTypename = 0); 01758 01759 // "Tentative parsing" functions, used for disambiguation. If a parsing error 01760 // is encountered they will return TPResult::Error(). 01761 // Returning TPResult::True()/False() indicates that the ambiguity was 01762 // resolved and tentative parsing may stop. TPResult::Ambiguous() indicates 01763 // that more tentative parsing is necessary for disambiguation. 01764 // They all consume tokens, so backtracking should be used after calling them. 01765 01766 TPResult TryParseDeclarationSpecifier(bool *HasMissingTypename = 0); 01767 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl); 01768 TPResult TryParseTypeofSpecifier(); 01769 TPResult TryParseProtocolQualifiers(); 01770 TPResult TryParseInitDeclaratorList(); 01771 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true); 01772 TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = 0); 01773 TPResult TryParseFunctionDeclarator(); 01774 TPResult TryParseBracketDeclarator(); 01775 01776 TypeResult ParseTypeName(SourceRange *Range = 0, 01777 Declarator::TheContext Context 01778 = Declarator::TypeNameContext, 01779 AccessSpecifier AS = AS_none, 01780 Decl **OwnedType = 0); 01781 void ParseBlockId(); 01782 01783 // Check for the start of a C++11 attribute-specifier-seq in a context where 01784 // an attribute is not allowed. 01785 bool CheckProhibitedCXX11Attribute() { 01786 assert(Tok.is(tok::l_square)); 01787 if (!getLangOpts().CPlusPlus0x || NextToken().isNot(tok::l_square)) 01788 return false; 01789 return DiagnoseProhibitedCXX11Attribute(); 01790 } 01791 bool DiagnoseProhibitedCXX11Attribute(); 01792 01793 void ProhibitAttributes(ParsedAttributesWithRange &attrs) { 01794 if (!attrs.Range.isValid()) return; 01795 DiagnoseProhibitedAttributes(attrs); 01796 attrs.clear(); 01797 } 01798 void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs); 01799 01800 void MaybeParseGNUAttributes(Declarator &D, 01801 LateParsedAttrList *LateAttrs = 0) { 01802 if (Tok.is(tok::kw___attribute)) { 01803 ParsedAttributes attrs(AttrFactory); 01804 SourceLocation endLoc; 01805 ParseGNUAttributes(attrs, &endLoc, LateAttrs); 01806 D.takeAttributes(attrs, endLoc); 01807 } 01808 } 01809 void MaybeParseGNUAttributes(ParsedAttributes &attrs, 01810 SourceLocation *endLoc = 0, 01811 LateParsedAttrList *LateAttrs = 0) { 01812 if (Tok.is(tok::kw___attribute)) 01813 ParseGNUAttributes(attrs, endLoc, LateAttrs); 01814 } 01815 void ParseGNUAttributes(ParsedAttributes &attrs, 01816 SourceLocation *endLoc = 0, 01817 LateParsedAttrList *LateAttrs = 0); 01818 void ParseGNUAttributeArgs(IdentifierInfo *AttrName, 01819 SourceLocation AttrNameLoc, 01820 ParsedAttributes &Attrs, 01821 SourceLocation *EndLoc); 01822 01823 void MaybeParseCXX0XAttributes(Declarator &D) { 01824 if (getLangOpts().CPlusPlus0x && isCXX11AttributeSpecifier()) { 01825 ParsedAttributesWithRange attrs(AttrFactory); 01826 SourceLocation endLoc; 01827 ParseCXX11Attributes(attrs, &endLoc); 01828 D.takeAttributes(attrs, endLoc); 01829 } 01830 } 01831 void MaybeParseCXX0XAttributes(ParsedAttributes &attrs, 01832 SourceLocation *endLoc = 0) { 01833 if (getLangOpts().CPlusPlus0x && isCXX11AttributeSpecifier()) { 01834 ParsedAttributesWithRange attrsWithRange(AttrFactory); 01835 ParseCXX11Attributes(attrsWithRange, endLoc); 01836 attrs.takeAllFrom(attrsWithRange); 01837 } 01838 } 01839 void MaybeParseCXX0XAttributes(ParsedAttributesWithRange &attrs, 01840 SourceLocation *endLoc = 0, 01841 bool OuterMightBeMessageSend = false) { 01842 if (getLangOpts().CPlusPlus0x && 01843 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) 01844 ParseCXX11Attributes(attrs, endLoc); 01845 } 01846 01847 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, 01848 SourceLocation *EndLoc = 0); 01849 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs, 01850 SourceLocation *EndLoc = 0); 01851 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc); 01852 01853 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs, 01854 SourceLocation *endLoc = 0) { 01855 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square)) 01856 ParseMicrosoftAttributes(attrs, endLoc); 01857 } 01858 void ParseMicrosoftAttributes(ParsedAttributes &attrs, 01859 SourceLocation *endLoc = 0); 01860 void ParseMicrosoftDeclSpec(ParsedAttributes &attrs); 01861 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs); 01862 void ParseBorlandTypeAttributes(ParsedAttributes &attrs); 01863 void ParseOpenCLAttributes(ParsedAttributes &attrs); 01864 void ParseOpenCLQualifiers(DeclSpec &DS); 01865 01866 VersionTuple ParseVersionTuple(SourceRange &Range); 01867 void ParseAvailabilityAttribute(IdentifierInfo &Availability, 01868 SourceLocation AvailabilityLoc, 01869 ParsedAttributes &attrs, 01870 SourceLocation *endLoc); 01871 01872 bool IsThreadSafetyAttribute(llvm::StringRef AttrName); 01873 void ParseThreadSafetyAttribute(IdentifierInfo &AttrName, 01874 SourceLocation AttrNameLoc, 01875 ParsedAttributes &Attrs, 01876 SourceLocation *EndLoc); 01877 01878 01879 void ParseTypeofSpecifier(DeclSpec &DS); 01880 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS); 01881 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS, 01882 SourceLocation StartLoc, 01883 SourceLocation EndLoc); 01884 void ParseUnderlyingTypeSpecifier(DeclSpec &DS); 01885 void ParseAtomicSpecifier(DeclSpec &DS); 01886 01887 ExprResult ParseAlignArgument(SourceLocation Start, 01888 SourceLocation &EllipsisLoc); 01889 void ParseAlignmentSpecifier(ParsedAttributes &Attrs, 01890 SourceLocation *endLoc = 0); 01891 01892 VirtSpecifiers::Specifier isCXX0XVirtSpecifier(const Token &Tok) const; 01893 VirtSpecifiers::Specifier isCXX0XVirtSpecifier() const { 01894 return isCXX0XVirtSpecifier(Tok); 01895 } 01896 void ParseOptionalCXX0XVirtSpecifierSeq(VirtSpecifiers &VS); 01897 01898 bool isCXX0XFinalKeyword() const; 01899 01900 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to 01901 /// enter a new C++ declarator scope and exit it when the function is 01902 /// finished. 01903 class DeclaratorScopeObj { 01904 Parser &P; 01905 CXXScopeSpec &SS; 01906 bool EnteredScope; 01907 bool CreatedScope; 01908 public: 01909 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) 01910 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {} 01911 01912 void EnterDeclaratorScope() { 01913 assert(!EnteredScope && "Already entered the scope!"); 01914 assert(SS.isSet() && "C++ scope was not set!"); 01915 01916 CreatedScope = true; 01917 P.EnterScope(0); // Not a decl scope. 01918 01919 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS)) 01920 EnteredScope = true; 01921 } 01922 01923 ~DeclaratorScopeObj() { 01924 if (EnteredScope) { 01925 assert(SS.isSet() && "C++ scope was cleared ?"); 01926 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS); 01927 } 01928 if (CreatedScope) 01929 P.ExitScope(); 01930 } 01931 }; 01932 01933 /// ParseDeclarator - Parse and verify a newly-initialized declarator. 01934 void ParseDeclarator(Declarator &D); 01935 /// A function that parses a variant of direct-declarator. 01936 typedef void (Parser::*DirectDeclParseFunction)(Declarator&); 01937 void ParseDeclaratorInternal(Declarator &D, 01938 DirectDeclParseFunction DirectDeclParser); 01939 01940 void ParseTypeQualifierListOpt(DeclSpec &DS, bool GNUAttributesAllowed = true, 01941 bool CXX0XAttributesAllowed = true); 01942 void ParseDirectDeclarator(Declarator &D); 01943 void ParseParenDeclarator(Declarator &D); 01944 void ParseFunctionDeclarator(Declarator &D, 01945 ParsedAttributes &attrs, 01946 BalancedDelimiterTracker &Tracker, 01947 bool RequiresArg = false); 01948 bool isFunctionDeclaratorIdentifierList(); 01949 void ParseFunctionDeclaratorIdentifierList( 01950 Declarator &D, 01951 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo); 01952 void ParseParameterDeclarationClause( 01953 Declarator &D, 01954 ParsedAttributes &attrs, 01955 SmallVector<DeclaratorChunk::ParamInfo, 16> &ParamInfo, 01956 SourceLocation &EllipsisLoc); 01957 void ParseBracketDeclarator(Declarator &D); 01958 01959 //===--------------------------------------------------------------------===// 01960 // C++ 7: Declarations [dcl.dcl] 01961 01962 /// The kind of attribute specifier we have found. 01963 enum CXX11AttributeKind { 01964 /// This is not an attribute specifier. 01965 CAK_NotAttributeSpecifier, 01966 /// This should be treated as an attribute-specifier. 01967 CAK_AttributeSpecifier, 01968 /// The next tokens are '[[', but this is not an attribute-specifier. This 01969 /// is ill-formed by C++11 [dcl.attr.grammar]p6. 01970 CAK_InvalidAttributeSpecifier 01971 }; 01972 CXX11AttributeKind 01973 isCXX11AttributeSpecifier(bool Disambiguate = false, 01974 bool OuterMightBeMessageSend = false); 01975 01976 Decl *ParseNamespace(unsigned Context, SourceLocation &DeclEnd, 01977 SourceLocation InlineLoc = SourceLocation()); 01978 void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc, 01979 std::vector<IdentifierInfo*>& Ident, 01980 std::vector<SourceLocation>& NamespaceLoc, 01981 unsigned int index, SourceLocation& InlineLoc, 01982 ParsedAttributes& attrs, 01983 BalancedDelimiterTracker &Tracker); 01984 Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context); 01985 Decl *ParseUsingDirectiveOrDeclaration(unsigned Context, 01986 const ParsedTemplateInfo &TemplateInfo, 01987 SourceLocation &DeclEnd, 01988 ParsedAttributesWithRange &attrs, 01989 Decl **OwnedType = 0); 01990 Decl *ParseUsingDirective(unsigned Context, 01991 SourceLocation UsingLoc, 01992 SourceLocation &DeclEnd, 01993 ParsedAttributes &attrs); 01994 Decl *ParseUsingDeclaration(unsigned Context, 01995 const ParsedTemplateInfo &TemplateInfo, 01996 SourceLocation UsingLoc, 01997 SourceLocation &DeclEnd, 01998 AccessSpecifier AS = AS_none, 01999 Decl **OwnedType = 0); 02000 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd); 02001 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc, 02002 SourceLocation AliasLoc, IdentifierInfo *Alias, 02003 SourceLocation &DeclEnd); 02004 02005 //===--------------------------------------------------------------------===// 02006 // C++ 9: classes [class] and C structs/unions. 02007 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, 02008 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, 02009 AccessSpecifier AS, bool EnteringContext, 02010 DeclSpecContext DSC); 02011 void ParseCXXMemberSpecification(SourceLocation StartLoc, unsigned TagType, 02012 Decl *TagDecl); 02013 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction, 02014 SourceLocation &EqualLoc); 02015 void ParseCXXClassMemberDeclaration(AccessSpecifier AS, AttributeList *Attr, 02016 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), 02017 ParsingDeclRAIIObject *DiagsFromTParams = 0); 02018 void ParseConstructorInitializer(Decl *ConstructorDecl); 02019 MemInitResult ParseMemInitializer(Decl *ConstructorDecl); 02020 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, 02021 Decl *ThisDecl); 02022 02023 //===--------------------------------------------------------------------===// 02024 // C++ 10: Derived classes [class.derived] 02025 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc, 02026 SourceLocation &EndLocation); 02027 void ParseBaseClause(Decl *ClassDecl); 02028 BaseResult ParseBaseSpecifier(Decl *ClassDecl); 02029 AccessSpecifier getAccessSpecifierIfPresent() const; 02030 02031 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, 02032 SourceLocation TemplateKWLoc, 02033 IdentifierInfo *Name, 02034 SourceLocation NameLoc, 02035 bool EnteringContext, 02036 ParsedType ObjectType, 02037 UnqualifiedId &Id, 02038 bool AssumeTemplateId); 02039 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, 02040 ParsedType ObjectType, 02041 UnqualifiedId &Result); 02042 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, 02043 bool AllowDestructorName, 02044 bool AllowConstructorName, 02045 ParsedType ObjectType, 02046 SourceLocation& TemplateKWLoc, 02047 UnqualifiedId &Result); 02048 02049 //===--------------------------------------------------------------------===// 02050 // C++ 14: Templates [temp] 02051 02052 // C++ 14.1: Template Parameters [temp.param] 02053 Decl *ParseDeclarationStartingWithTemplate(unsigned Context, 02054 SourceLocation &DeclEnd, 02055 AccessSpecifier AS = AS_none, 02056 AttributeList *AccessAttrs = 0); 02057 Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context, 02058 SourceLocation &DeclEnd, 02059 AccessSpecifier AS, 02060 AttributeList *AccessAttrs); 02061 Decl *ParseSingleDeclarationAfterTemplate( 02062 unsigned Context, 02063 const ParsedTemplateInfo &TemplateInfo, 02064 ParsingDeclRAIIObject &DiagsFromParams, 02065 SourceLocation &DeclEnd, 02066 AccessSpecifier AS=AS_none, 02067 AttributeList *AccessAttrs = 0); 02068 bool ParseTemplateParameters(unsigned Depth, 02069 SmallVectorImpl<Decl*> &TemplateParams, 02070 SourceLocation &LAngleLoc, 02071 SourceLocation &RAngleLoc); 02072 bool ParseTemplateParameterList(unsigned Depth, 02073 SmallVectorImpl<Decl*> &TemplateParams); 02074 bool isStartOfTemplateTypeParameter(); 02075 Decl *ParseTemplateParameter(unsigned Depth, unsigned Position); 02076 Decl *ParseTypeParameter(unsigned Depth, unsigned Position); 02077 Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); 02078 Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); 02079 // C++ 14.3: Template arguments [temp.arg] 02080 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList; 02081 02082 bool ParseTemplateIdAfterTemplateName(TemplateTy Template, 02083 SourceLocation TemplateNameLoc, 02084 const CXXScopeSpec &SS, 02085 bool ConsumeLastToken, 02086 SourceLocation &LAngleLoc, 02087 TemplateArgList &TemplateArgs, 02088 SourceLocation &RAngleLoc); 02089 02090 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, 02091 CXXScopeSpec &SS, 02092 SourceLocation TemplateKWLoc, 02093 UnqualifiedId &TemplateName, 02094 bool AllowTypeAnnotation = true); 02095 void AnnotateTemplateIdTokenAsType(); 02096 bool IsTemplateArgumentList(unsigned Skip = 0); 02097 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs); 02098 ParsedTemplateArgument ParseTemplateTemplateArgument(); 02099 ParsedTemplateArgument ParseTemplateArgument(); 02100 Decl *ParseExplicitInstantiation(unsigned Context, 02101 SourceLocation ExternLoc, 02102 SourceLocation TemplateLoc, 02103 SourceLocation &DeclEnd, 02104 AccessSpecifier AS = AS_none); 02105 02106 //===--------------------------------------------------------------------===// 02107 // Modules 02108 DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc); 02109 02110 //===--------------------------------------------------------------------===// 02111 // GNU G++: Type Traits [Type-Traits.html in the GCC manual] 02112 ExprResult ParseUnaryTypeTrait(); 02113 ExprResult ParseBinaryTypeTrait(); 02114 ExprResult ParseTypeTrait(); 02115 02116 //===--------------------------------------------------------------------===// 02117 // Embarcadero: Arary and Expression Traits 02118 ExprResult ParseArrayTypeTrait(); 02119 ExprResult ParseExpressionTrait(); 02120 02121 //===--------------------------------------------------------------------===// 02122 // Preprocessor code-completion pass-through 02123 virtual void CodeCompleteDirective(bool InConditional); 02124 virtual void CodeCompleteInConditionalExclusion(); 02125 virtual void CodeCompleteMacroName(bool IsDefinition); 02126 virtual void CodeCompletePreprocessorExpression(); 02127 virtual void CodeCompleteMacroArgument(IdentifierInfo *Macro, 02128 MacroInfo *MacroInfo, 02129 unsigned ArgumentIndex); 02130 virtual void CodeCompleteNaturalLanguage(); 02131 }; 02132 02133 } // end namespace clang 02134 02135 #endif