Repository: rust-lang/rust-analyzer
Pull request #15206 (2023-07-03 18:34:54)

internal: Format let-else
As nightly finally got support for it I went ahead and formatted r-a with the latest nightly, then with the latest stable (in case other stuff changed)


Patch:
diff --git a/Cargo.lock b/Cargo.lock
index e94dd9b407..5621224116 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -730,7 +730,7 @@ dependencies = [
  "indexmap 2.0.0",
  "itertools",
  "limit",
- "line-index 0.1.0-pre.1",
+ "line-index 0.1.0-pre.1 (registry+https://github.com/rust-lang/crates.io-index)",
  "memchr",
  "nohash-hasher",
  "once_cell",
@@ -947,8 +947,6 @@ version = "0.0.0"
 [[package]]
 name = "line-index"
 version = "0.1.0-pre.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2cad96769710c1745e11d4f940a8ff36000ade4bbada4285b001cb8aa2f745ce"
 dependencies = [
  "nohash-hasher",
  "text-size",
@@ -956,7 +954,9 @@ dependencies = [
 
 [[package]]
 name = "line-index"
-version = "0.1.0"
+version = "0.1.0-pre.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2cad96769710c1745e11d4f940a8ff36000ade4bbada4285b001cb8aa2f745ce"
 dependencies = [
  "nohash-hasher",
  "text-size",
diff --git a/crates/hir-def/src/attr.rs b/crates/hir-def/src/attr.rs
index 3ff58814d1..a16670b244 100644
--- a/crates/hir-def/src/attr.rs
+++ b/crates/hir-def/src/attr.rs
@@ -137,13 +137,16 @@ impl Attrs {
 
                 let cfg_options = &crate_graph[krate].cfg_options;
 
-                let Some(variant) = enum_.variants.clone().filter(|variant| {
-                    let attrs = item_tree.attrs(db, krate, (*variant).into());
-                    attrs.is_cfg_enabled(cfg_options)
-                })
-                .zip(0u32..)
-                .find(|(_variant, idx)| it.local_id == Idx::from_raw(RawIdx::from(*idx)))
-                .map(|(variant, _idx)| variant)
+                let Some(variant) = enum_
+                    .variants
+                    .clone()
+                    .filter(|variant| {
+                        let attrs = item_tree.attrs(db, krate, (*variant).into());
+                        attrs.is_cfg_enabled(cfg_options)
+                    })
+                    .zip(0u32..)
+                    .find(|(_variant, idx)| it.local_id == Idx::from_raw(RawIdx::from(*idx)))
+                    .map(|(variant, _idx)| variant)
                 else {
                     return Arc::new(res);
                 };
diff --git a/crates/hir-def/src/body/lower.rs b/crates/hir-def/src/body/lower.rs
index b375ec63a6..b89eb9fe62 100644
--- a/crates/hir-def/src/body/lower.rs
+++ b/crates/hir-def/src/body/lower.rs
@@ -1451,9 +1451,7 @@ impl ExprCollector<'_> {
         &self,
         lifetime: Option<ast::Lifetime>,
     ) -> Result<Option<LabelId>, BodyDiagnostic> {
-        let Some(lifetime) = lifetime else {
-            return Ok(None)
-        };
+        let Some(lifetime) = lifetime else { return Ok(None) };
         let name = Name::new_lifetime(&lifetime);
 
         for (rib_idx, rib) in self.label_ribs.iter().enumerate().rev() {
diff --git a/crates/hir-def/src/find_path.rs b/crates/hir-def/src/find_path.rs
index df2af4c89b..8c49ae1c4a 100644
--- a/crates/hir-def/src/find_path.rs
+++ b/crates/hir-def/src/find_path.rs
@@ -360,7 +360,7 @@ fn calculate_best_path(
                     prefer_no_std,
                 )?;
                 cov_mark::hit!(partially_imported);
-                path.push_segment(info.name.clone());
+                path.push_segment(info.path.segments.last()?.clone());
                 Some(path)
             })
         });
diff --git a/crates/hir-def/src/import_map.rs b/crates/hir-def/src/import_map.rs
index d742b2eef0..ec150dc068 100644
--- a/crates/hir-def/src/import_map.rs
+++ b/crates/hir-def/src/import_map.rs
@@ -1,14 +1,13 @@
 //! A map of all publicly exported items in a crate.
 
-use std::collections::hash_map::Entry;
 use std::{fmt, hash::BuildHasherDefault};
 
 use base_db::CrateId;
 use fst::{self, Streamer};
 use hir_expand::name::Name;
-use indexmap::IndexMap;
+use indexmap::{map::Entry, IndexMap};
 use itertools::Itertools;
-use rustc_hash::{FxHashMap, FxHashSet, FxHasher};
+use rustc_hash::{FxHashSet, FxHasher};
 use triomphe::Arc;
 
 use crate::{
@@ -18,23 +17,52 @@ use crate::{
 
 type FxIndexMap<K, V> = IndexMap<K, V, BuildHasherDefault<FxHasher>>;
 
-// FIXME: Support aliases: an item may be exported under multiple names, so `ImportInfo` should
-// have `Vec<(Name, ModuleId)>` instead of `(Name, ModuleId)`.
 /// Item import details stored in the `ImportMap`.
 #[derive(Debug, Clone, Eq, PartialEq)]
 pub struct ImportInfo {
-    /// A name that can be used to import the item, relative to the crate's root.
-    pub name: Name,
+    /// A path that can be used to import the item, relative to the crate's root.
+    pub path: ImportPath,
     /// The module containing this item.
     pub container: ModuleId,
     /// Whether the import is a trait associated item or not.
     pub is_trait_assoc_item: bool,
 }
 
-/// A map from publicly exported items to its name.
+#[derive(Debug, Clone, Eq, PartialEq)]
+pub struct ImportPath {
+    pub segments: Vec<Name>,
+}
+
+impl ImportPath {
+    pub fn display<'a>(&'a self, db: &'a dyn DefDatabase) -> impl fmt::Display + 'a {
+        struct Display<'a> {
+            db: &'a dyn DefDatabase,
+            path: &'a ImportPath,
+        }
+        impl fmt::Display for Display<'_> {
+            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+                fmt::Display::fmt(
+                    &self.path.segments.iter().map(|it| it.display(self.db.upcast())).format("::"),
+                    f,
+                )
+            }
+        }
+        Display { db, path: self }
+    }
+
+    fn len(&self) -> usize {
+        self.segments.len()
+    }
+}
+
+/// A map from publicly exported items to the path needed to import/name them from a downstream
+/// crate.
 ///
 /// Reexports of items are taken into account, ie. if something is exported under multiple
 /// names, the one with the shortest import path will be used.
+///
+/// Note that all paths are relative to the containing crate's root, so the crate name still needs
+/// to be prepended to the `ModPath` before the path is valid.
 #[derive(Default)]
 pub struct ImportMap {
     map: FxIndexMap<ItemInNs, ImportInfo>,
@@ -42,58 +70,122 @@ pub struct ImportMap {
     /// List of keys stored in `map`, sorted lexicographically by their `ModPath`. Indexed by the
     /// values returned by running `fst`.
     ///
-    /// Since a name can refer to multiple items due to namespacing, we store all items with the
-    /// same name right after each other. This allows us to find all items after the FST gives us
+    /// Since a path can refer to multiple items due to namespacing, we store all items with the
+    /// same path right after each other. This allows us to find all items after the FST gives us
     /// the index of the first one.
     importables: Vec<ItemInNs>,
     fst: fst::Map<Vec<u8>>,
 }
 
 impl ImportMap {
-    pub(crate) fn import_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<Self> {
+    pub fn import_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<Self> {
         let _p = profile::span("import_map_query");
 
-        let map = collect_import_map(db, krate);
+        let mut import_map = collect_import_map(db, krate);
 
-        let mut importables: Vec<_> = map
+        let mut importables = import_map
+            .map
             .iter()
-            // We've only collected items, whose name cannot be tuple field.
-            .map(|(&item, info)| (item, info.name.as_str().unwrap().to_ascii_lowercase()))
-            .collect();
-        importables.sort_by(|(_, lhs_name), (_, rhs_name)| lhs_name.cmp(rhs_name));
+            .map(|(item, info)| (item, fst_path(db, &info.path)))
+            .collect::<Vec<_>>();
+        importables.sort_by(|(_, fst_path), (_, fst_path2)| fst_path.cmp(fst_path2));
 
         // Build the FST, taking care not to insert duplicate values.
+
         let mut builder = fst::MapBuilder::memory();
-        let iter = importables.iter().enumerate().dedup_by(|lhs, rhs| lhs.1 .1 == rhs.1 .1);
-        for (start_idx, (_, name)) in iter {
-            let _ = builder.insert(name, start_idx as u64);
+        let mut last_batch_start = 0;
+
+        for idx in 0..importables.len() {
+            let key = &importables[last_batch_start].1;
+            if let Some((_, fst_path)) = importables.get(idx + 1) {
+                if key == fst_path {
+                    continue;
+                }
+            }
+
+            let _ = builder.insert(key, last_batch_start as u64);
+
+            last_batch_start = idx + 1;
         }
 
-        Arc::new(ImportMap {
-            map,
-            fst: builder.into_map(),
-            importables: importables.into_iter().map(|(item, _)| item).collect(),
-        })
+        import_map.fst = builder.into_map();
+        import_map.importables = importables.iter().map(|&(&item, _)| item).collect();
+
+        Arc::new(import_map)
+    }
+
+    /// Returns the `ModPath` needed to import/mention `item`, relative to this crate's root.
+    pub fn path_of(&self, item: ItemInNs) -> Option<&ImportPath> {
+        self.import_info_for(item).map(|it| &it.path)
     }
 
     pub fn import_info_for(&self, item: ItemInNs) -> Option<&ImportInfo> {
         self.map.get(&item)
     }
+
+    #[cfg(test)]
+    fn fmt_for_test(&self, db: &dyn DefDatabase) -> String {
+        let mut importable_paths: Vec<_> = self
+            .map
+            .iter()
+            .map(|(item, info)| {
+                let ns = match item {
+                    ItemInNs::Types(_) => "t",
+                    ItemInNs::Values(_) => "v",
+                    ItemInNs::Macros(_) => "m",
+                };
+                format!("- {} ({ns})", info.path.display(db))
+            })
+            .collect();
+
+        importable_paths.sort();
+        importable_paths.join("\n")
+    }
+
+    fn collect_trait_assoc_items(
+        &mut self,
+        db: &dyn DefDatabase,
+        tr: TraitId,
+        is_type_in_ns: bool,
+        original_import_info: &ImportInfo,
+    ) {
+        let _p = profile::span("collect_trait_assoc_items");
+        for (assoc_item_name, item) in &db.trait_data(tr).items {
+            let module_def_id = match item {
+                AssocItemId::FunctionId(f) => ModuleDefId::from(*f),
+                AssocItemId::ConstId(c) => ModuleDefId::from(*c),
+                // cannot use associated type aliases directly: need a `<Struct as Trait>::TypeAlias`
+                // qualifier, ergo no need to store it for imports in import_map
+                AssocItemId::TypeAliasId(_) => {
+                    cov_mark::hit!(type_aliases_ignored);
+                    continue;
+                }
+            };
+            let assoc_item = if is_type_in_ns {
+                ItemInNs::Types(module_def_id)
+            } else {
+                ItemInNs::Values(module_def_id)
+            };
+
+            let mut assoc_item_info = original_import_info.clone();
+            assoc_item_info.path.segments.push(assoc_item_name.to_owned());
+            assoc_item_info.is_trait_assoc_item = true;
+            self.map.insert(assoc_item, assoc_item_info);
+        }
+    }
 }
 
-fn collect_import_map(db: &dyn DefDatabase, krate: CrateId) -> FxIndexMap<ItemInNs, ImportInfo> {
+fn collect_import_map(db: &dyn DefDatabase, krate: CrateId) -> ImportMap {
     let _p = profile::span("collect_import_map");
 
     let def_map = db.crate_def_map(krate);
-    let mut map = FxIndexMap::default();
+    let mut import_map = ImportMap::default();
 
     // We look only into modules that are public(ly reexported), starting with the crate root.
+    let empty = ImportPath { segments: vec![] };
     let root = def_map.module_id(DefMap::ROOT);
-    let mut worklist = vec![(root, 0)];
-    // Records items' minimum module depth.
-    let mut depth_map = FxHashMap::default();
-
-    while let Some((module, depth)) = worklist.pop() {
+    let mut worklist = vec![(root, empty)];
+    while let Some((module, mod_path)) = worklist.pop() {
         let ext_def_map;
         let mod_data = if module.krate == krate {
             &def_map[module.local_id]
@@ -113,83 +205,52 @@ fn collect_import_map(db: &dyn DefDatabase, krate: CrateId) -> FxIndexMap<ItemIn
         });
 
         for (name, per_ns) in visible_items {
-            for item in per_ns.iter_items() {
-                let import_info = ImportInfo {
-                    name: name.clone(),
-                    container: module,
-                    is_trait_assoc_item: false,
-                };
+            let mk_path = || {
+                let mut path = mod_path.clone();
+                path.segments.push(name.clone());
+                path
+            };
 
-                match depth_map.entry(item) {
-                    Entry::Vacant(entry) => {
-                        entry.insert(depth);
-                    }
-                    Entry::Occupied(mut entry) => {
-                        if depth < *entry.get() {
-                            entry.insert(depth);
-                        } else {
-                            continue;
-                        }
-                    }
-                }
+            for item in per_ns.iter_items() {
+                let path = mk_path();
+                let path_len = path.len();
+                let import_info =
+                    ImportInfo { path, container: module, is_trait_assoc_item: false };
 
                 if let Some(ModuleDefId::TraitId(tr)) = item.as_module_def_id() {
-                    collect_trait_assoc_items(
+                    import_map.collect_trait_assoc_items(
                         db,
-                        &mut map,
                         tr,
                         matches!(item, ItemInNs::Types(_)),
                         &import_info,
                     );
                 }
 
-                map.insert(item, import_info);
+                match import_map.map.entry(item) {
+                    Entry::Vacant(entry) => {
+                        entry.insert(import_info);
+                    }
+                    Entry::Occupied(mut entry) => {
+                        // If the new path is shorter, prefer that one.
+                        if path_len < entry.get().path.len() {
+                            *entry.get_mut() = import_info;
+                        } else {
+                            continue;
+                        }
+                    }
+                }
 
-                // If we've just added a module, descend into it. We might traverse modules
-                // multiple times, but only if the module depth is smaller (else we `continue`
-                // above).
+                // If we've just added a path to a module, descend into it. We might traverse
+                // modules multiple times, but only if the new path to it is shorter than the
+                // first (else we `continue` above).
                 if let Some(ModuleDefId::ModuleId(mod_id)) = item.as_module_def_id() {
-                    worklist.push((mod_id, depth + 1));
+                    worklist.push((mod_id, mk_path()));
                 }
             }
         }
     }
 
-    map
-}
-
-fn collect_trait_assoc_items(
-    db: &dyn DefDatabase,
-    map: &mut FxIndexMap<ItemInNs, ImportInfo>,
-    tr: TraitId,
-    is_type_in_ns: bool,
-    trait_import_info: &ImportInfo,
-) {
-    let _p = profile::span("collect_trait_assoc_items");
-    for (assoc_item_name, item) in &db.trait_data(tr).items {
-        let module_def_id = match item {
-            AssocItemId::FunctionId(f) => ModuleDefId::from(*f),
-            AssocItemId::ConstId(c) => ModuleDefId::from(*c),
-            // cannot use associated type aliases directly: need a `<Struct as Trait>::TypeAlias`
-            // qualifier, ergo no need to store it for imports in import_map
-            AssocItemId::TypeAliasId(_) => {
-                cov_mark::hit!(type_aliases_ignored);
-                continue;
-            }
-        };
-        let assoc_item = if is_type_in_ns {
-            ItemInNs::Types(module_def_id)
-        } else {
-            ItemInNs::Values(module_def_id)
-        };
-
-        let assoc_item_info = ImportInfo {
-            container: trait_import_info.container,
-            name: assoc_item_name.clone(),
-            is_trait_assoc_item: true,
-        };
-        map.insert(assoc_item, assoc_item_info);
-    }
+    import_map
 }
 
 impl PartialEq for ImportMap {
@@ -203,7 +264,7 @@ impl Eq for ImportMap {}
 
 impl fmt::Debug for ImportMap {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        let mut importable_names: Vec<_> = self
+        let mut importable_paths: Vec<_> = self
             .map
             .iter()
             .map(|(item, _)| match item {
@@ -213,40 +274,56 @@ impl fmt::Debug for ImportMap {
             })
             .collect();
 
-        importable_names.sort();
-        f.write_str(&importable_names.join("\n"))
+        importable_paths.sort();
+        f.write_str(&importable_paths.join("\n"))
     }
 }
 
+fn fst_path(db: &dyn DefDatabase, path: &ImportPath) -> String {
+    let _p = profile::span("fst_path");
+    let mut s = path.display(db).to_string();
+    s.make_ascii_lowercase();
+    s
+}
+
+#[derive(Debug, Eq, PartialEq, Hash)]
+pub enum ImportKind {
+    Module,
+    Function,
+    Adt,
+    EnumVariant,
+    Const,
+    Static,
+    Trait,
+    TraitAlias,
+    TypeAlias,
+    BuiltinType,
+    AssociatedItem,
+    Macro,
+}
+
 /// A way to match import map contents against the search query.
 #[derive(Debug)]
-enum SearchMode {
+pub enum SearchMode {
     /// Import map entry should strictly match the query string.
-    Exact,
+    Equals,
+    /// Import map entry should contain the query string.
+    Contains,
     /// Import map entry should contain all letters from the query string,
     /// in the same order, but not necessary adjacent.
     Fuzzy,
 }
 
-/// Three possible ways to search for the name in associated and/or other items.
-#[derive(Debug, Clone, Copy)]
-pub enum AssocSearchMode {
-    /// Search for the name in both associated and other items.
-    Include,
-    /// Search for the name in other items only.
-    Exclude,
-    /// Search for the name in the associated items only.
-    AssocItemsOnly,
-}
-
 #[derive(Debug)]
 pub struct Query {
     query: String,
     lowercased: String,
+    name_only: bool,
+    assoc_items_only: bool,
     search_mode: SearchMode,
-    assoc_mode: AssocSearchMode,
     case_sensitive: bool,
     limit: usize,
+    exclude_import_kinds: FxHashSet<ImportKind>,
 }
 
 impl Query {
@@ -255,21 +332,30 @@ impl Query {
         Self {
             query,
             lowercased,
-            search_mode: SearchMode::Exact,
-            assoc_mode: AssocSearchMode::Include,
+            name_only: false,
+            assoc_items_only: false,
+            search_mode: SearchMode::Contains,
             case_sensitive: false,
-            limit: usize::MAX,
+            limit: usize::max_value(),
+            exclude_import_kinds: FxHashSet::default(),
         }
     }
 
-    /// Fuzzy finds items instead of exact matching.
-    pub fn fuzzy(self) -> Self {
-        Self { search_mode: SearchMode::Fuzzy, ..self }
+    /// Matches entries' names only, ignoring the rest of
+    /// the qualifier.
+    /// Example: for `std::marker::PhantomData`, the name is `PhantomData`.
+    pub fn name_only(self) -> Self {
+        Self { name_only: true, ..self }
     }
 
-    /// Specifies whether we want to include associated items in the result.
-    pub fn assoc_search_mode(self, assoc_mode: AssocSearchMode) -> Self {
-        Self { assoc_mode, ..self }
+    /// Matches only the entries that are associated items, ignoring the rest.
+    pub fn assoc_items_only(self) -> Self {
+        Self { assoc_items_only: true, ..self }
+    }
+
+    /// Specifies the way to search for the entries using the query.
+    pub fn search_mode(self, search_mode: SearchMode) -> Self {
+        Self { search_mode, ..self }
     }
 
     /// Limits the returned number of items to `limit`.
@@ -282,6 +368,12 @@ impl Query {
         Self { case_sensitive: true, ..self }
     }
 
+    /// Do not include imports of the specified kind in the search results.
+    pub fn exclude_import_kind(mut self, import_kind: ImportKind) -> Self {
+        self.exclude_import_kinds.insert(import_kind);
+        self
+    }
+
     fn import_matches(
         &self,
         db: &dyn DefDatabase,
@@ -289,36 +381,49 @@ impl Query {
         enforce_lowercase: bool,
     ) -> bool {
         let _p = profile::span("import_map::Query::import_matches");
-        match (import.is_trait_assoc_item, self.assoc_mode) {
-            (true, AssocSearchMode::Exclude) => return false,
-            (false, AssocSearchMode::AssocItemsOnly) => return false,
-            _ => {}
+        if import.is_trait_assoc_item {
+            if self.exclude_import_kinds.contains(&ImportKind::AssociatedItem) {
+                return false;
+            }
+        } else if self.assoc_items_only {
+            return false;
         }
 
-        let mut input = import.name.display(db.upcast()).to_string();
-        let case_insensitive = enforce_lowercase || !self.case_sensitive;
-        if case_insensitive {
+        let mut input = if import.is_trait_assoc_item || self.name_only {
+            import.path.segments.last().unwrap().display(db.upcast()).to_string()
+        } else {
+            import.path.display(db).to_string()
+        };
+        if enforce_lowercase || !self.case_sensitive {
             input.make_ascii_lowercase();
         }
 
-        let query_string = if case_insensitive { &self.lowercased } else { &self.query };
+        let query_string =
+            if !enforce_lowercase && self.case_sensitive { &self.query } else { &self.lowercased };
 
         match self.search_mode {
-            SearchMode::Exact => &input == query_string,
+            SearchMode::Equals => &input == query_string,
+            SearchMode::Contains => input.contains(query_string),
             SearchMode::Fuzzy => {
-                let mut input_chars = input.chars();
-                for query_char in query_string.chars() {
-                    if input_chars.find(|&it| it == query_char).is_none() {
-                        return false;
+                let mut unchecked_query_chars = query_string.chars();
+                let mut mismatching_query_char = unchecked_query_chars.next();
+
+                for input_char in input.chars() {
+                    match mismatching_query_char {
+                        None => return true,
+                        Some(matching_query_char) if matching_query_char == input_char => {
+                            mismatching_query_char = unchecked_query_chars.next();
+                        }
+                        _ => (),
                     }
                 }
-                true
+                mismatching_query_char.is_none()
             }
         }
     }
 }
 
-/// Searches dependencies of `krate` for an importable name matching `query`.
+/// Searches dependencies of `krate` for an importable path matching `query`.
 ///
 /// This returns a list of items that could be imported from dependencies of `krate`.
 pub fn search_dependencies(
@@ -341,44 +446,65 @@ pub fn search_dependencies(
 
     let mut stream = op.union();
 
-    let mut res = FxHashSet::default();
+    let mut all_indexed_values = FxHashSet::default();
     while let Some((_, indexed_values)) = stream.next() {
-        for indexed_value in indexed_values {
-            let import_map = &import_maps[indexed_value.index];
-            let importables = &import_map.importables[indexed_value.value as usize..];
+        all_indexed_values.extend(indexed_values.iter().copied());
+    }
 
-            let common_importable_data = &import_map.map[&importables[0]];
-            if !query.import_matches(db, common_importable_data, true) {
-                continue;
-            }
+    let mut res = FxHashSet::default();
+    for indexed_value in all_indexed_values {
+        let import_map = &import_maps[indexed_value.index];
+        let importables = &import_map.importables[indexed_value.value as usize..];
 
-            // Name shared by the importable items in this group.
-            let common_importable_name =
-                common_importable_data.name.to_smol_str().to_ascii_lowercase();
-            // Add the items from this name group. Those are all subsequent items in
-            // `importables` whose name match `common_importable_name`.
-            let iter = importables
-                .iter()
-                .copied()
-                .take_while(|item| {
-                    common_importable_name
-                        == import_map.map[item].name.to_smol_str().to_ascii_lowercase()
-                })
-                .filter(|item| {
-                    !query.case_sensitive // we've already checked the common importables name case-insensitively
+        let common_importable_data = &import_map.map[&importables[0]];
+        if !query.import_matches(db, common_importable_data, true) {
+            continue;
+        }
+
+        // Path shared by the importable items in this group.
+        let common_importables_path_fst = fst_path(db, &common_importable_data.path);
+        // Add the items from this `ModPath` group. Those are all subsequent items in
+        // `importables` whose paths match `path`.
+        let iter = importables
+            .iter()
+            .copied()
+            .take_while(|item| {
+                common_importables_path_fst == fst_path(db, &import_map.map[item].path)
+            })
+            .filter(|&item| match item_import_kind(item) {
+                Some(import_kind) => !query.exclude_import_kinds.contains(&import_kind),
+                None => true,
+            })
+            .filter(|item| {
+                !query.case_sensitive // we've already checked the common importables path case-insensitively
                         || query.import_matches(db, &import_map.map[item], false)
-                });
-            res.extend(iter);
+            });
+        res.extend(iter);
 
-            if res.len() >= query.limit {
-                return res;
-            }
+        if res.len() >= query.limit {
+            return res;
         }
     }
 
     res
 }
 
+fn item_import_kind(item: ItemInNs) -> Option<ImportKind> {
+    Some(match item.as_module_def_id()? {
+        ModuleDefId::ModuleId(_) => ImportKind::Module,
+        ModuleDefId::FunctionId(_) => ImportKind::Function,
+        ModuleDefId::AdtId(_) => ImportKind::Adt,
+        ModuleDefId::EnumVariantId(_) => ImportKind::EnumVariant,
+        ModuleDefId::ConstId(_) => ImportKind::Const,
+        ModuleDefId::StaticId(_) => ImportKind::Static,
+        ModuleDefId::TraitId(_) => ImportKind::Trait,
+        ModuleDefId::TraitAliasId(_) => ImportKind::TraitAlias,
+        ModuleDefId::TypeAliasId(_) => ImportKind::TypeAlias,
+        ModuleDefId::BuiltinType(_) => ImportKind::BuiltinType,
+        ModuleDefId::MacroId(_) => ImportKind::Macro,
+    })
+}
+
 #[cfg(test)]
 mod tests {
     use base_db::{fixture::WithFixture, SourceDatabase, Upcast};
@@ -388,39 +514,16 @@ mod tests {
 
     use super::*;
 
-    impl ImportMap {
-        fn fmt_for_test(&self, db: &dyn DefDatabase) -> String {
-            let mut importable_paths: Vec<_> = self
-                .map
-                .iter()
-                .map(|(item, info)| {
-                    let path = render_path(db, info);
-                    let ns = match item {
-                        ItemInNs::Types(_) => "t",
-                        ItemInNs::Values(_) => "v",
-                        ItemInNs::Macros(_) => "m",
-                    };
-                    format!("- {path} ({ns})")
-                })
-                .collect();
-
-            importable_paths.sort();
-            importable_paths.join("\n")
-        }
-    }
-
     fn check_search(ra_fixture: &str, crate_name: &str, query: Query, expect: Expect) {
         let db = TestDB::with_files(ra_fixture);
         let crate_graph = db.crate_graph();
         let krate = crate_graph
             .iter()
-            .find(|&krate| {
-                crate_graph[krate]
-                    .display_name
-                    .as_ref()
-                    .is_some_and(|it| &**it.crate_name() == crate_name)
+            .find(|krate| {
+                crate_graph[*krate].display_name.as_ref().map(|n| n.to_string())
+                    == Some(crate_name.to_string())
             })
-            .expect("could not find crate");
+            .unwrap();
 
         let actual = search_dependencies(db.upcast(), krate, query)
             .into_iter()
@@ -431,7 +534,7 @@ mod tests {
                 let (path, mark) = match assoc_item_path(&db, &dependency_imports, dependency) {
                     Some(assoc_item_path) => (assoc_item_path, "a"),
                     None => (
-                        render_path(&db, dependency_imports.import_info_for(dependency)?),
+                        dependency_imports.path_of(dependency)?.display(&db).to_string(),
                         match dependency {
                             ItemInNs::Types(ModuleDefId::FunctionId(_))
                             | ItemInNs::Values(ModuleDefId::FunctionId(_)) => "f",
@@ -461,25 +564,57 @@ mod tests {
         dependency_imports: &ImportMap,
         dependency: ItemInNs,
     ) -> Option<String> {
-        let (dependency_assoc_item_id, container) = match dependency.as_module_def_id()? {
-            ModuleDefId::FunctionId(id) => (AssocItemId::from(id), id.lookup(db).container),
-            ModuleDefId::ConstId(id) => (AssocItemId::from(id), id.lookup(db).container),
-            ModuleDefId::TypeAliasId(id) => (AssocItemId::from(id), id.lookup(db).container),
+        let dependency_assoc_item_id = match dependency {
+            ItemInNs::Types(ModuleDefId::FunctionId(id))
+            | ItemInNs::Values(ModuleDefId::FunctionId(id)) => AssocItemId::from(id),
+            ItemInNs::Types(ModuleDefId::ConstId(id))
+            | ItemInNs::Values(ModuleDefId::ConstId(id)) => AssocItemId::from(id),
+            ItemInNs::Types(ModuleDefId::TypeAliasId(id))
+            | ItemInNs::Values(ModuleDefId::TypeAliasId(id)) => AssocItemId::from(id),
             _ => return None,
         };
 
-        let ItemContainerId::TraitId(trait_id) = container else {
-            return None;
+        let trait_ = assoc_to_trait(db, dependency)?;
+        if let ModuleDefId::TraitId(tr) = trait_.as_module_def_id()? {
+            let trait_data = db.trait_data(tr);
+            let assoc_item_name =
+                trait_data.items.iter().find_map(|(assoc_item_name, assoc_item_id)| {
+                    if &dependency_assoc_item_id == assoc_item_id {
+                        Some(assoc_item_name)
+                    } else {
+                        None
+                    }
+                })?;
+            return Some(format!(
+                "{}::{}",
+                dependency_imports.path_of(trait_)?.display(db),
+                assoc_item_name.display(db.upcast())
+            ));
+        }
+        None
+    }
+
+    fn assoc_to_trait(db: &dyn DefDatabase, item: ItemInNs) -> Option<ItemInNs> {
+        let assoc: AssocItemId = match item {
+            ItemInNs::Types(it) | ItemInNs::Values(it) => match it {
+                ModuleDefId::TypeAliasId(it) => it.into(),
+                ModuleDefId::FunctionId(it) => it.into(),
+                ModuleDefId::ConstId(it) => it.into(),
+                _ => return None,
+            },
+            _ => return None,
         };
 
-        let trait_info = dependency_imports.import_info_for(ItemInNs::Types(trait_id.into()))?;
+        let container = match assoc {
+            AssocItemId::FunctionId(it) => it.lookup(db).container,
+            AssocItemId::ConstId(it) => it.lookup(db).container,
+            AssocItemId::TypeAliasId(it) => it.lookup(db).container,
+        };
 
-        let trait_data = db.trait_data(trait_id);
-        let (assoc_item_name, _) = trait_data
-            .items
-            .iter()
-            .find(|(_, assoc_item_id)| &dependency_assoc_item_id == assoc_item_id)?;
-        Some(format!("{}::{}", render_path(db, trait_info), assoc_item_name.display(db.upcast())))
+        match container {
+            ItemContainerId::TraitId(it) => Some(ItemInNs::Types(it.into())),
+            _ => None,
+        }
     }
 
     fn check(ra_fixture: &str, expect: Expect) {
@@ -502,24 +637,6 @@ mod tests {
         expect.assert_eq(&actual)
     }
 
-    fn render_path(db: &dyn DefDatabase, info: &ImportInfo) -> String {
-        let mut module = info.container;
-        let mut segments = vec![&info.name];
-
-        let def_map = module.def_map(db);
-        assert!(def_map.block_id().is_none(), "block local items should not be in `ImportMap`");
-
-        while let Some(parent) = module.containing_module(db) {
-            let parent_data = &def_map[parent.local_id];
-            let (name, _) =
-                parent_data.children.iter().find(|(_, id)| **id == module.local_id).unwrap();
-            segments.push(name);
-            module = parent;
-        }
-
-        segments.iter().rev().map(|it| it.display(db.upcast())).join("::")
-    }
-
     #[test]
     fn smoke() {
         check(
@@ -636,7 +753,6 @@ mod tests {
     #[test]
     fn module_reexport() {
         // Reexporting modules from a dependency adds all contents to the import map.
-        // XXX: The rendered paths are relative to the defining crate.
         check(
             r"
             //- /main.rs crate:main deps:lib
@@ -652,9 +768,9 @@ mod tests {
                 - module::S (t)
                 - module::S (v)
                 main:
-                - module::S (t)
-                - module::S (v)
                 - reexported_module (t)
+                - reexported_module::S (t)
+                - reexported_module::S (v)
             "#]],
         );
     }
@@ -756,9 +872,10 @@ mod tests {
         check_search(
             ra_fixture,
             "main",
-            Query::new("fmt".to_string()).fuzzy(),
+            Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy),
             expect![[r#"
                 dep::fmt (t)
+                dep::fmt::Display (t)
                 dep::fmt::Display::FMT_CONST (a)
                 dep::fmt::Display::format_function (a)
                 dep::fmt::Display::format_method (a)
@@ -785,9 +902,7 @@ mod tests {
         check_search(
             ra_fixture,
             "main",
-            Query::new("fmt".to_string())
-                .fuzzy()
-                .assoc_search_mode(AssocSearchMode::AssocItemsOnly),
+            Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy).assoc_items_only(),
             expect![[r#"
                 dep::fmt::Display::FMT_CONST (a)
                 dep::fmt::Display::format_function (a)
@@ -798,10 +913,23 @@ mod tests {
         check_search(
             ra_fixture,
             "main",
-            Query::new("fmt".to_string()).fuzzy().assoc_search_mode(AssocSearchMode::Exclude),
+            Query::new("fmt".to_string())
+                .search_mode(SearchMode::Fuzzy)
+                .exclude_import_kind(ImportKind::AssociatedItem),
             expect![[r#"
-                dep::fmt (t)
-            "#]],
+            dep::fmt (t)
+            dep::fmt::Display (t)
+        "#]],
+        );
+
+        check_search(
+            ra_fixture,
+            "main",
+            Query::new("fmt".to_string())
+                .search_mode(SearchMode::Fuzzy)
+                .assoc_items_only()
+                .exclude_import_kind(ImportKind::AssociatedItem),
+            expect![[r#""#]],
         );
     }
 
@@ -834,12 +962,13 @@ mod tests {
         check_search(
             ra_fixture,
             "main",
-            Query::new("fmt".to_string()).fuzzy(),
+            Query::new("fmt".to_string()).search_mode(SearchMode::Fuzzy),
             expect![[r#"
                 dep::Fmt (m)
                 dep::Fmt (t)
                 dep::Fmt (v)
                 dep::fmt (t)
+                dep::fmt::Display (t)
                 dep::fmt::Display::fmt (a)
                 dep::format (f)
             "#]],
@@ -848,12 +977,26 @@ mod tests {
         check_search(
             ra_fixture,
             "main",
-            Query::new("fmt".to_string()),
+            Query::new("fmt".to_string()).search_mode(SearchMode::Equals),
+            expect![[r#"
+                dep::Fmt (m)
+                dep::Fmt (t)
+                dep::Fmt (v)
+                dep::fmt (t)
+                dep::fmt::Display::fmt (a)
+            "#]],
+        );
+
+        check_search(
+            ra_fixture,
+            "main",
+            Query::new("fmt".to_string()).search_mode(SearchMode::Contains),
             expect![[r#"
                 dep::Fmt (m)
                 dep::Fmt (t)
                 dep::Fmt (v)
                 dep::fmt (t)
+                dep::fmt::Display (t)
                 dep::fmt::Display::fmt (a)
             "#]],
         );
@@ -894,6 +1037,7 @@ mod tests {
                 dep::Fmt (t)
                 dep::Fmt (v)
                 dep::fmt (t)
+                dep::fmt::Display (t)
                 dep::fmt::Display::fmt (a)
             "#]],
         );
@@ -901,7 +1045,7 @@ mod tests {
         check_search(
             ra_fixture,
             "main",
-            Query::new("fmt".to_string()),
+            Query::new("fmt".to_string()).name_only(),
             expect![[r#"
                 dep::Fmt (m)
                 dep::Fmt (t)
@@ -966,10 +1110,43 @@ mod tests {
         pub fn no() {}
     "#,
             "main",
-            Query::new("".to_string()).fuzzy().limit(1),
+            Query::new("".to_string()).limit(2),
             expect![[r#"
-                dep::fmt::Display (t)
+                dep::Fmt (m)
+                dep::Fmt (t)
+                dep::Fmt (v)
+                dep::fmt (t)
             "#]],
         );
     }
+
+    #[test]
+    fn search_exclusions() {
+        let ra_fixture = r#"
+            //- /main.rs crate:main deps:dep
+            //- /dep.rs crate:dep
+
+            pub struct fmt;
+            pub struct FMT;
+        "#;
+
+        check_search(
+            ra_fixture,
+            "main",
+            Query::new("FMT".to_string()),
+            expect![[r#"
+                dep::FMT (t)
+                dep::FMT (v)
+                dep::fmt (t)
+                dep::fmt (v)
+            "#]],
+        );
+
+        check_search(
+            ra_fixture,
+            "main",
+            Query::new("FMT".to_string()).exclude_import_kind(ImportKind::Adt),
+            expect![[r#""#]],
+        );
+    }
 }
diff --git a/crates/hir-def/src/nameres/collector.rs b/crates/hir-def/src/nameres/collector.rs
index fb332c06d0..a5cdee9628 100644
--- a/crates/hir-def/src/nameres/collector.rs
+++ b/crates/hir-def/src/nameres/collector.rs
@@ -2235,8 +2235,12 @@ impl ModCollector<'_, '_> {
     }
 
     fn import_all_legacy_macros(&mut self, module_id: LocalModuleId) {
-        let Some((source, target)) = Self::borrow_modules(self.def_collector.def_map.modules.as_mut(), module_id, self.module_id) else {
-            return
+        let Some((source, target)) = Self::borrow_modules(
+            self.def_collector.def_map.modules.as_mut(),
+            module_id,
+            self.module_id,
+        ) else {
+            return;
         };
 
         for (name, macs) in source.scope.legacy_macros() {
diff --git a/crates/hir-def/src/path.rs b/crates/hir-def/src/path.rs
index ff4ae69546..409c9f8748 100644
--- a/crates/hir-def/src/path.rs
+++ b/crates/hir-def/src/path.rs
@@ -135,10 +135,7 @@ impl Path {
 
     pub fn segments(&self) -> PathSegments<'_> {
         let Path::Normal { mod_path, generic_args, .. } = self else {
-            return PathSegments {
-                segments: &[],
-                generic_args: None,
-            };
+            return PathSegments { segments: &[], generic_args: None };
         };
         let s =
             PathSegments { segments: mod_path.segments(), generic_args: generic_args.as_deref() };
diff --git a/crates/hir-def/src/path/lower.rs b/crates/hir-def/src/path/lower.rs
index 1cb17ff0d2..abd817893c 100644
--- a/crates/hir-def/src/path/lower.rs
+++ b/crates/hir-def/src/path/lower.rs
@@ -74,8 +74,8 @@ pub(super) fn lower_path(mut path: ast::Path, ctx: &LowerCtx<'_>) -> Option<Path
                     // <T as Trait<A>>::Foo desugars to Trait<Self=T, A>::Foo
                     Some(trait_ref) => {
                         let Path::Normal { mod_path, generic_args: path_generic_args, .. } =
-                            Path::from_src(trait_ref.path()?, ctx)? else
-                        {
+                            Path::from_src(trait_ref.path()?, ctx)?
+                        else {
                             return None;
                         };
                         let num_segments = mod_path.segments().len();
diff --git a/crates/hir-expand/src/builtin_fn_macro.rs b/crates/hir-expand/src/builtin_fn_macro.rs
index dc00b8601b..306bae45b4 100644
--- a/crates/hir-expand/src/builtin_fn_macro.rs
+++ b/crates/hir-expand/src/builtin_fn_macro.rs
@@ -692,7 +692,7 @@ pub(crate) fn include_arg_to_tt(
     arg_id: MacroCallId,
 ) -> Result<(triomphe::Arc<(::tt::Subtree<::tt::TokenId>, TokenMap)>, FileId), ExpandError> {
     let loc = db.lookup_intern_macro_call(arg_id);
-    let Some(EagerCallInfo {arg, arg_id: Some(arg_id), .. }) = loc.eager.as_deref() else {
+    let Some(EagerCallInfo { arg, arg_id: Some(arg_id), .. }) = loc.eager.as_deref() else {
         panic!("include_arg_to_tt called on non include macro call: {:?}", &loc.eager);
     };
     let path = parse_string(&arg.0)?;
diff --git a/crates/hir-expand/src/db.rs b/crates/hir-expand/src/db.rs
index de653d76b4..3f08a09869 100644
--- a/crates/hir-expand/src/db.rs
+++ b/crates/hir-expand/src/db.rs
@@ -471,17 +471,13 @@ fn macro_expand(db: &dyn ExpandDatabase, id: MacroCallId) -> ExpandResult<Arc<tt
     };
     let Some(macro_arg) = db.macro_arg(id) else {
         return ExpandResult {
-            value: Arc::new(
-                tt::Subtree {
-                    delimiter: tt::Delimiter::UNSPECIFIED,
-                    token_trees: Vec::new(),
-                },
-            ),
+            value: Arc::new(tt::Subtree {
+                delimiter: tt::Delimiter::UNSPECIFIED,
+                token_trees: Vec::new(),
+            }),
             // FIXME: We should make sure to enforce an invariant that invalid macro
             // calls do not reach this call path!
-            err: Some(ExpandError::other(
-                "invalid token tree"
-            )),
+            err: Some(ExpandError::other("invalid token tree")),
         };
     };
     let (arg_tt, arg_tm, undo_info) = &*macro_arg;
@@ -510,9 +506,7 @@ fn expand_proc_macro(db: &dyn ExpandDatabase, id: MacroCallId) -> ExpandResult<A
                 delimiter: tt::Delimiter::UNSPECIFIED,
                 token_trees: Vec::new(),
             }),
-            err: Some(ExpandError::other(
-                "invalid token tree"
-            )),
+            err: Some(ExpandError::other("invalid token tree")),
         };
     };
     let (arg_tt, arg_tm, undo_info) = &*macro_arg;
diff --git a/crates/hir-expand/src/eager.rs b/crates/hir-expand/src/eager.rs
index 7ee3fd375f..3ccc3ab1e1 100644
--- a/crates/hir-expand/src/eager.rs
+++ b/crates/hir-expand/src/eager.rs
@@ -42,10 +42,9 @@ pub fn expand_eager_macro_input(
     let token_tree = macro_call.value.token_tree();
 
     let Some(token_tree) = token_tree else {
-        return Ok(ExpandResult { value: None, err:
-            Some(ExpandError::other(
-                "invalid token tree"
-            )),
+        return Ok(ExpandResult {
+            value: None,
+            err: Some(ExpandError::other("invalid token tree")),
         });
     };
     let (parsed_args, arg_token_map) = mbe::syntax_node_to_token_tree(token_tree.syntax());
@@ -85,7 +84,7 @@ pub fn expand_eager_macro_input(
         resolver,
     )?;
     let Some(expanded_eager_input) = expanded_eager_input else {
-        return Ok(ExpandResult { value: None, err })
+        return Ok(ExpandResult { value: None, err });
     };
     let (mut subtree, token_map) = mbe::syntax_node_to_token_tree(&expanded_eager_input);
     subtree.delimiter = crate::tt::Delimiter::unspecified();
diff --git a/crates/hir-ty/src/autoderef.rs b/crates/hir-ty/src/autoderef.rs
index 4625a3b01a..3860bccec8 100644
--- a/crates/hir-ty/src/autoderef.rs
+++ b/crates/hir-ty/src/autoderef.rs
@@ -36,7 +36,7 @@ pub fn autoderef(
 ) -> impl Iterator<Item = Ty> {
     let mut table = InferenceTable::new(db, env);
     let ty = table.instantiate_canonical(ty);
-    let mut autoderef = Autoderef::new(&mut table, ty, false);
+    let mut autoderef = Autoderef::new(&mut table, ty);
     let mut v = Vec::new();
     while let Some((ty, _steps)) = autoderef.next() {
         // `ty` may contain unresolved inference variables. Since there's no chance they would be
@@ -63,13 +63,12 @@ pub(crate) struct Autoderef<'a, 'db> {
     ty: Ty,
     at_start: bool,
     steps: Vec<(AutoderefKind, Ty)>,
-    explicit: bool,
 }
 
 impl<'a, 'db> Autoderef<'a, 'db> {
-    pub(crate) fn new(table: &'a mut InferenceTable<'db>, ty: Ty, explicit: bool) -> Self {
+    pub(crate) fn new(table: &'a mut InferenceTable<'db>, ty: Ty) -> Self {
         let ty = table.resolve_ty_shallow(&ty);
-        Autoderef { table, ty, at_start: true, steps: Vec::new(), explicit }
+        Autoderef { table, ty, at_start: true, steps: Vec::new() }
     }
 
     pub(crate) fn step_count(&self) -> usize {
@@ -98,7 +97,7 @@ impl Iterator for Autoderef<'_, '_> {
             return None;
         }
 
-        let (kind, new_ty) = autoderef_step(self.table, self.ty.clone(), self.explicit)?;
+        let (kind, new_ty) = autoderef_step(self.table, self.ty.clone())?;
 
         self.steps.push((kind, self.ty.clone()));
         self.ty = new_ty;
@@ -110,9 +109,8 @@ impl Iterator for Autoderef<'_, '_> {
 pub(crate) fn autoderef_step(
     table: &mut InferenceTable<'_>,
     ty: Ty,
-    explicit: bool,
 ) -> Option<(AutoderefKind, Ty)> {
-    if let Some(derefed) = builtin_deref(table, &ty, explicit) {
+    if let Some(derefed) = builtin_deref(table, &ty, false) {
         Some((AutoderefKind::Builtin, table.resolve_ty_shallow(derefed)))
     } else {
         Some((AutoderefKind::Overloaded, deref_by_trait(table, ty)?))
@@ -126,6 +124,7 @@ pub(crate) fn builtin_deref<'ty>(
 ) -> Option<&'ty Ty> {
     match ty.kind(Interner) {
         TyKind::Ref(.., ty) => Some(ty),
+        // FIXME: Maybe accept this but diagnose if its not explicit?
         TyKind::Raw(.., ty) if explicit => Some(ty),
         &TyKind::Adt(chalk_ir::AdtId(adt), ref substs) => {
             if crate::lang_items::is_box(table.db, adt) {
diff --git a/crates/hir-ty/src/chalk_ext.rs b/crates/hir-ty/src/chalk_ext.rs
index a8071591ad..0e33b63939 100644
--- a/crates/hir-ty/src/chalk_ext.rs
+++ b/crates/hir-ty/src/chalk_ext.rs
@@ -343,7 +343,8 @@ impl TyExt for Ty {
 
     fn is_copy(self, db: &dyn HirDatabase, owner: DefWithBodyId) -> bool {
         let crate_id = owner.module(db.upcast()).krate();
-        let Some(copy_trait) = db.lang_item(crate_id, LangItem::Copy).and_then(|x| x.as_trait()) else {
+        let Some(copy_trait) = db.lang_item(crate_id, LangItem::Copy).and_then(|x| x.as_trait())
+        else {
             return false;
         };
         let trait_ref = TyBuilder::trait_ref(db, copy_trait).push(self).build();
diff --git a/crates/hir-ty/src/display.rs b/crates/hir-ty/src/display.rs
index 82cc4f9f59..7405b51e6e 100644
--- a/crates/hir-ty/src/display.rs
+++ b/crates/hir-ty/src/display.rs
@@ -636,7 +636,8 @@ fn render_const_scalar(
                 }
                 hir_def::AdtId::EnumId(e) => {
                     let Some((var_id, var_layout)) =
-                            detect_variant_from_bytes(&layout, f.db, krate, b, e) else {
+                        detect_variant_from_bytes(&layout, f.db, krate, b, e)
+                    else {
                         return f.write_str("<failed-to-detect-variant>");
                     };
                     let data = &f.db.enum_data(e).variants[var_id];
diff --git a/crates/hir-ty/src/infer.rs b/crates/hir-ty/src/infer.rs
index 1ac0837b5b..d53644e279 100644
--- a/crates/hir-ty/src/infer.rs
+++ b/crates/hir-ty/src/infer.rs
@@ -1232,7 +1232,9 @@ impl<'a> InferenceContext<'a> {
             .as_function()?
             .lookup(self.db.upcast())
             .container
-        else { return None };
+        else {
+            return None;
+        };
         self.resolve_output_on(trait_)
     }
 
diff --git a/crates/hir-ty/src/infer/coerce.rs b/crates/hir-ty/src/infer/coerce.rs
index 8e7e62c496..7c5fe22bfa 100644
--- a/crates/hir-ty/src/infer/coerce.rs
+++ b/crates/hir-ty/src/infer/coerce.rs
@@ -377,7 +377,7 @@ impl InferenceTable<'_> {
 
         let snapshot = self.snapshot();
 
-        let mut autoderef = Autoderef::new(self, from_ty.clone(), false);
+        let mut autoderef = Autoderef::new(self, from_ty.clone());
         let mut first_error = None;
         let mut found = None;
 
diff --git a/crates/hir-ty/src/infer/expr.rs b/crates/hir-ty/src/infer/expr.rs
index 8377eb2349..6c91f8426e 100644
--- a/crates/hir-ty/src/infer/expr.rs
+++ b/crates/hir-ty/src/infer/expr.rs
@@ -316,7 +316,7 @@ impl InferenceContext<'_> {
             }
             Expr::Call { callee, args, .. } => {
                 let callee_ty = self.infer_expr(*callee, &Expectation::none());
-                let mut derefs = Autoderef::new(&mut self.table, callee_ty.clone(), false);
+                let mut derefs = Autoderef::new(&mut self.table, callee_ty.clone());
                 let (res, derefed_callee) = 'b: {
                     // manual loop to be able to access `derefs.table`
                     while let Some((callee_deref_ty, _)) = derefs.next() {
@@ -1385,7 +1385,7 @@ impl InferenceContext<'_> {
         receiver_ty: &Ty,
         name: &Name,
     ) -> Option<(Ty, Option<FieldId>, Vec<Adjustment>, bool)> {
-        let mut autoderef = Autoderef::new(&mut self.table, receiver_ty.clone(), false);
+        let mut autoderef = Autoderef::new(&mut self.table, receiver_ty.clone());
         let mut private_field = None;
         let res = autoderef.by_ref().find_map(|(derefed_ty, _)| {
             let (field_id, parameters) = match derefed_ty.kind(Interner) {
diff --git a/crates/hir-ty/src/layout.rs b/crates/hir-ty/src/layout.rs
index 2a9b2debd4..06be1f80ad 100644
--- a/crates/hir-ty/src/layout.rs
+++ b/crates/hir-ty/src/layout.rs
@@ -154,7 +154,9 @@ pub fn layout_of_ty_query(
     ty: Ty,
     krate: CrateId,
 ) -> Result<Arc<Layout>, LayoutError> {
-    let Some(target) = db.target_data_layout(krate) else { return Err(LayoutError::TargetLayoutNotAvailable) };
+    let Some(target) = db.target_data_layout(krate) else {
+        return Err(LayoutError::TargetLayoutNotAvailable);
+    };
     let cx = LayoutCx { krate, target: &target };
     let dl = &*cx.current_data_layout();
     let trait_env = Arc::new(TraitEnvironment::empty(krate));
diff --git a/crates/hir-ty/src/layout/adt.rs b/crates/hir-ty/src/layout/adt.rs
index bd2752a711..0012b4179d 100644
--- a/crates/hir-ty/src/layout/adt.rs
+++ b/crates/hir-ty/src/layout/adt.rs
@@ -31,7 +31,9 @@ pub fn layout_of_adt_query(
     subst: Substitution,
     krate: CrateId,
 ) -> Result<Arc<Layout>, LayoutError> {
-    let Some(target) = db.target_data_layout(krate) else { return Err(LayoutError::TargetLayoutNotAvailable) };
+    let Some(target) = db.target_data_layout(krate) else {
+        return Err(LayoutError::TargetLayoutNotAvailable);
+    };
     let cx = LayoutCx { krate, target: &target };
     let dl = cx.current_data_layout();
     let handle_variant = |def: VariantId, var: &VariantData| {
diff --git a/crates/hir-ty/src/method_resolution.rs b/crates/hir-ty/src/method_resolution.rs
index 38959b18bf..39d1a0e05f 100644
--- a/crates/hir-ty/src/method_resolution.rs
+++ b/crates/hir-ty/src/method_resolution.rs
@@ -534,7 +534,7 @@ impl ReceiverAdjustments {
         let mut ty = table.resolve_ty_shallow(&ty);
         let mut adjust = Vec::new();
         for _ in 0..self.autoderefs {
-            match autoderef::autoderef_step(table, ty.clone(), true) {
+            match autoderef::autoderef_step(table, ty.clone()) {
                 None => {
                     never!("autoderef not possible for {:?}", ty);
                     ty = TyKind::Error.intern(Interner);
@@ -689,7 +689,7 @@ pub fn lookup_impl_method(
     fn_subst: Substitution,
 ) -> (FunctionId, Substitution) {
     let ItemContainerId::TraitId(trait_id) = func.lookup(db.upcast()).container else {
-        return (func, fn_subst)
+        return (func, fn_subst);
     };
     let trait_params = db.generic_params(trait_id.into()).type_or_consts.len();
     let fn_params = fn_subst.len(Interner) - trait_params;
@@ -699,8 +699,8 @@ pub fn lookup_impl_method(
     };
 
     let name = &db.function_data(func).name;
-    let Some((impl_fn, impl_subst)) = lookup_impl_assoc_item_for_trait_ref(trait_ref, db, env, name)
-        .and_then(|assoc| {
+    let Some((impl_fn, impl_subst)) =
+        lookup_impl_assoc_item_for_trait_ref(trait_ref, db, env, name).and_then(|assoc| {
             if let (AssocItemId::FunctionId(id), subst) = assoc {
                 Some((id, subst))
             } else {
@@ -1012,8 +1012,8 @@ fn iterate_method_candidates_by_receiver(
     let snapshot = table.snapshot();
     // We're looking for methods with *receiver* type receiver_ty. These could
     // be found in any of the derefs of receiver_ty, so we have to go through
-    // that, including raw derefs.
-    let mut autoderef = autoderef::Autoderef::new(&mut table, receiver_ty.clone(), true);
+    // that.
+    let mut autoderef = autoderef::Autoderef::new(&mut table, receiver_ty.clone());
     while let Some((self_ty, _)) = autoderef.next() {
         iterate_inherent_methods(
             &self_ty,
@@ -1028,7 +1028,7 @@ fn iterate_method_candidates_by_receiver(
 
     table.rollback_to(snapshot);
 
-    let mut autoderef = autoderef::Autoderef::new(&mut table, receiver_ty.clone(), true);
+    let mut autoderef = autoderef::Autoderef::new(&mut table, receiver_ty.clone());
     while let Some((self_ty, _)) = autoderef.next() {
         iterate_trait_method_candidates(
             &self_ty,
@@ -1504,7 +1504,7 @@ fn autoderef_method_receiver(
     ty: Ty,
 ) -> Vec<(Canonical<Ty>, ReceiverAdjustments)> {
     let mut deref_chain: Vec<_> = Vec::new();
-    let mut autoderef = autoderef::Autoderef::new(table, ty, true);
+    let mut autoderef = autoderef::Autoderef::new(table, ty);
     while let Some((ty, derefs)) = autoderef.next() {
         deref_chain.push((
             autoderef.table.canonicalize(ty).value,
diff --git a/crates/hir-ty/src/mir/borrowck.rs b/crates/hir-ty/src/mir/borrowck.rs
index a5dd0182eb..0e6a63df41 100644
--- a/crates/hir-ty/src/mir/borrowck.rs
+++ b/crates/hir-ty/src/mir/borrowck.rs
@@ -271,7 +271,10 @@ fn ever_initialized_map(
             }
         }
         let Some(terminator) = &block.terminator else {
-            never!("Terminator should be none only in construction.\nThe body:\n{}", body.pretty_print(db));
+            never!(
+                "Terminator should be none only in construction.\nThe body:\n{}",
+                body.pretty_print(db)
+            );
             return;
         };
         let targets = match &terminator.kind {
diff --git a/crates/hir-ty/src/mir/eval.rs b/crates/hir-ty/src/mir/eval.rs
index ddcfc57185..51a75cbbff 100644
--- a/crates/hir-ty/src/mir/eval.rs
+++ b/crates/hir-ty/src/mir/eval.rs
@@ -1226,8 +1226,8 @@ impl Evaluator<'_> {
             }
             Variants::Multiple { tag, tag_encoding, variants, .. } => {
                 let Some(target_data_layout) = self.db.target_data_layout(self.crate_id) else {
-                            not_supported!("missing target data layout");
-                        };
+                    not_supported!("missing target data layout");
+                };
                 let size = tag.size(&*target_data_layout).bytes_usize();
                 let offset = layout.fields.offset(0).bytes_usize(); // The only field on enum variants is the tag field
                 match tag_encoding {
@@ -1344,7 +1344,9 @@ impl Evaluator<'_> {
                         AdtId::UnionId(_) => not_supported!("unsizing unions"),
                         AdtId::EnumId(_) => not_supported!("unsizing enums"),
                     };
-                    let Some((last_field, _)) = self.db.struct_data(id).variant_data.fields().iter().rev().next() else {
+                    let Some((last_field, _)) =
+                        self.db.struct_data(id).variant_data.fields().iter().rev().next()
+                    else {
                         not_supported!("unsizing struct without field");
                     };
                     let target_last_field = self.db.field_types(id.into())[last_field]
diff --git a/crates/hir-ty/src/mir/eval/shim.rs b/crates/hir-ty/src/mir/eval/shim.rs
index 23bb4a29f8..73ed52f3b3 100644
--- a/crates/hir-ty/src/mir/eval/shim.rs
+++ b/crates/hir-ty/src/mir/eval/shim.rs
@@ -327,7 +327,9 @@ impl Evaluator<'_> {
             }
             "pthread_getspecific" => {
                 let Some(arg0) = args.get(0) else {
-                    return Err(MirEvalError::TypeError("pthread_getspecific arg0 is not provided"));
+                    return Err(MirEvalError::TypeError(
+                        "pthread_getspecific arg0 is not provided",
+                    ));
                 };
                 let key = from_bytes!(usize, &pad16(arg0.get(self)?, false)[0..8]);
                 let value = self.thread_local_storage.get_key(key)?;
@@ -336,11 +338,15 @@ impl Evaluator<'_> {
             }
             "pthread_setspecific" => {
                 let Some(arg0) = args.get(0) else {
-                    return Err(MirEvalError::TypeError("pthread_setspecific arg0 is not provided"));
+                    return Err(MirEvalError::TypeError(
+                        "pthread_setspecific arg0 is not provided",
+                    ));
                 };
                 let key = from_bytes!(usize, &pad16(arg0.get(self)?, false)[0..8]);
                 let Some(arg1) = args.get(1) else {
-                    return Err(MirEvalError::TypeError("pthread_setspecific arg1 is not provided"));
+                    return Err(MirEvalError::TypeError(
+                        "pthread_setspecific arg1 is not provided",
+                    ));
                 };
                 let value = from_bytes!(u128, pad16(arg1.get(self)?, false));
                 self.thread_local_storage.set_key(key, value)?;
@@ -390,7 +396,9 @@ impl Evaluator<'_> {
                 "sqrt" | "sin" | "cos" | "exp" | "exp2" | "log" | "log10" | "log2" | "fabs"
                 | "floor" | "ceil" | "trunc" | "rint" | "nearbyint" | "round" | "roundeven" => {
                     let [arg] = args else {
-                        return Err(MirEvalError::TypeError("f64 intrinsic signature doesn't match fn (f64) -> f64"));
+                        return Err(MirEvalError::TypeError(
+                            "f64 intrinsic signature doesn't match fn (f64) -> f64",
+                        ));
                     };
                     let arg = from_bytes!(f64, arg.get(self)?);
                     match name {
@@ -416,7 +424,9 @@ impl Evaluator<'_> {
                 }
                 "pow" | "minnum" | "maxnum" | "copysign" => {
                     let [arg1, arg2] = args else {
-                        return Err(MirEvalError::TypeError("f64 intrinsic signature doesn't match fn (f64, f64) -> f64"));
+                        return Err(MirEvalError::TypeError(
+                            "f64 intrinsic signature doesn't match fn (f64, f64) -> f64",
+                        ));
                     };
                     let arg1 = from_bytes!(f64, arg1.get(self)?);
                     let arg2 = from_bytes!(f64, arg2.get(self)?);
@@ -430,7 +440,9 @@ impl Evaluator<'_> {
                 }
                 "powi" => {
                     let [arg1, arg2] = args else {
-                        return Err(MirEvalError::TypeError("powif64 signature doesn't match fn (f64, i32) -> f64"));
+                        return Err(MirEvalError::TypeError(
+                            "powif64 signature doesn't match fn (f64, i32) -> f64",
+                        ));
                     };
                     let arg1 = from_bytes!(f64, arg1.get(self)?);
                     let arg2 = from_bytes!(i32, arg2.get(self)?);
@@ -438,7 +450,9 @@ impl Evaluator<'_> {
                 }
                 "fma" => {
                     let [arg1, arg2, arg3] = args else {
-                        return Err(MirEvalError::TypeError("fmaf64 signature doesn't match fn (f64, f64, f64) -> f64"));
+                        return Err(MirEvalError::TypeError(
+                            "fmaf64 signature doesn't match fn (f64, f64, f64) -> f64",
+                        ));
                     };
                     let arg1 = from_bytes!(f64, arg1.get(self)?);
                     let arg2 = from_bytes!(f64, arg2.get(self)?);
@@ -454,7 +468,9 @@ impl Evaluator<'_> {
                 "sqrt" | "sin" | "cos" | "exp" | "exp2" | "log" | "log10" | "log2" | "fabs"
                 | "floor" | "ceil" | "trunc" | "rint" | "nearbyint" | "round" | "roundeven" => {
                     let [arg] = args else {
-                        return Err(MirEvalError::TypeError("f32 intrinsic signature doesn't match fn (f32) -> f32"));
+                        return Err(MirEvalError::TypeError(
+                            "f32 intrinsic signature doesn't match fn (f32) -> f32",
+                        ));
                     };
                     let arg = from_bytes!(f32, arg.get(self)?);
                     match name {
@@ -480,7 +496,9 @@ impl Evaluator<'_> {
                 }
                 "pow" | "minnum" | "maxnum" | "copysign" => {
                     let [arg1, arg2] = args else {
-                        return Err(MirEvalError::TypeError("f32 intrinsic signature doesn't match fn (f32, f32) -> f32"));
+                        return Err(MirEvalError::TypeError(
+                            "f32 intrinsic signature doesn't match fn (f32, f32) -> f32",
+                        ));
                     };
                     let arg1 = from_bytes!(f32, arg1.get(self)?);
                     let arg2 = from_bytes!(f32, arg2.get(self)?);
@@ -494,7 +512,9 @@ impl Evaluator<'_> {
                 }
                 "powi" => {
                     let [arg1, arg2] = args else {
-                        return Err(MirEvalError::TypeError("powif32 signature doesn't match fn (f32, i32) -> f32"));
+                        return Err(MirEvalError::TypeError(
+                            "powif32 signature doesn't match fn (f32, i32) -> f32",
+                        ));
                     };
                     let arg1 = from_bytes!(f32, arg1.get(self)?);
                     let arg2 = from_bytes!(i32, arg2.get(self)?);
@@ -502,7 +522,9 @@ impl Evaluator<'_> {
                 }
                 "fma" => {
                     let [arg1, arg2, arg3] = args else {
-                        return Err(MirEvalError::TypeError("fmaf32 signature doesn't match fn (f32, f32, f32) -> f32"));
+                        return Err(MirEvalError::TypeError(
+                            "fmaf32 signature doesn't match fn (f32, f32, f32) -> f32",
+                        ));
                     };
                     let arg1 = from_bytes!(f32, arg1.get(self)?);
                     let arg2 = from_bytes!(f32, arg2.get(self)?);
@@ -515,14 +537,16 @@ impl Evaluator<'_> {
         }
         match name {
             "size_of" => {
-                let Some(ty) = generic_args.as_slice(Interner).get(0).and_then(|x| x.ty(Interner)) else {
+                let Some(ty) = generic_args.as_slice(Interner).get(0).and_then(|x| x.ty(Interner))
+                else {
                     return Err(MirEvalError::TypeError("size_of generic arg is not provided"));
                 };
                 let size = self.size_of_sized(ty, locals, "size_of arg")?;
                 destination.write_from_bytes(self, &size.to_le_bytes()[0..destination.size])
             }
             "size_of_val" => {
-                let Some(ty) = generic_args.as_slice(Interner).get(0).and_then(|x| x.ty(Interner)) else {
+                let Some(ty) = generic_args.as_slice(Interner).get(0).and_then(|x| x.ty(Interner))
+                else {
                     return Err(MirEvalError::TypeError("size_of_val generic arg is not provided"));
                 };
                 let [arg] = args else {
@@ -549,14 +573,16 @@ impl Evaluator<'_> {
                 destination.write_from_bytes(self, &size.to_le_bytes())
             }
             "min_align_of" | "pref_align_of" => {
-                let Some(ty) = generic_args.as_slice(Interner).get(0).and_then(|x| x.ty(Interner)) else {
+                let Some(ty) = generic_args.as_slice(Interner).get(0).and_then(|x| x.ty(Interner))
+                else {
                     return Err(MirEvalError::TypeError("align_of generic arg is not provided"));
                 };
                 let align = self.layout(ty)?.align.abi.bytes();
                 destination.write_from_bytes(self, &align.to_le_bytes()[0..destination.size])
             }
             "needs_drop" => {
-                let Some(ty) = generic_args.as_slice(Interner).get(0).and_then(|x| x.ty(Interner)) else {
+                let Some(ty) = generic_args.as_slice(Interner).get(0).and_then(|x| x.ty(Interner))
+                else {
                     return Err(MirEvalError::TypeError("size_of generic arg is not provided"));
                 };
                 let result = !ty.clone().is_copy(self.db, locals.body.owner);
@@ -697,10 +723,15 @@ impl Evaluator<'_> {
             }
             "copy" | "copy_nonoverlapping" => {
                 let [src, dst, offset] = args else {
-                    return Err(MirEvalError::TypeError("copy_nonoverlapping args are not provided"));
+                    return Err(MirEvalError::TypeError(
+                        "copy_nonoverlapping args are not provided",
+                    ));
                 };
-                let Some(ty) = generic_args.as_slice(Interner).get(0).and_then(|x| x.ty(Interner)) else {
-                    return Err(MirEvalError::TypeError("copy_nonoverlapping generic arg is not provided"));
+                let Some(ty) = generic_args.as_slice(Interner).get(0).and_then(|x| x.ty(Interner))
+                else {
+                    return Err(MirEvalError::TypeError(
+                        "copy_nonoverlapping generic arg is not provided",
+                    ));
                 };
                 let src = Address::from_bytes(src.get(self)?)?;
                 let dst = Address::from_bytes(dst.get(self)?)?;
@@ -715,7 +746,8 @@ impl Evaluator<'_> {
                 let [ptr, offset] = args else {
                     return Err(MirEvalError::TypeError("offset args are not provided"));
                 };
-                let Some(ty) = generic_args.as_slice(Interner).get(0).and_then(|x| x.ty(Interner)) else {
+                let Some(ty) = generic_args.as_slice(Interner).get(0).and_then(|x| x.ty(Interner))
+                else {
                     return Err(MirEvalError::TypeError("offset generic arg is not provided"));
                 };
                 let ptr = u128::from_le_bytes(pad16(ptr.get(self)?, false));
@@ -824,8 +856,11 @@ impl Evaluator<'_> {
                 let [arg] = args else {
                     return Err(MirEvalError::TypeError("discriminant_value arg is not provided"));
                 };
-                let Some(ty) = generic_args.as_slice(Interner).get(0).and_then(|x| x.ty(Interner)) else {
-                    return Err(MirEvalError::TypeError("discriminant_value generic arg is not provided"));
+                let Some(ty) = generic_args.as_slice(Interner).get(0).and_then(|x| x.ty(Interner))
+                else {
+                    return Err(MirEvalError::TypeError(
+                        "discriminant_value generic arg is not provided",
+                    ));
                 };
                 let addr = Address::from_bytes(arg.get(self)?)?;
                 let size = self.size_of_sized(ty, locals, "discriminant_value ptr type")?;
diff --git a/crates/hir-ty/src/mir/eval/shim/simd.rs b/crates/hir-ty/src/mir/eval/shim/simd.rs
index c41e2790c1..89b04eb36b 100644
--- a/crates/hir-ty/src/mir/eval/shim/simd.rs
+++ b/crates/hir-ty/src/mir/eval/shim/simd.rs
@@ -23,7 +23,8 @@ impl Evaluator<'_> {
     fn detect_simd_ty(&self, ty: &Ty) -> Result<usize> {
         match ty.kind(Interner) {
             TyKind::Adt(_, subst) => {
-                let Some(len) = subst.as_slice(Interner).get(1).and_then(|x| x.constant(Interner)) else {
+                let Some(len) = subst.as_slice(Interner).get(1).and_then(|x| x.constant(Interner))
+                else {
                     return Err(MirEvalError::TypeError("simd type without len param"));
                 };
                 match try_const_usize(self.db, len) {
@@ -89,7 +90,9 @@ impl Evaluator<'_> {
                     return Err(MirEvalError::TypeError("simd_shuffle args are not provided"));
                 };
                 let TyKind::Array(_, index_len) = index.ty.kind(Interner) else {
-                    return Err(MirEvalError::TypeError("simd_shuffle index argument has non-array type"));
+                    return Err(MirEvalError::TypeError(
+                        "simd_shuffle index argument has non-array type",
+                    ));
                 };
                 let index_len = match try_const_usize(self.db, index_len) {
                     Some(x) => x as usize,
diff --git a/crates/hir-ty/src/mir/lower.rs b/crates/hir-ty/src/mir/lower.rs
index 800e490e9a..41a7738357 100644
--- a/crates/hir-ty/src/mir/lower.rs
+++ b/crates/hir-ty/src/mir/lower.rs
@@ -310,24 +310,30 @@ impl<'ctx> MirLowerCtx<'ctx> {
                     self.lower_expr_to_place_with_adjust(expr_id, temp.into(), current, rest)
                 }
                 Adjust::Deref(_) => {
-                    let Some((p, current)) = self.lower_expr_as_place_with_adjust(current, expr_id, true, adjustments)? else {
-                            return Ok(None);
-                        };
+                    let Some((p, current)) =
+                        self.lower_expr_as_place_with_adjust(current, expr_id, true, adjustments)?
+                    else {
+                        return Ok(None);
+                    };
                     self.push_assignment(current, place, Operand::Copy(p).into(), expr_id.into());
                     Ok(Some(current))
                 }
                 Adjust::Borrow(AutoBorrow::Ref(m) | AutoBorrow::RawPtr(m)) => {
-                    let Some((p, current)) = self.lower_expr_as_place_with_adjust(current, expr_id, true, rest)? else {
-                            return Ok(None);
-                        };
+                    let Some((p, current)) =
+                        self.lower_expr_as_place_with_adjust(current, expr_id, true, rest)?
+                    else {
+                        return Ok(None);
+                    };
                     let bk = BorrowKind::from_chalk(*m);
                     self.push_assignment(current, place, Rvalue::Ref(bk, p), expr_id.into());
                     Ok(Some(current))
                 }
                 Adjust::Pointer(cast) => {
-                    let Some((p, current)) = self.lower_expr_as_place_with_adjust(current, expr_id, true, rest)? else {
-                            return Ok(None);
-                        };
+                    let Some((p, current)) =
+                        self.lower_expr_as_place_with_adjust(current, expr_id, true, rest)?
+                    else {
+                        return Ok(None);
+                    };
                     self.push_assignment(
                         current,
                         place,
@@ -373,45 +379,49 @@ impl<'ctx> MirLowerCtx<'ctx> {
                     }
                 }
                 Err(MirLowerError::IncompleteExpr)
-            },
+            }
             Expr::Path(p) => {
-                let pr = if let Some((assoc, subst)) = self
-                    .infer
-                    .assoc_resolutions_for_expr(expr_id)
-                {
-                    match assoc {
-                        hir_def::AssocItemId::ConstId(c) => {
-                            self.lower_const(c.into(), current, place, subst, expr_id.into(), self.expr_ty_without_adjust(expr_id))?;
-                            return Ok(Some(current))
-                        },
-                        hir_def::AssocItemId::FunctionId(_) => {
-                            // FnDefs are zero sized, no action is needed.
-                            return Ok(Some(current))
+                let pr =
+                    if let Some((assoc, subst)) = self.infer.assoc_resolutions_for_expr(expr_id) {
+                        match assoc {
+                            hir_def::AssocItemId::ConstId(c) => {
+                                self.lower_const(
+                                    c.into(),
+                                    current,
+                                    place,
+                                    subst,
+                                    expr_id.into(),
+                                    self.expr_ty_without_adjust(expr_id),
+                                )?;
+                                return Ok(Some(current));
+                            }
+                            hir_def::AssocItemId::FunctionId(_) => {
+                                // FnDefs are zero sized, no action is needed.
+                                return Ok(Some(current));
+                            }
+                            hir_def::AssocItemId::TypeAliasId(_) => {
+                                // FIXME: If it is unreachable, use proper error instead of `not_supported`.
+                                not_supported!("associated functions and types")
+                            }
                         }
-                        hir_def::AssocItemId::TypeAliasId(_) => {
-                            // FIXME: If it is unreachable, use proper error instead of `not_supported`.
-                            not_supported!("associated functions and types")
-                        },
-                    }
-                } else if let Some(variant) = self
-                    .infer
-                    .variant_resolution_for_expr(expr_id)
-                {
-                    match variant {
-                        VariantId::EnumVariantId(e) => ValueNs::EnumVariantId(e),
-                        VariantId::StructId(s) => ValueNs::StructId(s),
-                        VariantId::UnionId(_) => implementation_error!("Union variant as path"),
-                    }
-                } else {
-                    let unresolved_name = || MirLowerError::unresolved_path(self.db, p);
-                    let resolver = resolver_for_expr(self.db.upcast(), self.owner, expr_id);
-                    resolver
-                        .resolve_path_in_value_ns_fully(self.db.upcast(), p)
-                        .ok_or_else(unresolved_name)?
-                };
+                    } else if let Some(variant) = self.infer.variant_resolution_for_expr(expr_id) {
+                        match variant {
+                            VariantId::EnumVariantId(e) => ValueNs::EnumVariantId(e),
+                            VariantId::StructId(s) => ValueNs::StructId(s),
+                            VariantId::UnionId(_) => implementation_error!("Union variant as path"),
+                        }
+                    } else {
+                        let unresolved_name = || MirLowerError::unresolved_path(self.db, p);
+                        let resolver = resolver_for_expr(self.db.upcast(), self.owner, expr_id);
+                        resolver
+                            .resolve_path_in_value_ns_fully(self.db.upcast(), p)
+                            .ok_or_else(unresolved_name)?
+                    };
                 match pr {
                     ValueNs::LocalBinding(_) | ValueNs::StaticId(_) => {
-                        let Some((temp, current)) = self.lower_expr_as_place_without_adjust(current, expr_id, false)? else {
+                        let Some((temp, current)) =
+                            self.lower_expr_as_place_without_adjust(current, expr_id, false)?
+                        else {
                             return Ok(None);
                         };
                         self.push_assignment(
@@ -423,11 +433,19 @@ impl<'ctx> MirLowerCtx<'ctx> {
                         Ok(Some(current))
                     }
                     ValueNs::ConstId(const_id) => {
-                        self.lower_const(const_id.into(), current, place, Substitution::empty(Interner), expr_id.into(), self.expr_ty_without_adjust(expr_id))?;
+                        self.lower_const(
+                            const_id.into(),
+                            current,
+                            place,
+                            Substitution::empty(Interner),
+                            expr_id.into(),
+                            self.expr_ty_without_adjust(expr_id),
+                        )?;
                         Ok(Some(current))
                     }
                     ValueNs::EnumVariantId(variant_id) => {
-                        let variant_data = &self.db.enum_data(variant_id.parent).variants[variant_id.local_id];
+                        let variant_data =
+                            &self.db.enum_data(variant_id.parent).variants[variant_id.local_id];
                         if variant_data.variant_data.kind() == StructKind::Unit {
                             let ty = self.infer.type_of_expr[expr_id].clone();
                             current = self.lower_enum_variant(
@@ -478,7 +496,9 @@ impl<'ctx> MirLowerCtx<'ctx> {
                 }
             }
             Expr::If { condition, then_branch, else_branch } => {
-                let Some((discr, current)) = self.lower_expr_to_some_operand(*condition, current)? else {
+                let Some((discr, current)) =
+                    self.lower_expr_to_some_operand(*condition, current)?
+                else {
                     return Ok(None);
                 };
                 let start_of_then = self.new_basic_block();
@@ -501,15 +521,12 @@ impl<'ctx> MirLowerCtx<'ctx> {
                 Ok(self.merge_blocks(end_of_then, end_of_else, expr_id.into()))
             }
             Expr::Let { pat, expr } => {
-                let Some((cond_place, current)) = self.lower_expr_as_place(current, *expr, true)? else {
+                let Some((cond_place, current)) = self.lower_expr_as_place(current, *expr, true)?
+                else {
                     return Ok(None);
                 };
-                let (then_target, else_target) = self.pattern_match(
-                    current,
-                    None,
-                    cond_place,
-                    *pat,
-                )?;
+                let (then_target, else_target) =
+                    self.pattern_match(current, None, cond_place, *pat)?;
                 self.write_bytes_to_place(
                     then_target,
                     place.clone(),
@@ -533,31 +550,47 @@ impl<'ctx> MirLowerCtx<'ctx> {
             }
             Expr::Block { id: _, statements, tail, label } => {
                 if let Some(label) = label {
-                    self.lower_loop(current, place.clone(), Some(*label), expr_id.into(), |this, begin| {
-                        if let Some(current) = this.lower_block_to_place(statements, begin, *tail, place, expr_id.into())? {
-                            let end = this.current_loop_end()?;
-                            this.set_goto(current, end, expr_id.into());
-                        }
-                        Ok(())
-                    })
+                    self.lower_loop(
+                        current,
+                        place.clone(),
+                        Some(*label),
+                        expr_id.into(),
+                        |this, begin| {
+                            if let Some(current) = this.lower_block_to_place(
+                                statements,
+                                begin,
+                                *tail,
+                                place,
+                                expr_id.into(),
+                            )? {
+                                let end = this.current_loop_end()?;
+                                this.set_goto(current, end, expr_id.into());
+                            }
+                            Ok(())
+                        },
+                    )
                 } else {
                     self.lower_block_to_place(statements, current, *tail, place, expr_id.into())
                 }
             }
-            Expr::Loop { body, label } => self.lower_loop(current, place, *label, expr_id.into(), |this, begin| {
-                let scope = this.push_drop_scope();
-                if let Some((_, mut current)) = this.lower_expr_as_place(begin, *body, true)? {
-                    current = scope.pop_and_drop(this, current);
-                    this.set_goto(current, begin, expr_id.into());
-                } else {
-                    scope.pop_assume_dropped(this);
-                }
-                Ok(())
-            }),
+            Expr::Loop { body, label } => {
+                self.lower_loop(current, place, *label, expr_id.into(), |this, begin| {
+                    let scope = this.push_drop_scope();
+                    if let Some((_, mut current)) = this.lower_expr_as_place(begin, *body, true)? {
+                        current = scope.pop_and_drop(this, current);
+                        this.set_goto(current, begin, expr_id.into());
+                    } else {
+                        scope.pop_assume_dropped(this);
+                    }
+                    Ok(())
+                })
+            }
             Expr::While { condition, body, label } => {
-                self.lower_loop(current, place, *label, expr_id.into(),|this, begin| {
+                self.lower_loop(current, place, *label, expr_id.into(), |this, begin| {
                     let scope = this.push_drop_scope();
-                    let Some((discr, to_switch)) = this.lower_expr_to_some_operand(*condition, begin)? else {
+                    let Some((discr, to_switch)) =
+                        this.lower_expr_to_some_operand(*condition, begin)?
+                    else {
                         return Ok(());
                     };
                     let fail_cond = this.new_basic_block();
@@ -583,8 +616,7 @@ impl<'ctx> MirLowerCtx<'ctx> {
                 })
             }
             Expr::Call { callee, args, .. } => {
-                if let Some((func_id, generic_args)) =
-                    self.infer.method_resolution(expr_id) {
+                if let Some((func_id, generic_args)) = self.infer.method_resolution(expr_id) {
                     let ty = chalk_ir::TyKind::FnDef(
                         CallableDefId::FunctionId(func_id).to_chalk(self.db),
                         generic_args,
@@ -604,21 +636,43 @@ impl<'ctx> MirLowerCtx<'ctx> {
                 match &callee_ty.data(Interner).kind {
                     chalk_ir::TyKind::FnDef(..) => {
                         let func = Operand::from_bytes(vec![], callee_ty.clone());
-                        self.lower_call_and_args(func, args.iter().copied(), place, current, self.is_uninhabited(expr_id), expr_id.into())
+                        self.lower_call_and_args(
+                            func,
+                            args.iter().copied(),
+                            place,
+                            current,
+                            self.is_uninhabited(expr_id),
+                            expr_id.into(),
+                        )
                     }
                     chalk_ir::TyKind::Function(_) => {
-                        let Some((func, current)) = self.lower_expr_to_some_operand(*callee, current)? else {
+                        let Some((func, current)) =
+                            self.lower_expr_to_some_operand(*callee, current)?
+                        else {
                             return Ok(None);
                         };
-                        self.lower_call_and_args(func, args.iter().copied(), place, current, self.is_uninhabited(expr_id), expr_id.into())
+                        self.lower_call_and_args(
+                            func,
+                            args.iter().copied(),
+                            place,
+                            current,
+                            self.is_uninhabited(expr_id),
+                            expr_id.into(),
+                        )
+                    }
+                    TyKind::Error => {
+                        return Err(MirLowerError::MissingFunctionDefinition(self.owner, expr_id))
                     }
-                    TyKind::Error => return Err(MirLowerError::MissingFunctionDefinition(self.owner, expr_id)),
                     _ => return Err(MirLowerError::TypeError("function call on bad type")),
                 }
             }
             Expr::MethodCall { receiver, args, method_name, .. } => {
                 let (func_id, generic_args) =
-                    self.infer.method_resolution(expr_id).ok_or_else(|| MirLowerError::UnresolvedMethod(method_name.display(self.db.upcast()).to_string()))?;
+                    self.infer.method_resolution(expr_id).ok_or_else(|| {
+                        MirLowerError::UnresolvedMethod(
+                            method_name.display(self.db.upcast()).to_string(),
+                        )
+                    })?;
                 let func = Operand::from_fn(self.db, func_id, generic_args);
                 self.lower_call_and_args(
                     func,
@@ -630,23 +684,27 @@ impl<'ctx> MirLowerCtx<'ctx> {
                 )
             }
             Expr::Match { expr, arms } => {
-                let Some((cond_place, mut current)) = self.lower_expr_as_place(current, *expr, true)?
+                let Some((cond_place, mut current)) =
+                    self.lower_expr_as_place(current, *expr, true)?
                 else {
                     return Ok(None);
                 };
                 let mut end = None;
                 for MatchArm { pat, guard, expr } in arms.iter() {
-                    let (then, mut otherwise) = self.pattern_match(
-                        current,
-                        None,
-                        cond_place.clone(),
-                        *pat,
-                    )?;
+                    let (then, mut otherwise) =
+                        self.pattern_match(current, None, cond_place.clone(), *pat)?;
                     let then = if let &Some(guard) = guard {
                         let next = self.new_basic_block();
                         let o = otherwise.get_or_insert_with(|| self.new_basic_block());
                         if let Some((discr, c)) = self.lower_expr_to_some_operand(guard, then)? {
-                            self.set_terminator(c, TerminatorKind::SwitchInt { discr, targets: SwitchTargets::static_if(1, next, *o) }, expr_id.into());
+                            self.set_terminator(
+                                c,
+                                TerminatorKind::SwitchInt {
+                                    discr,
+                                    targets: SwitchTargets::static_if(1, next, *o),
+                                },
+                                expr_id.into(),
+                            );
                         }
                         next
                     } else {
@@ -672,33 +730,53 @@ impl<'ctx> MirLowerCtx<'ctx> {
             }
             Expr::Continue { label } => {
                 let loop_data = match label {
-                    Some(l) => self.labeled_loop_blocks.get(l).ok_or(MirLowerError::UnresolvedLabel)?,
-                    None => self.current_loop_blocks.as_ref().ok_or(MirLowerError::ContinueWithoutLoop)?,
+                    Some(l) => {
+                        self.labeled_loop_blocks.get(l).ok_or(MirLowerError::UnresolvedLabel)?
+                    }
+                    None => self
+                        .current_loop_blocks
+                        .as_ref()
+                        .ok_or(MirLowerError::ContinueWithoutLoop)?,
                 };
                 let begin = loop_data.begin;
                 current = self.drop_until_scope(loop_data.drop_scope_index, current);
                 self.set_goto(current, begin, expr_id.into());
                 Ok(None)
-            },
+            }
             &Expr::Break { expr, label } => {
                 if let Some(expr) = expr {
                     let loop_data = match label {
-                        Some(l) => self.labeled_loop_blocks.get(&l).ok_or(MirLowerError::UnresolvedLabel)?,
-                        None => self.current_loop_blocks.as_ref().ok_or(MirLowerError::BreakWithoutLoop)?,
+                        Some(l) => self
+                            .labeled_loop_blocks
+                            .get(&l)
+                            .ok_or(MirLowerError::UnresolvedLabel)?,
+                        None => self
+                            .current_loop_blocks
+                            .as_ref()
+                            .ok_or(MirLowerError::BreakWithoutLoop)?,
                     };
-                    let Some(c) = self.lower_expr_to_place(expr, loop_data.place.clone(), current)? else {
+                    let Some(c) =
+                        self.lower_expr_to_place(expr, loop_data.place.clone(), current)?
+                    else {
                         return Ok(None);
                     };
                     current = c;
                 }
                 let (end, drop_scope) = match label {
                     Some(l) => {
-                        let loop_blocks = self.labeled_loop_blocks.get(&l).ok_or(MirLowerError::UnresolvedLabel)?;
-                        (loop_blocks.end.expect("We always generate end for labeled loops"), loop_blocks.drop_scope_index)
-                    },
-                    None => {
-                        (self.current_loop_end()?, self.current_loop_blocks.as_ref().unwrap().drop_scope_index)
-                    },
+                        let loop_blocks = self
+                            .labeled_loop_blocks
+                            .get(&l)
+                            .ok_or(MirLowerError::UnresolvedLabel)?;
+                        (
+                            loop_blocks.end.expect("We always generate end for labeled loops"),
+                            loop_blocks.drop_scope_index,
+                        )
+                    }
+                    None => (
+                        self.current_loop_end()?,
+                        self.current_loop_blocks.as_ref().unwrap().drop_scope_index,
+                    ),
                 };
                 current = self.drop_until_scope(drop_scope, current);
                 self.set_goto(current, end, expr_id.into());
@@ -706,7 +784,9 @@ impl<'ctx> MirLowerCtx<'ctx> {
             }
             Expr::Return { expr } => {
                 if let Some(expr) = expr {
-                    if let Some(c) = self.lower_expr_to_place(*expr, return_slot().into(), current)? {
+                    if let Some(c) =
+                        self.lower_expr_to_place(*expr, return_slot().into(), current)?
+                    {
                         current = c;
                     } else {
                         return Ok(None);
@@ -725,13 +805,11 @@ impl<'ctx> MirLowerCtx<'ctx> {
                         };
                         current = c;
                         Some(p)
-                    },
+                    }
                     None => None,
                 };
-                let variant_id = self
-                    .infer
-                    .variant_resolution_for_expr(expr_id)
-                    .ok_or_else(|| match path {
+                let variant_id =
+                    self.infer.variant_resolution_for_expr(expr_id).ok_or_else(|| match path {
                         Some(p) => MirLowerError::UnresolvedName(p.display(self.db).to_string()),
                         None => MirLowerError::RecordLiteralWithoutPath,
                     })?;
@@ -746,7 +824,8 @@ impl<'ctx> MirLowerCtx<'ctx> {
                         for RecordLitField { name, expr } in fields.iter() {
                             let field_id =
                                 variant_data.field(name).ok_or(MirLowerError::UnresolvedField)?;
-                            let Some((op, c)) = self.lower_expr_to_some_operand(*expr, current)? else {
+                            let Some((op, c)) = self.lower_expr_to_some_operand(*expr, current)?
+                            else {
                                 return Ok(None);
                             };
                             current = c;
@@ -758,18 +837,23 @@ impl<'ctx> MirLowerCtx<'ctx> {
                             Rvalue::Aggregate(
                                 AggregateKind::Adt(variant_id, subst),
                                 match spread_place {
-                                    Some(sp) => operands.into_iter().enumerate().map(|(i, x)| {
-                                        match x {
+                                    Some(sp) => operands
+                                        .into_iter()
+                                        .enumerate()
+                                        .map(|(i, x)| match x {
                                             Some(x) => x,
                                             None => {
-                                                let p = sp.project(ProjectionElem::Field(FieldId {
-                                                    parent: variant_id,
-                                                    local_id: LocalFieldId::from_raw(RawIdx::from(i as u32)),
-                                                }));
+                                                let p =
+                                                    sp.project(ProjectionElem::Field(FieldId {
+                                                        parent: variant_id,
+                                                        local_id: LocalFieldId::from_raw(
+                                                            RawIdx::from(i as u32),
+                                                        ),
+                                                    }));
                                                 Operand::Copy(p)
-                                            },
-                                        }
-                                    }).collect(),
+                                            }
+                                        })
+                                        .collect(),
                                     None => operands.into_iter().collect::<Option<_>>().ok_or(
                                         MirLowerError::TypeError("missing field in record literal"),
                                     )?,
@@ -785,7 +869,10 @@ impl<'ctx> MirLowerCtx<'ctx> {
                         };
                         let local_id =
                             variant_data.field(name).ok_or(MirLowerError::UnresolvedField)?;
-                        let place = place.project(PlaceElem::Field(FieldId { parent: union_id.into(), local_id }));
+                        let place = place.project(PlaceElem::Field(FieldId {
+                            parent: union_id.into(),
+                            local_id,
+                        }));
                         self.lower_expr_to_place(*expr, place, current)
                     }
                 }
@@ -795,9 +882,16 @@ impl<'ctx> MirLowerCtx<'ctx> {
             Expr::Async { .. } => not_supported!("async block"),
             &Expr::Const(id) => {
                 let subst = self.placeholder_subst();
-                self.lower_const(id.into(), current, place, subst, expr_id.into(), self.expr_ty_without_adjust(expr_id))?;
+                self.lower_const(
+                    id.into(),
+                    current,
+                    place,
+                    subst,
+                    expr_id.into(),
+                    self.expr_ty_without_adjust(expr_id),
+                )?;
                 Ok(Some(current))
-            },
+            }
             Expr::Cast { expr, type_ref: _ } => {
                 let Some((x, current)) = self.lower_expr_to_some_operand(*expr, current)? else {
                     return Ok(None);
@@ -822,23 +916,37 @@ impl<'ctx> MirLowerCtx<'ctx> {
             }
             Expr::Box { expr } => {
                 let ty = self.expr_ty_after_adjustments(*expr);
-                self.push_assignment(current, place.clone(), Rvalue::ShallowInitBoxWithAlloc(ty), expr_id.into());
-                let Some((operand, current)) = self.lower_expr_to_some_operand(*expr, current)? else {
+                self.push_assignment(
+                    current,
+                    place.clone(),
+                    Rvalue::ShallowInitBoxWithAlloc(ty),
+                    expr_id.into(),
+                );
+                let Some((operand, current)) = self.lower_expr_to_some_operand(*expr, current)?
+                else {
                     return Ok(None);
                 };
                 let p = place.project(ProjectionElem::Deref);
                 self.push_assignment(current, p, operand.into(), expr_id.into());
                 Ok(Some(current))
-            },
-            Expr::Field { .. } | Expr::Index { .. } | Expr::UnaryOp { op: hir_def::hir::UnaryOp::Deref, .. } => {
-                let Some((p, current)) = self.lower_expr_as_place_without_adjust(current, expr_id, true)? else {
+            }
+            Expr::Field { .. }
+            | Expr::Index { .. }
+            | Expr::UnaryOp { op: hir_def::hir::UnaryOp::Deref, .. } => {
+                let Some((p, current)) =
+                    self.lower_expr_as_place_without_adjust(current, expr_id, true)?
+                else {
                     return Ok(None);
                 };
                 self.push_assignment(current, place, Operand::Copy(p).into(), expr_id.into());
                 Ok(Some(current))
             }
-            Expr::UnaryOp { expr, op: op @ (hir_def::hir::UnaryOp::Not | hir_def::hir::UnaryOp::Neg) } => {
-                let Some((operand, current)) = self.lower_expr_to_some_operand(*expr, current)? else {
+            Expr::UnaryOp {
+                expr,
+                op: op @ (hir_def::hir::UnaryOp::Not | hir_def::hir::UnaryOp::Neg),
+            } => {
+                let Some((operand, current)) = self.lower_expr_to_some_operand(*expr, current)?
+                else {
                     return Ok(None);
                 };
                 let operation = match op {
@@ -853,7 +961,7 @@ impl<'ctx> MirLowerCtx<'ctx> {
                     expr_id.into(),
                 );
                 Ok(Some(current))
-            },
+            }
             Expr::BinaryOp { lhs, rhs, op } => {
                 let op = op.ok_or(MirLowerError::IncompleteExpr)?;
                 let is_builtin = 'b: {
@@ -861,16 +969,19 @@ impl<'ctx> MirLowerCtx<'ctx> {
                     // for binary operator, and use without adjust to simplify our conditions.
                     let lhs_ty = self.expr_ty_without_adjust(*lhs);
                     let rhs_ty = self.expr_ty_without_adjust(*rhs);
-                    if matches!(op ,BinaryOp::CmpOp(syntax::ast::CmpOp::Eq { .. })) {
+                    if matches!(op, BinaryOp::CmpOp(syntax::ast::CmpOp::Eq { .. })) {
                         if lhs_ty.as_raw_ptr().is_some() && rhs_ty.as_raw_ptr().is_some() {
                             break 'b true;
                         }
                     }
                     let builtin_inequal_impls = matches!(
                         op,
-                        BinaryOp::ArithOp(ArithOp::Shl | ArithOp::Shr) | BinaryOp::Assignment { op: Some(ArithOp::Shl | ArithOp::Shr) }
+                        BinaryOp::ArithOp(ArithOp::Shl | ArithOp::Shr)
+                            | BinaryOp::Assignment { op: Some(ArithOp::Shl | ArithOp::Shr) }
                     );
-                    lhs_ty.is_scalar() && rhs_ty.is_scalar() && (lhs_ty == rhs_ty || builtin_inequal_impls)
+                    lhs_ty.is_scalar()
+                        && rhs_ty.is_scalar()
+                        && (lhs_ty == rhs_ty || builtin_inequal_impls)
                 };
                 if !is_builtin {
                     if let Some((func_id, generic_args)) = self.infer.method_resolution(expr_id) {
@@ -894,32 +1005,43 @@ impl<'ctx> MirLowerCtx<'ctx> {
                             .get(lhs)
                             .and_then(|x| x.split_last())
                             .map(|x| x.1)
-                            .ok_or(MirLowerError::TypeError("adjustment of binary op was missing"))?;
+                            .ok_or(MirLowerError::TypeError(
+                                "adjustment of binary op was missing",
+                            ))?;
                         let Some((lhs_place, current)) =
                             self.lower_expr_as_place_with_adjust(current, *lhs, false, adjusts)?
                         else {
                             return Ok(None);
                         };
-                        let Some((rhs_op, current)) = self.lower_expr_to_some_operand(*rhs, current)? else {
+                        let Some((rhs_op, current)) =
+                            self.lower_expr_to_some_operand(*rhs, current)?
+                        else {
                             return Ok(None);
                         };
-                        let r_value = Rvalue::CheckedBinaryOp(op.into(), Operand::Copy(lhs_place.clone()), rhs_op);
+                        let r_value = Rvalue::CheckedBinaryOp(
+                            op.into(),
+                            Operand::Copy(lhs_place.clone()),
+                            rhs_op,
+                        );
                         self.push_assignment(current, lhs_place, r_value, expr_id.into());
                         return Ok(Some(current));
                     } else {
                         let Some((lhs_place, current)) =
-                        self.lower_expr_as_place(current, *lhs, false)?
+                            self.lower_expr_as_place(current, *lhs, false)?
                         else {
                             return Ok(None);
                         };
-                        let Some((rhs_op, current)) = self.lower_expr_to_some_operand(*rhs, current)? else {
+                        let Some((rhs_op, current)) =
+                            self.lower_expr_to_some_operand(*rhs, current)?
+                        else {
                             return Ok(None);
                         };
                         self.push_assignment(current, lhs_place, rhs_op.into(), expr_id.into());
                         return Ok(Some(current));
                     }
                 }
-                let Some((lhs_op, current)) = self.lower_expr_to_some_operand(*lhs, current)? else {
+                let Some((lhs_op, current)) = self.lower_expr_to_some_operand(*lhs, current)?
+                else {
                     return Ok(None);
                 };
                 if let hir_def::hir::BinaryOp::LogicOp(op) = op {
@@ -928,22 +1050,31 @@ impl<'ctx> MirLowerCtx<'ctx> {
                         syntax::ast::LogicOp::Or => 1,
                     };
                     let start_of_then = self.new_basic_block();
-                    self.push_assignment(start_of_then, place.clone(), lhs_op.clone().into(), expr_id.into());
+                    self.push_assignment(
+                        start_of_then,
+                        place.clone(),
+                        lhs_op.clone().into(),
+                        expr_id.into(),
+                    );
                     let end_of_then = Some(start_of_then);
                     let start_of_else = self.new_basic_block();
-                    let end_of_else =
-                        self.lower_expr_to_place(*rhs, place, start_of_else)?;
+                    let end_of_else = self.lower_expr_to_place(*rhs, place, start_of_else)?;
                     self.set_terminator(
                         current,
                         TerminatorKind::SwitchInt {
                             discr: lhs_op,
-                            targets: SwitchTargets::static_if(value_to_short, start_of_then, start_of_else),
+                            targets: SwitchTargets::static_if(
+                                value_to_short,
+                                start_of_then,
+                                start_of_else,
+                            ),
                         },
                         expr_id.into(),
                     );
                     return Ok(self.merge_blocks(end_of_then, end_of_else, expr_id.into()));
                 }
-                let Some((rhs_op, current)) = self.lower_expr_to_some_operand(*rhs, current)? else {
+                let Some((rhs_op, current)) = self.lower_expr_to_some_operand(*rhs, current)?
+                else {
                     return Ok(None);
                 };
                 self.push_assignment(
@@ -995,20 +1126,28 @@ impl<'ctx> MirLowerCtx<'ctx> {
                     place,
                     Rvalue::Aggregate(
                         AggregateKind::Adt(st.into(), subst.clone()),
-                        self.db.struct_data(st).variant_data.fields().iter().map(|x| {
-                            let o = match x.1.name.as_str() {
-                                Some("start") => lp.take(),
-                                Some("end") => rp.take(),
-                                Some("exhausted") => Some(Operand::from_bytes(vec![0], TyBuilder::bool())),
-                                _ => None,
-                            };
-                            o.ok_or(MirLowerError::UnresolvedField)
-                        }).collect::<Result<_>>()?,
+                        self.db
+                            .struct_data(st)
+                            .variant_data
+                            .fields()
+                            .iter()
+                            .map(|x| {
+                                let o = match x.1.name.as_str() {
+                                    Some("start") => lp.take(),
+                                    Some("end") => rp.take(),
+                                    Some("exhausted") => {
+                                        Some(Operand::from_bytes(vec![0], TyBuilder::bool()))
+                                    }
+                                    _ => None,
+                                };
+                                o.ok_or(MirLowerError::UnresolvedField)
+                            })
+                            .collect::<Result<_>>()?,
                     ),
                     expr_id.into(),
                 );
                 Ok(Some(current))
-            },
+            }
             Expr::Closure { .. } => {
                 let ty = self.expr_ty_without_adjust(expr_id);
                 let TyKind::Closure(id, _) = ty.kind(Interner) else {
@@ -1020,22 +1159,33 @@ impl<'ctx> MirLowerCtx<'ctx> {
                 for capture in captures.iter() {
                     let p = Place {
                         local: self.binding_local(capture.place.local)?,
-                        projection: capture.place.projections.clone().into_iter().map(|x| {
-                            match x {
+                        projection: capture
+                            .place
+                            .projections
+                            .clone()
+                            .into_iter()
+                            .map(|x| match x {
                                 ProjectionElem::Deref => ProjectionElem::Deref,
                                 ProjectionElem::Field(x) => ProjectionElem::Field(x),
-                                ProjectionElem::TupleOrClosureField(x) => ProjectionElem::TupleOrClosureField(x),
-                                ProjectionElem::ConstantIndex { offset, from_end } => ProjectionElem::ConstantIndex { offset, from_end },
-                                ProjectionElem::Subslice { from, to } => ProjectionElem::Subslice { from, to },
+                                ProjectionElem::TupleOrClosureField(x) => {
+                                    ProjectionElem::TupleOrClosureField(x)
+                                }
+                                ProjectionElem::ConstantIndex { offset, from_end } => {
+                                    ProjectionElem::ConstantIndex { offset, from_end }
+                                }
+                                ProjectionElem::Subslice { from, to } => {
+                                    ProjectionElem::Subslice { from, to }
+                                }
                                 ProjectionElem::OpaqueCast(x) => ProjectionElem::OpaqueCast(x),
-                                ProjectionElem::Index(x) => match x { },
-                            }
-                        }).collect(),
+                                ProjectionElem::Index(x) => match x {},
+                            })
+                            .collect(),
                     };
                     match &capture.kind {
                         CaptureKind::ByRef(bk) => {
                             let placeholder_subst = self.placeholder_subst();
-                            let tmp_ty = capture.ty.clone().substitute(Interner, &placeholder_subst);
+                            let tmp_ty =
+                                capture.ty.clone().substitute(Interner, &placeholder_subst);
                             let tmp: Place = self.temp(tmp_ty, current, capture.span)?.into();
                             self.push_assignment(
                                 current,
@@ -1044,7 +1194,7 @@ impl<'ctx> MirLowerCtx<'ctx> {
                                 capture.span,
                             );
                             operands.push(Operand::Move(tmp));
-                        },
+                        }
                         CaptureKind::ByValue => operands.push(Operand::Move(p)),
                     }
                 }
@@ -1055,18 +1205,18 @@ impl<'ctx> MirLowerCtx<'ctx> {
                     expr_id.into(),
                 );
                 Ok(Some(current))
-            },
+            }
             Expr::Tuple { exprs, is_assignee_expr: _ } => {
                 let Some(values) = exprs
-                        .iter()
-                        .map(|x| {
-                            let Some((o, c)) = self.lower_expr_to_some_operand(*x, current)? else {
-                                return Ok(None);
-                            };
-                            current = c;
-                            Ok(Some(o))
-                        })
-                        .collect::<Result<Option<_>>>()?
+                    .iter()
+                    .map(|x| {
+                        let Some((o, c)) = self.lower_expr_to_some_operand(*x, current)? else {
+                            return Ok(None);
+                        };
+                        current = c;
+                        Ok(Some(o))
+                    })
+                    .collect::<Result<Option<_>>>()?
                 else {
                     return Ok(None);
                 };
@@ -1088,27 +1238,26 @@ impl<'ctx> MirLowerCtx<'ctx> {
                         }
                     };
                     let Some(values) = elements
-                            .iter()
-                            .map(|x| {
-                                let Some((o, c)) = self.lower_expr_to_some_operand(*x, current)? else {
-                                    return Ok(None);
-                                };
-                                current = c;
-                                Ok(Some(o))
-                            })
-                            .collect::<Result<Option<_>>>()?
+                        .iter()
+                        .map(|x| {
+                            let Some((o, c)) = self.lower_expr_to_some_operand(*x, current)? else {
+                                return Ok(None);
+                            };
+                            current = c;
+                            Ok(Some(o))
+                        })
+                        .collect::<Result<Option<_>>>()?
                     else {
                         return Ok(None);
                     };
-                    let r = Rvalue::Aggregate(
-                        AggregateKind::Array(elem_ty),
-                        values,
-                    );
+                    let r = Rvalue::Aggregate(AggregateKind::Array(elem_ty), values);
                     self.push_assignment(current, place, r, expr_id.into());
                     Ok(Some(current))
                 }
                 Array::Repeat { initializer, .. } => {
-                    let Some((init, current)) = self.lower_expr_to_some_operand(*initializer, current)? else {
+                    let Some((init, current)) =
+                        self.lower_expr_to_some_operand(*initializer, current)?
+                    else {
                         return Ok(None);
                     };
                     let len = match &self.expr_ty_without_adjust(expr_id).data(Interner).kind {
@@ -1122,7 +1271,7 @@ impl<'ctx> MirLowerCtx<'ctx> {
                     let r = Rvalue::Repeat(init, len);
                     self.push_assignment(current, place, r, expr_id.into());
                     Ok(Some(current))
-                },
+                }
             },
             Expr::Literal(l) => {
                 let ty = self.expr_ty_without_adjust(expr_id);
diff --git a/crates/hir-ty/src/mir/lower/as_place.rs b/crates/hir-ty/src/mir/lower/as_place.rs
index d2c8d9a089..79f6da48ce 100644
--- a/crates/hir-ty/src/mir/lower/as_place.rs
+++ b/crates/hir-ty/src/mir/lower/as_place.rs
@@ -18,7 +18,9 @@ impl MirLowerCtx<'_> {
     ) -> Result<Option<(Place, BasicBlockId)>> {
         let ty = self.expr_ty_without_adjust(expr_id);
         let place = self.temp(ty, prev_block, expr_id.into())?;
-        let Some(current) = self.lower_expr_to_place_without_adjust(expr_id, place.into(), prev_block)? else {
+        let Some(current) =
+            self.lower_expr_to_place_without_adjust(expr_id, place.into(), prev_block)?
+        else {
             return Ok(None);
         };
         Ok(Some((place.into(), current)))
@@ -35,7 +37,9 @@ impl MirLowerCtx<'_> {
             .map(|x| x.target.clone())
             .unwrap_or_else(|| self.expr_ty_without_adjust(expr_id));
         let place = self.temp(ty, prev_block, expr_id.into())?;
-        let Some(current) = self.lower_expr_to_place_with_adjust(expr_id, place.into(), prev_block, adjustments)? else {
+        let Some(current) =
+            self.lower_expr_to_place_with_adjust(expr_id, place.into(), prev_block, adjustments)?
+        else {
             return Ok(None);
         };
         Ok(Some((place.into(), current)))
@@ -62,7 +66,8 @@ impl MirLowerCtx<'_> {
                         expr_id,
                         upgrade_rvalue,
                         rest,
-                    )? else {
+                    )?
+                    else {
                         return Ok(None);
                     };
                     x.0 = x.0.project(ProjectionElem::Deref);
@@ -74,7 +79,8 @@ impl MirLowerCtx<'_> {
                         expr_id,
                         upgrade_rvalue,
                         rest,
-                    )? else {
+                    )?
+                    else {
                         return Ok(None);
                     };
                     self.lower_overloaded_deref(
@@ -165,7 +171,8 @@ impl MirLowerCtx<'_> {
                         _ => false,
                     };
                     if !is_builtin {
-                        let Some((p, current)) = self.lower_expr_as_place(current, *expr, true)? else {
+                        let Some((p, current)) = self.lower_expr_as_place(current, *expr, true)?
+                        else {
                             return Ok(None);
                         };
                         return self.lower_overloaded_deref(
@@ -192,7 +199,8 @@ impl MirLowerCtx<'_> {
                             },
                         );
                     }
-                    let Some((mut r, current)) = self.lower_expr_as_place(current, *expr, true)? else {
+                    let Some((mut r, current)) = self.lower_expr_as_place(current, *expr, true)?
+                    else {
                         return Ok(None);
                     };
                     r = r.project(ProjectionElem::Deref);
@@ -217,12 +225,18 @@ impl MirLowerCtx<'_> {
                     )
                 {
                     let Some(index_fn) = self.infer.method_resolution(expr_id) else {
-                        return Err(MirLowerError::UnresolvedMethod("[overloaded index]".to_string()));
+                        return Err(MirLowerError::UnresolvedMethod(
+                            "[overloaded index]".to_string(),
+                        ));
                     };
-                    let Some((base_place, current)) = self.lower_expr_as_place(current, *base, true)? else {
+                    let Some((base_place, current)) =
+                        self.lower_expr_as_place(current, *base, true)?
+                    else {
                         return Ok(None);
                     };
-                    let Some((index_operand, current)) = self.lower_expr_to_some_operand(*index, current)? else {
+                    let Some((index_operand, current)) =
+                        self.lower_expr_to_some_operand(*index, current)?
+                    else {
                         return Ok(None);
                     };
                     return self.lower_overloaded_index(
@@ -249,7 +263,8 @@ impl MirLowerCtx<'_> {
                 };
                 let l_index =
                     self.temp(self.expr_ty_after_adjustments(*index), current, expr_id.into())?;
-                let Some(current) = self.lower_expr_to_place(*index, l_index.into(), current)? else {
+                let Some(current) = self.lower_expr_to_place(*index, l_index.into(), current)?
+                else {
                     return Ok(None);
                 };
                 p_base = p_base.project(ProjectionElem::Index(l_index));
@@ -282,7 +297,15 @@ impl MirLowerCtx<'_> {
             )
             .intern(Interner),
         );
-        let Some(current) = self.lower_call(index_fn_op, Box::new([Operand::Copy(place), index_operand]), result.clone(), current, false, span)? else {
+        let Some(current) = self.lower_call(
+            index_fn_op,
+            Box::new([Operand::Copy(place), index_operand]),
+            result.clone(),
+            current,
+            false,
+            span,
+        )?
+        else {
             return Ok(None);
         };
         result = result.project(ProjectionElem::Deref);
@@ -329,7 +352,15 @@ impl MirLowerCtx<'_> {
             .intern(Interner),
         );
         let mut result: Place = self.temp(target_ty_ref, current, span)?.into();
-        let Some(current) = self.lower_call(deref_fn_op, Box::new([Operand::Copy(ref_place)]), result.clone(), current, false, span)? else {
+        let Some(current) = self.lower_call(
+            deref_fn_op,
+            Box::new([Operand::Copy(ref_place)]),
+            result.clone(),
+            current,
+            false,
+            span,
+        )?
+        else {
             return Ok(None);
         };
         result = result.project(ProjectionElem::Deref);
diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs
index 7d07e9cce4..9082568436 100644
--- a/crates/hir/src/lib.rs
+++ b/crates/hir/src/lib.rs
@@ -701,9 +701,9 @@ fn emit_macro_def_diagnostics(db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>
     let id = macro_id_to_def_id(db.upcast(), m.id);
     if let Err(e) = db.macro_def(id) {
         let Some(ast) = id.ast_id().left() else {
-                never!("MacroDefError for proc-macro: {:?}", e);
-                return;
-            };
+            never!("MacroDefError for proc-macro: {:?}", e);
+            return;
+        };
         emit_def_diagnostic_(
             db,
             acc,
diff --git a/crates/hir/src/semantics.rs b/crates/hir/src/semantics.rs
index 0c46e2a4fe..39a3e1c448 100644
--- a/crates/hir/src/semantics.rs
+++ b/crates/hir/src/semantics.rs
@@ -1494,7 +1494,11 @@ impl<'db> SemanticsImpl<'db> {
     }
 
     fn is_inside_unsafe(&self, expr: &ast::Expr) -> bool {
-        let Some(enclosing_item) = expr.syntax().ancestors().find_map(Either::<ast::Item, ast::Variant>::cast) else { return false };
+        let Some(enclosing_item) =
+            expr.syntax().ancestors().find_map(Either::<ast::Item, ast::Variant>::cast)
+        else {
+            return false;
+        };
 
         let def = match &enclosing_item {
             Either::Left(ast::Item::Fn(it)) if it.unsafe_token().is_some() => return true,
diff --git a/crates/ide-assists/src/handlers/desugar_doc_comment.rs b/crates/ide-assists/src/handlers/desugar_doc_comment.rs
index 226a5dd9fa..ddc8a50ed4 100644
--- a/crates/ide-assists/src/handlers/desugar_doc_comment.rs
+++ b/crates/ide-assists/src/handlers/desugar_doc_comment.rs
@@ -27,7 +27,9 @@ use crate::{
 pub(crate) fn desugar_doc_comment(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
     let comment = ctx.find_token_at_offset::<ast::Comment>()?;
     // Only allow doc comments
-    let Some(placement) = comment.kind().doc else { return None; };
+    let Some(placement) = comment.kind().doc else {
+        return None;
+    };
 
     // Only allow comments which are alone on their line
     if let Some(prev) = comment.syntax().prev_token() {
diff --git a/crates/ide-assists/src/handlers/fix_visibility.rs b/crates/ide-assists/src/handlers/fix_visibility.rs
index d6c59a9c82..4a2ab18c98 100644
--- a/crates/ide-assists/src/handlers/fix_visibility.rs
+++ b/crates/ide-assists/src/handlers/fix_visibility.rs
@@ -40,12 +40,16 @@ fn add_vis_to_referenced_module_def(acc: &mut Assists, ctx: &AssistContext<'_>)
     let qualifier = path.qualifier()?;
     let name_ref = path.segment()?.name_ref()?;
     let qualifier_res = ctx.sema.resolve_path(&qualifier)?;
-    let PathResolution::Def(ModuleDef::Module(module)) = qualifier_res else { return None; };
+    let PathResolution::Def(ModuleDef::Module(module)) = qualifier_res else {
+        return None;
+    };
     let (_, def) = module
         .scope(ctx.db(), None)
         .into_iter()
         .find(|(name, _)| name.to_smol_str() == name_ref.text().as_str())?;
-    let ScopeDef::ModuleDef(def) = def else { return None; };
+    let ScopeDef::ModuleDef(def) = def else {
+        return None;
+    };
 
     let current_module = ctx.sema.scope(path.syntax())?.module();
     let target_module = def.module(ctx.db())?;
diff --git a/crates/ide-assists/src/handlers/generate_delegate_methods.rs b/crates/ide-assists/src/handlers/generate_delegate_methods.rs
index b68c766e64..1c2ec79809 100644
--- a/crates/ide-assists/src/handlers/generate_delegate_methods.rs
+++ b/crates/ide-assists/src/handlers/generate_delegate_methods.rs
@@ -88,7 +88,9 @@ pub(crate) fn generate_delegate_methods(acc: &mut Assists, ctx: &AssistContext<'
         let adt = ast::Adt::Struct(strukt.clone());
         let name = name.display(ctx.db()).to_string();
         // if `find_struct_impl` returns None, that means that a function named `name` already exists.
-        let Some(impl_def) = find_struct_impl(ctx, &adt, std::slice::from_ref(&name)) else { continue; };
+        let Some(impl_def) = find_struct_impl(ctx, &adt, std::slice::from_ref(&name)) else {
+            continue;
+        };
         acc.add_group(
             &GroupLabel("Generate delegate methods…".to_owned()),
             AssistId("generate_delegate_methods", AssistKind::Generate),
diff --git a/crates/ide-assists/src/handlers/generate_function.rs b/crates/ide-assists/src/handlers/generate_function.rs
index c579f6780d..8085572497 100644
--- a/crates/ide-assists/src/handlers/generate_function.rs
+++ b/crates/ide-assists/src/handlers/generate_function.rs
@@ -623,7 +623,9 @@ fn fn_generic_params(
 fn params_and_where_preds_in_scope(
     ctx: &AssistContext<'_>,
 ) -> (Vec<ast::GenericParam>, Vec<ast::WherePred>) {
-    let Some(body) = containing_body(ctx) else { return Default::default(); };
+    let Some(body) = containing_body(ctx) else {
+        return Default::default();
+    };
 
     let mut generic_params = Vec::new();
     let mut where_clauses = Vec::new();
diff --git a/crates/ide-assists/src/handlers/move_const_to_impl.rs b/crates/ide-assists/src/handlers/move_const_to_impl.rs
index b6027eac55..e1849eb71d 100644
--- a/crates/ide-assists/src/handlers/move_const_to_impl.rs
+++ b/crates/ide-assists/src/handlers/move_const_to_impl.rs
@@ -54,7 +54,11 @@ pub(crate) fn move_const_to_impl(acc: &mut Assists, ctx: &AssistContext<'_>) ->
     // NOTE: We can technically provide this assist for default methods in trait definitions, but
     // it's somewhat complex to handle it correctly when the const's name conflicts with
     // supertrait's item. We may want to consider implementing it in the future.
-    let AssocItemContainer::Impl(impl_) = ctx.sema.to_def(&parent_fn)?.as_assoc_item(db)?.container(db) else { return None; };
+    let AssocItemContainer::Impl(impl_) =
+        ctx.sema.to_def(&parent_fn)?.as_assoc_item(db)?.container(db)
+    else {
+        return None;
+    };
     if impl_.trait_(db).is_some() {
         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 c03bc2f41d..3bdd795bea 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
@@ -73,7 +73,7 @@ pub(crate) fn replace_derive_with_manual_impl(
         &ctx.sema,
         current_crate,
         NameToImport::exact_case_sensitive(path.segments().last()?.to_string()),
-        items_locator::AssocSearchMode::Exclude,
+        items_locator::AssocItemSearch::Exclude,
         Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT.inner()),
     )
     .filter_map(|item| match item.as_module_def()? {
diff --git a/crates/ide-assists/src/handlers/unwrap_result_return_type.rs b/crates/ide-assists/src/handlers/unwrap_result_return_type.rs
index 26f3c19261..f235b554e6 100644
--- a/crates/ide-assists/src/handlers/unwrap_result_return_type.rs
+++ b/crates/ide-assists/src/handlers/unwrap_result_return_type.rs
@@ -38,14 +38,18 @@ pub(crate) fn unwrap_result_return_type(acc: &mut Assists, ctx: &AssistContext<'
     };
 
     let type_ref = &ret_type.ty()?;
-    let Some(hir::Adt::Enum(ret_enum)) = ctx.sema.resolve_type(type_ref)?.as_adt() else { return None; };
+    let Some(hir::Adt::Enum(ret_enum)) = ctx.sema.resolve_type(type_ref)?.as_adt() else {
+        return None;
+    };
     let result_enum =
         FamousDefs(&ctx.sema, ctx.sema.scope(type_ref.syntax())?.krate()).core_result_Result()?;
     if ret_enum != result_enum {
         return None;
     }
 
-    let Some(ok_type) = unwrap_result_type(type_ref) else { return None; };
+    let Some(ok_type) = unwrap_result_type(type_ref) else {
+        return None;
+    };
 
     acc.add(
         AssistId("unwrap_result_return_type", AssistKind::RefactorRewrite),
@@ -130,12 +134,16 @@ fn tail_cb_impl(acc: &mut Vec<ast::Expr>, e: &ast::Expr) {
 
 // Tries to extract `T` from `Result<T, E>`.
 fn unwrap_result_type(ty: &ast::Type) -> Option<ast::Type> {
-    let ast::Type::PathType(path_ty) = ty else { return None; };
+    let ast::Type::PathType(path_ty) = ty else {
+        return None;
+    };
     let path = path_ty.path()?;
     let segment = path.first_segment()?;
     let generic_arg_list = segment.generic_arg_list()?;
     let generic_args: Vec<_> = generic_arg_list.generic_args().collect();
-    let ast::GenericArg::TypeArg(ok_type) = generic_args.first()? else { return None; };
+    let ast::GenericArg::TypeArg(ok_type) = generic_args.first()? else {
+        return None;
+    };
     ok_type.ty()
 }
 
diff --git a/crates/ide-completion/src/context.rs b/crates/ide-completion/src/context.rs
index 7b145f3c14..3cb65b2729 100644
--- a/crates/ide-completion/src/context.rs
+++ b/crates/ide-completion/src/context.rs
@@ -463,7 +463,9 @@ impl CompletionContext<'_> {
 
     /// Checks whether this item should be listed in regards to stability. Returns `true` if we should.
     pub(crate) fn check_stability(&self, attrs: Option<&hir::Attrs>) -> bool {
-        let Some(attrs) = attrs else { return true; };
+        let Some(attrs) = attrs else {
+            return true;
+        };
         !attrs.is_unstable() || self.is_nightly
     }
 
diff --git a/crates/ide-completion/src/context/analysis.rs b/crates/ide-completion/src/context/analysis.rs
index cc5221cfcc..932233ad63 100644
--- a/crates/ide-completion/src/context/analysis.rs
+++ b/crates/ide-completion/src/context/analysis.rs
@@ -243,10 +243,7 @@ fn analyze(
 
     let Some(name_like) = find_node_at_offset(&speculative_file, offset) else {
         let analysis = if let Some(original) = ast::String::cast(original_token.clone()) {
-            CompletionAnalysis::String {
-                original,
-                expanded: ast::String::cast(self_token.clone()),
-            }
+            CompletionAnalysis::String { original, expanded: ast::String::cast(self_token.clone()) }
         } else {
             // Fix up trailing whitespace problem
             // #[attr(foo = $0
diff --git a/crates/ide-completion/src/lib.rs b/crates/ide-completion/src/lib.rs
index 2eaa42040a..106d4e1e52 100644
--- a/crates/ide-completion/src/lib.rs
+++ b/crates/ide-completion/src/lib.rs
@@ -231,7 +231,7 @@ pub fn resolve_completion_edits(
             &sema,
             current_crate,
             NameToImport::exact_case_sensitive(imported_name),
-            items_locator::AssocSearchMode::Include,
+            items_locator::AssocItemSearch::Include,
             Some(items_locator::DEFAULT_QUERY_SEARCH_LIMIT.inner()),
         );
         let import = items_with_name
diff --git a/crates/ide-db/src/imports/import_assets.rs b/crates/ide-db/src/imports/import_assets.rs
index e52dc35677..901d592c69 100644
--- a/crates/ide-db/src/imports/import_assets.rs
+++ b/crates/ide-db/src/imports/import_assets.rs
@@ -13,7 +13,7 @@ use syntax::{
 
 use crate::{
     helpers::item_name,
-    items_locator::{self, AssocSearchMode, DEFAULT_QUERY_SEARCH_LIMIT},
+    items_locator::{self, AssocItemSearch, DEFAULT_QUERY_SEARCH_LIMIT},
     RootDatabase,
 };
 
@@ -317,7 +317,7 @@ fn path_applicable_imports(
                 // * improve the associated completion item matching and/or scoring to ensure no noisy completions appear
                 //
                 // see also an ignored test under FIXME comment in the qualify_path.rs module
-                AssocSearchMode::Exclude,
+                AssocItemSearch::Exclude,
                 Some(DEFAULT_QUERY_SEARCH_LIMIT.inner()),
             )
             .filter_map(|item| {
@@ -334,7 +334,7 @@ fn path_applicable_imports(
                 sema,
                 current_crate,
                 path_candidate.name.clone(),
-                AssocSearchMode::Include,
+                AssocItemSearch::Include,
                 Some(DEFAULT_QUERY_SEARCH_LIMIT.inner()),
             )
             .filter_map(|item| {
@@ -483,7 +483,7 @@ fn trait_applicable_items(
         sema,
         current_crate,
         trait_candidate.assoc_item_name.clone(),
-        AssocSearchMode::AssocItemsOnly,
+        AssocItemSearch::AssocItemsOnly,
         Some(DEFAULT_QUERY_SEARCH_LIMIT.inner()),
     )
     .filter_map(|input| item_as_assoc(db, input))
diff --git a/crates/ide-db/src/items_locator.rs b/crates/ide-db/src/items_locator.rs
index 3f7a3ec2d0..46f1353e2e 100644
--- a/crates/ide-db/src/items_locator.rs
+++ b/crates/ide-db/src/items_locator.rs
@@ -3,7 +3,10 @@
 //! The main reason for this module to exist is the fact that project's items and dependencies' items
 //! are located in different caches, with different APIs.
 use either::Either;
-use hir::{import_map, AsAssocItem, Crate, ItemInNs, Semantics};
+use hir::{
+    import_map::{self, ImportKind},
+    AsAssocItem, Crate, ItemInNs, Semantics,
+};
 use limit::Limit;
 
 use crate::{imports::import_assets::NameToImport, symbol_index, RootDatabase};
@@ -11,14 +14,23 @@ use crate::{imports::import_assets::NameToImport, symbol_index, RootDatabase};
 /// A value to use, when uncertain which limit to pick.
 pub static DEFAULT_QUERY_SEARCH_LIMIT: Limit = Limit::new(40);
 
-pub use import_map::AssocSearchMode;
+/// Three possible ways to search for the name in associated and/or other items.
+#[derive(Debug, Clone, Copy)]
+pub enum AssocItemSearch {
+    /// Search for the name in both associated and other items.
+    Include,
+    /// Search for the name in other items only.
+    Exclude,
+    /// Search for the name in the associated items only.
+    AssocItemsOnly,
+}
 
 /// Searches for importable items with the given name in the crate and its dependencies.
 pub fn items_with_name<'a>(
     sema: &'a Semantics<'_, RootDatabase>,
     krate: Crate,
     name: NameToImport,
-    assoc_item_search: AssocSearchMode,
+    assoc_item_search: AssocItemSearch,
     limit: Option<usize>,
 ) -> impl Iterator<Item = ItemInNs> + 'a {
     let _p = profile::span("items_with_name").detail(|| {
@@ -36,7 +48,9 @@ pub fn items_with_name<'a>(
             let mut local_query = symbol_index::Query::new(exact_name.clone());
             local_query.exact();
 
-            let external_query = import_map::Query::new(exact_name);
+            let external_query = import_map::Query::new(exact_name)
+                .name_only()
+                .search_mode(import_map::SearchMode::Equals);
 
             (
                 local_query,
@@ -47,8 +61,17 @@ pub fn items_with_name<'a>(
             let mut local_query = symbol_index::Query::new(fuzzy_search_string.clone());
 
             let mut external_query = import_map::Query::new(fuzzy_search_string.clone())
-                .fuzzy()
-                .assoc_search_mode(assoc_item_search);
+                .search_mode(import_map::SearchMode::Fuzzy)
+                .name_only();
+            match assoc_item_search {
+                AssocItemSearch::Include => {}
+                AssocItemSearch::Exclude => {
+                    external_query = external_query.exclude_import_kind(ImportKind::AssociatedItem);
+                }
+                AssocItemSearch::AssocItemsOnly => {
+                    external_query = external_query.assoc_items_only();
+                }
+            }
 
             if fuzzy_search_string.to_lowercase() != fuzzy_search_string {
                 local_query.case_sensitive();
@@ -70,15 +93,13 @@ pub fn items_with_name<'a>(
 fn find_items<'a>(
     sema: &'a Semantics<'_, RootDatabase>,
     krate: Crate,
-    assoc_item_search: AssocSearchMode,
+    assoc_item_search: AssocItemSearch,
     local_query: symbol_index::Query,
     external_query: import_map::Query,
 ) -> impl Iterator<Item = ItemInNs> + 'a {
     let _p = profile::span("find_items");
     let db = sema.db;
 
-    // NOTE: `external_query` includes `assoc_item_search`, so we don't need to
-    // filter on our own.
     let external_importables =
         krate.query_external_importables(db, external_query).map(|external_importable| {
             match external_importable {
@@ -91,15 +112,18 @@ fn find_items<'a>(
     let local_results = local_query
         .search(&symbol_index::crate_symbols(db, krate))
         .into_iter()
-        .filter(move |candidate| match assoc_item_search {
-            AssocSearchMode::Include => true,
-            AssocSearchMode::Exclude => candidate.def.as_assoc_item(db).is_none(),
-            AssocSearchMode::AssocItemsOnly => candidate.def.as_assoc_item(db).is_some(),
-        })
-        .map(|local_candidate| match local_candidate.def {
-            hir::ModuleDef::Macro(macro_def) => ItemInNs::Macros(macro_def),
-            def => ItemInNs::from(def),
+        .filter_map(|local_candidate| match local_candidate.def {
+            hir::ModuleDef::Macro(macro_def) => Some(ItemInNs::Macros(macro_def)),
+            def => Some(ItemInNs::from(def)),
         });
 
-    external_importables.chain(local_results)
+    external_importables.chain(local_results).filter(move |&item| match assoc_item_search {
+        AssocItemSearch::Include => true,
+        AssocItemSearch::Exclude => !is_assoc_item(item, sema.db),
+        AssocItemSearch::AssocItemsOnly => is_assoc_item(item, sema.db),
+    })
+}
+
+fn is_assoc_item(item: ItemInNs, db: &RootDatabase) -> bool {
+    item.as_module_def().and_then(|module_def| module_def.as_assoc_item(db)).is_some()
 }
diff --git a/crates/ide-diagnostics/src/handlers/unlinked_file.rs b/crates/ide-diagnostics/src/handlers/unlinked_file.rs
index 271e7ce73b..7e0d953281 100644
--- a/crates/ide-diagnostics/src/handlers/unlinked_file.rs
+++ b/crates/ide-diagnostics/src/handlers/unlinked_file.rs
@@ -119,10 +119,11 @@ fn fixes(ctx: &DiagnosticsContext<'_>, file_id: FileId) -> Option<Vec<Assist>> {
     stack.pop();
     'crates: for &krate in ctx.sema.db.relevant_crates(parent_id).iter() {
         let crate_def_map = ctx.sema.db.crate_def_map(krate);
-        let Some((_, module)) =
-            crate_def_map.modules()
-            .find(|(_, module)| module.origin.file_id() == Some(parent_id) && !module.origin.is_inline())
-        else { continue };
+        let Some((_, module)) = crate_def_map.modules().find(|(_, module)| {
+            module.origin.file_id() == Some(parent_id) && !module.origin.is_inline()
+        }) else {
+            continue;
+        };
 
         if stack.is_empty() {
             return make_fixes(
diff --git a/crates/ide-diagnostics/src/lib.rs b/crates/ide-diagnostics/src/lib.rs
index 3d6cfddb3b..f883ea8d4f 100644
--- a/crates/ide-diagnostics/src/lib.rs
+++ b/crates/ide-diagnostics/src/lib.rs
@@ -155,8 +155,6 @@ impl Default for ExprFillDefaultMode {
 
 #[derive(Debug, Clone)]
 pub struct DiagnosticsConfig {
-    /// Whether native diagnostics are enabled.
-    pub enabled: bool,
     pub proc_macros_enabled: bool,
     pub proc_attr_macros_enabled: bool,
     pub disable_experimental: bool,
@@ -173,7 +171,6 @@ impl DiagnosticsConfig {
         use ide_db::imports::insert_use::ImportGranularity;
 
         Self {
-            enabled: true,
             proc_macros_enabled: Default::default(),
             proc_attr_macros_enabled: Default::default(),
             disable_experimental: Default::default(),
diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs
index 8112c4f725..c90ba21253 100644
--- a/crates/ide/src/doc_links.rs
+++ b/crates/ide/src/doc_links.rs
@@ -330,7 +330,9 @@ fn get_doc_links(
         base_url.and_then(|url| url.join(path).ok())
     };
 
-    let Some((target, file, frag)) = filename_and_frag_for_def(db, def) else { return Default::default(); };
+    let Some((target, file, frag)) = filename_and_frag_for_def(db, def) else {
+        return Default::default();
+    };
 
     let (mut web_url, mut local_url) = get_doc_base_urls(db, target, target_dir, sysroot);
 
diff --git a/crates/ide/src/inlay_hints/adjustment.rs b/crates/ide/src/inlay_hints/adjustment.rs
index 10bee2a6ac..6d6bd315eb 100644
--- a/crates/ide/src/inlay_hints/adjustment.rs
+++ b/crates/ide/src/inlay_hints/adjustment.rs
@@ -259,7 +259,7 @@ fn needs_parens_for_adjustment_hints(expr: &ast::Expr, postfix: bool) -> (bool,
         }
     })() else {
         never!("broken syntax tree?\n{:?}\n{:?}", expr, dummy_expr);
-        return (true, true)
+        return (true, true);
     };
 
     // At this point
diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs
index cb2a1140ba..f195f78b3a 100644
--- a/crates/ide/src/lib.rs
+++ b/crates/ide/src/lib.rs
@@ -642,7 +642,7 @@ impl Analysis {
         };
 
         self.with_db(|db| {
-            let diagnostic_assists = if diagnostics_config.enabled && include_fixes {
+            let diagnostic_assists = if include_fixes {
                 ide_diagnostics::diagnostics(db, diagnostics_config, &resolve, frange.file_id)
                     .into_iter()
                     .flat_map(|it| it.fixes.unwrap_or_default())
diff --git a/crates/rust-analyzer/src/cli/analysis_stats.rs b/crates/rust-analyzer/src/cli/analysis_stats.rs
index 7016bd0046..e2db1957ea 100644
--- a/crates/rust-analyzer/src/cli/analysis_stats.rs
+++ b/crates/rust-analyzer/src/cli/analysis_stats.rs
@@ -15,7 +15,7 @@ use hir_def::{
     hir::{ExprId, PatId},
 };
 use hir_ty::{Interner, Substitution, TyExt, TypeFlags};
-use ide::{Analysis, AnnotationConfig, DiagnosticsConfig, InlayHintsConfig, LineCol, RootDatabase};
+use ide::{LineCol, RootDatabase};
 use ide_db::{
     base_db::{
         salsa::{self, debug::DebugQueryTable, ParallelDatabase},
@@ -31,7 +31,7 @@ use project_model::{CargoConfig, ProjectManifest, ProjectWorkspace, RustLibSourc
 use rayon::prelude::*;
 use rustc_hash::FxHashSet;
 use syntax::{AstNode, SyntaxNode};
-use vfs::{AbsPathBuf, FileId, Vfs, VfsPath};
+use vfs::{AbsPathBuf, Vfs, VfsPath};
 
 use crate::cli::{
     flags::{self, OutputFormat},
@@ -148,10 +148,8 @@ impl flags::AnalysisStats {
         let mut bodies = Vec::new();
         let mut adts = Vec::new();
         let mut consts = Vec::new();
-        let mut file_ids = Vec::new();
         while let Some(module) = visit_queue.pop() {
             if visited_modules.insert(module) {
-                file_ids.extend(module.as_source_file_id(db));
                 visit_queue.extend(module.children(db));
 
                 for decl in module.declarations(db) {
@@ -225,10 +223,6 @@ impl flags::AnalysisStats {
             self.run_const_eval(db, &consts, verbosity);
         }
 
-        if self.run_all_ide_things {
-            self.run_ide_things(host.analysis(), file_ids);
-        }
-
         let total_span = analysis_sw.elapsed();
         eprintln!("{:<20} {total_span}", "Total:");
         report_metric("total time", total_span.time.as_millis() as u64, "ms");
@@ -274,10 +268,12 @@ impl flags::AnalysisStats {
                 continue;
             }
             all += 1;
-            let Err(e)
-                = db.layout_of_adt(hir_def::AdtId::from(a).into(), Substitution::empty(Interner), a.krate(db).into())
-            else {
-                continue
+            let Err(e) = db.layout_of_adt(
+                hir_def::AdtId::from(a).into(),
+                Substitution::empty(Interner),
+                a.krate(db).into(),
+            ) else {
+                continue;
             };
             if verbosity.is_spammy() {
                 let full_name = full_name_of_item(db, a.module(db), a.name(db));
@@ -734,83 +730,6 @@ impl flags::AnalysisStats {
         report_metric("body lowering time", body_lowering_time.time.as_millis() as u64, "ms");
     }
 
-    fn run_ide_things(&self, analysis: Analysis, mut file_ids: Vec<FileId>) {
-        file_ids.sort();
-        file_ids.dedup();
-        let mut sw = self.stop_watch();
-
-        for &file_id in &file_ids {
-            _ = analysis.diagnostics(
-                &DiagnosticsConfig {
-                    enabled: true,
-                    proc_macros_enabled: true,
-                    proc_attr_macros_enabled: true,
-                    disable_experimental: false,
-                    disabled: Default::default(),
-                    expr_fill_default: Default::default(),
-                    insert_use: ide_db::imports::insert_use::InsertUseConfig {
-                        granularity: ide_db::imports::insert_use::ImportGranularity::Crate,
-                        enforce_granularity: true,
-                        prefix_kind: hir::PrefixKind::ByCrate,
-                        group: true,
-                        skip_glob_imports: true,
-                    },
-                    prefer_no_std: Default::default(),
-                },
-                ide::AssistResolveStrategy::All,
-                file_id,
-            );
-        }
-        for &file_id in &file_ids {
-            _ = analysis.inlay_hints(
-                &InlayHintsConfig {
-                    render_colons: false,
-                    type_hints: true,
-                    discriminant_hints: ide::DiscriminantHints::Always,
-                    parameter_hints: true,
-                    chaining_hints: true,
-                    adjustment_hints: ide::AdjustmentHints::Always,
-                    adjustment_hints_mode: ide::AdjustmentHintsMode::Postfix,
-                    adjustment_hints_hide_outside_unsafe: false,
-                    closure_return_type_hints: ide::ClosureReturnTypeHints::Always,
-                    closure_capture_hints: true,
-                    binding_mode_hints: true,
-                    lifetime_elision_hints: ide::LifetimeElisionHints::Always,
-                    param_names_for_lifetime_elision_hints: true,
-                    hide_named_constructor_hints: false,
-                    hide_closure_initialization_hints: false,
-                    closure_style: hir::ClosureStyle::ImplFn,
-                    max_length: Some(25),
-                    closing_brace_hints_min_lines: Some(20),
-                },
-                file_id,
-                None,
-            );
-        }
-        for &file_id in &file_ids {
-            analysis
-                .annotations(
-                    &AnnotationConfig {
-                        binary_target: true,
-                        annotate_runnables: true,
-                        annotate_impls: true,
-                        annotate_references: false,
-                        annotate_method_references: false,
-                        annotate_enum_variant_references: false,
-                        location: ide::AnnotationLocation::AboveName,
-                    },
-                    file_id,
-                )
-                .unwrap()
-                .into_iter()
-                .for_each(|annotation| {
-                    _ = analysis.resolve_annotation(annotation);
-                });
-        }
-        let ide_time = sw.elapsed();
-        eprintln!("{:<20} {} ({} files)", "IDE:", ide_time, file_ids.len());
-    }
-
     fn stop_watch(&self) -> StopWatch {
         StopWatch::start().memory(self.memory_usage)
     }
diff --git a/crates/rust-analyzer/src/cli/flags.rs b/crates/rust-analyzer/src/cli/flags.rs
index 31be535fc2..9848739504 100644
--- a/crates/rust-analyzer/src/cli/flags.rs
+++ b/crates/rust-analyzer/src/cli/flags.rs
@@ -88,10 +88,6 @@ xflags::xflags! {
             optional --skip-data-layout
             /// Skip const evaluation
             optional --skip-const-eval
-            /// Runs several IDE features after analysis, including semantics highlighting, diagnostics
-            /// and annotations. This is useful for benchmarking the memory usage on a project that has
-            /// been worked on for a bit in a longer running session.
-            optional --run-all-ide-things
         }
 
         /// Run unit tests of the project using mir interpreter
@@ -203,7 +199,6 @@ pub struct AnalysisStats {
     pub skip_mir_stats: bool,
     pub skip_data_layout: bool,
     pub skip_const_eval: bool,
-    pub run_all_ide_things: bool,
 }
 
 #[derive(Debug)]
diff --git a/crates/rust-analyzer/src/config.rs b/crates/rust-analyzer/src/config.rs
index fa20c796ec..6355c620f7 100644
--- a/crates/rust-analyzer/src/config.rs
+++ b/crates/rust-analyzer/src/config.rs
@@ -1079,7 +1079,6 @@ impl Config {
 
     pub fn diagnostics(&self) -> DiagnosticsConfig {
         DiagnosticsConfig {
-            enabled: self.data.diagnostics_enable,
             proc_attr_macros_enabled: self.expand_proc_attr_macros(),
             proc_macros_enabled: self.data.procMacro_enable,
             disable_experimental: !self.data.diagnostics_experimental_enable,
diff --git a/crates/rust-analyzer/src/handlers/request.rs b/crates/rust-analyzer/src/handlers/request.rs
index 69799a54cb..bb0c7ffa72 100644
--- a/crates/rust-analyzer/src/handlers/request.rs
+++ b/crates/rust-analyzer/src/handlers/request.rs
@@ -1331,7 +1331,9 @@ pub(crate) fn handle_code_lens_resolve(
     snap: GlobalStateSnapshot,
     code_lens: CodeLens,
 ) -> anyhow::Result<CodeLens> {
-    let Some(annotation) = from_proto::annotation(&snap, code_lens.clone())? else { return Ok(code_lens) };
+    let Some(annotation) = from_proto::annotation(&snap, code_lens.clone())? else {
+        return Ok(code_lens);
+    };
     let annotation = snap.analysis.resolve_annotation(annotation)?;
 
     let mut acc = Vec::new();
@@ -1632,9 +1634,9 @@ pub(crate) fn handle_open_docs(
     let Ok(remote_urls) = snap.analysis.external_docs(position, target_dir, sysroot) else {
         return if snap.config.local_docs() {
             Ok(ExternalDocsResponse::WithLocal(Default::default()))
-            } else {
+        } else {
             Ok(ExternalDocsResponse::Simple(None))
-            }
+        };
     };
 
     let web = remote_urls.web_url.and_then(|it| Url::parse(&it).ok());
diff --git a/crates/rust-analyzer/src/reload.rs b/crates/rust-analyzer/src/reload.rs
index dd5517e697..18d9151d4a 100644
--- a/crates/rust-analyzer/src/reload.rs
+++ b/crates/rust-analyzer/src/reload.rs
@@ -334,7 +334,11 @@ impl GlobalState {
         let _p = profile::span("GlobalState::switch_workspaces");
         tracing::info!(%cause, "will switch workspaces");
 
-        let Some((workspaces, force_reload_crate_graph)) = self.fetch_workspaces_queue.last_op_result() else { return; };
+        let Some((workspaces, force_reload_crate_graph)) =
+            self.fetch_workspaces_queue.last_op_result()
+        else {
+            return;
+        };
 
         if let Err(_) = self.fetch_workspace_error() {
             if !self.workspaces.is_empty() {
@@ -525,7 +529,7 @@ impl GlobalState {
         let mut buf = String::new();
 
         let Some((last_op_result, _)) = self.fetch_workspaces_queue.last_op_result() else {
-            return Ok(())
+            return Ok(());
         };
         if last_op_result.is_empty() {
             stdx::format_to!(buf, "rust-analyzer failed to discover workspace");
diff --git a/crates/sourcegen/src/lib.rs b/crates/sourcegen/src/lib.rs
index c5da6ceb4d..1514c6c7d4 100644
--- a/crates/sourcegen/src/lib.rs
+++ b/crates/sourcegen/src/lib.rs
@@ -61,7 +61,9 @@ impl CommentBlock {
         let mut blocks = CommentBlock::extract_untagged(text);
         blocks.retain_mut(|block| {
             let first = block.contents.remove(0);
-            let Some(id) = first.strip_prefix(&tag) else { return false; };
+            let Some(id) = first.strip_prefix(&tag) else {
+                return false;
+            };
 
             if block.is_doc {
                 panic!("Use plain (non-doc) comments with tags like {tag}:\n    {first}");
diff --git a/lib/line-index/Cargo.toml b/lib/line-index/Cargo.toml
index 6c0d06f471..b267daa205 100644
--- a/lib/line-index/Cargo.toml
+++ b/lib/line-index/Cargo.toml
@@ -1,6 +1,6 @@
 [package]
 name = "line-index"
-version = "0.1.0"
+version = "0.1.0-pre.1"
 description = "Maps flat `TextSize` offsets to/from `(line, column)` representation."
 license = "MIT OR Apache-2.0"
 repository = "https://github.com/rust-lang/rust-analyzer/tree/master/lib/line-index"
diff --git a/lib/line-index/src/lib.rs b/lib/line-index/src/lib.rs
index 58db93a589..ad67d3f246 100644
--- a/lib/line-index/src/lib.rs
+++ b/lib/line-index/src/lib.rs
@@ -94,7 +94,44 @@ pub struct LineIndex {
 impl LineIndex {
     /// Returns a `LineIndex` for the `text`.
     pub fn new(text: &str) -> LineIndex {
-        let (newlines, line_wide_chars) = analyze_source_file(text);
+        let mut newlines = Vec::<TextSize>::with_capacity(16);
+        let mut line_wide_chars = IntMap::<u32, Box<[WideChar]>>::default();
+
+        let mut wide_chars = Vec::<WideChar>::new();
+        let mut cur_row = TextSize::from(0);
+        let mut cur_col = TextSize::from(0);
+        let mut line = 0u32;
+
+        for c in text.chars() {
+            let c_len = TextSize::of(c);
+            cur_row += c_len;
+            if c == '\n' {
+                newlines.push(cur_row);
+
+                // Save any wide characters seen in the previous line
+                if !wide_chars.is_empty() {
+                    let cs = std::mem::take(&mut wide_chars).into_boxed_slice();
+                    line_wide_chars.insert(line, cs);
+                }
+
+                // Prepare for processing the next line
+                cur_col = TextSize::from(0);
+                line += 1;
+                continue;
+            }
+
+            if !c.is_ascii() {
+                wide_chars.push(WideChar { start: cur_col, end: cur_col + c_len });
+            }
+
+            cur_col += c_len;
+        }
+
+        // Save any wide characters seen in the last line
+        if !wide_chars.is_empty() {
+            line_wide_chars.insert(line, wide_chars.into_boxed_slice());
+        }
+
         LineIndex {
             newlines: newlines.into_boxed_slice(),
             line_wide_chars,
@@ -198,182 +235,3 @@ impl LineIndex {
         self.len
     }
 }
-
-/// This is adapted from the rustc_span crate, https://github.com/rust-lang/rust/blob/master/compiler/rustc_span/src/analyze_source_file.rs
-fn analyze_source_file(src: &str) -> (Vec<TextSize>, IntMap<u32, Box<[WideChar]>>) {
-    assert!(src.len() < !0u32 as usize);
-    let mut lines = vec![];
-    let mut line_wide_chars = IntMap::<u32, Vec<WideChar>>::default();
-
-    // Calls the right implementation, depending on hardware support available.
-    analyze_source_file_dispatch(src, &mut lines, &mut line_wide_chars);
-
-    (lines, line_wide_chars.into_iter().map(|(k, v)| (k, v.into_boxed_slice())).collect())
-}
-
-#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
-fn analyze_source_file_dispatch(
-    src: &str,
-    lines: &mut Vec<TextSize>,
-    multi_byte_chars: &mut IntMap<u32, Vec<WideChar>>,
-) {
-    if is_x86_feature_detected!("sse2") {
-        // SAFETY: SSE2 support was checked
-        unsafe {
-            analyze_source_file_sse2(src, lines, multi_byte_chars);
-        }
-    } else {
-        analyze_source_file_generic(src, src.len(), TextSize::from(0), lines, multi_byte_chars);
-    }
-}
-
-/// Checks 16 byte chunks of text at a time. If the chunk contains
-/// something other than printable ASCII characters and newlines, the
-/// function falls back to the generic implementation. Otherwise it uses
-/// SSE2 intrinsics to quickly find all newlines.
-#[target_feature(enable = "sse2")]
-#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
-unsafe fn analyze_source_file_sse2(
-    src: &str,
-    lines: &mut Vec<TextSize>,
-    multi_byte_chars: &mut IntMap<u32, Vec<WideChar>>,
-) {
-    #[cfg(target_arch = "x86")]
-    use std::arch::x86::*;
-    #[cfg(target_arch = "x86_64")]
-    use std::arch::x86_64::*;
-
-    const CHUNK_SIZE: usize = 16;
-
-    let src_bytes = src.as_bytes();
-
-    let chunk_count = src.len() / CHUNK_SIZE;
-
-    // This variable keeps track of where we should start decoding a
-    // chunk. If a multi-byte character spans across chunk boundaries,
-    // we need to skip that part in the next chunk because we already
-    // handled it.
-    let mut intra_chunk_offset = 0;
-
-    for chunk_index in 0..chunk_count {
-        let ptr = src_bytes.as_ptr() as *const __m128i;
-        // We don't know if the pointer is aligned to 16 bytes, so we
-        // use `loadu`, which supports unaligned loading.
-        let chunk = _mm_loadu_si128(ptr.add(chunk_index));
-
-        // For character in the chunk, see if its byte value is < 0, which
-        // indicates that it's part of a UTF-8 char.
-        let multibyte_test = _mm_cmplt_epi8(chunk, _mm_set1_epi8(0));
-        // Create a bit mask from the comparison results.
-        let multibyte_mask = _mm_movemask_epi8(multibyte_test);
-
-        // If the bit mask is all zero, we only have ASCII chars here:
-        if multibyte_mask == 0 {
-            assert!(intra_chunk_offset == 0);
-
-            // Check for newlines in the chunk
-            let newlines_test = _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'\n' as i8));
-            let newlines_mask = _mm_movemask_epi8(newlines_test);
-
-            if newlines_mask != 0 {
-                // All control characters are newlines, record them
-                let mut newlines_mask = 0xFFFF0000 | newlines_mask as u32;
-                let output_offset = TextSize::from((chunk_index * CHUNK_SIZE + 1) as u32);
-
-                loop {
-                    let index = newlines_mask.trailing_zeros();
-
-                    if index >= CHUNK_SIZE as u32 {
-                        // We have arrived at the end of the chunk.
-                        break;
-                    }
-
-                    lines.push(TextSize::from(index) + output_offset);
-
-                    // Clear the bit, so we can find the next one.
-                    newlines_mask &= (!1) << index;
-                }
-            }
-            continue;
-        }
-
-        // The slow path.
-        // There are control chars in here, fallback to generic decoding.
-        let scan_start = chunk_index * CHUNK_SIZE + intra_chunk_offset;
-        intra_chunk_offset = analyze_source_file_generic(
-            &src[scan_start..],
-            CHUNK_SIZE - intra_chunk_offset,
-            TextSize::from(scan_start as u32),
-            lines,
-            multi_byte_chars,
-        );
-    }
-
-    // There might still be a tail left to analyze
-    let tail_start = chunk_count * CHUNK_SIZE + intra_chunk_offset;
-    if tail_start < src.len() {
-        analyze_source_file_generic(
-            &src[tail_start..],
-            src.len() - tail_start,
-            TextSize::from(tail_start as u32),
-            lines,
-            multi_byte_chars,
-        );
-    }
-}
-
-#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
-// The target (or compiler version) does not support SSE2 ...
-fn analyze_source_file_dispatch(
-    src: &str,
-    lines: &mut Vec<TextSize>,
-    multi_byte_chars: &mut IntMap<u32, Vec<WideChar>>,
-) {
-    analyze_source_file_generic(src, src.len(), TextSize::from(0), lines, multi_byte_chars);
-}
-
-// `scan_len` determines the number of bytes in `src` to scan. Note that the
-// function can read past `scan_len` if a multi-byte character start within the
-// range but extends past it. The overflow is returned by the function.
-fn analyze_source_file_generic(
-    src: &str,
-    scan_len: usize,
-    output_offset: TextSize,
-    lines: &mut Vec<TextSize>,
-    multi_byte_chars: &mut IntMap<u32, Vec<WideChar>>,
-) -> usize {
-    assert!(src.len() >= scan_len);
-    let mut i = 0;
-    let src_bytes = src.as_bytes();
-
-    while i < scan_len {
-        let byte = unsafe {
-            // We verified that i < scan_len <= src.len()
-            *src_bytes.get_unchecked(i)
-        };
-
-        // How much to advance in order to get to the next UTF-8 char in the
-        // string.
-        let mut char_len = 1;
-
-        if byte == b'\n' {
-            lines.push(TextSize::from(i as u32 + 1) + output_offset);
-        } else if byte >= 127 {
-            // The slow path: Just decode to `char`.
-            let c = src[i..].chars().next().unwrap();
-            char_len = c.len_utf8();
-
-            let pos = TextSize::from(i as u32) + output_offset;
-
-            if char_len > 1 {
-                assert!((2..=4).contains(&char_len));
-                let mbc = WideChar { start: pos, end: pos + TextSize::from(char_len as u32) };
-                multi_byte_chars.entry(lines.len() as u32).or_default().push(mbc);
-            }
-        }
-
-        i += char_len;
-    }
-
-    i - scan_len
-}


Test patch:
diff --git a/crates/hir-ty/src/tests.rs b/crates/hir-ty/src/tests.rs
index 8e5514353d..d22d0d85c8 100644
--- a/crates/hir-ty/src/tests.rs
+++ b/crates/hir-ty/src/tests.rs
@@ -206,7 +206,9 @@ fn check_impl(ra_fixture: &str, allow_none: bool, only_types: bool, display_sour
             let Some(node) = (match expr_or_pat {
                 hir_def::hir::ExprOrPatId::ExprId(expr) => expr_node(&body_source_map, expr, &db),
                 hir_def::hir::ExprOrPatId::PatId(pat) => pat_node(&body_source_map, pat, &db),
-            }) else { continue; };
+            }) else {
+                continue;
+            };
             let range = node.as_ref().original_file_range(&db);
             let actual = format!(
                 "expected {}, got {}",
diff --git a/crates/hir-ty/src/tests/method_resolution.rs b/crates/hir-ty/src/tests/method_resolution.rs
index a8e146b096..1e57a4ae29 100644
--- a/crates/hir-ty/src/tests/method_resolution.rs
+++ b/crates/hir-ty/src/tests/method_resolution.rs
@@ -1215,52 +1215,6 @@ fn main() {
     );
 }
 
-#[test]
-fn inherent_method_deref_raw() {
-    check_types(
-        r#"
-struct Val;
-
-impl Val {
-    pub fn method(self: *const Val) -> u32 {
-        0
-    }
-}
-
-fn main() {
-    let foo: *const Val;
-    foo.method();
- // ^^^^^^^^^^^^ u32
-}
-"#,
-    );
-}
-
-#[test]
-fn trait_method_deref_raw() {
-    check_types(
-        r#"
-trait Trait {
-    fn method(self: *const Self) -> u32;
-}
-
-struct Val;
-
-impl Trait for Val {
-    fn method(self: *const Self) -> u32 {
-        0
-    }
-}
-
-fn main() {
-    let foo: *const Val;
-    foo.method();
- // ^^^^^^^^^^^^ u32
-}
-"#,
-    );
-}
-
 #[test]
 fn method_on_dyn_impl() {
     check_types(
diff --git a/lib/line-index/src/tests.rs b/lib/line-index/src/tests.rs
index 8f3762d191..31c01c20ee 100644
--- a/lib/line-index/src/tests.rs
+++ b/lib/line-index/src/tests.rs
@@ -1,120 +1,11 @@
-use crate::{LineIndex, TextSize, WideChar};
-
-macro_rules! test {
-    (
-        case: $test_name:ident,
-     text: $text:expr,
-     lines: $lines:expr,
-     multi_byte_chars: $multi_byte_chars:expr,
-    ) => {
-        #[test]
-        fn $test_name() {
-            let line_index = LineIndex::new($text);
-
-            let expected_lines: Vec<TextSize> =
-                $lines.into_iter().map(<TextSize as From<u32>>::from).collect();
-
-            assert_eq!(&*line_index.newlines, &*expected_lines);
-
-            let expected_mbcs: Vec<_> = $multi_byte_chars
-                .into_iter()
-                .map(|(line, (pos, end)): (u32, (u32, u32))| {
-                    (line, WideChar { start: TextSize::from(pos), end: TextSize::from(end) })
-                })
-                .collect();
-
-            assert_eq!(
-                line_index
-                    .line_wide_chars
-                    .iter()
-                    .flat_map(|(line, val)| std::iter::repeat(*line).zip(val.iter().copied()))
-                    .collect::<Vec<_>>(),
-                expected_mbcs
-            );
-        }
-    };
+use super::LineIndex;
+
+#[test]
+fn test_empty_index() {
+    let col_index = LineIndex::new(
+        "
+const C: char = 'x';
+",
+    );
+    assert_eq!(col_index.line_wide_chars.len(), 0);
 }
-
-test!(
-    case: empty_text,
-    text: "",
-    lines: vec![],
-    multi_byte_chars: vec![],
-);
-
-test!(
-    case: newlines_short,
-    text: "a\nc",
-    lines: vec![2],
-    multi_byte_chars: vec![],
-);
-
-test!(
-    case: newlines_long,
-    text: "012345678\nabcdef012345678\na",
-    lines: vec![10, 26],
-    multi_byte_chars: vec![],
-);
-
-test!(
-    case: newline_and_multi_byte_char_in_same_chunk,
-    text: "01234β789\nbcdef0123456789abcdef",
-    lines: vec![11],
-    multi_byte_chars: vec![(0, (5, 7))],
-);
-
-test!(
-    case: newline_and_control_char_in_same_chunk,
-    text: "01234\u{07}6789\nbcdef0123456789abcdef",
-    lines: vec![11],
-    multi_byte_chars: vec![],
-);
-
-test!(
-    case: multi_byte_char_short,
-    text: "aβc",
-    lines: vec![],
-    multi_byte_chars: vec![(0, (1, 3))],
-);
-
-test!(
-    case: multi_byte_char_long,
-    text: "0123456789abcΔf012345β",
-    lines: vec![],
-    multi_byte_chars: vec![(0, (13, 15)), (0, (22, 24))],
-);
-
-test!(
-    case: multi_byte_char_across_chunk_boundary,
-    text: "0123456789abcdeΔ123456789abcdef01234",
-    lines: vec![],
-    multi_byte_chars: vec![(0, (15, 17))],
-);
-
-test!(
-    case: multi_byte_char_across_chunk_boundary_tail,
-    text: "0123456789abcdeΔ....",
-    lines: vec![],
-    multi_byte_chars: vec![(0, (15, 17))],
-);
-
-test!(
-    case: multi_byte_with_new_lines,
-    text: "01\t345\n789abcΔf01234567\u{07}9\nbcΔf",
-    lines: vec![7, 27],
-    multi_byte_chars: vec![(1, (13, 15)), (2, (29, 31))],
-);
-
-test!(
-    case: trailing_newline,
-    text: "0123456789\n",
-    lines: vec![11],
-    multi_byte_chars: vec![],
-);
-
-test!(
-    case: trailing_newline_chunk_boundary,
-    text: "0123456789abcde\n",
-    lines: vec![16],
-    multi_byte_chars: vec![],
-);
diff --git a/lib/line-index/tests/it.rs b/lib/line-index/tests/it.rs
new file mode 100644
index 0000000000..ce1c0bc6f1
--- /dev/null
+++ b/lib/line-index/tests/it.rs
@@ -0,0 +1,62 @@
+use line_index::{LineCol, LineIndex, TextRange};
+
+#[test]
+fn test_line_index() {
+    let text = "hello\nworld";
+    let table = [
+        (00, 0, 0),
+        (01, 0, 1),
+        (05, 0, 5),
+        (06, 1, 0),
+        (07, 1, 1),
+        (08, 1, 2),
+        (10, 1, 4),
+        (11, 1, 5),
+    ];
+
+    let index = LineIndex::new(text);
+    for (offset, line, col) in table {
+        assert_eq!(index.line_col(offset.into()), LineCol { line, col });
+    }
+
+    let text = "\nhello\nworld";
+    let table = [(0, 0, 0), (1, 1, 0), (2, 1, 1), (6, 1, 5), (7, 2, 0)];
+    let index = LineIndex::new(text);
+    for (offset, line, col) in table {
+        assert_eq!(index.line_col(offset.into()), LineCol { line, col });
+    }
+}
+
+#[test]
+fn test_char_len() {
+    assert_eq!('メ'.len_utf8(), 3);
+    assert_eq!('メ'.len_utf16(), 1);
+}
+
+#[test]
+fn test_splitlines() {
+    fn r(lo: u32, hi: u32) -> TextRange {
+        TextRange::new(lo.into(), hi.into())
+    }
+
+    let text = "a\nbb\nccc\n";
+    let line_index = LineIndex::new(text);
+
+    let actual = line_index.lines(r(0, 9)).collect::<Vec<_>>();
+    let expected = vec![r(0, 2), r(2, 5), r(5, 9)];
+    assert_eq!(actual, expected);
+
+    let text = "";
+    let line_index = LineIndex::new(text);
+
+    let actual = line_index.lines(r(0, 0)).collect::<Vec<_>>();
+    let expected = vec![];
+    assert_eq!(actual, expected);
+
+    let text = "\n";
+    let line_index = LineIndex::new(text);
+
+    let actual = line_index.lines(r(0, 1)).collect::<Vec<_>>();
+    let expected = vec![r(0, 1)];
+    assert_eq!(actual, expected)
+}