1 //===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
20 //===----------------------------------------------------------------------===//
22 #include "clang/Parse/Parser.h"
23 #include "clang/Basic/Diagnostic.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/SmallString.h"
26 using namespace clang;
28 /// PrecedenceLevels - These are precedences for the binary/ternary operators in
29 /// the C99 grammar. These have been named to relate with the C99 grammar
30 /// productions. Low precedences numbers bind more weakly than high numbers.
33 Unknown = 0, // Not binary operator.
35 Assignment = 2, // =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=
42 Equality = 9, // ==, !=
43 Relational = 10, // >=, <=, >, <
45 Additive = 12, // -, +
46 Multiplicative = 13 // *, /, %
51 /// getBinOpPrecedence - Return the precedence of the specified binary operator
52 /// token. This returns:
54 static prec::Level getBinOpPrecedence(tok::TokenKind Kind) {
56 default: return prec::Unknown;
57 case tok::comma: return prec::Comma;
61 case tok::percentequal:
64 case tok::lesslessequal:
65 case tok::greatergreaterequal:
68 case tok::pipeequal: return prec::Assignment;
69 case tok::question: return prec::Conditional;
70 case tok::pipepipe: return prec::LogicalOr;
71 case tok::ampamp: return prec::LogicalAnd;
72 case tok::pipe: return prec::InclusiveOr;
73 case tok::caret: return prec::ExclusiveOr;
74 case tok::amp: return prec::And;
75 case tok::exclaimequal:
76 case tok::equalequal: return prec::Equality;
79 case tok::greaterequal:
80 case tok::greater: return prec::Relational;
82 case tok::greatergreater: return prec::Shift;
84 case tok::minus: return prec::Additive;
87 case tok::star: return prec::Multiplicative;
92 /// ParseExpression - Simple precedence-based parser for binary/ternary
95 /// Note: we diverge from the C99 grammar when parsing the assignment-expression
96 /// production. C99 specifies that the LHS of an assignment operator should be
97 /// parsed as a unary-expression, but consistency dictates that it be a
98 /// conditional-expession. In practice, the important thing here is that the
99 /// LHS of an assignment has to be an l-value, which productions between
100 /// unary-expression and conditional-expression don't produce. Because we want
101 /// consistency, we parse the LHS as a conditional-expression, then check for
102 /// l-value-ness in semantic analysis stages.
104 /// multiplicative-expression: [C99 6.5.5]
106 /// multiplicative-expression '*' cast-expression
107 /// multiplicative-expression '/' cast-expression
108 /// multiplicative-expression '%' cast-expression
110 /// additive-expression: [C99 6.5.6]
111 /// multiplicative-expression
112 /// additive-expression '+' multiplicative-expression
113 /// additive-expression '-' multiplicative-expression
115 /// shift-expression: [C99 6.5.7]
116 /// additive-expression
117 /// shift-expression '<<' additive-expression
118 /// shift-expression '>>' additive-expression
120 /// relational-expression: [C99 6.5.8]
122 /// relational-expression '<' shift-expression
123 /// relational-expression '>' shift-expression
124 /// relational-expression '<=' shift-expression
125 /// relational-expression '>=' shift-expression
127 /// equality-expression: [C99 6.5.9]
128 /// relational-expression
129 /// equality-expression '==' relational-expression
130 /// equality-expression '!=' relational-expression
132 /// AND-expression: [C99 6.5.10]
133 /// equality-expression
134 /// AND-expression '&' equality-expression
136 /// exclusive-OR-expression: [C99 6.5.11]
138 /// exclusive-OR-expression '^' AND-expression
140 /// inclusive-OR-expression: [C99 6.5.12]
141 /// exclusive-OR-expression
142 /// inclusive-OR-expression '|' exclusive-OR-expression
144 /// logical-AND-expression: [C99 6.5.13]
145 /// inclusive-OR-expression
146 /// logical-AND-expression '&&' inclusive-OR-expression
148 /// logical-OR-expression: [C99 6.5.14]
149 /// logical-AND-expression
150 /// logical-OR-expression '||' logical-AND-expression
152 /// conditional-expression: [C99 6.5.15]
153 /// logical-OR-expression
154 /// logical-OR-expression '?' expression ':' conditional-expression
155 /// [GNU] logical-OR-expression '?' ':' conditional-expression
157 /// assignment-expression: [C99 6.5.16]
158 /// conditional-expression
159 /// unary-expression assignment-operator assignment-expression
160 /// [C++] throw-expression [C++ 15]
162 /// assignment-operator: one of
163 /// = *= /= %= += -= <<= >>= &= ^= |=
165 /// expression: [C99 6.5.17]
166 /// assignment-expression
167 /// expression ',' assignment-expression
169 Parser::ExprResult Parser::ParseExpression() {
170 if (Tok.is(tok::kw_throw))
171 return ParseThrowExpression();
173 ExprResult LHS = ParseCastExpression(false);
174 if (LHS.isInvalid) return LHS;
176 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
179 /// This routine is called when the '@' is seen and consumed.
180 /// Current token is an Identifier and is not a 'try'. This
181 /// routine is necessary to disambiguate @try-statement from,
182 /// for example, @encode-expression.
184 Parser::ExprResult Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
185 ExprResult LHS = ParseObjCAtExpression(AtLoc);
186 if (LHS.isInvalid) return LHS;
188 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
191 /// ParseAssignmentExpression - Parse an expr that doesn't include commas.
193 Parser::ExprResult Parser::ParseAssignmentExpression() {
194 if (Tok.is(tok::kw_throw))
195 return ParseThrowExpression();
197 ExprResult LHS = ParseCastExpression(false);
198 if (LHS.isInvalid) return LHS;
200 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
203 Parser::ExprResult Parser::ParseConstantExpression() {
204 ExprResult LHS = ParseCastExpression(false);
205 if (LHS.isInvalid) return LHS;
207 return ParseRHSOfBinaryExpression(LHS, prec::Conditional);
210 /// ParseExpressionWithLeadingIdentifier - This special purpose method is used
211 /// in contexts where we have already consumed an identifier (which we saved in
212 /// 'IdTok'), then discovered that the identifier was really the leading token
213 /// of part of an expression. For example, in "A[1]+B", we consumed "A" (which
214 /// is now in 'IdTok') and the current token is "[".
215 Parser::ExprResult Parser::
216 ParseExpressionWithLeadingIdentifier(const Token &IdTok) {
217 // We know that 'IdTok' must correspond to this production:
218 // primary-expression: identifier
220 // Let the actions module handle the identifier.
221 ExprResult Res = Actions.ActOnIdentifierExpr(CurScope, IdTok.getLocation(),
222 *IdTok.getIdentifierInfo(),
223 Tok.is(tok::l_paren));
225 // Because we have to parse an entire cast-expression before starting the
226 // ParseRHSOfBinaryExpression method (which parses any trailing binops), we
227 // need to handle the 'postfix-expression' rules. We do this by invoking
228 // ParsePostfixExpressionSuffix to consume any postfix-expression suffixes:
229 Res = ParsePostfixExpressionSuffix(Res);
230 if (Res.isInvalid) return Res;
232 // At this point, the "A[1]" part of "A[1]+B" has been consumed. Once this is
233 // done, we know we don't have to do anything for cast-expression, because the
234 // only non-postfix-expression production starts with a '(' token, and we know
235 // we have an identifier. As such, we can invoke ParseRHSOfBinaryExpression
236 // to consume any trailing operators (e.g. "+" in this example) and connected
237 // chunks of the expression.
238 return ParseRHSOfBinaryExpression(Res, prec::Comma);
241 /// ParseExpressionWithLeadingIdentifier - This special purpose method is used
242 /// in contexts where we have already consumed an identifier (which we saved in
243 /// 'IdTok'), then discovered that the identifier was really the leading token
244 /// of part of an assignment-expression. For example, in "A[1]+B", we consumed
245 /// "A" (which is now in 'IdTok') and the current token is "[".
246 Parser::ExprResult Parser::
247 ParseAssignmentExprWithLeadingIdentifier(const Token &IdTok) {
248 // We know that 'IdTok' must correspond to this production:
249 // primary-expression: identifier
251 // Let the actions module handle the identifier.
252 ExprResult Res = Actions.ActOnIdentifierExpr(CurScope, IdTok.getLocation(),
253 *IdTok.getIdentifierInfo(),
254 Tok.is(tok::l_paren));
256 // Because we have to parse an entire cast-expression before starting the
257 // ParseRHSOfBinaryExpression method (which parses any trailing binops), we
258 // need to handle the 'postfix-expression' rules. We do this by invoking
259 // ParsePostfixExpressionSuffix to consume any postfix-expression suffixes:
260 Res = ParsePostfixExpressionSuffix(Res);
261 if (Res.isInvalid) return Res;
263 // At this point, the "A[1]" part of "A[1]+B" has been consumed. Once this is
264 // done, we know we don't have to do anything for cast-expression, because the
265 // only non-postfix-expression production starts with a '(' token, and we know
266 // we have an identifier. As such, we can invoke ParseRHSOfBinaryExpression
267 // to consume any trailing operators (e.g. "+" in this example) and connected
268 // chunks of the expression.
269 return ParseRHSOfBinaryExpression(Res, prec::Assignment);
273 /// ParseAssignmentExpressionWithLeadingStar - This special purpose method is
274 /// used in contexts where we have already consumed a '*' (which we saved in
275 /// 'StarTok'), then discovered that the '*' was really the leading token of an
276 /// expression. For example, in "*(int*)P+B", we consumed "*" (which is
277 /// now in 'StarTok') and the current token is "(".
278 Parser::ExprResult Parser::
279 ParseAssignmentExpressionWithLeadingStar(const Token &StarTok) {
280 // We know that 'StarTok' must correspond to this production:
281 // unary-expression: unary-operator cast-expression
282 // where 'unary-operator' is '*'.
284 // Parse the cast-expression that follows the '*'. This will parse the
285 // "*(int*)P" part of "*(int*)P+B".
286 ExprResult Res = ParseCastExpression(false);
287 if (Res.isInvalid) return Res;
289 // Combine StarTok + Res to get the new AST for the combined expression..
290 Res = Actions.ActOnUnaryOp(StarTok.getLocation(), tok::star, Res.Val);
291 if (Res.isInvalid) return Res;
294 // We have to parse an entire cast-expression before starting the
295 // ParseRHSOfBinaryExpression method (which parses any trailing binops). Since
296 // we know that the only production above us is the cast-expression
297 // production, and because the only alternative productions start with a '('
298 // token (we know we had a '*'), there is no work to do to get a whole
301 // At this point, the "*(int*)P" part of "*(int*)P+B" has been consumed. Once
302 // this is done, we can invoke ParseRHSOfBinaryExpression to consume any
303 // trailing operators (e.g. "+" in this example) and connected chunks of the
304 // assignment-expression.
305 return ParseRHSOfBinaryExpression(Res, prec::Assignment);
309 /// ParseRHSOfBinaryExpression - Parse a binary expression that starts with
310 /// LHS and has a precedence of at least MinPrec.
312 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, unsigned MinPrec) {
313 unsigned NextTokPrec = getBinOpPrecedence(Tok.getKind());
314 SourceLocation ColonLoc;
317 // If this token has a lower precedence than we are allowed to parse (e.g.
318 // because we are called recursively, or because the token is not a binop),
320 if (NextTokPrec < MinPrec)
323 // Consume the operator, saving the operator token for error reporting.
327 // Special case handling for the ternary operator.
328 ExprResult TernaryMiddle(true);
329 if (NextTokPrec == prec::Conditional) {
330 if (Tok.isNot(tok::colon)) {
331 // Handle this production specially:
332 // logical-OR-expression '?' expression ':' conditional-expression
333 // In particular, the RHS of the '?' is 'expression', not
334 // 'logical-OR-expression' as we might expect.
335 TernaryMiddle = ParseExpression();
336 if (TernaryMiddle.isInvalid) {
337 Actions.DeleteExpr(LHS.Val);
338 return TernaryMiddle;
341 // Special case handling of "X ? Y : Z" where Y is empty:
342 // logical-OR-expression '?' ':' conditional-expression [GNU]
343 TernaryMiddle = ExprResult(false);
344 Diag(Tok, diag::ext_gnu_conditional_expr);
347 if (Tok.isNot(tok::colon)) {
348 Diag(Tok, diag::err_expected_colon);
349 Diag(OpToken, diag::err_matching, "?");
350 Actions.DeleteExpr(LHS.Val);
351 Actions.DeleteExpr(TernaryMiddle.Val);
352 return ExprResult(true);
356 ColonLoc = ConsumeToken();
359 // Parse another leaf here for the RHS of the operator.
360 ExprResult RHS = ParseCastExpression(false);
362 Actions.DeleteExpr(LHS.Val);
363 Actions.DeleteExpr(TernaryMiddle.Val);
367 // Remember the precedence of this operator and get the precedence of the
368 // operator immediately to the right of the RHS.
369 unsigned ThisPrec = NextTokPrec;
370 NextTokPrec = getBinOpPrecedence(Tok.getKind());
372 // Assignment and conditional expressions are right-associative.
373 bool isRightAssoc = ThisPrec == prec::Conditional ||
374 ThisPrec == prec::Assignment;
376 // Get the precedence of the operator to the right of the RHS. If it binds
377 // more tightly with RHS than we do, evaluate it completely first.
378 if (ThisPrec < NextTokPrec ||
379 (ThisPrec == NextTokPrec && isRightAssoc)) {
380 // If this is left-associative, only parse things on the RHS that bind
381 // more tightly than the current operator. If it is left-associative, it
382 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
383 // A=(B=(C=D)), where each paren is a level of recursion here.
384 RHS = ParseRHSOfBinaryExpression(RHS, ThisPrec + !isRightAssoc);
386 Actions.DeleteExpr(LHS.Val);
387 Actions.DeleteExpr(TernaryMiddle.Val);
391 NextTokPrec = getBinOpPrecedence(Tok.getKind());
393 assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
395 if (!LHS.isInvalid) {
396 // Combine the LHS and RHS into the LHS (e.g. build AST).
397 if (TernaryMiddle.isInvalid)
398 LHS = Actions.ActOnBinOp(OpToken.getLocation(), OpToken.getKind(),
401 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
402 LHS.Val, TernaryMiddle.Val, RHS.Val);
404 // We had a semantic error on the LHS. Just free the RHS and continue.
405 Actions.DeleteExpr(TernaryMiddle.Val);
406 Actions.DeleteExpr(RHS.Val);
411 /// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
412 /// true, parse a unary-expression.
414 /// cast-expression: [C99 6.5.4]
416 /// '(' type-name ')' cast-expression
418 /// unary-expression: [C99 6.5.3]
419 /// postfix-expression
420 /// '++' unary-expression
421 /// '--' unary-expression
422 /// unary-operator cast-expression
423 /// 'sizeof' unary-expression
424 /// 'sizeof' '(' type-name ')'
425 /// [GNU] '__alignof' unary-expression
426 /// [GNU] '__alignof' '(' type-name ')'
427 /// [GNU] '&&' identifier
429 /// unary-operator: one of
430 /// '&' '*' '+' '-' '~' '!'
431 /// [GNU] '__extension__' '__real' '__imag'
433 /// primary-expression: [C99 6.5.1]
437 /// [C++] boolean-literal [C++ 2.13.5]
438 /// '(' expression ')'
439 /// '__func__' [C99 6.4.2.2]
440 /// [GNU] '__FUNCTION__'
441 /// [GNU] '__PRETTY_FUNCTION__'
442 /// [GNU] '(' compound-statement ')'
443 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
444 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
445 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
447 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
448 /// [OBJC] '[' objc-message-expr ']'
449 /// [OBJC] '@selector' '(' objc-selector-arg ')'
450 /// [OBJC] '@protocol' '(' identifier ')'
451 /// [OBJC] '@encode' '(' type-name ')'
452 /// [OBJC] objc-string-literal
453 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
454 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
455 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
456 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
458 /// constant: [C99 6.4.4]
460 /// floating-constant
461 /// enumeration-constant -> identifier
462 /// character-constant
464 Parser::ExprResult Parser::ParseCastExpression(bool isUnaryExpression) {
466 tok::TokenKind SavedKind = Tok.getKind();
468 // This handles all of cast-expression, unary-expression, postfix-expression,
469 // and primary-expression. We handle them together like this for efficiency
470 // and to simplify handling of an expression starting with a '(' token: which
471 // may be one of a parenthesized expression, cast-expression, compound literal
472 // expression, or statement expression.
474 // If the parsed tokens consist of a primary-expression, the cases below
475 // call ParsePostfixExpressionSuffix to handle the postfix expression
476 // suffixes. Cases that cannot be followed by postfix exprs should
477 // return without invoking ParsePostfixExpressionSuffix.
480 // If this expression is limited to being a unary-expression, the parent can
481 // not start a cast expression.
482 ParenParseOption ParenExprType =
483 isUnaryExpression ? CompoundLiteral : CastExpr;
485 SourceLocation LParenLoc = Tok.getLocation();
486 SourceLocation RParenLoc;
487 Res = ParseParenExpression(ParenExprType, CastTy, RParenLoc);
488 if (Res.isInvalid) return Res;
490 switch (ParenExprType) {
491 case SimpleExpr: break; // Nothing else to do.
492 case CompoundStmt: break; // Nothing else to do.
493 case CompoundLiteral:
494 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
495 // postfix-expression exist, parse them now.
498 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. Parse
499 // the cast-expression that follows it next.
500 // TODO: For cast expression with CastTy.
501 Res = ParseCastExpression(false);
503 Res = Actions.ActOnCastExpr(LParenLoc, CastTy, RParenLoc, Res.Val);
507 // These can be followed by postfix-expr pieces.
508 return ParsePostfixExpressionSuffix(Res);
511 // primary-expression
512 case tok::numeric_constant:
513 // constant: integer-constant
514 // constant: floating-constant
516 Res = Actions.ActOnNumericConstant(Tok);
519 // These can be followed by postfix-expr pieces.
520 return ParsePostfixExpressionSuffix(Res);
524 return ParseCXXBoolLiteral();
526 case tok::identifier: { // primary-expression: identifier
527 // constant: enumeration-constant
528 // Consume the identifier so that we can see if it is followed by a '('.
529 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
530 // need to know whether or not this identifier is a function designator or
532 IdentifierInfo &II = *Tok.getIdentifierInfo();
533 SourceLocation L = ConsumeToken();
534 Res = Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren));
535 // These can be followed by postfix-expr pieces.
536 return ParsePostfixExpressionSuffix(Res);
538 case tok::char_constant: // constant: character-constant
539 Res = Actions.ActOnCharacterConstant(Tok);
541 // These can be followed by postfix-expr pieces.
542 return ParsePostfixExpressionSuffix(Res);
543 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
544 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
545 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
546 Res = Actions.ActOnPreDefinedExpr(Tok.getLocation(), SavedKind);
548 // These can be followed by postfix-expr pieces.
549 return ParsePostfixExpressionSuffix(Res);
550 case tok::string_literal: // primary-expression: string-literal
551 case tok::wide_string_literal:
552 Res = ParseStringLiteralExpression();
553 if (Res.isInvalid) return Res;
554 // This can be followed by postfix-expr pieces (e.g. "foo"[1]).
555 return ParsePostfixExpressionSuffix(Res);
556 case tok::kw___builtin_va_arg:
557 case tok::kw___builtin_offsetof:
558 case tok::kw___builtin_choose_expr:
559 case tok::kw___builtin_overload:
560 case tok::kw___builtin_types_compatible_p:
561 return ParseBuiltinPrimaryExpression();
562 case tok::plusplus: // unary-expression: '++' unary-expression
563 case tok::minusminus: { // unary-expression: '--' unary-expression
564 SourceLocation SavedLoc = ConsumeToken();
565 Res = ParseCastExpression(true);
567 Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
570 case tok::amp: // unary-expression: '&' cast-expression
571 case tok::star: // unary-expression: '*' cast-expression
572 case tok::plus: // unary-expression: '+' cast-expression
573 case tok::minus: // unary-expression: '-' cast-expression
574 case tok::tilde: // unary-expression: '~' cast-expression
575 case tok::exclaim: // unary-expression: '!' cast-expression
576 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
577 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
578 SourceLocation SavedLoc = ConsumeToken();
579 Res = ParseCastExpression(false);
581 Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
585 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
586 // __extension__ silences extension warnings in the subexpression.
587 bool SavedExtWarn = Diags.getWarnOnExtensions();
588 Diags.setWarnOnExtensions(false);
589 SourceLocation SavedLoc = ConsumeToken();
590 Res = ParseCastExpression(false);
592 Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
593 Diags.setWarnOnExtensions(SavedExtWarn);
596 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
597 // unary-expression: 'sizeof' '(' type-name ')'
598 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
599 // unary-expression: '__alignof' '(' type-name ')'
600 return ParseSizeofAlignofExpression();
601 case tok::ampamp: { // unary-expression: '&&' identifier
602 SourceLocation AmpAmpLoc = ConsumeToken();
603 if (Tok.isNot(tok::identifier)) {
604 Diag(Tok, diag::err_expected_ident);
605 return ExprResult(true);
608 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
609 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(),
610 Tok.getIdentifierInfo());
614 case tok::kw_const_cast:
615 case tok::kw_dynamic_cast:
616 case tok::kw_reinterpret_cast:
617 case tok::kw_static_cast:
618 return ParseCXXCasts();
620 SourceLocation AtLoc = ConsumeToken();
621 return ParseObjCAtExpression(AtLoc);
624 // These can be followed by postfix-expr pieces.
625 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression());
627 Diag(Tok, diag::err_expected_expression);
628 return ExprResult(true);
635 /// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
636 /// is parsed, this method parses any suffixes that apply.
638 /// postfix-expression: [C99 6.5.2]
639 /// primary-expression
640 /// postfix-expression '[' expression ']'
641 /// postfix-expression '(' argument-expression-list[opt] ')'
642 /// postfix-expression '.' identifier
643 /// postfix-expression '->' identifier
644 /// postfix-expression '++'
645 /// postfix-expression '--'
646 /// '(' type-name ')' '{' initializer-list '}'
647 /// '(' type-name ')' '{' initializer-list ',' '}'
649 /// argument-expression-list: [C99 6.5.2]
650 /// argument-expression
651 /// argument-expression-list ',' assignment-expression
653 Parser::ExprResult Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
655 // Now that the primary-expression piece of the postfix-expression has been
656 // parsed, see if there are any postfix-expression pieces here.
659 switch (Tok.getKind()) {
660 default: // Not a postfix-expression suffix.
662 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
663 Loc = ConsumeBracket();
664 ExprResult Idx = ParseExpression();
666 SourceLocation RLoc = Tok.getLocation();
668 if (!LHS.isInvalid && !Idx.isInvalid && Tok.is(tok::r_square))
669 LHS = Actions.ActOnArraySubscriptExpr(LHS.Val, Loc, Idx.Val, RLoc);
671 LHS = ExprResult(true);
674 MatchRHSPunctuation(tok::r_square, Loc);
678 case tok::l_paren: { // p-e: p-e '(' argument-expression-list[opt] ')'
679 llvm::SmallVector<ExprTy*, 8> ArgExprs;
680 llvm::SmallVector<SourceLocation, 8> CommaLocs;
682 Loc = ConsumeParen();
684 if (Tok.isNot(tok::r_paren)) {
686 ExprResult ArgExpr = ParseAssignmentExpression();
687 if (ArgExpr.isInvalid) {
688 SkipUntil(tok::r_paren);
689 return ExprResult(true);
691 ArgExprs.push_back(ArgExpr.Val);
693 if (Tok.isNot(tok::comma))
695 // Move to the next argument, remember where the comma was.
696 CommaLocs.push_back(ConsumeToken());
701 if (!LHS.isInvalid && Tok.is(tok::r_paren)) {
702 assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&&
703 "Unexpected number of commas!");
704 LHS = Actions.ActOnCallExpr(LHS.Val, Loc, &ArgExprs[0], ArgExprs.size(),
705 &CommaLocs[0], Tok.getLocation());
708 MatchRHSPunctuation(tok::r_paren, Loc);
711 case tok::arrow: // postfix-expression: p-e '->' identifier
712 case tok::period: { // postfix-expression: p-e '.' identifier
713 tok::TokenKind OpKind = Tok.getKind();
714 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
716 if (Tok.isNot(tok::identifier)) {
717 Diag(Tok, diag::err_expected_ident);
718 return ExprResult(true);
722 LHS = Actions.ActOnMemberReferenceExpr(LHS.Val, OpLoc, OpKind,
724 *Tok.getIdentifierInfo());
728 case tok::plusplus: // postfix-expression: postfix-expression '++'
729 case tok::minusminus: // postfix-expression: postfix-expression '--'
731 LHS = Actions.ActOnPostfixUnaryOp(Tok.getLocation(), Tok.getKind(),
740 /// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression.
741 /// unary-expression: [C99 6.5.3]
742 /// 'sizeof' unary-expression
743 /// 'sizeof' '(' type-name ')'
744 /// [GNU] '__alignof' unary-expression
745 /// [GNU] '__alignof' '(' type-name ')'
746 Parser::ExprResult Parser::ParseSizeofAlignofExpression() {
747 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof)) &&
748 "Not a sizeof/alignof expression!");
752 // If the operand doesn't start with an '(', it must be an expression.
754 if (Tok.isNot(tok::l_paren)) {
755 Operand = ParseCastExpression(true);
757 // If it starts with a '(', we know that it is either a parenthesized
758 // type-name, or it is a unary-expression that starts with a compound
759 // literal, or starts with a primary-expression that is a parenthesized
761 ParenParseOption ExprType = CastExpr;
763 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
764 Operand = ParseParenExpression(ExprType, CastTy, RParenLoc);
766 // If ParseParenExpression parsed a '(typename)' sequence only, the this is
767 // sizeof/alignof a type. Otherwise, it is sizeof/alignof an expression.
768 if (ExprType == CastExpr)
769 return Actions.ActOnSizeOfAlignOfTypeExpr(OpTok.getLocation(),
770 OpTok.is(tok::kw_sizeof),
771 LParenLoc, CastTy, RParenLoc);
773 // If this is a parenthesized expression, it is the start of a
774 // unary-expression, but doesn't include any postfix pieces. Parse these
776 Operand = ParsePostfixExpressionSuffix(Operand);
779 // If we get here, the operand to the sizeof/alignof was an expresion.
780 if (!Operand.isInvalid)
781 Operand = Actions.ActOnUnaryOp(OpTok.getLocation(), OpTok.getKind(),
786 /// ParseBuiltinPrimaryExpression
788 /// primary-expression: [C99 6.5.1]
789 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
790 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
791 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
793 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
794 /// [CLANG] '__builtin_overload' '(' expr (',' expr)* ')'
796 /// [GNU] offsetof-member-designator:
798 /// [GNU] offsetof-member-designator '.' identifier
799 /// [GNU] offsetof-member-designator '[' expression ']'
801 Parser::ExprResult Parser::ParseBuiltinPrimaryExpression() {
802 ExprResult Res(false);
803 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
805 tok::TokenKind T = Tok.getKind();
806 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
808 // All of these start with an open paren.
809 if (Tok.isNot(tok::l_paren)) {
810 Diag(Tok, diag::err_expected_lparen_after, BuiltinII->getName());
811 return ExprResult(true);
814 SourceLocation LParenLoc = ConsumeParen();
818 default: assert(0 && "Not a builtin primary expression!");
819 case tok::kw___builtin_va_arg: {
820 ExprResult Expr = ParseAssignmentExpression();
821 if (Expr.isInvalid) {
822 SkipUntil(tok::r_paren);
826 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
827 return ExprResult(true);
829 TypeTy *Ty = ParseTypeName();
831 if (Tok.isNot(tok::r_paren)) {
832 Diag(Tok, diag::err_expected_rparen);
833 return ExprResult(true);
835 Res = Actions.ActOnVAArg(StartLoc, Expr.Val, Ty, ConsumeParen());
838 case tok::kw___builtin_offsetof: {
839 SourceLocation TypeLoc = Tok.getLocation();
840 TypeTy *Ty = ParseTypeName();
842 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
843 return ExprResult(true);
845 // We must have at least one identifier here.
846 if (Tok.isNot(tok::identifier)) {
847 Diag(Tok, diag::err_expected_ident);
848 SkipUntil(tok::r_paren);
852 // Keep track of the various subcomponents we see.
853 llvm::SmallVector<Action::OffsetOfComponent, 4> Comps;
855 Comps.push_back(Action::OffsetOfComponent());
856 Comps.back().isBrackets = false;
857 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
858 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
861 if (Tok.is(tok::period)) {
862 // offsetof-member-designator: offsetof-member-designator '.' identifier
863 Comps.push_back(Action::OffsetOfComponent());
864 Comps.back().isBrackets = false;
865 Comps.back().LocStart = ConsumeToken();
867 if (Tok.isNot(tok::identifier)) {
868 Diag(Tok, diag::err_expected_ident);
869 SkipUntil(tok::r_paren);
872 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
873 Comps.back().LocEnd = ConsumeToken();
875 } else if (Tok.is(tok::l_square)) {
876 // offsetof-member-designator: offsetof-member-design '[' expression ']'
877 Comps.push_back(Action::OffsetOfComponent());
878 Comps.back().isBrackets = true;
879 Comps.back().LocStart = ConsumeBracket();
880 Res = ParseExpression();
882 SkipUntil(tok::r_paren);
885 Comps.back().U.E = Res.Val;
887 Comps.back().LocEnd =
888 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart);
889 } else if (Tok.is(tok::r_paren)) {
890 Res = Actions.ActOnBuiltinOffsetOf(StartLoc, TypeLoc, Ty, &Comps[0],
891 Comps.size(), ConsumeParen());
895 return ExprResult(true);
900 case tok::kw___builtin_choose_expr: {
901 ExprResult Cond = ParseAssignmentExpression();
902 if (Cond.isInvalid) {
903 SkipUntil(tok::r_paren);
906 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
907 return ExprResult(true);
909 ExprResult Expr1 = ParseAssignmentExpression();
910 if (Expr1.isInvalid) {
911 SkipUntil(tok::r_paren);
914 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
915 return ExprResult(true);
917 ExprResult Expr2 = ParseAssignmentExpression();
918 if (Expr2.isInvalid) {
919 SkipUntil(tok::r_paren);
922 if (Tok.isNot(tok::r_paren)) {
923 Diag(Tok, diag::err_expected_rparen);
924 return ExprResult(true);
926 Res = Actions.ActOnChooseExpr(StartLoc, Cond.Val, Expr1.Val, Expr2.Val,
930 case tok::kw___builtin_overload: {
931 llvm::SmallVector<ExprTy*, 8> ArgExprs;
932 llvm::SmallVector<SourceLocation, 8> CommaLocs;
934 // For each iteration through the loop look for assign-expr followed by a
935 // comma. If there is no comma, break and attempt to match r-paren.
936 if (Tok.isNot(tok::r_paren)) {
938 ExprResult ArgExpr = ParseAssignmentExpression();
939 if (ArgExpr.isInvalid) {
940 SkipUntil(tok::r_paren);
941 return ExprResult(true);
943 ArgExprs.push_back(ArgExpr.Val);
945 if (Tok.isNot(tok::comma))
947 // Move to the next argument, remember where the comma was.
948 CommaLocs.push_back(ConsumeToken());
952 // Attempt to consume the r-paren
953 if (Tok.isNot(tok::r_paren)) {
954 Diag(Tok, diag::err_expected_rparen);
955 SkipUntil(tok::r_paren);
956 return ExprResult(true);
958 Res = Actions.ActOnOverloadExpr(&ArgExprs[0], ArgExprs.size(),
959 &CommaLocs[0], StartLoc, ConsumeParen());
962 case tok::kw___builtin_types_compatible_p:
963 TypeTy *Ty1 = ParseTypeName();
965 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
966 return ExprResult(true);
968 TypeTy *Ty2 = ParseTypeName();
970 if (Tok.isNot(tok::r_paren)) {
971 Diag(Tok, diag::err_expected_rparen);
972 return ExprResult(true);
974 Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1, Ty2, ConsumeParen());
978 // These can be followed by postfix-expr pieces because they are
979 // primary-expressions.
980 return ParsePostfixExpressionSuffix(Res);
983 /// ParseParenExpression - This parses the unit that starts with a '(' token,
984 /// based on what is allowed by ExprType. The actual thing parsed is returned
987 /// primary-expression: [C99 6.5.1]
988 /// '(' expression ')'
989 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
990 /// postfix-expression: [C99 6.5.2]
991 /// '(' type-name ')' '{' initializer-list '}'
992 /// '(' type-name ')' '{' initializer-list ',' '}'
993 /// cast-expression: [C99 6.5.4]
994 /// '(' type-name ')' cast-expression
996 Parser::ExprResult Parser::ParseParenExpression(ParenParseOption &ExprType,
998 SourceLocation &RParenLoc) {
999 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
1000 SourceLocation OpenLoc = ConsumeParen();
1001 ExprResult Result(true);
1004 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
1005 Diag(Tok, diag::ext_gnu_statement_expr);
1006 Parser::StmtResult Stmt = ParseCompoundStatement(true);
1007 ExprType = CompoundStmt;
1009 // If the substmt parsed correctly, build the AST node.
1010 if (!Stmt.isInvalid && Tok.is(tok::r_paren))
1011 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.Val, Tok.getLocation());
1013 } else if (ExprType >= CompoundLiteral && isTypeSpecifierQualifier()) {
1014 // Otherwise, this is a compound literal expression or cast expression.
1015 TypeTy *Ty = ParseTypeName();
1018 if (Tok.is(tok::r_paren))
1019 RParenLoc = ConsumeParen();
1021 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1023 if (Tok.is(tok::l_brace)) {
1024 if (!getLang().C99) // Compound literals don't exist in C90.
1025 Diag(OpenLoc, diag::ext_c99_compound_literal);
1026 Result = ParseInitializer();
1027 ExprType = CompoundLiteral;
1028 if (!Result.isInvalid)
1029 return Actions.ActOnCompoundLiteral(OpenLoc, Ty, RParenLoc, Result.Val);
1030 } else if (ExprType == CastExpr) {
1031 // Note that this doesn't parse the subsequence cast-expression, it just
1032 // returns the parsed type to the callee.
1033 ExprType = CastExpr;
1035 return ExprResult(false);
1037 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
1038 return ExprResult(true);
1042 Result = ParseExpression();
1043 ExprType = SimpleExpr;
1044 if (!Result.isInvalid && Tok.is(tok::r_paren))
1045 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.Val);
1049 if (Result.isInvalid)
1050 SkipUntil(tok::r_paren);
1052 if (Tok.is(tok::r_paren))
1053 RParenLoc = ConsumeParen();
1055 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1061 /// ParseStringLiteralExpression - This handles the various token types that
1062 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
1063 /// translation phase #6].
1065 /// primary-expression: [C99 6.5.1]
1067 Parser::ExprResult Parser::ParseStringLiteralExpression() {
1068 assert(isTokenStringLiteral() && "Not a string literal!");
1070 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
1071 // considered to be strings for concatenation purposes.
1072 llvm::SmallVector<Token, 4> StringToks;
1075 StringToks.push_back(Tok);
1076 ConsumeStringToken();
1077 } while (isTokenStringLiteral());
1079 // Pass the set of string tokens, ready for concatenation, to the actions.
1080 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size());