impl PartialOrd codegen for struct records

This commit is contained in:
Yoshua Wuyts 2021-10-12 14:24:42 +02:00
parent 6941fdc49f
commit c0263fb07a
2 changed files with 38 additions and 5 deletions

View File

@ -712,6 +712,35 @@ impl PartialOrd for Foo {
)
}
#[test]
fn add_custom_impl_partial_ord_tuple_struct() {
check_assist(
replace_derive_with_manual_impl,
r#"
//- minicore: ord
#[derive(Partial$0Ord)]
struct Foo(usize, usize, usize);
"#,
r#"
struct Foo(usize, usize, usize);
impl PartialOrd for Foo {
$0fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
match self.0.partial_cmp(other.0) {
Some(core::cmp::Ordering::Eq) => {}
ord => return ord,
}
match self.1.partial_cmp(other.1) {
Some(core::cmp::Ordering::Eq) => {}
ord => return ord,
}
self.2.partial_cmp(other.2)
}
}
"#,
)
}
#[test]
fn add_custom_impl_partial_eq_record_struct() {
check_assist(

View File

@ -594,7 +594,6 @@ fn gen_partial_ord(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
None,
make::expr_return(Some(make::expr_path(make::ext::ident_path("ord")))),
));
// let rhs = make::expr_path(make::ext::ident_path("other"));
let list = make::match_arm_list(arms).indent(ast::edit::IndentLevel(1));
Some(make::expr_stmt(make::expr_match(match_target, list)).into())
}
@ -742,17 +741,22 @@ fn gen_partial_ord(adt: &ast::Adt, func: &ast::Fn) -> Option<()> {
}
Some(ast::FieldList::TupleFieldList(field_list)) => {
let mut expr = None;
let mut exprs = vec![];
for (i, _) in field_list.fields().enumerate() {
let idx = format!("{}", i);
let lhs = make::expr_path(make::ext::ident_path("self"));
let lhs = make::expr_field(lhs, &idx);
let rhs = make::expr_path(make::ext::ident_path("other"));
let rhs = make::expr_field(rhs, &idx);
let cmp = make::expr_op(ast::BinOp::EqualityTest, lhs, rhs);
expr = gen_eq_chain(expr, cmp);
let ord = gen_partial_cmp_call(lhs, rhs);
exprs.push(ord);
}
make::block_expr(None, expr).indent(ast::edit::IndentLevel(1))
let tail = exprs.pop();
let stmts = exprs
.into_iter()
.map(gen_partial_eq_match)
.collect::<Option<Vec<ast::Stmt>>>()?;
make::block_expr(stmts.into_iter(), tail).indent(ast::edit::IndentLevel(1))
}
// No fields in the body means there's nothing to hash.