Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit 2ff505a

Browse files
committed
Auto merge of rust-lang#12428 - lowr:experimental/destructuring-assignment, r=flodiebold
feat: implement destructuring assignment This is an attempt to implement destructuring assignments, or more specifically, type inference for [assignee expressions](https://doc.rust-lang.org/reference/expressions.html#place-expressions-and-value-expressions). I'm not sure if this is the right approach, so I don't even expect this to be merged (hence the branch name 😉) but rather want to propose one direction we could choose. I don't mind getting merged if this is good enough though! Some notes on the implementation choices: - Assignee expressions are **not** desugared on HIR level unlike rustc, but are inferred directly along with other expressions. This matches the processing of other syntaxes that are desugared in rustc but not in r-a. I find this reasonable because r-a only needs to infer types and it's easier to relate AST nodes and HIR nodes, so I followed it. - Assignee expressions obviously resemble patterns, so type inference for each kind of pattern and its corresponding assignee expressions share a significant amount of logic. I tried to reuse the type inference functions for patterns by introducing `PatLike` trait which generalizes assignee expressions and patterns. - This is not the most elegant solution I suspect (and I really don't like the name of the trait!), but it's cleaner and the change is smaller than other ways I experimented, like making the functions generic without such trait, or making them take `Either<ExprId, PatId>` in place of `PatId`. in case this is merged: Closes rust-lang#11532 Closes rust-lang#11839 Closes rust-lang#12322
2 parents b0102bd + b7a4175 commit 2ff505a

File tree

7 files changed

+532
-68
lines changed

7 files changed

+532
-68
lines changed

crates/hir-def/src/body/lower.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -536,7 +536,7 @@ impl ExprCollector<'_> {
536536

537537
self.alloc_expr(Expr::MacroStmts { tail }, syntax_ptr)
538538
}
539-
ast::Expr::UnderscoreExpr(_) => return None,
539+
ast::Expr::UnderscoreExpr(_) => self.alloc_expr(Expr::Underscore, syntax_ptr),
540540
})
541541
}
542542

crates/hir-def/src/expr.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,7 @@ pub enum Expr {
203203
},
204204
Array(Array),
205205
Literal(Literal),
206+
Underscore,
206207
}
207208

208209
#[derive(Debug, Clone, Eq, PartialEq)]
@@ -345,6 +346,7 @@ impl Expr {
345346
},
346347
Expr::MacroStmts { tail } => f(*tail),
347348
Expr::Literal(_) => {}
349+
Expr::Underscore => {}
348350
}
349351
}
350352
}

crates/hir-ty/src/infer.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,39 @@ impl Default for BindingMode {
125125
}
126126
}
127127

128+
/// Used to generalize patterns and assignee expressions.
129+
trait PatLike: Into<ExprOrPatId> + Copy {
130+
type BindingMode: Copy;
131+
132+
fn infer(
133+
this: &mut InferenceContext,
134+
id: Self,
135+
expected_ty: &Ty,
136+
default_bm: Self::BindingMode,
137+
) -> Ty;
138+
}
139+
140+
impl PatLike for ExprId {
141+
type BindingMode = ();
142+
143+
fn infer(this: &mut InferenceContext, id: Self, expected_ty: &Ty, _: Self::BindingMode) -> Ty {
144+
this.infer_assignee_expr(id, expected_ty)
145+
}
146+
}
147+
148+
impl PatLike for PatId {
149+
type BindingMode = BindingMode;
150+
151+
fn infer(
152+
this: &mut InferenceContext,
153+
id: Self,
154+
expected_ty: &Ty,
155+
default_bm: Self::BindingMode,
156+
) -> Ty {
157+
this.infer_pat(id, expected_ty, default_bm)
158+
}
159+
}
160+
128161
#[derive(Debug)]
129162
pub(crate) struct InferOk<T> {
130163
value: T,

crates/hir-ty/src/infer/expr.rs

Lines changed: 97 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -593,8 +593,8 @@ impl<'a> InferenceContext<'a> {
593593
}
594594
Expr::BinaryOp { lhs, rhs, op } => match op {
595595
Some(BinaryOp::Assignment { op: None }) => {
596-
let lhs_ty = self.infer_expr(*lhs, &Expectation::none());
597-
self.infer_expr_coerce(*rhs, &Expectation::has_type(lhs_ty));
596+
let rhs_ty = self.infer_expr(*rhs, &Expectation::none());
597+
self.infer_assignee_expr(*lhs, &rhs_ty);
598598
self.result.standard_types.unit.clone()
599599
}
600600
Some(BinaryOp::LogicOp(_)) => {
@@ -775,6 +775,12 @@ impl<'a> InferenceContext<'a> {
775775
},
776776
},
777777
Expr::MacroStmts { tail } => self.infer_expr_inner(*tail, expected),
778+
Expr::Underscore => {
779+
// Underscore expressions may only appear in assignee expressions,
780+
// which are handled by `infer_assignee_expr()`, so any underscore
781+
// expression reaching this branch is an error.
782+
self.err_ty()
783+
}
778784
};
779785
// use a new type variable if we got unknown here
780786
let ty = self.insert_type_vars_shallow(ty);
@@ -811,6 +817,95 @@ impl<'a> InferenceContext<'a> {
811817
}
812818
}
813819

