Parser.h revision 198893
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/Lex/Preprocessor.h" 18#include "clang/Parse/AccessSpecifier.h" 19#include "clang/Parse/Action.h" 20#include "clang/Parse/DeclSpec.h" 21#include "llvm/ADT/OwningPtr.h" 22#include <stack> 23#include <list> 24 25namespace clang { 26 class AttributeList; 27 class PragmaHandler; 28 class Scope; 29 class DiagnosticBuilder; 30 class Parser; 31 class PragmaUnusedHandler; 32 33/// PrettyStackTraceParserEntry - If a crash happens while the parser is active, 34/// an entry is printed for it. 35class PrettyStackTraceParserEntry : public llvm::PrettyStackTraceEntry { 36 const Parser &P; 37public: 38 PrettyStackTraceParserEntry(const Parser &p) : P(p) {} 39 virtual void print(llvm::raw_ostream &OS) const; 40}; 41 42 43/// Parser - This implements a parser for the C family of languages. After 44/// parsing units of the grammar, productions are invoked to handle whatever has 45/// been read. 46/// 47class Parser { 48 friend class PragmaUnusedHandler; 49 PrettyStackTraceParserEntry CrashInfo; 50 51 Preprocessor &PP; 52 53 /// Tok - The current token we are peeking ahead. All parsing methods assume 54 /// that this is valid. 55 Token Tok; 56 57 // PrevTokLocation - The location of the token we previously 58 // consumed. This token is used for diagnostics where we expected to 59 // see a token following another token (e.g., the ';' at the end of 60 // a statement). 61 SourceLocation PrevTokLocation; 62 63 unsigned short ParenCount, BracketCount, BraceCount; 64 65 /// Actions - These are the callbacks we invoke as we parse various constructs 66 /// in the file. This refers to the common base class between MinimalActions 67 /// and SemaActions for those uses that don't matter. 68 Action &Actions; 69 70 Scope *CurScope; 71 Diagnostic &Diags; 72 73 /// ScopeCache - Cache scopes to reduce malloc traffic. 74 enum { ScopeCacheSize = 16 }; 75 unsigned NumCachedScopes; 76 Scope *ScopeCache[ScopeCacheSize]; 77 78 /// Ident_super - IdentifierInfo for "super", to support fast 79 /// comparison. 80 IdentifierInfo *Ident_super; 81 82 llvm::OwningPtr<PragmaHandler> PackHandler; 83 llvm::OwningPtr<PragmaHandler> UnusedHandler; 84 llvm::OwningPtr<PragmaHandler> WeakHandler; 85 llvm::OwningPtr<clang::CommentHandler> CommentHandler; 86 87 /// Whether the '>' token acts as an operator or not. This will be 88 /// true except when we are parsing an expression within a C++ 89 /// template argument list, where the '>' closes the template 90 /// argument list. 91 bool GreaterThanIsOperator; 92 93 /// The "depth" of the template parameters currently being parsed. 94 unsigned TemplateParameterDepth; 95 96 /// \brief RAII object that makes '>' behave either as an operator 97 /// or as the closing angle bracket for a template argument list. 98 struct GreaterThanIsOperatorScope { 99 bool &GreaterThanIsOperator; 100 bool OldGreaterThanIsOperator; 101 102 GreaterThanIsOperatorScope(bool >IO, bool Val) 103 : GreaterThanIsOperator(GTIO), OldGreaterThanIsOperator(GTIO) { 104 GreaterThanIsOperator = Val; 105 } 106 107 ~GreaterThanIsOperatorScope() { 108 GreaterThanIsOperator = OldGreaterThanIsOperator; 109 } 110 }; 111 112public: 113 Parser(Preprocessor &PP, Action &Actions); 114 ~Parser(); 115 116 const LangOptions &getLang() const { return PP.getLangOptions(); } 117 TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } 118 Preprocessor &getPreprocessor() const { return PP; } 119 Action &getActions() const { return Actions; } 120 121 const Token &getCurToken() const { return Tok; } 122 123 // Type forwarding. All of these are statically 'void*', but they may all be 124 // different actual classes based on the actions in place. 125 typedef Action::ExprTy ExprTy; 126 typedef Action::StmtTy StmtTy; 127 typedef Action::DeclPtrTy DeclPtrTy; 128 typedef Action::DeclGroupPtrTy DeclGroupPtrTy; 129 typedef Action::TypeTy TypeTy; 130 typedef Action::BaseTy BaseTy; 131 typedef Action::MemInitTy MemInitTy; 132 typedef Action::CXXScopeTy CXXScopeTy; 133 typedef Action::TemplateParamsTy TemplateParamsTy; 134 typedef Action::TemplateTy TemplateTy; 135 136 typedef llvm::SmallVector<TemplateParamsTy *, 4> TemplateParameterLists; 137 138 typedef Action::ExprResult ExprResult; 139 typedef Action::StmtResult StmtResult; 140 typedef Action::BaseResult BaseResult; 141 typedef Action::MemInitResult MemInitResult; 142 typedef Action::TypeResult TypeResult; 143 144 typedef Action::OwningExprResult OwningExprResult; 145 typedef Action::OwningStmtResult OwningStmtResult; 146 147 typedef Action::ExprArg ExprArg; 148 typedef Action::MultiStmtArg MultiStmtArg; 149 typedef Action::FullExprArg FullExprArg; 150 151 /// Adorns a ExprResult with Actions to make it an OwningExprResult 152 OwningExprResult Owned(ExprResult res) { 153 return OwningExprResult(Actions, res); 154 } 155 /// Adorns a StmtResult with Actions to make it an OwningStmtResult 156 OwningStmtResult Owned(StmtResult res) { 157 return OwningStmtResult(Actions, res); 158 } 159 160 OwningExprResult ExprError() { return OwningExprResult(Actions, true); } 161 OwningStmtResult StmtError() { return OwningStmtResult(Actions, true); } 162 163 OwningExprResult ExprError(const DiagnosticBuilder &) { return ExprError(); } 164 OwningStmtResult StmtError(const DiagnosticBuilder &) { return StmtError(); } 165 166 OwningExprResult ExprEmpty() { return OwningExprResult(Actions, false); } 167 168 // Parsing methods. 169 170 /// ParseTranslationUnit - All in one method that initializes parses, and 171 /// shuts down the parser. 172 void ParseTranslationUnit(); 173 174 /// Initialize - Warm up the parser. 175 /// 176 void Initialize(); 177 178 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if 179 /// the EOF was encountered. 180 bool ParseTopLevelDecl(DeclGroupPtrTy &Result); 181 182private: 183 //===--------------------------------------------------------------------===// 184 // Low-Level token peeking and consumption methods. 185 // 186 187 /// isTokenParen - Return true if the cur token is '(' or ')'. 188 bool isTokenParen() const { 189 return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren; 190 } 191 /// isTokenBracket - Return true if the cur token is '[' or ']'. 192 bool isTokenBracket() const { 193 return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square; 194 } 195 /// isTokenBrace - Return true if the cur token is '{' or '}'. 196 bool isTokenBrace() const { 197 return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace; 198 } 199 200 /// isTokenStringLiteral - True if this token is a string-literal. 201 /// 202 bool isTokenStringLiteral() const { 203 return Tok.getKind() == tok::string_literal || 204 Tok.getKind() == tok::wide_string_literal; 205 } 206 207 /// ConsumeToken - Consume the current 'peek token' and lex the next one. 208 /// This does not work with all kinds of tokens: strings and specific other 209 /// tokens must be consumed with custom methods below. This returns the 210 /// location of the consumed token. 211 SourceLocation ConsumeToken() { 212 assert(!isTokenStringLiteral() && !isTokenParen() && !isTokenBracket() && 213 !isTokenBrace() && 214 "Should consume special tokens with Consume*Token"); 215 PrevTokLocation = Tok.getLocation(); 216 PP.Lex(Tok); 217 return PrevTokLocation; 218 } 219 220 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the 221 /// current token type. This should only be used in cases where the type of 222 /// the token really isn't known, e.g. in error recovery. 223 SourceLocation ConsumeAnyToken() { 224 if (isTokenParen()) 225 return ConsumeParen(); 226 else if (isTokenBracket()) 227 return ConsumeBracket(); 228 else if (isTokenBrace()) 229 return ConsumeBrace(); 230 else if (isTokenStringLiteral()) 231 return ConsumeStringToken(); 232 else 233 return ConsumeToken(); 234 } 235 236 /// ConsumeParen - This consume method keeps the paren count up-to-date. 237 /// 238 SourceLocation ConsumeParen() { 239 assert(isTokenParen() && "wrong consume method"); 240 if (Tok.getKind() == tok::l_paren) 241 ++ParenCount; 242 else if (ParenCount) 243 --ParenCount; // Don't let unbalanced )'s drive the count negative. 244 PrevTokLocation = Tok.getLocation(); 245 PP.Lex(Tok); 246 return PrevTokLocation; 247 } 248 249 /// ConsumeBracket - This consume method keeps the bracket count up-to-date. 250 /// 251 SourceLocation ConsumeBracket() { 252 assert(isTokenBracket() && "wrong consume method"); 253 if (Tok.getKind() == tok::l_square) 254 ++BracketCount; 255 else if (BracketCount) 256 --BracketCount; // Don't let unbalanced ]'s drive the count negative. 257 258 PrevTokLocation = Tok.getLocation(); 259 PP.Lex(Tok); 260 return PrevTokLocation; 261 } 262 263 /// ConsumeBrace - This consume method keeps the brace count up-to-date. 264 /// 265 SourceLocation ConsumeBrace() { 266 assert(isTokenBrace() && "wrong consume method"); 267 if (Tok.getKind() == tok::l_brace) 268 ++BraceCount; 269 else if (BraceCount) 270 --BraceCount; // Don't let unbalanced }'s drive the count negative. 271 272 PrevTokLocation = Tok.getLocation(); 273 PP.Lex(Tok); 274 return PrevTokLocation; 275 } 276 277 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one 278 /// and returning the token kind. This method is specific to strings, as it 279 /// handles string literal concatenation, as per C99 5.1.1.2, translation 280 /// phase #6. 281 SourceLocation ConsumeStringToken() { 282 assert(isTokenStringLiteral() && 283 "Should only consume string literals with this method"); 284 PrevTokLocation = Tok.getLocation(); 285 PP.Lex(Tok); 286 return PrevTokLocation; 287 } 288 289 /// GetLookAheadToken - This peeks ahead N tokens and returns that token 290 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) 291 /// returns the token after Tok, etc. 292 /// 293 /// Note that this differs from the Preprocessor's LookAhead method, because 294 /// the Parser always has one token lexed that the preprocessor doesn't. 295 /// 296 const Token &GetLookAheadToken(unsigned N) { 297 if (N == 0 || Tok.is(tok::eof)) return Tok; 298 return PP.LookAhead(N-1); 299 } 300 301 /// NextToken - This peeks ahead one token and returns it without 302 /// consuming it. 303 const Token &NextToken() { 304 return PP.LookAhead(0); 305 } 306 307 /// TryAnnotateTypeOrScopeToken - If the current token position is on a 308 /// typename (possibly qualified in C++) or a C++ scope specifier not followed 309 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens 310 /// with a single annotation token representing the typename or C++ scope 311 /// respectively. 312 /// This simplifies handling of C++ scope specifiers and allows efficient 313 /// backtracking without the need to re-parse and resolve nested-names and 314 /// typenames. 315 /// It will mainly be called when we expect to treat identifiers as typenames 316 /// (if they are typenames). For example, in C we do not expect identifiers 317 /// inside expressions to be treated as typenames so it will not be called 318 /// for expressions in C. 319 /// 320 /// This returns true if the token was annotated. 321 bool TryAnnotateTypeOrScopeToken(bool EnteringContext = false); 322 323 /// TryAnnotateCXXScopeToken - Like TryAnnotateTypeOrScopeToken but only 324 /// annotates C++ scope specifiers. This returns true if the token was 325 /// annotated. 326 bool TryAnnotateCXXScopeToken(bool EnteringContext = false); 327 328 /// TentativeParsingAction - An object that is used as a kind of "tentative 329 /// parsing transaction". It gets instantiated to mark the token position and 330 /// after the token consumption is done, Commit() or Revert() is called to 331 /// either "commit the consumed tokens" or revert to the previously marked 332 /// token position. Example: 333 /// 334 /// TentativeParsingAction TPA; 335 /// ConsumeToken(); 336 /// .... 337 /// TPA.Revert(); 338 /// 339 class TentativeParsingAction { 340 Parser &P; 341 Token PrevTok; 342 bool isActive; 343 344 public: 345 explicit TentativeParsingAction(Parser& p) : P(p) { 346 PrevTok = P.Tok; 347 P.PP.EnableBacktrackAtThisPos(); 348 isActive = true; 349 } 350 void Commit() { 351 assert(isActive && "Parsing action was finished!"); 352 P.PP.CommitBacktrackedTokens(); 353 isActive = false; 354 } 355 void Revert() { 356 assert(isActive && "Parsing action was finished!"); 357 P.PP.Backtrack(); 358 P.Tok = PrevTok; 359 isActive = false; 360 } 361 ~TentativeParsingAction() { 362 assert(!isActive && "Forgot to call Commit or Revert!"); 363 } 364 }; 365 366 367 /// MatchRHSPunctuation - For punctuation with a LHS and RHS (e.g. '['/']'), 368 /// this helper function matches and consumes the specified RHS token if 369 /// present. If not present, it emits the specified diagnostic indicating 370 /// that the parser failed to match the RHS of the token at LHSLoc. LHSName 371 /// should be the name of the unmatched LHS token. This returns the location 372 /// of the consumed token. 373 SourceLocation MatchRHSPunctuation(tok::TokenKind RHSTok, 374 SourceLocation LHSLoc); 375 376 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the 377 /// input. If so, it is consumed and false is returned. 378 /// 379 /// If the input is malformed, this emits the specified diagnostic. Next, if 380 /// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is 381 /// returned. 382 bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag, 383 const char *DiagMsg = "", 384 tok::TokenKind SkipToTok = tok::unknown); 385 386 //===--------------------------------------------------------------------===// 387 // Scope manipulation 388 389 /// ParseScope - Introduces a new scope for parsing. The kind of 390 /// scope is determined by ScopeFlags. Objects of this type should 391 /// be created on the stack to coincide with the position where the 392 /// parser enters the new scope, and this object's constructor will 393 /// create that new scope. Similarly, once the object is destroyed 394 /// the parser will exit the scope. 395 class ParseScope { 396 Parser *Self; 397 ParseScope(const ParseScope&); // do not implement 398 ParseScope& operator=(const ParseScope&); // do not implement 399 400 public: 401 // ParseScope - Construct a new object to manage a scope in the 402 // parser Self where the new Scope is created with the flags 403 // ScopeFlags, but only when ManageScope is true (the default). If 404 // ManageScope is false, this object does nothing. 405 ParseScope(Parser *Self, unsigned ScopeFlags, bool ManageScope = true) 406 : Self(Self) { 407 if (ManageScope) 408 Self->EnterScope(ScopeFlags); 409 else 410 this->Self = 0; 411 } 412 413 // Exit - Exit the scope associated with this object now, rather 414 // than waiting until the object is destroyed. 415 void Exit() { 416 if (Self) { 417 Self->ExitScope(); 418 Self = 0; 419 } 420 } 421 422 ~ParseScope() { 423 Exit(); 424 } 425 }; 426 427 /// EnterScope - Start a new scope. 428 void EnterScope(unsigned ScopeFlags); 429 430 /// ExitScope - Pop a scope off the scope stack. 431 void ExitScope(); 432 433 //===--------------------------------------------------------------------===// 434 // Diagnostic Emission and Error recovery. 435 436 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); 437 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); 438 439 void SuggestParentheses(SourceLocation Loc, unsigned DK, 440 SourceRange ParenRange); 441 442 /// SkipUntil - Read tokens until we get to the specified token, then consume 443 /// it (unless DontConsume is true). Because we cannot guarantee that the 444 /// token will ever occur, this skips to the next token, or to some likely 445 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';' 446 /// character. 447 /// 448 /// If SkipUntil finds the specified token, it returns true, otherwise it 449 /// returns false. 450 bool SkipUntil(tok::TokenKind T, bool StopAtSemi = true, 451 bool DontConsume = false) { 452 return SkipUntil(&T, 1, StopAtSemi, DontConsume); 453 } 454 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, bool StopAtSemi = true, 455 bool DontConsume = false) { 456 tok::TokenKind TokArray[] = {T1, T2}; 457 return SkipUntil(TokArray, 2, StopAtSemi, DontConsume); 458 } 459 bool SkipUntil(const tok::TokenKind *Toks, unsigned NumToks, 460 bool StopAtSemi = true, bool DontConsume = false); 461 462 //===--------------------------------------------------------------------===// 463 // Lexing and parsing of C++ inline methods. 464 465 struct LexedMethod { 466 Action::DeclPtrTy D; 467 CachedTokens Toks; 468 469 /// \brief Whether this member function had an associated template 470 /// scope. When true, D is a template declaration. 471 /// othewise, it is a member function declaration. 472 bool TemplateScope; 473 474 explicit LexedMethod(Action::DeclPtrTy MD) : D(MD), TemplateScope(false) {} 475 }; 476 477 /// LateParsedDefaultArgument - Keeps track of a parameter that may 478 /// have a default argument that cannot be parsed yet because it 479 /// occurs within a member function declaration inside the class 480 /// (C++ [class.mem]p2). 481 struct LateParsedDefaultArgument { 482 explicit LateParsedDefaultArgument(Action::DeclPtrTy P, 483 CachedTokens *Toks = 0) 484 : Param(P), Toks(Toks) { } 485 486 /// Param - The parameter declaration for this parameter. 487 Action::DeclPtrTy Param; 488 489 /// Toks - The sequence of tokens that comprises the default 490 /// argument expression, not including the '=' or the terminating 491 /// ')' or ','. This will be NULL for parameters that have no 492 /// default argument. 493 CachedTokens *Toks; 494 }; 495 496 /// LateParsedMethodDeclaration - A method declaration inside a class that 497 /// contains at least one entity whose parsing needs to be delayed 498 /// until the class itself is completely-defined, such as a default 499 /// argument (C++ [class.mem]p2). 500 struct LateParsedMethodDeclaration { 501 explicit LateParsedMethodDeclaration(Action::DeclPtrTy M) 502 : Method(M), TemplateScope(false) { } 503 504 /// Method - The method declaration. 505 Action::DeclPtrTy Method; 506 507 /// \brief Whether this member function had an associated template 508 /// scope. When true, D is a template declaration. 509 /// othewise, it is a member function declaration. 510 bool TemplateScope; 511 512 /// DefaultArgs - Contains the parameters of the function and 513 /// their default arguments. At least one of the parameters will 514 /// have a default argument, but all of the parameters of the 515 /// method will be stored so that they can be reintroduced into 516 /// scope at the appropriate times. 517 llvm::SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; 518 }; 519 520 /// LateParsedMethodDecls - During parsing of a top (non-nested) C++ 521 /// class, its method declarations that contain parts that won't be 522 /// parsed until after the definiton is completed (C++ [class.mem]p2), 523 /// the method declarations will be stored here with the tokens that 524 /// will be parsed to create those entities. 525 typedef std::list<LateParsedMethodDeclaration> LateParsedMethodDecls; 526 527 /// LexedMethodsForTopClass - During parsing of a top (non-nested) C++ class, 528 /// its inline method definitions and the inline method definitions of its 529 /// nested classes are lexed and stored here. 530 typedef std::list<LexedMethod> LexedMethodsForTopClass; 531 532 /// \brief Representation of a class that has been parsed, including 533 /// any member function declarations or definitions that need to be 534 /// parsed after the corresponding top-level class is complete. 535 struct ParsingClass { 536 ParsingClass(DeclPtrTy TagOrTemplate, bool TopLevelClass) 537 : TopLevelClass(TopLevelClass), TemplateScope(false), 538 TagOrTemplate(TagOrTemplate) { } 539 540 /// \brief Whether this is a "top-level" class, meaning that it is 541 /// not nested within another class. 542 bool TopLevelClass : 1; 543 544 /// \brief Whether this class had an associated template 545 /// scope. When true, TagOrTemplate is a template declaration; 546 /// othewise, it is a tag declaration. 547 bool TemplateScope : 1; 548 549 /// \brief The class or class template whose definition we are parsing. 550 DeclPtrTy TagOrTemplate; 551 552 /// MethodDecls - Method declarations that contain pieces whose 553 /// parsing will be delayed until the class is fully defined. 554 LateParsedMethodDecls MethodDecls; 555 556 /// MethodDefs - Methods whose definitions will be parsed once the 557 /// class has been fully defined. 558 LexedMethodsForTopClass MethodDefs; 559 560 /// \brief Nested classes inside this class. 561 llvm::SmallVector<ParsingClass*, 4> NestedClasses; 562 }; 563 564 /// \brief The stack of classes that is currently being 565 /// parsed. Nested and local classes will be pushed onto this stack 566 /// when they are parsed, and removed afterward. 567 std::stack<ParsingClass *> ClassStack; 568 569 ParsingClass &getCurrentClass() { 570 assert(!ClassStack.empty() && "No lexed method stacks!"); 571 return *ClassStack.top(); 572 } 573 574 /// \brief RAII object used to inform the actions that we're 575 /// currently parsing a declaration. This is active when parsing a 576 /// variable's initializer, but not when parsing the body of a 577 /// class or function definition. 578 class ParsingDeclRAIIObject { 579 Action &Actions; 580 Action::ParsingDeclStackState State; 581 bool Popped; 582 583 public: 584 ParsingDeclRAIIObject(Parser &P) : Actions(P.Actions) { 585 push(); 586 } 587 588 ~ParsingDeclRAIIObject() { 589 abort(); 590 } 591 592 /// Resets the RAII object for a new declaration. 593 void reset() { 594 abort(); 595 push(); 596 } 597 598 /// Signals that the context was completed without an appropriate 599 /// declaration being parsed. 600 void abort() { 601 pop(DeclPtrTy()); 602 } 603 604 void complete(DeclPtrTy D) { 605 assert(!Popped && "ParsingDeclaration has already been popped!"); 606 pop(D); 607 } 608 609 private: 610 void push() { 611 State = Actions.PushParsingDeclaration(); 612 Popped = false; 613 } 614 615 void pop(DeclPtrTy D) { 616 if (!Popped) { 617 Actions.PopParsingDeclaration(State, D); 618 Popped = true; 619 } 620 } 621 }; 622 623 /// A class for parsing a DeclSpec. 624 class ParsingDeclSpec : public DeclSpec { 625 ParsingDeclRAIIObject ParsingRAII; 626 627 public: 628 ParsingDeclSpec(Parser &P) : ParsingRAII(P) { 629 } 630 631 void complete(DeclPtrTy D) { 632 ParsingRAII.complete(D); 633 } 634 635 void abort() { 636 ParsingRAII.abort(); 637 } 638 }; 639 640 /// A class for parsing a declarator. 641 class ParsingDeclarator : public Declarator { 642 ParsingDeclRAIIObject ParsingRAII; 643 644 public: 645 ParsingDeclarator(Parser &P, const ParsingDeclSpec &DS, TheContext C) 646 : Declarator(DS, C), ParsingRAII(P) { 647 } 648 649 const ParsingDeclSpec &getDeclSpec() const { 650 return static_cast<const ParsingDeclSpec&>(Declarator::getDeclSpec()); 651 } 652 653 ParsingDeclSpec &getMutableDeclSpec() const { 654 return const_cast<ParsingDeclSpec&>(getDeclSpec()); 655 } 656 657 void clear() { 658 Declarator::clear(); 659 ParsingRAII.reset(); 660 } 661 662 void complete(DeclPtrTy D) { 663 ParsingRAII.complete(D); 664 } 665 }; 666 667 /// \brief RAII object used to 668 class ParsingClassDefinition { 669 Parser &P; 670 bool Popped; 671 672 public: 673 ParsingClassDefinition(Parser &P, DeclPtrTy TagOrTemplate, bool TopLevelClass) 674 : P(P), Popped(false) { 675 P.PushParsingClass(TagOrTemplate, TopLevelClass); 676 } 677 678 /// \brief Pop this class of the stack. 679 void Pop() { 680 assert(!Popped && "Nested class has already been popped"); 681 Popped = true; 682 P.PopParsingClass(); 683 } 684 685 ~ParsingClassDefinition() { 686 if (!Popped) 687 P.PopParsingClass(); 688 } 689 }; 690 691 /// \brief Contains information about any template-specific 692 /// information that has been parsed prior to parsing declaration 693 /// specifiers. 694 struct ParsedTemplateInfo { 695 ParsedTemplateInfo() 696 : Kind(NonTemplate), TemplateParams(0), TemplateLoc() { } 697 698 ParsedTemplateInfo(TemplateParameterLists *TemplateParams, 699 bool isSpecialization, 700 bool lastParameterListWasEmpty = false) 701 : Kind(isSpecialization? ExplicitSpecialization : Template), 702 TemplateParams(TemplateParams), 703 LastParameterListWasEmpty(lastParameterListWasEmpty) { } 704 705 explicit ParsedTemplateInfo(SourceLocation ExternLoc, 706 SourceLocation TemplateLoc) 707 : Kind(ExplicitInstantiation), TemplateParams(0), 708 ExternLoc(ExternLoc), TemplateLoc(TemplateLoc), 709 LastParameterListWasEmpty(false){ } 710 711 /// \brief The kind of template we are parsing. 712 enum { 713 /// \brief We are not parsing a template at all. 714 NonTemplate = 0, 715 /// \brief We are parsing a template declaration. 716 Template, 717 /// \brief We are parsing an explicit specialization. 718 ExplicitSpecialization, 719 /// \brief We are parsing an explicit instantiation. 720 ExplicitInstantiation 721 } Kind; 722 723 /// \brief The template parameter lists, for template declarations 724 /// and explicit specializations. 725 TemplateParameterLists *TemplateParams; 726 727 /// \brief The location of the 'extern' keyword, if any, for an explicit 728 /// instantiation 729 SourceLocation ExternLoc; 730 731 /// \brief The location of the 'template' keyword, for an explicit 732 /// instantiation. 733 SourceLocation TemplateLoc; 734 735 /// \brief Whether the last template parameter list was empty. 736 bool LastParameterListWasEmpty; 737 }; 738 739 void PushParsingClass(DeclPtrTy TagOrTemplate, bool TopLevelClass); 740 void DeallocateParsedClasses(ParsingClass *Class); 741 void PopParsingClass(); 742 743 DeclPtrTy ParseCXXInlineMethodDef(AccessSpecifier AS, Declarator &D, 744 const ParsedTemplateInfo &TemplateInfo); 745 void ParseLexedMethodDeclarations(ParsingClass &Class); 746 void ParseLexedMethodDefs(ParsingClass &Class); 747 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, 748 CachedTokens &Toks, 749 tok::TokenKind EarlyAbortIf = tok::unknown, 750 bool ConsumeFinalToken = true); 751 752 //===--------------------------------------------------------------------===// 753 // C99 6.9: External Definitions. 754 DeclGroupPtrTy ParseExternalDeclaration(); 755 bool isDeclarationAfterDeclarator(); 756 bool isStartOfFunctionDefinition(); 757 DeclGroupPtrTy ParseDeclarationOrFunctionDefinition( 758 AccessSpecifier AS = AS_none); 759 760 DeclPtrTy ParseFunctionDefinition(ParsingDeclarator &D, 761 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); 762 void ParseKNRParamDeclarations(Declarator &D); 763 // EndLoc, if non-NULL, is filled with the location of the last token of 764 // the simple-asm. 765 OwningExprResult ParseSimpleAsm(SourceLocation *EndLoc = 0); 766 OwningExprResult ParseAsmStringLiteral(); 767 768 // Objective-C External Declarations 769 DeclPtrTy ParseObjCAtDirectives(); 770 DeclPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); 771 DeclPtrTy ParseObjCAtInterfaceDeclaration(SourceLocation atLoc, 772 AttributeList *prefixAttrs = 0); 773 void ParseObjCClassInstanceVariables(DeclPtrTy interfaceDecl, 774 SourceLocation atLoc); 775 bool ParseObjCProtocolReferences(llvm::SmallVectorImpl<Action::DeclPtrTy> &P, 776 llvm::SmallVectorImpl<SourceLocation> &PLocs, 777 bool WarnOnDeclarations, 778 SourceLocation &LAngleLoc, 779 SourceLocation &EndProtoLoc); 780 void ParseObjCInterfaceDeclList(DeclPtrTy interfaceDecl, 781 tok::ObjCKeywordKind contextKey); 782 DeclPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, 783 AttributeList *prefixAttrs = 0); 784 785 DeclPtrTy ObjCImpDecl; 786 787 DeclPtrTy ParseObjCAtImplementationDeclaration(SourceLocation atLoc); 788 DeclPtrTy ParseObjCAtEndDeclaration(SourceLocation atLoc); 789 DeclPtrTy ParseObjCAtAliasDeclaration(SourceLocation atLoc); 790 DeclPtrTy ParseObjCPropertySynthesize(SourceLocation atLoc); 791 DeclPtrTy ParseObjCPropertyDynamic(SourceLocation atLoc); 792 793 IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); 794 // Definitions for Objective-c context sensitive keywords recognition. 795 enum ObjCTypeQual { 796 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, 797 objc_NumQuals 798 }; 799 IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; 800 801 bool isTokIdentifier_in() const; 802 803 TypeTy *ParseObjCTypeName(ObjCDeclSpec &DS); 804 void ParseObjCMethodRequirement(); 805 DeclPtrTy ParseObjCMethodPrototype(DeclPtrTy classOrCat, 806 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword); 807 DeclPtrTy ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, 808 DeclPtrTy classDecl, 809 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword); 810 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); 811 812 DeclPtrTy ParseObjCMethodDefinition(); 813 814 //===--------------------------------------------------------------------===// 815 // C99 6.5: Expressions. 816 817 OwningExprResult ParseExpression(); 818 OwningExprResult ParseConstantExpression(); 819 // Expr that doesn't include commas. 820 OwningExprResult ParseAssignmentExpression(); 821 822 OwningExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); 823 824 OwningExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); 825 826 OwningExprResult ParseRHSOfBinaryExpression(OwningExprResult LHS, 827 unsigned MinPrec); 828 OwningExprResult ParseCastExpression(bool isUnaryExpression, 829 bool isAddressOfOperand, 830 bool &NotCastExpr, 831 bool parseParenAsExprList); 832 OwningExprResult ParseCastExpression(bool isUnaryExpression, 833 bool isAddressOfOperand = false, 834 bool parseParenAsExprList = false); 835 OwningExprResult ParsePostfixExpressionSuffix(OwningExprResult LHS); 836 OwningExprResult ParseSizeofAlignofExpression(); 837 OwningExprResult ParseBuiltinPrimaryExpression(); 838 839 OwningExprResult ParseExprAfterTypeofSizeofAlignof(const Token &OpTok, 840 bool &isCastExpr, 841 TypeTy *&CastTy, 842 SourceRange &CastRange); 843 844 static const unsigned ExprListSize = 12; 845 typedef llvm::SmallVector<ExprTy*, ExprListSize> ExprListTy; 846 typedef llvm::SmallVector<SourceLocation, ExprListSize> CommaLocsTy; 847 848 /// ParseExpressionList - Used for C/C++ (argument-)expression-list. 849 bool ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs, 850 void (Action::*Completer)(Scope *S, void *Data, 851 ExprTy **Args, 852 unsigned NumArgs) = 0, 853 void *Data = 0); 854 855 /// ParenParseOption - Control what ParseParenExpression will parse. 856 enum ParenParseOption { 857 SimpleExpr, // Only parse '(' expression ')' 858 CompoundStmt, // Also allow '(' compound-statement ')' 859 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' 860 CastExpr // Also allow '(' type-name ')' <anything> 861 }; 862 OwningExprResult ParseParenExpression(ParenParseOption &ExprType, 863 bool stopIfCastExpr, 864 bool parseAsExprList, 865 TypeTy *&CastTy, 866 SourceLocation &RParenLoc); 867 868 OwningExprResult ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, 869 TypeTy *&CastTy, 870 SourceLocation LParenLoc, 871 SourceLocation &RParenLoc); 872 873 OwningExprResult ParseCompoundLiteralExpression(TypeTy *Ty, 874 SourceLocation LParenLoc, 875 SourceLocation RParenLoc); 876 877 OwningExprResult ParseStringLiteralExpression(); 878 879 //===--------------------------------------------------------------------===// 880 // C++ Expressions 881 OwningExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); 882 883 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, 884 TypeTy *ObjectType, 885 bool EnteringContext); 886 887 //===--------------------------------------------------------------------===// 888 // C++ 5.2p1: C++ Casts 889 OwningExprResult ParseCXXCasts(); 890 891 //===--------------------------------------------------------------------===// 892 // C++ 5.2p1: C++ Type Identification 893 OwningExprResult ParseCXXTypeid(); 894 895 //===--------------------------------------------------------------------===// 896 // C++ 9.3.2: C++ 'this' pointer 897 OwningExprResult ParseCXXThis(); 898 899 //===--------------------------------------------------------------------===// 900 // C++ 15: C++ Throw Expression 901 OwningExprResult ParseThrowExpression(); 902 // EndLoc is filled with the location of the last token of the specification. 903 bool ParseExceptionSpecification(SourceLocation &EndLoc, 904 llvm::SmallVector<TypeTy*, 2> &Exceptions, 905 llvm::SmallVector<SourceRange, 2> &Ranges, 906 bool &hasAnyExceptionSpec); 907 908 //===--------------------------------------------------------------------===// 909 // C++ 2.13.5: C++ Boolean Literals 910 OwningExprResult ParseCXXBoolLiteral(); 911 912 //===--------------------------------------------------------------------===// 913 // C++ 5.2.3: Explicit type conversion (functional notation) 914 OwningExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); 915 916 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. 917 /// This should only be called when the current token is known to be part of 918 /// simple-type-specifier. 919 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); 920 921 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS); 922 923 //===--------------------------------------------------------------------===// 924 // C++ 5.3.4 and 5.3.5: C++ new and delete 925 bool ParseExpressionListOrTypeId(ExprListTy &Exprs, Declarator &D); 926 void ParseDirectNewDeclarator(Declarator &D); 927 OwningExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); 928 OwningExprResult ParseCXXDeleteExpression(bool UseGlobal, 929 SourceLocation Start); 930 931 //===--------------------------------------------------------------------===// 932 // C++ if/switch/while/for condition expression. 933 OwningExprResult ParseCXXCondition(); 934 935 //===--------------------------------------------------------------------===// 936 // C++ types 937 938 //===--------------------------------------------------------------------===// 939 // C99 6.7.8: Initialization. 940 941 /// ParseInitializer 942 /// initializer: [C99 6.7.8] 943 /// assignment-expression 944 /// '{' ... 945 OwningExprResult ParseInitializer() { 946 if (Tok.isNot(tok::l_brace)) 947 return ParseAssignmentExpression(); 948 return ParseBraceInitializer(); 949 } 950 OwningExprResult ParseBraceInitializer(); 951 OwningExprResult ParseInitializerWithPotentialDesignator(); 952 953 //===--------------------------------------------------------------------===// 954 // clang Expressions 955 956 OwningExprResult ParseBlockLiteralExpression(); // ^{...} 957 958 //===--------------------------------------------------------------------===// 959 // Objective-C Expressions 960 961 bool isTokObjCMessageIdentifierReceiver() const { 962 if (!Tok.is(tok::identifier)) 963 return false; 964 965 IdentifierInfo *II = Tok.getIdentifierInfo(); 966 if (Actions.getTypeName(*II, Tok.getLocation(), CurScope)) 967 return true; 968 969 return II == Ident_super; 970 } 971 972 OwningExprResult ParseObjCAtExpression(SourceLocation AtLocation); 973 OwningExprResult ParseObjCStringLiteral(SourceLocation AtLoc); 974 OwningExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); 975 OwningExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); 976 OwningExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); 977 OwningExprResult ParseObjCMessageExpression(); 978 OwningExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, 979 SourceLocation NameLoc, 980 IdentifierInfo *ReceiverName, 981 ExprArg ReceiverExpr); 982 OwningExprResult ParseAssignmentExprWithObjCMessageExprStart( 983 SourceLocation LBracloc, SourceLocation NameLoc, 984 IdentifierInfo *ReceiverName, ExprArg ReceiverExpr); 985 986 //===--------------------------------------------------------------------===// 987 // C99 6.8: Statements and Blocks. 988 989 OwningStmtResult ParseStatement() { 990 return ParseStatementOrDeclaration(true); 991 } 992 OwningStmtResult ParseStatementOrDeclaration(bool OnlyStatement = false); 993 OwningStmtResult ParseLabeledStatement(); 994 OwningStmtResult ParseCaseStatement(); 995 OwningStmtResult ParseDefaultStatement(); 996 OwningStmtResult ParseCompoundStatement(bool isStmtExpr = false); 997 OwningStmtResult ParseCompoundStatementBody(bool isStmtExpr = false); 998 bool ParseParenExprOrCondition(OwningExprResult &CondExp, 999 bool OnlyAllowCondition = false, 1000 SourceLocation *LParenLoc = 0, 1001 SourceLocation *RParenLoc = 0); 1002 OwningStmtResult ParseIfStatement(); 1003 OwningStmtResult ParseSwitchStatement(); 1004 OwningStmtResult ParseWhileStatement(); 1005 OwningStmtResult ParseDoStatement(); 1006 OwningStmtResult ParseForStatement(); 1007 OwningStmtResult ParseGotoStatement(); 1008 OwningStmtResult ParseContinueStatement(); 1009 OwningStmtResult ParseBreakStatement(); 1010 OwningStmtResult ParseReturnStatement(); 1011 OwningStmtResult ParseAsmStatement(bool &msAsm); 1012 OwningStmtResult FuzzyParseMicrosoftAsmStatement(); 1013 bool ParseAsmOperandsOpt(llvm::SmallVectorImpl<std::string> &Names, 1014 llvm::SmallVectorImpl<ExprTy*> &Constraints, 1015 llvm::SmallVectorImpl<ExprTy*> &Exprs); 1016 1017 //===--------------------------------------------------------------------===// 1018 // C++ 6: Statements and Blocks 1019 1020 OwningStmtResult ParseCXXTryBlock(); 1021 OwningStmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc); 1022 OwningStmtResult ParseCXXCatchBlock(); 1023 1024 //===--------------------------------------------------------------------===// 1025 // Objective-C Statements 1026 1027 OwningStmtResult ParseObjCAtStatement(SourceLocation atLoc); 1028 OwningStmtResult ParseObjCTryStmt(SourceLocation atLoc); 1029 OwningStmtResult ParseObjCThrowStmt(SourceLocation atLoc); 1030 OwningStmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); 1031 1032 1033 //===--------------------------------------------------------------------===// 1034 // C99 6.7: Declarations. 1035 1036 /// A context for parsing declaration specifiers. TODO: flesh this 1037 /// out, there are other significant restrictions on specifiers than 1038 /// would be best implemented in the parser. 1039 enum DeclSpecContext { 1040 DSC_normal, // normal context 1041 DSC_class // class context, enables 'friend' 1042 }; 1043 1044 DeclGroupPtrTy ParseDeclaration(unsigned Context, SourceLocation &DeclEnd); 1045 DeclGroupPtrTy ParseSimpleDeclaration(unsigned Context, 1046 SourceLocation &DeclEnd); 1047 DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context, 1048 bool AllowFunctionDefinitions, 1049 SourceLocation *DeclEnd = 0); 1050 DeclPtrTy ParseDeclarationAfterDeclarator(Declarator &D, 1051 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); 1052 DeclPtrTy ParseFunctionStatementBody(DeclPtrTy Decl); 1053 DeclPtrTy ParseFunctionTryBlock(DeclPtrTy Decl); 1054 1055 bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, 1056 const ParsedTemplateInfo &TemplateInfo, 1057 AccessSpecifier AS); 1058 void ParseDeclarationSpecifiers(DeclSpec &DS, 1059 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), 1060 AccessSpecifier AS = AS_none, 1061 DeclSpecContext DSC = DSC_normal); 1062 bool ParseOptionalTypeSpecifier(DeclSpec &DS, bool &isInvalid, 1063 const char *&PrevSpec, 1064 unsigned &DiagID, 1065 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); 1066 1067 void ParseSpecifierQualifierList(DeclSpec &DS); 1068 1069 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS); 1070 1071 void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, 1072 AccessSpecifier AS = AS_none); 1073 void ParseEnumBody(SourceLocation StartLoc, DeclPtrTy TagDecl); 1074 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType, 1075 DeclPtrTy TagDecl); 1076 1077 struct FieldCallback { 1078 virtual DeclPtrTy invoke(FieldDeclarator &Field) = 0; 1079 virtual ~FieldCallback() {} 1080 1081 private: 1082 virtual void _anchor(); 1083 }; 1084 1085 void ParseStructDeclaration(DeclSpec &DS, FieldCallback &Callback); 1086 1087 bool isDeclarationSpecifier(); 1088 bool isTypeSpecifierQualifier(); 1089 bool isTypeQualifier() const; 1090 1091 /// isDeclarationStatement - Disambiguates between a declaration or an 1092 /// expression statement, when parsing function bodies. 1093 /// Returns true for declaration, false for expression. 1094 bool isDeclarationStatement() { 1095 if (getLang().CPlusPlus) 1096 return isCXXDeclarationStatement(); 1097 return isDeclarationSpecifier(); 1098 } 1099 1100 /// isSimpleDeclaration - Disambiguates between a declaration or an 1101 /// expression, mainly used for the C 'clause-1' or the C++ 1102 // 'for-init-statement' part of a 'for' statement. 1103 /// Returns true for declaration, false for expression. 1104 bool isSimpleDeclaration() { 1105 if (getLang().CPlusPlus) 1106 return isCXXSimpleDeclaration(); 1107 return isDeclarationSpecifier(); 1108 } 1109 1110 /// \brief Specifies the context in which type-id/expression 1111 /// disambiguation will occur. 1112 enum TentativeCXXTypeIdContext { 1113 TypeIdInParens, 1114 TypeIdAsTemplateArgument 1115 }; 1116 1117 1118 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know 1119 /// whether the parens contain an expression or a type-id. 1120 /// Returns true for a type-id and false for an expression. 1121 bool isTypeIdInParens(bool &isAmbiguous) { 1122 if (getLang().CPlusPlus) 1123 return isCXXTypeId(TypeIdInParens, isAmbiguous); 1124 isAmbiguous = false; 1125 return isTypeSpecifierQualifier(); 1126 } 1127 bool isTypeIdInParens() { 1128 bool isAmbiguous; 1129 return isTypeIdInParens(isAmbiguous); 1130 } 1131 1132 /// isCXXDeclarationStatement - C++-specialized function that disambiguates 1133 /// between a declaration or an expression statement, when parsing function 1134 /// bodies. Returns true for declaration, false for expression. 1135 bool isCXXDeclarationStatement(); 1136 1137 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates 1138 /// between a simple-declaration or an expression-statement. 1139 /// If during the disambiguation process a parsing error is encountered, 1140 /// the function returns true to let the declaration parsing code handle it. 1141 /// Returns false if the statement is disambiguated as expression. 1142 bool isCXXSimpleDeclaration(); 1143 1144 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or 1145 /// a constructor-style initializer, when parsing declaration statements. 1146 /// Returns true for function declarator and false for constructor-style 1147 /// initializer. If 'warnIfAmbiguous' is true a warning will be emitted to 1148 /// indicate that the parens were disambiguated as function declarator. 1149 /// If during the disambiguation process a parsing error is encountered, 1150 /// the function returns true to let the declaration parsing code handle it. 1151 bool isCXXFunctionDeclarator(bool warnIfAmbiguous); 1152 1153 /// isCXXConditionDeclaration - Disambiguates between a declaration or an 1154 /// expression for a condition of a if/switch/while/for statement. 1155 /// If during the disambiguation process a parsing error is encountered, 1156 /// the function returns true to let the declaration parsing code handle it. 1157 bool isCXXConditionDeclaration(); 1158 1159 bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous); 1160 bool isCXXTypeId(TentativeCXXTypeIdContext Context) { 1161 bool isAmbiguous; 1162 return isCXXTypeId(Context, isAmbiguous); 1163 } 1164 1165 /// TPResult - Used as the result value for functions whose purpose is to 1166 /// disambiguate C++ constructs by "tentatively parsing" them. 1167 /// This is a class instead of a simple enum because the implicit enum-to-bool 1168 /// conversions may cause subtle bugs. 1169 class TPResult { 1170 enum Result { 1171 TPR_true, 1172 TPR_false, 1173 TPR_ambiguous, 1174 TPR_error 1175 }; 1176 Result Res; 1177 TPResult(Result result) : Res(result) {} 1178 public: 1179 static TPResult True() { return TPR_true; } 1180 static TPResult False() { return TPR_false; } 1181 static TPResult Ambiguous() { return TPR_ambiguous; } 1182 static TPResult Error() { return TPR_error; } 1183 1184 bool operator==(const TPResult &RHS) const { return Res == RHS.Res; } 1185 bool operator!=(const TPResult &RHS) const { return Res != RHS.Res; } 1186 }; 1187 1188 /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a 1189 /// declaration specifier, TPResult::False() if it is not, 1190 /// TPResult::Ambiguous() if it could be either a decl-specifier or a 1191 /// function-style cast, and TPResult::Error() if a parsing error was 1192 /// encountered. 1193 /// Doesn't consume tokens. 1194 TPResult isCXXDeclarationSpecifier(); 1195 1196 // "Tentative parsing" functions, used for disambiguation. If a parsing error 1197 // is encountered they will return TPResult::Error(). 1198 // Returning TPResult::True()/False() indicates that the ambiguity was 1199 // resolved and tentative parsing may stop. TPResult::Ambiguous() indicates 1200 // that more tentative parsing is necessary for disambiguation. 1201 // They all consume tokens, so backtracking should be used after calling them. 1202 1203 TPResult TryParseDeclarationSpecifier(); 1204 TPResult TryParseSimpleDeclaration(); 1205 TPResult TryParseTypeofSpecifier(); 1206 TPResult TryParseInitDeclaratorList(); 1207 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true); 1208 TPResult TryParseParameterDeclarationClause(); 1209 TPResult TryParseFunctionDeclarator(); 1210 TPResult TryParseBracketDeclarator(); 1211 1212 TypeResult ParseTypeName(SourceRange *Range = 0); 1213 void ParseBlockId(); 1214 // EndLoc, if non-NULL, is filled with the location of the last token of 1215 // the attribute list. 1216 AttributeList *ParseAttributes(SourceLocation *EndLoc = 0); 1217 AttributeList *ParseMicrosoftDeclSpec(AttributeList* CurrAttr = 0); 1218 AttributeList *ParseMicrosoftTypeAttributes(AttributeList* CurrAttr = 0); 1219 void ParseTypeofSpecifier(DeclSpec &DS); 1220 void ParseDecltypeSpecifier(DeclSpec &DS); 1221 1222 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to 1223 /// enter a new C++ declarator scope and exit it when the function is 1224 /// finished. 1225 class DeclaratorScopeObj { 1226 Parser &P; 1227 CXXScopeSpec &SS; 1228 bool EnteredScope; 1229 public: 1230 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) 1231 : P(p), SS(ss), EnteredScope(false) {} 1232 1233 void EnterDeclaratorScope() { 1234 assert(!EnteredScope && "Already entered the scope!"); 1235 assert(SS.isSet() && "C++ scope was not set!"); 1236 if (P.Actions.ActOnCXXEnterDeclaratorScope(P.CurScope, SS)) 1237 SS.setScopeRep(0); 1238 1239 if (!SS.isInvalid()) 1240 EnteredScope = true; 1241 } 1242 1243 ~DeclaratorScopeObj() { 1244 if (EnteredScope) { 1245 assert(SS.isSet() && "C++ scope was cleared ?"); 1246 P.Actions.ActOnCXXExitDeclaratorScope(P.CurScope, SS); 1247 } 1248 } 1249 }; 1250 1251 /// ParseDeclarator - Parse and verify a newly-initialized declarator. 1252 void ParseDeclarator(Declarator &D); 1253 /// A function that parses a variant of direct-declarator. 1254 typedef void (Parser::*DirectDeclParseFunction)(Declarator&); 1255 void ParseDeclaratorInternal(Declarator &D, 1256 DirectDeclParseFunction DirectDeclParser); 1257 void ParseTypeQualifierListOpt(DeclSpec &DS, bool AttributesAllowed = true); 1258 void ParseDirectDeclarator(Declarator &D); 1259 void ParseParenDeclarator(Declarator &D); 1260 void ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, 1261 AttributeList *AttrList = 0, 1262 bool RequiresArg = false); 1263 void ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc, 1264 Declarator &D); 1265 void ParseBracketDeclarator(Declarator &D); 1266 1267 //===--------------------------------------------------------------------===// 1268 // C++ 7: Declarations [dcl.dcl] 1269 1270 DeclPtrTy ParseNamespace(unsigned Context, SourceLocation &DeclEnd); 1271 DeclPtrTy ParseLinkage(unsigned Context); 1272 DeclPtrTy ParseUsingDirectiveOrDeclaration(unsigned Context, 1273 SourceLocation &DeclEnd); 1274 DeclPtrTy ParseUsingDirective(unsigned Context, SourceLocation UsingLoc, 1275 SourceLocation &DeclEnd); 1276 DeclPtrTy ParseUsingDeclaration(unsigned Context, SourceLocation UsingLoc, 1277 SourceLocation &DeclEnd, 1278 AccessSpecifier AS = AS_none); 1279 DeclPtrTy ParseStaticAssertDeclaration(SourceLocation &DeclEnd); 1280 DeclPtrTy ParseNamespaceAlias(SourceLocation NamespaceLoc, 1281 SourceLocation AliasLoc, IdentifierInfo *Alias, 1282 SourceLocation &DeclEnd); 1283 1284 //===--------------------------------------------------------------------===// 1285 // C++ 9: classes [class] and C structs/unions. 1286 TypeResult ParseClassName(SourceLocation &EndLocation, 1287 const CXXScopeSpec *SS = 0, 1288 bool DestrExpected = false); 1289 void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, 1290 DeclSpec &DS, 1291 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), 1292 AccessSpecifier AS = AS_none); 1293 void ParseCXXMemberSpecification(SourceLocation StartLoc, unsigned TagType, 1294 DeclPtrTy TagDecl); 1295 void ParseCXXClassMemberDeclaration(AccessSpecifier AS, 1296 const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); 1297 void ParseConstructorInitializer(DeclPtrTy ConstructorDecl); 1298 MemInitResult ParseMemInitializer(DeclPtrTy ConstructorDecl); 1299 void HandleMemberFunctionDefaultArgs(Declarator& DeclaratorInfo, 1300 DeclPtrTy ThisDecl); 1301 1302 //===--------------------------------------------------------------------===// 1303 // C++ 10: Derived classes [class.derived] 1304 void ParseBaseClause(DeclPtrTy ClassDecl); 1305 BaseResult ParseBaseSpecifier(DeclPtrTy ClassDecl); 1306 AccessSpecifier getAccessSpecifierIfPresent() const; 1307 1308 bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, 1309 IdentifierInfo *Name, 1310 SourceLocation NameLoc, 1311 bool EnteringContext, 1312 TypeTy *ObjectType, 1313 UnqualifiedId &Id); 1314 bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, 1315 TypeTy *ObjectType, 1316 UnqualifiedId &Result); 1317 bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, 1318 bool AllowDestructorName, 1319 bool AllowConstructorName, 1320 TypeTy *ObjectType, 1321 UnqualifiedId &Result); 1322 1323 //===--------------------------------------------------------------------===// 1324 // C++ 13.5: Overloaded operators [over.oper] 1325 // EndLoc, if non-NULL, is filled with the location of the last token of 1326 // the ID. 1327 OverloadedOperatorKind TryParseOperatorFunctionId(SourceLocation *EndLoc = 0); 1328 TypeTy *ParseConversionFunctionId(SourceLocation *EndLoc = 0); 1329 1330 //===--------------------------------------------------------------------===// 1331 // C++ 14: Templates [temp] 1332 typedef llvm::SmallVector<DeclPtrTy, 4> TemplateParameterList; 1333 1334 // C++ 14.1: Template Parameters [temp.param] 1335 DeclPtrTy ParseDeclarationStartingWithTemplate(unsigned Context, 1336 SourceLocation &DeclEnd, 1337 AccessSpecifier AS = AS_none); 1338 DeclPtrTy ParseTemplateDeclarationOrSpecialization(unsigned Context, 1339 SourceLocation &DeclEnd, 1340 AccessSpecifier AS); 1341 DeclPtrTy ParseSingleDeclarationAfterTemplate( 1342 unsigned Context, 1343 const ParsedTemplateInfo &TemplateInfo, 1344 SourceLocation &DeclEnd, 1345 AccessSpecifier AS=AS_none); 1346 bool ParseTemplateParameters(unsigned Depth, 1347 TemplateParameterList &TemplateParams, 1348 SourceLocation &LAngleLoc, 1349 SourceLocation &RAngleLoc); 1350 bool ParseTemplateParameterList(unsigned Depth, 1351 TemplateParameterList &TemplateParams); 1352 DeclPtrTy ParseTemplateParameter(unsigned Depth, unsigned Position); 1353 DeclPtrTy ParseTypeParameter(unsigned Depth, unsigned Position); 1354 DeclPtrTy ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); 1355 DeclPtrTy ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); 1356 // C++ 14.3: Template arguments [temp.arg] 1357 typedef llvm::SmallVector<void *, 16> TemplateArgList; 1358 typedef llvm::SmallVector<bool, 16> TemplateArgIsTypeList; 1359 typedef llvm::SmallVector<SourceLocation, 16> TemplateArgLocationList; 1360 1361 bool ParseTemplateIdAfterTemplateName(TemplateTy Template, 1362 SourceLocation TemplateNameLoc, 1363 const CXXScopeSpec *SS, 1364 bool ConsumeLastToken, 1365 SourceLocation &LAngleLoc, 1366 TemplateArgList &TemplateArgs, 1367 TemplateArgIsTypeList &TemplateArgIsType, 1368 TemplateArgLocationList &TemplateArgLocations, 1369 SourceLocation &RAngleLoc); 1370 1371 bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, 1372 const CXXScopeSpec *SS, 1373 UnqualifiedId &TemplateName, 1374 SourceLocation TemplateKWLoc = SourceLocation(), 1375 bool AllowTypeAnnotation = true); 1376 void AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS = 0); 1377 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs, 1378 TemplateArgIsTypeList &TemplateArgIsType, 1379 TemplateArgLocationList &TemplateArgLocations); 1380 void *ParseTemplateArgument(bool &ArgIsType); 1381 DeclPtrTy ParseExplicitInstantiation(SourceLocation ExternLoc, 1382 SourceLocation TemplateLoc, 1383 SourceLocation &DeclEnd); 1384 1385 //===--------------------------------------------------------------------===// 1386 // GNU G++: Type Traits [Type-Traits.html in the GCC manual] 1387 OwningExprResult ParseUnaryTypeTrait(); 1388}; 1389 1390} // end namespace clang 1391 1392#endif 1393