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