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