Skip to content

Commit e43b280

Browse files
committed
Tighten up assignment operator representations.
In the AST, currently we use `BinOpKind` within `ExprKind::AssignOp` and `AssocOp::AssignOp`, even though this allows some nonsensical combinations. E.g. there is no `&&=` operator. Likewise for HIR and THIR. This commit introduces `AssignOpKind` which only includes the ten assignable operators, and uses it in `ExprKind::AssignOp` and `AssocOp::AssignOp`. (And does similar things for `hir::ExprKind` and `thir::ExprKind`.) This avoids the possibility of nonsensical combinations, as seen by the removal of the `bug!` case in `lang_item_for_binop`. The commit is mostly plumbing, including: - Adds an `impl From<AssignOpKind> for BinOpKind` (AST) and `impl From<AssignOp> for BinOp` (MIR/THIR). - `BinOpCategory` can now be created from both `BinOpKind` and `AssignOpKind`. - Replaces the `IsAssign` type with `Op`, which has more information and a few methods. - `suggest_swapping_lhs_and_rhs`: moves the condition to the call site, it's easier that way. - `check_expr_inner`: had to factor out some code into a separate method. I'm on the fence about whether avoiding the nonsensical combinations is worth the extra code.
1 parent 3e3e69b commit e43b280

File tree

26 files changed

+395
-235
lines changed

26 files changed

+395
-235
lines changed

compiler/rustc_ast/src/ast.rs

