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