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