blob: 17b14bd2a1b953e915527631381c3f038830b0be [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"
Sebastian Redla55e52c2008-11-25 22:21:31 +000026#include "AstGuard.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/SmallString.h"
29using namespace clang;
30
31/// PrecedenceLevels - These are precedences for the binary/ternary operators in
32/// the C99 grammar. These have been named to relate with the C99 grammar
33/// productions. Low precedences numbers bind more weakly than high numbers.
34namespace prec {
35 enum Level {
36 Unknown = 0, // Not binary operator.
37 Comma = 1, // ,
38 Assignment = 2, // =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=
39 Conditional = 3, // ?
40 LogicalOr = 4, // ||
41 LogicalAnd = 5, // &&
42 InclusiveOr = 6, // |
43 ExclusiveOr = 7, // ^
44 And = 8, // &
45 Equality = 9, // ==, !=
46 Relational = 10, // >=, <=, >, <
47 Shift = 11, // <<, >>
48 Additive = 12, // -, +
49 Multiplicative = 13 // *, /, %
50 };
51}
52
53
54/// getBinOpPrecedence - Return the precedence of the specified binary operator
55/// token. This returns:
56///
57static prec::Level getBinOpPrecedence(tok::TokenKind Kind) {
58 switch (Kind) {
59 default: return prec::Unknown;
60 case tok::comma: return prec::Comma;
61 case tok::equal:
62 case tok::starequal:
63 case tok::slashequal:
64 case tok::percentequal:
65 case tok::plusequal:
66 case tok::minusequal:
67 case tok::lesslessequal:
68 case tok::greatergreaterequal:
69 case tok::ampequal:
70 case tok::caretequal:
71 case tok::pipeequal: return prec::Assignment;
72 case tok::question: return prec::Conditional;
73 case tok::pipepipe: return prec::LogicalOr;
74 case tok::ampamp: return prec::LogicalAnd;
75 case tok::pipe: return prec::InclusiveOr;
76 case tok::caret: return prec::ExclusiveOr;
77 case tok::amp: return prec::And;
78 case tok::exclaimequal:
79 case tok::equalequal: return prec::Equality;
80 case tok::lessequal:
81 case tok::less:
82 case tok::greaterequal:
83 case tok::greater: return prec::Relational;
84 case tok::lessless:
85 case tok::greatergreater: return prec::Shift;
86 case tok::plus:
87 case tok::minus: return prec::Additive;
88 case tok::percent:
89 case tok::slash:
90 case tok::star: return prec::Multiplicative;
91 }
92}
93
94
95/// ParseExpression - Simple precedence-based parser for binary/ternary
96/// operators.
97///
98/// Note: we diverge from the C99 grammar when parsing the assignment-expression
99/// production. C99 specifies that the LHS of an assignment operator should be
100/// parsed as a unary-expression, but consistency dictates that it be a
101/// conditional-expession. In practice, the important thing here is that the
102/// LHS of an assignment has to be an l-value, which productions between
103/// unary-expression and conditional-expression don't produce. Because we want
104/// consistency, we parse the LHS as a conditional-expression, then check for
105/// l-value-ness in semantic analysis stages.
106///
107/// multiplicative-expression: [C99 6.5.5]
108/// cast-expression
109/// multiplicative-expression '*' cast-expression
110/// multiplicative-expression '/' cast-expression
111/// multiplicative-expression '%' cast-expression
112///
113/// additive-expression: [C99 6.5.6]
114/// multiplicative-expression
115/// additive-expression '+' multiplicative-expression
116/// additive-expression '-' multiplicative-expression
117///
118/// shift-expression: [C99 6.5.7]
119/// additive-expression
120/// shift-expression '<<' additive-expression
121/// shift-expression '>>' additive-expression
122///
123/// relational-expression: [C99 6.5.8]
124/// shift-expression
125/// relational-expression '<' shift-expression
126/// relational-expression '>' shift-expression
127/// relational-expression '<=' shift-expression
128/// relational-expression '>=' shift-expression
129///
130/// equality-expression: [C99 6.5.9]
131/// relational-expression
132/// equality-expression '==' relational-expression
133/// equality-expression '!=' relational-expression
134///
135/// AND-expression: [C99 6.5.10]
136/// equality-expression
137/// AND-expression '&' equality-expression
138///
139/// exclusive-OR-expression: [C99 6.5.11]
140/// AND-expression
141/// exclusive-OR-expression '^' AND-expression
142///
143/// inclusive-OR-expression: [C99 6.5.12]
144/// exclusive-OR-expression
145/// inclusive-OR-expression '|' exclusive-OR-expression
146///
147/// logical-AND-expression: [C99 6.5.13]
148/// inclusive-OR-expression
149/// logical-AND-expression '&&' inclusive-OR-expression
150///
151/// logical-OR-expression: [C99 6.5.14]
152/// logical-AND-expression
153/// logical-OR-expression '||' logical-AND-expression
154///
155/// conditional-expression: [C99 6.5.15]
156/// logical-OR-expression
157/// logical-OR-expression '?' expression ':' conditional-expression
158/// [GNU] logical-OR-expression '?' ':' conditional-expression
159///
160/// assignment-expression: [C99 6.5.16]
161/// conditional-expression
162/// unary-expression assignment-operator assignment-expression
Chris Lattner50dd2892008-02-26 00:51:44 +0000163/// [C++] throw-expression [C++ 15]
Reid Spencer5f016e22007-07-11 17:01:13 +0000164///
165/// assignment-operator: one of
166/// = *= /= %= += -= <<= >>= &= ^= |=
167///
168/// expression: [C99 6.5.17]
169/// assignment-expression
170/// expression ',' assignment-expression
171///
172Parser::ExprResult Parser::ParseExpression() {
Chris Lattner50dd2892008-02-26 00:51:44 +0000173 if (Tok.is(tok::kw_throw))
174 return ParseThrowExpression();
175
Reid Spencer5f016e22007-07-11 17:01:13 +0000176 ExprResult LHS = ParseCastExpression(false);
177 if (LHS.isInvalid) return LHS;
178
179 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
180}
181
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000182/// This routine is called when the '@' is seen and consumed.
183/// Current token is an Identifier and is not a 'try'. This
Chris Lattnerc97c2042007-10-03 22:03:06 +0000184/// routine is necessary to disambiguate @try-statement from,
185/// for example, @encode-expression.
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000186///
Fariborz Jahanianb384d322007-10-04 20:19:06 +0000187Parser::ExprResult Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
Steve Naroffa642beb2007-10-15 20:55:58 +0000188 ExprResult LHS = ParseObjCAtExpression(AtLoc);
Fariborz Jahanian397fcc12007-09-19 19:14:32 +0000189 if (LHS.isInvalid) return LHS;
190
191 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
192}
193
Reid Spencer5f016e22007-07-11 17:01:13 +0000194/// ParseAssignmentExpression - Parse an expr that doesn't include commas.
195///
196Parser::ExprResult Parser::ParseAssignmentExpression() {
Chris Lattner50dd2892008-02-26 00:51:44 +0000197 if (Tok.is(tok::kw_throw))
198 return ParseThrowExpression();
199
Reid Spencer5f016e22007-07-11 17:01:13 +0000200 ExprResult LHS = ParseCastExpression(false);
201 if (LHS.isInvalid) return LHS;
202
203 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
204}
205
Chris Lattnerb93fb492008-06-02 21:31:07 +0000206/// ParseAssignmentExprWithObjCMessageExprStart - Parse an assignment expression
207/// where part of an objc message send has already been parsed. In this case
208/// LBracLoc indicates the location of the '[' of the message send, and either
209/// ReceiverName or ReceiverExpr is non-null indicating the receiver of the
210/// message.
211///
212/// Since this handles full assignment-expression's, it handles postfix
213/// expressions and other binary operators for these expressions as well.
214Parser::ExprResult
215Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
Steve Naroff5cb93b82008-11-19 15:54:23 +0000216 SourceLocation NameLoc,
Chris Lattnerb93fb492008-06-02 21:31:07 +0000217 IdentifierInfo *ReceiverName,
218 ExprTy *ReceiverExpr) {
Steve Naroff5cb93b82008-11-19 15:54:23 +0000219 ExprResult R = ParseObjCMessageExpressionBody(LBracLoc, NameLoc, ReceiverName,
Chris Lattnerb93fb492008-06-02 21:31:07 +0000220 ReceiverExpr);
221 if (R.isInvalid) return R;
222 R = ParsePostfixExpressionSuffix(R);
223 if (R.isInvalid) return R;
224 return ParseRHSOfBinaryExpression(R, 2);
225}
226
227
Reid Spencer5f016e22007-07-11 17:01:13 +0000228Parser::ExprResult Parser::ParseConstantExpression() {
229 ExprResult LHS = ParseCastExpression(false);
230 if (LHS.isInvalid) return LHS;
231
Reid Spencer5f016e22007-07-11 17:01:13 +0000232 return ParseRHSOfBinaryExpression(LHS, prec::Conditional);
233}
234
Reid Spencer5f016e22007-07-11 17:01:13 +0000235/// ParseRHSOfBinaryExpression - Parse a binary expression that starts with
236/// LHS and has a precedence of at least MinPrec.
237Parser::ExprResult
238Parser::ParseRHSOfBinaryExpression(ExprResult LHS, unsigned MinPrec) {
239 unsigned NextTokPrec = getBinOpPrecedence(Tok.getKind());
240 SourceLocation ColonLoc;
241
Sebastian Redla55e52c2008-11-25 22:21:31 +0000242 ExprGuard LHSGuard(Actions, LHS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000243 while (1) {
244 // If this token has a lower precedence than we are allowed to parse (e.g.
245 // because we are called recursively, or because the token is not a binop),
246 // then we are done!
Sebastian Redla55e52c2008-11-25 22:21:31 +0000247 if (NextTokPrec < MinPrec) {
248 LHSGuard.take();
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 return LHS;
Sebastian Redla55e52c2008-11-25 22:21:31 +0000250 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000251
252 // Consume the operator, saving the operator token for error reporting.
Chris Lattnerd2177732007-07-20 16:59:19 +0000253 Token OpToken = Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000254 ConsumeToken();
255
256 // Special case handling for the ternary operator.
257 ExprResult TernaryMiddle(true);
Sebastian Redla55e52c2008-11-25 22:21:31 +0000258 ExprGuard MiddleGuard(Actions);
Reid Spencer5f016e22007-07-11 17:01:13 +0000259 if (NextTokPrec == prec::Conditional) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000260 if (Tok.isNot(tok::colon)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000261 // Handle this production specially:
262 // logical-OR-expression '?' expression ':' conditional-expression
263 // In particular, the RHS of the '?' is 'expression', not
264 // 'logical-OR-expression' as we might expect.
265 TernaryMiddle = ParseExpression();
Chris Lattnerdbd583c2007-08-31 04:58:34 +0000266 if (TernaryMiddle.isInvalid) {
Chris Lattnerdbd583c2007-08-31 04:58:34 +0000267 return TernaryMiddle;
268 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000269 } else {
270 // Special case handling of "X ? Y : Z" where Y is empty:
271 // logical-OR-expression '?' ':' conditional-expression [GNU]
272 TernaryMiddle = ExprResult(false);
273 Diag(Tok, diag::ext_gnu_conditional_expr);
274 }
Sebastian Redla55e52c2008-11-25 22:21:31 +0000275 MiddleGuard.reset(TernaryMiddle);
Reid Spencer5f016e22007-07-11 17:01:13 +0000276
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000277 if (Tok.isNot(tok::colon)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000278 Diag(Tok, diag::err_expected_colon);
Chris Lattner28eb7e92008-11-23 23:17:07 +0000279 Diag(OpToken, diag::note_matching) << "?";
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 return ExprResult(true);
281 }
282
283 // Eat the colon.
284 ColonLoc = ConsumeToken();
285 }
286
287 // Parse another leaf here for the RHS of the operator.
288 ExprResult RHS = ParseCastExpression(false);
Chris Lattnerdbd583c2007-08-31 04:58:34 +0000289 if (RHS.isInvalid) {
Chris Lattnerdbd583c2007-08-31 04:58:34 +0000290 return RHS;
291 }
Sebastian Redla55e52c2008-11-25 22:21:31 +0000292 ExprGuard RHSGuard(Actions, RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000293
294 // Remember the precedence of this operator and get the precedence of the
295 // operator immediately to the right of the RHS.
296 unsigned ThisPrec = NextTokPrec;
297 NextTokPrec = getBinOpPrecedence(Tok.getKind());
298
299 // Assignment and conditional expressions are right-associative.
Chris Lattnerd7d860d2007-12-18 06:06:23 +0000300 bool isRightAssoc = ThisPrec == prec::Conditional ||
301 ThisPrec == prec::Assignment;
Reid Spencer5f016e22007-07-11 17:01:13 +0000302
303 // Get the precedence of the operator to the right of the RHS. If it binds
304 // more tightly with RHS than we do, evaluate it completely first.
305 if (ThisPrec < NextTokPrec ||
306 (ThisPrec == NextTokPrec && isRightAssoc)) {
307 // If this is left-associative, only parse things on the RHS that bind
308 // more tightly than the current operator. If it is left-associative, it
309 // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
310 // A=(B=(C=D)), where each paren is a level of recursion here.
Sebastian Redla55e52c2008-11-25 22:21:31 +0000311 // The function takes ownership of the RHS.
312 RHSGuard.take();
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 RHS = ParseRHSOfBinaryExpression(RHS, ThisPrec + !isRightAssoc);
Chris Lattnerdbd583c2007-08-31 04:58:34 +0000314 if (RHS.isInvalid) {
Chris Lattnerdbd583c2007-08-31 04:58:34 +0000315 return RHS;
316 }
Sebastian Redla55e52c2008-11-25 22:21:31 +0000317 RHSGuard.reset(RHS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000318
319 NextTokPrec = getBinOpPrecedence(Tok.getKind());
320 }
321 assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
Sebastian Redla55e52c2008-11-25 22:21:31 +0000322
Chris Lattnerd56d6b62007-08-31 05:01:50 +0000323 if (!LHS.isInvalid) {
324 // Combine the LHS and RHS into the LHS (e.g. build AST).
Sebastian Redla55e52c2008-11-25 22:21:31 +0000325 LHSGuard.take();
326 MiddleGuard.take();
327 RHSGuard.take();
Chris Lattnerd56d6b62007-08-31 05:01:50 +0000328 if (TernaryMiddle.isInvalid)
Douglas Gregoreaebc752008-11-06 23:29:22 +0000329 LHS = Actions.ActOnBinOp(CurScope, OpToken.getLocation(),
330 OpToken.getKind(), LHS.Val, RHS.Val);
Chris Lattnerd56d6b62007-08-31 05:01:50 +0000331 else
Steve Narofff69936d2007-09-16 03:34:24 +0000332 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
Chris Lattnerd56d6b62007-08-31 05:01:50 +0000333 LHS.Val, TernaryMiddle.Val, RHS.Val);
Sebastian Redla55e52c2008-11-25 22:21:31 +0000334 LHSGuard.reset(LHS);
Chris Lattnerd56d6b62007-08-31 05:01:50 +0000335 }
Sebastian Redla55e52c2008-11-25 22:21:31 +0000336 // If we had an invalid LHS, Middle and RHS will be freed by the guards here
Reid Spencer5f016e22007-07-11 17:01:13 +0000337 }
338}
339
340/// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
341/// true, parse a unary-expression.
342///
343/// cast-expression: [C99 6.5.4]
344/// unary-expression
345/// '(' type-name ')' cast-expression
346///
347/// unary-expression: [C99 6.5.3]
348/// postfix-expression
349/// '++' unary-expression
350/// '--' unary-expression
351/// unary-operator cast-expression
352/// 'sizeof' unary-expression
353/// 'sizeof' '(' type-name ')'
354/// [GNU] '__alignof' unary-expression
355/// [GNU] '__alignof' '(' type-name ')'
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000356/// [C++0x] 'alignof' '(' type-id ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000357/// [GNU] '&&' identifier
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000358/// [C++] new-expression
359/// [C++] delete-expression
Reid Spencer5f016e22007-07-11 17:01:13 +0000360///
361/// unary-operator: one of
362/// '&' '*' '+' '-' '~' '!'
363/// [GNU] '__extension__' '__real' '__imag'
364///
365/// primary-expression: [C99 6.5.1]
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +0000366/// [C99] identifier
Sebastian Redlc42e1182008-11-11 11:37:55 +0000367/// [C++] id-expression
Reid Spencer5f016e22007-07-11 17:01:13 +0000368/// constant
369/// string-literal
370/// [C++] boolean-literal [C++ 2.13.5]
371/// '(' expression ')'
372/// '__func__' [C99 6.4.2.2]
373/// [GNU] '__FUNCTION__'
374/// [GNU] '__PRETTY_FUNCTION__'
375/// [GNU] '(' compound-statement ')'
376/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
377/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
378/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
379/// assign-expr ')'
380/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
Fariborz Jahanian095ffca2007-09-26 17:03:44 +0000381/// [OBJC] '[' objc-message-expr ']'
Chris Lattner5ac87ed2008-01-25 18:58:06 +0000382/// [OBJC] '@selector' '(' objc-selector-arg ')'
Fariborz Jahanian095ffca2007-09-26 17:03:44 +0000383/// [OBJC] '@protocol' '(' identifier ')'
384/// [OBJC] '@encode' '(' type-name ')'
Fariborz Jahanian0ccb27d2007-09-05 19:52:07 +0000385/// [OBJC] objc-string-literal
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000386/// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
387/// [C++] typename-specifier '(' expression-list[opt] ')' [TODO]
Reid Spencer5f016e22007-07-11 17:01:13 +0000388/// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
389/// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
390/// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
391/// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
Sebastian Redlc42e1182008-11-11 11:37:55 +0000392/// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
393/// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
Argyrios Kyrtzidisd7464be2008-07-16 07:23:27 +0000394/// [C++] 'this' [C++ 9.3.2]
Steve Naroff296e8d52008-08-28 19:20:44 +0000395/// [clang] '^' block-literal
Reid Spencer5f016e22007-07-11 17:01:13 +0000396///
397/// constant: [C99 6.4.4]
398/// integer-constant
399/// floating-constant
400/// enumeration-constant -> identifier
401/// character-constant
402///
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +0000403/// id-expression: [C++ 5.1]
404/// unqualified-id
405/// qualified-id [TODO]
406///
407/// unqualified-id: [C++ 5.1]
408/// identifier
409/// operator-function-id
410/// conversion-function-id [TODO]
411/// '~' class-name [TODO]
412/// template-id [TODO]
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000413///
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000414/// new-expression: [C++ 5.3.4]
415/// '::'[opt] 'new' new-placement[opt] new-type-id
416/// new-initializer[opt]
417/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
418/// new-initializer[opt]
419///
420/// delete-expression: [C++ 5.3.5]
421/// '::'[opt] 'delete' cast-expression
422/// '::'[opt] 'delete' '[' ']' cast-expression
423///
Reid Spencer5f016e22007-07-11 17:01:13 +0000424Parser::ExprResult Parser::ParseCastExpression(bool isUnaryExpression) {
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000425 if (getLang().CPlusPlus) {
426 // Annotate typenames and C++ scope specifiers.
427 // Used only in C++; in C let the typedef name be handled as an identifier.
428 TryAnnotateTypeOrScopeToken();
429 }
430
Reid Spencer5f016e22007-07-11 17:01:13 +0000431 ExprResult Res;
432 tok::TokenKind SavedKind = Tok.getKind();
433
434 // This handles all of cast-expression, unary-expression, postfix-expression,
435 // and primary-expression. We handle them together like this for efficiency
436 // and to simplify handling of an expression starting with a '(' token: which
437 // may be one of a parenthesized expression, cast-expression, compound literal
438 // expression, or statement expression.
439 //
440 // If the parsed tokens consist of a primary-expression, the cases below
441 // call ParsePostfixExpressionSuffix to handle the postfix expression
442 // suffixes. Cases that cannot be followed by postfix exprs should
443 // return without invoking ParsePostfixExpressionSuffix.
444 switch (SavedKind) {
445 case tok::l_paren: {
446 // If this expression is limited to being a unary-expression, the parent can
447 // not start a cast expression.
448 ParenParseOption ParenExprType =
449 isUnaryExpression ? CompoundLiteral : CastExpr;
450 TypeTy *CastTy;
451 SourceLocation LParenLoc = Tok.getLocation();
452 SourceLocation RParenLoc;
453 Res = ParseParenExpression(ParenExprType, CastTy, RParenLoc);
454 if (Res.isInvalid) return Res;
455
456 switch (ParenExprType) {
457 case SimpleExpr: break; // Nothing else to do.
458 case CompoundStmt: break; // Nothing else to do.
459 case CompoundLiteral:
460 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
461 // postfix-expression exist, parse them now.
462 break;
463 case CastExpr:
464 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. Parse
465 // the cast-expression that follows it next.
466 // TODO: For cast expression with CastTy.
467 Res = ParseCastExpression(false);
468 if (!Res.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000469 Res = Actions.ActOnCastExpr(LParenLoc, CastTy, RParenLoc, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 return Res;
471 }
472
473 // These can be followed by postfix-expr pieces.
474 return ParsePostfixExpressionSuffix(Res);
475 }
476
477 // primary-expression
478 case tok::numeric_constant:
479 // constant: integer-constant
480 // constant: floating-constant
481
Steve Narofff69936d2007-09-16 03:34:24 +0000482 Res = Actions.ActOnNumericConstant(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000483 ConsumeToken();
484
485 // These can be followed by postfix-expr pieces.
486 return ParsePostfixExpressionSuffix(Res);
487
488 case tok::kw_true:
489 case tok::kw_false:
490 return ParseCXXBoolLiteral();
491
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000492 case tok::identifier: { // primary-expression: identifier
493 // unqualified-id: identifier
494 // constant: enumeration-constant
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000495
Reid Spencer5f016e22007-07-11 17:01:13 +0000496 // Consume the identifier so that we can see if it is followed by a '('.
497 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
498 // need to know whether or not this identifier is a function designator or
499 // not.
500 IdentifierInfo &II = *Tok.getIdentifierInfo();
501 SourceLocation L = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000502 Res = Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren));
Reid Spencer5f016e22007-07-11 17:01:13 +0000503 // These can be followed by postfix-expr pieces.
504 return ParsePostfixExpressionSuffix(Res);
505 }
506 case tok::char_constant: // constant: character-constant
Steve Narofff69936d2007-09-16 03:34:24 +0000507 Res = Actions.ActOnCharacterConstant(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 ConsumeToken();
509 // These can be followed by postfix-expr pieces.
510 return ParsePostfixExpressionSuffix(Res);
511 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
512 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
513 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Chris Lattnerd9f69102008-08-10 01:53:14 +0000514 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
Reid Spencer5f016e22007-07-11 17:01:13 +0000515 ConsumeToken();
516 // These can be followed by postfix-expr pieces.
517 return ParsePostfixExpressionSuffix(Res);
518 case tok::string_literal: // primary-expression: string-literal
519 case tok::wide_string_literal:
520 Res = ParseStringLiteralExpression();
521 if (Res.isInvalid) return Res;
522 // This can be followed by postfix-expr pieces (e.g. "foo"[1]).
523 return ParsePostfixExpressionSuffix(Res);
524 case tok::kw___builtin_va_arg:
525 case tok::kw___builtin_offsetof:
526 case tok::kw___builtin_choose_expr:
Nate Begemane2ce1d92008-01-17 17:46:27 +0000527 case tok::kw___builtin_overload:
Reid Spencer5f016e22007-07-11 17:01:13 +0000528 case tok::kw___builtin_types_compatible_p:
529 return ParseBuiltinPrimaryExpression();
530 case tok::plusplus: // unary-expression: '++' unary-expression
531 case tok::minusminus: { // unary-expression: '--' unary-expression
532 SourceLocation SavedLoc = ConsumeToken();
533 Res = ParseCastExpression(true);
534 if (!Res.isInvalid)
Douglas Gregor74253732008-11-19 15:42:04 +0000535 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000536 return Res;
537 }
538 case tok::amp: // unary-expression: '&' cast-expression
539 case tok::star: // unary-expression: '*' cast-expression
540 case tok::plus: // unary-expression: '+' cast-expression
541 case tok::minus: // unary-expression: '-' cast-expression
542 case tok::tilde: // unary-expression: '~' cast-expression
543 case tok::exclaim: // unary-expression: '!' cast-expression
544 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
Chris Lattner35080842008-02-02 20:20:10 +0000545 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 SourceLocation SavedLoc = ConsumeToken();
547 Res = ParseCastExpression(false);
548 if (!Res.isInvalid)
Douglas Gregor74253732008-11-19 15:42:04 +0000549 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000550 return Res;
Chris Lattner35080842008-02-02 20:20:10 +0000551 }
552
553 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
554 // __extension__ silences extension warnings in the subexpression.
Chris Lattnerc46d1a12008-10-20 06:45:43 +0000555 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Chris Lattner35080842008-02-02 20:20:10 +0000556 SourceLocation SavedLoc = ConsumeToken();
557 Res = ParseCastExpression(false);
558 if (!Res.isInvalid)
Douglas Gregor74253732008-11-19 15:42:04 +0000559 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Chris Lattner35080842008-02-02 20:20:10 +0000560 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 }
562 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
563 // unary-expression: 'sizeof' '(' type-name ')'
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000564 case tok::kw_alignof:
Reid Spencer5f016e22007-07-11 17:01:13 +0000565 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
566 // unary-expression: '__alignof' '(' type-name ')'
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000567 // unary-expression: 'alignof' '(' type-id ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000568 return ParseSizeofAlignofExpression();
569 case tok::ampamp: { // unary-expression: '&&' identifier
570 SourceLocation AmpAmpLoc = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000571 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 Diag(Tok, diag::err_expected_ident);
573 return ExprResult(true);
574 }
575
576 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
Steve Naroff1b273c42007-09-16 14:56:35 +0000577 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 Tok.getIdentifierInfo());
579 ConsumeToken();
580 return Res;
581 }
582 case tok::kw_const_cast:
583 case tok::kw_dynamic_cast:
584 case tok::kw_reinterpret_cast:
585 case tok::kw_static_cast:
Argyrios Kyrtzidisb348b812008-08-16 19:45:32 +0000586 Res = ParseCXXCasts();
587 // These can be followed by postfix-expr pieces.
588 return ParsePostfixExpressionSuffix(Res);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000589 case tok::kw_typeid:
590 Res = ParseCXXTypeid();
591 // This can be followed by postfix-expr pieces.
592 return ParsePostfixExpressionSuffix(Res);
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000593 case tok::kw_this:
Argyrios Kyrtzidis289d7732008-08-16 19:34:46 +0000594 Res = ParseCXXThis();
595 // This can be followed by postfix-expr pieces.
596 return ParsePostfixExpressionSuffix(Res);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000597
598 case tok::kw_char:
599 case tok::kw_wchar_t:
600 case tok::kw_bool:
601 case tok::kw_short:
602 case tok::kw_int:
603 case tok::kw_long:
604 case tok::kw_signed:
605 case tok::kw_unsigned:
606 case tok::kw_float:
607 case tok::kw_double:
608 case tok::kw_void:
609 case tok::kw_typeof: {
610 if (!getLang().CPlusPlus)
611 goto UnhandledToken;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000612 case tok::annot_qualtypename:
613 assert(getLang().CPlusPlus && "Expected C++");
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000614 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
615 //
616 DeclSpec DS;
617 ParseCXXSimpleTypeSpecifier(DS);
618 if (Tok.isNot(tok::l_paren))
Chris Lattner1ab3b962008-11-18 07:48:38 +0000619 return Diag(Tok, diag::err_expected_lparen_after_type)
620 << DS.getSourceRange();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000621
622 Res = ParseCXXTypeConstructExpression(DS);
623 // This can be followed by postfix-expr pieces.
624 return ParsePostfixExpressionSuffix(Res);
625 }
626
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000627 case tok::annot_cxxscope: // [C++] id-expression: qualified-id
628 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
629 // template-id
630 Res = ParseCXXIdExpression();
631 return ParsePostfixExpressionSuffix(Res);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +0000632
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000633 case tok::kw_new: // [C++] new-expression
634 // FIXME: ParseCXXIdExpression currently steals :: tokens.
635 return ParseCXXNewExpression();
636
637 case tok::kw_delete: // [C++] delete-expression
638 return ParseCXXDeleteExpression();
639
Chris Lattnerc97c2042007-10-03 22:03:06 +0000640 case tok::at: {
641 SourceLocation AtLoc = ConsumeToken();
Steve Naroffa642beb2007-10-15 20:55:58 +0000642 return ParseObjCAtExpression(AtLoc);
Chris Lattnerc97c2042007-10-03 22:03:06 +0000643 }
Fariborz Jahanian0ccb27d2007-09-05 19:52:07 +0000644 case tok::l_square:
Steve Naroffa642beb2007-10-15 20:55:58 +0000645 // These can be followed by postfix-expr pieces.
Chris Lattner039a6422008-05-09 05:28:21 +0000646 if (getLang().ObjC1)
647 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression());
648 // FALL THROUGH.
Steve Naroff296e8d52008-08-28 19:20:44 +0000649 case tok::caret:
650 if (getLang().Blocks)
651 return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression());
652 Diag(Tok, diag::err_expected_expression);
653 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000654 default:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000655 UnhandledToken:
Reid Spencer5f016e22007-07-11 17:01:13 +0000656 Diag(Tok, diag::err_expected_expression);
657 return ExprResult(true);
658 }
659
660 // unreachable.
661 abort();
662}
663
664/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
665/// is parsed, this method parses any suffixes that apply.
666///
667/// postfix-expression: [C99 6.5.2]
668/// primary-expression
669/// postfix-expression '[' expression ']'
670/// postfix-expression '(' argument-expression-list[opt] ')'
671/// postfix-expression '.' identifier
672/// postfix-expression '->' identifier
673/// postfix-expression '++'
674/// postfix-expression '--'
675/// '(' type-name ')' '{' initializer-list '}'
676/// '(' type-name ')' '{' initializer-list ',' '}'
677///
678/// argument-expression-list: [C99 6.5.2]
679/// argument-expression
680/// argument-expression-list ',' assignment-expression
681///
682Parser::ExprResult Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
Sebastian Redla55e52c2008-11-25 22:21:31 +0000683 ExprGuard LHSGuard(Actions, LHS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000684 // Now that the primary-expression piece of the postfix-expression has been
685 // parsed, see if there are any postfix-expression pieces here.
686 SourceLocation Loc;
687 while (1) {
688 switch (Tok.getKind()) {
689 default: // Not a postfix-expression suffix.
Sebastian Redla55e52c2008-11-25 22:21:31 +0000690 LHSGuard.take();
Reid Spencer5f016e22007-07-11 17:01:13 +0000691 return LHS;
692 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
693 Loc = ConsumeBracket();
694 ExprResult Idx = ParseExpression();
Sebastian Redla55e52c2008-11-25 22:21:31 +0000695 ExprGuard IdxGuard(Actions, Idx);
696
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 SourceLocation RLoc = Tok.getLocation();
698
Sebastian Redla55e52c2008-11-25 22:21:31 +0000699 if (!LHS.isInvalid && !Idx.isInvalid && Tok.is(tok::r_square)) {
700 LHS = Actions.ActOnArraySubscriptExpr(CurScope, LHSGuard.take(), Loc,
701 IdxGuard.take(), RLoc);
702 LHSGuard.reset(LHS);
703 } else
Reid Spencer5f016e22007-07-11 17:01:13 +0000704 LHS = ExprResult(true);
705
706 // Match the ']'.
707 MatchRHSPunctuation(tok::r_square, Loc);
708 break;
709 }
710
711 case tok::l_paren: { // p-e: p-e '(' argument-expression-list[opt] ')'
Sebastian Redla55e52c2008-11-25 22:21:31 +0000712 ExprVector ArgExprs(Actions);
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +0000713 CommaLocsTy CommaLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000714
715 Loc = ConsumeParen();
716
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000717 if (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +0000718 if (ParseExpressionList(ArgExprs, CommaLocs)) {
719 SkipUntil(tok::r_paren);
720 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000721 }
722 }
723
724 // Match the ')'.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000725 if (!LHS.isInvalid && Tok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&&
727 "Unexpected number of commas!");
Sebastian Redla55e52c2008-11-25 22:21:31 +0000728 LHS = Actions.ActOnCallExpr(LHSGuard.take(), Loc, ArgExprs.take(),
729 ArgExprs.size(), &CommaLocs[0],
730 Tok.getLocation());
731 LHSGuard.reset(LHS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000732 }
733
Chris Lattner2ff54262007-07-21 05:18:12 +0000734 MatchRHSPunctuation(tok::r_paren, Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000735 break;
736 }
737 case tok::arrow: // postfix-expression: p-e '->' identifier
738 case tok::period: { // postfix-expression: p-e '.' identifier
739 tok::TokenKind OpKind = Tok.getKind();
740 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
741
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000742 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000743 Diag(Tok, diag::err_expected_ident);
744 return ExprResult(true);
745 }
746
Sebastian Redla55e52c2008-11-25 22:21:31 +0000747 if (!LHS.isInvalid) {
748 LHS = Actions.ActOnMemberReferenceExpr(LHSGuard.take(), OpLoc, OpKind,
Reid Spencer5f016e22007-07-11 17:01:13 +0000749 Tok.getLocation(),
750 *Tok.getIdentifierInfo());
Sebastian Redla55e52c2008-11-25 22:21:31 +0000751 LHSGuard.reset(LHS);
752 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000753 ConsumeToken();
754 break;
755 }
756 case tok::plusplus: // postfix-expression: postfix-expression '++'
757 case tok::minusminus: // postfix-expression: postfix-expression '--'
Sebastian Redla55e52c2008-11-25 22:21:31 +0000758 if (!LHS.isInvalid) {
Douglas Gregor74253732008-11-19 15:42:04 +0000759 LHS = Actions.ActOnPostfixUnaryOp(CurScope, Tok.getLocation(),
Sebastian Redla55e52c2008-11-25 22:21:31 +0000760 Tok.getKind(), LHSGuard.take());
761 LHSGuard.reset(LHS);
762 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 ConsumeToken();
764 break;
765 }
766 }
767}
768
769
770/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression.
771/// unary-expression: [C99 6.5.3]
772/// 'sizeof' unary-expression
773/// 'sizeof' '(' type-name ')'
774/// [GNU] '__alignof' unary-expression
775/// [GNU] '__alignof' '(' type-name ')'
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000776/// [C++0x] 'alignof' '(' type-id ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000777Parser::ExprResult Parser::ParseSizeofAlignofExpression() {
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000778 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof)
779 || Tok.is(tok::kw_alignof)) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000780 "Not a sizeof/alignof expression!");
Chris Lattnerd2177732007-07-20 16:59:19 +0000781 Token OpTok = Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000782 ConsumeToken();
783
784 // If the operand doesn't start with an '(', it must be an expression.
785 ExprResult Operand;
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000786 if (Tok.isNot(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000787 Operand = ParseCastExpression(true);
788 } else {
789 // If it starts with a '(', we know that it is either a parenthesized
790 // type-name, or it is a unary-expression that starts with a compound
791 // literal, or starts with a primary-expression that is a parenthesized
792 // expression.
793 ParenParseOption ExprType = CastExpr;
794 TypeTy *CastTy;
795 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
796 Operand = ParseParenExpression(ExprType, CastTy, RParenLoc);
797
798 // If ParseParenExpression parsed a '(typename)' sequence only, the this is
799 // sizeof/alignof a type. Otherwise, it is sizeof/alignof an expression.
Chris Lattner4c1a2a92007-11-13 20:50:37 +0000800 if (ExprType == CastExpr)
Sebastian Redl05189992008-11-11 17:56:53 +0000801 return Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
802 OpTok.is(tok::kw_sizeof),
803 /*isType=*/true, CastTy,
804 SourceRange(LParenLoc, RParenLoc));
Chris Lattner4c1a2a92007-11-13 20:50:37 +0000805
806 // If this is a parenthesized expression, it is the start of a
807 // unary-expression, but doesn't include any postfix pieces. Parse these
808 // now if present.
809 Operand = ParsePostfixExpressionSuffix(Operand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 }
811
812 // If we get here, the operand to the sizeof/alignof was an expresion.
813 if (!Operand.isInvalid)
Sebastian Redl05189992008-11-11 17:56:53 +0000814 Operand = Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
815 OpTok.is(tok::kw_sizeof),
816 /*isType=*/false, Operand.Val,
817 SourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000818 return Operand;
819}
820
821/// ParseBuiltinPrimaryExpression
822///
823/// primary-expression: [C99 6.5.1]
824/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
825/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
826/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
827/// assign-expr ')'
828/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
Nate Begemane2ce1d92008-01-17 17:46:27 +0000829/// [CLANG] '__builtin_overload' '(' expr (',' expr)* ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000830///
831/// [GNU] offsetof-member-designator:
832/// [GNU] identifier
833/// [GNU] offsetof-member-designator '.' identifier
834/// [GNU] offsetof-member-designator '[' expression ']'
835///
836Parser::ExprResult Parser::ParseBuiltinPrimaryExpression() {
837 ExprResult Res(false);
838 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
839
840 tok::TokenKind T = Tok.getKind();
841 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
842
843 // All of these start with an open paren.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000844 if (Tok.isNot(tok::l_paren)) {
Chris Lattner08631c52008-11-23 21:45:46 +0000845 Diag(Tok, diag::err_expected_lparen_after_id) << BuiltinII;
Reid Spencer5f016e22007-07-11 17:01:13 +0000846 return ExprResult(true);
847 }
848
849 SourceLocation LParenLoc = ConsumeParen();
850 // TODO: Build AST.
851
852 switch (T) {
853 default: assert(0 && "Not a builtin primary expression!");
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000854 case tok::kw___builtin_va_arg: {
855 ExprResult Expr = ParseAssignmentExpression();
Sebastian Redla55e52c2008-11-25 22:21:31 +0000856 ExprGuard ExprGuard(Actions, Expr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000857 if (Expr.isInvalid) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000858 SkipUntil(tok::r_paren);
Eli Friedman09762782008-08-20 22:07:34 +0000859 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000860 }
861
862 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
863 return ExprResult(true);
864
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000865 TypeTy *Ty = ParseTypeName();
Chris Lattner6eb21092007-08-30 15:52:49 +0000866
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000867 if (Tok.isNot(tok::r_paren)) {
868 Diag(Tok, diag::err_expected_rparen);
869 return ExprResult(true);
870 }
Sebastian Redla55e52c2008-11-25 22:21:31 +0000871 Res = Actions.ActOnVAArg(StartLoc, ExprGuard.take(), Ty, ConsumeParen());
Reid Spencer5f016e22007-07-11 17:01:13 +0000872 break;
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000873 }
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000874 case tok::kw___builtin_offsetof: {
Chris Lattner9fddf0a2007-08-30 17:08:45 +0000875 SourceLocation TypeLoc = Tok.getLocation();
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000876 TypeTy *Ty = ParseTypeName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000877
878 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
879 return ExprResult(true);
880
881 // We must have at least one identifier here.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000882 if (Tok.isNot(tok::identifier)) {
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000883 Diag(Tok, diag::err_expected_ident);
884 SkipUntil(tok::r_paren);
885 return true;
886 }
887
888 // Keep track of the various subcomponents we see.
889 llvm::SmallVector<Action::OffsetOfComponent, 4> Comps;
890
891 Comps.push_back(Action::OffsetOfComponent());
892 Comps.back().isBrackets = false;
893 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
894 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
Reid Spencer5f016e22007-07-11 17:01:13 +0000895
Sebastian Redla55e52c2008-11-25 22:21:31 +0000896 // FIXME: This loop leaks the index expressions on error.
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 while (1) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000898 if (Tok.is(tok::period)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000899 // offsetof-member-designator: offsetof-member-designator '.' identifier
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000900 Comps.push_back(Action::OffsetOfComponent());
901 Comps.back().isBrackets = false;
902 Comps.back().LocStart = ConsumeToken();
Reid Spencer5f016e22007-07-11 17:01:13 +0000903
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000904 if (Tok.isNot(tok::identifier)) {
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000905 Diag(Tok, diag::err_expected_ident);
906 SkipUntil(tok::r_paren);
907 return true;
908 }
909 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
910 Comps.back().LocEnd = ConsumeToken();
911
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000912 } else if (Tok.is(tok::l_square)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000913 // offsetof-member-designator: offsetof-member-design '[' expression ']'
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000914 Comps.push_back(Action::OffsetOfComponent());
915 Comps.back().isBrackets = true;
916 Comps.back().LocStart = ConsumeBracket();
Reid Spencer5f016e22007-07-11 17:01:13 +0000917 Res = ParseExpression();
918 if (Res.isInvalid) {
919 SkipUntil(tok::r_paren);
920 return Res;
921 }
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000922 Comps.back().U.E = Res.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000923
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000924 Comps.back().LocEnd =
925 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart);
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000926 } else if (Tok.is(tok::r_paren)) {
Steve Naroff1b273c42007-09-16 14:56:35 +0000927 Res = Actions.ActOnBuiltinOffsetOf(StartLoc, TypeLoc, Ty, &Comps[0],
Chris Lattner6eb21092007-08-30 15:52:49 +0000928 Comps.size(), ConsumeParen());
929 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000930 } else {
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000931 // Error occurred.
932 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000933 }
934 }
935 break;
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000936 }
Steve Naroffd04fdd52007-08-03 21:21:27 +0000937 case tok::kw___builtin_choose_expr: {
938 ExprResult Cond = ParseAssignmentExpression();
Sebastian Redla55e52c2008-11-25 22:21:31 +0000939 ExprGuard CondGuard(Actions, Cond);
Steve Naroffd04fdd52007-08-03 21:21:27 +0000940 if (Cond.isInvalid) {
941 SkipUntil(tok::r_paren);
942 return Cond;
943 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000944 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
945 return ExprResult(true);
946
Steve Naroffd04fdd52007-08-03 21:21:27 +0000947 ExprResult Expr1 = ParseAssignmentExpression();
Sebastian Redla55e52c2008-11-25 22:21:31 +0000948 ExprGuard Guard1(Actions, Expr1);
Steve Naroffd04fdd52007-08-03 21:21:27 +0000949 if (Expr1.isInvalid) {
950 SkipUntil(tok::r_paren);
951 return Expr1;
952 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000953 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
954 return ExprResult(true);
955
Steve Naroffd04fdd52007-08-03 21:21:27 +0000956 ExprResult Expr2 = ParseAssignmentExpression();
Sebastian Redla55e52c2008-11-25 22:21:31 +0000957 ExprGuard Guard2(Actions, Expr2);
Steve Naroffd04fdd52007-08-03 21:21:27 +0000958 if (Expr2.isInvalid) {
959 SkipUntil(tok::r_paren);
960 return Expr2;
961 }
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000962 if (Tok.isNot(tok::r_paren)) {
Steve Naroffd04fdd52007-08-03 21:21:27 +0000963 Diag(Tok, diag::err_expected_rparen);
964 return ExprResult(true);
965 }
Sebastian Redla55e52c2008-11-25 22:21:31 +0000966 Res = Actions.ActOnChooseExpr(StartLoc, CondGuard.take(), Guard1.take(),
967 Guard2.take(), ConsumeParen());
Chris Lattner6eb21092007-08-30 15:52:49 +0000968 break;
Steve Naroffd04fdd52007-08-03 21:21:27 +0000969 }
Nate Begemane2ce1d92008-01-17 17:46:27 +0000970 case tok::kw___builtin_overload: {
Sebastian Redla55e52c2008-11-25 22:21:31 +0000971 ExprVector ArgExprs(Actions);
Nate Begemane2ce1d92008-01-17 17:46:27 +0000972 llvm::SmallVector<SourceLocation, 8> CommaLocs;
973
974 // For each iteration through the loop look for assign-expr followed by a
975 // comma. If there is no comma, break and attempt to match r-paren.
976 if (Tok.isNot(tok::r_paren)) {
977 while (1) {
978 ExprResult ArgExpr = ParseAssignmentExpression();
979 if (ArgExpr.isInvalid) {
980 SkipUntil(tok::r_paren);
981 return ExprResult(true);
982 } else
983 ArgExprs.push_back(ArgExpr.Val);
984
985 if (Tok.isNot(tok::comma))
986 break;
987 // Move to the next argument, remember where the comma was.
988 CommaLocs.push_back(ConsumeToken());
989 }
990 }
991
992 // Attempt to consume the r-paren
993 if (Tok.isNot(tok::r_paren)) {
994 Diag(Tok, diag::err_expected_rparen);
995 SkipUntil(tok::r_paren);
996 return ExprResult(true);
997 }
Sebastian Redla55e52c2008-11-25 22:21:31 +0000998 Res = Actions.ActOnOverloadExpr(ArgExprs.take(), ArgExprs.size(),
Nate Begemane2ce1d92008-01-17 17:46:27 +0000999 &CommaLocs[0], StartLoc, ConsumeParen());
1000 break;
1001 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001002 case tok::kw___builtin_types_compatible_p:
Steve Naroff363bcff2007-08-01 23:45:51 +00001003 TypeTy *Ty1 = ParseTypeName();
Reid Spencer5f016e22007-07-11 17:01:13 +00001004
1005 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1006 return ExprResult(true);
1007
Steve Naroff363bcff2007-08-01 23:45:51 +00001008 TypeTy *Ty2 = ParseTypeName();
1009
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001010 if (Tok.isNot(tok::r_paren)) {
Steve Naroff363bcff2007-08-01 23:45:51 +00001011 Diag(Tok, diag::err_expected_rparen);
1012 return ExprResult(true);
1013 }
Steve Naroff1b273c42007-09-16 14:56:35 +00001014 Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1, Ty2, ConsumeParen());
Chris Lattner6eb21092007-08-30 15:52:49 +00001015 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001016 }
1017
Reid Spencer5f016e22007-07-11 17:01:13 +00001018 // These can be followed by postfix-expr pieces because they are
1019 // primary-expressions.
1020 return ParsePostfixExpressionSuffix(Res);
1021}
1022
1023/// ParseParenExpression - This parses the unit that starts with a '(' token,
1024/// based on what is allowed by ExprType. The actual thing parsed is returned
1025/// in ExprType.
1026///
1027/// primary-expression: [C99 6.5.1]
1028/// '(' expression ')'
1029/// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
1030/// postfix-expression: [C99 6.5.2]
1031/// '(' type-name ')' '{' initializer-list '}'
1032/// '(' type-name ')' '{' initializer-list ',' '}'
1033/// cast-expression: [C99 6.5.4]
1034/// '(' type-name ')' cast-expression
1035///
1036Parser::ExprResult Parser::ParseParenExpression(ParenParseOption &ExprType,
1037 TypeTy *&CastTy,
1038 SourceLocation &RParenLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001039 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001040 SourceLocation OpenLoc = ConsumeParen();
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001041 ExprResult Result(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001042 CastTy = 0;
1043
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001044 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001045 Diag(Tok, diag::ext_gnu_statement_expr);
Chris Lattner98414c12007-08-31 21:49:55 +00001046 Parser::StmtResult Stmt = ParseCompoundStatement(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001047 ExprType = CompoundStmt;
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001048
1049 // If the substmt parsed correctly, build the AST node.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001050 if (!Stmt.isInvalid && Tok.is(tok::r_paren))
Steve Naroff1b273c42007-09-16 14:56:35 +00001051 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.Val, Tok.getLocation());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001052
Argyrios Kyrtzidis78c8d802008-10-05 19:56:22 +00001053 } else if (ExprType >= CompoundLiteral && isTypeIdInParens()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001054 // Otherwise, this is a compound literal expression or cast expression.
1055 TypeTy *Ty = ParseTypeName();
1056
1057 // Match the ')'.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001058 if (Tok.is(tok::r_paren))
Reid Spencer5f016e22007-07-11 17:01:13 +00001059 RParenLoc = ConsumeParen();
1060 else
1061 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1062
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001063 if (Tok.is(tok::l_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001064 if (!getLang().C99) // Compound literals don't exist in C90.
1065 Diag(OpenLoc, diag::ext_c99_compound_literal);
1066 Result = ParseInitializer();
1067 ExprType = CompoundLiteral;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001068 if (!Result.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +00001069 return Actions.ActOnCompoundLiteral(OpenLoc, Ty, RParenLoc, Result.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +00001070 } else if (ExprType == CastExpr) {
1071 // Note that this doesn't parse the subsequence cast-expression, it just
1072 // returns the parsed type to the callee.
1073 ExprType = CastExpr;
1074 CastTy = Ty;
1075 return ExprResult(false);
1076 } else {
1077 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
1078 return ExprResult(true);
1079 }
1080 return Result;
1081 } else {
1082 Result = ParseExpression();
1083 ExprType = SimpleExpr;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001084 if (!Result.isInvalid && Tok.is(tok::r_paren))
Steve Narofff69936d2007-09-16 03:34:24 +00001085 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +00001086 }
1087
1088 // Match the ')'.
1089 if (Result.isInvalid)
1090 SkipUntil(tok::r_paren);
1091 else {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001092 if (Tok.is(tok::r_paren))
Reid Spencer5f016e22007-07-11 17:01:13 +00001093 RParenLoc = ConsumeParen();
1094 else
1095 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1096 }
1097
1098 return Result;
1099}
1100
1101/// ParseStringLiteralExpression - This handles the various token types that
1102/// form string literals, and also handles string concatenation [C99 5.1.1.2,
1103/// translation phase #6].
1104///
1105/// primary-expression: [C99 6.5.1]
1106/// string-literal
1107Parser::ExprResult Parser::ParseStringLiteralExpression() {
1108 assert(isTokenStringLiteral() && "Not a string literal!");
1109
1110 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
1111 // considered to be strings for concatenation purposes.
Chris Lattnerd2177732007-07-20 16:59:19 +00001112 llvm::SmallVector<Token, 4> StringToks;
Reid Spencer5f016e22007-07-11 17:01:13 +00001113
1114 do {
1115 StringToks.push_back(Tok);
1116 ConsumeStringToken();
1117 } while (isTokenStringLiteral());
1118
1119 // Pass the set of string tokens, ready for concatenation, to the actions.
Steve Narofff69936d2007-09-16 03:34:24 +00001120 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size());
Reid Spencer5f016e22007-07-11 17:01:13 +00001121}
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +00001122
1123/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1124///
1125/// argument-expression-list:
1126/// assignment-expression
1127/// argument-expression-list , assignment-expression
1128///
1129/// [C++] expression-list:
1130/// [C++] assignment-expression
1131/// [C++] expression-list , assignment-expression
1132///
1133bool Parser::ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs) {
1134 while (1) {
1135 ExprResult Expr = ParseAssignmentExpression();
1136 if (Expr.isInvalid)
1137 return true;
Argyrios Kyrtzidis4fdc1ca2008-08-18 22:49:40 +00001138
1139 Exprs.push_back(Expr.Val);
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +00001140
1141 if (Tok.isNot(tok::comma))
1142 return false;
1143 // Move to the next argument, remember where the comma was.
1144 CommaLocs.push_back(ConsumeToken());
1145 }
1146}
Steve Naroff296e8d52008-08-28 19:20:44 +00001147
1148/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
Steve Naroff17dab4f2008-09-16 23:11:46 +00001149/// like ^(int x){ return x+1; }
Steve Naroff296e8d52008-08-28 19:20:44 +00001150///
1151/// block-literal:
1152/// [clang] '^' block-args[opt] compound-statement
Steve Naroff296e8d52008-08-28 19:20:44 +00001153/// [clang] block-args:
1154/// [clang] '(' parameter-list ')'
1155///
1156Parser::ExprResult Parser::ParseBlockLiteralExpression() {
1157 assert(Tok.is(tok::caret) && "block literal starts with ^");
1158 SourceLocation CaretLoc = ConsumeToken();
1159
1160 // Enter a scope to hold everything within the block. This includes the
1161 // argument decls, decls within the compound expression, etc. This also
1162 // allows determining whether a variable reference inside the block is
1163 // within or outside of the block.
1164 EnterScope(Scope::BlockScope|Scope::FnScope|Scope::BreakScope|
1165 Scope::ContinueScope|Scope::DeclScope);
Steve Naroff090276f2008-10-10 01:28:17 +00001166
1167 // Inform sema that we are starting a block.
1168 Actions.ActOnBlockStart(CaretLoc, CurScope);
Steve Naroff296e8d52008-08-28 19:20:44 +00001169
1170 // Parse the return type if present.
1171 DeclSpec DS;
1172 Declarator ParamInfo(DS, Declarator::PrototypeContext);
1173
1174 // If this block has arguments, parse them. There is no ambiguity here with
1175 // the expression case, because the expression case requires a parameter list.
1176 if (Tok.is(tok::l_paren)) {
1177 ParseParenDeclarator(ParamInfo);
1178 // Parse the pieces after the identifier as if we had "int(...)".
1179 ParamInfo.SetIdentifier(0, CaretLoc);
1180 if (ParamInfo.getInvalidType()) {
1181 // If there was an error parsing the arguments, they may have tried to use
1182 // ^(x+y) which requires an argument list. Just skip the whole block
1183 // literal.
1184 ExitScope();
1185 return true;
1186 }
1187 } else {
1188 // Otherwise, pretend we saw (void).
1189 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001190 0, 0, 0, CaretLoc));
Steve Naroff296e8d52008-08-28 19:20:44 +00001191 }
1192
1193 // Inform sema that we are starting a block.
Steve Naroff090276f2008-10-10 01:28:17 +00001194 Actions.ActOnBlockArguments(ParamInfo);
Steve Naroff296e8d52008-08-28 19:20:44 +00001195
Steve Naroff17dab4f2008-09-16 23:11:46 +00001196 ExprResult Result = true;
Steve Naroff296e8d52008-08-28 19:20:44 +00001197 if (Tok.is(tok::l_brace)) {
1198 StmtResult Stmt = ParseCompoundStatementBody();
1199 if (!Stmt.isInvalid) {
1200 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.Val, CurScope);
1201 } else {
1202 Actions.ActOnBlockError(CaretLoc, CurScope);
Steve Naroff296e8d52008-08-28 19:20:44 +00001203 }
1204 }
Steve Naroff296e8d52008-08-28 19:20:44 +00001205 ExitScope();
1206 return Result;
1207}
1208