]> granicus.if.org Git - clang/blob - Parse/ParseExpr.cpp
add parsing, ast building and pretty printing support for C++ throw expressions.
[clang] / Parse / ParseExpr.cpp
1 //===--- ParseExpr.cpp - Expression Parsing -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Expression parsing implementation.  Expressions in
11 // C99 basically consist of a bunch of binary operators with unary operators and
12 // other random stuff at the leaves.
13 //
14 // In the C99 grammar, these unary operators bind tightest and are represented
15 // as the 'cast-expression' production.  Everything else is either a binary
16 // operator (e.g. '/') or a ternary operator ("?:").  The unary leaves are
17 // handled by ParseCastExpression, the higher level pieces are handled by
18 // ParseBinaryExpression.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "clang/Parse/Parser.h"
23 #include "clang/Basic/Diagnostic.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/SmallString.h"
26 using namespace clang;
27
28 /// PrecedenceLevels - These are precedences for the binary/ternary operators in
29 /// the C99 grammar.  These have been named to relate with the C99 grammar
30 /// productions.  Low precedences numbers bind more weakly than high numbers.
31 namespace prec {
32   enum Level {
33     Unknown        = 0,    // Not binary operator.
34     Comma          = 1,    // ,
35     Assignment     = 2,    // =, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=
36     Conditional    = 3,    // ?
37     LogicalOr      = 4,    // ||
38     LogicalAnd     = 5,    // &&
39     InclusiveOr    = 6,    // |
40     ExclusiveOr    = 7,    // ^
41     And            = 8,    // &
42     Equality       = 9,    // ==, !=
43     Relational     = 10,   //  >=, <=, >, <
44     Shift          = 11,   // <<, >>
45     Additive       = 12,   // -, +
46     Multiplicative = 13    // *, /, %
47   };
48 }
49
50
51 /// getBinOpPrecedence - Return the precedence of the specified binary operator
52 /// token.  This returns:
53 ///
54 static prec::Level getBinOpPrecedence(tok::TokenKind Kind) {
55   switch (Kind) {
56   default:                        return prec::Unknown;
57   case tok::comma:                return prec::Comma;
58   case tok::equal:
59   case tok::starequal:
60   case tok::slashequal:
61   case tok::percentequal:
62   case tok::plusequal:
63   case tok::minusequal:
64   case tok::lesslessequal:
65   case tok::greatergreaterequal:
66   case tok::ampequal:
67   case tok::caretequal:
68   case tok::pipeequal:            return prec::Assignment;
69   case tok::question:             return prec::Conditional;
70   case tok::pipepipe:             return prec::LogicalOr;
71   case tok::ampamp:               return prec::LogicalAnd;
72   case tok::pipe:                 return prec::InclusiveOr;
73   case tok::caret:                return prec::ExclusiveOr;
74   case tok::amp:                  return prec::And;
75   case tok::exclaimequal:
76   case tok::equalequal:           return prec::Equality;
77   case tok::lessequal:
78   case tok::less:
79   case tok::greaterequal:
80   case tok::greater:              return prec::Relational;
81   case tok::lessless:
82   case tok::greatergreater:       return prec::Shift;
83   case tok::plus:
84   case tok::minus:                return prec::Additive;
85   case tok::percent:
86   case tok::slash:
87   case tok::star:                 return prec::Multiplicative;
88   }
89 }
90
91
92 /// ParseExpression - Simple precedence-based parser for binary/ternary
93 /// operators.
94 ///
95 /// Note: we diverge from the C99 grammar when parsing the assignment-expression
96 /// production.  C99 specifies that the LHS of an assignment operator should be
97 /// parsed as a unary-expression, but consistency dictates that it be a
98 /// conditional-expession.  In practice, the important thing here is that the
99 /// LHS of an assignment has to be an l-value, which productions between
100 /// unary-expression and conditional-expression don't produce.  Because we want
101 /// consistency, we parse the LHS as a conditional-expression, then check for
102 /// l-value-ness in semantic analysis stages.
103 ///
104 ///       multiplicative-expression: [C99 6.5.5]
105 ///         cast-expression
106 ///         multiplicative-expression '*' cast-expression
107 ///         multiplicative-expression '/' cast-expression
108 ///         multiplicative-expression '%' cast-expression
109 ///
110 ///       additive-expression: [C99 6.5.6]
111 ///         multiplicative-expression
112 ///         additive-expression '+' multiplicative-expression
113 ///         additive-expression '-' multiplicative-expression
114 ///
115 ///       shift-expression: [C99 6.5.7]
116 ///         additive-expression
117 ///         shift-expression '<<' additive-expression
118 ///         shift-expression '>>' additive-expression
119 ///
120 ///       relational-expression: [C99 6.5.8]
121 ///         shift-expression
122 ///         relational-expression '<' shift-expression
123 ///         relational-expression '>' shift-expression
124 ///         relational-expression '<=' shift-expression
125 ///         relational-expression '>=' shift-expression
126 ///
127 ///       equality-expression: [C99 6.5.9]
128 ///         relational-expression
129 ///         equality-expression '==' relational-expression
130 ///         equality-expression '!=' relational-expression
131 ///
132 ///       AND-expression: [C99 6.5.10]
133 ///         equality-expression
134 ///         AND-expression '&' equality-expression
135 ///
136 ///       exclusive-OR-expression: [C99 6.5.11]
137 ///         AND-expression
138 ///         exclusive-OR-expression '^' AND-expression
139 ///
140 ///       inclusive-OR-expression: [C99 6.5.12]
141 ///         exclusive-OR-expression
142 ///         inclusive-OR-expression '|' exclusive-OR-expression
143 ///
144 ///       logical-AND-expression: [C99 6.5.13]
145 ///         inclusive-OR-expression
146 ///         logical-AND-expression '&&' inclusive-OR-expression
147 ///
148 ///       logical-OR-expression: [C99 6.5.14]
149 ///         logical-AND-expression
150 ///         logical-OR-expression '||' logical-AND-expression
151 ///
152 ///       conditional-expression: [C99 6.5.15]
153 ///         logical-OR-expression
154 ///         logical-OR-expression '?' expression ':' conditional-expression
155 /// [GNU]   logical-OR-expression '?' ':' conditional-expression
156 ///
157 ///       assignment-expression: [C99 6.5.16]
158 ///         conditional-expression
159 ///         unary-expression assignment-operator assignment-expression
160 /// [C++]   throw-expression [C++ 15]
161 ///
162 ///       assignment-operator: one of
163 ///         = *= /= %= += -= <<= >>= &= ^= |=
164 ///
165 ///       expression: [C99 6.5.17]
166 ///         assignment-expression
167 ///         expression ',' assignment-expression
168 ///
169 Parser::ExprResult Parser::ParseExpression() {
170   if (Tok.is(tok::kw_throw))
171     return ParseThrowExpression();
172
173   ExprResult LHS = ParseCastExpression(false);
174   if (LHS.isInvalid) return LHS;
175   
176   return ParseRHSOfBinaryExpression(LHS, prec::Comma);
177 }
178
179 /// This routine is called when the '@' is seen and consumed. 
180 /// Current token is an Identifier and is not a 'try'. This
181 /// routine is necessary to disambiguate @try-statement from,
182 /// for example, @encode-expression.
183 ///
184 Parser::ExprResult Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
185   ExprResult LHS = ParseObjCAtExpression(AtLoc);
186   if (LHS.isInvalid) return LHS;
187  
188   return ParseRHSOfBinaryExpression(LHS, prec::Comma);
189 }
190
191 /// ParseAssignmentExpression - Parse an expr that doesn't include commas.
192 ///
193 Parser::ExprResult Parser::ParseAssignmentExpression() {
194   if (Tok.is(tok::kw_throw))
195     return ParseThrowExpression();
196
197   ExprResult LHS = ParseCastExpression(false);
198   if (LHS.isInvalid) return LHS;
199   
200   return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
201 }
202
203 Parser::ExprResult Parser::ParseConstantExpression() {
204   ExprResult LHS = ParseCastExpression(false);
205   if (LHS.isInvalid) return LHS;
206   
207   return ParseRHSOfBinaryExpression(LHS, prec::Conditional);
208 }
209
210 /// ParseExpressionWithLeadingIdentifier - This special purpose method is used
211 /// in contexts where we have already consumed an identifier (which we saved in
212 /// 'IdTok'), then discovered that the identifier was really the leading token
213 /// of part of an expression.  For example, in "A[1]+B", we consumed "A" (which
214 /// is now in 'IdTok') and the current token is "[".
215 Parser::ExprResult Parser::
216 ParseExpressionWithLeadingIdentifier(const Token &IdTok) {
217   // We know that 'IdTok' must correspond to this production:
218   //   primary-expression: identifier
219   
220   // Let the actions module handle the identifier.
221   ExprResult Res = Actions.ActOnIdentifierExpr(CurScope, IdTok.getLocation(),
222                                                *IdTok.getIdentifierInfo(),
223                                                Tok.is(tok::l_paren));
224   
225   // Because we have to parse an entire cast-expression before starting the
226   // ParseRHSOfBinaryExpression method (which parses any trailing binops), we
227   // need to handle the 'postfix-expression' rules.  We do this by invoking
228   // ParsePostfixExpressionSuffix to consume any postfix-expression suffixes:
229   Res = ParsePostfixExpressionSuffix(Res);
230   if (Res.isInvalid) return Res;
231
232   // At this point, the "A[1]" part of "A[1]+B" has been consumed. Once this is
233   // done, we know we don't have to do anything for cast-expression, because the
234   // only non-postfix-expression production starts with a '(' token, and we know
235   // we have an identifier.  As such, we can invoke ParseRHSOfBinaryExpression
236   // to consume any trailing operators (e.g. "+" in this example) and connected
237   // chunks of the expression.
238   return ParseRHSOfBinaryExpression(Res, prec::Comma);
239 }
240
241 /// ParseExpressionWithLeadingIdentifier - This special purpose method is used
242 /// in contexts where we have already consumed an identifier (which we saved in
243 /// 'IdTok'), then discovered that the identifier was really the leading token
244 /// of part of an assignment-expression.  For example, in "A[1]+B", we consumed
245 /// "A" (which is now in 'IdTok') and the current token is "[".
246 Parser::ExprResult Parser::
247 ParseAssignmentExprWithLeadingIdentifier(const Token &IdTok) {
248   // We know that 'IdTok' must correspond to this production:
249   //   primary-expression: identifier
250   
251   // Let the actions module handle the identifier.
252   ExprResult Res = Actions.ActOnIdentifierExpr(CurScope, IdTok.getLocation(),
253                                                *IdTok.getIdentifierInfo(),
254                                                Tok.is(tok::l_paren));
255   
256   // Because we have to parse an entire cast-expression before starting the
257   // ParseRHSOfBinaryExpression method (which parses any trailing binops), we
258   // need to handle the 'postfix-expression' rules.  We do this by invoking
259   // ParsePostfixExpressionSuffix to consume any postfix-expression suffixes:
260   Res = ParsePostfixExpressionSuffix(Res);
261   if (Res.isInvalid) return Res;
262   
263   // At this point, the "A[1]" part of "A[1]+B" has been consumed. Once this is
264   // done, we know we don't have to do anything for cast-expression, because the
265   // only non-postfix-expression production starts with a '(' token, and we know
266   // we have an identifier.  As such, we can invoke ParseRHSOfBinaryExpression
267   // to consume any trailing operators (e.g. "+" in this example) and connected
268   // chunks of the expression.
269   return ParseRHSOfBinaryExpression(Res, prec::Assignment);
270 }
271
272
273 /// ParseAssignmentExpressionWithLeadingStar - This special purpose method is
274 /// used in contexts where we have already consumed a '*' (which we saved in
275 /// 'StarTok'), then discovered that the '*' was really the leading token of an
276 /// expression.  For example, in "*(int*)P+B", we consumed "*" (which is
277 /// now in 'StarTok') and the current token is "(".
278 Parser::ExprResult Parser::
279 ParseAssignmentExpressionWithLeadingStar(const Token &StarTok) {
280   // We know that 'StarTok' must correspond to this production:
281   //  unary-expression: unary-operator cast-expression
282   // where 'unary-operator' is '*'.
283   
284   // Parse the cast-expression that follows the '*'.  This will parse the
285   // "*(int*)P" part of "*(int*)P+B".
286   ExprResult Res = ParseCastExpression(false);
287   if (Res.isInvalid) return Res;
288
289   // Combine StarTok + Res to get the new AST for the combined expression..
290   Res = Actions.ActOnUnaryOp(StarTok.getLocation(), tok::star, Res.Val);
291   if (Res.isInvalid) return Res;
292   
293   
294   // We have to parse an entire cast-expression before starting the
295   // ParseRHSOfBinaryExpression method (which parses any trailing binops). Since
296   // we know that the only production above us is the cast-expression
297   // production, and because the only alternative productions start with a '('
298   // token (we know we had a '*'), there is no work to do to get a whole
299   // cast-expression.
300   
301   // At this point, the "*(int*)P" part of "*(int*)P+B" has been consumed. Once
302   // this is done, we can invoke ParseRHSOfBinaryExpression to consume any
303   // trailing operators (e.g. "+" in this example) and connected chunks of the
304   // assignment-expression.
305   return ParseRHSOfBinaryExpression(Res, prec::Assignment);
306 }
307
308
309 /// ParseRHSOfBinaryExpression - Parse a binary expression that starts with
310 /// LHS and has a precedence of at least MinPrec.
311 Parser::ExprResult
312 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, unsigned MinPrec) {
313   unsigned NextTokPrec = getBinOpPrecedence(Tok.getKind());
314   SourceLocation ColonLoc;
315
316   while (1) {
317     // If this token has a lower precedence than we are allowed to parse (e.g.
318     // because we are called recursively, or because the token is not a binop),
319     // then we are done!
320     if (NextTokPrec < MinPrec)
321       return LHS;
322
323     // Consume the operator, saving the operator token for error reporting.
324     Token OpToken = Tok;
325     ConsumeToken();
326     
327     // Special case handling for the ternary operator.
328     ExprResult TernaryMiddle(true);
329     if (NextTokPrec == prec::Conditional) {
330       if (Tok.isNot(tok::colon)) {
331         // Handle this production specially:
332         //   logical-OR-expression '?' expression ':' conditional-expression
333         // In particular, the RHS of the '?' is 'expression', not
334         // 'logical-OR-expression' as we might expect.
335         TernaryMiddle = ParseExpression();
336         if (TernaryMiddle.isInvalid) {
337           Actions.DeleteExpr(LHS.Val);
338           return TernaryMiddle;
339         }
340       } else {
341         // Special case handling of "X ? Y : Z" where Y is empty:
342         //   logical-OR-expression '?' ':' conditional-expression   [GNU]
343         TernaryMiddle = ExprResult(false);
344         Diag(Tok, diag::ext_gnu_conditional_expr);
345       }
346       
347       if (Tok.isNot(tok::colon)) {
348         Diag(Tok, diag::err_expected_colon);
349         Diag(OpToken, diag::err_matching, "?");
350         Actions.DeleteExpr(LHS.Val);
351         Actions.DeleteExpr(TernaryMiddle.Val);
352         return ExprResult(true);
353       }
354       
355       // Eat the colon.
356       ColonLoc = ConsumeToken();
357     }
358     
359     // Parse another leaf here for the RHS of the operator.
360     ExprResult RHS = ParseCastExpression(false);
361     if (RHS.isInvalid) {
362       Actions.DeleteExpr(LHS.Val);
363       Actions.DeleteExpr(TernaryMiddle.Val);
364       return RHS;
365     }
366
367     // Remember the precedence of this operator and get the precedence of the
368     // operator immediately to the right of the RHS.
369     unsigned ThisPrec = NextTokPrec;
370     NextTokPrec = getBinOpPrecedence(Tok.getKind());
371
372     // Assignment and conditional expressions are right-associative.
373     bool isRightAssoc = ThisPrec == prec::Conditional ||
374                         ThisPrec == prec::Assignment;
375
376     // Get the precedence of the operator to the right of the RHS.  If it binds
377     // more tightly with RHS than we do, evaluate it completely first.
378     if (ThisPrec < NextTokPrec ||
379         (ThisPrec == NextTokPrec && isRightAssoc)) {
380       // If this is left-associative, only parse things on the RHS that bind
381       // more tightly than the current operator.  If it is left-associative, it
382       // is okay, to bind exactly as tightly.  For example, compile A=B=C=D as
383       // A=(B=(C=D)), where each paren is a level of recursion here.
384       RHS = ParseRHSOfBinaryExpression(RHS, ThisPrec + !isRightAssoc);
385       if (RHS.isInvalid) {
386         Actions.DeleteExpr(LHS.Val);
387         Actions.DeleteExpr(TernaryMiddle.Val);
388         return RHS;
389       }
390
391       NextTokPrec = getBinOpPrecedence(Tok.getKind());
392     }
393     assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
394   
395     if (!LHS.isInvalid) {
396       // Combine the LHS and RHS into the LHS (e.g. build AST).
397       if (TernaryMiddle.isInvalid)
398         LHS = Actions.ActOnBinOp(OpToken.getLocation(), OpToken.getKind(),
399                                  LHS.Val, RHS.Val);
400       else
401         LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
402                                          LHS.Val, TernaryMiddle.Val, RHS.Val);
403     } else {
404       // We had a semantic error on the LHS.  Just free the RHS and continue.
405       Actions.DeleteExpr(TernaryMiddle.Val);
406       Actions.DeleteExpr(RHS.Val);
407     }
408   }
409 }
410
411 /// ParseCastExpression - Parse a cast-expression, or, if isUnaryExpression is
412 /// true, parse a unary-expression.
413 ///
414 ///       cast-expression: [C99 6.5.4]
415 ///         unary-expression
416 ///         '(' type-name ')' cast-expression
417 ///
418 ///       unary-expression:  [C99 6.5.3]
419 ///         postfix-expression
420 ///         '++' unary-expression
421 ///         '--' unary-expression
422 ///         unary-operator cast-expression
423 ///         'sizeof' unary-expression
424 ///         'sizeof' '(' type-name ')'
425 /// [GNU]   '__alignof' unary-expression
426 /// [GNU]   '__alignof' '(' type-name ')'
427 /// [GNU]   '&&' identifier
428 ///
429 ///       unary-operator: one of
430 ///         '&'  '*'  '+'  '-'  '~'  '!'
431 /// [GNU]   '__extension__'  '__real'  '__imag'
432 ///
433 ///       primary-expression: [C99 6.5.1]
434 ///         identifier
435 ///         constant
436 ///         string-literal
437 /// [C++]   boolean-literal  [C++ 2.13.5]
438 ///         '(' expression ')'
439 ///         '__func__'        [C99 6.4.2.2]
440 /// [GNU]   '__FUNCTION__'
441 /// [GNU]   '__PRETTY_FUNCTION__'
442 /// [GNU]   '(' compound-statement ')'
443 /// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
444 /// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
445 /// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
446 ///                                     assign-expr ')'
447 /// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
448 /// [OBJC]  '[' objc-message-expr ']'    
449 /// [OBJC]  '@selector' '(' objc-selector-arg ')'
450 /// [OBJC]  '@protocol' '(' identifier ')'             
451 /// [OBJC]  '@encode' '(' type-name ')'                
452 /// [OBJC]  objc-string-literal
453 /// [C++]   'const_cast' '<' type-name '>' '(' expression ')'       [C++ 5.2p1]
454 /// [C++]   'dynamic_cast' '<' type-name '>' '(' expression ')'     [C++ 5.2p1]
455 /// [C++]   'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
456 /// [C++]   'static_cast' '<' type-name '>' '(' expression ')'      [C++ 5.2p1]
457 ///
458 ///       constant: [C99 6.4.4]
459 ///         integer-constant
460 ///         floating-constant
461 ///         enumeration-constant -> identifier
462 ///         character-constant
463 ///
464 Parser::ExprResult Parser::ParseCastExpression(bool isUnaryExpression) {
465   ExprResult Res;
466   tok::TokenKind SavedKind = Tok.getKind();
467   
468   // This handles all of cast-expression, unary-expression, postfix-expression,
469   // and primary-expression.  We handle them together like this for efficiency
470   // and to simplify handling of an expression starting with a '(' token: which
471   // may be one of a parenthesized expression, cast-expression, compound literal
472   // expression, or statement expression.
473   //
474   // If the parsed tokens consist of a primary-expression, the cases below
475   // call ParsePostfixExpressionSuffix to handle the postfix expression
476   // suffixes.  Cases that cannot be followed by postfix exprs should
477   // return without invoking ParsePostfixExpressionSuffix.
478   switch (SavedKind) {
479   case tok::l_paren: {
480     // If this expression is limited to being a unary-expression, the parent can
481     // not start a cast expression.
482     ParenParseOption ParenExprType =
483       isUnaryExpression ? CompoundLiteral : CastExpr;
484     TypeTy *CastTy;
485     SourceLocation LParenLoc = Tok.getLocation();
486     SourceLocation RParenLoc;
487     Res = ParseParenExpression(ParenExprType, CastTy, RParenLoc);
488     if (Res.isInvalid) return Res;
489     
490     switch (ParenExprType) {
491     case SimpleExpr:   break;    // Nothing else to do.
492     case CompoundStmt: break;  // Nothing else to do.
493     case CompoundLiteral:
494       // We parsed '(' type-name ')' '{' ... '}'.  If any suffixes of
495       // postfix-expression exist, parse them now.
496       break;
497     case CastExpr:
498       // We parsed '(' type-name ')' and the thing after it wasn't a '{'.  Parse
499       // the cast-expression that follows it next.
500       // TODO: For cast expression with CastTy.
501       Res = ParseCastExpression(false);
502       if (!Res.isInvalid)
503         Res = Actions.ActOnCastExpr(LParenLoc, CastTy, RParenLoc, Res.Val);
504       return Res;
505     }
506       
507     // These can be followed by postfix-expr pieces.
508     return ParsePostfixExpressionSuffix(Res);
509   }
510     
511     // primary-expression
512   case tok::numeric_constant:
513     // constant: integer-constant
514     // constant: floating-constant
515     
516     Res = Actions.ActOnNumericConstant(Tok);
517     ConsumeToken();
518     
519     // These can be followed by postfix-expr pieces.
520     return ParsePostfixExpressionSuffix(Res);
521
522   case tok::kw_true:
523   case tok::kw_false:
524     return ParseCXXBoolLiteral();
525
526   case tok::identifier: {      // primary-expression: identifier
527                                // constant: enumeration-constant
528     // Consume the identifier so that we can see if it is followed by a '('.
529     // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
530     // need to know whether or not this identifier is a function designator or
531     // not.
532     IdentifierInfo &II = *Tok.getIdentifierInfo();
533     SourceLocation L = ConsumeToken();
534     Res = Actions.ActOnIdentifierExpr(CurScope, L, II, Tok.is(tok::l_paren));
535     // These can be followed by postfix-expr pieces.
536     return ParsePostfixExpressionSuffix(Res);
537   }
538   case tok::char_constant:     // constant: character-constant
539     Res = Actions.ActOnCharacterConstant(Tok);
540     ConsumeToken();
541     // These can be followed by postfix-expr pieces.
542     return ParsePostfixExpressionSuffix(Res);    
543   case tok::kw___func__:       // primary-expression: __func__ [C99 6.4.2.2]
544   case tok::kw___FUNCTION__:   // primary-expression: __FUNCTION__ [GNU]
545   case tok::kw___PRETTY_FUNCTION__:  // primary-expression: __P..Y_F..N__ [GNU]
546     Res = Actions.ActOnPreDefinedExpr(Tok.getLocation(), SavedKind);
547     ConsumeToken();
548     // These can be followed by postfix-expr pieces.
549     return ParsePostfixExpressionSuffix(Res);
550   case tok::string_literal:    // primary-expression: string-literal
551   case tok::wide_string_literal:
552     Res = ParseStringLiteralExpression();
553     if (Res.isInvalid) return Res;
554     // This can be followed by postfix-expr pieces (e.g. "foo"[1]).
555     return ParsePostfixExpressionSuffix(Res);
556   case tok::kw___builtin_va_arg:
557   case tok::kw___builtin_offsetof:
558   case tok::kw___builtin_choose_expr:
559   case tok::kw___builtin_overload:
560   case tok::kw___builtin_types_compatible_p:
561     return ParseBuiltinPrimaryExpression();
562   case tok::plusplus:      // unary-expression: '++' unary-expression
563   case tok::minusminus: {  // unary-expression: '--' unary-expression
564     SourceLocation SavedLoc = ConsumeToken();
565     Res = ParseCastExpression(true);
566     if (!Res.isInvalid)
567       Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
568     return Res;
569   }
570   case tok::amp:           // unary-expression: '&' cast-expression
571   case tok::star:          // unary-expression: '*' cast-expression
572   case tok::plus:          // unary-expression: '+' cast-expression
573   case tok::minus:         // unary-expression: '-' cast-expression
574   case tok::tilde:         // unary-expression: '~' cast-expression
575   case tok::exclaim:       // unary-expression: '!' cast-expression
576   case tok::kw___real:     // unary-expression: '__real' cast-expression [GNU]
577   case tok::kw___imag: {   // unary-expression: '__imag' cast-expression [GNU]
578     SourceLocation SavedLoc = ConsumeToken();
579     Res = ParseCastExpression(false);
580     if (!Res.isInvalid)
581       Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
582     return Res;
583   }    
584       
585   case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
586     // __extension__ silences extension warnings in the subexpression.
587     bool SavedExtWarn = Diags.getWarnOnExtensions();
588     Diags.setWarnOnExtensions(false);
589     SourceLocation SavedLoc = ConsumeToken();
590     Res = ParseCastExpression(false);
591     if (!Res.isInvalid)
592       Res = Actions.ActOnUnaryOp(SavedLoc, SavedKind, Res.Val);
593     Diags.setWarnOnExtensions(SavedExtWarn);
594     return Res;
595   }
596   case tok::kw_sizeof:     // unary-expression: 'sizeof' unary-expression
597                            // unary-expression: 'sizeof' '(' type-name ')'
598   case tok::kw___alignof:  // unary-expression: '__alignof' unary-expression
599                            // unary-expression: '__alignof' '(' type-name ')'
600     return ParseSizeofAlignofExpression();
601   case tok::ampamp: {      // unary-expression: '&&' identifier
602     SourceLocation AmpAmpLoc = ConsumeToken();
603     if (Tok.isNot(tok::identifier)) {
604       Diag(Tok, diag::err_expected_ident);
605       return ExprResult(true);
606     }
607     
608     Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
609     Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(),
610                                  Tok.getIdentifierInfo());
611     ConsumeToken();
612     return Res;
613   }
614   case tok::kw_const_cast:
615   case tok::kw_dynamic_cast:
616   case tok::kw_reinterpret_cast:
617   case tok::kw_static_cast:
618     return ParseCXXCasts();
619   case tok::at: {
620     SourceLocation AtLoc = ConsumeToken();
621     return ParseObjCAtExpression(AtLoc);
622   }
623   case tok::l_square:
624     // These can be followed by postfix-expr pieces.
625     return ParsePostfixExpressionSuffix(ParseObjCMessageExpression());
626   default:
627     Diag(Tok, diag::err_expected_expression);
628     return ExprResult(true);
629   }
630   
631   // unreachable.
632   abort();
633 }
634
635 /// ParsePostfixExpressionSuffix - Once the leading part of a postfix-expression
636 /// is parsed, this method parses any suffixes that apply.
637 ///
638 ///       postfix-expression: [C99 6.5.2]
639 ///         primary-expression
640 ///         postfix-expression '[' expression ']'
641 ///         postfix-expression '(' argument-expression-list[opt] ')'
642 ///         postfix-expression '.' identifier
643 ///         postfix-expression '->' identifier
644 ///         postfix-expression '++'
645 ///         postfix-expression '--'
646 ///         '(' type-name ')' '{' initializer-list '}'
647 ///         '(' type-name ')' '{' initializer-list ',' '}'
648 ///
649 ///       argument-expression-list: [C99 6.5.2]
650 ///         argument-expression
651 ///         argument-expression-list ',' assignment-expression
652 ///
653 Parser::ExprResult Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
654   
655   // Now that the primary-expression piece of the postfix-expression has been
656   // parsed, see if there are any postfix-expression pieces here.
657   SourceLocation Loc;
658   while (1) {
659     switch (Tok.getKind()) {
660     default:  // Not a postfix-expression suffix.
661       return LHS;
662     case tok::l_square: {  // postfix-expression: p-e '[' expression ']'
663       Loc = ConsumeBracket();
664       ExprResult Idx = ParseExpression();
665       
666       SourceLocation RLoc = Tok.getLocation();
667       
668       if (!LHS.isInvalid && !Idx.isInvalid && Tok.is(tok::r_square))
669         LHS = Actions.ActOnArraySubscriptExpr(LHS.Val, Loc, Idx.Val, RLoc);
670       else 
671         LHS = ExprResult(true);
672
673       // Match the ']'.
674       MatchRHSPunctuation(tok::r_square, Loc);
675       break;
676     }
677       
678     case tok::l_paren: {   // p-e: p-e '(' argument-expression-list[opt] ')'
679       llvm::SmallVector<ExprTy*, 8> ArgExprs;
680       llvm::SmallVector<SourceLocation, 8> CommaLocs;
681       
682       Loc = ConsumeParen();
683       
684       if (Tok.isNot(tok::r_paren)) {
685         while (1) {
686           ExprResult ArgExpr = ParseAssignmentExpression();
687           if (ArgExpr.isInvalid) {
688             SkipUntil(tok::r_paren);
689             return ExprResult(true);
690           } else
691             ArgExprs.push_back(ArgExpr.Val);
692           
693           if (Tok.isNot(tok::comma))
694             break;
695           // Move to the next argument, remember where the comma was.
696           CommaLocs.push_back(ConsumeToken());
697         }
698       }
699         
700       // Match the ')'.
701       if (!LHS.isInvalid && Tok.is(tok::r_paren)) {
702         assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&&
703                "Unexpected number of commas!");
704         LHS = Actions.ActOnCallExpr(LHS.Val, Loc, &ArgExprs[0], ArgExprs.size(),
705                                     &CommaLocs[0], Tok.getLocation());
706       }
707       
708       MatchRHSPunctuation(tok::r_paren, Loc);
709       break;
710     }
711     case tok::arrow:       // postfix-expression: p-e '->' identifier
712     case tok::period: {    // postfix-expression: p-e '.' identifier
713       tok::TokenKind OpKind = Tok.getKind();
714       SourceLocation OpLoc = ConsumeToken();  // Eat the "." or "->" token.
715       
716       if (Tok.isNot(tok::identifier)) {
717         Diag(Tok, diag::err_expected_ident);
718         return ExprResult(true);
719       }
720       
721       if (!LHS.isInvalid)
722         LHS = Actions.ActOnMemberReferenceExpr(LHS.Val, OpLoc, OpKind,
723                                                Tok.getLocation(),
724                                                *Tok.getIdentifierInfo());
725       ConsumeToken();
726       break;
727     }
728     case tok::plusplus:    // postfix-expression: postfix-expression '++'
729     case tok::minusminus:  // postfix-expression: postfix-expression '--'
730       if (!LHS.isInvalid)
731         LHS = Actions.ActOnPostfixUnaryOp(Tok.getLocation(), Tok.getKind(),
732                                           LHS.Val);
733       ConsumeToken();
734       break;
735     }
736   }
737 }
738
739
740 /// ParseSizeofAlignofExpression - Parse a sizeof or alignof expression.
741 ///       unary-expression:  [C99 6.5.3]
742 ///         'sizeof' unary-expression
743 ///         'sizeof' '(' type-name ')'
744 /// [GNU]   '__alignof' unary-expression
745 /// [GNU]   '__alignof' '(' type-name ')'
746 Parser::ExprResult Parser::ParseSizeofAlignofExpression() {
747   assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof)) &&
748          "Not a sizeof/alignof expression!");
749   Token OpTok = Tok;
750   ConsumeToken();
751   
752   // If the operand doesn't start with an '(', it must be an expression.
753   ExprResult Operand;
754   if (Tok.isNot(tok::l_paren)) {
755     Operand = ParseCastExpression(true);
756   } else {
757     // If it starts with a '(', we know that it is either a parenthesized
758     // type-name, or it is a unary-expression that starts with a compound
759     // literal, or starts with a primary-expression that is a parenthesized
760     // expression.
761     ParenParseOption ExprType = CastExpr;
762     TypeTy *CastTy;
763     SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
764     Operand = ParseParenExpression(ExprType, CastTy, RParenLoc);
765     
766     // If ParseParenExpression parsed a '(typename)' sequence only, the this is
767     // sizeof/alignof a type.  Otherwise, it is sizeof/alignof an expression.
768     if (ExprType == CastExpr)
769       return Actions.ActOnSizeOfAlignOfTypeExpr(OpTok.getLocation(),
770                                                 OpTok.is(tok::kw_sizeof),
771                                                 LParenLoc, CastTy, RParenLoc);
772     
773     // If this is a parenthesized expression, it is the start of a 
774     // unary-expression, but doesn't include any postfix pieces.  Parse these
775     // now if present.
776     Operand = ParsePostfixExpressionSuffix(Operand);
777   }
778   
779   // If we get here, the operand to the sizeof/alignof was an expresion.
780   if (!Operand.isInvalid)
781     Operand = Actions.ActOnUnaryOp(OpTok.getLocation(), OpTok.getKind(),
782                                    Operand.Val);
783   return Operand;
784 }
785
786 /// ParseBuiltinPrimaryExpression
787 ///
788 ///       primary-expression: [C99 6.5.1]
789 /// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
790 /// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
791 /// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
792 ///                                     assign-expr ')'
793 /// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
794 /// [CLANG] '__builtin_overload' '(' expr (',' expr)* ')'
795 /// 
796 /// [GNU] offsetof-member-designator:
797 /// [GNU]   identifier
798 /// [GNU]   offsetof-member-designator '.' identifier
799 /// [GNU]   offsetof-member-designator '[' expression ']'
800 ///
801 Parser::ExprResult Parser::ParseBuiltinPrimaryExpression() {
802   ExprResult Res(false);
803   const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
804
805   tok::TokenKind T = Tok.getKind();
806   SourceLocation StartLoc = ConsumeToken();   // Eat the builtin identifier.
807
808   // All of these start with an open paren.
809   if (Tok.isNot(tok::l_paren)) {
810     Diag(Tok, diag::err_expected_lparen_after, BuiltinII->getName());
811     return ExprResult(true);
812   }
813   
814   SourceLocation LParenLoc = ConsumeParen();
815   // TODO: Build AST.
816
817   switch (T) {
818   default: assert(0 && "Not a builtin primary expression!");
819   case tok::kw___builtin_va_arg: {
820     ExprResult Expr = ParseAssignmentExpression();
821     if (Expr.isInvalid) {
822       SkipUntil(tok::r_paren);
823       return Res;
824     }
825
826     if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
827       return ExprResult(true);
828
829     TypeTy *Ty = ParseTypeName();
830     
831     if (Tok.isNot(tok::r_paren)) {
832       Diag(Tok, diag::err_expected_rparen);
833       return ExprResult(true);
834     }
835     Res = Actions.ActOnVAArg(StartLoc, Expr.Val, Ty, ConsumeParen());
836     break;
837   }
838   case tok::kw___builtin_offsetof: {
839     SourceLocation TypeLoc = Tok.getLocation();
840     TypeTy *Ty = ParseTypeName();
841
842     if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
843       return ExprResult(true);
844     
845     // We must have at least one identifier here.
846     if (Tok.isNot(tok::identifier)) {
847       Diag(Tok, diag::err_expected_ident);
848       SkipUntil(tok::r_paren);
849       return true;
850     }
851     
852     // Keep track of the various subcomponents we see.
853     llvm::SmallVector<Action::OffsetOfComponent, 4> Comps;
854     
855     Comps.push_back(Action::OffsetOfComponent());
856     Comps.back().isBrackets = false;
857     Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
858     Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
859
860     while (1) {
861       if (Tok.is(tok::period)) {
862         // offsetof-member-designator: offsetof-member-designator '.' identifier
863         Comps.push_back(Action::OffsetOfComponent());
864         Comps.back().isBrackets = false;
865         Comps.back().LocStart = ConsumeToken();
866         
867         if (Tok.isNot(tok::identifier)) {
868           Diag(Tok, diag::err_expected_ident);
869           SkipUntil(tok::r_paren);
870           return true;
871         }
872         Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
873         Comps.back().LocEnd = ConsumeToken();
874         
875       } else if (Tok.is(tok::l_square)) {
876         // offsetof-member-designator: offsetof-member-design '[' expression ']'
877         Comps.push_back(Action::OffsetOfComponent());
878         Comps.back().isBrackets = true;
879         Comps.back().LocStart = ConsumeBracket();
880         Res = ParseExpression();
881         if (Res.isInvalid) {
882           SkipUntil(tok::r_paren);
883           return Res;
884         }
885         Comps.back().U.E = Res.Val;
886
887         Comps.back().LocEnd =
888           MatchRHSPunctuation(tok::r_square, Comps.back().LocStart);
889       } else if (Tok.is(tok::r_paren)) {
890         Res = Actions.ActOnBuiltinOffsetOf(StartLoc, TypeLoc, Ty, &Comps[0],
891                                            Comps.size(), ConsumeParen());
892         break;
893       } else {
894         // Error occurred.
895         return ExprResult(true);
896       }
897     }
898     break;
899   }
900   case tok::kw___builtin_choose_expr: {
901     ExprResult Cond = ParseAssignmentExpression();
902     if (Cond.isInvalid) {
903       SkipUntil(tok::r_paren);
904       return Cond;
905     }
906     if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
907       return ExprResult(true);
908     
909     ExprResult Expr1 = ParseAssignmentExpression();
910     if (Expr1.isInvalid) {
911       SkipUntil(tok::r_paren);
912       return Expr1;
913     }    
914     if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
915       return ExprResult(true);
916     
917     ExprResult Expr2 = ParseAssignmentExpression();
918     if (Expr2.isInvalid) {
919       SkipUntil(tok::r_paren);
920       return Expr2;
921     }    
922     if (Tok.isNot(tok::r_paren)) {
923       Diag(Tok, diag::err_expected_rparen);
924       return ExprResult(true);
925     }
926     Res = Actions.ActOnChooseExpr(StartLoc, Cond.Val, Expr1.Val, Expr2.Val,
927                                   ConsumeParen());
928     break;
929   }
930   case tok::kw___builtin_overload: {
931     llvm::SmallVector<ExprTy*, 8> ArgExprs;
932     llvm::SmallVector<SourceLocation, 8> CommaLocs;
933
934     // For each iteration through the loop look for assign-expr followed by a
935     // comma.  If there is no comma, break and attempt to match r-paren.
936     if (Tok.isNot(tok::r_paren)) {
937       while (1) {
938         ExprResult ArgExpr = ParseAssignmentExpression();
939         if (ArgExpr.isInvalid) {
940           SkipUntil(tok::r_paren);
941           return ExprResult(true);
942         } else
943           ArgExprs.push_back(ArgExpr.Val);
944         
945         if (Tok.isNot(tok::comma))
946           break;
947         // Move to the next argument, remember where the comma was.
948         CommaLocs.push_back(ConsumeToken());
949       }
950     }
951     
952     // Attempt to consume the r-paren
953     if (Tok.isNot(tok::r_paren)) {
954       Diag(Tok, diag::err_expected_rparen);
955       SkipUntil(tok::r_paren);
956       return ExprResult(true);
957     }
958     Res = Actions.ActOnOverloadExpr(&ArgExprs[0], ArgExprs.size(), 
959                                     &CommaLocs[0], StartLoc, ConsumeParen());
960     break;
961   }
962   case tok::kw___builtin_types_compatible_p:
963     TypeTy *Ty1 = ParseTypeName();
964     
965     if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
966       return ExprResult(true);
967     
968     TypeTy *Ty2 = ParseTypeName();
969     
970     if (Tok.isNot(tok::r_paren)) {
971       Diag(Tok, diag::err_expected_rparen);
972       return ExprResult(true);
973     }
974     Res = Actions.ActOnTypesCompatibleExpr(StartLoc, Ty1, Ty2, ConsumeParen());
975     break;
976   }      
977   
978   // These can be followed by postfix-expr pieces because they are
979   // primary-expressions.
980   return ParsePostfixExpressionSuffix(Res);
981 }
982
983 /// ParseParenExpression - This parses the unit that starts with a '(' token,
984 /// based on what is allowed by ExprType.  The actual thing parsed is returned
985 /// in ExprType.
986 ///
987 ///       primary-expression: [C99 6.5.1]
988 ///         '(' expression ')'
989 /// [GNU]   '(' compound-statement ')'      (if !ParenExprOnly)
990 ///       postfix-expression: [C99 6.5.2]
991 ///         '(' type-name ')' '{' initializer-list '}'
992 ///         '(' type-name ')' '{' initializer-list ',' '}'
993 ///       cast-expression: [C99 6.5.4]
994 ///         '(' type-name ')' cast-expression
995 ///
996 Parser::ExprResult Parser::ParseParenExpression(ParenParseOption &ExprType,
997                                                 TypeTy *&CastTy,
998                                                 SourceLocation &RParenLoc) {
999   assert(Tok.is(tok::l_paren) && "Not a paren expr!");
1000   SourceLocation OpenLoc = ConsumeParen();
1001   ExprResult Result(true);
1002   CastTy = 0;
1003   
1004   if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
1005     Diag(Tok, diag::ext_gnu_statement_expr);
1006     Parser::StmtResult Stmt = ParseCompoundStatement(true);
1007     ExprType = CompoundStmt;
1008     
1009     // If the substmt parsed correctly, build the AST node.
1010     if (!Stmt.isInvalid && Tok.is(tok::r_paren))
1011       Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.Val, Tok.getLocation());
1012     
1013   } else if (ExprType >= CompoundLiteral && isTypeSpecifierQualifier()) {
1014     // Otherwise, this is a compound literal expression or cast expression.
1015     TypeTy *Ty = ParseTypeName();
1016
1017     // Match the ')'.
1018     if (Tok.is(tok::r_paren))
1019       RParenLoc = ConsumeParen();
1020     else
1021       MatchRHSPunctuation(tok::r_paren, OpenLoc);
1022     
1023     if (Tok.is(tok::l_brace)) {
1024       if (!getLang().C99)   // Compound literals don't exist in C90.
1025         Diag(OpenLoc, diag::ext_c99_compound_literal);
1026       Result = ParseInitializer();
1027       ExprType = CompoundLiteral;
1028       if (!Result.isInvalid)
1029         return Actions.ActOnCompoundLiteral(OpenLoc, Ty, RParenLoc, Result.Val);
1030     } else if (ExprType == CastExpr) {
1031       // Note that this doesn't parse the subsequence cast-expression, it just
1032       // returns the parsed type to the callee.
1033       ExprType = CastExpr;
1034       CastTy = Ty;
1035       return ExprResult(false);
1036     } else {
1037       Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
1038       return ExprResult(true);
1039     }
1040     return Result;
1041   } else {
1042     Result = ParseExpression();
1043     ExprType = SimpleExpr;
1044     if (!Result.isInvalid && Tok.is(tok::r_paren))
1045       Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.Val);
1046   }
1047   
1048   // Match the ')'.
1049   if (Result.isInvalid)
1050     SkipUntil(tok::r_paren);
1051   else {
1052     if (Tok.is(tok::r_paren))
1053       RParenLoc = ConsumeParen();
1054     else
1055       MatchRHSPunctuation(tok::r_paren, OpenLoc);
1056   }
1057   
1058   return Result;
1059 }
1060
1061 /// ParseStringLiteralExpression - This handles the various token types that
1062 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
1063 /// translation phase #6].
1064 ///
1065 ///       primary-expression: [C99 6.5.1]
1066 ///         string-literal
1067 Parser::ExprResult Parser::ParseStringLiteralExpression() {
1068   assert(isTokenStringLiteral() && "Not a string literal!");
1069   
1070   // String concat.  Note that keywords like __func__ and __FUNCTION__ are not
1071   // considered to be strings for concatenation purposes.
1072   llvm::SmallVector<Token, 4> StringToks;
1073   
1074   do {
1075     StringToks.push_back(Tok);
1076     ConsumeStringToken();
1077   } while (isTokenStringLiteral());
1078
1079   // Pass the set of string tokens, ready for concatenation, to the actions.
1080   return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size());
1081 }