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