Skip to content

Commit 2e8b977

Browse files
committed
Auto merge of #17516 - kilpkonn:master, r=kilpkonn
Quality of life improvements to term search Basically two things: - Allow optionally disabling "borrow checking" restrictions on term search code assists. Sometimes it is better to get invalid suggestions and fix borrow checking issues later... - Remove explicit generics in generated expressions. I find it quite rare that one writes `None::<T>` instead of `None`.
2 parents ba01c0a + 585e4d6 commit 2e8b977

File tree

12 files changed

+51
-77
lines changed

12 files changed

+51
-77
lines changed

src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs

Lines changed: 8 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ use hir_ty::{
99
use itertools::Itertools;
1010

1111
use crate::{
12-
Adt, AsAssocItem, AssocItemContainer, Const, ConstParam, Field, Function, GenericDef, Local,
13-
ModuleDef, SemanticsScope, Static, Struct, StructKind, Trait, Type, Variant,
12+
Adt, AsAssocItem, AssocItemContainer, Const, ConstParam, Field, Function, Local, ModuleDef,
13+
SemanticsScope, Static, Struct, StructKind, Trait, Type, Variant,
1414
};
1515

1616
/// Helper function to get path to `ModuleDef`
@@ -35,43 +35,6 @@ fn mod_item_path_str(
3535
.ok_or(DisplaySourceCodeError::PathNotFound)
3636
}
3737

38-
/// Helper function to get path to `Type`
39-
fn type_path(
40-
sema_scope: &SemanticsScope<'_>,
41-
ty: &Type,
42-
cfg: ImportPathConfig,
43-
) -> Result<String, DisplaySourceCodeError> {
44-
let db = sema_scope.db;
45-
let m = sema_scope.module();
46-
47-
match ty.as_adt() {
48-
Some(adt) => {
49-
let ty_name = ty.display_source_code(db, m.id, true)?;
50-
51-
let mut path = mod_item_path(sema_scope, &ModuleDef::Adt(adt), cfg).unwrap();
52-
path.pop_segment();
53-
let path = path.display(db.upcast()).to_string();
54-
let res = match path.is_empty() {
55-
true => ty_name,
56-
false => format!("{path}::{ty_name}"),
57-
};
58-
Ok(res)
59-
}
60-
None => ty.display_source_code(db, m.id, true),
61-
}
62-
}
63-
64-
/// Helper function to filter out generic parameters that are default
65-
fn non_default_generics(db: &dyn HirDatabase, def: GenericDef, generics: &[Type]) -> Vec<Type> {
66-
def.type_or_const_params(db)
67-
.into_iter()
68-
.filter_map(|it| it.as_type_param(db))
69-
.zip(generics)
70-
.filter(|(tp, arg)| tp.default(db).as_ref() != Some(arg))
71-
.map(|(_, arg)| arg.clone())
72-
.collect()
73-
}
74-
7538
/// Type tree shows how can we get from set of types to some type.
7639
///
7740
/// Consider the following code as an example
@@ -208,20 +171,7 @@ impl Expr {
208171
None => Ok(format!("{target_str}.{func_name}({args})")),
209172
}
210173
}
211-
Expr::Variant { variant, generics, params } => {
212-
let generics = non_default_generics(db, variant.parent_enum(db).into(), generics);
213-
let generics_str = match generics.is_empty() {
214-
true => String::new(),
215-
false => {
216-
let generics = generics
217-
.iter()
218-
.map(|it| type_path(sema_scope, it, cfg))
219-
.collect::<Result<Vec<String>, DisplaySourceCodeError>>()?
220-
.into_iter()
221-
.join(", ");
222-
format!("::<{generics}>")
223-
}
224-
};
174+
Expr::Variant { variant, params, .. } => {
225175
let inner = match variant.kind(db) {
226176
StructKind::Tuple => {
227177
let args = params
@@ -230,7 +180,7 @@ impl Expr {
230180
.collect::<Result<Vec<String>, DisplaySourceCodeError>>()?
231181
.into_iter()
232182
.join(", ");
233-
format!("{generics_str}({args})")
183+
format!("({args})")
234184
}
235185
StructKind::Record => {
236186
let fields = variant.fields(db);
@@ -248,16 +198,15 @@ impl Expr {
248198
.collect::<Result<Vec<String>, DisplaySourceCodeError>>()?
249199
.into_iter()
250200
.join(", ");
251-
format!("{generics_str}{{ {args} }}")
201+
format!("{{ {args} }}")
252202
}
253-
StructKind::Unit => generics_str,
203+
StructKind::Unit => String::new(),
254204
};
255205

256206
let prefix = mod_item_path_str(sema_scope, &ModuleDef::Variant(*variant))?;
257207
Ok(format!("{prefix}{inner}"))
258208
}
259-
Expr::Struct { strukt, generics, params } => {
260-
let generics = non_default_generics(db, (*strukt).into(), generics);
209+
Expr::Struct { strukt, params, .. } => {
261210
let inner = match strukt.kind(db) {
262211
StructKind::Tuple => {
263212
let args = params
@@ -286,18 +235,7 @@ impl Expr {
286235
.join(", ");
287236
format!(" {{ {args} }}")
288237
}
289-
StructKind::Unit => match generics.is_empty() {
290-
true => String::new(),
291-
false => {
292-
let generics = generics
293-
.iter()
294-
.map(|it| type_path(sema_scope, it, cfg))
295-
.collect::<Result<Vec<String>, DisplaySourceCodeError>>()?
296-
.into_iter()
297-
.join(", ");
298-
format!("::<{generics}>")
299-
}
300-
},
238+
StructKind::Unit => String::new(),
301239
};
302240

303241
let prefix = mod_item_path_str(sema_scope, &ModuleDef::Adt(Adt::Struct(*strukt)))?;

src/tools/rust-analyzer/crates/ide-assists/src/assist_config.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,5 @@ pub struct AssistConfig {
1717
pub prefer_prelude: bool,
1818
pub assist_emit_must_use: bool,
1919
pub term_search_fuel: u64,
20+
pub term_search_borrowck: bool,
2021
}

src/tools/rust-analyzer/crates/ide-assists/src/handlers/term_search.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,11 @@ pub(crate) fn term_search(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<
3737
sema: &ctx.sema,
3838
scope: &scope,
3939
goal: target_ty,
40-
config: TermSearchConfig { fuel: ctx.config.term_search_fuel, ..Default::default() },
40+
config: TermSearchConfig {
41+
fuel: ctx.config.term_search_fuel,
42+
enable_borrowcheck: ctx.config.term_search_borrowck,
43+
..Default::default()
44+
},
4145
};
4246
let paths = hir::term_search::term_search(&term_search_ctx);
4347

@@ -144,7 +148,7 @@ fn f() { let a = A { x: 1, y: true }; let b: i32 = a.x; }"#,
144148
term_search,
145149
r#"//- minicore: todo, unimplemented, option
146150
fn f() { let a: i32 = 1; let b: Option<i32> = todo$0!(); }"#,
147-
r#"fn f() { let a: i32 = 1; let b: Option<i32> = Some::<i32>(a); }"#,
151+
r#"fn f() { let a: i32 = 1; let b: Option<i32> = Some(a); }"#,
148152
)
149153
}
150154

@@ -156,7 +160,7 @@ fn f() { let a: i32 = 1; let b: Option<i32> = todo$0!(); }"#,
156160
enum Option<T> { None, Some(T) }
157161
fn f() { let a: i32 = 1; let b: Option<i32> = todo$0!(); }"#,
158162
r#"enum Option<T> { None, Some(T) }
159-
fn f() { let a: i32 = 1; let b: Option<i32> = Option::Some::<i32>(a); }"#,
163+
fn f() { let a: i32 = 1; let b: Option<i32> = Option::Some(a); }"#,
160164
)
161165
}
162166

@@ -168,7 +172,7 @@ fn f() { let a: i32 = 1; let b: Option<i32> = Option::Some::<i32>(a); }"#,
168172
enum Option<T> { None, Some(T) }
169173
fn f() { let a: Option<i32> = Option::None; let b: Option<Option<i32>> = todo$0!(); }"#,
170174
r#"enum Option<T> { None, Some(T) }
171-
fn f() { let a: Option<i32> = Option::None; let b: Option<Option<i32>> = Option::Some::<Option<i32>>(a); }"#,
175+
fn f() { let a: Option<i32> = Option::None; let b: Option<Option<i32>> = Option::Some(a); }"#,
172176
)
173177
}
174178

