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