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