820+
pub(super) fn infer_assignee_expr(&mut self, lhs: ExprId, rhs_ty: &Ty) -> Ty {
821+
let is_rest_expr = |expr| {
822+
matches!(
823+
&self.body[expr],
824+
Expr::Range { lhs: None, rhs: None, range_type: RangeOp::Exclusive },
825+
)
826+
};
827+
828+
let rhs_ty = self.resolve_ty_shallow(rhs_ty);
829+
830+
let ty = match &self.body[lhs] {
831+
Expr::Tuple { exprs } => {
832+
// We don't consider multiple ellipses. This is analogous to
833+
// `hir_def::body::lower::ExprCollector::collect_tuple_pat()`.
834+
let ellipsis = exprs.iter().position(|e| is_rest_expr(*e));
835+
let exprs: Vec<_> = exprs.iter().filter(|e| !is_rest_expr(**e)).copied().collect();
836+
837+
self.infer_tuple_pat_like(&rhs_ty, (), ellipsis, &exprs)
838+
}
839+
Expr::Call { callee, args } => {
840+
// Tuple structs
841+
let path = match &self.body[*callee] {
842+
Expr::Path(path) => Some(path),
843+
_ => None,
844+
};
845+
846+
// We don't consider multiple ellipses. This is analogous to
847+
// `hir_def::body::lower::ExprCollector::collect_tuple_pat()`.
848+
let ellipsis = args.iter().position(|e| is_rest_expr(*e));
849+
let args: Vec<_> = args.iter().filter(|e| !is_rest_expr(**e)).copied().collect();
850+
851+
self.infer_tuple_struct_pat_like(path, &rhs_ty, (), lhs, ellipsis, &args)
852+
}
853+
Expr::Array(Array::ElementList(elements)) => {
854+
let elem_ty = match rhs_ty.kind(Interner) {
855+
TyKind::Array(st, _) => st.clone(),
856+
_ => self.err_ty(),
857+
};
858+
859+
// There's no need to handle `..` as it cannot be bound.
860+
let sub_exprs = elements.iter().filter(|e| !is_rest_expr(**e));
861+
862+
for e in sub_exprs {
863+
self.infer_assignee_expr(*e, &elem_ty);
864+
}
865+
866+
match rhs_ty.kind(Interner) {
867+
TyKind::Array(_, _) => rhs_ty.clone(),
868+
// Even when `rhs_ty` is not an array type, this assignee
869+
// expression is infered to be an array (of unknown element
870+
// type and length). This should not be just an error type,
871+
// because we are to compute the unifiability of this type and
872+
// `rhs_ty` in the end of this function to issue type mismatches.
873+
_ => TyKind::Array(self.err_ty(), crate::consteval::usize_const(None))
874+
.intern(Interner),
875+
}
876+
}
877+
Expr::RecordLit { path, fields, .. } => {
878+
let subs = fields.iter().map(|f| (f.name.clone(), f.expr));
879+
880+
self.infer_record_pat_like(path.as_deref(), &rhs_ty, (), lhs.into(), subs)
881+
}
882+
Expr::Underscore => rhs_ty.clone(),
883+
_ => {
884+
// `lhs` is a place expression, a unit struct, or an enum variant.
885+
let lhs_ty = self.infer_expr(lhs, &Expectation::none());
886+
887+
// This is the only branch where this function may coerce any type.
888+
// We are returning early to avoid the unifiability check below.
889+
let lhs_ty = self.insert_type_vars_shallow(lhs_ty);
890+
let ty = match self.coerce(None, &rhs_ty, &lhs_ty) {
891+
Ok(ty) => ty,
892+
Err(_) => self.err_ty(),
893+
};
894+
self.write_expr_ty(lhs, ty.clone());
895+
return ty;
896+
}
897+
};
898+
899+
let ty = self.insert_type_vars_shallow(ty);
900+
if !self.unify(&ty, &rhs_ty) {
901+
self.result
902+
.type_mismatches
903+
.insert(lhs.into(), TypeMismatch { expected: rhs_ty.clone(), actual: ty.clone() });
904+
}
905+
self.write_expr_ty(lhs, ty.clone());
906+
ty
907+
}
908+
814909
fn infer_overloadable_binop(
815910
&mut self,
816911
lhs: ExprId,

0 commit comments

Comments
 (0)