ParseExpr.cpp revision b3e277222ac7e2148fc8ce2d5cf596231e1ee926
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/// \file
11/// \brief Provides the Expression parsing implementation.
12///
13/// Expressions in C99 basically consist of a bunch of binary operators with
14/// unary operators and other random stuff at the leaves.
15///
16/// In the C99 grammar, these unary operators bind tightest and are represented
17/// as the 'cast-expression' production.  Everything else is either a binary
18/// operator (e.g. '/') or a ternary operator ("?:").  The unary leaves are
19/// handled by ParseCastExpression, the higher level pieces are handled by
20/// ParseBinaryExpression.
21///
22//===----------------------------------------------------------------------===//
23
24#include "clang/Parse/Parser.h"
25#include "RAIIObjectsForParser.h"
26#include "clang/Basic/PrettyStackTrace.h"
27#include "clang/Sema/DeclSpec.h"
28#include "clang/Sema/ParsedTemplate.h"
29#include "clang/Sema/Scope.h"
30#include "clang/Sema/TypoCorrection.h"
31#include "llvm/ADT/SmallString.h"
32#include "llvm/ADT/SmallVector.h"
33using namespace clang;
34
35/// \brief Simple precedence-based parser for binary/ternary operators.
36///
37/// Note: we diverge from the C99 grammar when parsing the assignment-expression
38/// production.  C99 specifies that the LHS of an assignment operator should be
39/// parsed as a unary-expression, but consistency dictates that it be a
40/// conditional-expession.  In practice, the important thing here is that the
41/// LHS of an assignment has to be an l-value, which productions between
42/// unary-expression and conditional-expression don't produce.  Because we want
43/// consistency, we parse the LHS as a conditional-expression, then check for
44/// l-value-ness in semantic analysis stages.
45///
46/// \verbatim
47///       pm-expression: [C++ 5.5]
48///         cast-expression
49///         pm-expression '.*' cast-expression
50///         pm-expression '->*' cast-expression
51///
52///       multiplicative-expression: [C99 6.5.5]
53///     Note: in C++, apply pm-expression instead of cast-expression
54///         cast-expression
55///         multiplicative-expression '*' cast-expression
56///         multiplicative-expression '/' cast-expression
57///         multiplicative-expression '%' cast-expression
58///
59///       additive-expression: [C99 6.5.6]
60///         multiplicative-expression
61///         additive-expression '+' multiplicative-expression
62///         additive-expression '-' multiplicative-expression
63///
64///       shift-expression: [C99 6.5.7]
65///         additive-expression
66///         shift-expression '<<' additive-expression
67///         shift-expression '>>' additive-expression
68///
69///       relational-expression: [C99 6.5.8]
70///         shift-expression
71///         relational-expression '<' shift-expression
72///         relational-expression '>' shift-expression
73///         relational-expression '<=' shift-expression
74///         relational-expression '>=' shift-expression
75///
76///       equality-expression: [C99 6.5.9]
77///         relational-expression
78///         equality-expression '==' relational-expression
79///         equality-expression '!=' relational-expression
80///
81///       AND-expression: [C99 6.5.10]
82///         equality-expression
83///         AND-expression '&' equality-expression
84///
85///       exclusive-OR-expression: [C99 6.5.11]
86///         AND-expression
87///         exclusive-OR-expression '^' AND-expression
88///
89///       inclusive-OR-expression: [C99 6.5.12]
90///         exclusive-OR-expression
91///         inclusive-OR-expression '|' exclusive-OR-expression
92///
93///       logical-AND-expression: [C99 6.5.13]
94///         inclusive-OR-expression
95///         logical-AND-expression '&&' inclusive-OR-expression
96///
97///       logical-OR-expression: [C99 6.5.14]
98///         logical-AND-expression
99///         logical-OR-expression '||' logical-AND-expression
100///
101///       conditional-expression: [C99 6.5.15]
102///         logical-OR-expression
103///         logical-OR-expression '?' expression ':' conditional-expression
104/// [GNU]   logical-OR-expression '?' ':' conditional-expression
105/// [C++] the third operand is an assignment-expression
106///
107///       assignment-expression: [C99 6.5.16]
108///         conditional-expression
109///         unary-expression assignment-operator assignment-expression
110/// [C++]   throw-expression [C++ 15]
111///
112///       assignment-operator: one of
113///         = *= /= %= += -= <<= >>= &= ^= |=
114///
115///       expression: [C99 6.5.17]
116///         assignment-expression ...[opt]
117///         expression ',' assignment-expression ...[opt]
118/// \endverbatim
119ExprResult Parser::ParseExpression(TypeCastState isTypeCast) {
120  ExprResult LHS(ParseAssignmentExpression(isTypeCast));
121  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
122}
123
124/// This routine is called when the '@' is seen and consumed.
125/// Current token is an Identifier and is not a 'try'. This
126/// routine is necessary to disambiguate \@try-statement from,
127/// for example, \@encode-expression.
128///
129ExprResult
130Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
131  ExprResult LHS(ParseObjCAtExpression(AtLoc));
132  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
133}
134
135/// This routine is called when a leading '__extension__' is seen and
136/// consumed.  This is necessary because the token gets consumed in the
137/// process of disambiguating between an expression and a declaration.
138ExprResult
139Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
140  ExprResult LHS(true);
141  {
142    // Silence extension warnings in the sub-expression
143    ExtensionRAIIObject O(Diags);
144
145    LHS = ParseCastExpression(false);
146  }
147
148  if (!LHS.isInvalid())
149    LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
150                               LHS.take());
151
152  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
153}
154
155/// \brief Parse an expr that doesn't include (top-level) commas.
156ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) {
157  if (Tok.is(tok::code_completion)) {
158    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
159    cutOffParsing();
160    return ExprError();
161  }
162
163  if (Tok.is(tok::kw_throw))
164    return ParseThrowExpression();
165
166  ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false,
167                                       /*isAddressOfOperand=*/false,
168                                       isTypeCast);
169
170  // Check for a possible typo of "-" or ">" instead of "->" after a
171  // pointer to a struct or class, while recovery is still possible.
172  if (LHS.isUsable() && (Tok.is(tok::minus) || Tok.is(tok::greater))) {
173    QualType LHSType = LHS.get()->getType();
174    const RecordType *Pointee =
175        LHSType->isPointerType()
176            ? LHSType->getPointeeType()->getAsStructureType()
177            : 0;
178    const RecordDecl *RD = Pointee ? Pointee->getDecl() : 0;
179    const Token &NextTok = NextToken();
180    if (RD && NextTok.is(tok::identifier)) {
181      UnqualifiedId Name;
182      CXXScopeSpec ScopeSpec;
183      SourceLocation TemplateKWLoc;
184      NoTypoCorrectionCCC NoTCValidator;
185      Name.setIdentifier(NextTok.getIdentifierInfo(), NextTok.getLocation());
186      Sema::SFINAETrap Trap(Actions);
187      ExprResult Res =
188          Actions.ActOnIdExpression(getCurScope(), ScopeSpec, TemplateKWLoc,
189                                    Name, false, false, &NoTCValidator);
190      if (Res.isInvalid()) {
191        Token OpTok = Tok;
192        Tok.setKind(tok::arrow);
193        PP.EnableBacktrackAtThisPos();
194        Res = ParsePostfixExpressionSuffix(LHS);
195        if (Res.isUsable()) {
196          LHS = Res;
197          PP.CommitBacktrackedTokens();
198          Diag(OpTok, diag::err_mistyped_arrow_in_member_access)
199              << NextTok.getIdentifierInfo() << OpTok.is(tok::greater)
200              << FixItHint::CreateReplacement(OpTok.getLocation(), "->");
201        } else {
202          Tok = OpTok;
203          PP.Backtrack();
204        }
205      }
206    }
207  }
208
209  return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
210}
211
212/// \brief Parse an assignment expression where part of an Objective-C message
213/// send has already been parsed.
214///
215/// In this case \p LBracLoc indicates the location of the '[' of the message
216/// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
217/// the receiver of the message.
218///
219/// Since this handles full assignment-expression's, it handles postfix
220/// expressions and other binary operators for these expressions as well.
221ExprResult
222Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
223                                                    SourceLocation SuperLoc,
224                                                    ParsedType ReceiverType,
225                                                    Expr *ReceiverExpr) {
226  ExprResult R
227    = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
228                                     ReceiverType, ReceiverExpr);
229  R = ParsePostfixExpressionSuffix(R);
230  return ParseRHSOfBinaryExpression(R, prec::Assignment);
231}
232
233
234ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) {
235  // C++03 [basic.def.odr]p2:
236  //   An expression is potentially evaluated unless it appears where an
237  //   integral constant expression is required (see 5.19) [...].
238  // C++98 and C++11 have no such rule, but this is only a defect in C++98.
239  EnterExpressionEvaluationContext Unevaluated(Actions,
240                                               Sema::ConstantEvaluated);
241
242  ExprResult LHS(ParseCastExpression(false, false, isTypeCast));
243  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
244  return Actions.ActOnConstantExpression(Res);
245}
246
247bool Parser::isNotExpressionStart() {
248  tok::TokenKind K = Tok.getKind();
249  if (K == tok::l_brace || K == tok::r_brace  ||
250      K == tok::kw_for  || K == tok::kw_while ||
251      K == tok::kw_if   || K == tok::kw_else  ||
252      K == tok::kw_goto || K == tok::kw_try)
253    return true;
254  // If this is a decl-specifier, we can't be at the start of an expression.
255  return isKnownToBeDeclarationSpecifier();
256}
257
258/// \brief Parse a binary expression that starts with \p LHS and has a
259/// precedence of at least \p MinPrec.
260ExprResult
261Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
262  prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
263                                               GreaterThanIsOperator,
264                                               getLangOpts().CPlusPlus11);
265  SourceLocation ColonLoc;
266
267  while (1) {
268    // If this token has a lower precedence than we are allowed to parse (e.g.
269    // because we are called recursively, or because the token is not a binop),
270    // then we are done!
271    if (NextTokPrec < MinPrec)
272      return LHS;
273
274    // Consume the operator, saving the operator token for error reporting.
275    Token OpToken = Tok;
276    ConsumeToken();
277
278    // Bail out when encountering a comma followed by a token which can't
279    // possibly be the start of an expression. For instance:
280    //   int f() { return 1, }
281    // We can't do this before consuming the comma, because
282    // isNotExpressionStart() looks at the token stream.
283    if (OpToken.is(tok::comma) && isNotExpressionStart()) {
284      PP.EnterToken(Tok);
285      Tok = OpToken;
286      return LHS;
287    }
288
289    // Special case handling for the ternary operator.
290    ExprResult TernaryMiddle(true);
291    if (NextTokPrec == prec::Conditional) {
292      if (Tok.isNot(tok::colon)) {
293        // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
294        ColonProtectionRAIIObject X(*this);
295
296        // Handle this production specially:
297        //   logical-OR-expression '?' expression ':' conditional-expression
298        // In particular, the RHS of the '?' is 'expression', not
299        // 'logical-OR-expression' as we might expect.
300        TernaryMiddle = ParseExpression();
301        if (TernaryMiddle.isInvalid()) {
302          LHS = ExprError();
303          TernaryMiddle = 0;
304        }
305      } else {
306        // Special case handling of "X ? Y : Z" where Y is empty:
307        //   logical-OR-expression '?' ':' conditional-expression   [GNU]
308        TernaryMiddle = 0;
309        Diag(Tok, diag::ext_gnu_conditional_expr);
310      }
311
312      if (Tok.is(tok::colon)) {
313        // Eat the colon.
314        ColonLoc = ConsumeToken();
315      } else {
316        // Otherwise, we're missing a ':'.  Assume that this was a typo that
317        // the user forgot. If we're not in a macro expansion, we can suggest
318        // a fixit hint. If there were two spaces before the current token,
319        // suggest inserting the colon in between them, otherwise insert ": ".
320        SourceLocation FILoc = Tok.getLocation();
321        const char *FIText = ": ";
322        const SourceManager &SM = PP.getSourceManager();
323        if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
324          assert(FILoc.isFileID());
325          bool IsInvalid = false;
326          const char *SourcePtr =
327            SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
328          if (!IsInvalid && *SourcePtr == ' ') {
329            SourcePtr =
330              SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
331            if (!IsInvalid && *SourcePtr == ' ') {
332              FILoc = FILoc.getLocWithOffset(-1);
333              FIText = ":";
334            }
335          }
336        }
337
338        Diag(Tok, diag::err_expected_colon)
339          << FixItHint::CreateInsertion(FILoc, FIText);
340        Diag(OpToken, diag::note_matching) << "?";
341        ColonLoc = Tok.getLocation();
342      }
343    }
344
345    // Code completion for the right-hand side of an assignment expression
346    // goes through a special hook that takes the left-hand side into account.
347    if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) {
348      Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get());
349      cutOffParsing();
350      return ExprError();
351    }
352
353    // Parse another leaf here for the RHS of the operator.
354    // ParseCastExpression works here because all RHS expressions in C have it
355    // as a prefix, at least. However, in C++, an assignment-expression could
356    // be a throw-expression, which is not a valid cast-expression.
357    // Therefore we need some special-casing here.
358    // Also note that the third operand of the conditional operator is
359    // an assignment-expression in C++, and in C++11, we can have a
360    // braced-init-list on the RHS of an assignment. For better diagnostics,
361    // parse as if we were allowed braced-init-lists everywhere, and check that
362    // they only appear on the RHS of assignments later.
363    ExprResult RHS;
364    bool RHSIsInitList = false;
365    if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
366      RHS = ParseBraceInitializer();
367      RHSIsInitList = true;
368    } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
369      RHS = ParseAssignmentExpression();
370    else
371      RHS = ParseCastExpression(false);
372
373    if (RHS.isInvalid())
374      LHS = ExprError();
375
376    // Remember the precedence of this operator and get the precedence of the
377    // operator immediately to the right of the RHS.
378    prec::Level ThisPrec = NextTokPrec;
379    NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
380                                     getLangOpts().CPlusPlus11);
381
382    // Assignment and conditional expressions are right-associative.
383    bool isRightAssoc = ThisPrec == prec::Conditional ||
384                        ThisPrec == prec::Assignment;
385
386    // Get the precedence of the operator to the right of the RHS.  If it binds
387    // more tightly with RHS than we do, evaluate it completely first.
388    if (ThisPrec < NextTokPrec ||
389        (ThisPrec == NextTokPrec && isRightAssoc)) {
390      if (!RHS.isInvalid() && RHSIsInitList) {
391        Diag(Tok, diag::err_init_list_bin_op)
392          << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
393        RHS = ExprError();
394      }
395      // If this is left-associative, only parse things on the RHS that bind
396      // more tightly than the current operator.  If it is left-associative, it
397      // is okay, to bind exactly as tightly.  For example, compile A=B=C=D as
398      // A=(B=(C=D)), where each paren is a level of recursion here.
399      // The function takes ownership of the RHS.
400      RHS = ParseRHSOfBinaryExpression(RHS,
401                            static_cast<prec::Level>(ThisPrec + !isRightAssoc));
402      RHSIsInitList = false;
403
404      if (RHS.isInvalid())
405        LHS = ExprError();
406
407      NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
408                                       getLangOpts().CPlusPlus11);
409    }
410    assert(NextTokPrec <= ThisPrec && "Recursion didn't work!");
411
412    if (!RHS.isInvalid() && RHSIsInitList) {
413      if (ThisPrec == prec::Assignment) {
414        Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
415          << Actions.getExprRange(RHS.get());
416      } else {
417        Diag(OpToken, diag::err_init_list_bin_op)
418          << /*RHS*/1 << PP.getSpelling(OpToken)
419          << Actions.getExprRange(RHS.get());
420        LHS = ExprError();
421      }
422    }
423
424    if (!LHS.isInvalid()) {
425      // Combine the LHS and RHS into the LHS (e.g. build AST).
426      if (TernaryMiddle.isInvalid()) {
427        // If we're using '>>' as an operator within a template
428        // argument list (in C++98), suggest the addition of
429        // parentheses so that the code remains well-formed in C++0x.
430        if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
431          SuggestParentheses(OpToken.getLocation(),
432                             diag::warn_cxx11_right_shift_in_template_arg,
433                         SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
434                                     Actions.getExprRange(RHS.get()).getEnd()));
435
436        LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
437                                 OpToken.getKind(), LHS.take(), RHS.take());
438      } else
439        LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc,
440                                         LHS.take(), TernaryMiddle.take(),
441                                         RHS.take());
442    }
443  }
444}
445
446/// \brief Parse a cast-expression, or, if \p isUnaryExpression is true,
447/// parse a unary-expression.
448///
449/// \p isAddressOfOperand exists because an id-expression that is the
450/// operand of address-of gets special treatment due to member pointers.
451///
452ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
453                                       bool isAddressOfOperand,
454                                       TypeCastState isTypeCast) {
455  bool NotCastExpr;
456  ExprResult Res = ParseCastExpression(isUnaryExpression,
457                                       isAddressOfOperand,
458                                       NotCastExpr,
459                                       isTypeCast);
460  if (NotCastExpr)
461    Diag(Tok, diag::err_expected_expression);
462  return Res;
463}
464
465namespace {
466class CastExpressionIdValidator : public CorrectionCandidateCallback {
467 public:
468  CastExpressionIdValidator(bool AllowTypes, bool AllowNonTypes)
469      : AllowNonTypes(AllowNonTypes) {
470    WantTypeSpecifiers = AllowTypes;
471  }
472
473  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
474    NamedDecl *ND = candidate.getCorrectionDecl();
475    if (!ND)
476      return candidate.isKeyword();
477
478    if (isa<TypeDecl>(ND))
479      return WantTypeSpecifiers;
480    return AllowNonTypes;
481  }
482
483 private:
484  bool AllowNonTypes;
485};
486}
487
488/// \brief Parse a cast-expression, or, if \pisUnaryExpression is true, parse
489/// a unary-expression.
490///
491/// \p isAddressOfOperand exists because an id-expression that is the operand
492/// of address-of gets special treatment due to member pointers. NotCastExpr
493/// is set to true if the token is not the start of a cast-expression, and no
494/// diagnostic is emitted in this case.
495///
496/// \verbatim
497///       cast-expression: [C99 6.5.4]
498///         unary-expression
499///         '(' type-name ')' cast-expression
500///
501///       unary-expression:  [C99 6.5.3]
502///         postfix-expression
503///         '++' unary-expression
504///         '--' unary-expression
505///         unary-operator cast-expression
506///         'sizeof' unary-expression
507///         'sizeof' '(' type-name ')'
508/// [C++11] 'sizeof' '...' '(' identifier ')'
509/// [GNU]   '__alignof' unary-expression
510/// [GNU]   '__alignof' '(' type-name ')'
511/// [C11]   '_Alignof' '(' type-name ')'
512/// [C++11] 'alignof' '(' type-id ')'
513/// [GNU]   '&&' identifier
514/// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
515/// [C++]   new-expression
516/// [C++]   delete-expression
517///
518///       unary-operator: one of
519///         '&'  '*'  '+'  '-'  '~'  '!'
520/// [GNU]   '__extension__'  '__real'  '__imag'
521///
522///       primary-expression: [C99 6.5.1]
523/// [C99]   identifier
524/// [C++]   id-expression
525///         constant
526///         string-literal
527/// [C++]   boolean-literal  [C++ 2.13.5]
528/// [C++11] 'nullptr'        [C++11 2.14.7]
529/// [C++11] user-defined-literal
530///         '(' expression ')'
531/// [C11]   generic-selection
532///         '__func__'        [C99 6.4.2.2]
533/// [GNU]   '__FUNCTION__'
534/// [GNU]   '__PRETTY_FUNCTION__'
535/// [GNU]   '(' compound-statement ')'
536/// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
537/// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
538/// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
539///                                     assign-expr ')'
540/// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
541/// [GNU]   '__null'
542/// [OBJC]  '[' objc-message-expr ']'
543/// [OBJC]  '\@selector' '(' objc-selector-arg ')'
544/// [OBJC]  '\@protocol' '(' identifier ')'
545/// [OBJC]  '\@encode' '(' type-name ')'
546/// [OBJC]  objc-string-literal
547/// [C++]   simple-type-specifier '(' expression-list[opt] ')'      [C++ 5.2.3]
548/// [C++11] simple-type-specifier braced-init-list                  [C++11 5.2.3]
549/// [C++]   typename-specifier '(' expression-list[opt] ')'         [C++ 5.2.3]
550/// [C++11] typename-specifier braced-init-list                     [C++11 5.2.3]
551/// [C++]   'const_cast' '<' type-name '>' '(' expression ')'       [C++ 5.2p1]
552/// [C++]   'dynamic_cast' '<' type-name '>' '(' expression ')'     [C++ 5.2p1]
553/// [C++]   'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
554/// [C++]   'static_cast' '<' type-name '>' '(' expression ')'      [C++ 5.2p1]
555/// [C++]   'typeid' '(' expression ')'                             [C++ 5.2p1]
556/// [C++]   'typeid' '(' type-id ')'                                [C++ 5.2p1]
557/// [C++]   'this'          [C++ 9.3.2]
558/// [G++]   unary-type-trait '(' type-id ')'
559/// [G++]   binary-type-trait '(' type-id ',' type-id ')'           [TODO]
560/// [EMBT]  array-type-trait '(' type-id ',' integer ')'
561/// [clang] '^' block-literal
562///
563///       constant: [C99 6.4.4]
564///         integer-constant
565///         floating-constant
566///         enumeration-constant -> identifier
567///         character-constant
568///
569///       id-expression: [C++ 5.1]
570///                   unqualified-id
571///                   qualified-id
572///
573///       unqualified-id: [C++ 5.1]
574///                   identifier
575///                   operator-function-id
576///                   conversion-function-id
577///                   '~' class-name
578///                   template-id
579///
580///       new-expression: [C++ 5.3.4]
581///                   '::'[opt] 'new' new-placement[opt] new-type-id
582///                                     new-initializer[opt]
583///                   '::'[opt] 'new' new-placement[opt] '(' type-id ')'
584///                                     new-initializer[opt]
585///
586///       delete-expression: [C++ 5.3.5]
587///                   '::'[opt] 'delete' cast-expression
588///                   '::'[opt] 'delete' '[' ']' cast-expression
589///
590/// [GNU/Embarcadero] unary-type-trait:
591///                   '__is_arithmetic'
592///                   '__is_floating_point'
593///                   '__is_integral'
594///                   '__is_lvalue_expr'
595///                   '__is_rvalue_expr'
596///                   '__is_complete_type'
597///                   '__is_void'
598///                   '__is_array'
599///                   '__is_function'
600///                   '__is_reference'
601///                   '__is_lvalue_reference'
602///                   '__is_rvalue_reference'
603///                   '__is_fundamental'
604///                   '__is_object'
605///                   '__is_scalar'
606///                   '__is_compound'
607///                   '__is_pointer'
608///                   '__is_member_object_pointer'
609///                   '__is_member_function_pointer'
610///                   '__is_member_pointer'
611///                   '__is_const'
612///                   '__is_volatile'
613///                   '__is_trivial'
614///                   '__is_standard_layout'
615///                   '__is_signed'
616///                   '__is_unsigned'
617///
618/// [GNU] unary-type-trait:
619///                   '__has_nothrow_assign'
620///                   '__has_nothrow_copy'
621///                   '__has_nothrow_constructor'
622///                   '__has_trivial_assign'                  [TODO]
623///                   '__has_trivial_copy'                    [TODO]
624///                   '__has_trivial_constructor'
625///                   '__has_trivial_destructor'
626///                   '__has_virtual_destructor'
627///                   '__is_abstract'                         [TODO]
628///                   '__is_class'
629///                   '__is_empty'                            [TODO]
630///                   '__is_enum'
631///                   '__is_final'
632///                   '__is_pod'
633///                   '__is_polymorphic'
634///                   '__is_sealed'                           [MS]
635///                   '__is_trivial'
636///                   '__is_union'
637///
638/// [Clang] unary-type-trait:
639///                   '__trivially_copyable'
640///
641///       binary-type-trait:
642/// [GNU]             '__is_base_of'
643/// [MS]              '__is_convertible_to'
644///                   '__is_convertible'
645///                   '__is_same'
646///
647/// [Embarcadero] array-type-trait:
648///                   '__array_rank'
649///                   '__array_extent'
650///
651/// [Embarcadero] expression-trait:
652///                   '__is_lvalue_expr'
653///                   '__is_rvalue_expr'
654/// \endverbatim
655///
656ExprResult Parser::ParseCastExpression(bool isUnaryExpression,
657                                       bool isAddressOfOperand,
658                                       bool &NotCastExpr,
659                                       TypeCastState isTypeCast) {
660  ExprResult Res;
661  tok::TokenKind SavedKind = Tok.getKind();
662  NotCastExpr = false;
663
664  // This handles all of cast-expression, unary-expression, postfix-expression,
665  // and primary-expression.  We handle them together like this for efficiency
666  // and to simplify handling of an expression starting with a '(' token: which
667  // may be one of a parenthesized expression, cast-expression, compound literal
668  // expression, or statement expression.
669  //
670  // If the parsed tokens consist of a primary-expression, the cases below
671  // break out of the switch;  at the end we call ParsePostfixExpressionSuffix
672  // to handle the postfix expression suffixes.  Cases that cannot be followed
673  // by postfix exprs should return without invoking
674  // ParsePostfixExpressionSuffix.
675  switch (SavedKind) {
676  case tok::l_paren: {
677    // If this expression is limited to being a unary-expression, the parent can
678    // not start a cast expression.
679    ParenParseOption ParenExprType =
680      (isUnaryExpression && !getLangOpts().CPlusPlus)? CompoundLiteral : CastExpr;
681    ParsedType CastTy;
682    SourceLocation RParenLoc;
683
684    {
685      // The inside of the parens don't need to be a colon protected scope, and
686      // isn't immediately a message send.
687      ColonProtectionRAIIObject X(*this, false);
688
689      Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
690                                 isTypeCast == IsTypeCast, CastTy, RParenLoc);
691    }
692
693    switch (ParenExprType) {
694    case SimpleExpr:   break;    // Nothing else to do.
695    case CompoundStmt: break;  // Nothing else to do.
696    case CompoundLiteral:
697      // We parsed '(' type-name ')' '{' ... '}'.  If any suffixes of
698      // postfix-expression exist, parse them now.
699      break;
700    case CastExpr:
701      // We have parsed the cast-expression and no postfix-expr pieces are
702      // following.
703      return Res;
704    }
705
706    break;
707  }
708
709    // primary-expression
710  case tok::numeric_constant:
711    // constant: integer-constant
712    // constant: floating-constant
713
714    Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
715    ConsumeToken();
716    break;
717
718  case tok::kw_true:
719  case tok::kw_false:
720    return ParseCXXBoolLiteral();
721
722  case tok::kw___objc_yes:
723  case tok::kw___objc_no:
724      return ParseObjCBoolLiteral();
725
726  case tok::kw_nullptr:
727    Diag(Tok, diag::warn_cxx98_compat_nullptr);
728    return Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
729
730  case tok::annot_primary_expr:
731    assert(Res.get() == 0 && "Stray primary-expression annotation?");
732    Res = getExprAnnotation(Tok);
733    ConsumeToken();
734    break;
735
736  case tok::kw_decltype:
737    // Annotate the token and tail recurse.
738    if (TryAnnotateTypeOrScopeToken())
739      return ExprError();
740    assert(Tok.isNot(tok::kw_decltype));
741    return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
742
743  case tok::identifier: {      // primary-expression: identifier
744                               // unqualified-id: identifier
745                               // constant: enumeration-constant
746    // Turn a potentially qualified name into a annot_typename or
747    // annot_cxxscope if it would be valid.  This handles things like x::y, etc.
748    if (getLangOpts().CPlusPlus) {
749      // Avoid the unnecessary parse-time lookup in the common case
750      // where the syntax forbids a type.
751      const Token &Next = NextToken();
752
753      // If this identifier was reverted from a token ID, and the next token
754      // is a parenthesis, this is likely to be a use of a type trait. Check
755      // those tokens.
756      if (Next.is(tok::l_paren) &&
757          Tok.is(tok::identifier) &&
758          Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) {
759        IdentifierInfo *II = Tok.getIdentifierInfo();
760        // Build up the mapping of revertable type traits, for future use.
761        if (RevertableTypeTraits.empty()) {
762#define RTT_JOIN(X,Y) X##Y
763#define REVERTABLE_TYPE_TRAIT(Name)                         \
764          RevertableTypeTraits[PP.getIdentifierInfo(#Name)] \
765            = RTT_JOIN(tok::kw_,Name)
766
767          REVERTABLE_TYPE_TRAIT(__is_arithmetic);
768          REVERTABLE_TYPE_TRAIT(__is_convertible);
769          REVERTABLE_TYPE_TRAIT(__is_empty);
770          REVERTABLE_TYPE_TRAIT(__is_floating_point);
771          REVERTABLE_TYPE_TRAIT(__is_function);
772          REVERTABLE_TYPE_TRAIT(__is_fundamental);
773          REVERTABLE_TYPE_TRAIT(__is_integral);
774          REVERTABLE_TYPE_TRAIT(__is_member_function_pointer);
775          REVERTABLE_TYPE_TRAIT(__is_member_pointer);
776          REVERTABLE_TYPE_TRAIT(__is_pod);
777          REVERTABLE_TYPE_TRAIT(__is_pointer);
778          REVERTABLE_TYPE_TRAIT(__is_same);
779          REVERTABLE_TYPE_TRAIT(__is_scalar);
780          REVERTABLE_TYPE_TRAIT(__is_signed);
781          REVERTABLE_TYPE_TRAIT(__is_unsigned);
782          REVERTABLE_TYPE_TRAIT(__is_void);
783#undef REVERTABLE_TYPE_TRAIT
784#undef RTT_JOIN
785        }
786
787        // If we find that this is in fact the name of a type trait,
788        // update the token kind in place and parse again to treat it as
789        // the appropriate kind of type trait.
790        llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known
791          = RevertableTypeTraits.find(II);
792        if (Known != RevertableTypeTraits.end()) {
793          Tok.setKind(Known->second);
794          return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
795                                     NotCastExpr, isTypeCast);
796        }
797      }
798
799      if (Next.is(tok::coloncolon) ||
800          (!ColonIsSacred && Next.is(tok::colon)) ||
801          Next.is(tok::less) ||
802          Next.is(tok::l_paren) ||
803          Next.is(tok::l_brace)) {
804        // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
805        if (TryAnnotateTypeOrScopeToken())
806          return ExprError();
807        if (!Tok.is(tok::identifier))
808          return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
809      }
810    }
811
812    // Consume the identifier so that we can see if it is followed by a '(' or
813    // '.'.
814    IdentifierInfo &II = *Tok.getIdentifierInfo();
815    SourceLocation ILoc = ConsumeToken();
816
817    // Support 'Class.property' and 'super.property' notation.
818    if (getLangOpts().ObjC1 && Tok.is(tok::period) &&
819        (Actions.getTypeName(II, ILoc, getCurScope()) ||
820         // Allow the base to be 'super' if in an objc-method.
821         (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
822      ConsumeToken();
823
824      // Allow either an identifier or the keyword 'class' (in C++).
825      if (Tok.isNot(tok::identifier) &&
826          !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
827        Diag(Tok, diag::err_expected_property_name);
828        return ExprError();
829      }
830      IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
831      SourceLocation PropertyLoc = ConsumeToken();
832
833      Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName,
834                                              ILoc, PropertyLoc);
835      break;
836    }
837
838    // In an Objective-C method, if we have "super" followed by an identifier,
839    // the token sequence is ill-formed. However, if there's a ':' or ']' after
840    // that identifier, this is probably a message send with a missing open
841    // bracket. Treat it as such.
842    if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression &&
843        getCurScope()->isInObjcMethodScope() &&
844        ((Tok.is(tok::identifier) &&
845         (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
846         Tok.is(tok::code_completion))) {
847      Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(),
848                                           0);
849      break;
850    }
851
852    // If we have an Objective-C class name followed by an identifier
853    // and either ':' or ']', this is an Objective-C class message
854    // send that's missing the opening '['. Recovery
855    // appropriately. Also take this path if we're performing code
856    // completion after an Objective-C class name.
857    if (getLangOpts().ObjC1 &&
858        ((Tok.is(tok::identifier) && !InMessageExpression) ||
859         Tok.is(tok::code_completion))) {
860      const Token& Next = NextToken();
861      if (Tok.is(tok::code_completion) ||
862          Next.is(tok::colon) || Next.is(tok::r_square))
863        if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
864          if (Typ.get()->isObjCObjectOrInterfaceType()) {
865            // Fake up a Declarator to use with ActOnTypeName.
866            DeclSpec DS(AttrFactory);
867            DS.SetRangeStart(ILoc);
868            DS.SetRangeEnd(ILoc);
869            const char *PrevSpec = 0;
870            unsigned DiagID;
871            DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ);
872
873            Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
874            TypeResult Ty = Actions.ActOnTypeName(getCurScope(),
875                                                  DeclaratorInfo);
876            if (Ty.isInvalid())
877              break;
878
879            Res = ParseObjCMessageExpressionBody(SourceLocation(),
880                                                 SourceLocation(),
881                                                 Ty.get(), 0);
882            break;
883          }
884    }
885
886    // Make sure to pass down the right value for isAddressOfOperand.
887    if (isAddressOfOperand && isPostfixExpressionSuffixStart())
888      isAddressOfOperand = false;
889
890    // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
891    // need to know whether or not this identifier is a function designator or
892    // not.
893    UnqualifiedId Name;
894    CXXScopeSpec ScopeSpec;
895    SourceLocation TemplateKWLoc;
896    CastExpressionIdValidator Validator(isTypeCast != NotTypeCast,
897                                        isTypeCast != IsTypeCast);
898    Name.setIdentifier(&II, ILoc);
899    Res = Actions.ActOnIdExpression(getCurScope(), ScopeSpec, TemplateKWLoc,
900                                    Name, Tok.is(tok::l_paren),
901                                    isAddressOfOperand, &Validator);
902    break;
903  }
904  case tok::char_constant:     // constant: character-constant
905  case tok::wide_char_constant:
906  case tok::utf16_char_constant:
907  case tok::utf32_char_constant:
908    Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
909    ConsumeToken();
910    break;
911  case tok::kw___func__:       // primary-expression: __func__ [C99 6.4.2.2]
912  case tok::kw___FUNCTION__:   // primary-expression: __FUNCTION__ [GNU]
913  case tok::kw_L__FUNCTION__:   // primary-expression: L__FUNCTION__ [MS]
914  case tok::kw___PRETTY_FUNCTION__:  // primary-expression: __P..Y_F..N__ [GNU]
915    Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
916    ConsumeToken();
917    break;
918  case tok::string_literal:    // primary-expression: string-literal
919  case tok::wide_string_literal:
920  case tok::utf8_string_literal:
921  case tok::utf16_string_literal:
922  case tok::utf32_string_literal:
923    Res = ParseStringLiteralExpression(true);
924    break;
925  case tok::kw__Generic:   // primary-expression: generic-selection [C11 6.5.1]
926    Res = ParseGenericSelectionExpression();
927    break;
928  case tok::kw___builtin_va_arg:
929  case tok::kw___builtin_offsetof:
930  case tok::kw___builtin_choose_expr:
931  case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
932  case tok::kw___builtin_convertvector:
933    return ParseBuiltinPrimaryExpression();
934  case tok::kw___null:
935    return Actions.ActOnGNUNullExpr(ConsumeToken());
936
937  case tok::plusplus:      // unary-expression: '++' unary-expression [C99]
938  case tok::minusminus: {  // unary-expression: '--' unary-expression [C99]
939    // C++ [expr.unary] has:
940    //   unary-expression:
941    //     ++ cast-expression
942    //     -- cast-expression
943    SourceLocation SavedLoc = ConsumeToken();
944    Res = ParseCastExpression(!getLangOpts().CPlusPlus);
945    if (!Res.isInvalid())
946      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
947    return Res;
948  }
949  case tok::amp: {         // unary-expression: '&' cast-expression
950    // Special treatment because of member pointers
951    SourceLocation SavedLoc = ConsumeToken();
952    Res = ParseCastExpression(false, true);
953    if (!Res.isInvalid())
954      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
955    return Res;
956  }
957
958  case tok::star:          // unary-expression: '*' cast-expression
959  case tok::plus:          // unary-expression: '+' cast-expression
960  case tok::minus:         // unary-expression: '-' cast-expression
961  case tok::tilde:         // unary-expression: '~' cast-expression
962  case tok::exclaim:       // unary-expression: '!' cast-expression
963  case tok::kw___real:     // unary-expression: '__real' cast-expression [GNU]
964  case tok::kw___imag: {   // unary-expression: '__imag' cast-expression [GNU]
965    SourceLocation SavedLoc = ConsumeToken();
966    Res = ParseCastExpression(false);
967    if (!Res.isInvalid())
968      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
969    return Res;
970  }
971
972  case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
973    // __extension__ silences extension warnings in the subexpression.
974    ExtensionRAIIObject O(Diags);  // Use RAII to do this.
975    SourceLocation SavedLoc = ConsumeToken();
976    Res = ParseCastExpression(false);
977    if (!Res.isInvalid())
978      Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
979    return Res;
980  }
981  case tok::kw__Alignof:   // unary-expression: '_Alignof' '(' type-name ')'
982    if (!getLangOpts().C11)
983      Diag(Tok, diag::ext_c11_alignment) << Tok.getName();
984    // fallthrough
985  case tok::kw_alignof:    // unary-expression: 'alignof' '(' type-id ')'
986  case tok::kw___alignof:  // unary-expression: '__alignof' unary-expression
987                           // unary-expression: '__alignof' '(' type-name ')'
988  case tok::kw_sizeof:     // unary-expression: 'sizeof' unary-expression
989                           // unary-expression: 'sizeof' '(' type-name ')'
990  case tok::kw_vec_step:   // unary-expression: OpenCL 'vec_step' expression
991    return ParseUnaryExprOrTypeTraitExpression();
992  case tok::ampamp: {      // unary-expression: '&&' identifier
993    SourceLocation AmpAmpLoc = ConsumeToken();
994    if (Tok.isNot(tok::identifier))
995      return ExprError(Diag(Tok, diag::err_expected_ident));
996
997    if (getCurScope()->getFnParent() == 0)
998      return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
999
1000    Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1001    LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1002                                                Tok.getLocation());
1003    Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1004    ConsumeToken();
1005    return Res;
1006  }
1007  case tok::kw_const_cast:
1008  case tok::kw_dynamic_cast:
1009  case tok::kw_reinterpret_cast:
1010  case tok::kw_static_cast:
1011    Res = ParseCXXCasts();
1012    break;
1013  case tok::kw_typeid:
1014    Res = ParseCXXTypeid();
1015    break;
1016  case tok::kw___uuidof:
1017    Res = ParseCXXUuidof();
1018    break;
1019  case tok::kw_this:
1020    Res = ParseCXXThis();
1021    break;
1022
1023  case tok::annot_typename:
1024    if (isStartOfObjCClassMessageMissingOpenBracket()) {
1025      ParsedType Type = getTypeAnnotation(Tok);
1026
1027      // Fake up a Declarator to use with ActOnTypeName.
1028      DeclSpec DS(AttrFactory);
1029      DS.SetRangeStart(Tok.getLocation());
1030      DS.SetRangeEnd(Tok.getLastLoc());
1031
1032      const char *PrevSpec = 0;
1033      unsigned DiagID;
1034      DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1035                         PrevSpec, DiagID, Type);
1036
1037      Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1038      TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
1039      if (Ty.isInvalid())
1040        break;
1041
1042      ConsumeToken();
1043      Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1044                                           Ty.get(), 0);
1045      break;
1046    }
1047    // Fall through
1048
1049  case tok::annot_decltype:
1050  case tok::kw_char:
1051  case tok::kw_wchar_t:
1052  case tok::kw_char16_t:
1053  case tok::kw_char32_t:
1054  case tok::kw_bool:
1055  case tok::kw_short:
1056  case tok::kw_int:
1057  case tok::kw_long:
1058  case tok::kw___int64:
1059  case tok::kw___int128:
1060  case tok::kw_signed:
1061  case tok::kw_unsigned:
1062  case tok::kw_half:
1063  case tok::kw_float:
1064  case tok::kw_double:
1065  case tok::kw_void:
1066  case tok::kw_typename:
1067  case tok::kw_typeof:
1068  case tok::kw___vector:
1069  case tok::kw_image1d_t:
1070  case tok::kw_image1d_array_t:
1071  case tok::kw_image1d_buffer_t:
1072  case tok::kw_image2d_t:
1073  case tok::kw_image2d_array_t:
1074  case tok::kw_image3d_t:
1075  case tok::kw_sampler_t:
1076  case tok::kw_event_t: {
1077    if (!getLangOpts().CPlusPlus) {
1078      Diag(Tok, diag::err_expected_expression);
1079      return ExprError();
1080    }
1081
1082    if (SavedKind == tok::kw_typename) {
1083      // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1084      //                     typename-specifier braced-init-list
1085      if (TryAnnotateTypeOrScopeToken())
1086        return ExprError();
1087
1088      if (!Actions.isSimpleTypeSpecifier(Tok.getKind()))
1089        // We are trying to parse a simple-type-specifier but might not get such
1090        // a token after error recovery.
1091        return ExprError();
1092    }
1093
1094    // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1095    //                     simple-type-specifier braced-init-list
1096    //
1097    DeclSpec DS(AttrFactory);
1098
1099    ParseCXXSimpleTypeSpecifier(DS);
1100    if (Tok.isNot(tok::l_paren) &&
1101        (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1102      return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1103                         << DS.getSourceRange());
1104
1105    if (Tok.is(tok::l_brace))
1106      Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1107
1108    Res = ParseCXXTypeConstructExpression(DS);
1109    break;
1110  }
1111
1112  case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1113    // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1114    // (We can end up in this situation after tentative parsing.)
1115    if (TryAnnotateTypeOrScopeToken())
1116      return ExprError();
1117    if (!Tok.is(tok::annot_cxxscope))
1118      return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1119                                 NotCastExpr, isTypeCast);
1120
1121    Token Next = NextToken();
1122    if (Next.is(tok::annot_template_id)) {
1123      TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1124      if (TemplateId->Kind == TNK_Type_template) {
1125        // We have a qualified template-id that we know refers to a
1126        // type, translate it into a type and continue parsing as a
1127        // cast expression.
1128        CXXScopeSpec SS;
1129        ParseOptionalCXXScopeSpecifier(SS, ParsedType(),
1130                                       /*EnteringContext=*/false);
1131        AnnotateTemplateIdTokenAsType();
1132        return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1133                                   NotCastExpr, isTypeCast);
1134      }
1135    }
1136
1137    // Parse as an id-expression.
1138    Res = ParseCXXIdExpression(isAddressOfOperand);
1139    break;
1140  }
1141
1142  case tok::annot_template_id: { // [C++]          template-id
1143    TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1144    if (TemplateId->Kind == TNK_Type_template) {
1145      // We have a template-id that we know refers to a type,
1146      // translate it into a type and continue parsing as a cast
1147      // expression.
1148      AnnotateTemplateIdTokenAsType();
1149      return ParseCastExpression(isUnaryExpression, isAddressOfOperand,
1150                                 NotCastExpr, isTypeCast);
1151    }
1152
1153    // Fall through to treat the template-id as an id-expression.
1154  }
1155
1156  case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1157    Res = ParseCXXIdExpression(isAddressOfOperand);
1158    break;
1159
1160  case tok::coloncolon: {
1161    // ::foo::bar -> global qualified name etc.   If TryAnnotateTypeOrScopeToken
1162    // annotates the token, tail recurse.
1163    if (TryAnnotateTypeOrScopeToken())
1164      return ExprError();
1165    if (!Tok.is(tok::coloncolon))
1166      return ParseCastExpression(isUnaryExpression, isAddressOfOperand);
1167
1168    // ::new -> [C++] new-expression
1169    // ::delete -> [C++] delete-expression
1170    SourceLocation CCLoc = ConsumeToken();
1171    if (Tok.is(tok::kw_new))
1172      return ParseCXXNewExpression(true, CCLoc);
1173    if (Tok.is(tok::kw_delete))
1174      return ParseCXXDeleteExpression(true, CCLoc);
1175
1176    // This is not a type name or scope specifier, it is an invalid expression.
1177    Diag(CCLoc, diag::err_expected_expression);
1178    return ExprError();
1179  }
1180
1181  case tok::kw_new: // [C++] new-expression
1182    return ParseCXXNewExpression(false, Tok.getLocation());
1183
1184  case tok::kw_delete: // [C++] delete-expression
1185    return ParseCXXDeleteExpression(false, Tok.getLocation());
1186
1187  case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1188    Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1189    SourceLocation KeyLoc = ConsumeToken();
1190    BalancedDelimiterTracker T(*this, tok::l_paren);
1191
1192    if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1193      return ExprError();
1194    // C++11 [expr.unary.noexcept]p1:
1195    //   The noexcept operator determines whether the evaluation of its operand,
1196    //   which is an unevaluated operand, can throw an exception.
1197    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1198    ExprResult Result = ParseExpression();
1199
1200    T.consumeClose();
1201
1202    if (!Result.isInvalid())
1203      Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(),
1204                                         Result.take(), T.getCloseLocation());
1205    return Result;
1206  }
1207
1208  case tok::kw___is_abstract: // [GNU] unary-type-trait
1209  case tok::kw___is_class:
1210  case tok::kw___is_empty:
1211  case tok::kw___is_enum:
1212  case tok::kw___is_interface_class:
1213  case tok::kw___is_literal:
1214  case tok::kw___is_arithmetic:
1215  case tok::kw___is_integral:
1216  case tok::kw___is_floating_point:
1217  case tok::kw___is_complete_type:
1218  case tok::kw___is_void:
1219  case tok::kw___is_array:
1220  case tok::kw___is_function:
1221  case tok::kw___is_reference:
1222  case tok::kw___is_lvalue_reference:
1223  case tok::kw___is_rvalue_reference:
1224  case tok::kw___is_fundamental:
1225  case tok::kw___is_object:
1226  case tok::kw___is_scalar:
1227  case tok::kw___is_compound:
1228  case tok::kw___is_pointer:
1229  case tok::kw___is_member_object_pointer:
1230  case tok::kw___is_member_function_pointer:
1231  case tok::kw___is_member_pointer:
1232  case tok::kw___is_const:
1233  case tok::kw___is_volatile:
1234  case tok::kw___is_standard_layout:
1235  case tok::kw___is_signed:
1236  case tok::kw___is_unsigned:
1237  case tok::kw___is_literal_type:
1238  case tok::kw___is_pod:
1239  case tok::kw___is_polymorphic:
1240  case tok::kw___is_trivial:
1241  case tok::kw___is_trivially_copyable:
1242  case tok::kw___is_union:
1243  case tok::kw___is_final:
1244  case tok::kw___is_sealed:
1245  case tok::kw___has_trivial_constructor:
1246  case tok::kw___has_trivial_move_constructor:
1247  case tok::kw___has_trivial_copy:
1248  case tok::kw___has_trivial_assign:
1249  case tok::kw___has_trivial_move_assign:
1250  case tok::kw___has_trivial_destructor:
1251  case tok::kw___has_nothrow_assign:
1252  case tok::kw___has_nothrow_move_assign:
1253  case tok::kw___has_nothrow_copy:
1254  case tok::kw___has_nothrow_constructor:
1255  case tok::kw___has_virtual_destructor:
1256    return ParseUnaryTypeTrait();
1257
1258  case tok::kw___builtin_types_compatible_p:
1259  case tok::kw___is_base_of:
1260  case tok::kw___is_same:
1261  case tok::kw___is_convertible:
1262  case tok::kw___is_convertible_to:
1263  case tok::kw___is_trivially_assignable:
1264    return ParseBinaryTypeTrait();
1265
1266  case tok::kw___is_trivially_constructible:
1267    return ParseTypeTrait();
1268
1269  case tok::kw___array_rank:
1270  case tok::kw___array_extent:
1271    return ParseArrayTypeTrait();
1272
1273  case tok::kw___is_lvalue_expr:
1274  case tok::kw___is_rvalue_expr:
1275    return ParseExpressionTrait();
1276
1277  case tok::at: {
1278    SourceLocation AtLoc = ConsumeToken();
1279    return ParseObjCAtExpression(AtLoc);
1280  }
1281  case tok::caret:
1282    Res = ParseBlockLiteralExpression();
1283    break;
1284  case tok::code_completion: {
1285    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
1286    cutOffParsing();
1287    return ExprError();
1288  }
1289  case tok::l_square:
1290    if (getLangOpts().CPlusPlus11) {
1291      if (getLangOpts().ObjC1) {
1292        // C++11 lambda expressions and Objective-C message sends both start with a
1293        // square bracket.  There are three possibilities here:
1294        // we have a valid lambda expression, we have an invalid lambda
1295        // expression, or we have something that doesn't appear to be a lambda.
1296        // If we're in the last case, we fall back to ParseObjCMessageExpression.
1297        Res = TryParseLambdaExpression();
1298        if (!Res.isInvalid() && !Res.get())
1299          Res = ParseObjCMessageExpression();
1300        break;
1301      }
1302      Res = ParseLambdaExpression();
1303      break;
1304    }
1305    if (getLangOpts().ObjC1) {
1306      Res = ParseObjCMessageExpression();
1307      break;
1308    }
1309    // FALL THROUGH.
1310  default:
1311    NotCastExpr = true;
1312    return ExprError();
1313  }
1314
1315  // These can be followed by postfix-expr pieces.
1316  return ParsePostfixExpressionSuffix(Res);
1317}
1318
1319/// \brief Once the leading part of a postfix-expression is parsed, this
1320/// method parses any suffixes that apply.
1321///
1322/// \verbatim
1323///       postfix-expression: [C99 6.5.2]
1324///         primary-expression
1325///         postfix-expression '[' expression ']'
1326///         postfix-expression '[' braced-init-list ']'
1327///         postfix-expression '(' argument-expression-list[opt] ')'
1328///         postfix-expression '.' identifier
1329///         postfix-expression '->' identifier
1330///         postfix-expression '++'
1331///         postfix-expression '--'
1332///         '(' type-name ')' '{' initializer-list '}'
1333///         '(' type-name ')' '{' initializer-list ',' '}'
1334///
1335///       argument-expression-list: [C99 6.5.2]
1336///         argument-expression ...[opt]
1337///         argument-expression-list ',' assignment-expression ...[opt]
1338/// \endverbatim
1339ExprResult
1340Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
1341  // Now that the primary-expression piece of the postfix-expression has been
1342  // parsed, see if there are any postfix-expression pieces here.
1343  SourceLocation Loc;
1344  while (1) {
1345    switch (Tok.getKind()) {
1346    case tok::code_completion:
1347      if (InMessageExpression)
1348        return LHS;
1349
1350      Actions.CodeCompletePostfixExpression(getCurScope(), LHS);
1351      cutOffParsing();
1352      return ExprError();
1353
1354    case tok::identifier:
1355      // If we see identifier: after an expression, and we're not already in a
1356      // message send, then this is probably a message send with a missing
1357      // opening bracket '['.
1358      if (getLangOpts().ObjC1 && !InMessageExpression &&
1359          (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
1360        LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1361                                             ParsedType(), LHS.get());
1362        break;
1363      }
1364
1365      // Fall through; this isn't a message send.
1366
1367    default:  // Not a postfix-expression suffix.
1368      return LHS;
1369    case tok::l_square: {  // postfix-expression: p-e '[' expression ']'
1370      // If we have a array postfix expression that starts on a new line and
1371      // Objective-C is enabled, it is highly likely that the user forgot a
1372      // semicolon after the base expression and that the array postfix-expr is
1373      // actually another message send.  In this case, do some look-ahead to see
1374      // if the contents of the square brackets are obviously not a valid
1375      // expression and recover by pretending there is no suffix.
1376      if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() &&
1377          isSimpleObjCMessageExpression())
1378        return LHS;
1379
1380      // Reject array indices starting with a lambda-expression. '[[' is
1381      // reserved for attributes.
1382      if (CheckProhibitedCXX11Attribute())
1383        return ExprError();
1384
1385      BalancedDelimiterTracker T(*this, tok::l_square);
1386      T.consumeOpen();
1387      Loc = T.getOpenLocation();
1388      ExprResult Idx;
1389      if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
1390        Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1391        Idx = ParseBraceInitializer();
1392      } else
1393        Idx = ParseExpression();
1394
1395      SourceLocation RLoc = Tok.getLocation();
1396
1397      if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) {
1398        LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.take(), Loc,
1399                                              Idx.take(), RLoc);
1400      } else
1401        LHS = ExprError();
1402
1403      // Match the ']'.
1404      T.consumeClose();
1405      break;
1406    }
1407
1408    case tok::l_paren:         // p-e: p-e '(' argument-expression-list[opt] ')'
1409    case tok::lesslessless: {  // p-e: p-e '<<<' argument-expression-list '>>>'
1410                               //   '(' argument-expression-list[opt] ')'
1411      tok::TokenKind OpKind = Tok.getKind();
1412      InMessageExpressionRAIIObject InMessage(*this, false);
1413
1414      Expr *ExecConfig = 0;
1415
1416      BalancedDelimiterTracker PT(*this, tok::l_paren);
1417
1418      if (OpKind == tok::lesslessless) {
1419        ExprVector ExecConfigExprs;
1420        CommaLocsTy ExecConfigCommaLocs;
1421        SourceLocation OpenLoc = ConsumeToken();
1422
1423        if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) {
1424          LHS = ExprError();
1425        }
1426
1427        SourceLocation CloseLoc = Tok.getLocation();
1428        if (Tok.is(tok::greatergreatergreater)) {
1429          ConsumeToken();
1430        } else if (LHS.isInvalid()) {
1431          SkipUntil(tok::greatergreatergreater);
1432        } else {
1433          // There was an error closing the brackets
1434          Diag(Tok, diag::err_expected_ggg);
1435          Diag(OpenLoc, diag::note_matching) << "<<<";
1436          SkipUntil(tok::greatergreatergreater);
1437          LHS = ExprError();
1438        }
1439
1440        if (!LHS.isInvalid()) {
1441          if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen, ""))
1442            LHS = ExprError();
1443          else
1444            Loc = PrevTokLocation;
1445        }
1446
1447        if (!LHS.isInvalid()) {
1448          ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(),
1449                                    OpenLoc,
1450                                    ExecConfigExprs,
1451                                    CloseLoc);
1452          if (ECResult.isInvalid())
1453            LHS = ExprError();
1454          else
1455            ExecConfig = ECResult.get();
1456        }
1457      } else {
1458        PT.consumeOpen();
1459        Loc = PT.getOpenLocation();
1460      }
1461
1462      ExprVector ArgExprs;
1463      CommaLocsTy CommaLocs;
1464
1465      if (Tok.is(tok::code_completion)) {
1466        Actions.CodeCompleteCall(getCurScope(), LHS.get(), None);
1467        cutOffParsing();
1468        return ExprError();
1469      }
1470
1471      if (OpKind == tok::l_paren || !LHS.isInvalid()) {
1472        if (Tok.isNot(tok::r_paren)) {
1473          if (ParseExpressionList(ArgExprs, CommaLocs, &Sema::CodeCompleteCall,
1474                                  LHS.get())) {
1475            LHS = ExprError();
1476          }
1477        }
1478      }
1479
1480      // Match the ')'.
1481      if (LHS.isInvalid()) {
1482        SkipUntil(tok::r_paren);
1483      } else if (Tok.isNot(tok::r_paren)) {
1484        PT.consumeClose();
1485        LHS = ExprError();
1486      } else {
1487        assert((ArgExprs.size() == 0 ||
1488                ArgExprs.size()-1 == CommaLocs.size())&&
1489               "Unexpected number of commas!");
1490        LHS = Actions.ActOnCallExpr(getCurScope(), LHS.take(), Loc,
1491                                    ArgExprs, Tok.getLocation(),
1492                                    ExecConfig);
1493        PT.consumeClose();
1494      }
1495
1496      break;
1497    }
1498    case tok::arrow:
1499    case tok::period: {
1500      // postfix-expression: p-e '->' template[opt] id-expression
1501      // postfix-expression: p-e '.' template[opt] id-expression
1502      tok::TokenKind OpKind = Tok.getKind();
1503      SourceLocation OpLoc = ConsumeToken();  // Eat the "." or "->" token.
1504
1505      CXXScopeSpec SS;
1506      ParsedType ObjectType;
1507      bool MayBePseudoDestructor = false;
1508      if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
1509        Expr *Base = LHS.take();
1510        const Type* BaseType = Base->getType().getTypePtrOrNull();
1511        if (BaseType && Tok.is(tok::l_paren) &&
1512            (BaseType->isFunctionType() ||
1513             BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
1514          Diag(OpLoc, diag::err_function_is_not_record)
1515            << (OpKind == tok::arrow) << Base->getSourceRange()
1516            << FixItHint::CreateRemoval(OpLoc);
1517          return ParsePostfixExpressionSuffix(Base);
1518        }
1519
1520        LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base,
1521                                                   OpLoc, OpKind, ObjectType,
1522                                                   MayBePseudoDestructor);
1523        if (LHS.isInvalid())
1524          break;
1525
1526        ParseOptionalCXXScopeSpecifier(SS, ObjectType,
1527                                       /*EnteringContext=*/false,
1528                                       &MayBePseudoDestructor);
1529        if (SS.isNotEmpty())
1530          ObjectType = ParsedType();
1531      }
1532
1533      if (Tok.is(tok::code_completion)) {
1534        // Code completion for a member access expression.
1535        Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(),
1536                                                OpLoc, OpKind == tok::arrow);
1537
1538        cutOffParsing();
1539        return ExprError();
1540      }
1541
1542      if (MayBePseudoDestructor && !LHS.isInvalid()) {
1543        LHS = ParseCXXPseudoDestructor(LHS.take(), OpLoc, OpKind, SS,
1544                                       ObjectType);
1545        break;
1546      }
1547
1548      // Either the action has told is that this cannot be a
1549      // pseudo-destructor expression (based on the type of base
1550      // expression), or we didn't see a '~' in the right place. We
1551      // can still parse a destructor name here, but in that case it
1552      // names a real destructor.
1553      // Allow explicit constructor calls in Microsoft mode.
1554      // FIXME: Add support for explicit call of template constructor.
1555      SourceLocation TemplateKWLoc;
1556      UnqualifiedId Name;
1557      if (getLangOpts().ObjC2 && OpKind == tok::period && Tok.is(tok::kw_class)) {
1558        // Objective-C++:
1559        //   After a '.' in a member access expression, treat the keyword
1560        //   'class' as if it were an identifier.
1561        //
1562        // This hack allows property access to the 'class' method because it is
1563        // such a common method name. For other C++ keywords that are
1564        // Objective-C method names, one must use the message send syntax.
1565        IdentifierInfo *Id = Tok.getIdentifierInfo();
1566        SourceLocation Loc = ConsumeToken();
1567        Name.setIdentifier(Id, Loc);
1568      } else if (ParseUnqualifiedId(SS,
1569                                    /*EnteringContext=*/false,
1570                                    /*AllowDestructorName=*/true,
1571                                    /*AllowConstructorName=*/
1572                                      getLangOpts().MicrosoftExt,
1573                                    ObjectType, TemplateKWLoc, Name))
1574        LHS = ExprError();
1575
1576      if (!LHS.isInvalid())
1577        LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.take(), OpLoc,
1578                                            OpKind, SS, TemplateKWLoc, Name,
1579                                 CurParsedObjCImpl ? CurParsedObjCImpl->Dcl : 0,
1580                                            Tok.is(tok::l_paren));
1581      break;
1582    }
1583    case tok::plusplus:    // postfix-expression: postfix-expression '++'
1584    case tok::minusminus:  // postfix-expression: postfix-expression '--'
1585      if (!LHS.isInvalid()) {
1586        LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
1587                                          Tok.getKind(), LHS.take());
1588      }
1589      ConsumeToken();
1590      break;
1591    }
1592  }
1593}
1594
1595/// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
1596/// vec_step and we are at the start of an expression or a parenthesized
1597/// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
1598/// expression (isCastExpr == false) or the type (isCastExpr == true).
1599///
1600/// \verbatim
1601///       unary-expression:  [C99 6.5.3]
1602///         'sizeof' unary-expression
1603///         'sizeof' '(' type-name ')'
1604/// [GNU]   '__alignof' unary-expression
1605/// [GNU]   '__alignof' '(' type-name ')'
1606/// [C11]   '_Alignof' '(' type-name ')'
1607/// [C++0x] 'alignof' '(' type-id ')'
1608///
1609/// [GNU]   typeof-specifier:
1610///           typeof ( expressions )
1611///           typeof ( type-name )
1612/// [GNU/C++] typeof unary-expression
1613///
1614/// [OpenCL 1.1 6.11.12] vec_step built-in function:
1615///           vec_step ( expressions )
1616///           vec_step ( type-name )
1617/// \endverbatim
1618ExprResult
1619Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
1620                                           bool &isCastExpr,
1621                                           ParsedType &CastTy,
1622                                           SourceRange &CastRange) {
1623
1624  assert((OpTok.is(tok::kw_typeof)    || OpTok.is(tok::kw_sizeof) ||
1625          OpTok.is(tok::kw___alignof) || OpTok.is(tok::kw_alignof) ||
1626          OpTok.is(tok::kw__Alignof)  || OpTok.is(tok::kw_vec_step)) &&
1627          "Not a typeof/sizeof/alignof/vec_step expression!");
1628
1629  ExprResult Operand;
1630
1631  // If the operand doesn't start with an '(', it must be an expression.
1632  if (Tok.isNot(tok::l_paren)) {
1633    // If construct allows a form without parenthesis, user may forget to put
1634    // pathenthesis around type name.
1635    if (OpTok.is(tok::kw_sizeof)  || OpTok.is(tok::kw___alignof) ||
1636        OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw__Alignof)) {
1637      bool isAmbiguousTypeId;
1638      if (isTypeIdInParens(isAmbiguousTypeId)) {
1639        DeclSpec DS(AttrFactory);
1640        ParseSpecifierQualifierList(DS);
1641        Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1642        ParseDeclarator(DeclaratorInfo);
1643
1644        SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
1645        SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
1646        Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
1647          << OpTok.getName()
1648          << FixItHint::CreateInsertion(LParenLoc, "(")
1649          << FixItHint::CreateInsertion(RParenLoc, ")");
1650        isCastExpr = true;
1651        return ExprEmpty();
1652      }
1653    }
1654
1655    isCastExpr = false;
1656    if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) {
1657      Diag(Tok,diag::err_expected_lparen_after_id) << OpTok.getIdentifierInfo();
1658      return ExprError();
1659    }
1660
1661    Operand = ParseCastExpression(true/*isUnaryExpression*/);
1662  } else {
1663    // If it starts with a '(', we know that it is either a parenthesized
1664    // type-name, or it is a unary-expression that starts with a compound
1665    // literal, or starts with a primary-expression that is a parenthesized
1666    // expression.
1667    ParenParseOption ExprType = CastExpr;
1668    SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
1669
1670    Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
1671                                   false, CastTy, RParenLoc);
1672    CastRange = SourceRange(LParenLoc, RParenLoc);
1673
1674    // If ParseParenExpression parsed a '(typename)' sequence only, then this is
1675    // a type.
1676    if (ExprType == CastExpr) {
1677      isCastExpr = true;
1678      return ExprEmpty();
1679    }
1680
1681    if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) {
1682      // GNU typeof in C requires the expression to be parenthesized. Not so for
1683      // sizeof/alignof or in C++. Therefore, the parenthesized expression is
1684      // the start of a unary-expression, but doesn't include any postfix
1685      // pieces. Parse these now if present.
1686      if (!Operand.isInvalid())
1687        Operand = ParsePostfixExpressionSuffix(Operand.get());
1688    }
1689  }
1690
1691  // If we get here, the operand to the typeof/sizeof/alignof was an expresion.
1692  isCastExpr = false;
1693  return Operand;
1694}
1695
1696
1697/// \brief Parse a sizeof or alignof expression.
1698///
1699/// \verbatim
1700///       unary-expression:  [C99 6.5.3]
1701///         'sizeof' unary-expression
1702///         'sizeof' '(' type-name ')'
1703/// [C++11] 'sizeof' '...' '(' identifier ')'
1704/// [GNU]   '__alignof' unary-expression
1705/// [GNU]   '__alignof' '(' type-name ')'
1706/// [C11]   '_Alignof' '(' type-name ')'
1707/// [C++11] 'alignof' '(' type-id ')'
1708/// \endverbatim
1709ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
1710  assert((Tok.is(tok::kw_sizeof) || Tok.is(tok::kw___alignof) ||
1711          Tok.is(tok::kw_alignof) || Tok.is(tok::kw__Alignof) ||
1712          Tok.is(tok::kw_vec_step)) &&
1713         "Not a sizeof/alignof/vec_step expression!");
1714  Token OpTok = Tok;
1715  ConsumeToken();
1716
1717  // [C++11] 'sizeof' '...' '(' identifier ')'
1718  if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
1719    SourceLocation EllipsisLoc = ConsumeToken();
1720    SourceLocation LParenLoc, RParenLoc;
1721    IdentifierInfo *Name = 0;
1722    SourceLocation NameLoc;
1723    if (Tok.is(tok::l_paren)) {
1724      BalancedDelimiterTracker T(*this, tok::l_paren);
1725      T.consumeOpen();
1726      LParenLoc = T.getOpenLocation();
1727      if (Tok.is(tok::identifier)) {
1728        Name = Tok.getIdentifierInfo();
1729        NameLoc = ConsumeToken();
1730        T.consumeClose();
1731        RParenLoc = T.getCloseLocation();
1732        if (RParenLoc.isInvalid())
1733          RParenLoc = PP.getLocForEndOfToken(NameLoc);
1734      } else {
1735        Diag(Tok, diag::err_expected_parameter_pack);
1736        SkipUntil(tok::r_paren);
1737      }
1738    } else if (Tok.is(tok::identifier)) {
1739      Name = Tok.getIdentifierInfo();
1740      NameLoc = ConsumeToken();
1741      LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
1742      RParenLoc = PP.getLocForEndOfToken(NameLoc);
1743      Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
1744        << Name
1745        << FixItHint::CreateInsertion(LParenLoc, "(")
1746        << FixItHint::CreateInsertion(RParenLoc, ")");
1747    } else {
1748      Diag(Tok, diag::err_sizeof_parameter_pack);
1749    }
1750
1751    if (!Name)
1752      return ExprError();
1753
1754    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1755                                                 Sema::ReuseLambdaContextDecl);
1756
1757    return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
1758                                                OpTok.getLocation(),
1759                                                *Name, NameLoc,
1760                                                RParenLoc);
1761  }
1762
1763  if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw__Alignof))
1764    Diag(OpTok, diag::warn_cxx98_compat_alignof);
1765
1766  EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1767                                               Sema::ReuseLambdaContextDecl);
1768
1769  bool isCastExpr;
1770  ParsedType CastTy;
1771  SourceRange CastRange;
1772  ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
1773                                                          isCastExpr,
1774                                                          CastTy,
1775                                                          CastRange);
1776
1777  UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
1778  if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw___alignof) ||
1779      OpTok.is(tok::kw__Alignof))
1780    ExprKind = UETT_AlignOf;
1781  else if (OpTok.is(tok::kw_vec_step))
1782    ExprKind = UETT_VecStep;
1783
1784  if (isCastExpr)
1785    return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1786                                                 ExprKind,
1787                                                 /*isType=*/true,
1788                                                 CastTy.getAsOpaquePtr(),
1789                                                 CastRange);
1790
1791  if (OpTok.is(tok::kw_alignof) || OpTok.is(tok::kw__Alignof))
1792    Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
1793
1794  // If we get here, the operand to the sizeof/alignof was an expresion.
1795  if (!Operand.isInvalid())
1796    Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
1797                                                    ExprKind,
1798                                                    /*isType=*/false,
1799                                                    Operand.release(),
1800                                                    CastRange);
1801  return Operand;
1802}
1803
1804/// ParseBuiltinPrimaryExpression
1805///
1806/// \verbatim
1807///       primary-expression: [C99 6.5.1]
1808/// [GNU]   '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
1809/// [GNU]   '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
1810/// [GNU]   '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
1811///                                     assign-expr ')'
1812/// [GNU]   '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
1813/// [OCL]   '__builtin_astype' '(' assignment-expression ',' type-name ')'
1814///
1815/// [GNU] offsetof-member-designator:
1816/// [GNU]   identifier
1817/// [GNU]   offsetof-member-designator '.' identifier
1818/// [GNU]   offsetof-member-designator '[' expression ']'
1819/// \endverbatim
1820ExprResult Parser::ParseBuiltinPrimaryExpression() {
1821  ExprResult Res;
1822  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
1823
1824  tok::TokenKind T = Tok.getKind();
1825  SourceLocation StartLoc = ConsumeToken();   // Eat the builtin identifier.
1826
1827  // All of these start with an open paren.
1828  if (Tok.isNot(tok::l_paren))
1829    return ExprError(Diag(Tok, diag::err_expected_lparen_after_id)
1830                       << BuiltinII);
1831
1832  BalancedDelimiterTracker PT(*this, tok::l_paren);
1833  PT.consumeOpen();
1834
1835  // TODO: Build AST.
1836
1837  switch (T) {
1838  default: llvm_unreachable("Not a builtin primary expression!");
1839  case tok::kw___builtin_va_arg: {
1840    ExprResult Expr(ParseAssignmentExpression());
1841
1842    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1843      Expr = ExprError();
1844
1845    TypeResult Ty = ParseTypeName();
1846
1847    if (Tok.isNot(tok::r_paren)) {
1848      Diag(Tok, diag::err_expected_rparen);
1849      Expr = ExprError();
1850    }
1851
1852    if (Expr.isInvalid() || Ty.isInvalid())
1853      Res = ExprError();
1854    else
1855      Res = Actions.ActOnVAArg(StartLoc, Expr.take(), Ty.get(), ConsumeParen());
1856    break;
1857  }
1858  case tok::kw___builtin_offsetof: {
1859    SourceLocation TypeLoc = Tok.getLocation();
1860    TypeResult Ty = ParseTypeName();
1861    if (Ty.isInvalid()) {
1862      SkipUntil(tok::r_paren);
1863      return ExprError();
1864    }
1865
1866    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1867      return ExprError();
1868
1869    // We must have at least one identifier here.
1870    if (Tok.isNot(tok::identifier)) {
1871      Diag(Tok, diag::err_expected_ident);
1872      SkipUntil(tok::r_paren);
1873      return ExprError();
1874    }
1875
1876    // Keep track of the various subcomponents we see.
1877    SmallVector<Sema::OffsetOfComponent, 4> Comps;
1878
1879    Comps.push_back(Sema::OffsetOfComponent());
1880    Comps.back().isBrackets = false;
1881    Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1882    Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
1883
1884    // FIXME: This loop leaks the index expressions on error.
1885    while (1) {
1886      if (Tok.is(tok::period)) {
1887        // offsetof-member-designator: offsetof-member-designator '.' identifier
1888        Comps.push_back(Sema::OffsetOfComponent());
1889        Comps.back().isBrackets = false;
1890        Comps.back().LocStart = ConsumeToken();
1891
1892        if (Tok.isNot(tok::identifier)) {
1893          Diag(Tok, diag::err_expected_ident);
1894          SkipUntil(tok::r_paren);
1895          return ExprError();
1896        }
1897        Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
1898        Comps.back().LocEnd = ConsumeToken();
1899
1900      } else if (Tok.is(tok::l_square)) {
1901        if (CheckProhibitedCXX11Attribute())
1902          return ExprError();
1903
1904        // offsetof-member-designator: offsetof-member-design '[' expression ']'
1905        Comps.push_back(Sema::OffsetOfComponent());
1906        Comps.back().isBrackets = true;
1907        BalancedDelimiterTracker ST(*this, tok::l_square);
1908        ST.consumeOpen();
1909        Comps.back().LocStart = ST.getOpenLocation();
1910        Res = ParseExpression();
1911        if (Res.isInvalid()) {
1912          SkipUntil(tok::r_paren);
1913          return Res;
1914        }
1915        Comps.back().U.E = Res.release();
1916
1917        ST.consumeClose();
1918        Comps.back().LocEnd = ST.getCloseLocation();
1919      } else {
1920        if (Tok.isNot(tok::r_paren)) {
1921          PT.consumeClose();
1922          Res = ExprError();
1923        } else if (Ty.isInvalid()) {
1924          Res = ExprError();
1925        } else {
1926          PT.consumeClose();
1927          Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
1928                                             Ty.get(), &Comps[0], Comps.size(),
1929                                             PT.getCloseLocation());
1930        }
1931        break;
1932      }
1933    }
1934    break;
1935  }
1936  case tok::kw___builtin_choose_expr: {
1937    ExprResult Cond(ParseAssignmentExpression());
1938    if (Cond.isInvalid()) {
1939      SkipUntil(tok::r_paren);
1940      return Cond;
1941    }
1942    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1943      return ExprError();
1944
1945    ExprResult Expr1(ParseAssignmentExpression());
1946    if (Expr1.isInvalid()) {
1947      SkipUntil(tok::r_paren);
1948      return Expr1;
1949    }
1950    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",tok::r_paren))
1951      return ExprError();
1952
1953    ExprResult Expr2(ParseAssignmentExpression());
1954    if (Expr2.isInvalid()) {
1955      SkipUntil(tok::r_paren);
1956      return Expr2;
1957    }
1958    if (Tok.isNot(tok::r_paren)) {
1959      Diag(Tok, diag::err_expected_rparen);
1960      return ExprError();
1961    }
1962    Res = Actions.ActOnChooseExpr(StartLoc, Cond.take(), Expr1.take(),
1963                                  Expr2.take(), ConsumeParen());
1964    break;
1965  }
1966  case tok::kw___builtin_astype: {
1967    // The first argument is an expression to be converted, followed by a comma.
1968    ExprResult Expr(ParseAssignmentExpression());
1969    if (Expr.isInvalid()) {
1970      SkipUntil(tok::r_paren);
1971      return ExprError();
1972    }
1973
1974    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",
1975                         tok::r_paren))
1976      return ExprError();
1977
1978    // Second argument is the type to bitcast to.
1979    TypeResult DestTy = ParseTypeName();
1980    if (DestTy.isInvalid())
1981      return ExprError();
1982
1983    // Attempt to consume the r-paren.
1984    if (Tok.isNot(tok::r_paren)) {
1985      Diag(Tok, diag::err_expected_rparen);
1986      SkipUntil(tok::r_paren);
1987      return ExprError();
1988    }
1989
1990    Res = Actions.ActOnAsTypeExpr(Expr.take(), DestTy.get(), StartLoc,
1991                                  ConsumeParen());
1992    break;
1993  }
1994  case tok::kw___builtin_convertvector: {
1995    // The first argument is an expression to be converted, followed by a comma.
1996    ExprResult Expr(ParseAssignmentExpression());
1997    if (Expr.isInvalid()) {
1998      SkipUntil(tok::r_paren);
1999      return ExprError();
2000    }
2001
2002    if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "",
2003                         tok::r_paren))
2004      return ExprError();
2005
2006    // Second argument is the type to bitcast to.
2007    TypeResult DestTy = ParseTypeName();
2008    if (DestTy.isInvalid())
2009      return ExprError();
2010
2011    // Attempt to consume the r-paren.
2012    if (Tok.isNot(tok::r_paren)) {
2013      Diag(Tok, diag::err_expected_rparen);
2014      SkipUntil(tok::r_paren);
2015      return ExprError();
2016    }
2017
2018    Res = Actions.ActOnConvertVectorExpr(Expr.take(), DestTy.get(), StartLoc,
2019                                         ConsumeParen());
2020    break;
2021  }
2022  }
2023
2024  if (Res.isInvalid())
2025    return ExprError();
2026
2027  // These can be followed by postfix-expr pieces because they are
2028  // primary-expressions.
2029  return ParsePostfixExpressionSuffix(Res.take());
2030}
2031
2032/// ParseParenExpression - This parses the unit that starts with a '(' token,
2033/// based on what is allowed by ExprType.  The actual thing parsed is returned
2034/// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
2035/// not the parsed cast-expression.
2036///
2037/// \verbatim
2038///       primary-expression: [C99 6.5.1]
2039///         '(' expression ')'
2040/// [GNU]   '(' compound-statement ')'      (if !ParenExprOnly)
2041///       postfix-expression: [C99 6.5.2]
2042///         '(' type-name ')' '{' initializer-list '}'
2043///         '(' type-name ')' '{' initializer-list ',' '}'
2044///       cast-expression: [C99 6.5.4]
2045///         '(' type-name ')' cast-expression
2046/// [ARC]   bridged-cast-expression
2047///
2048/// [ARC] bridged-cast-expression:
2049///         (__bridge type-name) cast-expression
2050///         (__bridge_transfer type-name) cast-expression
2051///         (__bridge_retained type-name) cast-expression
2052/// \endverbatim
2053ExprResult
2054Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
2055                             bool isTypeCast, ParsedType &CastTy,
2056                             SourceLocation &RParenLoc) {
2057  assert(Tok.is(tok::l_paren) && "Not a paren expr!");
2058  BalancedDelimiterTracker T(*this, tok::l_paren);
2059  if (T.consumeOpen())
2060    return ExprError();
2061  SourceLocation OpenLoc = T.getOpenLocation();
2062
2063  ExprResult Result(true);
2064  bool isAmbiguousTypeId;
2065  CastTy = ParsedType();
2066
2067  if (Tok.is(tok::code_completion)) {
2068    Actions.CodeCompleteOrdinaryName(getCurScope(),
2069                 ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression
2070                                            : Sema::PCC_Expression);
2071    cutOffParsing();
2072    return ExprError();
2073  }
2074
2075  // Diagnose use of bridge casts in non-arc mode.
2076  bool BridgeCast = (getLangOpts().ObjC2 &&
2077                     (Tok.is(tok::kw___bridge) ||
2078                      Tok.is(tok::kw___bridge_transfer) ||
2079                      Tok.is(tok::kw___bridge_retained) ||
2080                      Tok.is(tok::kw___bridge_retain)));
2081  if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
2082    if (Tok.isNot(tok::kw___bridge)) {
2083      StringRef BridgeCastName = Tok.getName();
2084      SourceLocation BridgeKeywordLoc = ConsumeToken();
2085      if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2086        Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
2087          << BridgeCastName
2088          << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
2089    }
2090    else
2091      ConsumeToken(); // consume __bridge
2092    BridgeCast = false;
2093  }
2094
2095  // None of these cases should fall through with an invalid Result
2096  // unless they've already reported an error.
2097  if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
2098    Diag(Tok, diag::ext_gnu_statement_expr);
2099    Actions.ActOnStartStmtExpr();
2100
2101    StmtResult Stmt(ParseCompoundStatement(true));
2102    ExprType = CompoundStmt;
2103
2104    // If the substmt parsed correctly, build the AST node.
2105    if (!Stmt.isInvalid()) {
2106      Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.take(), Tok.getLocation());
2107    } else {
2108      Actions.ActOnStmtExprError();
2109    }
2110  } else if (ExprType >= CompoundLiteral && BridgeCast) {
2111    tok::TokenKind tokenKind = Tok.getKind();
2112    SourceLocation BridgeKeywordLoc = ConsumeToken();
2113
2114    // Parse an Objective-C ARC ownership cast expression.
2115    ObjCBridgeCastKind Kind;
2116    if (tokenKind == tok::kw___bridge)
2117      Kind = OBC_Bridge;
2118    else if (tokenKind == tok::kw___bridge_transfer)
2119      Kind = OBC_BridgeTransfer;
2120    else if (tokenKind == tok::kw___bridge_retained)
2121      Kind = OBC_BridgeRetained;
2122    else {
2123      // As a hopefully temporary workaround, allow __bridge_retain as
2124      // a synonym for __bridge_retained, but only in system headers.
2125      assert(tokenKind == tok::kw___bridge_retain);
2126      Kind = OBC_BridgeRetained;
2127      if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
2128        Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
2129          << FixItHint::CreateReplacement(BridgeKeywordLoc,
2130                                          "__bridge_retained");
2131    }
2132
2133    TypeResult Ty = ParseTypeName();
2134    T.consumeClose();
2135    RParenLoc = T.getCloseLocation();
2136    ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false);
2137
2138    if (Ty.isInvalid() || SubExpr.isInvalid())
2139      return ExprError();
2140
2141    return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
2142                                        BridgeKeywordLoc, Ty.get(),
2143                                        RParenLoc, SubExpr.get());
2144  } else if (ExprType >= CompoundLiteral &&
2145             isTypeIdInParens(isAmbiguousTypeId)) {
2146
2147    // Otherwise, this is a compound literal expression or cast expression.
2148
2149    // In C++, if the type-id is ambiguous we disambiguate based on context.
2150    // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
2151    // in which case we should treat it as type-id.
2152    // if stopIfCastExpr is false, we need to determine the context past the
2153    // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
2154    if (isAmbiguousTypeId && !stopIfCastExpr) {
2155      ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T);
2156      RParenLoc = T.getCloseLocation();
2157      return res;
2158    }
2159
2160    // Parse the type declarator.
2161    DeclSpec DS(AttrFactory);
2162    ParseSpecifierQualifierList(DS);
2163    Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2164    ParseDeclarator(DeclaratorInfo);
2165
2166    // If our type is followed by an identifier and either ':' or ']', then
2167    // this is probably an Objective-C message send where the leading '[' is
2168    // missing. Recover as if that were the case.
2169    if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
2170        !InMessageExpression && getLangOpts().ObjC1 &&
2171        (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2172      TypeResult Ty;
2173      {
2174        InMessageExpressionRAIIObject InMessage(*this, false);
2175        Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2176      }
2177      Result = ParseObjCMessageExpressionBody(SourceLocation(),
2178                                              SourceLocation(),
2179                                              Ty.get(), 0);
2180    } else {
2181      // Match the ')'.
2182      T.consumeClose();
2183      RParenLoc = T.getCloseLocation();
2184      if (Tok.is(tok::l_brace)) {
2185        ExprType = CompoundLiteral;
2186        TypeResult Ty;
2187        {
2188          InMessageExpressionRAIIObject InMessage(*this, false);
2189          Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2190        }
2191        return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
2192      }
2193
2194      if (ExprType == CastExpr) {
2195        // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
2196
2197        if (DeclaratorInfo.isInvalidType())
2198          return ExprError();
2199
2200        // Note that this doesn't parse the subsequent cast-expression, it just
2201        // returns the parsed type to the callee.
2202        if (stopIfCastExpr) {
2203          TypeResult Ty;
2204          {
2205            InMessageExpressionRAIIObject InMessage(*this, false);
2206            Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
2207          }
2208          CastTy = Ty.get();
2209          return ExprResult();
2210        }
2211
2212        // Reject the cast of super idiom in ObjC.
2213        if (Tok.is(tok::identifier) && getLangOpts().ObjC1 &&
2214            Tok.getIdentifierInfo() == Ident_super &&
2215            getCurScope()->isInObjcMethodScope() &&
2216            GetLookAheadToken(1).isNot(tok::period)) {
2217          Diag(Tok.getLocation(), diag::err_illegal_super_cast)
2218            << SourceRange(OpenLoc, RParenLoc);
2219          return ExprError();
2220        }
2221
2222        // Parse the cast-expression that follows it next.
2223        // TODO: For cast expression with CastTy.
2224        Result = ParseCastExpression(/*isUnaryExpression=*/false,
2225                                     /*isAddressOfOperand=*/false,
2226                                     /*isTypeCast=*/IsTypeCast);
2227        if (!Result.isInvalid()) {
2228          Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
2229                                         DeclaratorInfo, CastTy,
2230                                         RParenLoc, Result.take());
2231        }
2232        return Result;
2233      }
2234
2235      Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
2236      return ExprError();
2237    }
2238  } else if (isTypeCast) {
2239    // Parse the expression-list.
2240    InMessageExpressionRAIIObject InMessage(*this, false);
2241
2242    ExprVector ArgExprs;
2243    CommaLocsTy CommaLocs;
2244
2245    if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) {
2246      ExprType = SimpleExpr;
2247      Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
2248                                          ArgExprs);
2249    }
2250  } else {
2251    InMessageExpressionRAIIObject InMessage(*this, false);
2252
2253    Result = ParseExpression(MaybeTypeCast);
2254    ExprType = SimpleExpr;
2255
2256    // Don't build a paren expression unless we actually match a ')'.
2257    if (!Result.isInvalid() && Tok.is(tok::r_paren))
2258      Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.take());
2259  }
2260
2261  // Match the ')'.
2262  if (Result.isInvalid()) {
2263    SkipUntil(tok::r_paren);
2264    return ExprError();
2265  }
2266
2267  T.consumeClose();
2268  RParenLoc = T.getCloseLocation();
2269  return Result;
2270}
2271
2272/// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
2273/// and we are at the left brace.
2274///
2275/// \verbatim
2276///       postfix-expression: [C99 6.5.2]
2277///         '(' type-name ')' '{' initializer-list '}'
2278///         '(' type-name ')' '{' initializer-list ',' '}'
2279/// \endverbatim
2280ExprResult
2281Parser::ParseCompoundLiteralExpression(ParsedType Ty,
2282                                       SourceLocation LParenLoc,
2283                                       SourceLocation RParenLoc) {
2284  assert(Tok.is(tok::l_brace) && "Not a compound literal!");
2285  if (!getLangOpts().C99)   // Compound literals don't exist in C90.
2286    Diag(LParenLoc, diag::ext_c99_compound_literal);
2287  ExprResult Result = ParseInitializer();
2288  if (!Result.isInvalid() && Ty)
2289    return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.take());
2290  return Result;
2291}
2292
2293/// ParseStringLiteralExpression - This handles the various token types that
2294/// form string literals, and also handles string concatenation [C99 5.1.1.2,
2295/// translation phase #6].
2296///
2297/// \verbatim
2298///       primary-expression: [C99 6.5.1]
2299///         string-literal
2300/// \verbatim
2301ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
2302  assert(isTokenStringLiteral() && "Not a string literal!");
2303
2304  // String concat.  Note that keywords like __func__ and __FUNCTION__ are not
2305  // considered to be strings for concatenation purposes.
2306  SmallVector<Token, 4> StringToks;
2307
2308  do {
2309    StringToks.push_back(Tok);
2310    ConsumeStringToken();
2311  } while (isTokenStringLiteral());
2312
2313  // Pass the set of string tokens, ready for concatenation, to the actions.
2314  return Actions.ActOnStringLiteral(&StringToks[0], StringToks.size(),
2315                                   AllowUserDefinedLiteral ? getCurScope() : 0);
2316}
2317
2318/// ParseGenericSelectionExpression - Parse a C11 generic-selection
2319/// [C11 6.5.1.1].
2320///
2321/// \verbatim
2322///    generic-selection:
2323///           _Generic ( assignment-expression , generic-assoc-list )
2324///    generic-assoc-list:
2325///           generic-association
2326///           generic-assoc-list , generic-association
2327///    generic-association:
2328///           type-name : assignment-expression
2329///           default : assignment-expression
2330/// \endverbatim
2331ExprResult Parser::ParseGenericSelectionExpression() {
2332  assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
2333  SourceLocation KeyLoc = ConsumeToken();
2334
2335  if (!getLangOpts().C11)
2336    Diag(KeyLoc, diag::ext_c11_generic_selection);
2337
2338  BalancedDelimiterTracker T(*this, tok::l_paren);
2339  if (T.expectAndConsume(diag::err_expected_lparen))
2340    return ExprError();
2341
2342  ExprResult ControllingExpr;
2343  {
2344    // C11 6.5.1.1p3 "The controlling expression of a generic selection is
2345    // not evaluated."
2346    EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
2347    ControllingExpr = ParseAssignmentExpression();
2348    if (ControllingExpr.isInvalid()) {
2349      SkipUntil(tok::r_paren);
2350      return ExprError();
2351    }
2352  }
2353
2354  if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "")) {
2355    SkipUntil(tok::r_paren);
2356    return ExprError();
2357  }
2358
2359  SourceLocation DefaultLoc;
2360  TypeVector Types;
2361  ExprVector Exprs;
2362  while (1) {
2363    ParsedType Ty;
2364    if (Tok.is(tok::kw_default)) {
2365      // C11 6.5.1.1p2 "A generic selection shall have no more than one default
2366      // generic association."
2367      if (!DefaultLoc.isInvalid()) {
2368        Diag(Tok, diag::err_duplicate_default_assoc);
2369        Diag(DefaultLoc, diag::note_previous_default_assoc);
2370        SkipUntil(tok::r_paren);
2371        return ExprError();
2372      }
2373      DefaultLoc = ConsumeToken();
2374      Ty = ParsedType();
2375    } else {
2376      ColonProtectionRAIIObject X(*this);
2377      TypeResult TR = ParseTypeName();
2378      if (TR.isInvalid()) {
2379        SkipUntil(tok::r_paren);
2380        return ExprError();
2381      }
2382      Ty = TR.release();
2383    }
2384    Types.push_back(Ty);
2385
2386    if (ExpectAndConsume(tok::colon, diag::err_expected_colon, "")) {
2387      SkipUntil(tok::r_paren);
2388      return ExprError();
2389    }
2390
2391    // FIXME: These expressions should be parsed in a potentially potentially
2392    // evaluated context.
2393    ExprResult ER(ParseAssignmentExpression());
2394    if (ER.isInvalid()) {
2395      SkipUntil(tok::r_paren);
2396      return ExprError();
2397    }
2398    Exprs.push_back(ER.release());
2399
2400    if (Tok.isNot(tok::comma))
2401      break;
2402    ConsumeToken();
2403  }
2404
2405  T.consumeClose();
2406  if (T.getCloseLocation().isInvalid())
2407    return ExprError();
2408
2409  return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc,
2410                                           T.getCloseLocation(),
2411                                           ControllingExpr.release(),
2412                                           Types, Exprs);
2413}
2414
2415/// ParseExpressionList - Used for C/C++ (argument-)expression-list.
2416///
2417/// \verbatim
2418///       argument-expression-list:
2419///         assignment-expression
2420///         argument-expression-list , assignment-expression
2421///
2422/// [C++] expression-list:
2423/// [C++]   assignment-expression
2424/// [C++]   expression-list , assignment-expression
2425///
2426/// [C++0x] expression-list:
2427/// [C++0x]   initializer-list
2428///
2429/// [C++0x] initializer-list
2430/// [C++0x]   initializer-clause ...[opt]
2431/// [C++0x]   initializer-list , initializer-clause ...[opt]
2432///
2433/// [C++0x] initializer-clause:
2434/// [C++0x]   assignment-expression
2435/// [C++0x]   braced-init-list
2436/// \endverbatim
2437bool Parser::ParseExpressionList(SmallVectorImpl<Expr*> &Exprs,
2438                                 SmallVectorImpl<SourceLocation> &CommaLocs,
2439                                 void (Sema::*Completer)(Scope *S,
2440                                                         Expr *Data,
2441                                                         ArrayRef<Expr *> Args),
2442                                 Expr *Data) {
2443  while (1) {
2444    if (Tok.is(tok::code_completion)) {
2445      if (Completer)
2446        (Actions.*Completer)(getCurScope(), Data, Exprs);
2447      else
2448        Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression);
2449      cutOffParsing();
2450      return true;
2451    }
2452
2453    ExprResult Expr;
2454    if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2455      Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2456      Expr = ParseBraceInitializer();
2457    } else
2458      Expr = ParseAssignmentExpression();
2459
2460    if (Tok.is(tok::ellipsis))
2461      Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
2462    if (Expr.isInvalid())
2463      return true;
2464
2465    Exprs.push_back(Expr.release());
2466
2467    if (Tok.isNot(tok::comma))
2468      return false;
2469    // Move to the next argument, remember where the comma was.
2470    CommaLocs.push_back(ConsumeToken());
2471  }
2472}
2473
2474/// ParseSimpleExpressionList - A simple comma-separated list of expressions,
2475/// used for misc language extensions.
2476///
2477/// \verbatim
2478///       simple-expression-list:
2479///         assignment-expression
2480///         simple-expression-list , assignment-expression
2481/// \endverbatim
2482bool
2483Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs,
2484                                  SmallVectorImpl<SourceLocation> &CommaLocs) {
2485  while (1) {
2486    ExprResult Expr = ParseAssignmentExpression();
2487    if (Expr.isInvalid())
2488      return true;
2489
2490    Exprs.push_back(Expr.release());
2491
2492    if (Tok.isNot(tok::comma))
2493      return false;
2494
2495    // Move to the next argument, remember where the comma was.
2496    CommaLocs.push_back(ConsumeToken());
2497  }
2498}
2499
2500/// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
2501///
2502/// \verbatim
2503/// [clang] block-id:
2504/// [clang]   specifier-qualifier-list block-declarator
2505/// \endverbatim
2506void Parser::ParseBlockId(SourceLocation CaretLoc) {
2507  if (Tok.is(tok::code_completion)) {
2508    Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type);
2509    return cutOffParsing();
2510  }
2511
2512  // Parse the specifier-qualifier-list piece.
2513  DeclSpec DS(AttrFactory);
2514  ParseSpecifierQualifierList(DS);
2515
2516  // Parse the block-declarator.
2517  Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext);
2518  ParseDeclarator(DeclaratorInfo);
2519
2520  // We do this for: ^ __attribute__((noreturn)) {, as DS has the attributes.
2521  DeclaratorInfo.takeAttributes(DS.getAttributes(), SourceLocation());
2522
2523  MaybeParseGNUAttributes(DeclaratorInfo);
2524
2525  // Inform sema that we are starting a block.
2526  Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
2527}
2528
2529/// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
2530/// like ^(int x){ return x+1; }
2531///
2532/// \verbatim
2533///         block-literal:
2534/// [clang]   '^' block-args[opt] compound-statement
2535/// [clang]   '^' block-id compound-statement
2536/// [clang] block-args:
2537/// [clang]   '(' parameter-list ')'
2538/// \endverbatim
2539ExprResult Parser::ParseBlockLiteralExpression() {
2540  assert(Tok.is(tok::caret) && "block literal starts with ^");
2541  SourceLocation CaretLoc = ConsumeToken();
2542
2543  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
2544                                "block literal parsing");
2545
2546  // Enter a scope to hold everything within the block.  This includes the
2547  // argument decls, decls within the compound expression, etc.  This also
2548  // allows determining whether a variable reference inside the block is
2549  // within or outside of the block.
2550  ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
2551                              Scope::DeclScope);
2552
2553  // Inform sema that we are starting a block.
2554  Actions.ActOnBlockStart(CaretLoc, getCurScope());
2555
2556  // Parse the return type if present.
2557  DeclSpec DS(AttrFactory);
2558  Declarator ParamInfo(DS, Declarator::BlockLiteralContext);
2559  // FIXME: Since the return type isn't actually parsed, it can't be used to
2560  // fill ParamInfo with an initial valid range, so do it manually.
2561  ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
2562
2563  // If this block has arguments, parse them.  There is no ambiguity here with
2564  // the expression case, because the expression case requires a parameter list.
2565  if (Tok.is(tok::l_paren)) {
2566    ParseParenDeclarator(ParamInfo);
2567    // Parse the pieces after the identifier as if we had "int(...)".
2568    // SetIdentifier sets the source range end, but in this case we're past
2569    // that location.
2570    SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
2571    ParamInfo.SetIdentifier(0, CaretLoc);
2572    ParamInfo.SetRangeEnd(Tmp);
2573    if (ParamInfo.isInvalidType()) {
2574      // If there was an error parsing the arguments, they may have
2575      // tried to use ^(x+y) which requires an argument list.  Just
2576      // skip the whole block literal.
2577      Actions.ActOnBlockError(CaretLoc, getCurScope());
2578      return ExprError();
2579    }
2580
2581    MaybeParseGNUAttributes(ParamInfo);
2582
2583    // Inform sema that we are starting a block.
2584    Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2585  } else if (!Tok.is(tok::l_brace)) {
2586    ParseBlockId(CaretLoc);
2587  } else {
2588    // Otherwise, pretend we saw (void).
2589    ParsedAttributes attrs(AttrFactory);
2590    SourceLocation NoLoc;
2591    ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true,
2592                                             /*IsAmbiguous=*/false,
2593                                             /*RParenLoc=*/NoLoc,
2594                                             /*ArgInfo=*/0,
2595                                             /*NumArgs=*/0,
2596                                             /*EllipsisLoc=*/NoLoc,
2597                                             /*RParenLoc=*/NoLoc,
2598                                             /*TypeQuals=*/0,
2599                                             /*RefQualifierIsLvalueRef=*/true,
2600                                             /*RefQualifierLoc=*/NoLoc,
2601                                             /*ConstQualifierLoc=*/NoLoc,
2602                                             /*VolatileQualifierLoc=*/NoLoc,
2603                                             /*MutableLoc=*/NoLoc,
2604                                             EST_None,
2605                                             /*ESpecLoc=*/NoLoc,
2606                                             /*Exceptions=*/0,
2607                                             /*ExceptionRanges=*/0,
2608                                             /*NumExceptions=*/0,
2609                                             /*NoexceptExpr=*/0,
2610                                             CaretLoc, CaretLoc,
2611                                             ParamInfo),
2612                          attrs, CaretLoc);
2613
2614    MaybeParseGNUAttributes(ParamInfo);
2615
2616    // Inform sema that we are starting a block.
2617    Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
2618  }
2619
2620
2621  ExprResult Result(true);
2622  if (!Tok.is(tok::l_brace)) {
2623    // Saw something like: ^expr
2624    Diag(Tok, diag::err_expected_expression);
2625    Actions.ActOnBlockError(CaretLoc, getCurScope());
2626    return ExprError();
2627  }
2628
2629  StmtResult Stmt(ParseCompoundStatementBody());
2630  BlockScope.Exit();
2631  if (!Stmt.isInvalid())
2632    Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.take(), getCurScope());
2633  else
2634    Actions.ActOnBlockError(CaretLoc, getCurScope());
2635  return Result;
2636}
2637
2638/// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
2639///
2640///         '__objc_yes'
2641///         '__objc_no'
2642ExprResult Parser::ParseObjCBoolLiteral() {
2643  tok::TokenKind Kind = Tok.getKind();
2644  return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind);
2645}
2646