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