ParseExpr.cpp revision 2e0cdb4e5442c2f1976dcf8f304bfa6b5f90f728
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/// 403Parser::OwningExprResult Parser::ParseCastExpression(bool isUnaryExpression, 404 bool isAddressOfOperand) { 405 bool NotCastExpr; 406 OwningExprResult Res = ParseCastExpression(isUnaryExpression, 407 isAddressOfOperand, 408 NotCastExpr); 409 if (NotCastExpr) 410 Diag(Tok, diag::err_expected_expression); 411 return move(Res); 412} 413 414/// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is 415/// true, parse a unary-expression. isAddressOfOperand exists because an 416/// id-expression that is the operand of address-of gets special treatment 417/// due to member pointers. NotCastExpr is set to true if the token is not the 418/// start of a cast-expression, and no diagnostic is emitted in this case. 419/// 420/// cast-expression: [C99 6.5.4] 421/// unary-expression 422/// '(' type-name ')' cast-expression 423/// 424/// unary-expression: [C99 6.5.3] 425/// postfix-expression 426/// '++' unary-expression 427/// '--' unary-expression 428/// unary-operator cast-expression 429/// 'sizeof' unary-expression 430/// 'sizeof' '(' type-name ')' 431/// [GNU] '__alignof' unary-expression 432/// [GNU] '__alignof' '(' type-name ')' 433/// [C++0x] 'alignof' '(' type-id ')' 434/// [GNU] '&&' identifier 435/// [C++] new-expression 436/// [C++] delete-expression 437/// 438/// unary-operator: one of 439/// '&' '*' '+' '-' '~' '!' 440/// [GNU] '__extension__' '__real' '__imag' 441/// 442/// primary-expression: [C99 6.5.1] 443/// [C99] identifier 444/// [C++] id-expression 445/// constant 446/// string-literal 447/// [C++] boolean-literal [C++ 2.13.5] 448/// [C++0x] 'nullptr' [C++0x 2.14.7] 449/// '(' expression ')' 450/// '__func__' [C99 6.4.2.2] 451/// [GNU] '__FUNCTION__' 452/// [GNU] '__PRETTY_FUNCTION__' 453/// [GNU] '(' compound-statement ')' 454/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' 455/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' 456/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' 457/// assign-expr ')' 458/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' 459/// [GNU] '__null' 460/// [OBJC] '[' objc-message-expr ']' 461/// [OBJC] '@selector' '(' objc-selector-arg ')' 462/// [OBJC] '@protocol' '(' identifier ')' 463/// [OBJC] '@encode' '(' type-name ')' 464/// [OBJC] objc-string-literal 465/// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3] 466/// [C++] typename-specifier '(' expression-list[opt] ')' [TODO] 467/// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 468/// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 469/// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 470/// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] 471/// [C++] 'typeid' '(' expression ')' [C++ 5.2p1] 472/// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1] 473/// [C++] 'this' [C++ 9.3.2] 474/// [G++] unary-type-trait '(' type-id ')' 475/// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO] 476/// [clang] '^' block-literal 477/// 478/// constant: [C99 6.4.4] 479/// integer-constant 480/// floating-constant 481/// enumeration-constant -> identifier 482/// character-constant 483/// 484/// id-expression: [C++ 5.1] 485/// unqualified-id 486/// qualified-id [TODO] 487/// 488/// unqualified-id: [C++ 5.1] 489/// identifier 490/// operator-function-id 491/// conversion-function-id [TODO] 492/// '~' class-name [TODO] 493/// template-id [TODO] 494/// 495/// new-expression: [C++ 5.3.4] 496/// '::'[opt] 'new' new-placement[opt] new-type-id 497/// new-initializer[opt] 498/// '::'[opt] 'new' new-placement[opt] '(' type-id ')' 499/// new-initializer[opt] 500/// 501/// delete-expression: [C++ 5.3.5] 502/// '::'[opt] 'delete' cast-expression 503/// '::'[opt] 'delete' '[' ']' cast-expression 504/// 505/// [GNU] unary-type-trait: 506/// '__has_nothrow_assign' [TODO] 507/// '__has_nothrow_copy' [TODO] 508/// '__has_nothrow_constructor' [TODO] 509/// '__has_trivial_assign' [TODO] 510/// '__has_trivial_copy' [TODO] 511/// '__has_trivial_constructor' 512/// '__has_trivial_destructor' 513/// '__has_virtual_destructor' [TODO] 514/// '__is_abstract' [TODO] 515/// '__is_class' 516/// '__is_empty' [TODO] 517/// '__is_enum' 518/// '__is_pod' 519/// '__is_polymorphic' 520/// '__is_union' 521/// 522/// [GNU] binary-type-trait: 523/// '__is_base_of' [TODO] 524/// 525Parser::OwningExprResult Parser::ParseCastExpression(bool isUnaryExpression, 526 bool isAddressOfOperand, 527 bool &NotCastExpr) { 528 OwningExprResult Res(Actions); 529 tok::TokenKind SavedKind = Tok.getKind(); 530 NotCastExpr = false; 531 532 // This handles all of cast-expression, unary-expression, postfix-expression, 533 // and primary-expression. We handle them together like this for efficiency 534 // and to simplify handling of an expression starting with a '(' token: which 535 // may be one of a parenthesized expression, cast-expression, compound literal 536 // expression, or statement expression. 537 // 538 // If the parsed tokens consist of a primary-expression, the cases below 539 // call ParsePostfixExpressionSuffix to handle the postfix expression 540 // suffixes. Cases that cannot be followed by postfix exprs should 541 // return without invoking ParsePostfixExpressionSuffix. 542 switch (SavedKind) { 543 case tok::l_paren: { 544 // If this expression is limited to being a unary-expression, the parent can 545 // not start a cast expression. 546 ParenParseOption ParenExprType = 547 isUnaryExpression ? CompoundLiteral : CastExpr; 548 TypeTy *CastTy; 549 SourceLocation LParenLoc = Tok.getLocation(); 550 SourceLocation RParenLoc; 551 Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/, 552 CastTy, RParenLoc); 553 if (Res.isInvalid()) return move(Res); 554 555 switch (ParenExprType) { 556 case SimpleExpr: break; // Nothing else to do. 557 case CompoundStmt: break; // Nothing else to do. 558 case CompoundLiteral: 559 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of 560 // postfix-expression exist, parse them now. 561 break; 562 case CastExpr: 563 // We have parsed the cast-expression and no postfix-expr pieces are 564 // following. 565 return move(Res); 566 } 567 568 // These can be followed by postfix-expr pieces. 569 return ParsePostfixExpressionSuffix(move(Res)); 570 } 571 572 // primary-expression 573 case tok::numeric_constant: 574 // constant: integer-constant 575 // constant: floating-constant 576 577 Res = Actions.ActOnNumericConstant(Tok); 578 ConsumeToken(); 579 580 // These can be followed by postfix-expr pieces. 581 return ParsePostfixExpressionSuffix(move(Res)); 582 583 case tok::kw_true: 584 case tok::kw_false: 585 return ParseCXXBoolLiteral(); 586 587 case tok::kw_nullptr: 588 return Actions.ActOnCXXNullPtrLiteral(ConsumeToken()); 589 590 case tok::identifier: { // primary-expression: identifier 591 // unqualified-id: identifier 592 // constant: enumeration-constant 593 // Turn a potentially qualified name into a annot_typename or 594 // annot_cxxscope if it would be valid. This handles things like x::y, etc. 595 if (getLang().CPlusPlus) { 596 // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. 597 if (TryAnnotateTypeOrScopeToken()) 598 return ParseCastExpression(isUnaryExpression, isAddressOfOperand); 599 } 600 601 // Support 'Class.property' notation. 602 // We don't use isTokObjCMessageIdentifierReceiver(), since it allows 603 // 'super' (which is inappropriate here). 604 if (getLang().ObjC1 && 605 Actions.getTypeName(*Tok.getIdentifierInfo(), 606 Tok.getLocation(), CurScope) && 607 NextToken().is(tok::period)) { 608 IdentifierInfo &ReceiverName = *Tok.getIdentifierInfo(); 609 SourceLocation IdentLoc = ConsumeToken(); 610 SourceLocation DotLoc = ConsumeToken(); 611 612 if (Tok.isNot(tok::identifier)) { 613 Diag(Tok, diag::err_expected_ident); 614 return ExprError(); 615 } 616 IdentifierInfo &PropertyName = *Tok.getIdentifierInfo(); 617 SourceLocation PropertyLoc = ConsumeToken(); 618 619 Res = Actions.ActOnClassPropertyRefExpr(ReceiverName, PropertyName, 620 IdentLoc, PropertyLoc); 621 // These can be followed by postfix-expr pieces. 622 return ParsePostfixExpressionSuffix(move(Res)); 623 } 624 // Consume the identifier so that we can see if it is followed by a '('. 625 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we 626 // need to know whether or not this identifier is a function designator or 627 // not. 628 IdentifierInfo &II = *Tok.getIdentifierInfo(); 629 SourceLocation L = ConsumeToken(); 630 Res = Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren)); 631 // These can be followed by postfix-expr pieces. 632 return ParsePostfixExpressionSuffix(move(Res)); 633 } 634 case tok::char_constant: // constant: character-constant 635 Res = Actions.ActOnCharacterConstant(Tok); 636 ConsumeToken(); 637 // These can be followed by postfix-expr pieces. 638 return ParsePostfixExpressionSuffix(move(Res)); 639 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2] 640 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU] 641 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU] 642 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind); 643 ConsumeToken(); 644 // These can be followed by postfix-expr pieces. 645 return ParsePostfixExpressionSuffix(move(Res)); 646 case tok::string_literal: // primary-expression: string-literal 647 case tok::wide_string_literal: 648 Res = ParseStringLiteralExpression(); 649 if (Res.isInvalid()) return move(Res); 650 // This can be followed by postfix-expr pieces (e.g. "foo"[1]). 651 return ParsePostfixExpressionSuffix(move(Res)); 652 case tok::kw___builtin_va_arg: 653 case tok::kw___builtin_offsetof: 654 case tok::kw___builtin_choose_expr: 655 case tok::kw___builtin_types_compatible_p: 656 return ParseBuiltinPrimaryExpression(); 657 case tok::kw___null: 658 return Actions.ActOnGNUNullExpr(ConsumeToken()); 659 break; 660 case tok::plusplus: // unary-expression: '++' unary-expression 661 case tok::minusminus: { // unary-expression: '--' unary-expression 662 SourceLocation SavedLoc = ConsumeToken(); 663 Res = ParseCastExpression(true); 664 if (!Res.isInvalid()) 665 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, move(Res)); 666 return move(Res); 667 } 668 case tok::amp: { // unary-expression: '&' cast-expression 669 // Special treatment because of member pointers 670 SourceLocation SavedLoc = ConsumeToken(); 671 Res = ParseCastExpression(false, true); 672 if (!Res.isInvalid()) 673 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, move(Res)); 674 return move(Res); 675 } 676 677 case tok::star: // unary-expression: '*' cast-expression 678 case tok::plus: // unary-expression: '+' cast-expression 679 case tok::minus: // unary-expression: '-' cast-expression 680 case tok::tilde: // unary-expression: '~' cast-expression 681 case tok::exclaim: // unary-expression: '!' cast-expression 682 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU] 683 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU] 684 SourceLocation SavedLoc = ConsumeToken(); 685 Res = ParseCastExpression(false); 686 if (!Res.isInvalid()) 687 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, move(Res)); 688 return move(Res); 689 } 690 691 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU] 692 // __extension__ silences extension warnings in the subexpression. 693 ExtensionRAIIObject O(Diags); // Use RAII to do this. 694 SourceLocation SavedLoc = ConsumeToken(); 695 Res = ParseCastExpression(false); 696 if (!Res.isInvalid()) 697 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, move(Res)); 698 return move(Res); 699 } 700 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression 701 // unary-expression: 'sizeof' '(' type-name ')' 702 case tok::kw_alignof: 703 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression 704 // unary-expression: '__alignof' '(' type-name ')' 705 // unary-expression: 'alignof' '(' type-id ')' 706 return ParseSizeofAlignofExpression(); 707 case tok::ampamp: { // unary-expression: '&&' identifier 708 SourceLocation AmpAmpLoc = ConsumeToken(); 709 if (Tok.isNot(tok::identifier)) 710 return ExprError(Diag(Tok, diag::err_expected_ident)); 711 712 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label); 713 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), 714 Tok.getIdentifierInfo()); 715 ConsumeToken(); 716 return move(Res); 717 } 718 case tok::kw_const_cast: 719 case tok::kw_dynamic_cast: 720 case tok::kw_reinterpret_cast: 721 case tok::kw_static_cast: 722 Res = ParseCXXCasts(); 723 // These can be followed by postfix-expr pieces. 724 return ParsePostfixExpressionSuffix(move(Res)); 725 case tok::kw_typeid: 726 Res = ParseCXXTypeid(); 727 // This can be followed by postfix-expr pieces. 728 return ParsePostfixExpressionSuffix(move(Res)); 729 case tok::kw_this: 730 Res = ParseCXXThis(); 731 // This can be followed by postfix-expr pieces. 732 return ParsePostfixExpressionSuffix(move(Res)); 733 734 case tok::kw_char: 735 case tok::kw_wchar_t: 736 case tok::kw_bool: 737 case tok::kw_short: 738 case tok::kw_int: 739 case tok::kw_long: 740 case tok::kw_signed: 741 case tok::kw_unsigned: 742 case tok::kw_float: 743 case tok::kw_double: 744 case tok::kw_void: 745 case tok::kw_typename: 746 case tok::kw_typeof: 747 case tok::annot_typename: { 748 if (!getLang().CPlusPlus) { 749 Diag(Tok, diag::err_expected_expression); 750 return ExprError(); 751 } 752 753 if (SavedKind == tok::kw_typename) { 754 // postfix-expression: typename-specifier '(' expression-list[opt] ')' 755 if (!TryAnnotateTypeOrScopeToken()) 756 return ExprError(); 757 } 758 759 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')' 760 // 761 DeclSpec DS; 762 ParseCXXSimpleTypeSpecifier(DS); 763 if (Tok.isNot(tok::l_paren)) 764 return ExprError(Diag(Tok, diag::err_expected_lparen_after_type) 765 << DS.getSourceRange()); 766 767 Res = ParseCXXTypeConstructExpression(DS); 768 // This can be followed by postfix-expr pieces. 769 return ParsePostfixExpressionSuffix(move(Res)); 770 } 771 772 case tok::annot_cxxscope: // [C++] id-expression: qualified-id 773 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id 774 // template-id 775 Res = ParseCXXIdExpression(isAddressOfOperand); 776 return ParsePostfixExpressionSuffix(move(Res)); 777 778 case tok::coloncolon: { 779 // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken 780 // annotates the token, tail recurse. 781 if (TryAnnotateTypeOrScopeToken()) 782 return ParseCastExpression(isUnaryExpression, isAddressOfOperand); 783 784 // ::new -> [C++] new-expression 785 // ::delete -> [C++] delete-expression 786 SourceLocation CCLoc = ConsumeToken(); 787 if (Tok.is(tok::kw_new)) 788 return ParseCXXNewExpression(true, CCLoc); 789 if (Tok.is(tok::kw_delete)) 790 return ParseCXXDeleteExpression(true, CCLoc); 791 792 // This is not a type name or scope specifier, it is an invalid expression. 793 Diag(CCLoc, diag::err_expected_expression); 794 return ExprError(); 795 } 796 797 case tok::kw_new: // [C++] new-expression 798 return ParseCXXNewExpression(false, Tok.getLocation()); 799 800 case tok::kw_delete: // [C++] delete-expression 801 return ParseCXXDeleteExpression(false, Tok.getLocation()); 802 803 case tok::kw___is_pod: // [GNU] unary-type-trait 804 case tok::kw___is_class: 805 case tok::kw___is_enum: 806 case tok::kw___is_union: 807 case tok::kw___is_polymorphic: 808 case tok::kw___is_abstract: 809 case tok::kw___has_trivial_constructor: 810 case tok::kw___has_trivial_destructor: 811 return ParseUnaryTypeTrait(); 812 813 case tok::at: { 814 SourceLocation AtLoc = ConsumeToken(); 815 return ParseObjCAtExpression(AtLoc); 816 } 817 case tok::caret: 818 return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression()); 819 case tok::l_square: 820 // These can be followed by postfix-expr pieces. 821 if (getLang().ObjC1) 822 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression()); 823 // FALL THROUGH. 824 default: 825 NotCastExpr = true; 826 return ExprError(); 827 } 828 829 // unreachable. 830 abort(); 831} 832 833/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression 834/// is parsed, this method parses any suffixes that apply. 835/// 836/// postfix-expression: [C99 6.5.2] 837/// primary-expression 838/// postfix-expression '[' expression ']' 839/// postfix-expression '(' argument-expression-list[opt] ')' 840/// postfix-expression '.' identifier 841/// postfix-expression '->' identifier 842/// postfix-expression '++' 843/// postfix-expression '--' 844/// '(' type-name ')' '{' initializer-list '}' 845/// '(' type-name ')' '{' initializer-list ',' '}' 846/// 847/// argument-expression-list: [C99 6.5.2] 848/// argument-expression 849/// argument-expression-list ',' assignment-expression 850/// 851Parser::OwningExprResult 852Parser::ParsePostfixExpressionSuffix(OwningExprResult LHS) { 853 // Now that the primary-expression piece of the postfix-expression has been 854 // parsed, see if there are any postfix-expression pieces here. 855 SourceLocation Loc; 856 while (1) { 857 switch (Tok.getKind()) { 858 default: // Not a postfix-expression suffix. 859 return move(LHS); 860 case tok::l_square: { // postfix-expression: p-e '[' expression ']' 861 Loc = ConsumeBracket(); 862 OwningExprResult Idx(ParseExpression()); 863 864 SourceLocation RLoc = Tok.getLocation(); 865 866 if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) { 867 LHS = Actions.ActOnArraySubscriptExpr(CurScope, move(LHS), Loc, 868 move(Idx), RLoc); 869 } else 870 LHS = ExprError(); 871 872 // Match the ']'. 873 MatchRHSPunctuation(tok::r_square, Loc); 874 break; 875 } 876 877 case tok::l_paren: { // p-e: p-e '(' argument-expression-list[opt] ')' 878 ExprVector ArgExprs(Actions); 879 CommaLocsTy CommaLocs; 880 881 Loc = ConsumeParen(); 882 883 if (Tok.isNot(tok::r_paren)) { 884 if (ParseExpressionList(ArgExprs, CommaLocs)) { 885 SkipUntil(tok::r_paren); 886 return ExprError(); 887 } 888 } 889 890 // Match the ')'. 891 if (Tok.isNot(tok::r_paren)) { 892 MatchRHSPunctuation(tok::r_paren, Loc); 893 return ExprError(); 894 } 895 896 if (!LHS.isInvalid()) { 897 assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&& 898 "Unexpected number of commas!"); 899 LHS = Actions.ActOnCallExpr(CurScope, move(LHS), Loc, 900 move_arg(ArgExprs), CommaLocs.data(), 901 Tok.getLocation()); 902 } 903 904 ConsumeParen(); 905 break; 906 } 907 case tok::arrow: // postfix-expression: p-e '->' identifier 908 case tok::period: { // postfix-expression: p-e '.' identifier 909 tok::TokenKind OpKind = Tok.getKind(); 910 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token. 911 912 if (Tok.isNot(tok::identifier)) { 913 Diag(Tok, diag::err_expected_ident); 914 return ExprError(); 915 } 916 917 if (!LHS.isInvalid()) { 918 LHS = Actions.ActOnMemberReferenceExpr(CurScope, move(LHS), OpLoc, 919 OpKind, Tok.getLocation(), 920 *Tok.getIdentifierInfo(), 921 ObjCImpDecl); 922 } 923 ConsumeToken(); 924 break; 925 } 926 case tok::plusplus: // postfix-expression: postfix-expression '++' 927 case tok::minusminus: // postfix-expression: postfix-expression '--' 928 if (!LHS.isInvalid()) { 929 LHS = Actions.ActOnPostfixUnaryOp(CurScope, Tok.getLocation(), 930 Tok.getKind(), move(LHS)); 931 } 932 ConsumeToken(); 933 break; 934 } 935 } 936} 937 938/// ParseExprAfterTypeofSizeofAlignof - We parsed a typeof/sizeof/alignof and 939/// we are at the start of an expression or a parenthesized type-id. 940/// OpTok is the operand token (typeof/sizeof/alignof). Returns the expression 941/// (isCastExpr == false) or the type (isCastExpr == true). 942/// 943/// unary-expression: [C99 6.5.3] 944/// 'sizeof' unary-expression 945/// 'sizeof' '(' type-name ')' 946/// [GNU] '__alignof' unary-expression 947/// [GNU] '__alignof' '(' type-name ')' 948/// [C++0x] 'alignof' '(' type-id ')' 949/// 950/// [GNU] typeof-specifier: 951/// typeof ( expressions ) 952/// typeof ( type-name ) 953/// [GNU/C++] typeof unary-expression 954/// 955Parser::OwningExprResult 956Parser::ParseExprAfterTypeofSizeofAlignof(const Token &OpTok, 957 bool &isCastExpr, 958 TypeTy *&CastTy, 959 SourceRange &CastRange) { 960 961 assert((OpTok.is(tok::kw_typeof) || OpTok.is(tok::kw_sizeof) || 962 OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof)) && 963 "Not a typeof/sizeof/alignof expression!"); 964 965 OwningExprResult Operand(Actions); 966 967 // If the operand doesn't start with an '(', it must be an expression. 968 if (Tok.isNot(tok::l_paren)) { 969 isCastExpr = false; 970 if (OpTok.is(tok::kw_typeof) && !getLang().CPlusPlus) { 971 Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierInfo(); 972 return ExprError(); 973 } 974 Operand = ParseCastExpression(true/*isUnaryExpression*/); 975 976 } else { 977 // If it starts with a '(', we know that it is either a parenthesized 978 // type-name, or it is a unary-expression that starts with a compound 979 // literal, or starts with a primary-expression that is a parenthesized 980 // expression. 981 ParenParseOption ExprType = CastExpr; 982 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; 983 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/, 984 CastTy, RParenLoc); 985 CastRange = SourceRange(LParenLoc, RParenLoc); 986 987 // If ParseParenExpression parsed a '(typename)' sequence only, then this is 988 // a type. 989 if (ExprType == CastExpr) { 990 isCastExpr = true; 991 return ExprEmpty(); 992 } 993 994 // If this is a parenthesized expression, it is the start of a 995 // unary-expression, but doesn't include any postfix pieces. Parse these 996 // now if present. 997 Operand = ParsePostfixExpressionSuffix(move(Operand)); 998 } 999 1000 // If we get here, the operand to the typeof/sizeof/alignof was an expresion. 1001 isCastExpr = false; 1002 return move(Operand); 1003} 1004 1005 1006/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression. 1007/// unary-expression: [C99 6.5.3] 1008/// 'sizeof' unary-expression 1009/// 'sizeof' '(' type-name ')' 1010/// [GNU] '__alignof' unary-expression 1011/// [GNU] '__alignof' '(' type-name ')' 1012/// [C++0x] 'alignof' '(' type-id ')' 1013Parser::OwningExprResult Parser::ParseSizeofAlignofExpression() { 1014 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof) 1015 || Tok.is(tok::kw_alignof)) && 1016 "Not a sizeof/alignof expression!"); 1017 Token OpTok = Tok; 1018 ConsumeToken(); 1019 1020 bool isCastExpr; 1021 TypeTy *CastTy; 1022 SourceRange CastRange; 1023 OwningExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok, 1024 isCastExpr, 1025 CastTy, 1026 CastRange); 1027 1028 if (isCastExpr) 1029 return Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(), 1030 OpTok.is(tok::kw_sizeof), 1031 /*isType=*/true, CastTy, 1032 CastRange); 1033 1034 // If we get here, the operand to the sizeof/alignof was an expresion. 1035 if (!Operand.isInvalid()) 1036 Operand = Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(), 1037 OpTok.is(tok::kw_sizeof), 1038 /*isType=*/false, 1039 Operand.release(), CastRange); 1040 return move(Operand); 1041} 1042 1043/// ParseBuiltinPrimaryExpression 1044/// 1045/// primary-expression: [C99 6.5.1] 1046/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' 1047/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' 1048/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' 1049/// assign-expr ')' 1050/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' 1051/// 1052/// [GNU] offsetof-member-designator: 1053/// [GNU] identifier 1054/// [GNU] offsetof-member-designator '.' identifier 1055/// [GNU] offsetof-member-designator '[' expression ']' 1056/// 1057Parser::OwningExprResult Parser::ParseBuiltinPrimaryExpression() { 1058 OwningExprResult Res(Actions); 1059 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo(); 1060 1061 tok::TokenKind T = Tok.getKind(); 1062 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier. 1063 1064 // All of these start with an open paren. 1065 if (Tok.isNot(tok::l_paren)) 1066 return ExprError(Diag(Tok, diag::err_expected_lparen_after_id) 1067 << BuiltinII); 1068 1069 SourceLocation LParenLoc = ConsumeParen(); 1070 // TODO: Build AST. 1071 1072 switch (T) { 1073 default: assert(0 && "Not a builtin primary expression!"); 1074 case tok::kw___builtin_va_arg: { 1075 OwningExprResult Expr(ParseAssignmentExpression()); 1076 if (Expr.isInvalid()) { 1077 SkipUntil(tok::r_paren); 1078 return ExprError(); 1079 } 1080 1081 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1082 return ExprError(); 1083 1084 TypeResult Ty = ParseTypeName(); 1085 1086 if (Tok.isNot(tok::r_paren)) { 1087 Diag(Tok, diag::err_expected_rparen); 1088 return ExprError(); 1089 } 1090 if (Ty.isInvalid()) 1091 Res = ExprError(); 1092 else 1093 Res = Actions.ActOnVAArg(StartLoc, move(Expr), Ty.get(), ConsumeParen()); 1094 break; 1095 } 1096 case tok::kw___builtin_offsetof: { 1097 SourceLocation TypeLoc = Tok.getLocation(); 1098 TypeResult Ty = ParseTypeName(); 1099 if (Ty.isInvalid()) { 1100 SkipUntil(tok::r_paren); 1101 return ExprError(); 1102 } 1103 1104 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1105 return ExprError(); 1106 1107 // We must have at least one identifier here. 1108 if (Tok.isNot(tok::identifier)) { 1109 Diag(Tok, diag::err_expected_ident); 1110 SkipUntil(tok::r_paren); 1111 return ExprError(); 1112 } 1113 1114 // Keep track of the various subcomponents we see. 1115 llvm::SmallVector<Action::OffsetOfComponent, 4> Comps; 1116 1117 Comps.push_back(Action::OffsetOfComponent()); 1118 Comps.back().isBrackets = false; 1119 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1120 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken(); 1121 1122 // FIXME: This loop leaks the index expressions on error. 1123 while (1) { 1124 if (Tok.is(tok::period)) { 1125 // offsetof-member-designator: offsetof-member-designator '.' identifier 1126 Comps.push_back(Action::OffsetOfComponent()); 1127 Comps.back().isBrackets = false; 1128 Comps.back().LocStart = ConsumeToken(); 1129 1130 if (Tok.isNot(tok::identifier)) { 1131 Diag(Tok, diag::err_expected_ident); 1132 SkipUntil(tok::r_paren); 1133 return ExprError(); 1134 } 1135 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1136 Comps.back().LocEnd = ConsumeToken(); 1137 1138 } else if (Tok.is(tok::l_square)) { 1139 // offsetof-member-designator: offsetof-member-design '[' expression ']' 1140 Comps.push_back(Action::OffsetOfComponent()); 1141 Comps.back().isBrackets = true; 1142 Comps.back().LocStart = ConsumeBracket(); 1143 Res = ParseExpression(); 1144 if (Res.isInvalid()) { 1145 SkipUntil(tok::r_paren); 1146 return move(Res); 1147 } 1148 Comps.back().U.E = Res.release(); 1149 1150 Comps.back().LocEnd = 1151 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart); 1152 } else if (Tok.is(tok::r_paren)) { 1153 if (Ty.isInvalid()) 1154 Res = ExprError(); 1155 else 1156 Res = Actions.ActOnBuiltinOffsetOf(CurScope, StartLoc, TypeLoc, 1157 Ty.get(), &Comps[0], 1158 Comps.size(), ConsumeParen()); 1159 break; 1160 } else { 1161 // Error occurred. 1162 return ExprError(); 1163 } 1164 } 1165 break; 1166 } 1167 case tok::kw___builtin_choose_expr: { 1168 OwningExprResult Cond(ParseAssignmentExpression()); 1169 if (Cond.isInvalid()) { 1170 SkipUntil(tok::r_paren); 1171 return move(Cond); 1172 } 1173 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1174 return ExprError(); 1175 1176 OwningExprResult Expr1(ParseAssignmentExpression()); 1177 if (Expr1.isInvalid()) { 1178 SkipUntil(tok::r_paren); 1179 return move(Expr1); 1180 } 1181 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1182 return ExprError(); 1183 1184 OwningExprResult Expr2(ParseAssignmentExpression()); 1185 if (Expr2.isInvalid()) { 1186 SkipUntil(tok::r_paren); 1187 return move(Expr2); 1188 } 1189 if (Tok.isNot(tok::r_paren)) { 1190 Diag(Tok, diag::err_expected_rparen); 1191 return ExprError(); 1192 } 1193 Res = Actions.ActOnChooseExpr(StartLoc, move(Cond), move(Expr1), 1194 move(Expr2), ConsumeParen()); 1195 break; 1196 } 1197 case tok::kw___builtin_types_compatible_p: 1198 TypeResult Ty1 = ParseTypeName(); 1199 1200 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1201 return ExprError(); 1202 1203 TypeResult Ty2 = ParseTypeName(); 1204 1205 if (Tok.isNot(tok::r_paren)) { 1206 Diag(Tok, diag::err_expected_rparen); 1207 return ExprError(); 1208 } 1209 1210 if (Ty1.isInvalid() || Ty2.isInvalid()) 1211 Res = ExprError(); 1212 else 1213 Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1.get(), Ty2.get(), 1214 ConsumeParen()); 1215 break; 1216 } 1217 1218 // These can be followed by postfix-expr pieces because they are 1219 // primary-expressions. 1220 return ParsePostfixExpressionSuffix(move(Res)); 1221} 1222 1223/// ParseParenExpression - This parses the unit that starts with a '(' token, 1224/// based on what is allowed by ExprType. The actual thing parsed is returned 1225/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type, 1226/// not the parsed cast-expression. 1227/// 1228/// primary-expression: [C99 6.5.1] 1229/// '(' expression ')' 1230/// [GNU] '(' compound-statement ')' (if !ParenExprOnly) 1231/// postfix-expression: [C99 6.5.2] 1232/// '(' type-name ')' '{' initializer-list '}' 1233/// '(' type-name ')' '{' initializer-list ',' '}' 1234/// cast-expression: [C99 6.5.4] 1235/// '(' type-name ')' cast-expression 1236/// 1237Parser::OwningExprResult 1238Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, 1239 TypeTy *&CastTy, SourceLocation &RParenLoc) { 1240 assert(Tok.is(tok::l_paren) && "Not a paren expr!"); 1241 GreaterThanIsOperatorScope G(GreaterThanIsOperator, true); 1242 SourceLocation OpenLoc = ConsumeParen(); 1243 OwningExprResult Result(Actions, true); 1244 bool isAmbiguousTypeId; 1245 CastTy = 0; 1246 1247 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) { 1248 Diag(Tok, diag::ext_gnu_statement_expr); 1249 OwningStmtResult Stmt(ParseCompoundStatement(true)); 1250 ExprType = CompoundStmt; 1251 1252 // If the substmt parsed correctly, build the AST node. 1253 if (!Stmt.isInvalid() && Tok.is(tok::r_paren)) 1254 Result = Actions.ActOnStmtExpr(OpenLoc, move(Stmt), Tok.getLocation()); 1255 1256 } else if (ExprType >= CompoundLiteral && 1257 isTypeIdInParens(isAmbiguousTypeId)) { 1258 1259 // Otherwise, this is a compound literal expression or cast expression. 1260 1261 // In C++, if the type-id is ambiguous we disambiguate based on context. 1262 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof 1263 // in which case we should treat it as type-id. 1264 // if stopIfCastExpr is false, we need to determine the context past the 1265 // parens, so we defer to ParseCXXAmbiguousParenExpression for that. 1266 if (isAmbiguousTypeId && !stopIfCastExpr) 1267 return ParseCXXAmbiguousParenExpression(ExprType, CastTy, 1268 OpenLoc, RParenLoc); 1269 1270 TypeResult Ty = ParseTypeName(); 1271 1272 // Match the ')'. 1273 if (Tok.is(tok::r_paren)) 1274 RParenLoc = ConsumeParen(); 1275 else 1276 MatchRHSPunctuation(tok::r_paren, OpenLoc); 1277 1278 if (Tok.is(tok::l_brace)) { 1279 ExprType = CompoundLiteral; 1280 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc); 1281 } 1282 1283 if (ExprType == CastExpr) { 1284 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. 1285 1286 if (Ty.isInvalid()) 1287 return ExprError(); 1288 1289 CastTy = Ty.get(); 1290 1291 if (stopIfCastExpr) { 1292 // Note that this doesn't parse the subsequent cast-expression, it just 1293 // returns the parsed type to the callee. 1294 return OwningExprResult(Actions); 1295 } 1296 1297 // Parse the cast-expression that follows it next. 1298 // TODO: For cast expression with CastTy. 1299 Result = ParseCastExpression(false); 1300 if (!Result.isInvalid()) 1301 Result = Actions.ActOnCastExpr(OpenLoc, CastTy, RParenLoc,move(Result)); 1302 return move(Result); 1303 } 1304 1305 Diag(Tok, diag::err_expected_lbrace_in_compound_literal); 1306 return ExprError(); 1307 } else { 1308 Result = ParseExpression(); 1309 ExprType = SimpleExpr; 1310 if (!Result.isInvalid() && Tok.is(tok::r_paren)) 1311 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), move(Result)); 1312 } 1313 1314 // Match the ')'. 1315 if (Result.isInvalid()) { 1316 SkipUntil(tok::r_paren); 1317 return ExprError(); 1318 } 1319 1320 if (Tok.is(tok::r_paren)) 1321 RParenLoc = ConsumeParen(); 1322 else 1323 MatchRHSPunctuation(tok::r_paren, OpenLoc); 1324 1325 return move(Result); 1326} 1327 1328/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name 1329/// and we are at the left brace. 1330/// 1331/// postfix-expression: [C99 6.5.2] 1332/// '(' type-name ')' '{' initializer-list '}' 1333/// '(' type-name ')' '{' initializer-list ',' '}' 1334/// 1335Parser::OwningExprResult 1336Parser::ParseCompoundLiteralExpression(TypeTy *Ty, 1337 SourceLocation LParenLoc, 1338 SourceLocation RParenLoc) { 1339 assert(Tok.is(tok::l_brace) && "Not a compound literal!"); 1340 if (!getLang().C99) // Compound literals don't exist in C90. 1341 Diag(LParenLoc, diag::ext_c99_compound_literal); 1342 OwningExprResult Result = ParseInitializer(); 1343 if (!Result.isInvalid() && Ty) 1344 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, move(Result)); 1345 return move(Result); 1346} 1347 1348/// ParseStringLiteralExpression - This handles the various token types that 1349/// form string literals, and also handles string concatenation [C99 5.1.1.2, 1350/// translation phase #6]. 1351/// 1352/// primary-expression: [C99 6.5.1] 1353/// string-literal 1354Parser::OwningExprResult Parser::ParseStringLiteralExpression() { 1355 assert(isTokenStringLiteral() && "Not a string literal!"); 1356 1357 // String concat. Note that keywords like __func__ and __FUNCTION__ are not 1358 // considered to be strings for concatenation purposes. 1359 llvm::SmallVector<Token, 4> StringToks; 1360 1361 do { 1362 StringToks.push_back(Tok); 1363 ConsumeStringToken(); 1364 } while (isTokenStringLiteral()); 1365 1366 // Pass the set of string tokens, ready for concatenation, to the actions. 1367 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size()); 1368} 1369 1370/// ParseExpressionList - Used for C/C++ (argument-)expression-list. 1371/// 1372/// argument-expression-list: 1373/// assignment-expression 1374/// argument-expression-list , assignment-expression 1375/// 1376/// [C++] expression-list: 1377/// [C++] assignment-expression 1378/// [C++] expression-list , assignment-expression 1379/// 1380bool Parser::ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs) { 1381 while (1) { 1382 OwningExprResult Expr(ParseAssignmentExpression()); 1383 if (Expr.isInvalid()) 1384 return true; 1385 1386 Exprs.push_back(Expr.release()); 1387 1388 if (Tok.isNot(tok::comma)) 1389 return false; 1390 // Move to the next argument, remember where the comma was. 1391 CommaLocs.push_back(ConsumeToken()); 1392 } 1393} 1394 1395/// ParseBlockId - Parse a block-id, which roughly looks like int (int x). 1396/// 1397/// [clang] block-id: 1398/// [clang] specifier-qualifier-list block-declarator 1399/// 1400void Parser::ParseBlockId() { 1401 // Parse the specifier-qualifier-list piece. 1402 DeclSpec DS; 1403 ParseSpecifierQualifierList(DS); 1404 1405 // Parse the block-declarator. 1406 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext); 1407 ParseDeclarator(DeclaratorInfo); 1408 1409 // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes. 1410 DeclaratorInfo.AddAttributes(DS.TakeAttributes(), 1411 SourceLocation()); 1412 1413 if (Tok.is(tok::kw___attribute)) { 1414 SourceLocation Loc; 1415 AttributeList *AttrList = ParseAttributes(&Loc); 1416 DeclaratorInfo.AddAttributes(AttrList, Loc); 1417 } 1418 1419 // Inform sema that we are starting a block. 1420 Actions.ActOnBlockArguments(DeclaratorInfo, CurScope); 1421} 1422 1423/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks 1424/// like ^(int x){ return x+1; } 1425/// 1426/// block-literal: 1427/// [clang] '^' block-args[opt] compound-statement 1428/// [clang] '^' block-id compound-statement 1429/// [clang] block-args: 1430/// [clang] '(' parameter-list ')' 1431/// 1432Parser::OwningExprResult Parser::ParseBlockLiteralExpression() { 1433 assert(Tok.is(tok::caret) && "block literal starts with ^"); 1434 SourceLocation CaretLoc = ConsumeToken(); 1435 1436 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc, 1437 "block literal parsing"); 1438 1439 // Enter a scope to hold everything within the block. This includes the 1440 // argument decls, decls within the compound expression, etc. This also 1441 // allows determining whether a variable reference inside the block is 1442 // within or outside of the block. 1443 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope | 1444 Scope::BreakScope | Scope::ContinueScope | 1445 Scope::DeclScope); 1446 1447 // Inform sema that we are starting a block. 1448 Actions.ActOnBlockStart(CaretLoc, CurScope); 1449 1450 // Parse the return type if present. 1451 DeclSpec DS; 1452 Declarator ParamInfo(DS, Declarator::BlockLiteralContext); 1453 // FIXME: Since the return type isn't actually parsed, it can't be used to 1454 // fill ParamInfo with an initial valid range, so do it manually. 1455 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation())); 1456 1457 // If this block has arguments, parse them. There is no ambiguity here with 1458 // the expression case, because the expression case requires a parameter list. 1459 if (Tok.is(tok::l_paren)) { 1460 ParseParenDeclarator(ParamInfo); 1461 // Parse the pieces after the identifier as if we had "int(...)". 1462 // SetIdentifier sets the source range end, but in this case we're past 1463 // that location. 1464 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd(); 1465 ParamInfo.SetIdentifier(0, CaretLoc); 1466 ParamInfo.SetRangeEnd(Tmp); 1467 if (ParamInfo.isInvalidType()) { 1468 // If there was an error parsing the arguments, they may have 1469 // tried to use ^(x+y) which requires an argument list. Just 1470 // skip the whole block literal. 1471 Actions.ActOnBlockError(CaretLoc, CurScope); 1472 return ExprError(); 1473 } 1474 1475 if (Tok.is(tok::kw___attribute)) { 1476 SourceLocation Loc; 1477 AttributeList *AttrList = ParseAttributes(&Loc); 1478 ParamInfo.AddAttributes(AttrList, Loc); 1479 } 1480 1481 // Inform sema that we are starting a block. 1482 Actions.ActOnBlockArguments(ParamInfo, CurScope); 1483 } else if (!Tok.is(tok::l_brace)) { 1484 ParseBlockId(); 1485 } else { 1486 // Otherwise, pretend we saw (void). 1487 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false, 1488 SourceLocation(), 1489 0, 0, 0, 1490 false, SourceLocation(), 1491 false, 0, 0, 0, 1492 CaretLoc, ParamInfo), 1493 CaretLoc); 1494 1495 if (Tok.is(tok::kw___attribute)) { 1496 SourceLocation Loc; 1497 AttributeList *AttrList = ParseAttributes(&Loc); 1498 ParamInfo.AddAttributes(AttrList, Loc); 1499 } 1500 1501 // Inform sema that we are starting a block. 1502 Actions.ActOnBlockArguments(ParamInfo, CurScope); 1503 } 1504 1505 1506 OwningExprResult Result(Actions, true); 1507 if (!Tok.is(tok::l_brace)) { 1508 // Saw something like: ^expr 1509 Diag(Tok, diag::err_expected_expression); 1510 Actions.ActOnBlockError(CaretLoc, CurScope); 1511 return ExprError(); 1512 } 1513 1514 OwningStmtResult Stmt(ParseCompoundStatementBody()); 1515 if (!Stmt.isInvalid()) 1516 Result = Actions.ActOnBlockStmtExpr(CaretLoc, move(Stmt), CurScope); 1517 else 1518 Actions.ActOnBlockError(CaretLoc, CurScope); 1519 return move(Result); 1520} 1521