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