ParseExpr.cpp revision d974a7b72eb84cdc735b189bcea56fd37e13ebf6
1//===--- ParseExpr.cpp - Expression Parsing -------------------------------===// 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 implements the Expression parsing implementation. Expressions in 11// C99 basically consist of a bunch of binary operators with unary operators and 12// other random stuff at the leaves. 13// 14// In the C99 grammar, these unary operators bind tightest and are represented 15// as the 'cast-expression' production. Everything else is either a binary 16// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are 17// handled by ParseCastExpression, the higher level pieces are handled by 18// ParseBinaryExpression. 19// 20//===----------------------------------------------------------------------===// 21 22#include "clang/Parse/Parser.h" 23#include "clang/Parse/DeclSpec.h" 24#include "clang/Parse/Scope.h" 25#include "clang/Basic/PrettyStackTrace.h" 26#include "ExtensionRAIIObject.h" 27#include "llvm/ADT/SmallVector.h" 28#include "llvm/ADT/SmallString.h" 29using namespace clang; 30 31/// PrecedenceLevels - These are precedences for the binary/ternary operators in 32/// the C99 grammar. These have been named to relate with the C99 grammar 33/// productions. Low precedences numbers bind more weakly than high numbers. 34namespace prec { 35 enum Level { 36 Unknown = 0, // Not binary operator. 37 Comma = 1, // , 38 Assignment = 2, // =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |= 39 Conditional = 3, // ? 40 LogicalOr = 4, // || 41 LogicalAnd = 5, // && 42 InclusiveOr = 6, // | 43 ExclusiveOr = 7, // ^ 44 And = 8, // & 45 Equality = 9, // ==, != 46 Relational = 10, // >=, <=, >, < 47 Shift = 11, // <<, >> 48 Additive = 12, // -, + 49 Multiplicative = 13, // *, /, % 50 PointerToMember = 14 // .*, ->* 51 }; 52} 53 54 55/// getBinOpPrecedence - Return the precedence of the specified binary operator 56/// token. This returns: 57/// 58static prec::Level getBinOpPrecedence(tok::TokenKind Kind, 59 bool GreaterThanIsOperator, 60 bool CPlusPlus0x) { 61 switch (Kind) { 62 case tok::greater: 63 // C++ [temp.names]p3: 64 // [...] When parsing a template-argument-list, the first 65 // non-nested > is taken as the ending delimiter rather than a 66 // greater-than operator. [...] 67 if (GreaterThanIsOperator) 68 return prec::Relational; 69 return prec::Unknown; 70 71 case tok::greatergreater: 72 // C++0x [temp.names]p3: 73 // 74 // [...] Similarly, the first non-nested >> is treated as two 75 // consecutive but distinct > tokens, the first of which is 76 // taken as the end of the template-argument-list and completes 77 // the template-id. [...] 78 if (GreaterThanIsOperator || !CPlusPlus0x) 79 return prec::Shift; 80 return prec::Unknown; 81 82 default: return prec::Unknown; 83 case tok::comma: return prec::Comma; 84 case tok::equal: 85 case tok::starequal: 86 case tok::slashequal: 87 case tok::percentequal: 88 case tok::plusequal: 89 case tok::minusequal: 90 case tok::lesslessequal: 91 case tok::greatergreaterequal: 92 case tok::ampequal: 93 case tok::caretequal: 94 case tok::pipeequal: return prec::Assignment; 95 case tok::question: return prec::Conditional; 96 case tok::pipepipe: return prec::LogicalOr; 97 case tok::ampamp: return prec::LogicalAnd; 98 case tok::pipe: return prec::InclusiveOr; 99 case tok::caret: return prec::ExclusiveOr; 100 case tok::amp: return prec::And; 101 case tok::exclaimequal: 102 case tok::equalequal: return prec::Equality; 103 case tok::lessequal: 104 case tok::less: 105 case tok::greaterequal: return prec::Relational; 106 case tok::lessless: return prec::Shift; 107 case tok::plus: 108 case tok::minus: return prec::Additive; 109 case tok::percent: 110 case tok::slash: 111 case tok::star: return prec::Multiplicative; 112 case tok::periodstar: 113 case tok::arrowstar: return prec::PointerToMember; 114 } 115} 116 117 118/// ParseExpression - Simple precedence-based parser for binary/ternary 119/// operators. 120/// 121/// Note: we diverge from the C99 grammar when parsing the assignment-expression 122/// production. C99 specifies that the LHS of an assignment operator should be 123/// parsed as a unary-expression, but consistency dictates that it be a 124/// conditional-expession. In practice, the important thing here is that the 125/// LHS of an assignment has to be an l-value, which productions between 126/// unary-expression and conditional-expression don't produce. Because we want 127/// consistency, we parse the LHS as a conditional-expression, then check for 128/// l-value-ness in semantic analysis stages. 129/// 130/// pm-expression: [C++ 5.5] 131/// cast-expression 132/// pm-expression '.*' cast-expression 133/// pm-expression '->*' cast-expression 134/// 135/// multiplicative-expression: [C99 6.5.5] 136/// Note: in C++, apply pm-expression instead of cast-expression 137/// cast-expression 138/// multiplicative-expression '*' cast-expression 139/// multiplicative-expression '/' cast-expression 140/// multiplicative-expression '%' cast-expression 141/// 142/// additive-expression: [C99 6.5.6] 143/// multiplicative-expression 144/// additive-expression '+' multiplicative-expression 145/// additive-expression '-' multiplicative-expression 146/// 147/// shift-expression: [C99 6.5.7] 148/// additive-expression 149/// shift-expression '<<' additive-expression 150/// shift-expression '>>' additive-expression 151/// 152/// relational-expression: [C99 6.5.8] 153/// shift-expression 154/// relational-expression '<' shift-expression 155/// relational-expression '>' shift-expression 156/// relational-expression '<=' shift-expression 157/// relational-expression '>=' shift-expression 158/// 159/// equality-expression: [C99 6.5.9] 160/// relational-expression 161/// equality-expression '==' relational-expression 162/// equality-expression '!=' relational-expression 163/// 164/// AND-expression: [C99 6.5.10] 165/// equality-expression 166/// AND-expression '&' equality-expression 167/// 168/// exclusive-OR-expression: [C99 6.5.11] 169/// AND-expression 170/// exclusive-OR-expression '^' AND-expression 171/// 172/// inclusive-OR-expression: [C99 6.5.12] 173/// exclusive-OR-expression 174/// inclusive-OR-expression '|' exclusive-OR-expression 175/// 176/// logical-AND-expression: [C99 6.5.13] 177/// inclusive-OR-expression 178/// logical-AND-expression '&&' inclusive-OR-expression 179/// 180/// logical-OR-expression: [C99 6.5.14] 181/// logical-AND-expression 182/// logical-OR-expression '||' logical-AND-expression 183/// 184/// conditional-expression: [C99 6.5.15] 185/// logical-OR-expression 186/// logical-OR-expression '?' expression ':' conditional-expression 187/// [GNU] logical-OR-expression '?' ':' conditional-expression 188/// [C++] the third operand is an assignment-expression 189/// 190/// assignment-expression: [C99 6.5.16] 191/// conditional-expression 192/// unary-expression assignment-operator assignment-expression 193/// [C++] throw-expression [C++ 15] 194/// 195/// assignment-operator: one of 196/// = *= /= %= += -= <<= >>= &= ^= |= 197/// 198/// expression: [C99 6.5.17] 199/// assignment-expression 200/// expression ',' assignment-expression 201/// 202Parser::OwningExprResult Parser::ParseExpression() { 203 OwningExprResult LHS(ParseAssignmentExpression()); 204 if (LHS.isInvalid()) return move(LHS); 205 206 return ParseRHSOfBinaryExpression(move(LHS), prec::Comma); 207} 208 209/// This routine is called when the '@' is seen and consumed. 210/// Current token is an Identifier and is not a 'try'. This 211/// routine is necessary to disambiguate @try-statement from, 212/// for example, @encode-expression. 213/// 214Parser::OwningExprResult 215Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) { 216 OwningExprResult LHS(ParseObjCAtExpression(AtLoc)); 217 if (LHS.isInvalid()) return move(LHS); 218 219 return ParseRHSOfBinaryExpression(move(LHS), prec::Comma); 220} 221 222/// This routine is called when a leading '__extension__' is seen and 223/// consumed. This is necessary because the token gets consumed in the 224/// process of disambiguating between an expression and a declaration. 225Parser::OwningExprResult 226Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) { 227 OwningExprResult LHS(Actions, true); 228 { 229 // Silence extension warnings in the sub-expression 230 ExtensionRAIIObject O(Diags); 231 232 LHS = ParseCastExpression(false); 233 if (LHS.isInvalid()) return move(LHS); 234 } 235 236 LHS = Actions.ActOnUnaryOp(CurScope, ExtLoc, tok::kw___extension__, 237 move(LHS)); 238 if (LHS.isInvalid()) return move(LHS); 239 240 return ParseRHSOfBinaryExpression(move(LHS), prec::Comma); 241} 242 243/// ParseAssignmentExpression - Parse an expr that doesn't include commas. 244/// 245Parser::OwningExprResult Parser::ParseAssignmentExpression() { 246 if (Tok.is(tok::kw_throw)) 247 return ParseThrowExpression(); 248 249 OwningExprResult LHS(ParseCastExpression(false)); 250 if (LHS.isInvalid()) return move(LHS); 251 252 return ParseRHSOfBinaryExpression(move(LHS), prec::Assignment); 253} 254 255/// ParseAssignmentExprWithObjCMessageExprStart - Parse an assignment expression 256/// where part of an objc message send has already been parsed. In this case 257/// LBracLoc indicates the location of the '[' of the message send, and either 258/// ReceiverName or ReceiverExpr is non-null indicating the receiver of the 259/// message. 260/// 261/// Since this handles full assignment-expression's, it handles postfix 262/// expressions and other binary operators for these expressions as well. 263Parser::OwningExprResult 264Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc, 265 SourceLocation NameLoc, 266 IdentifierInfo *ReceiverName, 267 ExprArg ReceiverExpr) { 268 OwningExprResult R(ParseObjCMessageExpressionBody(LBracLoc, NameLoc, 269 ReceiverName, 270 move(ReceiverExpr))); 271 if (R.isInvalid()) return move(R); 272 R = ParsePostfixExpressionSuffix(move(R)); 273 if (R.isInvalid()) return move(R); 274 return ParseRHSOfBinaryExpression(move(R), prec::Assignment); 275} 276 277 278Parser::OwningExprResult Parser::ParseConstantExpression() { 279 OwningExprResult LHS(ParseCastExpression(false)); 280 if (LHS.isInvalid()) return move(LHS); 281 282 return ParseRHSOfBinaryExpression(move(LHS), prec::Conditional); 283} 284 285/// ParseRHSOfBinaryExpression - Parse a binary expression that starts with 286/// LHS and has a precedence of at least MinPrec. 287Parser::OwningExprResult 288Parser::ParseRHSOfBinaryExpression(OwningExprResult LHS, unsigned MinPrec) { 289 unsigned NextTokPrec = getBinOpPrecedence(Tok.getKind(), 290 GreaterThanIsOperator, 291 getLang().CPlusPlus0x); 292 SourceLocation ColonLoc; 293 294 while (1) { 295 // If this token has a lower precedence than we are allowed to parse (e.g. 296 // because we are called recursively, or because the token is not a binop), 297 // then we are done! 298 if (NextTokPrec < MinPrec) 299 return move(LHS); 300 301 // Consume the operator, saving the operator token for error reporting. 302 Token OpToken = Tok; 303 ConsumeToken(); 304 305 // Special case handling for the ternary operator. 306 OwningExprResult TernaryMiddle(Actions, true); 307 if (NextTokPrec == prec::Conditional) { 308 if (Tok.isNot(tok::colon)) { 309 // Handle this production specially: 310 // logical-OR-expression '?' expression ':' conditional-expression 311 // In particular, the RHS of the '?' is 'expression', not 312 // 'logical-OR-expression' as we might expect. 313 TernaryMiddle = ParseExpression(); 314 if (TernaryMiddle.isInvalid()) 315 return move(TernaryMiddle); 316 } else { 317 // Special case handling of "X ? Y : Z" where Y is empty: 318 // logical-OR-expression '?' ':' conditional-expression [GNU] 319 TernaryMiddle = 0; 320 Diag(Tok, diag::ext_gnu_conditional_expr); 321 } 322 323 if (Tok.isNot(tok::colon)) { 324 Diag(Tok, diag::err_expected_colon); 325 Diag(OpToken, diag::note_matching) << "?"; 326 return ExprError(); 327 } 328 329 // Eat the colon. 330 ColonLoc = ConsumeToken(); 331 } 332 333 // Parse another leaf here for the RHS of the operator. 334 // ParseCastExpression works here because all RHS expressions in C have it 335 // as a prefix, at least. However, in C++, an assignment-expression could 336 // be a throw-expression, which is not a valid cast-expression. 337 // Therefore we need some special-casing here. 338 // Also note that the third operand of the conditional operator is 339 // an assignment-expression in C++. 340 OwningExprResult RHS(Actions); 341 if (getLang().CPlusPlus && NextTokPrec <= prec::Conditional) 342 RHS = ParseAssignmentExpression(); 343 else 344 RHS = ParseCastExpression(false); 345 if (RHS.isInvalid()) 346 return move(RHS); 347 348 // Remember the precedence of this operator and get the precedence of the 349 // operator immediately to the right of the RHS. 350 unsigned ThisPrec = NextTokPrec; 351 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator, 352 getLang().CPlusPlus0x); 353 354 // Assignment and conditional expressions are right-associative. 355 bool isRightAssoc = ThisPrec == prec::Conditional || 356 ThisPrec == prec::Assignment; 357 358 // Get the precedence of the operator to the right of the RHS. If it binds 359 // more tightly with RHS than we do, evaluate it completely first. 360 if (ThisPrec < NextTokPrec || 361 (ThisPrec == NextTokPrec && isRightAssoc)) { 362 // If this is left-associative, only parse things on the RHS that bind 363 // more tightly than the current operator. If it is left-associative, it 364 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as 365 // A=(B=(C=D)), where each paren is a level of recursion here. 366 // The function takes ownership of the RHS. 367 RHS = ParseRHSOfBinaryExpression(move(RHS), ThisPrec + !isRightAssoc); 368 if (RHS.isInvalid()) 369 return move(RHS); 370 371 NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator, 372 getLang().CPlusPlus0x); 373 } 374 assert(NextTokPrec <= ThisPrec && "Recursion didn't work!"); 375 376 if (!LHS.isInvalid()) { 377 // Combine the LHS and RHS into the LHS (e.g. build AST). 378 if (TernaryMiddle.isInvalid()) { 379 // If we're using '>>' as an operator within a template 380 // argument list (in C++98), suggest the addition of 381 // parentheses so that the code remains well-formed in C++0x. 382 if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater)) 383 SuggestParentheses(OpToken.getLocation(), 384 diag::warn_cxx0x_right_shift_in_template_arg, 385 SourceRange(Actions.getExprRange(LHS.get()).getBegin(), 386 Actions.getExprRange(RHS.get()).getEnd())); 387 388 LHS = Actions.ActOnBinOp(CurScope, OpToken.getLocation(), 389 OpToken.getKind(), move(LHS), move(RHS)); 390 } else 391 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc, 392 move(LHS), move(TernaryMiddle), 393 move(RHS)); 394 } 395 } 396} 397 398/// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is 399/// true, parse a unary-expression. isAddressOfOperand exists because an 400/// id-expression that is the operand of address-of gets special treatment 401/// due to member pointers. 402/// 403/// cast-expression: [C99 6.5.4] 404/// unary-expression 405/// '(' type-name ')' cast-expression 406/// 407/// unary-expression: [C99 6.5.3] 408/// postfix-expression 409/// '++' unary-expression 410/// '--' unary-expression 411/// unary-operator cast-expression 412/// 'sizeof' unary-expression 413/// 'sizeof' '(' type-name ')' 414/// [GNU] '__alignof' unary-expression 415/// [GNU] '__alignof' '(' type-name ')' 416/// [C++0x] 'alignof' '(' type-id ')' 417/// [GNU] '&&' identifier 418/// [C++] new-expression 419/// [C++] delete-expression 420/// 421/// unary-operator: one of 422/// '&' '*' '+' '-' '~' '!' 423/// [GNU] '__extension__' '__real' '__imag' 424/// 425/// primary-expression: [C99 6.5.1] 426/// [C99] identifier 427/// [C++] id-expression 428/// constant 429/// string-literal 430/// [C++] boolean-literal [C++ 2.13.5] 431/// [C++0x] 'nullptr' [C++0x 2.14.7] 432/// '(' expression ')' 433/// '__func__' [C99 6.4.2.2] 434/// [GNU] '__FUNCTION__' 435/// [GNU] '__PRETTY_FUNCTION__' 436/// [GNU] '(' compound-statement ')' 437/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' 438/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' 439/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' 440/// assign-expr ')' 441/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' 442/// [GNU] '__null' 443/// [OBJC] '[' objc-message-expr ']' 444/// [OBJC] '@selector' '(' objc-selector-arg ')' 445/// [OBJC] '@protocol' '(' identifier ')' 446/// [OBJC] '@encode' '(' type-name ')' 447/// [OBJC] objc-string-literal 448/// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3] 449/// [C++] typename-specifier '(' expression-list[opt] ')' [TODO] 450/// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 451/// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 452/// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 453/// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 454/// [C++] 'typeid' '(' expression ')' [C++ 5.2p1] 455/// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1] 456/// [C++] 'this' [C++ 9.3.2] 457/// [G++] unary-type-trait '(' type-id ')' 458/// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO] 459/// [clang] '^' block-literal 460/// 461/// constant: [C99 6.4.4] 462/// integer-constant 463/// floating-constant 464/// enumeration-constant -> identifier 465/// character-constant 466/// 467/// id-expression: [C++ 5.1] 468/// unqualified-id 469/// qualified-id [TODO] 470/// 471/// unqualified-id: [C++ 5.1] 472/// identifier 473/// operator-function-id 474/// conversion-function-id [TODO] 475/// '~' class-name [TODO] 476/// template-id [TODO] 477/// 478/// new-expression: [C++ 5.3.4] 479/// '::'[opt] 'new' new-placement[opt] new-type-id 480/// new-initializer[opt] 481/// '::'[opt] 'new' new-placement[opt] '(' type-id ')' 482/// new-initializer[opt] 483/// 484/// delete-expression: [C++ 5.3.5] 485/// '::'[opt] 'delete' cast-expression 486/// '::'[opt] 'delete' '[' ']' cast-expression 487/// 488/// [GNU] unary-type-trait: 489/// '__has_nothrow_assign' [TODO] 490/// '__has_nothrow_copy' [TODO] 491/// '__has_nothrow_constructor' [TODO] 492/// '__has_trivial_assign' [TODO] 493/// '__has_trivial_copy' [TODO] 494/// '__has_trivial_constructor' 495/// '__has_trivial_destructor' 496/// '__has_virtual_destructor' [TODO] 497/// '__is_abstract' [TODO] 498/// '__is_class' 499/// '__is_empty' [TODO] 500/// '__is_enum' 501/// '__is_pod' 502/// '__is_polymorphic' 503/// '__is_union' 504/// 505/// [GNU] binary-type-trait: 506/// '__is_base_of' [TODO] 507/// 508Parser::OwningExprResult Parser::ParseCastExpression(bool isUnaryExpression, 509 bool isAddressOfOperand) { 510 OwningExprResult Res(Actions); 511 tok::TokenKind SavedKind = Tok.getKind(); 512 513 // This handles all of cast-expression, unary-expression, postfix-expression, 514 // and primary-expression. We handle them together like this for efficiency 515 // and to simplify handling of an expression starting with a '(' token: which 516 // may be one of a parenthesized expression, cast-expression, compound literal 517 // expression, or statement expression. 518 // 519 // If the parsed tokens consist of a primary-expression, the cases below 520 // call ParsePostfixExpressionSuffix to handle the postfix expression 521 // suffixes. Cases that cannot be followed by postfix exprs should 522 // return without invoking ParsePostfixExpressionSuffix. 523 switch (SavedKind) { 524 case tok::l_paren: { 525 // If this expression is limited to being a unary-expression, the parent can 526 // not start a cast expression. 527 ParenParseOption ParenExprType = 528 isUnaryExpression ? CompoundLiteral : CastExpr; 529 TypeTy *CastTy; 530 SourceLocation LParenLoc = Tok.getLocation(); 531 SourceLocation RParenLoc; 532 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/, 533 CastTy, RParenLoc); 534 if (Res.isInvalid()) return move(Res); 535 536 switch (ParenExprType) { 537 case SimpleExpr: break; // Nothing else to do. 538 case CompoundStmt: break; // Nothing else to do. 539 case CompoundLiteral: 540 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of 541 // postfix-expression exist, parse them now. 542 break; 543 case CastExpr: 544 // We have parsed the cast-expression and no postfix-expr pieces are 545 // following. 546 return move(Res); 547 } 548 549 // These can be followed by postfix-expr pieces. 550 return ParsePostfixExpressionSuffix(move(Res)); 551 } 552 553 // primary-expression 554 case tok::numeric_constant: 555 // constant: integer-constant 556 // constant: floating-constant 557 558 Res = Actions.ActOnNumericConstant(Tok); 559 ConsumeToken(); 560 561 // These can be followed by postfix-expr pieces. 562 return ParsePostfixExpressionSuffix(move(Res)); 563 564 case tok::kw_true: 565 case tok::kw_false: 566 return ParseCXXBoolLiteral(); 567 568 case tok::kw_nullptr: 569 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken()); 570 571 case tok::identifier: { // primary-expression: identifier 572 // unqualified-id: identifier 573 // constant: enumeration-constant 574 // Turn a potentially qualified name into a annot_typename or 575 // annot_cxxscope if it would be valid. This handles things like x::y, etc. 576 if (getLang().CPlusPlus) { 577 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. 578 if (TryAnnotateTypeOrScopeToken()) 579 return ParseCastExpression(isUnaryExpression, isAddressOfOperand); 580 } 581 582 // Support 'Class.property' notation. 583 // We don't use isTokObjCMessageIdentifierReceiver(), since it allows 584 // 'super' (which is inappropriate here). 585 if (getLang().ObjC1 && 586 Actions.getTypeName(*Tok.getIdentifierInfo(), 587 Tok.getLocation(), CurScope) && 588 NextToken().is(tok::period)) { 589 IdentifierInfo &ReceiverName = *Tok.getIdentifierInfo(); 590 SourceLocation IdentLoc = ConsumeToken(); 591 SourceLocation DotLoc = ConsumeToken(); 592 593 if (Tok.isNot(tok::identifier)) { 594 Diag(Tok, diag::err_expected_ident); 595 return ExprError(); 596 } 597 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo(); 598 SourceLocation PropertyLoc = ConsumeToken(); 599 600 Res = Actions.ActOnClassPropertyRefExpr(ReceiverName, PropertyName, 601 IdentLoc, PropertyLoc); 602 // These can be followed by postfix-expr pieces. 603 return ParsePostfixExpressionSuffix(move(Res)); 604 } 605 // Consume the identifier so that we can see if it is followed by a '('. 606 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we 607 // need to know whether or not this identifier is a function designator or 608 // not. 609 IdentifierInfo &II = *Tok.getIdentifierInfo(); 610 SourceLocation L = ConsumeToken(); 611 Res = Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren)); 612 // These can be followed by postfix-expr pieces. 613 return ParsePostfixExpressionSuffix(move(Res)); 614 } 615 case tok::char_constant: // constant: character-constant 616 Res = Actions.ActOnCharacterConstant(Tok); 617 ConsumeToken(); 618 // These can be followed by postfix-expr pieces. 619 return ParsePostfixExpressionSuffix(move(Res)); 620 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2] 621 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU] 622 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU] 623 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind); 624 ConsumeToken(); 625 // These can be followed by postfix-expr pieces. 626 return ParsePostfixExpressionSuffix(move(Res)); 627 case tok::string_literal: // primary-expression: string-literal 628 case tok::wide_string_literal: 629 Res = ParseStringLiteralExpression(); 630 if (Res.isInvalid()) return move(Res); 631 // This can be followed by postfix-expr pieces (e.g. "foo"[1]). 632 return ParsePostfixExpressionSuffix(move(Res)); 633 case tok::kw___builtin_va_arg: 634 case tok::kw___builtin_offsetof: 635 case tok::kw___builtin_choose_expr: 636 case tok::kw___builtin_types_compatible_p: 637 return ParseBuiltinPrimaryExpression(); 638 case tok::kw___null: 639 return Actions.ActOnGNUNullExpr(ConsumeToken()); 640 break; 641 case tok::plusplus: // unary-expression: '++' unary-expression 642 case tok::minusminus: { // unary-expression: '--' unary-expression 643 SourceLocation SavedLoc = ConsumeToken(); 644 Res = ParseCastExpression(true); 645 if (!Res.isInvalid()) 646 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, move(Res)); 647 return move(Res); 648 } 649 case tok::amp: { // unary-expression: '&' cast-expression 650 // Special treatment because of member pointers 651 SourceLocation SavedLoc = ConsumeToken(); 652 Res = ParseCastExpression(false, true); 653 if (!Res.isInvalid()) 654 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, move(Res)); 655 return move(Res); 656 } 657 658 case tok::star: // unary-expression: '*' cast-expression 659 case tok::plus: // unary-expression: '+' cast-expression 660 case tok::minus: // unary-expression: '-' cast-expression 661 case tok::tilde: // unary-expression: '~' cast-expression 662 case tok::exclaim: // unary-expression: '!' cast-expression 663 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU] 664 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU] 665 SourceLocation SavedLoc = ConsumeToken(); 666 Res = ParseCastExpression(false); 667 if (!Res.isInvalid()) 668 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, move(Res)); 669 return move(Res); 670 } 671 672 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU] 673 // __extension__ silences extension warnings in the subexpression. 674 ExtensionRAIIObject O(Diags); // Use RAII to do this. 675 SourceLocation SavedLoc = ConsumeToken(); 676 Res = ParseCastExpression(false); 677 if (!Res.isInvalid()) 678 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, move(Res)); 679 return move(Res); 680 } 681 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression 682 // unary-expression: 'sizeof' '(' type-name ')' 683 case tok::kw_alignof: 684 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression 685 // unary-expression: '__alignof' '(' type-name ')' 686 // unary-expression: 'alignof' '(' type-id ')' 687 return ParseSizeofAlignofExpression(); 688 case tok::ampamp: { // unary-expression: '&&' identifier 689 SourceLocation AmpAmpLoc = ConsumeToken(); 690 if (Tok.isNot(tok::identifier)) 691 return ExprError(Diag(Tok, diag::err_expected_ident)); 692 693 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label); 694 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), 695 Tok.getIdentifierInfo()); 696 ConsumeToken(); 697 return move(Res); 698 } 699 case tok::kw_const_cast: 700 case tok::kw_dynamic_cast: 701 case tok::kw_reinterpret_cast: 702 case tok::kw_static_cast: 703 Res = ParseCXXCasts(); 704 // These can be followed by postfix-expr pieces. 705 return ParsePostfixExpressionSuffix(move(Res)); 706 case tok::kw_typeid: 707 Res = ParseCXXTypeid(); 708 // This can be followed by postfix-expr pieces. 709 return ParsePostfixExpressionSuffix(move(Res)); 710 case tok::kw_this: 711 Res = ParseCXXThis(); 712 // This can be followed by postfix-expr pieces. 713 return ParsePostfixExpressionSuffix(move(Res)); 714 715 case tok::kw_char: 716 case tok::kw_wchar_t: 717 case tok::kw_bool: 718 case tok::kw_short: 719 case tok::kw_int: 720 case tok::kw_long: 721 case tok::kw_signed: 722 case tok::kw_unsigned: 723 case tok::kw_float: 724 case tok::kw_double: 725 case tok::kw_void: 726 case tok::kw_typename: 727 case tok::kw_typeof: 728 case tok::annot_typename: { 729 if (!getLang().CPlusPlus) { 730 Diag(Tok, diag::err_expected_expression); 731 return ExprError(); 732 } 733 734 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')' 735 // 736 DeclSpec DS; 737 ParseCXXSimpleTypeSpecifier(DS); 738 if (Tok.isNot(tok::l_paren)) 739 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type) 740 << DS.getSourceRange()); 741 742 Res = ParseCXXTypeConstructExpression(DS); 743 // This can be followed by postfix-expr pieces. 744 return ParsePostfixExpressionSuffix(move(Res)); 745 } 746 747 case tok::annot_cxxscope: // [C++] id-expression: qualified-id 748 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id 749 // template-id 750 Res = ParseCXXIdExpression(isAddressOfOperand); 751 return ParsePostfixExpressionSuffix(move(Res)); 752 753 case tok::coloncolon: { 754 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken 755 // annotates the token, tail recurse. 756 if (TryAnnotateTypeOrScopeToken()) 757 return ParseCastExpression(isUnaryExpression, isAddressOfOperand); 758 759 // ::new -> [C++] new-expression 760 // ::delete -> [C++] delete-expression 761 SourceLocation CCLoc = ConsumeToken(); 762 if (Tok.is(tok::kw_new)) 763 return ParseCXXNewExpression(true, CCLoc); 764 if (Tok.is(tok::kw_delete)) 765 return ParseCXXDeleteExpression(true, CCLoc); 766 767 // This is not a type name or scope specifier, it is an invalid expression. 768 Diag(CCLoc, diag::err_expected_expression); 769 return ExprError(); 770 } 771 772 case tok::kw_new: // [C++] new-expression 773 return ParseCXXNewExpression(false, Tok.getLocation()); 774 775 case tok::kw_delete: // [C++] delete-expression 776 return ParseCXXDeleteExpression(false, Tok.getLocation()); 777 778 case tok::kw___is_pod: // [GNU] unary-type-trait 779 case tok::kw___is_class: 780 case tok::kw___is_enum: 781 case tok::kw___is_union: 782 case tok::kw___is_polymorphic: 783 case tok::kw___is_abstract: 784 case tok::kw___has_trivial_constructor: 785 case tok::kw___has_trivial_destructor: 786 return ParseUnaryTypeTrait(); 787 788 case tok::at: { 789 SourceLocation AtLoc = ConsumeToken(); 790 return ParseObjCAtExpression(AtLoc); 791 } 792 case tok::caret: 793 return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression()); 794 case tok::l_square: 795 // These can be followed by postfix-expr pieces. 796 if (getLang().ObjC1) 797 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression()); 798 // FALL THROUGH. 799 default: 800 Diag(Tok, diag::err_expected_expression); 801 return ExprError(); 802 } 803 804 // unreachable. 805 abort(); 806} 807 808/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression 809/// is parsed, this method parses any suffixes that apply. 810/// 811/// postfix-expression: [C99 6.5.2] 812/// primary-expression 813/// postfix-expression '[' expression ']' 814/// postfix-expression '(' argument-expression-list[opt] ')' 815/// postfix-expression '.' identifier 816/// postfix-expression '->' identifier 817/// postfix-expression '++' 818/// postfix-expression '--' 819/// '(' type-name ')' '{' initializer-list '}' 820/// '(' type-name ')' '{' initializer-list ',' '}' 821/// 822/// argument-expression-list: [C99 6.5.2] 823/// argument-expression 824/// argument-expression-list ',' assignment-expression 825/// 826Parser::OwningExprResult 827Parser::ParsePostfixExpressionSuffix(OwningExprResult LHS) { 828 // Now that the primary-expression piece of the postfix-expression has been 829 // parsed, see if there are any postfix-expression pieces here. 830 SourceLocation Loc; 831 while (1) { 832 switch (Tok.getKind()) { 833 default: // Not a postfix-expression suffix. 834 return move(LHS); 835 case tok::l_square: { // postfix-expression: p-e '[' expression ']' 836 Loc = ConsumeBracket(); 837 OwningExprResult Idx(ParseExpression()); 838 839 SourceLocation RLoc = Tok.getLocation(); 840 841 if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) { 842 LHS = Actions.ActOnArraySubscriptExpr(CurScope, move(LHS), Loc, 843 move(Idx), RLoc); 844 } else 845 LHS = ExprError(); 846 847 // Match the ']'. 848 MatchRHSPunctuation(tok::r_square, Loc); 849 break; 850 } 851 852 case tok::l_paren: { // p-e: p-e '(' argument-expression-list[opt] ')' 853 ExprVector ArgExprs(Actions); 854 CommaLocsTy CommaLocs; 855 856 Loc = ConsumeParen(); 857 858 if (Tok.isNot(tok::r_paren)) { 859 if (ParseExpressionList(ArgExprs, CommaLocs)) { 860 SkipUntil(tok::r_paren); 861 return ExprError(); 862 } 863 } 864 865 // Match the ')'. 866 if (Tok.isNot(tok::r_paren)) { 867 MatchRHSPunctuation(tok::r_paren, Loc); 868 return ExprError(); 869 } 870 871 if (!LHS.isInvalid()) { 872 assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&& 873 "Unexpected number of commas!"); 874 LHS = Actions.ActOnCallExpr(CurScope, move(LHS), Loc, 875 move_arg(ArgExprs), CommaLocs.data(), 876 Tok.getLocation()); 877 } 878 879 ConsumeParen(); 880 break; 881 } 882 case tok::arrow: // postfix-expression: p-e '->' identifier 883 case tok::period: { // postfix-expression: p-e '.' identifier 884 tok::TokenKind OpKind = Tok.getKind(); 885 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token. 886 887 if (Tok.isNot(tok::identifier)) { 888 Diag(Tok, diag::err_expected_ident); 889 return ExprError(); 890 } 891 892 if (!LHS.isInvalid()) { 893 LHS = Actions.ActOnMemberReferenceExpr(CurScope, move(LHS), OpLoc, 894 OpKind, Tok.getLocation(), 895 *Tok.getIdentifierInfo(), 896 ObjCImpDecl); 897 } 898 ConsumeToken(); 899 break; 900 } 901 case tok::plusplus: // postfix-expression: postfix-expression '++' 902 case tok::minusminus: // postfix-expression: postfix-expression '--' 903 if (!LHS.isInvalid()) { 904 LHS = Actions.ActOnPostfixUnaryOp(CurScope, Tok.getLocation(), 905 Tok.getKind(), move(LHS)); 906 } 907 ConsumeToken(); 908 break; 909 } 910 } 911} 912 913/// ParseExprAfterTypeofSizeofAlignof - We parsed a typeof/sizeof/alignof and 914/// we are at the start of an expression or a parenthesized type-id. 915/// OpTok is the operand token (typeof/sizeof/alignof). Returns the expression 916/// (isCastExpr == false) or the type (isCastExpr == true). 917/// 918/// unary-expression: [C99 6.5.3] 919/// 'sizeof' unary-expression 920/// 'sizeof' '(' type-name ')' 921/// [GNU] '__alignof' unary-expression 922/// [GNU] '__alignof' '(' type-name ')' 923/// [C++0x] 'alignof' '(' type-id ')' 924/// 925/// [GNU] typeof-specifier: 926/// typeof ( expressions ) 927/// typeof ( type-name ) 928/// [GNU/C++] typeof unary-expression 929/// 930Parser::OwningExprResult 931Parser::ParseExprAfterTypeofSizeofAlignof(const Token &OpTok, 932 bool &isCastExpr, 933 TypeTy *&CastTy, 934 SourceRange &CastRange) { 935 936 assert((OpTok.is(tok::kw_typeof) || OpTok.is(tok::kw_sizeof) || 937 OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof)) && 938 "Not a typeof/sizeof/alignof expression!"); 939 940 OwningExprResult Operand(Actions); 941 942 // If the operand doesn't start with an '(', it must be an expression. 943 if (Tok.isNot(tok::l_paren)) { 944 isCastExpr = false; 945 if (OpTok.is(tok::kw_typeof) && !getLang().CPlusPlus) { 946 Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierInfo(); 947 return ExprError(); 948 } 949 Operand = ParseCastExpression(true/*isUnaryExpression*/); 950 951 } else { 952 // If it starts with a '(', we know that it is either a parenthesized 953 // type-name, or it is a unary-expression that starts with a compound 954 // literal, or starts with a primary-expression that is a parenthesized 955 // expression. 956 ParenParseOption ExprType = CastExpr; 957 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; 958 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/, 959 CastTy, RParenLoc); 960 CastRange = SourceRange(LParenLoc, RParenLoc); 961 962 // If ParseParenExpression parsed a '(typename)' sequence only, then this is 963 // a type. 964 if (ExprType == CastExpr) { 965 isCastExpr = true; 966 return ExprEmpty(); 967 } 968 969 // If this is a parenthesized expression, it is the start of a 970 // unary-expression, but doesn't include any postfix pieces. Parse these 971 // now if present. 972 Operand = ParsePostfixExpressionSuffix(move(Operand)); 973 } 974 975 // If we get here, the operand to the typeof/sizeof/alignof was an expresion. 976 isCastExpr = false; 977 return move(Operand); 978} 979 980 981/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression. 982/// unary-expression: [C99 6.5.3] 983/// 'sizeof' unary-expression 984/// 'sizeof' '(' type-name ')' 985/// [GNU] '__alignof' unary-expression 986/// [GNU] '__alignof' '(' type-name ')' 987/// [C++0x] 'alignof' '(' type-id ')' 988Parser::OwningExprResult Parser::ParseSizeofAlignofExpression() { 989 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof) 990 || Tok.is(tok::kw_alignof)) && 991 "Not a sizeof/alignof expression!"); 992 Token OpTok = Tok; 993 ConsumeToken(); 994 995 bool isCastExpr; 996 TypeTy *CastTy; 997 SourceRange CastRange; 998 OwningExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok, 999 isCastExpr, 1000 CastTy, 1001 CastRange); 1002 1003 if (isCastExpr) 1004 return Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(), 1005 OpTok.is(tok::kw_sizeof), 1006 /*isType=*/true, CastTy, 1007 CastRange); 1008 1009 // If we get here, the operand to the sizeof/alignof was an expresion. 1010 if (!Operand.isInvalid()) 1011 Operand = Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(), 1012 OpTok.is(tok::kw_sizeof), 1013 /*isType=*/false, 1014 Operand.release(), CastRange); 1015 return move(Operand); 1016} 1017 1018/// ParseBuiltinPrimaryExpression 1019/// 1020/// primary-expression: [C99 6.5.1] 1021/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' 1022/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' 1023/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' 1024/// assign-expr ')' 1025/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' 1026/// 1027/// [GNU] offsetof-member-designator: 1028/// [GNU] identifier 1029/// [GNU] offsetof-member-designator '.' identifier 1030/// [GNU] offsetof-member-designator '[' expression ']' 1031/// 1032Parser::OwningExprResult Parser::ParseBuiltinPrimaryExpression() { 1033 OwningExprResult Res(Actions); 1034 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo(); 1035 1036 tok::TokenKind T = Tok.getKind(); 1037 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier. 1038 1039 // All of these start with an open paren. 1040 if (Tok.isNot(tok::l_paren)) 1041 return ExprError(Diag(Tok, diag::err_expected_lparen_after_id) 1042 << BuiltinII); 1043 1044 SourceLocation LParenLoc = ConsumeParen(); 1045 // TODO: Build AST. 1046 1047 switch (T) { 1048 default: assert(0 && "Not a builtin primary expression!"); 1049 case tok::kw___builtin_va_arg: { 1050 OwningExprResult Expr(ParseAssignmentExpression()); 1051 if (Expr.isInvalid()) { 1052 SkipUntil(tok::r_paren); 1053 return ExprError(); 1054 } 1055 1056 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1057 return ExprError(); 1058 1059 TypeResult Ty = ParseTypeName(); 1060 1061 if (Tok.isNot(tok::r_paren)) { 1062 Diag(Tok, diag::err_expected_rparen); 1063 return ExprError(); 1064 } 1065 if (Ty.isInvalid()) 1066 Res = ExprError(); 1067 else 1068 Res = Actions.ActOnVAArg(StartLoc, move(Expr), Ty.get(), ConsumeParen()); 1069 break; 1070 } 1071 case tok::kw___builtin_offsetof: { 1072 SourceLocation TypeLoc = Tok.getLocation(); 1073 TypeResult Ty = ParseTypeName(); 1074 if (Ty.isInvalid()) { 1075 SkipUntil(tok::r_paren); 1076 return ExprError(); 1077 } 1078 1079 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1080 return ExprError(); 1081 1082 // We must have at least one identifier here. 1083 if (Tok.isNot(tok::identifier)) { 1084 Diag(Tok, diag::err_expected_ident); 1085 SkipUntil(tok::r_paren); 1086 return ExprError(); 1087 } 1088 1089 // Keep track of the various subcomponents we see. 1090 llvm::SmallVector<Action::OffsetOfComponent, 4> Comps; 1091 1092 Comps.push_back(Action::OffsetOfComponent()); 1093 Comps.back().isBrackets = false; 1094 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1095 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken(); 1096 1097 // FIXME: This loop leaks the index expressions on error. 1098 while (1) { 1099 if (Tok.is(tok::period)) { 1100 // offsetof-member-designator: offsetof-member-designator '.' identifier 1101 Comps.push_back(Action::OffsetOfComponent()); 1102 Comps.back().isBrackets = false; 1103 Comps.back().LocStart = ConsumeToken(); 1104 1105 if (Tok.isNot(tok::identifier)) { 1106 Diag(Tok, diag::err_expected_ident); 1107 SkipUntil(tok::r_paren); 1108 return ExprError(); 1109 } 1110 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1111 Comps.back().LocEnd = ConsumeToken(); 1112 1113 } else if (Tok.is(tok::l_square)) { 1114 // offsetof-member-designator: offsetof-member-design '[' expression ']' 1115 Comps.push_back(Action::OffsetOfComponent()); 1116 Comps.back().isBrackets = true; 1117 Comps.back().LocStart = ConsumeBracket(); 1118 Res = ParseExpression(); 1119 if (Res.isInvalid()) { 1120 SkipUntil(tok::r_paren); 1121 return move(Res); 1122 } 1123 Comps.back().U.E = Res.release(); 1124 1125 Comps.back().LocEnd = 1126 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart); 1127 } else if (Tok.is(tok::r_paren)) { 1128 if (Ty.isInvalid()) 1129 Res = ExprError(); 1130 else 1131 Res = Actions.ActOnBuiltinOffsetOf(CurScope, StartLoc, TypeLoc, 1132 Ty.get(), &Comps[0], 1133 Comps.size(), ConsumeParen()); 1134 break; 1135 } else { 1136 // Error occurred. 1137 return ExprError(); 1138 } 1139 } 1140 break; 1141 } 1142 case tok::kw___builtin_choose_expr: { 1143 OwningExprResult Cond(ParseAssignmentExpression()); 1144 if (Cond.isInvalid()) { 1145 SkipUntil(tok::r_paren); 1146 return move(Cond); 1147 } 1148 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1149 return ExprError(); 1150 1151 OwningExprResult Expr1(ParseAssignmentExpression()); 1152 if (Expr1.isInvalid()) { 1153 SkipUntil(tok::r_paren); 1154 return move(Expr1); 1155 } 1156 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1157 return ExprError(); 1158 1159 OwningExprResult Expr2(ParseAssignmentExpression()); 1160 if (Expr2.isInvalid()) { 1161 SkipUntil(tok::r_paren); 1162 return move(Expr2); 1163 } 1164 if (Tok.isNot(tok::r_paren)) { 1165 Diag(Tok, diag::err_expected_rparen); 1166 return ExprError(); 1167 } 1168 Res = Actions.ActOnChooseExpr(StartLoc, move(Cond), move(Expr1), 1169 move(Expr2), ConsumeParen()); 1170 break; 1171 } 1172 case tok::kw___builtin_types_compatible_p: 1173 TypeResult Ty1 = ParseTypeName(); 1174 1175 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1176 return ExprError(); 1177 1178 TypeResult Ty2 = ParseTypeName(); 1179 1180 if (Tok.isNot(tok::r_paren)) { 1181 Diag(Tok, diag::err_expected_rparen); 1182 return ExprError(); 1183 } 1184 1185 if (Ty1.isInvalid() || Ty2.isInvalid()) 1186 Res = ExprError(); 1187 else 1188 Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1.get(), Ty2.get(), 1189 ConsumeParen()); 1190 break; 1191 } 1192 1193 // These can be followed by postfix-expr pieces because they are 1194 // primary-expressions. 1195 return ParsePostfixExpressionSuffix(move(Res)); 1196} 1197 1198/// ParseParenExpression - This parses the unit that starts with a '(' token, 1199/// based on what is allowed by ExprType. The actual thing parsed is returned 1200/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type, 1201/// not the parsed cast-expression. 1202/// 1203/// primary-expression: [C99 6.5.1] 1204/// '(' expression ')' 1205/// [GNU] '(' compound-statement ')' (if !ParenExprOnly) 1206/// postfix-expression: [C99 6.5.2] 1207/// '(' type-name ')' '{' initializer-list '}' 1208/// '(' type-name ')' '{' initializer-list ',' '}' 1209/// cast-expression: [C99 6.5.4] 1210/// '(' type-name ')' cast-expression 1211/// 1212Parser::OwningExprResult 1213Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, 1214 TypeTy *&CastTy, SourceLocation &RParenLoc) { 1215 assert(Tok.is(tok::l_paren) && "Not a paren expr!"); 1216 GreaterThanIsOperatorScope G(GreaterThanIsOperator, true); 1217 SourceLocation OpenLoc = ConsumeParen(); 1218 OwningExprResult Result(Actions, true); 1219 CastTy = 0; 1220 1221 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) { 1222 Diag(Tok, diag::ext_gnu_statement_expr); 1223 OwningStmtResult Stmt(ParseCompoundStatement(true)); 1224 ExprType = CompoundStmt; 1225 1226 // If the substmt parsed correctly, build the AST node. 1227 if (!Stmt.isInvalid() && Tok.is(tok::r_paren)) 1228 Result = Actions.ActOnStmtExpr(OpenLoc, move(Stmt), Tok.getLocation()); 1229 1230 } else if (ExprType >= CompoundLiteral && isTypeIdInParens()) { 1231 1232 // Otherwise, this is a compound literal expression or cast expression. 1233 TypeResult Ty = ParseTypeName(); 1234 1235 // Match the ')'. 1236 if (Tok.is(tok::r_paren)) 1237 RParenLoc = ConsumeParen(); 1238 else 1239 MatchRHSPunctuation(tok::r_paren, OpenLoc); 1240 1241 if (Tok.is(tok::l_brace)) { 1242 ExprType = CompoundLiteral; 1243 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc); 1244 } 1245 1246 if (ExprType == CastExpr) { 1247 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. 1248 1249 if (Ty.isInvalid()) 1250 return ExprError(); 1251 1252 CastTy = Ty.get(); 1253 1254 if (stopIfCastExpr) { 1255 // Note that this doesn't parse the subsequent cast-expression, it just 1256 // returns the parsed type to the callee. 1257 return OwningExprResult(Actions); 1258 } 1259 1260 // Parse the cast-expression that follows it next. 1261 // TODO: For cast expression with CastTy. 1262 Result = ParseCastExpression(false); 1263 if (!Result.isInvalid()) 1264 Result = Actions.ActOnCastExpr(OpenLoc, CastTy, RParenLoc,move(Result)); 1265 return move(Result); 1266 } 1267 1268 Diag(Tok, diag::err_expected_lbrace_in_compound_literal); 1269 return ExprError(); 1270 } else { 1271 Result = ParseExpression(); 1272 ExprType = SimpleExpr; 1273 if (!Result.isInvalid() && Tok.is(tok::r_paren)) 1274 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), move(Result)); 1275 } 1276 1277 // Match the ')'. 1278 if (Result.isInvalid()) { 1279 SkipUntil(tok::r_paren); 1280 return ExprError(); 1281 } 1282 1283 if (Tok.is(tok::r_paren)) 1284 RParenLoc = ConsumeParen(); 1285 else 1286 MatchRHSPunctuation(tok::r_paren, OpenLoc); 1287 1288 return move(Result); 1289} 1290 1291/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name 1292/// and we are at the left brace. 1293/// 1294/// postfix-expression: [C99 6.5.2] 1295/// '(' type-name ')' '{' initializer-list '}' 1296/// '(' type-name ')' '{' initializer-list ',' '}' 1297/// 1298Parser::OwningExprResult 1299Parser::ParseCompoundLiteralExpression(TypeTy *Ty, 1300 SourceLocation LParenLoc, 1301 SourceLocation RParenLoc) { 1302 assert(Tok.is(tok::l_brace) && "Not a compound literal!"); 1303 if (!getLang().C99) // Compound literals don't exist in C90. 1304 Diag(LParenLoc, diag::ext_c99_compound_literal); 1305 OwningExprResult Result = ParseInitializer(); 1306 if (!Result.isInvalid() && Ty) 1307 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, move(Result)); 1308 return move(Result); 1309} 1310 1311/// ParseStringLiteralExpression - This handles the various token types that 1312/// form string literals, and also handles string concatenation [C99 5.1.1.2, 1313/// translation phase #6]. 1314/// 1315/// primary-expression: [C99 6.5.1] 1316/// string-literal 1317Parser::OwningExprResult Parser::ParseStringLiteralExpression() { 1318 assert(isTokenStringLiteral() && "Not a string literal!"); 1319 1320 // String concat. Note that keywords like __func__ and __FUNCTION__ are not 1321 // considered to be strings for concatenation purposes. 1322 llvm::SmallVector<Token, 4> StringToks; 1323 1324 do { 1325 StringToks.push_back(Tok); 1326 ConsumeStringToken(); 1327 } while (isTokenStringLiteral()); 1328 1329 // Pass the set of string tokens, ready for concatenation, to the actions. 1330 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size()); 1331} 1332 1333/// ParseExpressionList - Used for C/C++ (argument-)expression-list. 1334/// 1335/// argument-expression-list: 1336/// assignment-expression 1337/// argument-expression-list , assignment-expression 1338/// 1339/// [C++] expression-list: 1340/// [C++] assignment-expression 1341/// [C++] expression-list , assignment-expression 1342/// 1343bool Parser::ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs) { 1344 while (1) { 1345 OwningExprResult Expr(ParseAssignmentExpression()); 1346 if (Expr.isInvalid()) 1347 return true; 1348 1349 Exprs.push_back(Expr.release()); 1350 1351 if (Tok.isNot(tok::comma)) 1352 return false; 1353 // Move to the next argument, remember where the comma was. 1354 CommaLocs.push_back(ConsumeToken()); 1355 } 1356} 1357 1358/// ParseBlockId - Parse a block-id, which roughly looks like int (int x). 1359/// 1360/// [clang] block-id: 1361/// [clang] specifier-qualifier-list block-declarator 1362/// 1363void Parser::ParseBlockId() { 1364 // Parse the specifier-qualifier-list piece. 1365 DeclSpec DS; 1366 ParseSpecifierQualifierList(DS); 1367 1368 // Parse the block-declarator. 1369 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext); 1370 ParseDeclarator(DeclaratorInfo); 1371 1372 // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes. 1373 DeclaratorInfo.AddAttributes(DS.TakeAttributes(), 1374 SourceLocation()); 1375 1376 if (Tok.is(tok::kw___attribute)) { 1377 SourceLocation Loc; 1378 AttributeList *AttrList = ParseAttributes(&Loc); 1379 DeclaratorInfo.AddAttributes(AttrList, Loc); 1380 } 1381 1382 // Inform sema that we are starting a block. 1383 Actions.ActOnBlockArguments(DeclaratorInfo, CurScope); 1384} 1385 1386/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks 1387/// like ^(int x){ return x+1; } 1388/// 1389/// block-literal: 1390/// [clang] '^' block-args[opt] compound-statement 1391/// [clang] '^' block-id compound-statement 1392/// [clang] block-args: 1393/// [clang] '(' parameter-list ')' 1394/// 1395Parser::OwningExprResult Parser::ParseBlockLiteralExpression() { 1396 assert(Tok.is(tok::caret) && "block literal starts with ^"); 1397 SourceLocation CaretLoc = ConsumeToken(); 1398 1399 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc, 1400 "block literal parsing"); 1401 1402 // Enter a scope to hold everything within the block. This includes the 1403 // argument decls, decls within the compound expression, etc. This also 1404 // allows determining whether a variable reference inside the block is 1405 // within or outside of the block. 1406 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope | 1407 Scope::BreakScope | Scope::ContinueScope | 1408 Scope::DeclScope); 1409 1410 // Inform sema that we are starting a block. 1411 Actions.ActOnBlockStart(CaretLoc, CurScope); 1412 1413 // Parse the return type if present. 1414 DeclSpec DS; 1415 Declarator ParamInfo(DS, Declarator::BlockLiteralContext); 1416 // FIXME: Since the return type isn't actually parsed, it can't be used to 1417 // fill ParamInfo with an initial valid range, so do it manually. 1418 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation())); 1419 1420 // If this block has arguments, parse them. There is no ambiguity here with 1421 // the expression case, because the expression case requires a parameter list. 1422 if (Tok.is(tok::l_paren)) { 1423 ParseParenDeclarator(ParamInfo); 1424 // Parse the pieces after the identifier as if we had "int(...)". 1425 // SetIdentifier sets the source range end, but in this case we're past 1426 // that location. 1427 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd(); 1428 ParamInfo.SetIdentifier(0, CaretLoc); 1429 ParamInfo.SetRangeEnd(Tmp); 1430 if (ParamInfo.isInvalidType()) { 1431 // If there was an error parsing the arguments, they may have 1432 // tried to use ^(x+y) which requires an argument list. Just 1433 // skip the whole block literal. 1434 Actions.ActOnBlockError(CaretLoc, CurScope); 1435 return ExprError(); 1436 } 1437 1438 if (Tok.is(tok::kw___attribute)) { 1439 SourceLocation Loc; 1440 AttributeList *AttrList = ParseAttributes(&Loc); 1441 ParamInfo.AddAttributes(AttrList, Loc); 1442 } 1443 1444 // Inform sema that we are starting a block. 1445 Actions.ActOnBlockArguments(ParamInfo, CurScope); 1446 } else if (!Tok.is(tok::l_brace)) { 1447 ParseBlockId(); 1448 } else { 1449 // Otherwise, pretend we saw (void). 1450 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false, 1451 SourceLocation(), 1452 0, 0, 0, 1453 false, false, 0, 0, 1454 CaretLoc, ParamInfo), 1455 CaretLoc); 1456 1457 if (Tok.is(tok::kw___attribute)) { 1458 SourceLocation Loc; 1459 AttributeList *AttrList = ParseAttributes(&Loc); 1460 ParamInfo.AddAttributes(AttrList, Loc); 1461 } 1462 1463 // Inform sema that we are starting a block. 1464 Actions.ActOnBlockArguments(ParamInfo, CurScope); 1465 } 1466 1467 1468 OwningExprResult Result(Actions, true); 1469 if (!Tok.is(tok::l_brace)) { 1470 // Saw something like: ^expr 1471 Diag(Tok, diag::err_expected_expression); 1472 Actions.ActOnBlockError(CaretLoc, CurScope); 1473 return ExprError(); 1474 } 1475 1476 OwningStmtResult Stmt(ParseCompoundStatementBody()); 1477 if (!Stmt.isInvalid()) 1478 Result = Actions.ActOnBlockStmtExpr(CaretLoc, move(Stmt), CurScope); 1479 else 1480 Actions.ActOnBlockError(CaretLoc, CurScope); 1481 return move(Result); 1482} 1483