Repository: rust-lang/rust-analyzer
Pull request #13227 (2022-09-13 12:33:03)

Restructure `find_path` into a separate functions for modules and non-module items
Follow up to https://github.com/rust-lang/rust-analyzer/pull/13212
Also renames `prefer_core` imports config to `prefer_no_std` and changes the behavior of no_std path searching by preferring `core` paths `over` alloc

This PR turned into a slight rewrite, so it unfortunately does a few more things that I initially planned to (including a bug fix for enum variant paths)

Veykril: @bors r+
bors: :pushpin: Commit cb00af073879bd9db5332ae148e380f0d0dddde9 has been approved by `Veykril`

It is now in the [queue](https://bors.rust-lang.org/homu/queue/rust-analyzer) for this repository.

<!-- @bors r=Veykril cb00af073879bd9db5332ae148e380f0d0dddde9 -->
<!-- homu: {"type":"Approved","sha":"cb00af073879bd9db5332ae148e380f0d0dddde9","approver":"Veykril","queue":"https://bors.rust-lang.org/homu/queue/rust-analyzer"} -->
bors: :hourglass: Testing commit cb00af073879bd9db5332ae148e380f0d0dddde9 with merge 6b6c05cc186285d05082d3e23696e4810ece38c1...
<!-- homu: {"type":"BuildStarted","head_sha":"cb00af073879bd9db5332ae148e380f0d0dddde9","merge_sha":"6b6c05cc186285d05082d3e23696e4810ece38c1"} -->

Patch:
diff --git a/crates/hir-def/src/find_path.rs b/crates/hir-def/src/find_path.rs
index f46054e8cc..b94b500040 100644
--- a/crates/hir-def/src/find_path.rs
+++ b/crates/hir-def/src/find_path.rs
@@ -1,6 +1,6 @@
 //! An algorithm to find a path to refer to a certain item.
 
-use std::iter;
+use std::{cmp::Ordering, iter};
 
 use hir_expand::name::{known, AsName, Name};
 use rustc_hash::FxHashSet;
@@ -20,10 +20,10 @@ pub fn find_path(
     db: &dyn DefDatabase,
     item: ItemInNs,
     from: ModuleId,
-    prefer_core: bool,
+    prefer_no_std: bool,
 ) -> Option<ModPath> {
     let _p = profile::span("find_path");
-    find_path_inner(db, item, from, None, prefer_core)
+    find_path_inner(db, item, from, None, prefer_no_std)
 }
 
 pub fn find_path_prefixed(
@@ -31,48 +31,14 @@ pub fn find_path_prefixed(
     item: ItemInNs,
     from: ModuleId,
     prefix_kind: PrefixKind,
-    prefer_core: bool,
+    prefer_no_std: bool,
 ) -> Option<ModPath> {
     let _p = profile::span("find_path_prefixed");
-    find_path_inner(db, item, from, Some(prefix_kind), prefer_core)
+    find_path_inner(db, item, from, Some(prefix_kind), prefer_no_std)
 }
 
 const MAX_PATH_LEN: usize = 15;
 
-trait ModPathExt {
-    fn starts_with_std(&self) -> bool;
-    fn can_start_with_std(&self) -> bool;
-}
-
-impl ModPathExt for ModPath {
-    fn starts_with_std(&self) -> bool {
-        self.segments().first() == Some(&known::std)
-    }
-
-    // Can we replace the first segment with `std::` and still get a valid, identical path?
-    fn can_start_with_std(&self) -> bool {
-        let first_segment = self.segments().first();
-        first_segment == Some(&known::alloc) || first_segment == Some(&known::core)
-    }
-}
-
-fn check_self_super(def_map: &DefMap, item: ItemInNs, from: ModuleId) -> Option<ModPath> {
-    if item == ItemInNs::Types(from.into()) {
-        // - if the item is the module we're in, use `self`
-        Some(ModPath::from_segments(PathKind::Super(0), None))
-    } else if let Some(parent_id) = def_map[from.local_id].parent {
-        // - if the item is the parent module, use `super` (this is not used recursively, since `super::super` is ugly)
-        let parent_id = def_map.module_id(parent_id);
-        if item == ItemInNs::Types(ModuleDefId::ModuleId(parent_id)) {
-            Some(ModPath::from_segments(PathKind::Super(1), None))
-        } else {
-            None
-        }
-    } else {
-        None
-    }
-}
-
 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
 pub enum PrefixKind {
     /// Causes paths to always start with either `self`, `super`, `crate` or a crate-name.
@@ -100,149 +66,247 @@ impl PrefixKind {
         self == &PrefixKind::ByCrate
     }
 }
+
 /// Attempts to find a path to refer to the given `item` visible from the `from` ModuleId
 fn find_path_inner(
     db: &dyn DefDatabase,
     item: ItemInNs,
     from: ModuleId,
     prefixed: Option<PrefixKind>,
-    prefer_core: bool,
+    prefer_no_std: bool,
 ) -> Option<ModPath> {
-    // FIXME: Do fast path for std/core libs?
+    // - if the item is a builtin, it's in scope
+    if let ItemInNs::Types(ModuleDefId::BuiltinType(builtin)) = item {
+        return Some(ModPath::from_segments(PathKind::Plain, Some(builtin.as_name())));
+    }
 
-    let mut visited_modules = FxHashSet::default();
     let def_map = from.def_map(db);
-    find_path_inner_(
+    let crate_root = def_map.crate_root(db);
+    // - if the item is a module, jump straight to module search
+    if let ItemInNs::Types(ModuleDefId::ModuleId(module_id)) = item {
+        let mut visited_modules = FxHashSet::default();
+        return find_path_for_module(
+            db,
+            &def_map,
+            &mut visited_modules,
+            crate_root,
+            from,
+            module_id,
+            MAX_PATH_LEN,
+            prefixed,
+            prefer_no_std || db.crate_supports_no_std(crate_root.krate),
+        );
+    }
+
+    // - if the item is already in scope, return the name under which it is
+    let scope_name = find_in_scope(db, &def_map, from, item);
+    if prefixed.is_none() {
+        if let Some(scope_name) = scope_name {
+            return Some(ModPath::from_segments(PathKind::Plain, Some(scope_name)));
+        }
+    }
+
+    // - if the item is in the prelude, return the name from there
+    if let Some(value) = find_in_prelude(db, &crate_root.def_map(db), item, from) {
+        return value;
+    }
+
+    if let Some(ModuleDefId::EnumVariantId(variant)) = item.as_module_def_id() {
+        // - if the item is an enum variant, refer to it via the enum
+        if let Some(mut path) = find_path_inner(
+            db,
+            ItemInNs::Types(variant.parent.into()),
+            from,
+            prefixed,
+            prefer_no_std,
+        ) {
+            let data = db.enum_data(variant.parent);
+            path.push_segment(data.variants[variant.local_id].name.clone());
+            return Some(path);
+        }
+        // If this doesn't work, it seems we have no way of referring to the
+        // enum; that's very weird, but there might still be a reexport of the
+        // variant somewhere
+    }
+
+    let mut visited_modules = FxHashSet::default();
+
+    calculate_best_path(
         db,
         &def_map,
-        from,
-        item,
+        &mut visited_modules,
+        crate_root,
         MAX_PATH_LEN,
+        item,
+        from,
         prefixed,
-        &mut visited_modules,
-        prefer_core,
+        prefer_no_std || db.crate_supports_no_std(crate_root.krate),
+        scope_name,
     )
 }
 
-fn find_path_inner_(
+fn find_path_for_module(
     db: &dyn DefDatabase,
     def_map: &DefMap,
+    visited_modules: &mut FxHashSet<ModuleId>,
+    crate_root: ModuleId,
     from: ModuleId,
-    item: ItemInNs,
+    module_id: ModuleId,
     max_len: usize,
-    mut prefixed: Option<PrefixKind>,
-    visited_modules: &mut FxHashSet<ModuleId>,
-    prefer_core: bool,
+    prefixed: Option<PrefixKind>,
+    prefer_no_std: bool,
 ) -> Option<ModPath> {
     if max_len == 0 {
         return None;
     }
 
     // Base cases:
-
     // - if the item is already in scope, return the name under which it is
-    let scope_name = def_map.with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
-        def_map[local_id].scope.name_of(item).map(|(name, _)| name.clone())
-    });
+    let scope_name = find_in_scope(db, def_map, from, ItemInNs::Types(module_id.into()));
     if prefixed.is_none() {
         if let Some(scope_name) = scope_name {
             return Some(ModPath::from_segments(PathKind::Plain, Some(scope_name)));
         }
     }
 
-    // - if the item is a builtin, it's in scope
-    if let ItemInNs::Types(ModuleDefId::BuiltinType(builtin)) = item {
-        return Some(ModPath::from_segments(PathKind::Plain, Some(builtin.as_name())));
-    }
-
     // - if the item is the crate root, return `crate`
-    let crate_root = def_map.crate_root(db);
-    if item == ItemInNs::Types(ModuleDefId::ModuleId(crate_root)) {
+    if module_id == crate_root {
         return Some(ModPath::from_segments(PathKind::Crate, None));
     }
 
+    // - if relative paths are fine, check if we are searching for a parent
     if prefixed.filter(PrefixKind::is_absolute).is_none() {
-        if let modpath @ Some(_) = check_self_super(&def_map, item, from) {
+        if let modpath @ Some(_) = find_self_super(&def_map, module_id, from) {
             return modpath;
         }
     }
 
     // - if the item is the crate root of a dependency crate, return the name from the extern prelude
     let root_def_map = crate_root.def_map(db);
-    if let ItemInNs::Types(ModuleDefId::ModuleId(item)) = item {
-        for (name, &def_id) in root_def_map.extern_prelude() {
-            if item == def_id {
-                let name = scope_name.unwrap_or_else(|| name.clone());
-
-                let name_already_occupied_in_type_ns = def_map
-                    .with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
-                        def_map[local_id]
-                            .scope
-                            .type_(&name)
-                            .filter(|&(id, _)| id != ModuleDefId::ModuleId(def_id))
-                    })
-                    .is_some();
-                let kind = if name_already_occupied_in_type_ns {
-                    cov_mark::hit!(ambiguous_crate_start);
-                    PathKind::Abs
-                } else {
-                    PathKind::Plain
-                };
-                return Some(ModPath::from_segments(kind, Some(name)));
-            }
+    for (name, &def_id) in root_def_map.extern_prelude() {
+        if module_id == def_id {
+            let name = scope_name.unwrap_or_else(|| name.clone());
+
+            let name_already_occupied_in_type_ns = def_map
+                .with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
+                    def_map[local_id]
+                        .scope
+                        .type_(&name)
+                        .filter(|&(id, _)| id != ModuleDefId::ModuleId(def_id))
+                })
+                .is_some();
+            let kind = if name_already_occupied_in_type_ns {
+                cov_mark::hit!(ambiguous_crate_start);
+                PathKind::Abs
+            } else {
+                PathKind::Plain
+            };
+            return Some(ModPath::from_segments(kind, Some(name)));
         }
     }
 
-    // - if the item is in the prelude, return the name from there
+    if let Some(value) = find_in_prelude(db, &root_def_map, ItemInNs::Types(module_id.into()), from)
+    {
+        return value;
+    }
+    calculate_best_path(
+        db,
+        def_map,
+        visited_modules,
+        crate_root,
+        max_len,
+        ItemInNs::Types(module_id.into()),
+        from,
+        prefixed,
+        prefer_no_std,
+        scope_name,
+    )
+}
+
+fn find_in_scope(
+    db: &dyn DefDatabase,
+    def_map: &DefMap,
+    from: ModuleId,
+    item: ItemInNs,
+) -> Option<Name> {
+    def_map.with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
+        def_map[local_id].scope.name_of(item).map(|(name, _)| name.clone())
+    })
+}
+
+fn find_in_prelude(
+    db: &dyn DefDatabase,
+    root_def_map: &DefMap,
+    item: ItemInNs,
+    from: ModuleId,
+) -> Option<Option<ModPath>> {
     if let Some(prelude_module) = root_def_map.prelude() {
         // Preludes in block DefMaps are ignored, only the crate DefMap is searched
         let prelude_def_map = prelude_module.def_map(db);
         let prelude_scope = &prelude_def_map[prelude_module.local_id].scope;
         if let Some((name, vis)) = prelude_scope.name_of(item) {
             if vis.is_visible_from(db, from) {
-                return Some(ModPath::from_segments(PathKind::Plain, Some(name.clone())));
+                return Some(Some(ModPath::from_segments(PathKind::Plain, Some(name.clone()))));
             }
         }
     }
+    None
+}
 
