blob: 5f36f0bb272cf0f4ce0cecb87931d356719e2ed1 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expression parsing implementation. Expressions in
11// C99 basically consist of a bunch of binary operators with unary operators and
12// other random stuff at the leaves.
13//
14// In the C99 grammar, these unary operators bind tightest and are represented
15// as the 'cast-expression' production. Everything else is either a binary
16// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
17// handled by ParseCastExpression, the higher level pieces are handled by
18// ParseBinaryExpression.
19//
20//===----------------------------------------------------------------------===//
21
22#include "clang/Parse/Parser.h"
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +000023#include "clang/Parse/DeclSpec.h"
Steve Narofffd5b19d2008-08-28 19:20:44 +000024#include "clang/Parse/Scope.h"
Chris Lattnerdaa5c002008-10-20 06:45:43 +000025#include "ExtensionRAIIObject.h"
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnera7447ba2008-02-26 00:51:44 +0000162/// [C++] throw-expression [C++ 15]
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnera7447ba2008-02-26 00:51:44 +0000172 if (Tok.is(tok::kw_throw))
173 return ParseThrowExpression();
174
Chris Lattner4b009652007-07-25 00:24:17 +0000175 ExprResult LHS = ParseCastExpression(false);
176 if (LHS.isInvalid) return LHS;
177
178 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
179}
180
Fariborz Jahanian64b864e2007-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 Lattnerb82d6ef2007-10-03 22:03:06 +0000183/// routine is necessary to disambiguate @try-statement from,
184/// for example, @encode-expression.
Fariborz Jahanian64b864e2007-09-19 19:14:32 +0000185///
Fariborz Jahanian37c9c612007-10-04 20:19:06 +0000186Parser::ExprResult Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
Steve Narofffb9dd752007-10-15 20:55:58 +0000187 ExprResult LHS = ParseObjCAtExpression(AtLoc);
Fariborz Jahanian64b864e2007-09-19 19:14:32 +0000188 if (LHS.isInvalid) return LHS;
189
190 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
191}
192
Chris Lattner4b009652007-07-25 00:24:17 +0000193/// ParseAssignmentExpression - Parse an expr that doesn't include commas.
194///
195Parser::ExprResult Parser::ParseAssignmentExpression() {
Chris Lattnera7447ba2008-02-26 00:51:44 +0000196 if (Tok.is(tok::kw_throw))
197 return ParseThrowExpression();
198
Chris Lattner4b009652007-07-25 00:24:17 +0000199 ExprResult LHS = ParseCastExpression(false);
200 if (LHS.isInvalid) return LHS;
201
202 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
203}
204
Chris Lattnerbfcf4772008-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,
Steve Naroffc64a53d2008-11-19 15:54:23 +0000215 SourceLocation NameLoc,
Chris Lattnerbfcf4772008-06-02 21:31:07 +0000216 IdentifierInfo *ReceiverName,
217 ExprTy *ReceiverExpr) {
Steve Naroffc64a53d2008-11-19 15:54:23 +0000218 ExprResult R = ParseObjCMessageExpressionBody(LBracLoc, NameLoc, ReceiverName,
Chris Lattnerbfcf4772008-06-02 21:31:07 +0000219 ReceiverExpr);
220 if (R.isInvalid) return R;
221 R = ParsePostfixExpressionSuffix(R);
222 if (R.isInvalid) return R;
223 return ParseRHSOfBinaryExpression(R, 2);
224}
225
226
Chris Lattner4b009652007-07-25 00:24:17 +0000227Parser::ExprResult Parser::ParseConstantExpression() {
228 ExprResult LHS = ParseCastExpression(false);
229 if (LHS.isInvalid) return LHS;
230
Chris Lattner4b009652007-07-25 00:24:17 +0000231 return ParseRHSOfBinaryExpression(LHS, prec::Conditional);
232}
233
Chris Lattner4b009652007-07-25 00:24:17 +0000234/// ParseRHSOfBinaryExpression - Parse a binary expression that starts with
235/// LHS and has a precedence of at least MinPrec.
236Parser::ExprResult
237Parser::ParseRHSOfBinaryExpression(ExprResult LHS, unsigned MinPrec) {
238 unsigned NextTokPrec = getBinOpPrecedence(Tok.getKind());
239 SourceLocation ColonLoc;
240
241 while (1) {
242 // If this token has a lower precedence than we are allowed to parse (e.g.
243 // because we are called recursively, or because the token is not a binop),
244 // then we are done!
245 if (NextTokPrec < MinPrec)
246 return LHS;
247
248 // Consume the operator, saving the operator token for error reporting.
249 Token OpToken = Tok;
250 ConsumeToken();
251
252 // Special case handling for the ternary operator.
253 ExprResult TernaryMiddle(true);
254 if (NextTokPrec == prec::Conditional) {
Chris Lattner4d7d2342007-10-09 17:41:39 +0000255 if (Tok.isNot(tok::colon)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000256 // Handle this production specially:
257 // logical-OR-expression '?' expression ':' conditional-expression
258 // In particular, the RHS of the '?' is 'expression', not
259 // 'logical-OR-expression' as we might expect.
260 TernaryMiddle = ParseExpression();
Chris Lattner214cbaf2007-08-31 04:58:34 +0000261 if (TernaryMiddle.isInvalid) {
262 Actions.DeleteExpr(LHS.Val);
263 return TernaryMiddle;
264 }
Chris Lattner4b009652007-07-25 00:24:17 +0000265 } else {
266 // Special case handling of "X ? Y : Z" where Y is empty:
267 // logical-OR-expression '?' ':' conditional-expression [GNU]
268 TernaryMiddle = ExprResult(false);
269 Diag(Tok, diag::ext_gnu_conditional_expr);
270 }
271
Chris Lattner4d7d2342007-10-09 17:41:39 +0000272 if (Tok.isNot(tok::colon)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000273 Diag(Tok, diag::err_expected_colon);
Chris Lattnerf006a222008-11-18 07:48:38 +0000274 Diag(OpToken, diag::err_matching) << "?";
Chris Lattner214cbaf2007-08-31 04:58:34 +0000275 Actions.DeleteExpr(LHS.Val);
276 Actions.DeleteExpr(TernaryMiddle.Val);
Chris Lattner4b009652007-07-25 00:24:17 +0000277 return ExprResult(true);
278 }
279
280 // Eat the colon.
281 ColonLoc = ConsumeToken();
282 }
283
284 // Parse another leaf here for the RHS of the operator.
285 ExprResult RHS = ParseCastExpression(false);
Chris Lattner214cbaf2007-08-31 04:58:34 +0000286 if (RHS.isInvalid) {
287 Actions.DeleteExpr(LHS.Val);
288 Actions.DeleteExpr(TernaryMiddle.Val);
289 return RHS;
290 }
Chris Lattner4b009652007-07-25 00:24:17 +0000291
292 // Remember the precedence of this operator and get the precedence of the
293 // operator immediately to the right of the RHS.
294 unsigned ThisPrec = NextTokPrec;
295 NextTokPrec = getBinOpPrecedence(Tok.getKind());
296
297 // Assignment and conditional expressions are right-associative.
Chris Lattner464c7f62007-12-18 06:06:23 +0000298 bool isRightAssoc = ThisPrec == prec::Conditional ||
299 ThisPrec == prec::Assignment;
Chris Lattner4b009652007-07-25 00:24:17 +0000300
301 // Get the precedence of the operator to the right of the RHS. If it binds
302 // more tightly with RHS than we do, evaluate it completely first.
303 if (ThisPrec < NextTokPrec ||
304 (ThisPrec == NextTokPrec && isRightAssoc)) {
305 // If this is left-associative, only parse things on the RHS that bind
306 // more tightly than the current operator. If it is left-associative, it
307 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
308 // A=(B=(C=D)), where each paren is a level of recursion here.
309 RHS = ParseRHSOfBinaryExpression(RHS, ThisPrec + !isRightAssoc);
Chris Lattner214cbaf2007-08-31 04:58:34 +0000310 if (RHS.isInvalid) {
311 Actions.DeleteExpr(LHS.Val);
312 Actions.DeleteExpr(TernaryMiddle.Val);
313 return RHS;
314 }
Chris Lattner4b009652007-07-25 00:24:17 +0000315
316 NextTokPrec = getBinOpPrecedence(Tok.getKind());
317 }
318 assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
319
Chris Lattner4a149b62007-08-31 05:01:50 +0000320 if (!LHS.isInvalid) {
321 // Combine the LHS and RHS into the LHS (e.g. build AST).
322 if (TernaryMiddle.isInvalid)
Douglas Gregord7f915e2008-11-06 23:29:22 +0000323 LHS = Actions.ActOnBinOp(CurScope, OpToken.getLocation(),
324 OpToken.getKind(), LHS.Val, RHS.Val);
Chris Lattner4a149b62007-08-31 05:01:50 +0000325 else
Steve Naroff87d58b42007-09-16 03:34:24 +0000326 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
Chris Lattner4a149b62007-08-31 05:01:50 +0000327 LHS.Val, TernaryMiddle.Val, RHS.Val);
328 } else {
329 // We had a semantic error on the LHS. Just free the RHS and continue.
330 Actions.DeleteExpr(TernaryMiddle.Val);
331 Actions.DeleteExpr(RHS.Val);
332 }
Chris Lattner4b009652007-07-25 00:24:17 +0000333 }
334}
335
336/// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
337/// true, parse a unary-expression.
338///
339/// cast-expression: [C99 6.5.4]
340/// unary-expression
341/// '(' type-name ')' cast-expression
342///
343/// unary-expression: [C99 6.5.3]
344/// postfix-expression
345/// '++' unary-expression
346/// '--' unary-expression
347/// unary-operator cast-expression
348/// 'sizeof' unary-expression
349/// 'sizeof' '(' type-name ')'
350/// [GNU] '__alignof' unary-expression
351/// [GNU] '__alignof' '(' type-name ')'
Douglas Gregor658b4442008-11-06 15:17:27 +0000352/// [C++0x] 'alignof' '(' type-id ')'
Chris Lattner4b009652007-07-25 00:24:17 +0000353/// [GNU] '&&' identifier
354///
355/// unary-operator: one of
356/// '&' '*' '+' '-' '~' '!'
357/// [GNU] '__extension__' '__real' '__imag'
358///
359/// primary-expression: [C99 6.5.1]
Douglas Gregore60e5d32008-11-06 22:13:31 +0000360/// [C99] identifier
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000361/// [C++] id-expression
Chris Lattner4b009652007-07-25 00:24:17 +0000362/// constant
363/// string-literal
364/// [C++] boolean-literal [C++ 2.13.5]
365/// '(' expression ')'
366/// '__func__' [C99 6.4.2.2]
367/// [GNU] '__FUNCTION__'
368/// [GNU] '__PRETTY_FUNCTION__'
369/// [GNU] '(' compound-statement ')'
370/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
371/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
372/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
373/// assign-expr ')'
374/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
Fariborz Jahanian628abf12007-09-26 17:03:44 +0000375/// [OBJC] '[' objc-message-expr ']'
Chris Lattner8d050af2008-01-25 18:58:06 +0000376/// [OBJC] '@selector' '(' objc-selector-arg ')'
Fariborz Jahanian628abf12007-09-26 17:03:44 +0000377/// [OBJC] '@protocol' '(' identifier ')'
378/// [OBJC] '@encode' '(' type-name ')'
Fariborz Jahanian1e534dc2007-09-05 19:52:07 +0000379/// [OBJC] objc-string-literal
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000380/// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
381/// [C++] typename-specifier '(' expression-list[opt] ')' [TODO]
Chris Lattner4b009652007-07-25 00:24:17 +0000382/// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
383/// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
384/// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
385/// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000386/// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
387/// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
Argiris Kirtzidisfdde2762008-07-16 07:23:27 +0000388/// [C++] 'this' [C++ 9.3.2]
Steve Narofffd5b19d2008-08-28 19:20:44 +0000389/// [clang] '^' block-literal
Chris Lattner4b009652007-07-25 00:24:17 +0000390///
391/// constant: [C99 6.4.4]
392/// integer-constant
393/// floating-constant
394/// enumeration-constant -> identifier
395/// character-constant
396///
Douglas Gregore60e5d32008-11-06 22:13:31 +0000397/// id-expression: [C++ 5.1]
398/// unqualified-id
399/// qualified-id [TODO]
400///
401/// unqualified-id: [C++ 5.1]
402/// identifier
403/// operator-function-id
404/// conversion-function-id [TODO]
405/// '~' class-name [TODO]
406/// template-id [TODO]
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000407///
Chris Lattner4b009652007-07-25 00:24:17 +0000408Parser::ExprResult Parser::ParseCastExpression(bool isUnaryExpression) {
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000409 if (getLang().CPlusPlus) {
410 // Annotate typenames and C++ scope specifiers.
411 // Used only in C++; in C let the typedef name be handled as an identifier.
412 TryAnnotateTypeOrScopeToken();
413 }
414
Chris Lattner4b009652007-07-25 00:24:17 +0000415 ExprResult Res;
416 tok::TokenKind SavedKind = Tok.getKind();
417
418 // This handles all of cast-expression, unary-expression, postfix-expression,
419 // and primary-expression. We handle them together like this for efficiency
420 // and to simplify handling of an expression starting with a '(' token: which
421 // may be one of a parenthesized expression, cast-expression, compound literal
422 // expression, or statement expression.
423 //
424 // If the parsed tokens consist of a primary-expression, the cases below
425 // call ParsePostfixExpressionSuffix to handle the postfix expression
426 // suffixes. Cases that cannot be followed by postfix exprs should
427 // return without invoking ParsePostfixExpressionSuffix.
428 switch (SavedKind) {
429 case tok::l_paren: {
430 // If this expression is limited to being a unary-expression, the parent can
431 // not start a cast expression.
432 ParenParseOption ParenExprType =
433 isUnaryExpression ? CompoundLiteral : CastExpr;
434 TypeTy *CastTy;
435 SourceLocation LParenLoc = Tok.getLocation();
436 SourceLocation RParenLoc;
437 Res = ParseParenExpression(ParenExprType, CastTy, RParenLoc);
438 if (Res.isInvalid) return Res;
439
440 switch (ParenExprType) {
441 case SimpleExpr: break; // Nothing else to do.
442 case CompoundStmt: break; // Nothing else to do.
443 case CompoundLiteral:
444 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
445 // postfix-expression exist, parse them now.
446 break;
447 case CastExpr:
448 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. Parse
449 // the cast-expression that follows it next.
450 // TODO: For cast expression with CastTy.
451 Res = ParseCastExpression(false);
452 if (!Res.isInvalid)
Steve Naroff87d58b42007-09-16 03:34:24 +0000453 Res = Actions.ActOnCastExpr(LParenLoc, CastTy, RParenLoc, Res.Val);
Chris Lattner4b009652007-07-25 00:24:17 +0000454 return Res;
455 }
456
457 // These can be followed by postfix-expr pieces.
458 return ParsePostfixExpressionSuffix(Res);
459 }
460
461 // primary-expression
462 case tok::numeric_constant:
463 // constant: integer-constant
464 // constant: floating-constant
465
Steve Naroff87d58b42007-09-16 03:34:24 +0000466 Res = Actions.ActOnNumericConstant(Tok);
Chris Lattner4b009652007-07-25 00:24:17 +0000467 ConsumeToken();
468
469 // These can be followed by postfix-expr pieces.
470 return ParsePostfixExpressionSuffix(Res);
471
472 case tok::kw_true:
473 case tok::kw_false:
474 return ParseCXXBoolLiteral();
475
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000476 case tok::identifier: { // primary-expression: identifier
477 // unqualified-id: identifier
478 // constant: enumeration-constant
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000479
Chris Lattner4b009652007-07-25 00:24:17 +0000480 // Consume the identifier so that we can see if it is followed by a '('.
481 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
482 // need to know whether or not this identifier is a function designator or
483 // not.
484 IdentifierInfo &II = *Tok.getIdentifierInfo();
485 SourceLocation L = ConsumeToken();
Chris Lattner4d7d2342007-10-09 17:41:39 +0000486 Res = Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren));
Chris Lattner4b009652007-07-25 00:24:17 +0000487 // These can be followed by postfix-expr pieces.
488 return ParsePostfixExpressionSuffix(Res);
489 }
490 case tok::char_constant: // constant: character-constant
Steve Naroff87d58b42007-09-16 03:34:24 +0000491 Res = Actions.ActOnCharacterConstant(Tok);
Chris Lattner4b009652007-07-25 00:24:17 +0000492 ConsumeToken();
493 // These can be followed by postfix-expr pieces.
494 return ParsePostfixExpressionSuffix(Res);
495 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
496 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
497 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Chris Lattner69909292008-08-10 01:53:14 +0000498 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
Chris Lattner4b009652007-07-25 00:24:17 +0000499 ConsumeToken();
500 // These can be followed by postfix-expr pieces.
501 return ParsePostfixExpressionSuffix(Res);
502 case tok::string_literal: // primary-expression: string-literal
503 case tok::wide_string_literal:
504 Res = ParseStringLiteralExpression();
505 if (Res.isInvalid) return Res;
506 // This can be followed by postfix-expr pieces (e.g. "foo"[1]).
507 return ParsePostfixExpressionSuffix(Res);
508 case tok::kw___builtin_va_arg:
509 case tok::kw___builtin_offsetof:
510 case tok::kw___builtin_choose_expr:
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000511 case tok::kw___builtin_overload:
Chris Lattner4b009652007-07-25 00:24:17 +0000512 case tok::kw___builtin_types_compatible_p:
513 return ParseBuiltinPrimaryExpression();
514 case tok::plusplus: // unary-expression: '++' unary-expression
515 case tok::minusminus: { // unary-expression: '--' unary-expression
516 SourceLocation SavedLoc = ConsumeToken();
517 Res = ParseCastExpression(true);
518 if (!Res.isInvalid)
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000519 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Chris Lattner4b009652007-07-25 00:24:17 +0000520 return Res;
521 }
522 case tok::amp: // unary-expression: '&' cast-expression
523 case tok::star: // unary-expression: '*' cast-expression
524 case tok::plus: // unary-expression: '+' cast-expression
525 case tok::minus: // unary-expression: '-' cast-expression
526 case tok::tilde: // unary-expression: '~' cast-expression
527 case tok::exclaim: // unary-expression: '!' cast-expression
528 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
Chris Lattner6cf92942008-02-02 20:20:10 +0000529 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
Chris Lattner4b009652007-07-25 00:24:17 +0000530 SourceLocation SavedLoc = ConsumeToken();
531 Res = ParseCastExpression(false);
532 if (!Res.isInvalid)
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000533 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Chris Lattner4b009652007-07-25 00:24:17 +0000534 return Res;
Chris Lattner6cf92942008-02-02 20:20:10 +0000535 }
536
537 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
538 // __extension__ silences extension warnings in the subexpression.
Chris Lattnerdaa5c002008-10-20 06:45:43 +0000539 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Chris Lattner6cf92942008-02-02 20:20:10 +0000540 SourceLocation SavedLoc = ConsumeToken();
541 Res = ParseCastExpression(false);
542 if (!Res.isInvalid)
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000543 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Chris Lattner6cf92942008-02-02 20:20:10 +0000544 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000545 }
546 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
547 // unary-expression: 'sizeof' '(' type-name ')'
Douglas Gregor658b4442008-11-06 15:17:27 +0000548 case tok::kw_alignof:
Chris Lattner4b009652007-07-25 00:24:17 +0000549 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
550 // unary-expression: '__alignof' '(' type-name ')'
Douglas Gregor658b4442008-11-06 15:17:27 +0000551 // unary-expression: 'alignof' '(' type-id ')'
Chris Lattner4b009652007-07-25 00:24:17 +0000552 return ParseSizeofAlignofExpression();
553 case tok::ampamp: { // unary-expression: '&&' identifier
554 SourceLocation AmpAmpLoc = ConsumeToken();
Chris Lattner4d7d2342007-10-09 17:41:39 +0000555 if (Tok.isNot(tok::identifier)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000556 Diag(Tok, diag::err_expected_ident);
557 return ExprResult(true);
558 }
559
560 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000561 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000562 Tok.getIdentifierInfo());
563 ConsumeToken();
564 return Res;
565 }
566 case tok::kw_const_cast:
567 case tok::kw_dynamic_cast:
568 case tok::kw_reinterpret_cast:
569 case tok::kw_static_cast:
Argiris Kirtzidis4963ee42008-08-16 19:45:32 +0000570 Res = ParseCXXCasts();
571 // These can be followed by postfix-expr pieces.
572 return ParsePostfixExpressionSuffix(Res);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000573 case tok::kw_typeid:
574 Res = ParseCXXTypeid();
575 // This can be followed by postfix-expr pieces.
576 return ParsePostfixExpressionSuffix(Res);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000577 case tok::kw_this:
Argiris Kirtzidis8f8a52a2008-08-16 19:34:46 +0000578 Res = ParseCXXThis();
579 // This can be followed by postfix-expr pieces.
580 return ParsePostfixExpressionSuffix(Res);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000581
582 case tok::kw_char:
583 case tok::kw_wchar_t:
584 case tok::kw_bool:
585 case tok::kw_short:
586 case tok::kw_int:
587 case tok::kw_long:
588 case tok::kw_signed:
589 case tok::kw_unsigned:
590 case tok::kw_float:
591 case tok::kw_double:
592 case tok::kw_void:
593 case tok::kw_typeof: {
594 if (!getLang().CPlusPlus)
595 goto UnhandledToken;
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000596 case tok::annot_qualtypename:
597 assert(getLang().CPlusPlus && "Expected C++");
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000598 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
599 //
600 DeclSpec DS;
601 ParseCXXSimpleTypeSpecifier(DS);
602 if (Tok.isNot(tok::l_paren))
Chris Lattnerf006a222008-11-18 07:48:38 +0000603 return Diag(Tok, diag::err_expected_lparen_after_type)
604 << DS.getSourceRange();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000605
606 Res = ParseCXXTypeConstructExpression(DS);
607 // This can be followed by postfix-expr pieces.
608 return ParsePostfixExpressionSuffix(Res);
609 }
610
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000611 case tok::annot_cxxscope: // [C++] id-expression: qualified-id
612 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
613 // template-id
614 Res = ParseCXXIdExpression();
615 return ParsePostfixExpressionSuffix(Res);
Douglas Gregore60e5d32008-11-06 22:13:31 +0000616
Chris Lattnerb82d6ef2007-10-03 22:03:06 +0000617 case tok::at: {
618 SourceLocation AtLoc = ConsumeToken();
Steve Narofffb9dd752007-10-15 20:55:58 +0000619 return ParseObjCAtExpression(AtLoc);
Chris Lattnerb82d6ef2007-10-03 22:03:06 +0000620 }
Fariborz Jahanian1e534dc2007-09-05 19:52:07 +0000621 case tok::l_square:
Steve Narofffb9dd752007-10-15 20:55:58 +0000622 // These can be followed by postfix-expr pieces.
Chris Lattner02d3c732008-05-09 05:28:21 +0000623 if (getLang().ObjC1)
624 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression());
625 // FALL THROUGH.
Steve Narofffd5b19d2008-08-28 19:20:44 +0000626 case tok::caret:
627 if (getLang().Blocks)
628 return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression());
629 Diag(Tok, diag::err_expected_expression);
630 return ExprResult(true);
Chris Lattner4b009652007-07-25 00:24:17 +0000631 default:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000632 UnhandledToken:
Chris Lattner4b009652007-07-25 00:24:17 +0000633 Diag(Tok, diag::err_expected_expression);
634 return ExprResult(true);
635 }
636
637 // unreachable.
638 abort();
639}
640
641/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
642/// is parsed, this method parses any suffixes that apply.
643///
644/// postfix-expression: [C99 6.5.2]
645/// primary-expression
646/// postfix-expression '[' expression ']'
647/// postfix-expression '(' argument-expression-list[opt] ')'
648/// postfix-expression '.' identifier
649/// postfix-expression '->' identifier
650/// postfix-expression '++'
651/// postfix-expression '--'
652/// '(' type-name ')' '{' initializer-list '}'
653/// '(' type-name ')' '{' initializer-list ',' '}'
654///
655/// argument-expression-list: [C99 6.5.2]
656/// argument-expression
657/// argument-expression-list ',' assignment-expression
658///
659Parser::ExprResult Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
660
661 // Now that the primary-expression piece of the postfix-expression has been
662 // parsed, see if there are any postfix-expression pieces here.
663 SourceLocation Loc;
664 while (1) {
665 switch (Tok.getKind()) {
666 default: // Not a postfix-expression suffix.
667 return LHS;
668 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
669 Loc = ConsumeBracket();
670 ExprResult Idx = ParseExpression();
671
672 SourceLocation RLoc = Tok.getLocation();
673
Chris Lattner4d7d2342007-10-09 17:41:39 +0000674 if (!LHS.isInvalid && !Idx.isInvalid && Tok.is(tok::r_square))
Steve Naroff87d58b42007-09-16 03:34:24 +0000675 LHS = Actions.ActOnArraySubscriptExpr(LHS.Val, Loc, Idx.Val, RLoc);
Chris Lattner4b009652007-07-25 00:24:17 +0000676 else
677 LHS = ExprResult(true);
678
679 // Match the ']'.
680 MatchRHSPunctuation(tok::r_square, Loc);
681 break;
682 }
683
684 case tok::l_paren: { // p-e: p-e '(' argument-expression-list[opt] ')'
Argiris Kirtzidis83dce112008-08-16 20:03:01 +0000685 ExprListTy ArgExprs;
686 CommaLocsTy CommaLocs;
Chris Lattner4b009652007-07-25 00:24:17 +0000687
688 Loc = ConsumeParen();
689
Chris Lattner4d7d2342007-10-09 17:41:39 +0000690 if (Tok.isNot(tok::r_paren)) {
Argiris Kirtzidis83dce112008-08-16 20:03:01 +0000691 if (ParseExpressionList(ArgExprs, CommaLocs)) {
692 SkipUntil(tok::r_paren);
693 return ExprResult(true);
Chris Lattner4b009652007-07-25 00:24:17 +0000694 }
695 }
696
697 // Match the ')'.
Chris Lattner4d7d2342007-10-09 17:41:39 +0000698 if (!LHS.isInvalid && Tok.is(tok::r_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000699 assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&&
700 "Unexpected number of commas!");
Steve Naroff87d58b42007-09-16 03:34:24 +0000701 LHS = Actions.ActOnCallExpr(LHS.Val, Loc, &ArgExprs[0], ArgExprs.size(),
Chris Lattner4b009652007-07-25 00:24:17 +0000702 &CommaLocs[0], Tok.getLocation());
703 }
704
705 MatchRHSPunctuation(tok::r_paren, Loc);
706 break;
707 }
708 case tok::arrow: // postfix-expression: p-e '->' identifier
709 case tok::period: { // postfix-expression: p-e '.' identifier
710 tok::TokenKind OpKind = Tok.getKind();
711 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
712
Chris Lattner4d7d2342007-10-09 17:41:39 +0000713 if (Tok.isNot(tok::identifier)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000714 Diag(Tok, diag::err_expected_ident);
715 return ExprResult(true);
716 }
717
718 if (!LHS.isInvalid)
Steve Naroff87d58b42007-09-16 03:34:24 +0000719 LHS = Actions.ActOnMemberReferenceExpr(LHS.Val, OpLoc, OpKind,
Chris Lattner4b009652007-07-25 00:24:17 +0000720 Tok.getLocation(),
721 *Tok.getIdentifierInfo());
722 ConsumeToken();
723 break;
724 }
725 case tok::plusplus: // postfix-expression: postfix-expression '++'
726 case tok::minusminus: // postfix-expression: postfix-expression '--'
727 if (!LHS.isInvalid)
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000728 LHS = Actions.ActOnPostfixUnaryOp(CurScope, Tok.getLocation(),
729 Tok.getKind(), LHS.Val);
Chris Lattner4b009652007-07-25 00:24:17 +0000730 ConsumeToken();
731 break;
732 }
733 }
734}
735
736
737/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression.
738/// unary-expression: [C99 6.5.3]
739/// 'sizeof' unary-expression
740/// 'sizeof' '(' type-name ')'
741/// [GNU] '__alignof' unary-expression
742/// [GNU] '__alignof' '(' type-name ')'
Douglas Gregor658b4442008-11-06 15:17:27 +0000743/// [C++0x] 'alignof' '(' type-id ')'
Chris Lattner4b009652007-07-25 00:24:17 +0000744Parser::ExprResult Parser::ParseSizeofAlignofExpression() {
Douglas Gregor658b4442008-11-06 15:17:27 +0000745 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof)
746 || Tok.is(tok::kw_alignof)) &&
Chris Lattner4b009652007-07-25 00:24:17 +0000747 "Not a sizeof/alignof expression!");
748 Token OpTok = Tok;
749 ConsumeToken();
750
751 // If the operand doesn't start with an '(', it must be an expression.
752 ExprResult Operand;
Chris Lattner4d7d2342007-10-09 17:41:39 +0000753 if (Tok.isNot(tok::l_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000754 Operand = ParseCastExpression(true);
755 } else {
756 // If it starts with a '(', we know that it is either a parenthesized
757 // type-name, or it is a unary-expression that starts with a compound
758 // literal, or starts with a primary-expression that is a parenthesized
759 // expression.
760 ParenParseOption ExprType = CastExpr;
761 TypeTy *CastTy;
762 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
763 Operand = ParseParenExpression(ExprType, CastTy, RParenLoc);
764
765 // If ParseParenExpression parsed a '(typename)' sequence only, the this is
766 // sizeof/alignof a type. Otherwise, it is sizeof/alignof an expression.
Chris Lattner48553562007-11-13 20:50:37 +0000767 if (ExprType == CastExpr)
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000768 return Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
769 OpTok.is(tok::kw_sizeof),
770 /*isType=*/true, CastTy,
771 SourceRange(LParenLoc, RParenLoc));
Chris Lattner48553562007-11-13 20:50:37 +0000772
773 // If this is a parenthesized expression, it is the start of a
774 // unary-expression, but doesn't include any postfix pieces. Parse these
775 // now if present.
776 Operand = ParsePostfixExpressionSuffix(Operand);
Chris Lattner4b009652007-07-25 00:24:17 +0000777 }
778
779 // If we get here, the operand to the sizeof/alignof was an expresion.
780 if (!Operand.isInvalid)
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000781 Operand = Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
782 OpTok.is(tok::kw_sizeof),
783 /*isType=*/false, Operand.Val,
784 SourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000785 return Operand;
786}
787
788/// ParseBuiltinPrimaryExpression
789///
790/// primary-expression: [C99 6.5.1]
791/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
792/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
793/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
794/// assign-expr ')'
795/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000796/// [CLANG] '__builtin_overload' '(' expr (',' expr)* ')'
Chris Lattner4b009652007-07-25 00:24:17 +0000797///
798/// [GNU] offsetof-member-designator:
799/// [GNU] identifier
800/// [GNU] offsetof-member-designator '.' identifier
801/// [GNU] offsetof-member-designator '[' expression ']'
802///
803Parser::ExprResult Parser::ParseBuiltinPrimaryExpression() {
804 ExprResult Res(false);
805 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
806
807 tok::TokenKind T = Tok.getKind();
808 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
809
810 // All of these start with an open paren.
Chris Lattner4d7d2342007-10-09 17:41:39 +0000811 if (Tok.isNot(tok::l_paren)) {
Chris Lattner8f7db152008-11-19 07:37:42 +0000812 Diag(Tok, diag::err_expected_lparen_after) << BuiltinII;
Chris Lattner4b009652007-07-25 00:24:17 +0000813 return ExprResult(true);
814 }
815
816 SourceLocation LParenLoc = ConsumeParen();
817 // TODO: Build AST.
818
819 switch (T) {
820 default: assert(0 && "Not a builtin primary expression!");
Anders Carlsson36760332007-10-15 20:28:48 +0000821 case tok::kw___builtin_va_arg: {
822 ExprResult Expr = ParseAssignmentExpression();
823 if (Expr.isInvalid) {
Chris Lattner4b009652007-07-25 00:24:17 +0000824 SkipUntil(tok::r_paren);
Eli Friedmana1b6d802008-08-20 22:07:34 +0000825 return ExprResult(true);
Chris Lattner4b009652007-07-25 00:24:17 +0000826 }
827
828 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
829 return ExprResult(true);
830
Anders Carlsson36760332007-10-15 20:28:48 +0000831 TypeTy *Ty = ParseTypeName();
Chris Lattnercb8943a2007-08-30 15:52:49 +0000832
Anders Carlsson36760332007-10-15 20:28:48 +0000833 if (Tok.isNot(tok::r_paren)) {
834 Diag(Tok, diag::err_expected_rparen);
835 return ExprResult(true);
836 }
837 Res = Actions.ActOnVAArg(StartLoc, Expr.Val, Ty, ConsumeParen());
Chris Lattner4b009652007-07-25 00:24:17 +0000838 break;
Anders Carlsson36760332007-10-15 20:28:48 +0000839 }
Chris Lattner69638b12007-08-30 15:51:11 +0000840 case tok::kw___builtin_offsetof: {
Chris Lattner1b6b5be2007-08-30 17:08:45 +0000841 SourceLocation TypeLoc = Tok.getLocation();
Chris Lattner69638b12007-08-30 15:51:11 +0000842 TypeTy *Ty = ParseTypeName();
Chris Lattner4b009652007-07-25 00:24:17 +0000843
844 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
845 return ExprResult(true);
846
847 // We must have at least one identifier here.
Chris Lattner4d7d2342007-10-09 17:41:39 +0000848 if (Tok.isNot(tok::identifier)) {
Chris Lattner69638b12007-08-30 15:51:11 +0000849 Diag(Tok, diag::err_expected_ident);
850 SkipUntil(tok::r_paren);
851 return true;
852 }
853
854 // Keep track of the various subcomponents we see.
855 llvm::SmallVector<Action::OffsetOfComponent, 4> Comps;
856
857 Comps.push_back(Action::OffsetOfComponent());
858 Comps.back().isBrackets = false;
859 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
860 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
Chris Lattner4b009652007-07-25 00:24:17 +0000861
862 while (1) {
Chris Lattner4d7d2342007-10-09 17:41:39 +0000863 if (Tok.is(tok::period)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000864 // offsetof-member-designator: offsetof-member-designator '.' identifier
Chris Lattner69638b12007-08-30 15:51:11 +0000865 Comps.push_back(Action::OffsetOfComponent());
866 Comps.back().isBrackets = false;
867 Comps.back().LocStart = ConsumeToken();
Chris Lattner4b009652007-07-25 00:24:17 +0000868
Chris Lattner4d7d2342007-10-09 17:41:39 +0000869 if (Tok.isNot(tok::identifier)) {
Chris Lattner69638b12007-08-30 15:51:11 +0000870 Diag(Tok, diag::err_expected_ident);
871 SkipUntil(tok::r_paren);
872 return true;
873 }
874 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
875 Comps.back().LocEnd = ConsumeToken();
876
Chris Lattner4d7d2342007-10-09 17:41:39 +0000877 } else if (Tok.is(tok::l_square)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000878 // offsetof-member-designator: offsetof-member-design '[' expression ']'
Chris Lattner69638b12007-08-30 15:51:11 +0000879 Comps.push_back(Action::OffsetOfComponent());
880 Comps.back().isBrackets = true;
881 Comps.back().LocStart = ConsumeBracket();
Chris Lattner4b009652007-07-25 00:24:17 +0000882 Res = ParseExpression();
883 if (Res.isInvalid) {
884 SkipUntil(tok::r_paren);
885 return Res;
886 }
Chris Lattner69638b12007-08-30 15:51:11 +0000887 Comps.back().U.E = Res.Val;
Chris Lattner4b009652007-07-25 00:24:17 +0000888
Chris Lattner69638b12007-08-30 15:51:11 +0000889 Comps.back().LocEnd =
890 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart);
Chris Lattner4d7d2342007-10-09 17:41:39 +0000891 } else if (Tok.is(tok::r_paren)) {
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000892 Res = Actions.ActOnBuiltinOffsetOf(StartLoc, TypeLoc, Ty, &Comps[0],
Chris Lattnercb8943a2007-08-30 15:52:49 +0000893 Comps.size(), ConsumeParen());
894 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000895 } else {
Chris Lattner69638b12007-08-30 15:51:11 +0000896 // Error occurred.
897 return ExprResult(true);
Chris Lattner4b009652007-07-25 00:24:17 +0000898 }
899 }
900 break;
Chris Lattner69638b12007-08-30 15:51:11 +0000901 }
Steve Naroff93c53012007-08-03 21:21:27 +0000902 case tok::kw___builtin_choose_expr: {
903 ExprResult Cond = ParseAssignmentExpression();
904 if (Cond.isInvalid) {
905 SkipUntil(tok::r_paren);
906 return Cond;
907 }
Chris Lattner4b009652007-07-25 00:24:17 +0000908 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
909 return ExprResult(true);
910
Steve Naroff93c53012007-08-03 21:21:27 +0000911 ExprResult Expr1 = ParseAssignmentExpression();
912 if (Expr1.isInvalid) {
913 SkipUntil(tok::r_paren);
914 return Expr1;
915 }
Chris Lattner4b009652007-07-25 00:24:17 +0000916 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
917 return ExprResult(true);
918
Steve Naroff93c53012007-08-03 21:21:27 +0000919 ExprResult Expr2 = ParseAssignmentExpression();
920 if (Expr2.isInvalid) {
921 SkipUntil(tok::r_paren);
922 return Expr2;
923 }
Chris Lattner4d7d2342007-10-09 17:41:39 +0000924 if (Tok.isNot(tok::r_paren)) {
Steve Naroff93c53012007-08-03 21:21:27 +0000925 Diag(Tok, diag::err_expected_rparen);
926 return ExprResult(true);
927 }
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000928 Res = Actions.ActOnChooseExpr(StartLoc, Cond.Val, Expr1.Val, Expr2.Val,
Chris Lattnercb8943a2007-08-30 15:52:49 +0000929 ConsumeParen());
930 break;
Steve Naroff93c53012007-08-03 21:21:27 +0000931 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000932 case tok::kw___builtin_overload: {
933 llvm::SmallVector<ExprTy*, 8> ArgExprs;
934 llvm::SmallVector<SourceLocation, 8> CommaLocs;
935
936 // For each iteration through the loop look for assign-expr followed by a
937 // comma. If there is no comma, break and attempt to match r-paren.
938 if (Tok.isNot(tok::r_paren)) {
939 while (1) {
940 ExprResult ArgExpr = ParseAssignmentExpression();
941 if (ArgExpr.isInvalid) {
942 SkipUntil(tok::r_paren);
943 return ExprResult(true);
944 } else
945 ArgExprs.push_back(ArgExpr.Val);
946
947 if (Tok.isNot(tok::comma))
948 break;
949 // Move to the next argument, remember where the comma was.
950 CommaLocs.push_back(ConsumeToken());
951 }
952 }
953
954 // Attempt to consume the r-paren
955 if (Tok.isNot(tok::r_paren)) {
956 Diag(Tok, diag::err_expected_rparen);
957 SkipUntil(tok::r_paren);
958 return ExprResult(true);
959 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000960 Res = Actions.ActOnOverloadExpr(&ArgExprs[0], ArgExprs.size(),
961 &CommaLocs[0], StartLoc, ConsumeParen());
962 break;
963 }
Chris Lattner4b009652007-07-25 00:24:17 +0000964 case tok::kw___builtin_types_compatible_p:
Steve Naroff5b528922007-08-01 23:45:51 +0000965 TypeTy *Ty1 = ParseTypeName();
Chris Lattner4b009652007-07-25 00:24:17 +0000966
967 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
968 return ExprResult(true);
969
Steve Naroff5b528922007-08-01 23:45:51 +0000970 TypeTy *Ty2 = ParseTypeName();
971
Chris Lattner4d7d2342007-10-09 17:41:39 +0000972 if (Tok.isNot(tok::r_paren)) {
Steve Naroff5b528922007-08-01 23:45:51 +0000973 Diag(Tok, diag::err_expected_rparen);
974 return ExprResult(true);
975 }
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000976 Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1, Ty2, ConsumeParen());
Chris Lattnercb8943a2007-08-30 15:52:49 +0000977 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000978 }
979
Chris Lattner4b009652007-07-25 00:24:17 +0000980 // These can be followed by postfix-expr pieces because they are
981 // primary-expressions.
982 return ParsePostfixExpressionSuffix(Res);
983}
984
985/// ParseParenExpression - This parses the unit that starts with a '(' token,
986/// based on what is allowed by ExprType. The actual thing parsed is returned
987/// in ExprType.
988///
989/// primary-expression: [C99 6.5.1]
990/// '(' expression ')'
991/// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
992/// postfix-expression: [C99 6.5.2]
993/// '(' type-name ')' '{' initializer-list '}'
994/// '(' type-name ')' '{' initializer-list ',' '}'
995/// cast-expression: [C99 6.5.4]
996/// '(' type-name ')' cast-expression
997///
998Parser::ExprResult Parser::ParseParenExpression(ParenParseOption &ExprType,
999 TypeTy *&CastTy,
1000 SourceLocation &RParenLoc) {
Chris Lattner4d7d2342007-10-09 17:41:39 +00001001 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
Chris Lattner4b009652007-07-25 00:24:17 +00001002 SourceLocation OpenLoc = ConsumeParen();
1003 ExprResult Result(true);
1004 CastTy = 0;
1005
Chris Lattner4d7d2342007-10-09 17:41:39 +00001006 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001007 Diag(Tok, diag::ext_gnu_statement_expr);
Chris Lattnerf2b07572007-08-31 21:49:55 +00001008 Parser::StmtResult Stmt = ParseCompoundStatement(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001009 ExprType = CompoundStmt;
1010
1011 // If the substmt parsed correctly, build the AST node.
Chris Lattner4d7d2342007-10-09 17:41:39 +00001012 if (!Stmt.isInvalid && Tok.is(tok::r_paren))
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001013 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.Val, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001014
Argiris Kirtzidis3276cbc2008-10-05 19:56:22 +00001015 } else if (ExprType >= CompoundLiteral && isTypeIdInParens()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001016 // Otherwise, this is a compound literal expression or cast expression.
1017 TypeTy *Ty = ParseTypeName();
1018
1019 // Match the ')'.
Chris Lattner4d7d2342007-10-09 17:41:39 +00001020 if (Tok.is(tok::r_paren))
Chris Lattner4b009652007-07-25 00:24:17 +00001021 RParenLoc = ConsumeParen();
1022 else
1023 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1024
Chris Lattner4d7d2342007-10-09 17:41:39 +00001025 if (Tok.is(tok::l_brace)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001026 if (!getLang().C99) // Compound literals don't exist in C90.
1027 Diag(OpenLoc, diag::ext_c99_compound_literal);
1028 Result = ParseInitializer();
1029 ExprType = CompoundLiteral;
1030 if (!Result.isInvalid)
Steve Naroff87d58b42007-09-16 03:34:24 +00001031 return Actions.ActOnCompoundLiteral(OpenLoc, Ty, RParenLoc, Result.Val);
Chris Lattner4b009652007-07-25 00:24:17 +00001032 } else if (ExprType == CastExpr) {
1033 // Note that this doesn't parse the subsequence cast-expression, it just
1034 // returns the parsed type to the callee.
1035 ExprType = CastExpr;
1036 CastTy = Ty;
1037 return ExprResult(false);
1038 } else {
1039 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
1040 return ExprResult(true);
1041 }
1042 return Result;
1043 } else {
1044 Result = ParseExpression();
1045 ExprType = SimpleExpr;
Chris Lattner4d7d2342007-10-09 17:41:39 +00001046 if (!Result.isInvalid && Tok.is(tok::r_paren))
Steve Naroff87d58b42007-09-16 03:34:24 +00001047 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.Val);
Chris Lattner4b009652007-07-25 00:24:17 +00001048 }
1049
1050 // Match the ')'.
1051 if (Result.isInvalid)
1052 SkipUntil(tok::r_paren);
1053 else {
Chris Lattner4d7d2342007-10-09 17:41:39 +00001054 if (Tok.is(tok::r_paren))
Chris Lattner4b009652007-07-25 00:24:17 +00001055 RParenLoc = ConsumeParen();
1056 else
1057 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1058 }
1059
1060 return Result;
1061}
1062
1063/// ParseStringLiteralExpression - This handles the various token types that
1064/// form string literals, and also handles string concatenation [C99 5.1.1.2,
1065/// translation phase #6].
1066///
1067/// primary-expression: [C99 6.5.1]
1068/// string-literal
1069Parser::ExprResult Parser::ParseStringLiteralExpression() {
1070 assert(isTokenStringLiteral() && "Not a string literal!");
1071
1072 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
1073 // considered to be strings for concatenation purposes.
1074 llvm::SmallVector<Token, 4> StringToks;
1075
1076 do {
1077 StringToks.push_back(Tok);
1078 ConsumeStringToken();
1079 } while (isTokenStringLiteral());
1080
1081 // Pass the set of string tokens, ready for concatenation, to the actions.
Steve Naroff87d58b42007-09-16 03:34:24 +00001082 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size());
Chris Lattner4b009652007-07-25 00:24:17 +00001083}
Argiris Kirtzidis83dce112008-08-16 20:03:01 +00001084
1085/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1086///
1087/// argument-expression-list:
1088/// assignment-expression
1089/// argument-expression-list , assignment-expression
1090///
1091/// [C++] expression-list:
1092/// [C++] assignment-expression
1093/// [C++] expression-list , assignment-expression
1094///
1095bool Parser::ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs) {
1096 while (1) {
1097 ExprResult Expr = ParseAssignmentExpression();
1098 if (Expr.isInvalid)
1099 return true;
Argiris Kirtzidisd37a4182008-08-18 22:49:40 +00001100
1101 Exprs.push_back(Expr.Val);
Argiris Kirtzidis83dce112008-08-16 20:03:01 +00001102
1103 if (Tok.isNot(tok::comma))
1104 return false;
1105 // Move to the next argument, remember where the comma was.
1106 CommaLocs.push_back(ConsumeToken());
1107 }
1108}
Steve Narofffd5b19d2008-08-28 19:20:44 +00001109
1110/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
Steve Naroffa095a752008-09-16 23:11:46 +00001111/// like ^(int x){ return x+1; }
Steve Narofffd5b19d2008-08-28 19:20:44 +00001112///
1113/// block-literal:
1114/// [clang] '^' block-args[opt] compound-statement
Steve Narofffd5b19d2008-08-28 19:20:44 +00001115/// [clang] block-args:
1116/// [clang] '(' parameter-list ')'
1117///
1118Parser::ExprResult Parser::ParseBlockLiteralExpression() {
1119 assert(Tok.is(tok::caret) && "block literal starts with ^");
1120 SourceLocation CaretLoc = ConsumeToken();
1121
1122 // Enter a scope to hold everything within the block. This includes the
1123 // argument decls, decls within the compound expression, etc. This also
1124 // allows determining whether a variable reference inside the block is
1125 // within or outside of the block.
1126 EnterScope(Scope::BlockScope|Scope::FnScope|Scope::BreakScope|
1127 Scope::ContinueScope|Scope::DeclScope);
Steve Naroff52059382008-10-10 01:28:17 +00001128
1129 // Inform sema that we are starting a block.
1130 Actions.ActOnBlockStart(CaretLoc, CurScope);
Steve Narofffd5b19d2008-08-28 19:20:44 +00001131
1132 // Parse the return type if present.
1133 DeclSpec DS;
1134 Declarator ParamInfo(DS, Declarator::PrototypeContext);
1135
1136 // If this block has arguments, parse them. There is no ambiguity here with
1137 // the expression case, because the expression case requires a parameter list.
1138 if (Tok.is(tok::l_paren)) {
1139 ParseParenDeclarator(ParamInfo);
1140 // Parse the pieces after the identifier as if we had "int(...)".
1141 ParamInfo.SetIdentifier(0, CaretLoc);
1142 if (ParamInfo.getInvalidType()) {
1143 // If there was an error parsing the arguments, they may have tried to use
1144 // ^(x+y) which requires an argument list. Just skip the whole block
1145 // literal.
1146 ExitScope();
1147 return true;
1148 }
1149 } else {
1150 // Otherwise, pretend we saw (void).
1151 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false,
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001152 0, 0, 0, CaretLoc));
Steve Narofffd5b19d2008-08-28 19:20:44 +00001153 }
1154
1155 // Inform sema that we are starting a block.
Steve Naroff52059382008-10-10 01:28:17 +00001156 Actions.ActOnBlockArguments(ParamInfo);
Steve Narofffd5b19d2008-08-28 19:20:44 +00001157
Steve Naroffa095a752008-09-16 23:11:46 +00001158 ExprResult Result = true;
Steve Narofffd5b19d2008-08-28 19:20:44 +00001159 if (Tok.is(tok::l_brace)) {
1160 StmtResult Stmt = ParseCompoundStatementBody();
1161 if (!Stmt.isInvalid) {
1162 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.Val, CurScope);
1163 } else {
1164 Actions.ActOnBlockError(CaretLoc, CurScope);
Steve Narofffd5b19d2008-08-28 19:20:44 +00001165 }
1166 }
Steve Narofffd5b19d2008-08-28 19:20:44 +00001167 ExitScope();
1168 return Result;
1169}
1170