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