blob: bb05c35464722ab7f5f625511c6e492a10c55512 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expression parsing implementation. Expressions in
11// C99 basically consist of a bunch of binary operators with unary operators and
12// other random stuff at the leaves.
13//
14// In the C99 grammar, these unary operators bind tightest and are represented
15// as the 'cast-expression' production. Everything else is either a binary
16// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
17// handled by ParseCastExpression, the higher level pieces are handled by
18// ParseBinaryExpression.
19//
20//===----------------------------------------------------------------------===//
21
22#include "clang/Parse/Parser.h"
23#include "clang/Basic/Diagnostic.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/SmallString.h"
26using namespace clang;
27
28/// PrecedenceLevels - These are precedences for the binary/ternary operators in
29/// the C99 grammar. These have been named to relate with the C99 grammar
30/// productions. Low precedences numbers bind more weakly than high numbers.
31namespace prec {
32 enum Level {
33 Unknown = 0, // Not binary operator.
34 Comma = 1, // ,
35 Assignment = 2, // =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=
36 Conditional = 3, // ?
37 LogicalOr = 4, // ||
38 LogicalAnd = 5, // &&
39 InclusiveOr = 6, // |
40 ExclusiveOr = 7, // ^
41 And = 8, // &
42 Equality = 9, // ==, !=
43 Relational = 10, // >=, <=, >, <
44 Shift = 11, // <<, >>
45 Additive = 12, // -, +
46 Multiplicative = 13 // *, /, %
47 };
48}
49
50
51/// getBinOpPrecedence - Return the precedence of the specified binary operator
52/// token. This returns:
53///
54static prec::Level getBinOpPrecedence(tok::TokenKind Kind) {
55 switch (Kind) {
56 default: return prec::Unknown;
57 case tok::comma: return prec::Comma;
58 case tok::equal:
59 case tok::starequal:
60 case tok::slashequal:
61 case tok::percentequal:
62 case tok::plusequal:
63 case tok::minusequal:
64 case tok::lesslessequal:
65 case tok::greatergreaterequal:
66 case tok::ampequal:
67 case tok::caretequal:
68 case tok::pipeequal: return prec::Assignment;
69 case tok::question: return prec::Conditional;
70 case tok::pipepipe: return prec::LogicalOr;
71 case tok::ampamp: return prec::LogicalAnd;
72 case tok::pipe: return prec::InclusiveOr;
73 case tok::caret: return prec::ExclusiveOr;
74 case tok::amp: return prec::And;
75 case tok::exclaimequal:
76 case tok::equalequal: return prec::Equality;
77 case tok::lessequal:
78 case tok::less:
79 case tok::greaterequal:
80 case tok::greater: return prec::Relational;
81 case tok::lessless:
82 case tok::greatergreater: return prec::Shift;
83 case tok::plus:
84 case tok::minus: return prec::Additive;
85 case tok::percent:
86 case tok::slash:
87 case tok::star: return prec::Multiplicative;
88 }
89}
90
91
92/// ParseExpression - Simple precedence-based parser for binary/ternary
93/// operators.
94///
95/// Note: we diverge from the C99 grammar when parsing the assignment-expression
96/// production. C99 specifies that the LHS of an assignment operator should be
97/// parsed as a unary-expression, but consistency dictates that it be a
98/// conditional-expession. In practice, the important thing here is that the
99/// LHS of an assignment has to be an l-value, which productions between
100/// unary-expression and conditional-expression don't produce. Because we want
101/// consistency, we parse the LHS as a conditional-expression, then check for
102/// l-value-ness in semantic analysis stages.
103///
104/// multiplicative-expression: [C99 6.5.5]
105/// cast-expression
106/// multiplicative-expression '*' cast-expression
107/// multiplicative-expression '/' cast-expression
108/// multiplicative-expression '%' cast-expression
109///
110/// additive-expression: [C99 6.5.6]
111/// multiplicative-expression
112/// additive-expression '+' multiplicative-expression
113/// additive-expression '-' multiplicative-expression
114///
115/// shift-expression: [C99 6.5.7]
116/// additive-expression
117/// shift-expression '<<' additive-expression
118/// shift-expression '>>' additive-expression
119///
120/// relational-expression: [C99 6.5.8]
121/// shift-expression
122/// relational-expression '<' shift-expression
123/// relational-expression '>' shift-expression
124/// relational-expression '<=' shift-expression
125/// relational-expression '>=' shift-expression
126///
127/// equality-expression: [C99 6.5.9]
128/// relational-expression
129/// equality-expression '==' relational-expression
130/// equality-expression '!=' relational-expression
131///
132/// AND-expression: [C99 6.5.10]
133/// equality-expression
134/// AND-expression '&' equality-expression
135///
136/// exclusive-OR-expression: [C99 6.5.11]
137/// AND-expression
138/// exclusive-OR-expression '^' AND-expression
139///
140/// inclusive-OR-expression: [C99 6.5.12]
141/// exclusive-OR-expression
142/// inclusive-OR-expression '|' exclusive-OR-expression
143///
144/// logical-AND-expression: [C99 6.5.13]
145/// inclusive-OR-expression
146/// logical-AND-expression '&&' inclusive-OR-expression
147///
148/// logical-OR-expression: [C99 6.5.14]
149/// logical-AND-expression
150/// logical-OR-expression '||' logical-AND-expression
151///
152/// conditional-expression: [C99 6.5.15]
153/// logical-OR-expression
154/// logical-OR-expression '?' expression ':' conditional-expression
155/// [GNU] logical-OR-expression '?' ':' conditional-expression
156///
157/// assignment-expression: [C99 6.5.16]
158/// conditional-expression
159/// unary-expression assignment-operator assignment-expression
160///
161/// assignment-operator: one of
162/// = *= /= %= += -= <<= >>= &= ^= |=
163///
164/// expression: [C99 6.5.17]
165/// assignment-expression
166/// expression ',' assignment-expression
167///
168Parser::ExprResult Parser::ParseExpression() {
169 ExprResult LHS = ParseCastExpression(false);
170 if (LHS.isInvalid) return LHS;
171
172 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
173}
174
175/// ParseAssignmentExpression - Parse an expr that doesn't include commas.
176///
177Parser::ExprResult Parser::ParseAssignmentExpression() {
178 ExprResult LHS = ParseCastExpression(false);
179 if (LHS.isInvalid) return LHS;
180
181 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
182}
183
184Parser::ExprResult Parser::ParseConstantExpression() {
185 ExprResult LHS = ParseCastExpression(false);
186 if (LHS.isInvalid) return LHS;
187
188 // TODO: Validate that this is a constant expr!
189 return ParseRHSOfBinaryExpression(LHS, prec::Conditional);
190}
191
192/// ParseExpressionWithLeadingIdentifier - This special purpose method is used
193/// in contexts where we have already consumed an identifier (which we saved in
194/// 'IdTok'), then discovered that the identifier was really the leading token
195/// of part of an expression. For example, in "A[1]+B", we consumed "A" (which
196/// is now in 'IdTok') and the current token is "[".
197Parser::ExprResult Parser::
Chris Lattnerd2177732007-07-20 16:59:19 +0000198ParseExpressionWithLeadingIdentifier(const Token &IdTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000199 // We know that 'IdTok' must correspond to this production:
200 // primary-expression: identifier
201
202 // Let the actions module handle the identifier.
203 ExprResult Res = Actions.ParseIdentifierExpr(CurScope, IdTok.getLocation(),
204 *IdTok.getIdentifierInfo(),
205 Tok.getKind() == tok::l_paren);
206
207 // Because we have to parse an entire cast-expression before starting the
208 // ParseRHSOfBinaryExpression method (which parses any trailing binops), we
209 // need to handle the 'postfix-expression' rules. We do this by invoking
210 // ParsePostfixExpressionSuffix to consume any postfix-expression suffixes:
211 Res = ParsePostfixExpressionSuffix(Res);
212 if (Res.isInvalid) return Res;
213
214 // At this point, the "A[1]" part of "A[1]+B" has been consumed. Once this is
215 // done, we know we don't have to do anything for cast-expression, because the
216 // only non-postfix-expression production starts with a '(' token, and we know
217 // we have an identifier. As such, we can invoke ParseRHSOfBinaryExpression
218 // to consume any trailing operators (e.g. "+" in this example) and connected
219 // chunks of the expression.
220 return ParseRHSOfBinaryExpression(Res, prec::Comma);
221}
222
223/// ParseExpressionWithLeadingIdentifier - This special purpose method is used
224/// in contexts where we have already consumed an identifier (which we saved in
225/// 'IdTok'), then discovered that the identifier was really the leading token
226/// of part of an assignment-expression. For example, in "A[1]+B", we consumed
227/// "A" (which is now in 'IdTok') and the current token is "[".
228Parser::ExprResult Parser::
Chris Lattnerd2177732007-07-20 16:59:19 +0000229ParseAssignmentExprWithLeadingIdentifier(const Token &IdTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000230 // We know that 'IdTok' must correspond to this production:
231 // primary-expression: identifier
232
233 // Let the actions module handle the identifier.
234 ExprResult Res = Actions.ParseIdentifierExpr(CurScope, IdTok.getLocation(),
235 *IdTok.getIdentifierInfo(),
236 Tok.getKind() == tok::l_paren);
237
238 // Because we have to parse an entire cast-expression before starting the
239 // ParseRHSOfBinaryExpression method (which parses any trailing binops), we
240 // need to handle the 'postfix-expression' rules. We do this by invoking
241 // ParsePostfixExpressionSuffix to consume any postfix-expression suffixes:
242 Res = ParsePostfixExpressionSuffix(Res);
243 if (Res.isInvalid) return Res;
244
245 // At this point, the "A[1]" part of "A[1]+B" has been consumed. Once this is
246 // done, we know we don't have to do anything for cast-expression, because the
247 // only non-postfix-expression production starts with a '(' token, and we know
248 // we have an identifier. As such, we can invoke ParseRHSOfBinaryExpression
249 // to consume any trailing operators (e.g. "+" in this example) and connected
250 // chunks of the expression.
251 return ParseRHSOfBinaryExpression(Res, prec::Assignment);
252}
253
254
255/// ParseAssignmentExpressionWithLeadingStar - This special purpose method is
256/// used in contexts where we have already consumed a '*' (which we saved in
257/// 'StarTok'), then discovered that the '*' was really the leading token of an
258/// expression. For example, in "*(int*)P+B", we consumed "*" (which is
259/// now in 'StarTok') and the current token is "(".
260Parser::ExprResult Parser::
Chris Lattnerd2177732007-07-20 16:59:19 +0000261ParseAssignmentExpressionWithLeadingStar(const Token &StarTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000262 // We know that 'StarTok' must correspond to this production:
263 // unary-expression: unary-operator cast-expression
264 // where 'unary-operator' is '*'.
265
266 // Parse the cast-expression that follows the '*'. This will parse the
267 // "*(int*)P" part of "*(int*)P+B".
268 ExprResult Res = ParseCastExpression(false);
269 if (Res.isInvalid) return Res;
270
271 // Combine StarTok + Res to get the new AST for the combined expression..
272 Res = Actions.ParseUnaryOp(StarTok.getLocation(), tok::star, Res.Val);
273 if (Res.isInvalid) return Res;
274
275
276 // We have to parse an entire cast-expression before starting the
277 // ParseRHSOfBinaryExpression method (which parses any trailing binops). Since
278 // we know that the only production above us is the cast-expression
279 // production, and because the only alternative productions start with a '('
280 // token (we know we had a '*'), there is no work to do to get a whole
281 // cast-expression.
282
283 // At this point, the "*(int*)P" part of "*(int*)P+B" has been consumed. Once
284 // this is done, we can invoke ParseRHSOfBinaryExpression to consume any
285 // trailing operators (e.g. "+" in this example) and connected chunks of the
286 // assignment-expression.
287 return ParseRHSOfBinaryExpression(Res, prec::Assignment);
288}
289
290
291/// ParseRHSOfBinaryExpression - Parse a binary expression that starts with
292/// LHS and has a precedence of at least MinPrec.
293Parser::ExprResult
294Parser::ParseRHSOfBinaryExpression(ExprResult LHS, unsigned MinPrec) {
295 unsigned NextTokPrec = getBinOpPrecedence(Tok.getKind());
296 SourceLocation ColonLoc;
297
298 while (1) {
299 // If this token has a lower precedence than we are allowed to parse (e.g.
300 // because we are called recursively, or because the token is not a binop),
301 // then we are done!
302 if (NextTokPrec < MinPrec)
303 return LHS;
304
305 // Consume the operator, saving the operator token for error reporting.
Chris Lattnerd2177732007-07-20 16:59:19 +0000306 Token OpToken = Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000307 ConsumeToken();
308
309 // Special case handling for the ternary operator.
310 ExprResult TernaryMiddle(true);
311 if (NextTokPrec == prec::Conditional) {
312 if (Tok.getKind() != tok::colon) {
313 // Handle this production specially:
314 // logical-OR-expression '?' expression ':' conditional-expression
315 // In particular, the RHS of the '?' is 'expression', not
316 // 'logical-OR-expression' as we might expect.
317 TernaryMiddle = ParseExpression();
318 if (TernaryMiddle.isInvalid) return TernaryMiddle;
319 } else {
320 // Special case handling of "X ? Y : Z" where Y is empty:
321 // logical-OR-expression '?' ':' conditional-expression [GNU]
322 TernaryMiddle = ExprResult(false);
323 Diag(Tok, diag::ext_gnu_conditional_expr);
324 }
325
326 if (Tok.getKind() != tok::colon) {
327 Diag(Tok, diag::err_expected_colon);
328 Diag(OpToken, diag::err_matching, "?");
329 return ExprResult(true);
330 }
331
332 // Eat the colon.
333 ColonLoc = ConsumeToken();
334 }
335
336 // Parse another leaf here for the RHS of the operator.
337 ExprResult RHS = ParseCastExpression(false);
338 if (RHS.isInvalid) return RHS;
339
340 // Remember the precedence of this operator and get the precedence of the
341 // operator immediately to the right of the RHS.
342 unsigned ThisPrec = NextTokPrec;
343 NextTokPrec = getBinOpPrecedence(Tok.getKind());
344
345 // Assignment and conditional expressions are right-associative.
346 bool isRightAssoc = NextTokPrec == prec::Conditional ||
347 NextTokPrec == prec::Assignment;
348
349 // Get the precedence of the operator to the right of the RHS. If it binds
350 // more tightly with RHS than we do, evaluate it completely first.
351 if (ThisPrec < NextTokPrec ||
352 (ThisPrec == NextTokPrec && isRightAssoc)) {
353 // If this is left-associative, only parse things on the RHS that bind
354 // more tightly than the current operator. If it is left-associative, it
355 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
356 // A=(B=(C=D)), where each paren is a level of recursion here.
357 RHS = ParseRHSOfBinaryExpression(RHS, ThisPrec + !isRightAssoc);
358 if (RHS.isInvalid) return RHS;
359
360 NextTokPrec = getBinOpPrecedence(Tok.getKind());
361 }
362 assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
363
364 // Combine the LHS and RHS into the LHS (e.g. build AST).
365 if (TernaryMiddle.isInvalid)
366 LHS = Actions.ParseBinOp(OpToken.getLocation(), OpToken.getKind(),
367 LHS.Val, RHS.Val);
368 else
369 LHS = Actions.ParseConditionalOp(OpToken.getLocation(), ColonLoc,
370 LHS.Val, TernaryMiddle.Val, RHS.Val);
371 }
372}
373
374/// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
375/// true, parse a unary-expression.
376///
377/// cast-expression: [C99 6.5.4]
378/// unary-expression
379/// '(' type-name ')' cast-expression
380///
381/// unary-expression: [C99 6.5.3]
382/// postfix-expression
383/// '++' unary-expression
384/// '--' unary-expression
385/// unary-operator cast-expression
386/// 'sizeof' unary-expression
387/// 'sizeof' '(' type-name ')'
388/// [GNU] '__alignof' unary-expression
389/// [GNU] '__alignof' '(' type-name ')'
390/// [GNU] '&&' identifier
391///
392/// unary-operator: one of
393/// '&' '*' '+' '-' '~' '!'
394/// [GNU] '__extension__' '__real' '__imag'
395///
396/// primary-expression: [C99 6.5.1]
397/// identifier
398/// constant
399/// string-literal
400/// [C++] boolean-literal [C++ 2.13.5]
401/// '(' expression ')'
402/// '__func__' [C99 6.4.2.2]
403/// [GNU] '__FUNCTION__'
404/// [GNU] '__PRETTY_FUNCTION__'
405/// [GNU] '(' compound-statement ')'
406/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
407/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
408/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
409/// assign-expr ')'
410/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
411/// [OBC] '[' objc-receiver objc-message-args ']' [TODO]
412/// [OBC] '@selector' '(' objc-selector-arg ')' [TODO]
413/// [OBC] '@protocol' '(' identifier ')' [TODO]
414/// [OBC] '@encode' '(' type-name ')' [TODO]
Reid Spencer5f016e22007-07-11 17:01:13 +0000415/// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
416/// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
417/// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
418/// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
419///
420/// constant: [C99 6.4.4]
421/// integer-constant
422/// floating-constant
423/// enumeration-constant -> identifier
424/// character-constant
425///
426Parser::ExprResult Parser::ParseCastExpression(bool isUnaryExpression) {
427 ExprResult Res;
428 tok::TokenKind SavedKind = Tok.getKind();
429
430 // This handles all of cast-expression, unary-expression, postfix-expression,
431 // and primary-expression. We handle them together like this for efficiency
432 // and to simplify handling of an expression starting with a '(' token: which
433 // may be one of a parenthesized expression, cast-expression, compound literal
434 // expression, or statement expression.
435 //
436 // If the parsed tokens consist of a primary-expression, the cases below
437 // call ParsePostfixExpressionSuffix to handle the postfix expression
438 // suffixes. Cases that cannot be followed by postfix exprs should
439 // return without invoking ParsePostfixExpressionSuffix.
440 switch (SavedKind) {
441 case tok::l_paren: {
442 // If this expression is limited to being a unary-expression, the parent can
443 // not start a cast expression.
444 ParenParseOption ParenExprType =
445 isUnaryExpression ? CompoundLiteral : CastExpr;
446 TypeTy *CastTy;
447 SourceLocation LParenLoc = Tok.getLocation();
448 SourceLocation RParenLoc;
449 Res = ParseParenExpression(ParenExprType, CastTy, RParenLoc);
450 if (Res.isInvalid) return Res;
451
452 switch (ParenExprType) {
453 case SimpleExpr: break; // Nothing else to do.
454 case CompoundStmt: break; // Nothing else to do.
455 case CompoundLiteral:
456 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
457 // postfix-expression exist, parse them now.
458 break;
459 case CastExpr:
460 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. Parse
461 // the cast-expression that follows it next.
462 // TODO: For cast expression with CastTy.
463 Res = ParseCastExpression(false);
464 if (!Res.isInvalid)
465 Res = Actions.ParseCastExpr(LParenLoc, CastTy, RParenLoc, Res.Val);
466 return Res;
467 }
468
469 // These can be followed by postfix-expr pieces.
470 return ParsePostfixExpressionSuffix(Res);
471 }
472
473 // primary-expression
474 case tok::numeric_constant:
475 // constant: integer-constant
476 // constant: floating-constant
477
478 Res = Actions.ParseNumericConstant(Tok);
479 ConsumeToken();
480
481 // These can be followed by postfix-expr pieces.
482 return ParsePostfixExpressionSuffix(Res);
483
484 case tok::kw_true:
485 case tok::kw_false:
486 return ParseCXXBoolLiteral();
487
488 case tok::identifier: { // primary-expression: identifier
489 // constant: enumeration-constant
490 // Consume the identifier so that we can see if it is followed by a '('.
491 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
492 // need to know whether or not this identifier is a function designator or
493 // not.
494 IdentifierInfo &II = *Tok.getIdentifierInfo();
495 SourceLocation L = ConsumeToken();
496 Res = Actions.ParseIdentifierExpr(CurScope, L, II,
497 Tok.getKind() == tok::l_paren);
498 // These can be followed by postfix-expr pieces.
499 return ParsePostfixExpressionSuffix(Res);
500 }
501 case tok::char_constant: // constant: character-constant
502 Res = Actions.ParseCharacterConstant(Tok);
503 ConsumeToken();
504 // These can be followed by postfix-expr pieces.
505 return ParsePostfixExpressionSuffix(Res);
506 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
507 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
508 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Anders Carlsson22742662007-07-21 05:21:51 +0000509 Res = Actions.ParsePreDefinedExpr(Tok.getLocation(), SavedKind);
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 ConsumeToken();
511 // These can be followed by postfix-expr pieces.
512 return ParsePostfixExpressionSuffix(Res);
513 case tok::string_literal: // primary-expression: string-literal
514 case tok::wide_string_literal:
515 Res = ParseStringLiteralExpression();
516 if (Res.isInvalid) return Res;
517 // This can be followed by postfix-expr pieces (e.g. "foo"[1]).
518 return ParsePostfixExpressionSuffix(Res);
519 case tok::kw___builtin_va_arg:
520 case tok::kw___builtin_offsetof:
521 case tok::kw___builtin_choose_expr:
522 case tok::kw___builtin_types_compatible_p:
523 return ParseBuiltinPrimaryExpression();
524 case tok::plusplus: // unary-expression: '++' unary-expression
525 case tok::minusminus: { // unary-expression: '--' unary-expression
526 SourceLocation SavedLoc = ConsumeToken();
527 Res = ParseCastExpression(true);
528 if (!Res.isInvalid)
529 Res = Actions.ParseUnaryOp(SavedLoc, SavedKind, Res.Val);
530 return Res;
531 }
532 case tok::amp: // unary-expression: '&' cast-expression
533 case tok::star: // unary-expression: '*' cast-expression
534 case tok::plus: // unary-expression: '+' cast-expression
535 case tok::minus: // unary-expression: '-' cast-expression
536 case tok::tilde: // unary-expression: '~' cast-expression
537 case tok::exclaim: // unary-expression: '!' cast-expression
538 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
539 case tok::kw___imag: // unary-expression: '__imag' cast-expression [GNU]
540 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
Chris Lattnerab18c4c2007-07-24 16:58:17 +0000541 // FIXME: Extension should silence extwarns in subexpressions.
Reid Spencer5f016e22007-07-11 17:01:13 +0000542 SourceLocation SavedLoc = ConsumeToken();
543 Res = ParseCastExpression(false);
544 if (!Res.isInvalid)
545 Res = Actions.ParseUnaryOp(SavedLoc, SavedKind, Res.Val);
546 return Res;
547 }
548 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
549 // unary-expression: 'sizeof' '(' type-name ')'
550 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
551 // unary-expression: '__alignof' '(' type-name ')'
552 return ParseSizeofAlignofExpression();
553 case tok::ampamp: { // unary-expression: '&&' identifier
554 SourceLocation AmpAmpLoc = ConsumeToken();
555 if (Tok.getKind() != tok::identifier) {
556 Diag(Tok, diag::err_expected_ident);
557 return ExprResult(true);
558 }
559
560 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
561 Res = Actions.ParseAddrLabel(AmpAmpLoc, Tok.getLocation(),
562 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:
570 return ParseCXXCasts();
Anders Carlsson55085182007-08-21 17:43:55 +0000571 case tok::at:
572 return ParseObjCExpression();
Reid Spencer5f016e22007-07-11 17:01:13 +0000573 default:
574 Diag(Tok, diag::err_expected_expression);
575 return ExprResult(true);
576 }
577
578 // unreachable.
579 abort();
580}
581
582/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
583/// is parsed, this method parses any suffixes that apply.
584///
585/// postfix-expression: [C99 6.5.2]
586/// primary-expression
587/// postfix-expression '[' expression ']'
588/// postfix-expression '(' argument-expression-list[opt] ')'
589/// postfix-expression '.' identifier
590/// postfix-expression '->' identifier
591/// postfix-expression '++'
592/// postfix-expression '--'
593/// '(' type-name ')' '{' initializer-list '}'
594/// '(' type-name ')' '{' initializer-list ',' '}'
595///
596/// argument-expression-list: [C99 6.5.2]
597/// argument-expression
598/// argument-expression-list ',' assignment-expression
599///
600Parser::ExprResult Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
601
602 // Now that the primary-expression piece of the postfix-expression has been
603 // parsed, see if there are any postfix-expression pieces here.
604 SourceLocation Loc;
605 while (1) {
606 switch (Tok.getKind()) {
607 default: // Not a postfix-expression suffix.
608 return LHS;
609 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
610 Loc = ConsumeBracket();
611 ExprResult Idx = ParseExpression();
612
613 SourceLocation RLoc = Tok.getLocation();
614
615 if (!LHS.isInvalid && !Idx.isInvalid && Tok.getKind() == tok::r_square)
616 LHS = Actions.ParseArraySubscriptExpr(LHS.Val, Loc, Idx.Val, RLoc);
617 else
618 LHS = ExprResult(true);
619
620 // Match the ']'.
621 MatchRHSPunctuation(tok::r_square, Loc);
622 break;
623 }
624
625 case tok::l_paren: { // p-e: p-e '(' argument-expression-list[opt] ')'
626 llvm::SmallVector<ExprTy*, 8> ArgExprs;
627 llvm::SmallVector<SourceLocation, 8> CommaLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000628
629 Loc = ConsumeParen();
630
631 if (Tok.getKind() != tok::r_paren) {
632 while (1) {
633 ExprResult ArgExpr = ParseAssignmentExpression();
634 if (ArgExpr.isInvalid) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000635 SkipUntil(tok::r_paren);
Chris Lattner2ff54262007-07-21 05:18:12 +0000636 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000637 } else
638 ArgExprs.push_back(ArgExpr.Val);
639
640 if (Tok.getKind() != tok::comma)
641 break;
642 // Move to the next argument, remember where the comma was.
643 CommaLocs.push_back(ConsumeToken());
644 }
645 }
646
647 // Match the ')'.
Chris Lattner2ff54262007-07-21 05:18:12 +0000648 if (!LHS.isInvalid && Tok.getKind() == tok::r_paren) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000649 assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&&
650 "Unexpected number of commas!");
651 LHS = Actions.ParseCallExpr(LHS.Val, Loc, &ArgExprs[0], ArgExprs.size(),
652 &CommaLocs[0], Tok.getLocation());
653 }
654
Chris Lattner2ff54262007-07-21 05:18:12 +0000655 MatchRHSPunctuation(tok::r_paren, Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000656 break;
657 }
658 case tok::arrow: // postfix-expression: p-e '->' identifier
659 case tok::period: { // postfix-expression: p-e '.' identifier
660 tok::TokenKind OpKind = Tok.getKind();
661 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
662
663 if (Tok.getKind() != tok::identifier) {
664 Diag(Tok, diag::err_expected_ident);
665 return ExprResult(true);
666 }
667
668 if (!LHS.isInvalid)
669 LHS = Actions.ParseMemberReferenceExpr(LHS.Val, OpLoc, OpKind,
670 Tok.getLocation(),
671 *Tok.getIdentifierInfo());
672 ConsumeToken();
673 break;
674 }
675 case tok::plusplus: // postfix-expression: postfix-expression '++'
676 case tok::minusminus: // postfix-expression: postfix-expression '--'
677 if (!LHS.isInvalid)
678 LHS = Actions.ParsePostfixUnaryOp(Tok.getLocation(), Tok.getKind(),
679 LHS.Val);
680 ConsumeToken();
681 break;
682 }
683 }
684}
685
686
687/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression.
688/// unary-expression: [C99 6.5.3]
689/// 'sizeof' unary-expression
690/// 'sizeof' '(' type-name ')'
691/// [GNU] '__alignof' unary-expression
692/// [GNU] '__alignof' '(' type-name ')'
693Parser::ExprResult Parser::ParseSizeofAlignofExpression() {
694 assert((Tok.getKind() == tok::kw_sizeof ||
695 Tok.getKind() == tok::kw___alignof) &&
696 "Not a sizeof/alignof expression!");
Chris Lattnerd2177732007-07-20 16:59:19 +0000697 Token OpTok = Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000698 ConsumeToken();
699
700 // If the operand doesn't start with an '(', it must be an expression.
701 ExprResult Operand;
702 if (Tok.getKind() != tok::l_paren) {
703 Operand = ParseCastExpression(true);
704 } else {
705 // If it starts with a '(', we know that it is either a parenthesized
706 // type-name, or it is a unary-expression that starts with a compound
707 // literal, or starts with a primary-expression that is a parenthesized
708 // expression.
709 ParenParseOption ExprType = CastExpr;
710 TypeTy *CastTy;
711 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
712 Operand = ParseParenExpression(ExprType, CastTy, RParenLoc);
713
714 // If ParseParenExpression parsed a '(typename)' sequence only, the this is
715 // sizeof/alignof a type. Otherwise, it is sizeof/alignof an expression.
716 if (ExprType == CastExpr) {
717 return Actions.ParseSizeOfAlignOfTypeExpr(OpTok.getLocation(),
718 OpTok.getKind() == tok::kw_sizeof,
719 LParenLoc, CastTy, RParenLoc);
720 }
721 }
722
723 // If we get here, the operand to the sizeof/alignof was an expresion.
724 if (!Operand.isInvalid)
725 Operand = Actions.ParseUnaryOp(OpTok.getLocation(), OpTok.getKind(),
726 Operand.Val);
727 return Operand;
728}
729
730/// ParseBuiltinPrimaryExpression
731///
732/// primary-expression: [C99 6.5.1]
733/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
734/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
735/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
736/// assign-expr ')'
737/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
738///
739/// [GNU] offsetof-member-designator:
740/// [GNU] identifier
741/// [GNU] offsetof-member-designator '.' identifier
742/// [GNU] offsetof-member-designator '[' expression ']'
743///
744Parser::ExprResult Parser::ParseBuiltinPrimaryExpression() {
745 ExprResult Res(false);
746 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
747
748 tok::TokenKind T = Tok.getKind();
749 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
750
751 // All of these start with an open paren.
752 if (Tok.getKind() != tok::l_paren) {
753 Diag(Tok, diag::err_expected_lparen_after, BuiltinII->getName());
754 return ExprResult(true);
755 }
756
757 SourceLocation LParenLoc = ConsumeParen();
758 // TODO: Build AST.
759
760 switch (T) {
761 default: assert(0 && "Not a builtin primary expression!");
762 case tok::kw___builtin_va_arg:
763 Res = ParseAssignmentExpression();
764 if (Res.isInvalid) {
765 SkipUntil(tok::r_paren);
766 return Res;
767 }
768
769 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
770 return ExprResult(true);
771
772 ParseTypeName();
773 break;
774
775 case tok::kw___builtin_offsetof:
776 ParseTypeName();
777
778 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
779 return ExprResult(true);
780
781 // We must have at least one identifier here.
782 if (ExpectAndConsume(tok::identifier, diag::err_expected_ident, "",
783 tok::r_paren))
784 return ExprResult(true);
785
786 while (1) {
787 if (Tok.getKind() == tok::period) {
788 // offsetof-member-designator: offsetof-member-designator '.' identifier
789 ConsumeToken();
790
791 if (ExpectAndConsume(tok::identifier, diag::err_expected_ident, "",
792 tok::r_paren))
793 return ExprResult(true);
794 } else if (Tok.getKind() == tok::l_square) {
795 // offsetof-member-designator: offsetof-member-design '[' expression ']'
796 SourceLocation LSquareLoc = ConsumeBracket();
797 Res = ParseExpression();
798 if (Res.isInvalid) {
799 SkipUntil(tok::r_paren);
800 return Res;
801 }
802
803 MatchRHSPunctuation(tok::r_square, LSquareLoc);
804 } else {
805 break;
806 }
807 }
808 break;
Steve Naroffd04fdd52007-08-03 21:21:27 +0000809 case tok::kw___builtin_choose_expr: {
810 ExprResult Cond = ParseAssignmentExpression();
811 if (Cond.isInvalid) {
812 SkipUntil(tok::r_paren);
813 return Cond;
814 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000815 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
816 return ExprResult(true);
817
Steve Naroffd04fdd52007-08-03 21:21:27 +0000818 ExprResult Expr1 = ParseAssignmentExpression();
819 if (Expr1.isInvalid) {
820 SkipUntil(tok::r_paren);
821 return Expr1;
822 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000823 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
824 return ExprResult(true);
825
Steve Naroffd04fdd52007-08-03 21:21:27 +0000826 ExprResult Expr2 = ParseAssignmentExpression();
827 if (Expr2.isInvalid) {
828 SkipUntil(tok::r_paren);
829 return Expr2;
830 }
831 if (Tok.getKind() != tok::r_paren) {
832 Diag(Tok, diag::err_expected_rparen);
833 return ExprResult(true);
834 }
835 return Actions.ParseChooseExpr(StartLoc, Cond.Val, Expr1.Val, Expr2.Val,
836 ConsumeParen());
837 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000838 case tok::kw___builtin_types_compatible_p:
Steve Naroff363bcff2007-08-01 23:45:51 +0000839 TypeTy *Ty1 = ParseTypeName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000840
841 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
842 return ExprResult(true);
843
Steve Naroff363bcff2007-08-01 23:45:51 +0000844 TypeTy *Ty2 = ParseTypeName();
845
846 if (Tok.getKind() != tok::r_paren) {
847 Diag(Tok, diag::err_expected_rparen);
848 return ExprResult(true);
849 }
850 return Actions.ParseTypesCompatibleExpr(StartLoc, Ty1, Ty2, ConsumeParen());
Reid Spencer5f016e22007-07-11 17:01:13 +0000851 }
852
853 MatchRHSPunctuation(tok::r_paren, LParenLoc);
854
855 // These can be followed by postfix-expr pieces because they are
856 // primary-expressions.
857 return ParsePostfixExpressionSuffix(Res);
858}
859
860/// ParseParenExpression - This parses the unit that starts with a '(' token,
861/// based on what is allowed by ExprType. The actual thing parsed is returned
862/// in ExprType.
863///
864/// primary-expression: [C99 6.5.1]
865/// '(' expression ')'
866/// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
867/// postfix-expression: [C99 6.5.2]
868/// '(' type-name ')' '{' initializer-list '}'
869/// '(' type-name ')' '{' initializer-list ',' '}'
870/// cast-expression: [C99 6.5.4]
871/// '(' type-name ')' cast-expression
872///
873Parser::ExprResult Parser::ParseParenExpression(ParenParseOption &ExprType,
874 TypeTy *&CastTy,
875 SourceLocation &RParenLoc) {
876 assert(Tok.getKind() == tok::l_paren && "Not a paren expr!");
877 SourceLocation OpenLoc = ConsumeParen();
Chris Lattnerab18c4c2007-07-24 16:58:17 +0000878 ExprResult Result(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000879 CastTy = 0;
880
881 if (ExprType >= CompoundStmt && Tok.getKind() == tok::l_brace &&
882 !getLang().NoExtensions) {
883 Diag(Tok, diag::ext_gnu_statement_expr);
Chris Lattnerab18c4c2007-07-24 16:58:17 +0000884 Parser::StmtResult Stmt = ParseCompoundStatement();
Reid Spencer5f016e22007-07-11 17:01:13 +0000885 ExprType = CompoundStmt;
Chris Lattnerab18c4c2007-07-24 16:58:17 +0000886
887 // If the substmt parsed correctly, build the AST node.
888 if (!Stmt.isInvalid && Tok.getKind() == tok::r_paren)
889 Result = Actions.ParseStmtExpr(OpenLoc, Stmt.Val, Tok.getLocation());
890
Reid Spencer5f016e22007-07-11 17:01:13 +0000891 } else if (ExprType >= CompoundLiteral && isTypeSpecifierQualifier()) {
892 // Otherwise, this is a compound literal expression or cast expression.
893 TypeTy *Ty = ParseTypeName();
894
895 // Match the ')'.
896 if (Tok.getKind() == tok::r_paren)
897 RParenLoc = ConsumeParen();
898 else
899 MatchRHSPunctuation(tok::r_paren, OpenLoc);
900
901 if (Tok.getKind() == tok::l_brace) {
902 if (!getLang().C99) // Compound literals don't exist in C90.
903 Diag(OpenLoc, diag::ext_c99_compound_literal);
904 Result = ParseInitializer();
905 ExprType = CompoundLiteral;
Steve Naroff4aa88f82007-07-19 01:06:55 +0000906 if (!Result.isInvalid)
907 return Actions.ParseCompoundLiteral(OpenLoc, Ty, RParenLoc, Result.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000908 } else if (ExprType == CastExpr) {
909 // Note that this doesn't parse the subsequence cast-expression, it just
910 // returns the parsed type to the callee.
911 ExprType = CastExpr;
912 CastTy = Ty;
913 return ExprResult(false);
914 } else {
915 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
916 return ExprResult(true);
917 }
918 return Result;
919 } else {
920 Result = ParseExpression();
921 ExprType = SimpleExpr;
922 if (!Result.isInvalid && Tok.getKind() == tok::r_paren)
923 Result = Actions.ParseParenExpr(OpenLoc, Tok.getLocation(), Result.Val);
924 }
925
926 // Match the ')'.
927 if (Result.isInvalid)
928 SkipUntil(tok::r_paren);
929 else {
930 if (Tok.getKind() == tok::r_paren)
931 RParenLoc = ConsumeParen();
932 else
933 MatchRHSPunctuation(tok::r_paren, OpenLoc);
934 }
935
936 return Result;
937}
938
939/// ParseStringLiteralExpression - This handles the various token types that
940/// form string literals, and also handles string concatenation [C99 5.1.1.2,
941/// translation phase #6].
942///
943/// primary-expression: [C99 6.5.1]
944/// string-literal
945Parser::ExprResult Parser::ParseStringLiteralExpression() {
946 assert(isTokenStringLiteral() && "Not a string literal!");
947
948 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
949 // considered to be strings for concatenation purposes.
Chris Lattnerd2177732007-07-20 16:59:19 +0000950 llvm::SmallVector<Token, 4> StringToks;
Reid Spencer5f016e22007-07-11 17:01:13 +0000951
952 do {
953 StringToks.push_back(Tok);
954 ConsumeStringToken();
955 } while (isTokenStringLiteral());
956
957 // Pass the set of string tokens, ready for concatenation, to the actions.
958 return Actions.ParseStringLiteral(&StringToks[0], StringToks.size());
959}