diff --git a/crates/hir-def/src/find_path.rs b/crates/hir-def/src/find_path.rs index 52d940d635..d9ef28785c 100644 --- a/crates/hir-def/src/find_path.rs +++ b/crates/hir-def/src/find_path.rs @@ -17,7 +17,7 @@ use crate::{ nameres::DefMap, path::{ModPath, PathKind}, visibility::{Visibility, VisibilityExplicitness}, - ModuleDefId, ModuleId, + ImportPathConfig, ModuleDefId, ModuleId, }; /// Find a path that can be used to refer to a certain item. This can depend on @@ -28,21 +28,10 @@ pub fn find_path( from: ModuleId, prefix_kind: PrefixKind, ignore_local_imports: bool, - prefer_no_std: bool, - prefer_prelude: bool, + cfg: ImportPathConfig, ) -> Option { let _p = tracing::span!(tracing::Level::INFO, "find_path").entered(); - find_path_inner( - FindPathCtx { - db, - prefix: prefix_kind, - prefer_no_std, - prefer_prelude, - ignore_local_imports, - }, - item, - from, - ) + find_path_inner(FindPathCtx { db, prefix: prefix_kind, cfg, ignore_local_imports }, item, from) } #[derive(Copy, Clone, Debug)] @@ -88,8 +77,7 @@ impl PrefixKind { struct FindPathCtx<'db> { db: &'db dyn DefDatabase, prefix: PrefixKind, - prefer_no_std: bool, - prefer_prelude: bool, + cfg: ImportPathConfig, ignore_local_imports: bool, } @@ -107,7 +95,11 @@ fn find_path_inner(ctx: FindPathCtx<'_>, item: ItemInNs, from: ModuleId) -> Opti let mut visited_modules = FxHashSet::default(); return find_path_for_module( FindPathCtx { - prefer_no_std: ctx.prefer_no_std || ctx.db.crate_supports_no_std(crate_root.krate), + cfg: ImportPathConfig { + prefer_no_std: ctx.cfg.prefer_no_std + || ctx.db.crate_supports_no_std(crate_root.krate), + ..ctx.cfg + }, ..ctx }, &def_map, @@ -160,7 +152,11 @@ fn find_path_inner(ctx: FindPathCtx<'_>, item: ItemInNs, from: ModuleId) -> Opti calculate_best_path( FindPathCtx { - prefer_no_std: ctx.prefer_no_std || ctx.db.crate_supports_no_std(crate_root.krate), + cfg: ImportPathConfig { + prefer_no_std: ctx.cfg.prefer_no_std + || ctx.db.crate_supports_no_std(crate_root.krate), + ..ctx.cfg + }, ..ctx }, &def_map, @@ -381,9 +377,7 @@ fn calculate_best_path( path.0.push_segment(name); let new_path = match best_path.take() { - Some(best_path) => { - select_best_path(best_path, path, ctx.prefer_no_std, ctx.prefer_prelude) - } + Some(best_path) => select_best_path(best_path, path, ctx.cfg), None => path, }; best_path_len = new_path.0.len(); @@ -425,12 +419,7 @@ fn calculate_best_path( ); let new_path_with_stab = match best_path.take() { - Some(best_path) => select_best_path( - best_path, - path_with_stab, - ctx.prefer_no_std, - ctx.prefer_prelude, - ), + Some(best_path) => select_best_path(best_path, path_with_stab, ctx.cfg), None => path_with_stab, }; update_best_path(&mut best_path, new_path_with_stab); @@ -446,8 +435,7 @@ fn calculate_best_path( fn select_best_path( old_path @ (_, old_stability): (ModPath, Stability), new_path @ (_, new_stability): (ModPath, Stability), - prefer_no_std: bool, - prefer_prelude: bool, + cfg: ImportPathConfig, ) -> (ModPath, Stability) { match (old_stability, new_stability) { (Stable, Unstable) => return old_path, @@ -461,7 +449,7 @@ fn select_best_path( let (old_path, _) = &old; let new_has_prelude = new_path.segments().iter().any(|seg| seg == &known::prelude); let old_has_prelude = old_path.segments().iter().any(|seg| seg == &known::prelude); - match (new_has_prelude, old_has_prelude, prefer_prelude) { + match (new_has_prelude, old_has_prelude, cfg.prefer_prelude) { (true, false, true) | (false, true, false) => new, (true, false, false) | (false, true, true) => old, // no prelude difference in the paths, so pick the shorter one @@ -482,7 +470,7 @@ fn select_best_path( match (old_path.0.segments().first(), new_path.0.segments().first()) { (Some(old), Some(new)) if STD_CRATES.contains(old) && STD_CRATES.contains(new) => { - let rank = match prefer_no_std { + let rank = match cfg.prefer_no_std { false => |name: &Name| match name { name if name == &known::core => 0, name if name == &known::alloc => 1, @@ -647,10 +635,9 @@ mod tests { { let found_path = find_path_inner( FindPathCtx { - prefer_no_std: false, db: &db, prefix, - prefer_prelude, + cfg: ImportPathConfig { prefer_no_std: false, prefer_prelude }, ignore_local_imports, }, resolved, diff --git a/crates/hir-def/src/lib.rs b/crates/hir-def/src/lib.rs index ca8cc1c3ea..682d169adb 100644 --- a/crates/hir-def/src/lib.rs +++ b/crates/hir-def/src/lib.rs @@ -108,6 +108,15 @@ use crate::{ type FxIndexMap = indexmap::IndexMap>; +/// A wrapper around two booleans, [`ImportPathConfig::prefer_no_std`] and [`ImportPathConfig::prefer_prelude`]. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Copy)] +pub struct ImportPathConfig { + /// If true, prefer to unconditionally use imports of the `core` and `alloc` crate + /// over the std. + pub prefer_no_std: bool, + /// If true, prefer import paths containing a prelude module. + pub prefer_prelude: bool, +} #[derive(Debug)] pub struct ItemLoc { diff --git a/crates/hir-ty/src/display.rs b/crates/hir-ty/src/display.rs index 82bbc28884..94a6066ee7 100644 --- a/crates/hir-ty/src/display.rs +++ b/crates/hir-ty/src/display.rs @@ -21,7 +21,8 @@ use hir_def::{ path::{Path, PathKind}, type_ref::{TraitBoundModifier, TypeBound, TypeRef}, visibility::Visibility, - HasModule, ItemContainerId, LocalFieldId, Lookup, ModuleDefId, ModuleId, TraitId, + HasModule, ImportPathConfig, ItemContainerId, LocalFieldId, Lookup, ModuleDefId, ModuleId, + TraitId, }; use hir_expand::name::Name; use intern::{Internable, Interned}; @@ -1000,9 +1001,8 @@ impl HirDisplay for Ty { ItemInNs::Types((*def_id).into()), module_id, PrefixKind::Plain, - false, - false, true, + ImportPathConfig { prefer_no_std: false, prefer_prelude: true }, ) { write!(f, "{}", path.display(f.db.upcast()))?; } else { diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index 7f0b0cd48c..0b68762e4f 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -122,6 +122,7 @@ pub use { per_ns::Namespace, type_ref::{Mutability, TypeRef}, visibility::Visibility, + ImportPathConfig, // FIXME: This is here since some queries take it as input that are used // outside of hir. {AdtId, MacroId, ModuleDefId}, @@ -792,8 +793,7 @@ impl Module { self, db: &dyn DefDatabase, item: impl Into, - prefer_no_std: bool, - prefer_prelude: bool, + cfg: ImportPathConfig, ) -> Option { hir_def::find_path::find_path( db, @@ -801,8 +801,7 @@ impl Module { self.into(), PrefixKind::Plain, false, - prefer_no_std, - prefer_prelude, + cfg, ) } @@ -813,18 +812,9 @@ impl Module { db: &dyn DefDatabase, item: impl Into, prefix_kind: PrefixKind, - prefer_no_std: bool, - prefer_prelude: bool, + cfg: ImportPathConfig, ) -> Option { - hir_def::find_path::find_path( - db, - item.into().into(), - self.into(), - prefix_kind, - true, - prefer_no_std, - prefer_prelude, - ) + hir_def::find_path::find_path(db, item.into().into(), self.into(), prefix_kind, true, cfg) } } diff --git a/crates/hir/src/term_search/expr.rs b/crates/hir/src/term_search/expr.rs index 3cbe0d217c..8173427cd9 100644 --- a/crates/hir/src/term_search/expr.rs +++ b/crates/hir/src/term_search/expr.rs @@ -1,5 +1,6 @@ //! Type tree for term search +use hir_def::ImportPathConfig; use hir_expand::mod_path::ModPath; use hir_ty::{ db::HirDatabase, @@ -16,22 +17,20 @@ use crate::{ fn mod_item_path( sema_scope: &SemanticsScope<'_>, def: &ModuleDef, - prefer_no_std: bool, - prefer_prelude: bool, + cfg: ImportPathConfig, ) -> Option { let db = sema_scope.db; let m = sema_scope.module(); - m.find_path(db.upcast(), *def, prefer_no_std, prefer_prelude) + m.find_path(db.upcast(), *def, cfg) } /// Helper function to get path to `ModuleDef` as string fn mod_item_path_str( sema_scope: &SemanticsScope<'_>, def: &ModuleDef, - prefer_no_std: bool, - prefer_prelude: bool, + cfg: ImportPathConfig, ) -> Result { - let path = mod_item_path(sema_scope, def, prefer_no_std, prefer_prelude); + let path = mod_item_path(sema_scope, def, cfg); path.map(|it| it.display(sema_scope.db.upcast()).to_string()) .ok_or(DisplaySourceCodeError::PathNotFound) } @@ -40,8 +39,7 @@ fn mod_item_path_str( fn type_path( sema_scope: &SemanticsScope<'_>, ty: &Type, - prefer_no_std: bool, - prefer_prelude: bool, + cfg: ImportPathConfig, ) -> Result { let db = sema_scope.db; let m = sema_scope.module(); @@ -50,9 +48,7 @@ fn type_path( Some(adt) => { let ty_name = ty.display_source_code(db, m.id, true)?; - let mut path = - mod_item_path(sema_scope, &ModuleDef::Adt(adt), prefer_no_std, prefer_prelude) - .unwrap(); + let mut path = mod_item_path(sema_scope, &ModuleDef::Adt(adt), cfg).unwrap(); path.pop_segment(); let path = path.display(db.upcast()).to_string(); let res = match path.is_empty() { @@ -137,11 +133,10 @@ impl Expr { &self, sema_scope: &SemanticsScope<'_>, many_formatter: &mut dyn FnMut(&Type) -> String, - prefer_no_std: bool, - prefer_prelude: bool, + cfg: ImportPathConfig, ) -> Result { let db = sema_scope.db; - let mod_item_path_str = |s, def| mod_item_path_str(s, def, prefer_no_std, prefer_prelude); + let mod_item_path_str = |s, def| mod_item_path_str(s, def, cfg); match self { Expr::Const(it) => mod_item_path_str(sema_scope, &ModuleDef::Const(*it)), Expr::Static(it) => mod_item_path_str(sema_scope, &ModuleDef::Static(*it)), @@ -151,9 +146,7 @@ impl Expr { Expr::Function { func, params, .. } => { let args = params .iter() - .map(|f| { - f.gen_source_code(sema_scope, many_formatter, prefer_no_std, prefer_prelude) - }) + .map(|f| f.gen_source_code(sema_scope, many_formatter, cfg)) .collect::, DisplaySourceCodeError>>()? .into_iter() .join(", "); @@ -167,14 +160,10 @@ impl Expr { crate::AssocItemContainer::Impl(imp) => { let self_ty = imp.self_ty(db); // Should it be guaranteed that `mod_item_path` always exists? - match self_ty.as_adt().and_then(|adt| { - mod_item_path( - sema_scope, - &adt.into(), - prefer_no_std, - prefer_prelude, - ) - }) { + match self_ty + .as_adt() + .and_then(|adt| mod_item_path(sema_scope, &adt.into(), cfg)) + { Some(path) => path.display(sema_scope.db.upcast()).to_string(), None => self_ty.display(db).to_string(), } @@ -196,17 +185,10 @@ impl Expr { let func_name = func.name(db).display(db.upcast()).to_string(); let self_param = func.self_param(db).unwrap(); - let target_str = target.gen_source_code( - sema_scope, - many_formatter, - prefer_no_std, - prefer_prelude, - )?; + let target_str = target.gen_source_code(sema_scope, many_formatter, cfg)?; let args = params .iter() - .map(|f| { - f.gen_source_code(sema_scope, many_formatter, prefer_no_std, prefer_prelude) - }) + .map(|f| f.gen_source_code(sema_scope, many_formatter, cfg)) .collect::, DisplaySourceCodeError>>()? .into_iter() .join(", "); @@ -238,7 +220,7 @@ impl Expr { false => { let generics = generics .iter() - .map(|it| type_path(sema_scope, it, prefer_no_std, prefer_prelude)) + .map(|it| type_path(sema_scope, it, cfg)) .collect::, DisplaySourceCodeError>>()? .into_iter() .join(", "); @@ -249,14 +231,7 @@ impl Expr { StructKind::Tuple => { let args = params .iter() - .map(|f| { - f.gen_source_code( - sema_scope, - many_formatter, - prefer_no_std, - prefer_prelude, - ) - }) + .map(|f| f.gen_source_code(sema_scope, many_formatter, cfg)) .collect::, DisplaySourceCodeError>>()? .into_iter() .join(", "); @@ -271,12 +246,7 @@ impl Expr { let tmp = format!( "{}: {}", f.name(db).display(db.upcast()), - a.gen_source_code( - sema_scope, - many_formatter, - prefer_no_std, - prefer_prelude - )? + a.gen_source_code(sema_scope, many_formatter, cfg)? ); Ok(tmp) }) @@ -297,14 +267,7 @@ impl Expr { StructKind::Tuple => { let args = params .iter() - .map(|a| { - a.gen_source_code( - sema_scope, - many_formatter, - prefer_no_std, - prefer_prelude, - ) - }) + .map(|a| a.gen_source_code(sema_scope, many_formatter, cfg)) .collect::, DisplaySourceCodeError>>()? .into_iter() .join(", "); @@ -319,12 +282,7 @@ impl Expr { let tmp = format!( "{}: {}", f.name(db).display(db.upcast()), - a.gen_source_code( - sema_scope, - many_formatter, - prefer_no_std, - prefer_prelude - )? + a.gen_source_code(sema_scope, many_formatter, cfg)? ); Ok(tmp) }) @@ -338,7 +296,7 @@ impl Expr { false => { let generics = generics .iter() - .map(|it| type_path(sema_scope, it, prefer_no_std, prefer_prelude)) + .map(|it| type_path(sema_scope, it, cfg)) .collect::, DisplaySourceCodeError>>()? .into_iter() .join(", "); @@ -353,9 +311,7 @@ impl Expr { Expr::Tuple { params, .. } => { let args = params .iter() - .map(|a| { - a.gen_source_code(sema_scope, many_formatter, prefer_no_std, prefer_prelude) - }) + .map(|a| a.gen_source_code(sema_scope, many_formatter, cfg)) .collect::, DisplaySourceCodeError>>()? .into_iter() .join(", "); @@ -367,12 +323,7 @@ impl Expr { return Ok(many_formatter(&expr.ty(db))); } - let strukt = expr.gen_source_code( - sema_scope, - many_formatter, - prefer_no_std, - prefer_prelude, - )?; + let strukt = expr.gen_source_code(sema_scope, many_formatter, cfg)?; let field = field.name(db).display(db.upcast()).to_string(); Ok(format!("{strukt}.{field}")) } @@ -381,12 +332,7 @@ impl Expr { return Ok(many_formatter(&expr.ty(db))); } - let inner = expr.gen_source_code( - sema_scope, - many_formatter, - prefer_no_std, - prefer_prelude, - )?; + let inner = expr.gen_source_code(sema_scope, many_formatter, cfg)?; Ok(format!("&{inner}")) } Expr::Many(ty) => Ok(many_formatter(ty)), diff --git a/crates/ide-assists/src/handlers/add_missing_match_arms.rs b/crates/ide-assists/src/handlers/add_missing_match_arms.rs index 8eddc562be..22a4674fd4 100644 --- a/crates/ide-assists/src/handlers/add_missing_match_arms.rs +++ b/crates/ide-assists/src/handlers/add_missing_match_arms.rs @@ -1,7 +1,7 @@ use std::iter::{self, Peekable}; use either::Either; -use hir::{Adt, Crate, HasAttrs, HasSource, ModuleDef, Semantics}; +use hir::{Adt, Crate, HasAttrs, HasSource, ImportPathConfig, ModuleDef, Semantics}; use ide_db::RootDatabase; use ide_db::{famous_defs::FamousDefs, helpers::mod_path_to_ast}; use itertools::Itertools; @@ -71,6 +71,11 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>) .filter(|pat| !matches!(pat, Pat::WildcardPat(_))) .collect(); + let cfg = ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }; + let module = ctx.sema.scope(expr.syntax())?.module(); let (mut missing_pats, is_non_exhaustive, has_hidden_variants): ( Peekable>>, @@ -88,13 +93,7 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>) .into_iter() .filter_map(|variant| { Some(( - build_pat( - ctx.db(), - module, - variant, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, - )?, + build_pat(ctx.db(), module, variant, cfg)?, variant.should_be_hidden(ctx.db(), module.krate()), )) }) @@ -145,15 +144,9 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>) let is_hidden = variants .iter() .any(|variant| variant.should_be_hidden(ctx.db(), module.krate())); - let patterns = variants.into_iter().filter_map(|variant| { - build_pat( - ctx.db(), - module, - variant, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, - ) - }); + let patterns = variants + .into_iter() + .filter_map(|variant| build_pat(ctx.db(), module, variant, cfg)); (ast::Pat::from(make::tuple_pat(patterns)), is_hidden) }) @@ -184,15 +177,9 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>) let is_hidden = variants .iter() .any(|variant| variant.should_be_hidden(ctx.db(), module.krate())); - let patterns = variants.into_iter().filter_map(|variant| { - build_pat( - ctx.db(), - module, - variant, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, - ) - }); + let patterns = variants + .into_iter() + .filter_map(|variant| build_pat(ctx.db(), module, variant, cfg)); (ast::Pat::from(make::slice_pat(patterns)), is_hidden) }) .filter(|(variant_pat, _)| is_variant_missing(&top_lvl_pats, variant_pat)); @@ -457,18 +444,11 @@ fn build_pat( db: &RootDatabase, module: hir::Module, var: ExtendedVariant, - prefer_no_std: bool, - prefer_prelude: bool, + cfg: ImportPathConfig, ) -> Option { match var { ExtendedVariant::Variant(var) => { - let path = mod_path_to_ast(&module.find_path( - db, - ModuleDef::from(var), - prefer_no_std, - prefer_prelude, - )?); - + let path = mod_path_to_ast(&module.find_path(db, ModuleDef::from(var), cfg)?); // FIXME: use HIR for this; it doesn't currently expose struct vs. tuple vs. unit variants though Some(match var.source(db)?.value.kind() { ast::StructKind::Tuple(field_list) => { diff --git a/crates/ide-assists/src/handlers/auto_import.rs b/crates/ide-assists/src/handlers/auto_import.rs index b90bccb48e..3bd003a267 100644 --- a/crates/ide-assists/src/handlers/auto_import.rs +++ b/crates/ide-assists/src/handlers/auto_import.rs @@ -1,6 +1,6 @@ use std::cmp::Reverse; -use hir::{db::HirDatabase, Module}; +use hir::{db::HirDatabase, ImportPathConfig, Module}; use ide_db::{ helpers::mod_path_to_ast, imports::{ @@ -90,14 +90,14 @@ use crate::{AssistContext, AssistId, AssistKind, Assists, GroupLabel}; // # pub mod std { pub mod collections { pub struct HashMap { } } } // ``` pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { + let cfg = ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }; + let (import_assets, syntax_under_caret) = find_importable_node(ctx)?; let mut proposed_imports: Vec<_> = import_assets - .search_for_imports( - &ctx.sema, - ctx.config.insert_use.prefix_kind, - ctx.config.prefer_no_std, - ctx.config.prefer_no_std, - ) + .search_for_imports(&ctx.sema, cfg, ctx.config.insert_use.prefix_kind) .collect(); if proposed_imports.is_empty() { return None; diff --git a/crates/ide-assists/src/handlers/bool_to_enum.rs b/crates/ide-assists/src/handlers/bool_to_enum.rs index 934d1f3b65..71436e6580 100644 --- a/crates/ide-assists/src/handlers/bool_to_enum.rs +++ b/crates/ide-assists/src/handlers/bool_to_enum.rs @@ -1,4 +1,4 @@ -use hir::ModuleDef; +use hir::{ImportPathConfig, ModuleDef}; use ide_db::{ assists::{AssistId, AssistKind}, defs::Definition, @@ -326,6 +326,11 @@ fn augment_references_with_imports( ) -> Vec { let mut visited_modules = FxHashSet::default(); + let cfg = ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }; + references .into_iter() .filter_map(|FileReference { range, name, .. }| { @@ -345,8 +350,7 @@ fn augment_references_with_imports( ctx.sema.db, ModuleDef::Module(*target_module), ctx.config.insert_use.prefix_kind, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, + cfg, ) .map(|mod_path| { make::path_concat(mod_path_to_ast(&mod_path), make::path_from_text("Bool")) diff --git a/crates/ide-assists/src/handlers/convert_into_to_from.rs b/crates/ide-assists/src/handlers/convert_into_to_from.rs index e0e2ac7585..be433c3333 100644 --- a/crates/ide-assists/src/handlers/convert_into_to_from.rs +++ b/crates/ide-assists/src/handlers/convert_into_to_from.rs @@ -1,3 +1,4 @@ +use hir::ImportPathConfig; use ide_db::{famous_defs::FamousDefs, helpers::mod_path_to_ast, traits::resolve_target_trait}; use syntax::ast::{self, AstNode, HasName}; @@ -43,19 +44,18 @@ pub(crate) fn convert_into_to_from(acc: &mut Assists, ctx: &AssistContext<'_>) - return None; } + let cfg = ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }; + let src_type_path = { let src_type_path = src_type.syntax().descendants().find_map(ast::Path::cast)?; let src_type_def = match ctx.sema.resolve_path(&src_type_path) { Some(hir::PathResolution::Def(module_def)) => module_def, _ => return None, }; - - mod_path_to_ast(&module.find_path( - ctx.db(), - src_type_def, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, - )?) + mod_path_to_ast(&module.find_path(ctx.db(), src_type_def, cfg)?) }; let dest_type = match &ast_trait { diff --git a/crates/ide-assists/src/handlers/convert_tuple_return_type_to_struct.rs b/crates/ide-assists/src/handlers/convert_tuple_return_type_to_struct.rs index 1f579d4221..241fc3b7a3 100644 --- a/crates/ide-assists/src/handlers/convert_tuple_return_type_to_struct.rs +++ b/crates/ide-assists/src/handlers/convert_tuple_return_type_to_struct.rs @@ -1,5 +1,5 @@ use either::Either; -use hir::ModuleDef; +use hir::{ImportPathConfig, ModuleDef}; use ide_db::{ assists::{AssistId, AssistKind}, defs::Definition, @@ -183,6 +183,11 @@ fn augment_references_with_imports( ) -> Vec<(ast::NameLike, Option<(ImportScope, ast::Path)>)> { let mut visited_modules = FxHashSet::default(); + let cfg = ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }; + references .iter() .filter_map(|FileReference { name, .. }| { @@ -205,8 +210,7 @@ fn augment_references_with_imports( ctx.sema.db, ModuleDef::Module(*target_module), ctx.config.insert_use.prefix_kind, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, + cfg, ) .map(|mod_path| { make::path_concat( diff --git a/crates/ide-assists/src/handlers/destructure_struct_binding.rs b/crates/ide-assists/src/handlers/destructure_struct_binding.rs index bdcefe0b4f..9adbdd220c 100644 --- a/crates/ide-assists/src/handlers/destructure_struct_binding.rs +++ b/crates/ide-assists/src/handlers/destructure_struct_binding.rs @@ -1,4 +1,4 @@ -use hir::HasVisibility; +use hir::{HasVisibility, ImportPathConfig}; use ide_db::{ assists::{AssistId, AssistKind}, defs::Definition, @@ -87,15 +87,15 @@ fn collect_data(ident_pat: ast::IdentPat, ctx: &AssistContext<'_>) -> Option) -> Op ctx.sema.db, ModuleDef::from(control_flow_enum), ctx.config.insert_use.prefix_kind, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, + ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }, ); if let Some(mod_path) = mod_path { diff --git a/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs b/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs index 2e4541b181..3c6d73b62e 100644 --- a/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs +++ b/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs @@ -1,7 +1,7 @@ use std::iter; use either::Either; -use hir::{Module, ModuleDef, Name, Variant}; +use hir::{ImportPathConfig, Module, ModuleDef, Name, Variant}; use ide_db::{ defs::Definition, helpers::mod_path_to_ast, @@ -390,8 +390,10 @@ fn process_references( ctx.sema.db, *enum_module_def, ctx.config.insert_use.prefix_kind, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, + ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }, ); if let Some(mut mod_path) = mod_path { mod_path.pop_segment(); diff --git a/crates/ide-assists/src/handlers/generate_deref.rs b/crates/ide-assists/src/handlers/generate_deref.rs index 54c320a39b..9a441fc5eb 100644 --- a/crates/ide-assists/src/handlers/generate_deref.rs +++ b/crates/ide-assists/src/handlers/generate_deref.rs @@ -1,6 +1,6 @@ use std::fmt::Display; -use hir::{ModPath, ModuleDef}; +use hir::{ImportPathConfig, ModPath, ModuleDef}; use ide_db::{famous_defs::FamousDefs, RootDatabase}; use syntax::{ ast::{self, HasName}, @@ -61,8 +61,10 @@ fn generate_record_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<( let trait_path = module.find_path( ctx.db(), ModuleDef::Trait(trait_), - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, + ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }, )?; let field_type = field.ty()?; @@ -106,8 +108,10 @@ fn generate_tuple_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<() let trait_path = module.find_path( ctx.db(), ModuleDef::Trait(trait_), - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, + ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }, )?; let field_type = field.ty()?; diff --git a/crates/ide-assists/src/handlers/generate_new.rs b/crates/ide-assists/src/handlers/generate_new.rs index 50342b0284..52007e0e29 100644 --- a/crates/ide-assists/src/handlers/generate_new.rs +++ b/crates/ide-assists/src/handlers/generate_new.rs @@ -1,3 +1,4 @@ +use hir::ImportPathConfig; use ide_db::{ imports::import_assets::item_for_path_search, use_trivial_constructor::use_trivial_constructor, }; @@ -61,8 +62,10 @@ pub(crate) fn generate_new(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option let type_path = current_module.find_path( ctx.sema.db, item_for_path_search(ctx.sema.db, item_in_ns)?, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, + ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }, )?; let expr = use_trivial_constructor( diff --git a/crates/ide-assists/src/handlers/qualify_method_call.rs b/crates/ide-assists/src/handlers/qualify_method_call.rs index 196b33e0f6..5d1140d57a 100644 --- a/crates/ide-assists/src/handlers/qualify_method_call.rs +++ b/crates/ide-assists/src/handlers/qualify_method_call.rs @@ -1,4 +1,7 @@ -use hir::{db::HirDatabase, AsAssocItem, AssocItem, AssocItemContainer, ItemInNs, ModuleDef}; +use hir::{ + db::HirDatabase, AsAssocItem, AssocItem, AssocItemContainer, ImportPathConfig, ItemInNs, + ModuleDef, +}; use ide_db::assists::{AssistId, AssistKind}; use syntax::{ast, AstNode}; @@ -47,8 +50,10 @@ pub(crate) fn qualify_method_call(acc: &mut Assists, ctx: &AssistContext<'_>) -> let receiver_path = current_module.find_path( ctx.sema.db, item_for_path_search(ctx.sema.db, item_in_ns)?, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, + ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }, )?; let qualify_candidate = QualifyCandidate::ImplMethod(ctx.sema.db, call, resolved_call); diff --git a/crates/ide-assists/src/handlers/qualify_path.rs b/crates/ide-assists/src/handlers/qualify_path.rs index 63a09ce2e9..978b719c30 100644 --- a/crates/ide-assists/src/handlers/qualify_path.rs +++ b/crates/ide-assists/src/handlers/qualify_path.rs @@ -1,6 +1,6 @@ use std::iter; -use hir::AsAssocItem; +use hir::{AsAssocItem, ImportPathConfig}; use ide_db::RootDatabase; use ide_db::{ helpers::mod_path_to_ast, @@ -37,9 +37,13 @@ use crate::{ // ``` pub(crate) fn qualify_path(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { let (import_assets, syntax_under_caret) = find_importable_node(ctx)?; - let mut proposed_imports: Vec<_> = import_assets - .search_for_relative_paths(&ctx.sema, ctx.config.prefer_no_std, ctx.config.prefer_prelude) - .collect(); + let cfg = ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }; + + let mut proposed_imports: Vec<_> = + import_assets.search_for_relative_paths(&ctx.sema, cfg).collect(); if proposed_imports.is_empty() { return None; } diff --git a/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs b/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs index 8cc7c883f4..e792debaa5 100644 --- a/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs +++ b/crates/ide-assists/src/handlers/replace_derive_with_manual_impl.rs @@ -1,4 +1,4 @@ -use hir::{InFile, MacroFileIdExt, ModuleDef}; +use hir::{ImportPathConfig, InFile, MacroFileIdExt, ModuleDef}; use ide_db::{helpers::mod_path_to_ast, imports::import_assets::NameToImport, items_locator}; use itertools::Itertools; use syntax::{ @@ -86,8 +86,10 @@ pub(crate) fn replace_derive_with_manual_impl( .find_path( ctx.sema.db, hir::ModuleDef::Trait(trait_), - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, + ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }, ) .as_ref() .map(mod_path_to_ast) diff --git a/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs b/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs index cb9de32d9c..188165e776 100644 --- a/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs +++ b/crates/ide-assists/src/handlers/replace_qualified_name_with_use.rs @@ -1,4 +1,4 @@ -use hir::AsAssocItem; +use hir::{AsAssocItem, ImportPathConfig}; use ide_db::{ helpers::mod_path_to_ast, imports::insert_use::{insert_use, ImportScope}, @@ -67,8 +67,10 @@ pub(crate) fn replace_qualified_name_with_use( ctx.sema.db, module, ctx.config.insert_use.prefix_kind, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, + ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }, ) }) .flatten(); diff --git a/crates/ide-assists/src/handlers/term_search.rs b/crates/ide-assists/src/handlers/term_search.rs index d0c6ae2198..ffd1508ccb 100644 --- a/crates/ide-assists/src/handlers/term_search.rs +++ b/crates/ide-assists/src/handlers/term_search.rs @@ -1,5 +1,8 @@ //! Term search assist -use hir::term_search::{TermSearchConfig, TermSearchCtx}; +use hir::{ + term_search::{TermSearchConfig, TermSearchCtx}, + ImportPathConfig, +}; use ide_db::{ assists::{AssistId, AssistKind, GroupLabel}, famous_defs::FamousDefs, @@ -50,8 +53,10 @@ pub(crate) fn term_search(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option< path.gen_source_code( &scope, &mut formatter, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, + ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }, ) .ok() }) diff --git a/crates/ide-completion/src/completions.rs b/crates/ide-completion/src/completions.rs index 69b0289fc1..11ffc8bc44 100644 --- a/crates/ide-completion/src/completions.rs +++ b/crates/ide-completion/src/completions.rs @@ -24,7 +24,7 @@ pub(crate) mod vis; use std::iter; -use hir::{known, HasAttrs, ScopeDef, Variant}; +use hir::{known, HasAttrs, ImportPathConfig, ScopeDef, Variant}; use ide_db::{imports::import_assets::LocatedImport, RootDatabase, SymbolKind}; use syntax::{ast, SmolStr}; @@ -636,8 +636,10 @@ fn enum_variants_with_paths( if let Some(path) = ctx.module.find_path( ctx.db, hir::ModuleDef::from(variant), - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, + ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }, ) { // Variants with trivial paths are already added by the existing completion logic, // so we should avoid adding these twice diff --git a/crates/ide-completion/src/completions/expr.rs b/crates/ide-completion/src/completions/expr.rs index f350c2743c..ddb1aeb371 100644 --- a/crates/ide-completion/src/completions/expr.rs +++ b/crates/ide-completion/src/completions/expr.rs @@ -1,6 +1,6 @@ //! Completion of names from the current scope in expression position. -use hir::ScopeDef; +use hir::{ImportPathConfig, ScopeDef}; use syntax::ast; use crate::{ @@ -174,8 +174,10 @@ pub(crate) fn complete_expr_path( .find_path( ctx.db, hir::ModuleDef::from(strukt), - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, + ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }, ) .filter(|it| it.len() > 1); @@ -197,8 +199,10 @@ pub(crate) fn complete_expr_path( .find_path( ctx.db, hir::ModuleDef::from(un), - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, + ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }, ) .filter(|it| it.len() > 1); diff --git a/crates/ide-completion/src/completions/flyimport.rs b/crates/ide-completion/src/completions/flyimport.rs index bf6747d71b..d5a4e9ecdc 100644 --- a/crates/ide-completion/src/completions/flyimport.rs +++ b/crates/ide-completion/src/completions/flyimport.rs @@ -1,5 +1,5 @@ //! See [`import_on_the_fly`]. -use hir::{ItemInNs, ModuleDef}; +use hir::{ImportPathConfig, ItemInNs, ModuleDef}; use ide_db::imports::{ import_assets::{ImportAssets, LocatedImport}, insert_use::ImportScope, @@ -257,13 +257,13 @@ fn import_on_the_fly( }; let user_input_lowercased = potential_import_name.to_lowercase(); + let import_cfg = ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }; + import_assets - .search_for_imports( - &ctx.sema, - ctx.config.insert_use.prefix_kind, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, - ) + .search_for_imports(&ctx.sema, import_cfg, ctx.config.insert_use.prefix_kind) .filter(ns_filter) .filter(|import| { let original_item = &import.original_item; @@ -308,13 +308,13 @@ fn import_on_the_fly_pat_( }; let user_input_lowercased = potential_import_name.to_lowercase(); + let cfg = ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }; + import_assets - .search_for_imports( - &ctx.sema, - ctx.config.insert_use.prefix_kind, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, - ) + .search_for_imports(&ctx.sema, cfg, ctx.config.insert_use.prefix_kind) .filter(ns_filter) .filter(|import| { let original_item = &import.original_item; @@ -355,13 +355,13 @@ fn import_on_the_fly_method( let user_input_lowercased = potential_import_name.to_lowercase(); + let cfg = ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }; + import_assets - .search_for_imports( - &ctx.sema, - ctx.config.insert_use.prefix_kind, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, - ) + .search_for_imports(&ctx.sema, cfg, ctx.config.insert_use.prefix_kind) .filter(|import| { !ctx.is_item_hidden(&import.item_to_import) && !ctx.is_item_hidden(&import.original_item) diff --git a/crates/ide-completion/src/completions/postfix.rs b/crates/ide-completion/src/completions/postfix.rs index c14da34874..a230edd39b 100644 --- a/crates/ide-completion/src/completions/postfix.rs +++ b/crates/ide-completion/src/completions/postfix.rs @@ -2,7 +2,7 @@ mod format_like; -use hir::ItemInNs; +use hir::{ImportPathConfig, ItemInNs}; use ide_db::{ documentation::{Documentation, HasDocs}, imports::insert_use::ImportScope, @@ -60,15 +60,17 @@ pub(crate) fn complete_postfix( None => return, }; + let cfg = ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }; + if let Some(drop_trait) = ctx.famous_defs().core_ops_Drop() { if receiver_ty.impls_trait(ctx.db, drop_trait, &[]) { if let Some(drop_fn) = ctx.famous_defs().core_mem_drop() { - if let Some(path) = ctx.module.find_path( - ctx.db, - ItemInNs::Values(drop_fn.into()), - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, - ) { + if let Some(path) = + ctx.module.find_path(ctx.db, ItemInNs::Values(drop_fn.into()), cfg) + { cov_mark::hit!(postfix_drop_completion); let mut item = postfix_snippet( "drop", diff --git a/crates/ide-completion/src/lib.rs b/crates/ide-completion/src/lib.rs index 4165dd48af..2b9e46a70f 100644 --- a/crates/ide-completion/src/lib.rs +++ b/crates/ide-completion/src/lib.rs @@ -12,6 +12,7 @@ mod snippet; #[cfg(test)] mod tests; +use hir::ImportPathConfig; use ide_db::{ base_db::FilePosition, helpers::mod_path_to_ast, @@ -251,6 +252,11 @@ pub fn resolve_completion_edits( let new_ast = scope.clone_for_update(); let mut import_insert = TextEdit::builder(); + let cfg = ImportPathConfig { + prefer_no_std: config.prefer_no_std, + prefer_prelude: config.prefer_prelude, + }; + imports.into_iter().for_each(|(full_import_path, imported_name)| { let items_with_name = items_locator::items_with_name( &sema, @@ -264,8 +270,7 @@ pub fn resolve_completion_edits( db, candidate, config.insert_use.prefix_kind, - config.prefer_no_std, - config.prefer_prelude, + cfg, ) }) .find(|mod_path| mod_path.display(db).to_string() == full_import_path); diff --git a/crates/ide-completion/src/render.rs b/crates/ide-completion/src/render.rs index d7b27f8b3b..8f56379073 100644 --- a/crates/ide-completion/src/render.rs +++ b/crates/ide-completion/src/render.rs @@ -10,7 +10,7 @@ pub(crate) mod type_alias; pub(crate) mod union_literal; pub(crate) mod variant; -use hir::{AsAssocItem, HasAttrs, HirDisplay, ModuleDef, ScopeDef, Type}; +use hir::{AsAssocItem, HasAttrs, HirDisplay, ImportPathConfig, ModuleDef, ScopeDef, Type}; use ide_db::{ documentation::{Documentation, HasDocs}, helpers::item_name, @@ -295,14 +295,12 @@ pub(crate) fn render_expr( .unwrap_or_else(|| String::from("...")) }; - let label = expr - .gen_source_code( - &ctx.scope, - &mut label_formatter, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, - ) - .ok()?; + let cfg = ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }; + + let label = expr.gen_source_code(&ctx.scope, &mut label_formatter, cfg).ok()?; let source_range = match ctx.original_token.parent() { Some(node) => match node.ancestors().find_map(ast::Path::cast) { @@ -314,16 +312,8 @@ pub(crate) fn render_expr( let mut item = CompletionItem::new(CompletionItemKind::Expression, source_range, label); - let snippet = format!( - "{}$0", - expr.gen_source_code( - &ctx.scope, - &mut snippet_formatter, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude - ) - .ok()? - ); + let snippet = + format!("{}$0", expr.gen_source_code(&ctx.scope, &mut snippet_formatter, cfg).ok()?); let edit = TextEdit::replace(source_range, snippet); item.snippet_edit(ctx.config.snippet_cap?, edit); item.documentation(Documentation::new(String::from("Autogenerated expression by term search"))); @@ -333,12 +323,7 @@ pub(crate) fn render_expr( }); for trait_ in expr.traits_used(ctx.db) { let trait_item = hir::ItemInNs::from(hir::ModuleDef::from(trait_)); - let Some(path) = ctx.module.find_path( - ctx.db, - trait_item, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, - ) else { + let Some(path) = ctx.module.find_path(ctx.db, trait_item, cfg) else { continue; }; diff --git a/crates/ide-completion/src/snippet.rs b/crates/ide-completion/src/snippet.rs index 37bb6cfef0..07836040b4 100644 --- a/crates/ide-completion/src/snippet.rs +++ b/crates/ide-completion/src/snippet.rs @@ -100,6 +100,7 @@ // } // ---- +use hir::ImportPathConfig; use ide_db::imports::import_assets::LocatedImport; use itertools::Itertools; use syntax::{ast, AstNode, GreenNode, SyntaxNode}; @@ -168,6 +169,11 @@ impl Snippet { } fn import_edits(ctx: &CompletionContext<'_>, requires: &[GreenNode]) -> Option> { + let import_cfg = ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }; + let resolve = |import: &GreenNode| { let path = ast::Path::cast(SyntaxNode::new_root(import.clone()))?; let item = match ctx.scope.speculative_resolve(&path)? { @@ -178,8 +184,7 @@ fn import_edits(ctx: &CompletionContext<'_>, requires: &[GreenNode]) -> Option 1).then(|| LocatedImport::new(path.clone(), item, item))) }; diff --git a/crates/ide-completion/src/tests.rs b/crates/ide-completion/src/tests.rs index 70e0aa4e9a..c1a67315b7 100644 --- a/crates/ide-completion/src/tests.rs +++ b/crates/ide-completion/src/tests.rs @@ -66,11 +66,10 @@ pub(crate) const TEST_CONFIG: CompletionConfig = CompletionConfig { enable_self_on_the_fly: true, enable_private_editable: false, enable_term_search: true, + term_search_fuel: 200, full_function_signatures: false, callable: Some(CallableSnippets::FillArguments), snippet_cap: SnippetCap::new(true), - prefer_no_std: false, - prefer_prelude: true, insert_use: InsertUseConfig { granularity: ImportGranularity::Crate, prefix_kind: PrefixKind::Plain, @@ -78,9 +77,10 @@ pub(crate) const TEST_CONFIG: CompletionConfig = CompletionConfig { group: true, skip_glob_imports: true, }, + prefer_no_std: false, + prefer_prelude: true, snippets: Vec::new(), limit: None, - term_search_fuel: 200, }; pub(crate) fn completion_list(ra_fixture: &str) -> String { diff --git a/crates/ide-db/src/imports/import_assets.rs b/crates/ide-db/src/imports/import_assets.rs index 530020f116..6e708182d0 100644 --- a/crates/ide-db/src/imports/import_assets.rs +++ b/crates/ide-db/src/imports/import_assets.rs @@ -1,8 +1,8 @@ //! Look up accessible paths for items. use hir::{ - db::HirDatabase, AsAssocItem, AssocItem, AssocItemContainer, Crate, HasCrate, ItemInNs, - ModPath, Module, ModuleDef, Name, PathResolution, PrefixKind, ScopeDef, Semantics, + db::HirDatabase, AsAssocItem, AssocItem, AssocItemContainer, Crate, HasCrate, ImportPathConfig, + ItemInNs, ModPath, Module, ModuleDef, Name, PathResolution, PrefixKind, ScopeDef, Semantics, SemanticsScope, Trait, Type, }; use itertools::{EitherOrBoth, Itertools}; @@ -205,24 +205,22 @@ impl ImportAssets { pub fn search_for_imports( &self, sema: &Semantics<'_, RootDatabase>, + cfg: ImportPathConfig, prefix_kind: PrefixKind, - prefer_no_std: bool, - prefer_prelude: bool, ) -> impl Iterator { let _p = tracing::span!(tracing::Level::INFO, "ImportAssets::search_for_imports").entered(); - self.search_for(sema, Some(prefix_kind), prefer_no_std, prefer_prelude) + self.search_for(sema, Some(prefix_kind), cfg) } /// This may return non-absolute paths if a part of the returned path is already imported into scope. pub fn search_for_relative_paths( &self, sema: &Semantics<'_, RootDatabase>, - prefer_no_std: bool, - prefer_prelude: bool, + cfg: ImportPathConfig, ) -> impl Iterator { let _p = tracing::span!(tracing::Level::INFO, "ImportAssets::search_for_relative_paths") .entered(); - self.search_for(sema, None, prefer_no_std, prefer_prelude) + self.search_for(sema, None, cfg) } /// Requires imports to by prefix instead of fuzzily. @@ -259,8 +257,7 @@ impl ImportAssets { &self, sema: &Semantics<'_, RootDatabase>, prefixed: Option, - prefer_no_std: bool, - prefer_prelude: bool, + cfg: ImportPathConfig, ) -> impl Iterator { let _p = tracing::span!(tracing::Level::INFO, "ImportAssets::search_for").entered(); @@ -277,8 +274,7 @@ impl ImportAssets { item_for_path_search(sema.db, item)?, &self.module_with_candidate, prefixed, - prefer_no_std, - prefer_prelude, + cfg, ) .filter(|path| path.len() > 1) }; @@ -634,19 +630,12 @@ fn get_mod_path( item_to_search: ItemInNs, module_with_candidate: &Module, prefixed: Option, - prefer_no_std: bool, - prefer_prelude: bool, + cfg: ImportPathConfig, ) -> Option { if let Some(prefix_kind) = prefixed { - module_with_candidate.find_use_path( - db, - item_to_search, - prefix_kind, - prefer_no_std, - prefer_prelude, - ) + module_with_candidate.find_use_path(db, item_to_search, prefix_kind, cfg) } else { - module_with_candidate.find_path(db, item_to_search, prefer_no_std, prefer_prelude) + module_with_candidate.find_path(db, item_to_search, cfg) } } diff --git a/crates/ide-db/src/path_transform.rs b/crates/ide-db/src/path_transform.rs index 6f4f97e0b8..7c11dd3e2a 100644 --- a/crates/ide-db/src/path_transform.rs +++ b/crates/ide-db/src/path_transform.rs @@ -2,7 +2,7 @@ use crate::helpers::mod_path_to_ast; use either::Either; -use hir::{AsAssocItem, HirDisplay, ModuleDef, SemanticsScope}; +use hir::{AsAssocItem, HirDisplay, ImportPathConfig, ModuleDef, SemanticsScope}; use itertools::Itertools; use rustc_hash::FxHashMap; use syntax::{ @@ -308,11 +308,12 @@ impl Ctx<'_> { parent.segment()?.name_ref()?, ) .and_then(|trait_ref| { + let cfg = + ImportPathConfig { prefer_no_std: false, prefer_prelude: true }; let found_path = self.target_module.find_path( self.source_scope.db.upcast(), hir::ModuleDef::Trait(trait_ref), - false, - true, + cfg, )?; match make::ty_path(mod_path_to_ast(&found_path)) { ast::Type::PathType(path_ty) => Some(path_ty), @@ -347,12 +348,9 @@ impl Ctx<'_> { } } - let found_path = self.target_module.find_path( - self.source_scope.db.upcast(), - def, - false, - true, - )?; + let cfg = ImportPathConfig { prefer_no_std: false, prefer_prelude: true }; + let found_path = + self.target_module.find_path(self.source_scope.db.upcast(), def, cfg)?; 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(segment) = res.segment() { @@ -385,11 +383,11 @@ impl Ctx<'_> { if let Some(adt) = ty.as_adt() { if let ast::Type::PathType(path_ty) = &ast_ty { + let cfg = ImportPathConfig { prefer_no_std: false, prefer_prelude: true }; let found_path = self.target_module.find_path( self.source_scope.db.upcast(), ModuleDef::from(adt), - false, - true, + cfg, )?; if let Some(qual) = mod_path_to_ast(&found_path).qualifier() { diff --git a/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs b/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs index 71958bc866..132b93df10 100644 --- a/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs +++ b/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs @@ -1,7 +1,7 @@ //! This diagnostic provides an assist for creating a struct definition from a JSON //! example. -use hir::{PathResolution, Semantics}; +use hir::{ImportPathConfig, PathResolution, Semantics}; use ide_db::{ base_db::{FileId, FileRange}, helpers::mod_path_to_ast, @@ -142,14 +142,19 @@ pub(crate) fn json_in_items( ImportScope::Block(it) => ImportScope::Block(scb.make_mut(it)), }; let current_module = semantics_scope.module(); + + let cfg = ImportPathConfig { + prefer_no_std: config.prefer_no_std, + prefer_prelude: config.prefer_prelude, + }; + if !scope_has("Serialize") { if let Some(PathResolution::Def(it)) = serialize_resolved { if let Some(it) = current_module.find_use_path( sema.db, it, config.insert_use.prefix_kind, - config.prefer_no_std, - config.prefer_prelude, + cfg, ) { insert_use(&scope, mod_path_to_ast(&it), &config.insert_use); } @@ -161,8 +166,7 @@ pub(crate) fn json_in_items( sema.db, it, config.insert_use.prefix_kind, - config.prefer_no_std, - config.prefer_prelude, + cfg, ) { insert_use(&scope, mod_path_to_ast(&it), &config.insert_use); } diff --git a/crates/ide-diagnostics/src/handlers/missing_fields.rs b/crates/ide-diagnostics/src/handlers/missing_fields.rs index ed9094f1f3..9eff84b898 100644 --- a/crates/ide-diagnostics/src/handlers/missing_fields.rs +++ b/crates/ide-diagnostics/src/handlers/missing_fields.rs @@ -1,7 +1,7 @@ use either::Either; use hir::{ db::{ExpandDatabase, HirDatabase}, - known, AssocItem, HirDisplay, HirFileIdExt, InFile, Type, + known, AssocItem, HirDisplay, HirFileIdExt, ImportPathConfig, InFile, Type, }; use ide_db::{ assists::Assist, famous_defs::FamousDefs, imports::import_assets::item_for_path_search, @@ -125,8 +125,10 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option, d: &hir::TypedHole) -> Option path.gen_source_code( &scope, &mut formatter, - ctx.config.prefer_no_std, - ctx.config.prefer_prelude, + ImportPathConfig { + prefer_no_std: ctx.config.prefer_no_std, + prefer_prelude: ctx.config.prefer_prelude, + }, ) .ok() }) diff --git a/crates/ide-ssr/src/matching.rs b/crates/ide-ssr/src/matching.rs index 99df3f2563..cf7e7e08bc 100644 --- a/crates/ide-ssr/src/matching.rs +++ b/crates/ide-ssr/src/matching.rs @@ -6,7 +6,7 @@ use crate::{ resolving::{ResolvedPattern, ResolvedRule, UfcsCallInfo}, SsrMatches, }; -use hir::Semantics; +use hir::{ImportPathConfig, Semantics}; use ide_db::{base_db::FileRange, FxHashMap}; use std::{cell::Cell, iter::Peekable}; use syntax::{ @@ -663,10 +663,10 @@ impl Match { .module(); for (path, resolved_path) in &template.resolved_paths { if let hir::PathResolution::Def(module_def) = resolved_path.resolution { - let mod_path = - module.find_path(sema.db, module_def, false, true).ok_or_else(|| { - match_error!("Failed to render template path `{}` at match location") - })?; + let cfg = ImportPathConfig { prefer_no_std: false, prefer_prelude: true }; + let mod_path = module.find_path(sema.db, module_def, cfg).ok_or_else(|| { + match_error!("Failed to render template path `{}` at match location") + })?; self.rendered_template_paths.insert(path.clone(), mod_path); } } diff --git a/crates/rust-analyzer/src/cli/analysis_stats.rs b/crates/rust-analyzer/src/cli/analysis_stats.rs index 5208aa9bf0..bded41932c 100644 --- a/crates/rust-analyzer/src/cli/analysis_stats.rs +++ b/crates/rust-analyzer/src/cli/analysis_stats.rs @@ -8,7 +8,8 @@ use std::{ use hir::{ db::{DefDatabase, ExpandDatabase, HirDatabase}, - Adt, AssocItem, Crate, DefWithBody, HasSource, HirDisplay, HirFileIdExt, ModuleDef, Name, + Adt, AssocItem, Crate, DefWithBody, HasSource, HirDisplay, HirFileIdExt, ImportPathConfig, + ModuleDef, Name, }; use hir_def::{ body::{BodySourceMap, SyntheticSyntax}, @@ -438,8 +439,13 @@ impl flags::AnalysisStats { let mut formatter = |_: &hir::Type| todo.clone(); let mut syntax_hit_found = false; for term in found_terms { - let generated = - term.gen_source_code(&scope, &mut formatter, false, true).unwrap(); + let generated = term + .gen_source_code( + &scope, + &mut formatter, + ImportPathConfig { prefer_no_std: false, prefer_prelude: true }, + ) + .unwrap(); syntax_hit_found |= trim(&original_text) == trim(&generated); // Validate if type-checks diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs index 6c332ae1cb..a8d1e72aed 100644 --- a/crates/rust-analyzer/src/config.rs +++ b/crates/rust-analyzer/src/config.rs @@ -1031,6 +1031,8 @@ impl Config { && completion_item_edit_resolve(&self.caps), enable_self_on_the_fly: self.completion_autoself_enable(source_root).to_owned(), enable_private_editable: self.completion_privateEditable_enable(source_root).to_owned(), + enable_term_search: self.completion_termSearch_enable(source_root).to_owned(), + term_search_fuel: self.completion_termSearch_fuel(source_root).to_owned() as u64, full_function_signatures: self .completion_fullFunctionSignatures_enable(source_root) .to_owned(), @@ -1039,8 +1041,6 @@ impl Config { CallableCompletionDef::AddParentheses => Some(CallableSnippets::AddParentheses), CallableCompletionDef::None => None, }, - insert_use: self.insert_use_config(source_root), - prefer_no_std: self.imports_preferNoStd(source_root).to_owned(), snippet_cap: SnippetCap::new(try_or_def!( self.caps .text_document @@ -1051,11 +1051,11 @@ impl Config { .as_ref()? .snippet_support? )), + insert_use: self.insert_use_config(source_root), + prefer_no_std: self.imports_preferNoStd(source_root).to_owned(), + prefer_prelude: self.imports_preferPrelude(source_root).to_owned(), snippets: self.snippets.clone().to_vec(), limit: self.completion_limit(source_root).to_owned(), - enable_term_search: self.completion_termSearch_enable(source_root).to_owned(), - term_search_fuel: self.completion_termSearch_fuel(source_root).to_owned() as u64, - prefer_prelude: self.imports_preferPrelude(source_root).to_owned(), } } diff --git a/crates/rust-analyzer/src/integrated_benchmarks.rs b/crates/rust-analyzer/src/integrated_benchmarks.rs index cc83d6246b..5d617780b6 100644 --- a/crates/rust-analyzer/src/integrated_benchmarks.rs +++ b/crates/rust-analyzer/src/integrated_benchmarks.rs @@ -139,6 +139,7 @@ fn integrated_completion_benchmark() { enable_self_on_the_fly: true, enable_private_editable: true, enable_term_search: true, + term_search_fuel: 200, full_function_signatures: false, callable: Some(CallableSnippets::FillArguments), snippet_cap: SnippetCap::new(true), @@ -149,11 +150,10 @@ fn integrated_completion_benchmark() { group: true, skip_glob_imports: true, }, - snippets: Vec::new(), prefer_no_std: false, prefer_prelude: true, + snippets: Vec::new(), limit: None, - term_search_fuel: 200, }; let position = FilePosition { file_id, offset: TextSize::try_from(completion_offset).unwrap() }; @@ -184,6 +184,7 @@ fn integrated_completion_benchmark() { enable_self_on_the_fly: true, enable_private_editable: true, enable_term_search: true, + term_search_fuel: 200, full_function_signatures: false, callable: Some(CallableSnippets::FillArguments), snippet_cap: SnippetCap::new(true), @@ -194,11 +195,10 @@ fn integrated_completion_benchmark() { group: true, skip_glob_imports: true, }, - snippets: Vec::new(), prefer_no_std: false, prefer_prelude: true, + snippets: Vec::new(), limit: None, - term_search_fuel: 200, }; let position = FilePosition { file_id, offset: TextSize::try_from(completion_offset).unwrap() }; @@ -227,6 +227,7 @@ fn integrated_completion_benchmark() { enable_self_on_the_fly: true, enable_private_editable: true, enable_term_search: true, + term_search_fuel: 200, full_function_signatures: false, callable: Some(CallableSnippets::FillArguments), snippet_cap: SnippetCap::new(true), @@ -237,11 +238,10 @@ fn integrated_completion_benchmark() { group: true, skip_glob_imports: true, }, - snippets: Vec::new(), prefer_no_std: false, prefer_prelude: true, + snippets: Vec::new(), limit: None, - term_search_fuel: 200, }; let position = FilePosition { file_id, offset: TextSize::try_from(completion_offset).unwrap() };