Skip to content

Tighten up assignment operator representations. #138017

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 70 additions & 1 deletion compiler/rustc_ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -981,6 +981,75 @@ impl BinOpKind {

pub type BinOp = Spanned<BinOpKind>;

// Sometimes `BinOpKind` and `AssignOpKind` need the same treatment. The
// operations covered by `AssignOpKind` are a subset of those covered by
// `BinOpKind`, so it makes sense to convert `AssignOpKind` to `BinOpKind`.
impl From<AssignOpKind> for BinOpKind {
fn from(op: AssignOpKind) -> BinOpKind {
match op {
AssignOpKind::AddAssign => BinOpKind::Add,
AssignOpKind::SubAssign => BinOpKind::Sub,
AssignOpKind::MulAssign => BinOpKind::Mul,
AssignOpKind::DivAssign => BinOpKind::Div,
AssignOpKind::RemAssign => BinOpKind::Rem,
AssignOpKind::BitXorAssign => BinOpKind::BitXor,
AssignOpKind::BitAndAssign => BinOpKind::BitAnd,
AssignOpKind::BitOrAssign => BinOpKind::BitOr,
AssignOpKind::ShlAssign => BinOpKind::Shl,
AssignOpKind::ShrAssign => BinOpKind::Shr,
}
}
}

#[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
pub enum AssignOpKind {
/// The `+=` operator (addition)
AddAssign,
/// The `-=` operator (subtraction)
SubAssign,
/// The `*=` operator (multiplication)
MulAssign,
/// The `/=` operator (division)
DivAssign,
/// The `%=` operator (modulus)
RemAssign,
/// The `^=` operator (bitwise xor)
BitXorAssign,
/// The `&=` operator (bitwise and)
BitAndAssign,
/// The `|=` operator (bitwise or)
BitOrAssign,
/// The `<<=` operator (shift left)
ShlAssign,
/// The `>>=` operator (shift right)
ShrAssign,
}

impl AssignOpKind {
pub fn as_str(&self) -> &'static str {
use AssignOpKind::*;
match self {
AddAssign => "+=",
SubAssign => "-=",
MulAssign => "*=",
DivAssign => "/=",
RemAssign => "%=",
BitXorAssign => "^=",
BitAndAssign => "&=",
BitOrAssign => "|=",
ShlAssign => "<<=",
ShrAssign => ">>=",
}
}

/// AssignOps are always by value.
pub fn is_by_value(self) -> bool {
true
}
}

pub type AssignOp = Spanned<AssignOpKind>;

