1
+ use ide_db:: imports:: insert_use:: ImportScope ;
1
2
use syntax:: {
2
3
ast:: { self , make, AstNode , HasArgList } ,
3
4
TextRange ,
@@ -17,6 +18,8 @@ use crate::{AssistContext, AssistId, AssistKind, Assists};
17
18
// ```
18
19
// ->
19
20
// ```
21
+ // use std::ops::Add;
22
+ //
20
23
// fn main() {
21
24
// 1.add(2);
22
25
// }
@@ -76,10 +79,49 @@ pub(crate) fn unqualify_method_call(acc: &mut Assists, ctx: &AssistContext<'_>)
76
79
edit. insert ( close, ")" ) ;
77
80
}
78
81
edit. replace ( replace_comma, format ! ( ".{method_name}(" ) ) ;
82
+ add_import ( & path, ctx, edit) ;
79
83
} ,
80
84
)
81
85
}
82
86
87
+ fn add_import (
88
+ path : & ast:: Path ,
89
+ ctx : & AssistContext < ' _ > ,
90
+ edit : & mut ide_db:: source_change:: SourceChangeBuilder ,
91
+ ) {
92
+ let qualifier = path. qualifier ( ) . unwrap ( ) ;
93
+
94
+ // for `<i32 as std::ops::Add>`
95
+ let path_type =
96
+ qualifier. segment ( ) . unwrap ( ) . syntax ( ) . children ( ) . filter_map ( ast:: PathType :: cast) . last ( ) ;
97
+ let import = match path_type {
98
+ Some ( it) => it. path ( ) . unwrap ( ) ,
99
+ None => qualifier,
100
+ } ;
101
+
102
+ // in case for `<_>`
103
+ match import. coloncolon_token ( ) {
104
+ Some ( _) => ( ) ,
105
+ None => {
106
+ return ;
107
+ }
108
+ }
109
+
110
+ let scope = ide_db:: imports:: insert_use:: ImportScope :: find_insert_use_container (
111
+ path. syntax ( ) ,
112
+ & ctx. sema ,
113
+ ) ;
114
+
115
+ if let Some ( scope) = scope {
116
+ let scope = match scope {
117
+ ImportScope :: File ( it) => ImportScope :: File ( edit. make_mut ( it) ) ,
118
+ ImportScope :: Module ( it) => ImportScope :: Module ( edit. make_mut ( it) ) ,
119
+ ImportScope :: Block ( it) => ImportScope :: Block ( edit. make_mut ( it) ) ,
120
+ } ;
121
+ ide_db:: imports:: insert_use:: insert_use ( & scope, import, & ctx. config . insert_use ) ;
122
+ }
123
+ }
124
+
83
125
fn needs_parens_as_receiver ( expr : & ast:: Expr ) -> bool {
84
126
// Make `(expr).dummy()`
85
127
let dummy_call = make:: expr_method_call (
@@ -127,6 +169,8 @@ fn f() { S.f(S); }"#,
127
169
//- minicore: add
128
170
fn f() { <u32 as core::ops::Add>::$0add(2, 2); }"# ,
129
171
r#"
172
+ use core::ops::Add;
173
+
130
174
fn f() { 2.add(2); }"# ,
131
175
) ;
132
176
@@ -136,6 +180,8 @@ fn f() { 2.add(2); }"#,
136
180
//- minicore: add
137
181
fn f() { core::ops::Add::$0add(2, 2); }"# ,
138
182
r#"
183
+ use core::ops::Add;
184
+
139
185
fn f() { 2.add(2); }"# ,
140
186
) ;
141
187
@@ -179,6 +225,8 @@ impl core::ops::Deref for S {
179
225
}
180
226
fn f() { core::ops::Deref::$0deref(&S); }"# ,
181
227
r#"
228
+ use core::ops::Deref;
229
+
182
230
struct S;
183
231
impl core::ops::Deref for S {
184
232
type Target = S;
0 commit comments