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