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