Add config for preferring / ignoring prelude modules in find_path

This commit is contained in:
Lukas Wirth 2023-11-11 14:52:11 +01:00
parent 801a887954
commit ba61766217
36 changed files with 260 additions and 54 deletions

View file

@ -21,9 +21,10 @@ pub fn find_path(
item: ItemInNs, item: ItemInNs,
from: ModuleId, from: ModuleId,
prefer_no_std: bool, prefer_no_std: bool,
prefer_prelude: bool,
) -> Option<ModPath> { ) -> Option<ModPath> {
let _p = profile::span("find_path"); let _p = profile::span("find_path");
find_path_inner(db, item, from, None, prefer_no_std) find_path_inner(db, item, from, None, prefer_no_std, prefer_prelude)
} }
pub fn find_path_prefixed( pub fn find_path_prefixed(
@ -32,9 +33,10 @@ pub fn find_path_prefixed(
from: ModuleId, from: ModuleId,
prefix_kind: PrefixKind, prefix_kind: PrefixKind,
prefer_no_std: bool, prefer_no_std: bool,
prefer_prelude: bool,
) -> Option<ModPath> { ) -> Option<ModPath> {
let _p = profile::span("find_path_prefixed"); let _p = profile::span("find_path_prefixed");
find_path_inner(db, item, from, Some(prefix_kind), prefer_no_std) find_path_inner(db, item, from, Some(prefix_kind), prefer_no_std, prefer_prelude)
} }
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
@ -88,6 +90,7 @@ fn find_path_inner(
from: ModuleId, from: ModuleId,
prefixed: Option<PrefixKind>, prefixed: Option<PrefixKind>,
prefer_no_std: bool, prefer_no_std: bool,
prefer_prelude: bool,
) -> Option<ModPath> { ) -> Option<ModPath> {
// - if the item is a builtin, it's in scope // - if the item is a builtin, it's in scope
if let ItemInNs::Types(ModuleDefId::BuiltinType(builtin)) = item { if let ItemInNs::Types(ModuleDefId::BuiltinType(builtin)) = item {
@ -109,6 +112,7 @@ fn find_path_inner(
MAX_PATH_LEN, MAX_PATH_LEN,
prefixed, prefixed,
prefer_no_std || db.crate_supports_no_std(crate_root.krate), prefer_no_std || db.crate_supports_no_std(crate_root.krate),
prefer_prelude,
) )
.map(|(item, _)| item); .map(|(item, _)| item);
} }
@ -134,6 +138,7 @@ fn find_path_inner(
from, from,
prefixed, prefixed,
prefer_no_std, prefer_no_std,
prefer_prelude,
) { ) {
let data = db.enum_data(variant.parent); let data = db.enum_data(variant.parent);
path.push_segment(data.variants[variant.local_id].name.clone()); path.push_segment(data.variants[variant.local_id].name.clone());
@ -156,6 +161,7 @@ fn find_path_inner(
from, from,
prefixed, prefixed,
prefer_no_std || db.crate_supports_no_std(crate_root.krate), prefer_no_std || db.crate_supports_no_std(crate_root.krate),
prefer_prelude,
scope_name, scope_name,
) )
.map(|(item, _)| item) .map(|(item, _)| item)
@ -171,6 +177,7 @@ fn find_path_for_module(
max_len: usize, max_len: usize,
prefixed: Option<PrefixKind>, prefixed: Option<PrefixKind>,
prefer_no_std: bool, prefer_no_std: bool,
prefer_prelude: bool,
) -> Option<(ModPath, Stability)> { ) -> Option<(ModPath, Stability)> {
if max_len == 0 { if max_len == 0 {
return None; return None;
@ -236,6 +243,7 @@ fn find_path_for_module(
from, from,
prefixed, prefixed,
prefer_no_std, prefer_no_std,
prefer_prelude,
scope_name, scope_name,
) )
} }
@ -316,6 +324,7 @@ fn calculate_best_path(
from: ModuleId, from: ModuleId,
mut prefixed: Option<PrefixKind>, mut prefixed: Option<PrefixKind>,
prefer_no_std: bool, prefer_no_std: bool,
prefer_prelude: bool,
scope_name: Option<Name>, scope_name: Option<Name>,
) -> Option<(ModPath, Stability)> { ) -> Option<(ModPath, Stability)> {
if max_len <= 1 { if max_len <= 1 {
@ -351,11 +360,14 @@ fn calculate_best_path(
best_path_len - 1, best_path_len - 1,
prefixed, prefixed,
prefer_no_std, prefer_no_std,
prefer_prelude,
) { ) {
path.0.push_segment(name); path.0.push_segment(name);
let new_path = match best_path.take() { let new_path = match best_path.take() {
Some(best_path) => select_best_path(best_path, path, prefer_no_std), Some(best_path) => {
select_best_path(best_path, path, prefer_no_std, prefer_prelude)
}
None => path, None => path,
}; };
best_path_len = new_path.0.len(); best_path_len = new_path.0.len();
@ -388,6 +400,7 @@ fn calculate_best_path(
max_len - 1, max_len - 1,
prefixed, prefixed,
prefer_no_std, prefer_no_std,
prefer_prelude,
) else { ) else {
continue; continue;
}; };
@ -400,7 +413,9 @@ fn calculate_best_path(
); );
let new_path_with_stab = match best_path.take() { let new_path_with_stab = match best_path.take() {
Some(best_path) => select_best_path(best_path, path_with_stab, prefer_no_std), Some(best_path) => {
select_best_path(best_path, path_with_stab, prefer_no_std, prefer_prelude)
}
None => path_with_stab, None => path_with_stab,
}; };
update_best_path(&mut best_path, new_path_with_stab); update_best_path(&mut best_path, new_path_with_stab);
@ -421,17 +436,39 @@ fn calculate_best_path(
} }
} }
/// Select the best (most relevant) path between two paths.
/// This accounts for stability, path length whether std should be chosen over alloc/core paths as
/// well as ignoring prelude like paths or not.
fn select_best_path( fn select_best_path(
old_path: (ModPath, Stability), old_path @ (_, old_stability): (ModPath, Stability),
new_path: (ModPath, Stability), new_path @ (_, new_stability): (ModPath, Stability),
prefer_no_std: bool, prefer_no_std: bool,
prefer_prelude: bool,
) -> (ModPath, Stability) { ) -> (ModPath, Stability) {
match (old_path.1, new_path.1) { match (old_stability, new_stability) {
(Stable, Unstable) => return old_path, (Stable, Unstable) => return old_path,
(Unstable, Stable) => return new_path, (Unstable, Stable) => return new_path,
_ => {} _ => {}
} }
const STD_CRATES: [Name; 3] = [known::std, known::core, known::alloc]; const STD_CRATES: [Name; 3] = [known::std, known::core, known::alloc];
let choose = |new_path: (ModPath, _), old_path: (ModPath, _)| {
let new_has_prelude = new_path.0.segments().iter().any(|seg| seg == &known::prelude);
let old_has_prelude = old_path.0.segments().iter().any(|seg| seg == &known::prelude);
match (new_has_prelude, old_has_prelude, prefer_prelude) {
(true, false, true) | (false, true, false) => new_path,
(true, false, false) | (false, true, true) => old_path,
// no prelude difference in the paths, so pick the smaller one
(true, true, _) | (false, false, _) => {
if new_path.0.len() < old_path.0.len() {
new_path
} else {
old_path
}
}
}
};
match (old_path.0.segments().first(), new_path.0.segments().first()) { match (old_path.0.segments().first(), new_path.0.segments().first()) {
(Some(old), Some(new)) if STD_CRATES.contains(old) && STD_CRATES.contains(new) => { (Some(old), Some(new)) if STD_CRATES.contains(old) && STD_CRATES.contains(new) => {
let rank = match prefer_no_std { let rank = match prefer_no_std {
@ -452,23 +489,11 @@ fn select_best_path(
let orank = rank(old); let orank = rank(old);
match nrank.cmp(&orank) { match nrank.cmp(&orank) {
Ordering::Less => old_path, Ordering::Less => old_path,
Ordering::Equal => { Ordering::Equal => choose(new_path, old_path),
if new_path.0.len() < old_path.0.len() {
new_path
} else {
old_path
}
}
Ordering::Greater => new_path, Ordering::Greater => new_path,
} }
} }
_ => { _ => choose(new_path, old_path),
if new_path.0.len() < old_path.0.len() {
new_path
} else {
old_path
}
}
} }
} }
@ -571,7 +596,13 @@ mod tests {
/// `code` needs to contain a cursor marker; checks that `find_path` for the /// `code` needs to contain a cursor marker; checks that `find_path` for the
/// item the `path` refers to returns that same path when called from the /// item the `path` refers to returns that same path when called from the
/// module the cursor is in. /// module the cursor is in.
fn check_found_path_(ra_fixture: &str, path: &str, prefix_kind: Option<PrefixKind>) { #[track_caller]
fn check_found_path_(
ra_fixture: &str,
path: &str,
prefix_kind: Option<PrefixKind>,
prefer_prelude: bool,
) {
let (db, pos) = TestDB::with_position(ra_fixture); let (db, pos) = TestDB::with_position(ra_fixture);
let module = db.module_at_position(pos); let module = db.module_at_position(pos);
let parsed_path_file = syntax::SourceFile::parse(&format!("use {path};")); let parsed_path_file = syntax::SourceFile::parse(&format!("use {path};"));
@ -590,10 +621,16 @@ mod tests {
) )
.0 .0
.take_types() .take_types()
.unwrap(); .expect("path does not resolve to a type");
let found_path = let found_path = find_path_inner(
find_path_inner(&db, ItemInNs::Types(resolved), module, prefix_kind, false); &db,
ItemInNs::Types(resolved),
module,
prefix_kind,
false,
prefer_prelude,
);
assert_eq!(found_path, Some(mod_path), "on kind: {prefix_kind:?}"); assert_eq!(found_path, Some(mod_path), "on kind: {prefix_kind:?}");
} }
@ -604,10 +641,23 @@ mod tests {
absolute: &str, absolute: &str,
self_prefixed: &str, self_prefixed: &str,
) { ) {
check_found_path_(ra_fixture, unprefixed, None); check_found_path_(ra_fixture, unprefixed, None, false);
check_found_path_(ra_fixture, prefixed, Some(PrefixKind::Plain)); check_found_path_(ra_fixture, prefixed, Some(PrefixKind::Plain), false);
check_found_path_(ra_fixture, absolute, Some(PrefixKind::ByCrate)); check_found_path_(ra_fixture, absolute, Some(PrefixKind::ByCrate), false);
check_found_path_(ra_fixture, self_prefixed, Some(PrefixKind::BySelf)); check_found_path_(ra_fixture, self_prefixed, Some(PrefixKind::BySelf), false);
}
fn check_found_path_prelude(
ra_fixture: &str,
unprefixed: &str,
prefixed: &str,
absolute: &str,
self_prefixed: &str,
) {
check_found_path_(ra_fixture, unprefixed, None, true);
check_found_path_(ra_fixture, prefixed, Some(PrefixKind::Plain), true);
check_found_path_(ra_fixture, absolute, Some(PrefixKind::ByCrate), true);
check_found_path_(ra_fixture, self_prefixed, Some(PrefixKind::BySelf), true);
} }
#[test] #[test]
@ -1422,4 +1472,34 @@ pub mod error {
"std::error::Error", "std::error::Error",
); );
} }
#[test]
fn respects_prelude_setting() {
let ra_fixture = r#"
//- /main.rs crate:main deps:krate
$0
//- /krate.rs crate:krate
pub mod prelude {
pub use crate::foo::*;
}
pub mod foo {
pub struct Foo;
}
"#;
check_found_path(
ra_fixture,
"krate::foo::Foo",
"krate::foo::Foo",
"krate::foo::Foo",
"krate::foo::Foo",
);
check_found_path_prelude(
ra_fixture,
"krate::prelude::Foo",
"krate::prelude::Foo",
"krate::prelude::Foo",
"krate::prelude::Foo",
);
}
} }

