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