Add config to unconditionally prefer core imports over std

Fixes https://github.com/rust-lang/rust-analyzer/issues/12979
This commit is contained in:
Lukas Wirth 2022-09-09 20:04:56 +02:00
parent 6909556435
commit 7d19971666
33 changed files with 156 additions and 43 deletions

View file

@ -16,9 +16,14 @@ use crate::{
/// Find a path that can be used to refer to a certain item. This can depend on /// Find a path that can be used to refer to a certain item. This can depend on
/// *from where* you're referring to the item, hence the `from` parameter. /// *from where* you're referring to the item, hence the `from` parameter.
pub fn find_path(db: &dyn DefDatabase, item: ItemInNs, from: ModuleId) -> Option<ModPath> { pub fn find_path(
db: &dyn DefDatabase,
item: ItemInNs,
from: ModuleId,
prefer_core: bool,
) -> Option<ModPath> {
let _p = profile::span("find_path"); let _p = profile::span("find_path");
find_path_inner(db, item, from, None) find_path_inner(db, item, from, None, prefer_core)
} }
pub fn find_path_prefixed( pub fn find_path_prefixed(
@ -26,9 +31,10 @@ pub fn find_path_prefixed(
item: ItemInNs, item: ItemInNs,
from: ModuleId, from: ModuleId,
prefix_kind: PrefixKind, prefix_kind: PrefixKind,
prefer_core: 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)) find_path_inner(db, item, from, Some(prefix_kind), prefer_core)
} }
const MAX_PATH_LEN: usize = 15; const MAX_PATH_LEN: usize = 15;
@ -100,12 +106,22 @@ fn find_path_inner(
item: ItemInNs, item: ItemInNs,
from: ModuleId, from: ModuleId,
prefixed: Option<PrefixKind>, prefixed: Option<PrefixKind>,
prefer_core: bool,
) -> Option<ModPath> { ) -> Option<ModPath> {
// FIXME: Do fast path for std/core libs? // FIXME: Do fast path for std/core libs?
let mut visited_modules = FxHashSet::default(); let mut visited_modules = FxHashSet::default();
let def_map = from.def_map(db); let def_map = from.def_map(db);
find_path_inner_(db, &def_map, from, item, MAX_PATH_LEN, prefixed, &mut visited_modules) find_path_inner_(
db,
&def_map,
from,
item,
MAX_PATH_LEN,
prefixed,
&mut visited_modules,
prefer_core,
)
} }
fn find_path_inner_( fn find_path_inner_(
@ -116,6 +132,7 @@ fn find_path_inner_(
max_len: usize, max_len: usize,
mut prefixed: Option<PrefixKind>, mut prefixed: Option<PrefixKind>,
visited_modules: &mut FxHashSet<ModuleId>, visited_modules: &mut FxHashSet<ModuleId>,
prefer_core: bool,
) -> Option<ModPath> { ) -> Option<ModPath> {
if max_len == 0 { if max_len == 0 {
return None; return None;
@ -191,7 +208,9 @@ fn find_path_inner_(
// Recursive case: // Recursive case:
// - if the item is an enum variant, refer to it via the enum // - if the item is an enum variant, refer to it via the enum
if let Some(ModuleDefId::EnumVariantId(variant)) = item.as_module_def_id() { if let Some(ModuleDefId::EnumVariantId(variant)) = item.as_module_def_id() {
if let Some(mut path) = find_path(db, ItemInNs::Types(variant.parent.into()), from) { if let Some(mut path) =
find_path(db, ItemInNs::Types(variant.parent.into()), from, prefer_core)
{
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());
return Some(path); return Some(path);
@ -202,7 +221,7 @@ fn find_path_inner_(
} }
// - otherwise, look for modules containing (reexporting) it and import it from one of those // - otherwise, look for modules containing (reexporting) it and import it from one of those
let prefer_no_std = db.crate_supports_no_std(crate_root.krate); let prefer_no_std = prefer_core || db.crate_supports_no_std(crate_root.krate);
let mut best_path = None; let mut best_path = None;
let mut best_path_len = max_len; let mut best_path_len = max_len;
@ -223,6 +242,7 @@ fn find_path_inner_(
best_path_len - 1, best_path_len - 1,
prefixed, prefixed,
visited_modules, visited_modules,
prefer_core,
) { ) {
path.push_segment(name); path.push_segment(name);
@ -253,6 +273,7 @@ fn find_path_inner_(
best_path_len - 1, best_path_len - 1,
prefixed, prefixed,
visited_modules, visited_modules,
prefer_core,
)?; )?;
cov_mark::hit!(partially_imported); cov_mark::hit!(partially_imported);
path.push_segment(info.path.segments.last()?.clone()); path.push_segment(info.path.segments.last()?.clone());
@ -428,7 +449,8 @@ mod tests {
.take_types() .take_types()
.unwrap(); .unwrap();
let found_path = find_path_inner(&db, ItemInNs::Types(resolved), module, prefix_kind); let found_path =
find_path_inner(&db, ItemInNs::Types(resolved), module, prefix_kind, false);
assert_eq!(found_path, Some(mod_path), "{:?}", prefix_kind); assert_eq!(found_path, Some(mod_path), "{:?}", prefix_kind);
} }

View file

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

View file

@ -582,8 +582,13 @@ impl Module {
/// 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
/// this module, if possible. /// this module, if possible.
pub fn find_use_path(self, db: &dyn DefDatabase, item: impl Into<ItemInNs>) -> Option<ModPath> { pub fn find_use_path(
hir_def::find_path::find_path(db, item.into().into(), self.into()) self,
db: &dyn DefDatabase,
item: impl Into<ItemInNs>,
prefer_core: bool,
) -> Option<ModPath> {
hir_def::find_path::find_path(db, item.into().into(), self.into(), prefer_core)
} }
/// 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
@ -593,8 +598,15 @@ impl Module {
db: &dyn DefDatabase, db: &dyn DefDatabase,
item: impl Into<ItemInNs>, item: impl Into<ItemInNs>,
prefix_kind: PrefixKind, prefix_kind: PrefixKind,
prefer_core: bool,
) -> Option<ModPath> { ) -> Option<ModPath> {
hir_def::find_path::find_path_prefixed(db, item.into().into(), self.into(), prefix_kind) hir_def::find_path::find_path_prefixed(
db,
item.into().into(),
self.into(),
prefix_kind,
prefer_core,
)
} }
} }

View file

@ -13,4 +13,5 @@ pub struct AssistConfig {
pub snippet_cap: Option<SnippetCap>, pub snippet_cap: Option<SnippetCap>,
pub allowed: Option<Vec<AssistKind>>, pub allowed: Option<Vec<AssistKind>>,
pub insert_use: InsertUseConfig, pub insert_use: InsertUseConfig,
pub prefer_core: bool,
} }

View file

@ -87,7 +87,7 @@ 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)?, build_pat(ctx.db(), module, variant, ctx.config.prefer_core)?,
variant.should_be_hidden(ctx.db(), module.krate()), variant.should_be_hidden(ctx.db(), module.krate()),
)) ))
}) })
@ -132,8 +132,9 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>)
let is_hidden = variants let is_hidden = variants
.iter() .iter()
.any(|variant| variant.should_be_hidden(ctx.db(), module.krate())); .any(|variant| variant.should_be_hidden(ctx.db(), module.krate()));
let patterns = let patterns = variants.into_iter().filter_map(|variant| {
variants.into_iter().filter_map(|variant| build_pat(ctx.db(), module, variant)); build_pat(ctx.db(), module, variant, ctx.config.prefer_core)
});
(ast::Pat::from(make::tuple_pat(patterns)), is_hidden) (ast::Pat::from(make::tuple_pat(patterns)), is_hidden)
}) })
@ -349,10 +350,16 @@ fn resolve_tuple_of_enum_def(
.collect() .collect()
} }
fn build_pat(db: &RootDatabase, module: hir::Module, var: ExtendedVariant) -> Option<ast::Pat> { fn build_pat(
db: &RootDatabase,
module: hir::Module,
var: ExtendedVariant,
prefer_core: bool,
) -> Option<ast::Pat> {
match var { match var {
ExtendedVariant::Variant(var) => { ExtendedVariant::Variant(var) => {
let path = mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var))?); let path =
mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var), prefer_core)?);
// 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
let pat: ast::Pat = match var.source(db)?.value.kind() { let pat: ast::Pat = match var.source(db)?.value.kind() {

View file

@ -89,8 +89,11 @@ use crate::{AssistContext, AssistId, AssistKind, Assists, GroupLabel};
// ``` // ```
pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> { pub(crate) fn auto_import(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_imports(
import_assets.search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind); &ctx.sema,
ctx.config.insert_use.prefix_kind,
ctx.config.prefer_core,
);
if proposed_imports.is_empty() { if proposed_imports.is_empty() {
return None; return None;
} }

View file

@ -50,7 +50,7 @@ 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)?) mod_path_to_ast(&module.find_use_path(ctx.db(), src_type_def, ctx.config.prefer_core)?)
}; };
let dest_type = match &ast_trait { let dest_type = match &ast_trait {

View file

@ -152,6 +152,7 @@ pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op
ctx.sema.db, ctx.sema.db,
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_core,
); );
if let Some(mod_path) = mod_path { if let Some(mod_path) = mod_path {

View file

@ -409,6 +409,7 @@ fn process_references(
ctx.sema.db, ctx.sema.db,
*enum_module_def, *enum_module_def,
ctx.config.insert_use.prefix_kind, ctx.config.insert_use.prefix_kind,
ctx.config.prefer_core,
); );
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,7 +58,8 @@ 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 = module.find_use_path(ctx.db(), ModuleDef::Trait(trait_))?; let trait_path =
module.find_use_path(ctx.db(), ModuleDef::Trait(trait_), ctx.config.prefer_core)?;
let field_type = field.ty()?; let field_type = field.ty()?;
let field_name = field.name()?; let field_name = field.name()?;
@ -98,7 +99,8 @@ 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 = module.find_use_path(ctx.db(), ModuleDef::Trait(trait_))?; let trait_path =
module.find_use_path(ctx.db(), ModuleDef::Trait(trait_), ctx.config.prefer_core)?;
let field_type = field.ty()?; let field_type = field.ty()?;
let target = field.syntax().text_range(); let target = field.syntax().text_range();

View file

@ -60,8 +60,11 @@ pub(crate) fn generate_new(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option
let item_in_ns = hir::ItemInNs::from(hir::ModuleDef::from(ty.as_adt()?)); let item_in_ns = hir::ItemInNs::from(hir::ModuleDef::from(ty.as_adt()?));
let type_path = current_module let type_path = current_module.find_use_path(
.find_use_path(ctx.sema.db, item_for_path_search(ctx.sema.db, item_in_ns)?)?; ctx.sema.db,
item_for_path_search(ctx.sema.db, item_in_ns)?,
ctx.config.prefer_core,
)?;
let expr = use_trivial_constructor( let expr = use_trivial_constructor(
&ctx.sema.db, &ctx.sema.db,

View file

@ -44,8 +44,11 @@ pub(crate) fn qualify_method_call(acc: &mut Assists, ctx: &AssistContext<'_>) ->
let current_module = ctx.sema.scope(call.syntax())?.module(); let current_module = ctx.sema.scope(call.syntax())?.module();
let target_module_def = ModuleDef::from(resolved_call); let target_module_def = ModuleDef::from(resolved_call);
let item_in_ns = ItemInNs::from(target_module_def); let item_in_ns = ItemInNs::from(target_module_def);
let receiver_path = current_module let receiver_path = current_module.find_use_path(
.find_use_path(ctx.sema.db, item_for_path_search(ctx.sema.db, item_in_ns)?)?; ctx.sema.db,
item_for_path_search(ctx.sema.db, item_in_ns)?,
ctx.config.prefer_core,
)?;
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,7 +37,8 @@ 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 = import_assets.search_for_relative_paths(&ctx.sema); let mut proposed_imports =
import_assets.search_for_relative_paths(&ctx.sema, ctx.config.prefer_core);
if proposed_imports.is_empty() { if proposed_imports.is_empty() {
return None; return None;
} }

View file

@ -85,7 +85,7 @@ 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_)) .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_), ctx.config.prefer_core)
.as_ref() .as_ref()
.map(mod_path_to_ast) .map(mod_path_to_ast)
.zip(Some(trait_)) .zip(Some(trait_))

View file

@ -67,6 +67,7 @@ pub(crate) fn replace_qualified_name_with_use(
ctx.sema.db, ctx.sema.db,
module, module,
ctx.config.insert_use.prefix_kind, ctx.config.insert_use.prefix_kind,
ctx.config.prefer_core,
) )
}) })
.flatten(); .flatten();