View file

@ -945,6 +945,7 @@ impl HirDisplay for Ty {
ItemInNs::Types((*def_id).into()), ItemInNs::Types((*def_id).into()),
module_id, module_id,
false, false,
true,
) { ) {
write!(f, "{}", path.display(f.db.upcast()))?; write!(f, "{}", path.display(f.db.upcast()))?;
} else { } else {

View file

@ -664,8 +664,15 @@ impl Module {
db: &dyn DefDatabase, db: &dyn DefDatabase,
item: impl Into<ItemInNs>, item: impl Into<ItemInNs>,
prefer_no_std: bool, prefer_no_std: bool,
prefer_prelude: bool,
) -> Option<ModPath> { ) -> Option<ModPath> {
hir_def::find_path::find_path(db, item.into().into(), self.into(), prefer_no_std) hir_def::find_path::find_path(
db,
item.into().into(),
self.into(),
prefer_no_std,
prefer_prelude,
)
} }
/// Finds a path that can be used to refer to the given item from within /// Finds a path that can be used to refer to the given item from within
@ -676,6 +683,7 @@ impl Module {
item: impl Into<ItemInNs>, item: impl Into<ItemInNs>,
prefix_kind: PrefixKind, prefix_kind: PrefixKind,
prefer_no_std: bool, prefer_no_std: bool,
prefer_prelude: bool,
) -> Option<ModPath> { ) -> Option<ModPath> {
hir_def::find_path::find_path_prefixed( hir_def::find_path::find_path_prefixed(
db, db,
@ -683,6 +691,7 @@ impl Module {
self.into(), self.into(),
prefix_kind, prefix_kind,
prefer_no_std, prefer_no_std,
prefer_prelude,
) )
} }
} }

