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