blob: 1b261aae266255151bbbab97693d84fafefecfac [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
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000175/// This routine is called when the '@' is seen and consumed.
176/// Current token is an Identifier and is not a 'try'. This
Chris Lattnerc97c2042007-10-03 22:03:06 +0000177/// routine is necessary to disambiguate @try-statement from,
178/// for example, @encode-expression.
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000179///
Fariborz Jahanianb384d322007-10-04 20:19:06 +0000180Parser::ExprResult Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000181 ExprResult LHS = ParseObjCExpression(AtLoc);
182 if (LHS.isInvalid) return LHS;
183
184 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
185}
186
Reid Spencer5f016e22007-07-11 17:01:13 +0000187/// ParseAssignmentExpression - Parse an expr that doesn't include commas.
188///
189Parser::ExprResult Parser::ParseAssignmentExpression() {
190 ExprResult LHS = ParseCastExpression(false);
191 if (LHS.isInvalid) return LHS;
192
193 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
194}
195
196Parser::ExprResult Parser::ParseConstantExpression() {
197 ExprResult LHS = ParseCastExpression(false);
198 if (LHS.isInvalid) return LHS;
199
200 // TODO: Validate that this is a constant expr!
201 return ParseRHSOfBinaryExpression(LHS, prec::Conditional);
202}
203
204/// ParseExpressionWithLeadingIdentifier - This special purpose method is used
205/// in contexts where we have already consumed an identifier (which we saved in
206/// 'IdTok'), then discovered that the identifier was really the leading token
207/// of part of an expression. For example, in "A[1]+B", we consumed "A" (which
208/// is now in 'IdTok') and the current token is "[".
209Parser::ExprResult Parser::
Chris Lattnerd2177732007-07-20 16:59:19 +0000210ParseExpressionWithLeadingIdentifier(const Token &IdTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000211 // We know that 'IdTok' must correspond to this production:
212 // primary-expression: identifier
213
214 // Let the actions module handle the identifier.
Steve Naroff08d92e42007-09-15 18:49:24 +0000215 ExprResult Res = Actions.ActOnIdentifierExpr(CurScope, IdTok.getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000216 *IdTok.getIdentifierInfo(),
217 Tok.getKind() == tok::l_paren);
218
219 // Because we have to parse an entire cast-expression before starting the
220 // ParseRHSOfBinaryExpression method (which parses any trailing binops), we
221 // need to handle the 'postfix-expression' rules. We do this by invoking
222 // ParsePostfixExpressionSuffix to consume any postfix-expression suffixes:
223 Res = ParsePostfixExpressionSuffix(Res);
224 if (Res.isInvalid) return Res;
225
226 // At this point, the "A[1]" part of "A[1]+B" has been consumed. Once this is
227 // done, we know we don't have to do anything for cast-expression, because the
228 // only non-postfix-expression production starts with a '(' token, and we know
229 // we have an identifier. As such, we can invoke ParseRHSOfBinaryExpression
230 // to consume any trailing operators (e.g. "+" in this example) and connected
231 // chunks of the expression.
232 return ParseRHSOfBinaryExpression(Res, prec::Comma);
233}
234
235/// ParseExpressionWithLeadingIdentifier - This special purpose method is used
236/// in contexts where we have already consumed an identifier (which we saved in
237/// 'IdTok'), then discovered that the identifier was really the leading token
238/// of part of an assignment-expression. For example, in "A[1]+B", we consumed
239/// "A" (which is now in 'IdTok') and the current token is "[".
240Parser::ExprResult Parser::
Chris Lattnerd2177732007-07-20 16:59:19 +0000241ParseAssignmentExprWithLeadingIdentifier(const Token &IdTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000242 // We know that 'IdTok' must correspond to this production:
243 // primary-expression: identifier
244
245 // Let the actions module handle the identifier.
Steve Naroff08d92e42007-09-15 18:49:24 +0000246 ExprResult Res = Actions.ActOnIdentifierExpr(CurScope, IdTok.getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000247 *IdTok.getIdentifierInfo(),
248 Tok.getKind() == tok::l_paren);
249
250 // Because we have to parse an entire cast-expression before starting the
251 // ParseRHSOfBinaryExpression method (which parses any trailing binops), we
252 // need to handle the 'postfix-expression' rules. We do this by invoking
253 // ParsePostfixExpressionSuffix to consume any postfix-expression suffixes:
254 Res = ParsePostfixExpressionSuffix(Res);
255 if (Res.isInvalid) return Res;
256
257 // At this point, the "A[1]" part of "A[1]+B" has been consumed. Once this is
258 // done, we know we don't have to do anything for cast-expression, because the
259 // only non-postfix-expression production starts with a '(' token, and we know
260 // we have an identifier. As such, we can invoke ParseRHSOfBinaryExpression
261 // to consume any trailing operators (e.g. "+" in this example) and connected
262 // chunks of the expression.
263 return ParseRHSOfBinaryExpression(Res, prec::Assignment);
264}
265
266
267/// ParseAssignmentExpressionWithLeadingStar - This special purpose method is
268/// used in contexts where we have already consumed a '*' (which we saved in
269/// 'StarTok'), then discovered that the '*' was really the leading token of an
270/// expression. For example, in "*(int*)P+B", we consumed "*" (which is
271/// now in 'StarTok') and the current token is "(".
272Parser::ExprResult Parser::
Chris Lattnerd2177732007-07-20 16:59:19 +0000273ParseAssignmentExpressionWithLeadingStar(const Token &StarTok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 // We know that 'StarTok' must correspond to this production:
275 // unary-expression: unary-operator cast-expression
276 // where 'unary-operator' is '*'.
277
278 // Parse the cast-expression that follows the '*'. This will parse the
279 // "*(int*)P" part of "*(int*)P+B".
280 ExprResult Res = ParseCastExpression(false);
281 if (Res.isInvalid) return Res;
282
283 // Combine StarTok + Res to get the new AST for the combined expression..
Steve Narofff69936d2007-09-16 03:34:24 +0000284 Res = Actions.ActOnUnaryOp(StarTok.getLocation(), tok::star, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000285 if (Res.isInvalid) return Res;
286
287
288 // We have to parse an entire cast-expression before starting the
289 // ParseRHSOfBinaryExpression method (which parses any trailing binops). Since
290 // we know that the only production above us is the cast-expression
291 // production, and because the only alternative productions start with a '('
292 // token (we know we had a '*'), there is no work to do to get a whole
293 // cast-expression.
294
295 // At this point, the "*(int*)P" part of "*(int*)P+B" has been consumed. Once
296 // this is done, we can invoke ParseRHSOfBinaryExpression to consume any
297 // trailing operators (e.g. "+" in this example) and connected chunks of the
298 // assignment-expression.
299 return ParseRHSOfBinaryExpression(Res, prec::Assignment);
300}
301
302
303/// ParseRHSOfBinaryExpression - Parse a binary expression that starts with
304/// LHS and has a precedence of at least MinPrec.
305Parser::ExprResult
306Parser::ParseRHSOfBinaryExpression(ExprResult LHS, unsigned MinPrec) {
307 unsigned NextTokPrec = getBinOpPrecedence(Tok.getKind());
308 SourceLocation ColonLoc;
309
310 while (1) {
311 // If this token has a lower precedence than we are allowed to parse (e.g.
312 // because we are called recursively, or because the token is not a binop),
313 // then we are done!
314 if (NextTokPrec < MinPrec)
315 return LHS;
316
317 // Consume the operator, saving the operator token for error reporting.
Chris Lattnerd2177732007-07-20 16:59:19 +0000318 Token OpToken = Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 ConsumeToken();
320
321 // Special case handling for the ternary operator.
322 ExprResult TernaryMiddle(true);
323 if (NextTokPrec == prec::Conditional) {
324 if (Tok.getKind() != tok::colon) {
325 // Handle this production specially:
326 // logical-OR-expression '?' expression ':' conditional-expression
327 // In particular, the RHS of the '?' is 'expression', not
328 // 'logical-OR-expression' as we might expect.
329 TernaryMiddle = ParseExpression();
Chris Lattnerdbd583c2007-08-31 04:58:34 +0000330 if (TernaryMiddle.isInvalid) {
331 Actions.DeleteExpr(LHS.Val);
332 return TernaryMiddle;
333 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 } else {
335 // Special case handling of "X ? Y : Z" where Y is empty:
336 // logical-OR-expression '?' ':' conditional-expression [GNU]
337 TernaryMiddle = ExprResult(false);
338 Diag(Tok, diag::ext_gnu_conditional_expr);
339 }
340
341 if (Tok.getKind() != tok::colon) {
342 Diag(Tok, diag::err_expected_colon);
343 Diag(OpToken, diag::err_matching, "?");
Chris Lattnerdbd583c2007-08-31 04:58:34 +0000344 Actions.DeleteExpr(LHS.Val);
345 Actions.DeleteExpr(TernaryMiddle.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000346 return ExprResult(true);
347 }
348
349 // Eat the colon.
350 ColonLoc = ConsumeToken();
351 }
352
353 // Parse another leaf here for the RHS of the operator.
354 ExprResult RHS = ParseCastExpression(false);
Chris Lattnerdbd583c2007-08-31 04:58:34 +0000355 if (RHS.isInvalid) {
356 Actions.DeleteExpr(LHS.Val);
357 Actions.DeleteExpr(TernaryMiddle.Val);
358 return RHS;
359 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000360
361 // Remember the precedence of this operator and get the precedence of the
362 // operator immediately to the right of the RHS.
363 unsigned ThisPrec = NextTokPrec;
364 NextTokPrec = getBinOpPrecedence(Tok.getKind());
365
366 // Assignment and conditional expressions are right-associative.
367 bool isRightAssoc = NextTokPrec == prec::Conditional ||
368 NextTokPrec == prec::Assignment;
369
370 // Get the precedence of the operator to the right of the RHS. If it binds
371 // more tightly with RHS than we do, evaluate it completely first.
372 if (ThisPrec < NextTokPrec ||
373 (ThisPrec == NextTokPrec && isRightAssoc)) {
374 // If this is left-associative, only parse things on the RHS that bind
375 // more tightly than the current operator. If it is left-associative, it
376 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
377 // A=(B=(C=D)), where each paren is a level of recursion here.
378 RHS = ParseRHSOfBinaryExpression(RHS, ThisPrec + !isRightAssoc);
Chris Lattnerdbd583c2007-08-31 04:58:34 +0000379 if (RHS.isInvalid) {
380 Actions.DeleteExpr(LHS.Val);
381 Actions.DeleteExpr(TernaryMiddle.Val);
382 return RHS;
383 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000384
385 NextTokPrec = getBinOpPrecedence(Tok.getKind());
386 }
387 assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
388
Chris Lattnerd56d6b62007-08-31 05:01:50 +0000389 if (!LHS.isInvalid) {
390 // Combine the LHS and RHS into the LHS (e.g. build AST).
391 if (TernaryMiddle.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000392 LHS = Actions.ActOnBinOp(OpToken.getLocation(), OpToken.getKind(),
Chris Lattnerd56d6b62007-08-31 05:01:50 +0000393 LHS.Val, RHS.Val);
394 else
Steve Narofff69936d2007-09-16 03:34:24 +0000395 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
Chris Lattnerd56d6b62007-08-31 05:01:50 +0000396 LHS.Val, TernaryMiddle.Val, RHS.Val);
397 } else {
398 // We had a semantic error on the LHS. Just free the RHS and continue.
399 Actions.DeleteExpr(TernaryMiddle.Val);
400 Actions.DeleteExpr(RHS.Val);
401 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 }
403}
404
405/// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
406/// true, parse a unary-expression.
407///
408/// cast-expression: [C99 6.5.4]
409/// unary-expression
410/// '(' type-name ')' cast-expression
411///
412/// unary-expression: [C99 6.5.3]
413/// postfix-expression
414/// '++' unary-expression
415/// '--' unary-expression
416/// unary-operator cast-expression
417/// 'sizeof' unary-expression
418/// 'sizeof' '(' type-name ')'
419/// [GNU] '__alignof' unary-expression
420/// [GNU] '__alignof' '(' type-name ')'
421/// [GNU] '&&' identifier
422///
423/// unary-operator: one of
424/// '&' '*' '+' '-' '~' '!'
425/// [GNU] '__extension__' '__real' '__imag'
426///
427/// primary-expression: [C99 6.5.1]
428/// identifier
429/// constant
430/// string-literal
431/// [C++] boolean-literal [C++ 2.13.5]
432/// '(' expression ')'
433/// '__func__' [C99 6.4.2.2]
434/// [GNU] '__FUNCTION__'
435/// [GNU] '__PRETTY_FUNCTION__'
436/// [GNU] '(' compound-statement ')'
437/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
438/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
439/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
440/// assign-expr ')'
441/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
Fariborz Jahanian095ffca2007-09-26 17:03:44 +0000442/// [OBJC] '[' objc-message-expr ']'
Fariborz Jahanian0ccb27d2007-09-05 19:52:07 +0000443/// [OBJC] '@selector' '(' objc-selector-arg ')' [TODO]
Fariborz Jahanian095ffca2007-09-26 17:03:44 +0000444/// [OBJC] '@protocol' '(' identifier ')'
445/// [OBJC] '@encode' '(' type-name ')'
Fariborz Jahanian0ccb27d2007-09-05 19:52:07 +0000446/// [OBJC] objc-string-literal
Reid Spencer5f016e22007-07-11 17:01:13 +0000447/// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
448/// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
449/// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
450/// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
451///
452/// constant: [C99 6.4.4]
453/// integer-constant
454/// floating-constant
455/// enumeration-constant -> identifier
456/// character-constant
457///
458Parser::ExprResult Parser::ParseCastExpression(bool isUnaryExpression) {
459 ExprResult Res;
460 tok::TokenKind SavedKind = Tok.getKind();
461
462 // This handles all of cast-expression, unary-expression, postfix-expression,
463 // and primary-expression. We handle them together like this for efficiency
464 // and to simplify handling of an expression starting with a '(' token: which
465 // may be one of a parenthesized expression, cast-expression, compound literal
466 // expression, or statement expression.
467 //
468 // If the parsed tokens consist of a primary-expression, the cases below
469 // call ParsePostfixExpressionSuffix to handle the postfix expression
470 // suffixes. Cases that cannot be followed by postfix exprs should
471 // return without invoking ParsePostfixExpressionSuffix.
472 switch (SavedKind) {
473 case tok::l_paren: {
474 // If this expression is limited to being a unary-expression, the parent can
475 // not start a cast expression.
476 ParenParseOption ParenExprType =
477 isUnaryExpression ? CompoundLiteral : CastExpr;
478 TypeTy *CastTy;
479 SourceLocation LParenLoc = Tok.getLocation();
480 SourceLocation RParenLoc;
481 Res = ParseParenExpression(ParenExprType, CastTy, RParenLoc);
482 if (Res.isInvalid) return Res;
483
484 switch (ParenExprType) {
485 case SimpleExpr: break; // Nothing else to do.
486 case CompoundStmt: break; // Nothing else to do.
487 case CompoundLiteral:
488 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
489 // postfix-expression exist, parse them now.
490 break;
491 case CastExpr:
492 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. Parse
493 // the cast-expression that follows it next.
494 // TODO: For cast expression with CastTy.
495 Res = ParseCastExpression(false);
496 if (!Res.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000497 Res = Actions.ActOnCastExpr(LParenLoc, CastTy, RParenLoc, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000498 return Res;
499 }
500
501 // These can be followed by postfix-expr pieces.
502 return ParsePostfixExpressionSuffix(Res);
503 }
504
505 // primary-expression
506 case tok::numeric_constant:
507 // constant: integer-constant
508 // constant: floating-constant
509
Steve Narofff69936d2007-09-16 03:34:24 +0000510 Res = Actions.ActOnNumericConstant(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 ConsumeToken();
512
513 // These can be followed by postfix-expr pieces.
514 return ParsePostfixExpressionSuffix(Res);
515
516 case tok::kw_true:
517 case tok::kw_false:
518 return ParseCXXBoolLiteral();
519
520 case tok::identifier: { // primary-expression: identifier
521 // constant: enumeration-constant
522 // Consume the identifier so that we can see if it is followed by a '('.
523 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
524 // need to know whether or not this identifier is a function designator or
525 // not.
526 IdentifierInfo &II = *Tok.getIdentifierInfo();
527 SourceLocation L = ConsumeToken();
Steve Naroff08d92e42007-09-15 18:49:24 +0000528 Res = Actions.ActOnIdentifierExpr(CurScope, L, II,
Reid Spencer5f016e22007-07-11 17:01:13 +0000529 Tok.getKind() == tok::l_paren);
530 // These can be followed by postfix-expr pieces.
531 return ParsePostfixExpressionSuffix(Res);
532 }
533 case tok::char_constant: // constant: character-constant
Steve Narofff69936d2007-09-16 03:34:24 +0000534 Res = Actions.ActOnCharacterConstant(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000535 ConsumeToken();
536 // These can be followed by postfix-expr pieces.
537 return ParsePostfixExpressionSuffix(Res);
538 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
539 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
540 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Steve Narofff69936d2007-09-16 03:34:24 +0000541 Res = Actions.ActOnPreDefinedExpr(Tok.getLocation(), SavedKind);
Reid Spencer5f016e22007-07-11 17:01:13 +0000542 ConsumeToken();
543 // These can be followed by postfix-expr pieces.
544 return ParsePostfixExpressionSuffix(Res);
545 case tok::string_literal: // primary-expression: string-literal
546 case tok::wide_string_literal:
547 Res = ParseStringLiteralExpression();
548 if (Res.isInvalid) return Res;
549 // This can be followed by postfix-expr pieces (e.g. "foo"[1]).
550 return ParsePostfixExpressionSuffix(Res);
551 case tok::kw___builtin_va_arg:
552 case tok::kw___builtin_offsetof:
553 case tok::kw___builtin_choose_expr:
554 case tok::kw___builtin_types_compatible_p:
555 return ParseBuiltinPrimaryExpression();
556 case tok::plusplus: // unary-expression: '++' unary-expression
557 case tok::minusminus: { // unary-expression: '--' unary-expression
558 SourceLocation SavedLoc = ConsumeToken();
559 Res = ParseCastExpression(true);
560 if (!Res.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000561 Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 return Res;
563 }
564 case tok::amp: // unary-expression: '&' cast-expression
565 case tok::star: // unary-expression: '*' cast-expression
566 case tok::plus: // unary-expression: '+' cast-expression
567 case tok::minus: // unary-expression: '-' cast-expression
568 case tok::tilde: // unary-expression: '~' cast-expression
569 case tok::exclaim: // unary-expression: '!' cast-expression
570 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
571 case tok::kw___imag: // unary-expression: '__imag' cast-expression [GNU]
572 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
Chris Lattnerab18c4c2007-07-24 16:58:17 +0000573 // FIXME: Extension should silence extwarns in subexpressions.
Reid Spencer5f016e22007-07-11 17:01:13 +0000574 SourceLocation SavedLoc = ConsumeToken();
575 Res = ParseCastExpression(false);
576 if (!Res.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000577 Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 return Res;
579 }
580 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
581 // unary-expression: 'sizeof' '(' type-name ')'
582 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
583 // unary-expression: '__alignof' '(' type-name ')'
584 return ParseSizeofAlignofExpression();
585 case tok::ampamp: { // unary-expression: '&&' identifier
586 SourceLocation AmpAmpLoc = ConsumeToken();
587 if (Tok.getKind() != tok::identifier) {
588 Diag(Tok, diag::err_expected_ident);
589 return ExprResult(true);
590 }
591
592 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
Steve Naroff1b273c42007-09-16 14:56:35 +0000593 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 Tok.getIdentifierInfo());
595 ConsumeToken();
596 return Res;
597 }
598 case tok::kw_const_cast:
599 case tok::kw_dynamic_cast:
600 case tok::kw_reinterpret_cast:
601 case tok::kw_static_cast:
602 return ParseCXXCasts();
Chris Lattnerc97c2042007-10-03 22:03:06 +0000603 case tok::at: {
604 SourceLocation AtLoc = ConsumeToken();
605 return ParseObjCExpression(AtLoc);
606 }
Fariborz Jahanian0ccb27d2007-09-05 19:52:07 +0000607 case tok::l_square:
Chris Lattnerc97c2042007-10-03 22:03:06 +0000608 return ParseObjCMessageExpression();
Reid Spencer5f016e22007-07-11 17:01:13 +0000609 default:
610 Diag(Tok, diag::err_expected_expression);
611 return ExprResult(true);
612 }
613
614 // unreachable.
615 abort();
616}
617
618/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
619/// is parsed, this method parses any suffixes that apply.
620///
621/// postfix-expression: [C99 6.5.2]
622/// primary-expression
623/// postfix-expression '[' expression ']'
624/// postfix-expression '(' argument-expression-list[opt] ')'
625/// postfix-expression '.' identifier
626/// postfix-expression '->' identifier
627/// postfix-expression '++'
628/// postfix-expression '--'
629/// '(' type-name ')' '{' initializer-list '}'
630/// '(' type-name ')' '{' initializer-list ',' '}'
631///
632/// argument-expression-list: [C99 6.5.2]
633/// argument-expression
634/// argument-expression-list ',' assignment-expression
635///
636Parser::ExprResult Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
637
638 // Now that the primary-expression piece of the postfix-expression has been
639 // parsed, see if there are any postfix-expression pieces here.
640 SourceLocation Loc;
641 while (1) {
642 switch (Tok.getKind()) {
643 default: // Not a postfix-expression suffix.
644 return LHS;
645 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
646 Loc = ConsumeBracket();
647 ExprResult Idx = ParseExpression();
648
649 SourceLocation RLoc = Tok.getLocation();
650
651 if (!LHS.isInvalid && !Idx.isInvalid && Tok.getKind() == tok::r_square)
Steve Narofff69936d2007-09-16 03:34:24 +0000652 LHS = Actions.ActOnArraySubscriptExpr(LHS.Val, Loc, Idx.Val, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000653 else
654 LHS = ExprResult(true);
655
656 // Match the ']'.
657 MatchRHSPunctuation(tok::r_square, Loc);
658 break;
659 }
660
661 case tok::l_paren: { // p-e: p-e '(' argument-expression-list[opt] ')'
662 llvm::SmallVector<ExprTy*, 8> ArgExprs;
663 llvm::SmallVector<SourceLocation, 8> CommaLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000664
665 Loc = ConsumeParen();
666
667 if (Tok.getKind() != tok::r_paren) {
668 while (1) {
669 ExprResult ArgExpr = ParseAssignmentExpression();
670 if (ArgExpr.isInvalid) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000671 SkipUntil(tok::r_paren);
Chris Lattner2ff54262007-07-21 05:18:12 +0000672 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000673 } else
674 ArgExprs.push_back(ArgExpr.Val);
675
676 if (Tok.getKind() != tok::comma)
677 break;
678 // Move to the next argument, remember where the comma was.
679 CommaLocs.push_back(ConsumeToken());
680 }
681 }
682
683 // Match the ')'.
Chris Lattner2ff54262007-07-21 05:18:12 +0000684 if (!LHS.isInvalid && Tok.getKind() == tok::r_paren) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000685 assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&&
686 "Unexpected number of commas!");
Steve Narofff69936d2007-09-16 03:34:24 +0000687 LHS = Actions.ActOnCallExpr(LHS.Val, Loc, &ArgExprs[0], ArgExprs.size(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000688 &CommaLocs[0], Tok.getLocation());
689 }
690
Chris Lattner2ff54262007-07-21 05:18:12 +0000691 MatchRHSPunctuation(tok::r_paren, Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000692 break;
693 }
694 case tok::arrow: // postfix-expression: p-e '->' identifier
695 case tok::period: { // postfix-expression: p-e '.' identifier
696 tok::TokenKind OpKind = Tok.getKind();
697 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
698
699 if (Tok.getKind() != tok::identifier) {
700 Diag(Tok, diag::err_expected_ident);
701 return ExprResult(true);
702 }
703
704 if (!LHS.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000705 LHS = Actions.ActOnMemberReferenceExpr(LHS.Val, OpLoc, OpKind,
Reid Spencer5f016e22007-07-11 17:01:13 +0000706 Tok.getLocation(),
707 *Tok.getIdentifierInfo());
708 ConsumeToken();
709 break;
710 }
711 case tok::plusplus: // postfix-expression: postfix-expression '++'
712 case tok::minusminus: // postfix-expression: postfix-expression '--'
713 if (!LHS.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000714 LHS = Actions.ActOnPostfixUnaryOp(Tok.getLocation(), Tok.getKind(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000715 LHS.Val);
716 ConsumeToken();
717 break;
718 }
719 }
720}
721
722
723/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression.
724/// unary-expression: [C99 6.5.3]
725/// 'sizeof' unary-expression
726/// 'sizeof' '(' type-name ')'
727/// [GNU] '__alignof' unary-expression
728/// [GNU] '__alignof' '(' type-name ')'
729Parser::ExprResult Parser::ParseSizeofAlignofExpression() {
730 assert((Tok.getKind() == tok::kw_sizeof ||
731 Tok.getKind() == tok::kw___alignof) &&
732 "Not a sizeof/alignof expression!");
Chris Lattnerd2177732007-07-20 16:59:19 +0000733 Token OpTok = Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 ConsumeToken();
735
736 // If the operand doesn't start with an '(', it must be an expression.
737 ExprResult Operand;
738 if (Tok.getKind() != tok::l_paren) {
739 Operand = ParseCastExpression(true);
740 } else {
741 // If it starts with a '(', we know that it is either a parenthesized
742 // type-name, or it is a unary-expression that starts with a compound
743 // literal, or starts with a primary-expression that is a parenthesized
744 // expression.
745 ParenParseOption ExprType = CastExpr;
746 TypeTy *CastTy;
747 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
748 Operand = ParseParenExpression(ExprType, CastTy, RParenLoc);
749
750 // If ParseParenExpression parsed a '(typename)' sequence only, the this is
751 // sizeof/alignof a type. Otherwise, it is sizeof/alignof an expression.
752 if (ExprType == CastExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +0000753 return Actions.ActOnSizeOfAlignOfTypeExpr(OpTok.getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000754 OpTok.getKind() == tok::kw_sizeof,
755 LParenLoc, CastTy, RParenLoc);
756 }
757 }
758
759 // If we get here, the operand to the sizeof/alignof was an expresion.
760 if (!Operand.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000761 Operand = Actions.ActOnUnaryOp(OpTok.getLocation(), OpTok.getKind(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 Operand.Val);
763 return Operand;
764}
765
766/// ParseBuiltinPrimaryExpression
767///
768/// primary-expression: [C99 6.5.1]
769/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
770/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
771/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
772/// assign-expr ')'
773/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
774///
775/// [GNU] offsetof-member-designator:
776/// [GNU] identifier
777/// [GNU] offsetof-member-designator '.' identifier
778/// [GNU] offsetof-member-designator '[' expression ']'
779///
780Parser::ExprResult Parser::ParseBuiltinPrimaryExpression() {
781 ExprResult Res(false);
782 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
783
784 tok::TokenKind T = Tok.getKind();
785 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
786
787 // All of these start with an open paren.
788 if (Tok.getKind() != tok::l_paren) {
789 Diag(Tok, diag::err_expected_lparen_after, BuiltinII->getName());
790 return ExprResult(true);
791 }
792
793 SourceLocation LParenLoc = ConsumeParen();
794 // TODO: Build AST.
795
796 switch (T) {
797 default: assert(0 && "Not a builtin primary expression!");
798 case tok::kw___builtin_va_arg:
799 Res = ParseAssignmentExpression();
800 if (Res.isInvalid) {
801 SkipUntil(tok::r_paren);
802 return Res;
803 }
804
805 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
806 return ExprResult(true);
807
808 ParseTypeName();
Chris Lattner6eb21092007-08-30 15:52:49 +0000809
810 MatchRHSPunctuation(tok::r_paren, LParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000811 break;
812
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000813 case tok::kw___builtin_offsetof: {
Chris Lattner9fddf0a2007-08-30 17:08:45 +0000814 SourceLocation TypeLoc = Tok.getLocation();
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000815 TypeTy *Ty = ParseTypeName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000816
817 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
818 return ExprResult(true);
819
820 // We must have at least one identifier here.
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000821 if (Tok.getKind() != tok::identifier) {
822 Diag(Tok, diag::err_expected_ident);
823 SkipUntil(tok::r_paren);
824 return true;
825 }
826
827 // Keep track of the various subcomponents we see.
828 llvm::SmallVector<Action::OffsetOfComponent, 4> Comps;
829
830 Comps.push_back(Action::OffsetOfComponent());
831 Comps.back().isBrackets = false;
832 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
833 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
Reid Spencer5f016e22007-07-11 17:01:13 +0000834
835 while (1) {
836 if (Tok.getKind() == tok::period) {
837 // offsetof-member-designator: offsetof-member-designator '.' identifier
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000838 Comps.push_back(Action::OffsetOfComponent());
839 Comps.back().isBrackets = false;
840 Comps.back().LocStart = ConsumeToken();
Reid Spencer5f016e22007-07-11 17:01:13 +0000841
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000842 if (Tok.getKind() != tok::identifier) {
843 Diag(Tok, diag::err_expected_ident);
844 SkipUntil(tok::r_paren);
845 return true;
846 }
847 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
848 Comps.back().LocEnd = ConsumeToken();
849
Reid Spencer5f016e22007-07-11 17:01:13 +0000850 } else if (Tok.getKind() == tok::l_square) {
851 // offsetof-member-designator: offsetof-member-design '[' expression ']'
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000852 Comps.push_back(Action::OffsetOfComponent());
853 Comps.back().isBrackets = true;
854 Comps.back().LocStart = ConsumeBracket();
Reid Spencer5f016e22007-07-11 17:01:13 +0000855 Res = ParseExpression();
856 if (Res.isInvalid) {
857 SkipUntil(tok::r_paren);
858 return Res;
859 }
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000860 Comps.back().U.E = Res.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000861
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000862 Comps.back().LocEnd =
863 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart);
864 } else if (Tok.getKind() == tok::r_paren) {
Steve Naroff1b273c42007-09-16 14:56:35 +0000865 Res = Actions.ActOnBuiltinOffsetOf(StartLoc, TypeLoc, Ty, &Comps[0],
Chris Lattner6eb21092007-08-30 15:52:49 +0000866 Comps.size(), ConsumeParen());
867 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000868 } else {
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000869 // Error occurred.
870 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000871 }
872 }
873 break;
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000874 }
Steve Naroffd04fdd52007-08-03 21:21:27 +0000875 case tok::kw___builtin_choose_expr: {
876 ExprResult Cond = ParseAssignmentExpression();
877 if (Cond.isInvalid) {
878 SkipUntil(tok::r_paren);
879 return Cond;
880 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000881 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
882 return ExprResult(true);
883
Steve Naroffd04fdd52007-08-03 21:21:27 +0000884 ExprResult Expr1 = ParseAssignmentExpression();
885 if (Expr1.isInvalid) {
886 SkipUntil(tok::r_paren);
887 return Expr1;
888 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000889 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
890 return ExprResult(true);
891
Steve Naroffd04fdd52007-08-03 21:21:27 +0000892 ExprResult Expr2 = ParseAssignmentExpression();
893 if (Expr2.isInvalid) {
894 SkipUntil(tok::r_paren);
895 return Expr2;
896 }
897 if (Tok.getKind() != tok::r_paren) {
898 Diag(Tok, diag::err_expected_rparen);
899 return ExprResult(true);
900 }
Steve Naroff1b273c42007-09-16 14:56:35 +0000901 Res = Actions.ActOnChooseExpr(StartLoc, Cond.Val, Expr1.Val, Expr2.Val,
Chris Lattner6eb21092007-08-30 15:52:49 +0000902 ConsumeParen());
903 break;
Steve Naroffd04fdd52007-08-03 21:21:27 +0000904 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000905 case tok::kw___builtin_types_compatible_p:
Steve Naroff363bcff2007-08-01 23:45:51 +0000906 TypeTy *Ty1 = ParseTypeName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000907
908 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
909 return ExprResult(true);
910
Steve Naroff363bcff2007-08-01 23:45:51 +0000911 TypeTy *Ty2 = ParseTypeName();
912
913 if (Tok.getKind() != tok::r_paren) {
914 Diag(Tok, diag::err_expected_rparen);
915 return ExprResult(true);
916 }
Steve Naroff1b273c42007-09-16 14:56:35 +0000917 Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1, Ty2, ConsumeParen());
Chris Lattner6eb21092007-08-30 15:52:49 +0000918 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000919 }
920
Reid Spencer5f016e22007-07-11 17:01:13 +0000921 // These can be followed by postfix-expr pieces because they are
922 // primary-expressions.
923 return ParsePostfixExpressionSuffix(Res);
924}
925
926/// ParseParenExpression - This parses the unit that starts with a '(' token,
927/// based on what is allowed by ExprType. The actual thing parsed is returned
928/// in ExprType.
929///
930/// primary-expression: [C99 6.5.1]
931/// '(' expression ')'
932/// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
933/// postfix-expression: [C99 6.5.2]
934/// '(' type-name ')' '{' initializer-list '}'
935/// '(' type-name ')' '{' initializer-list ',' '}'
936/// cast-expression: [C99 6.5.4]
937/// '(' type-name ')' cast-expression
938///
939Parser::ExprResult Parser::ParseParenExpression(ParenParseOption &ExprType,
940 TypeTy *&CastTy,
941 SourceLocation &RParenLoc) {
942 assert(Tok.getKind() == tok::l_paren && "Not a paren expr!");
943 SourceLocation OpenLoc = ConsumeParen();
Chris Lattnerab18c4c2007-07-24 16:58:17 +0000944 ExprResult Result(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000945 CastTy = 0;
946
Chris Lattner98414c12007-08-31 21:49:55 +0000947 if (ExprType >= CompoundStmt && Tok.getKind() == tok::l_brace) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000948 Diag(Tok, diag::ext_gnu_statement_expr);
Chris Lattner98414c12007-08-31 21:49:55 +0000949 Parser::StmtResult Stmt = ParseCompoundStatement(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000950 ExprType = CompoundStmt;
Chris Lattnerab18c4c2007-07-24 16:58:17 +0000951
952 // If the substmt parsed correctly, build the AST node.
953 if (!Stmt.isInvalid && Tok.getKind() == tok::r_paren)
Steve Naroff1b273c42007-09-16 14:56:35 +0000954 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.Val, Tok.getLocation());
Chris Lattnerab18c4c2007-07-24 16:58:17 +0000955
Reid Spencer5f016e22007-07-11 17:01:13 +0000956 } else if (ExprType >= CompoundLiteral && isTypeSpecifierQualifier()) {
957 // Otherwise, this is a compound literal expression or cast expression.
958 TypeTy *Ty = ParseTypeName();
959
960 // Match the ')'.
961 if (Tok.getKind() == tok::r_paren)
962 RParenLoc = ConsumeParen();
963 else
964 MatchRHSPunctuation(tok::r_paren, OpenLoc);
965
966 if (Tok.getKind() == tok::l_brace) {
967 if (!getLang().C99) // Compound literals don't exist in C90.
968 Diag(OpenLoc, diag::ext_c99_compound_literal);
969 Result = ParseInitializer();
970 ExprType = CompoundLiteral;
Steve Naroff4aa88f82007-07-19 01:06:55 +0000971 if (!Result.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000972 return Actions.ActOnCompoundLiteral(OpenLoc, Ty, RParenLoc, Result.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000973 } else if (ExprType == CastExpr) {
974 // Note that this doesn't parse the subsequence cast-expression, it just
975 // returns the parsed type to the callee.
976 ExprType = CastExpr;
977 CastTy = Ty;
978 return ExprResult(false);
979 } else {
980 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
981 return ExprResult(true);
982 }
983 return Result;
984 } else {
985 Result = ParseExpression();
986 ExprType = SimpleExpr;
987 if (!Result.isInvalid && Tok.getKind() == tok::r_paren)
Steve Narofff69936d2007-09-16 03:34:24 +0000988 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000989 }
990
991 // Match the ')'.
992 if (Result.isInvalid)
993 SkipUntil(tok::r_paren);
994 else {
995 if (Tok.getKind() == tok::r_paren)
996 RParenLoc = ConsumeParen();
997 else
998 MatchRHSPunctuation(tok::r_paren, OpenLoc);
999 }
1000
1001 return Result;
1002}
1003
1004/// ParseStringLiteralExpression - This handles the various token types that
1005/// form string literals, and also handles string concatenation [C99 5.1.1.2,
1006/// translation phase #6].
1007///
1008/// primary-expression: [C99 6.5.1]
1009/// string-literal
1010Parser::ExprResult Parser::ParseStringLiteralExpression() {
1011 assert(isTokenStringLiteral() && "Not a string literal!");
1012
1013 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
1014 // considered to be strings for concatenation purposes.
Chris Lattnerd2177732007-07-20 16:59:19 +00001015 llvm::SmallVector<Token, 4> StringToks;
Reid Spencer5f016e22007-07-11 17:01:13 +00001016
1017 do {
1018 StringToks.push_back(Tok);
1019 ConsumeStringToken();
1020 } while (isTokenStringLiteral());
1021
1022 // Pass the set of string tokens, ready for concatenation, to the actions.
Steve Narofff69936d2007-09-16 03:34:24 +00001023 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size());
Reid Spencer5f016e22007-07-11 17:01:13 +00001024}