View file

@ -14,5 +14,6 @@ pub struct AssistConfig {
pub allowed: Option<Vec<AssistKind>>, pub allowed: Option<Vec<AssistKind>>,
pub insert_use: InsertUseConfig, pub insert_use: InsertUseConfig,
pub prefer_no_std: bool, pub prefer_no_std: bool,
pub prefer_prelude: bool,
pub assist_emit_must_use: bool, pub assist_emit_must_use: bool,
} }

View file

@ -88,7 +88,13 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>)
.into_iter() .into_iter()
.filter_map(|variant| { .filter_map(|variant| {
Some(( Some((
build_pat(ctx.db(), module, variant, ctx.config.prefer_no_std)?, build_pat(
ctx.db(),
module,
variant,
ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
)?,
variant.should_be_hidden(ctx.db(), module.krate()), variant.should_be_hidden(ctx.db(), module.krate()),
)) ))
}) })
@ -140,7 +146,13 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>)
.iter() .iter()
.any(|variant| variant.should_be_hidden(ctx.db(), module.krate())); .any(|variant| variant.should_be_hidden(ctx.db(), module.krate()));
let patterns = variants.into_iter().filter_map(|variant| { let patterns = variants.into_iter().filter_map(|variant| {
build_pat(ctx.db(), module, variant, ctx.config.prefer_no_std) build_pat(
ctx.db(),
module,
variant,
ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
)
}); });
(ast::Pat::from(make::tuple_pat(patterns)), is_hidden) (ast::Pat::from(make::tuple_pat(patterns)), is_hidden)
@ -173,7 +185,13 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>)
.iter() .iter()
.any(|variant| variant.should_be_hidden(ctx.db(), module.krate())); .any(|variant| variant.should_be_hidden(ctx.db(), module.krate()));
let patterns = variants.into_iter().filter_map(|variant| { let patterns = variants.into_iter().filter_map(|variant| {
build_pat(ctx.db(), module, variant.clone(), ctx.config.prefer_no_std) build_pat(
ctx.db(),
module,
variant.clone(),
ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
)
}); });
(ast::Pat::from(make::slice_pat(patterns)), is_hidden) (ast::Pat::from(make::slice_pat(patterns)), is_hidden)
}) })
@ -440,11 +458,16 @@ fn build_pat(
module: hir::Module, module: hir::Module,
var: ExtendedVariant, var: ExtendedVariant,
prefer_no_std: bool, prefer_no_std: bool,
prefer_prelude: bool,
) -> Option<ast::Pat> { ) -> Option<ast::Pat> {
match var { match var {
ExtendedVariant::Variant(var) => { ExtendedVariant::Variant(var) => {
let path = let path = mod_path_to_ast(&module.find_use_path(
mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var), prefer_no_std)?); db,
ModuleDef::from(var),
prefer_no_std,
prefer_prelude,
)?);
// FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though
Some(match var.source(db)?.value.kind() { Some(match var.source(db)?.value.kind() {

View file

@ -93,6 +93,7 @@ pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<
&ctx.sema, &ctx.sema,
ctx.config.insert_use.prefix_kind, ctx.config.insert_use.prefix_kind,
ctx.config.prefer_no_std, ctx.config.prefer_no_std,
ctx.config.prefer_no_std,
); );
if proposed_imports.is_empty() { if proposed_imports.is_empty() {
return None; return None;

View file

@ -348,6 +348,7 @@ fn augment_references_with_imports(
ModuleDef::Module(*target_module), ModuleDef::Module(*target_module),
ctx.config.insert_use.prefix_kind, ctx.config.insert_use.prefix_kind,
ctx.config.prefer_no_std, ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
) )
.map(|mod_path| { .map(|mod_path| {
make::path_concat(mod_path_to_ast(&mod_path), make::path_from_text("Bool")) make::path_concat(mod_path_to_ast(&mod_path), make::path_from_text("Bool"))

View file

@ -50,7 +50,12 @@ pub(crate) fn convert_into_to_from(acc: &mut Assists, ctx: &AssistContext<'_>) -
_ => return None, _ => return None,
}; };
mod_path_to_ast(&module.find_use_path(ctx.db(), src_type_def, ctx.config.prefer_no_std)?) mod_path_to_ast(&module.find_use_path(
ctx.db(),
src_type_def,
ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
)?)
}; };
let dest_type = match &ast_trait { let dest_type = match &ast_trait {

View file

@ -205,6 +205,7 @@ fn augment_references_with_imports(
ModuleDef::Module(*target_module), ModuleDef::Module(*target_module),
ctx.config.insert_use.prefix_kind, ctx.config.insert_use.prefix_kind,
ctx.config.prefer_no_std, ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
) )
.map(|mod_path| { .map(|mod_path| {
make::path_concat( make::path_concat(

View file

@ -163,6 +163,7 @@ pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op
ModuleDef::from(control_flow_enum), ModuleDef::from(control_flow_enum),
ctx.config.insert_use.prefix_kind, ctx.config.insert_use.prefix_kind,
ctx.config.prefer_no_std, ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
); );
if let Some(mod_path) = mod_path { if let Some(mod_path) = mod_path {

View file

@ -384,6 +384,7 @@ fn process_references(
*enum_module_def, *enum_module_def,
ctx.config.insert_use.prefix_kind, ctx.config.insert_use.prefix_kind,
ctx.config.prefer_no_std, ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
); );
if let Some(mut mod_path) = mod_path { if let Some(mut mod_path) = mod_path {
mod_path.pop_segment(); mod_path.pop_segment();

View file

@ -58,8 +58,12 @@ fn generate_record_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<(
let module = ctx.sema.to_def(&strukt)?.module(ctx.db()); let module = ctx.sema.to_def(&strukt)?.module(ctx.db());
let trait_ = deref_type_to_generate.to_trait(&ctx.sema, module.krate())?; let trait_ = deref_type_to_generate.to_trait(&ctx.sema, module.krate())?;
let trait_path = let trait_path = module.find_use_path(
module.find_use_path(ctx.db(), ModuleDef::Trait(trait_), ctx.config.prefer_no_std)?; ctx.db(),
ModuleDef::Trait(trait_),
ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
)?;
let field_type = field.ty()?; let field_type = field.ty()?;
let field_name = field.name()?; let field_name = field.name()?;
@ -99,8 +103,12 @@ fn generate_tuple_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()
let module = ctx.sema.to_def(&strukt)?.module(ctx.db()); let module = ctx.sema.to_def(&strukt)?.module(ctx.db());
let trait_ = deref_type_to_generate.to_trait(&ctx.sema, module.krate())?; let trait_ = deref_type_to_generate.to_trait(&ctx.sema, module.krate())?;
let trait_path = let trait_path = module.find_use_path(
module.find_use_path(ctx.db(), ModuleDef::Trait(trait_), ctx.config.prefer_no_std)?; ctx.db(),
ModuleDef::Trait(trait_),
ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
)?;
let field_type = field.ty()?; let field_type = field.ty()?;
let target = field.syntax().text_range(); let target = field.syntax().text_range();

View file

@ -67,6 +67,7 @@ pub(crate) fn generate_new(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option
ctx.sema.db, ctx.sema.db,
item_for_path_search(ctx.sema.db, item_in_ns)?, item_for_path_search(ctx.sema.db, item_in_ns)?,
ctx.config.prefer_no_std, ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
)?; )?;
let expr = use_trivial_constructor( let expr = use_trivial_constructor(

View file

@ -48,6 +48,7 @@ pub(crate) fn qualify_method_call(acc: &mut Assists, ctx: &AssistContext<'_>) ->
ctx.sema.db, ctx.sema.db,
item_for_path_search(ctx.sema.db, item_in_ns)?, item_for_path_search(ctx.sema.db, item_in_ns)?,
ctx.config.prefer_no_std, ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
)?; )?;
let qualify_candidate = QualifyCandidate::ImplMethod(ctx.sema.db, call, resolved_call); let qualify_candidate = QualifyCandidate::ImplMethod(ctx.sema.db, call, resolved_call);

View file

@ -37,8 +37,11 @@ use crate::{
// ``` // ```
pub(crate) fn qualify_path(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { pub(crate) fn qualify_path(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
let (import_assets, syntax_under_caret) = find_importable_node(ctx)?; let (import_assets, syntax_under_caret) = find_importable_node(ctx)?;
let mut proposed_imports = let mut proposed_imports = import_assets.search_for_relative_paths(
import_assets.search_for_relative_paths(&ctx.sema, ctx.config.prefer_no_std); &ctx.sema,
ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
);
if proposed_imports.is_empty() { if proposed_imports.is_empty() {
return None; return None;
} }

View file

@ -82,7 +82,12 @@ pub(crate) fn replace_derive_with_manual_impl(
}) })
.flat_map(|trait_| { .flat_map(|trait_| {
current_module current_module
.find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_), ctx.config.prefer_no_std) .find_use_path(
ctx.sema.db,
hir::ModuleDef::Trait(trait_),
ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
)
.as_ref() .as_ref()
.map(mod_path_to_ast) .map(mod_path_to_ast)
.zip(Some(trait_)) .zip(Some(trait_))

View file

@ -68,6 +68,7 @@ pub(crate) fn replace_qualified_name_with_use(
module, module,
ctx.config.insert_use.prefix_kind, ctx.config.insert_use.prefix_kind,
ctx.config.prefer_no_std, ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
) )
}) })
.flatten(); .flatten();

View file

@ -30,6 +30,7 @@ pub(crate) const TEST_CONFIG: AssistConfig = AssistConfig {
skip_glob_imports: true, skip_glob_imports: true,
}, },
prefer_no_std: false, prefer_no_std: false,
prefer_prelude: true,
assist_emit_must_use: false, assist_emit_must_use: false,
}; };
@ -44,6 +45,7 @@ pub(crate) const TEST_CONFIG_NO_SNIPPET_CAP: AssistConfig = AssistConfig {
skip_glob_imports: true, skip_glob_imports: true,
}, },
prefer_no_std: false, prefer_no_std: false,
prefer_prelude: true,
assist_emit_must_use: false, assist_emit_must_use: false,
}; };

View file

@ -626,6 +626,7 @@ fn enum_variants_with_paths(
ctx.db, ctx.db,
hir::ModuleDef::from(variant), hir::ModuleDef::from(variant),
ctx.config.prefer_no_std, ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
) { ) {
// Variants with trivial paths are already added by the existing completion logic, // Variants with trivial paths are already added by the existing completion logic,
// so we should avoid adding these twice // so we should avoid adding these twice

View file

@ -175,6 +175,7 @@ pub(crate) fn complete_expr_path(
ctx.db, ctx.db,
hir::ModuleDef::from(strukt), hir::ModuleDef::from(strukt),
ctx.config.prefer_no_std, ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
) )
.filter(|it| it.len() > 1); .filter(|it| it.len() > 1);
@ -197,6 +198,7 @@ pub(crate) fn complete_expr_path(
ctx.db, ctx.db,
hir::ModuleDef::from(un), hir::ModuleDef::from(un),
ctx.config.prefer_no_std, ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
) )
.filter(|it| it.len() > 1); .filter(|it| it.len() > 1);

View file

@ -257,7 +257,12 @@ fn import_on_the_fly(
let user_input_lowercased = potential_import_name.to_lowercase(); let user_input_lowercased = potential_import_name.to_lowercase();
import_assets import_assets
.search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind, ctx.config.prefer_no_std) .search_for_imports(
&ctx.sema,
ctx.config.insert_use.prefix_kind,
ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
)
.into_iter() .into_iter()
.filter(ns_filter) .filter(ns_filter)
.filter(|import| { .filter(|import| {
@ -299,7 +304,12 @@ fn import_on_the_fly_pat_(
let user_input_lowercased = potential_import_name.to_lowercase(); let user_input_lowercased = potential_import_name.to_lowercase();
import_assets import_assets
.search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind, ctx.config.prefer_no_std) .search_for_imports(
&ctx.sema,
ctx.config.insert_use.prefix_kind,
ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
)
.into_iter() .into_iter()
.filter(ns_filter) .filter(ns_filter)
.filter(|import| { .filter(|import| {
@ -336,7 +346,12 @@ fn import_on_the_fly_method(
let user_input_lowercased = potential_import_name.to_lowercase(); let user_input_lowercased = potential_import_name.to_lowercase();
import_assets import_assets
.search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind, ctx.config.prefer_no_std) .search_for_imports(
&ctx.sema,
ctx.config.insert_use.prefix_kind,
ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
)
.into_iter() .into_iter()
.filter(|import| { .filter(|import| {
!ctx.is_item_hidden(&import.item_to_import) !ctx.is_item_hidden(&import.item_to_import)

View file

@ -19,6 +19,7 @@ pub struct CompletionConfig {
pub snippet_cap: Option<SnippetCap>, pub snippet_cap: Option<SnippetCap>,
pub insert_use: InsertUseConfig, pub insert_use: InsertUseConfig,
pub prefer_no_std: bool, pub prefer_no_std: bool,
pub prefer_prelude: bool,
pub snippets: Vec<Snippet>, pub snippets: Vec<Snippet>,
pub limit: Option<usize>, pub limit: Option<usize>,
} }

View file

@ -263,6 +263,7 @@ pub fn resolve_completion_edits(
candidate, candidate,
config.insert_use.prefix_kind, config.insert_use.prefix_kind,
config.prefer_no_std, config.prefer_no_std,
config.prefer_prelude,
) )
}) })
.find(|mod_path| mod_path.display(db).to_string() == full_import_path); .find(|mod_path| mod_path.display(db).to_string() == full_import_path);

View file

@ -179,6 +179,7 @@ fn import_edits(ctx: &CompletionContext<'_>, requires: &[GreenNode]) -> Option<V
item, item,
ctx.config.insert_use.prefix_kind, ctx.config.insert_use.prefix_kind,
ctx.config.prefer_no_std, ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
)?; )?;
Some((path.len() > 1).then(|| LocatedImport::new(path.clone(), item, item, None))) Some((path.len() > 1).then(|| LocatedImport::new(path.clone(), item, item, None)))
}; };

View file

@ -68,6 +68,7 @@ pub(crate) const TEST_CONFIG: CompletionConfig = CompletionConfig {
callable: Some(CallableSnippets::FillArguments), callable: Some(CallableSnippets::FillArguments),
snippet_cap: SnippetCap::new(true), snippet_cap: SnippetCap::new(true),
prefer_no_std: false, prefer_no_std: false,
prefer_prelude: true,
insert_use: InsertUseConfig { insert_use: InsertUseConfig {
granularity: ImportGranularity::Crate, granularity: ImportGranularity::Crate,
prefix_kind: PrefixKind::Plain, prefix_kind: PrefixKind::Plain,

View file

@ -220,9 +220,10 @@ impl ImportAssets {
sema: &Semantics<'_, RootDatabase>, sema: &Semantics<'_, RootDatabase>,
prefix_kind: PrefixKind, prefix_kind: PrefixKind,
prefer_no_std: bool, prefer_no_std: bool,
prefer_prelude: bool,
) -> Vec<LocatedImport> { ) -> Vec<LocatedImport> {
let _p = profile::span("import_assets::search_for_imports"); let _p = profile::span("import_assets::search_for_imports");
self.search_for(sema, Some(prefix_kind), prefer_no_std) self.search_for(sema, Some(prefix_kind), prefer_no_std, prefer_prelude)
} }
/// This may return non-absolute paths if a part of the returned path is already imported into scope. /// This may return non-absolute paths if a part of the returned path is already imported into scope.
@ -230,9 +231,10 @@ impl ImportAssets {
&self, &self,
sema: &Semantics<'_, RootDatabase>, sema: &Semantics<'_, RootDatabase>,
prefer_no_std: bool, prefer_no_std: bool,
prefer_prelude: bool,
) -> Vec<LocatedImport> { ) -> Vec<LocatedImport> {
let _p = profile::span("import_assets::search_for_relative_paths"); let _p = profile::span("import_assets::search_for_relative_paths");
self.search_for(sema, None, prefer_no_std) self.search_for(sema, None, prefer_no_std, prefer_prelude)
} }
/// Requires imports to by prefix instead of fuzzily. /// Requires imports to by prefix instead of fuzzily.
@ -270,6 +272,7 @@ impl ImportAssets {
sema: &Semantics<'_, RootDatabase>, sema: &Semantics<'_, RootDatabase>,
prefixed: Option<PrefixKind>, prefixed: Option<PrefixKind>,
prefer_no_std: bool, prefer_no_std: bool,
prefer_prelude: bool,
) -> Vec<LocatedImport> { ) -> Vec<LocatedImport> {
let _p = profile::span("import_assets::search_for"); let _p = profile::span("import_assets::search_for");
@ -281,6 +284,7 @@ impl ImportAssets {
&self.module_with_candidate, &self.module_with_candidate,
prefixed, prefixed,
prefer_no_std, prefer_no_std,
prefer_prelude,
) )
}; };
@ -594,11 +598,18 @@ fn get_mod_path(
module_with_candidate: &Module, module_with_candidate: &Module,
prefixed: Option<PrefixKind>, prefixed: Option<PrefixKind>,
prefer_no_std: bool, prefer_no_std: bool,
prefer_prelude: bool,
) -> Option<ModPath> { ) -> Option<ModPath> {
if let Some(prefix_kind) = prefixed { if let Some(prefix_kind) = prefixed {
module_with_candidate.find_use_path_prefixed(db, item_to_search, prefix_kind, prefer_no_std) module_with_candidate.find_use_path_prefixed(
db,
item_to_search,
prefix_kind,
prefer_no_std,
prefer_prelude,
)
} else { } else {
module_with_candidate.find_use_path(db, item_to_search, prefer_no_std) module_with_candidate.find_use_path(db, item_to_search, prefer_no_std, prefer_prelude)
} }
} }

View file

@ -277,6 +277,7 @@ impl Ctx<'_> {
self.source_scope.db.upcast(), self.source_scope.db.upcast(),
hir::ModuleDef::Trait(trait_ref), hir::ModuleDef::Trait(trait_ref),
false, false,
true,
)?; )?;
match make::ty_path(mod_path_to_ast(&found_path)) { match make::ty_path(mod_path_to_ast(&found_path)) {
ast::Type::PathType(path_ty) => Some(path_ty), ast::Type::PathType(path_ty) => Some(path_ty),
@ -311,8 +312,12 @@ impl Ctx<'_> {
} }
} }
let found_path = let found_path = self.target_module.find_use_path(
self.target_module.find_use_path(self.source_scope.db.upcast(), def, false)?; self.source_scope.db.upcast(),
def,
false,
true,
)?;
let res = mod_path_to_ast(&found_path).clone_for_update(); let res = mod_path_to_ast(&found_path).clone_for_update();
if let Some(args) = path.segment().and_then(|it| it.generic_arg_list()) { if let Some(args) = path.segment().and_then(|it| it.generic_arg_list()) {
if let Some(segment) = res.segment() { if let Some(segment) = res.segment() {

View file

@ -136,6 +136,7 @@ pub(crate) fn json_in_items(
it, it,
config.insert_use.prefix_kind, config.insert_use.prefix_kind,
config.prefer_no_std, config.prefer_no_std,
config.prefer_prelude,
) { ) {
insert_use(&scope, mod_path_to_ast(&it), &config.insert_use); insert_use(&scope, mod_path_to_ast(&it), &config.insert_use);
} }
@ -148,6 +149,7 @@ pub(crate) fn json_in_items(
it, it,
config.insert_use.prefix_kind, config.insert_use.prefix_kind,
config.prefer_no_std, config.prefer_no_std,
config.prefer_prelude,
) { ) {
insert_use(&scope, mod_path_to_ast(&it), &config.insert_use); insert_use(&scope, mod_path_to_ast(&it), &config.insert_use);
} }

View file

@ -122,6 +122,7 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option<Vec<Ass
ctx.sema.db, ctx.sema.db,
item_for_path_search(ctx.sema.db, item_in_ns)?, item_for_path_search(ctx.sema.db, item_in_ns)?,
ctx.config.prefer_no_std, ctx.config.prefer_no_std,
ctx.config.prefer_prelude,
)?; )?;
use_trivial_constructor( use_trivial_constructor(

View file

@ -225,6 +225,7 @@ pub struct DiagnosticsConfig {
// FIXME: We may want to include a whole `AssistConfig` here // FIXME: We may want to include a whole `AssistConfig` here
pub insert_use: InsertUseConfig, pub insert_use: InsertUseConfig,
pub prefer_no_std: bool, pub prefer_no_std: bool,
pub prefer_prelude: bool,
} }
impl DiagnosticsConfig { impl DiagnosticsConfig {
@ -247,6 +248,7 @@ impl DiagnosticsConfig {
skip_glob_imports: false, skip_glob_imports: false,
}, },
prefer_no_std: false, prefer_no_std: false,
prefer_prelude: true,
} }
} }
} }