View file

@ -29,6 +29,7 @@ pub(crate) const TEST_CONFIG: AssistConfig = AssistConfig {
group: true, group: true,
skip_glob_imports: true, skip_glob_imports: true,
}, },
prefer_core: false,
}; };
pub(crate) fn with_single_file(text: &str) -> (RootDatabase, FileId) { pub(crate) fn with_single_file(text: &str) -> (RootDatabase, FileId) {

View file

@ -551,7 +551,9 @@ fn enum_variants_with_paths(
} }
for variant in variants { for variant in variants {
if let Some(path) = ctx.module.find_use_path(ctx.db, hir::ModuleDef::from(variant)) { if let Some(path) =
ctx.module.find_use_path(ctx.db, hir::ModuleDef::from(variant), ctx.config.prefer_core)
{
// 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
if path.segments().len() > 1 { if path.segments().len() > 1 {

View file

@ -165,7 +165,11 @@ pub(crate) fn complete_expr_path(
hir::Adt::Struct(strukt) => { hir::Adt::Struct(strukt) => {
let path = ctx let path = ctx
.module .module
.find_use_path(ctx.db, hir::ModuleDef::from(strukt)) .find_use_path(
ctx.db,
hir::ModuleDef::from(strukt),
ctx.config.prefer_core,
)
.filter(|it| it.len() > 1); .filter(|it| it.len() > 1);
acc.add_struct_literal(ctx, path_ctx, strukt, path, None); acc.add_struct_literal(ctx, path_ctx, strukt, path, None);
@ -183,7 +187,7 @@ pub(crate) fn complete_expr_path(
hir::Adt::Union(un) => { hir::Adt::Union(un) => {
let path = ctx let path = ctx
.module .module
.find_use_path(ctx.db, hir::ModuleDef::from(un)) .find_use_path(ctx.db, hir::ModuleDef::from(un), ctx.config.prefer_core)
.filter(|it| it.len() > 1); .filter(|it| it.len() > 1);
acc.add_union_literal(ctx, un, path, None); acc.add_union_literal(ctx, un, path, None);

View file

@ -262,7 +262,11 @@ fn import_on_the_fly(
acc.add_all( acc.add_all(
import_assets import_assets
.search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind) .search_for_imports(
&ctx.sema,
ctx.config.insert_use.prefix_kind,
ctx.config.prefer_core,
)
.into_iter() .into_iter()
.filter(ns_filter) .filter(ns_filter)
.filter(|import| { .filter(|import| {
@ -306,7 +310,11 @@ fn import_on_the_fly_pat_(
acc.add_all( acc.add_all(
import_assets import_assets
.search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind) .search_for_imports(
&ctx.sema,
ctx.config.insert_use.prefix_kind,
ctx.config.prefer_core,
)
.into_iter() .into_iter()
.filter(ns_filter) .filter(ns_filter)
.filter(|import| { .filter(|import| {
@ -344,7 +352,7 @@ 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) .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind, ctx.config.prefer_core)
.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

@ -17,6 +17,7 @@ pub struct CompletionConfig {
pub callable: Option<CallableSnippets>, pub callable: Option<CallableSnippets>,
pub snippet_cap: Option<SnippetCap>, pub snippet_cap: Option<SnippetCap>,
pub insert_use: InsertUseConfig, pub insert_use: InsertUseConfig,
pub prefer_core: bool,
pub snippets: Vec<Snippet>, pub snippets: Vec<Snippet>,
} }

View file

@ -234,7 +234,12 @@ pub fn resolve_completion_edits(
); );
let import = items_with_name let import = items_with_name
.filter_map(|candidate| { .filter_map(|candidate| {
current_module.find_use_path_prefixed(db, candidate, config.insert_use.prefix_kind) current_module.find_use_path_prefixed(
db,
candidate,
config.insert_use.prefix_kind,
config.prefer_core,
)
}) })
.find(|mod_path| mod_path.to_string() == full_import_path); .find(|mod_path| mod_path.to_string() == full_import_path);
if let Some(import_path) = import { if let Some(import_path) = import {

View file

@ -174,8 +174,12 @@ fn import_edits(ctx: &CompletionContext<'_>, requires: &[GreenNode]) -> Option<V
hir::PathResolution::Def(def) => def.into(), hir::PathResolution::Def(def) => def.into(),
_ => return None, _ => return None,
}; };
let path = let path = ctx.module.find_use_path_prefixed(
ctx.module.find_use_path_prefixed(ctx.db, item, ctx.config.insert_use.prefix_kind)?; ctx.db,
item,
ctx.config.insert_use.prefix_kind,
ctx.config.prefer_core,
)?;
Some((path.len() > 1).then(|| LocatedImport::new(path.clone(), item, item, None))) Some((path.len() > 1).then(|| LocatedImport::new(path.clone(), item, item, None)))
}; };
let mut res = Vec::with_capacity(requires.len()); let mut res = Vec::with_capacity(requires.len());

View file

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

View file

@ -212,18 +212,20 @@ impl ImportAssets {
&self, &self,
sema: &Semantics<'_, RootDatabase>, sema: &Semantics<'_, RootDatabase>,
prefix_kind: PrefixKind, prefix_kind: PrefixKind,
prefer_core: 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)) self.search_for(sema, Some(prefix_kind), prefer_core)
} }
/// 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.
pub fn search_for_relative_paths( pub fn search_for_relative_paths(
&self, &self,
sema: &Semantics<'_, RootDatabase>, sema: &Semantics<'_, RootDatabase>,
prefer_core: 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) self.search_for(sema, None, prefer_core)
} }
pub fn path_fuzzy_name_to_exact(&mut self, case_sensitive: bool) { pub fn path_fuzzy_name_to_exact(&mut self, case_sensitive: bool) {
@ -242,6 +244,7 @@ impl ImportAssets {
&self, &self,
sema: &Semantics<'_, RootDatabase>, sema: &Semantics<'_, RootDatabase>,
prefixed: Option<PrefixKind>, prefixed: Option<PrefixKind>,
prefer_core: bool,
) -> Vec<LocatedImport> { ) -> Vec<LocatedImport> {
let _p = profile::span("import_assets::search_for"); let _p = profile::span("import_assets::search_for");
@ -252,6 +255,7 @@ impl ImportAssets {
item_for_path_search(sema.db, item)?, item_for_path_search(sema.db, item)?,
&self.module_with_candidate, &self.module_with_candidate,
prefixed, prefixed,
prefer_core,
) )
}; };
@ -564,11 +568,12 @@ fn get_mod_path(
item_to_search: ItemInNs, item_to_search: ItemInNs,
module_with_candidate: &Module, module_with_candidate: &Module,
prefixed: Option<PrefixKind>, prefixed: Option<PrefixKind>,
prefer_core: 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) module_with_candidate.find_use_path_prefixed(db, item_to_search, prefix_kind, prefer_core)
} else { } else {
module_with_candidate.find_use_path(db, item_to_search) module_with_candidate.find_use_path(db, item_to_search, prefer_core)
} }
} }

View file

@ -173,6 +173,7 @@ impl<'a> Ctx<'a> {
let found_path = self.target_module.find_use_path( let found_path = self.target_module.find_use_path(
self.source_scope.db.upcast(), self.source_scope.db.upcast(),
hir::ModuleDef::Trait(trait_ref), hir::ModuleDef::Trait(trait_ref),
false,
)?; )?;
match ast::make::ty_path(mod_path_to_ast(&found_path)) { match ast::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),
@ -209,7 +210,7 @@ impl<'a> Ctx<'a> {
} }
let found_path = let found_path =
self.target_module.find_use_path(self.source_scope.db.upcast(), def)?; self.target_module.find_use_path(self.source_scope.db.upcast(), def, false)?;
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

@ -137,6 +137,7 @@ pub(crate) fn json_in_items(
sema.db, sema.db,
it, it,
config.insert_use.prefix_kind, config.insert_use.prefix_kind,
config.prefer_core,
) { ) {
insert_use( insert_use(
&scope, &scope,
@ -152,6 +153,7 @@ pub(crate) fn json_in_items(
sema.db, sema.db,
it, it,
config.insert_use.prefix_kind, config.insert_use.prefix_kind,
config.prefer_core,
) { ) {
insert_use( insert_use(
&scope, &scope,

View file

@ -124,6 +124,7 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option<Vec<Ass
let type_path = current_module?.find_use_path( let type_path = current_module?.find_use_path(
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_core,
)?; )?;
use_trivial_constructor( use_trivial_constructor(

View file

@ -150,6 +150,7 @@ pub struct DiagnosticsConfig {
pub expr_fill_default: ExprFillDefaultMode, pub expr_fill_default: ExprFillDefaultMode,
// 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_core: bool,
} }
impl DiagnosticsConfig { impl DiagnosticsConfig {
@ -170,6 +171,7 @@ impl DiagnosticsConfig {
group: false, group: false,
skip_glob_imports: false, skip_glob_imports: false,
}, },
prefer_core: false,
} }
} }
} }

View file

@ -648,9 +648,10 @@ impl Match {
.module(); .module();
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 = module.find_use_path(sema.db, module_def).ok_or_else(|| { let mod_path =
match_error!("Failed to render template path `{}` at match location") module.find_use_path(sema.db, module_def, false).ok_or_else(|| {
})?; 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

@ -263,6 +263,8 @@ config_data! {
imports_group_enable: bool = "true", imports_group_enable: bool = "true",
/// Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`. /// Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`.
imports_merge_glob: bool = "true", imports_merge_glob: bool = "true",
/// Prefer to use imports of the core crate over the std crate.
imports_prefer_core: 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\"",
@ -918,6 +920,7 @@ impl Config {
ExprFillDefaultDef::Default => ExprFillDefaultMode::Default, ExprFillDefaultDef::Default => ExprFillDefaultMode::Default,
}, },
insert_use: self.insert_use_config(), insert_use: self.insert_use_config(),
prefer_core: self.data.imports_prefer_core,
} }
} }
@ -1133,6 +1136,7 @@ impl Config {
CallableCompletionDef::None => None, CallableCompletionDef::None => None,
}, },
insert_use: self.insert_use_config(), insert_use: self.insert_use_config(),
prefer_core: self.data.imports_prefer_core,
snippet_cap: SnippetCap::new(try_or_def!( snippet_cap: SnippetCap::new(try_or_def!(
self.caps self.caps
.text_document .text_document
@ -1156,6 +1160,7 @@ impl Config {
snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")), snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")),
allowed: None, allowed: None,
insert_use: self.insert_use_config(), insert_use: self.insert_use_config(),
prefer_core: self.data.imports_prefer_core,
} }
} }

View file

@ -145,6 +145,7 @@ fn integrated_completion_benchmark() {
skip_glob_imports: true, skip_glob_imports: true,
}, },
snippets: Vec::new(), snippets: Vec::new(),
prefer_core: false,
}; };
let position = let position =
FilePosition { file_id, offset: TextSize::try_from(completion_offset).unwrap() }; FilePosition { file_id, offset: TextSize::try_from(completion_offset).unwrap() };
@ -182,6 +183,7 @@ fn integrated_completion_benchmark() {
skip_glob_imports: true, skip_glob_imports: true,
}, },
snippets: Vec::new(), snippets: Vec::new(),
prefer_core: false,
}; };
let position = let position =
FilePosition { file_id, offset: TextSize::try_from(completion_offset).unwrap() }; FilePosition { file_id, offset: TextSize::try_from(completion_offset).unwrap() };

View file

@ -353,6 +353,11 @@ Group inserted imports by the https://rust-analyzer.github.io/manual.html#auto-i
-- --
Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`. Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`.
-- --
[[rust-analyzer.imports.prefer.core]]rust-analyzer.imports.prefer.core (default: `false`)::
+
--
Prefer to use imports of the core crate over the std crate.
--
[[rust-analyzer.imports.prefix]]rust-analyzer.imports.prefix (default: `"plain"`):: [[rust-analyzer.imports.prefix]]rust-analyzer.imports.prefix (default: `"plain"`)::
+ +
-- --

View file

@ -803,6 +803,11 @@
"default": true, "default": true,
"type": "boolean" "type": "boolean"
}, },
"rust-analyzer.imports.prefer.core": {
"markdownDescription": "Prefer to use imports of the core crate over the std crate.",
"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",