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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
|
use ra_ide_db::defs::{classify_name_ref, Definition, NameRefClass};
use ra_syntax::{ast, AstNode, SyntaxKind, T};
use test_utils::mark;
use crate::{
assist_context::{AssistContext, Assists},
AssistId, AssistKind,
};
// Assist: add_turbo_fish
//
// Adds `::<_>` to a call of a generic method or function.
//
// ```
// fn make<T>() -> T { todo!() }
// fn main() {
// let x = make<|>();
// }
// ```
// ->
// ```
// fn make<T>() -> T { todo!() }
// fn main() {
// let x = make::<${0:_}>();
// }
// ```
pub(crate) fn add_turbo_fish(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
let ident = ctx.find_token_at_offset(SyntaxKind::IDENT)?;
let next_token = ident.next_token()?;
if next_token.kind() == T![::] {
mark::hit!(add_turbo_fish_one_fish_is_enough);
return None;
}
let name_ref = ast::NameRef::cast(ident.parent())?;
let def = match classify_name_ref(&ctx.sema, &name_ref)? {
NameRefClass::Definition(def) => def,
NameRefClass::FieldShorthand { .. } => return None,
};
let fun = match def {
Definition::ModuleDef(hir::ModuleDef::Function(it)) => it,
_ => return None,
};
let generics = hir::GenericDef::Function(fun).params(ctx.sema.db);
if generics.is_empty() {
mark::hit!(add_turbo_fish_non_generic);
return None;
}
acc.add(
AssistId("add_turbo_fish", AssistKind::RefactorRewrite),
"Add `::<>`",
ident.text_range(),
|builder| match ctx.config.snippet_cap {
Some(cap) => builder.insert_snippet(cap, ident.text_range().end(), "::<${0:_}>"),
None => builder.insert(ident.text_range().end(), "::<_>"),
},
)
}
#[cfg(test)]
mod tests {
use crate::tests::{check_assist, check_assist_not_applicable};
use super::*;
use test_utils::mark;
#[test]
fn add_turbo_fish_function() {
check_assist(
add_turbo_fish,
r#"
fn make<T>() -> T {}
fn main() {
make<|>();
}
"#,
r#"
fn make<T>() -> T {}
fn main() {
make::<${0:_}>();
}
"#,
);
}
#[test]
fn add_turbo_fish_method() {
check_assist(
add_turbo_fish,
r#"
struct S;
impl S {
fn make<T>(&self) -> T {}
}
fn main() {
S.make<|>();
}
"#,
r#"
struct S;
impl S {
fn make<T>(&self) -> T {}
}
fn main() {
S.make::<${0:_}>();
}
"#,
);
}
#[test]
fn add_turbo_fish_one_fish_is_enough() {
mark::check!(add_turbo_fish_one_fish_is_enough);
check_assist_not_applicable(
add_turbo_fish,
r#"
fn make<T>() -> T {}
fn main() {
make<|>::<()>();
}
"#,
);
}
#[test]
fn add_turbo_fish_non_generic() {
mark::check!(add_turbo_fish_non_generic);
check_assist_not_applicable(
add_turbo_fish,
r#"
fn make() -> () {}
fn main() {
make<|>();
}
"#,
);
}
}
|