rust/crates/ide-assists/src/handlers/reorder_fields.rs

210 lines
5.1 KiB
Rust
Raw Normal View History

use either::Either;
use ide_db::FxHashMap;
use itertools::Itertools;
use syntax::{ast, ted, AstNode};
2020-06-28 17:36:05 -05:00
use crate::{AssistContext, AssistId, AssistKind, Assists};
2020-04-09 17:35:43 -05:00
2020-04-11 12:39:10 -05:00
// Assist: reorder_fields
//
// Reorder the fields of record literals and record patterns in the same order as in
// the definition.
//
// ```
// struct Foo {foo: i32, bar: i32};
2021-01-06 14:15:48 -06:00
// const test: Foo = $0Foo {bar: 0, foo: 1}
2020-04-11 12:39:10 -05:00
// ```
// ->
// ```
// struct Foo {foo: i32, bar: i32};
2020-04-11 13:32:48 -05:00
// const test: Foo = Foo {foo: 1, bar: 0}
2020-04-11 12:39:10 -05:00
// ```
2022-07-20 08:02:08 -05:00
pub(crate) fn reorder_fields(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
2023-01-14 09:20:32 -06:00
let record = ctx.find_node_at_offset::<Either<ast::RecordExpr, ast::RecordPat>>()?;
2020-04-09 17:35:43 -05:00
let path = record.as_ref().either(|it| it.path(), |it| it.path())?;
2021-06-12 22:54:16 -05:00
let ranks = compute_fields_ranks(&path, ctx)?;
let get_rank_of_field =
|of: Option<_>| *ranks.get(&of.unwrap_or_default()).unwrap_or(&usize::MAX);
2020-04-09 17:35:43 -05:00
let field_list = match &record {
Either::Left(it) => Either::Left(it.record_expr_field_list()?),
Either::Right(it) => Either::Right(it.record_pat_field_list()?),
2021-03-23 11:59:33 -05:00
};
let fields = match field_list {
Either::Left(it) => Either::Left((
it.fields()
.sorted_unstable_by_key(|field| {
get_rank_of_field(field.field_name().map(|it| it.to_string()))
})
.collect::<Vec<_>>(),
it,
)),
Either::Right(it) => Either::Right((
it.fields()
.sorted_unstable_by_key(|field| {
get_rank_of_field(field.field_name().map(|it| it.to_string()))
})
.collect::<Vec<_>>(),
it,
)),
2021-03-23 11:59:33 -05:00
};
2020-04-09 17:35:43 -05:00
let is_sorted = fields.as_ref().either(
|(sorted, field_list)| field_list.fields().zip(sorted).all(|(a, b)| a == *b),
|(sorted, field_list)| field_list.fields().zip(sorted).all(|(a, b)| a == *b),
);
if is_sorted {
2021-03-08 14:19:44 -06:00
cov_mark::hit!(reorder_sorted_fields);
2020-04-09 17:35:43 -05:00
return None;
}
let target = record.as_ref().either(AstNode::syntax, AstNode::syntax).text_range();
2020-06-28 17:36:05 -05:00
acc.add(
2020-07-02 16:48:35 -05:00
AssistId("reorder_fields", AssistKind::RefactorRewrite),
2020-06-28 17:36:05 -05:00
"Reorder record fields",
target,
|builder| match fields {
Either::Left((sorted, field_list)) => {
2021-05-16 06:18:49 -05:00
replace(builder.make_mut(field_list).fields(), sorted)
}
Either::Right((sorted, field_list)) => {
2021-05-16 06:18:49 -05:00
replace(builder.make_mut(field_list).fields(), sorted)
2020-06-28 17:36:05 -05:00
}
},
)
2020-04-09 17:35:43 -05:00
}
fn replace<T: AstNode + PartialEq>(
fields: impl Iterator<Item = T>,
sorted_fields: impl IntoIterator<Item = T>,
) {
fields.zip(sorted_fields).for_each(|(field, sorted_field)| {
ted::replace(field.syntax(), sorted_field.syntax().clone_for_update())
});
}
2022-07-20 08:06:15 -05:00
fn compute_fields_ranks(
path: &ast::Path,
ctx: &AssistContext<'_>,
) -> Option<FxHashMap<String, usize>> {
2021-03-23 11:59:33 -05:00
let strukt = match ctx.sema.resolve_path(path) {
Some(hir::PathResolution::Def(hir::ModuleDef::Adt(hir::Adt::Struct(it)))) => it,
_ => return None,
};
2020-04-09 17:35:43 -05:00
2021-03-23 11:59:33 -05:00
let res = strukt
.fields(ctx.db())
.into_iter()
2021-03-23 11:59:33 -05:00
.enumerate()
.map(|(idx, field)| (field.name(ctx.db()).to_string(), idx))
.collect();
2020-04-09 17:35:43 -05:00
2021-03-23 11:59:33 -05:00
Some(res)
2020-04-09 17:35:43 -05:00
}
#[cfg(test)]
mod tests {
2020-05-06 03:16:55 -05:00
use crate::tests::{check_assist, check_assist_not_applicable};
2020-04-09 17:35:43 -05:00
use super::*;
#[test]
2020-12-15 02:51:40 -06:00
fn reorder_sorted_fields() {
2021-03-08 14:19:44 -06:00
cov_mark::check!(reorder_sorted_fields);
2020-04-09 17:35:43 -05:00
check_assist_not_applicable(
reorder_fields,
r#"
2021-03-23 11:59:33 -05:00
struct Foo { foo: i32, bar: i32 }
2021-01-06 14:15:48 -06:00
const test: Foo = $0Foo { foo: 0, bar: 0 };
2020-12-15 02:51:40 -06:00
"#,
2020-04-09 17:35:43 -05:00
)
}
#[test]
fn trivial_empty_fields() {
check_assist_not_applicable(
reorder_fields,
r#"
2021-03-23 11:59:33 -05:00
struct Foo {}
const test: Foo = $0Foo {};
2020-12-15 02:51:40 -06:00
"#,
2020-04-09 17:35:43 -05:00
)
}
#[test]
fn reorder_struct_fields() {
check_assist(
reorder_fields,
r#"
2021-03-23 11:59:33 -05:00
struct Foo { foo: i32, bar: i32 }
const test: Foo = $0Foo { bar: 0, foo: 1 };
2020-12-15 02:51:40 -06:00
"#,
2020-04-09 17:35:43 -05:00
r#"
2021-03-23 11:59:33 -05:00
struct Foo { foo: i32, bar: i32 }
const test: Foo = Foo { foo: 1, bar: 0 };
2020-12-15 02:51:40 -06:00
"#,
2020-04-09 17:35:43 -05:00
)
}
#[test]
fn reorder_struct_pattern() {
check_assist(
reorder_fields,
r#"
2020-12-15 02:51:40 -06:00
struct Foo { foo: i64, bar: i64, baz: i64 }
2020-04-09 17:35:43 -05:00
2020-12-15 02:51:40 -06:00
fn f(f: Foo) -> {
match f {
2021-01-06 14:15:48 -06:00
$0Foo { baz: 0, ref mut bar, .. } => (),
2020-12-15 02:51:40 -06:00
_ => ()
}
}
"#,
2020-04-09 17:35:43 -05:00
r#"
2020-12-15 02:51:40 -06:00
struct Foo { foo: i64, bar: i64, baz: i64 }
2020-04-09 17:35:43 -05:00
2020-12-15 02:51:40 -06:00
fn f(f: Foo) -> {
match f {
Foo { ref mut bar, baz: 0, .. } => (),
_ => ()
}
}
"#,
2020-04-09 17:35:43 -05:00
)
}
#[test]
fn reorder_with_extra_field() {
check_assist(
reorder_fields,
r#"
2021-03-23 11:59:33 -05:00
struct Foo { foo: String, bar: String }
2020-04-09 17:35:43 -05:00
2020-12-15 02:51:40 -06:00
impl Foo {
fn new() -> Foo {
let foo = String::new();
2021-01-06 14:15:48 -06:00
$0Foo {
2020-12-15 02:51:40 -06:00
bar: foo.clone(),
extra: "Extra field",
foo,
}
}
}
"#,
2020-04-09 17:35:43 -05:00
r#"
2021-03-23 11:59:33 -05:00
struct Foo { foo: String, bar: String }
2020-04-09 17:35:43 -05:00
2020-12-15 02:51:40 -06:00
impl Foo {
fn new() -> Foo {
let foo = String::new();
Foo {
foo,
bar: foo.clone(),
extra: "Extra field",
}
}
}
"#,
2020-04-09 17:35:43 -05:00
)
}
}