1//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines the Parser interface. 11// 12//===----------------------------------------------------------------------===// 13 14#ifndef LLVM_CLANG_PARSE_PARSER_H 15#define LLVM_CLANG_PARSE_PARSER_H 16 17#include "clang/AST/Availability.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/LoopHint.h" 25#include "clang/Sema/Sema.h" 26#include "llvm/ADT/SmallVector.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 33namespace clang { 34 class PragmaHandler; 35 class Scope; 36 class BalancedDelimiterTracker; 37 class CorrectionCandidateCallback; 38 class DeclGroupRef; 39 class DiagnosticBuilder; 40 class Parser; 41 class ParsingDeclRAIIObject; 42 class ParsingDeclSpec; 43 class ParsingDeclarator; 44 class ParsingFieldDeclarator; 45 class ColonProtectionRAIIObject; 46 class InMessageExpressionRAIIObject; 47 class PoisonSEHIdentifiersRAIIObject; 48 class VersionTuple; 49 class OMPClause; 50 class ObjCTypeParamList; 51 class ObjCTypeParameter; 52 53/// Parser - This implements a parser for the C family of languages. After 54/// parsing units of the grammar, productions are invoked to handle whatever has 55/// been read. 56/// 57class Parser : public CodeCompletionHandler { 58 friend class ColonProtectionRAIIObject; 59 friend class InMessageExpressionRAIIObject; 60 friend class PoisonSEHIdentifiersRAIIObject; 61 friend class ObjCDeclContextSwitch; 62 friend class ParenBraceBracketBalancer; 63 friend class BalancedDelimiterTracker; 64 65 Preprocessor &PP; 66 67 /// Tok - The current token we are peeking ahead. All parsing methods assume 68 /// that this is valid. 69 Token Tok; 70 71 // PrevTokLocation - The location of the token we previously 72 // consumed. This token is used for diagnostics where we expected to 73 // see a token following another token (e.g., the ';' at the end of 74 // a statement). 75 SourceLocation PrevTokLocation; 76 77 unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0; 78 unsigned short MisplacedModuleBeginCount = 0; 79 80 /// Actions - These are the callbacks we invoke as we parse various constructs 81 /// in the file. 82 Sema &Actions; 83 84 DiagnosticsEngine &Diags; 85 86 /// ScopeCache - Cache scopes to reduce malloc traffic. 87 enum { ScopeCacheSize = 16 }; 88 unsigned NumCachedScopes; 89 Scope *ScopeCache[ScopeCacheSize]; 90 91 /// Identifiers used for SEH handling in Borland. These are only 92 /// allowed in particular circumstances 93 // __except block 94 IdentifierInfo *Ident__exception_code, 95 *Ident___exception_code, 96 *Ident_GetExceptionCode; 97 // __except filter expression 98 IdentifierInfo *Ident__exception_info, 99 *Ident___exception_info, 100 *Ident_GetExceptionInfo; 101 // __finally 102 IdentifierInfo *Ident__abnormal_termination, 103 *Ident___abnormal_termination, 104 *Ident_AbnormalTermination; 105 106 /// Contextual keywords for Microsoft extensions. 107 IdentifierInfo *Ident__except; 108 mutable IdentifierInfo *Ident_sealed; 109 110 /// Ident_super - IdentifierInfo for "super", to support fast 111 /// comparison. 112 IdentifierInfo *Ident_super; 113 /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and 114 /// "bool" fast comparison. Only present if AltiVec or ZVector are enabled. 115 IdentifierInfo *Ident_vector; 116 IdentifierInfo *Ident_bool; 117 /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison. 118 /// Only present if AltiVec enabled. 119 IdentifierInfo *Ident_pixel; 120 121 /// Objective-C contextual keywords. 122 mutable IdentifierInfo *Ident_instancetype; 123 124 /// \brief Identifier for "introduced". 125 IdentifierInfo *Ident_introduced; 126 127 /// \brief Identifier for "deprecated". 128 IdentifierInfo *Ident_deprecated; 129 130 /// \brief Identifier for "obsoleted". 131 IdentifierInfo *Ident_obsoleted; 132 133 /// \brief Identifier for "unavailable". 134 IdentifierInfo *Ident_unavailable; 135 136 /// \brief Identifier for "message". 137 IdentifierInfo *Ident_message; 138 139 /// \brief Identifier for "strict". 140 IdentifierInfo *Ident_strict; 141 142 /// \brief Identifier for "replacement". 143 IdentifierInfo *Ident_replacement; 144 145 /// Identifiers used by the 'external_source_symbol' attribute. 146 IdentifierInfo *Ident_language, *Ident_defined_in, 147 *Ident_generated_declaration; 148 149 /// C++0x contextual keywords. 150 mutable IdentifierInfo *Ident_final; 151 mutable IdentifierInfo *Ident_GNU_final; 152 mutable IdentifierInfo *Ident_override; 153 154 // C++ type trait keywords that can be reverted to identifiers and still be 155 // used as type traits. 156 llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits; 157 158 std::unique_ptr<PragmaHandler> AlignHandler; 159 std::unique_ptr<PragmaHandler> GCCVisibilityHandler; 160 std::unique_ptr<PragmaHandler> OptionsHandler; 161 std::unique_ptr<PragmaHandler> PackHandler; 162 std::unique_ptr<PragmaHandler> MSStructHandler; 163 std::unique_ptr<PragmaHandler> UnusedHandler; 164 std::unique_ptr<PragmaHandler> WeakHandler; 165 std::unique_ptr<PragmaHandler> RedefineExtnameHandler; 166 std::unique_ptr<PragmaHandler> FPContractHandler; 167 std::unique_ptr<PragmaHandler> OpenCLExtensionHandler; 168 std::unique_ptr<PragmaHandler> OpenMPHandler; 169 std::unique_ptr<PragmaHandler> PCSectionHandler; 170 std::unique_ptr<PragmaHandler> MSCommentHandler; 171 std::unique_ptr<PragmaHandler> MSDetectMismatchHandler; 172 std::unique_ptr<PragmaHandler> MSPointersToMembers; 173 std::unique_ptr<PragmaHandler> MSVtorDisp; 174 std::unique_ptr<PragmaHandler> MSInitSeg; 175 std::unique_ptr<PragmaHandler> MSDataSeg; 176 std::unique_ptr<PragmaHandler> MSBSSSeg; 177 std::unique_ptr<PragmaHandler> MSConstSeg; 178 std::unique_ptr<PragmaHandler> MSCodeSeg; 179 std::unique_ptr<PragmaHandler> MSSection; 180 std::unique_ptr<PragmaHandler> MSRuntimeChecks; 181 std::unique_ptr<PragmaHandler> MSIntrinsic; 182 std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler; 183 std::unique_ptr<PragmaHandler> OptimizeHandler; 184 std::unique_ptr<PragmaHandler> LoopHintHandler; 185 std::unique_ptr<PragmaHandler> UnrollHintHandler; 186 std::unique_ptr<PragmaHandler> NoUnrollHintHandler; 187 std::unique_ptr<PragmaHandler> FPHandler; 188 std::unique_ptr<PragmaHandler> AttributePragmaHandler; 189 190 std::unique_ptr<CommentHandler> CommentSemaHandler; 191 192 /// Whether the '>' token acts as an operator or not. This will be 193 /// true except when we are parsing an expression within a C++ 194 /// template argument list, where the '>' closes the template 195 /// argument list. 196 bool GreaterThanIsOperator; 197 198 /// ColonIsSacred - When this is false, we aggressively try to recover from 199 /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not 200 /// safe in case statements and a few other things. This is managed by the 201 /// ColonProtectionRAIIObject RAII object. 202 bool ColonIsSacred; 203 204 /// \brief When true, we are directly inside an Objective-C message 205 /// send expression. 206 /// 207 /// This is managed by the \c InMessageExpressionRAIIObject class, and 208 /// should not be set directly. 209 bool InMessageExpression; 210 211 /// The "depth" of the template parameters currently being parsed. 212 unsigned TemplateParameterDepth; 213 214 /// \brief RAII class that manages the template parameter depth. 215 class TemplateParameterDepthRAII { 216 unsigned &Depth; 217 unsigned AddedLevels; 218 public: 219 explicit TemplateParameterDepthRAII(unsigned &Depth) 220 : Depth(Depth), AddedLevels(0) {} 221 222 ~TemplateParameterDepthRAII() { 223 Depth -= AddedLevels; 224 } 225 226 void operator++() { 227 ++Depth; 228 ++AddedLevels; 229 } 230 void addDepth(unsigned D) { 231 Depth += D; 232 AddedLevels += D; 233 } 234 unsigned getDepth() const { return Depth; } 235 }; 236 237 /// Factory object for creating AttributeList objects. 238 AttributeFactory AttrFactory; 239 240 /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a 241 /// top-level declaration is finished. 242 SmallVector<TemplateIdAnnotation *, 16> TemplateIds; 243 244 /// \brief Identifiers which have been declared within a tentative parse. 245 SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers; 246 247 IdentifierInfo *getSEHExceptKeyword(); 248 249 /// True if we are within an Objective-C container while parsing C-like decls. 250 /// 251 /// This is necessary because Sema thinks we have left the container 252 /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will 253 /// be NULL. 254 bool ParsingInObjCContainer; 255 256 /// Whether to skip parsing of function bodies. 257 /// 258 /// This option can be used, for example, to speed up searches for 259 /// declarations/definitions when indexing. 260 bool SkipFunctionBodies; 261 262 /// The location of the expression statement that is being parsed right now. 263 /// Used to determine if an expression that is being parsed is a statement or 264 /// just a regular sub-expression. 265 SourceLocation ExprStatementTokLoc; 266 267public: 268 Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies); 269 ~Parser() override; 270 271 const LangOptions &getLangOpts() const { return PP.getLangOpts(); } 272 const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } 273 Preprocessor &getPreprocessor() const { return PP; } 274 Sema &getActions() const { return Actions; } 275 AttributeFactory &getAttrFactory() { return AttrFactory; } 276 277 const Token &getCurToken() const { return Tok; } 278 Scope *getCurScope() const { return Actions.getCurScope(); } 279 void incrementMSManglingNumber() const { 280 return Actions.incrementMSManglingNumber(); 281 } 282 283 Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); } 284 285 // Type forwarding. All of these are statically 'void*', but they may all be 286 // different actual classes based on the actions in place. 287 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; 288 typedef OpaquePtr<TemplateName> TemplateTy; 289 290 typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists; 291 292 typedef Sema::FullExprArg FullExprArg; 293 294 // Parsing methods. 295 296 /// Initialize - Warm up the parser. 297 /// 298 void Initialize(); 299 300 /// Parse the first top-level declaration in a translation unit. 301 bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result); 302 303 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if 304 /// the EOF was encountered. 305 bool ParseTopLevelDecl(DeclGroupPtrTy &Result); 306 bool ParseTopLevelDecl() { 307 DeclGroupPtrTy Result; 308 return ParseTopLevelDecl(Result); 309 } 310 311 /// ConsumeToken - Consume the current 'peek token' and lex the next one. 312 /// This does not work with special tokens: string literals, code completion, 313 /// annotation tokens and balanced tokens must be handled using the specific 314 /// consume methods. 315 /// Returns the location of the consumed token. 316 SourceLocation ConsumeToken() { 317 assert(!isTokenSpecial() && 318 "Should consume special tokens with Consume*Token"); 319 PrevTokLocation = Tok.getLocation(); 320 PP.Lex(Tok); 321 return PrevTokLocation; 322 } 323 324 bool TryConsumeToken(tok::TokenKind Expected) { 325 if (Tok.isNot(Expected)) 326 return false; 327 assert(!isTokenSpecial() && 328 "Should consume special tokens with Consume*Token"); 329 PrevTokLocation = Tok.getLocation(); 330 PP.Lex(Tok); 331 return true; 332 } 333 334 bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) { 335 if (!TryConsumeToken(Expected)) 336 return false; 337 Loc = PrevTokLocation; 338 return true; 339 } 340 341 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the 342 /// current token type. This should only be used in cases where the type of 343 /// the token really isn't known, e.g. in error recovery. 344 SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) { 345 if (isTokenParen()) 346 return ConsumeParen(); 347 if (isTokenBracket()) 348 return ConsumeBracket(); 349 if (isTokenBrace()) 350 return ConsumeBrace(); 351 if (isTokenStringLiteral()) 352 return ConsumeStringToken(); 353 if (Tok.is(tok::code_completion)) 354 return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken() 355 : handleUnexpectedCodeCompletionToken(); 356 if (Tok.isAnnotation()) 357 return ConsumeAnnotationToken(); 358 return ConsumeToken(); 359 } 360 361 362 SourceLocation getEndOfPreviousToken() { 363 return PP.getLocForEndOfToken(PrevTokLocation); 364 } 365 366 /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds 367 /// to the given nullability kind. 368 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) { 369 return Actions.getNullabilityKeyword(nullability); 370 } 371 372private: 373 //===--------------------------------------------------------------------===// 374 // Low-Level token peeking and consumption methods. 375 // 376 377 /// isTokenParen - Return true if the cur token is '(' or ')'. 378 bool isTokenParen() const { 379 return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren; 380 } 381 /// isTokenBracket - Return true if the cur token is '[' or ']'. 382 bool isTokenBracket() const { 383 return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square; 384 } 385 /// isTokenBrace - Return true if the cur token is '{' or '}'. 386 bool isTokenBrace() const { 387 return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace; 388 } 389 /// isTokenStringLiteral - True if this token is a string-literal. 390 bool isTokenStringLiteral() const { 391 return tok::isStringLiteral(Tok.getKind()); 392 } 393 /// isTokenSpecial - True if this token requires special consumption methods. 394 bool isTokenSpecial() const { 395 return isTokenStringLiteral() || isTokenParen() || isTokenBracket() || 396 isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation(); 397 } 398 399 /// \brief Returns true if the current token is '=' or is a type of '='. 400 /// For typos, give a fixit to '=' 401 bool isTokenEqualOrEqualTypo(); 402 403 /// \brief Return the current token to the token stream and make the given 404 /// token the current token. 405 void UnconsumeToken(Token &Consumed) { 406 Token Next = Tok; 407 PP.EnterToken(Consumed); 408 PP.Lex(Tok); 409 PP.EnterToken(Next); 410 } 411 412 SourceLocation ConsumeAnnotationToken() { 413 assert(Tok.isAnnotation() && "wrong consume method"); 414 SourceLocation Loc = Tok.getLocation(); 415 PrevTokLocation = Tok.getAnnotationEndLoc(); 416 PP.Lex(Tok); 417 return Loc; 418 } 419 420 /// ConsumeParen - This consume method keeps the paren count up-to-date. 421 /// 422 SourceLocation ConsumeParen() { 423 assert(isTokenParen() && "wrong consume method"); 424 if (Tok.getKind() == tok::l_paren) 425 ++ParenCount; 426 else if (ParenCount) 427 --ParenCount; // Don't let unbalanced )'s drive the count negative. 428 PrevTokLocation = Tok.getLocation(); 429 PP.Lex(Tok); 430 return PrevTokLocation; 431 } 432 433 /// ConsumeBracket - This consume method keeps the bracket count up-to-date. 434 /// 435 SourceLocation ConsumeBracket() { 436 assert(isTokenBracket() && "wrong consume method"); 437 if (Tok.getKind() == tok::l_square) 438 ++BracketCount; 439 else if (BracketCount) 440 --BracketCount; // Don't let unbalanced ]'s drive the count negative. 441 442 PrevTokLocation = Tok.getLocation(); 443 PP.Lex(Tok); 444 return PrevTokLocation; 445 } 446 447 /// ConsumeBrace - This consume method keeps the brace count up-to-date. 448 /// 449 SourceLocation ConsumeBrace() { 450 assert(isTokenBrace() && "wrong consume method"); 451 if (Tok.getKind() == tok::l_brace) 452 ++BraceCount; 453 else if (BraceCount) 454 --BraceCount; // Don't let unbalanced }'s drive the count negative. 455 456 PrevTokLocation = Tok.getLocation(); 457 PP.Lex(Tok); 458 return PrevTokLocation; 459 } 460 461 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one 462 /// and returning the token kind. This method is specific to strings, as it 463 /// handles string literal concatenation, as per C99 5.1.1.2, translation 464 /// phase #6. 465 SourceLocation ConsumeStringToken() { 466 assert(isTokenStringLiteral() && 467 "Should only consume string literals with this method"); 468 PrevTokLocation = Tok.getLocation(); 469 PP.Lex(Tok); 470 return PrevTokLocation; 471 } 472 473 /// \brief Consume the current code-completion token. 474 /// 475 /// This routine can be called to consume the code-completion token and 476 /// continue processing in special cases where \c cutOffParsing() isn't 477 /// desired, such as token caching or completion with lookahead. 478 SourceLocation ConsumeCodeCompletionToken() { 479 assert(Tok.is(tok::code_completion)); 480 PrevTokLocation = Tok.getLocation(); 481 PP.Lex(Tok); 482 return PrevTokLocation; 483 } 484 485 ///\ brief When we are consuming a code-completion token without having 486 /// matched specific position in the grammar, provide code-completion results 487 /// based on context. 488 /// 489 /// \returns the source location of the code-completion token. 490 SourceLocation handleUnexpectedCodeCompletionToken(); 491 492 /// \brief Abruptly cut off parsing; mainly used when we have reached the 493 /// code-completion point. 494 void cutOffParsing() { 495 if (PP.isCodeCompletionEnabled()) 496 PP.setCodeCompletionReached(); 497 // Cut off parsing by acting as if we reached the end-of-file. 498 Tok.setKind(tok::eof); 499 } 500 501 /// \brief Determine if we're at the end of the file or at a transition 502 /// between modules. 503 bool isEofOrEom() { 504 tok::TokenKind Kind = Tok.getKind(); 505 return Kind == tok::eof || Kind == tok::annot_module_begin || 506 Kind == tok::annot_module_end || Kind == tok::annot_module_include; 507 } 508 509 /// \brief Initialize all pragma handlers. 510 void initializePragmaHandlers(); 511 512 /// \brief Destroy and reset all pragma handlers. 513 void resetPragmaHandlers(); 514 515 /// \brief Handle the annotation token produced for #pragma unused(...) 516 void HandlePragmaUnused(); 517 518 /// \brief Handle the annotation token produced for 519 /// #pragma GCC visibility... 520 void HandlePragmaVisibility(); 521 522 /// \brief Handle the annotation token produced for 523 /// #pragma pack... 524 void HandlePragmaPack(); 525 526 /// \brief Handle the annotation token produced for 527 /// #pragma ms_struct... 528 void HandlePragmaMSStruct(); 529 530 /// \brief Handle the annotation token produced for 531 /// #pragma comment... 532 void HandlePragmaMSComment(); 533 534 void HandlePragmaMSPointersToMembers(); 535 536 void HandlePragmaMSVtorDisp(); 537 538 void HandlePragmaMSPragma(); 539 bool HandlePragmaMSSection(StringRef PragmaName, 540 SourceLocation PragmaLocation); 541 bool HandlePragmaMSSegment(StringRef PragmaName, 542 SourceLocation PragmaLocation); 543 bool HandlePragmaMSInitSeg(StringRef PragmaName, 544 SourceLocation PragmaLocation); 545 546 /// \brief Handle the annotation token produced for 547 /// #pragma align... 548 void HandlePragmaAlign(); 549 550 /// \brief Handle the annotation token produced for 551 /// #pragma clang __debug dump... 552 void HandlePragmaDump(); 553 554 /// \brief Handle the annotation token produced for 555 /// #pragma weak id... 556 void HandlePragmaWeak(); 557 558 /// \brief Handle the annotation token produced for 559 /// #pragma weak id = id... 560 void HandlePragmaWeakAlias(); 561 562 /// \brief Handle the annotation token produced for 563 /// #pragma redefine_extname... 564 void HandlePragmaRedefineExtname(); 565 566 /// \brief Handle the annotation token produced for 567 /// #pragma STDC FP_CONTRACT... 568 void HandlePragmaFPContract(); 569 570 /// \brief Handle the annotation token produced for 571 /// #pragma clang fp ... 572 void HandlePragmaFP(); 573 574 /// \brief Handle the annotation token produced for 575 /// #pragma OPENCL EXTENSION... 576 void HandlePragmaOpenCLExtension(); 577 578 /// \brief Handle the annotation token produced for 579 /// #pragma clang __debug captured 580 StmtResult HandlePragmaCaptured(); 581 582 /// \brief Handle the annotation token produced for 583 /// #pragma clang loop and #pragma unroll. 584 bool HandlePragmaLoopHint(LoopHint &Hint); 585 586 bool ParsePragmaAttributeSubjectMatchRuleSet( 587 attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, 588 SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc); 589 590 void HandlePragmaAttribute(); 591 592 /// GetLookAheadToken - This peeks ahead N tokens and returns that token 593 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) 594 /// returns the token after Tok, etc. 595 /// 596 /// Note that this differs from the Preprocessor's LookAhead method, because 597 /// the Parser always has one token lexed that the preprocessor doesn't. 598 /// 599 const Token &GetLookAheadToken(unsigned N) { 600 if (N == 0 || Tok.is(tok::eof)) return Tok; 601 return PP.LookAhead(N-1); 602 } 603 604public: 605 /// NextToken - This peeks ahead one token and returns it without 606 /// consuming it. 607 const Token &NextToken() { 608 return PP.LookAhead(0); 609 } 610 611 /// getTypeAnnotation - Read a parsed type out of an annotation token. 612 static ParsedType getTypeAnnotation(const Token &Tok) { 613 return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue()); 614 } 615 616private: 617 static void setTypeAnnotation(Token &Tok, ParsedType T) { 618 Tok.setAnnotationValue(T.getAsOpaquePtr()); 619 } 620 621 /// \brief Read an already-translated primary expression out of an annotation 622 /// token. 623 static ExprResult getExprAnnotation(const Token &Tok) { 624 return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue()); 625 } 626 627 /// \brief Set the primary expression corresponding to the given annotation 628 /// token. 629 static void setExprAnnotation(Token &Tok, ExprResult ER) { 630 Tok.setAnnotationValue(ER.getAsOpaquePointer()); 631 } 632 633public: 634 // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to 635 // find a type name by attempting typo correction. 636 bool TryAnnotateTypeOrScopeToken(); 637 bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, 638 bool IsNewScope); 639 bool TryAnnotateCXXScopeToken(bool EnteringContext = false); 640 641private: 642 enum AnnotatedNameKind { 643 /// Annotation has failed and emitted an error. 644 ANK_Error, 645 /// The identifier is a tentatively-declared name. 646 ANK_TentativeDecl, 647 /// The identifier is a template name. FIXME: Add an annotation for that. 648 ANK_TemplateName, 649 /// The identifier can't be resolved. 650 ANK_Unresolved, 651 /// Annotation was successful. 652 ANK_Success 653 }; 654 AnnotatedNameKind 655 TryAnnotateName(bool IsAddressOfOperand, 656 std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr); 657 658 /// Push a tok::annot_cxxscope token onto the token stream. 659 void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation); 660 661 /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens, 662 /// replacing them with the non-context-sensitive keywords. This returns 663 /// true if the token was replaced. 664 bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, 665 const char *&PrevSpec, unsigned &DiagID, 666 bool &isInvalid) { 667 if (!getLangOpts().AltiVec && !getLangOpts().ZVector) 668 return false; 669 670 if (Tok.getIdentifierInfo() != Ident_vector && 671 Tok.getIdentifierInfo() != Ident_bool && 672 (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel)) 673 return false; 674 675 return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid); 676 } 677 678 /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector 679 /// identifier token, replacing it with the non-context-sensitive __vector. 680 /// This returns true if the token was replaced. 681 bool TryAltiVecVectorToken() { 682 if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) || 683 Tok.getIdentifierInfo() != Ident_vector) return false; 684 return TryAltiVecVectorTokenOutOfLine(); 685 } 686 687 bool TryAltiVecVectorTokenOutOfLine(); 688 bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, 689 const char *&PrevSpec, unsigned &DiagID, 690 bool &isInvalid); 691 692 /// Returns true if the current token is the identifier 'instancetype'. 693 /// 694 /// Should only be used in Objective-C language modes. 695 bool isObjCInstancetype() { 696 assert(getLangOpts().ObjC1); 697 if (Tok.isAnnotation()) 698 return false; 699 if (!Ident_instancetype) 700 Ident_instancetype = PP.getIdentifierInfo("instancetype"); 701 return Tok.getIdentifierInfo() == Ident_instancetype; 702 } 703 704 /// TryKeywordIdentFallback - For compatibility with system headers using 705 /// keywords as identifiers, attempt to convert the current token to an 706 /// identifier and optionally disable the keyword for the remainder of the 707 /// translation unit. This returns false if the token was not replaced, 708 /// otherwise emits a diagnostic and returns true. 709 bool TryKeywordIdentFallback(bool DisableKeyword); 710 711 /// \brief Get the TemplateIdAnnotation from the token. 712 TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok); 713 714 /// TentativeParsingAction - An object that is used as a kind of "tentative 715 /// parsing transaction". It gets instantiated to mark the token position and 716 /// after the token consumption is done, Commit() or Revert() is called to 717 /// either "commit the consumed tokens" or revert to the previously marked 718 /// token position. Example: 719 /// 720 /// TentativeParsingAction TPA(*this); 721 /// ConsumeToken(); 722 /// .... 723 /// TPA.Revert(); 724 /// 725 class TentativeParsingAction { 726 Parser &P; 727 Token PrevTok; 728 size_t PrevTentativelyDeclaredIdentifierCount; 729 unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount; 730 bool isActive; 731 732 public: 733 explicit TentativeParsingAction(Parser& p) : P(p) { 734 PrevTok = P.Tok; 735 PrevTentativelyDeclaredIdentifierCount = 736 P.TentativelyDeclaredIdentifiers.size(); 737 PrevParenCount = P.ParenCount; 738 PrevBracketCount = P.BracketCount; 739 PrevBraceCount = P.BraceCount; 740 P.PP.EnableBacktrackAtThisPos(); 741 isActive = true; 742 } 743 void Commit() { 744 assert(isActive && "Parsing action was finished!"); 745 P.TentativelyDeclaredIdentifiers.resize( 746 PrevTentativelyDeclaredIdentifierCount); 747 P.PP.CommitBacktrackedTokens(); 748 isActive = false; 749 } 750 void Revert() { 751 assert(isActive && "Parsing action was finished!"); 752 P.PP.Backtrack(); 753 P.Tok = PrevTok; 754 P.TentativelyDeclaredIdentifiers.resize( 755 PrevTentativelyDeclaredIdentifierCount); 756 P.ParenCount = PrevParenCount; 757 P.BracketCount = PrevBracketCount; 758 P.BraceCount = PrevBraceCount; 759 isActive = false; 760 } 761 ~TentativeParsingAction() { 762 assert(!isActive && "Forgot to call Commit or Revert!"); 763 } 764 }; 765 /// A TentativeParsingAction that automatically reverts in its destructor. 766 /// Useful for disambiguation parses that will always be reverted. 767 class RevertingTentativeParsingAction 768 : private Parser::TentativeParsingAction { 769 public: 770 RevertingTentativeParsingAction(Parser &P) 771 : Parser::TentativeParsingAction(P) {} 772 ~RevertingTentativeParsingAction() { Revert(); } 773 }; 774 775 class UnannotatedTentativeParsingAction; 776 777 /// ObjCDeclContextSwitch - An object used to switch context from 778 /// an objective-c decl context to its enclosing decl context and 779 /// back. 780 class ObjCDeclContextSwitch { 781 Parser &P; 782 Decl *DC; 783 SaveAndRestore<bool> WithinObjCContainer; 784 public: 785 explicit ObjCDeclContextSwitch(Parser &p) 786 : P(p), DC(p.getObjCDeclContext()), 787 WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) { 788 if (DC) 789 P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC)); 790 } 791 ~ObjCDeclContextSwitch() { 792 if (DC) 793 P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC)); 794 } 795 }; 796 797 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the 798 /// input. If so, it is consumed and false is returned. 799 /// 800 /// If a trivial punctuator misspelling is encountered, a FixIt error 801 /// diagnostic is issued and false is returned after recovery. 802 /// 803 /// If the input is malformed, this emits the specified diagnostic and true is 804 /// returned. 805 bool ExpectAndConsume(tok::TokenKind ExpectedTok, 806 unsigned Diag = diag::err_expected, 807 StringRef DiagMsg = ""); 808 809 /// \brief The parser expects a semicolon and, if present, will consume it. 810 /// 811 /// If the next token is not a semicolon, this emits the specified diagnostic, 812 /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior 813 /// to the semicolon, consumes that extra token. 814 bool ExpectAndConsumeSemi(unsigned DiagID); 815 816 /// \brief The kind of extra semi diagnostic to emit. 817 enum ExtraSemiKind { 818 OutsideFunction = 0, 819 InsideStruct = 1, 820 InstanceVariableList = 2, 821 AfterMemberFunctionDefinition = 3 822 }; 823 824 /// \brief Consume any extra semi-colons until the end of the line. 825 void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified); 826 827 /// Return false if the next token is an identifier. An 'expected identifier' 828 /// error is emitted otherwise. 829 /// 830 /// The parser tries to recover from the error by checking if the next token 831 /// is a C++ keyword when parsing Objective-C++. Return false if the recovery 832 /// was successful. 833 bool expectIdentifier(); 834 835public: 836 //===--------------------------------------------------------------------===// 837 // Scope manipulation 838 839 /// ParseScope - Introduces a new scope for parsing. The kind of 840 /// scope is determined by ScopeFlags. Objects of this type should 841 /// be created on the stack to coincide with the position where the 842 /// parser enters the new scope, and this object's constructor will 843 /// create that new scope. Similarly, once the object is destroyed 844 /// the parser will exit the scope. 845 class ParseScope { 846 Parser *Self; 847 ParseScope(const ParseScope &) = delete; 848 void operator=(const ParseScope &) = delete; 849 850 public: 851 // ParseScope - Construct a new object to manage a scope in the 852 // parser Self where the new Scope is created with the flags 853 // ScopeFlags, but only when we aren't about to enter a compound statement. 854 ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true, 855 bool BeforeCompoundStmt = false) 856 : Self(Self) { 857 if (EnteredScope && !BeforeCompoundStmt) 858 Self->EnterScope(ScopeFlags); 859 else { 860 if (BeforeCompoundStmt) 861 Self->incrementMSManglingNumber(); 862 863 this->Self = nullptr; 864 } 865 } 866 867 // Exit - Exit the scope associated with this object now, rather 868 // than waiting until the object is destroyed. 869 void Exit() { 870 if (Self) { 871 Self->ExitScope(); 872 Self = nullptr; 873 } 874 } 875 876 ~ParseScope() { 877 Exit(); 878 } 879 }; 880 881 /// EnterScope - Start a new scope. 882 void EnterScope(unsigned ScopeFlags); 883 884 /// ExitScope - Pop a scope off the scope stack. 885 void ExitScope(); 886 887private: 888 /// \brief RAII object used to modify the scope flags for the current scope. 889 class ParseScopeFlags { 890 Scope *CurScope; 891 unsigned OldFlags; 892 ParseScopeFlags(const ParseScopeFlags &) = delete; 893 void operator=(const ParseScopeFlags &) = delete; 894 895 public: 896 ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true); 897 ~ParseScopeFlags(); 898 }; 899 900 //===--------------------------------------------------------------------===// 901 // Diagnostic Emission and Error recovery. 902 903public: 904 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); 905 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); 906 DiagnosticBuilder Diag(unsigned DiagID) { 907 return Diag(Tok, DiagID); 908 } 909 910private: 911 void SuggestParentheses(SourceLocation Loc, unsigned DK, 912 SourceRange ParenRange); 913 void CheckNestedObjCContexts(SourceLocation AtLoc); 914 915public: 916 917 /// \brief Control flags for SkipUntil functions. 918 enum SkipUntilFlags { 919 StopAtSemi = 1 << 0, ///< Stop skipping at semicolon 920 /// \brief Stop skipping at specified token, but don't skip the token itself 921 StopBeforeMatch = 1 << 1, 922 StopAtCodeCompletion = 1 << 2 ///< Stop at code completion 923 }; 924 925 friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, 926 SkipUntilFlags R) { 927 return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) | 928 static_cast<unsigned>(R)); 929 } 930 931 /// SkipUntil - Read tokens until we get to the specified token, then consume 932 /// it (unless StopBeforeMatch is specified). Because we cannot guarantee 933 /// that the token will ever occur, this skips to the next token, or to some 934 /// likely good stopping point. If Flags has StopAtSemi flag, skipping will 935 /// stop at a ';' character. 936 /// 937 /// If SkipUntil finds the specified token, it returns true, otherwise it 938 /// returns false. 939 bool SkipUntil(tok::TokenKind T, 940 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { 941 return SkipUntil(llvm::makeArrayRef(T), Flags); 942 } 943 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, 944 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { 945 tok::TokenKind TokArray[] = {T1, T2}; 946 return SkipUntil(TokArray, Flags); 947 } 948 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, 949 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { 950 tok::TokenKind TokArray[] = {T1, T2, T3}; 951 return SkipUntil(TokArray, Flags); 952 } 953 bool SkipUntil(ArrayRef<tok::TokenKind> Toks, 954 SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)); 955 956 /// SkipMalformedDecl - Read tokens until we get to some likely good stopping 957 /// point for skipping past a simple-declaration. 958 void SkipMalformedDecl(); 959 960private: 961 //===--------------------------------------------------------------------===// 962 // Lexing and parsing of C++ inline methods. 963 964 struct ParsingClass; 965 966 /// [class.mem]p1: "... the class is regarded as complete within 967 /// - function bodies 968 /// - default arguments 969 /// - exception-specifications (TODO: C++0x) 970 /// - and brace-or-equal-initializers for non-static data members 971 /// (including such things in nested classes)." 972 /// LateParsedDeclarations build the tree of those elements so they can 973 /// be parsed after parsing the top-level class. 974 class LateParsedDeclaration { 975 public: 976 virtual ~LateParsedDeclaration(); 977 978 virtual void ParseLexedMethodDeclarations(); 979 virtual void ParseLexedMemberInitializers(); 980 virtual void ParseLexedMethodDefs(); 981 virtual void ParseLexedAttributes(); 982 }; 983 984 /// Inner node of the LateParsedDeclaration tree that parses 985 /// all its members recursively. 986 class LateParsedClass : public LateParsedDeclaration { 987 public: 988 LateParsedClass(Parser *P, ParsingClass *C); 989 ~LateParsedClass() override; 990 991 void ParseLexedMethodDeclarations() override; 992 void ParseLexedMemberInitializers() override; 993 void ParseLexedMethodDefs() override; 994 void ParseLexedAttributes() override; 995 996 private: 997 Parser *Self; 998 ParsingClass *Class; 999 }; 1000 1001 /// Contains the lexed tokens of an attribute with arguments that 1002 /// may reference member variables and so need to be parsed at the 1003 /// end of the class declaration after parsing all other member 1004 /// member declarations. 1005 /// FIXME: Perhaps we should change the name of LateParsedDeclaration to 1006 /// LateParsedTokens. 1007 struct LateParsedAttribute : public LateParsedDeclaration { 1008 Parser *Self; 1009 CachedTokens Toks; 1010 IdentifierInfo &AttrName; 1011 SourceLocation AttrNameLoc; 1012 SmallVector<Decl*, 2> Decls; 1013 1014 explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name, 1015 SourceLocation Loc) 1016 : Self(P), AttrName(Name), AttrNameLoc(Loc) {} 1017 1018 void ParseLexedAttributes() override; 1019 1020 void addDecl(Decl *D) { Decls.push_back(D); } 1021 }; 1022 1023 // A list of late-parsed attributes. Used by ParseGNUAttributes. 1024 class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> { 1025 public: 1026 LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { } 1027 1028 bool parseSoon() { return ParseSoon; } 1029 1030 private: 1031 bool ParseSoon; // Are we planning to parse these shortly after creation? 1032 }; 1033 1034 /// Contains the lexed tokens of a member function definition 1035 /// which needs to be parsed at the end of the class declaration 1036 /// after parsing all other member declarations. 1037 struct LexedMethod : public LateParsedDeclaration { 1038 Parser *Self; 1039 Decl *D; 1040 CachedTokens Toks; 1041 1042 /// \brief Whether this member function had an associated template 1043 /// scope. When true, D is a template declaration. 1044 /// otherwise, it is a member function declaration. 1045 bool TemplateScope; 1046 1047 explicit LexedMethod(Parser* P, Decl *MD) 1048 : Self(P), D(MD), TemplateScope(false) {} 1049 1050 void ParseLexedMethodDefs() override; 1051 }; 1052 1053 /// LateParsedDefaultArgument - Keeps track of a parameter that may 1054 /// have a default argument that cannot be parsed yet because it 1055 /// occurs within a member function declaration inside the class 1056 /// (C++ [class.mem]p2). 1057 struct LateParsedDefaultArgument { 1058 explicit LateParsedDefaultArgument(Decl *P, 1059 std::unique_ptr<CachedTokens> Toks = nullptr) 1060 : Param(P), Toks(std::move(Toks)) { } 1061 1062 /// Param - The parameter declaration for this parameter. 1063 Decl *Param; 1064 1065 /// Toks - The sequence of tokens that comprises the default 1066 /// argument expression, not including the '=' or the terminating 1067 /// ')' or ','. This will be NULL for parameters that have no 1068 /// default argument. 1069 std::unique_ptr<CachedTokens> Toks; 1070 }; 1071 1072 /// LateParsedMethodDeclaration - A method declaration inside a class that 1073 /// contains at least one entity whose parsing needs to be delayed 1074 /// until the class itself is completely-defined, such as a default 1075 /// argument (C++ [class.mem]p2). 1076 struct LateParsedMethodDeclaration : public LateParsedDeclaration { 1077 explicit LateParsedMethodDeclaration(Parser *P, Decl *M) 1078 : Self(P), Method(M), TemplateScope(false), 1079 ExceptionSpecTokens(nullptr) {} 1080 1081 void ParseLexedMethodDeclarations() override; 1082 1083 Parser* Self; 1084 1085 /// Method - The method declaration. 1086 Decl *Method; 1087 1088 /// \brief Whether this member function had an associated template 1089 /// scope. When true, D is a template declaration. 1090 /// othewise, it is a member function declaration. 1091 bool TemplateScope; 1092 1093 /// DefaultArgs - Contains the parameters of the function and 1094 /// their default arguments. At least one of the parameters will 1095 /// have a default argument, but all of the parameters of the 1096 /// method will be stored so that they can be reintroduced into 1097 /// scope at the appropriate times. 1098 SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; 1099 1100 /// \brief The set of tokens that make up an exception-specification that 1101 /// has not yet been parsed. 1102 CachedTokens *ExceptionSpecTokens; 1103 }; 1104 1105 /// LateParsedMemberInitializer - An initializer for a non-static class data 1106 /// member whose parsing must to be delayed until the class is completely 1107 /// defined (C++11 [class.mem]p2). 1108 struct LateParsedMemberInitializer : public LateParsedDeclaration { 1109 LateParsedMemberInitializer(Parser *P, Decl *FD) 1110 : Self(P), Field(FD) { } 1111 1112 void ParseLexedMemberInitializers() override; 1113 1114 Parser *Self; 1115 1116 /// Field - The field declaration. 1117 Decl *Field; 1118 1119 /// CachedTokens - The sequence of tokens that comprises the initializer, 1120 /// including any leading '='. 1121 CachedTokens Toks; 1122 }; 1123 1124 /// LateParsedDeclarationsContainer - During parsing of a top (non-nested) 1125 /// C++ class, its method declarations that contain parts that won't be 1126 /// parsed until after the definition is completed (C++ [class.mem]p2), 1127 /// the method declarations and possibly attached inline definitions 1128 /// will be stored here with the tokens that will be parsed to create those 1129 /// entities. 1130 typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer; 1131 1132 /// \brief Representation of a class that has been parsed, including 1133 /// any member function declarations or definitions that need to be 1134 /// parsed after the corresponding top-level class is complete. 1135 struct ParsingClass { 1136 ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) 1137 : TopLevelClass(TopLevelClass), TemplateScope(false), 1138 IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { } 1139 1140 /// \brief Whether this is a "top-level" class, meaning that it is 1141 /// not nested within another class. 1142 bool TopLevelClass : 1; 1143 1144 /// \brief Whether this class had an associated template 1145 /// scope. When true, TagOrTemplate is a template declaration; 1146 /// othewise, it is a tag declaration. 1147 bool TemplateScope : 1; 1148 1149 /// \brief Whether this class is an __interface. 1150 bool IsInterface : 1; 1151 1152 /// \brief The class or class template whose definition we are parsing. 1153 Decl *TagOrTemplate; 1154 1155 /// LateParsedDeclarations - Method declarations, inline definitions and 1156 /// nested classes that contain pieces whose parsing will be delayed until 1157 /// the top-level class is fully defined. 1158 LateParsedDeclarationsContainer LateParsedDeclarations; 1159 }; 1160 1161 /// \brief The stack of classes that is currently being 1162 /// parsed. Nested and local classes will be pushed onto this stack 1163 /// when they are parsed, and removed afterward. 1164 std::stack<ParsingClass *> ClassStack; 1165 1166 ParsingClass &getCurrentClass() { 1167 assert(!ClassStack.empty() && "No lexed method stacks!"); 1168 return *ClassStack.top(); 1169 } 1170 1171 /// \brief RAII object used to manage the parsing of a class definition. 1172 class ParsingClassDefinition { 1173 Parser &P; 1174 bool Popped; 1175 Sema::ParsingClassState State; 1176 1177 public: 1178 ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass, 1179 bool IsInterface) 1180 : P(P), Popped(false), 1181 State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) { 1182 } 1183 1184 /// \brief Pop this class of the stack. 1185 void Pop() { 1186 assert(!Popped && "Nested class has already been popped"); 1187 Popped = true; 1188 P.PopParsingClass(State); 1189 } 1190 1191 ~ParsingClassDefinition() { 1192 if (!Popped) 1193 P.PopParsingClass(State); 1194 } 1195 }; 1196 1197 /// \brief Contains information about any template-specific 1198 /// information that has been parsed prior to parsing declaration 1199 /// specifiers. 1200 struct ParsedTemplateInfo { 1201 ParsedTemplateInfo() 1202 : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { } 1203 1204 ParsedTemplateInfo(TemplateParameterLists *TemplateParams, 1205 bool isSpecialization, 1206 bool lastParameterListWasEmpty = false) 1207 : Kind(isSpecialization? ExplicitSpecialization : Template), 1208 TemplateParams(TemplateParams), 1209 LastParameterListWasEmpty(lastParameterListWasEmpty) { } 1210 1211 explicit ParsedTemplateInfo(SourceLocation ExternLoc, 1212 SourceLocation TemplateLoc) 1213 : Kind(ExplicitInstantiation), TemplateParams(nullptr), 1214 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc), 1215 LastParameterListWasEmpty(false){ } 1216 1217 /// \brief The kind of template we are parsing. 1218 enum { 1219 /// \brief We are not parsing a template at all. 1220 NonTemplate = 0, 1221 /// \brief We are parsing a template declaration. 1222 Template, 1223 /// \brief We are parsing an explicit specialization. 1224 ExplicitSpecialization, 1225 /// \brief We are parsing an explicit instantiation. 1226 ExplicitInstantiation 1227 } Kind; 1228 1229 /// \brief The template parameter lists, for template declarations 1230 /// and explicit specializations. 1231 TemplateParameterLists *TemplateParams; 1232 1233 /// \brief The location of the 'extern' keyword, if any, for an explicit 1234 /// instantiation 1235 SourceLocation ExternLoc; 1236 1237 /// \brief The location of the 'template' keyword, for an explicit 1238 /// instantiation. 1239 SourceLocation TemplateLoc; 1240 1241 /// \brief Whether the last template parameter list was empty. 1242 bool LastParameterListWasEmpty; 1243 1244 SourceRange getSourceRange() const LLVM_READONLY; 1245 }; 1246 1247 void LexTemplateFunctionForLateParsing(CachedTokens &Toks); 1248 void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT); 1249 1250 static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT); 1251 static void LateTemplateParserCleanupCallback(void *P); 1252 1253 Sema::ParsingClassState 1254 PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface); 1255 void DeallocateParsedClasses(ParsingClass *Class); 1256 void PopParsingClass(Sema::ParsingClassState); 1257 1258 enum CachedInitKind { 1259 CIK_DefaultArgument, 1260 CIK_DefaultInitializer 1261 }; 1262 1263 NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS, 1264 AttributeList *AccessAttrs, 1265 ParsingDeclarator &D, 1266 const ParsedTemplateInfo &TemplateInfo, 1267 const VirtSpecifiers& VS, 1268 SourceLocation PureSpecLoc); 1269 void ParseCXXNonStaticMemberInitializer(Decl *VarD); 1270 void ParseLexedAttributes(ParsingClass &Class); 1271 void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, 1272 bool EnterScope, bool OnDefinition); 1273 void ParseLexedAttribute(LateParsedAttribute &LA, 1274 bool EnterScope, bool OnDefinition); 1275 void ParseLexedMethodDeclarations(ParsingClass &Class); 1276 void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM); 1277 void ParseLexedMethodDefs(ParsingClass &Class); 1278 void ParseLexedMethodDef(LexedMethod &LM); 1279 void ParseLexedMemberInitializers(ParsingClass &Class); 1280 void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI); 1281 void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod); 1282 bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks); 1283 bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK); 1284 bool ConsumeAndStoreConditional(CachedTokens &Toks); 1285 bool ConsumeAndStoreUntil(tok::TokenKind T1, 1286 CachedTokens &Toks, 1287 bool StopAtSemi = true, 1288 bool ConsumeFinalToken = true) { 1289 return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken); 1290 } 1291 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, 1292 CachedTokens &Toks, 1293 bool StopAtSemi = true, 1294 bool ConsumeFinalToken = true); 1295 1296 //===--------------------------------------------------------------------===// 1297 // C99 6.9: External Definitions. 1298 struct ParsedAttributesWithRange : ParsedAttributes { 1299 ParsedAttributesWithRange(AttributeFactory &factory) 1300 : ParsedAttributes(factory) {} 1301 1302 void clear() { 1303 ParsedAttributes::clear(); 1304 Range = SourceRange(); 1305 } 1306 1307 SourceRange Range; 1308 }; 1309 1310 DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs, 1311 ParsingDeclSpec *DS = nullptr); 1312 bool isDeclarationAfterDeclarator(); 1313 bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator); 1314 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition( 1315 ParsedAttributesWithRange &attrs, 1316 ParsingDeclSpec *DS = nullptr, 1317 AccessSpecifier AS = AS_none); 1318 DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, 1319 ParsingDeclSpec &DS, 1320 AccessSpecifier AS); 1321 1322 void SkipFunctionBody(); 1323 Decl *ParseFunctionDefinition(ParsingDeclarator &D, 1324 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), 1325 LateParsedAttrList *LateParsedAttrs = nullptr); 1326 void ParseKNRParamDeclarations(Declarator &D); 1327 // EndLoc, if non-NULL, is filled with the location of the last token of 1328 // the simple-asm. 1329 ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr); 1330 ExprResult ParseAsmStringLiteral(); 1331 1332 // Objective-C External Declarations 1333 void MaybeSkipAttributes(tok::ObjCKeywordKind Kind); 1334 DeclGroupPtrTy ParseObjCAtDirectives(); 1335 DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); 1336 Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, 1337 ParsedAttributes &prefixAttrs); 1338 class ObjCTypeParamListScope; 1339 ObjCTypeParamList *parseObjCTypeParamList(); 1340 ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs( 1341 ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc, 1342 SmallVectorImpl<IdentifierLocPair> &protocolIdents, 1343 SourceLocation &rAngleLoc, bool mayBeProtocolList = true); 1344 1345 void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, 1346 BalancedDelimiterTracker &T, 1347 SmallVectorImpl<Decl *> &AllIvarDecls, 1348 bool RBraceMissing); 1349 void ParseObjCClassInstanceVariables(Decl *interfaceDecl, 1350 tok::ObjCKeywordKind visibility, 1351 SourceLocation atLoc); 1352 bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P, 1353 SmallVectorImpl<SourceLocation> &PLocs, 1354 bool WarnOnDeclarations, 1355 bool ForObjCContainer, 1356 SourceLocation &LAngleLoc, 1357 SourceLocation &EndProtoLoc, 1358 bool consumeLastToken); 1359 1360 /// Parse the first angle-bracket-delimited clause for an 1361 /// Objective-C object or object pointer type, which may be either 1362 /// type arguments or protocol qualifiers. 1363 void parseObjCTypeArgsOrProtocolQualifiers( 1364 ParsedType baseType, 1365 SourceLocation &typeArgsLAngleLoc, 1366 SmallVectorImpl<ParsedType> &typeArgs, 1367 SourceLocation &typeArgsRAngleLoc, 1368 SourceLocation &protocolLAngleLoc, 1369 SmallVectorImpl<Decl *> &protocols, 1370 SmallVectorImpl<SourceLocation> &protocolLocs, 1371 SourceLocation &protocolRAngleLoc, 1372 bool consumeLastToken, 1373 bool warnOnIncompleteProtocols); 1374 1375 /// Parse either Objective-C type arguments or protocol qualifiers; if the 1376 /// former, also parse protocol qualifiers afterward. 1377 void parseObjCTypeArgsAndProtocolQualifiers( 1378 ParsedType baseType, 1379 SourceLocation &typeArgsLAngleLoc, 1380 SmallVectorImpl<ParsedType> &typeArgs, 1381 SourceLocation &typeArgsRAngleLoc, 1382 SourceLocation &protocolLAngleLoc, 1383 SmallVectorImpl<Decl *> &protocols, 1384 SmallVectorImpl<SourceLocation> &protocolLocs, 1385 SourceLocation &protocolRAngleLoc, 1386 bool consumeLastToken); 1387 1388 /// Parse a protocol qualifier type such as '<NSCopying>', which is 1389 /// an anachronistic way of writing 'id<NSCopying>'. 1390 TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc); 1391 1392 /// Parse Objective-C type arguments and protocol qualifiers, extending the 1393 /// current type with the parsed result. 1394 TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc, 1395 ParsedType type, 1396 bool consumeLastToken, 1397 SourceLocation &endLoc); 1398 1399 void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, 1400 Decl *CDecl); 1401 DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, 1402 ParsedAttributes &prefixAttrs); 1403 1404 struct ObjCImplParsingDataRAII { 1405 Parser &P; 1406 Decl *Dcl; 1407 bool HasCFunction; 1408 typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer; 1409 LateParsedObjCMethodContainer LateParsedObjCMethods; 1410 1411 ObjCImplParsingDataRAII(Parser &parser, Decl *D) 1412 : P(parser), Dcl(D), HasCFunction(false) { 1413 P.CurParsedObjCImpl = this; 1414 Finished = false; 1415 } 1416 ~ObjCImplParsingDataRAII(); 1417 1418 void finish(SourceRange AtEnd); 1419 bool isFinished() const { return Finished; } 1420 1421 private: 1422 bool Finished; 1423 }; 1424 ObjCImplParsingDataRAII *CurParsedObjCImpl; 1425 void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl); 1426 1427 DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc); 1428 DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd); 1429 Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc); 1430 Decl *ParseObjCPropertySynthesize(SourceLocation atLoc); 1431 Decl *ParseObjCPropertyDynamic(SourceLocation atLoc); 1432 1433 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); 1434 // Definitions for Objective-c context sensitive keywords recognition. 1435 enum ObjCTypeQual { 1436 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, 1437 objc_nonnull, objc_nullable, objc_null_unspecified, 1438 objc_NumQuals 1439 }; 1440 IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; 1441 1442 bool isTokIdentifier_in() const; 1443 1444 ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx, 1445 ParsedAttributes *ParamAttrs); 1446 void ParseObjCMethodRequirement(); 1447 Decl *ParseObjCMethodPrototype( 1448 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, 1449 bool MethodDefinition = true); 1450 Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, 1451 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, 1452 bool MethodDefinition=true); 1453 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); 1454 1455 Decl *ParseObjCMethodDefinition(); 1456 1457public: 1458 //===--------------------------------------------------------------------===// 1459 // C99 6.5: Expressions. 1460 1461 /// TypeCastState - State whether an expression is or may be a type cast. 1462 enum TypeCastState { 1463 NotTypeCast = 0, 1464 MaybeTypeCast, 1465 IsTypeCast 1466 }; 1467 1468 ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast); 1469 ExprResult ParseConstantExpressionInExprEvalContext( 1470 TypeCastState isTypeCast = NotTypeCast); 1471 ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast); 1472 ExprResult ParseConstraintExpression(); 1473 // Expr that doesn't include commas. 1474 ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); 1475 1476 ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, 1477 unsigned &NumLineToksConsumed, 1478 bool IsUnevaluated); 1479 1480private: 1481 ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); 1482 1483 ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); 1484 1485 ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, 1486 prec::Level MinPrec); 1487 ExprResult ParseCastExpression(bool isUnaryExpression, 1488 bool isAddressOfOperand, 1489 bool &NotCastExpr, 1490 TypeCastState isTypeCast, 1491 bool isVectorLiteral = false); 1492 ExprResult ParseCastExpression(bool isUnaryExpression, 1493 bool isAddressOfOperand = false, 1494 TypeCastState isTypeCast = NotTypeCast, 1495 bool isVectorLiteral = false); 1496 1497 /// Returns true if the next token cannot start an expression. 1498 bool isNotExpressionStart(); 1499 1500 /// Returns true if the next token would start a postfix-expression 1501 /// suffix. 1502 bool isPostfixExpressionSuffixStart() { 1503 tok::TokenKind K = Tok.getKind(); 1504 return (K == tok::l_square || K == tok::l_paren || 1505 K == tok::period || K == tok::arrow || 1506 K == tok::plusplus || K == tok::minusminus); 1507 } 1508 1509 bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less); 1510 1511 ExprResult ParsePostfixExpressionSuffix(ExprResult LHS); 1512 ExprResult ParseUnaryExprOrTypeTraitExpression(); 1513 ExprResult ParseBuiltinPrimaryExpression(); 1514 1515 ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, 1516 bool &isCastExpr, 1517 ParsedType &CastTy, 1518 SourceRange &CastRange); 1519 1520 typedef SmallVector<Expr*, 20> ExprListTy; 1521 typedef SmallVector<SourceLocation, 20> CommaLocsTy; 1522 1523 /// ParseExpressionList - Used for C/C++ (argument-)expression-list. 1524 bool ParseExpressionList( 1525 SmallVectorImpl<Expr *> &Exprs, 1526 SmallVectorImpl<SourceLocation> &CommaLocs, 1527 llvm::function_ref<void()> Completer = llvm::function_ref<void()>()); 1528 1529 /// ParseSimpleExpressionList - A simple comma-separated list of expressions, 1530 /// used for misc language extensions. 1531 bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs, 1532 SmallVectorImpl<SourceLocation> &CommaLocs); 1533 1534 1535 /// ParenParseOption - Control what ParseParenExpression will parse. 1536 enum ParenParseOption { 1537 SimpleExpr, // Only parse '(' expression ')' 1538 CompoundStmt, // Also allow '(' compound-statement ')' 1539 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' 1540 CastExpr // Also allow '(' type-name ')' <anything> 1541 }; 1542 ExprResult ParseParenExpression(ParenParseOption &ExprType, 1543 bool stopIfCastExpr, 1544 bool isTypeCast, 1545 ParsedType &CastTy, 1546 SourceLocation &RParenLoc); 1547 1548 ExprResult ParseCXXAmbiguousParenExpression( 1549 ParenParseOption &ExprType, ParsedType &CastTy, 1550 BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt); 1551 ExprResult ParseCompoundLiteralExpression(ParsedType Ty, 1552 SourceLocation LParenLoc, 1553 SourceLocation RParenLoc); 1554 1555 ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); 1556 1557 ExprResult ParseGenericSelectionExpression(); 1558 1559 ExprResult ParseObjCBoolLiteral(); 1560 1561 ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T); 1562 1563 //===--------------------------------------------------------------------===// 1564 // C++ Expressions 1565 ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand, 1566 Token &Replacement); 1567 ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); 1568 1569 bool areTokensAdjacent(const Token &A, const Token &B); 1570 1571 void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr, 1572 bool EnteringContext, IdentifierInfo &II, 1573 CXXScopeSpec &SS); 1574 1575 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, 1576 ParsedType ObjectType, 1577 bool EnteringContext, 1578 bool *MayBePseudoDestructor = nullptr, 1579 bool IsTypename = false, 1580 IdentifierInfo **LastII = nullptr, 1581 bool OnlyNamespace = false); 1582 1583 //===--------------------------------------------------------------------===// 1584 // C++0x 5.1.2: Lambda expressions 1585 1586 // [...] () -> type {...} 1587 ExprResult ParseLambdaExpression(); 1588 ExprResult TryParseLambdaExpression(); 1589 Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro, 1590 bool *SkippedInits = nullptr); 1591 bool TryParseLambdaIntroducer(LambdaIntroducer &Intro); 1592 ExprResult ParseLambdaExpressionAfterIntroducer( 1593 LambdaIntroducer &Intro); 1594 1595 //===--------------------------------------------------------------------===// 1596 // C++ 5.2p1: C++ Casts 1597 ExprResult ParseCXXCasts(); 1598 1599 //===--------------------------------------------------------------------===// 1600 // C++ 5.2p1: C++ Type Identification 1601 ExprResult ParseCXXTypeid(); 1602 1603 //===--------------------------------------------------------------------===// 1604 // C++ : Microsoft __uuidof Expression 1605 ExprResult ParseCXXUuidof(); 1606 1607 //===--------------------------------------------------------------------===// 1608 // C++ 5.2.4: C++ Pseudo-Destructor Expressions 1609 ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, 1610 tok::TokenKind OpKind, 1611 CXXScopeSpec &SS, 1612 ParsedType ObjectType); 1613 1614 //===--------------------------------------------------------------------===// 1615 // C++ 9.3.2: C++ 'this' pointer 1616 ExprResult ParseCXXThis(); 1617 1618 //===--------------------------------------------------------------------===// 1619 // C++ 15: C++ Throw Expression 1620 ExprResult ParseThrowExpression(); 1621 1622 ExceptionSpecificationType tryParseExceptionSpecification( 1623 bool Delayed, 1624 SourceRange &SpecificationRange, 1625 SmallVectorImpl<ParsedType> &DynamicExceptions, 1626 SmallVectorImpl<SourceRange> &DynamicExceptionRanges, 1627 ExprResult &NoexceptExpr, 1628 CachedTokens *&ExceptionSpecTokens); 1629 1630 // EndLoc is filled with the location of the last token of the specification. 1631 ExceptionSpecificationType ParseDynamicExceptionSpecification( 1632 SourceRange &SpecificationRange, 1633 SmallVectorImpl<ParsedType> &Exceptions, 1634 SmallVectorImpl<SourceRange> &Ranges); 1635 1636 //===--------------------------------------------------------------------===// 1637 // C++0x 8: Function declaration trailing-return-type 1638 TypeResult ParseTrailingReturnType(SourceRange &Range); 1639 1640 //===--------------------------------------------------------------------===// 1641 // C++ 2.13.5: C++ Boolean Literals 1642 ExprResult ParseCXXBoolLiteral(); 1643 1644 //===--------------------------------------------------------------------===// 1645 // C++ 5.2.3: Explicit type conversion (functional notation) 1646 ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); 1647 1648 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. 1649 /// This should only be called when the current token is known to be part of 1650 /// simple-type-specifier. 1651 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); 1652 1653 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS); 1654 1655 //===--------------------------------------------------------------------===// 1656 // C++ 5.3.4 and 5.3.5: C++ new and delete 1657 bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs, 1658 Declarator &D); 1659 void ParseDirectNewDeclarator(Declarator &D); 1660 ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); 1661 ExprResult ParseCXXDeleteExpression(bool UseGlobal, 1662 SourceLocation Start); 1663 1664 //===--------------------------------------------------------------------===// 1665 // C++ if/switch/while condition expression. 1666 Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt, 1667 SourceLocation Loc, 1668 Sema::ConditionKind CK); 1669 1670 //===--------------------------------------------------------------------===// 1671 // C++ Coroutines 1672 1673 ExprResult ParseCoyieldExpression(); 1674 1675 //===--------------------------------------------------------------------===// 1676 // C99 6.7.8: Initialization. 1677 1678 /// ParseInitializer 1679 /// initializer: [C99 6.7.8] 1680 /// assignment-expression 1681 /// '{' ... 1682 ExprResult ParseInitializer() { 1683 if (Tok.isNot(tok::l_brace)) 1684 return ParseAssignmentExpression(); 1685 return ParseBraceInitializer(); 1686 } 1687 bool MayBeDesignationStart(); 1688 ExprResult ParseBraceInitializer(); 1689 ExprResult ParseInitializerWithPotentialDesignator(); 1690 1691 //===--------------------------------------------------------------------===// 1692 // clang Expressions 1693 1694 ExprResult ParseBlockLiteralExpression(); // ^{...} 1695 1696 //===--------------------------------------------------------------------===// 1697 // Objective-C Expressions 1698 ExprResult ParseObjCAtExpression(SourceLocation AtLocation); 1699 ExprResult ParseObjCStringLiteral(SourceLocation AtLoc); 1700 ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc); 1701 ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc); 1702 ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue); 1703 ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc); 1704 ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc); 1705 ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc); 1706 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); 1707 ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); 1708 ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); 1709 bool isSimpleObjCMessageExpression(); 1710 ExprResult ParseObjCMessageExpression(); 1711 ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, 1712 SourceLocation SuperLoc, 1713 ParsedType ReceiverType, 1714 Expr *ReceiverExpr); 1715 ExprResult ParseAssignmentExprWithObjCMessageExprStart( 1716 SourceLocation LBracloc, SourceLocation SuperLoc, 1717 ParsedType ReceiverType, Expr *ReceiverExpr); 1718 bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr); 1719 1720 //===--------------------------------------------------------------------===// 1721 // C99 6.8: Statements and Blocks. 1722 1723 /// A SmallVector of statements, with stack size 32 (as that is the only one 1724 /// used.) 1725 typedef SmallVector<Stmt*, 32> StmtVector; 1726 /// A SmallVector of expressions, with stack size 12 (the maximum used.) 1727 typedef SmallVector<Expr*, 12> ExprVector; 1728 /// A SmallVector of types. 1729 typedef SmallVector<ParsedType, 12> TypeVector; 1730 1731 StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr, 1732 bool AllowOpenMPStandalone = false); 1733 enum AllowedConstructsKind { 1734 /// \brief Allow any declarations, statements, OpenMP directives. 1735 ACK_Any, 1736 /// \brief Allow only statements and non-standalone OpenMP directives. 1737 ACK_StatementsOpenMPNonStandalone, 1738 /// \brief Allow statements and all executable OpenMP directives 1739 ACK_StatementsOpenMPAnyExecutable 1740 }; 1741 StmtResult 1742 ParseStatementOrDeclaration(StmtVector &Stmts, AllowedConstructsKind Allowed, 1743 SourceLocation *TrailingElseLoc = nullptr); 1744 StmtResult ParseStatementOrDeclarationAfterAttributes( 1745 StmtVector &Stmts, 1746 AllowedConstructsKind Allowed, 1747 SourceLocation *TrailingElseLoc, 1748 ParsedAttributesWithRange &Attrs); 1749 StmtResult ParseExprStatement(); 1750 StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs); 1751 StmtResult ParseCaseStatement(bool MissingCase = false, 1752 ExprResult Expr = ExprResult()); 1753 StmtResult ParseDefaultStatement(); 1754 StmtResult ParseCompoundStatement(bool isStmtExpr = false); 1755 StmtResult ParseCompoundStatement(bool isStmtExpr, 1756 unsigned ScopeFlags); 1757 void ParseCompoundStatementLeadingPragmas(); 1758 StmtResult ParseCompoundStatementBody(bool isStmtExpr = false); 1759 bool ParseParenExprOrCondition(StmtResult *InitStmt, 1760 Sema::ConditionResult &CondResult, 1761 SourceLocation Loc, 1762 Sema::ConditionKind CK); 1763 StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc); 1764 StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc); 1765 StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc); 1766 StmtResult ParseDoStatement(); 1767 StmtResult ParseForStatement(SourceLocation *TrailingElseLoc); 1768 StmtResult ParseGotoStatement(); 1769 StmtResult ParseContinueStatement(); 1770 StmtResult ParseBreakStatement(); 1771 StmtResult ParseReturnStatement(); 1772 StmtResult ParseAsmStatement(bool &msAsm); 1773 StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc); 1774 StmtResult ParsePragmaLoopHint(StmtVector &Stmts, 1775 AllowedConstructsKind Allowed, 1776 SourceLocation *TrailingElseLoc, 1777 ParsedAttributesWithRange &Attrs); 1778 1779 /// \brief Describes the behavior that should be taken for an __if_exists 1780 /// block. 1781 enum IfExistsBehavior { 1782 /// \brief Parse the block; this code is always used. 1783 IEB_Parse, 1784 /// \brief Skip the block entirely; this code is never used. 1785 IEB_Skip, 1786 /// \brief Parse the block as a dependent block, which may be used in 1787 /// some template instantiations but not others. 1788 IEB_Dependent 1789 }; 1790 1791 /// \brief Describes the condition of a Microsoft __if_exists or 1792 /// __if_not_exists block. 1793 struct IfExistsCondition { 1794 /// \brief The location of the initial keyword. 1795 SourceLocation KeywordLoc; 1796 /// \brief Whether this is an __if_exists block (rather than an 1797 /// __if_not_exists block). 1798 bool IsIfExists; 1799 1800 /// \brief Nested-name-specifier preceding the name. 1801 CXXScopeSpec SS; 1802 1803 /// \brief The name we're looking for. 1804 UnqualifiedId Name; 1805 1806 /// \brief The behavior of this __if_exists or __if_not_exists block 1807 /// should. 1808 IfExistsBehavior Behavior; 1809 }; 1810 1811 bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result); 1812 void ParseMicrosoftIfExistsStatement(StmtVector &Stmts); 1813 void ParseMicrosoftIfExistsExternalDeclaration(); 1814 void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, 1815 AccessSpecifier& CurAS); 1816 bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, 1817 bool &InitExprsOk); 1818 bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, 1819 SmallVectorImpl<Expr *> &Constraints, 1820 SmallVectorImpl<Expr *> &Exprs); 1821 1822 //===--------------------------------------------------------------------===// 1823 // C++ 6: Statements and Blocks 1824 1825 StmtResult ParseCXXTryBlock(); 1826 StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false); 1827 StmtResult ParseCXXCatchBlock(bool FnCatch = false); 1828 1829 //===--------------------------------------------------------------------===// 1830 // MS: SEH Statements and Blocks 1831 1832 StmtResult ParseSEHTryBlock(); 1833 StmtResult ParseSEHExceptBlock(SourceLocation Loc); 1834 StmtResult ParseSEHFinallyBlock(SourceLocation Loc); 1835 StmtResult ParseSEHLeaveStatement(); 1836 1837 //===--------------------------------------------------------------------===// 1838 // Objective-C Statements 1839 1840 StmtResult ParseObjCAtStatement(SourceLocation atLoc); 1841 StmtResult ParseObjCTryStmt(SourceLocation atLoc); 1842 StmtResult ParseObjCThrowStmt(SourceLocation atLoc); 1843 StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); 1844 StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc); 1845 1846 1847 //===--------------------------------------------------------------------===// 1848 // C99 6.7: Declarations. 1849 1850 /// A context for parsing declaration specifiers. TODO: flesh this 1851 /// out, there are other significant restrictions on specifiers than 1852 /// would be best implemented in the parser. 1853 enum DeclSpecContext { 1854 DSC_normal, // normal context 1855 DSC_class, // class context, enables 'friend' 1856 DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list 1857 DSC_trailing, // C++11 trailing-type-specifier in a trailing return type 1858 DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration 1859 DSC_top_level, // top-level/namespace declaration context 1860 DSC_template_param, // template parameter context 1861 DSC_template_type_arg, // template type argument context 1862 DSC_objc_method_result, // ObjC method result context, enables 'instancetype' 1863 DSC_condition // condition declaration context 1864 }; 1865 1866 /// Is this a context in which we are parsing just a type-specifier (or 1867 /// trailing-type-specifier)? 1868 static bool isTypeSpecifier(DeclSpecContext DSC) { 1869 switch (DSC) { 1870 case DSC_normal: 1871 case DSC_template_param: 1872 case DSC_class: 1873 case DSC_top_level: 1874 case DSC_objc_method_result: 1875 case DSC_condition: 1876 return false; 1877 1878 case DSC_template_type_arg: 1879 case DSC_type_specifier: 1880 case DSC_trailing: 1881 case DSC_alias_declaration: 1882 return true; 1883 } 1884 llvm_unreachable("Missing DeclSpecContext case"); 1885 } 1886 1887 /// Is this a context in which we can perform class template argument 1888 /// deduction? 1889 static bool isClassTemplateDeductionContext(DeclSpecContext DSC) { 1890 switch (DSC) { 1891 case DSC_normal: 1892 case DSC_template_param: 1893 case DSC_class: 1894 case DSC_top_level: 1895 case DSC_condition: 1896 case DSC_type_specifier: 1897 return true; 1898 1899 case DSC_objc_method_result: 1900 case DSC_template_type_arg: 1901 case DSC_trailing: 1902 case DSC_alias_declaration: 1903 return false; 1904 } 1905 llvm_unreachable("Missing DeclSpecContext case"); 1906 } 1907 1908 /// Information on a C++0x for-range-initializer found while parsing a 1909 /// declaration which turns out to be a for-range-declaration. 1910 struct ForRangeInit { 1911 SourceLocation ColonLoc; 1912 ExprResult RangeExpr; 1913 1914 bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); } 1915 }; 1916 1917 DeclGroupPtrTy ParseDeclaration(unsigned Context, SourceLocation &DeclEnd, 1918 ParsedAttributesWithRange &attrs); 1919 DeclGroupPtrTy ParseSimpleDeclaration(unsigned Context, 1920 SourceLocation &DeclEnd, 1921 ParsedAttributesWithRange &attrs, 1922 bool RequireSemi, 1923 ForRangeInit *FRI = nullptr); 1924 bool MightBeDeclarator(unsigned Context); 1925 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context, 1926 SourceLocation *DeclEnd = nullptr, 1927 ForRangeInit *FRI = nullptr); 1928 Decl *ParseDeclarationAfterDeclarator(Declarator &D, 1929 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); 1930 bool ParseAsmAttributesAfterDeclarator(Declarator &D); 1931 Decl *ParseDeclarationAfterDeclaratorAndAttributes( 1932 Declarator &D, 1933 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), 1934 ForRangeInit *FRI = nullptr); 1935 Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope); 1936 Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope); 1937 1938 /// \brief When in code-completion, skip parsing of the function/method body 1939 /// unless the body contains the code-completion point. 1940 /// 1941 /// \returns true if the function body was skipped. 1942 bool trySkippingFunctionBody(); 1943 1944 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, 1945 const ParsedTemplateInfo &TemplateInfo, 1946 AccessSpecifier AS, DeclSpecContext DSC, 1947 ParsedAttributesWithRange &Attrs); 1948 DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context); 1949 void ParseDeclarationSpecifiers(DeclSpec &DS, 1950 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), 1951 AccessSpecifier AS = AS_none, 1952 DeclSpecContext DSC = DSC_normal, 1953 LateParsedAttrList *LateAttrs = nullptr); 1954 bool DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS, 1955 DeclSpecContext DSContext, 1956 LateParsedAttrList *LateAttrs = nullptr); 1957 1958 void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none, 1959 DeclSpecContext DSC = DSC_normal); 1960 1961 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, 1962 Declarator::TheContext Context); 1963 1964 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, 1965 const ParsedTemplateInfo &TemplateInfo, 1966 AccessSpecifier AS, DeclSpecContext DSC); 1967 void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl); 1968 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType, 1969 Decl *TagDecl); 1970 1971 void ParseStructDeclaration( 1972 ParsingDeclSpec &DS, 1973 llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback); 1974 1975 bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false); 1976 bool isTypeSpecifierQualifier(); 1977 1978 /// isKnownToBeTypeSpecifier - Return true if we know that the specified token 1979 /// is definitely a type-specifier. Return false if it isn't part of a type 1980 /// specifier or if we're not sure. 1981 bool isKnownToBeTypeSpecifier(const Token &Tok) const; 1982 1983 /// \brief Return true if we know that we are definitely looking at a 1984 /// decl-specifier, and isn't part of an expression such as a function-style 1985 /// cast. Return false if it's no a decl-specifier, or we're not sure. 1986 bool isKnownToBeDeclarationSpecifier() { 1987 if (getLangOpts().CPlusPlus) 1988 return isCXXDeclarationSpecifier() == TPResult::True; 1989 return isDeclarationSpecifier(true); 1990 } 1991 1992 /// isDeclarationStatement - Disambiguates between a declaration or an 1993 /// expression statement, when parsing function bodies. 1994 /// Returns true for declaration, false for expression. 1995 bool isDeclarationStatement() { 1996 if (getLangOpts().CPlusPlus) 1997 return isCXXDeclarationStatement(); 1998 return isDeclarationSpecifier(true); 1999 } 2000 2001 /// isForInitDeclaration - Disambiguates between a declaration or an 2002 /// expression in the context of the C 'clause-1' or the C++ 2003 // 'for-init-statement' part of a 'for' statement. 2004 /// Returns true for declaration, false for expression. 2005 bool isForInitDeclaration() { 2006 if (getLangOpts().CPlusPlus) 2007 return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true); 2008 return isDeclarationSpecifier(true); 2009 } 2010 2011 /// \brief Determine whether this is a C++1z for-range-identifier. 2012 bool isForRangeIdentifier(); 2013 2014 /// \brief Determine whether we are currently at the start of an Objective-C 2015 /// class message that appears to be missing the open bracket '['. 2016 bool isStartOfObjCClassMessageMissingOpenBracket(); 2017 2018 /// \brief Starting with a scope specifier, identifier, or 2019 /// template-id that refers to the current class, determine whether 2020 /// this is a constructor declarator. 2021 bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false); 2022 2023 /// \brief Specifies the context in which type-id/expression 2024 /// disambiguation will occur. 2025 enum TentativeCXXTypeIdContext { 2026 TypeIdInParens, 2027 TypeIdUnambiguous, 2028 TypeIdAsTemplateArgument 2029 }; 2030 2031 2032 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know 2033 /// whether the parens contain an expression or a type-id. 2034 /// Returns true for a type-id and false for an expression. 2035 bool isTypeIdInParens(bool &isAmbiguous) { 2036 if (getLangOpts().CPlusPlus) 2037 return isCXXTypeId(TypeIdInParens, isAmbiguous); 2038 isAmbiguous = false; 2039 return isTypeSpecifierQualifier(); 2040 } 2041 bool isTypeIdInParens() { 2042 bool isAmbiguous; 2043 return isTypeIdInParens(isAmbiguous); 2044 } 2045 2046 /// \brief Checks if the current tokens form type-id or expression. 2047 /// It is similar to isTypeIdInParens but does not suppose that type-id 2048 /// is in parenthesis. 2049 bool isTypeIdUnambiguously() { 2050 bool IsAmbiguous; 2051 if (getLangOpts().CPlusPlus) 2052 return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous); 2053 return isTypeSpecifierQualifier(); 2054 } 2055 2056 /// isCXXDeclarationStatement - C++-specialized function that disambiguates 2057 /// between a declaration or an expression statement, when parsing function 2058 /// bodies. Returns true for declaration, false for expression. 2059 bool isCXXDeclarationStatement(); 2060 2061 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates 2062 /// between a simple-declaration or an expression-statement. 2063 /// If during the disambiguation process a parsing error is encountered, 2064 /// the function returns true to let the declaration parsing code handle it. 2065 /// Returns false if the statement is disambiguated as expression. 2066 bool isCXXSimpleDeclaration(bool AllowForRangeDecl); 2067 2068 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or 2069 /// a constructor-style initializer, when parsing declaration statements. 2070 /// Returns true for function declarator and false for constructor-style 2071 /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration 2072 /// might be a constructor-style initializer. 2073 /// If during the disambiguation process a parsing error is encountered, 2074 /// the function returns true to let the declaration parsing code handle it. 2075 bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr); 2076 2077 struct ConditionDeclarationOrInitStatementState; 2078 enum class ConditionOrInitStatement { 2079 Expression, ///< Disambiguated as an expression (either kind). 2080 ConditionDecl, ///< Disambiguated as the declaration form of condition. 2081 InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement. 2082 Error ///< Can't be any of the above! 2083 }; 2084 /// \brief Disambiguates between the different kinds of things that can happen 2085 /// after 'if (' or 'switch ('. This could be one of two different kinds of 2086 /// declaration (depending on whether there is a ';' later) or an expression. 2087 ConditionOrInitStatement 2088 isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt); 2089 2090 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous); 2091 bool isCXXTypeId(TentativeCXXTypeIdContext Context) { 2092 bool isAmbiguous; 2093 return isCXXTypeId(Context, isAmbiguous); 2094 } 2095 2096 /// TPResult - Used as the result value for functions whose purpose is to 2097 /// disambiguate C++ constructs by "tentatively parsing" them. 2098 enum class TPResult { 2099 True, False, Ambiguous, Error 2100 }; 2101 2102 /// \brief Based only on the given token kind, determine whether we know that 2103 /// we're at the start of an expression or a type-specifier-seq (which may 2104 /// be an expression, in C++). 2105 /// 2106 /// This routine does not attempt to resolve any of the trick cases, e.g., 2107 /// those involving lookup of identifiers. 2108 /// 2109 /// \returns \c TPR_true if this token starts an expression, \c TPR_false if 2110 /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot 2111 /// tell. 2112 TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind); 2113 2114 /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a 2115 /// declaration specifier, TPResult::False if it is not, 2116 /// TPResult::Ambiguous if it could be either a decl-specifier or a 2117 /// function-style cast, and TPResult::Error if a parsing error was 2118 /// encountered. If it could be a braced C++11 function-style cast, returns 2119 /// BracedCastResult. 2120 /// Doesn't consume tokens. 2121 TPResult 2122 isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False, 2123 bool *HasMissingTypename = nullptr); 2124 2125 /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or 2126 /// \c TPResult::Ambiguous, determine whether the decl-specifier would be 2127 /// a type-specifier other than a cv-qualifier. 2128 bool isCXXDeclarationSpecifierAType(); 2129 2130 /// \brief Determine whether an identifier has been tentatively declared as a 2131 /// non-type. Such tentative declarations should not be found to name a type 2132 /// during a tentative parse, but also should not be annotated as a non-type. 2133 bool isTentativelyDeclared(IdentifierInfo *II); 2134 2135 // "Tentative parsing" functions, used for disambiguation. If a parsing error 2136 // is encountered they will return TPResult::Error. 2137 // Returning TPResult::True/False indicates that the ambiguity was 2138 // resolved and tentative parsing may stop. TPResult::Ambiguous indicates 2139 // that more tentative parsing is necessary for disambiguation. 2140 // They all consume tokens, so backtracking should be used after calling them. 2141 2142 TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl); 2143 TPResult TryParseTypeofSpecifier(); 2144 TPResult TryParseProtocolQualifiers(); 2145 TPResult TryParsePtrOperatorSeq(); 2146 TPResult TryParseOperatorId(); 2147 TPResult TryParseInitDeclaratorList(); 2148 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true); 2149 TPResult 2150 TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr, 2151 bool VersusTemplateArg = false); 2152 TPResult TryParseFunctionDeclarator(); 2153 TPResult TryParseBracketDeclarator(); 2154 TPResult TryConsumeDeclarationSpecifier(); 2155 2156public: 2157 TypeResult ParseTypeName(SourceRange *Range = nullptr, 2158 Declarator::TheContext Context 2159 = Declarator::TypeNameContext, 2160 AccessSpecifier AS = AS_none, 2161 Decl **OwnedType = nullptr, 2162 ParsedAttributes *Attrs = nullptr); 2163 2164private: 2165 void ParseBlockId(SourceLocation CaretLoc); 2166 2167 /// Are [[]] attributes enabled? 2168 bool standardAttributesAllowed() const { 2169 const LangOptions &LO = getLangOpts(); 2170 return LO.DoubleSquareBracketAttributes; 2171 } 2172 2173 // Check for the start of an attribute-specifier-seq in a context where an 2174 // attribute is not allowed. 2175 bool CheckProhibitedCXX11Attribute() { 2176 assert(Tok.is(tok::l_square)); 2177 if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square)) 2178 return false; 2179 return DiagnoseProhibitedCXX11Attribute(); 2180 } 2181 2182 bool DiagnoseProhibitedCXX11Attribute(); 2183 void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, 2184 SourceLocation CorrectLocation) { 2185 if (!standardAttributesAllowed()) 2186 return; 2187 if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) && 2188 Tok.isNot(tok::kw_alignas)) 2189 return; 2190 DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation); 2191 } 2192 void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, 2193 SourceLocation CorrectLocation); 2194 2195 void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs, 2196 DeclSpec &DS, Sema::TagUseKind TUK); 2197 2198 void ProhibitAttributes(ParsedAttributesWithRange &attrs) { 2199 if (!attrs.Range.isValid()) return; 2200 DiagnoseProhibitedAttributes(attrs); 2201 attrs.clear(); 2202 } 2203 void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs); 2204 2205 // Forbid C++11 and C2x attributes that appear on certain syntactic locations 2206 // which standard permits but we don't supported yet, for example, attributes 2207 // appertain to decl specifiers. 2208 void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs, 2209 unsigned DiagID); 2210 2211 /// \brief Skip C++11 and C2x attributes and return the end location of the 2212 /// last one. 2213 /// \returns SourceLocation() if there are no attributes. 2214 SourceLocation SkipCXX11Attributes(); 2215 2216 /// \brief Diagnose and skip C++11 and C2x attributes that appear in syntactic 2217 /// locations where attributes are not allowed. 2218 void DiagnoseAndSkipCXX11Attributes(); 2219 2220 /// \brief Parses syntax-generic attribute arguments for attributes which are 2221 /// known to the implementation, and adds them to the given ParsedAttributes 2222 /// list with the given attribute syntax. Returns the number of arguments 2223 /// parsed for the attribute. 2224 unsigned 2225 ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, 2226 ParsedAttributes &Attrs, SourceLocation *EndLoc, 2227 IdentifierInfo *ScopeName, SourceLocation ScopeLoc, 2228 AttributeList::Syntax Syntax); 2229 2230 void MaybeParseGNUAttributes(Declarator &D, 2231 LateParsedAttrList *LateAttrs = nullptr) { 2232 if (Tok.is(tok::kw___attribute)) { 2233 ParsedAttributes attrs(AttrFactory); 2234 SourceLocation endLoc; 2235 ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D); 2236 D.takeAttributes(attrs, endLoc); 2237 } 2238 } 2239 void MaybeParseGNUAttributes(ParsedAttributes &attrs, 2240 SourceLocation *endLoc = nullptr, 2241 LateParsedAttrList *LateAttrs = nullptr) { 2242 if (Tok.is(tok::kw___attribute)) 2243 ParseGNUAttributes(attrs, endLoc, LateAttrs); 2244 } 2245 void ParseGNUAttributes(ParsedAttributes &attrs, 2246 SourceLocation *endLoc = nullptr, 2247 LateParsedAttrList *LateAttrs = nullptr, 2248 Declarator *D = nullptr); 2249 void ParseGNUAttributeArgs(IdentifierInfo *AttrName, 2250 SourceLocation AttrNameLoc, 2251 ParsedAttributes &Attrs, 2252 SourceLocation *EndLoc, 2253 IdentifierInfo *ScopeName, 2254 SourceLocation ScopeLoc, 2255 AttributeList::Syntax Syntax, 2256 Declarator *D); 2257 IdentifierLoc *ParseIdentifierLoc(); 2258 2259 unsigned 2260 ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, 2261 ParsedAttributes &Attrs, SourceLocation *EndLoc, 2262 IdentifierInfo *ScopeName, SourceLocation ScopeLoc, 2263 AttributeList::Syntax Syntax); 2264 2265 void MaybeParseCXX11Attributes(Declarator &D) { 2266 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { 2267 ParsedAttributesWithRange attrs(AttrFactory); 2268 SourceLocation endLoc; 2269 ParseCXX11Attributes(attrs, &endLoc); 2270 D.takeAttributes(attrs, endLoc); 2271 } 2272 } 2273 void MaybeParseCXX11Attributes(ParsedAttributes &attrs, 2274 SourceLocation *endLoc = nullptr) { 2275 if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { 2276 ParsedAttributesWithRange attrsWithRange(AttrFactory); 2277 ParseCXX11Attributes(attrsWithRange, endLoc); 2278 attrs.takeAllFrom(attrsWithRange); 2279 } 2280 } 2281 void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs, 2282 SourceLocation *endLoc = nullptr, 2283 bool OuterMightBeMessageSend = false) { 2284 if (standardAttributesAllowed() && 2285 isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) 2286 ParseCXX11Attributes(attrs, endLoc); 2287 } 2288 2289 void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, 2290 SourceLocation *EndLoc = nullptr); 2291 void ParseCXX11Attributes(ParsedAttributesWithRange &attrs, 2292 SourceLocation *EndLoc = nullptr); 2293 /// \brief Parses a C++11 (or C2x)-style attribute argument list. Returns true 2294 /// if this results in adding an attribute to the ParsedAttributes list. 2295 bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName, 2296 SourceLocation AttrNameLoc, 2297 ParsedAttributes &Attrs, SourceLocation *EndLoc, 2298 IdentifierInfo *ScopeName, 2299 SourceLocation ScopeLoc); 2300 2301 IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc); 2302 2303 void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs, 2304 SourceLocation *endLoc = nullptr) { 2305 if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square)) 2306 ParseMicrosoftAttributes(attrs, endLoc); 2307 } 2308 void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs); 2309 void ParseMicrosoftAttributes(ParsedAttributes &attrs, 2310 SourceLocation *endLoc = nullptr); 2311 void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, 2312 SourceLocation *End = nullptr) { 2313 const auto &LO = getLangOpts(); 2314 if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec)) 2315 ParseMicrosoftDeclSpecs(Attrs, End); 2316 } 2317 void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, 2318 SourceLocation *End = nullptr); 2319 bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, 2320 SourceLocation AttrNameLoc, 2321 ParsedAttributes &Attrs); 2322 void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs); 2323 void DiagnoseAndSkipExtendedMicrosoftTypeAttributes(); 2324 SourceLocation SkipExtendedMicrosoftTypeAttributes(); 2325 void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs); 2326 void ParseBorlandTypeAttributes(ParsedAttributes &attrs); 2327 void ParseOpenCLKernelAttributes(ParsedAttributes &attrs); 2328 void ParseOpenCLQualifiers(ParsedAttributes &Attrs); 2329 /// \brief Parses opencl_unroll_hint attribute if language is OpenCL v2.0 2330 /// or higher. 2331 /// \return false if error happens. 2332 bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) { 2333 if (getLangOpts().OpenCL) 2334 return ParseOpenCLUnrollHintAttribute(Attrs); 2335 return true; 2336 } 2337 /// \brief Parses opencl_unroll_hint attribute. 2338 /// \return false if error happens. 2339 bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs); 2340 void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs); 2341 2342 VersionTuple ParseVersionTuple(SourceRange &Range); 2343 void ParseAvailabilityAttribute(IdentifierInfo &Availability, 2344 SourceLocation AvailabilityLoc, 2345 ParsedAttributes &attrs, 2346 SourceLocation *endLoc, 2347 IdentifierInfo *ScopeName, 2348 SourceLocation ScopeLoc, 2349 AttributeList::Syntax Syntax); 2350 2351 Optional<AvailabilitySpec> ParseAvailabilitySpec(); 2352 ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc); 2353 2354 void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol, 2355 SourceLocation Loc, 2356 ParsedAttributes &Attrs, 2357 SourceLocation *EndLoc, 2358 IdentifierInfo *ScopeName, 2359 SourceLocation ScopeLoc, 2360 AttributeList::Syntax Syntax); 2361 2362 void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, 2363 SourceLocation ObjCBridgeRelatedLoc, 2364 ParsedAttributes &attrs, 2365 SourceLocation *endLoc, 2366 IdentifierInfo *ScopeName, 2367 SourceLocation ScopeLoc, 2368 AttributeList::Syntax Syntax); 2369 2370 void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, 2371 SourceLocation AttrNameLoc, 2372 ParsedAttributes &Attrs, 2373 SourceLocation *EndLoc, 2374 IdentifierInfo *ScopeName, 2375 SourceLocation ScopeLoc, 2376 AttributeList::Syntax Syntax); 2377 2378 void ParseAttributeWithTypeArg(IdentifierInfo &AttrName, 2379 SourceLocation AttrNameLoc, 2380 ParsedAttributes &Attrs, 2381 SourceLocation *EndLoc, 2382 IdentifierInfo *ScopeName, 2383 SourceLocation ScopeLoc, 2384 AttributeList::Syntax Syntax); 2385 2386 void ParseTypeofSpecifier(DeclSpec &DS); 2387 SourceLocation ParseDecltypeSpecifier(DeclSpec &DS); 2388 void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS, 2389 SourceLocation StartLoc, 2390 SourceLocation EndLoc); 2391 void ParseUnderlyingTypeSpecifier(DeclSpec &DS); 2392 void ParseAtomicSpecifier(DeclSpec &DS); 2393 2394 ExprResult ParseAlignArgument(SourceLocation Start, 2395 SourceLocation &EllipsisLoc); 2396 void ParseAlignmentSpecifier(ParsedAttributes &Attrs, 2397 SourceLocation *endLoc = nullptr); 2398 2399 VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const; 2400 VirtSpecifiers::Specifier isCXX11VirtSpecifier() const { 2401 return isCXX11VirtSpecifier(Tok); 2402 } 2403 void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface, 2404 SourceLocation FriendLoc); 2405 2406 bool isCXX11FinalKeyword() const; 2407 2408 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to 2409 /// enter a new C++ declarator scope and exit it when the function is 2410 /// finished. 2411 class DeclaratorScopeObj { 2412 Parser &P; 2413 CXXScopeSpec &SS; 2414 bool EnteredScope; 2415 bool CreatedScope; 2416 public: 2417 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) 2418 : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {} 2419 2420 void EnterDeclaratorScope() { 2421 assert(!EnteredScope && "Already entered the scope!"); 2422 assert(SS.isSet() && "C++ scope was not set!"); 2423 2424 CreatedScope = true; 2425 P.EnterScope(0); // Not a decl scope. 2426 2427 if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS)) 2428 EnteredScope = true; 2429 } 2430 2431 ~DeclaratorScopeObj() { 2432 if (EnteredScope) { 2433 assert(SS.isSet() && "C++ scope was cleared ?"); 2434 P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS); 2435 } 2436 if (CreatedScope) 2437 P.ExitScope(); 2438 } 2439 }; 2440 2441 /// ParseDeclarator - Parse and verify a newly-initialized declarator. 2442 void ParseDeclarator(Declarator &D); 2443 /// A function that parses a variant of direct-declarator. 2444 typedef void (Parser::*DirectDeclParseFunction)(Declarator&); 2445 void ParseDeclaratorInternal(Declarator &D, 2446 DirectDeclParseFunction DirectDeclParser); 2447 2448 enum AttrRequirements { 2449 AR_NoAttributesParsed = 0, ///< No attributes are diagnosed. 2450 AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes. 2451 AR_GNUAttributesParsed = 1 << 1, 2452 AR_CXX11AttributesParsed = 1 << 2, 2453 AR_DeclspecAttributesParsed = 1 << 3, 2454 AR_AllAttributesParsed = AR_GNUAttributesParsed | 2455 AR_CXX11AttributesParsed | 2456 AR_DeclspecAttributesParsed, 2457 AR_VendorAttributesParsed = AR_GNUAttributesParsed | 2458 AR_DeclspecAttributesParsed 2459 }; 2460 2461 void ParseTypeQualifierListOpt( 2462 DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed, 2463 bool AtomicAllowed = true, bool IdentifierRequired = false, 2464 Optional<llvm::function_ref<void()>> CodeCompletionHandler = None); 2465 void ParseDirectDeclarator(Declarator &D); 2466 void ParseDecompositionDeclarator(Declarator &D); 2467 void ParseParenDeclarator(Declarator &D); 2468 void ParseFunctionDeclarator(Declarator &D, 2469 ParsedAttributes &attrs, 2470 BalancedDelimiterTracker &Tracker, 2471 bool IsAmbiguous, 2472 bool RequiresArg = false); 2473 bool ParseRefQualifier(bool &RefQualifierIsLValueRef, 2474 SourceLocation &RefQualifierLoc); 2475 bool isFunctionDeclaratorIdentifierList(); 2476 void ParseFunctionDeclaratorIdentifierList( 2477 Declarator &D, 2478 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo); 2479 void ParseParameterDeclarationClause( 2480 Declarator &D, 2481 ParsedAttributes &attrs, 2482 SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, 2483 SourceLocation &EllipsisLoc); 2484 void ParseBracketDeclarator(Declarator &D); 2485 void ParseMisplacedBracketDeclarator(Declarator &D); 2486 2487 //===--------------------------------------------------------------------===// 2488 // C++ 7: Declarations [dcl.dcl] 2489 2490 /// The kind of attribute specifier we have found. 2491 enum CXX11AttributeKind { 2492 /// This is not an attribute specifier. 2493 CAK_NotAttributeSpecifier, 2494 /// This should be treated as an attribute-specifier. 2495 CAK_AttributeSpecifier, 2496 /// The next tokens are '[[', but this is not an attribute-specifier. This 2497 /// is ill-formed by C++11 [dcl.attr.grammar]p6. 2498 CAK_InvalidAttributeSpecifier 2499 }; 2500 CXX11AttributeKind 2501 isCXX11AttributeSpecifier(bool Disambiguate = false, 2502 bool OuterMightBeMessageSend = false); 2503 2504 void DiagnoseUnexpectedNamespace(NamedDecl *Context); 2505 2506 DeclGroupPtrTy ParseNamespace(unsigned Context, SourceLocation &DeclEnd, 2507 SourceLocation InlineLoc = SourceLocation()); 2508 void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc, 2509 std::vector<IdentifierInfo*>& Ident, 2510 std::vector<SourceLocation>& NamespaceLoc, 2511 unsigned int index, SourceLocation& InlineLoc, 2512 ParsedAttributes& attrs, 2513 BalancedDelimiterTracker &Tracker); 2514 Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context); 2515 Decl *ParseExportDeclaration(); 2516 DeclGroupPtrTy ParseUsingDirectiveOrDeclaration( 2517 unsigned Context, const ParsedTemplateInfo &TemplateInfo, 2518 SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs); 2519 Decl *ParseUsingDirective(unsigned Context, 2520 SourceLocation UsingLoc, 2521 SourceLocation &DeclEnd, 2522 ParsedAttributes &attrs); 2523 2524 struct UsingDeclarator { 2525 SourceLocation TypenameLoc; 2526 CXXScopeSpec SS; 2527 SourceLocation TemplateKWLoc; 2528 UnqualifiedId Name; 2529 SourceLocation EllipsisLoc; 2530 2531 void clear() { 2532 TypenameLoc = TemplateKWLoc = EllipsisLoc = SourceLocation(); 2533 SS.clear(); 2534 Name.clear(); 2535 } 2536 }; 2537 2538 bool ParseUsingDeclarator(unsigned Context, UsingDeclarator &D); 2539 DeclGroupPtrTy ParseUsingDeclaration(unsigned Context, 2540 const ParsedTemplateInfo &TemplateInfo, 2541 SourceLocation UsingLoc, 2542 SourceLocation &DeclEnd, 2543 AccessSpecifier AS = AS_none); 2544 Decl *ParseAliasDeclarationAfterDeclarator( 2545 const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, 2546 UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS, 2547 ParsedAttributes &Attrs, Decl **OwnedType = nullptr); 2548 2549 Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd); 2550 Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc, 2551 SourceLocation AliasLoc, IdentifierInfo *Alias, 2552 SourceLocation &DeclEnd); 2553 2554 //===--------------------------------------------------------------------===// 2555 // C++ 9: classes [class] and C structs/unions. 2556 bool isValidAfterTypeSpecifier(bool CouldBeBitfield); 2557 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, 2558 DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, 2559 AccessSpecifier AS, bool EnteringContext, 2560 DeclSpecContext DSC, 2561 ParsedAttributesWithRange &Attributes); 2562 void SkipCXXMemberSpecification(SourceLocation StartLoc, 2563 SourceLocation AttrFixitLoc, 2564 unsigned TagType, 2565 Decl *TagDecl); 2566 void ParseCXXMemberSpecification(SourceLocation StartLoc, 2567 SourceLocation AttrFixitLoc, 2568 ParsedAttributesWithRange &Attrs, 2569 unsigned TagType, 2570 Decl *TagDecl); 2571 ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction, 2572 SourceLocation &EqualLoc); 2573 bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo, 2574 VirtSpecifiers &VS, 2575 ExprResult &BitfieldSize, 2576 LateParsedAttrList &LateAttrs); 2577 void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D, 2578 VirtSpecifiers &VS); 2579 DeclGroupPtrTy ParseCXXClassMemberDeclaration( 2580 AccessSpecifier AS, AttributeList *Attr, 2581 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), 2582 ParsingDeclRAIIObject *DiagsFromTParams = nullptr); 2583 DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas( 2584 AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs, 2585 DeclSpec::TST TagType, Decl *Tag); 2586 void ParseConstructorInitializer(Decl *ConstructorDecl); 2587 MemInitResult ParseMemInitializer(Decl *ConstructorDecl); 2588 void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, 2589 Decl *ThisDecl); 2590 2591 //===--------------------------------------------------------------------===// 2592 // C++ 10: Derived classes [class.derived] 2593 TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc, 2594 SourceLocation &EndLocation); 2595 void ParseBaseClause(Decl *ClassDecl); 2596 BaseResult ParseBaseSpecifier(Decl *ClassDecl); 2597 AccessSpecifier getAccessSpecifierIfPresent() const; 2598 2599 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, 2600 SourceLocation TemplateKWLoc, 2601 IdentifierInfo *Name, 2602 SourceLocation NameLoc, 2603 bool EnteringContext, 2604 ParsedType ObjectType, 2605 UnqualifiedId &Id, 2606 bool AssumeTemplateId); 2607 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, 2608 ParsedType ObjectType, 2609 UnqualifiedId &Result); 2610 2611 //===--------------------------------------------------------------------===// 2612 // OpenMP: Directives and clauses. 2613 /// Parse clauses for '#pragma omp declare simd'. 2614 DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr, 2615 CachedTokens &Toks, 2616 SourceLocation Loc); 2617 /// \brief Parses declarative OpenMP directives. 2618 DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl( 2619 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, 2620 DeclSpec::TST TagType = DeclSpec::TST_unspecified, 2621 Decl *TagDecl = nullptr); 2622 /// \brief Parse 'omp declare reduction' construct. 2623 DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS); 2624 /// Parses initializer for provided omp_priv declaration inside the reduction 2625 /// initializer. 2626 void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm); 2627 2628 /// \brief Parses simple list of variables. 2629 /// 2630 /// \param Kind Kind of the directive. 2631 /// \param Callback Callback function to be called for the list elements. 2632 /// \param AllowScopeSpecifier true, if the variables can have fully 2633 /// qualified names. 2634 /// 2635 bool ParseOpenMPSimpleVarList( 2636 OpenMPDirectiveKind Kind, 2637 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> & 2638 Callback, 2639 bool AllowScopeSpecifier); 2640 /// \brief Parses declarative or executable directive. 2641 /// 2642 /// \param Allowed ACK_Any, if any directives are allowed, 2643 /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are 2644 /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone 2645 /// executable directives are allowed. 2646 /// 2647 StmtResult 2648 ParseOpenMPDeclarativeOrExecutableDirective(AllowedConstructsKind Allowed); 2649 /// \brief Parses clause of kind \a CKind for directive of a kind \a Kind. 2650 /// 2651 /// \param DKind Kind of current directive. 2652 /// \param CKind Kind of current clause. 2653 /// \param FirstClause true, if this is the first clause of a kind \a CKind 2654 /// in current directive. 2655 /// 2656 OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind, 2657 OpenMPClauseKind CKind, bool FirstClause); 2658 /// \brief Parses clause with a single expression of a kind \a Kind. 2659 /// 2660 /// \param Kind Kind of current clause. 2661 /// 2662 OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind); 2663 /// \brief Parses simple clause of a kind \a Kind. 2664 /// 2665 /// \param Kind Kind of current clause. 2666 /// 2667 OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind); 2668 /// \brief Parses clause with a single expression and an additional argument 2669 /// of a kind \a Kind. 2670 /// 2671 /// \param Kind Kind of current clause. 2672 /// 2673 OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind); 2674 /// \brief Parses clause without any additional arguments. 2675 /// 2676 /// \param Kind Kind of current clause. 2677 /// 2678 OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind); 2679 /// \brief Parses clause with the list of variables of a kind \a Kind. 2680 /// 2681 /// \param Kind Kind of current clause. 2682 /// 2683 OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, 2684 OpenMPClauseKind Kind); 2685 2686public: 2687 /// Parses simple expression in parens for single-expression clauses of OpenMP 2688 /// constructs. 2689 /// \param RLoc Returned location of right paren. 2690 ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc); 2691 2692 /// Data used for parsing list of variables in OpenMP clauses. 2693 struct OpenMPVarListDataTy { 2694 Expr *TailExpr = nullptr; 2695 SourceLocation ColonLoc; 2696 CXXScopeSpec ReductionIdScopeSpec; 2697 DeclarationNameInfo ReductionId; 2698 OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown; 2699 OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val; 2700 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown; 2701 OpenMPMapClauseKind MapType = OMPC_MAP_unknown; 2702 bool IsMapTypeImplicit = false; 2703 SourceLocation DepLinMapLoc; 2704 }; 2705 2706 /// Parses clauses with list. 2707 bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, 2708 SmallVectorImpl<Expr *> &Vars, 2709 OpenMPVarListDataTy &Data); 2710 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, 2711 bool AllowDestructorName, 2712 bool AllowConstructorName, 2713 bool AllowDeductionGuide, 2714 ParsedType ObjectType, 2715 SourceLocation& TemplateKWLoc, 2716 UnqualifiedId &Result); 2717 2718private: 2719 //===--------------------------------------------------------------------===// 2720 // C++ 14: Templates [temp] 2721 2722 // C++ 14.1: Template Parameters [temp.param] 2723 Decl *ParseDeclarationStartingWithTemplate(unsigned Context, 2724 SourceLocation &DeclEnd, 2725 AccessSpecifier AS = AS_none, 2726 AttributeList *AccessAttrs = nullptr); 2727 Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context, 2728 SourceLocation &DeclEnd, 2729 AccessSpecifier AS, 2730 AttributeList *AccessAttrs); 2731 Decl *ParseSingleDeclarationAfterTemplate( 2732 unsigned Context, 2733 const ParsedTemplateInfo &TemplateInfo, 2734 ParsingDeclRAIIObject &DiagsFromParams, 2735 SourceLocation &DeclEnd, 2736 AccessSpecifier AS=AS_none, 2737 AttributeList *AccessAttrs = nullptr); 2738 bool ParseTemplateParameters(unsigned Depth, 2739 SmallVectorImpl<NamedDecl *> &TemplateParams, 2740 SourceLocation &LAngleLoc, 2741 SourceLocation &RAngleLoc); 2742 bool ParseTemplateParameterList(unsigned Depth, 2743 SmallVectorImpl<NamedDecl*> &TemplateParams); 2744 bool isStartOfTemplateTypeParameter(); 2745 Decl *ParseTemplateParameter(unsigned Depth, unsigned Position); 2746 Decl *ParseTypeParameter(unsigned Depth, unsigned Position); 2747 Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); 2748 Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); 2749 void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc, 2750 SourceLocation CorrectLoc, 2751 bool AlreadyHasEllipsis, 2752 bool IdentifierHasName); 2753 void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc, 2754 Declarator &D); 2755 // C++ 14.3: Template arguments [temp.arg] 2756 typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList; 2757 2758 bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc, 2759 bool ConsumeLastToken, 2760 bool ObjCGenericList); 2761 bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken, 2762 SourceLocation &LAngleLoc, 2763 TemplateArgList &TemplateArgs, 2764 SourceLocation &RAngleLoc); 2765 2766 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, 2767 CXXScopeSpec &SS, 2768 SourceLocation TemplateKWLoc, 2769 UnqualifiedId &TemplateName, 2770 bool AllowTypeAnnotation = true); 2771 void AnnotateTemplateIdTokenAsType(bool IsClassName = false); 2772 bool IsTemplateArgumentList(unsigned Skip = 0); 2773 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs); 2774 ParsedTemplateArgument ParseTemplateTemplateArgument(); 2775 ParsedTemplateArgument ParseTemplateArgument(); 2776 Decl *ParseExplicitInstantiation(unsigned Context, 2777 SourceLocation ExternLoc, 2778 SourceLocation TemplateLoc, 2779 SourceLocation &DeclEnd, 2780 AccessSpecifier AS = AS_none); 2781 2782 //===--------------------------------------------------------------------===// 2783 // Modules 2784 DeclGroupPtrTy ParseModuleDecl(); 2785 DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc); 2786 bool parseMisplacedModuleImport(); 2787 bool tryParseMisplacedModuleImport() { 2788 tok::TokenKind Kind = Tok.getKind(); 2789 if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end || 2790 Kind == tok::annot_module_include) 2791 return parseMisplacedModuleImport(); 2792 return false; 2793 } 2794 2795 bool ParseModuleName( 2796 SourceLocation UseLoc, 2797 SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, 2798 bool IsImport); 2799 2800 //===--------------------------------------------------------------------===// 2801 // C++11/G++: Type Traits [Type-Traits.html in the GCC manual] 2802 ExprResult ParseTypeTrait(); 2803 2804 //===--------------------------------------------------------------------===// 2805 // Embarcadero: Arary and Expression Traits 2806 ExprResult ParseArrayTypeTrait(); 2807 ExprResult ParseExpressionTrait(); 2808 2809 //===--------------------------------------------------------------------===// 2810 // Preprocessor code-completion pass-through 2811 void CodeCompleteDirective(bool InConditional) override; 2812 void CodeCompleteInConditionalExclusion() override; 2813 void CodeCompleteMacroName(bool IsDefinition) override; 2814 void CodeCompletePreprocessorExpression() override; 2815 void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, 2816 unsigned ArgumentIndex) override; 2817 void CodeCompleteNaturalLanguage() override; 2818}; 2819 2820} // end namespace clang 2821 2822#endif 2823