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