Parser.h revision 39a8de10c18365bde7062d8959b7ed525449c561
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/Action.h" 19#include "clang/Parse/DeclSpec.h" 20#include <stack> 21#include <list> 22 23namespace clang { 24 class AttributeList; 25 class PragmaHandler; 26 class Scope; 27 class DiagnosticBuilder; 28 29/// Parser - This implements a parser for the C family of languages. After 30/// parsing units of the grammar, productions are invoked to handle whatever has 31/// been read. 32/// 33class Parser { 34 Preprocessor &PP; 35 36 /// Tok - The current token we are peeking ahead. All parsing methods assume 37 /// that this is valid. 38 Token Tok; 39 40 unsigned short ParenCount, BracketCount, BraceCount; 41 42 /// Actions - These are the callbacks we invoke as we parse various constructs 43 /// in the file. This refers to the common base class between MinimalActions 44 /// and SemaActions for those uses that don't matter. 45 Action &Actions; 46 47 Scope *CurScope; 48 Diagnostic &Diags; 49 50 /// ScopeCache - Cache scopes to reduce malloc traffic. 51 enum { ScopeCacheSize = 16 }; 52 unsigned NumCachedScopes; 53 Scope *ScopeCache[ScopeCacheSize]; 54 55 /// Ident_super - IdentifierInfo for "super", to support fast 56 /// comparison. 57 IdentifierInfo *Ident_super; 58 59 PragmaHandler *PackHandler; 60 61 /// Whether the '>' token acts as an operator or not. This will be 62 /// true except when we are parsing an expression within a C++ 63 /// template argument list, where the '>' closes the template 64 /// argument list. 65 bool GreaterThanIsOperator; 66 67 /// \brief RAII object that makes '>' behave either as an operator 68 /// or as the closing angle bracket for a template argument list. 69 struct GreaterThanIsOperatorScope { 70 bool &GreaterThanIsOperator; 71 bool OldGreaterThanIsOperator; 72 73 GreaterThanIsOperatorScope(bool >IO, bool Val) 74 : GreaterThanIsOperator(GTIO), OldGreaterThanIsOperator(GTIO) { 75 GreaterThanIsOperator = Val; 76 } 77 78 ~GreaterThanIsOperatorScope() { 79 GreaterThanIsOperator = OldGreaterThanIsOperator; 80 } 81 }; 82 83public: 84 Parser(Preprocessor &PP, Action &Actions); 85 ~Parser(); 86 87 const LangOptions &getLang() const { return PP.getLangOptions(); } 88 TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } 89 Action &getActions() const { return Actions; } 90 91 // Type forwarding. All of these are statically 'void*', but they may all be 92 // different actual classes based on the actions in place. 93 typedef Action::ExprTy ExprTy; 94 typedef Action::StmtTy StmtTy; 95 typedef Action::DeclTy DeclTy; 96 typedef Action::TypeTy TypeTy; 97 typedef Action::BaseTy BaseTy; 98 typedef Action::MemInitTy MemInitTy; 99 typedef Action::CXXScopeTy CXXScopeTy; 100 typedef Action::TemplateParamsTy TemplateParamsTy; 101 102 typedef llvm::SmallVector<TemplateParamsTy *, 4> TemplateParameterLists; 103 104 typedef Action::ExprResult ExprResult; 105 typedef Action::StmtResult StmtResult; 106 typedef Action::BaseResult BaseResult; 107 typedef Action::MemInitResult MemInitResult; 108 typedef Action::TypeResult TypeResult; 109 110 typedef Action::OwningExprResult OwningExprResult; 111 typedef Action::OwningStmtResult OwningStmtResult; 112 113 typedef Action::ExprArg ExprArg; 114 typedef Action::MultiStmtArg MultiStmtArg; 115 116 /// Adorns a ExprResult with Actions to make it an OwningExprResult 117 OwningExprResult Owned(ExprResult res) { 118 return OwningExprResult(Actions, res); 119 } 120 /// Adorns a StmtResult with Actions to make it an OwningStmtResult 121 OwningStmtResult Owned(StmtResult res) { 122 return OwningStmtResult(Actions, res); 123 } 124 125 OwningExprResult ExprError() { return OwningExprResult(Actions, true); } 126 OwningStmtResult StmtError() { return OwningStmtResult(Actions, true); } 127 128 OwningExprResult ExprError(const DiagnosticBuilder &) { return ExprError(); } 129 OwningStmtResult StmtError(const DiagnosticBuilder &) { return StmtError(); } 130 131 // Parsing methods. 132 133 /// ParseTranslationUnit - All in one method that initializes parses, and 134 /// shuts down the parser. 135 void ParseTranslationUnit(); 136 137 /// Initialize - Warm up the parser. 138 /// 139 void Initialize(); 140 141 /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if 142 /// the EOF was encountered. 143 bool ParseTopLevelDecl(DeclTy*& Result); 144 145private: 146 //===--------------------------------------------------------------------===// 147 // Low-Level token peeking and consumption methods. 148 // 149 150 /// isTokenParen - Return true if the cur token is '(' or ')'. 151 bool isTokenParen() const { 152 return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren; 153 } 154 /// isTokenBracket - Return true if the cur token is '[' or ']'. 155 bool isTokenBracket() const { 156 return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square; 157 } 158 /// isTokenBrace - Return true if the cur token is '{' or '}'. 159 bool isTokenBrace() const { 160 return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace; 161 } 162 163 /// isTokenStringLiteral - True if this token is a string-literal. 164 /// 165 bool isTokenStringLiteral() const { 166 return Tok.getKind() == tok::string_literal || 167 Tok.getKind() == tok::wide_string_literal; 168 } 169 170 /// ConsumeToken - Consume the current 'peek token' and lex the next one. 171 /// This does not work with all kinds of tokens: strings and specific other 172 /// tokens must be consumed with custom methods below. This returns the 173 /// location of the consumed token. 174 SourceLocation ConsumeToken() { 175 assert(!isTokenStringLiteral() && !isTokenParen() && !isTokenBracket() && 176 !isTokenBrace() && 177 "Should consume special tokens with Consume*Token"); 178 SourceLocation L = Tok.getLocation(); 179 PP.Lex(Tok); 180 return L; 181 } 182 183 /// ConsumeAnyToken - Dispatch to the right Consume* method based on the 184 /// current token type. This should only be used in cases where the type of 185 /// the token really isn't known, e.g. in error recovery. 186 SourceLocation ConsumeAnyToken() { 187 if (isTokenParen()) 188 return ConsumeParen(); 189 else if (isTokenBracket()) 190 return ConsumeBracket(); 191 else if (isTokenBrace()) 192 return ConsumeBrace(); 193 else if (isTokenStringLiteral()) 194 return ConsumeStringToken(); 195 else 196 return ConsumeToken(); 197 } 198 199 /// ConsumeParen - This consume method keeps the paren count up-to-date. 200 /// 201 SourceLocation ConsumeParen() { 202 assert(isTokenParen() && "wrong consume method"); 203 if (Tok.getKind() == tok::l_paren) 204 ++ParenCount; 205 else if (ParenCount) 206 --ParenCount; // Don't let unbalanced )'s drive the count negative. 207 SourceLocation L = Tok.getLocation(); 208 PP.Lex(Tok); 209 return L; 210 } 211 212 /// ConsumeBracket - This consume method keeps the bracket count up-to-date. 213 /// 214 SourceLocation ConsumeBracket() { 215 assert(isTokenBracket() && "wrong consume method"); 216 if (Tok.getKind() == tok::l_square) 217 ++BracketCount; 218 else if (BracketCount) 219 --BracketCount; // Don't let unbalanced ]'s drive the count negative. 220 221 SourceLocation L = Tok.getLocation(); 222 PP.Lex(Tok); 223 return L; 224 } 225 226 /// ConsumeBrace - This consume method keeps the brace count up-to-date. 227 /// 228 SourceLocation ConsumeBrace() { 229 assert(isTokenBrace() && "wrong consume method"); 230 if (Tok.getKind() == tok::l_brace) 231 ++BraceCount; 232 else if (BraceCount) 233 --BraceCount; // Don't let unbalanced }'s drive the count negative. 234 235 SourceLocation L = Tok.getLocation(); 236 PP.Lex(Tok); 237 return L; 238 } 239 240 /// ConsumeStringToken - Consume the current 'peek token', lexing a new one 241 /// and returning the token kind. This method is specific to strings, as it 242 /// handles string literal concatenation, as per C99 5.1.1.2, translation 243 /// phase #6. 244 SourceLocation ConsumeStringToken() { 245 assert(isTokenStringLiteral() && 246 "Should only consume string literals with this method"); 247 SourceLocation L = Tok.getLocation(); 248 PP.Lex(Tok); 249 return L; 250 } 251 252 /// GetLookAheadToken - This peeks ahead N tokens and returns that token 253 /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) 254 /// returns the token after Tok, etc. 255 /// 256 /// Note that this differs from the Preprocessor's LookAhead method, because 257 /// the Parser always has one token lexed that the preprocessor doesn't. 258 /// 259 const Token &GetLookAheadToken(unsigned N) { 260 if (N == 0 || Tok.is(tok::eof)) return Tok; 261 return PP.LookAhead(N-1); 262 } 263 264 /// NextToken - This peeks ahead one token and returns it without 265 /// consuming it. 266 const Token &NextToken() { 267 return PP.LookAhead(0); 268 } 269 270 /// TryAnnotateTypeOrScopeToken - If the current token position is on a 271 /// typename (possibly qualified in C++) or a C++ scope specifier not followed 272 /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens 273 /// with a single annotation token representing the typename or C++ scope 274 /// respectively. 275 /// This simplifies handling of C++ scope specifiers and allows efficient 276 /// backtracking without the need to re-parse and resolve nested-names and 277 /// typenames. 278 /// It will mainly be called when we expect to treat identifiers as typenames 279 /// (if they are typenames). For example, in C we do not expect identifiers 280 /// inside expressions to be treated as typenames so it will not be called 281 /// for expressions in C. 282 /// 283 /// This returns true if the token was annotated. 284 bool TryAnnotateTypeOrScopeToken(); 285 286 /// TryAnnotateCXXScopeToken - Like TryAnnotateTypeOrScopeToken but only 287 /// annotates C++ scope specifiers. This returns true if the token was 288 /// annotated. 289 bool TryAnnotateCXXScopeToken(); 290 291 /// TentativeParsingAction - An object that is used as a kind of "tentative 292 /// parsing transaction". It gets instantiated to mark the token position and 293 /// after the token consumption is done, Commit() or Revert() is called to 294 /// either "commit the consumed tokens" or revert to the previously marked 295 /// token position. Example: 296 /// 297 /// TentativeParsingAction TPA; 298 /// ConsumeToken(); 299 /// .... 300 /// TPA.Revert(); 301 /// 302 class TentativeParsingAction { 303 Parser &P; 304 Token PrevTok; 305 bool isActive; 306 307 public: 308 explicit TentativeParsingAction(Parser& p) : P(p) { 309 PrevTok = P.Tok; 310 P.PP.EnableBacktrackAtThisPos(); 311 isActive = true; 312 } 313 void Commit() { 314 assert(isActive && "Parsing action was finished!"); 315 P.PP.CommitBacktrackedTokens(); 316 isActive = false; 317 } 318 void Revert() { 319 assert(isActive && "Parsing action was finished!"); 320 P.PP.Backtrack(); 321 P.Tok = PrevTok; 322 isActive = false; 323 } 324 ~TentativeParsingAction() { 325 assert(!isActive && "Forgot to call Commit or Revert!"); 326 } 327 }; 328 329 330 /// MatchRHSPunctuation - For punctuation with a LHS and RHS (e.g. '['/']'), 331 /// this helper function matches and consumes the specified RHS token if 332 /// present. If not present, it emits the specified diagnostic indicating 333 /// that the parser failed to match the RHS of the token at LHSLoc. LHSName 334 /// should be the name of the unmatched LHS token. This returns the location 335 /// of the consumed token. 336 SourceLocation MatchRHSPunctuation(tok::TokenKind RHSTok, 337 SourceLocation LHSLoc); 338 339 /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the 340 /// input. If so, it is consumed and false is returned. 341 /// 342 /// If the input is malformed, this emits the specified diagnostic. Next, if 343 /// SkipToTok is specified, it calls SkipUntil(SkipToTok). Finally, true is 344 /// returned. 345 bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag, 346 const char *DiagMsg = "", 347 tok::TokenKind SkipToTok = tok::unknown); 348 349 //===--------------------------------------------------------------------===// 350 // Scope manipulation 351 352 /// ParseScope - Introduces a new scope for parsing. The kind of 353 /// scope is determined by ScopeFlags. Objects of this type should 354 /// be created on the stack to coincide with the position where the 355 /// parser enters the new scope, and this object's constructor will 356 /// create that new scope. Similarly, once the object is destroyed 357 /// the parser will exit the scope. 358 class ParseScope { 359 Parser *Self; 360 ParseScope(const ParseScope&); // do not implement 361 ParseScope& operator=(const ParseScope&); // do not implement 362 363 public: 364 // ParseScope - Construct a new object to manage a scope in the 365 // parser Self where the new Scope is created with the flags 366 // ScopeFlags, but only when ManageScope is true (the default). If 367 // ManageScope is false, this object does nothing. 368 ParseScope(Parser *Self, unsigned ScopeFlags, bool ManageScope = true) 369 : Self(Self) { 370 if (ManageScope) 371 Self->EnterScope(ScopeFlags); 372 else 373 this->Self = 0; 374 } 375 376 // Exit - Exit the scope associated with this object now, rather 377 // than waiting until the object is destroyed. 378 void Exit() { 379 if (Self) { 380 Self->ExitScope(); 381 Self = 0; 382 } 383 } 384 385 ~ParseScope() { 386 Exit(); 387 } 388 }; 389 390 /// EnterScope - Start a new scope. 391 void EnterScope(unsigned ScopeFlags); 392 393 /// ExitScope - Pop a scope off the scope stack. 394 void ExitScope(); 395 396 //===--------------------------------------------------------------------===// 397 // Diagnostic Emission and Error recovery. 398 399 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); 400 DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); 401 402 /// SkipUntil - Read tokens until we get to the specified token, then consume 403 /// it (unless DontConsume is true). Because we cannot guarantee that the 404 /// token will ever occur, this skips to the next token, or to some likely 405 /// good stopping point. If StopAtSemi is true, skipping will stop at a ';' 406 /// character. 407 /// 408 /// If SkipUntil finds the specified token, it returns true, otherwise it 409 /// returns false. 410 bool SkipUntil(tok::TokenKind T, bool StopAtSemi = true, 411 bool DontConsume = false) { 412 return SkipUntil(&T, 1, StopAtSemi, DontConsume); 413 } 414 bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, bool StopAtSemi = true, 415 bool DontConsume = false) { 416 tok::TokenKind TokArray[] = {T1, T2}; 417 return SkipUntil(TokArray, 2, StopAtSemi, DontConsume); 418 } 419 bool SkipUntil(const tok::TokenKind *Toks, unsigned NumToks, 420 bool StopAtSemi = true, bool DontConsume = false); 421 422 //===--------------------------------------------------------------------===// 423 // Lexing and parsing of C++ inline methods. 424 425 struct LexedMethod { 426 Action::DeclTy *D; 427 CachedTokens Toks; 428 explicit LexedMethod(Action::DeclTy *MD) : D(MD) {} 429 }; 430 431 /// LateParsedDefaultArgument - Keeps track of a parameter that may 432 /// have a default argument that cannot be parsed yet because it 433 /// occurs within a member function declaration inside the class 434 /// (C++ [class.mem]p2). 435 struct LateParsedDefaultArgument { 436 explicit LateParsedDefaultArgument(Action::DeclTy *P, 437 CachedTokens *Toks = 0) 438 : Param(P), Toks(Toks) { } 439 440 /// Param - The parameter declaration for this parameter. 441 Action::DeclTy *Param; 442 443 /// Toks - The sequence of tokens that comprises the default 444 /// argument expression, not including the '=' or the terminating 445 /// ')' or ','. This will be NULL for parameters that have no 446 /// default argument. 447 CachedTokens *Toks; 448 }; 449 450 /// LateParsedMethodDeclaration - A method declaration inside a class that 451 /// contains at least one entity whose parsing needs to be delayed 452 /// until the class itself is completely-defined, such as a default 453 /// argument (C++ [class.mem]p2). 454 struct LateParsedMethodDeclaration { 455 explicit LateParsedMethodDeclaration(Action::DeclTy *M) : Method(M) { } 456 457 /// Method - The method declaration. 458 Action::DeclTy *Method; 459 460 /// DefaultArgs - Contains the parameters of the function and 461 /// their default arguments. At least one of the parameters will 462 /// have a default argument, but all of the parameters of the 463 /// method will be stored so that they can be reintroduced into 464 /// scope at the appropriate times. 465 llvm::SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; 466 }; 467 468 /// LateParsedMethodDecls - During parsing of a top (non-nested) C++ 469 /// class, its method declarations that contain parts that won't be 470 /// parsed until after the definiton is completed (C++ [class.mem]p2), 471 /// the method declarations will be stored here with the tokens that 472 /// will be parsed to create those entities. 473 typedef std::list<LateParsedMethodDeclaration> LateParsedMethodDecls; 474 475 /// LexedMethodsForTopClass - During parsing of a top (non-nested) C++ class, 476 /// its inline method definitions and the inline method definitions of its 477 /// nested classes are lexed and stored here. 478 typedef std::list<LexedMethod> LexedMethodsForTopClass; 479 480 481 /// TopClass - Contains information about parts of the top 482 /// (non-nested) C++ class that will need to be parsed after the 483 /// class is fully defined. 484 struct TopClass { 485 /// MethodDecls - Method declarations that contain pieces whose 486 /// parsing will be delayed until the class is fully defined. 487 LateParsedMethodDecls MethodDecls; 488 489 /// MethodDefs - Methods whose definitions will be parsed once the 490 /// class has been fully defined. 491 LexedMethodsForTopClass MethodDefs; 492 }; 493 494 /// TopClassStacks - This is initialized with one TopClass used 495 /// for lexing all top classes, until a local class in an inline method is 496 /// encountered, at which point a new TopClass is pushed here 497 /// and used until the parsing of that local class is finished. 498 std::stack<TopClass> TopClassStacks; 499 500 TopClass &getCurTopClassStack() { 501 assert(!TopClassStacks.empty() && "No lexed method stacks!"); 502 return TopClassStacks.top(); 503 } 504 505 void PushTopClassStack() { 506 TopClassStacks.push(TopClass()); 507 } 508 void PopTopClassStack() { TopClassStacks.pop(); } 509 510 DeclTy *ParseCXXInlineMethodDef(AccessSpecifier AS, Declarator &D); 511 void ParseLexedMethodDeclarations(); 512 void ParseLexedMethodDefs(); 513 bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, 514 CachedTokens &Toks, 515 tok::TokenKind EarlyAbortIf = tok::unknown, 516 bool ConsumeFinalToken = true); 517 518 //===--------------------------------------------------------------------===// 519 // C99 6.9: External Definitions. 520 DeclTy *ParseExternalDeclaration(); 521 DeclTy *ParseDeclarationOrFunctionDefinition( 522 TemplateParameterLists *TemplateParams = 0); 523 DeclTy *ParseFunctionDefinition(Declarator &D); 524 void ParseKNRParamDeclarations(Declarator &D); 525 // EndLoc, if non-NULL, is filled with the location of the last token of 526 // the simple-asm. 527 OwningExprResult ParseSimpleAsm(SourceLocation *EndLoc = 0); 528 OwningExprResult ParseAsmStringLiteral(); 529 530 // Objective-C External Declarations 531 DeclTy *ParseObjCAtDirectives(); 532 DeclTy *ParseObjCAtClassDeclaration(SourceLocation atLoc); 533 DeclTy *ParseObjCAtInterfaceDeclaration(SourceLocation atLoc, 534 AttributeList *prefixAttrs = 0); 535 void ParseObjCClassInstanceVariables(DeclTy *interfaceDecl, 536 SourceLocation atLoc); 537 bool ParseObjCProtocolReferences(llvm::SmallVectorImpl<Action::DeclTy*> &P, 538 bool WarnOnDeclarations, 539 SourceLocation &EndProtoLoc); 540 void ParseObjCInterfaceDeclList(DeclTy *interfaceDecl, 541 tok::ObjCKeywordKind contextKey); 542 DeclTy *ParseObjCAtProtocolDeclaration(SourceLocation atLoc, 543 AttributeList *prefixAttrs = 0); 544 545 DeclTy *ObjCImpDecl; 546 547 DeclTy *ParseObjCAtImplementationDeclaration(SourceLocation atLoc); 548 DeclTy *ParseObjCAtEndDeclaration(SourceLocation atLoc); 549 DeclTy *ParseObjCAtAliasDeclaration(SourceLocation atLoc); 550 DeclTy *ParseObjCPropertySynthesize(SourceLocation atLoc); 551 DeclTy *ParseObjCPropertyDynamic(SourceLocation atLoc); 552 553 IdentifierInfo *ParseObjCSelector(SourceLocation &MethodLocation); 554 // Definitions for Objective-c context sensitive keywords recognition. 555 enum ObjCTypeQual { 556 objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, 557 objc_NumQuals 558 }; 559 IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; 560 561 bool isTokIdentifier_in() const; 562 563 TypeTy *ParseObjCTypeName(ObjCDeclSpec &DS); 564 void ParseObjCMethodRequirement(); 565 DeclTy *ParseObjCMethodPrototype(DeclTy *classOrCat, 566 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword); 567 DeclTy *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, 568 DeclTy *classDecl, 569 tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword); 570 void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); 571 572 DeclTy *ParseObjCMethodDefinition(); 573 574 //===--------------------------------------------------------------------===// 575 // C99 6.5: Expressions. 576 577 OwningExprResult ParseExpression(); 578 OwningExprResult ParseConstantExpression(); 579 // Expr that doesn't include commas. 580 OwningExprResult ParseAssignmentExpression(); 581 582 OwningExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); 583 584 OwningExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); 585 586 OwningExprResult ParseRHSOfBinaryExpression(OwningExprResult LHS, 587 unsigned MinPrec); 588 OwningExprResult ParseCastExpression(bool isUnaryExpression, 589 bool isAddressOfOperand = false); 590 OwningExprResult ParsePostfixExpressionSuffix(OwningExprResult LHS); 591 OwningExprResult ParseSizeofAlignofExpression(); 592 OwningExprResult ParseBuiltinPrimaryExpression(); 593 594 static const unsigned ExprListSize = 12; 595 typedef llvm::SmallVector<ExprTy*, ExprListSize> ExprListTy; 596 typedef llvm::SmallVector<SourceLocation, ExprListSize> CommaLocsTy; 597 598 /// ParseExpressionList - Used for C/C++ (argument-)expression-list. 599 bool ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs); 600 601 /// ParenParseOption - Control what ParseParenExpression will parse. 602 enum ParenParseOption { 603 SimpleExpr, // Only parse '(' expression ')' 604 CompoundStmt, // Also allow '(' compound-statement ')' 605 CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' 606 CastExpr // Also allow '(' type-name ')' <anything> 607 }; 608 OwningExprResult ParseParenExpression(ParenParseOption &ExprType, 609 TypeTy *&CastTy, 610 SourceLocation &RParenLoc); 611 612 OwningExprResult ParseSimpleParenExpression() { // Parse SimpleExpr only. 613 SourceLocation RParenLoc; 614 return ParseSimpleParenExpression(RParenLoc); 615 } 616 OwningExprResult ParseSimpleParenExpression(SourceLocation &RParenLoc) { 617 ParenParseOption Op = SimpleExpr; 618 TypeTy *CastTy; 619 return ParseParenExpression(Op, CastTy, RParenLoc); 620 } 621 622 OwningExprResult ParseStringLiteralExpression(); 623 624 //===--------------------------------------------------------------------===// 625 // C++ Expressions 626 OwningExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); 627 628 /// ParseOptionalCXXScopeSpecifier - Parse global scope or 629 /// nested-name-specifier if present. Returns true if a nested-name-specifier 630 /// was parsed from the token stream. Note that this routine will not parse 631 /// ::new or ::delete, it will just leave them in the token stream. 632 /// 633 bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS); 634 635 //===--------------------------------------------------------------------===// 636 // C++ 5.2p1: C++ Casts 637 OwningExprResult ParseCXXCasts(); 638 639 //===--------------------------------------------------------------------===// 640 // C++ 5.2p1: C++ Type Identification 641 OwningExprResult ParseCXXTypeid(); 642 643 //===--------------------------------------------------------------------===// 644 // C++ 9.3.2: C++ 'this' pointer 645 OwningExprResult ParseCXXThis(); 646 647 //===--------------------------------------------------------------------===// 648 // C++ 15: C++ Throw Expression 649 OwningExprResult ParseThrowExpression(); 650 // EndLoc is filled with the location of the last token of the specification. 651 bool ParseExceptionSpecification(SourceLocation &EndLoc); 652 653 //===--------------------------------------------------------------------===// 654 // C++ 2.13.5: C++ Boolean Literals 655 OwningExprResult ParseCXXBoolLiteral(); 656 657 //===--------------------------------------------------------------------===// 658 // C++ 5.2.3: Explicit type conversion (functional notation) 659 OwningExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); 660 661 /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. 662 /// This should only be called when the current token is known to be part of 663 /// simple-type-specifier. 664 void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); 665 666 bool ParseCXXTypeSpecifierSeq(DeclSpec &DS); 667 668 //===--------------------------------------------------------------------===// 669 // C++ 5.3.4 and 5.3.5: C++ new and delete 670 bool ParseExpressionListOrTypeId(ExprListTy &Exprs, Declarator &D); 671 void ParseDirectNewDeclarator(Declarator &D); 672 OwningExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); 673 OwningExprResult ParseCXXDeleteExpression(bool UseGlobal, 674 SourceLocation Start); 675 676 //===--------------------------------------------------------------------===// 677 // C++ if/switch/while/for condition expression. 678 OwningExprResult ParseCXXCondition(); 679 680 //===--------------------------------------------------------------------===// 681 // C++ types 682 683 //===--------------------------------------------------------------------===// 684 // C99 6.7.8: Initialization. 685 686 /// ParseInitializer 687 /// initializer: [C99 6.7.8] 688 /// assignment-expression 689 /// '{' ... 690 OwningExprResult ParseInitializer() { 691 if (Tok.isNot(tok::l_brace)) 692 return ParseAssignmentExpression(); 693 return ParseBraceInitializer(); 694 } 695 OwningExprResult ParseBraceInitializer(); 696 OwningExprResult ParseInitializerWithPotentialDesignator( 697 InitListDesignations &D, unsigned InitNum); 698 699 //===--------------------------------------------------------------------===// 700 // clang Expressions 701 702 OwningExprResult ParseBlockLiteralExpression(); // ^{...} 703 704 //===--------------------------------------------------------------------===// 705 // Objective-C Expressions 706 707 bool isTokObjCMessageIdentifierReceiver() const { 708 if (!Tok.is(tok::identifier)) 709 return false; 710 711 IdentifierInfo *II = Tok.getIdentifierInfo(); 712 if (Actions.getTypeName(*II, Tok.getLocation(), CurScope)) 713 return true; 714 715 return II == Ident_super; 716 } 717 718 OwningExprResult ParseObjCAtExpression(SourceLocation AtLocation); 719 OwningExprResult ParseObjCStringLiteral(SourceLocation AtLoc); 720 OwningExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); 721 OwningExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); 722 OwningExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); 723 OwningExprResult ParseObjCMessageExpression(); 724 OwningExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, 725 SourceLocation NameLoc, 726 IdentifierInfo *ReceiverName, 727 ExprArg ReceiverExpr); 728 OwningExprResult ParseAssignmentExprWithObjCMessageExprStart( 729 SourceLocation LBracloc, SourceLocation NameLoc, 730 IdentifierInfo *ReceiverName, ExprArg ReceiverExpr); 731 732 //===--------------------------------------------------------------------===// 733 // C99 6.8: Statements and Blocks. 734 735 OwningStmtResult ParseStatement() { 736 return ParseStatementOrDeclaration(true); 737 } 738 OwningStmtResult ParseStatementOrDeclaration(bool OnlyStatement = false); 739 OwningStmtResult ParseLabeledStatement(); 740 OwningStmtResult ParseCaseStatement(); 741 OwningStmtResult ParseDefaultStatement(); 742 OwningStmtResult ParseCompoundStatement(bool isStmtExpr = false); 743 OwningStmtResult ParseCompoundStatementBody(bool isStmtExpr = false); 744 bool ParseParenExprOrCondition(OwningExprResult &CondExp, 745 bool OnlyAllowCondition = false); 746 OwningStmtResult ParseIfStatement(); 747 OwningStmtResult ParseSwitchStatement(); 748 OwningStmtResult ParseWhileStatement(); 749 OwningStmtResult ParseDoStatement(); 750 OwningStmtResult ParseForStatement(); 751 OwningStmtResult ParseGotoStatement(); 752 OwningStmtResult ParseContinueStatement(); 753 OwningStmtResult ParseBreakStatement(); 754 OwningStmtResult ParseReturnStatement(); 755 OwningStmtResult ParseAsmStatement(bool &msAsm); 756 OwningStmtResult FuzzyParseMicrosoftAsmStatement(); 757 bool ParseAsmOperandsOpt(llvm::SmallVectorImpl<std::string> &Names, 758 llvm::SmallVectorImpl<ExprTy*> &Constraints, 759 llvm::SmallVectorImpl<ExprTy*> &Exprs); 760 761 //===--------------------------------------------------------------------===// 762 // C++ 6: Statements and Blocks 763 764 OwningStmtResult ParseCXXTryBlock(); 765 OwningStmtResult ParseCXXCatchBlock(); 766 767 //===--------------------------------------------------------------------===// 768 // Objective-C Statements 769 770 OwningStmtResult ParseObjCAtStatement(SourceLocation atLoc); 771 OwningStmtResult ParseObjCTryStmt(SourceLocation atLoc); 772 OwningStmtResult ParseObjCThrowStmt(SourceLocation atLoc); 773 OwningStmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); 774 775 776 //===--------------------------------------------------------------------===// 777 // C99 6.7: Declarations. 778 779 DeclTy *ParseDeclaration(unsigned Context); 780 DeclTy *ParseSimpleDeclaration(unsigned Context); 781 DeclTy *ParseInitDeclaratorListAfterFirstDeclarator(Declarator &D); 782 DeclTy *ParseFunctionStatementBody(DeclTy *Decl, 783 SourceLocation L, SourceLocation R); 784 void ParseDeclarationSpecifiers(DeclSpec &DS, 785 TemplateParameterLists *TemplateParams = 0); 786 bool ParseOptionalTypeSpecifier(DeclSpec &DS, int &isInvalid, 787 const char *&PrevSpec, 788 TemplateParameterLists *TemplateParams = 0); 789 void ParseSpecifierQualifierList(DeclSpec &DS); 790 791 void ParseObjCTypeQualifierList(ObjCDeclSpec &DS); 792 793 void ParseEnumSpecifier(DeclSpec &DS); 794 void ParseEnumBody(SourceLocation StartLoc, DeclTy *TagDecl); 795 void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType, 796 DeclTy *TagDecl); 797 void ParseStructDeclaration(DeclSpec &DS, 798 llvm::SmallVectorImpl<FieldDeclarator> &Fields); 799 800 bool isDeclarationSpecifier(); 801 bool isTypeSpecifierQualifier(); 802 bool isTypeQualifier() const; 803 804 /// isDeclarationStatement - Disambiguates between a declaration or an 805 /// expression statement, when parsing function bodies. 806 /// Returns true for declaration, false for expression. 807 bool isDeclarationStatement() { 808 if (getLang().CPlusPlus) 809 return isCXXDeclarationStatement(); 810 return isDeclarationSpecifier(); 811 } 812 813 /// isSimpleDeclaration - Disambiguates between a declaration or an 814 /// expression, mainly used for the C 'clause-1' or the C++ 815 // 'for-init-statement' part of a 'for' statement. 816 /// Returns true for declaration, false for expression. 817 bool isSimpleDeclaration() { 818 if (getLang().CPlusPlus) 819 return isCXXSimpleDeclaration(); 820 return isDeclarationSpecifier(); 821 } 822 823 /// \brief Specifies the context in which type-id/expression 824 /// disambiguation will occur. 825 enum TentativeCXXTypeIdContext { 826 TypeIdInParens, 827 TypeIdAsTemplateArgument 828 }; 829 830 831 /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know 832 /// whether the parens contain an expression or a type-id. 833 /// Returns true for a type-id and false for an expression. 834 bool isTypeIdInParens() { 835 if (getLang().CPlusPlus) 836 return isCXXTypeId(TypeIdInParens); 837 return isTypeSpecifierQualifier(); 838 } 839 840 /// isCXXDeclarationStatement - C++-specialized function that disambiguates 841 /// between a declaration or an expression statement, when parsing function 842 /// bodies. Returns true for declaration, false for expression. 843 bool isCXXDeclarationStatement(); 844 845 /// isCXXSimpleDeclaration - C++-specialized function that disambiguates 846 /// between a simple-declaration or an expression-statement. 847 /// If during the disambiguation process a parsing error is encountered, 848 /// the function returns true to let the declaration parsing code handle it. 849 /// Returns false if the statement is disambiguated as expression. 850 bool isCXXSimpleDeclaration(); 851 852 /// isCXXFunctionDeclarator - Disambiguates between a function declarator or 853 /// a constructor-style initializer, when parsing declaration statements. 854 /// Returns true for function declarator and false for constructor-style 855 /// initializer. If 'warnIfAmbiguous' is true a warning will be emitted to 856 /// indicate that the parens were disambiguated as function declarator. 857 /// If during the disambiguation process a parsing error is encountered, 858 /// the function returns true to let the declaration parsing code handle it. 859 bool isCXXFunctionDeclarator(bool warnIfAmbiguous); 860 861 /// isCXXConditionDeclaration - Disambiguates between a declaration or an 862 /// expression for a condition of a if/switch/while/for statement. 863 /// If during the disambiguation process a parsing error is encountered, 864 /// the function returns true to let the declaration parsing code handle it. 865 bool isCXXConditionDeclaration(); 866 867 bool isCXXTypeId(TentativeCXXTypeIdContext Context); 868 869 /// TPResult - Used as the result value for functions whose purpose is to 870 /// disambiguate C++ constructs by "tentatively parsing" them. 871 /// This is a class instead of a simple enum because the implicit enum-to-bool 872 /// conversions may cause subtle bugs. 873 class TPResult { 874 enum Result { 875 TPR_true, 876 TPR_false, 877 TPR_ambiguous, 878 TPR_error 879 }; 880 Result Res; 881 TPResult(Result result) : Res(result) {} 882 public: 883 static TPResult True() { return TPR_true; } 884 static TPResult False() { return TPR_false; } 885 static TPResult Ambiguous() { return TPR_ambiguous; } 886 static TPResult Error() { return TPR_error; } 887 888 bool operator==(const TPResult &RHS) const { return Res == RHS.Res; } 889 bool operator!=(const TPResult &RHS) const { return Res != RHS.Res; } 890 }; 891 892 /// isCXXDeclarationSpecifier - Returns TPResult::True() if it is a 893 /// declaration specifier, TPResult::False() if it is not, 894 /// TPResult::Ambiguous() if it could be either a decl-specifier or a 895 /// function-style cast, and TPResult::Error() if a parsing error was 896 /// encountered. 897 /// Doesn't consume tokens. 898 TPResult isCXXDeclarationSpecifier(); 899 900 // "Tentative parsing" functions, used for disambiguation. If a parsing error 901 // is encountered they will return TPResult::Error(). 902 // Returning TPResult::True()/False() indicates that the ambiguity was 903 // resolved and tentative parsing may stop. TPResult::Ambiguous() indicates 904 // that more tentative parsing is necessary for disambiguation. 905 // They all consume tokens, so backtracking should be used after calling them. 906 907 TPResult TryParseDeclarationSpecifier(); 908 TPResult TryParseSimpleDeclaration(); 909 TPResult TryParseTypeofSpecifier(); 910 TPResult TryParseInitDeclaratorList(); 911 TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true); 912 TPResult TryParseParameterDeclarationClause(); 913 TPResult TryParseFunctionDeclarator(); 914 TPResult TryParseBracketDeclarator(); 915 916 TypeResult ParseTypeName(); 917 void ParseBlockId(); 918 // EndLoc, if non-NULL, is filled with the location of the last token of 919 // the attribute list. 920 AttributeList *ParseAttributes(SourceLocation *EndLoc = 0); 921 void FuzzyParseMicrosoftDeclSpec(); 922 void ParseTypeofSpecifier(DeclSpec &DS); 923 924 /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to 925 /// enter a new C++ declarator scope and exit it when the function is 926 /// finished. 927 class DeclaratorScopeObj { 928 Parser &P; 929 CXXScopeSpec &SS; 930 public: 931 DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) : P(p), SS(ss) {} 932 933 void EnterDeclaratorScope() { 934 if (SS.isSet()) 935 P.Actions.ActOnCXXEnterDeclaratorScope(P.CurScope, SS); 936 } 937 938 ~DeclaratorScopeObj() { 939 if (SS.isSet()) 940 P.Actions.ActOnCXXExitDeclaratorScope(P.CurScope, SS); 941 } 942 }; 943 944 /// ParseDeclarator - Parse and verify a newly-initialized declarator. 945 void ParseDeclarator(Declarator &D); 946 /// A function that parses a variant of direct-declarator. 947 typedef void (Parser::*DirectDeclParseFunction)(Declarator&); 948 void ParseDeclaratorInternal(Declarator &D, 949 DirectDeclParseFunction DirectDeclParser); 950 void ParseTypeQualifierListOpt(DeclSpec &DS, bool AttributesAllowed = true); 951 void ParseDirectDeclarator(Declarator &D); 952 void ParseParenDeclarator(Declarator &D); 953 void ParseFunctionDeclarator(SourceLocation LParenLoc, Declarator &D, 954 AttributeList *AttrList = 0, 955 bool RequiresArg = false); 956 void ParseFunctionDeclaratorIdentifierList(SourceLocation LParenLoc, 957 Declarator &D); 958 void ParseBracketDeclarator(Declarator &D); 959 960 //===--------------------------------------------------------------------===// 961 // C++ 7: Declarations [dcl.dcl] 962 963 DeclTy *ParseNamespace(unsigned Context); 964 DeclTy *ParseLinkage(unsigned Context); 965 DeclTy *ParseUsingDirectiveOrDeclaration(unsigned Context); 966 DeclTy *ParseUsingDirective(unsigned Context, SourceLocation UsingLoc); 967 DeclTy *ParseUsingDeclaration(unsigned Context, SourceLocation UsingLoc); 968 969 //===--------------------------------------------------------------------===// 970 // C++ 9: classes [class] and C structs/unions. 971 TypeTy *ParseClassName(const CXXScopeSpec *SS = 0); 972 void ParseClassSpecifier(DeclSpec &DS, 973 TemplateParameterLists *TemplateParams = 0); 974 void ParseCXXMemberSpecification(SourceLocation StartLoc, unsigned TagType, 975 DeclTy *TagDecl); 976 DeclTy *ParseCXXClassMemberDeclaration(AccessSpecifier AS); 977 void ParseConstructorInitializer(DeclTy *ConstructorDecl); 978 MemInitResult ParseMemInitializer(DeclTy *ConstructorDecl); 979 980 //===--------------------------------------------------------------------===// 981 // C++ 10: Derived classes [class.derived] 982 void ParseBaseClause(DeclTy *ClassDecl); 983 BaseResult ParseBaseSpecifier(DeclTy *ClassDecl); 984 AccessSpecifier getAccessSpecifierIfPresent() const; 985 986 //===--------------------------------------------------------------------===// 987 // C++ 13.5: Overloaded operators [over.oper] 988 // EndLoc, if non-NULL, is filled with the location of the last token of 989 // the ID. 990 OverloadedOperatorKind TryParseOperatorFunctionId(SourceLocation *EndLoc = 0); 991 TypeTy *ParseConversionFunctionId(SourceLocation *EndLoc = 0); 992 993 //===--------------------------------------------------------------------===// 994 // C++ 14: Templates [temp] 995 typedef llvm::SmallVector<DeclTy *, 4> TemplateParameterList; 996 997 // C++ 14.1: Template Parameters [temp.param] 998 DeclTy *ParseTemplateDeclarationOrSpecialization(unsigned Context); 999 bool ParseTemplateParameters(unsigned Depth, 1000 TemplateParameterList &TemplateParams, 1001 SourceLocation &LAngleLoc, 1002 SourceLocation &RAngleLoc); 1003 bool ParseTemplateParameterList(unsigned Depth, 1004 TemplateParameterList &TemplateParams); 1005 DeclTy *ParseTemplateParameter(unsigned Depth, unsigned Position); 1006 DeclTy *ParseTypeParameter(unsigned Depth, unsigned Position); 1007 DeclTy *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); 1008 DeclTy *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); 1009 // C++ 14.3: Template arguments [temp.arg] 1010 typedef llvm::SmallVector<void *, 16> TemplateArgList; 1011 typedef llvm::SmallVector<bool, 16> TemplateArgIsTypeList; 1012 typedef llvm::SmallVector<SourceLocation, 16> TemplateArgLocationList; 1013 1014 bool ParseTemplateIdAfterTemplateName(DeclTy *Template, 1015 SourceLocation TemplateNameLoc, 1016 const CXXScopeSpec *SS, 1017 bool ConsumeLastToken, 1018 SourceLocation &LAngleLoc, 1019 TemplateArgList &TemplateArgs, 1020 TemplateArgIsTypeList &TemplateArgIsType, 1021 TemplateArgLocationList &TemplateArgLocations, 1022 SourceLocation &RAngleLoc); 1023 1024 void AnnotateTemplateIdToken(DeclTy *Template, TemplateNameKind TNK, 1025 const CXXScopeSpec *SS, 1026 SourceLocation TemplateKWLoc = SourceLocation(), 1027 bool AllowTypeAnnotation = true); 1028 bool AnnotateTemplateIdTokenAsType(const CXXScopeSpec *SS = 0); 1029 bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs, 1030 TemplateArgIsTypeList &TemplateArgIsType, 1031 TemplateArgLocationList &TemplateArgLocations); 1032 void *ParseTemplateArgument(bool &ArgIsType); 1033 1034 //===--------------------------------------------------------------------===// 1035 // GNU G++: Type Traits [Type-Traits.html in the GCC manual] 1036 OwningExprResult ParseUnaryTypeTrait(); 1037}; 1038 1039} // end namespace clang 1040 1041#endif 1042