Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
use expect_test::expect;

mod logger_db;
use logger_db::LoggerDb;
use query_group_macro::query_group;

#[salsa_macros::input]
struct Input {
    str: String,
}

#[query_group]
trait PartialMigrationDatabase: salsa::Database {
    fn length_query(&self, input: Input) -> usize;

    // renamed/invoke query
    #[salsa::invoke(invoke_length_query_actual)]
    fn invoke_length_query(&self, input: Input) -> usize;

    // invoke tracked function
    #[salsa::invoke(invoke_length_tracked_actual)]
    fn invoke_length_tracked(&self, input: Input) -> usize;
}

fn length_query(db: &dyn PartialMigrationDatabase, input: Input) -> usize {
    input.str(db).len()
}

fn invoke_length_query_actual(db: &dyn PartialMigrationDatabase, input: Input) -> usize {
    input.str(db).len()
}

#[salsa_macros::tracked]
fn invoke_length_tracked_actual(db: &dyn PartialMigrationDatabase, input: Input) -> usize {
    input.str(db).len()
}

#[test]
fn unadorned_query() {
    let db = LoggerDb::default();

    let input = Input::new(&db, String::from("Hello, world!"));
    let len = db.length_query(input);

    assert_eq!(len, 13);
    db.assert_logs(expect![[r#"
        [
            "salsa_event(WillCheckCancellation)",
            "salsa_event(WillExecute { database_key: length_query_shim(Id(0)) })",
        ]"#]]);
}

#[test]
fn invoke_query() {
    let db = LoggerDb::default();

    let input = Input::new(&db, String::from("Hello, world!"));
    let len = db.invoke_length_query(input);

    assert_eq!(len, 13);
    db.assert_logs(expect![[r#"
        [
            "salsa_event(WillCheckCancellation)",
            "salsa_event(WillExecute { database_key: invoke_length_query_shim(Id(0)) })",
        ]"#]]);
}

// todo: does this even make sense?
#[test]
fn invoke_tracked_query() {
    let db = LoggerDb::default();

    let input = Input::new(&db, String::from("Hello, world!"));
    let len = db.invoke_length_tracked(input);

    assert_eq!(len, 13);
    db.assert_logs(expect![[r#"
        [
            "salsa_event(WillCheckCancellation)",
            "salsa_event(WillExecute { database_key: invoke_length_tracked_shim(Id(0)) })",
            "salsa_event(WillCheckCancellation)",
            "salsa_event(WillExecute { database_key: invoke_length_tracked_actual(Id(0)) })",
        ]"#]]);
}

#[test]
fn new_salsa_baseline() {
    let db = LoggerDb::default();

    #[salsa_macros::input]
    struct Input {
        str: String,
    }

    #[salsa_macros::tracked]
    fn new_salsa_length_query(db: &dyn PartialMigrationDatabase, input: Input) -> usize {
        input.str(db).len()
    }

    let input = Input::new(&db, String::from("Hello, world!"));
    let len = new_salsa_length_query(&db, input);

    assert_eq!(len, 13);
    db.assert_logs(expect![[r#"
        [
            "salsa_event(WillCheckCancellation)",
            "salsa_event(WillExecute { database_key: new_salsa_length_query(Id(0)) })",
        ]"#]]);
}
='#n241'>241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
use hir::{PathResolution, Semantics};
use ide_db::{FxHashMap, RootDatabase};
use itertools::Itertools;
use syntax::{
    ast::{self, HasName},
    ted, AstNode,
};

use crate::{AssistContext, AssistId, AssistKind, Assists};

// Assist: reorder_impl_items
//
// Reorder the items of an `impl Trait`. The items will be ordered
// in the same order as in the trait definition.
//
// ```
// trait Foo {
//     type A;
//     const B: u8;
//     fn c();
// }
//
// struct Bar;
// $0impl Foo for Bar$0 {
//     const B: u8 = 17;
//     fn c() {}
//     type A = String;
// }
// ```
// ->
// ```
// trait Foo {
//     type A;
//     const B: u8;
//     fn c();
// }
//
// struct Bar;
// impl Foo for Bar {
//     type A = String;
//     const B: u8 = 17;
//     fn c() {}
// }
// ```
pub(crate) fn reorder_impl_items(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
    let impl_ast = ctx.find_node_at_offset::<ast::Impl>()?;
    let items = impl_ast.assoc_item_list()?;

    // restrict the range
    // if cursor is in assoc_items, abort
    let assoc_range = items.syntax().text_range();
    let cursor_position = ctx.offset();
    if assoc_range.contains_inclusive(cursor_position) {
        cov_mark::hit!(not_applicable_editing_assoc_items);
        return None;
    }

    let assoc_items = items.assoc_items().collect::<Vec<_>>();

    let path = impl_ast
        .trait_()
        .and_then(|t| match t {
            ast::Type::PathType(path) => Some(path),
            _ => None,
        })?
        .path()?;

    let ranks = compute_item_ranks(&path, ctx)?;
    let sorted: Vec<_> = assoc_items
        .iter()
        .cloned()
        .sorted_by_key(|i| {
            let name = match i {
                ast::AssocItem::Const(c) => c.name(),
                ast::AssocItem::Fn(f) => f.name(),
                ast::AssocItem::TypeAlias(t) => t.name(),
                ast::AssocItem::MacroCall(_) => None,
            };

            name.and_then(|n| ranks.get(&n.to_string()).copied()).unwrap_or(usize::max_value())
        })
        .collect();

    // Don't edit already sorted methods:
    if assoc_items == sorted {
        cov_mark::hit!(not_applicable_if_sorted);
        return None;
    }

    let target = items.syntax().text_range();
    acc.add(
        AssistId("reorder_impl_items", AssistKind::RefactorRewrite),
        "Sort items by trait definition",
        target,
        |builder| {
            let assoc_items =
                assoc_items.into_iter().map(|item| builder.make_mut(item)).collect::<Vec<_>>();
            assoc_items
                .into_iter()
                .zip(sorted)
                .for_each(|(old, new)| ted::replace(old.syntax(), new.clone_for_update().syntax()));
        },
    )
}

fn compute_item_ranks(
    path: &ast::Path,
    ctx: &AssistContext<'_>,
) -> Option<FxHashMap<String, usize>> {
    let td = trait_definition(path, &ctx.sema)?;

    Some(
        td.items(ctx.db())
            .iter()
            .flat_map(|i| i.name(ctx.db()))
            .enumerate()
            .map(|(idx, name)| (name.display(ctx.db()).to_string(), idx))
            .collect(),
    )
}

fn trait_definition(path: &ast::Path, sema: &Semantics<'_, RootDatabase>) -> Option<hir::Trait> {
    match sema.resolve_path(path)? {
        PathResolution::Def(hir::ModuleDef::Trait(trait_)) => Some(trait_),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use crate::tests::{check_assist, check_assist_not_applicable};

    use super::*;

    #[test]
    fn not_applicable_if_sorted() {
        cov_mark::check!(not_applicable_if_sorted);
        check_assist_not_applicable(
            reorder_impl_items,
            r#"
trait Bar {
    type T;
    const C: ();
    fn a() {}
    fn z() {}
    fn b() {}
}
struct Foo;
$0impl Bar for Foo {
    type T = ();
    const C: () = ();
    fn a() {}
    fn z() {}
    fn b() {}
}
        "#,
        )
    }

    #[test]
    fn reorder_impl_trait_functions() {
        check_assist(
            reorder_impl_items,
            r#"
trait Bar {
    fn a() {}
    fn c() {}
    fn b() {}
    fn d() {}
}

struct Foo;
$0impl Bar for Foo {
    fn d() {}
    fn b() {}
    fn c() {}
    fn a() {}
}
"#,
            r#"
trait Bar {
    fn a() {}
    fn c() {}
    fn b() {}
    fn d() {}
}

struct Foo;
impl Bar for Foo {
    fn a() {}
    fn c() {}
    fn b() {}
    fn d() {}
}
"#,
        )
    }

    #[test]
    fn not_applicable_if_empty() {
        check_assist_not_applicable(
            reorder_impl_items,
            r#"
trait Bar {};
struct Foo;
$0impl Bar for Foo {}
        "#,
        )
    }

    #[test]
    fn reorder_impl_trait_items() {
        check_assist(
            reorder_impl_items,
            r#"
trait Bar {
    fn a() {}
    type T0;
    fn c() {}
    const C1: ();
    fn b() {}
    type T1;
    fn d() {}
    const C0: ();
}

struct Foo;
$0impl Bar for Foo {
    type T1 = ();
    fn d() {}
    fn b() {}
    fn c() {}
    const C1: () = ();
    fn a() {}
    type T0 = ();
    const C0: () = ();
}
        "#,
            r#"
trait Bar {
    fn a() {}
    type T0;
    fn c() {}
    const C1: ();
    fn b() {}
    type T1;
    fn d() {}
    const C0: ();
}

struct Foo;
impl Bar for Foo {
    fn a() {}
    type T0 = ();
    fn c() {}
    const C1: () = ();
    fn b() {}
    type T1 = ();
    fn d() {}
    const C0: () = ();
}
        "#,
        )
    }

    #[test]
    fn reorder_impl_trait_items_uneven_ident_lengths() {
        check_assist(
            reorder_impl_items,
            r#"
trait Bar {
    type Foo;
    type Fooo;
}

struct Foo;
$0impl Bar for Foo {
    type Fooo = ();
    type Foo = ();
}"#,
            r#"
trait Bar {
    type Foo;
    type Fooo;
}

struct Foo;
impl Bar for Foo {
    type Foo = ();
    type Fooo = ();
}"#,
        )
    }

    #[test]
    fn not_applicable_editing_assoc_items() {
        cov_mark::check!(not_applicable_editing_assoc_items);
        check_assist_not_applicable(
            reorder_impl_items,
            r#"
trait Bar {
    type T;
    const C: ();
    fn a() {}
    fn z() {}
    fn b() {}
}
struct Foo;
impl Bar for Foo {
    type T = ();$0
    const C: () = ();
    fn z() {}
    fn a() {}
    fn b() {}
}
        "#,
        )
    }
}