Coverage Report

Created: 2024-01-17 10:31

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