blob: 50b3a7a4ef9e3e5ac5c5914fa6e9993e0a927d9a [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 ')'
Douglas Gregor2d8b2732008-11-29 04:51:27 +0000381/// [GNU] '__null'
Fariborz Jahanian095ffca2007-09-26 17:03:44 +0000382/// [OBJC] '[' objc-message-expr ']'
Chris Lattner5ac87ed2008-01-25 18:58:06 +0000383/// [OBJC] '@selector' '(' objc-selector-arg ')'
Fariborz Jahanian095ffca2007-09-26 17:03:44 +0000384/// [OBJC] '@protocol' '(' identifier ')'
385/// [OBJC] '@encode' '(' type-name ')'
Fariborz Jahanian0ccb27d2007-09-05 19:52:07 +0000386/// [OBJC] objc-string-literal
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000387/// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
388/// [C++] typename-specifier '(' expression-list[opt] ')' [TODO]
Reid Spencer5f016e22007-07-11 17:01:13 +0000389/// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
390/// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
391/// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
392/// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
Sebastian Redlc42e1182008-11-11 11:37:55 +0000393/// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
394/// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
Argyrios Kyrtzidisd7464be2008-07-16 07:23:27 +0000395/// [C++] 'this' [C++ 9.3.2]
Steve Naroff296e8d52008-08-28 19:20:44 +0000396/// [clang] '^' block-literal
Reid Spencer5f016e22007-07-11 17:01:13 +0000397///
398/// constant: [C99 6.4.4]
399/// integer-constant
400/// floating-constant
401/// enumeration-constant -> identifier
402/// character-constant
403///
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +0000404/// id-expression: [C++ 5.1]
405/// unqualified-id
406/// qualified-id [TODO]
407///
408/// unqualified-id: [C++ 5.1]
409/// identifier
410/// operator-function-id
411/// conversion-function-id [TODO]
412/// '~' class-name [TODO]
413/// template-id [TODO]
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000414///
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000415/// new-expression: [C++ 5.3.4]
416/// '::'[opt] 'new' new-placement[opt] new-type-id
417/// new-initializer[opt]
418/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
419/// new-initializer[opt]
420///
421/// delete-expression: [C++ 5.3.5]
422/// '::'[opt] 'delete' cast-expression
423/// '::'[opt] 'delete' '[' ']' cast-expression
424///
Reid Spencer5f016e22007-07-11 17:01:13 +0000425Parser::ExprResult Parser::ParseCastExpression(bool isUnaryExpression) {
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000426 if (getLang().CPlusPlus) {
427 // Annotate typenames and C++ scope specifiers.
Argyrios Kyrtzidis44802cc2008-11-26 21:51:07 +0000428 // Used only in C++, where the typename can be considered as a functional
429 // style cast ("int(1)").
430 // In C we don't expect identifiers to be treated as typenames; if it's a
431 // typedef name, let it be handled as an identifier and
432 // Actions.ActOnIdentifierExpr will emit the proper diagnostic.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000433 TryAnnotateTypeOrScopeToken();
434 }
435
Reid Spencer5f016e22007-07-11 17:01:13 +0000436 ExprResult Res;
437 tok::TokenKind SavedKind = Tok.getKind();
438
439 // This handles all of cast-expression, unary-expression, postfix-expression,
440 // and primary-expression. We handle them together like this for efficiency
441 // and to simplify handling of an expression starting with a '(' token: which
442 // may be one of a parenthesized expression, cast-expression, compound literal
443 // expression, or statement expression.
444 //
445 // If the parsed tokens consist of a primary-expression, the cases below
446 // call ParsePostfixExpressionSuffix to handle the postfix expression
447 // suffixes. Cases that cannot be followed by postfix exprs should
448 // return without invoking ParsePostfixExpressionSuffix.
449 switch (SavedKind) {
450 case tok::l_paren: {
451 // If this expression is limited to being a unary-expression, the parent can
452 // not start a cast expression.
453 ParenParseOption ParenExprType =
454 isUnaryExpression ? CompoundLiteral : CastExpr;
455 TypeTy *CastTy;
456 SourceLocation LParenLoc = Tok.getLocation();
457 SourceLocation RParenLoc;
458 Res = ParseParenExpression(ParenExprType, CastTy, RParenLoc);
459 if (Res.isInvalid) return Res;
460
461 switch (ParenExprType) {
462 case SimpleExpr: break; // Nothing else to do.
463 case CompoundStmt: break; // Nothing else to do.
464 case CompoundLiteral:
465 // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
466 // postfix-expression exist, parse them now.
467 break;
468 case CastExpr:
469 // We parsed '(' type-name ')' and the thing after it wasn't a '{'. Parse
470 // the cast-expression that follows it next.
471 // TODO: For cast expression with CastTy.
472 Res = ParseCastExpression(false);
473 if (!Res.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +0000474 Res = Actions.ActOnCastExpr(LParenLoc, CastTy, RParenLoc, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000475 return Res;
476 }
477
478 // These can be followed by postfix-expr pieces.
479 return ParsePostfixExpressionSuffix(Res);
480 }
481
482 // primary-expression
483 case tok::numeric_constant:
484 // constant: integer-constant
485 // constant: floating-constant
486
Steve Narofff69936d2007-09-16 03:34:24 +0000487 Res = Actions.ActOnNumericConstant(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000488 ConsumeToken();
489
490 // These can be followed by postfix-expr pieces.
491 return ParsePostfixExpressionSuffix(Res);
492
493 case tok::kw_true:
494 case tok::kw_false:
495 return ParseCXXBoolLiteral();
496
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000497 case tok::identifier: { // primary-expression: identifier
498 // unqualified-id: identifier
499 // constant: enumeration-constant
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000500
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 // Consume the identifier so that we can see if it is followed by a '('.
502 // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
503 // need to know whether or not this identifier is a function designator or
504 // not.
505 IdentifierInfo &II = *Tok.getIdentifierInfo();
506 SourceLocation L = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000507 Res = Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren));
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 // These can be followed by postfix-expr pieces.
509 return ParsePostfixExpressionSuffix(Res);
510 }
511 case tok::char_constant: // constant: character-constant
Steve Narofff69936d2007-09-16 03:34:24 +0000512 Res = Actions.ActOnCharacterConstant(Tok);
Reid Spencer5f016e22007-07-11 17:01:13 +0000513 ConsumeToken();
514 // These can be followed by postfix-expr pieces.
515 return ParsePostfixExpressionSuffix(Res);
516 case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
517 case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
518 case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
Chris Lattnerd9f69102008-08-10 01:53:14 +0000519 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 ConsumeToken();
521 // These can be followed by postfix-expr pieces.
522 return ParsePostfixExpressionSuffix(Res);
523 case tok::string_literal: // primary-expression: string-literal
524 case tok::wide_string_literal:
525 Res = ParseStringLiteralExpression();
526 if (Res.isInvalid) return Res;
527 // This can be followed by postfix-expr pieces (e.g. "foo"[1]).
528 return ParsePostfixExpressionSuffix(Res);
529 case tok::kw___builtin_va_arg:
530 case tok::kw___builtin_offsetof:
531 case tok::kw___builtin_choose_expr:
Nate Begemane2ce1d92008-01-17 17:46:27 +0000532 case tok::kw___builtin_overload:
Reid Spencer5f016e22007-07-11 17:01:13 +0000533 case tok::kw___builtin_types_compatible_p:
534 return ParseBuiltinPrimaryExpression();
Douglas Gregor2d8b2732008-11-29 04:51:27 +0000535 case tok::kw___null:
536 return Actions.ActOnGNUNullExpr(ConsumeToken());
537 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000538 case tok::plusplus: // unary-expression: '++' unary-expression
539 case tok::minusminus: { // unary-expression: '--' unary-expression
540 SourceLocation SavedLoc = ConsumeToken();
541 Res = ParseCastExpression(true);
542 if (!Res.isInvalid)
Douglas Gregor74253732008-11-19 15:42:04 +0000543 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000544 return Res;
545 }
546 case tok::amp: // unary-expression: '&' cast-expression
547 case tok::star: // unary-expression: '*' cast-expression
548 case tok::plus: // unary-expression: '+' cast-expression
549 case tok::minus: // unary-expression: '-' cast-expression
550 case tok::tilde: // unary-expression: '~' cast-expression
551 case tok::exclaim: // unary-expression: '!' cast-expression
552 case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
Chris Lattner35080842008-02-02 20:20:10 +0000553 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
Reid Spencer5f016e22007-07-11 17:01:13 +0000554 SourceLocation SavedLoc = ConsumeToken();
555 Res = ParseCastExpression(false);
556 if (!Res.isInvalid)
Douglas Gregor74253732008-11-19 15:42:04 +0000557 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +0000558 return Res;
Chris Lattner35080842008-02-02 20:20:10 +0000559 }
560
561 case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
562 // __extension__ silences extension warnings in the subexpression.
Chris Lattnerc46d1a12008-10-20 06:45:43 +0000563 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Chris Lattner35080842008-02-02 20:20:10 +0000564 SourceLocation SavedLoc = ConsumeToken();
565 Res = ParseCastExpression(false);
566 if (!Res.isInvalid)
Douglas Gregor74253732008-11-19 15:42:04 +0000567 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Chris Lattner35080842008-02-02 20:20:10 +0000568 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 }
570 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
571 // unary-expression: 'sizeof' '(' type-name ')'
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000572 case tok::kw_alignof:
Reid Spencer5f016e22007-07-11 17:01:13 +0000573 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
574 // unary-expression: '__alignof' '(' type-name ')'
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000575 // unary-expression: 'alignof' '(' type-id ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000576 return ParseSizeofAlignofExpression();
577 case tok::ampamp: { // unary-expression: '&&' identifier
578 SourceLocation AmpAmpLoc = ConsumeToken();
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000579 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000580 Diag(Tok, diag::err_expected_ident);
581 return ExprResult(true);
582 }
583
584 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
Steve Naroff1b273c42007-09-16 14:56:35 +0000585 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 Tok.getIdentifierInfo());
587 ConsumeToken();
588 return Res;
589 }
590 case tok::kw_const_cast:
591 case tok::kw_dynamic_cast:
592 case tok::kw_reinterpret_cast:
593 case tok::kw_static_cast:
Argyrios Kyrtzidisb348b812008-08-16 19:45:32 +0000594 Res = ParseCXXCasts();
595 // These can be followed by postfix-expr pieces.
596 return ParsePostfixExpressionSuffix(Res);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000597 case tok::kw_typeid:
598 Res = ParseCXXTypeid();
599 // This can be followed by postfix-expr pieces.
600 return ParsePostfixExpressionSuffix(Res);
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +0000601 case tok::kw_this:
Argyrios Kyrtzidis289d7732008-08-16 19:34:46 +0000602 Res = ParseCXXThis();
603 // This can be followed by postfix-expr pieces.
604 return ParsePostfixExpressionSuffix(Res);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000605
606 case tok::kw_char:
607 case tok::kw_wchar_t:
608 case tok::kw_bool:
609 case tok::kw_short:
610 case tok::kw_int:
611 case tok::kw_long:
612 case tok::kw_signed:
613 case tok::kw_unsigned:
614 case tok::kw_float:
615 case tok::kw_double:
616 case tok::kw_void:
617 case tok::kw_typeof: {
618 if (!getLang().CPlusPlus)
619 goto UnhandledToken;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000620 case tok::annot_qualtypename:
621 assert(getLang().CPlusPlus && "Expected C++");
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000622 // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
623 //
624 DeclSpec DS;
625 ParseCXXSimpleTypeSpecifier(DS);
626 if (Tok.isNot(tok::l_paren))
Chris Lattner1ab3b962008-11-18 07:48:38 +0000627 return Diag(Tok, diag::err_expected_lparen_after_type)
628 << DS.getSourceRange();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000629
630 Res = ParseCXXTypeConstructExpression(DS);
631 // This can be followed by postfix-expr pieces.
632 return ParsePostfixExpressionSuffix(Res);
633 }
634
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000635 case tok::annot_cxxscope: // [C++] id-expression: qualified-id
636 case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
637 // template-id
638 Res = ParseCXXIdExpression();
639 return ParsePostfixExpressionSuffix(Res);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +0000640
Sebastian Redlfb4ccd72008-12-02 16:35:44 +0000641 case tok::coloncolon: // [C++] new-expression or [C++] delete-expression
642 if (NextToken().is(tok::kw_new))
643 return ParseCXXNewExpression();
644 else
645 return ParseCXXDeleteExpression();
646
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000647 case tok::kw_new: // [C++] new-expression
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000648 return ParseCXXNewExpression();
649
650 case tok::kw_delete: // [C++] delete-expression
651 return ParseCXXDeleteExpression();
652
Chris Lattnerc97c2042007-10-03 22:03:06 +0000653 case tok::at: {
654 SourceLocation AtLoc = ConsumeToken();
Steve Naroffa642beb2007-10-15 20:55:58 +0000655 return ParseObjCAtExpression(AtLoc);
Chris Lattnerc97c2042007-10-03 22:03:06 +0000656 }
Fariborz Jahanian0ccb27d2007-09-05 19:52:07 +0000657 case tok::l_square:
Steve Naroffa642beb2007-10-15 20:55:58 +0000658 // These can be followed by postfix-expr pieces.
Chris Lattner039a6422008-05-09 05:28:21 +0000659 if (getLang().ObjC1)
660 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression());
661 // FALL THROUGH.
Steve Naroff296e8d52008-08-28 19:20:44 +0000662 case tok::caret:
663 if (getLang().Blocks)
664 return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression());
665 Diag(Tok, diag::err_expected_expression);
666 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000667 default:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000668 UnhandledToken:
Reid Spencer5f016e22007-07-11 17:01:13 +0000669 Diag(Tok, diag::err_expected_expression);
670 return ExprResult(true);
671 }
672
673 // unreachable.
674 abort();
675}
676
677/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
678/// is parsed, this method parses any suffixes that apply.
679///
680/// postfix-expression: [C99 6.5.2]
681/// primary-expression
682/// postfix-expression '[' expression ']'
683/// postfix-expression '(' argument-expression-list[opt] ')'
684/// postfix-expression '.' identifier
685/// postfix-expression '->' identifier
686/// postfix-expression '++'
687/// postfix-expression '--'
688/// '(' type-name ')' '{' initializer-list '}'
689/// '(' type-name ')' '{' initializer-list ',' '}'
690///
691/// argument-expression-list: [C99 6.5.2]
692/// argument-expression
693/// argument-expression-list ',' assignment-expression
694///
695Parser::ExprResult Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
Sebastian Redla55e52c2008-11-25 22:21:31 +0000696 ExprGuard LHSGuard(Actions, LHS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 // Now that the primary-expression piece of the postfix-expression has been
698 // parsed, see if there are any postfix-expression pieces here.
699 SourceLocation Loc;
700 while (1) {
701 switch (Tok.getKind()) {
702 default: // Not a postfix-expression suffix.
Sebastian Redla55e52c2008-11-25 22:21:31 +0000703 LHSGuard.take();
Reid Spencer5f016e22007-07-11 17:01:13 +0000704 return LHS;
705 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
706 Loc = ConsumeBracket();
707 ExprResult Idx = ParseExpression();
Sebastian Redla55e52c2008-11-25 22:21:31 +0000708 ExprGuard IdxGuard(Actions, Idx);
709
Reid Spencer5f016e22007-07-11 17:01:13 +0000710 SourceLocation RLoc = Tok.getLocation();
711
Sebastian Redla55e52c2008-11-25 22:21:31 +0000712 if (!LHS.isInvalid && !Idx.isInvalid && Tok.is(tok::r_square)) {
713 LHS = Actions.ActOnArraySubscriptExpr(CurScope, LHSGuard.take(), Loc,
714 IdxGuard.take(), RLoc);
715 LHSGuard.reset(LHS);
716 } else
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 LHS = ExprResult(true);
718
719 // Match the ']'.
720 MatchRHSPunctuation(tok::r_square, Loc);
721 break;
722 }
723
724 case tok::l_paren: { // p-e: p-e '(' argument-expression-list[opt] ')'
Sebastian Redla55e52c2008-11-25 22:21:31 +0000725 ExprVector ArgExprs(Actions);
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +0000726 CommaLocsTy CommaLocs;
Reid Spencer5f016e22007-07-11 17:01:13 +0000727
728 Loc = ConsumeParen();
729
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000730 if (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +0000731 if (ParseExpressionList(ArgExprs, CommaLocs)) {
732 SkipUntil(tok::r_paren);
733 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000734 }
735 }
736
737 // Match the ')'.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000738 if (!LHS.isInvalid && Tok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000739 assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&&
740 "Unexpected number of commas!");
Sebastian Redla55e52c2008-11-25 22:21:31 +0000741 LHS = Actions.ActOnCallExpr(LHSGuard.take(), Loc, ArgExprs.take(),
742 ArgExprs.size(), &CommaLocs[0],
743 Tok.getLocation());
744 LHSGuard.reset(LHS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000745 }
746
Chris Lattner2ff54262007-07-21 05:18:12 +0000747 MatchRHSPunctuation(tok::r_paren, Loc);
Reid Spencer5f016e22007-07-11 17:01:13 +0000748 break;
749 }
750 case tok::arrow: // postfix-expression: p-e '->' identifier
751 case tok::period: { // postfix-expression: p-e '.' identifier
752 tok::TokenKind OpKind = Tok.getKind();
753 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
754
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000755 if (Tok.isNot(tok::identifier)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000756 Diag(Tok, diag::err_expected_ident);
757 return ExprResult(true);
758 }
759
Sebastian Redla55e52c2008-11-25 22:21:31 +0000760 if (!LHS.isInvalid) {
761 LHS = Actions.ActOnMemberReferenceExpr(LHSGuard.take(), OpLoc, OpKind,
Reid Spencer5f016e22007-07-11 17:01:13 +0000762 Tok.getLocation(),
763 *Tok.getIdentifierInfo());
Sebastian Redla55e52c2008-11-25 22:21:31 +0000764 LHSGuard.reset(LHS);
765 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000766 ConsumeToken();
767 break;
768 }
769 case tok::plusplus: // postfix-expression: postfix-expression '++'
770 case tok::minusminus: // postfix-expression: postfix-expression '--'
Sebastian Redla55e52c2008-11-25 22:21:31 +0000771 if (!LHS.isInvalid) {
Douglas Gregor74253732008-11-19 15:42:04 +0000772 LHS = Actions.ActOnPostfixUnaryOp(CurScope, Tok.getLocation(),
Sebastian Redla55e52c2008-11-25 22:21:31 +0000773 Tok.getKind(), LHSGuard.take());
774 LHSGuard.reset(LHS);
775 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000776 ConsumeToken();
777 break;
778 }
779 }
780}
781
782
783/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression.
784/// unary-expression: [C99 6.5.3]
785/// 'sizeof' unary-expression
786/// 'sizeof' '(' type-name ')'
787/// [GNU] '__alignof' unary-expression
788/// [GNU] '__alignof' '(' type-name ')'
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000789/// [C++0x] 'alignof' '(' type-id ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000790Parser::ExprResult Parser::ParseSizeofAlignofExpression() {
Douglas Gregor85bb3da2008-11-06 15:17:27 +0000791 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof)
792 || Tok.is(tok::kw_alignof)) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000793 "Not a sizeof/alignof expression!");
Chris Lattnerd2177732007-07-20 16:59:19 +0000794 Token OpTok = Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000795 ConsumeToken();
796
797 // If the operand doesn't start with an '(', it must be an expression.
798 ExprResult Operand;
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000799 if (Tok.isNot(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000800 Operand = ParseCastExpression(true);
801 } else {
802 // If it starts with a '(', we know that it is either a parenthesized
803 // type-name, or it is a unary-expression that starts with a compound
804 // literal, or starts with a primary-expression that is a parenthesized
805 // expression.
806 ParenParseOption ExprType = CastExpr;
807 TypeTy *CastTy;
808 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
809 Operand = ParseParenExpression(ExprType, CastTy, RParenLoc);
810
811 // If ParseParenExpression parsed a '(typename)' sequence only, the this is
812 // sizeof/alignof a type. Otherwise, it is sizeof/alignof an expression.
Chris Lattner4c1a2a92007-11-13 20:50:37 +0000813 if (ExprType == CastExpr)
Sebastian Redl05189992008-11-11 17:56:53 +0000814 return Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
815 OpTok.is(tok::kw_sizeof),
816 /*isType=*/true, CastTy,
817 SourceRange(LParenLoc, RParenLoc));
Chris Lattner4c1a2a92007-11-13 20:50:37 +0000818
819 // If this is a parenthesized expression, it is the start of a
820 // unary-expression, but doesn't include any postfix pieces. Parse these
821 // now if present.
822 Operand = ParsePostfixExpressionSuffix(Operand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000823 }
824
825 // If we get here, the operand to the sizeof/alignof was an expresion.
826 if (!Operand.isInvalid)
Sebastian Redl05189992008-11-11 17:56:53 +0000827 Operand = Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
828 OpTok.is(tok::kw_sizeof),
829 /*isType=*/false, Operand.Val,
830 SourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000831 return Operand;
832}
833
834/// ParseBuiltinPrimaryExpression
835///
836/// primary-expression: [C99 6.5.1]
837/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
838/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
839/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
840/// assign-expr ')'
841/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
Nate Begemane2ce1d92008-01-17 17:46:27 +0000842/// [CLANG] '__builtin_overload' '(' expr (',' expr)* ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000843///
844/// [GNU] offsetof-member-designator:
845/// [GNU] identifier
846/// [GNU] offsetof-member-designator '.' identifier
847/// [GNU] offsetof-member-designator '[' expression ']'
848///
849Parser::ExprResult Parser::ParseBuiltinPrimaryExpression() {
850 ExprResult Res(false);
851 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
852
853 tok::TokenKind T = Tok.getKind();
854 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
855
856 // All of these start with an open paren.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000857 if (Tok.isNot(tok::l_paren)) {
Chris Lattner08631c52008-11-23 21:45:46 +0000858 Diag(Tok, diag::err_expected_lparen_after_id) << BuiltinII;
Reid Spencer5f016e22007-07-11 17:01:13 +0000859 return ExprResult(true);
860 }
861
862 SourceLocation LParenLoc = ConsumeParen();
863 // TODO: Build AST.
864
865 switch (T) {
866 default: assert(0 && "Not a builtin primary expression!");
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000867 case tok::kw___builtin_va_arg: {
868 ExprResult Expr = ParseAssignmentExpression();
Sebastian Redla55e52c2008-11-25 22:21:31 +0000869 ExprGuard ExprGuard(Actions, Expr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000870 if (Expr.isInvalid) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000871 SkipUntil(tok::r_paren);
Eli Friedman09762782008-08-20 22:07:34 +0000872 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000873 }
874
875 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
876 return ExprResult(true);
877
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000878 TypeTy *Ty = ParseTypeName();
Chris Lattner6eb21092007-08-30 15:52:49 +0000879
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000880 if (Tok.isNot(tok::r_paren)) {
881 Diag(Tok, diag::err_expected_rparen);
882 return ExprResult(true);
883 }
Sebastian Redla55e52c2008-11-25 22:21:31 +0000884 Res = Actions.ActOnVAArg(StartLoc, ExprGuard.take(), Ty, ConsumeParen());
Reid Spencer5f016e22007-07-11 17:01:13 +0000885 break;
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000886 }
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000887 case tok::kw___builtin_offsetof: {
Chris Lattner9fddf0a2007-08-30 17:08:45 +0000888 SourceLocation TypeLoc = Tok.getLocation();
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000889 TypeTy *Ty = ParseTypeName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000890
891 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
892 return ExprResult(true);
893
894 // We must have at least one identifier here.
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000895 if (Tok.isNot(tok::identifier)) {
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000896 Diag(Tok, diag::err_expected_ident);
897 SkipUntil(tok::r_paren);
898 return true;
899 }
900
901 // Keep track of the various subcomponents we see.
902 llvm::SmallVector<Action::OffsetOfComponent, 4> Comps;
903
904 Comps.push_back(Action::OffsetOfComponent());
905 Comps.back().isBrackets = false;
906 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
907 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
Reid Spencer5f016e22007-07-11 17:01:13 +0000908
Sebastian Redla55e52c2008-11-25 22:21:31 +0000909 // FIXME: This loop leaks the index expressions on error.
Reid Spencer5f016e22007-07-11 17:01:13 +0000910 while (1) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000911 if (Tok.is(tok::period)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000912 // offsetof-member-designator: offsetof-member-designator '.' identifier
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000913 Comps.push_back(Action::OffsetOfComponent());
914 Comps.back().isBrackets = false;
915 Comps.back().LocStart = ConsumeToken();
Reid Spencer5f016e22007-07-11 17:01:13 +0000916
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000917 if (Tok.isNot(tok::identifier)) {
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000918 Diag(Tok, diag::err_expected_ident);
919 SkipUntil(tok::r_paren);
920 return true;
921 }
922 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
923 Comps.back().LocEnd = ConsumeToken();
924
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000925 } else if (Tok.is(tok::l_square)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000926 // offsetof-member-designator: offsetof-member-design '[' expression ']'
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000927 Comps.push_back(Action::OffsetOfComponent());
928 Comps.back().isBrackets = true;
929 Comps.back().LocStart = ConsumeBracket();
Reid Spencer5f016e22007-07-11 17:01:13 +0000930 Res = ParseExpression();
931 if (Res.isInvalid) {
932 SkipUntil(tok::r_paren);
933 return Res;
934 }
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000935 Comps.back().U.E = Res.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000936
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000937 Comps.back().LocEnd =
938 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart);
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000939 } else if (Tok.is(tok::r_paren)) {
Steve Naroff1b273c42007-09-16 14:56:35 +0000940 Res = Actions.ActOnBuiltinOffsetOf(StartLoc, TypeLoc, Ty, &Comps[0],
Chris Lattner6eb21092007-08-30 15:52:49 +0000941 Comps.size(), ConsumeParen());
942 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000943 } else {
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000944 // Error occurred.
945 return ExprResult(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000946 }
947 }
948 break;
Chris Lattnerf9aa3cb2007-08-30 15:51:11 +0000949 }
Steve Naroffd04fdd52007-08-03 21:21:27 +0000950 case tok::kw___builtin_choose_expr: {
951 ExprResult Cond = ParseAssignmentExpression();
Sebastian Redla55e52c2008-11-25 22:21:31 +0000952 ExprGuard CondGuard(Actions, Cond);
Steve Naroffd04fdd52007-08-03 21:21:27 +0000953 if (Cond.isInvalid) {
954 SkipUntil(tok::r_paren);
955 return Cond;
956 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000957 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
958 return ExprResult(true);
959
Steve Naroffd04fdd52007-08-03 21:21:27 +0000960 ExprResult Expr1 = ParseAssignmentExpression();
Sebastian Redla55e52c2008-11-25 22:21:31 +0000961 ExprGuard Guard1(Actions, Expr1);
Steve Naroffd04fdd52007-08-03 21:21:27 +0000962 if (Expr1.isInvalid) {
963 SkipUntil(tok::r_paren);
964 return Expr1;
965 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000966 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
967 return ExprResult(true);
968
Steve Naroffd04fdd52007-08-03 21:21:27 +0000969 ExprResult Expr2 = ParseAssignmentExpression();
Sebastian Redla55e52c2008-11-25 22:21:31 +0000970 ExprGuard Guard2(Actions, Expr2);
Steve Naroffd04fdd52007-08-03 21:21:27 +0000971 if (Expr2.isInvalid) {
972 SkipUntil(tok::r_paren);
973 return Expr2;
974 }
Chris Lattner4e1d99a2007-10-09 17:41:39 +0000975 if (Tok.isNot(tok::r_paren)) {
Steve Naroffd04fdd52007-08-03 21:21:27 +0000976 Diag(Tok, diag::err_expected_rparen);
977 return ExprResult(true);
978 }
Sebastian Redla55e52c2008-11-25 22:21:31 +0000979 Res = Actions.ActOnChooseExpr(StartLoc, CondGuard.take(), Guard1.take(),
980 Guard2.take(), ConsumeParen());
Chris Lattner6eb21092007-08-30 15:52:49 +0000981 break;
Steve Naroffd04fdd52007-08-03 21:21:27 +0000982 }
Nate Begemane2ce1d92008-01-17 17:46:27 +0000983 case tok::kw___builtin_overload: {
Sebastian Redla55e52c2008-11-25 22:21:31 +0000984 ExprVector ArgExprs(Actions);
Nate Begemane2ce1d92008-01-17 17:46:27 +0000985 llvm::SmallVector<SourceLocation, 8> CommaLocs;
986
987 // For each iteration through the loop look for assign-expr followed by a
988 // comma. If there is no comma, break and attempt to match r-paren.
989 if (Tok.isNot(tok::r_paren)) {
990 while (1) {
991 ExprResult ArgExpr = ParseAssignmentExpression();
992 if (ArgExpr.isInvalid) {
993 SkipUntil(tok::r_paren);
994 return ExprResult(true);
995 } else
996 ArgExprs.push_back(ArgExpr.Val);
997
998 if (Tok.isNot(tok::comma))
999 break;
1000 // Move to the next argument, remember where the comma was.
1001 CommaLocs.push_back(ConsumeToken());
1002 }
1003 }
1004
1005 // Attempt to consume the r-paren
1006 if (Tok.isNot(tok::r_paren)) {
1007 Diag(Tok, diag::err_expected_rparen);
1008 SkipUntil(tok::r_paren);
1009 return ExprResult(true);
1010 }
Sebastian Redla55e52c2008-11-25 22:21:31 +00001011 Res = Actions.ActOnOverloadExpr(ArgExprs.take(), ArgExprs.size(),
Nate Begemane2ce1d92008-01-17 17:46:27 +00001012 &CommaLocs[0], StartLoc, ConsumeParen());
1013 break;
1014 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001015 case tok::kw___builtin_types_compatible_p:
Steve Naroff363bcff2007-08-01 23:45:51 +00001016 TypeTy *Ty1 = ParseTypeName();
Reid Spencer5f016e22007-07-11 17:01:13 +00001017
1018 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1019 return ExprResult(true);
1020
Steve Naroff363bcff2007-08-01 23:45:51 +00001021 TypeTy *Ty2 = ParseTypeName();
1022
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001023 if (Tok.isNot(tok::r_paren)) {
Steve Naroff363bcff2007-08-01 23:45:51 +00001024 Diag(Tok, diag::err_expected_rparen);
1025 return ExprResult(true);
1026 }
Steve Naroff1b273c42007-09-16 14:56:35 +00001027 Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1, Ty2, ConsumeParen());
Chris Lattner6eb21092007-08-30 15:52:49 +00001028 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001029 }
1030
Reid Spencer5f016e22007-07-11 17:01:13 +00001031 // These can be followed by postfix-expr pieces because they are
1032 // primary-expressions.
1033 return ParsePostfixExpressionSuffix(Res);
1034}
1035
1036/// ParseParenExpression - This parses the unit that starts with a '(' token,
1037/// based on what is allowed by ExprType. The actual thing parsed is returned
1038/// in ExprType.
1039///
1040/// primary-expression: [C99 6.5.1]
1041/// '(' expression ')'
1042/// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
1043/// postfix-expression: [C99 6.5.2]
1044/// '(' type-name ')' '{' initializer-list '}'
1045/// '(' type-name ')' '{' initializer-list ',' '}'
1046/// cast-expression: [C99 6.5.4]
1047/// '(' type-name ')' cast-expression
1048///
1049Parser::ExprResult Parser::ParseParenExpression(ParenParseOption &ExprType,
1050 TypeTy *&CastTy,
1051 SourceLocation &RParenLoc) {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001052 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001053 SourceLocation OpenLoc = ConsumeParen();
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001054 ExprResult Result(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 CastTy = 0;
1056
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001057 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001058 Diag(Tok, diag::ext_gnu_statement_expr);
Chris Lattner98414c12007-08-31 21:49:55 +00001059 Parser::StmtResult Stmt = ParseCompoundStatement(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001060 ExprType = CompoundStmt;
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001061
1062 // If the substmt parsed correctly, build the AST node.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001063 if (!Stmt.isInvalid && Tok.is(tok::r_paren))
Steve Naroff1b273c42007-09-16 14:56:35 +00001064 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.Val, Tok.getLocation());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00001065
Argyrios Kyrtzidis78c8d802008-10-05 19:56:22 +00001066 } else if (ExprType >= CompoundLiteral && isTypeIdInParens()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001067 // Otherwise, this is a compound literal expression or cast expression.
1068 TypeTy *Ty = ParseTypeName();
1069
1070 // Match the ')'.
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001071 if (Tok.is(tok::r_paren))
Reid Spencer5f016e22007-07-11 17:01:13 +00001072 RParenLoc = ConsumeParen();
1073 else
1074 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1075
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001076 if (Tok.is(tok::l_brace)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001077 if (!getLang().C99) // Compound literals don't exist in C90.
1078 Diag(OpenLoc, diag::ext_c99_compound_literal);
1079 Result = ParseInitializer();
1080 ExprType = CompoundLiteral;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001081 if (!Result.isInvalid)
Steve Narofff69936d2007-09-16 03:34:24 +00001082 return Actions.ActOnCompoundLiteral(OpenLoc, Ty, RParenLoc, Result.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +00001083 } else if (ExprType == CastExpr) {
1084 // Note that this doesn't parse the subsequence cast-expression, it just
1085 // returns the parsed type to the callee.
1086 ExprType = CastExpr;
1087 CastTy = Ty;
1088 return ExprResult(false);
1089 } else {
1090 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
1091 return ExprResult(true);
1092 }
1093 return Result;
1094 } else {
1095 Result = ParseExpression();
1096 ExprType = SimpleExpr;
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001097 if (!Result.isInvalid && Tok.is(tok::r_paren))
Steve Narofff69936d2007-09-16 03:34:24 +00001098 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.Val);
Reid Spencer5f016e22007-07-11 17:01:13 +00001099 }
1100
1101 // Match the ')'.
1102 if (Result.isInvalid)
1103 SkipUntil(tok::r_paren);
1104 else {
Chris Lattner4e1d99a2007-10-09 17:41:39 +00001105 if (Tok.is(tok::r_paren))
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 RParenLoc = ConsumeParen();
1107 else
1108 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1109 }
1110
1111 return Result;
1112}
1113
1114/// ParseStringLiteralExpression - This handles the various token types that
1115/// form string literals, and also handles string concatenation [C99 5.1.1.2,
1116/// translation phase #6].
1117///
1118/// primary-expression: [C99 6.5.1]
1119/// string-literal
1120Parser::ExprResult Parser::ParseStringLiteralExpression() {
1121 assert(isTokenStringLiteral() && "Not a string literal!");
1122
1123 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
1124 // considered to be strings for concatenation purposes.
Chris Lattnerd2177732007-07-20 16:59:19 +00001125 llvm::SmallVector<Token, 4> StringToks;
Reid Spencer5f016e22007-07-11 17:01:13 +00001126
1127 do {
1128 StringToks.push_back(Tok);
1129 ConsumeStringToken();
1130 } while (isTokenStringLiteral());
1131
1132 // Pass the set of string tokens, ready for concatenation, to the actions.
Steve Narofff69936d2007-09-16 03:34:24 +00001133 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size());
Reid Spencer5f016e22007-07-11 17:01:13 +00001134}
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +00001135
1136/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1137///
1138/// argument-expression-list:
1139/// assignment-expression
1140/// argument-expression-list , assignment-expression
1141///
1142/// [C++] expression-list:
1143/// [C++] assignment-expression
1144/// [C++] expression-list , assignment-expression
1145///
1146bool Parser::ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs) {
1147 while (1) {
1148 ExprResult Expr = ParseAssignmentExpression();
1149 if (Expr.isInvalid)
1150 return true;
Argyrios Kyrtzidis4fdc1ca2008-08-18 22:49:40 +00001151
1152 Exprs.push_back(Expr.Val);
Argyrios Kyrtzidis0cd5b422008-08-16 20:03:01 +00001153
1154 if (Tok.isNot(tok::comma))
1155 return false;
1156 // Move to the next argument, remember where the comma was.
1157 CommaLocs.push_back(ConsumeToken());
1158 }
1159}
Steve Naroff296e8d52008-08-28 19:20:44 +00001160
1161/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
Steve Naroff17dab4f2008-09-16 23:11:46 +00001162/// like ^(int x){ return x+1; }
Steve Naroff296e8d52008-08-28 19:20:44 +00001163///
1164/// block-literal:
1165/// [clang] '^' block-args[opt] compound-statement
Steve Naroff296e8d52008-08-28 19:20:44 +00001166/// [clang] block-args:
1167/// [clang] '(' parameter-list ')'
1168///
1169Parser::ExprResult Parser::ParseBlockLiteralExpression() {
1170 assert(Tok.is(tok::caret) && "block literal starts with ^");
1171 SourceLocation CaretLoc = ConsumeToken();
1172
1173 // Enter a scope to hold everything within the block. This includes the
1174 // argument decls, decls within the compound expression, etc. This also
1175 // allows determining whether a variable reference inside the block is
1176 // within or outside of the block.
1177 EnterScope(Scope::BlockScope|Scope::FnScope|Scope::BreakScope|
1178 Scope::ContinueScope|Scope::DeclScope);
Steve Naroff090276f2008-10-10 01:28:17 +00001179
1180 // Inform sema that we are starting a block.
1181 Actions.ActOnBlockStart(CaretLoc, CurScope);
Steve Naroff296e8d52008-08-28 19:20:44 +00001182
1183 // Parse the return type if present.
1184 DeclSpec DS;
1185 Declarator ParamInfo(DS, Declarator::PrototypeContext);
1186
1187 // If this block has arguments, parse them. There is no ambiguity here with
1188 // the expression case, because the expression case requires a parameter list.
1189 if (Tok.is(tok::l_paren)) {
1190 ParseParenDeclarator(ParamInfo);
1191 // Parse the pieces after the identifier as if we had "int(...)".
1192 ParamInfo.SetIdentifier(0, CaretLoc);
1193 if (ParamInfo.getInvalidType()) {
1194 // If there was an error parsing the arguments, they may have tried to use
1195 // ^(x+y) which requires an argument list. Just skip the whole block
1196 // literal.
1197 ExitScope();
1198 return true;
1199 }
1200 } else {
1201 // Otherwise, pretend we saw (void).
1202 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false,
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001203 0, 0, 0, CaretLoc));
Steve Naroff296e8d52008-08-28 19:20:44 +00001204 }
1205
1206 // Inform sema that we are starting a block.
Steve Naroff090276f2008-10-10 01:28:17 +00001207 Actions.ActOnBlockArguments(ParamInfo);
Steve Naroff296e8d52008-08-28 19:20:44 +00001208
Steve Naroff17dab4f2008-09-16 23:11:46 +00001209 ExprResult Result = true;
Steve Naroff296e8d52008-08-28 19:20:44 +00001210 if (Tok.is(tok::l_brace)) {
1211 StmtResult Stmt = ParseCompoundStatementBody();
1212 if (!Stmt.isInvalid) {
1213 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.Val, CurScope);
1214 } else {
1215 Actions.ActOnBlockError(CaretLoc, CurScope);
Steve Naroff296e8d52008-08-28 19:20:44 +00001216 }
1217 }
Steve Naroff296e8d52008-08-28 19:20:44 +00001218 ExitScope();
1219 return Result;
1220}
1221