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