@@ -180,7 +184,7 @@ fn f() { let a: Option<i32> = Option::None; let b: Option<Option<i32>> = Option:
180184
enum Foo<T = i32> { Foo(T) }
181185
fn f() { let a = 0; let b: Foo = todo$0!(); }"#,
182186
r#"enum Foo<T = i32> { Foo(T) }
183-
fn f() { let a = 0; let b: Foo = Foo::Foo::<i32>(a); }"#,
187+
fn f() { let a = 0; let b: Foo = Foo::Foo(a); }"#,
184188
);
185189

186190
check_assist(

src/tools/rust-analyzer/crates/ide-assists/src/tests.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ pub(crate) const TEST_CONFIG: AssistConfig = AssistConfig {
3232
prefer_prelude: true,
3333
assist_emit_must_use: false,
3434
term_search_fuel: 400,
35+
term_search_borrowck: true,
3536
};
3637

3738
pub(crate) const TEST_CONFIG_NO_SNIPPET_CAP: AssistConfig = AssistConfig {
@@ -48,6 +49,7 @@ pub(crate) const TEST_CONFIG_NO_SNIPPET_CAP: AssistConfig = AssistConfig {
4849
prefer_prelude: true,
4950
assist_emit_must_use: false,
5051
term_search_fuel: 400,
52+
term_search_borrowck: true,
5153
};
5254

5355
pub(crate) const TEST_CONFIG_IMPORT_ONE: AssistConfig = AssistConfig {
@@ -64,6 +66,7 @@ pub(crate) const TEST_CONFIG_IMPORT_ONE: AssistConfig = AssistConfig {
6466
prefer_prelude: true,
6567
assist_emit_must_use: false,
6668
term_search_fuel: 400,
69+
term_search_borrowck: true,
6770
};
6871

6972
pub(crate) fn with_single_file(text: &str) -> (RootDatabase, FileId) {

src/tools/rust-analyzer/crates/ide-completion/src/render.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2641,7 +2641,7 @@ fn foo() {
26412641
expect![[r#"
26422642
lc foo [type+local]
26432643
ex foo [type]
2644-
ex Foo::B::<u32> [type]
2644+
ex Foo::B [type]
26452645
ev Foo::A(…) [type_could_unify]
26462646
ev Foo::B [type_could_unify]
26472647
en Foo [type_could_unify]

src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/typed_hole.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,12 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::TypedHole) -> Option<Vec<Assist>
4747
sema: &ctx.sema,
4848
scope: &scope,
4949
goal: d.expected.clone(),
50-
config: TermSearchConfig { fuel: ctx.config.term_search_fuel, ..Default::default() },
50+
config: TermSearchConfig {
51+
fuel: ctx.config.term_search_fuel,
52+
enable_borrowcheck: ctx.config.term_search_borrowck,
53+
54+
..Default::default()
55+
},
5156
};
5257
let paths = term_search(&term_search_ctx);
5358

src/tools/rust-analyzer/crates/ide-diagnostics/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,7 @@ pub struct DiagnosticsConfig {
234234
pub prefer_no_std: bool,
235235
pub prefer_prelude: bool,
236236
pub term_search_fuel: u64,
237+
pub term_search_borrowck: bool,
237238
}
238239

239240
impl DiagnosticsConfig {
@@ -260,6 +261,7 @@ impl DiagnosticsConfig {
260261
prefer_no_std: false,
261262
prefer_prelude: true,
262263
term_search_fuel: 400,
264+
term_search_borrowck: true,
263265
}
264266
}
265267
}

src/tools/rust-analyzer/crates/rust-analyzer/src/cli/analysis_stats.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -994,6 +994,7 @@ impl flags::AnalysisStats {
994994
prefer_prelude: true,
995995
style_lints: false,
996996
term_search_fuel: 400,
997+
term_search_borrowck: true,
997998
},
998999
ide::AssistResolveStrategy::All,
9991000
file_id,

src/tools/rust-analyzer/crates/rust-analyzer/src/config.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,8 @@ config_data! {
341341
assist_emitMustUse: bool = false,
342342
/// Placeholder expression to use for missing expressions in assists.
343343
assist_expressionFillDefault: ExprFillDefaultDef = ExprFillDefaultDef::Todo,
344+
/// Enable borrow checking for term search code assists. If set to false, also there will be more suggestions, but some of them may not borrow-check.
345+
assist_termSearch_borrowcheck: bool = true,
344346
/// Term search fuel in "units of work" for assists (Defaults to 1800).
345347
assist_termSearch_fuel: usize = 1800,
346348

@@ -1269,6 +1271,7 @@ impl Config {
12691271
assist_emit_must_use: self.assist_emitMustUse(source_root).to_owned(),
12701272
prefer_prelude: self.imports_preferPrelude(source_root).to_owned(),
12711273
term_search_fuel: self.assist_termSearch_fuel(source_root).to_owned() as u64,
1274+
term_search_borrowck: self.assist_termSearch_borrowcheck(source_root).to_owned(),
12721275
}
12731276
}
12741277

@@ -1328,6 +1331,7 @@ impl Config {
13281331
prefer_prelude: self.imports_preferPrelude(source_root).to_owned(),
13291332
style_lints: self.diagnostics_styleLints_enable().to_owned(),
13301333
term_search_fuel: self.assist_termSearch_fuel(source_root).to_owned() as u64,
1334+
term_search_borrowck: self.assist_termSearch_borrowcheck(source_root).to_owned(),
13311335
}
13321336
}
13331337
pub fn expand_proc_attr_macros(&self) -> bool {

src/tools/rust-analyzer/crates/rust-analyzer/src/integrated_benchmarks.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,7 @@ fn integrated_diagnostics_benchmark() {
300300
prefer_no_std: false,
301301
prefer_prelude: false,
302302
term_search_fuel: 400,
303+
term_search_borrowck: true,
303304
};
304305
host.analysis()
305306
.diagnostics(&diagnostics_config, ide::AssistResolveStrategy::None, file_id)

0 commit comments

Comments
 (0)