blob: e31c7a586ef8374c37d4bee54956d7dc0fb9d44e [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 ')'
Douglas Gregorad4b3792008-11-29 04:51:27 +0000381/// [GNU] '__null'
Fariborz Jahanian628abf12007-09-26 17:03:44 +0000382/// [OBJC] '[' objc-message-expr ']'
Chris Lattner8d050af2008-01-25 18:58:06 +0000383/// [OBJC] '@selector' '(' objc-selector-arg ')'
Fariborz Jahanian628abf12007-09-26 17:03:44 +0000384/// [OBJC] '@protocol' '(' identifier ')'
385/// [OBJC] '@encode' '(' type-name ')'
Fariborz Jahanian1e534dc2007-09-05 19:52:07 +0000386/// [OBJC] objc-string-literal
Argiris Kirtzidis7a1e7412008-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]
Chris Lattner4b009652007-07-25 00:24:17 +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 Redlb93b49c2008-11-11 11:37:55 +0000393/// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
394/// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
Argiris Kirtzidisfdde2762008-07-16 07:23:27 +0000395/// [C++] 'this' [C++ 9.3.2]
Steve Narofffd5b19d2008-08-28 19:20:44 +0000396/// [clang] '^' block-literal
Chris Lattner4b009652007-07-25 00:24:17 +0000397///
398/// constant: [C99 6.4.4]
399/// integer-constant
400/// floating-constant
401/// enumeration-constant -> identifier
402/// character-constant
403///
Douglas Gregore60e5d32008-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]
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000414///
Sebastian Redl19fec9d2008-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///
Chris Lattner4b009652007-07-25 00:24:17 +0000425Parser::ExprResult Parser::ParseCastExpression(bool isUnaryExpression) {
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000426 if (getLang().CPlusPlus) {
427 // Annotate typenames and C++ scope specifiers.
Argiris Kirtzidisfc332322008-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.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000433 TryAnnotateTypeOrScopeToken();
434 }
435
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroff87d58b42007-09-16 03:34:24 +0000474 Res = Actions.ActOnCastExpr(LParenLoc, CastTy, RParenLoc, Res.Val);
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroff87d58b42007-09-16 03:34:24 +0000487 Res = Actions.ActOnNumericConstant(Tok);
Chris Lattner4b009652007-07-25 00:24:17 +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
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000497 case tok::identifier: { // primary-expression: identifier
498 // unqualified-id: identifier
499 // constant: enumeration-constant
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000500
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner4d7d2342007-10-09 17:41:39 +0000507 Res = Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren));
Chris Lattner4b009652007-07-25 00:24:17 +0000508 // These can be followed by postfix-expr pieces.
509 return ParsePostfixExpressionSuffix(Res);
510 }
511 case tok::char_constant: // constant: character-constant
Steve Naroff87d58b42007-09-16 03:34:24 +0000512 Res = Actions.ActOnCharacterConstant(Tok);
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner69909292008-08-10 01:53:14 +0000519 Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
Chris Lattner4b009652007-07-25 00:24:17 +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 Begeman9f3bfb72008-01-17 17:46:27 +0000532 case tok::kw___builtin_overload:
Chris Lattner4b009652007-07-25 00:24:17 +0000533 case tok::kw___builtin_types_compatible_p:
534 return ParseBuiltinPrimaryExpression();
Douglas Gregorad4b3792008-11-29 04:51:27 +0000535 case tok::kw___null:
536 return Actions.ActOnGNUNullExpr(ConsumeToken());
537 break;
Chris Lattner4b009652007-07-25 00:24:17 +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 Gregor4f6904d2008-11-19 15:42:04 +0000543 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattner6cf92942008-02-02 20:20:10 +0000553 case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
Chris Lattner4b009652007-07-25 00:24:17 +0000554 SourceLocation SavedLoc = ConsumeToken();
555 Res = ParseCastExpression(false);
556 if (!Res.isInvalid)
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000557 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Chris Lattner4b009652007-07-25 00:24:17 +0000558 return Res;
Chris Lattner6cf92942008-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 Lattnerdaa5c002008-10-20 06:45:43 +0000563 ExtensionRAIIObject O(Diags); // Use RAII to do this.
Chris Lattner6cf92942008-02-02 20:20:10 +0000564 SourceLocation SavedLoc = ConsumeToken();
565 Res = ParseCastExpression(false);
566 if (!Res.isInvalid)
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000567 Res = Actions.ActOnUnaryOp(CurScope, SavedLoc, SavedKind, Res.Val);
Chris Lattner6cf92942008-02-02 20:20:10 +0000568 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000569 }
570 case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
571 // unary-expression: 'sizeof' '(' type-name ')'
Douglas Gregor658b4442008-11-06 15:17:27 +0000572 case tok::kw_alignof:
Chris Lattner4b009652007-07-25 00:24:17 +0000573 case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
574 // unary-expression: '__alignof' '(' type-name ')'
Douglas Gregor658b4442008-11-06 15:17:27 +0000575 // unary-expression: 'alignof' '(' type-id ')'
Chris Lattner4b009652007-07-25 00:24:17 +0000576 return ParseSizeofAlignofExpression();
577 case tok::ampamp: { // unary-expression: '&&' identifier
578 SourceLocation AmpAmpLoc = ConsumeToken();
Chris Lattner4d7d2342007-10-09 17:41:39 +0000579 if (Tok.isNot(tok::identifier)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000580 Diag(Tok, diag::err_expected_ident);
581 return ExprResult(true);
582 }
583
584 Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000585 Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +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:
Argiris Kirtzidis4963ee42008-08-16 19:45:32 +0000594 Res = ParseCXXCasts();
595 // These can be followed by postfix-expr pieces.
596 return ParsePostfixExpressionSuffix(Res);
Sebastian Redlb93b49c2008-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);
Argiris Kirtzidis9d784332008-06-24 22:12:16 +0000601 case tok::kw_this:
Argiris Kirtzidis8f8a52a2008-08-16 19:34:46 +0000602 Res = ParseCXXThis();
603 // This can be followed by postfix-expr pieces.
604 return ParsePostfixExpressionSuffix(Res);
Argiris Kirtzidis7a1e7412008-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;
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000620 case tok::annot_qualtypename:
621 assert(getLang().CPlusPlus && "Expected C++");
Argiris Kirtzidis7a1e7412008-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 Lattnerf006a222008-11-18 07:48:38 +0000627 return Diag(Tok, diag::err_expected_lparen_after_type)
628 << DS.getSourceRange();
Argiris Kirtzidis7a1e7412008-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
Argiris Kirtzidis311db8c2008-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 Gregore60e5d32008-11-06 22:13:31 +0000640
Sebastian Redl7c5955a2008-12-02 16:35:44 +0000641 case tok::coloncolon: // [C++] new-expression or [C++] delete-expression
Sebastian Redlb761e132008-12-02 17:10:24 +0000642 // If the next token is neither 'new' nor 'delete', the :: would have been
643 // parsed as a scope specifier already.
Sebastian Redl7c5955a2008-12-02 16:35:44 +0000644 if (NextToken().is(tok::kw_new))
645 return ParseCXXNewExpression();
646 else
647 return ParseCXXDeleteExpression();
648
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000649 case tok::kw_new: // [C++] new-expression
Sebastian Redl19fec9d2008-11-21 19:14:01 +0000650 return ParseCXXNewExpression();
651
652 case tok::kw_delete: // [C++] delete-expression
653 return ParseCXXDeleteExpression();
654
Chris Lattnerb82d6ef2007-10-03 22:03:06 +0000655 case tok::at: {
656 SourceLocation AtLoc = ConsumeToken();
Steve Narofffb9dd752007-10-15 20:55:58 +0000657 return ParseObjCAtExpression(AtLoc);
Chris Lattnerb82d6ef2007-10-03 22:03:06 +0000658 }
Fariborz Jahanian1e534dc2007-09-05 19:52:07 +0000659 case tok::l_square:
Steve Narofffb9dd752007-10-15 20:55:58 +0000660 // These can be followed by postfix-expr pieces.
Chris Lattner02d3c732008-05-09 05:28:21 +0000661 if (getLang().ObjC1)
662 return ParsePostfixExpressionSuffix(ParseObjCMessageExpression());
663 // FALL THROUGH.
Steve Narofffd5b19d2008-08-28 19:20:44 +0000664 case tok::caret:
665 if (getLang().Blocks)
666 return ParsePostfixExpressionSuffix(ParseBlockLiteralExpression());
667 Diag(Tok, diag::err_expected_expression);
668 return ExprResult(true);
Chris Lattner4b009652007-07-25 00:24:17 +0000669 default:
Argiris Kirtzidis7a1e7412008-08-22 15:38:55 +0000670 UnhandledToken:
Chris Lattner4b009652007-07-25 00:24:17 +0000671 Diag(Tok, diag::err_expected_expression);
672 return ExprResult(true);
673 }
674
675 // unreachable.
676 abort();
677}
678
679/// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
680/// is parsed, this method parses any suffixes that apply.
681///
682/// postfix-expression: [C99 6.5.2]
683/// primary-expression
684/// postfix-expression '[' expression ']'
685/// postfix-expression '(' argument-expression-list[opt] ')'
686/// postfix-expression '.' identifier
687/// postfix-expression '->' identifier
688/// postfix-expression '++'
689/// postfix-expression '--'
690/// '(' type-name ')' '{' initializer-list '}'
691/// '(' type-name ')' '{' initializer-list ',' '}'
692///
693/// argument-expression-list: [C99 6.5.2]
694/// argument-expression
695/// argument-expression-list ',' assignment-expression
696///
697Parser::ExprResult Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
Sebastian Redl6008ac32008-11-25 22:21:31 +0000698 ExprGuard LHSGuard(Actions, LHS);
Chris Lattner4b009652007-07-25 00:24:17 +0000699 // Now that the primary-expression piece of the postfix-expression has been
700 // parsed, see if there are any postfix-expression pieces here.
701 SourceLocation Loc;
702 while (1) {
703 switch (Tok.getKind()) {
704 default: // Not a postfix-expression suffix.
Sebastian Redl6008ac32008-11-25 22:21:31 +0000705 LHSGuard.take();
Chris Lattner4b009652007-07-25 00:24:17 +0000706 return LHS;
707 case tok::l_square: { // postfix-expression: p-e '[' expression ']'
708 Loc = ConsumeBracket();
709 ExprResult Idx = ParseExpression();
Sebastian Redl6008ac32008-11-25 22:21:31 +0000710 ExprGuard IdxGuard(Actions, Idx);
711
Chris Lattner4b009652007-07-25 00:24:17 +0000712 SourceLocation RLoc = Tok.getLocation();
713
Sebastian Redl6008ac32008-11-25 22:21:31 +0000714 if (!LHS.isInvalid && !Idx.isInvalid && Tok.is(tok::r_square)) {
715 LHS = Actions.ActOnArraySubscriptExpr(CurScope, LHSGuard.take(), Loc,
716 IdxGuard.take(), RLoc);
717 LHSGuard.reset(LHS);
718 } else
Chris Lattner4b009652007-07-25 00:24:17 +0000719 LHS = ExprResult(true);
720
721 // Match the ']'.
722 MatchRHSPunctuation(tok::r_square, Loc);
723 break;
724 }
725
726 case tok::l_paren: { // p-e: p-e '(' argument-expression-list[opt] ')'
Sebastian Redl6008ac32008-11-25 22:21:31 +0000727 ExprVector ArgExprs(Actions);
Argiris Kirtzidis83dce112008-08-16 20:03:01 +0000728 CommaLocsTy CommaLocs;
Chris Lattner4b009652007-07-25 00:24:17 +0000729
730 Loc = ConsumeParen();
731
Chris Lattner4d7d2342007-10-09 17:41:39 +0000732 if (Tok.isNot(tok::r_paren)) {
Argiris Kirtzidis83dce112008-08-16 20:03:01 +0000733 if (ParseExpressionList(ArgExprs, CommaLocs)) {
734 SkipUntil(tok::r_paren);
735 return ExprResult(true);
Chris Lattner4b009652007-07-25 00:24:17 +0000736 }
737 }
738
739 // Match the ')'.
Chris Lattner4d7d2342007-10-09 17:41:39 +0000740 if (!LHS.isInvalid && Tok.is(tok::r_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000741 assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&&
742 "Unexpected number of commas!");
Douglas Gregora133e262008-12-06 00:22:45 +0000743 LHS = Actions.ActOnCallExpr(CurScope, LHSGuard.take(), Loc,
744 ArgExprs.take(),
Sebastian Redl6008ac32008-11-25 22:21:31 +0000745 ArgExprs.size(), &CommaLocs[0],
746 Tok.getLocation());
747 LHSGuard.reset(LHS);
Chris Lattner4b009652007-07-25 00:24:17 +0000748 }
749
750 MatchRHSPunctuation(tok::r_paren, Loc);
751 break;
752 }
753 case tok::arrow: // postfix-expression: p-e '->' identifier
754 case tok::period: { // postfix-expression: p-e '.' identifier
755 tok::TokenKind OpKind = Tok.getKind();
756 SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
757
Chris Lattner4d7d2342007-10-09 17:41:39 +0000758 if (Tok.isNot(tok::identifier)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000759 Diag(Tok, diag::err_expected_ident);
760 return ExprResult(true);
761 }
762
Sebastian Redl6008ac32008-11-25 22:21:31 +0000763 if (!LHS.isInvalid) {
764 LHS = Actions.ActOnMemberReferenceExpr(LHSGuard.take(), OpLoc, OpKind,
Chris Lattner4b009652007-07-25 00:24:17 +0000765 Tok.getLocation(),
766 *Tok.getIdentifierInfo());
Sebastian Redl6008ac32008-11-25 22:21:31 +0000767 LHSGuard.reset(LHS);
768 }
Chris Lattner4b009652007-07-25 00:24:17 +0000769 ConsumeToken();
770 break;
771 }
772 case tok::plusplus: // postfix-expression: postfix-expression '++'
773 case tok::minusminus: // postfix-expression: postfix-expression '--'
Sebastian Redl6008ac32008-11-25 22:21:31 +0000774 if (!LHS.isInvalid) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000775 LHS = Actions.ActOnPostfixUnaryOp(CurScope, Tok.getLocation(),
Sebastian Redl6008ac32008-11-25 22:21:31 +0000776 Tok.getKind(), LHSGuard.take());
777 LHSGuard.reset(LHS);
778 }
Chris Lattner4b009652007-07-25 00:24:17 +0000779 ConsumeToken();
780 break;
781 }
782 }
783}
784
785
786/// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression.
787/// unary-expression: [C99 6.5.3]
788/// 'sizeof' unary-expression
789/// 'sizeof' '(' type-name ')'
790/// [GNU] '__alignof' unary-expression
791/// [GNU] '__alignof' '(' type-name ')'
Douglas Gregor658b4442008-11-06 15:17:27 +0000792/// [C++0x] 'alignof' '(' type-id ')'
Chris Lattner4b009652007-07-25 00:24:17 +0000793Parser::ExprResult Parser::ParseSizeofAlignofExpression() {
Douglas Gregor658b4442008-11-06 15:17:27 +0000794 assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof)
795 || Tok.is(tok::kw_alignof)) &&
Chris Lattner4b009652007-07-25 00:24:17 +0000796 "Not a sizeof/alignof expression!");
797 Token OpTok = Tok;
798 ConsumeToken();
799
800 // If the operand doesn't start with an '(', it must be an expression.
801 ExprResult Operand;
Chris Lattner4d7d2342007-10-09 17:41:39 +0000802 if (Tok.isNot(tok::l_paren)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000803 Operand = ParseCastExpression(true);
804 } else {
805 // If it starts with a '(', we know that it is either a parenthesized
806 // type-name, or it is a unary-expression that starts with a compound
807 // literal, or starts with a primary-expression that is a parenthesized
808 // expression.
809 ParenParseOption ExprType = CastExpr;
810 TypeTy *CastTy;
811 SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
812 Operand = ParseParenExpression(ExprType, CastTy, RParenLoc);
813
814 // If ParseParenExpression parsed a '(typename)' sequence only, the this is
815 // sizeof/alignof a type. Otherwise, it is sizeof/alignof an expression.
Chris Lattner48553562007-11-13 20:50:37 +0000816 if (ExprType == CastExpr)
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000817 return Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
818 OpTok.is(tok::kw_sizeof),
819 /*isType=*/true, CastTy,
820 SourceRange(LParenLoc, RParenLoc));
Chris Lattner48553562007-11-13 20:50:37 +0000821
822 // If this is a parenthesized expression, it is the start of a
823 // unary-expression, but doesn't include any postfix pieces. Parse these
824 // now if present.
825 Operand = ParsePostfixExpressionSuffix(Operand);
Chris Lattner4b009652007-07-25 00:24:17 +0000826 }
827
828 // If we get here, the operand to the sizeof/alignof was an expresion.
829 if (!Operand.isInvalid)
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000830 Operand = Actions.ActOnSizeOfAlignOfExpr(OpTok.getLocation(),
831 OpTok.is(tok::kw_sizeof),
832 /*isType=*/false, Operand.Val,
833 SourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000834 return Operand;
835}
836
837/// ParseBuiltinPrimaryExpression
838///
839/// primary-expression: [C99 6.5.1]
840/// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
841/// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
842/// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
843/// assign-expr ')'
844/// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000845/// [CLANG] '__builtin_overload' '(' expr (',' expr)* ')'
Chris Lattner4b009652007-07-25 00:24:17 +0000846///
847/// [GNU] offsetof-member-designator:
848/// [GNU] identifier
849/// [GNU] offsetof-member-designator '.' identifier
850/// [GNU] offsetof-member-designator '[' expression ']'
851///
852Parser::ExprResult Parser::ParseBuiltinPrimaryExpression() {
853 ExprResult Res(false);
854 const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
855
856 tok::TokenKind T = Tok.getKind();
857 SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
858
859 // All of these start with an open paren.
Chris Lattner4d7d2342007-10-09 17:41:39 +0000860 if (Tok.isNot(tok::l_paren)) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000861 Diag(Tok, diag::err_expected_lparen_after_id) << BuiltinII;
Chris Lattner4b009652007-07-25 00:24:17 +0000862 return ExprResult(true);
863 }
864
865 SourceLocation LParenLoc = ConsumeParen();
866 // TODO: Build AST.
867
868 switch (T) {
869 default: assert(0 && "Not a builtin primary expression!");
Anders Carlsson36760332007-10-15 20:28:48 +0000870 case tok::kw___builtin_va_arg: {
871 ExprResult Expr = ParseAssignmentExpression();
Sebastian Redl6008ac32008-11-25 22:21:31 +0000872 ExprGuard ExprGuard(Actions, Expr);
Anders Carlsson36760332007-10-15 20:28:48 +0000873 if (Expr.isInvalid) {
Chris Lattner4b009652007-07-25 00:24:17 +0000874 SkipUntil(tok::r_paren);
Eli Friedmana1b6d802008-08-20 22:07:34 +0000875 return ExprResult(true);
Chris Lattner4b009652007-07-25 00:24:17 +0000876 }
877
878 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
879 return ExprResult(true);
880
Anders Carlsson36760332007-10-15 20:28:48 +0000881 TypeTy *Ty = ParseTypeName();
Chris Lattnercb8943a2007-08-30 15:52:49 +0000882
Anders Carlsson36760332007-10-15 20:28:48 +0000883 if (Tok.isNot(tok::r_paren)) {
884 Diag(Tok, diag::err_expected_rparen);
885 return ExprResult(true);
886 }
Sebastian Redl6008ac32008-11-25 22:21:31 +0000887 Res = Actions.ActOnVAArg(StartLoc, ExprGuard.take(), Ty, ConsumeParen());
Chris Lattner4b009652007-07-25 00:24:17 +0000888 break;
Anders Carlsson36760332007-10-15 20:28:48 +0000889 }
Chris Lattner69638b12007-08-30 15:51:11 +0000890 case tok::kw___builtin_offsetof: {
Chris Lattner1b6b5be2007-08-30 17:08:45 +0000891 SourceLocation TypeLoc = Tok.getLocation();
Chris Lattner69638b12007-08-30 15:51:11 +0000892 TypeTy *Ty = ParseTypeName();
Chris Lattner4b009652007-07-25 00:24:17 +0000893
894 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
895 return ExprResult(true);
896
897 // We must have at least one identifier here.
Chris Lattner4d7d2342007-10-09 17:41:39 +0000898 if (Tok.isNot(tok::identifier)) {
Chris Lattner69638b12007-08-30 15:51:11 +0000899 Diag(Tok, diag::err_expected_ident);
900 SkipUntil(tok::r_paren);
901 return true;
902 }
903
904 // Keep track of the various subcomponents we see.
905 llvm::SmallVector<Action::OffsetOfComponent, 4> Comps;
906
907 Comps.push_back(Action::OffsetOfComponent());
908 Comps.back().isBrackets = false;
909 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
910 Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
Chris Lattner4b009652007-07-25 00:24:17 +0000911
Sebastian Redl6008ac32008-11-25 22:21:31 +0000912 // FIXME: This loop leaks the index expressions on error.
Chris Lattner4b009652007-07-25 00:24:17 +0000913 while (1) {
Chris Lattner4d7d2342007-10-09 17:41:39 +0000914 if (Tok.is(tok::period)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000915 // offsetof-member-designator: offsetof-member-designator '.' identifier
Chris Lattner69638b12007-08-30 15:51:11 +0000916 Comps.push_back(Action::OffsetOfComponent());
917 Comps.back().isBrackets = false;
918 Comps.back().LocStart = ConsumeToken();
Chris Lattner4b009652007-07-25 00:24:17 +0000919
Chris Lattner4d7d2342007-10-09 17:41:39 +0000920 if (Tok.isNot(tok::identifier)) {
Chris Lattner69638b12007-08-30 15:51:11 +0000921 Diag(Tok, diag::err_expected_ident);
922 SkipUntil(tok::r_paren);
923 return true;
924 }
925 Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
926 Comps.back().LocEnd = ConsumeToken();
927
Chris Lattner4d7d2342007-10-09 17:41:39 +0000928 } else if (Tok.is(tok::l_square)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000929 // offsetof-member-designator: offsetof-member-design '[' expression ']'
Chris Lattner69638b12007-08-30 15:51:11 +0000930 Comps.push_back(Action::OffsetOfComponent());
931 Comps.back().isBrackets = true;
932 Comps.back().LocStart = ConsumeBracket();
Chris Lattner4b009652007-07-25 00:24:17 +0000933 Res = ParseExpression();
934 if (Res.isInvalid) {
935 SkipUntil(tok::r_paren);
936 return Res;
937 }
Chris Lattner69638b12007-08-30 15:51:11 +0000938 Comps.back().U.E = Res.Val;
Chris Lattner4b009652007-07-25 00:24:17 +0000939
Chris Lattner69638b12007-08-30 15:51:11 +0000940 Comps.back().LocEnd =
941 MatchRHSPunctuation(tok::r_square, Comps.back().LocStart);
Chris Lattner4d7d2342007-10-09 17:41:39 +0000942 } else if (Tok.is(tok::r_paren)) {
Steve Naroff5cbb02f2007-09-16 14:56:35 +0000943 Res = Actions.ActOnBuiltinOffsetOf(StartLoc, TypeLoc, Ty, &Comps[0],
Chris Lattnercb8943a2007-08-30 15:52:49 +0000944 Comps.size(), ConsumeParen());
945 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000946 } else {
Chris Lattner69638b12007-08-30 15:51:11 +0000947 // Error occurred.
948 return ExprResult(true);
Chris Lattner4b009652007-07-25 00:24:17 +0000949 }
950 }
951 break;
Chris Lattner69638b12007-08-30 15:51:11 +0000952 }
Steve Naroff93c53012007-08-03 21:21:27 +0000953 case tok::kw___builtin_choose_expr: {
954 ExprResult Cond = ParseAssignmentExpression();
Sebastian Redl6008ac32008-11-25 22:21:31 +0000955 ExprGuard CondGuard(Actions, Cond);
Steve Naroff93c53012007-08-03 21:21:27 +0000956 if (Cond.isInvalid) {
957 SkipUntil(tok::r_paren);
958 return Cond;
959 }
Chris Lattner4b009652007-07-25 00:24:17 +0000960 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
961 return ExprResult(true);
962
Steve Naroff93c53012007-08-03 21:21:27 +0000963 ExprResult Expr1 = ParseAssignmentExpression();
Sebastian Redl6008ac32008-11-25 22:21:31 +0000964 ExprGuard Guard1(Actions, Expr1);
Steve Naroff93c53012007-08-03 21:21:27 +0000965 if (Expr1.isInvalid) {
966 SkipUntil(tok::r_paren);
967 return Expr1;
968 }
Chris Lattner4b009652007-07-25 00:24:17 +0000969 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
970 return ExprResult(true);
971
Steve Naroff93c53012007-08-03 21:21:27 +0000972 ExprResult Expr2 = ParseAssignmentExpression();
Sebastian Redl6008ac32008-11-25 22:21:31 +0000973 ExprGuard Guard2(Actions, Expr2);
Steve Naroff93c53012007-08-03 21:21:27 +0000974 if (Expr2.isInvalid) {
975 SkipUntil(tok::r_paren);
976 return Expr2;
977 }
Chris Lattner4d7d2342007-10-09 17:41:39 +0000978 if (Tok.isNot(tok::r_paren)) {
Steve Naroff93c53012007-08-03 21:21:27 +0000979 Diag(Tok, diag::err_expected_rparen);
980 return ExprResult(true);
981 }
Sebastian Redl6008ac32008-11-25 22:21:31 +0000982 Res = Actions.ActOnChooseExpr(StartLoc, CondGuard.take(), Guard1.take(),
983 Guard2.take(), ConsumeParen());
Chris Lattnercb8943a2007-08-30 15:52:49 +0000984 break;
Steve Naroff93c53012007-08-03 21:21:27 +0000985 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000986 case tok::kw___builtin_overload: {
Sebastian Redl6008ac32008-11-25 22:21:31 +0000987 ExprVector ArgExprs(Actions);
Nate Begeman9f3bfb72008-01-17 17:46:27 +0000988 llvm::SmallVector<SourceLocation, 8> CommaLocs;
989
990 // For each iteration through the loop look for assign-expr followed by a
991 // comma. If there is no comma, break and attempt to match r-paren.
992 if (Tok.isNot(tok::r_paren)) {
993 while (1) {
994 ExprResult ArgExpr = ParseAssignmentExpression();
995 if (ArgExpr.isInvalid) {
996 SkipUntil(tok::r_paren);
997 return ExprResult(true);
998 } else
999 ArgExprs.push_back(ArgExpr.Val);
1000
1001 if (Tok.isNot(tok::comma))
1002 break;
1003 // Move to the next argument, remember where the comma was.
1004 CommaLocs.push_back(ConsumeToken());
1005 }
1006 }
1007
1008 // Attempt to consume the r-paren
1009 if (Tok.isNot(tok::r_paren)) {
1010 Diag(Tok, diag::err_expected_rparen);
1011 SkipUntil(tok::r_paren);
1012 return ExprResult(true);
1013 }
Sebastian Redl6008ac32008-11-25 22:21:31 +00001014 Res = Actions.ActOnOverloadExpr(ArgExprs.take(), ArgExprs.size(),
Nate Begeman9f3bfb72008-01-17 17:46:27 +00001015 &CommaLocs[0], StartLoc, ConsumeParen());
1016 break;
1017 }
Chris Lattner4b009652007-07-25 00:24:17 +00001018 case tok::kw___builtin_types_compatible_p:
Steve Naroff5b528922007-08-01 23:45:51 +00001019 TypeTy *Ty1 = ParseTypeName();
Chris Lattner4b009652007-07-25 00:24:17 +00001020
1021 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1022 return ExprResult(true);
1023
Steve Naroff5b528922007-08-01 23:45:51 +00001024 TypeTy *Ty2 = ParseTypeName();
1025
Chris Lattner4d7d2342007-10-09 17:41:39 +00001026 if (Tok.isNot(tok::r_paren)) {
Steve Naroff5b528922007-08-01 23:45:51 +00001027 Diag(Tok, diag::err_expected_rparen);
1028 return ExprResult(true);
1029 }
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001030 Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1, Ty2, ConsumeParen());
Chris Lattnercb8943a2007-08-30 15:52:49 +00001031 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001032 }
1033
Chris Lattner4b009652007-07-25 00:24:17 +00001034 // These can be followed by postfix-expr pieces because they are
1035 // primary-expressions.
1036 return ParsePostfixExpressionSuffix(Res);
1037}
1038
1039/// ParseParenExpression - This parses the unit that starts with a '(' token,
1040/// based on what is allowed by ExprType. The actual thing parsed is returned
1041/// in ExprType.
1042///
1043/// primary-expression: [C99 6.5.1]
1044/// '(' expression ')'
1045/// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
1046/// postfix-expression: [C99 6.5.2]
1047/// '(' type-name ')' '{' initializer-list '}'
1048/// '(' type-name ')' '{' initializer-list ',' '}'
1049/// cast-expression: [C99 6.5.4]
1050/// '(' type-name ')' cast-expression
1051///
1052Parser::ExprResult Parser::ParseParenExpression(ParenParseOption &ExprType,
1053 TypeTy *&CastTy,
1054 SourceLocation &RParenLoc) {
Chris Lattner4d7d2342007-10-09 17:41:39 +00001055 assert(Tok.is(tok::l_paren) && "Not a paren expr!");
Chris Lattner4b009652007-07-25 00:24:17 +00001056 SourceLocation OpenLoc = ConsumeParen();
1057 ExprResult Result(true);
1058 CastTy = 0;
1059
Chris Lattner4d7d2342007-10-09 17:41:39 +00001060 if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001061 Diag(Tok, diag::ext_gnu_statement_expr);
Chris Lattnerf2b07572007-08-31 21:49:55 +00001062 Parser::StmtResult Stmt = ParseCompoundStatement(true);
Chris Lattner4b009652007-07-25 00:24:17 +00001063 ExprType = CompoundStmt;
1064
1065 // If the substmt parsed correctly, build the AST node.
Chris Lattner4d7d2342007-10-09 17:41:39 +00001066 if (!Stmt.isInvalid && Tok.is(tok::r_paren))
Steve Naroff5cbb02f2007-09-16 14:56:35 +00001067 Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.Val, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001068
Argiris Kirtzidis3276cbc2008-10-05 19:56:22 +00001069 } else if (ExprType >= CompoundLiteral && isTypeIdInParens()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001070 // Otherwise, this is a compound literal expression or cast expression.
1071 TypeTy *Ty = ParseTypeName();
1072
1073 // Match the ')'.
Chris Lattner4d7d2342007-10-09 17:41:39 +00001074 if (Tok.is(tok::r_paren))
Chris Lattner4b009652007-07-25 00:24:17 +00001075 RParenLoc = ConsumeParen();
1076 else
1077 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1078
Chris Lattner4d7d2342007-10-09 17:41:39 +00001079 if (Tok.is(tok::l_brace)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001080 if (!getLang().C99) // Compound literals don't exist in C90.
1081 Diag(OpenLoc, diag::ext_c99_compound_literal);
1082 Result = ParseInitializer();
1083 ExprType = CompoundLiteral;
1084 if (!Result.isInvalid)
Steve Naroff87d58b42007-09-16 03:34:24 +00001085 return Actions.ActOnCompoundLiteral(OpenLoc, Ty, RParenLoc, Result.Val);
Chris Lattner4b009652007-07-25 00:24:17 +00001086 } else if (ExprType == CastExpr) {
1087 // Note that this doesn't parse the subsequence cast-expression, it just
1088 // returns the parsed type to the callee.
1089 ExprType = CastExpr;
1090 CastTy = Ty;
1091 return ExprResult(false);
1092 } else {
1093 Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
1094 return ExprResult(true);
1095 }
1096 return Result;
1097 } else {
1098 Result = ParseExpression();
1099 ExprType = SimpleExpr;
Chris Lattner4d7d2342007-10-09 17:41:39 +00001100 if (!Result.isInvalid && Tok.is(tok::r_paren))
Steve Naroff87d58b42007-09-16 03:34:24 +00001101 Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.Val);
Chris Lattner4b009652007-07-25 00:24:17 +00001102 }
1103
1104 // Match the ')'.
1105 if (Result.isInvalid)
1106 SkipUntil(tok::r_paren);
1107 else {
Chris Lattner4d7d2342007-10-09 17:41:39 +00001108 if (Tok.is(tok::r_paren))
Chris Lattner4b009652007-07-25 00:24:17 +00001109 RParenLoc = ConsumeParen();
1110 else
1111 MatchRHSPunctuation(tok::r_paren, OpenLoc);
1112 }
1113
1114 return Result;
1115}
1116
1117/// ParseStringLiteralExpression - This handles the various token types that
1118/// form string literals, and also handles string concatenation [C99 5.1.1.2,
1119/// translation phase #6].
1120///
1121/// primary-expression: [C99 6.5.1]
1122/// string-literal
1123Parser::ExprResult Parser::ParseStringLiteralExpression() {
1124 assert(isTokenStringLiteral() && "Not a string literal!");
1125
1126 // String concat. Note that keywords like __func__ and __FUNCTION__ are not
1127 // considered to be strings for concatenation purposes.
1128 llvm::SmallVector<Token, 4> StringToks;
1129
1130 do {
1131 StringToks.push_back(Tok);
1132 ConsumeStringToken();
1133 } while (isTokenStringLiteral());
1134
1135 // Pass the set of string tokens, ready for concatenation, to the actions.
Steve Naroff87d58b42007-09-16 03:34:24 +00001136 return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size());
Chris Lattner4b009652007-07-25 00:24:17 +00001137}
Argiris Kirtzidis83dce112008-08-16 20:03:01 +00001138
1139/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
1140///
1141/// argument-expression-list:
1142/// assignment-expression
1143/// argument-expression-list , assignment-expression
1144///
1145/// [C++] expression-list:
1146/// [C++] assignment-expression
1147/// [C++] expression-list , assignment-expression
1148///
1149bool Parser::ParseExpressionList(ExprListTy &Exprs, CommaLocsTy &CommaLocs) {
1150 while (1) {
1151 ExprResult Expr = ParseAssignmentExpression();
1152 if (Expr.isInvalid)
1153 return true;
Argiris Kirtzidisd37a4182008-08-18 22:49:40 +00001154
1155 Exprs.push_back(Expr.Val);
Argiris Kirtzidis83dce112008-08-16 20:03:01 +00001156
1157 if (Tok.isNot(tok::comma))
1158 return false;
1159 // Move to the next argument, remember where the comma was.
1160 CommaLocs.push_back(ConsumeToken());
1161 }
1162}
Steve Narofffd5b19d2008-08-28 19:20:44 +00001163
1164/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
Steve Naroffa095a752008-09-16 23:11:46 +00001165/// like ^(int x){ return x+1; }
Steve Narofffd5b19d2008-08-28 19:20:44 +00001166///
1167/// block-literal:
1168/// [clang] '^' block-args[opt] compound-statement
Steve Narofffd5b19d2008-08-28 19:20:44 +00001169/// [clang] block-args:
1170/// [clang] '(' parameter-list ')'
1171///
1172Parser::ExprResult Parser::ParseBlockLiteralExpression() {
1173 assert(Tok.is(tok::caret) && "block literal starts with ^");
1174 SourceLocation CaretLoc = ConsumeToken();
1175
1176 // Enter a scope to hold everything within the block. This includes the
1177 // argument decls, decls within the compound expression, etc. This also
1178 // allows determining whether a variable reference inside the block is
1179 // within or outside of the block.
1180 EnterScope(Scope::BlockScope|Scope::FnScope|Scope::BreakScope|
1181 Scope::ContinueScope|Scope::DeclScope);
Steve Naroff52059382008-10-10 01:28:17 +00001182
1183 // Inform sema that we are starting a block.
1184 Actions.ActOnBlockStart(CaretLoc, CurScope);
Steve Narofffd5b19d2008-08-28 19:20:44 +00001185
1186 // Parse the return type if present.
1187 DeclSpec DS;
1188 Declarator ParamInfo(DS, Declarator::PrototypeContext);
1189
1190 // If this block has arguments, parse them. There is no ambiguity here with
1191 // the expression case, because the expression case requires a parameter list.
1192 if (Tok.is(tok::l_paren)) {
1193 ParseParenDeclarator(ParamInfo);
1194 // Parse the pieces after the identifier as if we had "int(...)".
1195 ParamInfo.SetIdentifier(0, CaretLoc);
1196 if (ParamInfo.getInvalidType()) {
1197 // If there was an error parsing the arguments, they may have tried to use
1198 // ^(x+y) which requires an argument list. Just skip the whole block
1199 // literal.
1200 ExitScope();
1201 return true;
1202 }
1203 } else {
1204 // Otherwise, pretend we saw (void).
1205 ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(true, false,
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001206 0, 0, 0, CaretLoc));
Steve Narofffd5b19d2008-08-28 19:20:44 +00001207 }
1208
1209 // Inform sema that we are starting a block.
Steve Naroff52059382008-10-10 01:28:17 +00001210 Actions.ActOnBlockArguments(ParamInfo);
Steve Narofffd5b19d2008-08-28 19:20:44 +00001211
Steve Naroffa095a752008-09-16 23:11:46 +00001212 ExprResult Result = true;
Steve Narofffd5b19d2008-08-28 19:20:44 +00001213 if (Tok.is(tok::l_brace)) {
1214 StmtResult Stmt = ParseCompoundStatementBody();
1215 if (!Stmt.isInvalid) {
1216 Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.Val, CurScope);
1217 } else {
1218 Actions.ActOnBlockError(CaretLoc, CurScope);
Steve Narofffd5b19d2008-08-28 19:20:44 +00001219 }
1220 }
Steve Narofffd5b19d2008-08-28 19:20:44 +00001221 ExitScope();
1222 return Result;
1223}
1224