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