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