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