ParseExpr.cpp revision 3aa4ca439da54bc71def778126c9cf10c7d910ed
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.is(tok::identifier)) { 937 if (!LHS.isInvalid()) 938 LHS = Actions.ActOnMemberReferenceExpr(CurScope, move(LHS), OpLoc, 939 OpKind, Tok.getLocation(), 940 *Tok.getIdentifierInfo(), 941 ObjCImpDecl, &SS); 942 } else if (getLang().CPlusPlus && Tok.is(tok::tilde)) { 943 // We have a C++ pseudo-destructor. 944 945 // Consume the tilde. 946 ConsumeToken(); 947 948 if (!Tok.is(tok::identifier)) { 949 Diag(Tok, diag::err_expected_ident); 950 return ExprError(); 951 } 952 953 if (!LHS.isInvalid()) 954 LHS = Actions.ActOnDestructorReferenceExpr(CurScope, move(LHS), 955 OpLoc, OpKind, 956 Tok.getLocation(), 957 Tok.getIdentifierInfo(), 958 &SS); 959 } else { 960 Diag(Tok, diag::err_expected_ident); 961 return ExprError(); 962 } 963 964 if (getLang().CPlusPlus) 965 Actions.ActOnCXXExitMemberScope(CurScope, MemberSS); 966 967 ConsumeToken(); 968 break; 969 } 970 case tok::plusplus: // postfix-expression: postfix-expression '++' 971 case tok::minusminus: // postfix-expression: postfix-expression '--' 972 if (!LHS.isInvalid()) { 973 LHS = Actions.ActOnPostfixUnaryOp(CurScope, Tok.getLocation(), 974 Tok.getKind(), move(LHS)); 975 } 976 ConsumeToken(); 977 break; 978 } 979 } 980} 981 982/// ParseExprAfterTypeofSizeofAlignof - We parsed a typeof/sizeof/alignof and 983/// we are at the start of an expression or a parenthesized type-id. 984/// OpTok is the operand token (typeof/sizeof/alignof). Returns the expression 985/// (isCastExpr == false) or the type (isCastExpr == true). 986/// 987/// unary-expression: [C99 6.5.3] 988/// 'sizeof' unary-expression 989/// 'sizeof' '(' type-name ')' 990/// [GNU] '__alignof' unary-expression 991/// [GNU] '__alignof' '(' type-name ')' 992/// [C++0x] 'alignof' '(' type-id ')' 993/// 994/// [GNU] typeof-specifier: 995/// typeof ( expressions ) 996/// typeof ( type-name ) 997/// [GNU/C++] typeof unary-expression 998/// 999Parser::OwningExprResult 1000Parser::ParseExprAfterTypeofSizeofAlignof(const Token &OpTok, 1001 bool &isCastExpr, 1002 TypeTy *&CastTy, 1003 SourceRange &CastRange) { 1004 1005 assert((OpTok.is(tok::kw_typeof) || OpTok.is(tok::kw_sizeof) || 1006 OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof)) && 1007 "Not a typeof/sizeof/alignof expression!"); 1008 1009 OwningExprResult Operand(Actions); 1010 1011 // If the operand doesn't start with an '(', it must be an expression. 1012 if (Tok.isNot(tok::l_paren)) { 1013 isCastExpr = false; 1014 if (OpTok.is(tok::kw_typeof) && !getLang().CPlusPlus) { 1015 Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierInfo(); 1016 return ExprError(); 1017 } 1018 1019 // C++0x [expr.sizeof]p1: 1020 // [...] The operand is either an expression, which is an unevaluated 1021 // operand (Clause 5) [...] 1022 // 1023 // The GNU typeof and alignof extensions also behave as unevaluated 1024 // operands. 1025 EnterExpressionEvaluationContext Unevaluated(Actions, 1026 Action::Unevaluated); 1027 Operand = ParseCastExpression(true/*isUnaryExpression*/); 1028 } else { 1029 // If it starts with a '(', we know that it is either a parenthesized 1030 // type-name, or it is a unary-expression that starts with a compound 1031 // literal, or starts with a primary-expression that is a parenthesized 1032 // expression. 1033 ParenParseOption ExprType = CastExpr; 1034 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; 1035 1036 // C++0x [expr.sizeof]p1: 1037 // [...] The operand is either an expression, which is an unevaluated 1038 // operand (Clause 5) [...] 1039 // 1040 // The GNU typeof and alignof extensions also behave as unevaluated 1041 // operands. 1042 EnterExpressionEvaluationContext Unevaluated(Actions, 1043 Action::Unevaluated); 1044 Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/, false, 1045 CastTy, RParenLoc); 1046 CastRange = SourceRange(LParenLoc, RParenLoc); 1047 1048 // If ParseParenExpression parsed a '(typename)' sequence only, then this is 1049 // a type. 1050 if (ExprType == CastExpr) { 1051 isCastExpr = true; 1052 return ExprEmpty(); 1053 } 1054 1055 // If this is a parenthesized expression, it is the start of a 1056 // unary-expression, but doesn't include any postfix pieces. Parse these 1057 // now if present. 1058 Operand = ParsePostfixExpressionSuffix(move(Operand)); 1059 } 1060 1061 // If we get here, the operand to the typeof/sizeof/alignof was an expresion. 1062 isCastExpr = false; 1063 return move(Operand); 1064} 1065 1066 1067/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression. 1068/// unary-expression: [C99 6.5.3] 1069/// 'sizeof' unary-expression 1070/// 'sizeof' '(' type-name ')' 1071/// [GNU] '__alignof' unary-expression 1072/// [GNU] '__alignof' '(' type-name ')' 1073/// [C++0x] 'alignof' '(' type-id ')' 1074Parser::OwningExprResult Parser::ParseSizeofAlignofExpression() { 1075 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof) 1076 || Tok.is(tok::kw_alignof)) && 1077 "Not a sizeof/alignof expression!"); 1078 Token OpTok = Tok; 1079 ConsumeToken(); 1080 1081 bool isCastExpr; 1082 TypeTy *CastTy; 1083 SourceRange CastRange; 1084 OwningExprResult Operand = ParseExprAfterTypeofSizeofAlignof(OpTok, 1085 isCastExpr, 1086 CastTy, 1087 CastRange); 1088 1089 if (isCastExpr) 1090 return Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(), 1091 OpTok.is(tok::kw_sizeof), 1092 /*isType=*/true, CastTy, 1093 CastRange); 1094 1095 // If we get here, the operand to the sizeof/alignof was an expresion. 1096 if (!Operand.isInvalid()) 1097 Operand = Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(), 1098 OpTok.is(tok::kw_sizeof), 1099 /*isType=*/false, 1100 Operand.release(), CastRange); 1101 return move(Operand); 1102} 1103 1104/// ParseBuiltinPrimaryExpression 1105/// 1106/// primary-expression: [C99 6.5.1] 1107/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' 1108/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' 1109/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' 1110/// assign-expr ')' 1111/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' 1112/// 1113/// [GNU] offsetof-member-designator: 1114/// [GNU] identifier 1115/// [GNU] offsetof-member-designator '.' identifier 1116/// [GNU] offsetof-member-designator '[' expression ']' 1117/// 1118Parser::OwningExprResult Parser::ParseBuiltinPrimaryExpression() { 1119 OwningExprResult Res(Actions); 1120 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo(); 1121 1122 tok::TokenKind T = Tok.getKind(); 1123 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier. 1124 1125 // All of these start with an open paren. 1126 if (Tok.isNot(tok::l_paren)) 1127 return ExprError(Diag(Tok, diag::err_expected_lparen_after_id) 1128 << BuiltinII); 1129 1130 SourceLocation LParenLoc = ConsumeParen(); 1131 // TODO: Build AST. 1132 1133 switch (T) { 1134 default: assert(0 && "Not a builtin primary expression!"); 1135 case tok::kw___builtin_va_arg: { 1136 OwningExprResult Expr(ParseAssignmentExpression()); 1137 if (Expr.isInvalid()) { 1138 SkipUntil(tok::r_paren); 1139 return ExprError(); 1140 } 1141 1142 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1143 return ExprError(); 1144 1145 TypeResult Ty = ParseTypeName(); 1146 1147 if (Tok.isNot(tok::r_paren)) { 1148 Diag(Tok, diag::err_expected_rparen); 1149 return ExprError(); 1150 } 1151 if (Ty.isInvalid()) 1152 Res = ExprError(); 1153 else 1154 Res = Actions.ActOnVAArg(StartLoc, move(Expr), Ty.get(), ConsumeParen()); 1155 break; 1156 } 1157 case tok::kw___builtin_offsetof: { 1158 SourceLocation TypeLoc = Tok.getLocation(); 1159 TypeResult Ty = ParseTypeName(); 1160 if (Ty.isInvalid()) { 1161 SkipUntil(tok::r_paren); 1162 return ExprError(); 1163 } 1164 1165 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1166 return ExprError(); 1167 1168 // We must have at least one identifier here. 1169 if (Tok.isNot(tok::identifier)) { 1170 Diag(Tok, diag::err_expected_ident); 1171 SkipUntil(tok::r_paren); 1172 return ExprError(); 1173 } 1174 1175 // Keep track of the various subcomponents we see. 1176 llvm::SmallVector<Action::OffsetOfComponent, 4> Comps; 1177 1178 Comps.push_back(Action::OffsetOfComponent()); 1179 Comps.back().isBrackets = false; 1180 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1181 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken(); 1182 1183 // FIXME: This loop leaks the index expressions on error. 1184 while (1) { 1185 if (Tok.is(tok::period)) { 1186 // offsetof-member-designator: offsetof-member-designator '.' identifier 1187 Comps.push_back(Action::OffsetOfComponent()); 1188 Comps.back().isBrackets = false; 1189 Comps.back().LocStart = ConsumeToken(); 1190 1191 if (Tok.isNot(tok::identifier)) { 1192 Diag(Tok, diag::err_expected_ident); 1193 SkipUntil(tok::r_paren); 1194 return ExprError(); 1195 } 1196 Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); 1197 Comps.back().LocEnd = ConsumeToken(); 1198 1199 } else if (Tok.is(tok::l_square)) { 1200 // offsetof-member-designator: offsetof-member-design '[' expression ']' 1201 Comps.push_back(Action::OffsetOfComponent()); 1202 Comps.back().isBrackets = true; 1203 Comps.back().LocStart = ConsumeBracket(); 1204 Res = ParseExpression(); 1205 if (Res.isInvalid()) { 1206 SkipUntil(tok::r_paren); 1207 return move(Res); 1208 } 1209 Comps.back().U.E = Res.release(); 1210 1211 Comps.back().LocEnd = 1212 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart); 1213 } else { 1214 if (Tok.isNot(tok::r_paren)) { 1215 MatchRHSPunctuation(tok::r_paren, LParenLoc); 1216 Res = ExprError(); 1217 } else if (Ty.isInvalid()) { 1218 Res = ExprError(); 1219 } else { 1220 Res = Actions.ActOnBuiltinOffsetOf(CurScope, StartLoc, TypeLoc, 1221 Ty.get(), &Comps[0], 1222 Comps.size(), ConsumeParen()); 1223 } 1224 break; 1225 } 1226 } 1227 break; 1228 } 1229 case tok::kw___builtin_choose_expr: { 1230 OwningExprResult Cond(ParseAssignmentExpression()); 1231 if (Cond.isInvalid()) { 1232 SkipUntil(tok::r_paren); 1233 return move(Cond); 1234 } 1235 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1236 return ExprError(); 1237 1238 OwningExprResult Expr1(ParseAssignmentExpression()); 1239 if (Expr1.isInvalid()) { 1240 SkipUntil(tok::r_paren); 1241 return move(Expr1); 1242 } 1243 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1244 return ExprError(); 1245 1246 OwningExprResult Expr2(ParseAssignmentExpression()); 1247 if (Expr2.isInvalid()) { 1248 SkipUntil(tok::r_paren); 1249 return move(Expr2); 1250 } 1251 if (Tok.isNot(tok::r_paren)) { 1252 Diag(Tok, diag::err_expected_rparen); 1253 return ExprError(); 1254 } 1255 Res = Actions.ActOnChooseExpr(StartLoc, move(Cond), move(Expr1), 1256 move(Expr2), ConsumeParen()); 1257 break; 1258 } 1259 case tok::kw___builtin_types_compatible_p: 1260 TypeResult Ty1 = ParseTypeName(); 1261 1262 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren)) 1263 return ExprError(); 1264 1265 TypeResult Ty2 = ParseTypeName(); 1266 1267 if (Tok.isNot(tok::r_paren)) { 1268 Diag(Tok, diag::err_expected_rparen); 1269 return ExprError(); 1270 } 1271 1272 if (Ty1.isInvalid() || Ty2.isInvalid()) 1273 Res = ExprError(); 1274 else 1275 Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1.get(), Ty2.get(), 1276 ConsumeParen()); 1277 break; 1278 } 1279 1280 // These can be followed by postfix-expr pieces because they are 1281 // primary-expressions. 1282 return ParsePostfixExpressionSuffix(move(Res)); 1283} 1284 1285/// ParseParenExpression - This parses the unit that starts with a '(' token, 1286/// based on what is allowed by ExprType. The actual thing parsed is returned 1287/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type, 1288/// not the parsed cast-expression. 1289/// 1290/// primary-expression: [C99 6.5.1] 1291/// '(' expression ')' 1292/// [GNU] '(' compound-statement ')' (if !ParenExprOnly) 1293/// postfix-expression: [C99 6.5.2] 1294/// '(' type-name ')' '{' initializer-list '}' 1295/// '(' type-name ')' '{' initializer-list ',' '}' 1296/// cast-expression: [C99 6.5.4] 1297/// '(' type-name ')' cast-expression 1298/// 1299Parser::OwningExprResult 1300Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, 1301 bool parseAsExprList, TypeTy *&CastTy, 1302 SourceLocation &RParenLoc) { 1303 assert(Tok.is(tok::l_paren) && "Not a paren expr!"); 1304 GreaterThanIsOperatorScope G(GreaterThanIsOperator, true); 1305 SourceLocation OpenLoc = ConsumeParen(); 1306 OwningExprResult Result(Actions, true); 1307 bool isAmbiguousTypeId; 1308 CastTy = 0; 1309 1310 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) { 1311 Diag(Tok, diag::ext_gnu_statement_expr); 1312 OwningStmtResult Stmt(ParseCompoundStatement(true)); 1313 ExprType = CompoundStmt; 1314 1315 // If the substmt parsed correctly, build the AST node. 1316 if (!Stmt.isInvalid() && Tok.is(tok::r_paren)) 1317 Result = Actions.ActOnStmtExpr(OpenLoc, move(Stmt), Tok.getLocation()); 1318 1319 } else if (ExprType >= CompoundLiteral && 1320 isTypeIdInParens(isAmbiguousTypeId)) { 1321 1322 // Otherwise, this is a compound literal expression or cast expression. 1323 1324 // In C++, if the type-id is ambiguous we disambiguate based on context. 1325 // If stopIfCastExpr is true the context is a typeof/sizeof/alignof 1326 // in which case we should treat it as type-id. 1327 // if stopIfCastExpr is false, we need to determine the context past the 1328 // parens, so we defer to ParseCXXAmbiguousParenExpression for that. 1329 if (isAmbiguousTypeId && !stopIfCastExpr) 1330 return ParseCXXAmbiguousParenExpression(ExprType, CastTy, 1331 OpenLoc, RParenLoc); 1332 1333 TypeResult Ty = ParseTypeName(); 1334 1335 // Match the ')'. 1336 if (Tok.is(tok::r_paren)) 1337 RParenLoc = ConsumeParen(); 1338 else 1339 MatchRHSPunctuation(tok::r_paren, OpenLoc); 1340 1341 if (Tok.is(tok::l_brace)) { 1342 ExprType = CompoundLiteral; 1343 return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc); 1344 } 1345 1346 if (ExprType == CastExpr) { 1347 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. 1348 1349 if (Ty.isInvalid()) 1350 return ExprError(); 1351 1352 CastTy = Ty.get(); 1353 1354 if (stopIfCastExpr) { 1355 // Note that this doesn't parse the subsequent cast-expression, it just 1356 // returns the parsed type to the callee. 1357 return OwningExprResult(Actions); 1358 } 1359 1360 // Parse the cast-expression that follows it next. 1361 // TODO: For cast expression with CastTy. 1362 Result = ParseCastExpression(false, false, true); 1363 if (!Result.isInvalid()) 1364 Result = Actions.ActOnCastExpr(CurScope, OpenLoc, CastTy, RParenLoc, 1365 move(Result)); 1366 return move(Result); 1367 } 1368 1369 Diag(Tok, diag::err_expected_lbrace_in_compound_literal); 1370 return ExprError(); 1371 } else if (parseAsExprList) { 1372 // Parse the expression-list. 1373 ExprVector ArgExprs(Actions); 1374 CommaLocsTy CommaLocs; 1375 1376 if (!ParseExpressionList(ArgExprs, CommaLocs)) { 1377 ExprType = SimpleExpr; 1378 Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(), 1379 move_arg(ArgExprs)); 1380 } 1381 } else { 1382 Result = ParseExpression(); 1383 ExprType = SimpleExpr; 1384 if (!Result.isInvalid() && Tok.is(tok::r_paren)) 1385 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), move(Result)); 1386 } 1387 1388 // Match the ')'. 1389 if (Result.isInvalid()) { 1390 SkipUntil(tok::r_paren); 1391 return ExprError(); 1392 } 1393 1394 if (Tok.is(tok::r_paren)) 1395 RParenLoc = ConsumeParen(); 1396 else 1397 MatchRHSPunctuation(tok::r_paren, OpenLoc); 1398 1399 return move(Result); 1400} 1401 1402/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name 1403/// and we are at the left brace. 1404/// 1405/// postfix-expression: [C99 6.5.2] 1406/// '(' type-name ')' '{' initializer-list '}' 1407/// '(' type-name ')' '{' initializer-list ',' '}' 1408/// 1409Parser::OwningExprResult 1410Parser::ParseCompoundLiteralExpression(TypeTy *Ty, 1411 SourceLocation LParenLoc, 1412 SourceLocation RParenLoc) { 1413 assert(Tok.is(tok::l_brace) && "Not a compound literal!"); 1414 if (!getLang().C99) // Compound literals don't exist in C90. 1415 Diag(LParenLoc, diag::ext_c99_compound_literal); 1416 OwningExprResult Result = ParseInitializer(); 1417 if (!Result.isInvalid() && Ty) 1418 return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, move(Result)); 1419 return move(Result); 1420} 1421 1422/// ParseStringLiteralExpression - This handles the various token types that 1423/// form string literals, and also handles string concatenation [C99 5.1.1.2, 1424/// translation phase #6]. 1425/// 1426/// primary-expression: [C99 6.5.1] 1427/// string-literal 1428Parser::OwningExprResult Parser::ParseStringLiteralExpression() { 1429 assert(isTokenStringLiteral() && "Not a string literal!"); 1430 1431 // String concat. Note that keywords like __func__ and __FUNCTION__ are not 1432 // considered to be strings for concatenation purposes. 1433 llvm::SmallVector<Token, 4> StringToks; 1434 1435 do { 1436 StringToks.push_back(Tok); 1437 ConsumeStringToken(); 1438 } while (isTokenStringLiteral()); 1439 1440 // Pass the set of string tokens, ready for concatenation, to the actions. 1441 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size()); 1442} 1443 1444/// ParseExpressionList - Used for C/C++ (argument-)expression-list. 1445/// 1446/// argument-expression-list: 1447/// assignment-expression 1448/// argument-expression-list , assignment-expression 1449/// 1450/// [C++] expression-list: 1451/// [C++] assignment-expression 1452/// [C++] expression-list , assignment-expression 1453/// 1454bool Parser::ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs) { 1455 while (1) { 1456 OwningExprResult Expr(ParseAssignmentExpression()); 1457 if (Expr.isInvalid()) 1458 return true; 1459 1460 Exprs.push_back(Expr.release()); 1461 1462 if (Tok.isNot(tok::comma)) 1463 return false; 1464 // Move to the next argument, remember where the comma was. 1465 CommaLocs.push_back(ConsumeToken()); 1466 } 1467} 1468 1469/// ParseBlockId - Parse a block-id, which roughly looks like int (int x). 1470/// 1471/// [clang] block-id: 1472/// [clang] specifier-qualifier-list block-declarator 1473/// 1474void Parser::ParseBlockId() { 1475 // Parse the specifier-qualifier-list piece. 1476 DeclSpec DS; 1477 ParseSpecifierQualifierList(DS); 1478 1479 // Parse the block-declarator. 1480 Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext); 1481 ParseDeclarator(DeclaratorInfo); 1482 1483 // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes. 1484 DeclaratorInfo.AddAttributes(DS.TakeAttributes(), 1485 SourceLocation()); 1486 1487 if (Tok.is(tok::kw___attribute)) { 1488 SourceLocation Loc; 1489 AttributeList *AttrList = ParseAttributes(&Loc); 1490 DeclaratorInfo.AddAttributes(AttrList, Loc); 1491 } 1492 1493 // Inform sema that we are starting a block. 1494 Actions.ActOnBlockArguments(DeclaratorInfo, CurScope); 1495} 1496 1497/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks 1498/// like ^(int x){ return x+1; } 1499/// 1500/// block-literal: 1501/// [clang] '^' block-args[opt] compound-statement 1502/// [clang] '^' block-id compound-statement 1503/// [clang] block-args: 1504/// [clang] '(' parameter-list ')' 1505/// 1506Parser::OwningExprResult Parser::ParseBlockLiteralExpression() { 1507 assert(Tok.is(tok::caret) && "block literal starts with ^"); 1508 SourceLocation CaretLoc = ConsumeToken(); 1509 1510 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc, 1511 "block literal parsing"); 1512 1513 // Enter a scope to hold everything within the block. This includes the 1514 // argument decls, decls within the compound expression, etc. This also 1515 // allows determining whether a variable reference inside the block is 1516 // within or outside of the block. 1517 ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope | 1518 Scope::BreakScope | Scope::ContinueScope | 1519 Scope::DeclScope); 1520 1521 // Inform sema that we are starting a block. 1522 Actions.ActOnBlockStart(CaretLoc, CurScope); 1523 1524 // Parse the return type if present. 1525 DeclSpec DS; 1526 Declarator ParamInfo(DS, Declarator::BlockLiteralContext); 1527 // FIXME: Since the return type isn't actually parsed, it can't be used to 1528 // fill ParamInfo with an initial valid range, so do it manually. 1529 ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation())); 1530 1531 // If this block has arguments, parse them. There is no ambiguity here with 1532 // the expression case, because the expression case requires a parameter list. 1533 if (Tok.is(tok::l_paren)) { 1534 ParseParenDeclarator(ParamInfo); 1535 // Parse the pieces after the identifier as if we had "int(...)". 1536 // SetIdentifier sets the source range end, but in this case we're past 1537 // that location. 1538 SourceLocation Tmp = ParamInfo.getSourceRange().getEnd(); 1539 ParamInfo.SetIdentifier(0, CaretLoc); 1540 ParamInfo.SetRangeEnd(Tmp); 1541 if (ParamInfo.isInvalidType()) { 1542 // If there was an error parsing the arguments, they may have 1543 // tried to use ^(x+y) which requires an argument list. Just 1544 // skip the whole block literal. 1545 Actions.ActOnBlockError(CaretLoc, CurScope); 1546 return ExprError(); 1547 } 1548 1549 if (Tok.is(tok::kw___attribute)) { 1550 SourceLocation Loc; 1551 AttributeList *AttrList = ParseAttributes(&Loc); 1552 ParamInfo.AddAttributes(AttrList, Loc); 1553 } 1554 1555 // Inform sema that we are starting a block. 1556 Actions.ActOnBlockArguments(ParamInfo, CurScope); 1557 } else if (!Tok.is(tok::l_brace)) { 1558 ParseBlockId(); 1559 } else { 1560 // Otherwise, pretend we saw (void). 1561 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false, 1562 SourceLocation(), 1563 0, 0, 0, 1564 false, SourceLocation(), 1565 false, 0, 0, 0, 1566 CaretLoc, CaretLoc, 1567 ParamInfo), 1568 CaretLoc); 1569 1570 if (Tok.is(tok::kw___attribute)) { 1571 SourceLocation Loc; 1572 AttributeList *AttrList = ParseAttributes(&Loc); 1573 ParamInfo.AddAttributes(AttrList, Loc); 1574 } 1575 1576 // Inform sema that we are starting a block. 1577 Actions.ActOnBlockArguments(ParamInfo, CurScope); 1578 } 1579 1580 1581 OwningExprResult Result(Actions, true); 1582 if (!Tok.is(tok::l_brace)) { 1583 // Saw something like: ^expr 1584 Diag(Tok, diag::err_expected_expression); 1585 Actions.ActOnBlockError(CaretLoc, CurScope); 1586 return ExprError(); 1587 } 1588 1589 OwningStmtResult Stmt(ParseCompoundStatementBody()); 1590 if (!Stmt.isInvalid()) 1591 Result = Actions.ActOnBlockStmtExpr(CaretLoc, move(Stmt), CurScope); 1592 else 1593 Actions.ActOnBlockError(CaretLoc, CurScope); 1594 return move(Result); 1595} 1596