clang  20.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/AST/ASTContext.h"
24 #include "clang/AST/Availability.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/LocInfoType.h"
29 #include "clang/Parse/Parser.h"
31 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Scope.h"
35 #include "clang/Sema/SemaCUDA.h"
37 #include "clang/Sema/SemaObjC.h"
38 #include "clang/Sema/SemaOpenACC.h"
39 #include "clang/Sema/SemaOpenMP.h"
40 #include "clang/Sema/SemaSYCL.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include <optional>
44 using namespace clang;
45 
46 /// Simple precedence-based parser for binary/ternary operators.
47 ///
48 /// Note: we diverge from the C99 grammar when parsing the assignment-expression
49 /// production. C99 specifies that the LHS of an assignment operator should be
50 /// parsed as a unary-expression, but consistency dictates that it be a
51 /// conditional-expession. In practice, the important thing here is that the
52 /// LHS of an assignment has to be an l-value, which productions between
53 /// unary-expression and conditional-expression don't produce. Because we want
54 /// consistency, we parse the LHS as a conditional-expression, then check for
55 /// l-value-ness in semantic analysis stages.
56 ///
57 /// \verbatim
58 /// pm-expression: [C++ 5.5]
59 /// cast-expression
60 /// pm-expression '.*' cast-expression
61 /// pm-expression '->*' cast-expression
62 ///
63 /// multiplicative-expression: [C99 6.5.5]
64 /// Note: in C++, apply pm-expression instead of cast-expression
65 /// cast-expression
66 /// multiplicative-expression '*' cast-expression
67 /// multiplicative-expression '/' cast-expression
68 /// multiplicative-expression '%' cast-expression
69 ///
70 /// additive-expression: [C99 6.5.6]
71 /// multiplicative-expression
72 /// additive-expression '+' multiplicative-expression
73 /// additive-expression '-' multiplicative-expression
74 ///
75 /// shift-expression: [C99 6.5.7]
76 /// additive-expression
77 /// shift-expression '<<' additive-expression
78 /// shift-expression '>>' additive-expression
79 ///
80 /// compare-expression: [C++20 expr.spaceship]
81 /// shift-expression
82 /// compare-expression '<=>' shift-expression
83 ///
84 /// relational-expression: [C99 6.5.8]
85 /// compare-expression
86 /// relational-expression '<' compare-expression
87 /// relational-expression '>' compare-expression
88 /// relational-expression '<=' compare-expression
89 /// relational-expression '>=' compare-expression
90 ///
91 /// equality-expression: [C99 6.5.9]
92 /// relational-expression
93 /// equality-expression '==' relational-expression
94 /// equality-expression '!=' relational-expression
95 ///
96 /// AND-expression: [C99 6.5.10]
97 /// equality-expression
98 /// AND-expression '&' equality-expression
99 ///
100 /// exclusive-OR-expression: [C99 6.5.11]
101 /// AND-expression
102 /// exclusive-OR-expression '^' AND-expression
103 ///
104 /// inclusive-OR-expression: [C99 6.5.12]
105 /// exclusive-OR-expression
106 /// inclusive-OR-expression '|' exclusive-OR-expression
107 ///
108 /// logical-AND-expression: [C99 6.5.13]
109 /// inclusive-OR-expression
110 /// logical-AND-expression '&&' inclusive-OR-expression
111 ///
112 /// logical-OR-expression: [C99 6.5.14]
113 /// logical-AND-expression
114 /// logical-OR-expression '||' logical-AND-expression
115 ///
116 /// conditional-expression: [C99 6.5.15]
117 /// logical-OR-expression
118 /// logical-OR-expression '?' expression ':' conditional-expression
119 /// [GNU] logical-OR-expression '?' ':' conditional-expression
120 /// [C++] the third operand is an assignment-expression
121 ///
122 /// assignment-expression: [C99 6.5.16]
123 /// conditional-expression
124 /// unary-expression assignment-operator assignment-expression
125 /// [C++] throw-expression [C++ 15]
126 ///
127 /// assignment-operator: one of
128 /// = *= /= %= += -= <<= >>= &= ^= |=
129 ///
130 /// expression: [C99 6.5.17]
131 /// assignment-expression ...[opt]
132 /// expression ',' assignment-expression ...[opt]
133 /// \endverbatim
135  ExprResult LHS(ParseAssignmentExpression(isTypeCast));
136  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
137 }
138 
139 /// This routine is called when the '@' is seen and consumed.
140 /// Current token is an Identifier and is not a 'try'. This
141 /// routine is necessary to disambiguate \@try-statement from,
142 /// for example, \@encode-expression.
143 ///
145 Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) {
146  ExprResult LHS(ParseObjCAtExpression(AtLoc));
147  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
148 }
149 
150 /// This routine is called when a leading '__extension__' is seen and
151 /// consumed. This is necessary because the token gets consumed in the
152 /// process of disambiguating between an expression and a declaration.
154 Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) {
155  ExprResult LHS(true);
156  {
157  // Silence extension warnings in the sub-expression
158  ExtensionRAIIObject O(Diags);
159 
160  LHS = ParseCastExpression(AnyCastExpr);
161  }
162 
163  if (!LHS.isInvalid())
164  LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__,
165  LHS.get());
166 
167  return ParseRHSOfBinaryExpression(LHS, prec::Comma);
168 }
169 
170 /// Parse an expr that doesn't include (top-level) commas.
172  if (Tok.is(tok::code_completion)) {
173  cutOffParsing();
175  getCurScope(), PreferredType.get(Tok.getLocation()));
176  return ExprError();
177  }
178 
179  if (Tok.is(tok::kw_throw))
180  return ParseThrowExpression();
181  if (Tok.is(tok::kw_co_yield))
182  return ParseCoyieldExpression();
183 
184  ExprResult LHS = ParseCastExpression(AnyCastExpr,
185  /*isAddressOfOperand=*/false,
186  isTypeCast);
187  return ParseRHSOfBinaryExpression(LHS, prec::Assignment);
188 }
189 
191  if (Tok.is(tok::code_completion)) {
192  cutOffParsing();
194  getCurScope(), PreferredType.get(Tok.getLocation()));
195  return ExprError();
196  }
197 
198  ExprResult LHS = ParseCastExpression(
199  AnyCastExpr, /*isAddressOfOperand=*/false, NotTypeCast);
200  return ParseRHSOfBinaryExpression(LHS, prec::Conditional);
201 }
202 
203 /// Parse an assignment expression where part of an Objective-C message
204 /// send has already been parsed.
205 ///
206 /// In this case \p LBracLoc indicates the location of the '[' of the message
207 /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating
208 /// the receiver of the message.
209 ///
210 /// Since this handles full assignment-expression's, it handles postfix
211 /// expressions and other binary operators for these expressions as well.
213 Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc,
214  SourceLocation SuperLoc,
215  ParsedType ReceiverType,
216  Expr *ReceiverExpr) {
217  ExprResult R
218  = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc,
219  ReceiverType, ReceiverExpr);
220  R = ParsePostfixExpressionSuffix(R);
221  return ParseRHSOfBinaryExpression(R, prec::Assignment);
222 }
223 
226  assert(Actions.ExprEvalContexts.back().Context ==
228  "Call this function only if your ExpressionEvaluationContext is "
229  "already ConstantEvaluated");
230  ExprResult LHS(ParseCastExpression(AnyCastExpr, false, isTypeCast));
231  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
232  return Actions.ActOnConstantExpression(Res);
233 }
234 
236  // C++03 [basic.def.odr]p2:
237  // An expression is potentially evaluated unless it appears where an
238  // integral constant expression is required (see 5.19) [...].
239  // C++98 and C++11 have no such rule, but this is only a defect in C++98.
240  EnterExpressionEvaluationContext ConstantEvaluated(
243 }
244 
246  EnterExpressionEvaluationContext ConstantEvaluated(
248  // If we parse the bound of a VLA... we parse a non-constant
249  // constant-expression!
250  Actions.ExprEvalContexts.back().InConditionallyConstantEvaluateContext = true;
252 }
253 
255  EnterExpressionEvaluationContext ConstantEvaluated(
257  ExprResult LHS(ParseCastExpression(AnyCastExpr, false, NotTypeCast));
258  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
259  return Actions.ActOnCaseExpr(CaseLoc, Res);
260 }
261 
262 /// Parse a constraint-expression.
263 ///
264 /// \verbatim
265 /// constraint-expression: C++2a[temp.constr.decl]p1
266 /// logical-or-expression
267 /// \endverbatim
269  EnterExpressionEvaluationContext ConstantEvaluated(
271  ExprResult LHS(ParseCastExpression(AnyCastExpr));
272  ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr));
273  if (Res.isUsable() && !Actions.CheckConstraintExpression(Res.get())) {
274  Actions.CorrectDelayedTyposInExpr(Res);
275  return ExprError();
276  }
277  return Res;
278 }
279 
280 /// \brief Parse a constraint-logical-and-expression.
281 ///
282 /// \verbatim
283 /// C++2a[temp.constr.decl]p1
284 /// constraint-logical-and-expression:
285 /// primary-expression
286 /// constraint-logical-and-expression '&&' primary-expression
287 ///
288 /// \endverbatim
290 Parser::ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause) {
291  EnterExpressionEvaluationContext ConstantEvaluated(
293  bool NotPrimaryExpression = false;
294  auto ParsePrimary = [&] () {
295  ExprResult E = ParseCastExpression(PrimaryExprOnly,
296  /*isAddressOfOperand=*/false,
297  /*isTypeCast=*/NotTypeCast,
298  /*isVectorLiteral=*/false,
299  &NotPrimaryExpression);
300  if (E.isInvalid())
301  return ExprError();
302  auto RecoverFromNonPrimary = [&] (ExprResult E, bool Note) {
303  E = ParsePostfixExpressionSuffix(E);
304  // Use InclusiveOr, the precedence just after '&&' to not parse the
305  // next arguments to the logical and.
306  E = ParseRHSOfBinaryExpression(E, prec::InclusiveOr);
307  if (!E.isInvalid())
308  Diag(E.get()->getExprLoc(),
309  Note
310  ? diag::note_unparenthesized_non_primary_expr_in_requires_clause
311  : diag::err_unparenthesized_non_primary_expr_in_requires_clause)
312  << FixItHint::CreateInsertion(E.get()->getBeginLoc(), "(")
314  PP.getLocForEndOfToken(E.get()->getEndLoc()), ")")
315  << E.get()->getSourceRange();
316  return E;
317  };
318 
319  if (NotPrimaryExpression ||
320  // Check if the following tokens must be a part of a non-primary
321  // expression
322  getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
323  /*CPlusPlus11=*/true) > prec::LogicalAnd ||
324  // Postfix operators other than '(' (which will be checked for in
325  // CheckConstraintExpression).
326  Tok.isOneOf(tok::period, tok::plusplus, tok::minusminus) ||
327  (Tok.is(tok::l_square) && !NextToken().is(tok::l_square))) {
328  E = RecoverFromNonPrimary(E, /*Note=*/false);
329  if (E.isInvalid())
330  return ExprError();
331  NotPrimaryExpression = false;
332  }
333  bool PossibleNonPrimary;
334  bool IsConstraintExpr =
335  Actions.CheckConstraintExpression(E.get(), Tok, &PossibleNonPrimary,
336  IsTrailingRequiresClause);
337  if (!IsConstraintExpr || PossibleNonPrimary) {
338  // Atomic constraint might be an unparenthesized non-primary expression
339  // (such as a binary operator), in which case we might get here (e.g. in
340  // 'requires 0 + 1 && true' we would now be at '+', and parse and ignore
341  // the rest of the addition expression). Try to parse the rest of it here.
342  if (PossibleNonPrimary)
343  E = RecoverFromNonPrimary(E, /*Note=*/!IsConstraintExpr);
344  Actions.CorrectDelayedTyposInExpr(E);
345  return ExprError();
346  }
347  return E;
348  };
349  ExprResult LHS = ParsePrimary();
350  if (LHS.isInvalid())
351  return ExprError();
352  while (Tok.is(tok::ampamp)) {
353  SourceLocation LogicalAndLoc = ConsumeToken();
354  ExprResult RHS = ParsePrimary();
355  if (RHS.isInvalid()) {
356  Actions.CorrectDelayedTyposInExpr(LHS);
357  return ExprError();
358  }
359  ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalAndLoc,
360  tok::ampamp, LHS.get(), RHS.get());
361  if (!Op.isUsable()) {
362  Actions.CorrectDelayedTyposInExpr(RHS);
363  Actions.CorrectDelayedTyposInExpr(LHS);
364  return ExprError();
365  }
366  LHS = Op;
367  }
368  return LHS;
369 }
370 
371 /// \brief Parse a constraint-logical-or-expression.
372 ///
373 /// \verbatim
374 /// C++2a[temp.constr.decl]p1
375 /// constraint-logical-or-expression:
376 /// constraint-logical-and-expression
377 /// constraint-logical-or-expression '||'
378 /// constraint-logical-and-expression
379 ///
380 /// \endverbatim
382 Parser::ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause) {
383  ExprResult LHS(ParseConstraintLogicalAndExpression(IsTrailingRequiresClause));
384  if (!LHS.isUsable())
385  return ExprError();
386  while (Tok.is(tok::pipepipe)) {
387  SourceLocation LogicalOrLoc = ConsumeToken();
388  ExprResult RHS =
389  ParseConstraintLogicalAndExpression(IsTrailingRequiresClause);
390  if (!RHS.isUsable()) {
391  Actions.CorrectDelayedTyposInExpr(LHS);
392  return ExprError();
393  }
394  ExprResult Op = Actions.ActOnBinOp(getCurScope(), LogicalOrLoc,
395  tok::pipepipe, LHS.get(), RHS.get());
396  if (!Op.isUsable()) {
397  Actions.CorrectDelayedTyposInExpr(RHS);
398  Actions.CorrectDelayedTyposInExpr(LHS);
399  return ExprError();
400  }
401  LHS = Op;
402  }
403  return LHS;
404 }
405 
406 bool Parser::isNotExpressionStart() {
407  tok::TokenKind K = Tok.getKind();
408  if (K == tok::l_brace || K == tok::r_brace ||
409  K == tok::kw_for || K == tok::kw_while ||
410  K == tok::kw_if || K == tok::kw_else ||
411  K == tok::kw_goto || K == tok::kw_try)
412  return true;
413  // If this is a decl-specifier, we can't be at the start of an expression.
414  return isKnownToBeDeclarationSpecifier();
415 }
416 
417 bool Parser::isFoldOperator(prec::Level Level) const {
418  return Level > prec::Unknown && Level != prec::Conditional &&
420 }
421 
422 bool Parser::isFoldOperator(tok::TokenKind Kind) const {
423  return isFoldOperator(getBinOpPrecedence(Kind, GreaterThanIsOperator, true));
424 }
425 
426 /// Parse a binary expression that starts with \p LHS and has a
427 /// precedence of at least \p MinPrec.
429 Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) {
430  prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(),
431  GreaterThanIsOperator,
433  SourceLocation ColonLoc;
434 
435  auto SavedType = PreferredType;
436  while (true) {
437  // Every iteration may rely on a preferred type for the whole expression.
438  PreferredType = SavedType;
439  // If this token has a lower precedence than we are allowed to parse (e.g.
440  // because we are called recursively, or because the token is not a binop),
441  // then we are done!
442  if (NextTokPrec < MinPrec)
443  return LHS;
444 
445  // Consume the operator, saving the operator token for error reporting.
446  Token OpToken = Tok;
447  ConsumeToken();
448 
449  if (OpToken.is(tok::caretcaret)) {
450  return ExprError(Diag(Tok, diag::err_opencl_logical_exclusive_or));
451  }
452 
453  // If we're potentially in a template-id, we may now be able to determine
454  // whether we're actually in one or not.
455  if (OpToken.isOneOf(tok::comma, tok::greater, tok::greatergreater,
456  tok::greatergreatergreater) &&
457  checkPotentialAngleBracketDelimiter(OpToken))
458  return ExprError();
459 
460  // Bail out when encountering a comma followed by a token which can't
461  // possibly be the start of an expression. For instance:
462  // int f() { return 1, }
463  // We can't do this before consuming the comma, because
464  // isNotExpressionStart() looks at the token stream.
465  if (OpToken.is(tok::comma) && isNotExpressionStart()) {
466  PP.EnterToken(Tok, /*IsReinject*/true);
467  Tok = OpToken;
468  return LHS;
469  }
470 
471  // If the next token is an ellipsis, then this is a fold-expression. Leave
472  // it alone so we can handle it in the paren expression.
473  if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) {
474  // FIXME: We can't check this via lookahead before we consume the token
475  // because that tickles a lexer bug.
476  PP.EnterToken(Tok, /*IsReinject*/true);
477  Tok = OpToken;
478  return LHS;
479  }
480 
481  // In Objective-C++, alternative operator tokens can be used as keyword args
482  // in message expressions. Unconsume the token so that it can reinterpreted
483  // as an identifier in ParseObjCMessageExpressionBody. i.e., we support:
484  // [foo meth:0 and:0];
485  // [foo not_eq];
486  if (getLangOpts().ObjC && getLangOpts().CPlusPlus &&
487  Tok.isOneOf(tok::colon, tok::r_square) &&
488  OpToken.getIdentifierInfo() != nullptr) {
489  PP.EnterToken(Tok, /*IsReinject*/true);
490  Tok = OpToken;
491  return LHS;
492  }
493 
494  // Special case handling for the ternary operator.
495  ExprResult TernaryMiddle(true);
496  if (NextTokPrec == prec::Conditional) {
497  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
498  // Parse a braced-init-list here for error recovery purposes.
499  SourceLocation BraceLoc = Tok.getLocation();
500  TernaryMiddle = ParseBraceInitializer();
501  if (!TernaryMiddle.isInvalid()) {
502  Diag(BraceLoc, diag::err_init_list_bin_op)
503  << /*RHS*/ 1 << PP.getSpelling(OpToken)
504  << Actions.getExprRange(TernaryMiddle.get());
505  TernaryMiddle = ExprError();
506  }
507  } else if (Tok.isNot(tok::colon)) {
508  // Don't parse FOO:BAR as if it were a typo for FOO::BAR.
510 
511  // Handle this production specially:
512  // logical-OR-expression '?' expression ':' conditional-expression
513  // In particular, the RHS of the '?' is 'expression', not
514  // 'logical-OR-expression' as we might expect.
515  TernaryMiddle = ParseExpression();
516  } else {
517  // Special case handling of "X ? Y : Z" where Y is empty:
518  // logical-OR-expression '?' ':' conditional-expression [GNU]
519  TernaryMiddle = nullptr;
520  Diag(Tok, diag::ext_gnu_conditional_expr);
521  }
522 
523  if (TernaryMiddle.isInvalid()) {
524  Actions.CorrectDelayedTyposInExpr(LHS);
525  LHS = ExprError();
526  TernaryMiddle = nullptr;
527  }
528 
529  if (!TryConsumeToken(tok::colon, ColonLoc)) {
530  // Otherwise, we're missing a ':'. Assume that this was a typo that
531  // the user forgot. If we're not in a macro expansion, we can suggest
532  // a fixit hint. If there were two spaces before the current token,
533  // suggest inserting the colon in between them, otherwise insert ": ".
534  SourceLocation FILoc = Tok.getLocation();
535  const char *FIText = ": ";
536  const SourceManager &SM = PP.getSourceManager();
537  if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) {
538  assert(FILoc.isFileID());
539  bool IsInvalid = false;
540  const char *SourcePtr =
541  SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid);
542  if (!IsInvalid && *SourcePtr == ' ') {
543  SourcePtr =
544  SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid);
545  if (!IsInvalid && *SourcePtr == ' ') {
546  FILoc = FILoc.getLocWithOffset(-1);
547  FIText = ":";
548  }
549  }
550  }
551 
552  Diag(Tok, diag::err_expected)
553  << tok::colon << FixItHint::CreateInsertion(FILoc, FIText);
554  Diag(OpToken, diag::note_matching) << tok::question;
555  ColonLoc = Tok.getLocation();
556  }
557  }
558 
559  PreferredType.enterBinary(Actions, Tok.getLocation(), LHS.get(),
560  OpToken.getKind());
561  // Parse another leaf here for the RHS of the operator.
562  // ParseCastExpression works here because all RHS expressions in C have it
563  // as a prefix, at least. However, in C++, an assignment-expression could
564  // be a throw-expression, which is not a valid cast-expression.
565  // Therefore we need some special-casing here.
566  // Also note that the third operand of the conditional operator is
567  // an assignment-expression in C++, and in C++11, we can have a
568  // braced-init-list on the RHS of an assignment. For better diagnostics,
569  // parse as if we were allowed braced-init-lists everywhere, and check that
570  // they only appear on the RHS of assignments later.
571  ExprResult RHS;
572  bool RHSIsInitList = false;
573  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
574  RHS = ParseBraceInitializer();
575  RHSIsInitList = true;
576  } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional)
578  else
579  RHS = ParseCastExpression(AnyCastExpr);
580 
581  if (RHS.isInvalid()) {
582  // FIXME: Errors generated by the delayed typo correction should be
583  // printed before errors from parsing the RHS, not after.
584  Actions.CorrectDelayedTyposInExpr(LHS);
585  if (TernaryMiddle.isUsable())
586  TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
587  LHS = ExprError();
588  }
589 
590  // Remember the precedence of this operator and get the precedence of the
591  // operator immediately to the right of the RHS.
592  prec::Level ThisPrec = NextTokPrec;
593  NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
595 
596  // Assignment and conditional expressions are right-associative.
597  bool isRightAssoc = ThisPrec == prec::Conditional ||
598  ThisPrec == prec::Assignment;
599 
600  // Get the precedence of the operator to the right of the RHS. If it binds
601  // more tightly with RHS than we do, evaluate it completely first.
602  if (ThisPrec < NextTokPrec ||
603  (ThisPrec == NextTokPrec && isRightAssoc)) {
604  if (!RHS.isInvalid() && RHSIsInitList) {
605  Diag(Tok, diag::err_init_list_bin_op)
606  << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get());
607  RHS = ExprError();
608  }
609  // If this is left-associative, only parse things on the RHS that bind
610  // more tightly than the current operator. If it is left-associative, it
611  // is okay, to bind exactly as tightly. For example, compile A=B=C=D as
612  // A=(B=(C=D)), where each paren is a level of recursion here.
613  // The function takes ownership of the RHS.
614  RHS = ParseRHSOfBinaryExpression(RHS,
615  static_cast<prec::Level>(ThisPrec + !isRightAssoc));
616  RHSIsInitList = false;
617 
618  if (RHS.isInvalid()) {
619  // FIXME: Errors generated by the delayed typo correction should be
620  // printed before errors from ParseRHSOfBinaryExpression, not after.
621  Actions.CorrectDelayedTyposInExpr(LHS);
622  if (TernaryMiddle.isUsable())
623  TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
624  LHS = ExprError();
625  }
626 
627  NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator,
629  }
630 
631  if (!RHS.isInvalid() && RHSIsInitList) {
632  if (ThisPrec == prec::Assignment) {
633  Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists)
634  << Actions.getExprRange(RHS.get());
635  } else if (ColonLoc.isValid()) {
636  Diag(ColonLoc, diag::err_init_list_bin_op)
637  << /*RHS*/1 << ":"
638  << Actions.getExprRange(RHS.get());
639  LHS = ExprError();
640  } else {
641  Diag(OpToken, diag::err_init_list_bin_op)
642  << /*RHS*/1 << PP.getSpelling(OpToken)
643  << Actions.getExprRange(RHS.get());
644  LHS = ExprError();
645  }
646  }
647 
648  ExprResult OrigLHS = LHS;
649  if (!LHS.isInvalid()) {
650  // Combine the LHS and RHS into the LHS (e.g. build AST).
651  if (TernaryMiddle.isInvalid()) {
652  // If we're using '>>' as an operator within a template
653  // argument list (in C++98), suggest the addition of
654  // parentheses so that the code remains well-formed in C++0x.
655  if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater))
656  SuggestParentheses(OpToken.getLocation(),
657  diag::warn_cxx11_right_shift_in_template_arg,
658  SourceRange(Actions.getExprRange(LHS.get()).getBegin(),
659  Actions.getExprRange(RHS.get()).getEnd()));
660 
661  ExprResult BinOp =
662  Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(),
663  OpToken.getKind(), LHS.get(), RHS.get());
664  if (BinOp.isInvalid())
665  BinOp = Actions.CreateRecoveryExpr(LHS.get()->getBeginLoc(),
666  RHS.get()->getEndLoc(),
667  {LHS.get(), RHS.get()});
668 
669  LHS = BinOp;
670  } else {
671  ExprResult CondOp = Actions.ActOnConditionalOp(
672  OpToken.getLocation(), ColonLoc, LHS.get(), TernaryMiddle.get(),
673  RHS.get());
674  if (CondOp.isInvalid()) {
675  std::vector<clang::Expr *> Args;
676  // TernaryMiddle can be null for the GNU conditional expr extension.
677  if (TernaryMiddle.get())
678  Args = {LHS.get(), TernaryMiddle.get(), RHS.get()};
679  else
680  Args = {LHS.get(), RHS.get()};
681  CondOp = Actions.CreateRecoveryExpr(LHS.get()->getBeginLoc(),
682  RHS.get()->getEndLoc(), Args);
683  }
684 
685  LHS = CondOp;
686  }
687  // In this case, ActOnBinOp or ActOnConditionalOp performed the
688  // CorrectDelayedTyposInExpr check.
689  if (!getLangOpts().CPlusPlus)
690  continue;
691  }
692 
693  // Ensure potential typos aren't left undiagnosed.
694  if (LHS.isInvalid()) {
695  Actions.CorrectDelayedTyposInExpr(OrigLHS);
696  Actions.CorrectDelayedTyposInExpr(TernaryMiddle);
697  Actions.CorrectDelayedTyposInExpr(RHS);
698  }
699  }
700 }
701 
702 /// Parse a cast-expression, unary-expression or primary-expression, based
703 /// on \p ExprType.
704 ///
705 /// \p isAddressOfOperand exists because an id-expression that is the
706 /// operand of address-of gets special treatment due to member pointers.
707 ///
708 ExprResult Parser::ParseCastExpression(CastParseKind ParseKind,
709  bool isAddressOfOperand,
710  TypeCastState isTypeCast,
711  bool isVectorLiteral,
712  bool *NotPrimaryExpression) {
713  bool NotCastExpr;
714  ExprResult Res = ParseCastExpression(ParseKind,
715  isAddressOfOperand,
716  NotCastExpr,
717  isTypeCast,
718  isVectorLiteral,
719  NotPrimaryExpression);
720  if (NotCastExpr)
721  Diag(Tok, diag::err_expected_expression);
722  return Res;
723 }
724 
725 namespace {
726 class CastExpressionIdValidator final : public CorrectionCandidateCallback {
727  public:
728  CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes)
729  : NextToken(Next), AllowNonTypes(AllowNonTypes) {
730  WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes;
731  }
732 
733  bool ValidateCandidate(const TypoCorrection &candidate) override {
734  NamedDecl *ND = candidate.getCorrectionDecl();
735  if (!ND)
736  return candidate.isKeyword();
737 
738  if (isa<TypeDecl>(ND))
739  return WantTypeSpecifiers;
740 
741  if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate))
742  return false;
743 
744  if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period))
745  return true;
746 
747  for (auto *C : candidate) {
748  NamedDecl *ND = C->getUnderlyingDecl();
749  if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND))
750  return true;
751  }
752  return false;
753  }
754 
755  std::unique_ptr<CorrectionCandidateCallback> clone() override {
756  return std::make_unique<CastExpressionIdValidator>(*this);
757  }
758 
759  private:
760  Token NextToken;
761  bool AllowNonTypes;
762 };
763 }
764 
765 bool Parser::isRevertibleTypeTrait(const IdentifierInfo *II,
766  tok::TokenKind *Kind) {
767  if (RevertibleTypeTraits.empty()) {
768 // Revertible type trait is a feature for backwards compatibility with older
769 // standard libraries that declare their own structs with the same name as
770 // the builtins listed below. New builtins should NOT be added to this list.
771 #define RTT_JOIN(X, Y) X##Y
772 #define REVERTIBLE_TYPE_TRAIT(Name) \
773  RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] = RTT_JOIN(tok::kw_, Name)
774 
775  REVERTIBLE_TYPE_TRAIT(__is_abstract);
776  REVERTIBLE_TYPE_TRAIT(__is_aggregate);
777  REVERTIBLE_TYPE_TRAIT(__is_arithmetic);
778  REVERTIBLE_TYPE_TRAIT(__is_array);
779  REVERTIBLE_TYPE_TRAIT(__is_assignable);
780  REVERTIBLE_TYPE_TRAIT(__is_base_of);
781  REVERTIBLE_TYPE_TRAIT(__is_bounded_array);
782  REVERTIBLE_TYPE_TRAIT(__is_class);
783  REVERTIBLE_TYPE_TRAIT(__is_complete_type);
784  REVERTIBLE_TYPE_TRAIT(__is_compound);
785  REVERTIBLE_TYPE_TRAIT(__is_const);
786  REVERTIBLE_TYPE_TRAIT(__is_constructible);
787  REVERTIBLE_TYPE_TRAIT(__is_convertible);
788  REVERTIBLE_TYPE_TRAIT(__is_convertible_to);
789  REVERTIBLE_TYPE_TRAIT(__is_destructible);
790  REVERTIBLE_TYPE_TRAIT(__is_empty);
791  REVERTIBLE_TYPE_TRAIT(__is_enum);
792  REVERTIBLE_TYPE_TRAIT(__is_floating_point);
793  REVERTIBLE_TYPE_TRAIT(__is_final);
794  REVERTIBLE_TYPE_TRAIT(__is_function);
795  REVERTIBLE_TYPE_TRAIT(__is_fundamental);
796  REVERTIBLE_TYPE_TRAIT(__is_integral);
797  REVERTIBLE_TYPE_TRAIT(__is_interface_class);
798  REVERTIBLE_TYPE_TRAIT(__is_literal);
799  REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
800  REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
801  REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer);
802  REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer);
803  REVERTIBLE_TYPE_TRAIT(__is_member_pointer);
804  REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable);
805  REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible);
806  REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible);
807  REVERTIBLE_TYPE_TRAIT(__is_object);
808  REVERTIBLE_TYPE_TRAIT(__is_pod);
809  REVERTIBLE_TYPE_TRAIT(__is_pointer);
810  REVERTIBLE_TYPE_TRAIT(__is_polymorphic);
811  REVERTIBLE_TYPE_TRAIT(__is_reference);
812  REVERTIBLE_TYPE_TRAIT(__is_referenceable);
813  REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr);
814  REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference);
815  REVERTIBLE_TYPE_TRAIT(__is_same);
816  REVERTIBLE_TYPE_TRAIT(__is_scalar);
817  REVERTIBLE_TYPE_TRAIT(__is_scoped_enum);
818  REVERTIBLE_TYPE_TRAIT(__is_sealed);
819  REVERTIBLE_TYPE_TRAIT(__is_signed);
820  REVERTIBLE_TYPE_TRAIT(__is_standard_layout);
821  REVERTIBLE_TYPE_TRAIT(__is_trivial);
822  REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable);
823  REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible);
824  REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable);
825  REVERTIBLE_TYPE_TRAIT(__is_unbounded_array);
826  REVERTIBLE_TYPE_TRAIT(__is_union);
827  REVERTIBLE_TYPE_TRAIT(__is_unsigned);
828  REVERTIBLE_TYPE_TRAIT(__is_void);
829  REVERTIBLE_TYPE_TRAIT(__is_volatile);
830  REVERTIBLE_TYPE_TRAIT(__reference_binds_to_temporary);
831 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) \
832  REVERTIBLE_TYPE_TRAIT(RTT_JOIN(__, Trait));
833 #include "clang/Basic/TransformTypeTraits.def"
834 #undef REVERTIBLE_TYPE_TRAIT
835 #undef RTT_JOIN
836  }
837  llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known =
838  RevertibleTypeTraits.find(II);
839  if (Known != RevertibleTypeTraits.end()) {
840  if (Kind)
841  *Kind = Known->second;
842  return true;
843  }
844  return false;
845 }
846 
847 ExprResult Parser::ParseBuiltinPtrauthTypeDiscriminator() {
849 
850  BalancedDelimiterTracker T(*this, tok::l_paren);
851  if (T.expectAndConsume())
852  return ExprError();
853 
854  TypeResult Ty = ParseTypeName();
855  if (Ty.isInvalid()) {
856  SkipUntil(tok::r_paren, StopAtSemi);
857  return ExprError();
858  }
859 
860  SourceLocation EndLoc = Tok.getLocation();
861  T.consumeClose();
862  return Actions.ActOnUnaryExprOrTypeTraitExpr(
863  Loc, UETT_PtrAuthTypeDiscriminator,
864  /*isType=*/true, Ty.get().getAsOpaquePtr(), SourceRange(Loc, EndLoc));
865 }
866 
867 /// Parse a cast-expression, or, if \pisUnaryExpression is true, parse
868 /// a unary-expression.
869 ///
870 /// \p isAddressOfOperand exists because an id-expression that is the operand
871 /// of address-of gets special treatment due to member pointers. NotCastExpr
872 /// is set to true if the token is not the start of a cast-expression, and no
873 /// diagnostic is emitted in this case and no tokens are consumed.
874 ///
875 /// \verbatim
876 /// cast-expression: [C99 6.5.4]
877 /// unary-expression
878 /// '(' type-name ')' cast-expression
879 ///
880 /// unary-expression: [C99 6.5.3]
881 /// postfix-expression
882 /// '++' unary-expression
883 /// '--' unary-expression
884 /// [Coro] 'co_await' cast-expression
885 /// unary-operator cast-expression
886 /// 'sizeof' unary-expression
887 /// 'sizeof' '(' type-name ')'
888 /// [C++11] 'sizeof' '...' '(' identifier ')'
889 /// [GNU] '__alignof' unary-expression
890 /// [GNU] '__alignof' '(' type-name ')'
891 /// [C11] '_Alignof' '(' type-name ')'
892 /// [C++11] 'alignof' '(' type-id ')'
893 /// [GNU] '&&' identifier
894 /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7]
895 /// [C++] new-expression
896 /// [C++] delete-expression
897 ///
898 /// unary-operator: one of
899 /// '&' '*' '+' '-' '~' '!'
900 /// [GNU] '__extension__' '__real' '__imag'
901 ///
902 /// primary-expression: [C99 6.5.1]
903 /// [C99] identifier
904 /// [C++] id-expression
905 /// constant
906 /// string-literal
907 /// [C++] boolean-literal [C++ 2.13.5]
908 /// [C++11] 'nullptr' [C++11 2.14.7]
909 /// [C++11] user-defined-literal
910 /// '(' expression ')'
911 /// [C11] generic-selection
912 /// [C++2a] requires-expression
913 /// '__func__' [C99 6.4.2.2]
914 /// [GNU] '__FUNCTION__'
915 /// [MS] '__FUNCDNAME__'
916 /// [MS] 'L__FUNCTION__'
917 /// [MS] '__FUNCSIG__'
918 /// [MS] 'L__FUNCSIG__'
919 /// [GNU] '__PRETTY_FUNCTION__'
920 /// [GNU] '(' compound-statement ')'
921 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
922 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
923 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
924 /// assign-expr ')'
925 /// [GNU] '__builtin_FILE' '(' ')'
926 /// [CLANG] '__builtin_FILE_NAME' '(' ')'
927 /// [GNU] '__builtin_FUNCTION' '(' ')'
928 /// [MS] '__builtin_FUNCSIG' '(' ')'
929 /// [GNU] '__builtin_LINE' '(' ')'
930 /// [CLANG] '__builtin_COLUMN' '(' ')'
931 /// [GNU] '__builtin_source_location' '(' ')'
932 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
933 /// [GNU] '__null'
934 /// [OBJC] '[' objc-message-expr ']'
935 /// [OBJC] '\@selector' '(' objc-selector-arg ')'
936 /// [OBJC] '\@protocol' '(' identifier ')'
937 /// [OBJC] '\@encode' '(' type-name ')'
938 /// [OBJC] objc-string-literal
939 /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
940 /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3]
941 /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3]
942 /// [C++11] typename-specifier braced-init-list [C++11 5.2.3]
943 /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
944 /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
945 /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
946 /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1]
947 /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1]
948 /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1]
949 /// [C++] 'this' [C++ 9.3.2]
950 /// [G++] unary-type-trait '(' type-id ')'
951 /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO]
952 /// [EMBT] array-type-trait '(' type-id ',' integer ')'
953 /// [clang] '^' block-literal
954 ///
955 /// constant: [C99 6.4.4]
956 /// integer-constant
957 /// floating-constant
958 /// enumeration-constant -> identifier
959 /// character-constant
960 ///
961 /// id-expression: [C++ 5.1]
962 /// unqualified-id
963 /// qualified-id
964 ///
965 /// unqualified-id: [C++ 5.1]
966 /// identifier
967 /// operator-function-id
968 /// conversion-function-id
969 /// '~' class-name
970 /// template-id
971 ///
972 /// new-expression: [C++ 5.3.4]
973 /// '::'[opt] 'new' new-placement[opt] new-type-id
974 /// new-initializer[opt]
975 /// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
976 /// new-initializer[opt]
977 ///
978 /// delete-expression: [C++ 5.3.5]
979 /// '::'[opt] 'delete' cast-expression
980 /// '::'[opt] 'delete' '[' ']' cast-expression
981 ///
982 /// [GNU/Embarcadero] unary-type-trait:
983 /// '__is_arithmetic'
984 /// '__is_floating_point'
985 /// '__is_integral'
986 /// '__is_lvalue_expr'
987 /// '__is_rvalue_expr'
988 /// '__is_complete_type'
989 /// '__is_void'
990 /// '__is_array'
991 /// '__is_function'
992 /// '__is_reference'
993 /// '__is_lvalue_reference'
994 /// '__is_rvalue_reference'
995 /// '__is_fundamental'
996 /// '__is_object'
997 /// '__is_scalar'
998 /// '__is_compound'
999 /// '__is_pointer'
1000 /// '__is_member_object_pointer'
1001 /// '__is_member_function_pointer'
1002 /// '__is_member_pointer'
1003 /// '__is_const'
1004 /// '__is_volatile'
1005 /// '__is_trivial'
1006 /// '__is_standard_layout'
1007 /// '__is_signed'
1008 /// '__is_unsigned'
1009 ///
1010 /// [GNU] unary-type-trait:
1011 /// '__has_nothrow_assign'
1012 /// '__has_nothrow_copy'
1013 /// '__has_nothrow_constructor'
1014 /// '__has_trivial_assign' [TODO]
1015 /// '__has_trivial_copy' [TODO]
1016 /// '__has_trivial_constructor'
1017 /// '__has_trivial_destructor'
1018 /// '__has_virtual_destructor'
1019 /// '__is_abstract' [TODO]
1020 /// '__is_class'
1021 /// '__is_empty' [TODO]
1022 /// '__is_enum'
1023 /// '__is_final'
1024 /// '__is_pod'
1025 /// '__is_polymorphic'
1026 /// '__is_sealed' [MS]
1027 /// '__is_trivial'
1028 /// '__is_union'
1029 /// '__has_unique_object_representations'
1030 ///
1031 /// [Clang] unary-type-trait:
1032 /// '__is_aggregate'
1033 /// '__trivially_copyable'
1034 ///
1035 /// binary-type-trait:
1036 /// [GNU] '__is_base_of'
1037 /// [MS] '__is_convertible_to'
1038 /// '__is_convertible'
1039 /// '__is_same'
1040 ///
1041 /// [Embarcadero] array-type-trait:
1042 /// '__array_rank'
1043 /// '__array_extent'
1044 ///
1045 /// [Embarcadero] expression-trait:
1046 /// '__is_lvalue_expr'
1047 /// '__is_rvalue_expr'
1048 /// \endverbatim
1049 ///
1050 ExprResult Parser::ParseCastExpression(CastParseKind ParseKind,
1051  bool isAddressOfOperand,
1052  bool &NotCastExpr,
1053  TypeCastState isTypeCast,
1054  bool isVectorLiteral,
1055  bool *NotPrimaryExpression) {
1056  ExprResult Res;
1057  tok::TokenKind SavedKind = Tok.getKind();
1058  auto SavedType = PreferredType;
1059  NotCastExpr = false;
1060 
1061  // Are postfix-expression suffix operators permitted after this
1062  // cast-expression? If not, and we find some, we'll parse them anyway and
1063  // diagnose them.
1064  bool AllowSuffix = true;
1065 
1066  // This handles all of cast-expression, unary-expression, postfix-expression,
1067  // and primary-expression. We handle them together like this for efficiency
1068  // and to simplify handling of an expression starting with a '(' token: which
1069  // may be one of a parenthesized expression, cast-expression, compound literal
1070  // expression, or statement expression.
1071  //
1072  // If the parsed tokens consist of a primary-expression, the cases below
1073  // break out of the switch; at the end we call ParsePostfixExpressionSuffix
1074  // to handle the postfix expression suffixes. Cases that cannot be followed
1075  // by postfix exprs should set AllowSuffix to false.
1076  switch (SavedKind) {
1077  case tok::l_paren: {
1078  // If this expression is limited to being a unary-expression, the paren can
1079  // not start a cast expression.
1080  ParenParseOption ParenExprType;
1081  switch (ParseKind) {
1082  case CastParseKind::UnaryExprOnly:
1083  assert(getLangOpts().CPlusPlus && "not possible to get here in C");
1084  [[fallthrough]];
1085  case CastParseKind::AnyCastExpr:
1086  ParenExprType = ParenParseOption::CastExpr;
1087  break;
1088  case CastParseKind::PrimaryExprOnly:
1089  ParenExprType = FoldExpr;
1090  break;
1091  }
1092  ParsedType CastTy;
1093  SourceLocation RParenLoc;
1094  Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/,
1095  isTypeCast == IsTypeCast, CastTy, RParenLoc);
1096 
1097  // FIXME: What should we do if a vector literal is followed by a
1098  // postfix-expression suffix? Usually postfix operators are permitted on
1099  // literals.
1100  if (isVectorLiteral)
1101  return Res;
1102 
1103  switch (ParenExprType) {
1104  case SimpleExpr: break; // Nothing else to do.
1105  case CompoundStmt: break; // Nothing else to do.
1106  case CompoundLiteral:
1107  // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of
1108  // postfix-expression exist, parse them now.
1109  break;
1110  case CastExpr:
1111  // We have parsed the cast-expression and no postfix-expr pieces are
1112  // following.
1113  return Res;
1114  case FoldExpr:
1115  // We only parsed a fold-expression. There might be postfix-expr pieces
1116  // afterwards; parse them now.
1117  break;
1118  }
1119 
1120  break;
1121  }
1122 
1123  // primary-expression
1124  case tok::numeric_constant:
1125  case tok::binary_data:
1126  // constant: integer-constant
1127  // constant: floating-constant
1128 
1129  Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope());
1130  ConsumeToken();
1131  break;
1132 
1133  case tok::kw_true:
1134  case tok::kw_false:
1135  Res = ParseCXXBoolLiteral();
1136  break;
1137 
1138  case tok::kw___objc_yes:
1139  case tok::kw___objc_no:
1140  Res = ParseObjCBoolLiteral();
1141  break;
1142 
1143  case tok::kw_nullptr:
1144  if (getLangOpts().CPlusPlus)
1145  Diag(Tok, diag::warn_cxx98_compat_nullptr);
1146  else
1147  Diag(Tok, getLangOpts().C23 ? diag::warn_c23_compat_keyword
1148  : diag::ext_c_nullptr) << Tok.getName();
1149 
1150  Res = Actions.ActOnCXXNullPtrLiteral(ConsumeToken());
1151  break;
1152 
1153  case tok::annot_primary_expr:
1154  case tok::annot_overload_set:
1155  Res = getExprAnnotation(Tok);
1156  if (!Res.isInvalid() && Tok.getKind() == tok::annot_overload_set)
1157  Res = Actions.ActOnNameClassifiedAsOverloadSet(getCurScope(), Res.get());
1158  ConsumeAnnotationToken();
1159  if (!Res.isInvalid() && Tok.is(tok::less))
1160  checkPotentialAngleBracket(Res);
1161  break;
1162 
1163  case tok::annot_non_type:
1164  case tok::annot_non_type_dependent:
1165  case tok::annot_non_type_undeclared: {
1166  CXXScopeSpec SS;
1167  Token Replacement;
1168  Res = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
1169  assert(!Res.isUnset() &&
1170  "should not perform typo correction on annotation token");
1171  break;
1172  }
1173 
1174  case tok::annot_embed: {
1175  injectEmbedTokens();
1176  return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1177  isVectorLiteral, NotPrimaryExpression);
1178  }
1179 
1180  case tok::kw___super:
1181  case tok::kw_decltype:
1182  // Annotate the token and tail recurse.
1184  return ExprError();
1185  assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super));
1186  return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1187  isVectorLiteral, NotPrimaryExpression);
1188 
1189  case tok::identifier:
1190  ParseIdentifier: { // primary-expression: identifier
1191  // unqualified-id: identifier
1192  // constant: enumeration-constant
1193  // Turn a potentially qualified name into a annot_typename or
1194  // annot_cxxscope if it would be valid. This handles things like x::y, etc.
1195  if (getLangOpts().CPlusPlus) {
1196  // Avoid the unnecessary parse-time lookup in the common case
1197  // where the syntax forbids a type.
1198  Token Next = NextToken();
1199 
1200  if (Next.is(tok::ellipsis) && Tok.is(tok::identifier) &&
1201  GetLookAheadToken(2).is(tok::l_square)) {
1202  // Annotate the token and tail recurse.
1203  // If the token is not annotated, then it might be an expression pack
1204  // indexing
1205  if (!TryAnnotateTypeOrScopeToken() &&
1206  Tok.is(tok::annot_pack_indexing_type))
1207  return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1208  isVectorLiteral, NotPrimaryExpression);
1209  }
1210 
1211  // If this identifier was reverted from a token ID, and the next token
1212  // is a parenthesis, this is likely to be a use of a type trait. Check
1213  // those tokens.
1214  else if (Next.is(tok::l_paren) && Tok.is(tok::identifier) &&
1216  IdentifierInfo *II = Tok.getIdentifierInfo();
1218  if (isRevertibleTypeTrait(II, &Kind)) {
1219  Tok.setKind(Kind);
1220  return ParseCastExpression(ParseKind, isAddressOfOperand,
1221  NotCastExpr, isTypeCast,
1222  isVectorLiteral, NotPrimaryExpression);
1223  }
1224  }
1225 
1226  else if ((!ColonIsSacred && Next.is(tok::colon)) ||
1227  Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren,
1228  tok::l_brace)) {
1229  // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1231  return ExprError();
1232  if (!Tok.is(tok::identifier))
1233  return ParseCastExpression(ParseKind, isAddressOfOperand,
1234  NotCastExpr, isTypeCast,
1235  isVectorLiteral,
1236  NotPrimaryExpression);
1237  }
1238  }
1239 
1240  // Consume the identifier so that we can see if it is followed by a '(' or
1241  // '.'.
1242  IdentifierInfo &II = *Tok.getIdentifierInfo();
1243  SourceLocation ILoc = ConsumeToken();
1244 
1245  // Support 'Class.property' and 'super.property' notation.
1246  if (getLangOpts().ObjC && Tok.is(tok::period) &&
1247  (Actions.getTypeName(II, ILoc, getCurScope()) ||
1248  // Allow the base to be 'super' if in an objc-method.
1249  (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) {
1250  ConsumeToken();
1251 
1252  if (Tok.is(tok::code_completion) && &II != Ident_super) {
1253  cutOffParsing();
1255  getCurScope(), II, ILoc, ExprStatementTokLoc == ILoc);
1256  return ExprError();
1257  }
1258  // Allow either an identifier or the keyword 'class' (in C++).
1259  if (Tok.isNot(tok::identifier) &&
1260  !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) {
1261  Diag(Tok, diag::err_expected_property_name);
1262  return ExprError();
1263  }
1264  IdentifierInfo &PropertyName = *Tok.getIdentifierInfo();
1265  SourceLocation PropertyLoc = ConsumeToken();
1266 
1267  Res = Actions.ObjC().ActOnClassPropertyRefExpr(II, PropertyName, ILoc,
1268  PropertyLoc);
1269  break;
1270  }
1271 
1272  // In an Objective-C method, if we have "super" followed by an identifier,
1273  // the token sequence is ill-formed. However, if there's a ':' or ']' after
1274  // that identifier, this is probably a message send with a missing open
1275  // bracket. Treat it as such.
1276  if (getLangOpts().ObjC && &II == Ident_super && !InMessageExpression &&
1277  getCurScope()->isInObjcMethodScope() &&
1278  ((Tok.is(tok::identifier) &&
1279  (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) ||
1280  Tok.is(tok::code_completion))) {
1281  Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, nullptr,
1282  nullptr);
1283  break;
1284  }
1285 
1286  // If we have an Objective-C class name followed by an identifier
1287  // and either ':' or ']', this is an Objective-C class message
1288  // send that's missing the opening '['. Recovery
1289  // appropriately. Also take this path if we're performing code
1290  // completion after an Objective-C class name.
1291  if (getLangOpts().ObjC &&
1292  ((Tok.is(tok::identifier) && !InMessageExpression) ||
1293  Tok.is(tok::code_completion))) {
1294  const Token& Next = NextToken();
1295  if (Tok.is(tok::code_completion) ||
1296  Next.is(tok::colon) || Next.is(tok::r_square))
1297  if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope()))
1298  if (Typ.get()->isObjCObjectOrInterfaceType()) {
1299  // Fake up a Declarator to use with ActOnTypeName.
1300  DeclSpec DS(AttrFactory);
1301  DS.SetRangeStart(ILoc);
1302  DS.SetRangeEnd(ILoc);
1303  const char *PrevSpec = nullptr;
1304  unsigned DiagID;
1305  DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ,
1306  Actions.getASTContext().getPrintingPolicy());
1307 
1308  Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1310  TypeResult Ty = Actions.ActOnTypeName(DeclaratorInfo);
1311  if (Ty.isInvalid())
1312  break;
1313 
1314  Res = ParseObjCMessageExpressionBody(SourceLocation(),
1315  SourceLocation(),
1316  Ty.get(), nullptr);
1317  break;
1318  }
1319  }
1320 
1321  // Make sure to pass down the right value for isAddressOfOperand.
1322  if (isAddressOfOperand && isPostfixExpressionSuffixStart())
1323  isAddressOfOperand = false;
1324 
1325  // Function designators are allowed to be undeclared (C99 6.5.1p2), so we
1326  // need to know whether or not this identifier is a function designator or
1327  // not.
1328  UnqualifiedId Name;
1329  CXXScopeSpec ScopeSpec;
1330  SourceLocation TemplateKWLoc;
1331  Token Replacement;
1332  CastExpressionIdValidator Validator(
1333  /*Next=*/Tok,
1334  /*AllowTypes=*/isTypeCast != NotTypeCast,
1335  /*AllowNonTypes=*/isTypeCast != IsTypeCast);
1336  Validator.IsAddressOfOperand = isAddressOfOperand;
1337  if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) {
1338  Validator.WantExpressionKeywords = false;
1339  Validator.WantRemainingKeywords = false;
1340  } else {
1341  Validator.WantRemainingKeywords = Tok.isNot(tok::r_paren);
1342  }
1343  Name.setIdentifier(&II, ILoc);
1344  Res = Actions.ActOnIdExpression(
1345  getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren),
1346  isAddressOfOperand, &Validator,
1347  /*IsInlineAsmIdentifier=*/false,
1348  Tok.is(tok::r_paren) ? nullptr : &Replacement);
1349  if (!Res.isInvalid() && Res.isUnset()) {
1350  UnconsumeToken(Replacement);
1351  return ParseCastExpression(ParseKind, isAddressOfOperand,
1352  NotCastExpr, isTypeCast,
1353  /*isVectorLiteral=*/false,
1354  NotPrimaryExpression);
1355  }
1356  Res = tryParseCXXPackIndexingExpression(Res);
1357  if (!Res.isInvalid() && Tok.is(tok::less))
1358  checkPotentialAngleBracket(Res);
1359  break;
1360  }
1361  case tok::char_constant: // constant: character-constant
1362  case tok::wide_char_constant:
1363  case tok::utf8_char_constant:
1364  case tok::utf16_char_constant:
1365  case tok::utf32_char_constant:
1366  Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope());
1367  ConsumeToken();
1368  break;
1369  case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2]
1370  case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU]
1371  case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS]
1372  case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS]
1373  case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS]
1374  case tok::kw_L__FUNCSIG__: // primary-expression: L__FUNCSIG__ [MS]
1375  case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU]
1376  // Function local predefined macros are represented by PredefinedExpr except
1377  // when Microsoft extensions are enabled and one of these macros is adjacent
1378  // to a string literal or another one of these macros.
1379  if (!(getLangOpts().MicrosoftExt &&
1382  Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
1383  ConsumeToken();
1384  break;
1385  }
1386  [[fallthrough]]; // treat MS function local macros as concatenable strings
1387  case tok::string_literal: // primary-expression: string-literal
1388  case tok::wide_string_literal:
1389  case tok::utf8_string_literal:
1390  case tok::utf16_string_literal:
1391  case tok::utf32_string_literal:
1392  Res = ParseStringLiteralExpression(true);
1393  break;
1394  case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1]
1395  Res = ParseGenericSelectionExpression();
1396  break;
1397  case tok::kw___builtin_available:
1398  Res = ParseAvailabilityCheckExpr(Tok.getLocation());
1399  break;
1400  case tok::kw___builtin_va_arg:
1401  case tok::kw___builtin_offsetof:
1402  case tok::kw___builtin_choose_expr:
1403  case tok::kw___builtin_astype: // primary-expression: [OCL] as_type()
1404  case tok::kw___builtin_convertvector:
1405  case tok::kw___builtin_COLUMN:
1406  case tok::kw___builtin_FILE:
1407  case tok::kw___builtin_FILE_NAME:
1408  case tok::kw___builtin_FUNCTION:
1409  case tok::kw___builtin_FUNCSIG:
1410  case tok::kw___builtin_LINE:
1411  case tok::kw___builtin_source_location:
1412  if (NotPrimaryExpression)
1413  *NotPrimaryExpression = true;
1414  // This parses the complete suffix; we can return early.
1415  return ParseBuiltinPrimaryExpression();
1416  case tok::kw___null:
1417  Res = Actions.ActOnGNUNullExpr(ConsumeToken());
1418  break;
1419 
1420  case tok::plusplus: // unary-expression: '++' unary-expression [C99]
1421  case tok::minusminus: { // unary-expression: '--' unary-expression [C99]
1422  if (NotPrimaryExpression)
1423  *NotPrimaryExpression = true;
1424  // C++ [expr.unary] has:
1425  // unary-expression:
1426  // ++ cast-expression
1427  // -- cast-expression
1428  Token SavedTok = Tok;
1429  ConsumeToken();
1430 
1431  PreferredType.enterUnary(Actions, Tok.getLocation(), SavedTok.getKind(),
1432  SavedTok.getLocation());
1433  // One special case is implicitly handled here: if the preceding tokens are
1434  // an ambiguous cast expression, such as "(T())++", then we recurse to
1435  // determine whether the '++' is prefix or postfix.
1436  Res = ParseCastExpression(getLangOpts().CPlusPlus ?
1437  UnaryExprOnly : AnyCastExpr,
1438  /*isAddressOfOperand*/false, NotCastExpr,
1439  NotTypeCast);
1440  if (NotCastExpr) {
1441  // If we return with NotCastExpr = true, we must not consume any tokens,
1442  // so put the token back where we found it.
1443  assert(Res.isInvalid());
1444  UnconsumeToken(SavedTok);
1445  return ExprError();
1446  }
1447  if (!Res.isInvalid()) {
1448  Expr *Arg = Res.get();
1449  Res = Actions.ActOnUnaryOp(getCurScope(), SavedTok.getLocation(),
1450  SavedKind, Arg);
1451  if (Res.isInvalid())
1452  Res = Actions.CreateRecoveryExpr(SavedTok.getLocation(),
1453  Arg->getEndLoc(), Arg);
1454  }
1455  return Res;
1456  }
1457  case tok::amp: { // unary-expression: '&' cast-expression
1458  if (NotPrimaryExpression)
1459  *NotPrimaryExpression = true;
1460  // Special treatment because of member pointers
1461  SourceLocation SavedLoc = ConsumeToken();
1462  PreferredType.enterUnary(Actions, Tok.getLocation(), tok::amp, SavedLoc);
1463 
1464  Res = ParseCastExpression(AnyCastExpr, /*isAddressOfOperand=*/true);
1465  if (!Res.isInvalid()) {
1466  Expr *Arg = Res.get();
1467  Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg);
1468  if (Res.isInvalid())
1469  Res = Actions.CreateRecoveryExpr(Tok.getLocation(), Arg->getEndLoc(),
1470  Arg);
1471  }
1472  return Res;
1473  }
1474 
1475  case tok::star: // unary-expression: '*' cast-expression
1476  case tok::plus: // unary-expression: '+' cast-expression
1477  case tok::minus: // unary-expression: '-' cast-expression
1478  case tok::tilde: // unary-expression: '~' cast-expression
1479  case tok::exclaim: // unary-expression: '!' cast-expression
1480  case tok::kw___real: // unary-expression: '__real' cast-expression [GNU]
1481  case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU]
1482  if (NotPrimaryExpression)
1483  *NotPrimaryExpression = true;
1484  SourceLocation SavedLoc = ConsumeToken();
1485  PreferredType.enterUnary(Actions, Tok.getLocation(), SavedKind, SavedLoc);
1486  Res = ParseCastExpression(AnyCastExpr);
1487  if (!Res.isInvalid()) {
1488  Expr *Arg = Res.get();
1489  Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Arg,
1490  isAddressOfOperand);
1491  if (Res.isInvalid())
1492  Res = Actions.CreateRecoveryExpr(SavedLoc, Arg->getEndLoc(), Arg);
1493  }
1494  return Res;
1495  }
1496 
1497  case tok::kw_co_await: { // unary-expression: 'co_await' cast-expression
1498  if (NotPrimaryExpression)
1499  *NotPrimaryExpression = true;
1500  SourceLocation CoawaitLoc = ConsumeToken();
1501  Res = ParseCastExpression(AnyCastExpr);
1502  if (!Res.isInvalid())
1503  Res = Actions.ActOnCoawaitExpr(getCurScope(), CoawaitLoc, Res.get());
1504  return Res;
1505  }
1506 
1507  case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU]
1508  // __extension__ silences extension warnings in the subexpression.
1509  if (NotPrimaryExpression)
1510  *NotPrimaryExpression = true;
1511  ExtensionRAIIObject O(Diags); // Use RAII to do this.
1512  SourceLocation SavedLoc = ConsumeToken();
1513  Res = ParseCastExpression(AnyCastExpr);
1514  if (!Res.isInvalid())
1515  Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get());
1516  return Res;
1517  }
1518  case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')'
1519  diagnoseUseOfC11Keyword(Tok);
1520  [[fallthrough]];
1521  case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')'
1522  case tok::kw___alignof: // unary-expression: '__alignof' unary-expression
1523  // unary-expression: '__alignof' '(' type-name ')'
1524  case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression
1525  // unary-expression: 'sizeof' '(' type-name ')'
1526  // unary-expression: '__datasizeof' unary-expression
1527  // unary-expression: '__datasizeof' '(' type-name ')'
1528  case tok::kw___datasizeof:
1529  case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression
1530  // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')'
1531  case tok::kw___builtin_omp_required_simd_align:
1532  case tok::kw___builtin_vectorelements:
1533  if (NotPrimaryExpression)
1534  *NotPrimaryExpression = true;
1535  AllowSuffix = false;
1536  Res = ParseUnaryExprOrTypeTraitExpression();
1537  break;
1538  case tok::ampamp: { // unary-expression: '&&' identifier
1539  if (NotPrimaryExpression)
1540  *NotPrimaryExpression = true;
1541  SourceLocation AmpAmpLoc = ConsumeToken();
1542  if (Tok.isNot(tok::identifier))
1543  return ExprError(Diag(Tok, diag::err_expected) << tok::identifier);
1544 
1545  if (getCurScope()->getFnParent() == nullptr)
1546  return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn));
1547 
1548  Diag(AmpAmpLoc, diag::ext_gnu_address_of_label);
1549  LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
1550  Tok.getLocation());
1551  Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD);
1552  ConsumeToken();
1553  AllowSuffix = false;
1554  break;
1555  }
1556  case tok::kw_const_cast:
1557  case tok::kw_dynamic_cast:
1558  case tok::kw_reinterpret_cast:
1559  case tok::kw_static_cast:
1560  case tok::kw_addrspace_cast:
1561  if (NotPrimaryExpression)
1562  *NotPrimaryExpression = true;
1563  Res = ParseCXXCasts();
1564  break;
1565  case tok::kw___builtin_bit_cast:
1566  if (NotPrimaryExpression)
1567  *NotPrimaryExpression = true;
1568  Res = ParseBuiltinBitCast();
1569  break;
1570  case tok::kw_typeid:
1571  if (NotPrimaryExpression)
1572  *NotPrimaryExpression = true;
1573  Res = ParseCXXTypeid();
1574  break;
1575  case tok::kw___uuidof:
1576  if (NotPrimaryExpression)
1577  *NotPrimaryExpression = true;
1578  Res = ParseCXXUuidof();
1579  break;
1580  case tok::kw_this:
1581  Res = ParseCXXThis();
1582  break;
1583  case tok::kw___builtin_sycl_unique_stable_name:
1584  Res = ParseSYCLUniqueStableNameExpression();
1585  break;
1586  case tok::kw___builtin_sycl_unique_stable_id:
1587  Res = ParseSYCLUniqueStableIdExpression();
1588  break;
1589 
1590  case tok::annot_typename:
1591  if (isStartOfObjCClassMessageMissingOpenBracket()) {
1593 
1594  // Fake up a Declarator to use with ActOnTypeName.
1595  DeclSpec DS(AttrFactory);
1596  DS.SetRangeStart(Tok.getLocation());
1597  DS.SetRangeEnd(Tok.getLastLoc());
1598 
1599  const char *PrevSpec = nullptr;
1600  unsigned DiagID;
1601  DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(),
1602  PrevSpec, DiagID, Type,
1603  Actions.getASTContext().getPrintingPolicy());
1604 
1605  Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
1607  TypeResult Ty = Actions.ActOnTypeName(DeclaratorInfo);
1608  if (Ty.isInvalid())
1609  break;
1610 
1611  ConsumeAnnotationToken();
1612  Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
1613  Ty.get(), nullptr);
1614  break;
1615  }
1616  [[fallthrough]];
1617 
1618  case tok::annot_decltype:
1619  case tok::annot_pack_indexing_type:
1620  case tok::kw_char:
1621  case tok::kw_wchar_t:
1622  case tok::kw_char8_t:
1623  case tok::kw_char16_t:
1624  case tok::kw_char32_t:
1625  case tok::kw_bool:
1626  case tok::kw_short:
1627  case tok::kw_int:
1628  case tok::kw_long:
1629  case tok::kw___int64:
1630  case tok::kw___int128:
1631  case tok::kw__ExtInt:
1632  case tok::kw__BitInt:
1633  case tok::kw_signed:
1634  case tok::kw_unsigned:
1635  case tok::kw_half:
1636  case tok::kw_float:
1637  case tok::kw_double:
1638  case tok::kw___bf16:
1639  case tok::kw__Float16:
1640  case tok::kw___float128:
1641  case tok::kw___ibm128:
1642  case tok::kw_void:
1643  case tok::kw_auto:
1644  case tok::kw_typename:
1645  case tok::kw_typeof:
1646  case tok::kw___vector:
1647  case tok::kw__Accum:
1648  case tok::kw__Fract:
1649  case tok::kw__Sat:
1650 #define GENERIC_IMAGE_TYPE(ImgType, Id) case tok::kw_##ImgType##_t:
1651 #include "clang/Basic/OpenCLImageTypes.def"
1652 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case tok::kw_##Name:
1653 #include "clang/Basic/HLSLIntangibleTypes.def"
1654  {
1655  if (!getLangOpts().CPlusPlus) {
1656  Diag(Tok, diag::err_expected_expression);
1657  return ExprError();
1658  }
1659 
1660  // Everything henceforth is a postfix-expression.
1661  if (NotPrimaryExpression)
1662  *NotPrimaryExpression = true;
1663 
1664  if (SavedKind == tok::kw_typename) {
1665  // postfix-expression: typename-specifier '(' expression-list[opt] ')'
1666  // typename-specifier braced-init-list
1668  return ExprError();
1669 
1670  if (!Tok.isSimpleTypeSpecifier(getLangOpts()))
1671  // We are trying to parse a simple-type-specifier but might not get such
1672  // a token after error recovery.
1673  return ExprError();
1674  }
1675 
1676  // postfix-expression: simple-type-specifier '(' expression-list[opt] ')'
1677  // simple-type-specifier braced-init-list
1678  //
1679  DeclSpec DS(AttrFactory);
1680 
1681  ParseCXXSimpleTypeSpecifier(DS);
1682  if (Tok.isNot(tok::l_paren) &&
1683  (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace)))
1684  return ExprError(Diag(Tok, diag::err_expected_lparen_after_type)
1685  << DS.getSourceRange());
1686 
1687  if (Tok.is(tok::l_brace))
1688  Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
1689 
1690  Res = ParseCXXTypeConstructExpression(DS);
1691  break;
1692  }
1693 
1694  case tok::annot_cxxscope: { // [C++] id-expression: qualified-id
1695  // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse.
1696  // (We can end up in this situation after tentative parsing.)
1698  return ExprError();
1699  if (!Tok.is(tok::annot_cxxscope))
1700  return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
1701  isTypeCast, isVectorLiteral,
1702  NotPrimaryExpression);
1703 
1704  Token Next = NextToken();
1705  if (Next.is(tok::annot_template_id)) {
1706  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next);
1707  if (TemplateId->Kind == TNK_Type_template) {
1708  // We have a qualified template-id that we know refers to a
1709  // type, translate it into a type and continue parsing as a
1710  // cast expression.
1711  CXXScopeSpec SS;
1712  ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
1713  /*ObjectHasErrors=*/false,
1714  /*EnteringContext=*/false);
1715  AnnotateTemplateIdTokenAsType(SS, ImplicitTypenameContext::Yes);
1716  return ParseCastExpression(ParseKind, isAddressOfOperand, NotCastExpr,
1717  isTypeCast, isVectorLiteral,
1718  NotPrimaryExpression);
1719  }
1720  }
1721 
1722  // Parse as an id-expression.
1723  Res = ParseCXXIdExpression(isAddressOfOperand);
1724  break;
1725  }
1726 
1727  case tok::annot_template_id: { // [C++] template-id
1728  TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
1729  if (TemplateId->Kind == TNK_Type_template) {
1730  // We have a template-id that we know refers to a type,
1731  // translate it into a type and continue parsing as a cast
1732  // expression.
1733  CXXScopeSpec SS;
1734  AnnotateTemplateIdTokenAsType(SS, ImplicitTypenameContext::Yes);
1735  return ParseCastExpression(ParseKind, isAddressOfOperand,
1736  NotCastExpr, isTypeCast, isVectorLiteral,
1737  NotPrimaryExpression);
1738  }
1739 
1740  // Fall through to treat the template-id as an id-expression.
1741  [[fallthrough]];
1742  }
1743 
1744  case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id
1745  Res = ParseCXXIdExpression(isAddressOfOperand);
1746  break;
1747 
1748  case tok::coloncolon: {
1749  // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken
1750  // annotates the token, tail recurse.
1752  return ExprError();
1753  if (!Tok.is(tok::coloncolon))
1754  return ParseCastExpression(ParseKind, isAddressOfOperand, isTypeCast,
1755  isVectorLiteral, NotPrimaryExpression);
1756 
1757  // ::new -> [C++] new-expression
1758  // ::delete -> [C++] delete-expression
1759  SourceLocation CCLoc = ConsumeToken();
1760  if (Tok.is(tok::kw_new)) {
1761  if (NotPrimaryExpression)
1762  *NotPrimaryExpression = true;
1763  Res = ParseCXXNewExpression(true, CCLoc);
1764  AllowSuffix = false;
1765  break;
1766  }
1767  if (Tok.is(tok::kw_delete)) {
1768  if (NotPrimaryExpression)
1769  *NotPrimaryExpression = true;
1770  Res = ParseCXXDeleteExpression(true, CCLoc);
1771  AllowSuffix = false;
1772  break;
1773  }
1774 
1775  // This is not a type name or scope specifier, it is an invalid expression.
1776  Diag(CCLoc, diag::err_expected_expression);
1777  return ExprError();
1778  }
1779 
1780  case tok::kw_new: // [C++] new-expression
1781  if (NotPrimaryExpression)
1782  *NotPrimaryExpression = true;
1783  Res = ParseCXXNewExpression(false, Tok.getLocation());
1784  AllowSuffix = false;
1785  break;
1786 
1787  case tok::kw_delete: // [C++] delete-expression
1788  if (NotPrimaryExpression)
1789  *NotPrimaryExpression = true;
1790  Res = ParseCXXDeleteExpression(false, Tok.getLocation());
1791  AllowSuffix = false;
1792  break;
1793 
1794  case tok::kw_requires: // [C++2a] requires-expression
1795  Res = ParseRequiresExpression();
1796  AllowSuffix = false;
1797  break;
1798 
1799  case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')'
1800  if (NotPrimaryExpression)
1801  *NotPrimaryExpression = true;
1802  Diag(Tok, diag::warn_cxx98_compat_noexcept_expr);
1803  SourceLocation KeyLoc = ConsumeToken();
1804  BalancedDelimiterTracker T(*this, tok::l_paren);
1805 
1806  if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept"))
1807  return ExprError();
1808  // C++11 [expr.unary.noexcept]p1:
1809  // The noexcept operator determines whether the evaluation of its operand,
1810  // which is an unevaluated operand, can throw an exception.
1813  Res = ParseExpression();
1814 
1815  T.consumeClose();
1816 
1817  if (!Res.isInvalid())
1818  Res = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(), Res.get(),
1819  T.getCloseLocation());
1820  AllowSuffix = false;
1821  break;
1822  }
1823 
1824 #define TYPE_TRAIT(N,Spelling,K) \
1825  case tok::kw_##Spelling:
1826 #include "clang/Basic/TokenKinds.def"
1827  Res = ParseTypeTrait();
1828  break;
1829 
1830  case tok::kw___builtin_num_fields:
1831  case tok::kw___builtin_num_bases:
1832  Res = ParseSYCLBuiltinNum();
1833  break;
1834  case tok::kw___builtin_field_type:
1835  case tok::kw___builtin_base_type:
1836  Res = ParseSYCLBuiltinType();
1837  break;
1838 
1839  case tok::kw___array_rank:
1840  case tok::kw___array_extent:
1841  if (NotPrimaryExpression)
1842  *NotPrimaryExpression = true;
1843  Res = ParseArrayTypeTrait();
1844  break;
1845 
1846  case tok::kw___builtin_ptrauth_type_discriminator:
1847  return ParseBuiltinPtrauthTypeDiscriminator();
1848 
1849  case tok::kw___is_lvalue_expr:
1850  case tok::kw___is_rvalue_expr:
1851  if (NotPrimaryExpression)
1852  *NotPrimaryExpression = true;
1853  Res = ParseExpressionTrait();
1854  break;
1855 
1856  case tok::at: {
1857  if (NotPrimaryExpression)
1858  *NotPrimaryExpression = true;
1859  SourceLocation AtLoc = ConsumeToken();
1860  return ParseObjCAtExpression(AtLoc);
1861  }
1862  case tok::caret:
1863  Res = ParseBlockLiteralExpression();
1864  break;
1865  case tok::code_completion: {
1866  cutOffParsing();
1868  getCurScope(), PreferredType.get(Tok.getLocation()));
1869  return ExprError();
1870  }
1871 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
1872 #include "clang/Basic/TransformTypeTraits.def"
1873  // HACK: libstdc++ uses some of the transform-type-traits as alias
1874  // templates, so we need to work around this.
1875  if (!NextToken().is(tok::l_paren)) {
1876  Tok.setKind(tok::identifier);
1877  Diag(Tok, diag::ext_keyword_as_ident)
1878  << Tok.getIdentifierInfo()->getName() << 0;
1879  goto ParseIdentifier;
1880  }
1881  goto ExpectedExpression;
1882  case tok::l_square:
1883  if (getLangOpts().CPlusPlus) {
1884  if (getLangOpts().ObjC) {
1885  // C++11 lambda expressions and Objective-C message sends both start with a
1886  // square bracket. There are three possibilities here:
1887  // we have a valid lambda expression, we have an invalid lambda
1888  // expression, or we have something that doesn't appear to be a lambda.
1889  // If we're in the last case, we fall back to ParseObjCMessageExpression.
1890  Res = TryParseLambdaExpression();
1891  if (!Res.isInvalid() && !Res.get()) {
1892  // We assume Objective-C++ message expressions are not
1893  // primary-expressions.
1894  if (NotPrimaryExpression)
1895  *NotPrimaryExpression = true;
1896  Res = ParseObjCMessageExpression();
1897  }
1898  break;
1899  }
1900  Res = ParseLambdaExpression();
1901  break;
1902  }
1903  if (getLangOpts().ObjC) {
1904  Res = ParseObjCMessageExpression();
1905  break;
1906  }
1907  [[fallthrough]];
1908  default:
1909  ExpectedExpression:
1910  NotCastExpr = true;
1911  return ExprError();
1912  }
1913 
1914  // Check to see whether Res is a function designator only. If it is and we
1915  // are compiling for OpenCL, we need to return an error as this implies
1916  // that the address of the function is being taken, which is illegal in CL.
1917 
1918  if (ParseKind == PrimaryExprOnly)
1919  // This is strictly a primary-expression - no postfix-expr pieces should be
1920  // parsed.
1921  return Res;
1922 
1923  if (!AllowSuffix) {
1924  // FIXME: Don't parse a primary-expression suffix if we encountered a parse
1925  // error already.
1926  if (Res.isInvalid())
1927  return Res;
1928 
1929  switch (Tok.getKind()) {
1930  case tok::l_square:
1931  case tok::l_paren:
1932  case tok::plusplus:
1933  case tok::minusminus:
1934  // "expected ';'" or similar is probably the right diagnostic here. Let
1935  // the caller decide what to do.
1936  if (Tok.isAtStartOfLine())
1937  return Res;
1938 
1939  [[fallthrough]];
1940  case tok::period:
1941  case tok::arrow:
1942  break;
1943 
1944  default:
1945  return Res;
1946  }
1947 
1948  // This was a unary-expression for which a postfix-expression suffix is
1949  // not permitted by the grammar (eg, a sizeof expression or
1950  // new-expression or similar). Diagnose but parse the suffix anyway.
1951  Diag(Tok.getLocation(), diag::err_postfix_after_unary_requires_parens)
1952  << Tok.getKind() << Res.get()->getSourceRange()
1953  << FixItHint::CreateInsertion(Res.get()->getBeginLoc(), "(")
1954  << FixItHint::CreateInsertion(PP.getLocForEndOfToken(PrevTokLocation),
1955  ")");
1956  }
1957 
1958  // These can be followed by postfix-expr pieces.
1959  PreferredType = SavedType;
1960  Res = ParsePostfixExpressionSuffix(Res);
1961  if (getLangOpts().OpenCL &&
1962  !getActions().getOpenCLOptions().isAvailableOption(
1963  "__cl_clang_function_pointers", getLangOpts()))
1964  if (Expr *PostfixExpr = Res.get()) {
1965  QualType Ty = PostfixExpr->getType();
1966  if (!Ty.isNull() && Ty->isFunctionType()) {
1967  Diag(PostfixExpr->getExprLoc(),
1968  diag::err_opencl_taking_function_address_parser);
1969  return ExprError();
1970  }
1971  }
1972 
1973  return Res;
1974 }
1975 
1976 /// __builtin_num_fields '(' type-id ')' or
1977 /// __builtin_num_bases '(' type-id ')'
1978 ExprResult Parser::ParseSYCLBuiltinNum() {
1979  assert(
1980  Tok.isOneOf(tok::kw___builtin_num_fields, tok::kw___builtin_num_bases));
1981  bool IsNumFields = Tok.is(tok::kw___builtin_num_fields);
1982  ConsumeToken(); // Eat the __builtin_num_* token
1983 
1984  BalancedDelimiterTracker T(*this, tok::l_paren);
1985  if (T.expectAndConsume(diag::err_expected_lparen_after, Tok.getName()))
1986  return ExprError();
1987 
1988  TypeResult TR = ParseTypeName();
1989  if (TR.isInvalid()) {
1990  SkipUntil(tok::r_paren, StopAtSemi);
1991  return ExprError();
1992  }
1993 
1994  T.consumeClose();
1995 
1996  if (IsNumFields)
1997  return Actions.SYCL().ActOnSYCLBuiltinNumFieldsExpr(TR.get());
1998  return Actions.SYCL().ActOnSYCLBuiltinNumBasesExpr(TR.get());
1999 }
2000 
2001 /// __builtin_field_type '(' type-id ',' integer-constant ')' or
2002 /// __builtin_base_type '(' type-id ',' integer-constant ')'
2003 ExprResult Parser::ParseSYCLBuiltinType() {
2004  assert(
2005  Tok.isOneOf(tok::kw___builtin_field_type, tok::kw___builtin_base_type));
2006  bool IsFieldType = Tok.is(tok::kw___builtin_field_type);
2007  ConsumeToken(); // Eat the __builtin_*_type token
2008 
2009  BalancedDelimiterTracker T(*this, tok::l_paren);
2010  if (T.expectAndConsume(diag::err_expected_lparen_after, Tok.getName()))
2011  return ExprError();
2012 
2013  TypeResult TR = ParseTypeName();
2014  if (TR.isInvalid()) {
2015  SkipUntil(tok::r_paren, StopAtSemi);
2016  return ExprError();
2017  }
2018 
2019  if (ExpectAndConsume(tok::comma))
2020  return ExprError();
2021 
2023  if (IdxRes.isInvalid())
2024  return ExprError();
2025 
2026  T.consumeClose();
2027 
2028  if (IsFieldType)
2029  return Actions.SYCL().ActOnSYCLBuiltinFieldTypeExpr(TR.get(), IdxRes.get());
2030  return Actions.SYCL().ActOnSYCLBuiltinBaseTypeExpr(TR.get(), IdxRes.get());
2031 }
2032 
2033 /// Once the leading part of a postfix-expression is parsed, this
2034 /// method parses any suffixes that apply.
2035 ///
2036 /// \verbatim
2037 /// postfix-expression: [C99 6.5.2]
2038 /// primary-expression
2039 /// postfix-expression '[' expression ']'
2040 /// postfix-expression '[' braced-init-list ']'
2041 /// postfix-expression '[' expression-list [opt] ']' [C++23 12.4.5]
2042 /// postfix-expression '(' argument-expression-list[opt] ')'
2043 /// postfix-expression '.' identifier
2044 /// postfix-expression '->' identifier
2045 /// postfix-expression '++'
2046 /// postfix-expression '--'
2047 /// '(' type-name ')' '{' initializer-list '}'
2048 /// '(' type-name ')' '{' initializer-list ',' '}'
2049 ///
2050 /// argument-expression-list: [C99 6.5.2]
2051 /// argument-expression ...[opt]
2052 /// argument-expression-list ',' assignment-expression ...[opt]
2053 /// \endverbatim
2054 ExprResult
2055 Parser::ParsePostfixExpressionSuffix(ExprResult LHS) {
2056  // Now that the primary-expression piece of the postfix-expression has been
2057  // parsed, see if there are any postfix-expression pieces here.
2059  auto SavedType = PreferredType;
2060  while (true) {
2061  // Each iteration relies on preferred type for the whole expression.
2062  PreferredType = SavedType;
2063  switch (Tok.getKind()) {
2064  case tok::code_completion:
2065  if (InMessageExpression)
2066  return LHS;
2067 
2068  cutOffParsing();
2070  getCurScope(), LHS, PreferredType.get(Tok.getLocation()));
2071  return ExprError();
2072 
2073  case tok::identifier:
2074  // If we see identifier: after an expression, and we're not already in a
2075  // message send, then this is probably a message send with a missing
2076  // opening bracket '['.
2077  if (getLangOpts().ObjC && !InMessageExpression &&
2078  (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
2079  LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(),
2080  nullptr, LHS.get());
2081  break;
2082  }
2083  // Fall through; this isn't a message send.
2084  [[fallthrough]];
2085 
2086  default: // Not a postfix-expression suffix.
2087  return LHS;
2088  case tok::l_square: { // postfix-expression: p-e '[' expression ']'
2089  // If we have a array postfix expression that starts on a new line and
2090  // Objective-C is enabled, it is highly likely that the user forgot a
2091  // semicolon after the base expression and that the array postfix-expr is
2092  // actually another message send. In this case, do some look-ahead to see
2093  // if the contents of the square brackets are obviously not a valid
2094  // expression and recover by pretending there is no suffix.
2095  if (getLangOpts().ObjC && Tok.isAtStartOfLine() &&
2096  isSimpleObjCMessageExpression())
2097  return LHS;
2098 
2099  // Reject array indices starting with a lambda-expression. '[[' is
2100  // reserved for attributes.
2101  if (CheckProhibitedCXX11Attribute()) {
2102  (void)Actions.CorrectDelayedTyposInExpr(LHS);
2103  return ExprError();
2104  }
2105  BalancedDelimiterTracker T(*this, tok::l_square);
2106  T.consumeOpen();
2107  Loc = T.getOpenLocation();
2108  ExprResult Length, Stride;
2109  SourceLocation ColonLocFirst, ColonLocSecond;
2110  ExprVector ArgExprs;
2111  bool HasError = false;
2112  PreferredType.enterSubscript(Actions, Tok.getLocation(), LHS.get());
2113 
2114  // We try to parse a list of indexes in all language mode first
2115  // and, in we find 0 or one index, we try to parse an OpenMP/OpenACC array
2116  // section. This allow us to support C++23 multi dimensional subscript and
2117  // OpenMP/OpenACC sections in the same language mode.
2118  if ((!getLangOpts().OpenMP && !AllowOpenACCArraySections) ||
2119  Tok.isNot(tok::colon)) {
2120  if (!getLangOpts().CPlusPlus23) {
2121  ExprResult Idx;
2122  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
2123  Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
2124  Idx = ParseBraceInitializer();
2125  } else {
2126  Idx = ParseExpression(); // May be a comma expression
2127  }
2128  LHS = Actions.CorrectDelayedTyposInExpr(LHS);
2129  Idx = Actions.CorrectDelayedTyposInExpr(Idx);
2130  if (Idx.isInvalid()) {
2131  HasError = true;
2132  } else {
2133  ArgExprs.push_back(Idx.get());
2134  }
2135  } else if (Tok.isNot(tok::r_square)) {
2136  if (ParseExpressionList(ArgExprs)) {
2137  LHS = Actions.CorrectDelayedTyposInExpr(LHS);
2138  HasError = true;
2139  }
2140  }
2141  }
2142 
2143  // Handle OpenACC first, since 'AllowOpenACCArraySections' is only enabled
2144  // when actively parsing a 'var' in a 'var-list' during clause/'cache'
2145  // parsing, so it is the most specific, and best allows us to handle
2146  // OpenACC and OpenMP at the same time.
2147  if (ArgExprs.size() <= 1 && AllowOpenACCArraySections) {
2148  ColonProtectionRAIIObject RAII(*this);
2149  if (Tok.is(tok::colon)) {
2150  // Consume ':'
2151  ColonLocFirst = ConsumeToken();
2152  if (Tok.isNot(tok::r_square))
2153  Length = Actions.CorrectDelayedTyposInExpr(ParseExpression());
2154  }
2155  } else if (ArgExprs.size() <= 1 && getLangOpts().OpenMP) {
2156  ColonProtectionRAIIObject RAII(*this);
2157  if (Tok.is(tok::colon)) {
2158  // Consume ':'
2159  ColonLocFirst = ConsumeToken();
2160  if (Tok.isNot(tok::r_square) &&
2161  (getLangOpts().OpenMP < 50 ||
2162  ((Tok.isNot(tok::colon) && getLangOpts().OpenMP >= 50)))) {
2163  Length = ParseExpression();
2164  Length = Actions.CorrectDelayedTyposInExpr(Length);
2165  }
2166  }
2167  if (getLangOpts().OpenMP >= 50 &&
2168  (OMPClauseKind == llvm::omp::Clause::OMPC_to ||
2169  OMPClauseKind == llvm::omp::Clause::OMPC_from) &&
2170  Tok.is(tok::colon)) {
2171  // Consume ':'
2172  ColonLocSecond = ConsumeToken();
2173  if (Tok.isNot(tok::r_square)) {
2174  Stride = ParseExpression();
2175  }
2176  }
2177  }
2178 
2179  SourceLocation RLoc = Tok.getLocation();
2180  LHS = Actions.CorrectDelayedTyposInExpr(LHS);
2181 
2182  if (!LHS.isInvalid() && !HasError && !Length.isInvalid() &&
2183  !Stride.isInvalid() && Tok.is(tok::r_square)) {
2184  if (ColonLocFirst.isValid() || ColonLocSecond.isValid()) {
2185  // Like above, AllowOpenACCArraySections is 'more specific' and only
2186  // enabled when actively parsing a 'var' in a 'var-list' during
2187  // clause/'cache' construct parsing, so it is more specific. So we
2188  // should do it first, so that the correct node gets created.
2189  if (AllowOpenACCArraySections) {
2190  assert(!Stride.isUsable() && !ColonLocSecond.isValid() &&
2191  "Stride/second colon not allowed for OpenACC");
2192  LHS = Actions.OpenACC().ActOnArraySectionExpr(
2193  LHS.get(), Loc, ArgExprs.empty() ? nullptr : ArgExprs[0],
2194  ColonLocFirst, Length.get(), RLoc);
2195  } else {
2196  LHS = Actions.OpenMP().ActOnOMPArraySectionExpr(
2197  LHS.get(), Loc, ArgExprs.empty() ? nullptr : ArgExprs[0],
2198  ColonLocFirst, ColonLocSecond, Length.get(), Stride.get(),
2199  RLoc);
2200  }
2201  } else {
2202  LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc,
2203  ArgExprs, RLoc);
2204  }
2205  } else {
2206  LHS = ExprError();
2207  }
2208 
2209  // Match the ']'.
2210  T.consumeClose();
2211  break;
2212  }
2213 
2214  case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')'
2215  case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>'
2216  // '(' argument-expression-list[opt] ')'
2217  tok::TokenKind OpKind = Tok.getKind();
2218  InMessageExpressionRAIIObject InMessage(*this, false);
2219 
2220  Expr *ExecConfig = nullptr;
2221 
2222  BalancedDelimiterTracker PT(*this, tok::l_paren);
2223 
2224  if (OpKind == tok::lesslessless) {
2225  ExprVector ExecConfigExprs;
2226  SourceLocation OpenLoc = ConsumeToken();
2227 
2228  if (ParseSimpleExpressionList(ExecConfigExprs)) {
2229  (void)Actions.CorrectDelayedTyposInExpr(LHS);
2230  LHS = ExprError();
2231  }
2232 
2233  SourceLocation CloseLoc;
2234  if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) {
2235  } else if (LHS.isInvalid()) {
2236  SkipUntil(tok::greatergreatergreater, StopAtSemi);
2237  } else {
2238  // There was an error closing the brackets
2239  Diag(Tok, diag::err_expected) << tok::greatergreatergreater;
2240  Diag(OpenLoc, diag::note_matching) << tok::lesslessless;
2241  SkipUntil(tok::greatergreatergreater, StopAtSemi);
2242  LHS = ExprError();
2243  }
2244 
2245  if (!LHS.isInvalid()) {
2246  if (ExpectAndConsume(tok::l_paren))
2247  LHS = ExprError();
2248  else
2249  Loc = PrevTokLocation;
2250  }
2251 
2252  if (!LHS.isInvalid()) {
2253  ExprResult ECResult = Actions.CUDA().ActOnExecConfigExpr(
2254  getCurScope(), OpenLoc, ExecConfigExprs, CloseLoc);
2255  if (ECResult.isInvalid())
2256  LHS = ExprError();
2257  else
2258  ExecConfig = ECResult.get();
2259  }
2260  } else {
2261  PT.consumeOpen();
2262  Loc = PT.getOpenLocation();
2263  }
2264 
2265  ExprVector ArgExprs;
2266  auto RunSignatureHelp = [&]() -> QualType {
2267  QualType PreferredType =
2269  LHS.get(), ArgExprs, PT.getOpenLocation());
2270  CalledSignatureHelp = true;
2271  return PreferredType;
2272  };
2273  if (OpKind == tok::l_paren || !LHS.isInvalid()) {
2274  if (Tok.isNot(tok::r_paren)) {
2275  if (ParseExpressionList(ArgExprs, [&] {
2276  PreferredType.enterFunctionArgument(Tok.getLocation(),
2277  RunSignatureHelp);
2278  })) {
2279  (void)Actions.CorrectDelayedTyposInExpr(LHS);
2280  // If we got an error when parsing expression list, we don't call
2281  // the CodeCompleteCall handler inside the parser. So call it here
2282  // to make sure we get overload suggestions even when we are in the
2283  // middle of a parameter.
2284  if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
2285  RunSignatureHelp();
2286  LHS = ExprError();
2287  } else if (LHS.isInvalid()) {
2288  for (auto &E : ArgExprs)
2289  Actions.CorrectDelayedTyposInExpr(E);
2290  }
2291  }
2292  }
2293 
2294  // Match the ')'.
2295  if (LHS.isInvalid()) {
2296  SkipUntil(tok::r_paren, StopAtSemi);
2297  } else if (Tok.isNot(tok::r_paren)) {
2298  bool HadDelayedTypo = false;
2299  if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get())
2300  HadDelayedTypo = true;
2301  for (auto &E : ArgExprs)
2302  if (Actions.CorrectDelayedTyposInExpr(E).get() != E)
2303  HadDelayedTypo = true;
2304  // If there were delayed typos in the LHS or ArgExprs, call SkipUntil
2305  // instead of PT.consumeClose() to avoid emitting extra diagnostics for
2306  // the unmatched l_paren.
2307  if (HadDelayedTypo)
2308  SkipUntil(tok::r_paren, StopAtSemi);
2309  else
2310  PT.consumeClose();
2311  LHS = ExprError();
2312  } else {
2313  Expr *Fn = LHS.get();
2314  SourceLocation RParLoc = Tok.getLocation();
2315  LHS = Actions.ActOnCallExpr(getCurScope(), Fn, Loc, ArgExprs, RParLoc,
2316  ExecConfig);
2317  if (LHS.isInvalid()) {
2318  ArgExprs.insert(ArgExprs.begin(), Fn);
2319  LHS =
2320  Actions.CreateRecoveryExpr(Fn->getBeginLoc(), RParLoc, ArgExprs);
2321  }
2322  PT.consumeClose();
2323  }
2324 
2325  break;
2326  }
2327  case tok::arrow:
2328  case tok::period: {
2329  // postfix-expression: p-e '->' template[opt] id-expression
2330  // postfix-expression: p-e '.' template[opt] id-expression
2331  tok::TokenKind OpKind = Tok.getKind();
2332  SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token.
2333 
2334  CXXScopeSpec SS;
2335  ParsedType ObjectType;
2336  bool MayBePseudoDestructor = false;
2337  Expr* OrigLHS = !LHS.isInvalid() ? LHS.get() : nullptr;
2338 
2339  PreferredType.enterMemAccess(Actions, Tok.getLocation(), OrigLHS);
2340 
2341  if (getLangOpts().CPlusPlus && !LHS.isInvalid()) {
2342  Expr *Base = OrigLHS;
2343  const Type* BaseType = Base->getType().getTypePtrOrNull();
2344  if (BaseType && Tok.is(tok::l_paren) &&
2345  (BaseType->isFunctionType() ||
2346  BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) {
2347  Diag(OpLoc, diag::err_function_is_not_record)
2348  << OpKind << Base->getSourceRange()
2349  << FixItHint::CreateRemoval(OpLoc);
2350  return ParsePostfixExpressionSuffix(Base);
2351  }
2352 
2353  LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base, OpLoc,
2354  OpKind, ObjectType,
2355  MayBePseudoDestructor);
2356  if (LHS.isInvalid()) {
2357  // Clang will try to perform expression based completion as a
2358  // fallback, which is confusing in case of member references. So we
2359  // stop here without any completions.
2360  if (Tok.is(tok::code_completion)) {
2361  cutOffParsing();
2362  return ExprError();
2363  }
2364  break;
2365  }
2366  ParseOptionalCXXScopeSpecifier(
2367  SS, ObjectType, LHS.get() && LHS.get()->containsErrors(),
2368  /*EnteringContext=*/false, &MayBePseudoDestructor);
2369  if (SS.isNotEmpty())
2370  ObjectType = nullptr;
2371  }
2372 
2373  if (Tok.is(tok::code_completion)) {
2374  tok::TokenKind CorrectedOpKind =
2375  OpKind == tok::arrow ? tok::period : tok::arrow;
2376  ExprResult CorrectedLHS(/*Invalid=*/true);
2377  if (getLangOpts().CPlusPlus && OrigLHS) {
2378  // FIXME: Creating a TentativeAnalysisScope from outside Sema is a
2379  // hack.
2380  Sema::TentativeAnalysisScope Trap(Actions);
2381  CorrectedLHS = Actions.ActOnStartCXXMemberReference(
2382  getCurScope(), OrigLHS, OpLoc, CorrectedOpKind, ObjectType,
2383  MayBePseudoDestructor);
2384  }
2385 
2386  Expr *Base = LHS.get();
2387  Expr *CorrectedBase = CorrectedLHS.get();
2388  if (!CorrectedBase && !getLangOpts().CPlusPlus)
2389  CorrectedBase = Base;
2390 
2391  // Code completion for a member access expression.
2392  cutOffParsing();
2394  getCurScope(), Base, CorrectedBase, OpLoc, OpKind == tok::arrow,
2395  Base && ExprStatementTokLoc == Base->getBeginLoc(),
2396  PreferredType.get(Tok.getLocation()));
2397 
2398  return ExprError();
2399  }
2400 
2401  if (MayBePseudoDestructor && !LHS.isInvalid()) {
2402  LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS,
2403  ObjectType);
2404  break;
2405  }
2406 
2407  // Either the action has told us that this cannot be a
2408  // pseudo-destructor expression (based on the type of base
2409  // expression), or we didn't see a '~' in the right place. We
2410  // can still parse a destructor name here, but in that case it
2411  // names a real destructor.
2412  // Allow explicit constructor calls in Microsoft mode.
2413  // FIXME: Add support for explicit call of template constructor.
2414  SourceLocation TemplateKWLoc;
2415  UnqualifiedId Name;
2416  if (getLangOpts().ObjC && OpKind == tok::period &&
2417  Tok.is(tok::kw_class)) {
2418  // Objective-C++:
2419  // After a '.' in a member access expression, treat the keyword
2420  // 'class' as if it were an identifier.
2421  //
2422  // This hack allows property access to the 'class' method because it is
2423  // such a common method name. For other C++ keywords that are
2424  // Objective-C method names, one must use the message send syntax.
2427  Name.setIdentifier(Id, Loc);
2428  } else if (ParseUnqualifiedId(
2429  SS, ObjectType, LHS.get() && LHS.get()->containsErrors(),
2430  /*EnteringContext=*/false,
2431  /*AllowDestructorName=*/true,
2432  /*AllowConstructorName=*/
2433  getLangOpts().MicrosoftExt && SS.isNotEmpty(),
2434  /*AllowDeductionGuide=*/false, &TemplateKWLoc, Name)) {
2435  (void)Actions.CorrectDelayedTyposInExpr(LHS);
2436  LHS = ExprError();
2437  }
2438 
2439  if (!LHS.isInvalid())
2440  LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc,
2441  OpKind, SS, TemplateKWLoc, Name,
2442  CurParsedObjCImpl ? CurParsedObjCImpl->Dcl
2443  : nullptr);
2444  if (!LHS.isInvalid()) {
2445  if (Tok.is(tok::less))
2446  checkPotentialAngleBracket(LHS);
2447  } else if (OrigLHS && Name.isValid()) {
2448  // Preserve the LHS if the RHS is an invalid member.
2449  LHS = Actions.CreateRecoveryExpr(OrigLHS->getBeginLoc(),
2450  Name.getEndLoc(), {OrigLHS});
2451  }
2452  break;
2453  }
2454  case tok::plusplus: // postfix-expression: postfix-expression '++'
2455  case tok::minusminus: // postfix-expression: postfix-expression '--'
2456  if (!LHS.isInvalid()) {
2457  Expr *Arg = LHS.get();
2458  LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(),
2459  Tok.getKind(), Arg);
2460  if (LHS.isInvalid())
2461  LHS = Actions.CreateRecoveryExpr(Arg->getBeginLoc(),
2462  Tok.getLocation(), Arg);
2463  }
2464  ConsumeToken();
2465  break;
2466  }
2467  }
2468 }
2469 
2470 /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/
2471 /// vec_step and we are at the start of an expression or a parenthesized
2472 /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the
2473 /// expression (isCastExpr == false) or the type (isCastExpr == true).
2474 ///
2475 /// \verbatim
2476 /// unary-expression: [C99 6.5.3]
2477 /// 'sizeof' unary-expression
2478 /// 'sizeof' '(' type-name ')'
2479 /// [Clang] '__datasizeof' unary-expression
2480 /// [Clang] '__datasizeof' '(' type-name ')'
2481 /// [GNU] '__alignof' unary-expression
2482 /// [GNU] '__alignof' '(' type-name ')'
2483 /// [C11] '_Alignof' '(' type-name ')'
2484 /// [C++0x] 'alignof' '(' type-id ')'
2485 ///
2486 /// [GNU] typeof-specifier:
2487 /// typeof ( expressions )
2488 /// typeof ( type-name )
2489 /// [GNU/C++] typeof unary-expression
2490 /// [C23] typeof-specifier:
2491 /// typeof '(' typeof-specifier-argument ')'
2492 /// typeof_unqual '(' typeof-specifier-argument ')'
2493 ///
2494 /// typeof-specifier-argument:
2495 /// expression
2496 /// type-name
2497 ///
2498 /// [OpenCL 1.1 6.11.12] vec_step built-in function:
2499 /// vec_step ( expressions )
2500 /// vec_step ( type-name )
2501 /// \endverbatim
2502 ExprResult
2503 Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok,
2504  bool &isCastExpr,
2505  ParsedType &CastTy,
2506  SourceRange &CastRange) {
2507 
2508  assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual, tok::kw_sizeof,
2509  tok::kw___datasizeof, tok::kw___alignof, tok::kw_alignof,
2510  tok::kw__Alignof, tok::kw_vec_step,
2511  tok::kw___builtin_omp_required_simd_align,
2512  tok::kw___builtin_vectorelements) &&
2513  "Not a typeof/sizeof/alignof/vec_step expression!");
2514 
2516 
2517  // If the operand doesn't start with an '(', it must be an expression.
2518  if (Tok.isNot(tok::l_paren)) {
2519  // If construct allows a form without parenthesis, user may forget to put
2520  // pathenthesis around type name.
2521  if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___datasizeof, tok::kw___alignof,
2522  tok::kw_alignof, tok::kw__Alignof)) {
2523  if (isTypeIdUnambiguously()) {
2524  DeclSpec DS(AttrFactory);
2525  ParseSpecifierQualifierList(DS);
2526  Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
2528  ParseDeclarator(DeclaratorInfo);
2529 
2530  SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation());
2531  SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation);
2532  if (LParenLoc.isInvalid() || RParenLoc.isInvalid()) {
2533  Diag(OpTok.getLocation(),
2534  diag::err_expected_parentheses_around_typename)
2535  << OpTok.getName();
2536  } else {
2537  Diag(LParenLoc, diag::err_expected_parentheses_around_typename)
2538  << OpTok.getName() << FixItHint::CreateInsertion(LParenLoc, "(")
2539  << FixItHint::CreateInsertion(RParenLoc, ")");
2540  }
2541  isCastExpr = true;
2542  return ExprEmpty();
2543  }
2544  }
2545 
2546  isCastExpr = false;
2547  if (OpTok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual) &&
2548  !getLangOpts().CPlusPlus) {
2549  Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo()
2550  << tok::l_paren;
2551  return ExprError();
2552  }
2553 
2554  // If we're parsing a chain that consists of keywords that could be
2555  // followed by a non-parenthesized expression, BalancedDelimiterTracker
2556  // is not going to help when the nesting is too deep. In this corner case
2557  // we continue to parse with sufficient stack space to avoid crashing.
2558  if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___datasizeof, tok::kw___alignof,
2559  tok::kw_alignof, tok::kw__Alignof) &&
2560  Tok.isOneOf(tok::kw_sizeof, tok::kw___datasizeof, tok::kw___alignof,
2561  tok::kw_alignof, tok::kw__Alignof))
2562  Actions.runWithSufficientStackSpace(Tok.getLocation(), [&] {
2563  Operand = ParseCastExpression(UnaryExprOnly);
2564  });
2565  else
2566  Operand = ParseCastExpression(UnaryExprOnly);
2567  } else {
2568  // If it starts with a '(', we know that it is either a parenthesized
2569  // type-name, or it is a unary-expression that starts with a compound
2570  // literal, or starts with a primary-expression that is a parenthesized
2571  // expression.
2572  ParenParseOption ExprType = CastExpr;
2573  SourceLocation LParenLoc = Tok.getLocation(), RParenLoc;
2574 
2575  Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/,
2576  false, CastTy, RParenLoc);
2577  CastRange = SourceRange(LParenLoc, RParenLoc);
2578 
2579  // If ParseParenExpression parsed a '(typename)' sequence only, then this is
2580  // a type.
2581  if (ExprType == CastExpr) {
2582  isCastExpr = true;
2583  return ExprEmpty();
2584  }
2585 
2586  if (getLangOpts().CPlusPlus ||
2587  !OpTok.isOneOf(tok::kw_typeof, tok::kw_typeof_unqual)) {
2588  // GNU typeof in C requires the expression to be parenthesized. Not so for
2589  // sizeof/alignof or in C++. Therefore, the parenthesized expression is
2590  // the start of a unary-expression, but doesn't include any postfix
2591  // pieces. Parse these now if present.
2592  if (!Operand.isInvalid())
2593  Operand = ParsePostfixExpressionSuffix(Operand.get());
2594  }
2595  }
2596 
2597  // If we get here, the operand to the typeof/sizeof/alignof was an expression.
2598  isCastExpr = false;
2599  return Operand;
2600 }
2601 
2602 /// Parse a __builtin_sycl_unique_stable_name expression. Accepts a type-id as
2603 /// a parameter.
2604 ExprResult Parser::ParseSYCLUniqueStableNameExpression() {
2605  assert(Tok.is(tok::kw___builtin_sycl_unique_stable_name) &&
2606  "Not __builtin_sycl_unique_stable_name");
2607 
2608  SourceLocation OpLoc = ConsumeToken();
2609  BalancedDelimiterTracker T(*this, tok::l_paren);
2610 
2611  // __builtin_sycl_unique_stable_name expressions are always parenthesized.
2612  if (T.expectAndConsume(diag::err_expected_lparen_after,
2613  "__builtin_sycl_unique_stable_name"))
2614  return ExprError();
2615 
2616  TypeResult Ty = ParseTypeName();
2617 
2618  if (Ty.isInvalid()) {
2619  T.skipToEnd();
2620  return ExprError();
2621  }
2622 
2623  if (T.consumeClose())
2624  return ExprError();
2625 
2626  return Actions.SYCL().ActOnUniqueStableNameExpr(
2627  OpLoc, T.getOpenLocation(), T.getCloseLocation(), Ty.get());
2628 }
2629 
2630 // Parse a __builtin_sycl_unique_stable_id expression. Accepts an expression,
2631 // but we later ensure that it MUST be a DeclRefExpr to a VarDecl of some form.
2632 ExprResult Parser::ParseSYCLUniqueStableIdExpression() {
2633  assert(Tok.is(tok::kw___builtin_sycl_unique_stable_id) &&
2634  "Not __bulitin_sycl_unique_stable_id");
2635 
2636  SourceLocation OpLoc = ConsumeToken();
2637  BalancedDelimiterTracker T(*this, tok::l_paren);
2638 
2639  if (T.expectAndConsume(diag::err_expected_lparen_after,
2640  "__builtin_sycl_unique_stable_id"))
2641  return ExprError();
2642 
2643  EnterExpressionEvaluationContext ConstantEvaluated(
2645 
2646  ExprResult VarExpr =
2648 
2649  if (!VarExpr.isUsable()) {
2650  T.skipToEnd();
2651  return ExprError();
2652  }
2653 
2654  if (T.consumeClose())
2655  return ExprError();
2656 
2657  return Actions.SYCL().ActOnUniqueStableIdExpr(
2658  OpLoc, T.getOpenLocation(), T.getCloseLocation(), VarExpr.get());
2659 }
2660 
2661 /// Parse a sizeof or alignof expression.
2662 ///
2663 /// \verbatim
2664 /// unary-expression: [C99 6.5.3]
2665 /// 'sizeof' unary-expression
2666 /// 'sizeof' '(' type-name ')'
2667 /// [C++11] 'sizeof' '...' '(' identifier ')'
2668 /// [Clang] '__datasizeof' unary-expression
2669 /// [Clang] '__datasizeof' '(' type-name ')'
2670 /// [GNU] '__alignof' unary-expression
2671 /// [GNU] '__alignof' '(' type-name ')'
2672 /// [C11] '_Alignof' '(' type-name ')'
2673 /// [C++11] 'alignof' '(' type-id ')'
2674 /// \endverbatim
2675 ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() {
2676  assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___datasizeof, tok::kw___alignof,
2677  tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step,
2678  tok::kw___builtin_omp_required_simd_align,
2679  tok::kw___builtin_vectorelements) &&
2680  "Not a sizeof/alignof/vec_step expression!");
2681  Token OpTok = Tok;
2682  ConsumeToken();
2683 
2684  // [C++11] 'sizeof' '...' '(' identifier ')'
2685  if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof)) {
2686  SourceLocation EllipsisLoc = ConsumeToken();
2687  SourceLocation LParenLoc, RParenLoc;
2688  IdentifierInfo *Name = nullptr;
2689  SourceLocation NameLoc;
2690  if (Tok.is(tok::l_paren)) {
2691  BalancedDelimiterTracker T(*this, tok::l_paren);
2692  T.consumeOpen();
2693  LParenLoc = T.getOpenLocation();
2694  if (Tok.is(tok::identifier)) {
2695  Name = Tok.getIdentifierInfo();
2696  NameLoc = ConsumeToken();
2697  T.consumeClose();
2698  RParenLoc = T.getCloseLocation();
2699  if (RParenLoc.isInvalid())
2700  RParenLoc = PP.getLocForEndOfToken(NameLoc);
2701  } else {
2702  Diag(Tok, diag::err_expected_parameter_pack);
2703  SkipUntil(tok::r_paren, StopAtSemi);
2704  }
2705  } else if (Tok.is(tok::identifier)) {
2706  Name = Tok.getIdentifierInfo();
2707  NameLoc = ConsumeToken();
2708  LParenLoc = PP.getLocForEndOfToken(EllipsisLoc);
2709  RParenLoc = PP.getLocForEndOfToken(NameLoc);
2710  Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack)
2711  << Name
2712  << FixItHint::CreateInsertion(LParenLoc, "(")
2713  << FixItHint::CreateInsertion(RParenLoc, ")");
2714  } else {
2715  Diag(Tok, diag::err_sizeof_parameter_pack);
2716  }
2717 
2718  if (!Name)
2719  return ExprError();
2720 
2724 
2725  return Actions.ActOnSizeofParameterPackExpr(getCurScope(),
2726  OpTok.getLocation(),
2727  *Name, NameLoc,
2728  RParenLoc);
2729  }
2730 
2731  if (getLangOpts().CPlusPlus &&
2732  OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2733  Diag(OpTok, diag::warn_cxx98_compat_alignof);
2734  else if (getLangOpts().C23 && OpTok.is(tok::kw_alignof))
2735  Diag(OpTok, diag::warn_c23_compat_keyword) << OpTok.getName();
2736 
2740 
2741  bool isCastExpr;
2742  ParsedType CastTy;
2743  SourceRange CastRange;
2744  ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok,
2745  isCastExpr,
2746  CastTy,
2747  CastRange);
2748 
2749  UnaryExprOrTypeTrait ExprKind = UETT_SizeOf;
2750  switch (OpTok.getKind()) {
2751  case tok::kw_alignof:
2752  case tok::kw__Alignof:
2753  ExprKind = UETT_AlignOf;
2754  break;
2755  case tok::kw___alignof:
2756  ExprKind = UETT_PreferredAlignOf;
2757  break;
2758  case tok::kw_vec_step:
2759  ExprKind = UETT_VecStep;
2760  break;
2761  case tok::kw___builtin_omp_required_simd_align:
2762  ExprKind = UETT_OpenMPRequiredSimdAlign;
2763  break;
2764  case tok::kw___datasizeof:
2765  ExprKind = UETT_DataSizeOf;
2766  break;
2767  case tok::kw___builtin_vectorelements:
2768  ExprKind = UETT_VectorElements;
2769  break;
2770  default:
2771  break;
2772  }
2773 
2774  if (isCastExpr)
2775  return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(),
2776  ExprKind,
2777  /*IsType=*/true,
2778  CastTy.getAsOpaquePtr(),
2779  CastRange);
2780 
2781  if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof))
2782  Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo();
2783 
2784  // If we get here, the operand to the sizeof/alignof was an expression.
2785  if (!Operand.isInvalid())
2787  ExprKind,
2788  /*IsType=*/false,
2789  Operand.get(),
2790  CastRange);
2791  return Operand;
2792 }
2793 
2794 /// ParseBuiltinPrimaryExpression
2795 ///
2796 /// \verbatim
2797 /// primary-expression: [C99 6.5.1]
2798 /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')'
2799 /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')'
2800 /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ','
2801 /// assign-expr ')'
2802 /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')'
2803 /// [GNU] '__builtin_FILE' '(' ')'
2804 /// [CLANG] '__builtin_FILE_NAME' '(' ')'
2805 /// [GNU] '__builtin_FUNCTION' '(' ')'
2806 /// [MS] '__builtin_FUNCSIG' '(' ')'
2807 /// [GNU] '__builtin_LINE' '(' ')'
2808 /// [CLANG] '__builtin_COLUMN' '(' ')'
2809 /// [GNU] '__builtin_source_location' '(' ')'
2810 /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')'
2811 ///
2812 /// [GNU] offsetof-member-designator:
2813 /// [GNU] identifier
2814 /// [GNU] offsetof-member-designator '.' identifier
2815 /// [GNU] offsetof-member-designator '[' expression ']'
2816 /// \endverbatim
2817 ExprResult Parser::ParseBuiltinPrimaryExpression() {
2818  ExprResult Res;
2819  const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo();
2820 
2821  tok::TokenKind T = Tok.getKind();
2822  SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier.
2823 
2824  // All of these start with an open paren.
2825  if (Tok.isNot(tok::l_paren))
2826  return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII
2827  << tok::l_paren);
2828 
2829  BalancedDelimiterTracker PT(*this, tok::l_paren);
2830  PT.consumeOpen();
2831 
2832  // TODO: Build AST.
2833 
2834  switch (T) {
2835  default: llvm_unreachable("Not a builtin primary expression!");
2836  case tok::kw___builtin_va_arg: {
2838 
2839  if (ExpectAndConsume(tok::comma)) {
2840  SkipUntil(tok::r_paren, StopAtSemi);
2841  Expr = ExprError();
2842  }
2843 
2844  TypeResult Ty = ParseTypeName();
2845 
2846  if (Tok.isNot(tok::r_paren)) {
2847  Diag(Tok, diag::err_expected) << tok::r_paren;
2848  Expr = ExprError();
2849  }
2850 
2851  if (Expr.isInvalid() || Ty.isInvalid())
2852  Res = ExprError();
2853  else
2854  Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen());
2855  break;
2856  }
2857  case tok::kw___builtin_offsetof: {
2859  auto OOK = Sema::OffsetOfKind::OOK_Builtin;
2860  if (Tok.getLocation().isMacroID()) {
2861  StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
2862  Tok.getLocation(), PP.getSourceManager(), getLangOpts());
2863  if (MacroName == "offsetof")
2864  OOK = Sema::OffsetOfKind::OOK_Macro;
2865  }
2866  TypeResult Ty;
2867  {
2868  OffsetOfStateRAIIObject InOffsetof(*this, OOK);
2869  Ty = ParseTypeName();
2870  if (Ty.isInvalid()) {
2871  SkipUntil(tok::r_paren, StopAtSemi);
2872  return ExprError();
2873  }
2874  }
2875 
2876  if (ExpectAndConsume(tok::comma)) {
2877  SkipUntil(tok::r_paren, StopAtSemi);
2878  return ExprError();
2879  }
2880 
2881  // We must have at least one identifier here.
2882  if (Tok.isNot(tok::identifier)) {
2883  Diag(Tok, diag::err_expected) << tok::identifier;
2884  SkipUntil(tok::r_paren, StopAtSemi);
2885  return ExprError();
2886  }
2887 
2888  // Keep track of the various subcomponents we see.
2890 
2891  Comps.push_back(Sema::OffsetOfComponent());
2892  Comps.back().isBrackets = false;
2893  Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2894  Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken();
2895 
2896  // FIXME: This loop leaks the index expressions on error.
2897  while (true) {
2898  if (Tok.is(tok::period)) {
2899  // offsetof-member-designator: offsetof-member-designator '.' identifier
2900  Comps.push_back(Sema::OffsetOfComponent());
2901  Comps.back().isBrackets = false;
2902  Comps.back().LocStart = ConsumeToken();
2903 
2904  if (Tok.isNot(tok::identifier)) {
2905  Diag(Tok, diag::err_expected) << tok::identifier;
2906  SkipUntil(tok::r_paren, StopAtSemi);
2907  return ExprError();
2908  }
2909  Comps.back().U.IdentInfo = Tok.getIdentifierInfo();
2910  Comps.back().LocEnd = ConsumeToken();
2911  } else if (Tok.is(tok::l_square)) {
2912  if (CheckProhibitedCXX11Attribute())
2913  return ExprError();
2914 
2915  // offsetof-member-designator: offsetof-member-design '[' expression ']'
2916  Comps.push_back(Sema::OffsetOfComponent());
2917  Comps.back().isBrackets = true;
2918  BalancedDelimiterTracker ST(*this, tok::l_square);
2919  ST.consumeOpen();
2920  Comps.back().LocStart = ST.getOpenLocation();
2921  Res = ParseExpression();
2922  if (Res.isInvalid()) {
2923  SkipUntil(tok::r_paren, StopAtSemi);
2924  return Res;
2925  }
2926  Comps.back().U.E = Res.get();
2927 
2928  ST.consumeClose();
2929  Comps.back().LocEnd = ST.getCloseLocation();
2930  } else {
2931  if (Tok.isNot(tok::r_paren)) {
2932  PT.consumeClose();
2933  Res = ExprError();
2934  } else if (Ty.isInvalid()) {
2935  Res = ExprError();
2936  } else {
2937  PT.consumeClose();
2938  Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc,
2939  Ty.get(), Comps,
2940  PT.getCloseLocation());
2941  }
2942  break;
2943  }
2944  }
2945  break;
2946  }
2947  case tok::kw___builtin_choose_expr: {
2949  if (Cond.isInvalid()) {
2950  SkipUntil(tok::r_paren, StopAtSemi);
2951  return Cond;
2952  }
2953  if (ExpectAndConsume(tok::comma)) {
2954  SkipUntil(tok::r_paren, StopAtSemi);
2955  return ExprError();
2956  }
2957 
2959  if (Expr1.isInvalid()) {
2960  SkipUntil(tok::r_paren, StopAtSemi);
2961  return Expr1;
2962  }
2963  if (ExpectAndConsume(tok::comma)) {
2964  SkipUntil(tok::r_paren, StopAtSemi);
2965  return ExprError();
2966  }
2967 
2969  if (Expr2.isInvalid()) {
2970  SkipUntil(tok::r_paren, StopAtSemi);
2971  return Expr2;
2972  }
2973  if (Tok.isNot(tok::r_paren)) {
2974  Diag(Tok, diag::err_expected) << tok::r_paren;
2975  return ExprError();
2976  }
2977  Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(),
2978  Expr2.get(), ConsumeParen());
2979  break;
2980  }
2981  case tok::kw___builtin_astype: {
2982  // The first argument is an expression to be converted, followed by a comma.
2984  if (Expr.isInvalid()) {
2985  SkipUntil(tok::r_paren, StopAtSemi);
2986  return ExprError();
2987  }
2988 
2989  if (ExpectAndConsume(tok::comma)) {
2990  SkipUntil(tok::r_paren, StopAtSemi);
2991  return ExprError();
2992  }
2993 
2994  // Second argument is the type to bitcast to.
2995  TypeResult DestTy = ParseTypeName();
2996  if (DestTy.isInvalid())
2997  return ExprError();
2998 
2999  // Attempt to consume the r-paren.
3000  if (Tok.isNot(tok::r_paren)) {
3001  Diag(Tok, diag::err_expected) << tok::r_paren;
3002  SkipUntil(tok::r_paren, StopAtSemi);
3003  return ExprError();
3004  }
3005 
3006  Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc,
3007  ConsumeParen());
3008  break;
3009  }
3010  case tok::kw___builtin_convertvector: {
3011  // The first argument is an expression to be converted, followed by a comma.
3013  if (Expr.isInvalid()) {
3014  SkipUntil(tok::r_paren, StopAtSemi);
3015  return ExprError();
3016  }
3017 
3018  if (ExpectAndConsume(tok::comma)) {
3019  SkipUntil(tok::r_paren, StopAtSemi);
3020  return ExprError();
3021  }
3022 
3023  // Second argument is the type to bitcast to.
3024  TypeResult DestTy = ParseTypeName();
3025  if (DestTy.isInvalid())
3026  return ExprError();
3027 
3028  // Attempt to consume the r-paren.
3029  if (Tok.isNot(tok::r_paren)) {
3030  Diag(Tok, diag::err_expected) << tok::r_paren;
3031  SkipUntil(tok::r_paren, StopAtSemi);
3032  return ExprError();
3033  }
3034 
3035  Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc,
3036  ConsumeParen());
3037  break;
3038  }
3039  case tok::kw___builtin_COLUMN:
3040  case tok::kw___builtin_FILE:
3041  case tok::kw___builtin_FILE_NAME:
3042  case tok::kw___builtin_FUNCTION:
3043  case tok::kw___builtin_FUNCSIG:
3044  case tok::kw___builtin_LINE:
3045  case tok::kw___builtin_source_location: {
3046  // Attempt to consume the r-paren.
3047  if (Tok.isNot(tok::r_paren)) {
3048  Diag(Tok, diag::err_expected) << tok::r_paren;
3049  SkipUntil(tok::r_paren, StopAtSemi);
3050  return ExprError();
3051  }
3052  SourceLocIdentKind Kind = [&] {
3053  switch (T) {
3054  case tok::kw___builtin_FILE:
3055  return SourceLocIdentKind::File;
3056  case tok::kw___builtin_FILE_NAME:
3058  case tok::kw___builtin_FUNCTION:
3060  case tok::kw___builtin_FUNCSIG:
3062  case tok::kw___builtin_LINE:
3063  return SourceLocIdentKind::Line;
3064  case tok::kw___builtin_COLUMN:
3066  case tok::kw___builtin_source_location:
3068  default:
3069  llvm_unreachable("invalid keyword");
3070  }
3071  }();
3072  Res = Actions.ActOnSourceLocExpr(Kind, StartLoc, ConsumeParen());
3073  break;
3074  }
3075  }
3076 
3077  if (Res.isInvalid())
3078  return ExprError();
3079 
3080  // These can be followed by postfix-expr pieces because they are
3081  // primary-expressions.
3082  return ParsePostfixExpressionSuffix(Res.get());
3083 }
3084 
3085 bool Parser::tryParseOpenMPArrayShapingCastPart() {
3086  assert(Tok.is(tok::l_square) && "Expected open bracket");
3087  bool ErrorFound = true;
3088  TentativeParsingAction TPA(*this);
3089  do {
3090  if (Tok.isNot(tok::l_square))
3091  break;
3092  // Consume '['
3093  ConsumeBracket();
3094  // Skip inner expression.
3095  while (!SkipUntil(tok::r_square, tok::annot_pragma_openmp_end,
3097  ;
3098  if (Tok.isNot(tok::r_square))
3099  break;
3100  // Consume ']'
3101  ConsumeBracket();
3102  // Found ')' - done.
3103  if (Tok.is(tok::r_paren)) {
3104  ErrorFound = false;
3105  break;
3106  }
3107  } while (Tok.isNot(tok::annot_pragma_openmp_end));
3108  TPA.Revert();
3109  return !ErrorFound;
3110 }
3111 
3112 /// ParseParenExpression - This parses the unit that starts with a '(' token,
3113 /// based on what is allowed by ExprType. The actual thing parsed is returned
3114 /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type,
3115 /// not the parsed cast-expression.
3116 ///
3117 /// \verbatim
3118 /// primary-expression: [C99 6.5.1]
3119 /// '(' expression ')'
3120 /// [GNU] '(' compound-statement ')' (if !ParenExprOnly)
3121 /// postfix-expression: [C99 6.5.2]
3122 /// '(' type-name ')' '{' initializer-list '}'
3123 /// '(' type-name ')' '{' initializer-list ',' '}'
3124 /// cast-expression: [C99 6.5.4]
3125 /// '(' type-name ')' cast-expression
3126 /// [ARC] bridged-cast-expression
3127 /// [ARC] bridged-cast-expression:
3128 /// (__bridge type-name) cast-expression
3129 /// (__bridge_transfer type-name) cast-expression
3130 /// (__bridge_retained type-name) cast-expression
3131 /// fold-expression: [C++1z]
3132 /// '(' cast-expression fold-operator '...' ')'
3133 /// '(' '...' fold-operator cast-expression ')'
3134 /// '(' cast-expression fold-operator '...'
3135 /// fold-operator cast-expression ')'
3136 /// [OPENMP] Array shaping operation
3137 /// '(' '[' expression ']' { '[' expression ']' } cast-expression
3138 /// \endverbatim
3139 ExprResult
3140 Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr,
3141  bool isTypeCast, ParsedType &CastTy,
3142  SourceLocation &RParenLoc) {
3143  assert(Tok.is(tok::l_paren) && "Not a paren expr!");
3144  ColonProtectionRAIIObject ColonProtection(*this, false);
3145  BalancedDelimiterTracker T(*this, tok::l_paren);
3146  if (T.consumeOpen())
3147  return ExprError();
3148  SourceLocation OpenLoc = T.getOpenLocation();
3149 
3150  PreferredType.enterParenExpr(Tok.getLocation(), OpenLoc);
3151 
3152  ExprResult Result(true);
3153  bool isAmbiguousTypeId;
3154  CastTy = nullptr;
3155 
3156  if (Tok.is(tok::code_completion)) {
3157  cutOffParsing();
3159  getCurScope(), PreferredType.get(Tok.getLocation()),
3160  /*IsParenthesized=*/ExprType >= CompoundLiteral);
3161  return ExprError();
3162  }
3163 
3164  // Diagnose use of bridge casts in non-arc mode.
3165  bool BridgeCast = (getLangOpts().ObjC &&
3166  Tok.isOneOf(tok::kw___bridge,
3167  tok::kw___bridge_transfer,
3168  tok::kw___bridge_retained,
3169  tok::kw___bridge_retain));
3170  if (BridgeCast && !getLangOpts().ObjCAutoRefCount) {
3171  if (!TryConsumeToken(tok::kw___bridge)) {
3172  StringRef BridgeCastName = Tok.getName();
3173  SourceLocation BridgeKeywordLoc = ConsumeToken();
3174  if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
3175  Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc)
3176  << BridgeCastName
3177  << FixItHint::CreateReplacement(BridgeKeywordLoc, "");
3178  }
3179  BridgeCast = false;
3180  }
3181 
3182  // None of these cases should fall through with an invalid Result
3183  // unless they've already reported an error.
3184  if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) {
3185  Diag(Tok, OpenLoc.isMacroID() ? diag::ext_gnu_statement_expr_macro
3186  : diag::ext_gnu_statement_expr);
3187 
3188  checkCompoundToken(OpenLoc, tok::l_paren, CompoundToken::StmtExprBegin);
3189 
3190  if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) {
3191  Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope));
3192  } else {
3193  // Find the nearest non-record decl context. Variables declared in a
3194  // statement expression behave as if they were declared in the enclosing
3195  // function, block, or other code construct.
3196  DeclContext *CodeDC = Actions.CurContext;
3197  while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) {
3198  CodeDC = CodeDC->getParent();
3199  assert(CodeDC && !CodeDC->isFileContext() &&
3200  "statement expr not in code context");
3201  }
3202  Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false);
3203 
3204  Actions.ActOnStartStmtExpr();
3205 
3206  StmtResult Stmt(ParseCompoundStatement(true));
3207  ExprType = CompoundStmt;
3208 
3209  // If the substmt parsed correctly, build the AST node.
3210  if (!Stmt.isInvalid()) {
3211  Result = Actions.ActOnStmtExpr(getCurScope(), OpenLoc, Stmt.get(),
3212  Tok.getLocation());
3213  } else {
3214  Actions.ActOnStmtExprError();
3215  }
3216  }
3217  } else if (ExprType >= CompoundLiteral && BridgeCast) {
3218  tok::TokenKind tokenKind = Tok.getKind();
3219  SourceLocation BridgeKeywordLoc = ConsumeToken();
3220 
3221  // Parse an Objective-C ARC ownership cast expression.
3223  if (tokenKind == tok::kw___bridge)
3224  Kind = OBC_Bridge;
3225  else if (tokenKind == tok::kw___bridge_transfer)
3227  else if (tokenKind == tok::kw___bridge_retained)
3229  else {
3230  // As a hopefully temporary workaround, allow __bridge_retain as
3231  // a synonym for __bridge_retained, but only in system headers.
3232  assert(tokenKind == tok::kw___bridge_retain);
3234  if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc))
3235  Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain)
3236  << FixItHint::CreateReplacement(BridgeKeywordLoc,
3237  "__bridge_retained");
3238  }
3239 
3240  TypeResult Ty = ParseTypeName();
3241  T.consumeClose();
3242  ColonProtection.restore();
3243  RParenLoc = T.getCloseLocation();
3244 
3245  PreferredType.enterTypeCast(Tok.getLocation(), Ty.get().get());
3246  ExprResult SubExpr = ParseCastExpression(AnyCastExpr);
3247 
3248  if (Ty.isInvalid() || SubExpr.isInvalid())
3249  return ExprError();
3250 
3251  return Actions.ObjC().ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind,
3252  BridgeKeywordLoc, Ty.get(),
3253  RParenLoc, SubExpr.get());
3254  } else if (ExprType >= CompoundLiteral &&
3255  isTypeIdInParens(isAmbiguousTypeId)) {
3256 
3257  // Otherwise, this is a compound literal expression or cast expression.
3258 
3259  // In C++, if the type-id is ambiguous we disambiguate based on context.
3260  // If stopIfCastExpr is true the context is a typeof/sizeof/alignof
3261  // in which case we should treat it as type-id.
3262  // if stopIfCastExpr is false, we need to determine the context past the
3263  // parens, so we defer to ParseCXXAmbiguousParenExpression for that.
3264  if (isAmbiguousTypeId && !stopIfCastExpr) {
3265  ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T,
3266  ColonProtection);
3267  RParenLoc = T.getCloseLocation();
3268  return res;
3269  }
3270 
3271  // Parse the type declarator.
3272  DeclSpec DS(AttrFactory);
3273  ParseSpecifierQualifierList(DS);
3274  Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
3276  ParseDeclarator(DeclaratorInfo);
3277 
3278  // If our type is followed by an identifier and either ':' or ']', then
3279  // this is probably an Objective-C message send where the leading '[' is
3280  // missing. Recover as if that were the case.
3281  if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) &&
3282  !InMessageExpression && getLangOpts().ObjC &&
3283  (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) {
3284  TypeResult Ty;
3285  {
3286  InMessageExpressionRAIIObject InMessage(*this, false);
3287  Ty = Actions.ActOnTypeName(DeclaratorInfo);
3288  }
3289  Result = ParseObjCMessageExpressionBody(SourceLocation(),
3290  SourceLocation(),
3291  Ty.get(), nullptr);
3292  } else {
3293  // Match the ')'.
3294  T.consumeClose();
3295  ColonProtection.restore();
3296  RParenLoc = T.getCloseLocation();
3297  if (Tok.is(tok::l_brace)) {
3298  ExprType = CompoundLiteral;
3299  TypeResult Ty;
3300  {
3301  InMessageExpressionRAIIObject InMessage(*this, false);
3302  Ty = Actions.ActOnTypeName(DeclaratorInfo);
3303  }
3304  return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc);
3305  }
3306 
3307  if (Tok.is(tok::l_paren)) {
3308  // This could be OpenCL vector Literals
3309  if (getLangOpts().OpenCL)
3310  {
3311  TypeResult Ty;
3312  {
3313  InMessageExpressionRAIIObject InMessage(*this, false);
3314  Ty = Actions.ActOnTypeName(DeclaratorInfo);
3315  }
3316  if(Ty.isInvalid())
3317  {
3318  return ExprError();
3319  }
3320  QualType QT = Ty.get().get().getCanonicalType();
3321  if (QT->isVectorType())
3322  {
3323  // We parsed '(' vector-type-name ')' followed by '('
3324 
3325  // Parse the cast-expression that follows it next.
3326  // isVectorLiteral = true will make sure we don't parse any
3327  // Postfix expression yet
3328  Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
3329  /*isAddressOfOperand=*/false,
3330  /*isTypeCast=*/IsTypeCast,
3331  /*isVectorLiteral=*/true);
3332 
3333  if (!Result.isInvalid()) {
3334  Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
3335  DeclaratorInfo, CastTy,
3336  RParenLoc, Result.get());
3337  }
3338 
3339  // After we performed the cast we can check for postfix-expr pieces.
3340  if (!Result.isInvalid()) {
3341  Result = ParsePostfixExpressionSuffix(Result);
3342  }
3343 
3344  return Result;
3345  }
3346  }
3347  }
3348 
3349  if (ExprType == CastExpr) {
3350  // We parsed '(' type-name ')' and the thing after it wasn't a '{'.
3351 
3352  if (DeclaratorInfo.isInvalidType())
3353  return ExprError();
3354 
3355  // Note that this doesn't parse the subsequent cast-expression, it just
3356  // returns the parsed type to the callee.
3357  if (stopIfCastExpr) {
3358  TypeResult Ty;
3359  {
3360  InMessageExpressionRAIIObject InMessage(*this, false);
3361  Ty = Actions.ActOnTypeName(DeclaratorInfo);
3362  }
3363  CastTy = Ty.get();
3364  return ExprResult();
3365  }
3366 
3367  // Reject the cast of super idiom in ObjC.
3368  if (Tok.is(tok::identifier) && getLangOpts().ObjC &&
3369  Tok.getIdentifierInfo() == Ident_super &&
3370  getCurScope()->isInObjcMethodScope() &&
3371  GetLookAheadToken(1).isNot(tok::period)) {
3372  Diag(Tok.getLocation(), diag::err_illegal_super_cast)
3373  << SourceRange(OpenLoc, RParenLoc);
3374  return ExprError();
3375  }
3376 
3377  PreferredType.enterTypeCast(Tok.getLocation(), CastTy.get());
3378  // Parse the cast-expression that follows it next.
3379  // TODO: For cast expression with CastTy.
3380  Result = ParseCastExpression(/*isUnaryExpression=*/AnyCastExpr,
3381  /*isAddressOfOperand=*/false,
3382  /*isTypeCast=*/IsTypeCast);
3383  if (!Result.isInvalid()) {
3384  Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc,
3385  DeclaratorInfo, CastTy,
3386  RParenLoc, Result.get());
3387  }
3388  return Result;
3389  }
3390 
3391  Diag(Tok, diag::err_expected_lbrace_in_compound_literal);
3392  return ExprError();
3393  }
3394  } else if (ExprType >= FoldExpr && Tok.is(tok::ellipsis) &&
3395  isFoldOperator(NextToken().getKind())) {
3396  ExprType = FoldExpr;
3397  return ParseFoldExpression(ExprResult(), T);
3398  } else if (isTypeCast) {
3399  // Parse the expression-list.
3400  InMessageExpressionRAIIObject InMessage(*this, false);
3401  ExprVector ArgExprs;
3402 
3403  if (!ParseSimpleExpressionList(ArgExprs)) {
3404  // FIXME: If we ever support comma expressions as operands to
3405  // fold-expressions, we'll need to allow multiple ArgExprs here.
3406  if (ExprType >= FoldExpr && ArgExprs.size() == 1 &&
3407  isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) {
3408  ExprType = FoldExpr;
3409  return ParseFoldExpression(ArgExprs[0], T);
3410  }
3411 
3412  ExprType = SimpleExpr;
3413  Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(),
3414  ArgExprs);
3415  }
3416  } else if (getLangOpts().OpenMP >= 50 && OpenMPDirectiveParsing &&
3417  ExprType == CastExpr && Tok.is(tok::l_square) &&
3418  tryParseOpenMPArrayShapingCastPart()) {
3419  bool ErrorFound = false;
3420  SmallVector<Expr *, 4> OMPDimensions;
3421  SmallVector<SourceRange, 4> OMPBracketsRanges;
3422  do {
3423  BalancedDelimiterTracker TS(*this, tok::l_square);
3424  TS.consumeOpen();
3425  ExprResult NumElements =
3427  if (!NumElements.isUsable()) {
3428  ErrorFound = true;
3429  while (!SkipUntil(tok::r_square, tok::r_paren,
3431  ;
3432  }
3433  TS.consumeClose();
3434  OMPDimensions.push_back(NumElements.get());
3435  OMPBracketsRanges.push_back(TS.getRange());
3436  } while (Tok.isNot(tok::r_paren));
3437  // Match the ')'.
3438  T.consumeClose();
3439  RParenLoc = T.getCloseLocation();
3441  if (ErrorFound) {
3442  Result = ExprError();
3443  } else if (!Result.isInvalid()) {
3444  Result = Actions.OpenMP().ActOnOMPArrayShapingExpr(
3445  Result.get(), OpenLoc, RParenLoc, OMPDimensions, OMPBracketsRanges);
3446  }
3447  return Result;
3448  } else {
3449  InMessageExpressionRAIIObject InMessage(*this, false);
3450 
3451  Result = ParseExpression(MaybeTypeCast);
3452  if (!getLangOpts().CPlusPlus && Result.isUsable()) {
3453  // Correct typos in non-C++ code earlier so that implicit-cast-like
3454  // expressions are parsed correctly.
3455  Result = Actions.CorrectDelayedTyposInExpr(Result);
3456  }
3457 
3458  if (ExprType >= FoldExpr && isFoldOperator(Tok.getKind()) &&
3459  NextToken().is(tok::ellipsis)) {
3460  ExprType = FoldExpr;
3461  return ParseFoldExpression(Result, T);
3462  }
3463  ExprType = SimpleExpr;
3464 
3465  // Don't build a paren expression unless we actually match a ')'.
3466  if (!Result.isInvalid() && Tok.is(tok::r_paren))
3467  Result =
3468  Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get());
3469  }
3470 
3471  // Match the ')'.
3472  if (Result.isInvalid()) {
3473  SkipUntil(tok::r_paren, StopAtSemi);
3474  return ExprError();
3475  }
3476 
3477  T.consumeClose();
3478  RParenLoc = T.getCloseLocation();
3479  return Result;
3480 }
3481 
3482 /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name
3483 /// and we are at the left brace.
3484 ///
3485 /// \verbatim
3486 /// postfix-expression: [C99 6.5.2]
3487 /// '(' type-name ')' '{' initializer-list '}'
3488 /// '(' type-name ')' '{' initializer-list ',' '}'
3489 /// \endverbatim
3490 ExprResult
3491 Parser::ParseCompoundLiteralExpression(ParsedType Ty,
3492  SourceLocation LParenLoc,
3493  SourceLocation RParenLoc) {
3494  assert(Tok.is(tok::l_brace) && "Not a compound literal!");
3495  if (!getLangOpts().C99) // Compound literals don't exist in C90.
3496  Diag(LParenLoc, diag::ext_c99_compound_literal);
3497  PreferredType.enterTypeCast(Tok.getLocation(), Ty.get());
3498  ExprResult Result = ParseInitializer();
3499  if (!Result.isInvalid() && Ty)
3500  return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get());
3501  return Result;
3502 }
3503 
3504 /// ParseStringLiteralExpression - This handles the various token types that
3505 /// form string literals, and also handles string concatenation [C99 5.1.1.2,
3506 /// translation phase #6].
3507 ///
3508 /// \verbatim
3509 /// primary-expression: [C99 6.5.1]
3510 /// string-literal
3511 /// \verbatim
3512 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) {
3513  return ParseStringLiteralExpression(AllowUserDefinedLiteral,
3514  /*Unevaluated=*/false);
3515 }
3516 
3518  return ParseStringLiteralExpression(/*AllowUserDefinedLiteral=*/false,
3519  /*Unevaluated=*/true);
3520 }
3521 
3522 ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral,
3523  bool Unevaluated) {
3524  assert(tokenIsLikeStringLiteral(Tok, getLangOpts()) &&
3525  "Not a string-literal-like token!");
3526 
3527  // String concatenation.
3528  // Note: some keywords like __FUNCTION__ are not considered to be strings
3529  // for concatenation purposes, unless Microsoft extensions are enabled.
3530  SmallVector<Token, 4> StringToks;
3531 
3532  do {
3533  StringToks.push_back(Tok);
3534  ConsumeAnyToken();
3535  } while (tokenIsLikeStringLiteral(Tok, getLangOpts()));
3536 
3537  if (Unevaluated) {
3538  assert(!AllowUserDefinedLiteral && "UDL are always evaluated");
3539  return Actions.ActOnUnevaluatedStringLiteral(StringToks);
3540  }
3541 
3542  // Pass the set of string tokens, ready for concatenation, to the actions.
3543  return Actions.ActOnStringLiteral(StringToks,
3544  AllowUserDefinedLiteral ? getCurScope()
3545  : nullptr);
3546 }
3547 
3548 /// ParseGenericSelectionExpression - Parse a C11 generic-selection
3549 /// [C11 6.5.1.1].
3550 ///
3551 /// \verbatim
3552 /// generic-selection:
3553 /// _Generic ( assignment-expression , generic-assoc-list )
3554 /// generic-assoc-list:
3555 /// generic-association
3556 /// generic-assoc-list , generic-association
3557 /// generic-association:
3558 /// type-name : assignment-expression
3559 /// default : assignment-expression
3560 /// \endverbatim
3561 ///
3562 /// As an extension, Clang also accepts:
3563 /// \verbatim
3564 /// generic-selection:
3565 /// _Generic ( type-name, generic-assoc-list )
3566 /// \endverbatim
3567 ExprResult Parser::ParseGenericSelectionExpression() {
3568  assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected");
3569 
3570  diagnoseUseOfC11Keyword(Tok);
3571 
3572  SourceLocation KeyLoc = ConsumeToken();
3573  BalancedDelimiterTracker T(*this, tok::l_paren);
3574  if (T.expectAndConsume())
3575  return ExprError();
3576 
3577  // We either have a controlling expression or we have a controlling type, and
3578  // we need to figure out which it is.
3579  TypeResult ControllingType;
3580  ExprResult ControllingExpr;
3581  if (isTypeIdForGenericSelection()) {
3582  ControllingType = ParseTypeName();
3583  if (ControllingType.isInvalid()) {
3584  SkipUntil(tok::r_paren, StopAtSemi);
3585  return ExprError();
3586  }
3587  const auto *LIT = cast<LocInfoType>(ControllingType.get().get());
3588  SourceLocation Loc = LIT->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
3589  Diag(Loc, getLangOpts().C2y ? diag::warn_c2y_compat_generic_with_type_arg
3590  : diag::ext_c2y_generic_with_type_arg);
3591  } else {
3592  // C11 6.5.1.1p3 "The controlling expression of a generic selection is
3593  // not evaluated."
3596  ControllingExpr =
3598  if (ControllingExpr.isInvalid()) {
3599  SkipUntil(tok::r_paren, StopAtSemi);
3600  return ExprError();
3601  }
3602  }
3603 
3604  if (ExpectAndConsume(tok::comma)) {
3605  SkipUntil(tok::r_paren, StopAtSemi);
3606  return ExprError();
3607  }
3608 
3609  SourceLocation DefaultLoc;
3611  ExprVector Exprs;
3612  do {
3613  ParsedType Ty;
3614  if (Tok.is(tok::kw_default)) {
3615  // C11 6.5.1.1p2 "A generic selection shall have no more than one default
3616  // generic association."
3617  if (!DefaultLoc.isInvalid()) {
3618  Diag(Tok, diag::err_duplicate_default_assoc);
3619  Diag(DefaultLoc, diag::note_previous_default_assoc);
3620  SkipUntil(tok::r_paren, StopAtSemi);
3621  return ExprError();
3622  }
3623  DefaultLoc = ConsumeToken();
3624  Ty = nullptr;
3625  } else {
3628  if (TR.isInvalid()) {
3629  SkipUntil(tok::r_paren, StopAtSemi);
3630  return ExprError();
3631  }
3632  Ty = TR.get();
3633  }
3634  Types.push_back(Ty);
3635 
3636  if (ExpectAndConsume(tok::colon)) {
3637  SkipUntil(tok::r_paren, StopAtSemi);
3638  return ExprError();
3639  }
3640 
3641  // FIXME: These expressions should be parsed in a potentially potentially
3642  // evaluated context.
3643  ExprResult ER(
3645  if (ER.isInvalid()) {
3646  SkipUntil(tok::r_paren, StopAtSemi);
3647  return ExprError();
3648  }
3649  Exprs.push_back(ER.get());
3650  } while (TryConsumeToken(tok::comma));
3651 
3652  T.consumeClose();
3653  if (T.getCloseLocation().isInvalid())
3654  return ExprError();
3655 
3656  void *ExprOrTy = ControllingExpr.isUsable()
3657  ? ControllingExpr.get()
3658  : ControllingType.get().getAsOpaquePtr();
3659 
3660  return Actions.ActOnGenericSelectionExpr(
3661  KeyLoc, DefaultLoc, T.getCloseLocation(), ControllingExpr.isUsable(),
3662  ExprOrTy, Types, Exprs);
3663 }
3664 
3665 /// Parse A C++1z fold-expression after the opening paren and optional
3666 /// left-hand-side expression.
3667 ///
3668 /// \verbatim
3669 /// fold-expression:
3670 /// ( cast-expression fold-operator ... )
3671 /// ( ... fold-operator cast-expression )
3672 /// ( cast-expression fold-operator ... fold-operator cast-expression )
3673 ExprResult Parser::ParseFoldExpression(ExprResult LHS,
3675  if (LHS.isInvalid()) {
3676  T.skipToEnd();
3677  return true;
3678  }
3679 
3680  tok::TokenKind Kind = tok::unknown;
3681  SourceLocation FirstOpLoc;
3682  if (LHS.isUsable()) {
3683  Kind = Tok.getKind();
3684  assert(isFoldOperator(Kind) && "missing fold-operator");
3685  FirstOpLoc = ConsumeToken();
3686  }
3687 
3688  assert(Tok.is(tok::ellipsis) && "not a fold-expression");
3689  SourceLocation EllipsisLoc = ConsumeToken();
3690 
3691  ExprResult RHS;
3692  if (Tok.isNot(tok::r_paren)) {
3693  if (!isFoldOperator(Tok.getKind()))
3694  return Diag(Tok.getLocation(), diag::err_expected_fold_operator);
3695 
3696  if (Kind != tok::unknown && Tok.getKind() != Kind)
3697  Diag(Tok.getLocation(), diag::err_fold_operator_mismatch)
3698  << SourceRange(FirstOpLoc);
3699  Kind = Tok.getKind();
3700  ConsumeToken();
3701 
3702  RHS = ParseExpression();
3703  if (RHS.isInvalid()) {
3704  T.skipToEnd();
3705  return true;
3706  }
3707  }
3708 
3709  Diag(EllipsisLoc, getLangOpts().CPlusPlus17
3710  ? diag::warn_cxx14_compat_fold_expression
3711  : diag::ext_fold_expression);
3712 
3713  T.consumeClose();
3714  return Actions.ActOnCXXFoldExpr(getCurScope(), T.getOpenLocation(), LHS.get(),
3715  Kind, EllipsisLoc, RHS.get(),
3716  T.getCloseLocation());
3717 }
3718 
3719 void Parser::injectEmbedTokens() {
3721  reinterpret_cast<EmbedAnnotationData *>(Tok.getAnnotationValue());
3723  Data->BinaryData.size() * 2 - 1),
3724  Data->BinaryData.size() * 2 - 1);
3725  unsigned I = 0;
3726  for (auto &Byte : Data->BinaryData) {
3727  Toks[I].startToken();
3728  Toks[I].setKind(tok::binary_data);
3729  Toks[I].setLocation(Tok.getLocation());
3730  Toks[I].setLength(1);
3731  Toks[I].setLiteralData(&Byte);
3732  if (I != ((Data->BinaryData.size() - 1) * 2)) {
3733  Toks[I + 1].startToken();
3734  Toks[I + 1].setKind(tok::comma);
3735  Toks[I + 1].setLocation(Tok.getLocation());
3736  }
3737  I += 2;
3738  }
3739  PP.EnterTokenStream(std::move(Toks), /*DisableMacroExpansion=*/true,
3740  /*IsReinject=*/true);
3741  ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
3742 }
3743 
3744 /// ParseExpressionList - Used for C/C++ (argument-)expression-list.
3745 ///
3746 /// \verbatim
3747 /// argument-expression-list:
3748 /// assignment-expression
3749 /// argument-expression-list , assignment-expression
3750 ///
3751 /// [C++] expression-list:
3752 /// [C++] assignment-expression
3753 /// [C++] expression-list , assignment-expression
3754 ///
3755 /// [C++0x] expression-list:
3756 /// [C++0x] initializer-list
3757 ///
3758 /// [C++0x] initializer-list
3759 /// [C++0x] initializer-clause ...[opt]
3760 /// [C++0x] initializer-list , initializer-clause ...[opt]
3761 ///
3762 /// [C++0x] initializer-clause:
3763 /// [C++0x] assignment-expression
3764 /// [C++0x] braced-init-list
3765 /// \endverbatim
3766 bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs,
3767  llvm::function_ref<void()> ExpressionStarts,
3768  bool FailImmediatelyOnInvalidExpr,
3769  bool EarlyTypoCorrection) {
3770  bool SawError = false;
3771  while (true) {
3772  if (ExpressionStarts)
3773  ExpressionStarts();
3774 
3775  ExprResult Expr;
3776  if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
3777  Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
3778  Expr = ParseBraceInitializer();
3779  } else
3781 
3782  if (EarlyTypoCorrection)
3783  Expr = Actions.CorrectDelayedTyposInExpr(Expr);
3784 
3785  if (Tok.is(tok::ellipsis))
3786  Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken());
3787  else if (Tok.is(tok::code_completion)) {
3788  // There's nothing to suggest in here as we parsed a full expression.
3789  // Instead fail and propagate the error since caller might have something
3790  // the suggest, e.g. signature help in function call. Note that this is
3791  // performed before pushing the \p Expr, so that signature help can report
3792  // current argument correctly.
3793  SawError = true;
3794  cutOffParsing();
3795  break;
3796  }
3797  if (Expr.isInvalid()) {
3798  SawError = true;
3799  if (FailImmediatelyOnInvalidExpr)
3800  break;
3801  SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch);
3802  } else {
3803  Exprs.push_back(Expr.get());
3804  }
3805 
3806  if (Tok.isNot(tok::comma))
3807  break;
3808  // Move to the next argument, remember where the comma was.
3809  Token Comma = Tok;
3810  ConsumeToken();
3811  checkPotentialAngleBracketDelimiter(Comma);
3812  }
3813  if (SawError) {
3814  // Ensure typos get diagnosed when errors were encountered while parsing the
3815  // expression list.
3816  for (auto &E : Exprs) {
3818  if (Expr.isUsable()) E = Expr.get();
3819  }
3820  }
3821  return SawError;
3822 }
3823 
3824 /// ParseSimpleExpressionList - A simple comma-separated list of expressions,
3825 /// used for misc language extensions.
3826 ///
3827 /// \verbatim
3828 /// simple-expression-list:
3829 /// assignment-expression
3830 /// simple-expression-list , assignment-expression
3831 /// \endverbatim
3832 bool Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr *> &Exprs) {
3833  while (true) {
3835  if (Expr.isInvalid())
3836  return true;
3837 
3838  Exprs.push_back(Expr.get());
3839 
3840  // We might be parsing the LHS of a fold-expression. If we reached the fold
3841  // operator, stop.
3842  if (Tok.isNot(tok::comma) || NextToken().is(tok::ellipsis))
3843  return false;
3844 
3845  // Move to the next argument, remember where the comma was.
3846  Token Comma = Tok;
3847  ConsumeToken();
3848  checkPotentialAngleBracketDelimiter(Comma);
3849  }
3850 }
3851 
3852 /// ParseBlockId - Parse a block-id, which roughly looks like int (int x).
3853 ///
3854 /// \verbatim
3855 /// [clang] block-id:
3856 /// [clang] specifier-qualifier-list block-declarator
3857 /// \endverbatim
3858 void Parser::ParseBlockId(SourceLocation CaretLoc) {
3859  if (Tok.is(tok::code_completion)) {
3860  cutOffParsing();
3863  return;
3864  }
3865 
3866  // Parse the specifier-qualifier-list piece.
3867  DeclSpec DS(AttrFactory);
3868  ParseSpecifierQualifierList(DS);
3869 
3870  // Parse the block-declarator.
3871  Declarator DeclaratorInfo(DS, ParsedAttributesView::none(),
3873  DeclaratorInfo.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
3874  ParseDeclarator(DeclaratorInfo);
3875 
3876  MaybeParseGNUAttributes(DeclaratorInfo);
3877 
3878  // Inform sema that we are starting a block.
3879  Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope());
3880 }
3881 
3882 /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks
3883 /// like ^(int x){ return x+1; }
3884 ///
3885 /// \verbatim
3886 /// block-literal:
3887 /// [clang] '^' block-args[opt] compound-statement
3888 /// [clang] '^' block-id compound-statement
3889 /// [clang] block-args:
3890 /// [clang] '(' parameter-list ')'
3891 /// \endverbatim
3892 ExprResult Parser::ParseBlockLiteralExpression() {
3893  assert(Tok.is(tok::caret) && "block literal starts with ^");
3894  SourceLocation CaretLoc = ConsumeToken();
3895 
3896  PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc,
3897  "block literal parsing");
3898 
3899  // Enter a scope to hold everything within the block. This includes the
3900  // argument decls, decls within the compound expression, etc. This also
3901  // allows determining whether a variable reference inside the block is
3902  // within or outside of the block.
3903  ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope |
3905 
3906  // Inform sema that we are starting a block.
3907  Actions.ActOnBlockStart(CaretLoc, getCurScope());
3908 
3909  // Parse the return type if present.
3910  DeclSpec DS(AttrFactory);
3911  Declarator ParamInfo(DS, ParsedAttributesView::none(),
3913  ParamInfo.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
3914  // FIXME: Since the return type isn't actually parsed, it can't be used to
3915  // fill ParamInfo with an initial valid range, so do it manually.
3916  ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation()));
3917 
3918  // If this block has arguments, parse them. There is no ambiguity here with
3919  // the expression case, because the expression case requires a parameter list.
3920  if (Tok.is(tok::l_paren)) {
3921  ParseParenDeclarator(ParamInfo);
3922  // Parse the pieces after the identifier as if we had "int(...)".
3923  // SetIdentifier sets the source range end, but in this case we're past
3924  // that location.
3925  SourceLocation Tmp = ParamInfo.getSourceRange().getEnd();
3926  ParamInfo.SetIdentifier(nullptr, CaretLoc);
3927  ParamInfo.SetRangeEnd(Tmp);
3928  if (ParamInfo.isInvalidType()) {
3929  // If there was an error parsing the arguments, they may have
3930  // tried to use ^(x+y) which requires an argument list. Just
3931  // skip the whole block literal.
3932  Actions.ActOnBlockError(CaretLoc, getCurScope());
3933  return ExprError();
3934  }
3935 
3936  MaybeParseGNUAttributes(ParamInfo);
3937 
3938  // Inform sema that we are starting a block.
3939  Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3940  } else if (!Tok.is(tok::l_brace)) {
3941  ParseBlockId(CaretLoc);
3942  } else {
3943  // Otherwise, pretend we saw (void).
3944  SourceLocation NoLoc;
3945  ParamInfo.AddTypeInfo(
3946  DeclaratorChunk::getFunction(/*HasProto=*/true,
3947  /*IsAmbiguous=*/false,
3948  /*RParenLoc=*/NoLoc,
3949  /*ArgInfo=*/nullptr,
3950  /*NumParams=*/0,
3951  /*EllipsisLoc=*/NoLoc,
3952  /*RParenLoc=*/NoLoc,
3953  /*RefQualifierIsLvalueRef=*/true,
3954  /*RefQualifierLoc=*/NoLoc,
3955  /*MutableLoc=*/NoLoc, EST_None,
3956  /*ESpecRange=*/SourceRange(),
3957  /*Exceptions=*/nullptr,
3958  /*ExceptionRanges=*/nullptr,
3959  /*NumExceptions=*/0,
3960  /*NoexceptExpr=*/nullptr,
3961  /*ExceptionSpecTokens=*/nullptr,
3962  /*DeclsInPrototype=*/std::nullopt,
3963  CaretLoc, CaretLoc, ParamInfo),
3964  CaretLoc);
3965 
3966  MaybeParseGNUAttributes(ParamInfo);
3967 
3968  // Inform sema that we are starting a block.
3969  Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope());
3970  }
3971 
3972 
3973  ExprResult Result(true);
3974  if (!Tok.is(tok::l_brace)) {
3975  // Saw something like: ^expr
3976  Diag(Tok, diag::err_expected_expression);
3977  Actions.ActOnBlockError(CaretLoc, getCurScope());
3978  return ExprError();
3979  }
3980 
3981  StmtResult Stmt(ParseCompoundStatementBody());
3982  BlockScope.Exit();
3983  if (!Stmt.isInvalid())
3984  Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope());
3985  else
3986  Actions.ActOnBlockError(CaretLoc, getCurScope());
3987  return Result;
3988 }
3989 
3990 /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals.
3991 ///
3992 /// '__objc_yes'
3993 /// '__objc_no'
3994 ExprResult Parser::ParseObjCBoolLiteral() {
3995  tok::TokenKind Kind = Tok.getKind();
3996  return Actions.ObjC().ActOnObjCBoolLiteral(ConsumeToken(), Kind);
3997 }
3998 
3999 /// Validate availability spec list, emitting diagnostics if necessary. Returns
4000 /// true if invalid.
4002  ArrayRef<AvailabilitySpec> AvailSpecs) {
4003  llvm::SmallSet<StringRef, 4> Platforms;
4004  bool HasOtherPlatformSpec = false;
4005  bool Valid = true;
4006  for (const auto &Spec : AvailSpecs) {
4007  if (Spec.isOtherPlatformSpec()) {
4008  if (HasOtherPlatformSpec) {
4009  P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_star);
4010  Valid = false;
4011  }
4012 
4013  HasOtherPlatformSpec = true;
4014  continue;
4015  }
4016 
4017  bool Inserted = Platforms.insert(Spec.getPlatform()).second;
4018  if (!Inserted) {
4019  // Rule out multiple version specs referring to the same platform.
4020  // For example, we emit an error for:
4021  // @available(macos 10.10, macos 10.11, *)
4022  StringRef Platform = Spec.getPlatform();
4023  P.Diag(Spec.getBeginLoc(), diag::err_availability_query_repeated_platform)
4024  << Spec.getEndLoc() << Platform;
4025  Valid = false;
4026  }
4027  }
4028 
4029  if (!HasOtherPlatformSpec) {
4030  SourceLocation InsertWildcardLoc = AvailSpecs.back().getEndLoc();
4031  P.Diag(InsertWildcardLoc, diag::err_availability_query_wildcard_required)
4032  << FixItHint::CreateInsertion(InsertWildcardLoc, ", *");
4033  return true;
4034  }
4035 
4036  return !Valid;
4037 }
4038 
4039 /// Parse availability query specification.
4040 ///
4041 /// availability-spec:
4042 /// '*'
4043 /// identifier version-tuple
4044 std::optional<AvailabilitySpec> Parser::ParseAvailabilitySpec() {
4045  if (Tok.is(tok::star)) {
4046  return AvailabilitySpec(ConsumeToken());
4047  } else {
4048  // Parse the platform name.
4049  if (Tok.is(tok::code_completion)) {
4050  cutOffParsing();
4052  return std::nullopt;
4053  }
4054  if (Tok.isNot(tok::identifier)) {
4055  Diag(Tok, diag::err_avail_query_expected_platform_name);
4056  return std::nullopt;
4057  }
4058 
4059  IdentifierLoc *PlatformIdentifier = ParseIdentifierLoc();
4060  SourceRange VersionRange;
4061  VersionTuple Version = ParseVersionTuple(VersionRange);
4062 
4063  if (Version.empty())
4064  return std::nullopt;
4065 
4066  StringRef GivenPlatform = PlatformIdentifier->Ident->getName();
4067  StringRef Platform =
4068  AvailabilityAttr::canonicalizePlatformName(GivenPlatform);
4069 
4070  if (AvailabilityAttr::getPrettyPlatformName(Platform).empty() ||
4071  (GivenPlatform.contains("xros") || GivenPlatform.contains("xrOS"))) {
4072  Diag(PlatformIdentifier->Loc,
4073  diag::err_avail_query_unrecognized_platform_name)
4074  << GivenPlatform;
4075  return std::nullopt;
4076  }
4077 
4078  return AvailabilitySpec(Version, Platform, PlatformIdentifier->Loc,
4079  VersionRange.getEnd());
4080  }
4081 }
4082 
4083 ExprResult Parser::ParseAvailabilityCheckExpr(SourceLocation BeginLoc) {
4084  assert(Tok.is(tok::kw___builtin_available) ||
4085  Tok.isObjCAtKeyword(tok::objc_available));
4086 
4087  // Eat the available or __builtin_available.
4088  ConsumeToken();
4089 
4090  BalancedDelimiterTracker Parens(*this, tok::l_paren);
4091  if (Parens.expectAndConsume())
4092  return ExprError();
4093 
4095  bool HasError = false;
4096  while (true) {
4097  std::optional<AvailabilitySpec> Spec = ParseAvailabilitySpec();
4098  if (!Spec)
4099  HasError = true;
4100  else
4101  AvailSpecs.push_back(*Spec);
4102 
4103  if (!TryConsumeToken(tok::comma))
4104  break;
4105  }
4106 
4107  if (HasError) {
4108  SkipUntil(tok::r_paren, StopAtSemi);
4109  return ExprError();
4110  }
4111 
4112  CheckAvailabilitySpecList(*this, AvailSpecs);
4113 
4114  if (Parens.consumeClose())
4115  return ExprError();
4116 
4117  return Actions.ObjC().ActOnObjCAvailabilityCheckExpr(
4118  AvailSpecs, BeginLoc, Parens.getCloseLocation());
4119 }
Defines the clang::ASTContext interface.
StringRef P
#define SM(sm)
Definition: Cuda.cpp:83
enum clang::sema::@1659::IndirectLocalPathEntry::EntryKind Kind
Expr * E
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1171
Defines the clang::Expr interface and subclasses for C++ expressions.
#define X(type, name)
Definition: Value.h:143
static bool CheckAvailabilitySpecList(Parser &P, ArrayRef< AvailabilitySpec > AvailSpecs)
Validate availability spec list, emitting diagnostics if necessary.
Definition: ParseExpr.cpp:4001
#define REVERTIBLE_TYPE_TRAIT(Name)
Defines the PrettyStackTraceEntry class, which is used to make crashes give more contextual informati...
uint32_t Id
Definition: SemaARM.cpp:1144
This file declares semantic analysis for CUDA constructs.
This file declares facilities that support code completion.
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenACC constructs and clauses.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis for SYCL constructs.
const char * Data
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:713
bool isUnset() const
Definition: Ownership.h:167
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
One specifier in an @available expression.
Definition: Availability.h:31
RAII class that helps handle the parsing of an open/close delimiter pair, such as braces { ....
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3550
ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and restores it when destroyed.
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
virtual bool ValidateCandidate(const TypoCorrection &candidate)
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
bool isFileContext() const
Definition: DeclBase.h:2161
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
bool isRecord() const
Definition: DeclBase.h:2170
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
RAII object that enters a new expression evaluation context.
This represents one expression.
Definition: Expr.h:110
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
ExtensionRAIIObject - This saves the state of extension warnings when constructed and disables them.
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:135
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:124
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:98
One of these records is kept for each identifier that is lexed.
bool hasRevertedTokenIDToIdentifier() const
True if revertTokenIDToIdentifier() was called.
StringRef getName() const
Return the actual identifier string.
Represents the declaration of a label.
Definition: Decl.h:500
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1107
This represents a decl that may have a name.
Definition: Decl.h:249
void * getAsOpaquePtr() const
Definition: Ownership.h:90
PtrTy get() const
Definition: Ownership.h:80
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:843
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:58
TypeResult ParseTypeName(SourceRange *Range=nullptr, DeclaratorContext Context=DeclaratorContext::TypeName, 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:50
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Definition: Parser.cpp:81
const Token & NextToken()
NextToken - This peeks ahead one token and returns it without consuming it.
Definition: Parser.h:872
SourceLocation ConsumeToken()
ConsumeToken - Consume the current 'peek token' and lex the next one.
Definition: Parser.h:548
static TypeResult getTypeAnnotation(const Token &Tok)
getTypeAnnotation - Read a parsed type out of an annotation token.
Definition: Parser.h:877
ExprResult ParseCaseExpression(SourceLocation CaseLoc)
Definition: ParseExpr.cpp:254
ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-or-expression.
Definition: ParseExpr.cpp:382
bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result)
Parse a C++ unqualified-id (or a C identifier), which describes the name of an entity.
Scope * getCurScope() const
Definition: Parser.h:502
Sema & getActions() const
Definition: Parser.h:498
SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok=false)
ConsumeAnyToken - Dispatch to the right Consume* method based on the current token type.
Definition: Parser.h:576
ExprResult ParseConstantExpression()
Definition: ParseExpr.cpp:235
ExprResult ParseConditionalExpression()
Definition: ParseExpr.cpp:190
bool TryConsumeToken(tok::TokenKind Expected)
Definition: Parser.h:556
const LangOptions & getLangOpts() const
Definition: Parser.h:495
ExprResult ParseArrayBoundExpression()
Definition: ParseExpr.cpp:245
ExprResult ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause)
Parse a constraint-logical-and-expression.
Definition: ParseExpr.cpp:290
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:1294
ExprResult ParseAssignmentExpression(TypeCastState isTypeCast=NotTypeCast)
Parse an expr that doesn't include (top-level) commas.
Definition: ParseExpr.cpp:171
ExprResult ParseConstantExpressionInExprEvalContext(TypeCastState isTypeCast=NotTypeCast)
Definition: ParseExpr.cpp:225
ExprResult ParseExpression(TypeCastState isTypeCast=NotTypeCast)
Simple precedence-based parser for binary/ternary operators.
Definition: ParseExpr.cpp:134
@ StopBeforeMatch
Stop skipping at specified token, but don't skip the token itself.
Definition: Parser.h:1275
@ StopAtSemi
Stop skipping at semicolon.
Definition: Parser.h:1273
bool TryAnnotateTypeOrScopeToken(ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
TryAnnotateTypeOrScopeToken - If the current token position is on a typename (possibly qualified in C...
Definition: Parser.cpp:1995
TypeCastState
TypeCastState - State whether an expression is or may be a type cast.
Definition: Parser.h:1837
ExprResult ParseUnevaluatedStringLiteralExpression()
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral=false)
ExprResult ParseConstraintExpression()
Parse a constraint-expression.
Definition: ParseExpr.cpp:268
void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS)
void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc)
void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op)
QualType get(SourceLocation Tok) const
Get the expected type associated with this location, if any.
Definition: Sema.h:307
void EnterToken(const Token &Tok, bool IsReinject)
Enters a token in the token stream to be lexed next.
SourceManager & getSourceManager() const
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool isAtStartOfMacroExpansion(SourceLocation loc, SourceLocation *MacroBegin=nullptr) const
Returns true if the given MacroID location points at the first token of the macro expansion.
bool isCodeCompletionReached() const
Returns true if code-completion is enabled and we have hit the code-completion point.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
llvm::BumpPtrAllocator & getPreprocessorAllocator()
If a crash happens while one of these objects are live, the message is printed out along with the spe...
A (possibly-)qualified type.
Definition: Type.h:941
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
@ BlockScope
This is a scope that corresponds to a block/closure object.
Definition: Scope.h:75
@ CompoundStmtScope
This is a compound statement scope.
Definition: Scope.h:134
@ FnScope
This indicates that the scope corresponds to a function, which means that labels are set here.
Definition: Scope.h:51
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
ExprResult ActOnExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc)
Definition: SemaCUDA.cpp:54
@ PCC_Type
Code completion occurs where only a type is permitted.
void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data)
Perform code-completion in an expression context when we know what type we're looking for.
QualType ProduceCallSignatureHelp(Expr *Fn, ArrayRef< Expr * > Args, SourceLocation OpenParLoc)
Determines the preferred type of the current function argument, by examining the signatures of all po...
void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext)
void CodeCompleteObjCClassPropertyRefExpr(Scope *S, const IdentifierInfo &ClassName, SourceLocation ClassNameLoc, bool IsBaseExprStatement)
void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement, QualType PreferredType)
void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, QualType PreferredType)
ExprResult ActOnObjCBridgedCast(Scope *S, SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, ParsedType Type, SourceLocation RParenLoc, Expr *SubExpr)
ExprResult ActOnClassPropertyRefExpr(const IdentifierInfo &receiverName, const IdentifierInfo &propertyName, SourceLocation receiverNameLoc, SourceLocation propertyNameLoc)
ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value)
ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef< AvailabilitySpec > AvailSpecs, SourceLocation AtLoc, SourceLocation RParen)
ExprResult ActOnArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, Expr *Length, SourceLocation RBLoc)
Checks and creates an Array Section used in an OpenACC construct/clause.
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc)
ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, SourceLocation RParenLoc, ArrayRef< Expr * > Dims, ArrayRef< SourceRange > Brackets)
ExprResult ActOnSYCLBuiltinFieldTypeExpr(ParsedType PT, Expr *Idx)
Get a value based on the type of the given field number so that callers can wrap it in a decltype() t...
Definition: SemaSYCL.cpp:143
ExprResult ActOnUniqueStableIdExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, Expr *E)
Definition: SemaSYCL.cpp:6829
ExprResult ActOnSYCLBuiltinNumBasesExpr(ParsedType PT)
Get the number of base classes within the parsed type.
Definition: SemaSYCL.cpp:222
ExprResult ActOnSYCLBuiltinNumFieldsExpr(ParsedType PT)
Get the number of fields or captures within the parsed type.
Definition: SemaSYCL.cpp:116
ExprResult ActOnSYCLBuiltinBaseTypeExpr(ParsedType PT, Expr *Idx)
Get a value based on the type of the given base number so that callers can wrap it in a decltype() to...
Definition: SemaSYCL.cpp:249
ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, ParsedType ParsedTy)
Definition: SemaSYCL.cpp:6843
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3037
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:12183
SemaObjC & ObjC()
Definition: Sema.h:1169
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
Definition: SemaExpr.cpp:15677
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19467
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen)
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:7034
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:15696
void ActOnStmtExprError()
Definition: SemaExpr.cpp:15702
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2723
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3591
ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor)
ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val)
Definition: SemaStmt.cpp:466
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc)
ActOnCXXNullPtrLiteral - Parse 'nullptr'.
bool CheckConstraintExpression(const Expr *CE, Token NextToken=Token(), bool *PossibleNonPrimary=nullptr, bool IsTrailingRequiresClause=false)
Check whether the given expression is a valid constraint expression.
Definition: SemaConcept.cpp:92
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:15683
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:7903
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
Definition: SemaExpr.cpp:15971
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
Definition: SemaExpr.cpp:2024
SourceRange getExprRange(Expr *E) const
Definition: SemaExpr.cpp:575
@ ReuseLambdaContextDecl
Definition: Sema.h:6572
ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E)
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl)
The main callback when the parser finds something like expression .
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr * > ArgExprs)
ControllingExprOrType is either an opaque pointer coming out of a ParsedType or an Expr *.
Definition: SemaExpr.cpp:1694
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
Definition: SemaExpr.cpp:16157
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1102
SemaOpenACC & OpenACC()
Definition: Sema.h:1174
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:16519
SemaSYCL & SYCL()
Definition: Sema.h:1204
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4154
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16604
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?: operation.
Definition: SemaExpr.cpp:8771
LabelDecl * LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc=SourceLocation())
LookupOrCreateLabel - Do a name lookup of a label with the specified name.
TypeResult ActOnTypeName(Declarator &D)
Definition: SemaType.cpp:6374
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc)
Invoked when parsing a template argument followed by an ellipsis, which creates a pack expansion.
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e....
Definition: SemaExpr.cpp:2103
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
Definition: SemaExpr.cpp:15138
ASTContext & getASTContext() const
Definition: Sema.h:560
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:289
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3587
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Parse a __builtin_astype expression.
Definition: SemaExpr.cpp:6696
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16356
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:7731
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7967
ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc)
Called when an expression computing the size of a parameter pack is parsed.
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:15710
ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc)
Handle a C++1z fold-expression: ( expr op ... op expr ).
SemaOpenMP & OpenMP()
Definition: Sema.h:1184
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
Definition: SemaExpr.cpp:16167
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:601
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4800
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:20985
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3724
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:16009
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
Definition: SemaExpr.cpp:4873
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6436
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
Definition: SemaExpr.cpp:4730
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:16038
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ActOnConvertVectorExpr - create a new convert-vector expression from the provided arguments.
Definition: SemaExpr.cpp:6717
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:15952
SemaCodeCompletion & CodeCompletion()
Definition: Sema.h:1124
SemaCUDA & CUDA()
Definition: Sema.h:1129
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, 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...
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Definition: SemaDecl.cpp:1264
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:132
void * getAnnotationValue() const
Definition: Token.h:234
void setKind(tok::TokenKind K)
Definition: Token.h:95
const char * getName() const
Definition: Token.h:174
SourceLocation getAnnotationEndLoc() const
Definition: Token.h:146
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:99
tok::TokenKind getKind() const
Definition: Token.h:94
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:276
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:187
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:101
bool isNot(tok::TokenKind K) const
Definition: Token.h:100
bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const
Return true if we have an ObjC keyword identifier.
Definition: Lexer.cpp:61
bool isSimpleTypeSpecifier(const LangOptions &LangOpts) const
Determine whether the token kind starts a simple-type-specifier.
Definition: Lexer.cpp:78
SourceLocation getLastLoc() const
Definition: Token.h:155
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
The base class of the type hierarchy.
Definition: Type.h:1829
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:8336
bool isFunctionType() const
Definition: Type.h:8009
bool isVectorType() const
Definition: Type.h:8125
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
@ TST_typename
Definition: Specifiers.h:84
@ OpenCL
Definition: LangStandard.h:66
@ CPlusPlus23
Definition: LangStandard.h:61
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus11
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:59
bool tokenIsLikeStringLiteral(const Token &Tok, const LangOptions &LO)
Return true if the token is a string literal, or a function local predefined macro,...
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:51
ExprResult ExprEmpty()
Definition: Ownership.h:271
ObjCBridgeCastKind
The kind of bridging performed by the Objective-C bridge cast.
@ OBC_Bridge
Bridging via __bridge, which does nothing but reinterpret the bits.
@ OBC_BridgeTransfer
Bridging via __bridge_transfer, which transfers ownership of an Objective-C pointer into ARC.
@ OBC_BridgeRetained
Bridging via __bridge_retain, which makes an ARC object available as a +1 C pointer.
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
ExprResult ExprError()
Definition: Ownership.h:264
prec::Level getBinOpPrecedence(tok::TokenKind Kind, bool GreaterThanIsOperator, bool CPlusPlus11)
Return the precedence of the specified binary operator token.
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:249
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
const FunctionProtoType * T
SourceLocIdentKind
Definition: Expr.h:4790
@ Parens
New-expression has a C++98 paren-delimited initializer.
@ EST_None
no exception specification
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(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:161
Helper class to shuttle information about #embed directives from the preprocessor to the parser throu...
Wraps an identifier and optional source location for the identifier.
Definition: ParsedAttr.h:103
SourceLocation Loc
Definition: ParsedAttr.h:104
IdentifierInfo * Ident
Definition: ParsedAttr.h:105
Information about a template-id annotation token.
TemplateNameKind Kind
The kind of template that Template refers to.