/// Unary operator.
///
/// Note that `&data` is not an operator, it's an `AddrOf` expression.
Expand Down Expand Up @@ -1593,7 +1662,7 @@ pub enum ExprKind {
/// An assignment with an operator.
///
/// E.g., `a += 1`.
AssignOp(BinOp, P<Expr>, P<Expr>),
AssignOp(AssignOp, P<Expr>, P<Expr>),
/// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
Field(P<Expr>, Ident),
/// An indexing operation (e.g., `foo[2]`).
Expand Down
24 changes: 12 additions & 12 deletions compiler/rustc_ast/src/util/parser.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use rustc_span::kw;

use crate::ast::{self, BinOpKind, RangeLimits};
use crate::ast::{self, AssignOpKind, BinOpKind, RangeLimits};
use crate::token::{self, Token};

/// Associative operator.
Expand All @@ -9,7 +9,7 @@ pub enum AssocOp {
/// A binary op.
Binary(BinOpKind),
/// `?=` where ? is one of the assignable BinOps
AssignOp(BinOpKind),
AssignOp(AssignOpKind),
/// `=`
Assign,
/// `as`
Expand Down Expand Up @@ -44,16 +44,16 @@ impl AssocOp {
token::Or => Some(Binary(BinOpKind::BitOr)),
token::Shl => Some(Binary(BinOpKind::Shl)),
token::Shr => Some(Binary(BinOpKind::Shr)),
token::PlusEq => Some(AssignOp(BinOpKind::Add)),
token::MinusEq => Some(AssignOp(BinOpKind::Sub)),
token::StarEq => Some(AssignOp(BinOpKind::Mul)),
token::SlashEq => Some(AssignOp(BinOpKind::Div)),
token::PercentEq => Some(AssignOp(BinOpKind::Rem)),
token::CaretEq => Some(AssignOp(BinOpKind::BitXor)),
token::AndEq => Some(AssignOp(BinOpKind::BitAnd)),
token::OrEq => Some(AssignOp(BinOpKind::BitOr)),
token::ShlEq => Some(AssignOp(BinOpKind::Shl)),
token::ShrEq => Some(AssignOp(BinOpKind::Shr)),
token::PlusEq => Some(AssignOp(AssignOpKind::AddAssign)),
token::MinusEq => Some(AssignOp(AssignOpKind::SubAssign)),
token::StarEq => Some(AssignOp(AssignOpKind::MulAssign)),
token::SlashEq => Some(AssignOp(AssignOpKind::DivAssign)),
token::PercentEq => Some(AssignOp(AssignOpKind::RemAssign)),
token::CaretEq => Some(AssignOp(AssignOpKind::BitXorAssign)),
token::AndEq => Some(AssignOp(AssignOpKind::BitAndAssign)),
token::OrEq => Some(AssignOp(AssignOpKind::BitOrAssign)),
token::ShlEq => Some(AssignOp(AssignOpKind::ShlAssign)),
token::ShrEq => Some(AssignOp(AssignOpKind::ShrAssign)),
token::Lt => Some(Binary(BinOpKind::Lt)),
token::Le => Some(Binary(BinOpKind::Le)),
token::Ge => Some(Binary(BinOpKind::Ge)),
Expand Down
6 changes: 5 additions & 1 deletion compiler/rustc_ast_lowering/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
}
ExprKind::Assign(el, er, span) => self.lower_expr_assign(el, er, *span, e.span),
ExprKind::AssignOp(op, el, er) => hir::ExprKind::AssignOp(
self.lower_binop(*op),
self.lower_assign_op(*op),
self.lower_expr(el),
self.lower_expr(er),
),
Expand Down Expand Up @@ -443,6 +443,10 @@ impl<'hir> LoweringContext<'_, 'hir> {
Spanned { node: b.node, span: self.lower_span(b.span) }
}

fn lower_assign_op(&mut self, a: AssignOp) -> AssignOp {
Spanned { node: a.node, span: self.lower_span(a.span) }
}

fn lower_legacy_const_generics(
&mut self,
mut f: Expr,
Expand Down
15 changes: 7 additions & 8 deletions compiler/rustc_ast_pretty/src/pprust/state/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,22 +274,22 @@ impl<'a> State<'a> {

fn print_expr_binary(
&mut self,
op: ast::BinOp,
op: ast::BinOpKind,
lhs: &ast::Expr,
rhs: &ast::Expr,
fixup: FixupContext,
) {
let binop_prec = op.node.precedence();
let binop_prec = op.precedence();
let left_prec = lhs.precedence();
let right_prec = rhs.precedence();

let (mut left_needs_paren, right_needs_paren) = match op.node.fixity() {
let (mut left_needs_paren, right_needs_paren) = match op.fixity() {
Fixity::Left => (left_prec < binop_prec, right_prec <= binop_prec),
Fixity::Right => (left_prec <= binop_prec, right_prec < binop_prec),
Fixity::None => (left_prec <= binop_prec, right_prec <= binop_prec),
};

match (&lhs.kind, op.node) {
match (&lhs.kind, op) {
// These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
// the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
// of `(x as i32) < ...`. We need to convince it _not_ to do that.
Expand All @@ -312,7 +312,7 @@ impl<'a> State<'a> {

self.print_expr_cond_paren(lhs, left_needs_paren, fixup.leftmost_subexpression());
self.space();
self.word_space(op.node.as_str());
self.word_space(op.as_str());
self.print_expr_cond_paren(rhs, right_needs_paren, fixup.subsequent_subexpression());
}

Expand Down Expand Up @@ -410,7 +410,7 @@ impl<'a> State<'a> {
self.print_expr_method_call(seg, receiver, args, fixup);
}
ast::ExprKind::Binary(op, lhs, rhs) => {
self.print_expr_binary(*op, lhs, rhs, fixup);
self.print_expr_binary(op.node, lhs, rhs, fixup);
}
ast::ExprKind::Unary(op, expr) => {
self.print_expr_unary(*op, expr, fixup);
Expand Down Expand Up @@ -605,8 +605,7 @@ impl<'a> State<'a> {
fixup.leftmost_subexpression(),
);
self.space();
self.word(op.node.as_str());
self.word_space("=");
self.word_space(op.node.as_str());
self.print_expr_cond_paren(
rhs,
rhs.precedence() < ExprPrecedence::Assign,
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ use rustc_ast::{
LitKind, TraitObjectSyntax, UintTy, UnsafeBinderCastKind,
};
pub use rustc_ast::{
AttrId, AttrStyle, BinOp, BinOpKind, BindingMode, BorrowKind, BoundConstness, BoundPolarity,
ByRef, CaptureBy, DelimArgs, ImplPolarity, IsAuto, MetaItemInner, MetaItemLit, Movability,
Mutability, UnOp,
AssignOp, AssignOpKind, AttrId, AttrStyle, BinOp, BinOpKind, BindingMode, BorrowKind,
BoundConstness, BoundPolarity, ByRef, CaptureBy, DelimArgs, ImplPolarity, IsAuto,
MetaItemInner, MetaItemLit, Movability, Mutability, UnOp,
};
use rustc_attr_data_structures::AttributeKind;
use rustc_data_structures::fingerprint::Fingerprint;
Expand Down Expand Up @@ -2648,7 +2648,7 @@ pub enum ExprKind<'hir> {
/// An assignment with an operator.
///
/// E.g., `a += 1`.
AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
AssignOp(AssignOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
/// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
Field(&'hir Expr<'hir>, Ident),
/// An indexing operation (`foo[2]`).
Expand Down
15 changes: 7 additions & 8 deletions compiler/rustc_hir_pretty/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1271,18 +1271,18 @@ impl<'a> State<'a> {
self.print_call_post(base_args)
}

fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
let binop_prec = op.node.precedence();
fn print_expr_binary(&mut self, op: hir::BinOpKind, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
let binop_prec = op.precedence();
let left_prec = lhs.precedence();
let right_prec = rhs.precedence();

let (mut left_needs_paren, right_needs_paren) = match op.node.fixity() {
let (mut left_needs_paren, right_needs_paren) = match op.fixity() {
Fixity::Left => (left_prec < binop_prec, right_prec <= binop_prec),
Fixity::Right => (left_prec <= binop_prec, right_prec < binop_prec),
Fixity::None => (left_prec <= binop_prec, right_prec <= binop_prec),
};

match (&lhs.kind, op.node) {
match (&lhs.kind, op) {
// These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
// the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
// of `(x as i32) < ...`. We need to convince it _not_ to do that.
Expand All @@ -1297,7 +1297,7 @@ impl<'a> State<'a> {

self.print_expr_cond_paren(lhs, left_needs_paren);
self.space();
self.word_space(op.node.as_str());
self.word_space(op.as_str());
self.print_expr_cond_paren(rhs, right_needs_paren);
}

Expand Down Expand Up @@ -1451,7 +1451,7 @@ impl<'a> State<'a> {
self.word(".use");
}
hir::ExprKind::Binary(op, lhs, rhs) => {
self.print_expr_binary(op, lhs, rhs);
self.print_expr_binary(op.node, lhs, rhs);
}
hir::ExprKind::Unary(op, expr) => {
self.print_expr_unary(op, expr);
Expand Down Expand Up @@ -1572,8 +1572,7 @@ impl<'a> State<'a> {
hir::ExprKind::AssignOp(op, lhs, rhs) => {
self.print_expr_cond_paren(lhs, lhs.precedence() <= ExprPrecedence::Assign);
self.space();
self.word(op.node.as_str());
self.word_space("=");
self.word_space(op.node.as_str());
self.print_expr_cond_paren(rhs, rhs.precedence() < ExprPrecedence::Assign);
}
hir::ExprKind::Field(expr, ident) => {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -512,7 +512,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.check_expr_assign(expr, expected, lhs, rhs, span)
}
ExprKind::AssignOp(op, lhs, rhs) => {
self.check_expr_binop_assign(expr, op, lhs, rhs, expected)
self.check_expr_assign_op(expr, op, lhs, rhs, expected)
}
ExprKind::Unary(unop, oprnd) => self.check_expr_unop(unop, oprnd, expected, expr),
ExprKind::AddrOf(kind, mutbl, oprnd) => {
Expand Down
38 changes: 16 additions & 22 deletions compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3477,30 +3477,24 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
lhs_ty: Ty<'tcx>,
rhs_expr: &'tcx hir::Expr<'tcx>,
lhs_expr: &'tcx hir::Expr<'tcx>,
op: hir::BinOp,
) {
match op.node {
hir::BinOpKind::Eq => {
if let Some(partial_eq_def_id) = self.infcx.tcx.lang_items().eq_trait()
&& self
.infcx
.type_implements_trait(partial_eq_def_id, [rhs_ty, lhs_ty], self.param_env)
.must_apply_modulo_regions()
{
let sm = self.tcx.sess.source_map();
if let Ok(rhs_snippet) = sm.span_to_snippet(rhs_expr.span)
&& let Ok(lhs_snippet) = sm.span_to_snippet(lhs_expr.span)
{
err.note(format!("`{rhs_ty}` implements `PartialEq<{lhs_ty}>`"));
err.multipart_suggestion(
"consider swapping the equality",
vec![(lhs_expr.span, rhs_snippet), (rhs_expr.span, lhs_snippet)],
Applicability::MaybeIncorrect,
);
}
}
if let Some(partial_eq_def_id) = self.infcx.tcx.lang_items().eq_trait()
&& self
.infcx
.type_implements_trait(partial_eq_def_id, [rhs_ty, lhs_ty], self.param_env)
.must_apply_modulo_regions()
{
let sm = self.tcx.sess.source_map();
if let Ok(rhs_snippet) = sm.span_to_snippet(rhs_expr.span)
&& let Ok(lhs_snippet) = sm.span_to_snippet(lhs_expr.span)
{
err.note(format!("`{rhs_ty}` implements `PartialEq<{lhs_ty}>`"));
err.multipart_suggestion(
"consider swapping the equality",
vec![(lhs_expr.span, rhs_snippet), (rhs_expr.span, lhs_snippet)],
Applicability::MaybeIncorrect,
);
}
_ => {}
}
}
}
Loading
Loading