blob: e8758e15f10eced609ebb63ded1f18d552b0c2a8 [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)
Douglas Gregoreaebc752008-11-06 23:29:22 +0000322 LHS = Actions.ActOnBinOp(CurScope, OpToken.getLocation(),
323 OpToken.getKind(), LHS.Val, RHS.Val);
Chris Lattnerd56d6b62007-08-31 05:01:50 +0000324 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 ')'
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000351/// [C++0x] 'alignof' '(' type-id ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000352/// [GNU] '&&' identifier
353///
354/// unary-operator: one of
355/// '&' '*' '+' '-' '~' '!'
356/// [GNU] '__extension__' '__real' '__imag'
357///
358/// primary-expression: [C99 6.5.1]
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +0000359/// [C99] identifier
360// [C++] id-expression
Reid Spencer5f016e22007-07-11 17:01:13 +0000361/// constant
362/// string-literal
363/// [C++] boolean-literal [C++ 2.13.5]
364/// '(' expression ')'
365/// '__func__' [C99 6.4.2.2]
366/// [GNU] '__FUNCTION__'
367/// [GNU] '__PRETTY_FUNCTION__'
368/// [GNU] '(' compound-statement ')'
369/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
370/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
371/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
372/// assign-expr ')'
373/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
Fariborz Jahanian095ffca2007-09-26 17:03:44 +0000374/// [OBJC] '[' objc-message-expr ']'
Chris Lattner5ac87ed2008-01-25 18:58:06 +0000375/// [OBJC] '@selector' '(' objc-selector-arg ')'
Fariborz Jahanian095ffca2007-09-26 17:03:44 +0000376/// [OBJC] '@protocol' '(' identifier ')'
377/// [OBJC] '@encode' '(' type-name ')'
Fariborz Jahanian0ccb27d2007-09-05 19:52:07 +0000378/// [OBJC] objc-string-literal
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000379/// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
380/// [C++] typename-specifier '(' expression-list[opt] ')' [TODO]
Reid Spencer5f016e22007-07-11 17:01:13 +0000381/// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
382/// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
383/// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
384/// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
Argyrios Kyrtzidisd7464be2008-07-16 07:23:27 +0000385/// [C++] 'this' [C++ 9.3.2]
Steve Naroff296e8d52008-08-28 19:20:44 +0000386/// [clang] '^' block-literal
Reid Spencer5f016e22007-07-11 17:01:13 +0000387///
388/// constant: [C99 6.4.4]
389/// integer-constant
390/// floating-constant
391/// enumeration-constant -> identifier
392/// character-constant
393///
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +0000394/// id-expression: [C++ 5.1]
395/// unqualified-id
396/// qualified-id [TODO]
397///
398/// unqualified-id: [C++ 5.1]
399/// identifier
400/// operator-function-id
401/// conversion-function-id [TODO]
402/// '~' class-name [TODO]
403/// template-id [TODO]
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000404///
Reid Spencer5f016e22007-07-11 17:01:13 +0000405Parser::ExprResult Parser::ParseCastExpression(bool isUnaryExpression) {
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000406 if (getLang().CPlusPlus) {
407 // Annotate typenames and C++ scope specifiers.
408 // Used only in C++; in C let the typedef name be handled as an identifier.
409 TryAnnotateTypeOrScopeToken();
410 }
411
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 ExprResult Res;
413 tok::TokenKind SavedKind = Tok.getKind();
414
415 // This handles all of cast-expression, unary-expression, postfix-expression,
416 // and primary-expression. We handle them together like this for efficiency
417 // and to simplify handling of an expression starting with a '(' token: which
418 // may be one of a parenthesized expression, cast-expression, compound literal
419 // expression, or statement expression.
420 //
421 // If the parsed tokens consist of a primary-expression, the cases below
422 // call ParsePostfixExpressionSuffix to handle the postfix expression
423 // suffixes. Cases that cannot be followed by postfix exprs should
424 // return without invoking ParsePostfixExpressionSuffix.
425 switch (SavedKind) {
426 case tok::l_paren: {
427 // If this expression is limited to being a unary-expression, the parent can
428 // not start a cast expression.
429 ParenParseOption ParenExprType =
430 isUnaryExpression ? CompoundLiteral : CastExpr;
431 TypeTy *CastTy;
432 SourceLocation LParenLoc = Tok.getLocation();
433 SourceLocation RParenLoc;
434 Res = ParseParenExpression(ParenExprType, CastTy, RParenLoc);
435 if (Res.isInvalid) return Res;
436
437 switch (ParenExprType) {
438 case SimpleExpr: break; // Nothing else to do.
439 case CompoundStmt: break; // Nothing else to do.
440 case CompoundLiteral:
441 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
442 // postfix-expression exist, parse them now.
443 break;
444 case CastExpr:
445 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. Parse
446 // the cast-expression that follows it next.
447 // TODO: For cast expression with CastTy.
448 Res = ParseCastExpression(false);
449 if (!Res.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000450 Res = Actions.ActOnCastExpr(LParenLoc, CastTy, RParenLoc, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 return Res;
452 }
453
454 // These can be followed by postfix-expr pieces.
455 return ParsePostfixExpressionSuffix(Res);
456 }
457
458 // primary-expression
459 case tok::numeric_constant:
460 // constant: integer-constant
461 // constant: floating-constant
462
Steve Narofff69936d2007-09-16 03:34:24 +0000463 Res = Actions.ActOnNumericConstant(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 ConsumeToken();
465
466 // These can be followed by postfix-expr pieces.
467 return ParsePostfixExpressionSuffix(Res);
468
469 case tok::kw_true:
470 case tok::kw_false:
471 return ParseCXXBoolLiteral();
472
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000473 case tok::identifier: { // primary-expression: identifier
474 // unqualified-id: identifier
475 // constant: enumeration-constant
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000476
Reid Spencer5f016e22007-07-11 17:01:13 +0000477 // Consume the identifier so that we can see if it is followed by a '('.
478 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
479 // need to know whether or not this identifier is a function designator or
480 // not.
481 IdentifierInfo &II = *Tok.getIdentifierInfo();
482 SourceLocation L = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000483 Res = Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren));
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 // These can be followed by postfix-expr pieces.
485 return ParsePostfixExpressionSuffix(Res);
486 }
487 case tok::char_constant: // constant: character-constant
Steve Narofff69936d2007-09-16 03:34:24 +0000488 Res = Actions.ActOnCharacterConstant(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000489 ConsumeToken();
490 // These can be followed by postfix-expr pieces.
491 return ParsePostfixExpressionSuffix(Res);
492 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
493 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
494 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Chris Lattnerd9f69102008-08-10 01:53:14 +0000495 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
Reid Spencer5f016e22007-07-11 17:01:13 +0000496 ConsumeToken();
497 // These can be followed by postfix-expr pieces.
498 return ParsePostfixExpressionSuffix(Res);
499 case tok::string_literal: // primary-expression: string-literal
500 case tok::wide_string_literal:
501 Res = ParseStringLiteralExpression();
502 if (Res.isInvalid) return Res;
503 // This can be followed by postfix-expr pieces (e.g. "foo"[1]).
504 return ParsePostfixExpressionSuffix(Res);
505 case tok::kw___builtin_va_arg:
506 case tok::kw___builtin_offsetof:
507 case tok::kw___builtin_choose_expr:
Nate Begemane2ce1d92008-01-17 17:46:27 +0000508 case tok::kw___builtin_overload:
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 case tok::kw___builtin_types_compatible_p:
510 return ParseBuiltinPrimaryExpression();
511 case tok::plusplus: // unary-expression: '++' unary-expression
512 case tok::minusminus: { // unary-expression: '--' unary-expression
513 SourceLocation SavedLoc = ConsumeToken();
514 Res = ParseCastExpression(true);
515 if (!Res.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000516 Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000517 return Res;
518 }
519 case tok::amp: // unary-expression: '&' cast-expression
520 case tok::star: // unary-expression: '*' cast-expression
521 case tok::plus: // unary-expression: '+' cast-expression
522 case tok::minus: // unary-expression: '-' cast-expression
523 case tok::tilde: // unary-expression: '~' cast-expression
524 case tok::exclaim: // unary-expression: '!' cast-expression
525 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
Chris Lattner35080842008-02-02 20:20:10 +0000526 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
Reid Spencer5f016e22007-07-11 17:01:13 +0000527 SourceLocation SavedLoc = ConsumeToken();
528 Res = ParseCastExpression(false);
529 if (!Res.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000530 Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000531 return Res;
Chris Lattner35080842008-02-02 20:20:10 +0000532 }
533
534 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
535 // __extension__ silences extension warnings in the subexpression.
Chris Lattnerc46d1a12008-10-20 06:45:43 +0000536 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Chris Lattner35080842008-02-02 20:20:10 +0000537 SourceLocation SavedLoc = ConsumeToken();
538 Res = ParseCastExpression(false);
539 if (!Res.isInvalid)
540 Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
Chris Lattner35080842008-02-02 20:20:10 +0000541 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000542 }
543 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
544 // unary-expression: 'sizeof' '(' type-name ')'
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000545 case tok::kw_alignof:
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
547 // unary-expression: '__alignof' '(' type-name ')'
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000548 // unary-expression: 'alignof' '(' type-id ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000549 return ParseSizeofAlignofExpression();
550 case tok::ampamp: { // unary-expression: '&&' identifier
551 SourceLocation AmpAmpLoc = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000552 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 Diag(Tok, diag::err_expected_ident);
554 return ExprResult(true);
555 }
556
557 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
Steve Naroff1b273c42007-09-16 14:56:35 +0000558 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 Tok.getIdentifierInfo());
560 ConsumeToken();
561 return Res;
562 }
563 case tok::kw_const_cast:
564 case tok::kw_dynamic_cast:
565 case tok::kw_reinterpret_cast:
566 case tok::kw_static_cast:
Argyrios Kyrtzidisb348b812008-08-16 19:45:32 +0000567 Res = ParseCXXCasts();
568 // These can be followed by postfix-expr pieces.
569 return ParsePostfixExpressionSuffix(Res);
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000570 case tok::kw_this:
Argyrios Kyrtzidis289d7732008-08-16 19:34:46 +0000571 Res = ParseCXXThis();
572 // This can be followed by postfix-expr pieces.
573 return ParsePostfixExpressionSuffix(Res);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000574
575 case tok::kw_char:
576 case tok::kw_wchar_t:
577 case tok::kw_bool:
578 case tok::kw_short:
579 case tok::kw_int:
580 case tok::kw_long:
581 case tok::kw_signed:
582 case tok::kw_unsigned:
583 case tok::kw_float:
584 case tok::kw_double:
585 case tok::kw_void:
586 case tok::kw_typeof: {
587 if (!getLang().CPlusPlus)
588 goto UnhandledToken;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000589 case tok::annot_qualtypename:
590 assert(getLang().CPlusPlus && "Expected C++");
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000591 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
592 //
593 DeclSpec DS;
594 ParseCXXSimpleTypeSpecifier(DS);
595 if (Tok.isNot(tok::l_paren))
596 return Diag(Tok.getLocation(), diag::err_expected_lparen_after_type,
597 DS.getSourceRange());
598
599 Res = ParseCXXTypeConstructExpression(DS);
600 // This can be followed by postfix-expr pieces.
601 return ParsePostfixExpressionSuffix(Res);
602 }
603
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000604 case tok::annot_cxxscope: // [C++] id-expression: qualified-id
605 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
606 // template-id
607 Res = ParseCXXIdExpression();
608 return ParsePostfixExpressionSuffix(Res);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +0000609
Chris Lattnerc97c2042007-10-03 22:03:06 +0000610 case tok::at: {
611 SourceLocation AtLoc = ConsumeToken();
Steve Naroffa642beb2007-10-15 20:55:58 +0000612 return ParseObjCAtExpression(AtLoc);
Chris Lattnerc97c2042007-10-03 22:03:06 +0000613 }
Fariborz Jahanian0ccb27d2007-09-05 19:52:07 +0000614 case tok::l_square:
Steve Naroffa642beb2007-10-15 20:55:58 +0000615 // These can be followed by postfix-expr pieces.
Chris Lattner039a6422008-05-09 05:28:21 +0000616 if (getLang().ObjC1)
617 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression());
618 // FALL THROUGH.
Steve Naroff296e8d52008-08-28 19:20:44 +0000619 case tok::caret:
620 if (getLang().Blocks)
621 return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression());
622 Diag(Tok, diag::err_expected_expression);
623 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000624 default:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000625 UnhandledToken:
Reid Spencer5f016e22007-07-11 17:01:13 +0000626 Diag(Tok, diag::err_expected_expression);
627 return ExprResult(true);
628 }
629
630 // unreachable.
631 abort();
632}
633
634/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
635/// is parsed, this method parses any suffixes that apply.
636///
637/// postfix-expression: [C99 6.5.2]
638/// primary-expression
639/// postfix-expression '[' expression ']'
640/// postfix-expression '(' argument-expression-list[opt] ')'
641/// postfix-expression '.' identifier
642/// postfix-expression '->' identifier
643/// postfix-expression '++'
644/// postfix-expression '--'
645/// '(' type-name ')' '{' initializer-list '}'
646/// '(' type-name ')' '{' initializer-list ',' '}'
647///
648/// argument-expression-list: [C99 6.5.2]
649/// argument-expression
650/// argument-expression-list ',' assignment-expression
651///
652Parser::ExprResult Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
653
654 // Now that the primary-expression piece of the postfix-expression has been
655 // parsed, see if there are any postfix-expression pieces here.
656 SourceLocation Loc;
657 while (1) {
658 switch (Tok.getKind()) {
659 default: // Not a postfix-expression suffix.
660 return LHS;
661 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
662 Loc = ConsumeBracket();
663 ExprResult Idx = ParseExpression();
664
665 SourceLocation RLoc = Tok.getLocation();
666
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000667 if (!LHS.isInvalid && !Idx.isInvalid && Tok.is(tok::r_square))
Steve Narofff69936d2007-09-16 03:34:24 +0000668 LHS = Actions.ActOnArraySubscriptExpr(LHS.Val, Loc, Idx.Val, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000669 else
670 LHS = ExprResult(true);
671
672 // Match the ']'.
673 MatchRHSPunctuation(tok::r_square, Loc);
674 break;
675 }
676
677 case tok::l_paren: { // p-e: p-e '(' argument-expression-list[opt] ')'
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +0000678 ExprListTy ArgExprs;
679 CommaLocsTy CommaLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000680
681 Loc = ConsumeParen();
682
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000683 if (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +0000684 if (ParseExpressionList(ArgExprs, CommaLocs)) {
685 SkipUntil(tok::r_paren);
686 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000687 }
688 }
689
690 // Match the ')'.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000691 if (!LHS.isInvalid && Tok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000692 assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&&
693 "Unexpected number of commas!");
Steve Narofff69936d2007-09-16 03:34:24 +0000694 LHS = Actions.ActOnCallExpr(LHS.Val, Loc, &ArgExprs[0], ArgExprs.size(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000695 &CommaLocs[0], Tok.getLocation());
696 }
697
Chris Lattner2ff54262007-07-21 05:18:12 +0000698 MatchRHSPunctuation(tok::r_paren, Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 break;
700 }
701 case tok::arrow: // postfix-expression: p-e '->' identifier
702 case tok::period: { // postfix-expression: p-e '.' identifier
703 tok::TokenKind OpKind = Tok.getKind();
704 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
705
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000706 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 Diag(Tok, diag::err_expected_ident);
708 return ExprResult(true);
709 }
710
711 if (!LHS.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000712 LHS = Actions.ActOnMemberReferenceExpr(LHS.Val, OpLoc, OpKind,
Reid Spencer5f016e22007-07-11 17:01:13 +0000713 Tok.getLocation(),
714 *Tok.getIdentifierInfo());
715 ConsumeToken();
716 break;
717 }
718 case tok::plusplus: // postfix-expression: postfix-expression '++'
719 case tok::minusminus: // postfix-expression: postfix-expression '--'
720 if (!LHS.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000721 LHS = Actions.ActOnPostfixUnaryOp(Tok.getLocation(), Tok.getKind(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000722 LHS.Val);
723 ConsumeToken();
724 break;
725 }
726 }
727}
728
729
730/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression.
731/// unary-expression: [C99 6.5.3]
732/// 'sizeof' unary-expression
733/// 'sizeof' '(' type-name ')'
734/// [GNU] '__alignof' unary-expression
735/// [GNU] '__alignof' '(' type-name ')'
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000736/// [C++0x] 'alignof' '(' type-id ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000737Parser::ExprResult Parser::ParseSizeofAlignofExpression() {
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000738 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof)
739 || Tok.is(tok::kw_alignof)) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000740 "Not a sizeof/alignof expression!");
Chris Lattnerd2177732007-07-20 16:59:19 +0000741 Token OpTok = Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000742 ConsumeToken();
743
744 // If the operand doesn't start with an '(', it must be an expression.
745 ExprResult Operand;
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000746 if (Tok.isNot(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000747 Operand = ParseCastExpression(true);
748 } else {
749 // If it starts with a '(', we know that it is either a parenthesized
750 // type-name, or it is a unary-expression that starts with a compound
751 // literal, or starts with a primary-expression that is a parenthesized
752 // expression.
753 ParenParseOption ExprType = CastExpr;
754 TypeTy *CastTy;
755 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
756 Operand = ParseParenExpression(ExprType, CastTy, RParenLoc);
757
758 // If ParseParenExpression parsed a '(typename)' sequence only, the this is
759 // sizeof/alignof a type. Otherwise, it is sizeof/alignof an expression.
Chris Lattner4c1a2a92007-11-13 20:50:37 +0000760 if (ExprType == CastExpr)
Steve Narofff69936d2007-09-16 03:34:24 +0000761 return Actions.ActOnSizeOfAlignOfTypeExpr(OpTok.getLocation(),
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000762 OpTok.is(tok::kw_sizeof),
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 LParenLoc, CastTy, RParenLoc);
Chris Lattner4c1a2a92007-11-13 20:50:37 +0000764
765 // If this is a parenthesized expression, it is the start of a
766 // unary-expression, but doesn't include any postfix pieces. Parse these
767 // now if present.
768 Operand = ParsePostfixExpressionSuffix(Operand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000769 }
770
771 // If we get here, the operand to the sizeof/alignof was an expresion.
772 if (!Operand.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000773 Operand = Actions.ActOnUnaryOp(OpTok.getLocation(), OpTok.getKind(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000774 Operand.Val);
775 return Operand;
776}
777
778/// ParseBuiltinPrimaryExpression
779///
780/// primary-expression: [C99 6.5.1]
781/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
782/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
783/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
784/// assign-expr ')'
785/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
Nate Begemane2ce1d92008-01-17 17:46:27 +0000786/// [CLANG] '__builtin_overload' '(' expr (',' expr)* ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000787///
788/// [GNU] offsetof-member-designator:
789/// [GNU] identifier
790/// [GNU] offsetof-member-designator '.' identifier
791/// [GNU] offsetof-member-designator '[' expression ']'
792///
793Parser::ExprResult Parser::ParseBuiltinPrimaryExpression() {
794 ExprResult Res(false);
795 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
796
797 tok::TokenKind T = Tok.getKind();
798 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
799
800 // All of these start with an open paren.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000801 if (Tok.isNot(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000802 Diag(Tok, diag::err_expected_lparen_after, BuiltinII->getName());
803 return ExprResult(true);
804 }
805
806 SourceLocation LParenLoc = ConsumeParen();
807 // TODO: Build AST.
808
809 switch (T) {
810 default: assert(0 && "Not a builtin primary expression!");
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000811 case tok::kw___builtin_va_arg: {
812 ExprResult Expr = ParseAssignmentExpression();
813 if (Expr.isInvalid) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000814 SkipUntil(tok::r_paren);
Eli Friedman09762782008-08-20 22:07:34 +0000815 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000816 }
817
818 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
819 return ExprResult(true);
820
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000821 TypeTy *Ty = ParseTypeName();
Chris Lattner6eb21092007-08-30 15:52:49 +0000822
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000823 if (Tok.isNot(tok::r_paren)) {
824 Diag(Tok, diag::err_expected_rparen);
825 return ExprResult(true);
826 }
827 Res = Actions.ActOnVAArg(StartLoc, Expr.Val, Ty, ConsumeParen());
Reid Spencer5f016e22007-07-11 17:01:13 +0000828 break;
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000829 }
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000830 case tok::kw___builtin_offsetof: {
Chris Lattner9fddf0a2007-08-30 17:08:45 +0000831 SourceLocation TypeLoc = Tok.getLocation();
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000832 TypeTy *Ty = ParseTypeName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000833
834 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
835 return ExprResult(true);
836
837 // We must have at least one identifier here.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000838 if (Tok.isNot(tok::identifier)) {
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000839 Diag(Tok, diag::err_expected_ident);
840 SkipUntil(tok::r_paren);
841 return true;
842 }
843
844 // Keep track of the various subcomponents we see.
845 llvm::SmallVector<Action::OffsetOfComponent, 4> Comps;
846
847 Comps.push_back(Action::OffsetOfComponent());
848 Comps.back().isBrackets = false;
849 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
850 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
Reid Spencer5f016e22007-07-11 17:01:13 +0000851
852 while (1) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000853 if (Tok.is(tok::period)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000854 // offsetof-member-designator: offsetof-member-designator '.' identifier
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000855 Comps.push_back(Action::OffsetOfComponent());
856 Comps.back().isBrackets = false;
857 Comps.back().LocStart = ConsumeToken();
Reid Spencer5f016e22007-07-11 17:01:13 +0000858
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000859 if (Tok.isNot(tok::identifier)) {
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000860 Diag(Tok, diag::err_expected_ident);
861 SkipUntil(tok::r_paren);
862 return true;
863 }
864 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
865 Comps.back().LocEnd = ConsumeToken();
866
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000867 } else if (Tok.is(tok::l_square)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000868 // offsetof-member-designator: offsetof-member-design '[' expression ']'
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000869 Comps.push_back(Action::OffsetOfComponent());
870 Comps.back().isBrackets = true;
871 Comps.back().LocStart = ConsumeBracket();
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 Res = ParseExpression();
873 if (Res.isInvalid) {
874 SkipUntil(tok::r_paren);
875 return Res;
876 }
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000877 Comps.back().U.E = Res.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000878
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000879 Comps.back().LocEnd =
880 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart);
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000881 } else if (Tok.is(tok::r_paren)) {
Steve Naroff1b273c42007-09-16 14:56:35 +0000882 Res = Actions.ActOnBuiltinOffsetOf(StartLoc, TypeLoc, Ty, &Comps[0],
Chris Lattner6eb21092007-08-30 15:52:49 +0000883 Comps.size(), ConsumeParen());
884 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000885 } else {
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000886 // Error occurred.
887 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000888 }
889 }
890 break;
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000891 }
Steve Naroffd04fdd52007-08-03 21:21:27 +0000892 case tok::kw___builtin_choose_expr: {
893 ExprResult Cond = ParseAssignmentExpression();
894 if (Cond.isInvalid) {
895 SkipUntil(tok::r_paren);
896 return Cond;
897 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000898 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
899 return ExprResult(true);
900
Steve Naroffd04fdd52007-08-03 21:21:27 +0000901 ExprResult Expr1 = ParseAssignmentExpression();
902 if (Expr1.isInvalid) {
903 SkipUntil(tok::r_paren);
904 return Expr1;
905 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000906 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
907 return ExprResult(true);
908
Steve Naroffd04fdd52007-08-03 21:21:27 +0000909 ExprResult Expr2 = ParseAssignmentExpression();
910 if (Expr2.isInvalid) {
911 SkipUntil(tok::r_paren);
912 return Expr2;
913 }
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000914 if (Tok.isNot(tok::r_paren)) {
Steve Naroffd04fdd52007-08-03 21:21:27 +0000915 Diag(Tok, diag::err_expected_rparen);
916 return ExprResult(true);
917 }
Steve Naroff1b273c42007-09-16 14:56:35 +0000918 Res = Actions.ActOnChooseExpr(StartLoc, Cond.Val, Expr1.Val, Expr2.Val,
Chris Lattner6eb21092007-08-30 15:52:49 +0000919 ConsumeParen());
920 break;
Steve Naroffd04fdd52007-08-03 21:21:27 +0000921 }
Nate Begemane2ce1d92008-01-17 17:46:27 +0000922 case tok::kw___builtin_overload: {
923 llvm::SmallVector<ExprTy*, 8> ArgExprs;
924 llvm::SmallVector<SourceLocation, 8> CommaLocs;
925
926 // For each iteration through the loop look for assign-expr followed by a
927 // comma. If there is no comma, break and attempt to match r-paren.
928 if (Tok.isNot(tok::r_paren)) {
929 while (1) {
930 ExprResult ArgExpr = ParseAssignmentExpression();
931 if (ArgExpr.isInvalid) {
932 SkipUntil(tok::r_paren);
933 return ExprResult(true);
934 } else
935 ArgExprs.push_back(ArgExpr.Val);
936
937 if (Tok.isNot(tok::comma))
938 break;
939 // Move to the next argument, remember where the comma was.
940 CommaLocs.push_back(ConsumeToken());
941 }
942 }
943
944 // Attempt to consume the r-paren
945 if (Tok.isNot(tok::r_paren)) {
946 Diag(Tok, diag::err_expected_rparen);
947 SkipUntil(tok::r_paren);
948 return ExprResult(true);
949 }
Nate Begemane2ce1d92008-01-17 17:46:27 +0000950 Res = Actions.ActOnOverloadExpr(&ArgExprs[0], ArgExprs.size(),
951 &CommaLocs[0], StartLoc, ConsumeParen());
952 break;
953 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000954 case tok::kw___builtin_types_compatible_p:
Steve Naroff363bcff2007-08-01 23:45:51 +0000955 TypeTy *Ty1 = ParseTypeName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000956
957 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
958 return ExprResult(true);
959
Steve Naroff363bcff2007-08-01 23:45:51 +0000960 TypeTy *Ty2 = ParseTypeName();
961
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000962 if (Tok.isNot(tok::r_paren)) {
Steve Naroff363bcff2007-08-01 23:45:51 +0000963 Diag(Tok, diag::err_expected_rparen);
964 return ExprResult(true);
965 }
Steve Naroff1b273c42007-09-16 14:56:35 +0000966 Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1, Ty2, ConsumeParen());
Chris Lattner6eb21092007-08-30 15:52:49 +0000967 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000968 }
969
Reid Spencer5f016e22007-07-11 17:01:13 +0000970 // These can be followed by postfix-expr pieces because they are
971 // primary-expressions.
972 return ParsePostfixExpressionSuffix(Res);
973}
974
975/// ParseParenExpression - This parses the unit that starts with a '(' token,
976/// based on what is allowed by ExprType. The actual thing parsed is returned
977/// in ExprType.
978///
979/// primary-expression: [C99 6.5.1]
980/// '(' expression ')'
981/// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
982/// postfix-expression: [C99 6.5.2]
983/// '(' type-name ')' '{' initializer-list '}'
984/// '(' type-name ')' '{' initializer-list ',' '}'
985/// cast-expression: [C99 6.5.4]
986/// '(' type-name ')' cast-expression
987///
988Parser::ExprResult Parser::ParseParenExpression(ParenParseOption &ExprType,
989 TypeTy *&CastTy,
990 SourceLocation &RParenLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000991 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000992 SourceLocation OpenLoc = ConsumeParen();
Chris Lattnerab18c4c2007-07-24 16:58:17 +0000993 ExprResult Result(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000994 CastTy = 0;
995
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000996 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000997 Diag(Tok, diag::ext_gnu_statement_expr);
Chris Lattner98414c12007-08-31 21:49:55 +0000998 Parser::StmtResult Stmt = ParseCompoundStatement(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000999 ExprType = CompoundStmt;
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001000
1001 // If the substmt parsed correctly, build the AST node.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001002 if (!Stmt.isInvalid && Tok.is(tok::r_paren))
Steve Naroff1b273c42007-09-16 14:56:35 +00001003 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.Val, Tok.getLocation());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001004
Argyrios Kyrtzidis78c8d802008-10-05 19:56:22 +00001005 } else if (ExprType >= CompoundLiteral && isTypeIdInParens()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001006 // Otherwise, this is a compound literal expression or cast expression.
1007 TypeTy *Ty = ParseTypeName();
1008
1009 // Match the ')'.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001010 if (Tok.is(tok::r_paren))
Reid Spencer5f016e22007-07-11 17:01:13 +00001011 RParenLoc = ConsumeParen();
1012 else
1013 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1014
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001015 if (Tok.is(tok::l_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001016 if (!getLang().C99) // Compound literals don't exist in C90.
1017 Diag(OpenLoc, diag::ext_c99_compound_literal);
1018 Result = ParseInitializer();
1019 ExprType = CompoundLiteral;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001020 if (!Result.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +00001021 return Actions.ActOnCompoundLiteral(OpenLoc, Ty, RParenLoc, Result.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +00001022 } else if (ExprType == CastExpr) {
1023 // Note that this doesn't parse the subsequence cast-expression, it just
1024 // returns the parsed type to the callee.
1025 ExprType = CastExpr;
1026 CastTy = Ty;
1027 return ExprResult(false);
1028 } else {
1029 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
1030 return ExprResult(true);
1031 }
1032 return Result;
1033 } else {
1034 Result = ParseExpression();
1035 ExprType = SimpleExpr;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001036 if (!Result.isInvalid && Tok.is(tok::r_paren))
Steve Narofff69936d2007-09-16 03:34:24 +00001037 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +00001038 }
1039
1040 // Match the ')'.
1041 if (Result.isInvalid)
1042 SkipUntil(tok::r_paren);
1043 else {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001044 if (Tok.is(tok::r_paren))
Reid Spencer5f016e22007-07-11 17:01:13 +00001045 RParenLoc = ConsumeParen();
1046 else
1047 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1048 }
1049
1050 return Result;
1051}
1052
1053/// ParseStringLiteralExpression - This handles the various token types that
1054/// form string literals, and also handles string concatenation [C99 5.1.1.2,
1055/// translation phase #6].
1056///
1057/// primary-expression: [C99 6.5.1]
1058/// string-literal
1059Parser::ExprResult Parser::ParseStringLiteralExpression() {
1060 assert(isTokenStringLiteral() && "Not a string literal!");
1061
1062 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
1063 // considered to be strings for concatenation purposes.
Chris Lattnerd2177732007-07-20 16:59:19 +00001064 llvm::SmallVector<Token, 4> StringToks;
Reid Spencer5f016e22007-07-11 17:01:13 +00001065
1066 do {
1067 StringToks.push_back(Tok);
1068 ConsumeStringToken();
1069 } while (isTokenStringLiteral());
1070
1071 // Pass the set of string tokens, ready for concatenation, to the actions.
Steve Narofff69936d2007-09-16 03:34:24 +00001072 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size());
Reid Spencer5f016e22007-07-11 17:01:13 +00001073}
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +00001074
1075/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1076///
1077/// argument-expression-list:
1078/// assignment-expression
1079/// argument-expression-list , assignment-expression
1080///
1081/// [C++] expression-list:
1082/// [C++] assignment-expression
1083/// [C++] expression-list , assignment-expression
1084///
1085bool Parser::ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs) {
1086 while (1) {
1087 ExprResult Expr = ParseAssignmentExpression();
1088 if (Expr.isInvalid)
1089 return true;
Argyrios Kyrtzidis4fdc1ca2008-08-18 22:49:40 +00001090
1091 Exprs.push_back(Expr.Val);
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +00001092
1093 if (Tok.isNot(tok::comma))
1094 return false;
1095 // Move to the next argument, remember where the comma was.
1096 CommaLocs.push_back(ConsumeToken());
1097 }
1098}
Steve Naroff296e8d52008-08-28 19:20:44 +00001099
1100/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
Steve Naroff17dab4f2008-09-16 23:11:46 +00001101/// like ^(int x){ return x+1; }
Steve Naroff296e8d52008-08-28 19:20:44 +00001102///
1103/// block-literal:
1104/// [clang] '^' block-args[opt] compound-statement
Steve Naroff296e8d52008-08-28 19:20:44 +00001105/// [clang] block-args:
1106/// [clang] '(' parameter-list ')'
1107///
1108Parser::ExprResult Parser::ParseBlockLiteralExpression() {
1109 assert(Tok.is(tok::caret) && "block literal starts with ^");
1110 SourceLocation CaretLoc = ConsumeToken();
1111
1112 // Enter a scope to hold everything within the block. This includes the
1113 // argument decls, decls within the compound expression, etc. This also
1114 // allows determining whether a variable reference inside the block is
1115 // within or outside of the block.
1116 EnterScope(Scope::BlockScope|Scope::FnScope|Scope::BreakScope|
1117 Scope::ContinueScope|Scope::DeclScope);
Steve Naroff090276f2008-10-10 01:28:17 +00001118
1119 // Inform sema that we are starting a block.
1120 Actions.ActOnBlockStart(CaretLoc, CurScope);
Steve Naroff296e8d52008-08-28 19:20:44 +00001121
1122 // Parse the return type if present.
1123 DeclSpec DS;
1124 Declarator ParamInfo(DS, Declarator::PrototypeContext);
1125
1126 // If this block has arguments, parse them. There is no ambiguity here with
1127 // the expression case, because the expression case requires a parameter list.
1128 if (Tok.is(tok::l_paren)) {
1129 ParseParenDeclarator(ParamInfo);
1130 // Parse the pieces after the identifier as if we had "int(...)".
1131 ParamInfo.SetIdentifier(0, CaretLoc);
1132 if (ParamInfo.getInvalidType()) {
1133 // If there was an error parsing the arguments, they may have tried to use
1134 // ^(x+y) which requires an argument list. Just skip the whole block
1135 // literal.
1136 ExitScope();
1137 return true;
1138 }
1139 } else {
1140 // Otherwise, pretend we saw (void).
1141 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001142 0, 0, 0, CaretLoc));
Steve Naroff296e8d52008-08-28 19:20:44 +00001143 }
1144
1145 // Inform sema that we are starting a block.
Steve Naroff090276f2008-10-10 01:28:17 +00001146 Actions.ActOnBlockArguments(ParamInfo);
Steve Naroff296e8d52008-08-28 19:20:44 +00001147
Steve Naroff17dab4f2008-09-16 23:11:46 +00001148 ExprResult Result = true;
Steve Naroff296e8d52008-08-28 19:20:44 +00001149 if (Tok.is(tok::l_brace)) {
1150 StmtResult Stmt = ParseCompoundStatementBody();
1151 if (!Stmt.isInvalid) {
1152 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.Val, CurScope);
1153 } else {
1154 Actions.ActOnBlockError(CaretLoc, CurScope);
Steve Naroff296e8d52008-08-28 19:20:44 +00001155 }
1156 }
Steve Naroff296e8d52008-08-28 19:20:44 +00001157 ExitScope();
1158 return Result;
1159}
1160