blob: 74b0715de2acbe196071fea0ac8a731a56425b59 [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,
Steve Naroff5cb93b82008-11-19 15:54:23 +0000215 SourceLocation NameLoc,
Chris Lattnerb93fb492008-06-02 21:31:07 +0000216 IdentifierInfo *ReceiverName,
217 ExprTy *ReceiverExpr) {
Steve Naroff5cb93b82008-11-19 15:54:23 +0000218 ExprResult R = ParseObjCMessageExpressionBody(LBracLoc, NameLoc, ReceiverName,
Chris Lattnerb93fb492008-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
Reid Spencer5f016e22007-07-11 17:01:13 +0000227Parser::ExprResult Parser::ParseConstantExpression() {
228 ExprResult LHS = ParseCastExpression(false);
229 if (LHS.isInvalid) return LHS;
230
Reid Spencer5f016e22007-07-11 17:01:13 +0000231 return ParseRHSOfBinaryExpression(LHS, prec::Conditional);
232}
233
Reid Spencer5f016e22007-07-11 17:01:13 +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.
Chris Lattnerd2177732007-07-20 16:59:19 +0000249 Token OpToken = Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000250 ConsumeToken();
251
252 // Special case handling for the ternary operator.
253 ExprResult TernaryMiddle(true);
254 if (NextTokPrec == prec::Conditional) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000255 if (Tok.isNot(tok::colon)) {
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerdbd583c2007-08-31 04:58:34 +0000261 if (TernaryMiddle.isInvalid) {
262 Actions.DeleteExpr(LHS.Val);
263 return TernaryMiddle;
264 }
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner4e1d99a2007-10-09 17:41:39 +0000272 if (Tok.isNot(tok::colon)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000273 Diag(Tok, diag::err_expected_colon);
Chris Lattner1ab3b962008-11-18 07:48:38 +0000274 Diag(OpToken, diag::err_matching) << "?";
Chris Lattnerdbd583c2007-08-31 04:58:34 +0000275 Actions.DeleteExpr(LHS.Val);
276 Actions.DeleteExpr(TernaryMiddle.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerdbd583c2007-08-31 04:58:34 +0000286 if (RHS.isInvalid) {
287 Actions.DeleteExpr(LHS.Val);
288 Actions.DeleteExpr(TernaryMiddle.Val);
289 return RHS;
290 }
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerd7d860d2007-12-18 06:06:23 +0000298 bool isRightAssoc = ThisPrec == prec::Conditional ||
299 ThisPrec == prec::Assignment;
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerdbd583c2007-08-31 04:58:34 +0000310 if (RHS.isInvalid) {
311 Actions.DeleteExpr(LHS.Val);
312 Actions.DeleteExpr(TernaryMiddle.Val);
313 return RHS;
314 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000315
316 NextTokPrec = getBinOpPrecedence(Tok.getKind());
317 }
318 assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
319
Chris Lattnerd56d6b62007-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 Gregoreaebc752008-11-06 23:29:22 +0000323 LHS = Actions.ActOnBinOp(CurScope, OpToken.getLocation(),
324 OpToken.getKind(), LHS.Val, RHS.Val);
Chris Lattnerd56d6b62007-08-31 05:01:50 +0000325 else
Steve Narofff69936d2007-09-16 03:34:24 +0000326 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
Chris Lattnerd56d6b62007-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 }
Reid Spencer5f016e22007-07-11 17:01:13 +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 Gregor85bb3da2008-11-06 15:17:27 +0000352/// [C++0x] 'alignof' '(' type-id ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000353/// [GNU] '&&' identifier
354///
355/// unary-operator: one of
356/// '&' '*' '+' '-' '~' '!'
357/// [GNU] '__extension__' '__real' '__imag'
358///
359/// primary-expression: [C99 6.5.1]
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +0000360/// [C99] identifier
Sebastian Redlc42e1182008-11-11 11:37:55 +0000361/// [C++] id-expression
Reid Spencer5f016e22007-07-11 17:01:13 +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 Jahanian095ffca2007-09-26 17:03:44 +0000375/// [OBJC] '[' objc-message-expr ']'
Chris Lattner5ac87ed2008-01-25 18:58:06 +0000376/// [OBJC] '@selector' '(' objc-selector-arg ')'
Fariborz Jahanian095ffca2007-09-26 17:03:44 +0000377/// [OBJC] '@protocol' '(' identifier ')'
378/// [OBJC] '@encode' '(' type-name ')'
Fariborz Jahanian0ccb27d2007-09-05 19:52:07 +0000379/// [OBJC] objc-string-literal
Argyrios Kyrtzidis987a14b2008-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]
Reid Spencer5f016e22007-07-11 17:01:13 +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 Redlc42e1182008-11-11 11:37:55 +0000386/// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
387/// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
Argyrios Kyrtzidisd7464be2008-07-16 07:23:27 +0000388/// [C++] 'this' [C++ 9.3.2]
Steve Naroff296e8d52008-08-28 19:20:44 +0000389/// [clang] '^' block-literal
Reid Spencer5f016e22007-07-11 17:01:13 +0000390///
391/// constant: [C99 6.4.4]
392/// integer-constant
393/// floating-constant
394/// enumeration-constant -> identifier
395/// character-constant
396///
Douglas Gregor1cd1b1e2008-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]
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000407///
Reid Spencer5f016e22007-07-11 17:01:13 +0000408Parser::ExprResult Parser::ParseCastExpression(bool isUnaryExpression) {
Argyrios Kyrtzidiseb83ecd2008-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
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +0000453 Res = Actions.ActOnCastExpr(LParenLoc, CastTy, RParenLoc, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Narofff69936d2007-09-16 03:34:24 +0000466 Res = Actions.ActOnNumericConstant(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +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
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000476 case tok::identifier: { // primary-expression: identifier
477 // unqualified-id: identifier
478 // constant: enumeration-constant
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000479
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner4e1d99a2007-10-09 17:41:39 +0000486 Res = Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren));
Reid Spencer5f016e22007-07-11 17:01:13 +0000487 // These can be followed by postfix-expr pieces.
488 return ParsePostfixExpressionSuffix(Res);
489 }
490 case tok::char_constant: // constant: character-constant
Steve Narofff69936d2007-09-16 03:34:24 +0000491 Res = Actions.ActOnCharacterConstant(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattnerd9f69102008-08-10 01:53:14 +0000498 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Begemane2ce1d92008-01-17 17:46:27 +0000511 case tok::kw___builtin_overload:
Reid Spencer5f016e22007-07-11 17:01:13 +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 Gregor74253732008-11-19 15:42:04 +0000519 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner35080842008-02-02 20:20:10 +0000529 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
Reid Spencer5f016e22007-07-11 17:01:13 +0000530 SourceLocation SavedLoc = ConsumeToken();
531 Res = ParseCastExpression(false);
532 if (!Res.isInvalid)
Douglas Gregor74253732008-11-19 15:42:04 +0000533 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000534 return Res;
Chris Lattner35080842008-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 Lattnerc46d1a12008-10-20 06:45:43 +0000539 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Chris Lattner35080842008-02-02 20:20:10 +0000540 SourceLocation SavedLoc = ConsumeToken();
541 Res = ParseCastExpression(false);
542 if (!Res.isInvalid)
Douglas Gregor74253732008-11-19 15:42:04 +0000543 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Chris Lattner35080842008-02-02 20:20:10 +0000544 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 }
546 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
547 // unary-expression: 'sizeof' '(' type-name ')'
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000548 case tok::kw_alignof:
Reid Spencer5f016e22007-07-11 17:01:13 +0000549 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
550 // unary-expression: '__alignof' '(' type-name ')'
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000551 // unary-expression: 'alignof' '(' type-id ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000552 return ParseSizeofAlignofExpression();
553 case tok::ampamp: { // unary-expression: '&&' identifier
554 SourceLocation AmpAmpLoc = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000555 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 Diag(Tok, diag::err_expected_ident);
557 return ExprResult(true);
558 }
559
560 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
Steve Naroff1b273c42007-09-16 14:56:35 +0000561 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +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:
Argyrios Kyrtzidisb348b812008-08-16 19:45:32 +0000570 Res = ParseCXXCasts();
571 // These can be followed by postfix-expr pieces.
572 return ParsePostfixExpressionSuffix(Res);
Sebastian Redlc42e1182008-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);
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000577 case tok::kw_this:
Argyrios Kyrtzidis289d7732008-08-16 19:34:46 +0000578 Res = ParseCXXThis();
579 // This can be followed by postfix-expr pieces.
580 return ParsePostfixExpressionSuffix(Res);
Argyrios Kyrtzidis987a14b2008-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;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000596 case tok::annot_qualtypename:
597 assert(getLang().CPlusPlus && "Expected C++");
Argyrios Kyrtzidis987a14b2008-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 Lattner1ab3b962008-11-18 07:48:38 +0000603 return Diag(Tok, diag::err_expected_lparen_after_type)
604 << DS.getSourceRange();
Argyrios Kyrtzidis987a14b2008-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
Argyrios Kyrtzidiseb83ecd2008-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 Gregor1cd1b1e2008-11-06 22:13:31 +0000616
Chris Lattnerc97c2042007-10-03 22:03:06 +0000617 case tok::at: {
618 SourceLocation AtLoc = ConsumeToken();
Steve Naroffa642beb2007-10-15 20:55:58 +0000619 return ParseObjCAtExpression(AtLoc);
Chris Lattnerc97c2042007-10-03 22:03:06 +0000620 }
Fariborz Jahanian0ccb27d2007-09-05 19:52:07 +0000621 case tok::l_square:
Steve Naroffa642beb2007-10-15 20:55:58 +0000622 // These can be followed by postfix-expr pieces.
Chris Lattner039a6422008-05-09 05:28:21 +0000623 if (getLang().ObjC1)
624 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression());
625 // FALL THROUGH.
Steve Naroff296e8d52008-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);
Reid Spencer5f016e22007-07-11 17:01:13 +0000631 default:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000632 UnhandledToken:
Reid Spencer5f016e22007-07-11 17:01:13 +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 Lattner4e1d99a2007-10-09 17:41:39 +0000674 if (!LHS.isInvalid && !Idx.isInvalid && Tok.is(tok::r_square))
Douglas Gregor337c6b92008-11-19 17:17:41 +0000675 LHS = Actions.ActOnArraySubscriptExpr(CurScope, LHS.Val, Loc,
676 Idx.Val, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000677 else
678 LHS = ExprResult(true);
679
680 // Match the ']'.
681 MatchRHSPunctuation(tok::r_square, Loc);
682 break;
683 }
684
685 case tok::l_paren: { // p-e: p-e '(' argument-expression-list[opt] ')'
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +0000686 ExprListTy ArgExprs;
687 CommaLocsTy CommaLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000688
689 Loc = ConsumeParen();
690
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000691 if (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +0000692 if (ParseExpressionList(ArgExprs, CommaLocs)) {
693 SkipUntil(tok::r_paren);
694 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000695 }
696 }
697
698 // Match the ')'.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000699 if (!LHS.isInvalid && Tok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&&
701 "Unexpected number of commas!");
Steve Narofff69936d2007-09-16 03:34:24 +0000702 LHS = Actions.ActOnCallExpr(LHS.Val, Loc, &ArgExprs[0], ArgExprs.size(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000703 &CommaLocs[0], Tok.getLocation());
704 }
705
Chris Lattner2ff54262007-07-21 05:18:12 +0000706 MatchRHSPunctuation(tok::r_paren, Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 break;
708 }
709 case tok::arrow: // postfix-expression: p-e '->' identifier
710 case tok::period: { // postfix-expression: p-e '.' identifier
711 tok::TokenKind OpKind = Tok.getKind();
712 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
713
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000714 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 Diag(Tok, diag::err_expected_ident);
716 return ExprResult(true);
717 }
718
719 if (!LHS.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000720 LHS = Actions.ActOnMemberReferenceExpr(LHS.Val, OpLoc, OpKind,
Reid Spencer5f016e22007-07-11 17:01:13 +0000721 Tok.getLocation(),
722 *Tok.getIdentifierInfo());
723 ConsumeToken();
724 break;
725 }
726 case tok::plusplus: // postfix-expression: postfix-expression '++'
727 case tok::minusminus: // postfix-expression: postfix-expression '--'
728 if (!LHS.isInvalid)
Douglas Gregor74253732008-11-19 15:42:04 +0000729 LHS = Actions.ActOnPostfixUnaryOp(CurScope, Tok.getLocation(),
730 Tok.getKind(), LHS.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 ConsumeToken();
732 break;
733 }
734 }
735}
736
737
738/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression.
739/// unary-expression: [C99 6.5.3]
740/// 'sizeof' unary-expression
741/// 'sizeof' '(' type-name ')'
742/// [GNU] '__alignof' unary-expression
743/// [GNU] '__alignof' '(' type-name ')'
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000744/// [C++0x] 'alignof' '(' type-id ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000745Parser::ExprResult Parser::ParseSizeofAlignofExpression() {
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000746 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof)
747 || Tok.is(tok::kw_alignof)) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000748 "Not a sizeof/alignof expression!");
Chris Lattnerd2177732007-07-20 16:59:19 +0000749 Token OpTok = Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000750 ConsumeToken();
751
752 // If the operand doesn't start with an '(', it must be an expression.
753 ExprResult Operand;
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000754 if (Tok.isNot(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000755 Operand = ParseCastExpression(true);
756 } else {
757 // If it starts with a '(', we know that it is either a parenthesized
758 // type-name, or it is a unary-expression that starts with a compound
759 // literal, or starts with a primary-expression that is a parenthesized
760 // expression.
761 ParenParseOption ExprType = CastExpr;
762 TypeTy *CastTy;
763 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
764 Operand = ParseParenExpression(ExprType, CastTy, RParenLoc);
765
766 // If ParseParenExpression parsed a '(typename)' sequence only, the this is
767 // sizeof/alignof a type. Otherwise, it is sizeof/alignof an expression.
Chris Lattner4c1a2a92007-11-13 20:50:37 +0000768 if (ExprType == CastExpr)
Sebastian Redl05189992008-11-11 17:56:53 +0000769 return Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
770 OpTok.is(tok::kw_sizeof),
771 /*isType=*/true, CastTy,
772 SourceRange(LParenLoc, RParenLoc));
Chris Lattner4c1a2a92007-11-13 20:50:37 +0000773
774 // If this is a parenthesized expression, it is the start of a
775 // unary-expression, but doesn't include any postfix pieces. Parse these
776 // now if present.
777 Operand = ParsePostfixExpressionSuffix(Operand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000778 }
779
780 // If we get here, the operand to the sizeof/alignof was an expresion.
781 if (!Operand.isInvalid)
Sebastian Redl05189992008-11-11 17:56:53 +0000782 Operand = Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
783 OpTok.is(tok::kw_sizeof),
784 /*isType=*/false, Operand.Val,
785 SourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000786 return Operand;
787}
788
789/// ParseBuiltinPrimaryExpression
790///
791/// primary-expression: [C99 6.5.1]
792/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
793/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
794/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
795/// assign-expr ')'
796/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
Nate Begemane2ce1d92008-01-17 17:46:27 +0000797/// [CLANG] '__builtin_overload' '(' expr (',' expr)* ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000798///
799/// [GNU] offsetof-member-designator:
800/// [GNU] identifier
801/// [GNU] offsetof-member-designator '.' identifier
802/// [GNU] offsetof-member-designator '[' expression ']'
803///
804Parser::ExprResult Parser::ParseBuiltinPrimaryExpression() {
805 ExprResult Res(false);
806 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
807
808 tok::TokenKind T = Tok.getKind();
809 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
810
811 // All of these start with an open paren.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000812 if (Tok.isNot(tok::l_paren)) {
Chris Lattnerda83bac2008-11-19 07:37:42 +0000813 Diag(Tok, diag::err_expected_lparen_after) << BuiltinII;
Reid Spencer5f016e22007-07-11 17:01:13 +0000814 return ExprResult(true);
815 }
816
817 SourceLocation LParenLoc = ConsumeParen();
818 // TODO: Build AST.
819
820 switch (T) {
821 default: assert(0 && "Not a builtin primary expression!");
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000822 case tok::kw___builtin_va_arg: {
823 ExprResult Expr = ParseAssignmentExpression();
824 if (Expr.isInvalid) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000825 SkipUntil(tok::r_paren);
Eli Friedman09762782008-08-20 22:07:34 +0000826 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000827 }
828
829 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
830 return ExprResult(true);
831
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000832 TypeTy *Ty = ParseTypeName();
Chris Lattner6eb21092007-08-30 15:52:49 +0000833
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000834 if (Tok.isNot(tok::r_paren)) {
835 Diag(Tok, diag::err_expected_rparen);
836 return ExprResult(true);
837 }
838 Res = Actions.ActOnVAArg(StartLoc, Expr.Val, Ty, ConsumeParen());
Reid Spencer5f016e22007-07-11 17:01:13 +0000839 break;
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000840 }
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000841 case tok::kw___builtin_offsetof: {
Chris Lattner9fddf0a2007-08-30 17:08:45 +0000842 SourceLocation TypeLoc = Tok.getLocation();
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000843 TypeTy *Ty = ParseTypeName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000844
845 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
846 return ExprResult(true);
847
848 // We must have at least one identifier here.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000849 if (Tok.isNot(tok::identifier)) {
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000850 Diag(Tok, diag::err_expected_ident);
851 SkipUntil(tok::r_paren);
852 return true;
853 }
854
855 // Keep track of the various subcomponents we see.
856 llvm::SmallVector<Action::OffsetOfComponent, 4> Comps;
857
858 Comps.push_back(Action::OffsetOfComponent());
859 Comps.back().isBrackets = false;
860 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
861 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
Reid Spencer5f016e22007-07-11 17:01:13 +0000862
863 while (1) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000864 if (Tok.is(tok::period)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000865 // offsetof-member-designator: offsetof-member-designator '.' identifier
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000866 Comps.push_back(Action::OffsetOfComponent());
867 Comps.back().isBrackets = false;
868 Comps.back().LocStart = ConsumeToken();
Reid Spencer5f016e22007-07-11 17:01:13 +0000869
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000870 if (Tok.isNot(tok::identifier)) {
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000871 Diag(Tok, diag::err_expected_ident);
872 SkipUntil(tok::r_paren);
873 return true;
874 }
875 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
876 Comps.back().LocEnd = ConsumeToken();
877
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000878 } else if (Tok.is(tok::l_square)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000879 // offsetof-member-designator: offsetof-member-design '[' expression ']'
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000880 Comps.push_back(Action::OffsetOfComponent());
881 Comps.back().isBrackets = true;
882 Comps.back().LocStart = ConsumeBracket();
Reid Spencer5f016e22007-07-11 17:01:13 +0000883 Res = ParseExpression();
884 if (Res.isInvalid) {
885 SkipUntil(tok::r_paren);
886 return Res;
887 }
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000888 Comps.back().U.E = Res.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000889
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000890 Comps.back().LocEnd =
891 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart);
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000892 } else if (Tok.is(tok::r_paren)) {
Steve Naroff1b273c42007-09-16 14:56:35 +0000893 Res = Actions.ActOnBuiltinOffsetOf(StartLoc, TypeLoc, Ty, &Comps[0],
Chris Lattner6eb21092007-08-30 15:52:49 +0000894 Comps.size(), ConsumeParen());
895 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000896 } else {
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000897 // Error occurred.
898 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000899 }
900 }
901 break;
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000902 }
Steve Naroffd04fdd52007-08-03 21:21:27 +0000903 case tok::kw___builtin_choose_expr: {
904 ExprResult Cond = ParseAssignmentExpression();
905 if (Cond.isInvalid) {
906 SkipUntil(tok::r_paren);
907 return Cond;
908 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000909 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
910 return ExprResult(true);
911
Steve Naroffd04fdd52007-08-03 21:21:27 +0000912 ExprResult Expr1 = ParseAssignmentExpression();
913 if (Expr1.isInvalid) {
914 SkipUntil(tok::r_paren);
915 return Expr1;
916 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000917 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
918 return ExprResult(true);
919
Steve Naroffd04fdd52007-08-03 21:21:27 +0000920 ExprResult Expr2 = ParseAssignmentExpression();
921 if (Expr2.isInvalid) {
922 SkipUntil(tok::r_paren);
923 return Expr2;
924 }
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000925 if (Tok.isNot(tok::r_paren)) {
Steve Naroffd04fdd52007-08-03 21:21:27 +0000926 Diag(Tok, diag::err_expected_rparen);
927 return ExprResult(true);
928 }
Steve Naroff1b273c42007-09-16 14:56:35 +0000929 Res = Actions.ActOnChooseExpr(StartLoc, Cond.Val, Expr1.Val, Expr2.Val,
Chris Lattner6eb21092007-08-30 15:52:49 +0000930 ConsumeParen());
931 break;
Steve Naroffd04fdd52007-08-03 21:21:27 +0000932 }
Nate Begemane2ce1d92008-01-17 17:46:27 +0000933 case tok::kw___builtin_overload: {
934 llvm::SmallVector<ExprTy*, 8> ArgExprs;
935 llvm::SmallVector<SourceLocation, 8> CommaLocs;
936
937 // For each iteration through the loop look for assign-expr followed by a
938 // comma. If there is no comma, break and attempt to match r-paren.
939 if (Tok.isNot(tok::r_paren)) {
940 while (1) {
941 ExprResult ArgExpr = ParseAssignmentExpression();
942 if (ArgExpr.isInvalid) {
943 SkipUntil(tok::r_paren);
944 return ExprResult(true);
945 } else
946 ArgExprs.push_back(ArgExpr.Val);
947
948 if (Tok.isNot(tok::comma))
949 break;
950 // Move to the next argument, remember where the comma was.
951 CommaLocs.push_back(ConsumeToken());
952 }
953 }
954
955 // Attempt to consume the r-paren
956 if (Tok.isNot(tok::r_paren)) {
957 Diag(Tok, diag::err_expected_rparen);
958 SkipUntil(tok::r_paren);
959 return ExprResult(true);
960 }
Nate Begemane2ce1d92008-01-17 17:46:27 +0000961 Res = Actions.ActOnOverloadExpr(&ArgExprs[0], ArgExprs.size(),
962 &CommaLocs[0], StartLoc, ConsumeParen());
963 break;
964 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000965 case tok::kw___builtin_types_compatible_p:
Steve Naroff363bcff2007-08-01 23:45:51 +0000966 TypeTy *Ty1 = ParseTypeName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000967
968 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
969 return ExprResult(true);
970
Steve Naroff363bcff2007-08-01 23:45:51 +0000971 TypeTy *Ty2 = ParseTypeName();
972
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000973 if (Tok.isNot(tok::r_paren)) {
Steve Naroff363bcff2007-08-01 23:45:51 +0000974 Diag(Tok, diag::err_expected_rparen);
975 return ExprResult(true);
976 }
Steve Naroff1b273c42007-09-16 14:56:35 +0000977 Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1, Ty2, ConsumeParen());
Chris Lattner6eb21092007-08-30 15:52:49 +0000978 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000979 }
980
Reid Spencer5f016e22007-07-11 17:01:13 +0000981 // These can be followed by postfix-expr pieces because they are
982 // primary-expressions.
983 return ParsePostfixExpressionSuffix(Res);
984}
985
986/// ParseParenExpression - This parses the unit that starts with a '(' token,
987/// based on what is allowed by ExprType. The actual thing parsed is returned
988/// in ExprType.
989///
990/// primary-expression: [C99 6.5.1]
991/// '(' expression ')'
992/// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
993/// postfix-expression: [C99 6.5.2]
994/// '(' type-name ')' '{' initializer-list '}'
995/// '(' type-name ')' '{' initializer-list ',' '}'
996/// cast-expression: [C99 6.5.4]
997/// '(' type-name ')' cast-expression
998///
999Parser::ExprResult Parser::ParseParenExpression(ParenParseOption &ExprType,
1000 TypeTy *&CastTy,
1001 SourceLocation &RParenLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001002 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001003 SourceLocation OpenLoc = ConsumeParen();
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001004 ExprResult Result(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001005 CastTy = 0;
1006
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001007 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001008 Diag(Tok, diag::ext_gnu_statement_expr);
Chris Lattner98414c12007-08-31 21:49:55 +00001009 Parser::StmtResult Stmt = ParseCompoundStatement(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001010 ExprType = CompoundStmt;
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001011
1012 // If the substmt parsed correctly, build the AST node.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001013 if (!Stmt.isInvalid && Tok.is(tok::r_paren))
Steve Naroff1b273c42007-09-16 14:56:35 +00001014 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.Val, Tok.getLocation());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001015
Argyrios Kyrtzidis78c8d802008-10-05 19:56:22 +00001016 } else if (ExprType >= CompoundLiteral && isTypeIdInParens()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001017 // Otherwise, this is a compound literal expression or cast expression.
1018 TypeTy *Ty = ParseTypeName();
1019
1020 // Match the ')'.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001021 if (Tok.is(tok::r_paren))
Reid Spencer5f016e22007-07-11 17:01:13 +00001022 RParenLoc = ConsumeParen();
1023 else
1024 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1025
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001026 if (Tok.is(tok::l_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001027 if (!getLang().C99) // Compound literals don't exist in C90.
1028 Diag(OpenLoc, diag::ext_c99_compound_literal);
1029 Result = ParseInitializer();
1030 ExprType = CompoundLiteral;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001031 if (!Result.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +00001032 return Actions.ActOnCompoundLiteral(OpenLoc, Ty, RParenLoc, Result.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +00001033 } else if (ExprType == CastExpr) {
1034 // Note that this doesn't parse the subsequence cast-expression, it just
1035 // returns the parsed type to the callee.
1036 ExprType = CastExpr;
1037 CastTy = Ty;
1038 return ExprResult(false);
1039 } else {
1040 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
1041 return ExprResult(true);
1042 }
1043 return Result;
1044 } else {
1045 Result = ParseExpression();
1046 ExprType = SimpleExpr;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001047 if (!Result.isInvalid && Tok.is(tok::r_paren))
Steve Narofff69936d2007-09-16 03:34:24 +00001048 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +00001049 }
1050
1051 // Match the ')'.
1052 if (Result.isInvalid)
1053 SkipUntil(tok::r_paren);
1054 else {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001055 if (Tok.is(tok::r_paren))
Reid Spencer5f016e22007-07-11 17:01:13 +00001056 RParenLoc = ConsumeParen();
1057 else
1058 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1059 }
1060
1061 return Result;
1062}
1063
1064/// ParseStringLiteralExpression - This handles the various token types that
1065/// form string literals, and also handles string concatenation [C99 5.1.1.2,
1066/// translation phase #6].
1067///
1068/// primary-expression: [C99 6.5.1]
1069/// string-literal
1070Parser::ExprResult Parser::ParseStringLiteralExpression() {
1071 assert(isTokenStringLiteral() && "Not a string literal!");
1072
1073 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
1074 // considered to be strings for concatenation purposes.
Chris Lattnerd2177732007-07-20 16:59:19 +00001075 llvm::SmallVector<Token, 4> StringToks;
Reid Spencer5f016e22007-07-11 17:01:13 +00001076
1077 do {
1078 StringToks.push_back(Tok);
1079 ConsumeStringToken();
1080 } while (isTokenStringLiteral());
1081
1082 // Pass the set of string tokens, ready for concatenation, to the actions.
Steve Narofff69936d2007-09-16 03:34:24 +00001083 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size());
Reid Spencer5f016e22007-07-11 17:01:13 +00001084}
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +00001085
1086/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1087///
1088/// argument-expression-list:
1089/// assignment-expression
1090/// argument-expression-list , assignment-expression
1091///
1092/// [C++] expression-list:
1093/// [C++] assignment-expression
1094/// [C++] expression-list , assignment-expression
1095///
1096bool Parser::ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs) {
1097 while (1) {
1098 ExprResult Expr = ParseAssignmentExpression();
1099 if (Expr.isInvalid)
1100 return true;
Argyrios Kyrtzidis4fdc1ca2008-08-18 22:49:40 +00001101
1102 Exprs.push_back(Expr.Val);
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +00001103
1104 if (Tok.isNot(tok::comma))
1105 return false;
1106 // Move to the next argument, remember where the comma was.
1107 CommaLocs.push_back(ConsumeToken());
1108 }
1109}
Steve Naroff296e8d52008-08-28 19:20:44 +00001110
1111/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
Steve Naroff17dab4f2008-09-16 23:11:46 +00001112/// like ^(int x){ return x+1; }
Steve Naroff296e8d52008-08-28 19:20:44 +00001113///
1114/// block-literal:
1115/// [clang] '^' block-args[opt] compound-statement
Steve Naroff296e8d52008-08-28 19:20:44 +00001116/// [clang] block-args:
1117/// [clang] '(' parameter-list ')'
1118///
1119Parser::ExprResult Parser::ParseBlockLiteralExpression() {
1120 assert(Tok.is(tok::caret) && "block literal starts with ^");
1121 SourceLocation CaretLoc = ConsumeToken();
1122
1123 // Enter a scope to hold everything within the block. This includes the
1124 // argument decls, decls within the compound expression, etc. This also
1125 // allows determining whether a variable reference inside the block is
1126 // within or outside of the block.
1127 EnterScope(Scope::BlockScope|Scope::FnScope|Scope::BreakScope|
1128 Scope::ContinueScope|Scope::DeclScope);
Steve Naroff090276f2008-10-10 01:28:17 +00001129
1130 // Inform sema that we are starting a block.
1131 Actions.ActOnBlockStart(CaretLoc, CurScope);
Steve Naroff296e8d52008-08-28 19:20:44 +00001132
1133 // Parse the return type if present.
1134 DeclSpec DS;
1135 Declarator ParamInfo(DS, Declarator::PrototypeContext);
1136
1137 // If this block has arguments, parse them. There is no ambiguity here with
1138 // the expression case, because the expression case requires a parameter list.
1139 if (Tok.is(tok::l_paren)) {
1140 ParseParenDeclarator(ParamInfo);
1141 // Parse the pieces after the identifier as if we had "int(...)".
1142 ParamInfo.SetIdentifier(0, CaretLoc);
1143 if (ParamInfo.getInvalidType()) {
1144 // If there was an error parsing the arguments, they may have tried to use
1145 // ^(x+y) which requires an argument list. Just skip the whole block
1146 // literal.
1147 ExitScope();
1148 return true;
1149 }
1150 } else {
1151 // Otherwise, pretend we saw (void).
1152 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001153 0, 0, 0, CaretLoc));
Steve Naroff296e8d52008-08-28 19:20:44 +00001154 }
1155
1156 // Inform sema that we are starting a block.
Steve Naroff090276f2008-10-10 01:28:17 +00001157 Actions.ActOnBlockArguments(ParamInfo);
Steve Naroff296e8d52008-08-28 19:20:44 +00001158
Steve Naroff17dab4f2008-09-16 23:11:46 +00001159 ExprResult Result = true;
Steve Naroff296e8d52008-08-28 19:20:44 +00001160 if (Tok.is(tok::l_brace)) {
1161 StmtResult Stmt = ParseCompoundStatementBody();
1162 if (!Stmt.isInvalid) {
1163 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.Val, CurScope);
1164 } else {
1165 Actions.ActOnBlockError(CaretLoc, CurScope);
Steve Naroff296e8d52008-08-28 19:20:44 +00001166 }
1167 }
Steve Naroff296e8d52008-08-28 19:20:44 +00001168 ExitScope();
1169 return Result;
1170}
1171