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