blob: 66b1d180780b83648ac191aa5c724ffffc65d91a [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expression parsing implementation. Expressions in
11// C99 basically consist of a bunch of binary operators with unary operators and
12// other random stuff at the leaves.
13//
14// In the C99 grammar, these unary operators bind tightest and are represented
15// as the 'cast-expression' production. Everything else is either a binary
16// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are
17// handled by ParseCastExpression, the higher level pieces are handled by
18// ParseBinaryExpression.
19//
20//===----------------------------------------------------------------------===//
21
22#include "clang/Parse/Parser.h"
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +000023#include "clang/Parse/DeclSpec.h"
Steve Narofffd5b19d2008-08-28 19:20:44 +000024#include "clang/Parse/Scope.h"
Chris Lattnerdaa5c002008-10-20 06:45:43 +000025#include "ExtensionRAIIObject.h"
Sebastian Redl6008ac32008-11-25 22:21:31 +000026#include "AstGuard.h"
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnera7447ba2008-02-26 00:51:44 +0000163/// [C++] throw-expression [C++ 15]
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnera7447ba2008-02-26 00:51:44 +0000173 if (Tok.is(tok::kw_throw))
174 return ParseThrowExpression();
175
Chris Lattner4b009652007-07-25 00:24:17 +0000176 ExprResult LHS = ParseCastExpression(false);
177 if (LHS.isInvalid) return LHS;
178
179 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
180}
181
Fariborz Jahanian64b864e2007-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 Lattnerb82d6ef2007-10-03 22:03:06 +0000184/// routine is necessary to disambiguate @try-statement from,
185/// for example, @encode-expression.
Fariborz Jahanian64b864e2007-09-19 19:14:32 +0000186///
Fariborz Jahanian37c9c612007-10-04 20:19:06 +0000187Parser::ExprResult Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
Steve Narofffb9dd752007-10-15 20:55:58 +0000188 ExprResult LHS = ParseObjCAtExpression(AtLoc);
Fariborz Jahanian64b864e2007-09-19 19:14:32 +0000189 if (LHS.isInvalid) return LHS;
190
191 return ParseRHSOfBinaryExpression(LHS, prec::Comma);
192}
193
Chris Lattner4b009652007-07-25 00:24:17 +0000194/// ParseAssignmentExpression - Parse an expr that doesn't include commas.
195///
196Parser::ExprResult Parser::ParseAssignmentExpression() {
Chris Lattnera7447ba2008-02-26 00:51:44 +0000197 if (Tok.is(tok::kw_throw))
198 return ParseThrowExpression();
199
Chris Lattner4b009652007-07-25 00:24:17 +0000200 ExprResult LHS = ParseCastExpression(false);
201 if (LHS.isInvalid) return LHS;
202
203 return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
204}
205
Chris Lattnerbfcf4772008-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 Naroffc64a53d2008-11-19 15:54:23 +0000216 SourceLocation NameLoc,
Chris Lattnerbfcf4772008-06-02 21:31:07 +0000217 IdentifierInfo *ReceiverName,
218 ExprTy *ReceiverExpr) {
Steve Naroffc64a53d2008-11-19 15:54:23 +0000219 ExprResult R = ParseObjCMessageExpressionBody(LBracLoc, NameLoc, ReceiverName,
Chris Lattnerbfcf4772008-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
Chris Lattner4b009652007-07-25 00:24:17 +0000228Parser::ExprResult Parser::ParseConstantExpression() {
229 ExprResult LHS = ParseCastExpression(false);
230 if (LHS.isInvalid) return LHS;
231
Chris Lattner4b009652007-07-25 00:24:17 +0000232 return ParseRHSOfBinaryExpression(LHS, prec::Conditional);
233}
234
Chris Lattner4b009652007-07-25 00:24:17 +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 Redl6008ac32008-11-25 22:21:31 +0000242 ExprGuard LHSGuard(Actions, LHS);
Chris Lattner4b009652007-07-25 00:24:17 +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 Redl6008ac32008-11-25 22:21:31 +0000247 if (NextTokPrec < MinPrec) {
248 LHSGuard.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000249 return LHS;
Sebastian Redl6008ac32008-11-25 22:21:31 +0000250 }
Chris Lattner4b009652007-07-25 00:24:17 +0000251
252 // Consume the operator, saving the operator token for error reporting.
253 Token OpToken = Tok;
254 ConsumeToken();
255
256 // Special case handling for the ternary operator.
257 ExprResult TernaryMiddle(true);
Sebastian Redl6008ac32008-11-25 22:21:31 +0000258 ExprGuard MiddleGuard(Actions);
Chris Lattner4b009652007-07-25 00:24:17 +0000259 if (NextTokPrec == prec::Conditional) {
Chris Lattner4d7d2342007-10-09 17:41:39 +0000260 if (Tok.isNot(tok::colon)) {
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner214cbaf2007-08-31 04:58:34 +0000266 if (TernaryMiddle.isInvalid) {
Chris Lattner214cbaf2007-08-31 04:58:34 +0000267 return TernaryMiddle;
268 }
Chris Lattner4b009652007-07-25 00:24:17 +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 Redl6008ac32008-11-25 22:21:31 +0000275 MiddleGuard.reset(TernaryMiddle);
Chris Lattner4b009652007-07-25 00:24:17 +0000276
Chris Lattner4d7d2342007-10-09 17:41:39 +0000277 if (Tok.isNot(tok::colon)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000278 Diag(Tok, diag::err_expected_colon);
Chris Lattner921342c2008-11-23 23:17:07 +0000279 Diag(OpToken, diag::note_matching) << "?";
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner214cbaf2007-08-31 04:58:34 +0000289 if (RHS.isInvalid) {
Chris Lattner214cbaf2007-08-31 04:58:34 +0000290 return RHS;
291 }
Sebastian Redl6008ac32008-11-25 22:21:31 +0000292 ExprGuard RHSGuard(Actions, RHS);
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner464c7f62007-12-18 06:06:23 +0000300 bool isRightAssoc = ThisPrec == prec::Conditional ||
301 ThisPrec == prec::Assignment;
Chris Lattner4b009652007-07-25 00:24:17 +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 Redl6008ac32008-11-25 22:21:31 +0000311 // The function takes ownership of the RHS.
312 RHSGuard.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000313 RHS = ParseRHSOfBinaryExpression(RHS, ThisPrec + !isRightAssoc);
Chris Lattner214cbaf2007-08-31 04:58:34 +0000314 if (RHS.isInvalid) {
Chris Lattner214cbaf2007-08-31 04:58:34 +0000315 return RHS;
316 }
Sebastian Redl6008ac32008-11-25 22:21:31 +0000317 RHSGuard.reset(RHS);
Chris Lattner4b009652007-07-25 00:24:17 +0000318
319 NextTokPrec = getBinOpPrecedence(Tok.getKind());
320 }
321 assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
Sebastian Redl6008ac32008-11-25 22:21:31 +0000322
Chris Lattner4a149b62007-08-31 05:01:50 +0000323 if (!LHS.isInvalid) {
324 // Combine the LHS and RHS into the LHS (e.g. build AST).
Sebastian Redl6008ac32008-11-25 22:21:31 +0000325 LHSGuard.take();
326 MiddleGuard.take();
327 RHSGuard.take();
Chris Lattner4a149b62007-08-31 05:01:50 +0000328 if (TernaryMiddle.isInvalid)
Douglas Gregord7f915e2008-11-06 23:29:22 +0000329 LHS = Actions.ActOnBinOp(CurScope, OpToken.getLocation(),
330 OpToken.getKind(), LHS.Val, RHS.Val);
Chris Lattner4a149b62007-08-31 05:01:50 +0000331 else
Steve Naroff87d58b42007-09-16 03:34:24 +0000332 LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
Chris Lattner4a149b62007-08-31 05:01:50 +0000333 LHS.Val, TernaryMiddle.Val, RHS.Val);
Sebastian Redl6008ac32008-11-25 22:21:31 +0000334 LHSGuard.reset(LHS);
Chris Lattner4a149b62007-08-31 05:01:50 +0000335 }
Sebastian Redl6008ac32008-11-25 22:21:31 +0000336 // If we had an invalid LHS, Middle and RHS will be freed by the guards here
Chris Lattner4b009652007-07-25 00:24:17 +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 Gregor658b4442008-11-06 15:17:27 +0000356/// [C++0x] 'alignof' '(' type-id ')'
Chris Lattner4b009652007-07-25 00:24:17 +0000357/// [GNU] '&&' identifier
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000358/// [C++] new-expression
359/// [C++] delete-expression
Chris Lattner4b009652007-07-25 00:24:17 +0000360///
361/// unary-operator: one of
362/// '&' '*' '+' '-' '~' '!'
363/// [GNU] '__extension__' '__real' '__imag'
364///
365/// primary-expression: [C99 6.5.1]
Douglas Gregore60e5d32008-11-06 22:13:31 +0000366/// [C99] identifier
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000367/// [C++] id-expression
Chris Lattner4b009652007-07-25 00:24:17 +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 Jahanian628abf12007-09-26 17:03:44 +0000381/// [OBJC] '[' objc-message-expr ']'
Chris Lattner8d050af2008-01-25 18:58:06 +0000382/// [OBJC] '@selector' '(' objc-selector-arg ')'
Fariborz Jahanian628abf12007-09-26 17:03:44 +0000383/// [OBJC] '@protocol' '(' identifier ')'
384/// [OBJC] '@encode' '(' type-name ')'
Fariborz Jahanian1e534dc2007-09-05 19:52:07 +0000385/// [OBJC] objc-string-literal
Argiris Kirtzidis7a1e7412008-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]
Chris Lattner4b009652007-07-25 00:24:17 +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 Redlb93b49c2008-11-11 11:37:55 +0000392/// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
393/// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
Argiris Kirtzidisfdde2762008-07-16 07:23:27 +0000394/// [C++] 'this' [C++ 9.3.2]
Steve Narofffd5b19d2008-08-28 19:20:44 +0000395/// [clang] '^' block-literal
Chris Lattner4b009652007-07-25 00:24:17 +0000396///
397/// constant: [C99 6.4.4]
398/// integer-constant
399/// floating-constant
400/// enumeration-constant -> identifier
401/// character-constant
402///
Douglas Gregore60e5d32008-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]
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000413///
Sebastian Redl19fec9d2008-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///
Chris Lattner4b009652007-07-25 00:24:17 +0000424Parser::ExprResult Parser::ParseCastExpression(bool isUnaryExpression) {
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000425 if (getLang().CPlusPlus) {
426 // Annotate typenames and C++ scope specifiers.
Argiris Kirtzidisfc332322008-11-26 21:51:07 +0000427 // Used only in C++, where the typename can be considered as a functional
428 // style cast ("int(1)").
429 // In C we don't expect identifiers to be treated as typenames; if it's a
430 // typedef name, let it be handled as an identifier and
431 // Actions.ActOnIdentifierExpr will emit the proper diagnostic.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000432 TryAnnotateTypeOrScopeToken();
433 }
434
Chris Lattner4b009652007-07-25 00:24:17 +0000435 ExprResult Res;
436 tok::TokenKind SavedKind = Tok.getKind();
437
438 // This handles all of cast-expression, unary-expression, postfix-expression,
439 // and primary-expression. We handle them together like this for efficiency
440 // and to simplify handling of an expression starting with a '(' token: which
441 // may be one of a parenthesized expression, cast-expression, compound literal
442 // expression, or statement expression.
443 //
444 // If the parsed tokens consist of a primary-expression, the cases below
445 // call ParsePostfixExpressionSuffix to handle the postfix expression
446 // suffixes. Cases that cannot be followed by postfix exprs should
447 // return without invoking ParsePostfixExpressionSuffix.
448 switch (SavedKind) {
449 case tok::l_paren: {
450 // If this expression is limited to being a unary-expression, the parent can
451 // not start a cast expression.
452 ParenParseOption ParenExprType =
453 isUnaryExpression ? CompoundLiteral : CastExpr;
454 TypeTy *CastTy;
455 SourceLocation LParenLoc = Tok.getLocation();
456 SourceLocation RParenLoc;
457 Res = ParseParenExpression(ParenExprType, CastTy, RParenLoc);
458 if (Res.isInvalid) return Res;
459
460 switch (ParenExprType) {
461 case SimpleExpr: break; // Nothing else to do.
462 case CompoundStmt: break; // Nothing else to do.
463 case CompoundLiteral:
464 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
465 // postfix-expression exist, parse them now.
466 break;
467 case CastExpr:
468 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. Parse
469 // the cast-expression that follows it next.
470 // TODO: For cast expression with CastTy.
471 Res = ParseCastExpression(false);
472 if (!Res.isInvalid)
Steve Naroff87d58b42007-09-16 03:34:24 +0000473 Res = Actions.ActOnCastExpr(LParenLoc, CastTy, RParenLoc, Res.Val);
Chris Lattner4b009652007-07-25 00:24:17 +0000474 return Res;
475 }
476
477 // These can be followed by postfix-expr pieces.
478 return ParsePostfixExpressionSuffix(Res);
479 }
480
481 // primary-expression
482 case tok::numeric_constant:
483 // constant: integer-constant
484 // constant: floating-constant
485
Steve Naroff87d58b42007-09-16 03:34:24 +0000486 Res = Actions.ActOnNumericConstant(Tok);
Chris Lattner4b009652007-07-25 00:24:17 +0000487 ConsumeToken();
488
489 // These can be followed by postfix-expr pieces.
490 return ParsePostfixExpressionSuffix(Res);
491
492 case tok::kw_true:
493 case tok::kw_false:
494 return ParseCXXBoolLiteral();
495
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000496 case tok::identifier: { // primary-expression: identifier
497 // unqualified-id: identifier
498 // constant: enumeration-constant
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000499
Chris Lattner4b009652007-07-25 00:24:17 +0000500 // Consume the identifier so that we can see if it is followed by a '('.
501 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
502 // need to know whether or not this identifier is a function designator or
503 // not.
504 IdentifierInfo &II = *Tok.getIdentifierInfo();
505 SourceLocation L = ConsumeToken();
Chris Lattner4d7d2342007-10-09 17:41:39 +0000506 Res = Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren));
Chris Lattner4b009652007-07-25 00:24:17 +0000507 // These can be followed by postfix-expr pieces.
508 return ParsePostfixExpressionSuffix(Res);
509 }
510 case tok::char_constant: // constant: character-constant
Steve Naroff87d58b42007-09-16 03:34:24 +0000511 Res = Actions.ActOnCharacterConstant(Tok);
Chris Lattner4b009652007-07-25 00:24:17 +0000512 ConsumeToken();
513 // These can be followed by postfix-expr pieces.
514 return ParsePostfixExpressionSuffix(Res);
515 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
516 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
517 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Chris Lattner69909292008-08-10 01:53:14 +0000518 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
Chris Lattner4b009652007-07-25 00:24:17 +0000519 ConsumeToken();
520 // These can be followed by postfix-expr pieces.
521 return ParsePostfixExpressionSuffix(Res);
522 case tok::string_literal: // primary-expression: string-literal
523 case tok::wide_string_literal:
524 Res = ParseStringLiteralExpression();
525 if (Res.isInvalid) return Res;
526 // This can be followed by postfix-expr pieces (e.g. "foo"[1]).
527 return ParsePostfixExpressionSuffix(Res);
528 case tok::kw___builtin_va_arg:
529 case tok::kw___builtin_offsetof:
530 case tok::kw___builtin_choose_expr:
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000531 case tok::kw___builtin_overload:
Chris Lattner4b009652007-07-25 00:24:17 +0000532 case tok::kw___builtin_types_compatible_p:
533 return ParseBuiltinPrimaryExpression();
534 case tok::plusplus: // unary-expression: '++' unary-expression
535 case tok::minusminus: { // unary-expression: '--' unary-expression
536 SourceLocation SavedLoc = ConsumeToken();
537 Res = ParseCastExpression(true);
538 if (!Res.isInvalid)
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000539 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Chris Lattner4b009652007-07-25 00:24:17 +0000540 return Res;
541 }
542 case tok::amp: // unary-expression: '&' cast-expression
543 case tok::star: // unary-expression: '*' cast-expression
544 case tok::plus: // unary-expression: '+' cast-expression
545 case tok::minus: // unary-expression: '-' cast-expression
546 case tok::tilde: // unary-expression: '~' cast-expression
547 case tok::exclaim: // unary-expression: '!' cast-expression
548 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
Chris Lattner6cf92942008-02-02 20:20:10 +0000549 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
Chris Lattner4b009652007-07-25 00:24:17 +0000550 SourceLocation SavedLoc = ConsumeToken();
551 Res = ParseCastExpression(false);
552 if (!Res.isInvalid)
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000553 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Chris Lattner4b009652007-07-25 00:24:17 +0000554 return Res;
Chris Lattner6cf92942008-02-02 20:20:10 +0000555 }
556
557 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
558 // __extension__ silences extension warnings in the subexpression.
Chris Lattnerdaa5c002008-10-20 06:45:43 +0000559 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Chris Lattner6cf92942008-02-02 20:20:10 +0000560 SourceLocation SavedLoc = ConsumeToken();
561 Res = ParseCastExpression(false);
562 if (!Res.isInvalid)
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000563 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Chris Lattner6cf92942008-02-02 20:20:10 +0000564 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000565 }
566 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
567 // unary-expression: 'sizeof' '(' type-name ')'
Douglas Gregor658b4442008-11-06 15:17:27 +0000568 case tok::kw_alignof:
Chris Lattner4b009652007-07-25 00:24:17 +0000569 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
570 // unary-expression: '__alignof' '(' type-name ')'
Douglas Gregor658b4442008-11-06 15:17:27 +0000571 // unary-expression: 'alignof' '(' type-id ')'
Chris Lattner4b009652007-07-25 00:24:17 +0000572 return ParseSizeofAlignofExpression();
573 case tok::ampamp: { // unary-expression: '&&' identifier
574 SourceLocation AmpAmpLoc = ConsumeToken();
Chris Lattner4d7d2342007-10-09 17:41:39 +0000575 if (Tok.isNot(tok::identifier)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000576 Diag(Tok, diag::err_expected_ident);
577 return ExprResult(true);
578 }
579
580 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000581 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000582 Tok.getIdentifierInfo());
583 ConsumeToken();
584 return Res;
585 }
586 case tok::kw_const_cast:
587 case tok::kw_dynamic_cast:
588 case tok::kw_reinterpret_cast:
589 case tok::kw_static_cast:
Argiris Kirtzidis4963ee42008-08-16 19:45:32 +0000590 Res = ParseCXXCasts();
591 // These can be followed by postfix-expr pieces.
592 return ParsePostfixExpressionSuffix(Res);
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000593 case tok::kw_typeid:
594 Res = ParseCXXTypeid();
595 // This can be followed by postfix-expr pieces.
596 return ParsePostfixExpressionSuffix(Res);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000597 case tok::kw_this:
Argiris Kirtzidis8f8a52a2008-08-16 19:34:46 +0000598 Res = ParseCXXThis();
599 // This can be followed by postfix-expr pieces.
600 return ParsePostfixExpressionSuffix(Res);
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000601
602 case tok::kw_char:
603 case tok::kw_wchar_t:
604 case tok::kw_bool:
605 case tok::kw_short:
606 case tok::kw_int:
607 case tok::kw_long:
608 case tok::kw_signed:
609 case tok::kw_unsigned:
610 case tok::kw_float:
611 case tok::kw_double:
612 case tok::kw_void:
613 case tok::kw_typeof: {
614 if (!getLang().CPlusPlus)
615 goto UnhandledToken;
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000616 case tok::annot_qualtypename:
617 assert(getLang().CPlusPlus && "Expected C++");
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000618 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
619 //
620 DeclSpec DS;
621 ParseCXXSimpleTypeSpecifier(DS);
622 if (Tok.isNot(tok::l_paren))
Chris Lattnerf006a222008-11-18 07:48:38 +0000623 return Diag(Tok, diag::err_expected_lparen_after_type)
624 << DS.getSourceRange();
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000625
626 Res = ParseCXXTypeConstructExpression(DS);
627 // This can be followed by postfix-expr pieces.
628 return ParsePostfixExpressionSuffix(Res);
629 }
630
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000631 case tok::annot_cxxscope: // [C++] id-expression: qualified-id
632 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
633 // template-id
634 Res = ParseCXXIdExpression();
635 return ParsePostfixExpressionSuffix(Res);
Douglas Gregore60e5d32008-11-06 22:13:31 +0000636
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000637 case tok::kw_new: // [C++] new-expression
638 // FIXME: ParseCXXIdExpression currently steals :: tokens.
639 return ParseCXXNewExpression();
640
641 case tok::kw_delete: // [C++] delete-expression
642 return ParseCXXDeleteExpression();
643
Chris Lattnerb82d6ef2007-10-03 22:03:06 +0000644 case tok::at: {
645 SourceLocation AtLoc = ConsumeToken();
Steve Narofffb9dd752007-10-15 20:55:58 +0000646 return ParseObjCAtExpression(AtLoc);
Chris Lattnerb82d6ef2007-10-03 22:03:06 +0000647 }
Fariborz Jahanian1e534dc2007-09-05 19:52:07 +0000648 case tok::l_square:
Steve Narofffb9dd752007-10-15 20:55:58 +0000649 // These can be followed by postfix-expr pieces.
Chris Lattner02d3c732008-05-09 05:28:21 +0000650 if (getLang().ObjC1)
651 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression());
652 // FALL THROUGH.
Steve Narofffd5b19d2008-08-28 19:20:44 +0000653 case tok::caret:
654 if (getLang().Blocks)
655 return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression());
656 Diag(Tok, diag::err_expected_expression);
657 return ExprResult(true);
Chris Lattner4b009652007-07-25 00:24:17 +0000658 default:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000659 UnhandledToken:
Chris Lattner4b009652007-07-25 00:24:17 +0000660 Diag(Tok, diag::err_expected_expression);
661 return ExprResult(true);
662 }
663
664 // unreachable.
665 abort();
666}
667
668/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
669/// is parsed, this method parses any suffixes that apply.
670///
671/// postfix-expression: [C99 6.5.2]
672/// primary-expression
673/// postfix-expression '[' expression ']'
674/// postfix-expression '(' argument-expression-list[opt] ')'
675/// postfix-expression '.' identifier
676/// postfix-expression '->' identifier
677/// postfix-expression '++'
678/// postfix-expression '--'
679/// '(' type-name ')' '{' initializer-list '}'
680/// '(' type-name ')' '{' initializer-list ',' '}'
681///
682/// argument-expression-list: [C99 6.5.2]
683/// argument-expression
684/// argument-expression-list ',' assignment-expression
685///
686Parser::ExprResult Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
Sebastian Redl6008ac32008-11-25 22:21:31 +0000687 ExprGuard LHSGuard(Actions, LHS);
Chris Lattner4b009652007-07-25 00:24:17 +0000688 // Now that the primary-expression piece of the postfix-expression has been
689 // parsed, see if there are any postfix-expression pieces here.
690 SourceLocation Loc;
691 while (1) {
692 switch (Tok.getKind()) {
693 default: // Not a postfix-expression suffix.
Sebastian Redl6008ac32008-11-25 22:21:31 +0000694 LHSGuard.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000695 return LHS;
696 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
697 Loc = ConsumeBracket();
698 ExprResult Idx = ParseExpression();
Sebastian Redl6008ac32008-11-25 22:21:31 +0000699 ExprGuard IdxGuard(Actions, Idx);
700
Chris Lattner4b009652007-07-25 00:24:17 +0000701 SourceLocation RLoc = Tok.getLocation();
702
Sebastian Redl6008ac32008-11-25 22:21:31 +0000703 if (!LHS.isInvalid && !Idx.isInvalid && Tok.is(tok::r_square)) {
704 LHS = Actions.ActOnArraySubscriptExpr(CurScope, LHSGuard.take(), Loc,
705 IdxGuard.take(), RLoc);
706 LHSGuard.reset(LHS);
707 } else
Chris Lattner4b009652007-07-25 00:24:17 +0000708 LHS = ExprResult(true);
709
710 // Match the ']'.
711 MatchRHSPunctuation(tok::r_square, Loc);
712 break;
713 }
714
715 case tok::l_paren: { // p-e: p-e '(' argument-expression-list[opt] ')'
Sebastian Redl6008ac32008-11-25 22:21:31 +0000716 ExprVector ArgExprs(Actions);
Argiris Kirtzidis83dce112008-08-16 20:03:01 +0000717 CommaLocsTy CommaLocs;
Chris Lattner4b009652007-07-25 00:24:17 +0000718
719 Loc = ConsumeParen();
720
Chris Lattner4d7d2342007-10-09 17:41:39 +0000721 if (Tok.isNot(tok::r_paren)) {
Argiris Kirtzidis83dce112008-08-16 20:03:01 +0000722 if (ParseExpressionList(ArgExprs, CommaLocs)) {
723 SkipUntil(tok::r_paren);
724 return ExprResult(true);
Chris Lattner4b009652007-07-25 00:24:17 +0000725 }
726 }
727
728 // Match the ')'.
Chris Lattner4d7d2342007-10-09 17:41:39 +0000729 if (!LHS.isInvalid && Tok.is(tok::r_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000730 assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&&
731 "Unexpected number of commas!");
Sebastian Redl6008ac32008-11-25 22:21:31 +0000732 LHS = Actions.ActOnCallExpr(LHSGuard.take(), Loc, ArgExprs.take(),
733 ArgExprs.size(), &CommaLocs[0],
734 Tok.getLocation());
735 LHSGuard.reset(LHS);
Chris Lattner4b009652007-07-25 00:24:17 +0000736 }
737
738 MatchRHSPunctuation(tok::r_paren, Loc);
739 break;
740 }
741 case tok::arrow: // postfix-expression: p-e '->' identifier
742 case tok::period: { // postfix-expression: p-e '.' identifier
743 tok::TokenKind OpKind = Tok.getKind();
744 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
745
Chris Lattner4d7d2342007-10-09 17:41:39 +0000746 if (Tok.isNot(tok::identifier)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000747 Diag(Tok, diag::err_expected_ident);
748 return ExprResult(true);
749 }
750
Sebastian Redl6008ac32008-11-25 22:21:31 +0000751 if (!LHS.isInvalid) {
752 LHS = Actions.ActOnMemberReferenceExpr(LHSGuard.take(), OpLoc, OpKind,
Chris Lattner4b009652007-07-25 00:24:17 +0000753 Tok.getLocation(),
754 *Tok.getIdentifierInfo());
Sebastian Redl6008ac32008-11-25 22:21:31 +0000755 LHSGuard.reset(LHS);
756 }
Chris Lattner4b009652007-07-25 00:24:17 +0000757 ConsumeToken();
758 break;
759 }
760 case tok::plusplus: // postfix-expression: postfix-expression '++'
761 case tok::minusminus: // postfix-expression: postfix-expression '--'
Sebastian Redl6008ac32008-11-25 22:21:31 +0000762 if (!LHS.isInvalid) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000763 LHS = Actions.ActOnPostfixUnaryOp(CurScope, Tok.getLocation(),
Sebastian Redl6008ac32008-11-25 22:21:31 +0000764 Tok.getKind(), LHSGuard.take());
765 LHSGuard.reset(LHS);
766 }
Chris Lattner4b009652007-07-25 00:24:17 +0000767 ConsumeToken();
768 break;
769 }
770 }
771}
772
773
774/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression.
775/// unary-expression: [C99 6.5.3]
776/// 'sizeof' unary-expression
777/// 'sizeof' '(' type-name ')'
778/// [GNU] '__alignof' unary-expression
779/// [GNU] '__alignof' '(' type-name ')'
Douglas Gregor658b4442008-11-06 15:17:27 +0000780/// [C++0x] 'alignof' '(' type-id ')'
Chris Lattner4b009652007-07-25 00:24:17 +0000781Parser::ExprResult Parser::ParseSizeofAlignofExpression() {
Douglas Gregor658b4442008-11-06 15:17:27 +0000782 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof)
783 || Tok.is(tok::kw_alignof)) &&
Chris Lattner4b009652007-07-25 00:24:17 +0000784 "Not a sizeof/alignof expression!");
785 Token OpTok = Tok;
786 ConsumeToken();
787
788 // If the operand doesn't start with an '(', it must be an expression.
789 ExprResult Operand;
Chris Lattner4d7d2342007-10-09 17:41:39 +0000790 if (Tok.isNot(tok::l_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000791 Operand = ParseCastExpression(true);
792 } else {
793 // If it starts with a '(', we know that it is either a parenthesized
794 // type-name, or it is a unary-expression that starts with a compound
795 // literal, or starts with a primary-expression that is a parenthesized
796 // expression.
797 ParenParseOption ExprType = CastExpr;
798 TypeTy *CastTy;
799 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
800 Operand = ParseParenExpression(ExprType, CastTy, RParenLoc);
801
802 // If ParseParenExpression parsed a '(typename)' sequence only, the this is
803 // sizeof/alignof a type. Otherwise, it is sizeof/alignof an expression.
Chris Lattner48553562007-11-13 20:50:37 +0000804 if (ExprType == CastExpr)
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000805 return Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
806 OpTok.is(tok::kw_sizeof),
807 /*isType=*/true, CastTy,
808 SourceRange(LParenLoc, RParenLoc));
Chris Lattner48553562007-11-13 20:50:37 +0000809
810 // If this is a parenthesized expression, it is the start of a
811 // unary-expression, but doesn't include any postfix pieces. Parse these
812 // now if present.
813 Operand = ParsePostfixExpressionSuffix(Operand);
Chris Lattner4b009652007-07-25 00:24:17 +0000814 }
815
816 // If we get here, the operand to the sizeof/alignof was an expresion.
817 if (!Operand.isInvalid)
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000818 Operand = Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
819 OpTok.is(tok::kw_sizeof),
820 /*isType=*/false, Operand.Val,
821 SourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000822 return Operand;
823}
824
825/// ParseBuiltinPrimaryExpression
826///
827/// primary-expression: [C99 6.5.1]
828/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
829/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
830/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
831/// assign-expr ')'
832/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000833/// [CLANG] '__builtin_overload' '(' expr (',' expr)* ')'
Chris Lattner4b009652007-07-25 00:24:17 +0000834///
835/// [GNU] offsetof-member-designator:
836/// [GNU] identifier
837/// [GNU] offsetof-member-designator '.' identifier
838/// [GNU] offsetof-member-designator '[' expression ']'
839///
840Parser::ExprResult Parser::ParseBuiltinPrimaryExpression() {
841 ExprResult Res(false);
842 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
843
844 tok::TokenKind T = Tok.getKind();
845 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
846
847 // All of these start with an open paren.
Chris Lattner4d7d2342007-10-09 17:41:39 +0000848 if (Tok.isNot(tok::l_paren)) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000849 Diag(Tok, diag::err_expected_lparen_after_id) << BuiltinII;
Chris Lattner4b009652007-07-25 00:24:17 +0000850 return ExprResult(true);
851 }
852
853 SourceLocation LParenLoc = ConsumeParen();
854 // TODO: Build AST.
855
856 switch (T) {
857 default: assert(0 && "Not a builtin primary expression!");
Anders Carlsson36760332007-10-15 20:28:48 +0000858 case tok::kw___builtin_va_arg: {
859 ExprResult Expr = ParseAssignmentExpression();
Sebastian Redl6008ac32008-11-25 22:21:31 +0000860 ExprGuard ExprGuard(Actions, Expr);
Anders Carlsson36760332007-10-15 20:28:48 +0000861 if (Expr.isInvalid) {
Chris Lattner4b009652007-07-25 00:24:17 +0000862 SkipUntil(tok::r_paren);
Eli Friedmana1b6d802008-08-20 22:07:34 +0000863 return ExprResult(true);
Chris Lattner4b009652007-07-25 00:24:17 +0000864 }
865
866 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
867 return ExprResult(true);
868
Anders Carlsson36760332007-10-15 20:28:48 +0000869 TypeTy *Ty = ParseTypeName();
Chris Lattnercb8943a2007-08-30 15:52:49 +0000870
Anders Carlsson36760332007-10-15 20:28:48 +0000871 if (Tok.isNot(tok::r_paren)) {
872 Diag(Tok, diag::err_expected_rparen);
873 return ExprResult(true);
874 }
Sebastian Redl6008ac32008-11-25 22:21:31 +0000875 Res = Actions.ActOnVAArg(StartLoc, ExprGuard.take(), Ty, ConsumeParen());
Chris Lattner4b009652007-07-25 00:24:17 +0000876 break;
Anders Carlsson36760332007-10-15 20:28:48 +0000877 }
Chris Lattner69638b12007-08-30 15:51:11 +0000878 case tok::kw___builtin_offsetof: {
Chris Lattner1b6b5be2007-08-30 17:08:45 +0000879 SourceLocation TypeLoc = Tok.getLocation();
Chris Lattner69638b12007-08-30 15:51:11 +0000880 TypeTy *Ty = ParseTypeName();
Chris Lattner4b009652007-07-25 00:24:17 +0000881
882 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
883 return ExprResult(true);
884
885 // We must have at least one identifier here.
Chris Lattner4d7d2342007-10-09 17:41:39 +0000886 if (Tok.isNot(tok::identifier)) {
Chris Lattner69638b12007-08-30 15:51:11 +0000887 Diag(Tok, diag::err_expected_ident);
888 SkipUntil(tok::r_paren);
889 return true;
890 }
891
892 // Keep track of the various subcomponents we see.
893 llvm::SmallVector<Action::OffsetOfComponent, 4> Comps;
894
895 Comps.push_back(Action::OffsetOfComponent());
896 Comps.back().isBrackets = false;
897 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
898 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
Chris Lattner4b009652007-07-25 00:24:17 +0000899
Sebastian Redl6008ac32008-11-25 22:21:31 +0000900 // FIXME: This loop leaks the index expressions on error.
Chris Lattner4b009652007-07-25 00:24:17 +0000901 while (1) {
Chris Lattner4d7d2342007-10-09 17:41:39 +0000902 if (Tok.is(tok::period)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000903 // offsetof-member-designator: offsetof-member-designator '.' identifier
Chris Lattner69638b12007-08-30 15:51:11 +0000904 Comps.push_back(Action::OffsetOfComponent());
905 Comps.back().isBrackets = false;
906 Comps.back().LocStart = ConsumeToken();
Chris Lattner4b009652007-07-25 00:24:17 +0000907
Chris Lattner4d7d2342007-10-09 17:41:39 +0000908 if (Tok.isNot(tok::identifier)) {
Chris Lattner69638b12007-08-30 15:51:11 +0000909 Diag(Tok, diag::err_expected_ident);
910 SkipUntil(tok::r_paren);
911 return true;
912 }
913 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
914 Comps.back().LocEnd = ConsumeToken();
915
Chris Lattner4d7d2342007-10-09 17:41:39 +0000916 } else if (Tok.is(tok::l_square)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000917 // offsetof-member-designator: offsetof-member-design '[' expression ']'
Chris Lattner69638b12007-08-30 15:51:11 +0000918 Comps.push_back(Action::OffsetOfComponent());
919 Comps.back().isBrackets = true;
920 Comps.back().LocStart = ConsumeBracket();
Chris Lattner4b009652007-07-25 00:24:17 +0000921 Res = ParseExpression();
922 if (Res.isInvalid) {
923 SkipUntil(tok::r_paren);
924 return Res;
925 }
Chris Lattner69638b12007-08-30 15:51:11 +0000926 Comps.back().U.E = Res.Val;
Chris Lattner4b009652007-07-25 00:24:17 +0000927
Chris Lattner69638b12007-08-30 15:51:11 +0000928 Comps.back().LocEnd =
929 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart);
Chris Lattner4d7d2342007-10-09 17:41:39 +0000930 } else if (Tok.is(tok::r_paren)) {
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000931 Res = Actions.ActOnBuiltinOffsetOf(StartLoc, TypeLoc, Ty, &Comps[0],
Chris Lattnercb8943a2007-08-30 15:52:49 +0000932 Comps.size(), ConsumeParen());
933 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000934 } else {
Chris Lattner69638b12007-08-30 15:51:11 +0000935 // Error occurred.
936 return ExprResult(true);
Chris Lattner4b009652007-07-25 00:24:17 +0000937 }
938 }
939 break;
Chris Lattner69638b12007-08-30 15:51:11 +0000940 }
Steve Naroff93c53012007-08-03 21:21:27 +0000941 case tok::kw___builtin_choose_expr: {
942 ExprResult Cond = ParseAssignmentExpression();
Sebastian Redl6008ac32008-11-25 22:21:31 +0000943 ExprGuard CondGuard(Actions, Cond);
Steve Naroff93c53012007-08-03 21:21:27 +0000944 if (Cond.isInvalid) {
945 SkipUntil(tok::r_paren);
946 return Cond;
947 }
Chris Lattner4b009652007-07-25 00:24:17 +0000948 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
949 return ExprResult(true);
950
Steve Naroff93c53012007-08-03 21:21:27 +0000951 ExprResult Expr1 = ParseAssignmentExpression();
Sebastian Redl6008ac32008-11-25 22:21:31 +0000952 ExprGuard Guard1(Actions, Expr1);
Steve Naroff93c53012007-08-03 21:21:27 +0000953 if (Expr1.isInvalid) {
954 SkipUntil(tok::r_paren);
955 return Expr1;
956 }
Chris Lattner4b009652007-07-25 00:24:17 +0000957 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
958 return ExprResult(true);
959
Steve Naroff93c53012007-08-03 21:21:27 +0000960 ExprResult Expr2 = ParseAssignmentExpression();
Sebastian Redl6008ac32008-11-25 22:21:31 +0000961 ExprGuard Guard2(Actions, Expr2);
Steve Naroff93c53012007-08-03 21:21:27 +0000962 if (Expr2.isInvalid) {
963 SkipUntil(tok::r_paren);
964 return Expr2;
965 }
Chris Lattner4d7d2342007-10-09 17:41:39 +0000966 if (Tok.isNot(tok::r_paren)) {
Steve Naroff93c53012007-08-03 21:21:27 +0000967 Diag(Tok, diag::err_expected_rparen);
968 return ExprResult(true);
969 }
Sebastian Redl6008ac32008-11-25 22:21:31 +0000970 Res = Actions.ActOnChooseExpr(StartLoc, CondGuard.take(), Guard1.take(),
971 Guard2.take(), ConsumeParen());
Chris Lattnercb8943a2007-08-30 15:52:49 +0000972 break;
Steve Naroff93c53012007-08-03 21:21:27 +0000973 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000974 case tok::kw___builtin_overload: {
Sebastian Redl6008ac32008-11-25 22:21:31 +0000975 ExprVector ArgExprs(Actions);
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000976 llvm::SmallVector<SourceLocation, 8> CommaLocs;
977
978 // For each iteration through the loop look for assign-expr followed by a
979 // comma. If there is no comma, break and attempt to match r-paren.
980 if (Tok.isNot(tok::r_paren)) {
981 while (1) {
982 ExprResult ArgExpr = ParseAssignmentExpression();
983 if (ArgExpr.isInvalid) {
984 SkipUntil(tok::r_paren);
985 return ExprResult(true);
986 } else
987 ArgExprs.push_back(ArgExpr.Val);
988
989 if (Tok.isNot(tok::comma))
990 break;
991 // Move to the next argument, remember where the comma was.
992 CommaLocs.push_back(ConsumeToken());
993 }
994 }
995
996 // Attempt to consume the r-paren
997 if (Tok.isNot(tok::r_paren)) {
998 Diag(Tok, diag::err_expected_rparen);
999 SkipUntil(tok::r_paren);
1000 return ExprResult(true);
1001 }
Sebastian Redl6008ac32008-11-25 22:21:31 +00001002 Res = Actions.ActOnOverloadExpr(ArgExprs.take(), ArgExprs.size(),
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001003 &CommaLocs[0], StartLoc, ConsumeParen());
1004 break;
1005 }
Chris Lattner4b009652007-07-25 00:24:17 +00001006 case tok::kw___builtin_types_compatible_p:
Steve Naroff5b528922007-08-01 23:45:51 +00001007 TypeTy *Ty1 = ParseTypeName();
Chris Lattner4b009652007-07-25 00:24:17 +00001008
1009 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1010 return ExprResult(true);
1011
Steve Naroff5b528922007-08-01 23:45:51 +00001012 TypeTy *Ty2 = ParseTypeName();
1013
Chris Lattner4d7d2342007-10-09 17:41:39 +00001014 if (Tok.isNot(tok::r_paren)) {
Steve Naroff5b528922007-08-01 23:45:51 +00001015 Diag(Tok, diag::err_expected_rparen);
1016 return ExprResult(true);
1017 }
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001018 Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1, Ty2, ConsumeParen());
Chris Lattnercb8943a2007-08-30 15:52:49 +00001019 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001020 }
1021
Chris Lattner4b009652007-07-25 00:24:17 +00001022 // These can be followed by postfix-expr pieces because they are
1023 // primary-expressions.
1024 return ParsePostfixExpressionSuffix(Res);
1025}
1026
1027/// ParseParenExpression - This parses the unit that starts with a '(' token,
1028/// based on what is allowed by ExprType. The actual thing parsed is returned
1029/// in ExprType.
1030///
1031/// primary-expression: [C99 6.5.1]
1032/// '(' expression ')'
1033/// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
1034/// postfix-expression: [C99 6.5.2]
1035/// '(' type-name ')' '{' initializer-list '}'
1036/// '(' type-name ')' '{' initializer-list ',' '}'
1037/// cast-expression: [C99 6.5.4]
1038/// '(' type-name ')' cast-expression
1039///
1040Parser::ExprResult Parser::ParseParenExpression(ParenParseOption &ExprType,
1041 TypeTy *&CastTy,
1042 SourceLocation &RParenLoc) {
Chris Lattner4d7d2342007-10-09 17:41:39 +00001043 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
Chris Lattner4b009652007-07-25 00:24:17 +00001044 SourceLocation OpenLoc = ConsumeParen();
1045 ExprResult Result(true);
1046 CastTy = 0;
1047
Chris Lattner4d7d2342007-10-09 17:41:39 +00001048 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001049 Diag(Tok, diag::ext_gnu_statement_expr);
Chris Lattnerf2b07572007-08-31 21:49:55 +00001050 Parser::StmtResult Stmt = ParseCompoundStatement(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001051 ExprType = CompoundStmt;
1052
1053 // If the substmt parsed correctly, build the AST node.
Chris Lattner4d7d2342007-10-09 17:41:39 +00001054 if (!Stmt.isInvalid && Tok.is(tok::r_paren))
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001055 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.Val, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001056
Argiris Kirtzidis3276cbc2008-10-05 19:56:22 +00001057 } else if (ExprType >= CompoundLiteral && isTypeIdInParens()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001058 // Otherwise, this is a compound literal expression or cast expression.
1059 TypeTy *Ty = ParseTypeName();
1060
1061 // Match the ')'.
Chris Lattner4d7d2342007-10-09 17:41:39 +00001062 if (Tok.is(tok::r_paren))
Chris Lattner4b009652007-07-25 00:24:17 +00001063 RParenLoc = ConsumeParen();
1064 else
1065 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1066
Chris Lattner4d7d2342007-10-09 17:41:39 +00001067 if (Tok.is(tok::l_brace)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001068 if (!getLang().C99) // Compound literals don't exist in C90.
1069 Diag(OpenLoc, diag::ext_c99_compound_literal);
1070 Result = ParseInitializer();
1071 ExprType = CompoundLiteral;
1072 if (!Result.isInvalid)
Steve Naroff87d58b42007-09-16 03:34:24 +00001073 return Actions.ActOnCompoundLiteral(OpenLoc, Ty, RParenLoc, Result.Val);
Chris Lattner4b009652007-07-25 00:24:17 +00001074 } else if (ExprType == CastExpr) {
1075 // Note that this doesn't parse the subsequence cast-expression, it just
1076 // returns the parsed type to the callee.
1077 ExprType = CastExpr;
1078 CastTy = Ty;
1079 return ExprResult(false);
1080 } else {
1081 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
1082 return ExprResult(true);
1083 }
1084 return Result;
1085 } else {
1086 Result = ParseExpression();
1087 ExprType = SimpleExpr;
Chris Lattner4d7d2342007-10-09 17:41:39 +00001088 if (!Result.isInvalid && Tok.is(tok::r_paren))
Steve Naroff87d58b42007-09-16 03:34:24 +00001089 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.Val);
Chris Lattner4b009652007-07-25 00:24:17 +00001090 }
1091
1092 // Match the ')'.
1093 if (Result.isInvalid)
1094 SkipUntil(tok::r_paren);
1095 else {
Chris Lattner4d7d2342007-10-09 17:41:39 +00001096 if (Tok.is(tok::r_paren))
Chris Lattner4b009652007-07-25 00:24:17 +00001097 RParenLoc = ConsumeParen();
1098 else
1099 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1100 }
1101
1102 return Result;
1103}
1104
1105/// ParseStringLiteralExpression - This handles the various token types that
1106/// form string literals, and also handles string concatenation [C99 5.1.1.2,
1107/// translation phase #6].
1108///
1109/// primary-expression: [C99 6.5.1]
1110/// string-literal
1111Parser::ExprResult Parser::ParseStringLiteralExpression() {
1112 assert(isTokenStringLiteral() && "Not a string literal!");
1113
1114 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
1115 // considered to be strings for concatenation purposes.
1116 llvm::SmallVector<Token, 4> StringToks;
1117
1118 do {
1119 StringToks.push_back(Tok);
1120 ConsumeStringToken();
1121 } while (isTokenStringLiteral());
1122
1123 // Pass the set of string tokens, ready for concatenation, to the actions.
Steve Naroff87d58b42007-09-16 03:34:24 +00001124 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size());
Chris Lattner4b009652007-07-25 00:24:17 +00001125}
Argiris Kirtzidis83dce112008-08-16 20:03:01 +00001126
1127/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1128///
1129/// argument-expression-list:
1130/// assignment-expression
1131/// argument-expression-list , assignment-expression
1132///
1133/// [C++] expression-list:
1134/// [C++] assignment-expression
1135/// [C++] expression-list , assignment-expression
1136///
1137bool Parser::ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs) {
1138 while (1) {
1139 ExprResult Expr = ParseAssignmentExpression();
1140 if (Expr.isInvalid)
1141 return true;
Argiris Kirtzidisd37a4182008-08-18 22:49:40 +00001142
1143 Exprs.push_back(Expr.Val);
Argiris Kirtzidis83dce112008-08-16 20:03:01 +00001144
1145 if (Tok.isNot(tok::comma))
1146 return false;
1147 // Move to the next argument, remember where the comma was.
1148 CommaLocs.push_back(ConsumeToken());
1149 }
1150}
Steve Narofffd5b19d2008-08-28 19:20:44 +00001151
1152/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
Steve Naroffa095a752008-09-16 23:11:46 +00001153/// like ^(int x){ return x+1; }
Steve Narofffd5b19d2008-08-28 19:20:44 +00001154///
1155/// block-literal:
1156/// [clang] '^' block-args[opt] compound-statement
Steve Narofffd5b19d2008-08-28 19:20:44 +00001157/// [clang] block-args:
1158/// [clang] '(' parameter-list ')'
1159///
1160Parser::ExprResult Parser::ParseBlockLiteralExpression() {
1161 assert(Tok.is(tok::caret) && "block literal starts with ^");
1162 SourceLocation CaretLoc = ConsumeToken();
1163
1164 // Enter a scope to hold everything within the block. This includes the
1165 // argument decls, decls within the compound expression, etc. This also
1166 // allows determining whether a variable reference inside the block is
1167 // within or outside of the block.
1168 EnterScope(Scope::BlockScope|Scope::FnScope|Scope::BreakScope|
1169 Scope::ContinueScope|Scope::DeclScope);
Steve Naroff52059382008-10-10 01:28:17 +00001170
1171 // Inform sema that we are starting a block.
1172 Actions.ActOnBlockStart(CaretLoc, CurScope);
Steve Narofffd5b19d2008-08-28 19:20:44 +00001173
1174 // Parse the return type if present.
1175 DeclSpec DS;
1176 Declarator ParamInfo(DS, Declarator::PrototypeContext);
1177
1178 // If this block has arguments, parse them. There is no ambiguity here with
1179 // the expression case, because the expression case requires a parameter list.
1180 if (Tok.is(tok::l_paren)) {
1181 ParseParenDeclarator(ParamInfo);
1182 // Parse the pieces after the identifier as if we had "int(...)".
1183 ParamInfo.SetIdentifier(0, CaretLoc);
1184 if (ParamInfo.getInvalidType()) {
1185 // If there was an error parsing the arguments, they may have tried to use
1186 // ^(x+y) which requires an argument list. Just skip the whole block
1187 // literal.
1188 ExitScope();
1189 return true;
1190 }
1191 } else {
1192 // Otherwise, pretend we saw (void).
1193 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false,
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001194 0, 0, 0, CaretLoc));
Steve Narofffd5b19d2008-08-28 19:20:44 +00001195 }
1196
1197 // Inform sema that we are starting a block.
Steve Naroff52059382008-10-10 01:28:17 +00001198 Actions.ActOnBlockArguments(ParamInfo);
Steve Narofffd5b19d2008-08-28 19:20:44 +00001199
Steve Naroffa095a752008-09-16 23:11:46 +00001200 ExprResult Result = true;
Steve Narofffd5b19d2008-08-28 19:20:44 +00001201 if (Tok.is(tok::l_brace)) {
1202 StmtResult Stmt = ParseCompoundStatementBody();
1203 if (!Stmt.isInvalid) {
1204 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.Val, CurScope);
1205 } else {
1206 Actions.ActOnBlockError(CaretLoc, CurScope);
Steve Narofffd5b19d2008-08-28 19:20:44 +00001207 }
1208 }
Steve Narofffd5b19d2008-08-28 19:20:44 +00001209 ExitScope();
1210 return Result;
1211}
1212