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