-    // Recursive case:
-    // - 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(mut path) =
-            find_path(db, ItemInNs::Types(variant.parent.into()), from, prefer_core)
-        {
-            let data = db.enum_data(variant.parent);
-            path.push_segment(data.variants[variant.local_id].name.clone());
-            return Some(path);
+fn find_self_super(def_map: &DefMap, item: ModuleId, from: ModuleId) -> Option<ModPath> {
+    if item == from {
+        // - if the item is the module we're in, use `self`
+        Some(ModPath::from_segments(PathKind::Super(0), None))
+    } else if let Some(parent_id) = def_map[from.local_id].parent {
+        // - if the item is the parent module, use `super` (this is not used recursively, since `super::super` is ugly)
+        let parent_id = def_map.module_id(parent_id);
+        if item == parent_id {
+            Some(ModPath::from_segments(PathKind::Super(1), None))
+        } else {
+            None
         }
-        // If this doesn't work, it seems we have no way of referring to the
-        // enum; that's very weird, but there might still be a reexport of the
-        // variant somewhere
+    } else {
+        None
     }
+}
 
-    // - otherwise, look for modules containing (reexporting) it and import it from one of those
-    let prefer_no_std = prefer_core || db.crate_supports_no_std(crate_root.krate);
+fn calculate_best_path(
+    db: &dyn DefDatabase,
+    def_map: &DefMap,
+    visited_modules: &mut FxHashSet<ModuleId>,
+    crate_root: ModuleId,
+    max_len: usize,
+    item: ItemInNs,
+    from: ModuleId,
+    mut prefixed: Option<PrefixKind>,
+    prefer_no_std: bool,
+    scope_name: Option<Name>,
+) -> Option<ModPath> {
+    if max_len <= 1 {
+        return None;
+    }
     let mut best_path = None;
-    let mut best_path_len = max_len;
-
+    // Recursive case:
+    // - otherwise, look for modules containing (reexporting) it and import it from one of those
     if item.krate(db) == Some(from.krate) {
+        let mut best_path_len = max_len;
         // Item was defined in the same crate that wants to import it. It cannot be found in any
         // dependency in this case.
-        // FIXME: this should have a fast path that doesn't look through the prelude again?
         for (module_id, name) in find_local_import_locations(db, item, from) {
             if !visited_modules.insert(module_id) {
                 cov_mark::hit!(recursive_imports);
                 continue;
             }
-            if let Some(mut path) = find_path_inner_(
+            if let Some(mut path) = find_path_for_module(
                 db,
                 def_map,
+                visited_modules,
+                crate_root,
                 from,
-                ItemInNs::Types(ModuleDefId::ModuleId(module_id)),
+                module_id,
                 best_path_len - 1,
                 prefixed,
-                visited_modules,
-                prefer_core,
+                prefer_no_std,
             ) {
                 path.push_segment(name);
 
@@ -265,15 +329,16 @@ fn find_path_inner_(
             import_map.import_info_for(item).and_then(|info| {
                 // Determine best path for containing module and append last segment from `info`.
                 // FIXME: we should guide this to look up the path locally, or from the same crate again?
-                let mut path = find_path_inner_(
+                let mut path = find_path_for_module(
                     db,
                     def_map,
+                    visited_modules,
                     from,
-                    ItemInNs::Types(ModuleDefId::ModuleId(info.container)),
-                    best_path_len - 1,
+                    crate_root,
+                    info.container,
+                    max_len - 1,
                     prefixed,
-                    visited_modules,
-                    prefer_core,
+                    prefer_no_std,
                 )?;
                 cov_mark::hit!(partially_imported);
                 path.push_segment(info.path.segments.last()?.clone());
@@ -289,16 +354,12 @@ fn find_path_inner_(
             best_path = Some(new_path);
         }
     }
-
-    // If the item is declared inside a block expression, don't use a prefix, as we don't handle
-    // that correctly (FIXME).
-    if let Some(item_module) = item.as_module_def_id().and_then(|did| did.module(db)) {
-        if item_module.def_map(db).block_id().is_some() && prefixed.is_some() {
+    if let Some(module) = item.module(db) {
+        if module.def_map(db).block_id().is_some() && prefixed.is_some() {
             cov_mark::hit!(prefixed_in_block_expression);
             prefixed = Some(PrefixKind::Plain);
         }
     }
-
     match prefixed.map(PrefixKind::prefix) {
         Some(prefix) => best_path.or_else(|| {
             scope_name.map(|scope_name| ModPath::from_segments(prefix, Some(scope_name)))
@@ -308,29 +369,48 @@ fn find_path_inner_(
 }
 
 fn select_best_path(old_path: ModPath, new_path: ModPath, prefer_no_std: bool) -> ModPath {
-    if old_path.starts_with_std() && new_path.can_start_with_std() {
-        if prefer_no_std {
-            cov_mark::hit!(prefer_no_std_paths);
-            new_path
-        } else {
-            cov_mark::hit!(prefer_std_paths);
-            old_path
+    const STD_CRATES: [Name; 3] = [known::std, known::core, known::alloc];
+    match (old_path.segments().first(), new_path.segments().first()) {
+        (Some(old), Some(new)) if STD_CRATES.contains(old) && STD_CRATES.contains(new) => {
+            let rank = match prefer_no_std {
+                false => |name: &Name| match name {
+                    name if name == &known::core => 0,
+                    name if name == &known::alloc => 0,
+                    name if name == &known::std => 1,
+                    _ => unreachable!(),
+                },
+                true => |name: &Name| match name {
+                    name if name == &known::core => 2,
+                    name if name == &known::alloc => 1,
+                    name if name == &known::std => 0,
+                    _ => unreachable!(),
+                },
+            };
+            let nrank = rank(new);
+            let orank = rank(old);
+            match nrank.cmp(&orank) {
+                Ordering::Less => old_path,
+                Ordering::Equal => {
+                    if new_path.len() < old_path.len() {
+                        new_path
+                    } else {
+                        old_path
+                    }
+                }
+                Ordering::Greater => new_path,
+            }
         }
-    } else if new_path.starts_with_std() && old_path.can_start_with_std() {
-        if prefer_no_std {
-            cov_mark::hit!(prefer_no_std_paths);
-            old_path
-        } else {
-            cov_mark::hit!(prefer_std_paths);
-            new_path
+        _ => {
+            if new_path.len() < old_path.len() {
+                new_path
+            } else {
+                old_path
+            }
         }
-    } else if new_path.len() < old_path.len() {
-        new_path
-    } else {
-        old_path
     }
 }
 
+// FIXME: Remove allocations
 /// Finds locations in `from.krate` from which `item` can be imported by `from`.
 fn find_local_import_locations(
     db: &dyn DefDatabase,
@@ -490,8 +570,8 @@ $0
         "#,
             "E::A",
             "E::A",
-            "E::A",
-            "E::A",
+            "crate::E::A",
+            "self::E::A",
         );
     }
 
@@ -810,7 +890,6 @@ pub use super::foo;
 
     #[test]
     fn prefer_std_paths_over_alloc() {
-        cov_mark::check!(prefer_std_paths);
         check_found_path(
             r#"
 //- /main.rs crate:main deps:alloc,std
@@ -835,7 +914,6 @@ pub mod sync {
 
     #[test]
     fn prefer_core_paths_over_std() {
-        cov_mark::check!(prefer_no_std_paths);
         check_found_path(
             r#"
 //- /main.rs crate:main deps:core,std
diff --git a/crates/hir-def/src/item_scope.rs b/crates/hir-def/src/item_scope.rs
index a11a92204c..a40656fd6a 100644
--- a/crates/hir-def/src/item_scope.rs
+++ b/crates/hir-def/src/item_scope.rs
@@ -457,8 +457,15 @@ impl ItemInNs {
     /// Returns the crate defining this item (or `None` if `self` is built-in).
     pub fn krate(&self, db: &dyn DefDatabase) -> Option<CrateId> {
         match self {
-            ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate),
+            ItemInNs::Types(id) | ItemInNs::Values(id) => id.module(db).map(|m| m.krate),
             ItemInNs::Macros(id) => Some(id.module(db).krate),
         }
     }
+
+    pub fn module(&self, db: &dyn DefDatabase) -> Option<ModuleId> {
+        match self {
+            ItemInNs::Types(id) | ItemInNs::Values(id) => id.module(db),
+            ItemInNs::Macros(id) => Some(id.module(db)),
+        }
+    }
 }
diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs
index 7dd891c86e..b5974a0cfc 100644
--- a/crates/hir/src/lib.rs
+++ b/crates/hir/src/lib.rs
@@ -585,9 +585,9 @@ impl Module {
         self,
         db: &dyn DefDatabase,
         item: impl Into<ItemInNs>,
-        prefer_core: bool,
+        prefer_no_std: bool,
     ) -> Option<ModPath> {
-        hir_def::find_path::find_path(db, item.into().into(), self.into(), prefer_core)
+        hir_def::find_path::find_path(db, item.into().into(), self.into(), prefer_no_std)
     }
 
     /// Finds a path that can be used to refer to the given item from within
@@ -597,14 +597,14 @@ impl Module {
         db: &dyn DefDatabase,
         item: impl Into<ItemInNs>,
         prefix_kind: PrefixKind,
-        prefer_core: bool,
+        prefer_no_std: bool,
     ) -> Option<ModPath> {
         hir_def::find_path::find_path_prefixed(
             db,
             item.into().into(),
             self.into(),
             prefix_kind,
-            prefer_core,
+            prefer_no_std,
         )
     }
 }
diff --git a/crates/ide-assists/src/assist_config.rs b/crates/ide-assists/src/assist_config.rs
index fe2dfca6d5..60d1588a44 100644
--- a/crates/ide-assists/src/assist_config.rs
+++ b/crates/ide-assists/src/assist_config.rs
@@ -13,5 +13,5 @@ pub struct AssistConfig {
     pub snippet_cap: Option<SnippetCap>,
     pub allowed: Option<Vec<AssistKind>>,
     pub insert_use: InsertUseConfig,
-    pub prefer_core: bool,
+    pub prefer_no_std: bool,
 }
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 d4e21b778c..73f4db4e5f 100644
--- a/crates/ide-assists/src/handlers/add_missing_match_arms.rs
+++ b/crates/ide-assists/src/handlers/add_missing_match_arms.rs
@@ -87,7 +87,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_core)?,
+                    build_pat(ctx.db(), module, variant, ctx.config.prefer_no_std)?,
                     variant.should_be_hidden(ctx.db(), module.krate()),
                 ))
             })
@@ -133,7 +133,7 @@ pub(crate) fn add_missing_match_arms(acc: &mut Assists, ctx: &AssistContext<'_>)
                     .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_core)
+                    build_pat(ctx.db(), module, variant, ctx.config.prefer_no_std)
                 });
 
                 (ast::Pat::from(make::tuple_pat(patterns)), is_hidden)
@@ -354,12 +354,12 @@ fn build_pat(
     db: &RootDatabase,
     module: hir::Module,
     var: ExtendedVariant,
-    prefer_core: bool,
+    prefer_no_std: bool,
 ) -> Option<ast::Pat> {
     match var {
         ExtendedVariant::Variant(var) => {
             let path =
-                mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var), prefer_core)?);
+                mod_path_to_ast(&module.find_use_path(db, ModuleDef::from(var), prefer_no_std)?);
 
             // 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() {
diff --git a/crates/ide-assists/src/handlers/auto_import.rs b/crates/ide-assists/src/handlers/auto_import.rs
index 88a6b8558c..e257218ba9 100644
--- a/crates/ide-assists/src/handlers/auto_import.rs
+++ b/crates/ide-assists/src/handlers/auto_import.rs
@@ -92,7 +92,7 @@ pub(crate) fn auto_import(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<
     let mut proposed_imports = import_assets.search_for_imports(
         &ctx.sema,
         ctx.config.insert_use.prefix_kind,
-        ctx.config.prefer_core,
+        ctx.config.prefer_no_std,
     );
     if proposed_imports.is_empty() {
         return None;
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 e0c0e9a484..95d11abe8b 100644
--- a/crates/ide-assists/src/handlers/convert_into_to_from.rs
+++ b/crates/ide-assists/src/handlers/convert_into_to_from.rs
@@ -50,7 +50,7 @@ pub(crate) fn convert_into_to_from(acc: &mut Assists, ctx: &AssistContext<'_>) -
             _ => return None,
         };
 
-        mod_path_to_ast(&module.find_use_path(ctx.db(), src_type_def, ctx.config.prefer_core)?)
+        mod_path_to_ast(&module.find_use_path(ctx.db(), src_type_def, ctx.config.prefer_no_std)?)
     };
 
     let dest_type = match &ast_trait {
diff --git a/crates/ide-assists/src/handlers/extract_function.rs b/crates/ide-assists/src/handlers/extract_function.rs
index 749d94d5a9..d6c8ea785f 100644
--- a/crates/ide-assists/src/handlers/extract_function.rs
+++ b/crates/ide-assists/src/handlers/extract_function.rs
@@ -152,7 +152,7 @@ pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext<'_>) -> Op
                         ctx.sema.db,
                         ModuleDef::from(control_flow_enum),
                         ctx.config.insert_use.prefix_kind,
-                        ctx.config.prefer_core,
+                        ctx.config.prefer_no_std,
                     );
 
                     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 431f7b3c0f..8d5cab283d 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
@@ -409,7 +409,7 @@ fn process_references(
                     ctx.sema.db,
                     *enum_module_def,
                     ctx.config.insert_use.prefix_kind,
-                    ctx.config.prefer_core,
+                    ctx.config.prefer_no_std,
                 );
                 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 cf4ed84281..8f4405a8c8 100644
--- a/crates/ide-assists/src/handlers/generate_deref.rs
+++ b/crates/ide-assists/src/handlers/generate_deref.rs
@@ -59,7 +59,7 @@ fn generate_record_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<(
     let module = ctx.sema.to_def(&strukt)?.module(ctx.db());
     let trait_ = deref_type_to_generate.to_trait(&ctx.sema, module.krate())?;
     let trait_path =
-        module.find_use_path(ctx.db(), ModuleDef::Trait(trait_), ctx.config.prefer_core)?;
+        module.find_use_path(ctx.db(), ModuleDef::Trait(trait_), ctx.config.prefer_no_std)?;
 
     let field_type = field.ty()?;
     let field_name = field.name()?;
@@ -100,7 +100,7 @@ fn generate_tuple_deref(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()
     let module = ctx.sema.to_def(&strukt)?.module(ctx.db());
     let trait_ = deref_type_to_generate.to_trait(&ctx.sema, module.krate())?;
     let trait_path =
-        module.find_use_path(ctx.db(), ModuleDef::Trait(trait_), ctx.config.prefer_core)?;
+        module.find_use_path(ctx.db(), ModuleDef::Trait(trait_), ctx.config.prefer_no_std)?;
 
     let field_type = field.ty()?;
     let target = field.syntax().text_range();
diff --git a/crates/ide-assists/src/handlers/generate_new.rs b/crates/ide-assists/src/handlers/generate_new.rs
index ceb7dac0fe..9cda74d9e0 100644
--- a/crates/ide-assists/src/handlers/generate_new.rs
+++ b/crates/ide-assists/src/handlers/generate_new.rs
@@ -63,7 +63,7 @@ pub(crate) fn generate_new(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option
                 let type_path = current_module.find_use_path(
                     ctx.sema.db,
                     item_for_path_search(ctx.sema.db, item_in_ns)?,
-                    ctx.config.prefer_core,
+                    ctx.config.prefer_no_std,
                 )?;
 
                 let expr = use_trivial_constructor(
diff --git a/crates/ide-assists/src/handlers/move_format_string_arg.rs b/crates/ide-assists/src/handlers/move_format_string_arg.rs
deleted file mode 100644
index 92b2fa79d7..0000000000
--- a/crates/ide-assists/src/handlers/move_format_string_arg.rs
+++ /dev/null
@@ -1,268 +0,0 @@
-use crate::{AssistContext, Assists};
-use ide_db::{
-    assists::{AssistId, AssistKind},
-    syntax_helpers::{
-        format_string::is_format_string,
-        format_string_exprs::{parse_format_exprs, Arg},
-    },
-};
-use itertools::Itertools;
-use syntax::{ast, AstNode, AstToken, NodeOrToken, SyntaxKind::COMMA, TextRange};
-
-// Assist: move_format_string_arg
-//
-// Move an expression out of a format string.
-//
-// ```
-// macro_rules! format_args {
-//     ($lit:literal $(tt:tt)*) => { 0 },
-// }
-// macro_rules! print {
-//     ($($arg:tt)*) => (std::io::_print(format_args!($($arg)*)));
-// }
-//
-// fn main() {
-//     print!("{x + 1}$0");
-// }
-// ```
-// ->
-// ```
-// macro_rules! format_args {
-//     ($lit:literal $(tt:tt)*) => { 0 },
-// }
-// macro_rules! print {
-//     ($($arg:tt)*) => (std::io::_print(format_args!($($arg)*)));
-// }
-//
-// fn main() {
-//     print!("{}"$0, x + 1);
-// }
-// ```
-
-pub(crate) fn move_format_string_arg(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
-    let fmt_string = ctx.find_token_at_offset::<ast::String>()?;
-    let tt = fmt_string.syntax().parent().and_then(ast::TokenTree::cast)?;
-
-    let expanded_t = ast::String::cast(
-        ctx.sema.descend_into_macros_with_kind_preference(fmt_string.syntax().clone()),
-    )?;
-    if !is_format_string(&expanded_t) {
-        return None;
-    }
-
-    let (new_fmt, extracted_args) = parse_format_exprs(fmt_string.text()).ok()?;
-    if extracted_args.is_empty() {
-        return None;
-    }
-
-    acc.add(
-        AssistId(
-            "move_format_string_arg",
-            // if there aren't any expressions, then make the assist a RefactorExtract
-            if extracted_args.iter().filter(|f| matches!(f, Arg::Expr(_))).count() == 0 {
-                AssistKind::RefactorExtract
-            } else {
-                AssistKind::QuickFix
-            },
-        ),
-        "Extract format args",
-        tt.syntax().text_range(),
-        |edit| {
-            let fmt_range = fmt_string.syntax().text_range();
-
-            // Replace old format string with new format string whose arguments have been extracted
-            edit.replace(fmt_range, new_fmt);
-
-            // Insert cursor at end of format string
-            edit.insert(fmt_range.end(), "$0");
-
-            // Extract existing arguments in macro
-            let tokens =
-                tt.token_trees_and_tokens().filter_map(NodeOrToken::into_token).collect_vec();
-
-            let mut existing_args: Vec<String> = vec![];
-
-            let mut current_arg = String::new();
-            if let [_opening_bracket, format_string, _args_start_comma, tokens @ .., end_bracket] =
-                tokens.as_slice()
-            {
-                for t in tokens {
-                    if t.kind() == COMMA {
-                        existing_args.push(current_arg.trim().into());
-                        current_arg.clear();
-                    } else {
-                        current_arg.push_str(t.text());
-                    }
-                }
-                existing_args.push(current_arg.trim().into());
-
-                // delete everything after the format string till end bracket
-                // we're going to insert the new arguments later
-                edit.delete(TextRange::new(
-                    format_string.text_range().end(),
-                    end_bracket.text_range().start(),
-                ));
-            }
-
-            // Start building the new args
-            let mut existing_args = existing_args.into_iter();
-            let mut args = String::new();
-
-            let mut placeholder_idx = 1;
-
-            for extracted_args in extracted_args {
-                // remove expr from format string
-                args.push_str(", ");
-
-                match extracted_args {
-                    Arg::Ident(s) | Arg::Expr(s) => {
-                        // insert arg
-                        args.push_str(&s);
-                    }
-                    Arg::Placeholder => {
-                        // try matching with existing argument
-                        match existing_args.next() {
-                            Some(ea) => {
-                                args.push_str(&ea);
-                            }
-                            None => {
-                                // insert placeholder
-                                args.push_str(&format!("${placeholder_idx}"));
-                                placeholder_idx += 1;
-                            }
-                        }
-                    }
-                }
-            }
-
-            // Insert new args
-            edit.insert(fmt_range.end(), args);
-        },
-    );
-
-    Some(())
-}
-
-#[cfg(test)]
-mod tests {
-    use super::*;
-    use crate::tests::check_assist;
-
-    const MACRO_DECL: &'static str = r#"
-macro_rules! format_args {
-    ($lit:literal $(tt:tt)*) => { 0 },
-}
-macro_rules! print {
-    ($($arg:tt)*) => (std::io::_print(format_args!($($arg)*)));
-}
-"#;
-
-    fn add_macro_decl(s: &'static str) -> String {
-        MACRO_DECL.to_string() + s
-    }
-
-    #[test]
-    fn multiple_middle_arg() {
-        check_assist(
-            move_format_string_arg,
-            &add_macro_decl(
-                r#"
-fn main() {
-    print!("{} {x + 1:b} {}$0", y + 2, 2);
-}
-"#,
-            ),
-            &add_macro_decl(
-                r#"
-fn main() {
-    print!("{} {:b} {}"$0, y + 2, x + 1, 2);
-}
-"#,
-            ),
-        );
-    }
-
-    #[test]
-    fn single_arg() {
-        check_assist(
-            move_format_string_arg,
-            &add_macro_decl(
-                r#"
-fn main() {
-    print!("{obj.value:b}$0",);
-}
-"#,
-            ),
-            &add_macro_decl(
-                r#"
-fn main() {
-    print!("{:b}"$0, obj.value);
-}
-"#,
-            ),
-        );
-    }
-
-    #[test]
-    fn multiple_middle_placeholders_arg() {
-        check_assist(
-            move_format_string_arg,
-            &add_macro_decl(
-                r#"
-fn main() {
-    print!("{} {x + 1:b} {} {}$0", y + 2, 2);
-}
-"#,
-            ),
-            &add_macro_decl(
-                r#"
-fn main() {
-    print!("{} {:b} {} {}"$0, y + 2, x + 1, 2, $1);
-}
-"#,
-            ),
-        );
-    }
-
-    #[test]
-    fn multiple_trailing_args() {
-        check_assist(
-            move_format_string_arg,
-            &add_macro_decl(
-                r#"
-fn main() {
-    print!("{} {x + 1:b} {Struct(1, 2)}$0", 1);
-}
-"#,
-            ),
-            &add_macro_decl(
-                r#"
-fn main() {
-    print!("{} {:b} {}"$0, 1, x + 1, Struct(1, 2));
-}
-"#,
-            ),
-        );
-    }
-
-    #[test]
-    fn improper_commas() {
-        check_assist(
-            move_format_string_arg,
-            &add_macro_decl(
-                r#"
-fn main() {
-    print!("{} {x + 1:b} {Struct(1, 2)}$0", 1,);
-}
-"#,
-            ),
-            &add_macro_decl(
-                r#"
-fn main() {
-    print!("{} {:b} {}"$0, 1, x + 1, Struct(1, 2));
-}
-"#,
-            ),
-        );
-    }
-}
diff --git a/crates/ide-assists/src/handlers/qualify_method_call.rs b/crates/ide-assists/src/handlers/qualify_method_call.rs
index cb81ebd228..e57d1d065d 100644
--- a/crates/ide-assists/src/handlers/qualify_method_call.rs
+++ b/crates/ide-assists/src/handlers/qualify_method_call.rs
@@ -47,7 +47,7 @@ pub(crate) fn qualify_method_call(acc: &mut Assists, ctx: &AssistContext<'_>) ->
     let receiver_path = current_module.find_use_path(
         ctx.sema.db,
         item_for_path_search(ctx.sema.db, item_in_ns)?,
-        ctx.config.prefer_core,
+        ctx.config.prefer_no_std,
     )?;
 
     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 232cd39e8b..4b2af550bc 100644
--- a/crates/ide-assists/src/handlers/qualify_path.rs
+++ b/crates/ide-assists/src/handlers/qualify_path.rs
@@ -38,7 +38,7 @@ 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 =
-        import_assets.search_for_relative_paths(&ctx.sema, ctx.config.prefer_core);
+        import_assets.search_for_relative_paths(&ctx.sema, ctx.config.prefer_no_std);
     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 04a1366327..9fd5e1886d 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
@@ -85,7 +85,7 @@ pub(crate) fn replace_derive_with_manual_impl(
     })
     .flat_map(|trait_| {
         current_module
-            .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_), ctx.config.prefer_core)
+            .find_use_path(ctx.sema.db, hir::ModuleDef::Trait(trait_), ctx.config.prefer_no_std)
             .as_ref()
             .map(mod_path_to_ast)
             .zip(Some(trait_))
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 533e1670a0..dbbc56958f 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
@@ -67,7 +67,7 @@ pub(crate) fn replace_qualified_name_with_use(
                 ctx.sema.db,
                 module,
                 ctx.config.insert_use.prefix_kind,
-                ctx.config.prefer_core,
+                ctx.config.prefer_no_std,
             )
         })
         .flatten();
diff --git a/crates/ide-assists/src/lib.rs b/crates/ide-assists/src/lib.rs
index 812d22efbd..e52544db5f 100644
--- a/crates/ide-assists/src/lib.rs
+++ b/crates/ide-assists/src/lib.rs
@@ -136,7 +136,6 @@ mod handlers {
     mod flip_binexpr;
     mod flip_comma;
     mod flip_trait_bound;
-    mod move_format_string_arg;
     mod generate_constant;
     mod generate_default_from_enum_variant;
     mod generate_default_from_new;
@@ -255,7 +254,6 @@ mod handlers {
             merge_imports::merge_imports,
             merge_match_arms::merge_match_arms,
             move_bounds::move_bounds_to_where_clause,
-            move_format_string_arg::move_format_string_arg,
             move_guard::move_arm_cond_to_match_guard,
             move_guard::move_guard_to_arm_body,
             move_module_to_file::move_module_to_file,
diff --git a/crates/ide-completion/src/completions.rs b/crates/ide-completion/src/completions.rs
index 89a971e544..97b90c62dd 100644
--- a/crates/ide-completion/src/completions.rs
+++ b/crates/ide-completion/src/completions.rs
@@ -551,9 +551,11 @@ fn enum_variants_with_paths(
     }
 
     for variant in variants {
-        if let Some(path) =
-            ctx.module.find_use_path(ctx.db, hir::ModuleDef::from(variant), ctx.config.prefer_core)
-        {
+        if let Some(path) = ctx.module.find_use_path(
+            ctx.db,
+            hir::ModuleDef::from(variant),
+            ctx.config.prefer_no_std,
+        ) {
             // Variants with trivial paths are already added by the existing completion logic,
             // so we should avoid adding these twice
             if path.segments().len() > 1 {
diff --git a/crates/ide-completion/src/completions/expr.rs b/crates/ide-completion/src/completions/expr.rs
index 1ccf33a96b..3192b21cfb 100644
--- a/crates/ide-completion/src/completions/expr.rs
+++ b/crates/ide-completion/src/completions/expr.rs
@@ -168,7 +168,7 @@ pub(crate) fn complete_expr_path(
                             .find_use_path(
                                 ctx.db,
                                 hir::ModuleDef::from(strukt),
-                                ctx.config.prefer_core,
+                                ctx.config.prefer_no_std,
                             )
                             .filter(|it| it.len() > 1);
 
@@ -187,7 +187,11 @@ pub(crate) fn complete_expr_path(
                     hir::Adt::Union(un) => {
                         let path = ctx
                             .module
-                            .find_use_path(ctx.db, hir::ModuleDef::from(un), ctx.config.prefer_core)
+                            .find_use_path(
+                                ctx.db,
+                                hir::ModuleDef::from(un),
+                                ctx.config.prefer_no_std,
+                            )
                             .filter(|it| it.len() > 1);
 
                         acc.add_union_literal(ctx, un, path, None);
diff --git a/crates/ide-completion/src/completions/flyimport.rs b/crates/ide-completion/src/completions/flyimport.rs
index 528959943b..364969af9c 100644
--- a/crates/ide-completion/src/completions/flyimport.rs
+++ b/crates/ide-completion/src/completions/flyimport.rs
@@ -265,7 +265,7 @@ fn import_on_the_fly(
             .search_for_imports(
                 &ctx.sema,
                 ctx.config.insert_use.prefix_kind,
-                ctx.config.prefer_core,
+                ctx.config.prefer_no_std,
             )
             .into_iter()
             .filter(ns_filter)
@@ -313,7 +313,7 @@ fn import_on_the_fly_pat_(
             .search_for_imports(
                 &ctx.sema,
                 ctx.config.insert_use.prefix_kind,
-                ctx.config.prefer_core,
+                ctx.config.prefer_no_std,
             )
             .into_iter()
             .filter(ns_filter)
@@ -352,7 +352,7 @@ fn import_on_the_fly_method(
     let user_input_lowercased = potential_import_name.to_lowercase();
 
     import_assets
-        .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind, ctx.config.prefer_core)
+        .search_for_imports(&ctx.sema, ctx.config.insert_use.prefix_kind, ctx.config.prefer_no_std)
         .into_iter()
         .filter(|import| {
             !ctx.is_item_hidden(&import.item_to_import)
diff --git a/crates/ide-completion/src/completions/postfix/format_like.rs b/crates/ide-completion/src/completions/postfix/format_like.rs
index b43bdb9ab9..b273a4cb53 100644
--- a/crates/ide-completion/src/completions/postfix/format_like.rs
+++ b/crates/ide-completion/src/completions/postfix/format_like.rs
@@ -16,11 +16,8 @@
 //
 // image::https://user-images.githubusercontent.com/48062697/113020656-b560f500-917a-11eb-87de-02991f61beb8.gif[]
 
-use ide_db::{
-    syntax_helpers::format_string_exprs::{parse_format_exprs, with_placeholders},
-    SnippetCap,
-};
-use syntax::{ast, AstToken};
+use ide_db::SnippetCap;
+use syntax::ast::{self, AstToken};
 
 use crate::{
     completions::postfix::build_postfix_snippet_builder, context::CompletionContext, Completions,
@@ -46,24 +43,250 @@ pub(crate) fn add_format_like_completions(
     cap: SnippetCap,
     receiver_text: &ast::String,
 ) {
+    let input = match string_literal_contents(receiver_text) {
+        // It's not a string literal, do not parse input.
+        Some(input) => input,
+        None => return,
+    };
+
     let postfix_snippet = match build_postfix_snippet_builder(ctx, cap, dot_receiver) {
         Some(it) => it,
         None => return,
     };
+    let mut parser = FormatStrParser::new(input);
 
-    if let Ok((out, exprs)) = parse_format_exprs(receiver_text.text()) {
-        let exprs = with_placeholders(exprs);
+    if parser.parse().is_ok() {
         for (label, macro_name) in KINDS {
-            let snippet = format!(r#"{}({}, {})"#, macro_name, out, exprs.join(", "));
+            let snippet = parser.to_suggestion(macro_name);
 
             postfix_snippet(label, macro_name, &snippet).add_to(acc);
         }
     }
 }
 
+/// Checks whether provided item is a string literal.
+fn string_literal_contents(item: &ast::String) -> Option<String> {
+    let item = item.text();
+    if item.len() >= 2 && item.starts_with('\"') && item.ends_with('\"') {
+        return Some(item[1..item.len() - 1].to_owned());
+    }
+
+    None
+}
+
+/// Parser for a format-like string. It is more allowing in terms of string contents,
+/// as we expect variable placeholders to be filled with expressions.
+#[derive(Debug)]
+pub(crate) struct FormatStrParser {
+    input: String,
+    output: String,
+    extracted_expressions: Vec<String>,
+    state: State,
+    parsed: bool,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+enum State {
+    NotExpr,
+    MaybeExpr,
+    Expr,
+    MaybeIncorrect,
+    FormatOpts,
+}
+
+impl FormatStrParser {
+    pub(crate) fn new(input: String) -> Self {
+        Self {
+            input,
+            output: String::new(),
+            extracted_expressions: Vec::new(),
+            state: State::NotExpr,
+            parsed: false,
+        }
+    }
+
+    pub(crate) fn parse(&mut self) -> Result<(), ()> {
+        let mut current_expr = String::new();
+
+        let mut placeholder_id = 1;
+
+        // Count of open braces inside of an expression.
+        // We assume that user knows what they're doing, thus we treat it like a correct pattern, e.g.
+        // "{MyStruct { val_a: 0, val_b: 1 }}".
+        let mut inexpr_open_count = 0;
+
+        // We need to escape '\' and '$'. See the comments on `get_receiver_text()` for detail.
+        let mut chars = self.input.chars().peekable();
+        while let Some(chr) = chars.next() {
+            match (self.state, chr) {
+                (State::NotExpr, '{') => {
+                    self.output.push(chr);
+                    self.state = State::MaybeExpr;
+                }
+                (State::NotExpr, '}') => {
+                    self.output.push(chr);
+                    self.state = State::MaybeIncorrect;
+                }
+                (State::NotExpr, _) => {
+                    if matches!(chr, '\\' | '$') {
+                        self.output.push('\\');
+                    }
+                    self.output.push(chr);
+                }
+                (State::MaybeIncorrect, '}') => {
+                    // It's okay, we met "}}".
+                    self.output.push(chr);
+                    self.state = State::NotExpr;
+                }
+                (State::MaybeIncorrect, _) => {
+                    // Error in the string.
+                    return Err(());
+                }
+                (State::MaybeExpr, '{') => {
+                    self.output.push(chr);
+                    self.state = State::NotExpr;
+                }
+                (State::MaybeExpr, '}') => {
+                    // This is an empty sequence '{}'. Replace it with placeholder.
+                    self.output.push(chr);
+                    self.extracted_expressions.push(format!("${}", placeholder_id));
+                    placeholder_id += 1;
+                    self.state = State::NotExpr;
+                }
+                (State::MaybeExpr, _) => {
+                    if matches!(chr, '\\' | '$') {
+                        current_expr.push('\\');
+                    }
+                    current_expr.push(chr);
+                    self.state = State::Expr;
+                }
+                (State::Expr, '}') => {
+                    if inexpr_open_count == 0 {
+                        self.output.push(chr);
+                        self.extracted_expressions.push(current_expr.trim().into());
+                        current_expr = String::new();
+                        self.state = State::NotExpr;
+                    } else {
+                        // We're closing one brace met before inside of the expression.
+                        current_expr.push(chr);
+                        inexpr_open_count -= 1;
+                    }
+                }
+                (State::Expr, ':') if chars.peek().copied() == Some(':') => {
+                    // path separator
+                    current_expr.push_str("::");
+                    chars.next();
+                }
+                (State::Expr, ':') => {
+                    if inexpr_open_count == 0 {
+                        // We're outside of braces, thus assume that it's a specifier, like "{Some(value):?}"
+                        self.output.push(chr);
+                        self.extracted_expressions.push(current_expr.trim().into());
+                        current_expr = String::new();
+                        self.state = State::FormatOpts;
+                    } else {
+                        // We're inside of braced expression, assume that it's a struct field name/value delimiter.
+                        current_expr.push(chr);
+                    }
+                }
+                (State::Expr, '{') => {
+                    current_expr.push(chr);
+                    inexpr_open_count += 1;
+                }
+                (State::Expr, _) => {
+                    if matches!(chr, '\\' | '$') {
+                        current_expr.push('\\');
+                    }
+                    current_expr.push(chr);
+                }
+                (State::FormatOpts, '}') => {
+                    self.output.push(chr);
+                    self.state = State::NotExpr;
+                }
+                (State::FormatOpts, _) => {
+                    if matches!(chr, '\\' | '$') {
+                        self.output.push('\\');
+                    }
+                    self.output.push(chr);
+                }
+            }
+        }
+
+        if self.state != State::NotExpr {
+            return Err(());
+        }
+
+        self.parsed = true;
+        Ok(())
+    }
+
+    pub(crate) fn to_suggestion(&self, macro_name: &str) -> String {
+        assert!(self.parsed, "Attempt to get a suggestion from not parsed expression");
+
+        let expressions_as_string = self.extracted_expressions.join(", ");
+        format!(r#"{}("{}", {})"#, macro_name, self.output, expressions_as_string)
+    }
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;
+    use expect_test::{expect, Expect};
+
+    fn check(input: &str, expect: &Expect) {
+        let mut parser = FormatStrParser::new((*input).to_owned());
+        let outcome_repr = if parser.parse().is_ok() {
+            // Parsing should be OK, expected repr is "string; expr_1, expr_2".
+            if parser.extracted_expressions.is_empty() {
+                parser.output
+            } else {
+                format!("{}; {}", parser.output, parser.extracted_expressions.join(", "))
+            }
+        } else {
+            // Parsing should fail, expected repr is "-".
+            "-".to_owned()
+        };
+
+        expect.assert_eq(&outcome_repr);
+    }
+
+    #[test]
+    fn format_str_parser() {
+        let test_vector = &[
+            ("no expressions", expect![["no expressions"]]),
+            (r"no expressions with \$0$1", expect![r"no expressions with \\\$0\$1"]),
+            ("{expr} is {2 + 2}", expect![["{} is {}; expr, 2 + 2"]]),
+            ("{expr:?}", expect![["{:?}; expr"]]),
+            ("{expr:1$}", expect![[r"{:1\$}; expr"]]),
+            ("{$0}", expect![[r"{}; \$0"]]),
+            ("{malformed", expect![["-"]]),
+            ("malformed}", expect![["-"]]),
+            ("{{correct", expect![["{{correct"]]),
+            ("correct}}", expect![["correct}}"]]),
+            ("{correct}}}", expect![["{}}}; correct"]]),
+            ("{correct}}}}}", expect![["{}}}}}; correct"]]),
+            ("{incorrect}}", expect![["-"]]),
+            ("placeholders {} {}", expect![["placeholders {} {}; $1, $2"]]),
+            ("mixed {} {2 + 2} {}", expect![["mixed {} {} {}; $1, 2 + 2, $2"]]),
+            (
+                "{SomeStruct { val_a: 0, val_b: 1 }}",
+                expect![["{}; SomeStruct { val_a: 0, val_b: 1 }"]],
+            ),
+            ("{expr:?} is {2.32f64:.5}", expect![["{:?} is {:.5}; expr, 2.32f64"]]),
+            (
+                "{SomeStruct { val_a: 0, val_b: 1 }:?}",
+                expect![["{:?}; SomeStruct { val_a: 0, val_b: 1 }"]],
+            ),
+            ("{     2 + 2        }", expect![["{}; 2 + 2"]]),
+            ("{strsim::jaro_winkle(a)}", expect![["{}; strsim::jaro_winkle(a)"]]),
+            ("{foo::bar::baz()}", expect![["{}; foo::bar::baz()"]]),
+            ("{foo::bar():?}", expect![["{:?}; foo::bar()"]]),
+        ];
+
+        for (input, output) in test_vector {
+            check(input, output)
+        }
+    }
 
     #[test]
     fn test_into_suggestion() {
@@ -79,10 +302,10 @@ mod tests {
         ];
 
         for (kind, input, output) in test_vector {
-            let (parsed_string, exprs) = parse_format_exprs(input).unwrap();
-            let exprs = with_placeholders(exprs);
-            let snippet = format!(r#"{}("{}", {})"#, kind, parsed_string, exprs.join(", "));
-            assert_eq!(&snippet, output);
+            let mut parser = FormatStrParser::new((*input).to_owned());
+            parser.parse().expect("Parsing must succeed");
+
+            assert_eq!(&parser.to_suggestion(*kind), output);
         }
     }
 }
diff --git a/crates/ide-completion/src/config.rs b/crates/ide-completion/src/config.rs
index 54ebce1eb7..a0f5e81b4f 100644
--- a/crates/ide-completion/src/config.rs
+++ b/crates/ide-completion/src/config.rs
@@ -17,7 +17,7 @@ pub struct CompletionConfig {
     pub callable: Option<CallableSnippets>,
     pub snippet_cap: Option<SnippetCap>,
     pub insert_use: InsertUseConfig,
-    pub prefer_core: bool,
+    pub prefer_no_std: bool,
     pub snippets: Vec<Snippet>,
 }
 
diff --git a/crates/ide-completion/src/lib.rs b/crates/ide-completion/src/lib.rs
index 7cefb6bb4a..8d21f4fce0 100644
--- a/crates/ide-completion/src/lib.rs
+++ b/crates/ide-completion/src/lib.rs
@@ -238,7 +238,7 @@ pub fn resolve_completion_edits(
                     db,
                     candidate,
                     config.insert_use.prefix_kind,
-                    config.prefer_core,
+                    config.prefer_no_std,
                 )
             })
             .find(|mod_path| mod_path.to_string() == full_import_path);
diff --git a/crates/ide-completion/src/snippet.rs b/crates/ide-completion/src/snippet.rs
index 2dc62bbdc6..f3b8eae4fe 100644
--- a/crates/ide-completion/src/snippet.rs
+++ b/crates/ide-completion/src/snippet.rs
@@ -178,7 +178,7 @@ fn import_edits(ctx: &CompletionContext<'_>, requires: &[GreenNode]) -> Option<V
             ctx.db,
             item,
             ctx.config.insert_use.prefix_kind,
-            ctx.config.prefer_core,
+            ctx.config.prefer_no_std,
         )?;
         Some((path.len() > 1).then(|| LocatedImport::new(path.clone(), item, item, None)))
     };
diff --git a/crates/ide-db/src/imports/import_assets.rs b/crates/ide-db/src/imports/import_assets.rs
index 53bc516109..40a6a3e897 100644
--- a/crates/ide-db/src/imports/import_assets.rs
+++ b/crates/ide-db/src/imports/import_assets.rs
@@ -212,20 +212,20 @@ impl ImportAssets {
         &self,
         sema: &Semantics<'_, RootDatabase>,
         prefix_kind: PrefixKind,
-        prefer_core: bool,
+        prefer_no_std: bool,
     ) -> Vec<LocatedImport> {
         let _p = profile::span("import_assets::search_for_imports");
-        self.search_for(sema, Some(prefix_kind), prefer_core)
+        self.search_for(sema, Some(prefix_kind), prefer_no_std)
     }
 
     /// 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_core: bool,
+        prefer_no_std: bool,
     ) -> Vec<LocatedImport> {
         let _p = profile::span("import_assets::search_for_relative_paths");
-        self.search_for(sema, None, prefer_core)
+        self.search_for(sema, None, prefer_no_std)
     }
 
     pub fn path_fuzzy_name_to_exact(&mut self, case_sensitive: bool) {
@@ -244,7 +244,7 @@ impl ImportAssets {
         &self,
         sema: &Semantics<'_, RootDatabase>,
         prefixed: Option<PrefixKind>,
-        prefer_core: bool,
+        prefer_no_std: bool,
     ) -> Vec<LocatedImport> {
         let _p = profile::span("import_assets::search_for");
 
@@ -255,7 +255,7 @@ impl ImportAssets {
                 item_for_path_search(sema.db, item)?,
                 &self.module_with_candidate,
                 prefixed,
-                prefer_core,
+                prefer_no_std,
             )
         };
 
@@ -568,12 +568,12 @@ fn get_mod_path(
     item_to_search: ItemInNs,
     module_with_candidate: &Module,
     prefixed: Option<PrefixKind>,
-    prefer_core: bool,
+    prefer_no_std: bool,
 ) -> Option<ModPath> {
     if let Some(prefix_kind) = prefixed {
-        module_with_candidate.find_use_path_prefixed(db, item_to_search, prefix_kind, prefer_core)
+        module_with_candidate.find_use_path_prefixed(db, item_to_search, prefix_kind, prefer_no_std)
     } else {
-        module_with_candidate.find_use_path(db, item_to_search, prefer_core)
+        module_with_candidate.find_use_path(db, item_to_search, prefer_no_std)
     }
 }
 
diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs
index e0bc0f89f0..1ec62a8425 100644
--- a/crates/ide-db/src/lib.rs
+++ b/crates/ide-db/src/lib.rs
@@ -38,7 +38,6 @@ pub mod syntax_helpers {
     pub mod node_ext;
     pub mod insert_whitespace_into_node;
     pub mod format_string;
-    pub mod format_string_exprs;
 
     pub use parser::LexedStr;
 }
diff --git a/crates/ide-db/src/search.rs b/crates/ide-db/src/search.rs
index 6f885fba78..7deffe8e0f 100644
--- a/crates/ide-db/src/search.rs
+++ b/crates/ide-db/src/search.rs
@@ -9,7 +9,6 @@ use std::{mem, sync::Arc};
 use base_db::{FileId, FileRange, SourceDatabase, SourceDatabaseExt};
 use hir::{DefWithBody, HasAttrs, HasSource, InFile, ModuleSource, Semantics, Visibility};
 use once_cell::unsync::Lazy;
-use parser::SyntaxKind;
 use stdx::hash::NoHashHashMap;
 use syntax::{ast, match_ast, AstNode, TextRange, TextSize};
 
@@ -68,7 +67,6 @@ pub enum ReferenceCategory {
     // Create
     Write,
     Read,
-    Import,
     // FIXME: Some day should be able to search in doc comments. Would probably
     // need to switch from enum to bitflags then?
     // DocComment
@@ -579,7 +577,7 @@ impl<'a> FindUsages<'a> {
                 let reference = FileReference {
                     range,
                     name: ast::NameLike::NameRef(name_ref.clone()),
-                    category: is_name_ref_in_import(name_ref).then(|| ReferenceCategory::Import),
+                    category: None,
                 };
                 sink(file_id, reference)
             }
@@ -758,7 +756,7 @@ impl ReferenceCategory {
     fn new(def: &Definition, r: &ast::NameRef) -> Option<ReferenceCategory> {
         // Only Locals and Fields have accesses for now.
         if !matches!(def, Definition::Local(_) | Definition::Field(_)) {
-            return is_name_ref_in_import(r).then(|| ReferenceCategory::Import);
+            return None;
         }
 
         let mode = r.syntax().ancestors().find_map(|node| {
@@ -785,12 +783,3 @@ impl ReferenceCategory {
         mode.or(Some(ReferenceCategory::Read))
     }
 }
-
-fn is_name_ref_in_import(name_ref: &ast::NameRef) -> bool {
-    name_ref
-        .syntax()
-        .parent()
-        .and_then(ast::PathSegment::cast)
-        .and_then(|it| it.parent_path().top_path().syntax().parent())
-        .map_or(false, |it| it.kind() == SyntaxKind::USE_TREE)
-}
diff --git a/crates/ide-db/src/syntax_helpers/format_string_exprs.rs b/crates/ide-db/src/syntax_helpers/format_string_exprs.rs
deleted file mode 100644
index ac6c6e8fee..0000000000
--- a/crates/ide-db/src/syntax_helpers/format_string_exprs.rs
+++ /dev/null
@@ -1,267 +0,0 @@
-//! Tools to work with expressions present in format string literals for the `format_args!` family of macros.
-//! Primarily meant for assists and completions.
-
-/// Enum for represenging extraced format string args.
-/// Can either be extracted expressions (which includes identifiers),
-/// or placeholders `{}`.
-#[derive(Debug, PartialEq, Eq)]
-pub enum Arg {
-    Placeholder,
-    Ident(String),
-    Expr(String),
-}
-
-/**
- Add placeholders like `$1` and `$2` in place of [`Arg::Placeholder`],
- and unwraps the [`Arg::Ident`] and [`Arg::Expr`] enums.
- ```rust
- # use ide_db::syntax_helpers::format_string_exprs::*;
- assert_eq!(with_placeholders(vec![Arg::Ident("ident".to_owned()), Arg::Placeholder, Arg::Expr("expr + 2".to_owned())]), vec!["ident".to_owned(), "$1".to_owned(), "expr + 2".to_owned()])
- ```
-*/
-
-pub fn with_placeholders(args: Vec<Arg>) -> Vec<String> {
-    let mut placeholder_id = 1;
-    args.into_iter()
-        .map(move |a| match a {
-            Arg::Expr(s) | Arg::Ident(s) => s,
-            Arg::Placeholder => {
-                let s = format!("${placeholder_id}");
-                placeholder_id += 1;
-                s
-            }
-        })
-        .collect()
-}
-
-/**
- Parser for a format-like string. It is more allowing in terms of string contents,
- as we expect variable placeholders to be filled with expressions.
-
- Built for completions and assists, and escapes `\` and `$` in output.
- (See the comments on `get_receiver_text()` for detail.)
- Splits a format string that may contain expressions
- like
- ```rust
- assert_eq!(parse("{ident} {} {expr + 42} ").unwrap(), ("{} {} {}", vec![Arg::Ident("ident"), Arg::Placeholder, Arg::Expr("expr + 42")]));
- ```
-*/
-pub fn parse_format_exprs(input: &str) -> Result<(String, Vec<Arg>), ()> {
-    #[derive(Debug, Clone, Copy, PartialEq)]
-    enum State {
-        NotArg,
-        MaybeArg,
-        Expr,
-        Ident,
-        MaybeIncorrect,
-        FormatOpts,
-    }
-
-    let mut state = State::NotArg;
-    let mut current_expr = String::new();
-    let mut extracted_expressions = Vec::new();
-    let mut output = String::new();
-
-    // Count of open braces inside of an expression.
-    // We assume that user knows what they're doing, thus we treat it like a correct pattern, e.g.
-    // "{MyStruct { val_a: 0, val_b: 1 }}".
-    let mut inexpr_open_count = 0;
-
-    let mut chars = input.chars().peekable();
-    while let Some(chr) = chars.next() {
-        match (state, chr) {
-            (State::NotArg, '{') => {
-                output.push(chr);
-                state = State::MaybeArg;
-            }
-            (State::NotArg, '}') => {
-                output.push(chr);
-                state = State::MaybeIncorrect;
-            }
-            (State::NotArg, _) => {
-                if matches!(chr, '\\' | '$') {
-                    output.push('\\');
-                }
-                output.push(chr);
-            }
-            (State::MaybeIncorrect, '}') => {
-                // It's okay, we met "}}".
-                output.push(chr);
-                state = State::NotArg;
-            }
-            (State::MaybeIncorrect, _) => {
-                // Error in the string.
-                return Err(());
-            }
-            // Escaped braces `{{`
-            (State::MaybeArg, '{') => {
-                output.push(chr);
-                state = State::NotArg;
-            }
-            (State::MaybeArg, '}') => {
-                // This is an empty sequence '{}'.
-                output.push(chr);
-                extracted_expressions.push(Arg::Placeholder);
-                state = State::NotArg;
-            }
-            (State::MaybeArg, _) => {
-                if matches!(chr, '\\' | '$') {
-                    current_expr.push('\\');
-                }
-                current_expr.push(chr);
-
-                // While Rust uses the unicode sets of XID_start and XID_continue for Identifiers
-                // this is probably the best we can do to avoid a false positive
-                if chr.is_alphabetic() || chr == '_' {
-                    state = State::Ident;
-                } else {
-                    state = State::Expr;
-                }
-            }
-            (State::Ident | State::Expr, '}') => {
-                if inexpr_open_count == 0 {
-                    output.push(chr);
-
-                    if matches!(state, State::Expr) {
-                        extracted_expressions.push(Arg::Expr(current_expr.trim().into()));
-                    } else {
-                        extracted_expressions.push(Arg::Ident(current_expr.trim().into()));
-                    }
-
-                    current_expr = String::new();
-                    state = State::NotArg;
-                } else {
-                    // We're closing one brace met before inside of the expression.
-                    current_expr.push(chr);
-                    inexpr_open_count -= 1;
-                }
-            }
-            (State::Ident | State::Expr, ':') if matches!(chars.peek(), Some(':')) => {
-                // path separator
-                state = State::Expr;
-                current_expr.push_str("::");
-                chars.next();
-            }
-            (State::Ident | State::Expr, ':') => {
-                if inexpr_open_count == 0 {
-                    // We're outside of braces, thus assume that it's a specifier, like "{Some(value):?}"
-                    output.push(chr);
-
-                    if matches!(state, State::Expr) {
-                        extracted_expressions.push(Arg::Expr(current_expr.trim().into()));
-                    } else {
-                        extracted_expressions.push(Arg::Ident(current_expr.trim().into()));
-                    }
-
-                    current_expr = String::new();
-                    state = State::FormatOpts;
-                } else {
-                    // We're inside of braced expression, assume that it's a struct field name/value delimiter.
-                    current_expr.push(chr);
-                }
-            }
-            (State::Ident | State::Expr, '{') => {
-                state = State::Expr;
-                current_expr.push(chr);
-                inexpr_open_count += 1;
-            }
-            (State::Ident | State::Expr, _) => {
-                if !(chr.is_alphanumeric() || chr == '_' || chr == '#') {
-                    state = State::Expr;
-                }
-
-                if matches!(chr, '\\' | '$') {
-                    current_expr.push('\\');
-                }
-                current_expr.push(chr);
-            }
-            (State::FormatOpts, '}') => {
-                output.push(chr);
-                state = State::NotArg;
-            }
-            (State::FormatOpts, _) => {
-                if matches!(chr, '\\' | '$') {
-                    output.push('\\');
-                }
-                output.push(chr);
-            }
-        }
-    }
-
-    if state != State::NotArg {
-        return Err(());
-    }
-
-    Ok((output, extracted_expressions))
-}
-
-#[cfg(test)]
-mod tests {
-    use super::*;
-    use expect_test::{expect, Expect};
-
-    fn check(input: &str, expect: &Expect) {
-        let (output, exprs) = parse_format_exprs(input).unwrap_or(("-".to_string(), vec![]));
-        let outcome_repr = if !exprs.is_empty() {
-            format!("{}; {}", output, with_placeholders(exprs).join(", "))
-        } else {
-            output
-        };
-
-        expect.assert_eq(&outcome_repr);
-    }
-
-    #[test]
-    fn format_str_parser() {
-        let test_vector = &[
-            ("no expressions", expect![["no expressions"]]),
-            (r"no expressions with \$0$1", expect![r"no expressions with \\\$0\$1"]),
-            ("{expr} is {2 + 2}", expect![["{} is {}; expr, 2 + 2"]]),
-            ("{expr:?}", expect![["{:?}; expr"]]),
-            ("{expr:1$}", expect![[r"{:1\$}; expr"]]),
-            ("{$0}", expect![[r"{}; \$0"]]),
-            ("{malformed", expect![["-"]]),
-            ("malformed}", expect![["-"]]),
-            ("{{correct", expect![["{{correct"]]),
-            ("correct}}", expect![["correct}}"]]),
-            ("{correct}}}", expect![["{}}}; correct"]]),
-            ("{correct}}}}}", expect![["{}}}}}; correct"]]),
-            ("{incorrect}}", expect![["-"]]),
-            ("placeholders {} {}", expect![["placeholders {} {}; $1, $2"]]),
-            ("mixed {} {2 + 2} {}", expect![["mixed {} {} {}; $1, 2 + 2, $2"]]),
-            (
-                "{SomeStruct { val_a: 0, val_b: 1 }}",
-                expect![["{}; SomeStruct { val_a: 0, val_b: 1 }"]],
-            ),
-            ("{expr:?} is {2.32f64:.5}", expect![["{:?} is {:.5}; expr, 2.32f64"]]),
-            (
-                "{SomeStruct { val_a: 0, val_b: 1 }:?}",
-                expect![["{:?}; SomeStruct { val_a: 0, val_b: 1 }"]],
-            ),
-            ("{     2 + 2        }", expect![["{}; 2 + 2"]]),
-            ("{strsim::jaro_winkle(a)}", expect![["{}; strsim::jaro_winkle(a)"]]),
-            ("{foo::bar::baz()}", expect![["{}; foo::bar::baz()"]]),
-            ("{foo::bar():?}", expect![["{:?}; foo::bar()"]]),
-        ];
-
-        for (input, output) in test_vector {
-            check(input, output)
-        }
-    }
-
-    #[test]
-    fn arg_type() {
-        assert_eq!(
-            parse_format_exprs("{_ident} {r#raw_ident} {expr.obj} {name {thing: 42} } {}")
-                .unwrap()
-                .1,
-            vec![
-                Arg::Ident("_ident".to_owned()),
-                Arg::Ident("r#raw_ident".to_owned()),
-                Arg::Expr("expr.obj".to_owned()),
-                Arg::Expr("name {thing: 42}".to_owned()),
-                Arg::Placeholder
-            ]
-        );
-    }
-}
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 06073ca1b2..3034295196 100644
--- a/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs
+++ b/crates/ide-diagnostics/src/handlers/json_is_not_rust.rs
@@ -137,7 +137,7 @@ pub(crate) fn json_in_items(
                                         sema.db,
                                         it,
                                         config.insert_use.prefix_kind,
-                                        config.prefer_core,
+                                        config.prefer_no_std,
                                     ) {
                                         insert_use(
                                             &scope,
@@ -153,7 +153,7 @@ pub(crate) fn json_in_items(
                                         sema.db,
                                         it,
                                         config.insert_use.prefix_kind,
-                                        config.prefer_core,
+                                        config.prefer_no_std,
                                     ) {
                                         insert_use(
                                             &scope,
diff --git a/crates/ide-diagnostics/src/handlers/missing_fields.rs b/crates/ide-diagnostics/src/handlers/missing_fields.rs
index 5a81a55d82..7f140eb6a7 100644
--- a/crates/ide-diagnostics/src/handlers/missing_fields.rs
+++ b/crates/ide-diagnostics/src/handlers/missing_fields.rs
@@ -124,7 +124,7 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option<Vec<Ass
                         let type_path = current_module?.find_use_path(
                             ctx.sema.db,
                             item_for_path_search(ctx.sema.db, item_in_ns)?,
-                            ctx.config.prefer_core,
+                            ctx.config.prefer_no_std,
                         )?;
 
                         use_trivial_constructor(
diff --git a/crates/ide-diagnostics/src/lib.rs b/crates/ide-diagnostics/src/lib.rs
index 22e644bb59..ae299f0584 100644
--- a/crates/ide-diagnostics/src/lib.rs
+++ b/crates/ide-diagnostics/src/lib.rs
@@ -150,7 +150,7 @@ pub struct DiagnosticsConfig {
     pub expr_fill_default: ExprFillDefaultMode,
     // FIXME: We may want to include a whole `AssistConfig` here
     pub insert_use: InsertUseConfig,
-    pub prefer_core: bool,
+    pub prefer_no_std: bool,
 }
 
 impl DiagnosticsConfig {
@@ -171,7 +171,7 @@ impl DiagnosticsConfig {
                 group: false,
                 skip_glob_imports: false,
             },
-            prefer_core: false,
+            prefer_no_std: false,
         }
     }
 }
diff --git a/crates/ide/src/annotations.rs b/crates/ide/src/annotations.rs
index 210c5c7fac..ba4c330bf3 100644
--- a/crates/ide/src/annotations.rs
+++ b/crates/ide/src/annotations.rs
@@ -158,6 +158,7 @@ pub(crate) fn resolve_annotation(db: &RootDatabase, mut annotation: Annotation)
                 &Semantics::new(db),
                 FilePosition { file_id, offset: annotation.range.start() },
                 None,
+                false,
             )
             .map(|result| {
                 result
diff --git a/crates/ide/src/highlight_related.rs b/crates/ide/src/highlight_related.rs
index 1bdd626f1e..f190da326e 100644
--- a/crates/ide/src/highlight_related.rs
+++ b/crates/ide/src/highlight_related.rs
@@ -377,7 +377,6 @@ mod tests {
                         match it {
                             ReferenceCategory::Read => "read",
                             ReferenceCategory::Write => "write",
-                            ReferenceCategory::Import => "import",
                         }
                         .to_string()
                     }),
@@ -424,12 +423,12 @@ struct Foo;
         check(
             r#"
 use crate$0;
-  //^^^^^ import
+  //^^^^^
 use self;
-  //^^^^ import
+  //^^^^
 mod __ {
     use super;
-      //^^^^^ import
+      //^^^^^
 }
 "#,
         );
@@ -437,7 +436,7 @@ mod __ {
             r#"
 //- /main.rs crate:main deps:lib
 use lib$0;
-  //^^^ import
+  //^^^
 //- /lib.rs crate:lib
 "#,
         );
@@ -451,7 +450,7 @@ use lib$0;
 mod foo;
 //- /foo.rs
 use self$0;
- // ^^^^ import
+ // ^^^^
 "#,
         );
     }
diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs
index 0552330814..065b48378b 100644
--- a/crates/ide/src/lib.rs
+++ b/crates/ide/src/lib.rs
@@ -425,8 +425,11 @@ impl Analysis {
         &self,
         position: FilePosition,
         search_scope: Option<SearchScope>,
+        exclude_imports: bool,
     ) -> Cancellable<Option<Vec<ReferenceSearchResult>>> {
-        self.with_db(|db| references::find_all_refs(&Semantics::new(db), position, search_scope))
+        self.with_db(|db| {
+            references::find_all_refs(&Semantics::new(db), position, search_scope, exclude_imports)
+        })
     }
 
     /// Finds all methods and free functions for the file. Does not return tests!
diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs
index e942413c11..5b410c454d 100644
--- a/crates/ide/src/references.rs
+++ b/crates/ide/src/references.rs
@@ -54,6 +54,7 @@ pub(crate) fn find_all_refs(
     sema: &Semantics<'_, RootDatabase>,
     position: FilePosition,
     search_scope: Option<SearchScope>,
+    exclude_imports: bool,
 ) -> Option<Vec<ReferenceSearchResult>> {
     let _p = profile::span("find_all_refs");
     let syntax = sema.parse(position.file_id).syntax().clone();
@@ -79,6 +80,10 @@ pub(crate) fn find_all_refs(
                 retain_adt_literal_usages(&mut usages, def, sema);
             }
 
+            if exclude_imports {
+                filter_import_references(&mut usages);
+            }
+
             let references = usages
                 .into_iter()
                 .map(|(file_id, refs)| {
@@ -112,6 +117,17 @@ pub(crate) fn find_all_refs(
     }
 }
 
+fn filter_import_references(usages: &mut UsageSearchResult) {
+    for (_file_id, refs) in &mut usages.references {
+        refs.retain(|it| match it.name.as_name_ref() {
+            Some(name_ref) => {
+                !name_ref.syntax().ancestors().any(|it_ref| matches!(it_ref.kind(), USE))
+            }
+            None => true,
+        });
+    }
+}
+
 pub(crate) fn find_defs<'a>(
     sema: &'a Semantics<'_, RootDatabase>,
     syntax: &SyntaxNode,
@@ -742,7 +758,7 @@ pub struct Foo {
             expect![[r#"
                 foo Module FileId(0) 0..8 4..7
 
-                FileId(0) 14..17 Import
+                FileId(0) 14..17
             "#]],
         );
     }
@@ -760,7 +776,7 @@ use self$0;
             expect![[r#"
                 foo Module FileId(0) 0..8 4..7
 
-                FileId(1) 4..8 Import
+                FileId(1) 4..8
             "#]],
         );
     }
@@ -775,7 +791,7 @@ use self$0;
             expect![[r#"
                 Module FileId(0) 0..10
 
-                FileId(0) 4..8 Import
+                FileId(0) 4..8
             "#]],
         );
     }
@@ -803,7 +819,7 @@ pub(super) struct Foo$0 {
             expect![[r#"
                 Foo Struct FileId(2) 0..41 18..21
 
-                FileId(1) 20..23 Import
+                FileId(1) 20..23
                 FileId(1) 47..50
             "#]],
         );
@@ -966,7 +982,7 @@ fn g() { f(); }
             expect![[r#"
                 f Function FileId(0) 22..31 25..26
 
-                FileId(1) 11..12 Import
+                FileId(1) 11..12
                 FileId(1) 24..25
             "#]],
         );
@@ -1094,7 +1110,7 @@ impl Foo {
 
     fn check_with_scope(ra_fixture: &str, search_scope: Option<SearchScope>, expect: Expect) {
         let (analysis, pos) = fixture::position(ra_fixture);
-        let refs = analysis.find_all_refs(pos, search_scope).unwrap().unwrap();
+        let refs = analysis.find_all_refs(pos, search_scope, false).unwrap().unwrap();
 
         let mut actual = String::new();
         for refs in refs {
@@ -1424,9 +1440,9 @@ pub use level1::Foo;
             expect![[r#"
                 Foo Struct FileId(0) 0..15 11..14
 
-                FileId(1) 16..19 Import
-                FileId(2) 16..19 Import
-                FileId(3) 16..19 Import
+                FileId(1) 16..19
+                FileId(2) 16..19
+                FileId(3) 16..19
             "#]],
         );
     }
@@ -1454,7 +1470,7 @@ lib::foo!();
             expect![[r#"
                 foo Macro FileId(1) 0..61 29..32
 
-                FileId(0) 46..49 Import
+                FileId(0) 46..49
                 FileId(2) 0..3
                 FileId(3) 5..8
             "#]],
@@ -1617,7 +1633,7 @@ struct Foo;
             expect![[r#"
                 derive_identity Derive FileId(2) 1..107 45..60
 
-                FileId(0) 17..31 Import
+                FileId(0) 17..31
                 FileId(0) 56..70
             "#]],
         );
diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs
index e0384e67d4..8504712c4b 100644
--- a/crates/rust-analyzer/src/config.rs
+++ b/crates/rust-analyzer/src/config.rs
@@ -262,8 +262,8 @@ config_data! {
         imports_group_enable: bool                           = "true",
         /// Whether to allow import insertion to merge new imports into single path glob imports like `use std::fmt::*;`.
         imports_merge_glob: bool           = "true",
-        /// Prefer to use imports of the core crate over the std crate.
-        imports_prefer_core: bool                     = "false",
+        /// Prefer to unconditionally use imports of the core and alloc crate, over the std crate.
+        imports_prefer_no_std: bool                     = "false",
         /// The path structure for newly inserted paths to use.
         imports_prefix: ImportPrefixDef               = "\"plain\"",
 
@@ -922,7 +922,7 @@ impl Config {
                 ExprFillDefaultDef::Default => ExprFillDefaultMode::Default,
             },
             insert_use: self.insert_use_config(),
-            prefer_core: self.data.imports_prefer_core,
+            prefer_no_std: self.data.imports_prefer_no_std,
         }
     }
 
@@ -1138,7 +1138,7 @@ impl Config {
                 CallableCompletionDef::None => None,
             },
             insert_use: self.insert_use_config(),
-            prefer_core: self.data.imports_prefer_core,
+            prefer_no_std: self.data.imports_prefer_no_std,
             snippet_cap: SnippetCap::new(try_or_def!(
                 self.caps
                     .text_document
@@ -1166,7 +1166,7 @@ impl Config {
             snippet_cap: SnippetCap::new(self.experimental("snippetTextEdit")),
             allowed: None,
             insert_use: self.insert_use_config(),
-            prefer_core: self.data.imports_prefer_core,
+            prefer_no_std: self.data.imports_prefer_no_std,
         }
     }
 
diff --git a/crates/rust-analyzer/src/handlers.rs b/crates/rust-analyzer/src/handlers.rs
index baf6dd7488..7b486744da 100644
--- a/crates/rust-analyzer/src/handlers.rs
+++ b/crates/rust-analyzer/src/handlers.rs
@@ -10,8 +10,8 @@ use std::{
 use anyhow::Context;
 use ide::{
     AnnotationConfig, AssistKind, AssistResolveStrategy, FileId, FilePosition, FileRange,
-    HoverAction, HoverGotoTypeData, Query, RangeInfo, ReferenceCategory, Runnable, RunnableKind,
-    SingleResolve, SourceChange, TextEdit,
+    HoverAction, HoverGotoTypeData, Query, RangeInfo, Runnable, RunnableKind, SingleResolve,
+    SourceChange, TextEdit,
 };
 use ide_db::SymbolKind;
 use lsp_server::ErrorCode;
@@ -1014,7 +1014,7 @@ pub(crate) fn handle_references(
 
     let exclude_imports = snap.config.find_all_refs_exclude_imports();
 
-    let refs = match snap.analysis.find_all_refs(position, None)? {
+    let refs = match snap.analysis.find_all_refs(position, None, exclude_imports)? {
         None => return Ok(None),
         Some(refs) => refs,
     };
@@ -1034,11 +1034,7 @@ pub(crate) fn handle_references(
             refs.references
                 .into_iter()
                 .flat_map(|(file_id, refs)| {
-                    refs.into_iter()
-                        .filter(|&(_, category)| {
-                            !exclude_imports || category != Some(ReferenceCategory::Import)
-                        })
-                        .map(move |(range, _)| FileRange { file_id, range })
+                    refs.into_iter().map(move |(range, _)| FileRange { file_id, range })
                 })
                 .chain(decl)
         })
@@ -1289,7 +1285,7 @@ pub(crate) fn handle_document_highlight(
         .into_iter()
         .map(|ide::HighlightedRange { range, category }| lsp_types::DocumentHighlight {
             range: to_proto::range(&line_index, range),
-            kind: category.and_then(to_proto::document_highlight_kind),
+            kind: category.map(to_proto::document_highlight_kind),
         })
         .collect();
     Ok(Some(res))
@@ -1658,7 +1654,9 @@ fn show_ref_command_link(
     position: &FilePosition,
 ) -> Option<lsp_ext::CommandLinkGroup> {
     if snap.config.hover_actions().references && snap.config.client_commands().show_reference {
-        if let Some(ref_search_res) = snap.analysis.find_all_refs(*position, None).unwrap_or(None) {
+        if let Some(ref_search_res) =
+            snap.analysis.find_all_refs(*position, None, false).unwrap_or(None)
+        {
             let uri = to_proto::url(snap, position.file_id);
             let line_index = snap.file_line_index(position.file_id).ok()?;
             let position = to_proto::position(&line_index, position.offset);
diff --git a/crates/rust-analyzer/src/integrated_benchmarks.rs b/crates/rust-analyzer/src/integrated_benchmarks.rs
index 5dbb64d7df..96b1cb6b12 100644
--- a/crates/rust-analyzer/src/integrated_benchmarks.rs
+++ b/crates/rust-analyzer/src/integrated_benchmarks.rs
@@ -145,7 +145,7 @@ fn integrated_completion_benchmark() {
                 skip_glob_imports: true,
             },
             snippets: Vec::new(),
-            prefer_core: false,
+            prefer_no_std: false,
         };
         let position =
             FilePosition { file_id, offset: TextSize::try_from(completion_offset).unwrap() };
@@ -183,7 +183,7 @@ fn integrated_completion_benchmark() {
                 skip_glob_imports: true,
             },
             snippets: Vec::new(),
-            prefer_core: false,
+            prefer_no_std: false,
         };
         let position =
             FilePosition { file_id, offset: TextSize::try_from(completion_offset).unwrap() };
diff --git a/crates/rust-analyzer/src/to_proto.rs b/crates/rust-analyzer/src/to_proto.rs
index 1de801e23e..e083b9d0e3 100644
--- a/crates/rust-analyzer/src/to_proto.rs
+++ b/crates/rust-analyzer/src/to_proto.rs
@@ -83,11 +83,10 @@ pub(crate) fn structure_node_kind(kind: StructureNodeKind) -> lsp_types::SymbolK
 
 pub(crate) fn document_highlight_kind(
     category: ReferenceCategory,
-) -> Option<lsp_types::DocumentHighlightKind> {
+) -> lsp_types::DocumentHighlightKind {
     match category {
-        ReferenceCategory::Read => Some(lsp_types::DocumentHighlightKind::READ),
-        ReferenceCategory::Write => Some(lsp_types::DocumentHighlightKind::WRITE),
-        ReferenceCategory::Import => None,
+        ReferenceCategory::Read => lsp_types::DocumentHighlightKind::READ,
+        ReferenceCategory::Write => lsp_types::DocumentHighlightKind::WRITE,
     }
 }
 
diff --git a/docs/user/generated_config.adoc b/docs/user/generated_config.adoc
index 2b02c64b66..e596e08f2c 100644
--- a/docs/user/generated_config.adoc
+++ b/docs/user/generated_config.adoc
@@ -353,10 +353,10 @@ 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::*;`.
 --
-[[rust-analyzer.imports.prefer.core]]rust-analyzer.imports.prefer.core (default: `false`)::
+[[rust-analyzer.imports.prefer.no.std]]rust-analyzer.imports.prefer.no.std (default: `false`)::
 +
 --
-Prefer to use imports of the core crate over the std crate.
+Prefer to unconditionally use imports of the core and alloc crate, over the std crate.
 --
 [[rust-analyzer.imports.prefix]]rust-analyzer.imports.prefix (default: `"plain"`)::
 +
diff --git a/editors/code/package.json b/editors/code/package.json
index cfba00d3ed..6aa74ce92a 100644
--- a/editors/code/package.json
+++ b/editors/code/package.json
@@ -798,8 +798,8 @@
                     "default": true,
                     "type": "boolean"
                 },
-                "rust-analyzer.imports.prefer.core": {
-                    "markdownDescription": "Prefer to use imports of the core crate over the std crate.",
+                "rust-analyzer.imports.prefer.no.std": {
+                    "markdownDescription": "Prefer to unconditionally use imports of the core and alloc crate, over the std crate.",
                     "default": false,
                     "type": "boolean"
                 },


Test patch:
diff --git a/crates/ide-assists/src/tests.rs b/crates/ide-assists/src/tests.rs
index 4e589dc86a..258144bae3 100644
--- a/crates/ide-assists/src/tests.rs
+++ b/crates/ide-assists/src/tests.rs
@@ -29,7 +29,7 @@ pub(crate) const TEST_CONFIG: AssistConfig = AssistConfig {
         group: true,
         skip_glob_imports: true,
     },
-    prefer_core: false,
+    prefer_no_std: false,
 };
 
 pub(crate) fn with_single_file(text: &str) -> (RootDatabase, FileId) {
diff --git a/crates/ide-assists/src/tests/generated.rs b/crates/ide-assists/src/tests/generated.rs
index 3a696635af..227e2300f9 100644
--- a/crates/ide-assists/src/tests/generated.rs
+++ b/crates/ide-assists/src/tests/generated.rs
@@ -1591,37 +1591,6 @@ fn apply<T, U, F>(f: F, x: T) -> U where F: FnOnce(T) -> U {
     )
 }
 
-#[test]
-fn doctest_move_format_string_arg() {
-    check_doc_test(
-        "move_format_string_arg",
-        r#####"
-macro_rules! format_args {
-    ($lit:literal $(tt:tt)*) => { 0 },
-}
-macro_rules! print {
-    ($($arg:tt)*) => (std::io::_print(format_args!($($arg)*)));
-}
-
-fn main() {
-    print!("{x + 1}$0");
-}
-"#####,
-        r#####"
-macro_rules! format_args {
-    ($lit:literal $(tt:tt)*) => { 0 },
-}
-macro_rules! print {
-    ($($arg:tt)*) => (std::io::_print(format_args!($($arg)*)));
-}
-
-fn main() {
-    print!("{}"$0, x + 1);
-}
-"#####,
-    )
-}
-
 #[test]
 fn doctest_move_from_mod_rs() {
     check_doc_test(
diff --git a/crates/ide-completion/src/tests.rs b/crates/ide-completion/src/tests.rs
index d24c914856..9e2beb9ee3 100644
--- a/crates/ide-completion/src/tests.rs
+++ b/crates/ide-completion/src/tests.rs
@@ -66,7 +66,7 @@ pub(crate) const TEST_CONFIG: CompletionConfig = CompletionConfig {
     enable_private_editable: false,
     callable: Some(CallableSnippets::FillArguments),
     snippet_cap: SnippetCap::new(true),
-    prefer_core: false,
+    prefer_no_std: false,
     insert_use: InsertUseConfig {
         granularity: ImportGranularity::Crate,
         prefix_kind: PrefixKind::Plain,