blob: 7ab9d869c2d24cc84b0c2d08dc5afc503fe57881 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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"
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +000023#include "clang/Parse/DeclSpec.h"
Steve Naroff296e8d52008-08-28 19:20:44 +000024#include "clang/Parse/Scope.h"
Chris Lattnerc46d1a12008-10-20 06:45:43 +000025#include "ExtensionRAIIObject.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000026#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/SmallString.h"
28using namespace clang;
29
30/// PrecedenceLevels - These are precedences for the binary/ternary operators in
31/// the C99 grammar. These have been named to relate with the C99 grammar
32/// productions. Low precedences numbers bind more weakly than high numbers.
33namespace prec {
34 enum Level {
35 Unknown = 0, // Not binary operator.
36 Comma = 1, // ,
37 Assignment = 2, // =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=
38 Conditional = 3, // ?
39 LogicalOr = 4, // ||
40 LogicalAnd = 5, // &&
41 InclusiveOr = 6, // |
42 ExclusiveOr = 7, // ^
43 And = 8, // &
44 Equality = 9, // ==, !=
45 Relational = 10, // >=, <=, >, <
46 Shift = 11, // <<, >>
47 Additive = 12, // -, +
48 Multiplicative = 13 // *, /, %
49 };
50}
51
52
53/// getBinOpPrecedence - Return the precedence of the specified binary operator
54/// token. This returns:
55///
56static prec::Level getBinOpPrecedence(tok::TokenKind Kind) {
57 switch (Kind) {
58 default: return prec::Unknown;
59 case tok::comma: return prec::Comma;
60 case tok::equal:
61 case tok::starequal:
62 case tok::slashequal:
63 case tok::percentequal:
64 case tok::plusequal:
65 case tok::minusequal:
66 case tok::lesslessequal:
67 case tok::greatergreaterequal:
68 case tok::ampequal:
69 case tok::caretequal:
70 case tok::pipeequal: return prec::Assignment;
71 case tok::question: return prec::Conditional;
72 case tok::pipepipe: return prec::LogicalOr;
73 case tok::ampamp: return prec::LogicalAnd;
74 case tok::pipe: return prec::InclusiveOr;
75 case tok::caret: return prec::ExclusiveOr;
76 case tok::amp: return prec::And;
77 case tok::exclaimequal:
78 case tok::equalequal: return prec::Equality;
79 case tok::lessequal:
80 case tok::less:
81 case tok::greaterequal:
82 case tok::greater: return prec::Relational;
83 case tok::lessless:
84 case tok::greatergreater: return prec::Shift;
85 case tok::plus:
86 case tok::minus: return prec::Additive;
87 case tok::percent:
88 case tok::slash:
89 case tok::star: return prec::Multiplicative;
90 }
91}
92
93
94/// ParseExpression - Simple precedence-based parser for binary/ternary
95/// operators.
96///
97/// Note: we diverge from the C99 grammar when parsing the assignment-expression
98/// production. C99 specifies that the LHS of an assignment operator should be
99/// parsed as a unary-expression, but consistency dictates that it be a
100/// conditional-expession. In practice, the important thing here is that the
101/// LHS of an assignment has to be an l-value, which productions between
102/// unary-expression and conditional-expression don't produce. Because we want
103/// consistency, we parse the LHS as a conditional-expression, then check for
104/// l-value-ness in semantic analysis stages.
105///
106/// multiplicative-expression: [C99 6.5.5]
107/// cast-expression
108/// multiplicative-expression '*' cast-expression
109/// multiplicative-expression '/' cast-expression
110/// multiplicative-expression '%' cast-expression
111///
112/// additive-expression: [C99 6.5.6]
113/// multiplicative-expression
114/// additive-expression '+' multiplicative-expression
115/// additive-expression '-' multiplicative-expression
116///
117/// shift-expression: [C99 6.5.7]
118/// additive-expression
119/// shift-expression '<<' additive-expression
120/// shift-expression '>>' additive-expression
121///
122/// relational-expression: [C99 6.5.8]
123/// shift-expression
124/// relational-expression '<' shift-expression
125/// relational-expression '>' shift-expression
126/// relational-expression '<=' shift-expression
127/// relational-expression '>=' shift-expression
128///
129/// equality-expression: [C99 6.5.9]
130/// relational-expression
131/// equality-expression '==' relational-expression
132/// equality-expression '!=' relational-expression
133///
134/// AND-expression: [C99 6.5.10]
135/// equality-expression
136/// AND-expression '&' equality-expression
137///
138/// exclusive-OR-expression: [C99 6.5.11]
139/// AND-expression
140/// exclusive-OR-expression '^' AND-expression
141///
142/// inclusive-OR-expression: [C99 6.5.12]
143/// exclusive-OR-expression
144/// inclusive-OR-expression '|' exclusive-OR-expression
145///
146/// logical-AND-expression: [C99 6.5.13]
147/// inclusive-OR-expression
148/// logical-AND-expression '&&' inclusive-OR-expression
149///
150/// logical-OR-expression: [C99 6.5.14]
151/// logical-AND-expression
152/// logical-OR-expression '||' logical-AND-expression
153///
154/// conditional-expression: [C99 6.5.15]
155/// logical-OR-expression
156/// logical-OR-expression '?' expression ':' conditional-expression
157/// [GNU] logical-OR-expression '?' ':' conditional-expression
158///
159/// assignment-expression: [C99 6.5.16]
160/// conditional-expression
161/// unary-expression assignment-operator assignment-expression
Chris Lattner50dd2892008-02-26 00:51:44 +0000162/// [C++] throw-expression [C++ 15]
Reid Spencer5f016e22007-07-11 17:01:13 +0000163///
164/// assignment-operator: one of
165/// = *= /= %= += -= <<= >>= &= ^= |=
166///
167/// expression: [C99 6.5.17]
168/// assignment-expression
169/// expression ',' assignment-expression
170///
171Parser::ExprResult Parser::ParseExpression() {
Chris Lattner50dd2892008-02-26 00:51:44 +0000172 if (Tok.is(tok::kw_throw))
173 return ParseThrowExpression();
174
Reid Spencer5f016e22007-07-11 17:01:13 +0000175 ExprResult LHS = ParseCastExpression(false);
176 if (LHS.isInvalid) return LHS;
177
178 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
179}
180
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000181/// This routine is called when the '@' is seen and consumed.
182/// Current token is an Identifier and is not a 'try'. This
Chris Lattnerc97c2042007-10-03 22:03:06 +0000183/// routine is necessary to disambiguate @try-statement from,
184/// for example, @encode-expression.
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000185///
Fariborz Jahanianb384d322007-10-04 20:19:06 +0000186Parser::ExprResult Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
Steve Naroffa642beb2007-10-15 20:55:58 +0000187 ExprResult LHS = ParseObjCAtExpression(AtLoc);
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000188 if (LHS.isInvalid) return LHS;
189
190 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
191}
192
Reid Spencer5f016e22007-07-11 17:01:13 +0000193/// ParseAssignmentExpression - Parse an expr that doesn't include commas.
194///
195Parser::ExprResult Parser::ParseAssignmentExpression() {
Chris Lattner50dd2892008-02-26 00:51:44 +0000196 if (Tok.is(tok::kw_throw))
197 return ParseThrowExpression();
198
Reid Spencer5f016e22007-07-11 17:01:13 +0000199 ExprResult LHS = ParseCastExpression(false);
200 if (LHS.isInvalid) return LHS;
201
202 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
203}
204
Chris Lattnerb93fb492008-06-02 21:31:07 +0000205/// ParseAssignmentExprWithObjCMessageExprStart - Parse an assignment expression
206/// where part of an objc message send has already been parsed. In this case
207/// LBracLoc indicates the location of the '[' of the message send, and either
208/// ReceiverName or ReceiverExpr is non-null indicating the receiver of the
209/// message.
210///
211/// Since this handles full assignment-expression's, it handles postfix
212/// expressions and other binary operators for these expressions as well.
213Parser::ExprResult
214Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
215 IdentifierInfo *ReceiverName,
216 ExprTy *ReceiverExpr) {
217 ExprResult R = ParseObjCMessageExpressionBody(LBracLoc, ReceiverName,
218 ReceiverExpr);
219 if (R.isInvalid) return R;
220 R = ParsePostfixExpressionSuffix(R);
221 if (R.isInvalid) return R;
222 return ParseRHSOfBinaryExpression(R, 2);
223}
224
225
Reid Spencer5f016e22007-07-11 17:01:13 +0000226Parser::ExprResult Parser::ParseConstantExpression() {
227 ExprResult LHS = ParseCastExpression(false);
228 if (LHS.isInvalid) return LHS;
229
Reid Spencer5f016e22007-07-11 17:01:13 +0000230 return ParseRHSOfBinaryExpression(LHS, prec::Conditional);
231}
232
Reid Spencer5f016e22007-07-11 17:01:13 +0000233/// ParseRHSOfBinaryExpression - Parse a binary expression that starts with
234/// LHS and has a precedence of at least MinPrec.
235Parser::ExprResult
236Parser::ParseRHSOfBinaryExpression(ExprResult LHS, unsigned MinPrec) {
237 unsigned NextTokPrec = getBinOpPrecedence(Tok.getKind());
238 SourceLocation ColonLoc;
239
240 while (1) {
241 // If this token has a lower precedence than we are allowed to parse (e.g.
242 // because we are called recursively, or because the token is not a binop),
243 // then we are done!
244 if (NextTokPrec < MinPrec)
245 return LHS;
246
247 // Consume the operator, saving the operator token for error reporting.
Chris Lattnerd2177732007-07-20 16:59:19 +0000248 Token OpToken = Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 ConsumeToken();
250
251 // Special case handling for the ternary operator.
252 ExprResult TernaryMiddle(true);
253 if (NextTokPrec == prec::Conditional) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000254 if (Tok.isNot(tok::colon)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000255 // Handle this production specially:
256 // logical-OR-expression '?' expression ':' conditional-expression
257 // In particular, the RHS of the '?' is 'expression', not
258 // 'logical-OR-expression' as we might expect.
259 TernaryMiddle = ParseExpression();
Chris Lattnerdbd583c2007-08-31 04:58:34 +0000260 if (TernaryMiddle.isInvalid) {
261 Actions.DeleteExpr(LHS.Val);
262 return TernaryMiddle;
263 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000264 } else {
265 // Special case handling of "X ? Y : Z" where Y is empty:
266 // logical-OR-expression '?' ':' conditional-expression [GNU]
267 TernaryMiddle = ExprResult(false);
268 Diag(Tok, diag::ext_gnu_conditional_expr);
269 }
270
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000271 if (Tok.isNot(tok::colon)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000272 Diag(Tok, diag::err_expected_colon);
273 Diag(OpToken, diag::err_matching, "?");
Chris Lattnerdbd583c2007-08-31 04:58:34 +0000274 Actions.DeleteExpr(LHS.Val);
275 Actions.DeleteExpr(TernaryMiddle.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 return ExprResult(true);
277 }
278
279 // Eat the colon.
280 ColonLoc = ConsumeToken();
281 }
282
283 // Parse another leaf here for the RHS of the operator.
284 ExprResult RHS = ParseCastExpression(false);
Chris Lattnerdbd583c2007-08-31 04:58:34 +0000285 if (RHS.isInvalid) {
286 Actions.DeleteExpr(LHS.Val);
287 Actions.DeleteExpr(TernaryMiddle.Val);
288 return RHS;
289 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000290
291 // Remember the precedence of this operator and get the precedence of the
292 // operator immediately to the right of the RHS.
293 unsigned ThisPrec = NextTokPrec;
294 NextTokPrec = getBinOpPrecedence(Tok.getKind());
295
296 // Assignment and conditional expressions are right-associative.
Chris Lattnerd7d860d2007-12-18 06:06:23 +0000297 bool isRightAssoc = ThisPrec == prec::Conditional ||
298 ThisPrec == prec::Assignment;
Reid Spencer5f016e22007-07-11 17:01:13 +0000299
300 // Get the precedence of the operator to the right of the RHS. If it binds
301 // more tightly with RHS than we do, evaluate it completely first.
302 if (ThisPrec < NextTokPrec ||
303 (ThisPrec == NextTokPrec && isRightAssoc)) {
304 // If this is left-associative, only parse things on the RHS that bind
305 // more tightly than the current operator. If it is left-associative, it
306 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
307 // A=(B=(C=D)), where each paren is a level of recursion here.
308 RHS = ParseRHSOfBinaryExpression(RHS, ThisPrec + !isRightAssoc);
Chris Lattnerdbd583c2007-08-31 04:58:34 +0000309 if (RHS.isInvalid) {
310 Actions.DeleteExpr(LHS.Val);
311 Actions.DeleteExpr(TernaryMiddle.Val);
312 return RHS;
313 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000314
315 NextTokPrec = getBinOpPrecedence(Tok.getKind());
316 }
317 assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
318
Chris Lattnerd56d6b62007-08-31 05:01:50 +0000319 if (!LHS.isInvalid) {
320 // Combine the LHS and RHS into the LHS (e.g. build AST).
321 if (TernaryMiddle.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000322 LHS = Actions.ActOnBinOp(OpToken.getLocation(), OpToken.getKind(),
Chris Lattnerd56d6b62007-08-31 05:01:50 +0000323 LHS.Val, RHS.Val);
324 else
Steve Narofff69936d2007-09-16 03:34:24 +0000325 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
Chris Lattnerd56d6b62007-08-31 05:01:50 +0000326 LHS.Val, TernaryMiddle.Val, RHS.Val);
327 } else {
328 // We had a semantic error on the LHS. Just free the RHS and continue.
329 Actions.DeleteExpr(TernaryMiddle.Val);
330 Actions.DeleteExpr(RHS.Val);
331 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000332 }
333}
334
335/// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
336/// true, parse a unary-expression.
337///
338/// cast-expression: [C99 6.5.4]
339/// unary-expression
340/// '(' type-name ')' cast-expression
341///
342/// unary-expression: [C99 6.5.3]
343/// postfix-expression
344/// '++' unary-expression
345/// '--' unary-expression
346/// unary-operator cast-expression
347/// 'sizeof' unary-expression
348/// 'sizeof' '(' type-name ')'
349/// [GNU] '__alignof' unary-expression
350/// [GNU] '__alignof' '(' type-name ')'
351/// [GNU] '&&' identifier
352///
353/// unary-operator: one of
354/// '&' '*' '+' '-' '~' '!'
355/// [GNU] '__extension__' '__real' '__imag'
356///
357/// primary-expression: [C99 6.5.1]
358/// identifier
359/// constant
360/// string-literal
361/// [C++] boolean-literal [C++ 2.13.5]
362/// '(' expression ')'
363/// '__func__' [C99 6.4.2.2]
364/// [GNU] '__FUNCTION__'
365/// [GNU] '__PRETTY_FUNCTION__'
366/// [GNU] '(' compound-statement ')'
367/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
368/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
369/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
370/// assign-expr ')'
371/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
Fariborz Jahanian095ffca2007-09-26 17:03:44 +0000372/// [OBJC] '[' objc-message-expr ']'
Chris Lattner5ac87ed2008-01-25 18:58:06 +0000373/// [OBJC] '@selector' '(' objc-selector-arg ')'
Fariborz Jahanian095ffca2007-09-26 17:03:44 +0000374/// [OBJC] '@protocol' '(' identifier ')'
375/// [OBJC] '@encode' '(' type-name ')'
Fariborz Jahanian0ccb27d2007-09-05 19:52:07 +0000376/// [OBJC] objc-string-literal
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000377/// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
378/// [C++] typename-specifier '(' expression-list[opt] ')' [TODO]
Reid Spencer5f016e22007-07-11 17:01:13 +0000379/// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
380/// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
381/// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
382/// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
Argyrios Kyrtzidisd7464be2008-07-16 07:23:27 +0000383/// [C++] 'this' [C++ 9.3.2]
Steve Naroff296e8d52008-08-28 19:20:44 +0000384/// [clang] '^' block-literal
Reid Spencer5f016e22007-07-11 17:01:13 +0000385///
386/// constant: [C99 6.4.4]
387/// integer-constant
388/// floating-constant
389/// enumeration-constant -> identifier
390/// character-constant
391///
392Parser::ExprResult Parser::ParseCastExpression(bool isUnaryExpression) {
393 ExprResult Res;
394 tok::TokenKind SavedKind = Tok.getKind();
395
396 // This handles all of cast-expression, unary-expression, postfix-expression,
397 // and primary-expression. We handle them together like this for efficiency
398 // and to simplify handling of an expression starting with a '(' token: which
399 // may be one of a parenthesized expression, cast-expression, compound literal
400 // expression, or statement expression.
401 //
402 // If the parsed tokens consist of a primary-expression, the cases below
403 // call ParsePostfixExpressionSuffix to handle the postfix expression
404 // suffixes. Cases that cannot be followed by postfix exprs should
405 // return without invoking ParsePostfixExpressionSuffix.
406 switch (SavedKind) {
407 case tok::l_paren: {
408 // If this expression is limited to being a unary-expression, the parent can
409 // not start a cast expression.
410 ParenParseOption ParenExprType =
411 isUnaryExpression ? CompoundLiteral : CastExpr;
412 TypeTy *CastTy;
413 SourceLocation LParenLoc = Tok.getLocation();
414 SourceLocation RParenLoc;
415 Res = ParseParenExpression(ParenExprType, CastTy, RParenLoc);
416 if (Res.isInvalid) return Res;
417
418 switch (ParenExprType) {
419 case SimpleExpr: break; // Nothing else to do.
420 case CompoundStmt: break; // Nothing else to do.
421 case CompoundLiteral:
422 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
423 // postfix-expression exist, parse them now.
424 break;
425 case CastExpr:
426 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. Parse
427 // the cast-expression that follows it next.
428 // TODO: For cast expression with CastTy.
429 Res = ParseCastExpression(false);
430 if (!Res.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000431 Res = Actions.ActOnCastExpr(LParenLoc, CastTy, RParenLoc, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000432 return Res;
433 }
434
435 // These can be followed by postfix-expr pieces.
436 return ParsePostfixExpressionSuffix(Res);
437 }
438
439 // primary-expression
440 case tok::numeric_constant:
441 // constant: integer-constant
442 // constant: floating-constant
443
Steve Narofff69936d2007-09-16 03:34:24 +0000444 Res = Actions.ActOnNumericConstant(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000445 ConsumeToken();
446
447 // These can be followed by postfix-expr pieces.
448 return ParsePostfixExpressionSuffix(Res);
449
450 case tok::kw_true:
451 case tok::kw_false:
452 return ParseCXXBoolLiteral();
453
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000454 case tok::identifier: {
455 if (getLang().CPlusPlus &&
456 Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope)) {
457 // Handle C++ function-style cast, e.g. "T(4.5)" where T is a typedef for
458 // double.
459 goto HandleType;
460 }
461
462 // primary-expression: identifier
463 // constant: enumeration-constant
464
Reid Spencer5f016e22007-07-11 17:01:13 +0000465 // Consume the identifier so that we can see if it is followed by a '('.
466 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
467 // need to know whether or not this identifier is a function designator or
468 // not.
469 IdentifierInfo &II = *Tok.getIdentifierInfo();
470 SourceLocation L = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000471 Res = Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren));
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 // These can be followed by postfix-expr pieces.
473 return ParsePostfixExpressionSuffix(Res);
474 }
475 case tok::char_constant: // constant: character-constant
Steve Narofff69936d2007-09-16 03:34:24 +0000476 Res = Actions.ActOnCharacterConstant(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000477 ConsumeToken();
478 // These can be followed by postfix-expr pieces.
479 return ParsePostfixExpressionSuffix(Res);
480 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
481 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
482 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Chris Lattnerd9f69102008-08-10 01:53:14 +0000483 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 ConsumeToken();
485 // These can be followed by postfix-expr pieces.
486 return ParsePostfixExpressionSuffix(Res);
487 case tok::string_literal: // primary-expression: string-literal
488 case tok::wide_string_literal:
489 Res = ParseStringLiteralExpression();
490 if (Res.isInvalid) return Res;
491 // This can be followed by postfix-expr pieces (e.g. "foo"[1]).
492 return ParsePostfixExpressionSuffix(Res);
493 case tok::kw___builtin_va_arg:
494 case tok::kw___builtin_offsetof:
495 case tok::kw___builtin_choose_expr:
Nate Begemane2ce1d92008-01-17 17:46:27 +0000496 case tok::kw___builtin_overload:
Reid Spencer5f016e22007-07-11 17:01:13 +0000497 case tok::kw___builtin_types_compatible_p:
498 return ParseBuiltinPrimaryExpression();
499 case tok::plusplus: // unary-expression: '++' unary-expression
500 case tok::minusminus: { // unary-expression: '--' unary-expression
501 SourceLocation SavedLoc = ConsumeToken();
502 Res = ParseCastExpression(true);
503 if (!Res.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000504 Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 return Res;
506 }
507 case tok::amp: // unary-expression: '&' cast-expression
508 case tok::star: // unary-expression: '*' cast-expression
509 case tok::plus: // unary-expression: '+' cast-expression
510 case tok::minus: // unary-expression: '-' cast-expression
511 case tok::tilde: // unary-expression: '~' cast-expression
512 case tok::exclaim: // unary-expression: '!' cast-expression
513 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
Chris Lattner35080842008-02-02 20:20:10 +0000514 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
Reid Spencer5f016e22007-07-11 17:01:13 +0000515 SourceLocation SavedLoc = ConsumeToken();
516 Res = ParseCastExpression(false);
517 if (!Res.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000518 Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000519 return Res;
Chris Lattner35080842008-02-02 20:20:10 +0000520 }
521
522 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
523 // __extension__ silences extension warnings in the subexpression.
Chris Lattnerc46d1a12008-10-20 06:45:43 +0000524 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Chris Lattner35080842008-02-02 20:20:10 +0000525 SourceLocation SavedLoc = ConsumeToken();
526 Res = ParseCastExpression(false);
527 if (!Res.isInvalid)
528 Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
Chris Lattner35080842008-02-02 20:20:10 +0000529 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000530 }
531 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
532 // unary-expression: 'sizeof' '(' type-name ')'
533 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
534 // unary-expression: '__alignof' '(' type-name ')'
535 return ParseSizeofAlignofExpression();
536 case tok::ampamp: { // unary-expression: '&&' identifier
537 SourceLocation AmpAmpLoc = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000538 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 Diag(Tok, diag::err_expected_ident);
540 return ExprResult(true);
541 }
542
543 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
Steve Naroff1b273c42007-09-16 14:56:35 +0000544 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 Tok.getIdentifierInfo());
546 ConsumeToken();
547 return Res;
548 }
549 case tok::kw_const_cast:
550 case tok::kw_dynamic_cast:
551 case tok::kw_reinterpret_cast:
552 case tok::kw_static_cast:
Argyrios Kyrtzidisb348b812008-08-16 19:45:32 +0000553 Res = ParseCXXCasts();
554 // These can be followed by postfix-expr pieces.
555 return ParsePostfixExpressionSuffix(Res);
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000556 case tok::kw_this:
Argyrios Kyrtzidis289d7732008-08-16 19:34:46 +0000557 Res = ParseCXXThis();
558 // This can be followed by postfix-expr pieces.
559 return ParsePostfixExpressionSuffix(Res);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000560
561 case tok::kw_char:
562 case tok::kw_wchar_t:
563 case tok::kw_bool:
564 case tok::kw_short:
565 case tok::kw_int:
566 case tok::kw_long:
567 case tok::kw_signed:
568 case tok::kw_unsigned:
569 case tok::kw_float:
570 case tok::kw_double:
571 case tok::kw_void:
572 case tok::kw_typeof: {
573 if (!getLang().CPlusPlus)
574 goto UnhandledToken;
575 HandleType:
576 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
577 //
578 DeclSpec DS;
579 ParseCXXSimpleTypeSpecifier(DS);
580 if (Tok.isNot(tok::l_paren))
581 return Diag(Tok.getLocation(), diag::err_expected_lparen_after_type,
582 DS.getSourceRange());
583
584 Res = ParseCXXTypeConstructExpression(DS);
585 // This can be followed by postfix-expr pieces.
586 return ParsePostfixExpressionSuffix(Res);
587 }
588
Chris Lattnerc97c2042007-10-03 22:03:06 +0000589 case tok::at: {
590 SourceLocation AtLoc = ConsumeToken();
Steve Naroffa642beb2007-10-15 20:55:58 +0000591 return ParseObjCAtExpression(AtLoc);
Chris Lattnerc97c2042007-10-03 22:03:06 +0000592 }
Fariborz Jahanian0ccb27d2007-09-05 19:52:07 +0000593 case tok::l_square:
Steve Naroffa642beb2007-10-15 20:55:58 +0000594 // These can be followed by postfix-expr pieces.
Chris Lattner039a6422008-05-09 05:28:21 +0000595 if (getLang().ObjC1)
596 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression());
597 // FALL THROUGH.
Steve Naroff296e8d52008-08-28 19:20:44 +0000598 case tok::caret:
599 if (getLang().Blocks)
600 return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression());
601 Diag(Tok, diag::err_expected_expression);
602 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000603 default:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000604 UnhandledToken:
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 Diag(Tok, diag::err_expected_expression);
606 return ExprResult(true);
607 }
608
609 // unreachable.
610 abort();
611}
612
613/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
614/// is parsed, this method parses any suffixes that apply.
615///
616/// postfix-expression: [C99 6.5.2]
617/// primary-expression
618/// postfix-expression '[' expression ']'
619/// postfix-expression '(' argument-expression-list[opt] ')'
620/// postfix-expression '.' identifier
621/// postfix-expression '->' identifier
622/// postfix-expression '++'
623/// postfix-expression '--'
624/// '(' type-name ')' '{' initializer-list '}'
625/// '(' type-name ')' '{' initializer-list ',' '}'
626///
627/// argument-expression-list: [C99 6.5.2]
628/// argument-expression
629/// argument-expression-list ',' assignment-expression
630///
631Parser::ExprResult Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
632
633 // Now that the primary-expression piece of the postfix-expression has been
634 // parsed, see if there are any postfix-expression pieces here.
635 SourceLocation Loc;
636 while (1) {
637 switch (Tok.getKind()) {
638 default: // Not a postfix-expression suffix.
639 return LHS;
640 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
641 Loc = ConsumeBracket();
642 ExprResult Idx = ParseExpression();
643
644 SourceLocation RLoc = Tok.getLocation();
645
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000646 if (!LHS.isInvalid && !Idx.isInvalid && Tok.is(tok::r_square))
Steve Narofff69936d2007-09-16 03:34:24 +0000647 LHS = Actions.ActOnArraySubscriptExpr(LHS.Val, Loc, Idx.Val, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000648 else
649 LHS = ExprResult(true);
650
651 // Match the ']'.
652 MatchRHSPunctuation(tok::r_square, Loc);
653 break;
654 }
655
656 case tok::l_paren: { // p-e: p-e '(' argument-expression-list[opt] ')'
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +0000657 ExprListTy ArgExprs;
658 CommaLocsTy CommaLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000659
660 Loc = ConsumeParen();
661
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000662 if (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +0000663 if (ParseExpressionList(ArgExprs, CommaLocs)) {
664 SkipUntil(tok::r_paren);
665 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000666 }
667 }
668
669 // Match the ')'.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000670 if (!LHS.isInvalid && Tok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000671 assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&&
672 "Unexpected number of commas!");
Steve Narofff69936d2007-09-16 03:34:24 +0000673 LHS = Actions.ActOnCallExpr(LHS.Val, Loc, &ArgExprs[0], ArgExprs.size(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000674 &CommaLocs[0], Tok.getLocation());
675 }
676
Chris Lattner2ff54262007-07-21 05:18:12 +0000677 MatchRHSPunctuation(tok::r_paren, Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000678 break;
679 }
680 case tok::arrow: // postfix-expression: p-e '->' identifier
681 case tok::period: { // postfix-expression: p-e '.' identifier
682 tok::TokenKind OpKind = Tok.getKind();
683 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
684
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000685 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000686 Diag(Tok, diag::err_expected_ident);
687 return ExprResult(true);
688 }
689
690 if (!LHS.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000691 LHS = Actions.ActOnMemberReferenceExpr(LHS.Val, OpLoc, OpKind,
Reid Spencer5f016e22007-07-11 17:01:13 +0000692 Tok.getLocation(),
693 *Tok.getIdentifierInfo());
694 ConsumeToken();
695 break;
696 }
697 case tok::plusplus: // postfix-expression: postfix-expression '++'
698 case tok::minusminus: // postfix-expression: postfix-expression '--'
699 if (!LHS.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000700 LHS = Actions.ActOnPostfixUnaryOp(Tok.getLocation(), Tok.getKind(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000701 LHS.Val);
702 ConsumeToken();
703 break;
704 }
705 }
706}
707
708
709/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression.
710/// unary-expression: [C99 6.5.3]
711/// 'sizeof' unary-expression
712/// 'sizeof' '(' type-name ')'
713/// [GNU] '__alignof' unary-expression
714/// [GNU] '__alignof' '(' type-name ')'
715Parser::ExprResult Parser::ParseSizeofAlignofExpression() {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000716 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof)) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 "Not a sizeof/alignof expression!");
Chris Lattnerd2177732007-07-20 16:59:19 +0000718 Token OpTok = Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000719 ConsumeToken();
720
721 // If the operand doesn't start with an '(', it must be an expression.
722 ExprResult Operand;
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000723 if (Tok.isNot(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000724 Operand = ParseCastExpression(true);
725 } else {
726 // If it starts with a '(', we know that it is either a parenthesized
727 // type-name, or it is a unary-expression that starts with a compound
728 // literal, or starts with a primary-expression that is a parenthesized
729 // expression.
730 ParenParseOption ExprType = CastExpr;
731 TypeTy *CastTy;
732 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
733 Operand = ParseParenExpression(ExprType, CastTy, RParenLoc);
734
735 // If ParseParenExpression parsed a '(typename)' sequence only, the this is
736 // sizeof/alignof a type. Otherwise, it is sizeof/alignof an expression.
Chris Lattner4c1a2a92007-11-13 20:50:37 +0000737 if (ExprType == CastExpr)
Steve Narofff69936d2007-09-16 03:34:24 +0000738 return Actions.ActOnSizeOfAlignOfTypeExpr(OpTok.getLocation(),
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000739 OpTok.is(tok::kw_sizeof),
Reid Spencer5f016e22007-07-11 17:01:13 +0000740 LParenLoc, CastTy, RParenLoc);
Chris Lattner4c1a2a92007-11-13 20:50:37 +0000741
742 // If this is a parenthesized expression, it is the start of a
743 // unary-expression, but doesn't include any postfix pieces. Parse these
744 // now if present.
745 Operand = ParsePostfixExpressionSuffix(Operand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 }
747
748 // If we get here, the operand to the sizeof/alignof was an expresion.
749 if (!Operand.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000750 Operand = Actions.ActOnUnaryOp(OpTok.getLocation(), OpTok.getKind(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000751 Operand.Val);
752 return Operand;
753}
754
755/// ParseBuiltinPrimaryExpression
756///
757/// primary-expression: [C99 6.5.1]
758/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
759/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
760/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
761/// assign-expr ')'
762/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
Nate Begemane2ce1d92008-01-17 17:46:27 +0000763/// [CLANG] '__builtin_overload' '(' expr (',' expr)* ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000764///
765/// [GNU] offsetof-member-designator:
766/// [GNU] identifier
767/// [GNU] offsetof-member-designator '.' identifier
768/// [GNU] offsetof-member-designator '[' expression ']'
769///
770Parser::ExprResult Parser::ParseBuiltinPrimaryExpression() {
771 ExprResult Res(false);
772 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
773
774 tok::TokenKind T = Tok.getKind();
775 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
776
777 // All of these start with an open paren.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000778 if (Tok.isNot(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000779 Diag(Tok, diag::err_expected_lparen_after, BuiltinII->getName());
780 return ExprResult(true);
781 }
782
783 SourceLocation LParenLoc = ConsumeParen();
784 // TODO: Build AST.
785
786 switch (T) {
787 default: assert(0 && "Not a builtin primary expression!");
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000788 case tok::kw___builtin_va_arg: {
789 ExprResult Expr = ParseAssignmentExpression();
790 if (Expr.isInvalid) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000791 SkipUntil(tok::r_paren);
Eli Friedman09762782008-08-20 22:07:34 +0000792 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000793 }
794
795 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
796 return ExprResult(true);
797
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000798 TypeTy *Ty = ParseTypeName();
Chris Lattner6eb21092007-08-30 15:52:49 +0000799
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000800 if (Tok.isNot(tok::r_paren)) {
801 Diag(Tok, diag::err_expected_rparen);
802 return ExprResult(true);
803 }
804 Res = Actions.ActOnVAArg(StartLoc, Expr.Val, Ty, ConsumeParen());
Reid Spencer5f016e22007-07-11 17:01:13 +0000805 break;
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000806 }
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000807 case tok::kw___builtin_offsetof: {
Chris Lattner9fddf0a2007-08-30 17:08:45 +0000808 SourceLocation TypeLoc = Tok.getLocation();
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000809 TypeTy *Ty = ParseTypeName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000810
811 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
812 return ExprResult(true);
813
814 // We must have at least one identifier here.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000815 if (Tok.isNot(tok::identifier)) {
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000816 Diag(Tok, diag::err_expected_ident);
817 SkipUntil(tok::r_paren);
818 return true;
819 }
820
821 // Keep track of the various subcomponents we see.
822 llvm::SmallVector<Action::OffsetOfComponent, 4> Comps;
823
824 Comps.push_back(Action::OffsetOfComponent());
825 Comps.back().isBrackets = false;
826 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
827 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
Reid Spencer5f016e22007-07-11 17:01:13 +0000828
829 while (1) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000830 if (Tok.is(tok::period)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000831 // offsetof-member-designator: offsetof-member-designator '.' identifier
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000832 Comps.push_back(Action::OffsetOfComponent());
833 Comps.back().isBrackets = false;
834 Comps.back().LocStart = ConsumeToken();
Reid Spencer5f016e22007-07-11 17:01:13 +0000835
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000836 if (Tok.isNot(tok::identifier)) {
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000837 Diag(Tok, diag::err_expected_ident);
838 SkipUntil(tok::r_paren);
839 return true;
840 }
841 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
842 Comps.back().LocEnd = ConsumeToken();
843
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000844 } else if (Tok.is(tok::l_square)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000845 // offsetof-member-designator: offsetof-member-design '[' expression ']'
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000846 Comps.push_back(Action::OffsetOfComponent());
847 Comps.back().isBrackets = true;
848 Comps.back().LocStart = ConsumeBracket();
Reid Spencer5f016e22007-07-11 17:01:13 +0000849 Res = ParseExpression();
850 if (Res.isInvalid) {
851 SkipUntil(tok::r_paren);
852 return Res;
853 }
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000854 Comps.back().U.E = Res.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000855
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000856 Comps.back().LocEnd =
857 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart);
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000858 } else if (Tok.is(tok::r_paren)) {
Steve Naroff1b273c42007-09-16 14:56:35 +0000859 Res = Actions.ActOnBuiltinOffsetOf(StartLoc, TypeLoc, Ty, &Comps[0],
Chris Lattner6eb21092007-08-30 15:52:49 +0000860 Comps.size(), ConsumeParen());
861 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000862 } else {
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000863 // Error occurred.
864 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000865 }
866 }
867 break;
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000868 }
Steve Naroffd04fdd52007-08-03 21:21:27 +0000869 case tok::kw___builtin_choose_expr: {
870 ExprResult Cond = ParseAssignmentExpression();
871 if (Cond.isInvalid) {
872 SkipUntil(tok::r_paren);
873 return Cond;
874 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000875 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
876 return ExprResult(true);
877
Steve Naroffd04fdd52007-08-03 21:21:27 +0000878 ExprResult Expr1 = ParseAssignmentExpression();
879 if (Expr1.isInvalid) {
880 SkipUntil(tok::r_paren);
881 return Expr1;
882 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000883 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
884 return ExprResult(true);
885
Steve Naroffd04fdd52007-08-03 21:21:27 +0000886 ExprResult Expr2 = ParseAssignmentExpression();
887 if (Expr2.isInvalid) {
888 SkipUntil(tok::r_paren);
889 return Expr2;
890 }
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000891 if (Tok.isNot(tok::r_paren)) {
Steve Naroffd04fdd52007-08-03 21:21:27 +0000892 Diag(Tok, diag::err_expected_rparen);
893 return ExprResult(true);
894 }
Steve Naroff1b273c42007-09-16 14:56:35 +0000895 Res = Actions.ActOnChooseExpr(StartLoc, Cond.Val, Expr1.Val, Expr2.Val,
Chris Lattner6eb21092007-08-30 15:52:49 +0000896 ConsumeParen());
897 break;
Steve Naroffd04fdd52007-08-03 21:21:27 +0000898 }
Nate Begemane2ce1d92008-01-17 17:46:27 +0000899 case tok::kw___builtin_overload: {
900 llvm::SmallVector<ExprTy*, 8> ArgExprs;
901 llvm::SmallVector<SourceLocation, 8> CommaLocs;
902
903 // For each iteration through the loop look for assign-expr followed by a
904 // comma. If there is no comma, break and attempt to match r-paren.
905 if (Tok.isNot(tok::r_paren)) {
906 while (1) {
907 ExprResult ArgExpr = ParseAssignmentExpression();
908 if (ArgExpr.isInvalid) {
909 SkipUntil(tok::r_paren);
910 return ExprResult(true);
911 } else
912 ArgExprs.push_back(ArgExpr.Val);
913
914 if (Tok.isNot(tok::comma))
915 break;
916 // Move to the next argument, remember where the comma was.
917 CommaLocs.push_back(ConsumeToken());
918 }
919 }
920
921 // Attempt to consume the r-paren
922 if (Tok.isNot(tok::r_paren)) {
923 Diag(Tok, diag::err_expected_rparen);
924 SkipUntil(tok::r_paren);
925 return ExprResult(true);
926 }
Nate Begemane2ce1d92008-01-17 17:46:27 +0000927 Res = Actions.ActOnOverloadExpr(&ArgExprs[0], ArgExprs.size(),
928 &CommaLocs[0], StartLoc, ConsumeParen());
929 break;
930 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000931 case tok::kw___builtin_types_compatible_p:
Steve Naroff363bcff2007-08-01 23:45:51 +0000932 TypeTy *Ty1 = ParseTypeName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000933
934 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
935 return ExprResult(true);
936
Steve Naroff363bcff2007-08-01 23:45:51 +0000937 TypeTy *Ty2 = ParseTypeName();
938
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000939 if (Tok.isNot(tok::r_paren)) {
Steve Naroff363bcff2007-08-01 23:45:51 +0000940 Diag(Tok, diag::err_expected_rparen);
941 return ExprResult(true);
942 }
Steve Naroff1b273c42007-09-16 14:56:35 +0000943 Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1, Ty2, ConsumeParen());
Chris Lattner6eb21092007-08-30 15:52:49 +0000944 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000945 }
946
Reid Spencer5f016e22007-07-11 17:01:13 +0000947 // These can be followed by postfix-expr pieces because they are
948 // primary-expressions.
949 return ParsePostfixExpressionSuffix(Res);
950}
951
952/// ParseParenExpression - This parses the unit that starts with a '(' token,
953/// based on what is allowed by ExprType. The actual thing parsed is returned
954/// in ExprType.
955///
956/// primary-expression: [C99 6.5.1]
957/// '(' expression ')'
958/// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
959/// postfix-expression: [C99 6.5.2]
960/// '(' type-name ')' '{' initializer-list '}'
961/// '(' type-name ')' '{' initializer-list ',' '}'
962/// cast-expression: [C99 6.5.4]
963/// '(' type-name ')' cast-expression
964///
965Parser::ExprResult Parser::ParseParenExpression(ParenParseOption &ExprType,
966 TypeTy *&CastTy,
967 SourceLocation &RParenLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000968 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000969 SourceLocation OpenLoc = ConsumeParen();
Chris Lattnerab18c4c2007-07-24 16:58:17 +0000970 ExprResult Result(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000971 CastTy = 0;
972
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000973 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000974 Diag(Tok, diag::ext_gnu_statement_expr);
Chris Lattner98414c12007-08-31 21:49:55 +0000975 Parser::StmtResult Stmt = ParseCompoundStatement(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000976 ExprType = CompoundStmt;
Chris Lattnerab18c4c2007-07-24 16:58:17 +0000977
978 // If the substmt parsed correctly, build the AST node.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000979 if (!Stmt.isInvalid && Tok.is(tok::r_paren))
Steve Naroff1b273c42007-09-16 14:56:35 +0000980 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.Val, Tok.getLocation());
Chris Lattnerab18c4c2007-07-24 16:58:17 +0000981
Argyrios Kyrtzidis78c8d802008-10-05 19:56:22 +0000982 } else if (ExprType >= CompoundLiteral && isTypeIdInParens()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000983 // Otherwise, this is a compound literal expression or cast expression.
984 TypeTy *Ty = ParseTypeName();
985
986 // Match the ')'.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000987 if (Tok.is(tok::r_paren))
Reid Spencer5f016e22007-07-11 17:01:13 +0000988 RParenLoc = ConsumeParen();
989 else
990 MatchRHSPunctuation(tok::r_paren, OpenLoc);
991
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000992 if (Tok.is(tok::l_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000993 if (!getLang().C99) // Compound literals don't exist in C90.
994 Diag(OpenLoc, diag::ext_c99_compound_literal);
995 Result = ParseInitializer();
996 ExprType = CompoundLiteral;
Steve Naroff4aa88f82007-07-19 01:06:55 +0000997 if (!Result.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000998 return Actions.ActOnCompoundLiteral(OpenLoc, Ty, RParenLoc, Result.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000999 } else if (ExprType == CastExpr) {
1000 // Note that this doesn't parse the subsequence cast-expression, it just
1001 // returns the parsed type to the callee.
1002 ExprType = CastExpr;
1003 CastTy = Ty;
1004 return ExprResult(false);
1005 } else {
1006 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
1007 return ExprResult(true);
1008 }
1009 return Result;
1010 } else {
1011 Result = ParseExpression();
1012 ExprType = SimpleExpr;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001013 if (!Result.isInvalid && Tok.is(tok::r_paren))
Steve Narofff69936d2007-09-16 03:34:24 +00001014 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +00001015 }
1016
1017 // Match the ')'.
1018 if (Result.isInvalid)
1019 SkipUntil(tok::r_paren);
1020 else {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001021 if (Tok.is(tok::r_paren))
Reid Spencer5f016e22007-07-11 17:01:13 +00001022 RParenLoc = ConsumeParen();
1023 else
1024 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1025 }
1026
1027 return Result;
1028}
1029
1030/// ParseStringLiteralExpression - This handles the various token types that
1031/// form string literals, and also handles string concatenation [C99 5.1.1.2,
1032/// translation phase #6].
1033///
1034/// primary-expression: [C99 6.5.1]
1035/// string-literal
1036Parser::ExprResult Parser::ParseStringLiteralExpression() {
1037 assert(isTokenStringLiteral() && "Not a string literal!");
1038
1039 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
1040 // considered to be strings for concatenation purposes.
Chris Lattnerd2177732007-07-20 16:59:19 +00001041 llvm::SmallVector<Token, 4> StringToks;
Reid Spencer5f016e22007-07-11 17:01:13 +00001042
1043 do {
1044 StringToks.push_back(Tok);
1045 ConsumeStringToken();
1046 } while (isTokenStringLiteral());
1047
1048 // Pass the set of string tokens, ready for concatenation, to the actions.
Steve Narofff69936d2007-09-16 03:34:24 +00001049 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size());
Reid Spencer5f016e22007-07-11 17:01:13 +00001050}
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +00001051
1052/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1053///
1054/// argument-expression-list:
1055/// assignment-expression
1056/// argument-expression-list , assignment-expression
1057///
1058/// [C++] expression-list:
1059/// [C++] assignment-expression
1060/// [C++] expression-list , assignment-expression
1061///
1062bool Parser::ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs) {
1063 while (1) {
1064 ExprResult Expr = ParseAssignmentExpression();
1065 if (Expr.isInvalid)
1066 return true;
Argyrios Kyrtzidis4fdc1ca2008-08-18 22:49:40 +00001067
1068 Exprs.push_back(Expr.Val);
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +00001069
1070 if (Tok.isNot(tok::comma))
1071 return false;
1072 // Move to the next argument, remember where the comma was.
1073 CommaLocs.push_back(ConsumeToken());
1074 }
1075}
Steve Naroff296e8d52008-08-28 19:20:44 +00001076
1077/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
Steve Naroff17dab4f2008-09-16 23:11:46 +00001078/// like ^(int x){ return x+1; }
Steve Naroff296e8d52008-08-28 19:20:44 +00001079///
1080/// block-literal:
1081/// [clang] '^' block-args[opt] compound-statement
Steve Naroff296e8d52008-08-28 19:20:44 +00001082/// [clang] block-args:
1083/// [clang] '(' parameter-list ')'
1084///
1085Parser::ExprResult Parser::ParseBlockLiteralExpression() {
1086 assert(Tok.is(tok::caret) && "block literal starts with ^");
1087 SourceLocation CaretLoc = ConsumeToken();
1088
1089 // Enter a scope to hold everything within the block. This includes the
1090 // argument decls, decls within the compound expression, etc. This also
1091 // allows determining whether a variable reference inside the block is
1092 // within or outside of the block.
1093 EnterScope(Scope::BlockScope|Scope::FnScope|Scope::BreakScope|
1094 Scope::ContinueScope|Scope::DeclScope);
Steve Naroff090276f2008-10-10 01:28:17 +00001095
1096 // Inform sema that we are starting a block.
1097 Actions.ActOnBlockStart(CaretLoc, CurScope);
Steve Naroff296e8d52008-08-28 19:20:44 +00001098
1099 // Parse the return type if present.
1100 DeclSpec DS;
1101 Declarator ParamInfo(DS, Declarator::PrototypeContext);
1102
1103 // If this block has arguments, parse them. There is no ambiguity here with
1104 // the expression case, because the expression case requires a parameter list.
1105 if (Tok.is(tok::l_paren)) {
1106 ParseParenDeclarator(ParamInfo);
1107 // Parse the pieces after the identifier as if we had "int(...)".
1108 ParamInfo.SetIdentifier(0, CaretLoc);
1109 if (ParamInfo.getInvalidType()) {
1110 // If there was an error parsing the arguments, they may have tried to use
1111 // ^(x+y) which requires an argument list. Just skip the whole block
1112 // literal.
1113 ExitScope();
1114 return true;
1115 }
1116 } else {
1117 // Otherwise, pretend we saw (void).
1118 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001119 0, 0, 0, CaretLoc));
Steve Naroff296e8d52008-08-28 19:20:44 +00001120 }
1121
1122 // Inform sema that we are starting a block.
Steve Naroff090276f2008-10-10 01:28:17 +00001123 Actions.ActOnBlockArguments(ParamInfo);
Steve Naroff296e8d52008-08-28 19:20:44 +00001124
Steve Naroff17dab4f2008-09-16 23:11:46 +00001125 ExprResult Result = true;
Steve Naroff296e8d52008-08-28 19:20:44 +00001126 if (Tok.is(tok::l_brace)) {
1127 StmtResult Stmt = ParseCompoundStatementBody();
1128 if (!Stmt.isInvalid) {
1129 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.Val, CurScope);
1130 } else {
1131 Actions.ActOnBlockError(CaretLoc, CurScope);
Steve Naroff296e8d52008-08-28 19:20:44 +00001132 }
1133 }
Steve Naroff296e8d52008-08-28 19:20:44 +00001134 ExitScope();
1135 return Result;
1136}
1137