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