View file

@ -651,7 +651,7 @@ impl Match {
for (path, resolved_path) in &template.resolved_paths { for (path, resolved_path) in &template.resolved_paths {
if let hir::PathResolution::Def(module_def) = resolved_path.resolution { if let hir::PathResolution::Def(module_def) = resolved_path.resolution {
let mod_path = let mod_path =
module.find_use_path(sema.db, module_def, false).ok_or_else(|| { module.find_use_path(sema.db, module_def, false, true).ok_or_else(|| {
match_error!("Failed to render template path `{}` at match location") match_error!("Failed to render template path `{}` at match location")
})?; })?;
self.rendered_template_paths.insert(path.clone(), mod_path); self.rendered_template_paths.insert(path.clone(), mod_path);

View file

@ -762,7 +762,8 @@ impl flags::AnalysisStats {
group: true, group: true,
skip_glob_imports: true, skip_glob_imports: true,
}, },
prefer_no_std: Default::default(), prefer_no_std: false,
prefer_prelude: true,
}, },
ide::AssistResolveStrategy::All, ide::AssistResolveStrategy::All,
file_id, file_id,

View file

@ -353,6 +353,8 @@ config_data! {
imports_merge_glob: bool = "true", imports_merge_glob: bool = "true",
/// Prefer to unconditionally use imports of the core and alloc crate, over the std crate. /// Prefer to unconditionally use imports of the core and alloc crate, over the std crate.
imports_prefer_no_std: bool = "false", imports_prefer_no_std: bool = "false",
/// Whether to prefer import paths containing a `prelude` module.
imports_prefer_prelude: bool = "false",
/// The path structure for newly inserted paths to use. /// The path structure for newly inserted paths to use.
imports_prefix: ImportPrefixDef = "\"plain\"", imports_prefix: ImportPrefixDef = "\"plain\"",
@ -1118,6 +1120,7 @@ impl Config {
}, },
insert_use: self.insert_use_config(), insert_use: self.insert_use_config(),
prefer_no_std: self.data.imports_prefer_no_std, prefer_no_std: self.data.imports_prefer_no_std,
prefer_prelude: self.data.imports_prefer_prelude,
} }
} }
@ -1487,6 +1490,7 @@ impl Config {
}, },
insert_use: self.insert_use_config(), insert_use: self.insert_use_config(),
prefer_no_std: self.data.imports_prefer_no_std, prefer_no_std: self.data.imports_prefer_no_std,
prefer_prelude: self.data.imports_prefer_prelude,
snippet_cap: SnippetCap::new(try_or_def!( snippet_cap: SnippetCap::new(try_or_def!(
self.caps self.caps
.text_document .text_document
@ -1516,6 +1520,7 @@ impl Config {
allowed: None, allowed: None,
insert_use: self.insert_use_config(), insert_use: self.insert_use_config(),
prefer_no_std: self.data.imports_prefer_no_std, prefer_no_std: self.data.imports_prefer_no_std,
prefer_prelude: self.data.imports_prefer_prelude,
assist_emit_must_use: self.data.assist_emitMustUse, assist_emit_must_use: self.data.assist_emitMustUse,
} }
} }

View file

@ -146,6 +146,7 @@ fn integrated_completion_benchmark() {
}, },
snippets: Vec::new(), snippets: Vec::new(),
prefer_no_std: false, prefer_no_std: false,
prefer_prelude: true,
limit: None, limit: None,
}; };
let position = let position =
@ -186,6 +187,7 @@ fn integrated_completion_benchmark() {
}, },
snippets: Vec::new(), snippets: Vec::new(),
prefer_no_std: false, prefer_no_std: false,
prefer_prelude: true,
limit: None, limit: None,
}; };
let position = let position =

View file

@ -498,6 +498,11 @@ Whether to allow import insertion to merge new imports into single path glob imp
-- --
Prefer to unconditionally use imports of the core and alloc crate, over the std crate. Prefer to unconditionally use imports of the core and alloc crate, over the std crate.
-- --
[[rust-analyzer.imports.prefer.prelude]]rust-analyzer.imports.prefer.prelude (default: `false`)::
+
--
Whether to prefer import paths containing a `prelude` module.
--
[[rust-analyzer.imports.prefix]]rust-analyzer.imports.prefix (default: `"plain"`):: [[rust-analyzer.imports.prefix]]rust-analyzer.imports.prefix (default: `"plain"`)::
+ +
-- --

View file

@ -1134,6 +1134,11 @@
"default": false, "default": false,
"type": "boolean" "type": "boolean"
}, },
"rust-analyzer.imports.prefer.prelude": {
"markdownDescription": "Whether to prefer import paths containing a `prelude` module.",
"default": false,
"type": "boolean"
},
"rust-analyzer.imports.prefix": { "rust-analyzer.imports.prefix": {
"markdownDescription": "The path structure for newly inserted paths to use.", "markdownDescription": "The path structure for newly inserted paths to use.",
"default": "plain", "default": "plain",