Skip to content

Commit 74227e1

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 5f66b0d commit 74227e1

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
@@ -980,6 +980,75 @@ impl BinOpKind {
980980

981981
pub type BinOp = Spanned<BinOpKind>;
982982

983+
// Sometimes `BinOpKind` and `AssignOpKind` need the same treatment. The
984+
// operations covered by `AssignOpKind` are a subset of those covered by
985+
// `BinOpKind`, so it makes sense to convert `AssignOpKind` to `BinOpKind`.
986+
impl From<AssignOpKind> for BinOpKind {
987+
fn from(op: AssignOpKind) -> BinOpKind {
988+
match op {
989+
AssignOpKind::AddAssign => BinOpKind::Add,
990+
AssignOpKind::SubAssign => BinOpKind::Sub,
991+
AssignOpKind::MulAssign => BinOpKind::Mul,
992+
AssignOpKind::DivAssign => BinOpKind::Div,
993+
AssignOpKind::RemAssign => BinOpKind::Rem,
994+
AssignOpKind::BitXorAssign => BinOpKind::BitXor,
995+
AssignOpKind::BitAndAssign => BinOpKind::BitAnd,
996+
AssignOpKind::BitOrAssign => BinOpKind::BitOr,
997+
AssignOpKind::ShlAssign => BinOpKind::Shl,
998+
AssignOpKind::ShrAssign => BinOpKind::Shr,
999+
}
1000+
}
1001+
}
1002+
1003+
#[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
1004+
pub enum AssignOpKind {
1005+
/// The `+=` operator (addition)
1006+
AddAssign,
1007+
/// The `-=` operator (subtraction)
1008+
SubAssign,
1009+
/// The `*=` operator (multiplication)
1010+
MulAssign,
1011+
/// The `/=` operator (division)
1012+
DivAssign,
1013+
/// The `%=` operator (modulus)
1014+
RemAssign,
1015+
/// The `^=` operator (bitwise xor)
1016+
BitXorAssign,
1017+
/// The `&=` operator (bitwise and)
1018+
BitAndAssign,
1019+
/// The `|=` operator (bitwise or)
1020+
BitOrAssign,
1021+
/// The `<<=` operator (shift left)
1022+
ShlAssign,
1023+
/// The `>>=` operator (shift right)
1024+
ShrAssign,
1025+
}
1026+
1027+
impl AssignOpKind {
1028+
pub fn as_str(&self) -> &'static str {
1029+
use AssignOpKind::*;
1030+
match self {
1031+
AddAssign => "+=",
1032+
SubAssign => "-=",
1033+
MulAssign => "*=",
1034+
DivAssign => "/=",
1035+
RemAssign => "%=",
1036+
BitXorAssign => "^=",
1037+
BitAndAssign => "&=",
1038+
BitOrAssign => "|=",
1039+
ShlAssign => "<<=",
1040+
ShrAssign => ">>=",
1041+
}
1042+
}
1043+
1044+
/// AssignOps are always by value.
1045+
pub fn is_by_value(self) -> bool {
1046+
true
1047+
}
1048+
}
1049+
1050+
pub type AssignOp = Spanned<AssignOpKind>;
1051+
9831052
/// Unary operator.
9841053
///
9851054
/// Note that `&data` is not an operator, it's an `AddrOf` expression.
@@ -1580,7 +1649,7 @@ pub enum ExprKind {
15801649
/// An assignment with an operator.
15811650
///
15821651
/// E.g., `a += 1`.
1583-
AssignOp(BinOp, P<Expr>, P<Expr>),
1652+
AssignOp(AssignOp, P<Expr>, P<Expr>),
15841653
/// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field.
15851654
Field(P<Expr>, Ident),
15861655
/// 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
@@ -273,7 +273,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
273273
}
274274
ExprKind::Assign(el, er, span) => self.lower_expr_assign(el, er, *span, e.span),
275275
ExprKind::AssignOp(op, el, er) => hir::ExprKind::AssignOp(
276-
self.lower_binop(*op),
276+
self.lower_assign_op(*op),
277277
self.lower_expr(el),
278278
self.lower_expr(er),
279279
),
@@ -442,6 +442,10 @@ impl<'hir> LoweringContext<'_, 'hir> {
442442
Spanned { node: b.node, span: self.lower_span(b.span) }
443443
}
444444

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

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

+1-2
Original file line numberDiff line numberDiff line change
@@ -597,8 +597,7 @@ impl<'a> State<'a> {
597597
fixup.leftmost_subexpression(),
598598
);
599599
self.space();
600-
self.word(op.node.as_str());
601-
self.word_space("=");
600+
self.word_space(op.node.as_str());
602601
self.print_expr_cond_paren(
603602
rhs,
604603
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;
@@ -2598,7 +2598,7 @@ pub enum ExprKind<'hir> {
25982598
/// An assignment with an operator.
25992599
///
26002600
/// E.g., `a += 1`.
2601-
AssignOp(BinOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
2601+
AssignOp(AssignOp, &'hir Expr<'hir>, &'hir Expr<'hir>),
26022602
/// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct or tuple field.
26032603
Field(&'hir Expr<'hir>, Ident),
26042604
/// An indexing operation (`foo[2]`).

compiler/rustc_hir_pretty/src/lib.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -1592,8 +1592,7 @@ impl<'a> State<'a> {
15921592
hir::ExprKind::AssignOp(op, lhs, rhs) => {
15931593
self.print_expr_cond_paren(lhs, lhs.precedence() <= ExprPrecedence::Assign);
15941594
self.space();
1595-
self.word(op.node.as_str());
1596-
self.word_space("=");
1595+
self.word_space(op.node.as_str());
15971596
self.print_expr_cond_paren(rhs, rhs.precedence() < ExprPrecedence::Assign);
15981597
}
15991598
hir::ExprKind::Field(expr, ident) => {

compiler/rustc_hir_typeck/src/expr.rs

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

compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs

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

0 commit comments

Comments
 (0)