+70-1
Original file line numberDiff line numberDiff line change
@@ -989,6 +989,75 @@ impl BinOpKind {
989989

990990
pub type BinOp = Spanned<BinOpKind>;
991991

992+
// Sometimes `BinOpKind` and `AssignOpKind` need the same treatment. The
993+
// operations covered by `AssignOpKind` are a subset of those covered by
994+
// `BinOpKind`, so it makes sense to convert `AssignOpKind` to `BinOpKind`.
995+
impl From<AssignOpKind> for BinOpKind {
996+
fn from(op: AssignOpKind) -> BinOpKind {
997+
match op {
998+
AssignOpKind::AddAssign => BinOpKind::Add,
999+
AssignOpKind::SubAssign => BinOpKind::Sub,
1000+
AssignOpKind::MulAssign => BinOpKind::Mul,
1001+
AssignOpKind::DivAssign => BinOpKind::Div,
1002+
AssignOpKind::RemAssign => BinOpKind::Rem,
1003+
AssignOpKind::BitXorAssign => BinOpKind::BitXor,
1004+
AssignOpKind::BitAndAssign => BinOpKind::BitAnd,
1005+
AssignOpKind::BitOrAssign => BinOpKind::BitOr,
1006+
AssignOpKind::ShlAssign => BinOpKind::Shl,
1007+
AssignOpKind::ShrAssign => BinOpKind::Shr,
1008+
}
1009+
}
1010+
}
1011+
1012+
#[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
1013+
pub enum AssignOpKind {
1014+
/// The `+=` operator (addition)
1015+
AddAssign,
1016+
/// The `-=` operator (subtraction)
1017+
SubAssign,
1018+
/// The `*=` operator (multiplication)
1019+
MulAssign,
1020+
/// The `/=` operator (division)
1021+
DivAssign,
1022+
/// The `%=` operator (modulus)
1023+
RemAssign,
1024+
/// The `^=` operator (bitwise xor)
1025+
BitXorAssign,
1026+
/// The `&=` operator (bitwise and)
1027+
BitAndAssign,
1028+
/// The `|=` operator (bitwise or)
1029+
BitOrAssign,
1030+
/// The `<<=` operator (shift left)
1031+
ShlAssign,
1032+
/// The `>>=` operator (shift right)
1033+
ShrAssign,
1034+
}
1035+
1036+
impl AssignOpKind {
1037+
pub fn as_str(&self) -> &'static str {
1038+
use AssignOpKind::*;
1039+
match self {
1040+
AddAssign => "+=",
1041+
SubAssign => "-=",
1042+
MulAssign => "*=",
1043+
DivAssign => "/=",
1044+
RemAssign => "%=",
1045+
BitXorAssign => "^=",
1046+
BitAndAssign => "&=",
1047+
BitOrAssign => "|=",
1048+
ShlAssign => "<<=",
1049+
ShrAssign => ">>=",
1050+
}
1051+
}
1052+
1053+
/// AssignOps are always by value.
1054+
pub fn is_by_value(self) -> bool {
1055+
true
1056+
}
1057+
}
1058+
1059+
pub type AssignOp = Spanned<AssignOpKind>;
1060+
9921061
/// Unary operator.
9931062
///
9941063
/// Note that `&data` is not an operator, it's an `AddrOf` expression.
@@ -1601,7 +1670,7 @@ pub enum ExprKind {
16011670
/// An assignment with an operator.
16021671
///
16031672
/// E.g., `a += 1`.
1604-
AssignOp(BinOp, P<Expr>, P<Expr>),
1673+
AssignOp(AssignOp, P<Expr>, P<Expr>),
16051674
/// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
16061675
Field(P<Expr>, Ident),
16071676
/// An indexing operation (e.g., `foo[2]`).

compiler/rustc_ast/src/util/parser.rs

+12-12
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use rustc_span::kw;
22

3-
use crate::ast::{self, BinOpKind, RangeLimits};
3+
use crate::ast::{self, AssignOpKind, BinOpKind, RangeLimits};
44
use crate::token::{self, Token};
55

66
/// Associative operator.
@@ -9,7 +9,7 @@ pub enum AssocOp {
99
/// A binary op.
1010
Binary(BinOpKind),
1111
/// `?=` where ? is one of the assignable BinOps
12-
AssignOp(BinOpKind),
12+
AssignOp(AssignOpKind),
1313
/// `=`
1414
Assign,
1515
/// `as`
@@ -44,16 +44,16 @@ impl AssocOp {
4444
token::Or => Some(Binary(BinOpKind::BitOr)),
4545
token::Shl => Some(Binary(BinOpKind::Shl)),
4646
token::Shr => Some(Binary(BinOpKind::Shr)),
47-
token::PlusEq => Some(AssignOp(BinOpKind::Add)),
48-
token::MinusEq => Some(AssignOp(BinOpKind::Sub)),
49-
token::StarEq => Some(AssignOp(BinOpKind::Mul)),
50-
token::SlashEq => Some(AssignOp(BinOpKind::Div)),
51-
token::PercentEq => Some(AssignOp(BinOpKind::Rem)),
52-
token::CaretEq => Some(AssignOp(BinOpKind::BitXor)),
53-
token::AndEq => Some(AssignOp(BinOpKind::BitAnd)),
54-
token::OrEq => Some(AssignOp(BinOpKind::BitOr)),
55-
token::ShlEq => Some(AssignOp(BinOpKind::Shl)),
56-
token::ShrEq => Some(AssignOp(BinOpKind::Shr)),
47+
token::PlusEq => Some(AssignOp(AssignOpKind::AddAssign)),
48+
token::MinusEq => Some(AssignOp(AssignOpKind::SubAssign)),
49+
token::StarEq => Some(AssignOp(AssignOpKind::MulAssign)),
50+
token::SlashEq => Some(AssignOp(AssignOpKind::DivAssign)),
51+
token::PercentEq => Some(AssignOp(AssignOpKind::RemAssign)),
52+
token::CaretEq => Some(AssignOp(AssignOpKind::BitXorAssign)),
53+
token::AndEq => Some(AssignOp(AssignOpKind::BitAndAssign)),
54+
token::OrEq => Some(AssignOp(AssignOpKind::BitOrAssign)),
55+
token::ShlEq => Some(AssignOp(AssignOpKind::ShlAssign)),
56+
token::ShrEq => Some(AssignOp(AssignOpKind::ShrAssign)),
5757
token::Lt => Some(Binary(BinOpKind::Lt)),
5858
token::Le => Some(Binary(BinOpKind::Le)),
5959
token::Ge => Some(Binary(BinOpKind::Ge)),

compiler/rustc_ast_lowering/src/expr.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
274274
}
275275
ExprKind::Assign(el, er, span) => self.lower_expr_assign(el, er, *span, e.span),
276276
ExprKind::AssignOp(op, el, er) => hir::ExprKind::AssignOp(
277-
self.lower_binop(*op),
277+
self.lower_assign_op(*op),
278278
self.lower_expr(el),
279279
self.lower_expr(er),
280280
),
@@ -443,6 +443,10 @@ impl<'hir> LoweringContext<'_, 'hir> {
443443
Spanned { node: b.node, span: self.lower_span(b.span) }
444444
}
445445

446+
fn lower_assign_op(&mut self, a: AssignOp) -> AssignOp {
447+
Spanned { node: a.node, span: self.lower_span(a.span) }
448+
}
449+
446450
fn lower_legacy_const_generics(
447451
&mut self,
448452
mut f: Expr,

compiler/rustc_ast_pretty/src/pprust/state/expr.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -605,8 +605,7 @@ impl<'a> State<'a> {
605605
fixup.leftmost_subexpression(),
606606
);
607607
self.space();
608-
self.word(op.node.as_str());
609-
self.word_space("=");
608+
self.word_space(op.node.as_str());
610609
self.print_expr_cond_paren(
611610
rhs,
612611
rhs.precedence() < ExprPrecedence::Assign,

compiler/rustc_hir/src/hir.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ use rustc_ast::{
1010
LitKind, TraitObjectSyntax, UintTy, UnsafeBinderCastKind,
1111
};
1212
pub use rustc_ast::{
13-
AttrId, AttrStyle, BinOp, BinOpKind, BindingMode, BorrowKind, BoundConstness, BoundPolarity,
14-
ByRef, CaptureBy, DelimArgs, ImplPolarity, IsAuto, MetaItemInner, MetaItemLit, Movability,
15-
Mutability, UnOp,
13+
AssignOp, AssignOpKind, AttrId, AttrStyle, BinOp, BinOpKind, BindingMode, BorrowKind,
14+
BoundConstness, BoundPolarity, ByRef, CaptureBy, DelimArgs, ImplPolarity, IsAuto,
15+
MetaItemInner, MetaItemLit, Movability, Mutability, UnOp,
1616
};
1717
use rustc_attr_data_structures::AttributeKind;
1818
use rustc_data_structures::fingerprint::Fingerprint;
@@ -2609,7 +2609,7 @@ pub enum ExprKind<'hir> {
26092609
/// An assignment with an operator.
26102610
///
26112611
/// E.g., `a += 1`.
2612-
AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2612+
AssignOp(AssignOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
26132613
/// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
26142614
Field(&'hir Expr<'hir>, Ident),
26152615
/// An indexing operation (`foo[2]`).

compiler/rustc_hir_pretty/src/lib.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -1577,8 +1577,7 @@ impl<'a> State<'a> {
15771577
hir::ExprKind::AssignOp(op, lhs, rhs) => {
15781578
self.print_expr_cond_paren(lhs, lhs.precedence() <= ExprPrecedence::Assign);
15791579
self.space();
1580-
self.word(op.node.as_str());
1581-
self.word_space("=");
1580+
self.word_space(op.node.as_str());
15821581
self.print_expr_cond_paren(rhs, rhs.precedence() < ExprPrecedence::Assign);
15831582
}
15841583
hir::ExprKind::Field(expr, ident) => {

compiler/rustc_hir_typeck/src/expr.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -512,7 +512,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
512512
self.check_expr_assign(expr, expected, lhs, rhs, span)
513513
}
514514
ExprKind::AssignOp(op, lhs, rhs) => {
515-
self.check_expr_binop_assign(expr, op, lhs, rhs, expected)
515+
self.check_expr_assign_op(expr, op, lhs, rhs, expected)
516516
}
517517
ExprKind::Unary(unop, oprnd) => self.check_expr_unop(unop, oprnd, expected, expr),
518518
ExprKind::AddrOf(kind, mutbl, oprnd) => {

compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs

+16-22
Original file line numberDiff line numberDiff line change
@@ -3478,30 +3478,24 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
34783478
lhs_ty: Ty<'tcx>,
34793479
rhs_expr: &'tcx hir::Expr<'tcx>,
34803480
lhs_expr: &'tcx hir::Expr<'tcx>,
3481-
op: hir::BinOpKind,
34823481
) {
3483-
match op {
3484-
hir::BinOpKind::Eq => {
3485-
if let Some(partial_eq_def_id) = self.infcx.tcx.lang_items().eq_trait()
3486-
&& self
3487-
.infcx
3488-
.type_implements_trait(partial_eq_def_id, [rhs_ty, lhs_ty], self.param_env)
3489-
.must_apply_modulo_regions()
3490-
{
3491-
let sm = self.tcx.sess.source_map();
3492-
if let Ok(rhs_snippet) = sm.span_to_snippet(rhs_expr.span)
3493-
&& let Ok(lhs_snippet) = sm.span_to_snippet(lhs_expr.span)
3494-
{
3495-
err.note(format!("`{rhs_ty}` implements `PartialEq<{lhs_ty}>`"));
3496-
err.multipart_suggestion(
3497-
"consider swapping the equality",
3498-
vec![(lhs_expr.span, rhs_snippet), (rhs_expr.span, lhs_snippet)],
3499-
Applicability::MaybeIncorrect,
3500-
);
3501-
}
3502-
}
3482+
if let Some(partial_eq_def_id) = self.infcx.tcx.lang_items().eq_trait()
3483+
&& self
3484+
.infcx
3485+
.type_implements_trait(partial_eq_def_id, [rhs_ty, lhs_ty], self.param_env)
3486+
.must_apply_modulo_regions()
3487+
{
3488+
let sm = self.tcx.sess.source_map();
3489+
if let Ok(rhs_snippet) = sm.span_to_snippet(rhs_expr.span)
3490+
&& let Ok(lhs_snippet) = sm.span_to_snippet(lhs_expr.span)
3491+
{
3492+
err.note(format!("`{rhs_ty}` implements `PartialEq<{lhs_ty}>`"));
3493+
err.multipart_suggestion(
3494+
"consider swapping the equality",
3495+
vec![(lhs_expr.span, rhs_snippet), (rhs_expr.span, lhs_snippet)],
3496+
Applicability::MaybeIncorrect,
3497+
);
35033498
}
3504-
_ => {}
35053499
}
35063500
}
35073501
}

0 commit comments

Comments
 (0)