blob: 46714b73ea7e3e811876c134eb7514f8d7bb1d22 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
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/Basic/Diagnostic.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/SmallString.h"
26using namespace clang;
27
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.
31namespace prec {
32 enum Level {
33 Unknown = 0, // Not binary operator.
34 Comma = 1, // ,
35 Assignment = 2, // =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=
36 Conditional = 3, // ?
37 LogicalOr = 4, // ||
38 LogicalAnd = 5, // &&
39 InclusiveOr = 6, // |
40 ExclusiveOr = 7, // ^
41 And = 8, // &
42 Equality = 9, // ==, !=
43 Relational = 10, // >=, <=, >, <
44 Shift = 11, // <<, >>
45 Additive = 12, // -, +
46 Multiplicative = 13 // *, /, %
47 };
48}
49
50
51/// getBinOpPrecedence - Return the precedence of the specified binary operator
52/// token. This returns:
53///
54static prec::Level getBinOpPrecedence(tok::TokenKind Kind) {
55 switch (Kind) {
56 default: return prec::Unknown;
57 case tok::comma: return prec::Comma;
58 case tok::equal:
59 case tok::starequal:
60 case tok::slashequal:
61 case tok::percentequal:
62 case tok::plusequal:
63 case tok::minusequal:
64 case tok::lesslessequal:
65 case tok::greatergreaterequal:
66 case tok::ampequal:
67 case tok::caretequal:
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;
77 case tok::lessequal:
78 case tok::less:
79 case tok::greaterequal:
80 case tok::greater: return prec::Relational;
81 case tok::lessless:
82 case tok::greatergreater: return prec::Shift;
83 case tok::plus:
84 case tok::minus: return prec::Additive;
85 case tok::percent:
86 case tok::slash:
87 case tok::star: return prec::Multiplicative;
88 }
89}
90
91
92/// ParseExpression - Simple precedence-based parser for binary/ternary
93/// operators.
94///
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.
103///
104/// multiplicative-expression: [C99 6.5.5]
105/// cast-expression
106/// multiplicative-expression '*' cast-expression
107/// multiplicative-expression '/' cast-expression
108/// multiplicative-expression '%' cast-expression
109///
110/// additive-expression: [C99 6.5.6]
111/// multiplicative-expression
112/// additive-expression '+' multiplicative-expression
113/// additive-expression '-' multiplicative-expression
114///
115/// shift-expression: [C99 6.5.7]
116/// additive-expression
117/// shift-expression '<<' additive-expression
118/// shift-expression '>>' additive-expression
119///
120/// relational-expression: [C99 6.5.8]
121/// shift-expression
122/// relational-expression '<' shift-expression
123/// relational-expression '>' shift-expression
124/// relational-expression '<=' shift-expression
125/// relational-expression '>=' shift-expression
126///
127/// equality-expression: [C99 6.5.9]
128/// relational-expression
129/// equality-expression '==' relational-expression
130/// equality-expression '!=' relational-expression
131///
132/// AND-expression: [C99 6.5.10]
133/// equality-expression
134/// AND-expression '&' equality-expression
135///
136/// exclusive-OR-expression: [C99 6.5.11]
137/// AND-expression
138/// exclusive-OR-expression '^' AND-expression
139///
140/// inclusive-OR-expression: [C99 6.5.12]
141/// exclusive-OR-expression
142/// inclusive-OR-expression '|' exclusive-OR-expression
143///
144/// logical-AND-expression: [C99 6.5.13]
145/// inclusive-OR-expression
146/// logical-AND-expression '&&' inclusive-OR-expression
147///
148/// logical-OR-expression: [C99 6.5.14]
149/// logical-AND-expression
150/// logical-OR-expression '||' logical-AND-expression
151///
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
156///
157/// assignment-expression: [C99 6.5.16]
158/// conditional-expression
159/// unary-expression assignment-operator assignment-expression
Chris Lattnera7447ba2008-02-26 00:51:44 +0000160/// [C++] throw-expression [C++ 15]
Chris Lattner4b009652007-07-25 00:24:17 +0000161///
162/// assignment-operator: one of
163/// = *= /= %= += -= <<= >>= &= ^= |=
164///
165/// expression: [C99 6.5.17]
166/// assignment-expression
167/// expression ',' assignment-expression
168///
169Parser::ExprResult Parser::ParseExpression() {
Chris Lattnera7447ba2008-02-26 00:51:44 +0000170 if (Tok.is(tok::kw_throw))
171 return ParseThrowExpression();
172
Chris Lattner4b009652007-07-25 00:24:17 +0000173 ExprResult LHS = ParseCastExpression(false);
174 if (LHS.isInvalid) return LHS;
175
176 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
177}
178
Fariborz Jahanian64b864e2007-09-19 19:14:32 +0000179/// This routine is called when the '@' is seen and consumed.
180/// Current token is an Identifier and is not a 'try'. This
Chris Lattnerb82d6ef2007-10-03 22:03:06 +0000181/// routine is necessary to disambiguate @try-statement from,
182/// for example, @encode-expression.
Fariborz Jahanian64b864e2007-09-19 19:14:32 +0000183///
Fariborz Jahanian37c9c612007-10-04 20:19:06 +0000184Parser::ExprResult Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
Steve Narofffb9dd752007-10-15 20:55:58 +0000185 ExprResult LHS = ParseObjCAtExpression(AtLoc);
Fariborz Jahanian64b864e2007-09-19 19:14:32 +0000186 if (LHS.isInvalid) return LHS;
187
188 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
189}
190
Chris Lattner4b009652007-07-25 00:24:17 +0000191/// ParseAssignmentExpression - Parse an expr that doesn't include commas.
192///
193Parser::ExprResult Parser::ParseAssignmentExpression() {
Chris Lattnera7447ba2008-02-26 00:51:44 +0000194 if (Tok.is(tok::kw_throw))
195 return ParseThrowExpression();
196
Chris Lattner4b009652007-07-25 00:24:17 +0000197 ExprResult LHS = ParseCastExpression(false);
198 if (LHS.isInvalid) return LHS;
199
200 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
201}
202
203Parser::ExprResult Parser::ParseConstantExpression() {
204 ExprResult LHS = ParseCastExpression(false);
205 if (LHS.isInvalid) return LHS;
206
Chris Lattner4b009652007-07-25 00:24:17 +0000207 return ParseRHSOfBinaryExpression(LHS, prec::Conditional);
208}
209
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 "[".
215Parser::ExprResult Parser::
216ParseExpressionWithLeadingIdentifier(const Token &IdTok) {
217 // We know that 'IdTok' must correspond to this production:
218 // primary-expression: identifier
219
220 // Let the actions module handle the identifier.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000221 ExprResult Res = Actions.ActOnIdentifierExpr(CurScope, IdTok.getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000222 *IdTok.getIdentifierInfo(),
Chris Lattner4d7d2342007-10-09 17:41:39 +0000223 Tok.is(tok::l_paren));
Chris Lattner4b009652007-07-25 00:24:17 +0000224
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;
231
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);
239}
240
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 "[".
246Parser::ExprResult Parser::
247ParseAssignmentExprWithLeadingIdentifier(const Token &IdTok) {
248 // We know that 'IdTok' must correspond to this production:
249 // primary-expression: identifier
250
251 // Let the actions module handle the identifier.
Steve Naroff0acc9c92007-09-15 18:49:24 +0000252 ExprResult Res = Actions.ActOnIdentifierExpr(CurScope, IdTok.getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000253 *IdTok.getIdentifierInfo(),
Chris Lattner4d7d2342007-10-09 17:41:39 +0000254 Tok.is(tok::l_paren));
Chris Lattner4b009652007-07-25 00:24:17 +0000255
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;
262
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);
270}
271
272
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 "(".
278Parser::ExprResult Parser::
279ParseAssignmentExpressionWithLeadingStar(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 '*'.
283
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;
288
289 // Combine StarTok + Res to get the new AST for the combined expression..
Steve Naroff87d58b42007-09-16 03:34:24 +0000290 Res = Actions.ActOnUnaryOp(StarTok.getLocation(), tok::star, Res.Val);
Chris Lattner4b009652007-07-25 00:24:17 +0000291 if (Res.isInvalid) return Res;
292
293
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
299 // cast-expression.
300
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);
306}
307
308
309/// ParseRHSOfBinaryExpression - Parse a binary expression that starts with
310/// LHS and has a precedence of at least MinPrec.
311Parser::ExprResult
312Parser::ParseRHSOfBinaryExpression(ExprResult LHS, unsigned MinPrec) {
313 unsigned NextTokPrec = getBinOpPrecedence(Tok.getKind());
314 SourceLocation ColonLoc;
315
316 while (1) {
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),
319 // then we are done!
320 if (NextTokPrec < MinPrec)
321 return LHS;
322
323 // Consume the operator, saving the operator token for error reporting.
324 Token OpToken = Tok;
325 ConsumeToken();
326
327 // Special case handling for the ternary operator.
328 ExprResult TernaryMiddle(true);
329 if (NextTokPrec == prec::Conditional) {
Chris Lattner4d7d2342007-10-09 17:41:39 +0000330 if (Tok.isNot(tok::colon)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000331 // 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();
Chris Lattner214cbaf2007-08-31 04:58:34 +0000336 if (TernaryMiddle.isInvalid) {
337 Actions.DeleteExpr(LHS.Val);
338 return TernaryMiddle;
339 }
Chris Lattner4b009652007-07-25 00:24:17 +0000340 } else {
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);
345 }
346
Chris Lattner4d7d2342007-10-09 17:41:39 +0000347 if (Tok.isNot(tok::colon)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000348 Diag(Tok, diag::err_expected_colon);
349 Diag(OpToken, diag::err_matching, "?");
Chris Lattner214cbaf2007-08-31 04:58:34 +0000350 Actions.DeleteExpr(LHS.Val);
351 Actions.DeleteExpr(TernaryMiddle.Val);
Chris Lattner4b009652007-07-25 00:24:17 +0000352 return ExprResult(true);
353 }
354
355 // Eat the colon.
356 ColonLoc = ConsumeToken();
357 }
358
359 // Parse another leaf here for the RHS of the operator.
360 ExprResult RHS = ParseCastExpression(false);
Chris Lattner214cbaf2007-08-31 04:58:34 +0000361 if (RHS.isInvalid) {
362 Actions.DeleteExpr(LHS.Val);
363 Actions.DeleteExpr(TernaryMiddle.Val);
364 return RHS;
365 }
Chris Lattner4b009652007-07-25 00:24:17 +0000366
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());
371
372 // Assignment and conditional expressions are right-associative.
Chris Lattner464c7f62007-12-18 06:06:23 +0000373 bool isRightAssoc = ThisPrec == prec::Conditional ||
374 ThisPrec == prec::Assignment;
Chris Lattner4b009652007-07-25 00:24:17 +0000375
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);
Chris Lattner214cbaf2007-08-31 04:58:34 +0000385 if (RHS.isInvalid) {
386 Actions.DeleteExpr(LHS.Val);
387 Actions.DeleteExpr(TernaryMiddle.Val);
388 return RHS;
389 }
Chris Lattner4b009652007-07-25 00:24:17 +0000390
391 NextTokPrec = getBinOpPrecedence(Tok.getKind());
392 }
393 assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
394
Chris Lattner4a149b62007-08-31 05:01:50 +0000395 if (!LHS.isInvalid) {
396 // Combine the LHS and RHS into the LHS (e.g. build AST).
397 if (TernaryMiddle.isInvalid)
Steve Naroff87d58b42007-09-16 03:34:24 +0000398 LHS = Actions.ActOnBinOp(OpToken.getLocation(), OpToken.getKind(),
Chris Lattner4a149b62007-08-31 05:01:50 +0000399 LHS.Val, RHS.Val);
400 else
Steve Naroff87d58b42007-09-16 03:34:24 +0000401 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
Chris Lattner4a149b62007-08-31 05:01:50 +0000402 LHS.Val, TernaryMiddle.Val, RHS.Val);
403 } else {
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);
407 }
Chris Lattner4b009652007-07-25 00:24:17 +0000408 }
409}
410
411/// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
412/// true, parse a unary-expression.
413///
414/// cast-expression: [C99 6.5.4]
415/// unary-expression
416/// '(' type-name ')' cast-expression
417///
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
428///
429/// unary-operator: one of
430/// '&' '*' '+' '-' '~' '!'
431/// [GNU] '__extension__' '__real' '__imag'
432///
433/// primary-expression: [C99 6.5.1]
434/// identifier
435/// constant
436/// string-literal
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 ','
446/// assign-expr ')'
447/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
Fariborz Jahanian628abf12007-09-26 17:03:44 +0000448/// [OBJC] '[' objc-message-expr ']'
Chris Lattner8d050af2008-01-25 18:58:06 +0000449/// [OBJC] '@selector' '(' objc-selector-arg ')'
Fariborz Jahanian628abf12007-09-26 17:03:44 +0000450/// [OBJC] '@protocol' '(' identifier ')'
451/// [OBJC] '@encode' '(' type-name ')'
Fariborz Jahanian1e534dc2007-09-05 19:52:07 +0000452/// [OBJC] objc-string-literal
Chris Lattner4b009652007-07-25 00:24:17 +0000453/// [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]
457///
458/// constant: [C99 6.4.4]
459/// integer-constant
460/// floating-constant
461/// enumeration-constant -> identifier
462/// character-constant
463///
464Parser::ExprResult Parser::ParseCastExpression(bool isUnaryExpression) {
465 ExprResult Res;
466 tok::TokenKind SavedKind = Tok.getKind();
467
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.
473 //
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.
478 switch (SavedKind) {
479 case tok::l_paren: {
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;
484 TypeTy *CastTy;
485 SourceLocation LParenLoc = Tok.getLocation();
486 SourceLocation RParenLoc;
487 Res = ParseParenExpression(ParenExprType, CastTy, RParenLoc);
488 if (Res.isInvalid) return Res;
489
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.
496 break;
497 case CastExpr:
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);
502 if (!Res.isInvalid)
Steve Naroff87d58b42007-09-16 03:34:24 +0000503 Res = Actions.ActOnCastExpr(LParenLoc, CastTy, RParenLoc, Res.Val);
Chris Lattner4b009652007-07-25 00:24:17 +0000504 return Res;
505 }
506
507 // These can be followed by postfix-expr pieces.
508 return ParsePostfixExpressionSuffix(Res);
509 }
510
511 // primary-expression
512 case tok::numeric_constant:
513 // constant: integer-constant
514 // constant: floating-constant
515
Steve Naroff87d58b42007-09-16 03:34:24 +0000516 Res = Actions.ActOnNumericConstant(Tok);
Chris Lattner4b009652007-07-25 00:24:17 +0000517 ConsumeToken();
518
519 // These can be followed by postfix-expr pieces.
520 return ParsePostfixExpressionSuffix(Res);
521
522 case tok::kw_true:
523 case tok::kw_false:
524 return ParseCXXBoolLiteral();
525
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
531 // not.
532 IdentifierInfo &II = *Tok.getIdentifierInfo();
533 SourceLocation L = ConsumeToken();
Chris Lattner4d7d2342007-10-09 17:41:39 +0000534 Res = Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren));
Chris Lattner4b009652007-07-25 00:24:17 +0000535 // These can be followed by postfix-expr pieces.
536 return ParsePostfixExpressionSuffix(Res);
537 }
538 case tok::char_constant: // constant: character-constant
Steve Naroff87d58b42007-09-16 03:34:24 +0000539 Res = Actions.ActOnCharacterConstant(Tok);
Chris Lattner4b009652007-07-25 00:24:17 +0000540 ConsumeToken();
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]
Steve Naroff87d58b42007-09-16 03:34:24 +0000546 Res = Actions.ActOnPreDefinedExpr(Tok.getLocation(), SavedKind);
Chris Lattner4b009652007-07-25 00:24:17 +0000547 ConsumeToken();
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:
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000559 case tok::kw___builtin_overload:
Chris Lattner4b009652007-07-25 00:24:17 +0000560 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);
566 if (!Res.isInvalid)
Steve Naroff87d58b42007-09-16 03:34:24 +0000567 Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
Chris Lattner4b009652007-07-25 00:24:17 +0000568 return Res;
569 }
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]
Chris Lattner6cf92942008-02-02 20:20:10 +0000577 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
Chris Lattner4b009652007-07-25 00:24:17 +0000578 SourceLocation SavedLoc = ConsumeToken();
579 Res = ParseCastExpression(false);
580 if (!Res.isInvalid)
Steve Naroff87d58b42007-09-16 03:34:24 +0000581 Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
Chris Lattner4b009652007-07-25 00:24:17 +0000582 return Res;
Chris Lattner6cf92942008-02-02 20:20:10 +0000583 }
584
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);
591 if (!Res.isInvalid)
592 Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
593 Diags.setWarnOnExtensions(SavedExtWarn);
594 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000595 }
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();
Chris Lattner4d7d2342007-10-09 17:41:39 +0000603 if (Tok.isNot(tok::identifier)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000604 Diag(Tok, diag::err_expected_ident);
605 return ExprResult(true);
606 }
607
608 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000609 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000610 Tok.getIdentifierInfo());
611 ConsumeToken();
612 return Res;
613 }
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();
Chris Lattnerb82d6ef2007-10-03 22:03:06 +0000619 case tok::at: {
620 SourceLocation AtLoc = ConsumeToken();
Steve Narofffb9dd752007-10-15 20:55:58 +0000621 return ParseObjCAtExpression(AtLoc);
Chris Lattnerb82d6ef2007-10-03 22:03:06 +0000622 }
Fariborz Jahanian1e534dc2007-09-05 19:52:07 +0000623 case tok::l_square:
Steve Narofffb9dd752007-10-15 20:55:58 +0000624 // These can be followed by postfix-expr pieces.
625 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression());
Chris Lattner4b009652007-07-25 00:24:17 +0000626 default:
627 Diag(Tok, diag::err_expected_expression);
628 return ExprResult(true);
629 }
630
631 // unreachable.
632 abort();
633}
634
635/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
636/// is parsed, this method parses any suffixes that apply.
637///
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 ',' '}'
648///
649/// argument-expression-list: [C99 6.5.2]
650/// argument-expression
651/// argument-expression-list ',' assignment-expression
652///
653Parser::ExprResult Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
654
655 // Now that the primary-expression piece of the postfix-expression has been
656 // parsed, see if there are any postfix-expression pieces here.
657 SourceLocation Loc;
658 while (1) {
659 switch (Tok.getKind()) {
660 default: // Not a postfix-expression suffix.
661 return LHS;
662 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
663 Loc = ConsumeBracket();
664 ExprResult Idx = ParseExpression();
665
666 SourceLocation RLoc = Tok.getLocation();
667
Chris Lattner4d7d2342007-10-09 17:41:39 +0000668 if (!LHS.isInvalid && !Idx.isInvalid && Tok.is(tok::r_square))
Steve Naroff87d58b42007-09-16 03:34:24 +0000669 LHS = Actions.ActOnArraySubscriptExpr(LHS.Val, Loc, Idx.Val, RLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000670 else
671 LHS = ExprResult(true);
672
673 // Match the ']'.
674 MatchRHSPunctuation(tok::r_square, Loc);
675 break;
676 }
677
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;
681
682 Loc = ConsumeParen();
683
Chris Lattner4d7d2342007-10-09 17:41:39 +0000684 if (Tok.isNot(tok::r_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000685 while (1) {
686 ExprResult ArgExpr = ParseAssignmentExpression();
687 if (ArgExpr.isInvalid) {
688 SkipUntil(tok::r_paren);
689 return ExprResult(true);
690 } else
691 ArgExprs.push_back(ArgExpr.Val);
692
Chris Lattner4d7d2342007-10-09 17:41:39 +0000693 if (Tok.isNot(tok::comma))
Chris Lattner4b009652007-07-25 00:24:17 +0000694 break;
695 // Move to the next argument, remember where the comma was.
696 CommaLocs.push_back(ConsumeToken());
697 }
698 }
699
700 // Match the ')'.
Chris Lattner4d7d2342007-10-09 17:41:39 +0000701 if (!LHS.isInvalid && Tok.is(tok::r_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000702 assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&&
703 "Unexpected number of commas!");
Steve Naroff87d58b42007-09-16 03:34:24 +0000704 LHS = Actions.ActOnCallExpr(LHS.Val, Loc, &ArgExprs[0], ArgExprs.size(),
Chris Lattner4b009652007-07-25 00:24:17 +0000705 &CommaLocs[0], Tok.getLocation());
706 }
707
708 MatchRHSPunctuation(tok::r_paren, Loc);
709 break;
710 }
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.
715
Chris Lattner4d7d2342007-10-09 17:41:39 +0000716 if (Tok.isNot(tok::identifier)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000717 Diag(Tok, diag::err_expected_ident);
718 return ExprResult(true);
719 }
720
721 if (!LHS.isInvalid)
Steve Naroff87d58b42007-09-16 03:34:24 +0000722 LHS = Actions.ActOnMemberReferenceExpr(LHS.Val, OpLoc, OpKind,
Chris Lattner4b009652007-07-25 00:24:17 +0000723 Tok.getLocation(),
724 *Tok.getIdentifierInfo());
725 ConsumeToken();
726 break;
727 }
728 case tok::plusplus: // postfix-expression: postfix-expression '++'
729 case tok::minusminus: // postfix-expression: postfix-expression '--'
730 if (!LHS.isInvalid)
Steve Naroff87d58b42007-09-16 03:34:24 +0000731 LHS = Actions.ActOnPostfixUnaryOp(Tok.getLocation(), Tok.getKind(),
Chris Lattner4b009652007-07-25 00:24:17 +0000732 LHS.Val);
733 ConsumeToken();
734 break;
735 }
736 }
737}
738
739
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 ')'
746Parser::ExprResult Parser::ParseSizeofAlignofExpression() {
Chris Lattner4d7d2342007-10-09 17:41:39 +0000747 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof)) &&
Chris Lattner4b009652007-07-25 00:24:17 +0000748 "Not a sizeof/alignof expression!");
749 Token OpTok = Tok;
750 ConsumeToken();
751
752 // If the operand doesn't start with an '(', it must be an expression.
753 ExprResult Operand;
Chris Lattner4d7d2342007-10-09 17:41:39 +0000754 if (Tok.isNot(tok::l_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000755 Operand = ParseCastExpression(true);
756 } else {
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
760 // expression.
761 ParenParseOption ExprType = CastExpr;
762 TypeTy *CastTy;
763 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
764 Operand = ParseParenExpression(ExprType, CastTy, RParenLoc);
765
766 // If ParseParenExpression parsed a '(typename)' sequence only, the this is
767 // sizeof/alignof a type. Otherwise, it is sizeof/alignof an expression.
Chris Lattner48553562007-11-13 20:50:37 +0000768 if (ExprType == CastExpr)
Steve Naroff87d58b42007-09-16 03:34:24 +0000769 return Actions.ActOnSizeOfAlignOfTypeExpr(OpTok.getLocation(),
Chris Lattner4d7d2342007-10-09 17:41:39 +0000770 OpTok.is(tok::kw_sizeof),
Chris Lattner4b009652007-07-25 00:24:17 +0000771 LParenLoc, CastTy, RParenLoc);
Chris Lattner48553562007-11-13 20:50:37 +0000772
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
775 // now if present.
776 Operand = ParsePostfixExpressionSuffix(Operand);
Chris Lattner4b009652007-07-25 00:24:17 +0000777 }
778
779 // If we get here, the operand to the sizeof/alignof was an expresion.
780 if (!Operand.isInvalid)
Steve Naroff87d58b42007-09-16 03:34:24 +0000781 Operand = Actions.ActOnUnaryOp(OpTok.getLocation(), OpTok.getKind(),
Chris Lattner4b009652007-07-25 00:24:17 +0000782 Operand.Val);
783 return Operand;
784}
785
786/// ParseBuiltinPrimaryExpression
787///
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 ','
792/// assign-expr ')'
793/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000794/// [CLANG] '__builtin_overload' '(' expr (',' expr)* ')'
Chris Lattner4b009652007-07-25 00:24:17 +0000795///
796/// [GNU] offsetof-member-designator:
797/// [GNU] identifier
798/// [GNU] offsetof-member-designator '.' identifier
799/// [GNU] offsetof-member-designator '[' expression ']'
800///
801Parser::ExprResult Parser::ParseBuiltinPrimaryExpression() {
802 ExprResult Res(false);
803 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
804
805 tok::TokenKind T = Tok.getKind();
806 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
807
808 // All of these start with an open paren.
Chris Lattner4d7d2342007-10-09 17:41:39 +0000809 if (Tok.isNot(tok::l_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000810 Diag(Tok, diag::err_expected_lparen_after, BuiltinII->getName());
811 return ExprResult(true);
812 }
813
814 SourceLocation LParenLoc = ConsumeParen();
815 // TODO: Build AST.
816
817 switch (T) {
818 default: assert(0 && "Not a builtin primary expression!");
Anders Carlsson36760332007-10-15 20:28:48 +0000819 case tok::kw___builtin_va_arg: {
820 ExprResult Expr = ParseAssignmentExpression();
821 if (Expr.isInvalid) {
Chris Lattner4b009652007-07-25 00:24:17 +0000822 SkipUntil(tok::r_paren);
823 return Res;
824 }
825
826 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
827 return ExprResult(true);
828
Anders Carlsson36760332007-10-15 20:28:48 +0000829 TypeTy *Ty = ParseTypeName();
Chris Lattnercb8943a2007-08-30 15:52:49 +0000830
Anders Carlsson36760332007-10-15 20:28:48 +0000831 if (Tok.isNot(tok::r_paren)) {
832 Diag(Tok, diag::err_expected_rparen);
833 return ExprResult(true);
834 }
835 Res = Actions.ActOnVAArg(StartLoc, Expr.Val, Ty, ConsumeParen());
Chris Lattner4b009652007-07-25 00:24:17 +0000836 break;
Anders Carlsson36760332007-10-15 20:28:48 +0000837 }
Chris Lattner69638b12007-08-30 15:51:11 +0000838 case tok::kw___builtin_offsetof: {
Chris Lattner1b6b5be2007-08-30 17:08:45 +0000839 SourceLocation TypeLoc = Tok.getLocation();
Chris Lattner69638b12007-08-30 15:51:11 +0000840 TypeTy *Ty = ParseTypeName();
Chris Lattner4b009652007-07-25 00:24:17 +0000841
842 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
843 return ExprResult(true);
844
845 // We must have at least one identifier here.
Chris Lattner4d7d2342007-10-09 17:41:39 +0000846 if (Tok.isNot(tok::identifier)) {
Chris Lattner69638b12007-08-30 15:51:11 +0000847 Diag(Tok, diag::err_expected_ident);
848 SkipUntil(tok::r_paren);
849 return true;
850 }
851
852 // Keep track of the various subcomponents we see.
853 llvm::SmallVector<Action::OffsetOfComponent, 4> Comps;
854
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();
Chris Lattner4b009652007-07-25 00:24:17 +0000859
860 while (1) {
Chris Lattner4d7d2342007-10-09 17:41:39 +0000861 if (Tok.is(tok::period)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000862 // offsetof-member-designator: offsetof-member-designator '.' identifier
Chris Lattner69638b12007-08-30 15:51:11 +0000863 Comps.push_back(Action::OffsetOfComponent());
864 Comps.back().isBrackets = false;
865 Comps.back().LocStart = ConsumeToken();
Chris Lattner4b009652007-07-25 00:24:17 +0000866
Chris Lattner4d7d2342007-10-09 17:41:39 +0000867 if (Tok.isNot(tok::identifier)) {
Chris Lattner69638b12007-08-30 15:51:11 +0000868 Diag(Tok, diag::err_expected_ident);
869 SkipUntil(tok::r_paren);
870 return true;
871 }
872 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
873 Comps.back().LocEnd = ConsumeToken();
874
Chris Lattner4d7d2342007-10-09 17:41:39 +0000875 } else if (Tok.is(tok::l_square)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000876 // offsetof-member-designator: offsetof-member-design '[' expression ']'
Chris Lattner69638b12007-08-30 15:51:11 +0000877 Comps.push_back(Action::OffsetOfComponent());
878 Comps.back().isBrackets = true;
879 Comps.back().LocStart = ConsumeBracket();
Chris Lattner4b009652007-07-25 00:24:17 +0000880 Res = ParseExpression();
881 if (Res.isInvalid) {
882 SkipUntil(tok::r_paren);
883 return Res;
884 }
Chris Lattner69638b12007-08-30 15:51:11 +0000885 Comps.back().U.E = Res.Val;
Chris Lattner4b009652007-07-25 00:24:17 +0000886
Chris Lattner69638b12007-08-30 15:51:11 +0000887 Comps.back().LocEnd =
888 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart);
Chris Lattner4d7d2342007-10-09 17:41:39 +0000889 } else if (Tok.is(tok::r_paren)) {
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000890 Res = Actions.ActOnBuiltinOffsetOf(StartLoc, TypeLoc, Ty, &Comps[0],
Chris Lattnercb8943a2007-08-30 15:52:49 +0000891 Comps.size(), ConsumeParen());
892 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000893 } else {
Chris Lattner69638b12007-08-30 15:51:11 +0000894 // Error occurred.
895 return ExprResult(true);
Chris Lattner4b009652007-07-25 00:24:17 +0000896 }
897 }
898 break;
Chris Lattner69638b12007-08-30 15:51:11 +0000899 }
Steve Naroff93c53012007-08-03 21:21:27 +0000900 case tok::kw___builtin_choose_expr: {
901 ExprResult Cond = ParseAssignmentExpression();
902 if (Cond.isInvalid) {
903 SkipUntil(tok::r_paren);
904 return Cond;
905 }
Chris Lattner4b009652007-07-25 00:24:17 +0000906 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
907 return ExprResult(true);
908
Steve Naroff93c53012007-08-03 21:21:27 +0000909 ExprResult Expr1 = ParseAssignmentExpression();
910 if (Expr1.isInvalid) {
911 SkipUntil(tok::r_paren);
912 return Expr1;
913 }
Chris Lattner4b009652007-07-25 00:24:17 +0000914 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
915 return ExprResult(true);
916
Steve Naroff93c53012007-08-03 21:21:27 +0000917 ExprResult Expr2 = ParseAssignmentExpression();
918 if (Expr2.isInvalid) {
919 SkipUntil(tok::r_paren);
920 return Expr2;
921 }
Chris Lattner4d7d2342007-10-09 17:41:39 +0000922 if (Tok.isNot(tok::r_paren)) {
Steve Naroff93c53012007-08-03 21:21:27 +0000923 Diag(Tok, diag::err_expected_rparen);
924 return ExprResult(true);
925 }
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000926 Res = Actions.ActOnChooseExpr(StartLoc, Cond.Val, Expr1.Val, Expr2.Val,
Chris Lattnercb8943a2007-08-30 15:52:49 +0000927 ConsumeParen());
928 break;
Steve Naroff93c53012007-08-03 21:21:27 +0000929 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000930 case tok::kw___builtin_overload: {
931 llvm::SmallVector<ExprTy*, 8> ArgExprs;
932 llvm::SmallVector<SourceLocation, 8> CommaLocs;
933
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)) {
937 while (1) {
938 ExprResult ArgExpr = ParseAssignmentExpression();
939 if (ArgExpr.isInvalid) {
940 SkipUntil(tok::r_paren);
941 return ExprResult(true);
942 } else
943 ArgExprs.push_back(ArgExpr.Val);
944
945 if (Tok.isNot(tok::comma))
946 break;
947 // Move to the next argument, remember where the comma was.
948 CommaLocs.push_back(ConsumeToken());
949 }
950 }
951
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);
957 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000958 Res = Actions.ActOnOverloadExpr(&ArgExprs[0], ArgExprs.size(),
959 &CommaLocs[0], StartLoc, ConsumeParen());
960 break;
961 }
Chris Lattner4b009652007-07-25 00:24:17 +0000962 case tok::kw___builtin_types_compatible_p:
Steve Naroff5b528922007-08-01 23:45:51 +0000963 TypeTy *Ty1 = ParseTypeName();
Chris Lattner4b009652007-07-25 00:24:17 +0000964
965 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
966 return ExprResult(true);
967
Steve Naroff5b528922007-08-01 23:45:51 +0000968 TypeTy *Ty2 = ParseTypeName();
969
Chris Lattner4d7d2342007-10-09 17:41:39 +0000970 if (Tok.isNot(tok::r_paren)) {
Steve Naroff5b528922007-08-01 23:45:51 +0000971 Diag(Tok, diag::err_expected_rparen);
972 return ExprResult(true);
973 }
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000974 Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1, Ty2, ConsumeParen());
Chris Lattnercb8943a2007-08-30 15:52:49 +0000975 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000976 }
977
Chris Lattner4b009652007-07-25 00:24:17 +0000978 // These can be followed by postfix-expr pieces because they are
979 // primary-expressions.
980 return ParsePostfixExpressionSuffix(Res);
981}
982
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
985/// in ExprType.
986///
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
995///
996Parser::ExprResult Parser::ParseParenExpression(ParenParseOption &ExprType,
997 TypeTy *&CastTy,
998 SourceLocation &RParenLoc) {
Chris Lattner4d7d2342007-10-09 17:41:39 +0000999 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
Chris Lattner4b009652007-07-25 00:24:17 +00001000 SourceLocation OpenLoc = ConsumeParen();
1001 ExprResult Result(true);
1002 CastTy = 0;
1003
Chris Lattner4d7d2342007-10-09 17:41:39 +00001004 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001005 Diag(Tok, diag::ext_gnu_statement_expr);
Chris Lattnerf2b07572007-08-31 21:49:55 +00001006 Parser::StmtResult Stmt = ParseCompoundStatement(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001007 ExprType = CompoundStmt;
1008
1009 // If the substmt parsed correctly, build the AST node.
Chris Lattner4d7d2342007-10-09 17:41:39 +00001010 if (!Stmt.isInvalid && Tok.is(tok::r_paren))
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001011 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.Val, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001012
1013 } else if (ExprType >= CompoundLiteral && isTypeSpecifierQualifier()) {
1014 // Otherwise, this is a compound literal expression or cast expression.
1015 TypeTy *Ty = ParseTypeName();
1016
1017 // Match the ')'.
Chris Lattner4d7d2342007-10-09 17:41:39 +00001018 if (Tok.is(tok::r_paren))
Chris Lattner4b009652007-07-25 00:24:17 +00001019 RParenLoc = ConsumeParen();
1020 else
1021 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1022
Chris Lattner4d7d2342007-10-09 17:41:39 +00001023 if (Tok.is(tok::l_brace)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001024 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)
Steve Naroff87d58b42007-09-16 03:34:24 +00001029 return Actions.ActOnCompoundLiteral(OpenLoc, Ty, RParenLoc, Result.Val);
Chris Lattner4b009652007-07-25 00:24:17 +00001030 } 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;
1034 CastTy = Ty;
1035 return ExprResult(false);
1036 } else {
1037 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
1038 return ExprResult(true);
1039 }
1040 return Result;
1041 } else {
1042 Result = ParseExpression();
1043 ExprType = SimpleExpr;
Chris Lattner4d7d2342007-10-09 17:41:39 +00001044 if (!Result.isInvalid && Tok.is(tok::r_paren))
Steve Naroff87d58b42007-09-16 03:34:24 +00001045 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.Val);
Chris Lattner4b009652007-07-25 00:24:17 +00001046 }
1047
1048 // Match the ')'.
1049 if (Result.isInvalid)
1050 SkipUntil(tok::r_paren);
1051 else {
Chris Lattner4d7d2342007-10-09 17:41:39 +00001052 if (Tok.is(tok::r_paren))
Chris Lattner4b009652007-07-25 00:24:17 +00001053 RParenLoc = ConsumeParen();
1054 else
1055 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1056 }
1057
1058 return Result;
1059}
1060
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].
1064///
1065/// primary-expression: [C99 6.5.1]
1066/// string-literal
1067Parser::ExprResult Parser::ParseStringLiteralExpression() {
1068 assert(isTokenStringLiteral() && "Not a string literal!");
1069
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;
1073
1074 do {
1075 StringToks.push_back(Tok);
1076 ConsumeStringToken();
1077 } while (isTokenStringLiteral());
1078
1079 // Pass the set of string tokens, ready for concatenation, to the actions.
Steve Naroff87d58b42007-09-16 03:34:24 +00001080 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size());
Chris Lattner4b009652007-07-25 00:24:17 +00001081}