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