Coverage Report

Created: 2020-02-25 14:32

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