about summary refs log tree commit diff
path: root/src/tools/rust-analyzer/crates/hir
diff options
context:
space:
mode:
authorroife <roifewu@gmail.com>2024-04-06 13:57:56 +0800
committerroife <roifewu@gmail.com>2024-04-16 16:26:23 +0800
commit3a4a69a51047d13be50439907c5c9f989d366264 (patch)
treec570a2c272fc21f3f98428deee3ba50011242983 /src/tools/rust-analyzer/crates/hir
parent1179c3ee83eb72508049c78d06c06057c21885a3 (diff)
downloadrust-3a4a69a51047d13be50439907c5c9f989d366264.tar.gz
rust-3a4a69a51047d13be50439907c5c9f989d366264.zip
Add config hover_show_adtFieldsOrVariants to handle hovering limitation for ADTs
Diffstat (limited to 'src/tools/rust-analyzer/crates/hir')
-rw-r--r--src/tools/rust-analyzer/crates/hir/Cargo.toml39
-rw-r--r--src/tools/rust-analyzer/crates/hir/src/attrs.rs337
-rw-r--r--src/tools/rust-analyzer/crates/hir/src/db.rs27
-rw-r--r--src/tools/rust-analyzer/crates/hir/src/diagnostics.rs628
-rw-r--r--src/tools/rust-analyzer/crates/hir/src/display.rs765
-rw-r--r--src/tools/rust-analyzer/crates/hir/src/from_id.rs300
-rw-r--r--src/tools/rust-analyzer/crates/hir/src/has_source.rs231
-rw-r--r--src/tools/rust-analyzer/crates/hir/src/lib.rs5328
-rw-r--r--src/tools/rust-analyzer/crates/hir/src/semantics.rs1749
-rw-r--r--src/tools/rust-analyzer/crates/hir/src/semantics/source_to_def.rs506
-rw-r--r--src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs1283
-rw-r--r--src/tools/rust-analyzer/crates/hir/src/symbols.rs352
-rw-r--r--src/tools/rust-analyzer/crates/hir/src/term_search.rs323
-rw-r--r--src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs483
-rw-r--r--src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs932
15 files changed, 13283 insertions, 0 deletions
diff --git a/src/tools/rust-analyzer/crates/hir/Cargo.toml b/src/tools/rust-analyzer/crates/hir/Cargo.toml
new file mode 100644
index 00000000000..190722075a2
--- /dev/null
+++ b/src/tools/rust-analyzer/crates/hir/Cargo.toml
@@ -0,0 +1,39 @@
+[package]
+name = "hir"
+version = "0.0.0"
+description = "TBD"
+
+authors.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lib]
+doctest = false
+
+[dependencies]
+rustc-hash.workspace = true
+either.workspace = true
+arrayvec.workspace = true
+itertools.workspace = true
+smallvec.workspace = true
+tracing.workspace = true
+triomphe.workspace = true
+once_cell = "1.17.1"
+
+# local deps
+base-db.workspace = true
+cfg.workspace = true
+hir-def.workspace = true
+hir-expand.workspace = true
+hir-ty.workspace = true
+stdx.workspace = true
+syntax.workspace = true
+tt.workspace = true
+span.workspace = true
+
+[features]
+in-rust-tree = []
+
+[lints]
+workspace = true
diff --git a/src/tools/rust-analyzer/crates/hir/src/attrs.rs b/src/tools/rust-analyzer/crates/hir/src/attrs.rs
new file mode 100644
index 00000000000..c7502890ef4
--- /dev/null
+++ b/src/tools/rust-analyzer/crates/hir/src/attrs.rs
@@ -0,0 +1,337 @@
+//! Attributes & documentation for hir types.
+
+use std::ops::ControlFlow;
+
+use hir_def::{
+    attr::AttrsWithOwner,
+    item_scope::ItemInNs,
+    path::{ModPath, Path},
+    per_ns::Namespace,
+    resolver::{HasResolver, Resolver, TypeNs},
+    AssocItemId, AttrDefId, ModuleDefId,
+};
+use hir_expand::{mod_path::PathKind, name::Name};
+use hir_ty::{db::HirDatabase, method_resolution};
+
+use crate::{
+    Adt, AsAssocItem, AssocItem, BuiltinType, Const, ConstParam, DocLinkDef, Enum, ExternCrateDecl,
+    Field, Function, GenericParam, HasCrate, Impl, LifetimeParam, Macro, Module, ModuleDef, Static,
+    Struct, Trait, TraitAlias, Type, TypeAlias, TypeParam, Union, Variant, VariantDef,
+};
+
+pub trait HasAttrs {
+    fn attrs(self, db: &dyn HirDatabase) -> AttrsWithOwner;
+    #[doc(hidden)]
+    fn attr_id(self) -> AttrDefId;
+}
+
+macro_rules! impl_has_attrs {
+    ($(($def:ident, $def_id:ident),)*) => {$(
+        impl HasAttrs for $def {
+            fn attrs(self, db: &dyn HirDatabase) -> AttrsWithOwner {
+                let def = AttrDefId::$def_id(self.into());
+                AttrsWithOwner::new(db.upcast(), def)
+            }
+            fn attr_id(self) -> AttrDefId {
+                AttrDefId::$def_id(self.into())
+            }
+        }
+    )*};
+}
+
+impl_has_attrs![
+    (Field, FieldId),
+    (Variant, EnumVariantId),
+    (Static, StaticId),
+    (Const, ConstId),
+    (Trait, TraitId),
+    (TraitAlias, TraitAliasId),
+    (TypeAlias, TypeAliasId),
+    (Macro, MacroId),
+    (Function, FunctionId),
+    (Adt, AdtId),
+    (Module, ModuleId),
+    (GenericParam, GenericParamId),
+    (Impl, ImplId),
+    (ExternCrateDecl, ExternCrateId),
+];
+
+macro_rules! impl_has_attrs_enum {
+    ($($variant:ident),* for $enum:ident) => {$(
+        impl HasAttrs for $variant {
+            fn attrs(self, db: &dyn HirDatabase) -> AttrsWithOwner {
+                $enum::$variant(self).attrs(db)
+            }
+            fn attr_id(self) -> AttrDefId {
+                $enum::$variant(self).attr_id()
+            }
+        }
+    )*};
+}
+
+impl_has_attrs_enum![Struct, Union, Enum for Adt];
+impl_has_attrs_enum![TypeParam, ConstParam, LifetimeParam for GenericParam];
+
+impl HasAttrs for AssocItem {
+    fn attrs(self, db: &dyn HirDatabase) -> AttrsWithOwner {
+        match self {
+            AssocItem::Function(it) => it.attrs(db),
+            AssocItem::Const(it) => it.attrs(db),
+            AssocItem::TypeAlias(it) => it.attrs(db),
+        }
+    }
+    fn attr_id(self) -> AttrDefId {
+        match self {
+            AssocItem::Function(it) => it.attr_id(),
+            AssocItem::Const(it) => it.attr_id(),
+            AssocItem::TypeAlias(it) => it.attr_id(),
+        }
+    }
+}
+
+/// Resolves the item `link` points to in the scope of `def`.
+pub fn resolve_doc_path_on(
+    db: &dyn HirDatabase,
+    def: impl HasAttrs,
+    link: &str,
+    ns: Option<Namespace>,
+) -> Option<DocLinkDef> {
+    resolve_doc_path_on_(db, link, def.attr_id(), ns)
+}
+
+fn resolve_doc_path_on_(
+    db: &dyn HirDatabase,
+    link: &str,
+    attr_id: AttrDefId,
+    ns: Option<Namespace>,
+) -> Option<DocLinkDef> {
+    let resolver = match attr_id {
+        AttrDefId::ModuleId(it) => it.resolver(db.upcast()),
+        AttrDefId::FieldId(it) => it.parent.resolver(db.upcast()),
+        AttrDefId::AdtId(it) => it.resolver(db.upcast()),
+        AttrDefId::FunctionId(it) => it.resolver(db.upcast()),
+        AttrDefId::EnumVariantId(it) => it.resolver(db.upcast()),
+        AttrDefId::StaticId(it) => it.resolver(db.upcast()),
+        AttrDefId::ConstId(it) => it.resolver(db.upcast()),
+        AttrDefId::TraitId(it) => it.resolver(db.upcast()),
+        AttrDefId::TraitAliasId(it) => it.resolver(db.upcast()),
+        AttrDefId::TypeAliasId(it) => it.resolver(db.upcast()),
+        AttrDefId::ImplId(it) => it.resolver(db.upcast()),
+        AttrDefId::ExternBlockId(it) => it.resolver(db.upcast()),
+        AttrDefId::UseId(it) => it.resolver(db.upcast()),
+        AttrDefId::MacroId(it) => it.resolver(db.upcast()),
+        AttrDefId::ExternCrateId(it) => it.resolver(db.upcast()),
+        AttrDefId::GenericParamId(_) => return None,
+    };
+
+    let mut modpath = doc_modpath_from_str(link)?;
+
+    let resolved = resolver.resolve_module_path_in_items(db.upcast(), &modpath);
+    if resolved.is_none() {
+        let last_name = modpath.pop_segment()?;
+        resolve_assoc_or_field(db, resolver, modpath, last_name, ns)
+    } else {
+        let def = match ns {
+            Some(Namespace::Types) => resolved.take_types(),
+            Some(Namespace::Values) => resolved.take_values(),
+            Some(Namespace::Macros) => resolved.take_macros().map(ModuleDefId::MacroId),
+            None => resolved.iter_items().next().map(|(it, _)| match it {
+                ItemInNs::Types(it) => it,
+                ItemInNs::Values(it) => it,
+                ItemInNs::Macros(it) => ModuleDefId::MacroId(it),
+            }),
+        };
+        Some(DocLinkDef::ModuleDef(def?.into()))
+    }
+}
+
+fn resolve_assoc_or_field(
+    db: &dyn HirDatabase,
+    resolver: Resolver,
+    path: ModPath,
+    name: Name,
+    ns: Option<Namespace>,
+) -> Option<DocLinkDef> {
+    let path = Path::from_known_path_with_no_generic(path);
+    // FIXME: This does not handle `Self` on trait definitions, which we should resolve to the
+    // trait itself.
+    let base_def = resolver.resolve_path_in_type_ns_fully(db.upcast(), &path)?;
+
+    let ty = match base_def {
+        TypeNs::SelfType(id) => Impl::from(id).self_ty(db),
+        TypeNs::GenericParam(_) => {
+            // Even if this generic parameter has some trait bounds, rustdoc doesn't
+            // resolve `name` to trait items.
+            return None;
+        }
+        TypeNs::AdtId(id) | TypeNs::AdtSelfType(id) => Adt::from(id).ty(db),
+        TypeNs::EnumVariantId(id) => {
+            // Enum variants don't have path candidates.
+            let variant = Variant::from(id);
+            return resolve_field(db, variant.into(), name, ns);
+        }
+        TypeNs::TypeAliasId(id) => {
+            let alias = TypeAlias::from(id);
+            if alias.as_assoc_item(db).is_some() {
+                // We don't normalize associated type aliases, so we have nothing to
+                // resolve `name` to.
+                return None;
+            }
+            alias.ty(db)
+        }
+        TypeNs::BuiltinType(id) => BuiltinType::from(id).ty(db),
+        TypeNs::TraitId(id) => {
+            // Doc paths in this context may only resolve to an item of this trait
+            // (i.e. no items of its supertraits), so we need to handle them here
+            // independently of others.
+            return db.trait_data(id).items.iter().find(|it| it.0 == name).map(|(_, assoc_id)| {
+                let def = match *assoc_id {
+                    AssocItemId::FunctionId(it) => ModuleDef::Function(it.into()),
+                    AssocItemId::ConstId(it) => ModuleDef::Const(it.into()),
+                    AssocItemId::TypeAliasId(it) => ModuleDef::TypeAlias(it.into()),
+                };
+                DocLinkDef::ModuleDef(def)
+            });
+        }
+        TypeNs::TraitAliasId(_) => {
+            // XXX: Do these get resolved?
+            return None;
+        }
+    };
+
+    // Resolve inherent items first, then trait items, then fields.
+    if let Some(assoc_item_def) = resolve_assoc_item(db, &ty, &name, ns) {
+        return Some(assoc_item_def);
+    }
+
+    if let Some(impl_trait_item_def) = resolve_impl_trait_item(db, resolver, &ty, &name, ns) {
+        return Some(impl_trait_item_def);
+    }
+
+    let variant_def = match ty.as_adt()? {
+        Adt::Struct(it) => it.into(),
+        Adt::Union(it) => it.into(),
+        Adt::Enum(_) => return None,
+    };
+    resolve_field(db, variant_def, name, ns)
+}
+
+fn resolve_assoc_item(
+    db: &dyn HirDatabase,
+    ty: &Type,
+    name: &Name,
+    ns: Option<Namespace>,
+) -> Option<DocLinkDef> {
+    ty.iterate_assoc_items(db, ty.krate(db), move |assoc_item| {
+        if assoc_item.name(db)? != *name {
+            return None;
+        }
+        as_module_def_if_namespace_matches(assoc_item, ns)
+    })
+}
+
+fn resolve_impl_trait_item(
+    db: &dyn HirDatabase,
+    resolver: Resolver,
+    ty: &Type,
+    name: &Name,
+    ns: Option<Namespace>,
+) -> Option<DocLinkDef> {
+    let canonical = ty.canonical();
+    let krate = ty.krate(db);
+    let environment = resolver
+        .generic_def()
+        .map_or_else(|| crate::TraitEnvironment::empty(krate.id), |d| db.trait_environment(d));
+    let traits_in_scope = resolver.traits_in_scope(db.upcast());
+
+    let mut result = None;
+
+    // `ty.iterate_path_candidates()` require a scope, which is not available when resolving
+    // attributes here. Use path resolution directly instead.
+    //
+    // FIXME: resolve type aliases (which are not yielded by iterate_path_candidates)
+    method_resolution::iterate_path_candidates(
+        &canonical,
+        db,
+        environment,
+        &traits_in_scope,
+        method_resolution::VisibleFromModule::None,
+        Some(name),
+        &mut |assoc_item_id| {
+            // If two traits in scope define the same item, Rustdoc links to no specific trait (for
+            // instance, given two methods `a`, Rustdoc simply links to `method.a` with no
+            // disambiguation) so we just pick the first one we find as well.
+            result = as_module_def_if_namespace_matches(assoc_item_id.into(), ns);
+
+            if result.is_some() {
+                ControlFlow::Break(())
+            } else {
+                ControlFlow::Continue(())
+            }
+        },
+    );
+
+    result
+}
+
+fn resolve_field(
+    db: &dyn HirDatabase,
+    def: VariantDef,
+    name: Name,
+    ns: Option<Namespace>,
+) -> Option<DocLinkDef> {
+    if let Some(Namespace::Types | Namespace::Macros) = ns {
+        return None;
+    }
+    def.fields(db).into_iter().find(|f| f.name(db) == name).map(DocLinkDef::Field)
+}
+
+fn as_module_def_if_namespace_matches(
+    assoc_item: AssocItem,
+    ns: Option<Namespace>,
+) -> Option<DocLinkDef> {
+    let (def, expected_ns) = match assoc_item {
+        AssocItem::Function(it) => (ModuleDef::Function(it), Namespace::Values),
+        AssocItem::Const(it) => (ModuleDef::Const(it), Namespace::Values),
+        AssocItem::TypeAlias(it) => (ModuleDef::TypeAlias(it), Namespace::Types),
+    };
+
+    (ns.unwrap_or(expected_ns) == expected_ns).then_some(DocLinkDef::ModuleDef(def))
+}
+
+fn doc_modpath_from_str(link: &str) -> Option<ModPath> {
+    // FIXME: this is not how we should get a mod path here.
+    let try_get_modpath = |link: &str| {
+        let mut parts = link.split("::");
+        let mut first_segment = None;
+        let kind = match parts.next()? {
+            "" => PathKind::Abs,
+            "crate" => PathKind::Crate,
+            "self" => PathKind::Super(0),
+            "super" => {
+                let mut deg = 1;
+                for segment in parts.by_ref() {
+                    if segment == "super" {
+                        deg += 1;
+                    } else {
+                        first_segment = Some(segment);
+                        break;
+                    }
+                }
+                PathKind::Super(deg)
+            }
+            segment => {
+                first_segment = Some(segment);
+                PathKind::Plain
+            }
+        };
+        let parts = first_segment.into_iter().chain(parts).map(|segment| match segment.parse() {
+            Ok(idx) => Name::new_tuple_field(idx),
+            Err(_) => {
+                Name::new_text_dont_use(segment.split_once('<').map_or(segment, |it| it.0).into())
+            }
+        });
+        Some(ModPath::from_segments(kind, parts))
+    };
+    try_get_modpath(link)
+}
diff --git a/src/tools/rust-analyzer/crates/hir/src/db.rs b/src/tools/rust-analyzer/crates/hir/src/db.rs
new file mode 100644
index 00000000000..1d74f9a4bb2
--- /dev/null
+++ b/src/tools/rust-analyzer/crates/hir/src/db.rs
@@ -0,0 +1,27 @@
+//! Re-exports various subcrates databases so that the calling code can depend
+//! only on `hir`. This breaks abstraction boundary a bit, it would be cool if
+//! we didn't do that.
+//!
+//! But we need this for at least LRU caching at the query level.
+pub use hir_def::db::{
+    AttrsQuery, BlockDefMapQuery, BodyQuery, BodyWithSourceMapQuery, ConstDataQuery,
+    ConstVisibilityQuery, CrateLangItemsQuery, CrateSupportsNoStdQuery, DefDatabase,
+    DefDatabaseStorage, EnumDataQuery, EnumVariantDataWithDiagnosticsQuery, ExprScopesQuery,
+    ExternCrateDeclDataQuery, FieldVisibilitiesQuery, FieldsAttrsQuery, FieldsAttrsSourceMapQuery,
+    FileItemTreeQuery, FunctionDataQuery, FunctionVisibilityQuery, GenericParamsQuery,
+    ImplDataWithDiagnosticsQuery, ImportMapQuery, InternAnonymousConstQuery, InternBlockQuery,
+    InternConstQuery, InternDatabase, InternDatabaseStorage, InternEnumQuery,
+    InternExternBlockQuery, InternExternCrateQuery, InternFunctionQuery, InternImplQuery,
+    InternInTypeConstQuery, InternMacro2Query, InternMacroRulesQuery, InternProcMacroQuery,
+    InternStaticQuery, InternStructQuery, InternTraitAliasQuery, InternTraitQuery,
+    InternTypeAliasQuery, InternUnionQuery, InternUseQuery, LangItemQuery, Macro2DataQuery,
+    MacroRulesDataQuery, ProcMacroDataQuery, StaticDataQuery, StructDataWithDiagnosticsQuery,
+    TraitAliasDataQuery, TraitDataWithDiagnosticsQuery, TypeAliasDataQuery,
+    UnionDataWithDiagnosticsQuery,
+};
+pub use hir_expand::db::{
+    AstIdMapQuery, DeclMacroExpanderQuery, ExpandDatabase, ExpandDatabaseStorage,
+    ExpandProcMacroQuery, InternMacroCallQuery, InternSyntaxContextQuery, MacroArgQuery,
+    ParseMacroExpansionErrorQuery, ParseMacroExpansionQuery, ProcMacrosQuery, RealSpanMapQuery,
+};
+pub use hir_ty::db::*;
diff --git a/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs b/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs
new file mode 100644
index 00000000000..4518422d27e
--- /dev/null
+++ b/src/tools/rust-analyzer/crates/hir/src/diagnostics.rs
@@ -0,0 +1,628 @@
+//! Re-export diagnostics such that clients of `hir` don't have to depend on
+//! low-level crates.
+//!
+//! This probably isn't the best way to do this -- ideally, diagnostics should
+//! be expressed in terms of hir types themselves.
+pub use hir_ty::diagnostics::{CaseType, IncorrectCase};
+use hir_ty::{db::HirDatabase, diagnostics::BodyValidationDiagnostic, InferenceDiagnostic};
+
+use base_db::CrateId;
+use cfg::{CfgExpr, CfgOptions};
+use either::Either;
+use hir_def::{body::SyntheticSyntax, hir::ExprOrPatId, path::ModPath, AssocItemId, DefWithBodyId};
+use hir_expand::{name::Name, HirFileId, InFile};
+use syntax::{ast, AstPtr, SyntaxError, SyntaxNodePtr, TextRange};
+
+use crate::{AssocItem, Field, Local, MacroKind, Trait, Type};
+
+macro_rules! diagnostics {
+    ($($diag:ident,)*) => {
+        #[derive(Debug)]
+        pub enum AnyDiagnostic {$(
+            $diag(Box<$diag>),
+        )*}
+
+        $(
+            impl From<$diag> for AnyDiagnostic {
+                fn from(d: $diag) -> AnyDiagnostic {
+                    AnyDiagnostic::$diag(Box::new(d))
+                }
+            }
+        )*
+    };
+}
+// FIXME Accept something like the following in the macro call instead
+// diagnostics![
+// pub struct BreakOutsideOfLoop {
+//     pub expr: InFile<AstPtr<ast::Expr>>,
+//     pub is_break: bool,
+//     pub bad_value_break: bool,
+// }, ...
+// or more concisely
+// BreakOutsideOfLoop {
+//     expr: InFile<AstPtr<ast::Expr>>,
+//     is_break: bool,
+//     bad_value_break: bool,
+// }, ...
+// ]
+
+diagnostics![
+    BreakOutsideOfLoop,
+    ExpectedFunction,
+    InactiveCode,
+    IncoherentImpl,
+    IncorrectCase,
+    InvalidDeriveTarget,
+    MacroDefError,
+    MacroError,
+    MacroExpansionParseError,
+    MalformedDerive,
+    MismatchedArgCount,
+    MismatchedTupleStructPatArgCount,
+    MissingFields,
+    MissingMatchArms,
+    MissingUnsafe,
+    MovedOutOfRef,
+    NeedMut,
+    NonExhaustiveLet,
+    NoSuchField,
+    PrivateAssocItem,
+    PrivateField,
+    RemoveTrailingReturn,
+    RemoveUnnecessaryElse,
+    ReplaceFilterMapNextWithFindMap,
+    TraitImplIncorrectSafety,
+    TraitImplMissingAssocItems,
+    TraitImplOrphan,
+    TraitImplRedundantAssocItems,
+    TypedHole,
+    TypeMismatch,
+    UndeclaredLabel,
+    UnimplementedBuiltinMacro,
+    UnreachableLabel,
+    UnresolvedAssocItem,
+    UnresolvedExternCrate,
+    UnresolvedField,
+    UnresolvedImport,
+    UnresolvedMacroCall,
+    UnresolvedMethodCall,
+    UnresolvedModule,
+    UnresolvedIdent,
+    UnresolvedProcMacro,
+    UnusedMut,
+    UnusedVariable,
+];
+
+#[derive(Debug)]
+pub struct BreakOutsideOfLoop {
+    pub expr: InFile<AstPtr<ast::Expr>>,
+    pub is_break: bool,
+    pub bad_value_break: bool,
+}
+
+#[derive(Debug)]
+pub struct TypedHole {
+    pub expr: InFile<AstPtr<ast::Expr>>,
+    pub expected: Type,
+}
+
+#[derive(Debug)]
+pub struct UnresolvedModule {
+    pub decl: InFile<AstPtr<ast::Module>>,
+    pub candidates: Box<[String]>,
+}
+
+#[derive(Debug)]
+pub struct UnresolvedExternCrate {
+    pub decl: InFile<AstPtr<ast::ExternCrate>>,
+}
+
+#[derive(Debug)]
+pub struct UnresolvedImport {
+    pub decl: InFile<AstPtr<ast::UseTree>>,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq)]
+pub struct UnresolvedMacroCall {
+    pub macro_call: InFile<SyntaxNodePtr>,
+    pub precise_location: Option<TextRange>,
+    pub path: ModPath,
+    pub is_bang: bool,
+}
+#[derive(Debug, Clone, Eq, PartialEq)]
+pub struct UnreachableLabel {
+    pub node: InFile<AstPtr<ast::Lifetime>>,
+    pub name: Name,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq)]
+pub struct UndeclaredLabel {
+    pub node: InFile<AstPtr<ast::Lifetime>>,
+    pub name: Name,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq)]
+pub struct InactiveCode {
+    pub node: InFile<SyntaxNodePtr>,
+    pub cfg: CfgExpr,
+    pub opts: CfgOptions,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq)]
+pub struct UnresolvedProcMacro {
+    pub node: InFile<SyntaxNodePtr>,
+    /// If the diagnostic can be pinpointed more accurately than via `node`, this is the `TextRange`
+    /// to use instead.
+    pub precise_location: Option<TextRange>,
+    pub macro_name: Option<String>,
+    pub kind: MacroKind,
+    /// The crate id of the proc-macro this macro belongs to, or `None` if the proc-macro can't be found.
+    pub krate: CrateId,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq)]
+pub struct MacroError {
+    pub node: InFile<SyntaxNodePtr>,
+    pub precise_location: Option<TextRange>,
+    pub message: String,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq)]
+pub struct MacroExpansionParseError {
+    pub node: InFile<SyntaxNodePtr>,
+    pub precise_location: Option<TextRange>,
+    pub errors: Box<[SyntaxError]>,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq)]
+pub struct MacroDefError {
+    pub node: InFile<AstPtr<ast::Macro>>,
+    pub message: String,
+    pub name: Option<TextRange>,
+}
+
+#[derive(Debug)]
+pub struct UnimplementedBuiltinMacro {
+    pub node: InFile<SyntaxNodePtr>,
+}
+
+#[derive(Debug)]
+pub struct InvalidDeriveTarget {
+    pub node: InFile<SyntaxNodePtr>,
+}
+
+#[derive(Debug)]
+pub struct MalformedDerive {
+    pub node: InFile<SyntaxNodePtr>,
+}
+
+#[derive(Debug)]
+pub struct NoSuchField {
+    pub field: InFile<AstPtr<Either<ast::RecordExprField, ast::RecordPatField>>>,
+    pub private: bool,
+}
+
+#[derive(Debug)]
+pub struct PrivateAssocItem {
+    pub expr_or_pat: InFile<AstPtr<Either<ast::Expr, ast::Pat>>>,
+    pub item: AssocItem,
+}
+
+#[derive(Debug)]
+pub struct MismatchedTupleStructPatArgCount {
+    pub expr_or_pat: InFile<AstPtr<Either<ast::Expr, ast::Pat>>>,
+    pub expected: usize,
+    pub found: usize,
+}
+
+#[derive(Debug)]
+pub struct ExpectedFunction {
+    pub call: InFile<AstPtr<ast::Expr>>,
+    pub found: Type,
+}
+
+#[derive(Debug)]
+pub struct UnresolvedField {
+    pub expr: InFile<AstPtr<ast::Expr>>,
+    pub receiver: Type,
+    pub name: Name,
+    pub method_with_same_name_exists: bool,
+}
+
+#[derive(Debug)]
+pub struct UnresolvedMethodCall {
+    pub expr: InFile<AstPtr<ast::Expr>>,
+    pub receiver: Type,
+    pub name: Name,
+    pub field_with_same_name: Option<Type>,
+    pub assoc_func_with_same_name: Option<AssocItemId>,
+}
+
+#[derive(Debug)]
+pub struct UnresolvedAssocItem {
+    pub expr_or_pat: InFile<AstPtr<Either<ast::Expr, ast::Pat>>>,
+}
+
+#[derive(Debug)]
+pub struct UnresolvedIdent {
+    pub expr: InFile<AstPtr<ast::Expr>>,
+}
+
+#[derive(Debug)]
+pub struct PrivateField {
+    pub expr: InFile<AstPtr<ast::Expr>>,
+    pub field: Field,
+}
+
+#[derive(Debug)]
+pub struct MissingUnsafe {
+    pub expr: InFile<AstPtr<ast::Expr>>,
+}
+
+#[derive(Debug)]
+pub struct MissingFields {
+    pub file: HirFileId,
+    pub field_list_parent: AstPtr<Either<ast::RecordExpr, ast::RecordPat>>,
+    pub field_list_parent_path: Option<AstPtr<ast::Path>>,
+    pub missed_fields: Vec<Name>,
+}
+
+#[derive(Debug)]
+pub struct ReplaceFilterMapNextWithFindMap {
+    pub file: HirFileId,
+    /// This expression is the whole method chain up to and including `.filter_map(..).next()`.
+    pub next_expr: AstPtr<ast::Expr>,
+}
+
+#[derive(Debug)]
+pub struct MismatchedArgCount {
+    pub call_expr: InFile<AstPtr<ast::Expr>>,
+    pub expected: usize,
+    pub found: usize,
+}
+
+#[derive(Debug)]
+pub struct MissingMatchArms {
+    pub scrutinee_expr: InFile<AstPtr<ast::Expr>>,
+    pub uncovered_patterns: String,
+}
+
+#[derive(Debug)]
+pub struct NonExhaustiveLet {
+    pub pat: InFile<AstPtr<ast::Pat>>,
+    pub uncovered_patterns: String,
+}
+
+#[derive(Debug)]
+pub struct TypeMismatch {
+    pub expr_or_pat: InFile<AstPtr<Either<ast::Expr, ast::Pat>>>,
+    pub expected: Type,
+    pub actual: Type,
+}
+
+#[derive(Debug)]
+pub struct NeedMut {
+    pub local: Local,
+    pub span: InFile<SyntaxNodePtr>,
+}
+
+#[derive(Debug)]
+pub struct UnusedMut {
+    pub local: Local,
+}
+
+#[derive(Debug)]
+pub struct UnusedVariable {
+    pub local: Local,
+}
+
+#[derive(Debug)]
+pub struct MovedOutOfRef {
+    pub ty: Type,
+    pub span: InFile<SyntaxNodePtr>,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct IncoherentImpl {
+    pub file_id: HirFileId,
+    pub impl_: AstPtr<ast::Impl>,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct TraitImplOrphan {
+    pub file_id: HirFileId,
+    pub impl_: AstPtr<ast::Impl>,
+}
+
+// FIXME: Split this off into the corresponding 4 rustc errors
+#[derive(Debug, PartialEq, Eq)]
+pub struct TraitImplIncorrectSafety {
+    pub file_id: HirFileId,
+    pub impl_: AstPtr<ast::Impl>,
+    pub should_be_safe: bool,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct TraitImplMissingAssocItems {
+    pub file_id: HirFileId,
+    pub impl_: AstPtr<ast::Impl>,
+    pub missing: Vec<(Name, AssocItem)>,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct TraitImplRedundantAssocItems {
+    pub file_id: HirFileId,
+    pub trait_: Trait,
+    pub impl_: AstPtr<ast::Impl>,
+    pub assoc_item: (Name, AssocItem),
+}
+
+#[derive(Debug)]
+pub struct RemoveTrailingReturn {
+    pub return_expr: InFile<AstPtr<ast::ReturnExpr>>,
+}
+
+#[derive(Debug)]
+pub struct RemoveUnnecessaryElse {
+    pub if_expr: InFile<AstPtr<ast::IfExpr>>,
+}
+
+impl AnyDiagnostic {
+    pub(crate) fn body_validation_diagnostic(
+        db: &dyn HirDatabase,
+        diagnostic: BodyValidationDiagnostic,
+        source_map: &hir_def::body::BodySourceMap,
+    ) -> Option<AnyDiagnostic> {
+        match diagnostic {
+            BodyValidationDiagnostic::RecordMissingFields { record, variant, missed_fields } => {
+                let variant_data = variant.variant_data(db.upcast());
+                let missed_fields = missed_fields
+                    .into_iter()
+                    .map(|idx| variant_data.fields()[idx].name.clone())
+                    .collect();
+
+                match record {
+                    Either::Left(record_expr) => match source_map.expr_syntax(record_expr) {
+                        Ok(source_ptr) => {
+                            let root = source_ptr.file_syntax(db.upcast());
+                            if let ast::Expr::RecordExpr(record_expr) =
+                                source_ptr.value.to_node(&root)
+                            {
+                                if record_expr.record_expr_field_list().is_some() {
+                                    let field_list_parent_path =
+                                        record_expr.path().map(|path| AstPtr::new(&path));
+                                    return Some(
+                                        MissingFields {
+                                            file: source_ptr.file_id,
+                                            field_list_parent: AstPtr::new(&Either::Left(
+                                                record_expr,
+                                            )),
+                                            field_list_parent_path,
+                                            missed_fields,
+                                        }
+                                        .into(),
+                                    );
+                                }
+                            }
+                        }
+                        Err(SyntheticSyntax) => (),
+                    },
+                    Either::Right(record_pat) => match source_map.pat_syntax(record_pat) {
+                        Ok(source_ptr) => {
+                            if let Some(ptr) = source_ptr.value.cast::<ast::RecordPat>() {
+                                let root = source_ptr.file_syntax(db.upcast());
+                                let record_pat = ptr.to_node(&root);
+                                if record_pat.record_pat_field_list().is_some() {
+                                    let field_list_parent_path =
+                                        record_pat.path().map(|path| AstPtr::new(&path));
+                                    return Some(
+                                        MissingFields {
+                                            file: source_ptr.file_id,
+                                            field_list_parent: AstPtr::new(&Either::Right(
+                                                record_pat,
+                                            )),
+                                            field_list_parent_path,
+                                            missed_fields,
+                                        }
+                                        .into(),
+                                    );
+                                }
+                            }
+                        }
+                        Err(SyntheticSyntax) => (),
+                    },
+                }
+            }
+            BodyValidationDiagnostic::ReplaceFilterMapNextWithFindMap { method_call_expr } => {
+                if let Ok(next_source_ptr) = source_map.expr_syntax(method_call_expr) {
+                    return Some(
+                        ReplaceFilterMapNextWithFindMap {
+                            file: next_source_ptr.file_id,
+                            next_expr: next_source_ptr.value,
+                        }
+                        .into(),
+                    );
+                }
+            }
+            BodyValidationDiagnostic::MissingMatchArms { match_expr, uncovered_patterns } => {
+                match source_map.expr_syntax(match_expr) {
+                    Ok(source_ptr) => {
+                        let root = source_ptr.file_syntax(db.upcast());
+                        if let ast::Expr::MatchExpr(match_expr) = &source_ptr.value.to_node(&root) {
+                            match match_expr.expr() {
+                                Some(scrut_expr) if match_expr.match_arm_list().is_some() => {
+                                    return Some(
+                                        MissingMatchArms {
+                                            scrutinee_expr: InFile::new(
+                                                source_ptr.file_id,
+                                                AstPtr::new(&scrut_expr),
+                                            ),
+                                            uncovered_patterns,
+                                        }
+                                        .into(),
+                                    );
+                                }
+                                _ => {}
+                            }
+                        }
+                    }
+                    Err(SyntheticSyntax) => (),
+                }
+            }
+            BodyValidationDiagnostic::NonExhaustiveLet { pat, uncovered_patterns } => {
+                match source_map.pat_syntax(pat) {
+                    Ok(source_ptr) => {
+                        if let Some(ast_pat) = source_ptr.value.cast::<ast::Pat>() {
+                            return Some(
+                                NonExhaustiveLet {
+                                    pat: InFile::new(source_ptr.file_id, ast_pat),
+                                    uncovered_patterns,
+                                }
+                                .into(),
+                            );
+                        }
+                    }
+                    Err(SyntheticSyntax) => {}
+                }
+            }
+            BodyValidationDiagnostic::RemoveTrailingReturn { return_expr } => {
+                if let Ok(source_ptr) = source_map.expr_syntax(return_expr) {
+                    // Filters out desugared return expressions (e.g. desugared try operators).
+                    if let Some(ptr) = source_ptr.value.cast::<ast::ReturnExpr>() {
+                        return Some(
+                            RemoveTrailingReturn {
+                                return_expr: InFile::new(source_ptr.file_id, ptr),
+                            }
+                            .into(),
+                        );
+                    }
+                }
+            }
+            BodyValidationDiagnostic::RemoveUnnecessaryElse { if_expr } => {
+                if let Ok(source_ptr) = source_map.expr_syntax(if_expr) {
+                    if let Some(ptr) = source_ptr.value.cast::<ast::IfExpr>() {
+                        return Some(
+                            RemoveUnnecessaryElse { if_expr: InFile::new(source_ptr.file_id, ptr) }
+                                .into(),
+                        );
+                    }
+                }
+            }
+        }
+        None
+    }
+
+    pub(crate) fn inference_diagnostic(
+        db: &dyn HirDatabase,
+        def: DefWithBodyId,
+        d: &InferenceDiagnostic,
+        source_map: &hir_def::body::BodySourceMap,
+    ) -> Option<AnyDiagnostic> {
+        let expr_syntax = |expr| {
+            source_map.expr_syntax(expr).inspect_err(|_| tracing::error!("synthetic syntax")).ok()
+        };
+        let pat_syntax = |pat| {
+            source_map.pat_syntax(pat).inspect_err(|_| tracing::error!("synthetic syntax")).ok()
+        };
+        Some(match d {
+            &InferenceDiagnostic::NoSuchField { field: expr, private } => {
+                let expr_or_pat = match expr {
+                    ExprOrPatId::ExprId(expr) => {
+                        source_map.field_syntax(expr).map(AstPtr::wrap_left)
+                    }
+                    ExprOrPatId::PatId(pat) => {
+                        source_map.pat_field_syntax(pat).map(AstPtr::wrap_right)
+                    }
+                };
+                NoSuchField { field: expr_or_pat, private }.into()
+            }
+            &InferenceDiagnostic::MismatchedArgCount { call_expr, expected, found } => {
+                MismatchedArgCount { call_expr: expr_syntax(call_expr)?, expected, found }.into()
+            }
+            &InferenceDiagnostic::PrivateField { expr, field } => {
+                let expr = expr_syntax(expr)?;
+                let field = field.into();
+                PrivateField { expr, field }.into()
+            }
+            &InferenceDiagnostic::PrivateAssocItem { id, item } => {
+                let expr_or_pat = match id {
+                    ExprOrPatId::ExprId(expr) => expr_syntax(expr)?.map(AstPtr::wrap_left),
+                    ExprOrPatId::PatId(pat) => pat_syntax(pat)?.map(AstPtr::wrap_right),
+                };
+                let item = item.into();
+                PrivateAssocItem { expr_or_pat, item }.into()
+            }
+            InferenceDiagnostic::ExpectedFunction { call_expr, found } => {
+                let call_expr = expr_syntax(*call_expr)?;
+                ExpectedFunction { call: call_expr, found: Type::new(db, def, found.clone()) }
+                    .into()
+            }
+            InferenceDiagnostic::UnresolvedField {
+                expr,
+                receiver,
+                name,
+                method_with_same_name_exists,
+            } => {
+                let expr = expr_syntax(*expr)?;
+                UnresolvedField {
+                    expr,
+                    name: name.clone(),
+                    receiver: Type::new(db, def, receiver.clone()),
+                    method_with_same_name_exists: *method_with_same_name_exists,
+                }
+                .into()
+            }
+            InferenceDiagnostic::UnresolvedMethodCall {
+                expr,
+                receiver,
+                name,
+                field_with_same_name,
+                assoc_func_with_same_name,
+            } => {
+                let expr = expr_syntax(*expr)?;
+                UnresolvedMethodCall {
+                    expr,
+                    name: name.clone(),
+                    receiver: Type::new(db, def, receiver.clone()),
+                    field_with_same_name: field_with_same_name
+                        .clone()
+                        .map(|ty| Type::new(db, def, ty)),
+                    assoc_func_with_same_name: *assoc_func_with_same_name,
+                }
+                .into()
+            }
+            &InferenceDiagnostic::UnresolvedAssocItem { id } => {
+                let expr_or_pat = match id {
+                    ExprOrPatId::ExprId(expr) => expr_syntax(expr)?.map(AstPtr::wrap_left),
+                    ExprOrPatId::PatId(pat) => pat_syntax(pat)?.map(AstPtr::wrap_right),
+                };
+                UnresolvedAssocItem { expr_or_pat }.into()
+            }
+            &InferenceDiagnostic::UnresolvedIdent { expr } => {
+                let expr = expr_syntax(expr)?;
+                UnresolvedIdent { expr }.into()
+            }
+            &InferenceDiagnostic::BreakOutsideOfLoop { expr, is_break, bad_value_break } => {
+                let expr = expr_syntax(expr)?;
+                BreakOutsideOfLoop { expr, is_break, bad_value_break }.into()
+            }
+            InferenceDiagnostic::TypedHole { expr, expected } => {
+                let expr = expr_syntax(*expr)?;
+                TypedHole { expr, expected: Type::new(db, def, expected.clone()) }.into()
+            }
+            &InferenceDiagnostic::MismatchedTupleStructPatArgCount { pat, expected, found } => {
+                let expr_or_pat = match pat {
+                    ExprOrPatId::ExprId(expr) => expr_syntax(expr)?.map(AstPtr::wrap_left),
+                    ExprOrPatId::PatId(pat) => {
+                        let InFile { file_id, value } = pat_syntax(pat)?;
+
+                        // cast from Either<Pat, SelfParam> -> Either<_, Pat>
+                        let ptr = AstPtr::try_from_raw(value.syntax_node_ptr())?;
+                        InFile { file_id, value: ptr }
+                    }
+                };
+                MismatchedTupleStructPatArgCount { expr_or_pat, expected, found }.into()
+            }
+        })
+    }
+}
diff --git a/src/tools/rust-analyzer/crates/hir/src/display.rs b/src/tools/rust-analyzer/crates/hir/src/display.rs
new file mode 100644
index 00000000000..b0468ea0809
--- /dev/null
+++ b/src/tools/rust-analyzer/crates/hir/src/display.rs
@@ -0,0 +1,765 @@
+//! HirDisplay implementations for various hir types.
+use either::Either;
+use hir_def::{
+    data::adt::{StructKind, VariantData},
+    generics::{
+        TypeOrConstParamData, TypeParamProvenance, WherePredicate, WherePredicateTypeTarget,
+    },
+    lang_item::LangItem,
+    type_ref::{TypeBound, TypeRef},
+    AdtId, GenericDefId,
+};
+use hir_ty::{
+    display::{
+        write_bounds_like_dyn_trait_with_prefix, write_visibility, HirDisplay, HirDisplayError,
+        HirFormatter, SizedByDefault,
+    },
+    AliasEq, AliasTy, Interner, ProjectionTyExt, TraitRefExt, TyKind, WhereClause,
+};
+
+use crate::{
+    Adt, AsAssocItem, AssocItem, AssocItemContainer, Const, ConstParam, Enum, ExternCrateDecl,
+    Field, Function, GenericParam, HasCrate, HasVisibility, LifetimeParam, Macro, Module,
+    SelfParam, Static, Struct, Trait, TraitAlias, TupleField, TyBuilder, Type, TypeAlias,
+    TypeOrConstParam, TypeParam, Union, Variant,
+};
+
+impl HirDisplay for Function {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        let db = f.db;
+        let data = db.function_data(self.id);
+        let container = self.as_assoc_item(db).map(|it| it.container(db));
+        let mut module = self.module(db);
+        if let Some(AssocItemContainer::Impl(_)) = container {
+            // Block-local impls are "hoisted" to the nearest (non-block) module.
+            module = module.nearest_non_block_module(db);
+        }
+        let module_id = module.id;
+        write_visibility(module_id, self.visibility(db), f)?;
+        if data.has_default_kw() {
+            f.write_str("default ")?;
+        }
+        if data.has_const_kw() {
+            f.write_str("const ")?;
+        }
+        if data.has_async_kw() {
+            f.write_str("async ")?;
+        }
+        if self.is_unsafe_to_call(db) {
+            f.write_str("unsafe ")?;
+        }
+        if let Some(abi) = &data.abi {
+            // FIXME: String escape?
+            write!(f, "extern \"{}\" ", &**abi)?;
+        }
+        write!(f, "fn {}", data.name.display(f.db.upcast()))?;
+
+        write_generic_params(GenericDefId::FunctionId(self.id), f)?;
+
+        f.write_char('(')?;
+
+        let mut first = true;
+        let mut skip_self = 0;
+        if let Some(self_param) = self.self_param(db) {
+            self_param.hir_fmt(f)?;
+            first = false;
+            skip_self = 1;
+        }
+
+        // FIXME: Use resolved `param.ty` once we no longer discard lifetimes
+        for (type_ref, param) in data.params.iter().zip(self.assoc_fn_params(db)).skip(skip_self) {
+            let local = param.as_local(db).map(|it| it.name(db));
+            if !first {
+                f.write_str(", ")?;
+            } else {
+                first = false;
+            }
+            match local {
+                Some(name) => write!(f, "{}: ", name.display(f.db.upcast()))?,
+                None => f.write_str("_: ")?,
+            }
+            type_ref.hir_fmt(f)?;
+        }
+
+        if data.is_varargs() {
+            f.write_str(", ...")?;
+        }
+
+        f.write_char(')')?;
+
+        // `FunctionData::ret_type` will be `::core::future::Future<Output = ...>` for async fns.
+        // Use ugly pattern match to strip the Future trait.
+        // Better way?
+        let ret_type = if !data.has_async_kw() {
+            &data.ret_type
+        } else {
+            match &*data.ret_type {
+                TypeRef::ImplTrait(bounds) => match bounds[0].as_ref() {
+                    TypeBound::Path(path, _) => {
+                        path.segments().iter().last().unwrap().args_and_bindings.unwrap().bindings
+                            [0]
+                        .type_ref
+                        .as_ref()
+                        .unwrap()
+                    }
+                    _ => panic!("Async fn ret_type should be impl Future"),
+                },
+                _ => panic!("Async fn ret_type should be impl Future"),
+            }
+        };
+
+        match ret_type {
+            TypeRef::Tuple(tup) if tup.is_empty() => {}
+            ty => {
+                f.write_str(" -> ")?;
+                ty.hir_fmt(f)?;
+            }
+        }
+
+        write_where_clause(GenericDefId::FunctionId(self.id), f)?;
+
+        Ok(())
+    }
+}
+
+impl HirDisplay for SelfParam {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        let data = f.db.function_data(self.func);
+        let param = data.params.first().unwrap();
+        match &**param {
+            TypeRef::Path(p) if p.is_self_type() => f.write_str("self"),
+            TypeRef::Reference(inner, lifetime, mut_) if matches!(&**inner, TypeRef::Path(p) if p.is_self_type()) =>
+            {
+                f.write_char('&')?;
+                if let Some(lifetime) = lifetime {
+                    write!(f, "{} ", lifetime.name.display(f.db.upcast()))?;
+                }
+                if let hir_def::type_ref::Mutability::Mut = mut_ {
+                    f.write_str("mut ")?;
+                }
+                f.write_str("self")
+            }
+            ty => {
+                f.write_str("self: ")?;
+                ty.hir_fmt(f)
+            }
+        }
+    }
+}
+
+impl HirDisplay for Adt {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        match self {
+            Adt::Struct(it) => it.hir_fmt(f),
+            Adt::Union(it) => it.hir_fmt(f),
+            Adt::Enum(it) => it.hir_fmt(f),
+        }
+    }
+}
+
+impl HirDisplay for Struct {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        let module_id = self.module(f.db).id;
+        // FIXME: Render repr if its set explicitly?
+        write_visibility(module_id, self.visibility(f.db), f)?;
+        f.write_str("struct ")?;
+        write!(f, "{}", self.name(f.db).display(f.db.upcast()))?;
+        let def_id = GenericDefId::AdtId(AdtId::StructId(self.id));
+        write_generic_params(def_id, f)?;
+
+        let variant_data = self.variant_data(f.db);
+        match variant_data.kind() {
+            StructKind::Tuple => {
+                f.write_char('(')?;
+                let mut it = variant_data.fields().iter().peekable();
+
+                while let Some((id, _)) = it.next() {
+                    let field = Field { parent: (*self).into(), id };
+                    write_visibility(module_id, field.visibility(f.db), f)?;
+                    field.ty(f.db).hir_fmt(f)?;
+                    if it.peek().is_some() {
+                        f.write_str(", ")?;
+                    }
+                }
+
+                f.write_char(')')?;
+                write_where_clause(def_id, f)?;
+            }
+            StructKind::Record => {
+                let has_where_clause = write_where_clause(def_id, f)?;
+                if let Some(limit) = f.entity_limit {
+                    display_fields_or_variants(
+                        &self.fields(f.db),
+                        has_where_clause,
+                        limit,
+                        f,
+                    )?;
+                }
+            }
+            StructKind::Unit => _ = write_where_clause(def_id, f)?,
+        }
+
+        Ok(())
+    }
+}
+
+impl HirDisplay for Enum {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        write_visibility(self.module(f.db).id, self.visibility(f.db), f)?;
+        f.write_str("enum ")?;
+        write!(f, "{}", self.name(f.db).display(f.db.upcast()))?;
+        let def_id = GenericDefId::AdtId(AdtId::EnumId(self.id));
+        write_generic_params(def_id, f)?;
+
+        let has_where_clause = write_where_clause(def_id, f)?;
+        if let Some(limit) = f.entity_limit {
+            display_fields_or_variants(
+                &self.variants(f.db),
+                has_where_clause,
+                limit,
+                f,
+            )?;
+        }
+
+        Ok(())
+    }
+}
+
+impl HirDisplay for Union {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        write_visibility(self.module(f.db).id, self.visibility(f.db), f)?;
+        f.write_str("union ")?;
+        write!(f, "{}", self.name(f.db).display(f.db.upcast()))?;
+        let def_id = GenericDefId::AdtId(AdtId::UnionId(self.id));
+        write_generic_params(def_id, f)?;
+
+        let has_where_clause = write_where_clause(def_id, f)?;
+        if let Some(limit) = f.entity_limit {
+            display_fields_or_variants(
+                &self.fields(f.db),
+                has_where_clause,
+                limit,
+                f,
+            )?;
+        }
+        Ok(())
+    }
+}
+
+fn display_fields_or_variants<T: HirDisplay>(
+    fields_or_variants: &[T],
+    has_where_clause: bool,
+    limit: usize,
+    f: &mut HirFormatter<'_>,
+)-> Result<(), HirDisplayError> {
+    let count = fields_or_variants.len().min(limit);
+    f.write_char(if !has_where_clause { ' ' } else { '\n' })?;
+    if count == 0 {
+        if fields_or_variants.is_empty() {
+            f.write_str("{}")?;
+        } else {
+            f.write_str("{ /* … */ }")?;
+        }
+    } else {
+        f.write_str("{\n")?;
+        for field in &fields_or_variants[..count] {
+            f.write_str("    ")?;
+            field.hir_fmt(f)?;
+            f.write_str(",\n")?;
+        }
+
+        if fields_or_variants.len() > count {
+            f.write_str("    /* … */\n")?;
+        }
+        f.write_str("}")?;
+    }
+
+    Ok(())
+}
+
+impl HirDisplay for Field {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        write_visibility(self.parent.module(f.db).id, self.visibility(f.db), f)?;
+        write!(f, "{}: ", self.name(f.db).display(f.db.upcast()))?;
+        self.ty(f.db).hir_fmt(f)
+    }
+}
+
+impl HirDisplay for TupleField {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        write!(f, "pub {}: ", self.name().display(f.db.upcast()))?;
+        self.ty(f.db).hir_fmt(f)
+    }
+}
+
+impl HirDisplay for Variant {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        write!(f, "{}", self.name(f.db).display(f.db.upcast()))?;
+        let data = self.variant_data(f.db);
+        match &*data {
+            VariantData::Unit => {}
+            VariantData::Tuple(fields) => {
+                f.write_char('(')?;
+                let mut first = true;
+                for (_, field) in fields.iter() {
+                    if first {
+                        first = false;
+                    } else {
+                        f.write_str(", ")?;
+                    }
+                    // Enum variant fields must be pub.
+                    field.type_ref.hir_fmt(f)?;
+                }
+                f.write_char(')')?;
+            }
+            VariantData::Record(fields) => {
+                f.write_str(" {")?;
+                let mut first = true;
+                for (_, field) in fields.iter() {
+                    if first {
+                        first = false;
+                        f.write_char(' ')?;
+                    } else {
+                        f.write_str(", ")?;
+                    }
+                    // Enum variant fields must be pub.
+                    write!(f, "{}: ", field.name.display(f.db.upcast()))?;
+                    field.type_ref.hir_fmt(f)?;
+                }
+                f.write_str(" }")?;
+            }
+        }
+        Ok(())
+    }
+}
+
+impl HirDisplay for Type {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        self.ty.hir_fmt(f)
+    }
+}
+
+impl HirDisplay for ExternCrateDecl {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        write_visibility(self.module(f.db).id, self.visibility(f.db), f)?;
+        f.write_str("extern crate ")?;
+        write!(f, "{}", self.name(f.db).display(f.db.upcast()))?;
+        if let Some(alias) = self.alias(f.db) {
+            write!(f, " as {alias}",)?;
+        }
+        Ok(())
+    }
+}
+
+impl HirDisplay for GenericParam {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        match self {
+            GenericParam::TypeParam(it) => it.hir_fmt(f),
+            GenericParam::ConstParam(it) => it.hir_fmt(f),
+            GenericParam::LifetimeParam(it) => it.hir_fmt(f),
+        }
+    }
+}
+
+impl HirDisplay for TypeOrConstParam {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        match self.split(f.db) {
+            either::Either::Left(it) => it.hir_fmt(f),
+            either::Either::Right(it) => it.hir_fmt(f),
+        }
+    }
+}
+
+impl HirDisplay for TypeParam {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        let params = f.db.generic_params(self.id.parent());
+        let param_data = &params.type_or_consts[self.id.local_id()];
+        let substs = TyBuilder::placeholder_subst(f.db, self.id.parent());
+        let krate = self.id.parent().krate(f.db).id;
+        let ty =
+            TyKind::Placeholder(hir_ty::to_placeholder_idx(f.db, self.id.into())).intern(Interner);
+        let predicates = f.db.generic_predicates(self.id.parent());
+        let predicates = predicates
+            .iter()
+            .cloned()
+            .map(|pred| pred.substitute(Interner, &substs))
+            .filter(|wc| match wc.skip_binders() {
+                WhereClause::Implemented(tr) => tr.self_type_parameter(Interner) == ty,
+                WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(proj), ty: _ }) => {
+                    proj.self_type_parameter(f.db) == ty
+                }
+                WhereClause::AliasEq(_) => false,
+                WhereClause::TypeOutlives(to) => to.ty == ty,
+                WhereClause::LifetimeOutlives(_) => false,
+            })
+            .collect::<Vec<_>>();
+
+        match param_data {
+            TypeOrConstParamData::TypeParamData(p) => match p.provenance {
+                TypeParamProvenance::TypeParamList | TypeParamProvenance::TraitSelf => {
+                    write!(f, "{}", p.name.clone().unwrap().display(f.db.upcast()))?
+                }
+                TypeParamProvenance::ArgumentImplTrait => {
+                    return write_bounds_like_dyn_trait_with_prefix(
+                        f,
+                        "impl",
+                        Either::Left(&ty),
+                        &predicates,
+                        SizedByDefault::Sized { anchor: krate },
+                    );
+                }
+            },
+            TypeOrConstParamData::ConstParamData(p) => {
+                write!(f, "{}", p.name.display(f.db.upcast()))?;
+            }
+        }
+
+        if f.omit_verbose_types() {
+            return Ok(());
+        }
+
+        let sized_trait =
+            f.db.lang_item(krate, LangItem::Sized).and_then(|lang_item| lang_item.as_trait());
+        let has_only_sized_bound = predicates.iter().all(move |pred| match pred.skip_binders() {
+            WhereClause::Implemented(it) => Some(it.hir_trait_id()) == sized_trait,
+            _ => false,
+        });
+        let has_only_not_sized_bound = predicates.is_empty();
+        if !has_only_sized_bound || has_only_not_sized_bound {
+            let default_sized = SizedByDefault::Sized { anchor: krate };
+            write_bounds_like_dyn_trait_with_prefix(
+                f,
+                ":",
+                Either::Left(
+                    &hir_ty::TyKind::Placeholder(hir_ty::to_placeholder_idx(f.db, self.id.into()))
+                        .intern(Interner),
+                ),
+                &predicates,
+                default_sized,
+            )?;
+        }
+        Ok(())
+    }
+}
+
+impl HirDisplay for LifetimeParam {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        write!(f, "{}", self.name(f.db).display(f.db.upcast()))
+    }
+}
+
+impl HirDisplay for ConstParam {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        write!(f, "const {}: ", self.name(f.db).display(f.db.upcast()))?;
+        self.ty(f.db).hir_fmt(f)
+    }
+}
+
+fn write_generic_params(
+    def: GenericDefId,
+    f: &mut HirFormatter<'_>,
+) -> Result<(), HirDisplayError> {
+    let params = f.db.generic_params(def);
+    if params.lifetimes.is_empty()
+        && params.type_or_consts.iter().all(|it| it.1.const_param().is_none())
+        && params
+            .type_or_consts
+            .iter()
+            .filter_map(|it| it.1.type_param())
+            .all(|param| !matches!(param.provenance, TypeParamProvenance::TypeParamList))
+    {
+        return Ok(());
+    }
+    f.write_char('<')?;
+
+    let mut first = true;
+    let mut delim = |f: &mut HirFormatter<'_>| {
+        if first {
+            first = false;
+            Ok(())
+        } else {
+            f.write_str(", ")
+        }
+    };
+    for (_, lifetime) in params.lifetimes.iter() {
+        delim(f)?;
+        write!(f, "{}", lifetime.name.display(f.db.upcast()))?;
+    }
+    for (_, ty) in params.type_or_consts.iter() {
+        if let Some(name) = &ty.name() {
+            match ty {
+                TypeOrConstParamData::TypeParamData(ty) => {
+                    if ty.provenance != TypeParamProvenance::TypeParamList {
+                        continue;
+                    }
+                    delim(f)?;
+                    write!(f, "{}", name.display(f.db.upcast()))?;
+                    if let Some(default) = &ty.default {
+                        f.write_str(" = ")?;
+                        default.hir_fmt(f)?;
+                    }
+                }
+                TypeOrConstParamData::ConstParamData(c) => {
+                    delim(f)?;
+                    write!(f, "const {}: ", name.display(f.db.upcast()))?;
+                    c.ty.hir_fmt(f)?;
+
+                    if let Some(default) = &c.default {
+                        f.write_str(" = ")?;
+                        write!(f, "{}", default.display(f.db.upcast()))?;
+                    }
+                }
+            }
+        }
+    }
+
+    f.write_char('>')?;
+    Ok(())
+}
+
+fn write_where_clause(
+    def: GenericDefId,
+    f: &mut HirFormatter<'_>,
+) -> Result<bool, HirDisplayError> {
+    let params = f.db.generic_params(def);
+
+    // unnamed type targets are displayed inline with the argument itself, e.g. `f: impl Y`.
+    let is_unnamed_type_target = |target: &WherePredicateTypeTarget| match target {
+        WherePredicateTypeTarget::TypeRef(_) => false,
+        WherePredicateTypeTarget::TypeOrConstParam(id) => {
+            params.type_or_consts[*id].name().is_none()
+        }
+    };
+
+    let has_displayable_predicate = params
+        .where_predicates
+        .iter()
+        .any(|pred| {
+            !matches!(pred, WherePredicate::TypeBound { target, .. } if is_unnamed_type_target(target))
+        });
+
+    if !has_displayable_predicate {
+        return Ok(false);
+    }
+
+    let write_target = |target: &WherePredicateTypeTarget, f: &mut HirFormatter<'_>| match target {
+        WherePredicateTypeTarget::TypeRef(ty) => ty.hir_fmt(f),
+        WherePredicateTypeTarget::TypeOrConstParam(id) => {
+            match &params.type_or_consts[*id].name() {
+                Some(name) => write!(f, "{}", name.display(f.db.upcast())),
+                None => f.write_str("{unnamed}"),
+            }
+        }
+    };
+
+    f.write_str("\nwhere")?;
+
+    for (pred_idx, pred) in params.where_predicates.iter().enumerate() {
+        let prev_pred =
+            if pred_idx == 0 { None } else { Some(&params.where_predicates[pred_idx - 1]) };
+
+        let new_predicate = |f: &mut HirFormatter<'_>| {
+            f.write_str(if pred_idx == 0 { "\n    " } else { ",\n    " })
+        };
+
+        match pred {
+            WherePredicate::TypeBound { target, .. } if is_unnamed_type_target(target) => {}
+            WherePredicate::TypeBound { target, bound } => {
+                if matches!(prev_pred, Some(WherePredicate::TypeBound { target: target_, .. }) if target_ == target)
+                {
+                    f.write_str(" + ")?;
+                } else {
+                    new_predicate(f)?;
+                    write_target(target, f)?;
+                    f.write_str(": ")?;
+                }
+                bound.hir_fmt(f)?;
+            }
+            WherePredicate::Lifetime { target, bound } => {
+                if matches!(prev_pred, Some(WherePredicate::Lifetime { target: target_, .. }) if target_ == target)
+                {
+                    write!(f, " + {}", bound.name.display(f.db.upcast()))?;
+                } else {
+                    new_predicate(f)?;
+                    write!(
+                        f,
+                        "{}: {}",
+                        target.name.display(f.db.upcast()),
+                        bound.name.display(f.db.upcast())
+                    )?;
+                }
+            }
+            WherePredicate::ForLifetime { lifetimes, target, bound } => {
+                if matches!(
+                    prev_pred,
+                    Some(WherePredicate::ForLifetime { lifetimes: lifetimes_, target: target_, .. })
+                    if lifetimes_ == lifetimes && target_ == target,
+                ) {
+                    f.write_str(" + ")?;
+                } else {
+                    new_predicate(f)?;
+                    f.write_str("for<")?;
+                    for (idx, lifetime) in lifetimes.iter().enumerate() {
+                        if idx != 0 {
+                            f.write_str(", ")?;
+                        }
+                        write!(f, "{}", lifetime.display(f.db.upcast()))?;
+                    }
+                    f.write_str("> ")?;
+                    write_target(target, f)?;
+                    f.write_str(": ")?;
+                }
+                bound.hir_fmt(f)?;
+            }
+        }
+    }
+
+    // End of final predicate. There must be at least one predicate here.
+    f.write_char(',')?;
+
+    Ok(true)
+}
+
+impl HirDisplay for Const {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        let db = f.db;
+        let container = self.as_assoc_item(db).map(|it| it.container(db));
+        let mut module = self.module(db);
+        if let Some(AssocItemContainer::Impl(_)) = container {
+            // Block-local impls are "hoisted" to the nearest (non-block) module.
+            module = module.nearest_non_block_module(db);
+        }
+        write_visibility(module.id, self.visibility(db), f)?;
+        let data = db.const_data(self.id);
+        f.write_str("const ")?;
+        match &data.name {
+            Some(name) => write!(f, "{}: ", name.display(f.db.upcast()))?,
+            None => f.write_str("_: ")?,
+        }
+        data.type_ref.hir_fmt(f)?;
+        Ok(())
+    }
+}
+
+impl HirDisplay for Static {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        write_visibility(self.module(f.db).id, self.visibility(f.db), f)?;
+        let data = f.db.static_data(self.id);
+        f.write_str("static ")?;
+        if data.mutable {
+            f.write_str("mut ")?;
+        }
+        write!(f, "{}: ", data.name.display(f.db.upcast()))?;
+        data.type_ref.hir_fmt(f)?;
+        Ok(())
+    }
+}
+
+impl HirDisplay for Trait {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        write_visibility(self.module(f.db).id, self.visibility(f.db), f)?;
+        let data = f.db.trait_data(self.id);
+        if data.is_unsafe {
+            f.write_str("unsafe ")?;
+        }
+        if data.is_auto {
+            f.write_str("auto ")?;
+        }
+        write!(f, "trait {}", data.name.display(f.db.upcast()))?;
+        let def_id = GenericDefId::TraitId(self.id);
+        write_generic_params(def_id, f)?;
+        let has_where_clause = write_where_clause(def_id, f)?;
+
+        if let Some(limit) = f.entity_limit {
+            let assoc_items = self.items(f.db);
+            let count = assoc_items.len().min(limit);
+            f.write_char(if !has_where_clause { ' ' } else { '\n' })?;
+            if count == 0 {
+                if assoc_items.is_empty() {
+                    f.write_str("{}")?;
+                } else {
+                    f.write_str("{ /* … */ }")?;
+                }
+            } else {
+                f.write_str("{\n")?;
+                for item in &assoc_items[..count] {
+                    f.write_str("    ")?;
+                    match item {
+                        AssocItem::Function(func) => func.hir_fmt(f),
+                        AssocItem::Const(cst) => cst.hir_fmt(f),
+                        AssocItem::TypeAlias(type_alias) => type_alias.hir_fmt(f),
+                    }?;
+                    f.write_str(";\n")?;
+                }
+
+                if assoc_items.len() > count {
+                    f.write_str("    /* … */\n")?;
+                }
+                f.write_str("}")?;
+            }
+        }
+
+        Ok(())
+    }
+}
+
+impl HirDisplay for TraitAlias {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        write_visibility(self.module(f.db).id, self.visibility(f.db), f)?;
+        let data = f.db.trait_alias_data(self.id);
+        write!(f, "trait {}", data.name.display(f.db.upcast()))?;
+        let def_id = GenericDefId::TraitAliasId(self.id);
+        write_generic_params(def_id, f)?;
+        f.write_str(" = ")?;
+        // FIXME: Currently we lower every bounds in a trait alias as a trait bound on `Self` i.e.
+        // `trait Foo = Bar` is stored and displayed as `trait Foo = where Self: Bar`, which might
+        // be less readable.
+        write_where_clause(def_id, f)?;
+        Ok(())
+    }
+}
+
+impl HirDisplay for TypeAlias {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        write_visibility(self.module(f.db).id, self.visibility(f.db), f)?;
+        let data = f.db.type_alias_data(self.id);
+        write!(f, "type {}", data.name.display(f.db.upcast()))?;
+        let def_id = GenericDefId::TypeAliasId(self.id);
+        write_generic_params(def_id, f)?;
+        if !data.bounds.is_empty() {
+            f.write_str(": ")?;
+            f.write_joined(data.bounds.iter(), " + ")?;
+        }
+        if let Some(ty) = &data.type_ref {
+            f.write_str(" = ")?;
+            ty.hir_fmt(f)?;
+        }
+        write_where_clause(def_id, f)?;
+        Ok(())
+    }
+}
+
+impl HirDisplay for Module {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        // FIXME: Module doesn't have visibility saved in data.
+        match self.name(f.db) {
+            Some(name) => write!(f, "mod {}", name.display(f.db.upcast())),
+            None if self.is_crate_root() => match self.krate(f.db).display_name(f.db) {
+                Some(name) => write!(f, "extern crate {name}"),
+                None => f.write_str("extern crate {unknown}"),
+            },
+            None => f.write_str("mod {unnamed}"),
+        }
+    }
+}
+
+impl HirDisplay for Macro {
+    fn hir_fmt(&self, f: &mut HirFormatter<'_>) -> Result<(), HirDisplayError> {
+        match self.id {
+            hir_def::MacroId::Macro2Id(_) => f.write_str("macro"),
+            hir_def::MacroId::MacroRulesId(_) => f.write_str("macro_rules!"),
+            hir_def::MacroId::ProcMacroId(_) => f.write_str("proc_macro"),
+        }?;
+        write!(f, " {}", self.name(f.db).display(f.db.upcast()))
+    }
+}
diff --git a/src/tools/rust-analyzer/crates/hir/src/from_id.rs b/src/tools/rust-analyzer/crates/hir/src/from_id.rs
new file mode 100644
index 00000000000..887227bf4d0
--- /dev/null
+++ b/src/tools/rust-analyzer/crates/hir/src/from_id.rs
@@ -0,0 +1,300 @@
+//! Utility module for converting between hir_def ids and code_model wrappers.
+//!
+//! It's unclear if we need this long-term, but it's definitely useful while we
+//! are splitting the hir.
+
+use hir_def::{
+    hir::{BindingId, LabelId},
+    AdtId, AssocItemId, DefWithBodyId, EnumVariantId, FieldId, GenericDefId, GenericParamId,
+    ModuleDefId, VariantId,
+};
+
+use crate::{
+    Adt, AssocItem, BuiltinType, DefWithBody, Field, GenericDef, GenericParam, ItemInNs, Label,
+    Local, ModuleDef, Variant, VariantDef,
+};
+
+macro_rules! from_id {
+    ($(($id:path, $ty:path)),* $(,)?) => {$(
+        impl From<$id> for $ty {
+            fn from(id: $id) -> $ty {
+                $ty { id }
+            }
+        }
+        impl From<$ty> for $id {
+            fn from(ty: $ty) -> $id {
+                ty.id
+            }
+        }
+    )*}
+}
+
+from_id![
+    (base_db::CrateId, crate::Crate),
+    (hir_def::ModuleId, crate::Module),
+    (hir_def::StructId, crate::Struct),
+    (hir_def::UnionId, crate::Union),
+    (hir_def::EnumId, crate::Enum),
+    (hir_def::TypeAliasId, crate::TypeAlias),
+    (hir_def::TraitId, crate::Trait),
+    (hir_def::TraitAliasId, crate::TraitAlias),
+    (hir_def::StaticId, crate::Static),
+    (hir_def::ConstId, crate::Const),
+    (hir_def::InTypeConstId, crate::InTypeConst),
+    (hir_def::FunctionId, crate::Function),
+    (hir_def::ImplId, crate::Impl),
+    (hir_def::TypeOrConstParamId, crate::TypeOrConstParam),
+    (hir_def::TypeParamId, crate::TypeParam),
+    (hir_def::ConstParamId, crate::ConstParam),
+    (hir_def::LifetimeParamId, crate::LifetimeParam),
+    (hir_def::MacroId, crate::Macro),
+    (hir_def::ExternCrateId, crate::ExternCrateDecl),
+];
+
+impl From<AdtId> for Adt {
+    fn from(id: AdtId) -> Self {
+        match id {
+            AdtId::StructId(it) => Adt::Struct(it.into()),
+            AdtId::UnionId(it) => Adt::Union(it.into()),
+            AdtId::EnumId(it) => Adt::Enum(it.into()),
+        }
+    }
+}
+
+impl From<Adt> for AdtId {
+    fn from(id: Adt) -> Self {
+        match id {
+            Adt::Struct(it) => AdtId::StructId(it.id),
+            Adt::Union(it) => AdtId::UnionId(it.id),
+            Adt::Enum(it) => AdtId::EnumId(it.id),
+        }
+    }
+}
+
+impl From<GenericParamId> for GenericParam {
+    fn from(id: GenericParamId) -> Self {
+        match id {
+            GenericParamId::TypeParamId(it) => GenericParam::TypeParam(it.into()),
+            GenericParamId::ConstParamId(it) => GenericParam::ConstParam(it.into()),
+            GenericParamId::LifetimeParamId(it) => GenericParam::LifetimeParam(it.into()),
+        }
+    }
+}
+
+impl From<GenericParam> for GenericParamId {
+    fn from(id: GenericParam) -> Self {
+        match id {
+            GenericParam::LifetimeParam(it) => GenericParamId::LifetimeParamId(it.id),
+            GenericParam::ConstParam(it) => GenericParamId::ConstParamId(it.id),
+            GenericParam::TypeParam(it) => GenericParamId::TypeParamId(it.id),
+        }
+    }
+}
+
+impl From<EnumVariantId> for Variant {
+    fn from(id: EnumVariantId) -> Self {
+        Variant { id }
+    }
+}
+
+impl From<Variant> for EnumVariantId {
+    fn from(def: Variant) -> Self {
+        def.id
+    }
+}
+
+impl From<ModuleDefId> for ModuleDef {
+    fn from(id: ModuleDefId) -> Self {
+        match id {
+            ModuleDefId::ModuleId(it) => ModuleDef::Module(it.into()),
+            ModuleDefId::FunctionId(it) => ModuleDef::Function(it.into()),
+            ModuleDefId::AdtId(it) => ModuleDef::Adt(it.into()),
+            ModuleDefId::EnumVariantId(it) => ModuleDef::Variant(it.into()),
+            ModuleDefId::ConstId(it) => ModuleDef::Const(it.into()),
+            ModuleDefId::StaticId(it) => ModuleDef::Static(it.into()),
+            ModuleDefId::TraitId(it) => ModuleDef::Trait(it.into()),
+            ModuleDefId::TraitAliasId(it) => ModuleDef::TraitAlias(it.into()),
+            ModuleDefId::TypeAliasId(it) => ModuleDef::TypeAlias(it.into()),
+            ModuleDefId::BuiltinType(it) => ModuleDef::BuiltinType(it.into()),
+            ModuleDefId::MacroId(it) => ModuleDef::Macro(it.into()),
+        }
+    }
+}
+
+impl From<ModuleDef> for ModuleDefId {
+    fn from(id: ModuleDef) -> Self {
+        match id {
+            ModuleDef::Module(it) => ModuleDefId::ModuleId(it.into()),
+            ModuleDef::Function(it) => ModuleDefId::FunctionId(it.into()),
+            ModuleDef::Adt(it) => ModuleDefId::AdtId(it.into()),
+            ModuleDef::Variant(it) => ModuleDefId::EnumVariantId(it.into()),
+            ModuleDef::Const(it) => ModuleDefId::ConstId(it.into()),
+            ModuleDef::Static(it) => ModuleDefId::StaticId(it.into()),
+            ModuleDef::Trait(it) => ModuleDefId::TraitId(it.into()),
+            ModuleDef::TraitAlias(it) => ModuleDefId::TraitAliasId(it.into()),
+            ModuleDef::TypeAlias(it) => ModuleDefId::TypeAliasId(it.into()),
+            ModuleDef::BuiltinType(it) => ModuleDefId::BuiltinType(it.into()),
+            ModuleDef::Macro(it) => ModuleDefId::MacroId(it.into()),
+        }
+    }
+}
+
+impl From<DefWithBody> for DefWithBodyId {
+    fn from(def: DefWithBody) -> Self {
+        match def {
+            DefWithBody::Function(it) => DefWithBodyId::FunctionId(it.id),
+            DefWithBody::Static(it) => DefWithBodyId::StaticId(it.id),
+            DefWithBody::Const(it) => DefWithBodyId::ConstId(it.id),
+            DefWithBody::Variant(it) => DefWithBodyId::VariantId(it.into()),
+            DefWithBody::InTypeConst(it) => DefWithBodyId::InTypeConstId(it.id),
+        }
+    }
+}
+
+impl From<DefWithBodyId> for DefWithBody {
+    fn from(def: DefWithBodyId) -> Self {
+        match def {
+            DefWithBodyId::FunctionId(it) => DefWithBody::Function(it.into()),
+            DefWithBodyId::StaticId(it) => DefWithBody::Static(it.into()),
+            DefWithBodyId::ConstId(it) => DefWithBody::Const(it.into()),
+            DefWithBodyId::VariantId(it) => DefWithBody::Variant(it.into()),
+            DefWithBodyId::InTypeConstId(it) => DefWithBody::InTypeConst(it.into()),
+        }
+    }
+}
+
+impl From<AssocItemId> for AssocItem {
+    fn from(def: AssocItemId) -> Self {
+        match def {
+            AssocItemId::FunctionId(it) => AssocItem::Function(it.into()),
+            AssocItemId::TypeAliasId(it) => AssocItem::TypeAlias(it.into()),
+            AssocItemId::ConstId(it) => AssocItem::Const(it.into()),
+        }
+    }
+}
+
+impl From<GenericDef> for GenericDefId {
+    fn from(def: GenericDef) -> Self {
+        match def {
+            GenericDef::Function(it) => GenericDefId::FunctionId(it.id),
+            GenericDef::Adt(it) => GenericDefId::AdtId(it.into()),
+            GenericDef::Trait(it) => GenericDefId::TraitId(it.id),
+            GenericDef::TraitAlias(it) => GenericDefId::TraitAliasId(it.id),
+            GenericDef::TypeAlias(it) => GenericDefId::TypeAliasId(it.id),
+            GenericDef::Impl(it) => GenericDefId::ImplId(it.id),
+            GenericDef::Variant(it) => GenericDefId::EnumVariantId(it.into()),
+            GenericDef::Const(it) => GenericDefId::ConstId(it.id),
+        }
+    }
+}
+
+impl From<GenericDefId> for GenericDef {
+    fn from(def: GenericDefId) -> Self {
+        match def {
+            GenericDefId::FunctionId(it) => GenericDef::Function(it.into()),
+            GenericDefId::AdtId(it) => GenericDef::Adt(it.into()),
+            GenericDefId::TraitId(it) => GenericDef::Trait(it.into()),
+            GenericDefId::TraitAliasId(it) => GenericDef::TraitAlias(it.into()),
+            GenericDefId::TypeAliasId(it) => GenericDef::TypeAlias(it.into()),
+            GenericDefId::ImplId(it) => GenericDef::Impl(it.into()),
+            GenericDefId::EnumVariantId(it) => GenericDef::Variant(it.into()),
+            GenericDefId::ConstId(it) => GenericDef::Const(it.into()),
+        }
+    }
+}
+
+impl From<Adt> for GenericDefId {
+    fn from(id: Adt) -> Self {
+        match id {
+            Adt::Struct(it) => it.id.into(),
+            Adt::Union(it) => it.id.into(),
+            Adt::Enum(it) => it.id.into(),
+        }
+    }
+}
+
+impl From<VariantId> for VariantDef {
+    fn from(def: VariantId) -> Self {
+        match def {
+            VariantId::StructId(it) => VariantDef::Struct(it.into()),
+            VariantId::EnumVariantId(it) => VariantDef::Variant(it.into()),
+            VariantId::UnionId(it) => VariantDef::Union(it.into()),
+        }
+    }
+}
+
+impl From<VariantDef> for VariantId {
+    fn from(def: VariantDef) -> Self {
+        match def {
+            VariantDef::Struct(it) => VariantId::StructId(it.id),
+            VariantDef::Variant(it) => VariantId::EnumVariantId(it.into()),
+            VariantDef::Union(it) => VariantId::UnionId(it.id),
+        }
+    }
+}
+
+impl From<Field> for FieldId {
+    fn from(def: Field) -> Self {
+        FieldId { parent: def.parent.into(), local_id: def.id }
+    }
+}
+
+impl From<FieldId> for Field {
+    fn from(def: FieldId) -> Self {
+        Field { parent: def.parent.into(), id: def.local_id }
+    }
+}
+
+impl From<AssocItem> for GenericDefId {
+    fn from(item: AssocItem) -> Self {
+        match item {
+            AssocItem::Function(f) => f.id.into(),
+            AssocItem::Const(c) => c.id.into(),
+            AssocItem::TypeAlias(t) => t.id.into(),
+        }
+    }
+}
+
+impl From<(DefWithBodyId, BindingId)> for Local {
+    fn from((parent, binding_id): (DefWithBodyId, BindingId)) -> Self {
+        Local { parent, binding_id }
+    }
+}
+
+impl From<(DefWithBodyId, LabelId)> for Label {
+    fn from((parent, label_id): (DefWithBodyId, LabelId)) -> Self {
+        Label { parent, label_id }
+    }
+}
+
+impl From<hir_def::item_scope::ItemInNs> for ItemInNs {
+    fn from(it: hir_def::item_scope::ItemInNs) -> Self {
+        match it {
+            hir_def::item_scope::ItemInNs::Types(it) => ItemInNs::Types(it.into()),
+            hir_def::item_scope::ItemInNs::Values(it) => ItemInNs::Values(it.into()),
+            hir_def::item_scope::ItemInNs::Macros(it) => ItemInNs::Macros(it.into()),
+        }
+    }
+}
+
+impl From<ItemInNs> for hir_def::item_scope::ItemInNs {
+    fn from(it: ItemInNs) -> Self {
+        match it {
+            ItemInNs::Types(it) => Self::Types(it.into()),
+            ItemInNs::Values(it) => Self::Values(it.into()),
+            ItemInNs::Macros(it) => Self::Macros(it.into()),
+        }
+    }
+}
+
+impl From<hir_def::builtin_type::BuiltinType> for BuiltinType {
+    fn from(inner: hir_def::builtin_type::BuiltinType) -> Self {
+        Self { inner }
+    }
+}
+
+impl From<BuiltinType> for hir_def::builtin_type::BuiltinType {
+    fn from(it: BuiltinType) -> Self {
+        it.inner
+    }
+}
diff --git a/src/tools/rust-analyzer/crates/hir/src/has_source.rs b/src/tools/rust-analyzer/crates/hir/src/has_source.rs
new file mode 100644
index 00000000000..7cdcdd76d18
--- /dev/null
+++ b/src/tools/rust-analyzer/crates/hir/src/has_source.rs
@@ -0,0 +1,231 @@
+//! Provides set of implementation for hir's objects that allows get back location in file.
+
+use base_db::FileId;
+use either::Either;
+use hir_def::{
+    nameres::{ModuleOrigin, ModuleSource},
+    src::{HasChildSource, HasSource as _},
+    Lookup, MacroId, VariantId,
+};
+use hir_expand::{HirFileId, InFile};
+use syntax::ast;
+use tt::TextRange;
+
+use crate::{
+    db::HirDatabase, Adt, Const, Enum, ExternCrateDecl, Field, FieldSource, Function, Impl,
+    LifetimeParam, LocalSource, Macro, Module, Static, Struct, Trait, TraitAlias, TypeAlias,
+    TypeOrConstParam, Union, Variant,
+};
+
+pub trait HasSource {
+    type Ast;
+    /// Fetches the definition's source node.
+    /// Using [`crate::Semantics::source`] is preferred when working with [`crate::Semantics`],
+    /// as that caches the parsed file in the semantics' cache.
+    ///
+    /// The current some implementations can return `InFile` instead of `Option<InFile>`.
+    /// But we made this method `Option` to support rlib in the future
+    /// by https://github.com/rust-lang/rust-analyzer/issues/6913
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>>;
+}
+
+/// NB: Module is !HasSource, because it has two source nodes at the same time:
+/// definition and declaration.
+impl Module {
+    /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
+    pub fn definition_source(self, db: &dyn HirDatabase) -> InFile<ModuleSource> {
+        let def_map = self.id.def_map(db.upcast());
+        def_map[self.id.local_id].definition_source(db.upcast())
+    }
+
+    /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
+    pub fn definition_source_range(self, db: &dyn HirDatabase) -> InFile<TextRange> {
+        let def_map = self.id.def_map(db.upcast());
+        def_map[self.id.local_id].definition_source_range(db.upcast())
+    }
+
+    pub fn definition_source_file_id(self, db: &dyn HirDatabase) -> HirFileId {
+        let def_map = self.id.def_map(db.upcast());
+        def_map[self.id.local_id].definition_source_file_id()
+    }
+
+    pub fn is_mod_rs(self, db: &dyn HirDatabase) -> bool {
+        let def_map = self.id.def_map(db.upcast());
+        match def_map[self.id.local_id].origin {
+            ModuleOrigin::File { is_mod_rs, .. } => is_mod_rs,
+            _ => false,
+        }
+    }
+
+    pub fn as_source_file_id(self, db: &dyn HirDatabase) -> Option<FileId> {
+        let def_map = self.id.def_map(db.upcast());
+        match def_map[self.id.local_id].origin {
+            ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition, .. } => {
+                Some(definition)
+            }
+            _ => None,
+        }
+    }
+
+    pub fn is_inline(self, db: &dyn HirDatabase) -> bool {
+        let def_map = self.id.def_map(db.upcast());
+        def_map[self.id.local_id].origin.is_inline()
+    }
+
+    /// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`.
+    /// `None` for the crate root.
+    pub fn declaration_source(self, db: &dyn HirDatabase) -> Option<InFile<ast::Module>> {
+        let def_map = self.id.def_map(db.upcast());
+        def_map[self.id.local_id].declaration_source(db.upcast())
+    }
+
+    /// Returns a text range which declares this module, either a `mod foo;` or a `mod foo {}`.
+    /// `None` for the crate root.
+    pub fn declaration_source_range(self, db: &dyn HirDatabase) -> Option<InFile<TextRange>> {
+        let def_map = self.id.def_map(db.upcast());
+        def_map[self.id.local_id].declaration_source_range(db.upcast())
+    }
+}
+
+impl HasSource for Field {
+    type Ast = FieldSource;
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        let var = VariantId::from(self.parent);
+        let src = var.child_source(db.upcast());
+        let field_source = src.map(|it| match it[self.id].clone() {
+            Either::Left(it) => FieldSource::Pos(it),
+            Either::Right(it) => FieldSource::Named(it),
+        });
+        Some(field_source)
+    }
+}
+impl HasSource for Adt {
+    type Ast = ast::Adt;
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        match self {
+            Adt::Struct(s) => Some(s.source(db)?.map(ast::Adt::Struct)),
+            Adt::Union(u) => Some(u.source(db)?.map(ast::Adt::Union)),
+            Adt::Enum(e) => Some(e.source(db)?.map(ast::Adt::Enum)),
+        }
+    }
+}
+impl HasSource for Struct {
+    type Ast = ast::Struct;
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        Some(self.id.lookup(db.upcast()).source(db.upcast()))
+    }
+}
+impl HasSource for Union {
+    type Ast = ast::Union;
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        Some(self.id.lookup(db.upcast()).source(db.upcast()))
+    }
+}
+impl HasSource for Enum {
+    type Ast = ast::Enum;
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        Some(self.id.lookup(db.upcast()).source(db.upcast()))
+    }
+}
+impl HasSource for Variant {
+    type Ast = ast::Variant;
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<ast::Variant>> {
+        Some(self.id.lookup(db.upcast()).source(db.upcast()))
+    }
+}
+impl HasSource for Function {
+    type Ast = ast::Fn;
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        Some(self.id.lookup(db.upcast()).source(db.upcast()))
+    }
+}
+impl HasSource for Const {
+    type Ast = ast::Const;
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        Some(self.id.lookup(db.upcast()).source(db.upcast()))
+    }
+}
+impl HasSource for Static {
+    type Ast = ast::Static;
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        Some(self.id.lookup(db.upcast()).source(db.upcast()))
+    }
+}
+impl HasSource for Trait {
+    type Ast = ast::Trait;
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        Some(self.id.lookup(db.upcast()).source(db.upcast()))
+    }
+}
+impl HasSource for TraitAlias {
+    type Ast = ast::TraitAlias;
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        Some(self.id.lookup(db.upcast()).source(db.upcast()))
+    }
+}
+impl HasSource for TypeAlias {
+    type Ast = ast::TypeAlias;
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        Some(self.id.lookup(db.upcast()).source(db.upcast()))
+    }
+}
+impl HasSource for Macro {
+    type Ast = Either<ast::Macro, ast::Fn>;
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        match self.id {
+            MacroId::Macro2Id(it) => Some(
+                it.lookup(db.upcast())
+                    .source(db.upcast())
+                    .map(ast::Macro::MacroDef)
+                    .map(Either::Left),
+            ),
+            MacroId::MacroRulesId(it) => Some(
+                it.lookup(db.upcast())
+                    .source(db.upcast())
+                    .map(ast::Macro::MacroRules)
+                    .map(Either::Left),
+            ),
+            MacroId::ProcMacroId(it) => {
+                Some(it.lookup(db.upcast()).source(db.upcast()).map(Either::Right))
+            }
+        }
+    }
+}
+impl HasSource for Impl {
+    type Ast = ast::Impl;
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        Some(self.id.lookup(db.upcast()).source(db.upcast()))
+    }
+}
+
+impl HasSource for TypeOrConstParam {
+    type Ast = Either<ast::TypeOrConstParam, ast::TraitOrAlias>;
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        let child_source = self.id.parent.child_source(db.upcast());
+        Some(child_source.map(|it| it[self.id.local_id].clone()))
+    }
+}
+
+impl HasSource for LifetimeParam {
+    type Ast = ast::LifetimeParam;
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        let child_source = self.id.parent.child_source(db.upcast());
+        Some(child_source.map(|it| it[self.id.local_id].clone()))
+    }
+}
+
+impl HasSource for LocalSource {
+    type Ast = Either<ast::IdentPat, ast::SelfParam>;
+
+    fn source(self, _: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        Some(self.source)
+    }
+}
+
+impl HasSource for ExternCrateDecl {
+    type Ast = ast::ExternCrate;
+
+    fn source(self, db: &dyn HirDatabase) -> Option<InFile<Self::Ast>> {
+        Some(self.id.lookup(db.upcast()).source(db.upcast()))
+    }
+}
diff --git a/src/tools/rust-analyzer/crates/hir/src/lib.rs b/src/tools/rust-analyzer/crates/hir/src/lib.rs
new file mode 100644
index 00000000000..12f5a89caaa
--- /dev/null
+++ b/src/tools/rust-analyzer/crates/hir/src/lib.rs
@@ -0,0 +1,5328 @@
+//! HIR (previously known as descriptors) provides a high-level object oriented
+//! access to Rust code.
+//!
+//! The principal difference between HIR and syntax trees is that HIR is bound
+//! to a particular crate instance. That is, it has cfg flags and features
+//! applied. So, the relation between syntax and HIR is many-to-one.
+//!
+//! HIR is the public API of the all of the compiler logic above syntax trees.
+//! It is written in "OO" style. Each type is self contained (as in, it knows its
+//! parents and full context). It should be "clean code".
+//!
+//! `hir_*` crates are the implementation of the compiler logic.
+//! They are written in "ECS" style, with relatively little abstractions.
+//! Many types are not self-contained, and explicitly use local indexes, arenas, etc.
+//!
+//! `hir` is what insulates the "we don't know how to actually write an incremental compiler"
+//! from the ide with completions, hovers, etc. It is a (soft, internal) boundary:
+//! <https://www.tedinski.com/2018/02/06/system-boundaries.html>.
+
+#![warn(rust_2018_idioms, unused_lifetimes)]
+#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
+#![recursion_limit = "512"]
+
+mod semantics;
+mod source_analyzer;
+
+mod attrs;
+mod from_id;
+mod has_source;
+
+pub mod db;
+pub mod diagnostics;
+pub mod symbols;
+pub mod term_search;
+
+mod display;
+
+use std::{iter, mem::discriminant, ops::ControlFlow};
+
+use arrayvec::ArrayVec;
+use base_db::{CrateDisplayName, CrateId, CrateOrigin, FileId};
+use either::Either;
+use hir_def::{
+    body::{BodyDiagnostic, SyntheticSyntax},
+    data::adt::VariantData,
+    generics::{LifetimeParamData, TypeOrConstParamData, TypeParamProvenance},
+    hir::{BindingAnnotation, BindingId, ExprOrPatId, LabelId, Pat},
+    item_tree::ItemTreeNode,
+    lang_item::LangItemTarget,
+    layout::{self, ReprOptions, TargetDataLayout},
+    nameres::{self, diagnostics::DefDiagnostic},
+    path::ImportAlias,
+    per_ns::PerNs,
+    resolver::{HasResolver, Resolver},
+    src::HasSource as _,
+    AssocItemId, AssocItemLoc, AttrDefId, ConstId, ConstParamId, CrateRootModuleId, DefWithBodyId,
+    EnumId, EnumVariantId, ExternCrateId, FunctionId, GenericDefId, GenericParamId, HasModule,
+    ImplId, InTypeConstId, ItemContainerId, LifetimeParamId, LocalFieldId, Lookup, MacroExpander,
+    ModuleId, StaticId, StructId, TraitAliasId, TraitId, TupleId, TypeAliasId, TypeOrConstParamId,
+    TypeParamId, UnionId,
+};
+use hir_expand::{attrs::collect_attrs, name::name, proc_macro::ProcMacroKind, MacroCallKind};
+use hir_ty::{
+    all_super_traits, autoderef, check_orphan_rules,
+    consteval::{try_const_usize, unknown_const_as_generic, ConstExt},
+    db::InternedClosure,
+    diagnostics::BodyValidationDiagnostic,
+    error_lifetime, known_const_to_ast,
+    layout::{Layout as TyLayout, RustcEnumVariantIdx, RustcFieldIdx, TagEncoding},
+    method_resolution::{self, TyFingerprint},
+    mir::{interpret_mir, MutBorrowKind},
+    primitive::UintTy,
+    traits::FnTrait,
+    AliasTy, CallableDefId, CallableSig, Canonical, CanonicalVarKinds, Cast, ClosureId, GenericArg,
+    GenericArgData, Interner, ParamKind, QuantifiedWhereClause, Scalar, Substitution,
+    TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyDefId, TyExt, TyKind, ValueTyDefId,
+    WhereClause,
+};
+use itertools::Itertools;
+use nameres::diagnostics::DefDiagnosticKind;
+use rustc_hash::FxHashSet;
+use span::Edition;
+use stdx::{impl_from, never};
+use syntax::{
+    ast::{self, HasAttrs as _, HasName},
+    format_smolstr, AstNode, AstPtr, SmolStr, SyntaxNode, SyntaxNodePtr, TextRange, T,
+};
+use triomphe::Arc;
+
+use crate::db::{DefDatabase, HirDatabase};
+
+pub use crate::{
+    attrs::{resolve_doc_path_on, HasAttrs},
+    diagnostics::*,
+    has_source::HasSource,
+    semantics::{
+        DescendPreference, PathResolution, Semantics, SemanticsImpl, SemanticsScope, TypeInfo,
+        VisibleTraits,
+    },
+};
+
+// Be careful with these re-exports.
+//
+// `hir` is the boundary between the compiler and the IDE. It should try hard to
+// isolate the compiler from the ide, to allow the two to be refactored
+// independently. Re-exporting something from the compiler is the sure way to
+// breach the boundary.
+//
+// Generally, a refactoring which *removes* a name from this list is a good
+// idea!
+pub use {
+    cfg::{CfgAtom, CfgExpr, CfgOptions},
+    hir_def::{
+        attr::{builtin::AttributeTemplate, AttrSourceMap, Attrs, AttrsWithOwner},
+        data::adt::StructKind,
+        find_path::PrefixKind,
+        import_map,
+        lang_item::LangItem,
+        nameres::{DefMap, ModuleSource},
+        path::{ModPath, PathKind},
+        per_ns::Namespace,
+        type_ref::{Mutability, TypeRef},
+        visibility::Visibility,
+        // FIXME: This is here since some queries take it as input that are used
+        // outside of hir.
+        {AdtId, MacroId, ModuleDefId},
+    },
+    hir_expand::{
+        attrs::{Attr, AttrId},
+        change::ChangeWithProcMacros,
+        hygiene::{marks_rev, SyntaxContextExt},
+        name::{known, Name},
+        proc_macro::ProcMacros,
+        tt, ExpandResult, HirFileId, HirFileIdExt, InFile, InMacroFile, InRealFile, MacroFileId,
+        MacroFileIdExt,
+    },
+    hir_ty::{
+        consteval::ConstEvalError,
+        display::{ClosureStyle, HirDisplay, HirDisplayError, HirWrite},
+        layout::LayoutError,
+        mir::{MirEvalError, MirLowerError},
+        PointerCast, Safety,
+    },
+    // FIXME: Properly encapsulate mir
+    hir_ty::{mir, Interner as ChalkTyInterner},
+};
+
+// These are negative re-exports: pub using these names is forbidden, they
+// should remain private to hir internals.
+#[allow(unused)]
+use {
+    hir_def::path::Path,
+    hir_expand::{
+        name::AsName,
+        span_map::{ExpansionSpanMap, RealSpanMap, SpanMap, SpanMapRef},
+    },
+};
+
+/// hir::Crate describes a single crate. It's the main interface with which
+/// a crate's dependencies interact. Mostly, it should be just a proxy for the
+/// root module.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct Crate {
+    pub(crate) id: CrateId,
+}
+
+#[derive(Debug)]
+pub struct CrateDependency {
+    pub krate: Crate,
+    pub name: Name,
+}
+
+impl Crate {
+    pub fn origin(self, db: &dyn HirDatabase) -> CrateOrigin {
+        db.crate_graph()[self.id].origin.clone()
+    }
+
+    pub fn is_builtin(self, db: &dyn HirDatabase) -> bool {
+        matches!(self.origin(db), CrateOrigin::Lang(_))
+    }
+
+    pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
+        db.crate_graph()[self.id]
+            .dependencies
+            .iter()
+            .map(|dep| {
+                let krate = Crate { id: dep.crate_id };
+                let name = dep.as_name();
+                CrateDependency { krate, name }
+            })
+            .collect()
+    }
+
+    pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
+        let crate_graph = db.crate_graph();
+        crate_graph
+            .iter()
+            .filter(|&krate| {
+                crate_graph[krate].dependencies.iter().any(|it| it.crate_id == self.id)
+            })
+            .map(|id| Crate { id })
+            .collect()
+    }
+
+    pub fn transitive_reverse_dependencies(
+        self,
+        db: &dyn HirDatabase,
+    ) -> impl Iterator<Item = Crate> {
+        db.crate_graph().transitive_rev_deps(self.id).map(|id| Crate { id })
+    }
+
+    pub fn root_module(self) -> Module {
+        Module { id: CrateRootModuleId::from(self.id).into() }
+    }
+
+    pub fn modules(self, db: &dyn HirDatabase) -> Vec<Module> {
+        let def_map = db.crate_def_map(self.id);
+        def_map.modules().map(|(id, _)| def_map.module_id(id).into()).collect()
+    }
+
+    pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
+        db.crate_graph()[self.id].root_file_id
+    }
+
+    pub fn edition(self, db: &dyn HirDatabase) -> Edition {
+        db.crate_graph()[self.id].edition
+    }
+
+    pub fn version(self, db: &dyn HirDatabase) -> Option<String> {
+        db.crate_graph()[self.id].version.clone()
+    }
+
+    pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
+        db.crate_graph()[self.id].display_name.clone()
+    }
+
+    pub fn query_external_importables(
+        self,
+        db: &dyn DefDatabase,
+        query: import_map::Query,
+    ) -> impl Iterator<Item = Either<ModuleDef, Macro>> {
+        let _p = tracing::span!(tracing::Level::INFO, "query_external_importables");
+        import_map::search_dependencies(db, self.into(), &query).into_iter().map(|item| {
+            match ItemInNs::from(item) {
+                ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id),
+                ItemInNs::Macros(mac_id) => Either::Right(mac_id),
+            }
+        })
+    }
+
+    pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
+        db.crate_graph().iter().map(|id| Crate { id }).collect()
+    }
+
+    /// Try to get the root URL of the documentation of a crate.
+    pub fn get_html_root_url(self: &Crate, db: &dyn HirDatabase) -> Option<String> {
+        // Look for #![doc(html_root_url = "...")]
+        let attrs = db.attrs(AttrDefId::ModuleId(self.root_module().into()));
+        let doc_url = attrs.by_key("doc").find_string_value_in_tt("html_root_url");
+        doc_url.map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
+    }
+
+    pub fn cfg(&self, db: &dyn HirDatabase) -> Arc<CfgOptions> {
+        db.crate_graph()[self.id].cfg_options.clone()
+    }
+
+    pub fn potential_cfg(&self, db: &dyn HirDatabase) -> Arc<CfgOptions> {
+        let data = &db.crate_graph()[self.id];
+        data.potential_cfg_options.clone().unwrap_or_else(|| data.cfg_options.clone())
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct Module {
+    pub(crate) id: ModuleId,
+}
+
+/// The defs which can be visible in the module.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum ModuleDef {
+    Module(Module),
+    Function(Function),
+    Adt(Adt),
+    // Can't be directly declared, but can be imported.
+    Variant(Variant),
+    Const(Const),
+    Static(Static),
+    Trait(Trait),
+    TraitAlias(TraitAlias),
+    TypeAlias(TypeAlias),
+    BuiltinType(BuiltinType),
+    Macro(Macro),
+}
+impl_from!(
+    Module,
+    Function,
+    Adt(Struct, Enum, Union),
+    Variant,
+    Const,
+    Static,
+    Trait,
+    TraitAlias,
+    TypeAlias,
+    BuiltinType,
+    Macro
+    for ModuleDef
+);
+
+impl From<VariantDef> for ModuleDef {
+    fn from(var: VariantDef) -> Self {
+        match var {
+            VariantDef::Struct(t) => Adt::from(t).into(),
+            VariantDef::Union(t) => Adt::from(t).into(),
+            VariantDef::Variant(t) => t.into(),
+        }
+    }
+}
+
+impl ModuleDef {
+    pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
+        match self {
+            ModuleDef::Module(it) => it.parent(db),
+            ModuleDef::Function(it) => Some(it.module(db)),
+            ModuleDef::Adt(it) => Some(it.module(db)),
+            ModuleDef::Variant(it) => Some(it.module(db)),
+            ModuleDef::Const(it) => Some(it.module(db)),
+            ModuleDef::Static(it) => Some(it.module(db)),
+            ModuleDef::Trait(it) => Some(it.module(db)),
+            ModuleDef::TraitAlias(it) => Some(it.module(db)),
+            ModuleDef::TypeAlias(it) => Some(it.module(db)),
+            ModuleDef::Macro(it) => Some(it.module(db)),
+            ModuleDef::BuiltinType(_) => None,
+        }
+    }
+
+    pub fn canonical_path(&self, db: &dyn HirDatabase) -> Option<String> {
+        let mut segments = vec![self.name(db)?];
+        for m in self.module(db)?.path_to_root(db) {
+            segments.extend(m.name(db))
+        }
+        segments.reverse();
+        Some(segments.iter().map(|it| it.display(db.upcast())).join("::"))
+    }
+
+    pub fn canonical_module_path(
+        &self,
+        db: &dyn HirDatabase,
+    ) -> Option<impl Iterator<Item = Module>> {
+        self.module(db).map(|it| it.path_to_root(db).into_iter().rev())
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
+        let name = match self {
+            ModuleDef::Module(it) => it.name(db)?,
+            ModuleDef::Const(it) => it.name(db)?,
+            ModuleDef::Adt(it) => it.name(db),
+            ModuleDef::Trait(it) => it.name(db),
+            ModuleDef::TraitAlias(it) => it.name(db),
+            ModuleDef::Function(it) => it.name(db),
+            ModuleDef::Variant(it) => it.name(db),
+            ModuleDef::TypeAlias(it) => it.name(db),
+            ModuleDef::Static(it) => it.name(db),
+            ModuleDef::Macro(it) => it.name(db),
+            ModuleDef::BuiltinType(it) => it.name(),
+        };
+        Some(name)
+    }
+
+    pub fn diagnostics(self, db: &dyn HirDatabase, style_lints: bool) -> Vec<AnyDiagnostic> {
+        let id = match self {
+            ModuleDef::Adt(it) => match it {
+                Adt::Struct(it) => it.id.into(),
+                Adt::Enum(it) => it.id.into(),
+                Adt::Union(it) => it.id.into(),
+            },
+            ModuleDef::Trait(it) => it.id.into(),
+            ModuleDef::TraitAlias(it) => it.id.into(),
+            ModuleDef::Function(it) => it.id.into(),
+            ModuleDef::TypeAlias(it) => it.id.into(),
+            ModuleDef::Module(it) => it.id.into(),
+            ModuleDef::Const(it) => it.id.into(),
+            ModuleDef::Static(it) => it.id.into(),
+            ModuleDef::Variant(it) => it.id.into(),
+            ModuleDef::BuiltinType(_) | ModuleDef::Macro(_) => return Vec::new(),
+        };
+
+        let mut acc = Vec::new();
+
+        match self.as_def_with_body() {
+            Some(def) => {
+                def.diagnostics(db, &mut acc, style_lints);
+            }
+            None => {
+                for diag in hir_ty::diagnostics::incorrect_case(db, id) {
+                    acc.push(diag.into())
+                }
+            }
+        }
+
+        acc
+    }
+
+    pub fn as_def_with_body(self) -> Option<DefWithBody> {
+        match self {
+            ModuleDef::Function(it) => Some(it.into()),
+            ModuleDef::Const(it) => Some(it.into()),
+            ModuleDef::Static(it) => Some(it.into()),
+            ModuleDef::Variant(it) => Some(it.into()),
+
+            ModuleDef::Module(_)
+            | ModuleDef::Adt(_)
+            | ModuleDef::Trait(_)
+            | ModuleDef::TraitAlias(_)
+            | ModuleDef::TypeAlias(_)
+            | ModuleDef::Macro(_)
+            | ModuleDef::BuiltinType(_) => None,
+        }
+    }
+
+    pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
+        Some(match self {
+            ModuleDef::Module(it) => it.attrs(db),
+            ModuleDef::Function(it) => it.attrs(db),
+            ModuleDef::Adt(it) => it.attrs(db),
+            ModuleDef::Variant(it) => it.attrs(db),
+            ModuleDef::Const(it) => it.attrs(db),
+            ModuleDef::Static(it) => it.attrs(db),
+            ModuleDef::Trait(it) => it.attrs(db),
+            ModuleDef::TraitAlias(it) => it.attrs(db),
+            ModuleDef::TypeAlias(it) => it.attrs(db),
+            ModuleDef::Macro(it) => it.attrs(db),
+            ModuleDef::BuiltinType(_) => return None,
+        })
+    }
+}
+
+impl HasVisibility for ModuleDef {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        match *self {
+            ModuleDef::Module(it) => it.visibility(db),
+            ModuleDef::Function(it) => it.visibility(db),
+            ModuleDef::Adt(it) => it.visibility(db),
+            ModuleDef::Const(it) => it.visibility(db),
+            ModuleDef::Static(it) => it.visibility(db),
+            ModuleDef::Trait(it) => it.visibility(db),
+            ModuleDef::TraitAlias(it) => it.visibility(db),
+            ModuleDef::TypeAlias(it) => it.visibility(db),
+            ModuleDef::Variant(it) => it.visibility(db),
+            ModuleDef::Macro(it) => it.visibility(db),
+            ModuleDef::BuiltinType(_) => Visibility::Public,
+        }
+    }
+}
+
+impl Module {
+    /// Name of this module.
+    pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
+        self.id.name(db.upcast())
+    }
+
+    /// Returns the crate this module is part of.
+    pub fn krate(self) -> Crate {
+        Crate { id: self.id.krate() }
+    }
+
+    /// Topmost parent of this module. Every module has a `crate_root`, but some
+    /// might be missing `krate`. This can happen if a module's file is not included
+    /// in the module tree of any target in `Cargo.toml`.
+    pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
+        let def_map = db.crate_def_map(self.id.krate());
+        Module { id: def_map.crate_root().into() }
+    }
+
+    pub fn is_crate_root(self) -> bool {
+        DefMap::ROOT == self.id.local_id
+    }
+
+    /// Iterates over all child modules.
+    pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
+        let def_map = self.id.def_map(db.upcast());
+        let children = def_map[self.id.local_id]
+            .children
+            .values()
+            .map(|module_id| Module { id: def_map.module_id(*module_id) })
+            .collect::<Vec<_>>();
+        children.into_iter()
+    }
+
+    /// Finds a parent module.
+    pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
+        // FIXME: handle block expressions as modules (their parent is in a different DefMap)
+        let def_map = self.id.def_map(db.upcast());
+        let parent_id = def_map[self.id.local_id].parent?;
+        Some(Module { id: def_map.module_id(parent_id) })
+    }
+
+    /// Finds nearest non-block ancestor `Module` (`self` included).
+    pub fn nearest_non_block_module(self, db: &dyn HirDatabase) -> Module {
+        let mut id = self.id;
+        while id.is_block_module() {
+            id = id.containing_module(db.upcast()).expect("block without parent module");
+        }
+        Module { id }
+    }
+
+    pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
+        let mut res = vec![self];
+        let mut curr = self;
+        while let Some(next) = curr.parent(db) {
+            res.push(next);
+            curr = next
+        }
+        res
+    }
+
+    /// Returns a `ModuleScope`: a set of items, visible in this module.
+    pub fn scope(
+        self,
+        db: &dyn HirDatabase,
+        visible_from: Option<Module>,
+    ) -> Vec<(Name, ScopeDef)> {
+        self.id.def_map(db.upcast())[self.id.local_id]
+            .scope
+            .entries()
+            .filter_map(|(name, def)| {
+                if let Some(m) = visible_from {
+                    let filtered =
+                        def.filter_visibility(|vis| vis.is_visible_from(db.upcast(), m.id));
+                    if filtered.is_none() && !def.is_none() {
+                        None
+                    } else {
+                        Some((name, filtered))
+                    }
+                } else {
+                    Some((name, def))
+                }
+            })
+            .flat_map(|(name, def)| {
+                ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
+            })
+            .collect()
+    }
+
+    /// Fills `acc` with the module's diagnostics.
+    pub fn diagnostics(
+        self,
+        db: &dyn HirDatabase,
+        acc: &mut Vec<AnyDiagnostic>,
+        style_lints: bool,
+    ) {
+        let _p = tracing::span!(tracing::Level::INFO, "Module::diagnostics", name = ?self.name(db));
+        let def_map = self.id.def_map(db.upcast());
+        for diag in def_map.diagnostics() {
+            if diag.in_module != self.id.local_id {
+                // FIXME: This is accidentally quadratic.
+                continue;
+            }
+            emit_def_diagnostic(db, acc, diag);
+        }
+
+        for def in self.declarations(db) {
+            match def {
+                ModuleDef::Module(m) => {
+                    // Only add diagnostics from inline modules
+                    if def_map[m.id.local_id].origin.is_inline() {
+                        m.diagnostics(db, acc, style_lints)
+                    }
+                    acc.extend(def.diagnostics(db, style_lints))
+                }
+                ModuleDef::Trait(t) => {
+                    for diag in db.trait_data_with_diagnostics(t.id).1.iter() {
+                        emit_def_diagnostic(db, acc, diag);
+                    }
+
+                    for item in t.items(db) {
+                        item.diagnostics(db, acc, style_lints);
+                    }
+
+                    acc.extend(def.diagnostics(db, style_lints))
+                }
+                ModuleDef::Adt(adt) => {
+                    match adt {
+                        Adt::Struct(s) => {
+                            for diag in db.struct_data_with_diagnostics(s.id).1.iter() {
+                                emit_def_diagnostic(db, acc, diag);
+                            }
+                        }
+                        Adt::Union(u) => {
+                            for diag in db.union_data_with_diagnostics(u.id).1.iter() {
+                                emit_def_diagnostic(db, acc, diag);
+                            }
+                        }
+                        Adt::Enum(e) => {
+                            for v in e.variants(db) {
+                                acc.extend(ModuleDef::Variant(v).diagnostics(db, style_lints));
+                                for diag in db.enum_variant_data_with_diagnostics(v.id).1.iter() {
+                                    emit_def_diagnostic(db, acc, diag);
+                                }
+                            }
+                        }
+                    }
+                    acc.extend(def.diagnostics(db, style_lints))
+                }
+                ModuleDef::Macro(m) => emit_macro_def_diagnostics(db, acc, m),
+                _ => acc.extend(def.diagnostics(db, style_lints)),
+            }
+        }
+        self.legacy_macros(db).into_iter().for_each(|m| emit_macro_def_diagnostics(db, acc, m));
+
+        let inherent_impls = db.inherent_impls_in_crate(self.id.krate());
+
+        let mut impl_assoc_items_scratch = vec![];
+        for impl_def in self.impl_defs(db) {
+            let loc = impl_def.id.lookup(db.upcast());
+            let tree = loc.id.item_tree(db.upcast());
+            let node = &tree[loc.id.value];
+            let file_id = loc.id.file_id();
+            if file_id.macro_file().map_or(false, |it| it.is_builtin_derive(db.upcast())) {
+                // these expansion come from us, diagnosing them is a waste of resources
+                // FIXME: Once we diagnose the inputs to builtin derives, we should at least extract those diagnostics somehow
+                continue;
+            }
+            let ast_id_map = db.ast_id_map(file_id);
+
+            for diag in db.impl_data_with_diagnostics(impl_def.id).1.iter() {
+                emit_def_diagnostic(db, acc, diag);
+            }
+
+            if inherent_impls.invalid_impls().contains(&impl_def.id) {
+                acc.push(IncoherentImpl { impl_: ast_id_map.get(node.ast_id()), file_id }.into())
+            }
+
+            if !impl_def.check_orphan_rules(db) {
+                acc.push(TraitImplOrphan { impl_: ast_id_map.get(node.ast_id()), file_id }.into())
+            }
+
+            let trait_ = impl_def.trait_(db);
+            let trait_is_unsafe = trait_.map_or(false, |t| t.is_unsafe(db));
+            let impl_is_negative = impl_def.is_negative(db);
+            let impl_is_unsafe = impl_def.is_unsafe(db);
+
+            let drop_maybe_dangle = (|| {
+                // FIXME: This can be simplified a lot by exposing hir-ty's utils.rs::Generics helper
+                let trait_ = trait_?;
+                let drop_trait = db.lang_item(self.krate().into(), LangItem::Drop)?.as_trait()?;
+                if drop_trait != trait_.into() {
+                    return None;
+                }
+                let parent = impl_def.id.into();
+                let generic_params = db.generic_params(parent);
+                let lifetime_params = generic_params.lifetimes.iter().map(|(local_id, _)| {
+                    GenericParamId::LifetimeParamId(LifetimeParamId { parent, local_id })
+                });
+                let type_params = generic_params
+                    .iter_type_or_consts()
+                    .filter(|(_, it)| it.type_param().is_some())
+                    .map(|(local_id, _)| {
+                        GenericParamId::TypeParamId(TypeParamId::from_unchecked(
+                            TypeOrConstParamId { parent, local_id },
+                        ))
+                    });
+                let res = type_params
+                    .chain(lifetime_params)
+                    .any(|p| db.attrs(AttrDefId::GenericParamId(p)).by_key("may_dangle").exists());
+                Some(res)
+            })()
+            .unwrap_or(false);
+
+            match (impl_is_unsafe, trait_is_unsafe, impl_is_negative, drop_maybe_dangle) {
+                // unsafe negative impl
+                (true, _, true, _) |
+                // unsafe impl for safe trait
+                (true, false, _, false) => acc.push(TraitImplIncorrectSafety { impl_: ast_id_map.get(node.ast_id()), file_id, should_be_safe: true }.into()),
+                // safe impl for unsafe trait
+                (false, true, false, _) |
+                // safe impl of dangling drop
+                (false, false, _, true) => acc.push(TraitImplIncorrectSafety { impl_: ast_id_map.get(node.ast_id()), file_id, should_be_safe: false }.into()),
+                _ => (),
+            };
+
+            // Negative impls can't have items, don't emit missing items diagnostic for them
+            if let (false, Some(trait_)) = (impl_is_negative, trait_) {
+                let items = &db.trait_data(trait_.into()).items;
+                let required_items = items.iter().filter(|&(_, assoc)| match *assoc {
+                    AssocItemId::FunctionId(it) => !db.function_data(it).has_body(),
+                    AssocItemId::ConstId(id) => !db.const_data(id).has_body,
+                    AssocItemId::TypeAliasId(it) => db.type_alias_data(it).type_ref.is_none(),
+                });
+                impl_assoc_items_scratch.extend(db.impl_data(impl_def.id).items.iter().filter_map(
+                    |&item| {
+                        Some((
+                            item,
+                            match item {
+                                AssocItemId::FunctionId(it) => db.function_data(it).name.clone(),
+                                AssocItemId::ConstId(it) => {
+                                    db.const_data(it).name.as_ref()?.clone()
+                                }
+                                AssocItemId::TypeAliasId(it) => db.type_alias_data(it).name.clone(),
+                            },
+                        ))
+                    },
+                ));
+
+                let redundant = impl_assoc_items_scratch
+                    .iter()
+                    .filter(|(id, name)| {
+                        !items.iter().any(|(impl_name, impl_item)| {
+                            discriminant(impl_item) == discriminant(id) && impl_name == name
+                        })
+                    })
+                    .map(|(item, name)| (name.clone(), AssocItem::from(*item)));
+                for (name, assoc_item) in redundant {
+                    acc.push(
+                        TraitImplRedundantAssocItems {
+                            trait_,
+                            file_id,
+                            impl_: ast_id_map.get(node.ast_id()),
+                            assoc_item: (name, assoc_item),
+                        }
+                        .into(),
+                    )
+                }
+
+                let missing: Vec<_> = required_items
+                    .filter(|(name, id)| {
+                        !impl_assoc_items_scratch.iter().any(|(impl_item, impl_name)| {
+                            discriminant(impl_item) == discriminant(id) && impl_name == name
+                        })
+                    })
+                    .map(|(name, item)| (name.clone(), AssocItem::from(*item)))
+                    .collect();
+                if !missing.is_empty() {
+                    acc.push(
+                        TraitImplMissingAssocItems {
+                            impl_: ast_id_map.get(node.ast_id()),
+                            file_id,
+                            missing,
+                        }
+                        .into(),
+                    )
+                }
+                impl_assoc_items_scratch.clear();
+            }
+
+            for &item in &db.impl_data(impl_def.id).items {
+                AssocItem::from(item).diagnostics(db, acc, style_lints);
+            }
+        }
+    }
+
+    pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
+        let def_map = self.id.def_map(db.upcast());
+        let scope = &def_map[self.id.local_id].scope;
+        scope
+            .declarations()
+            .map(ModuleDef::from)
+            .chain(scope.unnamed_consts().map(|id| ModuleDef::Const(Const::from(id))))
+            .collect()
+    }
+
+    pub fn legacy_macros(self, db: &dyn HirDatabase) -> Vec<Macro> {
+        let def_map = self.id.def_map(db.upcast());
+        let scope = &def_map[self.id.local_id].scope;
+        scope.legacy_macros().flat_map(|(_, it)| it).map(|&it| it.into()).collect()
+    }
+
+    pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
+        let def_map = self.id.def_map(db.upcast());
+        def_map[self.id.local_id].scope.impls().map(Impl::from).collect()
+    }
+
+    /// Finds a path that can be used to refer to the given item from within
+    /// this module, if possible.
+    pub fn find_use_path(
+        self,
+        db: &dyn DefDatabase,
+        item: impl Into<ItemInNs>,
+        prefer_no_std: bool,
+        prefer_prelude: bool,
+    ) -> Option<ModPath> {
+        hir_def::find_path::find_path(
+            db,
+            item.into().into(),
+            self.into(),
+            prefer_no_std,
+            prefer_prelude,
+        )
+    }
+
+    /// Finds a path that can be used to refer to the given item from within
+    /// this module, if possible. This is used for returning import paths for use-statements.
+    pub fn find_use_path_prefixed(
+        self,
+        db: &dyn DefDatabase,
+        item: impl Into<ItemInNs>,
+        prefix_kind: PrefixKind,
+        prefer_no_std: bool,
+        prefer_prelude: bool,
+    ) -> Option<ModPath> {
+        hir_def::find_path::find_path_prefixed(
+            db,
+            item.into().into(),
+            self.into(),
+            prefix_kind,
+            prefer_no_std,
+            prefer_prelude,
+        )
+    }
+}
+
+fn emit_macro_def_diagnostics(db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>, m: Macro) {
+    let id = db.macro_def(m.id);
+    if let hir_expand::db::TokenExpander::DeclarativeMacro(expander) = db.macro_expander(id) {
+        if let Some(e) = expander.mac.err() {
+            let Some(ast) = id.ast_id().left() else {
+                never!("declarative expander for non decl-macro: {:?}", e);
+                return;
+            };
+            emit_def_diagnostic_(
+                db,
+                acc,
+                &DefDiagnosticKind::MacroDefError { ast, message: e.to_string() },
+            );
+        }
+    }
+}
+
+fn emit_def_diagnostic(db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>, diag: &DefDiagnostic) {
+    emit_def_diagnostic_(db, acc, &diag.kind)
+}
+
+fn emit_def_diagnostic_(
+    db: &dyn HirDatabase,
+    acc: &mut Vec<AnyDiagnostic>,
+    diag: &DefDiagnosticKind,
+) {
+    match diag {
+        DefDiagnosticKind::UnresolvedModule { ast: declaration, candidates } => {
+            let decl = declaration.to_ptr(db.upcast());
+            acc.push(
+                UnresolvedModule {
+                    decl: InFile::new(declaration.file_id, decl),
+                    candidates: candidates.clone(),
+                }
+                .into(),
+            )
+        }
+        DefDiagnosticKind::UnresolvedExternCrate { ast } => {
+            let item = ast.to_ptr(db.upcast());
+            acc.push(UnresolvedExternCrate { decl: InFile::new(ast.file_id, item) }.into());
+        }
+
+        DefDiagnosticKind::UnresolvedImport { id, index } => {
+            let file_id = id.file_id();
+            let item_tree = id.item_tree(db.upcast());
+            let import = &item_tree[id.value];
+
+            let use_tree = import.use_tree_to_ast(db.upcast(), file_id, *index);
+            acc.push(
+                UnresolvedImport { decl: InFile::new(file_id, AstPtr::new(&use_tree)) }.into(),
+            );
+        }
+
+        DefDiagnosticKind::UnconfiguredCode { ast, cfg, opts } => {
+            let item = ast.to_ptr(db.upcast());
+            acc.push(
+                InactiveCode { node: ast.with_value(item), cfg: cfg.clone(), opts: opts.clone() }
+                    .into(),
+            );
+        }
+        DefDiagnosticKind::UnresolvedProcMacro { ast, krate } => {
+            let (node, precise_location, macro_name, kind) = precise_macro_call_location(ast, db);
+            acc.push(
+                UnresolvedProcMacro { node, precise_location, macro_name, kind, krate: *krate }
+                    .into(),
+            );
+        }
+        DefDiagnosticKind::UnresolvedMacroCall { ast, path } => {
+            let (node, precise_location, _, _) = precise_macro_call_location(ast, db);
+            acc.push(
+                UnresolvedMacroCall {
+                    macro_call: node,
+                    precise_location,
+                    path: path.clone(),
+                    is_bang: matches!(ast, MacroCallKind::FnLike { .. }),
+                }
+                .into(),
+            );
+        }
+        DefDiagnosticKind::MacroError { ast, message } => {
+            let (node, precise_location, _, _) = precise_macro_call_location(ast, db);
+            acc.push(MacroError { node, precise_location, message: message.clone() }.into());
+        }
+        DefDiagnosticKind::MacroExpansionParseError { ast, errors } => {
+            let (node, precise_location, _, _) = precise_macro_call_location(ast, db);
+            acc.push(
+                MacroExpansionParseError { node, precise_location, errors: errors.clone() }.into(),
+            );
+        }
+        DefDiagnosticKind::UnimplementedBuiltinMacro { ast } => {
+            let node = ast.to_node(db.upcast());
+            // Must have a name, otherwise we wouldn't emit it.
+            let name = node.name().expect("unimplemented builtin macro with no name");
+            acc.push(
+                UnimplementedBuiltinMacro {
+                    node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&name))),
+                }
+                .into(),
+            );
+        }
+        DefDiagnosticKind::InvalidDeriveTarget { ast, id } => {
+            let node = ast.to_node(db.upcast());
+            let derive = node.attrs().nth(*id);
+            match derive {
+                Some(derive) => {
+                    acc.push(
+                        InvalidDeriveTarget {
+                            node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
+                        }
+                        .into(),
+                    );
+                }
+                None => stdx::never!("derive diagnostic on item without derive attribute"),
+            }
+        }
+        DefDiagnosticKind::MalformedDerive { ast, id } => {
+            let node = ast.to_node(db.upcast());
+            let derive = node.attrs().nth(*id);
+            match derive {
+                Some(derive) => {
+                    acc.push(
+                        MalformedDerive {
+                            node: ast.with_value(SyntaxNodePtr::from(AstPtr::new(&derive))),
+                        }
+                        .into(),
+                    );
+                }
+                None => stdx::never!("derive diagnostic on item without derive attribute"),
+            }
+        }
+        DefDiagnosticKind::MacroDefError { ast, message } => {
+            let node = ast.to_node(db.upcast());
+            acc.push(
+                MacroDefError {
+                    node: InFile::new(ast.file_id, AstPtr::new(&node)),
+                    name: node.name().map(|it| it.syntax().text_range()),
+                    message: message.clone(),
+                }
+                .into(),
+            );
+        }
+    }
+}
+
+fn precise_macro_call_location(
+    ast: &MacroCallKind,
+    db: &dyn HirDatabase,
+) -> (InFile<SyntaxNodePtr>, Option<TextRange>, Option<String>, MacroKind) {
+    // FIXME: maybe we actually want slightly different ranges for the different macro diagnostics
+    // - e.g. the full attribute for macro errors, but only the name for name resolution
+    match ast {
+        MacroCallKind::FnLike { ast_id, .. } => {
+            let node = ast_id.to_node(db.upcast());
+            (
+                ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))),
+                node.path()
+                    .and_then(|it| it.segment())
+                    .and_then(|it| it.name_ref())
+                    .map(|it| it.syntax().text_range()),
+                node.path().and_then(|it| it.segment()).map(|it| it.to_string()),
+                MacroKind::ProcMacro,
+            )
+        }
+        MacroCallKind::Derive { ast_id, derive_attr_index, derive_index, .. } => {
+            let node = ast_id.to_node(db.upcast());
+            // Compute the precise location of the macro name's token in the derive
+            // list.
+            let token = (|| {
+                let derive_attr = collect_attrs(&node)
+                    .nth(derive_attr_index.ast_index())
+                    .and_then(|x| Either::left(x.1))?;
+                let token_tree = derive_attr.meta()?.token_tree()?;
+                let group_by = token_tree
+                    .syntax()
+                    .children_with_tokens()
+                    .filter_map(|elem| match elem {
+                        syntax::NodeOrToken::Token(tok) => Some(tok),
+                        _ => None,
+                    })
+                    .group_by(|t| t.kind() == T![,]);
+                let (_, mut group) = group_by
+                    .into_iter()
+                    .filter(|&(comma, _)| !comma)
+                    .nth(*derive_index as usize)?;
+                group.find(|t| t.kind() == T![ident])
+            })();
+            (
+                ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&node))),
+                token.as_ref().map(|tok| tok.text_range()),
+                token.as_ref().map(ToString::to_string),
+                MacroKind::Derive,
+            )
+        }
+        MacroCallKind::Attr { ast_id, invoc_attr_index, .. } => {
+            let node = ast_id.to_node(db.upcast());
+            let attr = collect_attrs(&node)
+                .nth(invoc_attr_index.ast_index())
+                .and_then(|x| Either::left(x.1))
+                .unwrap_or_else(|| {
+                    panic!("cannot find attribute #{}", invoc_attr_index.ast_index())
+                });
+
+            (
+                ast_id.with_value(SyntaxNodePtr::from(AstPtr::new(&attr))),
+                Some(attr.syntax().text_range()),
+                attr.path()
+                    .and_then(|path| path.segment())
+                    .and_then(|seg| seg.name_ref())
+                    .as_ref()
+                    .map(ToString::to_string),
+                MacroKind::Attr,
+            )
+        }
+    }
+}
+
+impl HasVisibility for Module {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        let def_map = self.id.def_map(db.upcast());
+        let module_data = &def_map[self.id.local_id];
+        module_data.visibility
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct Field {
+    pub(crate) parent: VariantDef,
+    pub(crate) id: LocalFieldId,
+}
+
+#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)]
+pub struct TupleField {
+    pub owner: DefWithBodyId,
+    pub tuple: TupleId,
+    pub index: u32,
+}
+
+impl TupleField {
+    pub fn name(&self) -> Name {
+        Name::new_tuple_field(self.index as usize)
+    }
+
+    pub fn ty(&self, db: &dyn HirDatabase) -> Type {
+        let ty = db.infer(self.owner).tuple_field_access_types[&self.tuple]
+            .as_slice(Interner)
+            .get(self.index as usize)
+            .and_then(|arg| arg.ty(Interner))
+            .cloned()
+            .unwrap_or_else(|| TyKind::Error.intern(Interner));
+        Type { env: db.trait_environment_for_body(self.owner), ty }
+    }
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub enum FieldSource {
+    Named(ast::RecordField),
+    Pos(ast::TupleField),
+}
+
+impl Field {
+    pub fn name(&self, db: &dyn HirDatabase) -> Name {
+        self.parent.variant_data(db).fields()[self.id].name.clone()
+    }
+
+    pub fn index(&self) -> usize {
+        u32::from(self.id.into_raw()) as usize
+    }
+
+    /// Returns the type as in the signature of the struct (i.e., with
+    /// placeholder types for type parameters). Only use this in the context of
+    /// the field definition.
+    pub fn ty(&self, db: &dyn HirDatabase) -> Type {
+        let var_id = self.parent.into();
+        let generic_def_id: GenericDefId = match self.parent {
+            VariantDef::Struct(it) => it.id.into(),
+            VariantDef::Union(it) => it.id.into(),
+            VariantDef::Variant(it) => it.id.into(),
+        };
+        let substs = TyBuilder::placeholder_subst(db, generic_def_id);
+        let ty = db.field_types(var_id)[self.id].clone().substitute(Interner, &substs);
+        Type::new(db, var_id, ty)
+    }
+
+    // FIXME: Find better API to also handle const generics
+    pub fn ty_with_args(&self, db: &dyn HirDatabase, generics: impl Iterator<Item = Type>) -> Type {
+        let var_id = self.parent.into();
+        let def_id: AdtId = match self.parent {
+            VariantDef::Struct(it) => it.id.into(),
+            VariantDef::Union(it) => it.id.into(),
+            VariantDef::Variant(it) => it.parent_enum(db).id.into(),
+        };
+        let mut generics = generics.map(|it| it.ty);
+        let substs = TyBuilder::subst_for_def(db, def_id, None)
+            .fill(|x| match x {
+                ParamKind::Type => {
+                    generics.next().unwrap_or_else(|| TyKind::Error.intern(Interner)).cast(Interner)
+                }
+                ParamKind::Const(ty) => unknown_const_as_generic(ty.clone()),
+                ParamKind::Lifetime => error_lifetime().cast(Interner),
+            })
+            .build();
+        let ty = db.field_types(var_id)[self.id].clone().substitute(Interner, &substs);
+        Type::new(db, var_id, ty)
+    }
+
+    pub fn layout(&self, db: &dyn HirDatabase) -> Result<Layout, LayoutError> {
+        db.layout_of_ty(
+            self.ty(db).ty,
+            db.trait_environment(match hir_def::VariantId::from(self.parent) {
+                hir_def::VariantId::EnumVariantId(id) => GenericDefId::EnumVariantId(id),
+                hir_def::VariantId::StructId(id) => GenericDefId::AdtId(id.into()),
+                hir_def::VariantId::UnionId(id) => GenericDefId::AdtId(id.into()),
+            }),
+        )
+        .map(|layout| Layout(layout, db.target_data_layout(self.krate(db).into()).unwrap()))
+    }
+
+    pub fn parent_def(&self, _db: &dyn HirDatabase) -> VariantDef {
+        self.parent
+    }
+}
+
+impl HasVisibility for Field {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        let variant_data = self.parent.variant_data(db);
+        let visibility = &variant_data.fields()[self.id].visibility;
+        let parent_id: hir_def::VariantId = self.parent.into();
+        visibility.resolve(db.upcast(), &parent_id.resolver(db.upcast()))
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct Struct {
+    pub(crate) id: StructId,
+}
+
+impl Struct {
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        Module { id: self.id.lookup(db.upcast()).container }
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        db.struct_data(self.id).name.clone()
+    }
+
+    pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
+        db.struct_data(self.id)
+            .variant_data
+            .fields()
+            .iter()
+            .map(|(id, _)| Field { parent: self.into(), id })
+            .collect()
+    }
+
+    pub fn ty(self, db: &dyn HirDatabase) -> Type {
+        Type::from_def(db, self.id)
+    }
+
+    pub fn constructor_ty(self, db: &dyn HirDatabase) -> Type {
+        Type::from_value_def(db, self.id)
+    }
+
+    pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprOptions> {
+        db.struct_data(self.id).repr
+    }
+
+    pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
+        self.variant_data(db).kind()
+    }
+
+    fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
+        db.struct_data(self.id).variant_data.clone()
+    }
+
+    pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
+        db.attrs(self.id.into()).is_unstable()
+    }
+}
+
+impl HasVisibility for Struct {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct Union {
+    pub(crate) id: UnionId,
+}
+
+impl Union {
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        db.union_data(self.id).name.clone()
+    }
+
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        Module { id: self.id.lookup(db.upcast()).container }
+    }
+
+    pub fn ty(self, db: &dyn HirDatabase) -> Type {
+        Type::from_def(db, self.id)
+    }
+
+    pub fn constructor_ty(self, db: &dyn HirDatabase) -> Type {
+        Type::from_value_def(db, self.id)
+    }
+
+    pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
+        db.union_data(self.id)
+            .variant_data
+            .fields()
+            .iter()
+            .map(|(id, _)| Field { parent: self.into(), id })
+            .collect()
+    }
+
+    fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
+        db.union_data(self.id).variant_data.clone()
+    }
+
+    pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
+        db.attrs(self.id.into()).is_unstable()
+    }
+}
+
+impl HasVisibility for Union {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct Enum {
+    pub(crate) id: EnumId,
+}
+
+impl Enum {
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        Module { id: self.id.lookup(db.upcast()).container }
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        db.enum_data(self.id).name.clone()
+    }
+
+    pub fn variants(self, db: &dyn HirDatabase) -> Vec<Variant> {
+        db.enum_data(self.id).variants.iter().map(|&(id, _)| Variant { id }).collect()
+    }
+
+    pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprOptions> {
+        db.enum_data(self.id).repr
+    }
+
+    pub fn ty(self, db: &dyn HirDatabase) -> Type {
+        Type::from_def(db, self.id)
+    }
+
+    /// The type of the enum variant bodies.
+    pub fn variant_body_ty(self, db: &dyn HirDatabase) -> Type {
+        Type::new_for_crate(
+            self.id.lookup(db.upcast()).container.krate(),
+            TyBuilder::builtin(match db.enum_data(self.id).variant_body_type() {
+                layout::IntegerType::Pointer(sign) => match sign {
+                    true => hir_def::builtin_type::BuiltinType::Int(
+                        hir_def::builtin_type::BuiltinInt::Isize,
+                    ),
+                    false => hir_def::builtin_type::BuiltinType::Uint(
+                        hir_def::builtin_type::BuiltinUint::Usize,
+                    ),
+                },
+                layout::IntegerType::Fixed(i, sign) => match sign {
+                    true => hir_def::builtin_type::BuiltinType::Int(match i {
+                        layout::Integer::I8 => hir_def::builtin_type::BuiltinInt::I8,
+                        layout::Integer::I16 => hir_def::builtin_type::BuiltinInt::I16,
+                        layout::Integer::I32 => hir_def::builtin_type::BuiltinInt::I32,
+                        layout::Integer::I64 => hir_def::builtin_type::BuiltinInt::I64,
+                        layout::Integer::I128 => hir_def::builtin_type::BuiltinInt::I128,
+                    }),
+                    false => hir_def::builtin_type::BuiltinType::Uint(match i {
+                        layout::Integer::I8 => hir_def::builtin_type::BuiltinUint::U8,
+                        layout::Integer::I16 => hir_def::builtin_type::BuiltinUint::U16,
+                        layout::Integer::I32 => hir_def::builtin_type::BuiltinUint::U32,
+                        layout::Integer::I64 => hir_def::builtin_type::BuiltinUint::U64,
+                        layout::Integer::I128 => hir_def::builtin_type::BuiltinUint::U128,
+                    }),
+                },
+            }),
+        )
+    }
+
+    /// Returns true if at least one variant of this enum is a non-unit variant.
+    pub fn is_data_carrying(self, db: &dyn HirDatabase) -> bool {
+        self.variants(db).iter().any(|v| !matches!(v.kind(db), StructKind::Unit))
+    }
+
+    pub fn layout(self, db: &dyn HirDatabase) -> Result<Layout, LayoutError> {
+        Adt::from(self).layout(db)
+    }
+
+    pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
+        db.attrs(self.id.into()).is_unstable()
+    }
+}
+
+impl HasVisibility for Enum {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
+    }
+}
+
+impl From<&Variant> for DefWithBodyId {
+    fn from(&v: &Variant) -> Self {
+        DefWithBodyId::VariantId(v.into())
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct Variant {
+    pub(crate) id: EnumVariantId,
+}
+
+impl Variant {
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        Module { id: self.id.module(db.upcast()) }
+    }
+
+    pub fn parent_enum(self, db: &dyn HirDatabase) -> Enum {
+        self.id.lookup(db.upcast()).parent.into()
+    }
+
+    pub fn constructor_ty(self, db: &dyn HirDatabase) -> Type {
+        Type::from_value_def(db, self.id)
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        db.enum_variant_data(self.id).name.clone()
+    }
+
+    pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
+        self.variant_data(db)
+            .fields()
+            .iter()
+            .map(|(id, _)| Field { parent: self.into(), id })
+            .collect()
+    }
+
+    pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
+        self.variant_data(db).kind()
+    }
+
+    pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
+        db.enum_variant_data(self.id).variant_data.clone()
+    }
+
+    pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
+        self.source(db)?.value.expr()
+    }
+
+    pub fn eval(self, db: &dyn HirDatabase) -> Result<i128, ConstEvalError> {
+        db.const_eval_discriminant(self.into())
+    }
+
+    pub fn layout(&self, db: &dyn HirDatabase) -> Result<Layout, LayoutError> {
+        let parent_enum = self.parent_enum(db);
+        let parent_layout = parent_enum.layout(db)?;
+        Ok(match &parent_layout.0.variants {
+            layout::Variants::Multiple { variants, .. } => Layout(
+                {
+                    let lookup = self.id.lookup(db.upcast());
+                    let rustc_enum_variant_idx = RustcEnumVariantIdx(lookup.index as usize);
+                    Arc::new(variants[rustc_enum_variant_idx].clone())
+                },
+                db.target_data_layout(parent_enum.krate(db).into()).unwrap(),
+            ),
+            _ => parent_layout,
+        })
+    }
+
+    pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
+        db.attrs(self.id.into()).is_unstable()
+    }
+}
+
+/// Variants inherit visibility from the parent enum.
+impl HasVisibility for Variant {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        self.parent_enum(db).visibility(db)
+    }
+}
+
+/// A Data Type
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Adt {
+    Struct(Struct),
+    Union(Union),
+    Enum(Enum),
+}
+impl_from!(Struct, Union, Enum for Adt);
+
+impl Adt {
+    pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
+        let subst = db.generic_defaults(self.into());
+        subst.iter().any(|ty| match ty.skip_binders().data(Interner) {
+            GenericArgData::Ty(it) => it.is_unknown(),
+            _ => false,
+        })
+    }
+
+    pub fn layout(self, db: &dyn HirDatabase) -> Result<Layout, LayoutError> {
+        db.layout_of_adt(
+            self.into(),
+            TyBuilder::adt(db, self.into())
+                .fill_with_defaults(db, || TyKind::Error.intern(Interner))
+                .build_into_subst(),
+            db.trait_environment(self.into()),
+        )
+        .map(|layout| Layout(layout, db.target_data_layout(self.krate(db).id).unwrap()))
+    }
+
+    /// Turns this ADT into a type. Any type parameters of the ADT will be
+    /// turned into unknown types, which is good for e.g. finding the most
+    /// general set of completions, but will not look very nice when printed.
+    pub fn ty(self, db: &dyn HirDatabase) -> Type {
+        let id = AdtId::from(self);
+        Type::from_def(db, id)
+    }
+
+    /// Turns this ADT into a type with the given type parameters. This isn't
+    /// the greatest API, FIXME find a better one.
+    pub fn ty_with_args(self, db: &dyn HirDatabase, args: impl Iterator<Item = Type>) -> Type {
+        let id = AdtId::from(self);
+        let mut it = args.map(|t| t.ty);
+        let ty = TyBuilder::def_ty(db, id.into(), None)
+            .fill(|x| {
+                let r = it.next().unwrap_or_else(|| TyKind::Error.intern(Interner));
+                match x {
+                    ParamKind::Type => r.cast(Interner),
+                    ParamKind::Const(ty) => unknown_const_as_generic(ty.clone()),
+                    ParamKind::Lifetime => error_lifetime().cast(Interner),
+                }
+            })
+            .build();
+        Type::new(db, id, ty)
+    }
+
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        match self {
+            Adt::Struct(s) => s.module(db),
+            Adt::Union(s) => s.module(db),
+            Adt::Enum(e) => e.module(db),
+        }
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        match self {
+            Adt::Struct(s) => s.name(db),
+            Adt::Union(u) => u.name(db),
+            Adt::Enum(e) => e.name(db),
+        }
+    }
+
+    /// Returns the lifetime of the DataType
+    pub fn lifetime(&self, db: &dyn HirDatabase) -> Option<LifetimeParamData> {
+        let resolver = match self {
+            Adt::Struct(s) => s.id.resolver(db.upcast()),
+            Adt::Union(u) => u.id.resolver(db.upcast()),
+            Adt::Enum(e) => e.id.resolver(db.upcast()),
+        };
+        resolver
+            .generic_params()
+            .and_then(|gp| {
+                gp.lifetimes
+                    .iter()
+                    // there should only be a single lifetime
+                    // but `Arena` requires to use an iterator
+                    .nth(0)
+            })
+            .map(|arena| arena.1.clone())
+    }
+
+    pub fn as_enum(&self) -> Option<Enum> {
+        if let Self::Enum(v) = self {
+            Some(*v)
+        } else {
+            None
+        }
+    }
+}
+
+impl HasVisibility for Adt {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        match self {
+            Adt::Struct(it) => it.visibility(db),
+            Adt::Union(it) => it.visibility(db),
+            Adt::Enum(it) => it.visibility(db),
+        }
+    }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum VariantDef {
+    Struct(Struct),
+    Union(Union),
+    Variant(Variant),
+}
+impl_from!(Struct, Union, Variant for VariantDef);
+
+impl VariantDef {
+    pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
+        match self {
+            VariantDef::Struct(it) => it.fields(db),
+            VariantDef::Union(it) => it.fields(db),
+            VariantDef::Variant(it) => it.fields(db),
+        }
+    }
+
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        match self {
+            VariantDef::Struct(it) => it.module(db),
+            VariantDef::Union(it) => it.module(db),
+            VariantDef::Variant(it) => it.module(db),
+        }
+    }
+
+    pub fn name(&self, db: &dyn HirDatabase) -> Name {
+        match self {
+            VariantDef::Struct(s) => s.name(db),
+            VariantDef::Union(u) => u.name(db),
+            VariantDef::Variant(e) => e.name(db),
+        }
+    }
+
+    pub(crate) fn variant_data(self, db: &dyn HirDatabase) -> Arc<VariantData> {
+        match self {
+            VariantDef::Struct(it) => it.variant_data(db),
+            VariantDef::Union(it) => it.variant_data(db),
+            VariantDef::Variant(it) => it.variant_data(db),
+        }
+    }
+}
+
+/// The defs which have a body.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum DefWithBody {
+    Function(Function),
+    Static(Static),
+    Const(Const),
+    Variant(Variant),
+    InTypeConst(InTypeConst),
+}
+impl_from!(Function, Const, Static, Variant, InTypeConst for DefWithBody);
+
+impl DefWithBody {
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        match self {
+            DefWithBody::Const(c) => c.module(db),
+            DefWithBody::Function(f) => f.module(db),
+            DefWithBody::Static(s) => s.module(db),
+            DefWithBody::Variant(v) => v.module(db),
+            DefWithBody::InTypeConst(c) => c.module(db),
+        }
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
+        match self {
+            DefWithBody::Function(f) => Some(f.name(db)),
+            DefWithBody::Static(s) => Some(s.name(db)),
+            DefWithBody::Const(c) => c.name(db),
+            DefWithBody::Variant(v) => Some(v.name(db)),
+            DefWithBody::InTypeConst(_) => None,
+        }
+    }
+
+    /// Returns the type this def's body has to evaluate to.
+    pub fn body_type(self, db: &dyn HirDatabase) -> Type {
+        match self {
+            DefWithBody::Function(it) => it.ret_type(db),
+            DefWithBody::Static(it) => it.ty(db),
+            DefWithBody::Const(it) => it.ty(db),
+            DefWithBody::Variant(it) => it.parent_enum(db).variant_body_ty(db),
+            DefWithBody::InTypeConst(it) => Type::new_with_resolver_inner(
+                db,
+                &DefWithBodyId::from(it.id).resolver(db.upcast()),
+                TyKind::Error.intern(Interner),
+            ),
+        }
+    }
+
+    fn id(&self) -> DefWithBodyId {
+        match self {
+            DefWithBody::Function(it) => it.id.into(),
+            DefWithBody::Static(it) => it.id.into(),
+            DefWithBody::Const(it) => it.id.into(),
+            DefWithBody::Variant(it) => it.into(),
+            DefWithBody::InTypeConst(it) => it.id.into(),
+        }
+    }
+
+    /// A textual representation of the HIR of this def's body for debugging purposes.
+    pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
+        let body = db.body(self.id());
+        body.pretty_print(db.upcast(), self.id())
+    }
+
+    /// A textual representation of the MIR of this def's body for debugging purposes.
+    pub fn debug_mir(self, db: &dyn HirDatabase) -> String {
+        let body = db.mir_body(self.id());
+        match body {
+            Ok(body) => body.pretty_print(db),
+            Err(e) => format!("error:\n{e:?}"),
+        }
+    }
+
+    pub fn diagnostics(
+        self,
+        db: &dyn HirDatabase,
+        acc: &mut Vec<AnyDiagnostic>,
+        style_lints: bool,
+    ) {
+        let krate = self.module(db).id.krate();
+
+        let (body, source_map) = db.body_with_source_map(self.into());
+
+        for (_, def_map) in body.blocks(db.upcast()) {
+            Module { id: def_map.module_id(DefMap::ROOT) }.diagnostics(db, acc, style_lints);
+        }
+
+        for diag in source_map.diagnostics() {
+            acc.push(match diag {
+                BodyDiagnostic::InactiveCode { node, cfg, opts } => {
+                    InactiveCode { node: *node, cfg: cfg.clone(), opts: opts.clone() }.into()
+                }
+                BodyDiagnostic::MacroError { node, message } => MacroError {
+                    node: (*node).map(|it| it.into()),
+                    precise_location: None,
+                    message: message.to_string(),
+                }
+                .into(),
+                BodyDiagnostic::UnresolvedProcMacro { node, krate } => UnresolvedProcMacro {
+                    node: (*node).map(|it| it.into()),
+                    precise_location: None,
+                    macro_name: None,
+                    kind: MacroKind::ProcMacro,
+                    krate: *krate,
+                }
+                .into(),
+                BodyDiagnostic::UnresolvedMacroCall { node, path } => UnresolvedMacroCall {
+                    macro_call: (*node).map(|ast_ptr| ast_ptr.into()),
+                    precise_location: None,
+                    path: path.clone(),
+                    is_bang: true,
+                }
+                .into(),
+                BodyDiagnostic::UnreachableLabel { node, name } => {
+                    UnreachableLabel { node: *node, name: name.clone() }.into()
+                }
+                BodyDiagnostic::UndeclaredLabel { node, name } => {
+                    UndeclaredLabel { node: *node, name: name.clone() }.into()
+                }
+            });
+        }
+
+        let infer = db.infer(self.into());
+        for d in &infer.diagnostics {
+            acc.extend(AnyDiagnostic::inference_diagnostic(db, self.into(), d, &source_map));
+        }
+
+        for (pat_or_expr, mismatch) in infer.type_mismatches() {
+            let expr_or_pat = match pat_or_expr {
+                ExprOrPatId::ExprId(expr) => source_map.expr_syntax(expr).map(Either::Left),
+                ExprOrPatId::PatId(pat) => source_map.pat_syntax(pat).map(Either::Right),
+            };
+            let expr_or_pat = match expr_or_pat {
+                Ok(Either::Left(expr)) => expr.map(AstPtr::wrap_left),
+                Ok(Either::Right(InFile { file_id, value: pat })) => {
+                    // cast from Either<Pat, SelfParam> -> Either<_, Pat>
+                    let Some(ptr) = AstPtr::try_from_raw(pat.syntax_node_ptr()) else {
+                        continue;
+                    };
+                    InFile { file_id, value: ptr }
+                }
+                Err(SyntheticSyntax) => continue,
+            };
+
+            acc.push(
+                TypeMismatch {
+                    expr_or_pat,
+                    expected: Type::new(db, DefWithBodyId::from(self), mismatch.expected.clone()),
+                    actual: Type::new(db, DefWithBodyId::from(self), mismatch.actual.clone()),
+                }
+                .into(),
+            );
+        }
+
+        for expr in hir_ty::diagnostics::missing_unsafe(db, self.into()) {
+            match source_map.expr_syntax(expr) {
+                Ok(expr) => acc.push(MissingUnsafe { expr }.into()),
+                Err(SyntheticSyntax) => {
+                    // FIXME: Here and elsewhere in this file, the `expr` was
+                    // desugared, report or assert that this doesn't happen.
+                }
+            }
+        }
+
+        if let Ok(borrowck_results) = db.borrowck(self.into()) {
+            for borrowck_result in borrowck_results.iter() {
+                let mir_body = &borrowck_result.mir_body;
+                for moof in &borrowck_result.moved_out_of_ref {
+                    let span: InFile<SyntaxNodePtr> = match moof.span {
+                        mir::MirSpan::ExprId(e) => match source_map.expr_syntax(e) {
+                            Ok(s) => s.map(|it| it.into()),
+                            Err(_) => continue,
+                        },
+                        mir::MirSpan::PatId(p) => match source_map.pat_syntax(p) {
+                            Ok(s) => s.map(|it| it.into()),
+                            Err(_) => continue,
+                        },
+                        mir::MirSpan::SelfParam => match source_map.self_param_syntax() {
+                            Some(s) => s.map(|it| it.into()),
+                            None => continue,
+                        },
+                        mir::MirSpan::Unknown => continue,
+                    };
+                    acc.push(
+                        MovedOutOfRef { ty: Type::new_for_crate(krate, moof.ty.clone()), span }
+                            .into(),
+                    )
+                }
+                let mol = &borrowck_result.mutability_of_locals;
+                for (binding_id, binding_data) in body.bindings.iter() {
+                    if binding_data.problems.is_some() {
+                        // We should report specific diagnostics for these problems, not `need-mut` and `unused-mut`.
+                        continue;
+                    }
+                    let Some(&local) = mir_body.binding_locals.get(binding_id) else {
+                        continue;
+                    };
+                    if body[binding_id]
+                        .definitions
+                        .iter()
+                        .any(|&pat| source_map.pat_syntax(pat).is_err())
+                    {
+                        // Skip synthetic bindings
+                        continue;
+                    }
+                    let mut need_mut = &mol[local];
+                    if body[binding_id].name.as_str() == Some("self")
+                        && need_mut == &mir::MutabilityReason::Unused
+                    {
+                        need_mut = &mir::MutabilityReason::Not;
+                    }
+                    let local = Local { parent: self.into(), binding_id };
+                    let is_mut = body[binding_id].mode == BindingAnnotation::Mutable;
+
+                    match (need_mut, is_mut) {
+                        (mir::MutabilityReason::Unused, _) => {
+                            let should_ignore = matches!(body[binding_id].name.as_str(), Some(it) if it.starts_with('_'));
+                            if !should_ignore {
+                                acc.push(UnusedVariable { local }.into())
+                            }
+                        }
+                        (mir::MutabilityReason::Mut { .. }, true)
+                        | (mir::MutabilityReason::Not, false) => (),
+                        (mir::MutabilityReason::Mut { spans }, false) => {
+                            for span in spans {
+                                let span: InFile<SyntaxNodePtr> = match span {
+                                    mir::MirSpan::ExprId(e) => match source_map.expr_syntax(*e) {
+                                        Ok(s) => s.map(|it| it.into()),
+                                        Err(_) => continue,
+                                    },
+                                    mir::MirSpan::PatId(p) => match source_map.pat_syntax(*p) {
+                                        Ok(s) => s.map(|it| it.into()),
+                                        Err(_) => continue,
+                                    },
+                                    mir::MirSpan::SelfParam => match source_map.self_param_syntax()
+                                    {
+                                        Some(s) => s.map(|it| it.into()),
+                                        None => continue,
+                                    },
+                                    mir::MirSpan::Unknown => continue,
+                                };
+                                acc.push(NeedMut { local, span }.into());
+                            }
+                        }
+                        (mir::MutabilityReason::Not, true) => {
+                            if !infer.mutated_bindings_in_closure.contains(&binding_id) {
+                                let should_ignore = matches!(body[binding_id].name.as_str(), Some(it) if it.starts_with('_'));
+                                if !should_ignore {
+                                    acc.push(UnusedMut { local }.into())
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+        }
+
+        for diagnostic in BodyValidationDiagnostic::collect(db, self.into(), style_lints) {
+            acc.extend(AnyDiagnostic::body_validation_diagnostic(db, diagnostic, &source_map));
+        }
+
+        let def: ModuleDef = match self {
+            DefWithBody::Function(it) => it.into(),
+            DefWithBody::Static(it) => it.into(),
+            DefWithBody::Const(it) => it.into(),
+            DefWithBody::Variant(it) => it.into(),
+            // FIXME: don't ignore diagnostics for in type const
+            DefWithBody::InTypeConst(_) => return,
+        };
+        for diag in hir_ty::diagnostics::incorrect_case(db, def.into()) {
+            acc.push(diag.into())
+        }
+    }
+}
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct Function {
+    pub(crate) id: FunctionId,
+}
+
+impl Function {
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        self.id.module(db.upcast()).into()
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        db.function_data(self.id).name.clone()
+    }
+
+    pub fn ty(self, db: &dyn HirDatabase) -> Type {
+        Type::from_value_def(db, self.id)
+    }
+
+    /// Get this function's return type
+    pub fn ret_type(self, db: &dyn HirDatabase) -> Type {
+        let resolver = self.id.resolver(db.upcast());
+        let substs = TyBuilder::placeholder_subst(db, self.id);
+        let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
+        let ty = callable_sig.ret().clone();
+        Type::new_with_resolver_inner(db, &resolver, ty)
+    }
+
+    // FIXME: Find better API to also handle const generics
+    pub fn ret_type_with_args(
+        self,
+        db: &dyn HirDatabase,
+        generics: impl Iterator<Item = Type>,
+    ) -> Type {
+        let resolver = self.id.resolver(db.upcast());
+        let parent_id: Option<GenericDefId> = match self.id.lookup(db.upcast()).container {
+            ItemContainerId::ImplId(it) => Some(it.into()),
+            ItemContainerId::TraitId(it) => Some(it.into()),
+            ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
+        };
+        let mut generics = generics.map(|it| it.ty);
+        let mut filler = |x: &_| match x {
+            ParamKind::Type => {
+                generics.next().unwrap_or_else(|| TyKind::Error.intern(Interner)).cast(Interner)
+            }
+            ParamKind::Const(ty) => unknown_const_as_generic(ty.clone()),
+            ParamKind::Lifetime => error_lifetime().cast(Interner),
+        };
+
+        let parent_substs =
+            parent_id.map(|id| TyBuilder::subst_for_def(db, id, None).fill(&mut filler).build());
+        let substs = TyBuilder::subst_for_def(db, self.id, parent_substs).fill(&mut filler).build();
+
+        let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
+        let ty = callable_sig.ret().clone();
+        Type::new_with_resolver_inner(db, &resolver, ty)
+    }
+
+    pub fn async_ret_type(self, db: &dyn HirDatabase) -> Option<Type> {
+        if !self.is_async(db) {
+            return None;
+        }
+        let resolver = self.id.resolver(db.upcast());
+        let substs = TyBuilder::placeholder_subst(db, self.id);
+        let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
+        let ret_ty = callable_sig.ret().clone();
+        for pred in ret_ty.impl_trait_bounds(db).into_iter().flatten() {
+            if let WhereClause::AliasEq(output_eq) = pred.into_value_and_skipped_binders().0 {
+                return Type::new_with_resolver_inner(db, &resolver, output_eq.ty).into();
+            }
+        }
+        never!("Async fn ret_type should be impl Future");
+        None
+    }
+
+    pub fn has_self_param(self, db: &dyn HirDatabase) -> bool {
+        db.function_data(self.id).has_self_param()
+    }
+
+    pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
+        self.has_self_param(db).then_some(SelfParam { func: self.id })
+    }
+
+    pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param> {
+        let environment = db.trait_environment(self.id.into());
+        let substs = TyBuilder::placeholder_subst(db, self.id);
+        let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
+        callable_sig
+            .params()
+            .iter()
+            .enumerate()
+            .map(|(idx, ty)| {
+                let ty = Type { env: environment.clone(), ty: ty.clone() };
+                Param { func: self, ty, idx }
+            })
+            .collect()
+    }
+
+    pub fn num_params(self, db: &dyn HirDatabase) -> usize {
+        db.function_data(self.id).params.len()
+    }
+
+    pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param>> {
+        self.self_param(db)?;
+        Some(self.params_without_self(db))
+    }
+
+    pub fn params_without_self(self, db: &dyn HirDatabase) -> Vec<Param> {
+        let environment = db.trait_environment(self.id.into());
+        let substs = TyBuilder::placeholder_subst(db, self.id);
+        let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
+        let skip = if db.function_data(self.id).has_self_param() { 1 } else { 0 };
+        callable_sig
+            .params()
+            .iter()
+            .enumerate()
+            .skip(skip)
+            .map(|(idx, ty)| {
+                let ty = Type { env: environment.clone(), ty: ty.clone() };
+                Param { func: self, ty, idx }
+            })
+            .collect()
+    }
+
+    // FIXME: Find better API to also handle const generics
+    pub fn params_without_self_with_args(
+        self,
+        db: &dyn HirDatabase,
+        generics: impl Iterator<Item = Type>,
+    ) -> Vec<Param> {
+        let environment = db.trait_environment(self.id.into());
+        let parent_id: Option<GenericDefId> = match self.id.lookup(db.upcast()).container {
+            ItemContainerId::ImplId(it) => Some(it.into()),
+            ItemContainerId::TraitId(it) => Some(it.into()),
+            ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
+        };
+        let mut generics = generics.map(|it| it.ty);
+        let parent_substs = parent_id.map(|id| {
+            TyBuilder::subst_for_def(db, id, None)
+                .fill(|x| match x {
+                    ParamKind::Type => generics
+                        .next()
+                        .unwrap_or_else(|| TyKind::Error.intern(Interner))
+                        .cast(Interner),
+                    ParamKind::Const(ty) => unknown_const_as_generic(ty.clone()),
+                    ParamKind::Lifetime => error_lifetime().cast(Interner),
+                })
+                .build()
+        });
+
+        let substs = TyBuilder::subst_for_def(db, self.id, parent_substs)
+            .fill(|_| {
+                let ty = generics.next().unwrap_or_else(|| TyKind::Error.intern(Interner));
+                GenericArg::new(Interner, GenericArgData::Ty(ty))
+            })
+            .build();
+        let callable_sig = db.callable_item_signature(self.id.into()).substitute(Interner, &substs);
+        let skip = if db.function_data(self.id).has_self_param() { 1 } else { 0 };
+        callable_sig
+            .params()
+            .iter()
+            .enumerate()
+            .skip(skip)
+            .map(|(idx, ty)| {
+                let ty = Type { env: environment.clone(), ty: ty.clone() };
+                Param { func: self, ty, idx }
+            })
+            .collect()
+    }
+
+    pub fn is_const(self, db: &dyn HirDatabase) -> bool {
+        db.function_data(self.id).has_const_kw()
+    }
+
+    pub fn is_async(self, db: &dyn HirDatabase) -> bool {
+        db.function_data(self.id).has_async_kw()
+    }
+
+    /// Does this function have `#[test]` attribute?
+    pub fn is_test(self, db: &dyn HirDatabase) -> bool {
+        db.function_data(self.id).attrs.is_test()
+    }
+
+    /// is this a `fn main` or a function with an `export_name` of `main`?
+    pub fn is_main(self, db: &dyn HirDatabase) -> bool {
+        let data = db.function_data(self.id);
+        data.attrs.export_name() == Some("main")
+            || self.module(db).is_crate_root() && data.name.to_smol_str() == "main"
+    }
+
+    /// Is this a function with an `export_name` of `main`?
+    pub fn exported_main(self, db: &dyn HirDatabase) -> bool {
+        let data = db.function_data(self.id);
+        data.attrs.export_name() == Some("main")
+    }
+
+    /// Does this function have the ignore attribute?
+    pub fn is_ignore(self, db: &dyn HirDatabase) -> bool {
+        db.function_data(self.id).attrs.is_ignore()
+    }
+
+    /// Does this function have `#[bench]` attribute?
+    pub fn is_bench(self, db: &dyn HirDatabase) -> bool {
+        db.function_data(self.id).attrs.is_bench()
+    }
+
+    /// Is this function marked as unstable with `#[feature]` attribute?
+    pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
+        db.function_data(self.id).attrs.is_unstable()
+    }
+
+    pub fn is_unsafe_to_call(self, db: &dyn HirDatabase) -> bool {
+        hir_ty::is_fn_unsafe_to_call(db, self.id)
+    }
+
+    /// Whether this function declaration has a definition.
+    ///
+    /// This is false in the case of required (not provided) trait methods.
+    pub fn has_body(self, db: &dyn HirDatabase) -> bool {
+        db.function_data(self.id).has_body()
+    }
+
+    pub fn as_proc_macro(self, db: &dyn HirDatabase) -> Option<Macro> {
+        let function_data = db.function_data(self.id);
+        let attrs = &function_data.attrs;
+        // FIXME: Store this in FunctionData flags?
+        if !(attrs.is_proc_macro()
+            || attrs.is_proc_macro_attribute()
+            || attrs.is_proc_macro_derive())
+        {
+            return None;
+        }
+        let def_map = db.crate_def_map(HasModule::krate(&self.id, db.upcast()));
+        def_map.fn_as_proc_macro(self.id).map(|id| Macro { id: id.into() })
+    }
+
+    pub fn eval(
+        self,
+        db: &dyn HirDatabase,
+        span_formatter: impl Fn(FileId, TextRange) -> String,
+    ) -> String {
+        let body = match db.monomorphized_mir_body(
+            self.id.into(),
+            Substitution::empty(Interner),
+            db.trait_environment(self.id.into()),
+        ) {
+            Ok(body) => body,
+            Err(e) => {
+                let mut r = String::new();
+                _ = e.pretty_print(&mut r, db, &span_formatter);
+                return r;
+            }
+        };
+        let (result, output) = interpret_mir(db, body, false, None);
+        let mut text = match result {
+            Ok(_) => "pass".to_owned(),
+            Err(e) => {
+                let mut r = String::new();
+                _ = e.pretty_print(&mut r, db, &span_formatter);
+                r
+            }
+        };
+        let stdout = output.stdout().into_owned();
+        if !stdout.is_empty() {
+            text += "\n--------- stdout ---------\n";
+            text += &stdout;
+        }
+        let stderr = output.stdout().into_owned();
+        if !stderr.is_empty() {
+            text += "\n--------- stderr ---------\n";
+            text += &stderr;
+        }
+        text
+    }
+}
+
+// Note: logically, this belongs to `hir_ty`, but we are not using it there yet.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum Access {
+    Shared,
+    Exclusive,
+    Owned,
+}
+
+impl From<hir_ty::Mutability> for Access {
+    fn from(mutability: hir_ty::Mutability) -> Access {
+        match mutability {
+            hir_ty::Mutability::Not => Access::Shared,
+            hir_ty::Mutability::Mut => Access::Exclusive,
+        }
+    }
+}
+
+#[derive(Clone, PartialEq, Eq, Hash, Debug)]
+pub struct Param {
+    func: Function,
+    /// The index in parameter list, including self parameter.
+    idx: usize,
+    ty: Type,
+}
+
+impl Param {
+    pub fn parent_fn(&self) -> Function {
+        self.func
+    }
+
+    pub fn index(&self) -> usize {
+        self.idx
+    }
+
+    pub fn ty(&self) -> &Type {
+        &self.ty
+    }
+
+    pub fn name(&self, db: &dyn HirDatabase) -> Option<Name> {
+        Some(self.as_local(db)?.name(db))
+    }
+
+    pub fn as_local(&self, db: &dyn HirDatabase) -> Option<Local> {
+        let parent = DefWithBodyId::FunctionId(self.func.into());
+        let body = db.body(parent);
+        if let Some(self_param) = body.self_param.filter(|_| self.idx == 0) {
+            Some(Local { parent, binding_id: self_param })
+        } else if let Pat::Bind { id, .. } =
+            &body[body.params[self.idx - body.self_param.is_some() as usize]]
+        {
+            Some(Local { parent, binding_id: *id })
+        } else {
+            None
+        }
+    }
+
+    pub fn pattern_source(&self, db: &dyn HirDatabase) -> Option<ast::Pat> {
+        self.source(db).and_then(|p| p.value.pat())
+    }
+
+    pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::Param>> {
+        let InFile { file_id, value } = self.func.source(db)?;
+        let params = value.param_list()?;
+        if params.self_param().is_some() {
+            params.params().nth(self.idx.checked_sub(params.self_param().is_some() as usize)?)
+        } else {
+            params.params().nth(self.idx)
+        }
+        .map(|value| InFile { file_id, value })
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct SelfParam {
+    func: FunctionId,
+}
+
+impl SelfParam {
+    pub fn access(self, db: &dyn HirDatabase) -> Access {
+        let func_data = db.function_data(self.func);
+        func_data
+            .params
+            .first()
+            .map(|param| match &**param {
+                TypeRef::Reference(.., mutability) => match mutability {
+                    hir_def::type_ref::Mutability::Shared => Access::Shared,
+                    hir_def::type_ref::Mutability::Mut => Access::Exclusive,
+                },
+                _ => Access::Owned,
+            })
+            .unwrap_or(Access::Owned)
+    }
+
+    pub fn source(&self, db: &dyn HirDatabase) -> Option<InFile<ast::SelfParam>> {
+        let InFile { file_id, value } = Function::from(self.func).source(db)?;
+        value
+            .param_list()
+            .and_then(|params| params.self_param())
+            .map(|value| InFile { file_id, value })
+    }
+
+    pub fn parent_fn(&self) -> Function {
+        Function::from(self.func)
+    }
+
+    pub fn ty(&self, db: &dyn HirDatabase) -> Type {
+        let substs = TyBuilder::placeholder_subst(db, self.func);
+        let callable_sig =
+            db.callable_item_signature(self.func.into()).substitute(Interner, &substs);
+        let environment = db.trait_environment(self.func.into());
+        let ty = callable_sig.params()[0].clone();
+        Type { env: environment, ty }
+    }
+
+    // FIXME: Find better API to also handle const generics
+    pub fn ty_with_args(&self, db: &dyn HirDatabase, generics: impl Iterator<Item = Type>) -> Type {
+        let parent_id: GenericDefId = match self.func.lookup(db.upcast()).container {
+            ItemContainerId::ImplId(it) => it.into(),
+            ItemContainerId::TraitId(it) => it.into(),
+            ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => {
+                panic!("Never get here")
+            }
+        };
+
+        let mut generics = generics.map(|it| it.ty);
+        let mut filler = |x: &_| match x {
+            ParamKind::Type => {
+                generics.next().unwrap_or_else(|| TyKind::Error.intern(Interner)).cast(Interner)
+            }
+            ParamKind::Const(ty) => unknown_const_as_generic(ty.clone()),
+            ParamKind::Lifetime => error_lifetime().cast(Interner),
+        };
+
+        let parent_substs = TyBuilder::subst_for_def(db, parent_id, None).fill(&mut filler).build();
+        let substs =
+            TyBuilder::subst_for_def(db, self.func, Some(parent_substs)).fill(&mut filler).build();
+        let callable_sig =
+            db.callable_item_signature(self.func.into()).substitute(Interner, &substs);
+        let environment = db.trait_environment(self.func.into());
+        let ty = callable_sig.params()[0].clone();
+        Type { env: environment, ty }
+    }
+}
+
+impl HasVisibility for Function {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        db.function_visibility(self.id)
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct ExternCrateDecl {
+    pub(crate) id: ExternCrateId,
+}
+
+impl ExternCrateDecl {
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        self.id.module(db.upcast()).into()
+    }
+
+    pub fn resolved_crate(self, db: &dyn HirDatabase) -> Option<Crate> {
+        db.extern_crate_decl_data(self.id).crate_id.map(Into::into)
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        db.extern_crate_decl_data(self.id).name.clone()
+    }
+
+    pub fn alias(self, db: &dyn HirDatabase) -> Option<ImportAlias> {
+        db.extern_crate_decl_data(self.id).alias.clone()
+    }
+
+    /// Returns the name under which this crate is made accessible, taking `_` into account.
+    pub fn alias_or_name(self, db: &dyn HirDatabase) -> Option<Name> {
+        let extern_crate_decl_data = db.extern_crate_decl_data(self.id);
+        match &extern_crate_decl_data.alias {
+            Some(ImportAlias::Underscore) => None,
+            Some(ImportAlias::Alias(alias)) => Some(alias.clone()),
+            None => Some(extern_crate_decl_data.name.clone()),
+        }
+    }
+}
+
+impl HasVisibility for ExternCrateDecl {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        db.extern_crate_decl_data(self.id)
+            .visibility
+            .resolve(db.upcast(), &self.id.resolver(db.upcast()))
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct InTypeConst {
+    pub(crate) id: InTypeConstId,
+}
+
+impl InTypeConst {
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        Module { id: self.id.lookup(db.upcast()).owner.module(db.upcast()) }
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct Const {
+    pub(crate) id: ConstId,
+}
+
+impl Const {
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        Module { id: self.id.module(db.upcast()) }
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
+        db.const_data(self.id).name.clone()
+    }
+
+    pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
+        self.source(db)?.value.body()
+    }
+
+    pub fn ty(self, db: &dyn HirDatabase) -> Type {
+        Type::from_value_def(db, self.id)
+    }
+
+    pub fn render_eval(self, db: &dyn HirDatabase) -> Result<String, ConstEvalError> {
+        let c = db.const_eval(self.id.into(), Substitution::empty(Interner), None)?;
+        let data = &c.data(Interner);
+        if let TyKind::Scalar(s) = data.ty.kind(Interner) {
+            if matches!(s, Scalar::Int(_) | Scalar::Uint(_)) {
+                if let hir_ty::ConstValue::Concrete(c) = &data.value {
+                    if let hir_ty::ConstScalar::Bytes(b, _) = &c.interned {
+                        let value = u128::from_le_bytes(mir::pad16(b, false));
+                        let value_signed =
+                            i128::from_le_bytes(mir::pad16(b, matches!(s, Scalar::Int(_))));
+                        if value >= 10 {
+                            return Ok(format!("{} ({:#X})", value_signed, value));
+                        } else {
+                            return Ok(format!("{}", value_signed));
+                        }
+                    }
+                }
+            }
+        }
+        if let Ok(s) = mir::render_const_using_debug_impl(db, self.id, &c) {
+            Ok(s)
+        } else {
+            Ok(format!("{}", c.display(db)))
+        }
+    }
+}
+
+impl HasVisibility for Const {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        db.const_visibility(self.id)
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct Static {
+    pub(crate) id: StaticId,
+}
+
+impl Static {
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        Module { id: self.id.module(db.upcast()) }
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        db.static_data(self.id).name.clone()
+    }
+
+    pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
+        db.static_data(self.id).mutable
+    }
+
+    pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
+        self.source(db)?.value.body()
+    }
+
+    pub fn ty(self, db: &dyn HirDatabase) -> Type {
+        Type::from_value_def(db, self.id)
+    }
+}
+
+impl HasVisibility for Static {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        db.static_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct Trait {
+    pub(crate) id: TraitId,
+}
+
+impl Trait {
+    pub fn lang(db: &dyn HirDatabase, krate: Crate, name: &Name) -> Option<Trait> {
+        db.lang_item(krate.into(), LangItem::from_name(name)?)
+            .and_then(LangItemTarget::as_trait)
+            .map(Into::into)
+    }
+
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        Module { id: self.id.lookup(db.upcast()).container }
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        db.trait_data(self.id).name.clone()
+    }
+
+    pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
+        db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect()
+    }
+
+    pub fn items_with_supertraits(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
+        let traits = all_super_traits(db.upcast(), self.into());
+        traits.iter().flat_map(|tr| Trait::from(*tr).items(db)).collect()
+    }
+
+    pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
+        db.trait_data(self.id).is_auto
+    }
+
+    pub fn is_unsafe(&self, db: &dyn HirDatabase) -> bool {
+        db.trait_data(self.id).is_unsafe
+    }
+
+    pub fn type_or_const_param_count(
+        &self,
+        db: &dyn HirDatabase,
+        count_required_only: bool,
+    ) -> usize {
+        db.generic_params(GenericDefId::from(self.id))
+            .type_or_consts
+            .iter()
+            .filter(|(_, ty)| !matches!(ty, TypeOrConstParamData::TypeParamData(ty) if ty.provenance != TypeParamProvenance::TypeParamList))
+            .filter(|(_, ty)| !count_required_only || !ty.has_default())
+            .count()
+    }
+}
+
+impl HasVisibility for Trait {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct TraitAlias {
+    pub(crate) id: TraitAliasId,
+}
+
+impl TraitAlias {
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        Module { id: self.id.lookup(db.upcast()).container }
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        db.trait_alias_data(self.id).name.clone()
+    }
+}
+
+impl HasVisibility for TraitAlias {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        db.trait_alias_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct TypeAlias {
+    pub(crate) id: TypeAliasId,
+}
+
+impl TypeAlias {
+    pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
+        let subst = db.generic_defaults(self.id.into());
+        subst.iter().any(|ty| match ty.skip_binders().data(Interner) {
+            GenericArgData::Ty(it) => it.is_unknown(),
+            _ => false,
+        })
+    }
+
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        Module { id: self.id.module(db.upcast()) }
+    }
+
+    pub fn type_ref(self, db: &dyn HirDatabase) -> Option<TypeRef> {
+        db.type_alias_data(self.id).type_ref.as_deref().cloned()
+    }
+
+    pub fn ty(self, db: &dyn HirDatabase) -> Type {
+        Type::from_def(db, self.id)
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        db.type_alias_data(self.id).name.clone()
+    }
+}
+
+impl HasVisibility for TypeAlias {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        let function_data = db.type_alias_data(self.id);
+        let visibility = &function_data.visibility;
+        visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct BuiltinType {
+    pub(crate) inner: hir_def::builtin_type::BuiltinType,
+}
+
+impl BuiltinType {
+    pub fn str() -> BuiltinType {
+        BuiltinType { inner: hir_def::builtin_type::BuiltinType::Str }
+    }
+
+    pub fn ty(self, db: &dyn HirDatabase) -> Type {
+        Type::new_for_crate(db.crate_graph().iter().next().unwrap(), TyBuilder::builtin(self.inner))
+    }
+
+    pub fn name(self) -> Name {
+        self.inner.as_name()
+    }
+
+    pub fn is_int(&self) -> bool {
+        matches!(self.inner, hir_def::builtin_type::BuiltinType::Int(_))
+    }
+
+    pub fn is_uint(&self) -> bool {
+        matches!(self.inner, hir_def::builtin_type::BuiltinType::Uint(_))
+    }
+
+    pub fn is_float(&self) -> bool {
+        matches!(self.inner, hir_def::builtin_type::BuiltinType::Float(_))
+    }
+
+    pub fn is_char(&self) -> bool {
+        matches!(self.inner, hir_def::builtin_type::BuiltinType::Char)
+    }
+
+    pub fn is_bool(&self) -> bool {
+        matches!(self.inner, hir_def::builtin_type::BuiltinType::Bool)
+    }
+
+    pub fn is_str(&self) -> bool {
+        matches!(self.inner, hir_def::builtin_type::BuiltinType::Str)
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum MacroKind {
+    /// `macro_rules!` or Macros 2.0 macro.
+    Declarative,
+    /// A built-in or custom derive.
+    Derive,
+    /// A built-in function-like macro.
+    BuiltIn,
+    /// A procedural attribute macro.
+    Attr,
+    /// A function-like procedural macro.
+    ProcMacro,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct Macro {
+    pub(crate) id: MacroId,
+}
+
+impl Macro {
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        Module { id: self.id.module(db.upcast()) }
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        match self.id {
+            MacroId::Macro2Id(id) => db.macro2_data(id).name.clone(),
+            MacroId::MacroRulesId(id) => db.macro_rules_data(id).name.clone(),
+            MacroId::ProcMacroId(id) => db.proc_macro_data(id).name.clone(),
+        }
+    }
+
+    pub fn is_macro_export(self, db: &dyn HirDatabase) -> bool {
+        matches!(self.id, MacroId::MacroRulesId(id) if db.macro_rules_data(id).macro_export)
+    }
+
+    pub fn kind(&self, db: &dyn HirDatabase) -> MacroKind {
+        match self.id {
+            MacroId::Macro2Id(it) => match it.lookup(db.upcast()).expander {
+                MacroExpander::Declarative => MacroKind::Declarative,
+                MacroExpander::BuiltIn(_) | MacroExpander::BuiltInEager(_) => MacroKind::BuiltIn,
+                MacroExpander::BuiltInAttr(_) => MacroKind::Attr,
+                MacroExpander::BuiltInDerive(_) => MacroKind::Derive,
+            },
+            MacroId::MacroRulesId(it) => match it.lookup(db.upcast()).expander {
+                MacroExpander::Declarative => MacroKind::Declarative,
+                MacroExpander::BuiltIn(_) | MacroExpander::BuiltInEager(_) => MacroKind::BuiltIn,
+                MacroExpander::BuiltInAttr(_) => MacroKind::Attr,
+                MacroExpander::BuiltInDerive(_) => MacroKind::Derive,
+            },
+            MacroId::ProcMacroId(it) => match it.lookup(db.upcast()).kind {
+                ProcMacroKind::CustomDerive => MacroKind::Derive,
+                ProcMacroKind::Bang => MacroKind::ProcMacro,
+                ProcMacroKind::Attr => MacroKind::Attr,
+            },
+        }
+    }
+
+    pub fn is_fn_like(&self, db: &dyn HirDatabase) -> bool {
+        match self.kind(db) {
+            MacroKind::Declarative | MacroKind::BuiltIn | MacroKind::ProcMacro => true,
+            MacroKind::Attr | MacroKind::Derive => false,
+        }
+    }
+
+    pub fn is_builtin_derive(&self, db: &dyn HirDatabase) -> bool {
+        match self.id {
+            MacroId::Macro2Id(it) => {
+                matches!(it.lookup(db.upcast()).expander, MacroExpander::BuiltInDerive(_))
+            }
+            MacroId::MacroRulesId(it) => {
+                matches!(it.lookup(db.upcast()).expander, MacroExpander::BuiltInDerive(_))
+            }
+            MacroId::ProcMacroId(_) => false,
+        }
+    }
+
+    pub fn is_env_or_option_env(&self, db: &dyn HirDatabase) -> bool {
+        match self.id {
+            MacroId::Macro2Id(it) => {
+                matches!(it.lookup(db.upcast()).expander, MacroExpander::BuiltInEager(eager) if eager.is_env_or_option_env())
+            }
+            MacroId::MacroRulesId(_) | MacroId::ProcMacroId(_) => false,
+        }
+    }
+
+    pub fn is_attr(&self, db: &dyn HirDatabase) -> bool {
+        matches!(self.kind(db), MacroKind::Attr)
+    }
+
+    pub fn is_derive(&self, db: &dyn HirDatabase) -> bool {
+        matches!(self.kind(db), MacroKind::Derive)
+    }
+}
+
+impl HasVisibility for Macro {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        match self.id {
+            MacroId::Macro2Id(id) => {
+                let data = db.macro2_data(id);
+                let visibility = &data.visibility;
+                visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
+            }
+            MacroId::MacroRulesId(_) => Visibility::Public,
+            MacroId::ProcMacroId(_) => Visibility::Public,
+        }
+    }
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
+pub enum ItemInNs {
+    Types(ModuleDef),
+    Values(ModuleDef),
+    Macros(Macro),
+}
+
+impl From<Macro> for ItemInNs {
+    fn from(it: Macro) -> Self {
+        Self::Macros(it)
+    }
+}
+
+impl From<ModuleDef> for ItemInNs {
+    fn from(module_def: ModuleDef) -> Self {
+        match module_def {
+            ModuleDef::Static(_) | ModuleDef::Const(_) | ModuleDef::Function(_) => {
+                ItemInNs::Values(module_def)
+            }
+            _ => ItemInNs::Types(module_def),
+        }
+    }
+}
+
+impl ItemInNs {
+    pub fn as_module_def(self) -> Option<ModuleDef> {
+        match self {
+            ItemInNs::Types(id) | ItemInNs::Values(id) => Some(id),
+            ItemInNs::Macros(_) => None,
+        }
+    }
+
+    /// Returns the crate defining this item (or `None` if `self` is built-in).
+    pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
+        match self {
+            ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate()),
+            ItemInNs::Macros(id) => Some(id.module(db).krate()),
+        }
+    }
+
+    pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
+        match self {
+            ItemInNs::Types(it) | ItemInNs::Values(it) => it.attrs(db),
+            ItemInNs::Macros(it) => Some(it.attrs(db)),
+        }
+    }
+}
+
+/// Invariant: `inner.as_extern_assoc_item(db).is_some()`
+/// We do not actively enforce this invariant.
+#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
+pub enum ExternAssocItem {
+    Function(Function),
+    Static(Static),
+    TypeAlias(TypeAlias),
+}
+
+pub trait AsExternAssocItem {
+    fn as_extern_assoc_item(self, db: &dyn HirDatabase) -> Option<ExternAssocItem>;
+}
+
+impl AsExternAssocItem for Function {
+    fn as_extern_assoc_item(self, db: &dyn HirDatabase) -> Option<ExternAssocItem> {
+        as_extern_assoc_item(db, ExternAssocItem::Function, self.id)
+    }
+}
+
+impl AsExternAssocItem for Static {
+    fn as_extern_assoc_item(self, db: &dyn HirDatabase) -> Option<ExternAssocItem> {
+        as_extern_assoc_item(db, ExternAssocItem::Static, self.id)
+    }
+}
+
+impl AsExternAssocItem for TypeAlias {
+    fn as_extern_assoc_item(self, db: &dyn HirDatabase) -> Option<ExternAssocItem> {
+        as_extern_assoc_item(db, ExternAssocItem::TypeAlias, self.id)
+    }
+}
+
+/// Invariant: `inner.as_assoc_item(db).is_some()`
+/// We do not actively enforce this invariant.
+#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
+pub enum AssocItem {
+    Function(Function),
+    Const(Const),
+    TypeAlias(TypeAlias),
+}
+
+#[derive(Debug, Clone)]
+pub enum AssocItemContainer {
+    Trait(Trait),
+    Impl(Impl),
+}
+
+pub trait AsAssocItem {
+    fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
+}
+
+impl AsAssocItem for Function {
+    fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
+        as_assoc_item(db, AssocItem::Function, self.id)
+    }
+}
+
+impl AsAssocItem for Const {
+    fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
+        as_assoc_item(db, AssocItem::Const, self.id)
+    }
+}
+
+impl AsAssocItem for TypeAlias {
+    fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
+        as_assoc_item(db, AssocItem::TypeAlias, self.id)
+    }
+}
+
+impl AsAssocItem for ModuleDef {
+    fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
+        match self {
+            ModuleDef::Function(it) => it.as_assoc_item(db),
+            ModuleDef::Const(it) => it.as_assoc_item(db),
+            ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
+            _ => None,
+        }
+    }
+}
+
+impl AsAssocItem for DefWithBody {
+    fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
+        match self {
+            DefWithBody::Function(it) => it.as_assoc_item(db),
+            DefWithBody::Const(it) => it.as_assoc_item(db),
+            DefWithBody::Static(_) | DefWithBody::Variant(_) | DefWithBody::InTypeConst(_) => None,
+        }
+    }
+}
+
+fn as_assoc_item<'db, ID, DEF, LOC>(
+    db: &(dyn HirDatabase + 'db),
+    ctor: impl FnOnce(DEF) -> AssocItem,
+    id: ID,
+) -> Option<AssocItem>
+where
+    ID: Lookup<Database<'db> = dyn DefDatabase + 'db, Data = AssocItemLoc<LOC>>,
+    DEF: From<ID>,
+    LOC: ItemTreeNode,
+{
+    match id.lookup(db.upcast()).container {
+        ItemContainerId::TraitId(_) | ItemContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
+        ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
+    }
+}
+
+fn as_extern_assoc_item<'db, ID, DEF, LOC>(
+    db: &(dyn HirDatabase + 'db),
+    ctor: impl FnOnce(DEF) -> ExternAssocItem,
+    id: ID,
+) -> Option<ExternAssocItem>
+where
+    ID: Lookup<Database<'db> = dyn DefDatabase + 'db, Data = AssocItemLoc<LOC>>,
+    DEF: From<ID>,
+    LOC: ItemTreeNode,
+{
+    match id.lookup(db.upcast()).container {
+        ItemContainerId::ExternBlockId(_) => Some(ctor(DEF::from(id))),
+        ItemContainerId::TraitId(_) | ItemContainerId::ImplId(_) | ItemContainerId::ModuleId(_) => {
+            None
+        }
+    }
+}
+
+impl ExternAssocItem {
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        match self {
+            Self::Function(it) => it.name(db),
+            Self::Static(it) => it.name(db),
+            Self::TypeAlias(it) => it.name(db),
+        }
+    }
+
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        match self {
+            Self::Function(f) => f.module(db),
+            Self::Static(c) => c.module(db),
+            Self::TypeAlias(t) => t.module(db),
+        }
+    }
+
+    pub fn as_function(self) -> Option<Function> {
+        match self {
+            Self::Function(v) => Some(v),
+            _ => None,
+        }
+    }
+
+    pub fn as_static(self) -> Option<Static> {
+        match self {
+            Self::Static(v) => Some(v),
+            _ => None,
+        }
+    }
+
+    pub fn as_type_alias(self) -> Option<TypeAlias> {
+        match self {
+            Self::TypeAlias(v) => Some(v),
+            _ => None,
+        }
+    }
+}
+
+impl AssocItem {
+    pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
+        match self {
+            AssocItem::Function(it) => Some(it.name(db)),
+            AssocItem::Const(it) => it.name(db),
+            AssocItem::TypeAlias(it) => Some(it.name(db)),
+        }
+    }
+
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        match self {
+            AssocItem::Function(f) => f.module(db),
+            AssocItem::Const(c) => c.module(db),
+            AssocItem::TypeAlias(t) => t.module(db),
+        }
+    }
+
+    pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
+        let container = match self {
+            AssocItem::Function(it) => it.id.lookup(db.upcast()).container,
+            AssocItem::Const(it) => it.id.lookup(db.upcast()).container,
+            AssocItem::TypeAlias(it) => it.id.lookup(db.upcast()).container,
+        };
+        match container {
+            ItemContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
+            ItemContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
+            ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => {
+                panic!("invalid AssocItem")
+            }
+        }
+    }
+
+    pub fn container_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
+        match self.container(db) {
+            AssocItemContainer::Trait(t) => Some(t),
+            _ => None,
+        }
+    }
+
+    pub fn implemented_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
+        match self.container(db) {
+            AssocItemContainer::Impl(i) => i.trait_(db),
+            _ => None,
+        }
+    }
+
+    pub fn container_or_implemented_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
+        match self.container(db) {
+            AssocItemContainer::Trait(t) => Some(t),
+            AssocItemContainer::Impl(i) => i.trait_(db),
+        }
+    }
+
+    pub fn implementing_ty(self, db: &dyn HirDatabase) -> Option<Type> {
+        match self.container(db) {
+            AssocItemContainer::Impl(i) => Some(i.self_ty(db)),
+            _ => None,
+        }
+    }
+
+    pub fn as_function(self) -> Option<Function> {
+        match self {
+            Self::Function(v) => Some(v),
+            _ => None,
+        }
+    }
+
+    pub fn as_const(self) -> Option<Const> {
+        match self {
+            Self::Const(v) => Some(v),
+            _ => None,
+        }
+    }
+
+    pub fn as_type_alias(self) -> Option<TypeAlias> {
+        match self {
+            Self::TypeAlias(v) => Some(v),
+            _ => None,
+        }
+    }
+
+    pub fn diagnostics(
+        self,
+        db: &dyn HirDatabase,
+        acc: &mut Vec<AnyDiagnostic>,
+        style_lints: bool,
+    ) {
+        match self {
+            AssocItem::Function(func) => {
+                DefWithBody::from(func).diagnostics(db, acc, style_lints);
+            }
+            AssocItem::Const(const_) => {
+                DefWithBody::from(const_).diagnostics(db, acc, style_lints);
+            }
+            AssocItem::TypeAlias(type_alias) => {
+                for diag in hir_ty::diagnostics::incorrect_case(db, type_alias.id.into()) {
+                    acc.push(diag.into());
+                }
+            }
+        }
+    }
+}
+
+impl HasVisibility for AssocItem {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
+        match self {
+            AssocItem::Function(f) => f.visibility(db),
+            AssocItem::Const(c) => c.visibility(db),
+            AssocItem::TypeAlias(t) => t.visibility(db),
+        }
+    }
+}
+
+impl From<AssocItem> for ModuleDef {
+    fn from(assoc: AssocItem) -> Self {
+        match assoc {
+            AssocItem::Function(it) => ModuleDef::Function(it),
+            AssocItem::Const(it) => ModuleDef::Const(it),
+            AssocItem::TypeAlias(it) => ModuleDef::TypeAlias(it),
+        }
+    }
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
+pub enum GenericDef {
+    Function(Function),
+    Adt(Adt),
+    Trait(Trait),
+    TraitAlias(TraitAlias),
+    TypeAlias(TypeAlias),
+    Impl(Impl),
+    // enum variants cannot have generics themselves, but their parent enums
+    // can, and this makes some code easier to write
+    Variant(Variant),
+    // consts can have type parameters from their parents (i.e. associated consts of traits)
+    Const(Const),
+}
+impl_from!(
+    Function,
+    Adt(Struct, Enum, Union),
+    Trait,
+    TraitAlias,
+    TypeAlias,
+    Impl,
+    Variant,
+    Const
+    for GenericDef
+);
+
+impl GenericDef {
+    pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
+        let generics = db.generic_params(self.into());
+        let ty_params = generics.type_or_consts.iter().map(|(local_id, _)| {
+            let toc = TypeOrConstParam { id: TypeOrConstParamId { parent: self.into(), local_id } };
+            match toc.split(db) {
+                Either::Left(it) => GenericParam::ConstParam(it),
+                Either::Right(it) => GenericParam::TypeParam(it),
+            }
+        });
+        self.lifetime_params(db)
+            .into_iter()
+            .map(GenericParam::LifetimeParam)
+            .chain(ty_params)
+            .collect()
+    }
+
+    pub fn lifetime_params(self, db: &dyn HirDatabase) -> Vec<LifetimeParam> {
+        let generics = db.generic_params(self.into());
+        generics
+            .lifetimes
+            .iter()
+            .map(|(local_id, _)| LifetimeParam {
+                id: LifetimeParamId { parent: self.into(), local_id },
+            })
+            .collect()
+    }
+
+    pub fn type_or_const_params(self, db: &dyn HirDatabase) -> Vec<TypeOrConstParam> {
+        let generics = db.generic_params(self.into());
+        generics
+            .type_or_consts
+            .iter()
+            .map(|(local_id, _)| TypeOrConstParam {
+                id: TypeOrConstParamId { parent: self.into(), local_id },
+            })
+            .collect()
+    }
+}
+
+/// A single local definition.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct Local {
+    pub(crate) parent: DefWithBodyId,
+    pub(crate) binding_id: BindingId,
+}
+
+pub struct LocalSource {
+    pub local: Local,
+    pub source: InFile<Either<ast::IdentPat, ast::SelfParam>>,
+}
+
+impl LocalSource {
+    pub fn as_ident_pat(&self) -> Option<&ast::IdentPat> {
+        match &self.source.value {
+            Either::Left(it) => Some(it),
+            Either::Right(_) => None,
+        }
+    }
+
+    pub fn into_ident_pat(self) -> Option<ast::IdentPat> {
+        match self.source.value {
+            Either::Left(it) => Some(it),
+            Either::Right(_) => None,
+        }
+    }
+
+    pub fn original_file(&self, db: &dyn HirDatabase) -> FileId {
+        self.source.file_id.original_file(db.upcast())
+    }
+
+    pub fn file(&self) -> HirFileId {
+        self.source.file_id
+    }
+
+    pub fn name(&self) -> Option<InFile<ast::Name>> {
+        self.source.as_ref().map(|it| it.name()).transpose()
+    }
+
+    pub fn syntax(&self) -> &SyntaxNode {
+        self.source.value.syntax()
+    }
+
+    pub fn syntax_ptr(self) -> InFile<SyntaxNodePtr> {
+        self.source.map(|it| SyntaxNodePtr::new(it.syntax()))
+    }
+}
+
+impl Local {
+    pub fn is_param(self, db: &dyn HirDatabase) -> bool {
+        // FIXME: This parses!
+        let src = self.primary_source(db);
+        match src.source.value {
+            Either::Left(pat) => pat
+                .syntax()
+                .ancestors()
+                .map(|it| it.kind())
+                .take_while(|&kind| ast::Pat::can_cast(kind) || ast::Param::can_cast(kind))
+                .any(ast::Param::can_cast),
+            Either::Right(_) => true,
+        }
+    }
+
+    pub fn as_self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
+        match self.parent {
+            DefWithBodyId::FunctionId(func) if self.is_self(db) => Some(SelfParam { func }),
+            _ => None,
+        }
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        let body = db.body(self.parent);
+        body[self.binding_id].name.clone()
+    }
+
+    pub fn is_self(self, db: &dyn HirDatabase) -> bool {
+        self.name(db) == name![self]
+    }
+
+    pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
+        let body = db.body(self.parent);
+        body[self.binding_id].mode == BindingAnnotation::Mutable
+    }
+
+    pub fn is_ref(self, db: &dyn HirDatabase) -> bool {
+        let body = db.body(self.parent);
+        matches!(body[self.binding_id].mode, BindingAnnotation::Ref | BindingAnnotation::RefMut)
+    }
+
+    pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
+        self.parent.into()
+    }
+
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        self.parent(db).module(db)
+    }
+
+    pub fn ty(self, db: &dyn HirDatabase) -> Type {
+        let def = self.parent;
+        let infer = db.infer(def);
+        let ty = infer[self.binding_id].clone();
+        Type::new(db, def, ty)
+    }
+
+    /// All definitions for this local. Example: `let (a$0, _) | (_, a$0) = it;`
+    pub fn sources(self, db: &dyn HirDatabase) -> Vec<LocalSource> {
+        let (body, source_map) = db.body_with_source_map(self.parent);
+        match body.self_param.zip(source_map.self_param_syntax()) {
+            Some((param, source)) if param == self.binding_id => {
+                let root = source.file_syntax(db.upcast());
+                vec![LocalSource {
+                    local: self,
+                    source: source.map(|ast| Either::Right(ast.to_node(&root))),
+                }]
+            }
+            _ => body[self.binding_id]
+                .definitions
+                .iter()
+                .map(|&definition| {
+                    let src = source_map.pat_syntax(definition).unwrap(); // Hmm...
+                    let root = src.file_syntax(db.upcast());
+                    LocalSource {
+                        local: self,
+                        source: src.map(|ast| match ast.to_node(&root) {
+                            ast::Pat::IdentPat(it) => Either::Left(it),
+                            _ => unreachable!("local with non ident-pattern"),
+                        }),
+                    }
+                })
+                .collect(),
+        }
+    }
+
+    /// The leftmost definition for this local. Example: `let (a$0, _) | (_, a) = it;`
+    pub fn primary_source(self, db: &dyn HirDatabase) -> LocalSource {
+        let (body, source_map) = db.body_with_source_map(self.parent);
+        match body.self_param.zip(source_map.self_param_syntax()) {
+            Some((param, source)) if param == self.binding_id => {
+                let root = source.file_syntax(db.upcast());
+                LocalSource {
+                    local: self,
+                    source: source.map(|ast| Either::Right(ast.to_node(&root))),
+                }
+            }
+            _ => body[self.binding_id]
+                .definitions
+                .first()
+                .map(|&definition| {
+                    let src = source_map.pat_syntax(definition).unwrap(); // Hmm...
+                    let root = src.file_syntax(db.upcast());
+                    LocalSource {
+                        local: self,
+                        source: src.map(|ast| match ast.to_node(&root) {
+                            ast::Pat::IdentPat(it) => Either::Left(it),
+                            _ => unreachable!("local with non ident-pattern"),
+                        }),
+                    }
+                })
+                .unwrap(),
+        }
+    }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct DeriveHelper {
+    pub(crate) derive: MacroId,
+    pub(crate) idx: u32,
+}
+
+impl DeriveHelper {
+    pub fn derive(&self) -> Macro {
+        Macro { id: self.derive }
+    }
+
+    pub fn name(&self, db: &dyn HirDatabase) -> Name {
+        match self.derive {
+            MacroId::Macro2Id(it) => db
+                .macro2_data(it)
+                .helpers
+                .as_deref()
+                .and_then(|it| it.get(self.idx as usize))
+                .cloned(),
+            MacroId::MacroRulesId(_) => None,
+            MacroId::ProcMacroId(proc_macro) => db
+                .proc_macro_data(proc_macro)
+                .helpers
+                .as_deref()
+                .and_then(|it| it.get(self.idx as usize))
+                .cloned(),
+        }
+        .unwrap_or_else(Name::missing)
+    }
+}
+
+// FIXME: Wrong name? This is could also be a registered attribute
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct BuiltinAttr {
+    krate: Option<CrateId>,
+    idx: u32,
+}
+
+impl BuiltinAttr {
+    // FIXME: consider crates\hir_def\src\nameres\attr_resolution.rs?
+    pub(crate) fn by_name(db: &dyn HirDatabase, krate: Crate, name: &str) -> Option<Self> {
+        if let builtin @ Some(_) = Self::builtin(name) {
+            return builtin;
+        }
+        let idx =
+            db.crate_def_map(krate.id).registered_attrs().iter().position(|it| it == name)? as u32;
+        Some(BuiltinAttr { krate: Some(krate.id), idx })
+    }
+
+    fn builtin(name: &str) -> Option<Self> {
+        hir_def::attr::builtin::find_builtin_attr_idx(name)
+            .map(|idx| BuiltinAttr { krate: None, idx: idx as u32 })
+    }
+
+    pub fn name(&self, db: &dyn HirDatabase) -> SmolStr {
+        // FIXME: Return a `Name` here
+        match self.krate {
+            Some(krate) => db.crate_def_map(krate).registered_attrs()[self.idx as usize].clone(),
+            None => SmolStr::new(hir_def::attr::builtin::INERT_ATTRIBUTES[self.idx as usize].name),
+        }
+    }
+
+    pub fn template(&self, _: &dyn HirDatabase) -> Option<AttributeTemplate> {
+        match self.krate {
+            Some(_) => None,
+            None => Some(hir_def::attr::builtin::INERT_ATTRIBUTES[self.idx as usize].template),
+        }
+    }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct ToolModule {
+    krate: Option<CrateId>,
+    idx: u32,
+}
+
+impl ToolModule {
+    // FIXME: consider crates\hir_def\src\nameres\attr_resolution.rs?
+    pub(crate) fn by_name(db: &dyn HirDatabase, krate: Crate, name: &str) -> Option<Self> {
+        if let builtin @ Some(_) = Self::builtin(name) {
+            return builtin;
+        }
+        let idx =
+            db.crate_def_map(krate.id).registered_tools().iter().position(|it| it == name)? as u32;
+        Some(ToolModule { krate: Some(krate.id), idx })
+    }
+
+    fn builtin(name: &str) -> Option<Self> {
+        hir_def::attr::builtin::TOOL_MODULES
+            .iter()
+            .position(|&tool| tool == name)
+            .map(|idx| ToolModule { krate: None, idx: idx as u32 })
+    }
+
+    pub fn name(&self, db: &dyn HirDatabase) -> SmolStr {
+        // FIXME: Return a `Name` here
+        match self.krate {
+            Some(krate) => db.crate_def_map(krate).registered_tools()[self.idx as usize].clone(),
+            None => SmolStr::new(hir_def::attr::builtin::TOOL_MODULES[self.idx as usize]),
+        }
+    }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct Label {
+    pub(crate) parent: DefWithBodyId,
+    pub(crate) label_id: LabelId,
+}
+
+impl Label {
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        self.parent(db).module(db)
+    }
+
+    pub fn parent(self, _db: &dyn HirDatabase) -> DefWithBody {
+        self.parent.into()
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        let body = db.body(self.parent);
+        body[self.label_id].name.clone()
+    }
+
+    pub fn source(self, db: &dyn HirDatabase) -> InFile<ast::Label> {
+        let (_body, source_map) = db.body_with_source_map(self.parent);
+        let src = source_map.label_syntax(self.label_id);
+        let root = src.file_syntax(db.upcast());
+        src.map(|ast| ast.to_node(&root))
+    }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum GenericParam {
+    TypeParam(TypeParam),
+    ConstParam(ConstParam),
+    LifetimeParam(LifetimeParam),
+}
+impl_from!(TypeParam, ConstParam, LifetimeParam for GenericParam);
+
+impl GenericParam {
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        match self {
+            GenericParam::TypeParam(it) => it.module(db),
+            GenericParam::ConstParam(it) => it.module(db),
+            GenericParam::LifetimeParam(it) => it.module(db),
+        }
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        match self {
+            GenericParam::TypeParam(it) => it.name(db),
+            GenericParam::ConstParam(it) => it.name(db),
+            GenericParam::LifetimeParam(it) => it.name(db),
+        }
+    }
+
+    pub fn parent(self) -> GenericDef {
+        match self {
+            GenericParam::TypeParam(it) => it.id.parent().into(),
+            GenericParam::ConstParam(it) => it.id.parent().into(),
+            GenericParam::LifetimeParam(it) => it.id.parent.into(),
+        }
+    }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct TypeParam {
+    pub(crate) id: TypeParamId,
+}
+
+impl TypeParam {
+    pub fn merge(self) -> TypeOrConstParam {
+        TypeOrConstParam { id: self.id.into() }
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        self.merge().name(db)
+    }
+
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        self.id.parent().module(db.upcast()).into()
+    }
+
+    /// Is this type parameter implicitly introduced (eg. `Self` in a trait or an `impl Trait`
+    /// argument)?
+    pub fn is_implicit(self, db: &dyn HirDatabase) -> bool {
+        let params = db.generic_params(self.id.parent());
+        let data = &params.type_or_consts[self.id.local_id()];
+        match data.type_param().unwrap().provenance {
+            hir_def::generics::TypeParamProvenance::TypeParamList => false,
+            hir_def::generics::TypeParamProvenance::TraitSelf
+            | hir_def::generics::TypeParamProvenance::ArgumentImplTrait => true,
+        }
+    }
+
+    pub fn ty(self, db: &dyn HirDatabase) -> Type {
+        let resolver = self.id.parent().resolver(db.upcast());
+        let ty =
+            TyKind::Placeholder(hir_ty::to_placeholder_idx(db, self.id.into())).intern(Interner);
+        Type::new_with_resolver_inner(db, &resolver, ty)
+    }
+
+    /// FIXME: this only lists trait bounds from the item defining the type
+    /// parameter, not additional bounds that might be added e.g. by a method if
+    /// the parameter comes from an impl!
+    pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
+        db.generic_predicates_for_param(self.id.parent(), self.id.into(), None)
+            .iter()
+            .filter_map(|pred| match &pred.skip_binders().skip_binders() {
+                hir_ty::WhereClause::Implemented(trait_ref) => {
+                    Some(Trait::from(trait_ref.hir_trait_id()))
+                }
+                _ => None,
+            })
+            .collect()
+    }
+
+    pub fn default(self, db: &dyn HirDatabase) -> Option<Type> {
+        let ty = generic_arg_from_param(db, self.id.into())?;
+        let resolver = self.id.parent().resolver(db.upcast());
+        match ty.data(Interner) {
+            GenericArgData::Ty(it) if *it.kind(Interner) != TyKind::Error => {
+                Some(Type::new_with_resolver_inner(db, &resolver, it.clone()))
+            }
+            _ => None,
+        }
+    }
+
+    pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
+        db.attrs(GenericParamId::from(self.id).into()).is_unstable()
+    }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct LifetimeParam {
+    pub(crate) id: LifetimeParamId,
+}
+
+impl LifetimeParam {
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        let params = db.generic_params(self.id.parent);
+        params.lifetimes[self.id.local_id].name.clone()
+    }
+
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        self.id.parent.module(db.upcast()).into()
+    }
+
+    pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
+        self.id.parent.into()
+    }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct ConstParam {
+    pub(crate) id: ConstParamId,
+}
+
+impl ConstParam {
+    pub fn merge(self) -> TypeOrConstParam {
+        TypeOrConstParam { id: self.id.into() }
+    }
+
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        let params = db.generic_params(self.id.parent());
+        match params.type_or_consts[self.id.local_id()].name() {
+            Some(it) => it.clone(),
+            None => {
+                never!();
+                Name::missing()
+            }
+        }
+    }
+
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        self.id.parent().module(db.upcast()).into()
+    }
+
+    pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
+        self.id.parent().into()
+    }
+
+    pub fn ty(self, db: &dyn HirDatabase) -> Type {
+        Type::new(db, self.id.parent(), db.const_param_ty(self.id))
+    }
+
+    pub fn default(self, db: &dyn HirDatabase) -> Option<ast::ConstArg> {
+        let arg = generic_arg_from_param(db, self.id.into())?;
+        known_const_to_ast(arg.constant(Interner)?, db)
+    }
+}
+
+fn generic_arg_from_param(db: &dyn HirDatabase, id: TypeOrConstParamId) -> Option<GenericArg> {
+    let params = db.generic_defaults(id.parent);
+    let local_idx = hir_ty::param_idx(db, id)?;
+    let ty = params.get(local_idx)?.clone();
+    let subst = TyBuilder::placeholder_subst(db, id.parent);
+    Some(ty.substitute(Interner, &subst))
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct TypeOrConstParam {
+    pub(crate) id: TypeOrConstParamId,
+}
+
+impl TypeOrConstParam {
+    pub fn name(self, db: &dyn HirDatabase) -> Name {
+        let params = db.generic_params(self.id.parent);
+        match params.type_or_consts[self.id.local_id].name() {
+            Some(n) => n.clone(),
+            _ => Name::missing(),
+        }
+    }
+
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        self.id.parent.module(db.upcast()).into()
+    }
+
+    pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
+        self.id.parent.into()
+    }
+
+    pub fn split(self, db: &dyn HirDatabase) -> Either<ConstParam, TypeParam> {
+        let params = db.generic_params(self.id.parent);
+        match &params.type_or_consts[self.id.local_id] {
+            hir_def::generics::TypeOrConstParamData::TypeParamData(_) => {
+                Either::Right(TypeParam { id: TypeParamId::from_unchecked(self.id) })
+            }
+            hir_def::generics::TypeOrConstParamData::ConstParamData(_) => {
+                Either::Left(ConstParam { id: ConstParamId::from_unchecked(self.id) })
+            }
+        }
+    }
+
+    pub fn ty(self, db: &dyn HirDatabase) -> Type {
+        match self.split(db) {
+            Either::Left(it) => it.ty(db),
+            Either::Right(it) => it.ty(db),
+        }
+    }
+
+    pub fn as_type_param(self, db: &dyn HirDatabase) -> Option<TypeParam> {
+        let params = db.generic_params(self.id.parent);
+        match &params.type_or_consts[self.id.local_id] {
+            hir_def::generics::TypeOrConstParamData::TypeParamData(_) => {
+                Some(TypeParam { id: TypeParamId::from_unchecked(self.id) })
+            }
+            hir_def::generics::TypeOrConstParamData::ConstParamData(_) => None,
+        }
+    }
+
+    pub fn as_const_param(self, db: &dyn HirDatabase) -> Option<ConstParam> {
+        let params = db.generic_params(self.id.parent);
+        match &params.type_or_consts[self.id.local_id] {
+            hir_def::generics::TypeOrConstParamData::TypeParamData(_) => None,
+            hir_def::generics::TypeOrConstParamData::ConstParamData(_) => {
+                Some(ConstParam { id: ConstParamId::from_unchecked(self.id) })
+            }
+        }
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct Impl {
+    pub(crate) id: ImplId,
+}
+
+impl Impl {
+    pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
+        let inherent = db.inherent_impls_in_crate(krate.id);
+        let trait_ = db.trait_impls_in_crate(krate.id);
+
+        inherent.all_impls().chain(trait_.all_impls()).map(Self::from).collect()
+    }
+
+    pub fn all_for_type(db: &dyn HirDatabase, Type { ty, env }: Type) -> Vec<Impl> {
+        let def_crates = match method_resolution::def_crates(db, &ty, env.krate) {
+            Some(def_crates) => def_crates,
+            None => return Vec::new(),
+        };
+
+        let filter = |impl_def: &Impl| {
+            let self_ty = impl_def.self_ty(db);
+            let rref = self_ty.remove_ref();
+            ty.equals_ctor(rref.as_ref().map_or(&self_ty.ty, |it| &it.ty))
+        };
+
+        let fp = TyFingerprint::for_inherent_impl(&ty);
+        let fp = match fp {
+            Some(fp) => fp,
+            None => return Vec::new(),
+        };
+
+        let mut all = Vec::new();
+        def_crates.iter().for_each(|&id| {
+            all.extend(
+                db.inherent_impls_in_crate(id)
+                    .for_self_ty(&ty)
+                    .iter()
+                    .cloned()
+                    .map(Self::from)
+                    .filter(filter),
+            )
+        });
+
+        for id in def_crates
+            .iter()
+            .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
+            .map(|Crate { id }| id)
+        {
+            all.extend(
+                db.trait_impls_in_crate(id)
+                    .for_self_ty_without_blanket_impls(fp)
+                    .map(Self::from)
+                    .filter(filter),
+            );
+        }
+
+        if let Some(block) =
+            ty.adt_id(Interner).and_then(|def| def.0.module(db.upcast()).containing_block())
+        {
+            if let Some(inherent_impls) = db.inherent_impls_in_block(block) {
+                all.extend(
+                    inherent_impls.for_self_ty(&ty).iter().cloned().map(Self::from).filter(filter),
+                );
+            }
+            if let Some(trait_impls) = db.trait_impls_in_block(block) {
+                all.extend(
+                    trait_impls
+                        .for_self_ty_without_blanket_impls(fp)
+                        .map(Self::from)
+                        .filter(filter),
+                );
+            }
+        }
+
+        all
+    }
+
+    pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
+        let module = trait_.module(db);
+        let krate = module.krate();
+        let mut all = Vec::new();
+        for Crate { id } in krate.transitive_reverse_dependencies(db) {
+            let impls = db.trait_impls_in_crate(id);
+            all.extend(impls.for_trait(trait_.id).map(Self::from))
+        }
+        if let Some(block) = module.id.containing_block() {
+            if let Some(trait_impls) = db.trait_impls_in_block(block) {
+                all.extend(trait_impls.for_trait(trait_.id).map(Self::from));
+            }
+        }
+        all
+    }
+
+    pub fn trait_(self, db: &dyn HirDatabase) -> Option<Trait> {
+        let trait_ref = db.impl_trait(self.id)?;
+        let id = trait_ref.skip_binders().hir_trait_id();
+        Some(Trait { id })
+    }
+
+    pub fn trait_ref(self, db: &dyn HirDatabase) -> Option<TraitRef> {
+        let substs = TyBuilder::placeholder_subst(db, self.id);
+        let trait_ref = db.impl_trait(self.id)?.substitute(Interner, &substs);
+        let resolver = self.id.resolver(db.upcast());
+        Some(TraitRef::new_with_resolver(db, &resolver, trait_ref))
+    }
+
+    pub fn self_ty(self, db: &dyn HirDatabase) -> Type {
+        let resolver = self.id.resolver(db.upcast());
+        let substs = TyBuilder::placeholder_subst(db, self.id);
+        let ty = db.impl_self_ty(self.id).substitute(Interner, &substs);
+        Type::new_with_resolver_inner(db, &resolver, ty)
+    }
+
+    pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
+        db.impl_data(self.id).items.iter().map(|&it| it.into()).collect()
+    }
+
+    pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
+        db.impl_data(self.id).is_negative
+    }
+
+    pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
+        db.impl_data(self.id).is_unsafe
+    }
+
+    pub fn module(self, db: &dyn HirDatabase) -> Module {
+        self.id.lookup(db.upcast()).container.into()
+    }
+
+    pub fn as_builtin_derive_path(self, db: &dyn HirDatabase) -> Option<InMacroFile<ast::Path>> {
+        let src = self.source(db)?;
+
+        let macro_file = src.file_id.macro_file()?;
+        let loc = macro_file.macro_call_id.lookup(db.upcast());
+        let (derive_attr, derive_index) = match loc.kind {
+            MacroCallKind::Derive { ast_id, derive_attr_index, derive_index, .. } => {
+                let module_id = self.id.lookup(db.upcast()).container;
+                (
+                    db.crate_def_map(module_id.krate())[module_id.local_id]
+                        .scope
+                        .derive_macro_invoc(ast_id, derive_attr_index)?,
+                    derive_index,
+                )
+            }
+            _ => return None,
+        };
+        let file_id = MacroFileId { macro_call_id: derive_attr };
+        let path = db
+            .parse_macro_expansion(file_id)
+            .value
+            .0
+            .syntax_node()
+            .children()
+            .nth(derive_index as usize)
+            .and_then(<ast::Attr as AstNode>::cast)
+            .and_then(|it| it.path())?;
+        Some(InMacroFile { file_id, value: path })
+    }
+
+    pub fn check_orphan_rules(self, db: &dyn HirDatabase) -> bool {
+        check_orphan_rules(db, self.id)
+    }
+}
+
+#[derive(Clone, PartialEq, Eq, Debug, Hash)]
+pub struct TraitRef {
+    env: Arc<TraitEnvironment>,
+    trait_ref: hir_ty::TraitRef,
+}
+
+impl TraitRef {
+    pub(crate) fn new_with_resolver(
+        db: &dyn HirDatabase,
+        resolver: &Resolver,
+        trait_ref: hir_ty::TraitRef,
+    ) -> TraitRef {
+        let env = resolver
+            .generic_def()
+            .map_or_else(|| TraitEnvironment::empty(resolver.krate()), |d| db.trait_environment(d));
+        TraitRef { env, trait_ref }
+    }
+
+    pub fn trait_(&self) -> Trait {
+        let id = self.trait_ref.hir_trait_id();
+        Trait { id }
+    }
+
+    pub fn self_ty(&self) -> Type {
+        let ty = self.trait_ref.self_type_parameter(Interner);
+        Type { env: self.env.clone(), ty }
+    }
+
+    /// Returns `idx`-th argument of this trait reference if it is a type argument. Note that the
+    /// first argument is the `Self` type.
+    pub fn get_type_argument(&self, idx: usize) -> Option<Type> {
+        self.trait_ref
+            .substitution
+            .as_slice(Interner)
+            .get(idx)
+            .and_then(|arg| arg.ty(Interner))
+            .cloned()
+            .map(|ty| Type { env: self.env.clone(), ty })
+    }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+pub struct Closure {
+    id: ClosureId,
+    subst: Substitution,
+}
+
+impl From<Closure> for ClosureId {
+    fn from(value: Closure) -> Self {
+        value.id
+    }
+}
+
+impl Closure {
+    fn as_ty(self) -> Ty {
+        TyKind::Closure(self.id, self.subst).intern(Interner)
+    }
+
+    pub fn display_with_id(&self, db: &dyn HirDatabase) -> String {
+        self.clone().as_ty().display(db).with_closure_style(ClosureStyle::ClosureWithId).to_string()
+    }
+
+    pub fn display_with_impl(&self, db: &dyn HirDatabase) -> String {
+        self.clone().as_ty().display(db).with_closure_style(ClosureStyle::ImplFn).to_string()
+    }
+
+    pub fn captured_items(&self, db: &dyn HirDatabase) -> Vec<ClosureCapture> {
+        let owner = db.lookup_intern_closure((self.id).into()).0;
+        let infer = &db.infer(owner);
+        let info = infer.closure_info(&self.id);
+        info.0
+            .iter()
+            .cloned()
+            .map(|capture| ClosureCapture { owner, closure: self.id, capture })
+            .collect()
+    }
+
+    pub fn capture_types(&self, db: &dyn HirDatabase) -> Vec<Type> {
+        let owner = db.lookup_intern_closure((self.id).into()).0;
+        let infer = &db.infer(owner);
+        let (captures, _) = infer.closure_info(&self.id);
+        captures
+            .iter()
+            .map(|capture| Type {
+                env: db.trait_environment_for_body(owner),
+                ty: capture.ty(&self.subst),
+            })
+            .collect()
+    }
+
+    pub fn fn_trait(&self, db: &dyn HirDatabase) -> FnTrait {
+        let owner = db.lookup_intern_closure((self.id).into()).0;
+        let infer = &db.infer(owner);
+        let info = infer.closure_info(&self.id);
+        info.1
+    }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ClosureCapture {
+    owner: DefWithBodyId,
+    closure: ClosureId,
+    capture: hir_ty::CapturedItem,
+}
+
+impl ClosureCapture {
+    pub fn local(&self) -> Local {
+        Local { parent: self.owner, binding_id: self.capture.local() }
+    }
+
+    pub fn kind(&self) -> CaptureKind {
+        match self.capture.kind() {
+            hir_ty::CaptureKind::ByRef(
+                hir_ty::mir::BorrowKind::Shallow | hir_ty::mir::BorrowKind::Shared,
+            ) => CaptureKind::SharedRef,
+            hir_ty::CaptureKind::ByRef(hir_ty::mir::BorrowKind::Mut {
+                kind: MutBorrowKind::ClosureCapture,
+            }) => CaptureKind::UniqueSharedRef,
+            hir_ty::CaptureKind::ByRef(hir_ty::mir::BorrowKind::Mut {
+                kind: MutBorrowKind::Default | MutBorrowKind::TwoPhasedBorrow,
+            }) => CaptureKind::MutableRef,
+            hir_ty::CaptureKind::ByValue => CaptureKind::Move,
+        }
+    }
+
+    pub fn display_place(&self, db: &dyn HirDatabase) -> String {
+        self.capture.display_place(self.owner, db)
+    }
+}
+
+pub enum CaptureKind {
+    SharedRef,
+    UniqueSharedRef,
+    MutableRef,
+    Move,
+}
+
+#[derive(Clone, PartialEq, Eq, Debug, Hash)]
+pub struct Type {
+    env: Arc<TraitEnvironment>,
+    ty: Ty,
+}
+
+impl Type {
+    pub(crate) fn new_with_resolver(db: &dyn HirDatabase, resolver: &Resolver, ty: Ty) -> Type {
+        Type::new_with_resolver_inner(db, resolver, ty)
+    }
+
+    pub(crate) fn new_with_resolver_inner(
+        db: &dyn HirDatabase,
+        resolver: &Resolver,
+        ty: Ty,
+    ) -> Type {
+        let environment = resolver
+            .generic_def()
+            .map_or_else(|| TraitEnvironment::empty(resolver.krate()), |d| db.trait_environment(d));
+        Type { env: environment, ty }
+    }
+
+    pub(crate) fn new_for_crate(krate: CrateId, ty: Ty) -> Type {
+        Type { env: TraitEnvironment::empty(krate), ty }
+    }
+
+    pub fn reference(inner: &Type, m: Mutability) -> Type {
+        inner.derived(
+            TyKind::Ref(
+                if m.is_mut() { hir_ty::Mutability::Mut } else { hir_ty::Mutability::Not },
+                hir_ty::error_lifetime(),
+                inner.ty.clone(),
+            )
+            .intern(Interner),
+        )
+    }
+
+    fn new(db: &dyn HirDatabase, lexical_env: impl HasResolver, ty: Ty) -> Type {
+        let resolver = lexical_env.resolver(db.upcast());
+        let environment = resolver
+            .generic_def()
+            .map_or_else(|| TraitEnvironment::empty(resolver.krate()), |d| db.trait_environment(d));
+        Type { env: environment, ty }
+    }
+
+    fn from_def(db: &dyn HirDatabase, def: impl Into<TyDefId> + HasResolver) -> Type {
+        let ty = db.ty(def.into());
+        let substs = TyBuilder::unknown_subst(
+            db,
+            match def.into() {
+                TyDefId::AdtId(it) => GenericDefId::AdtId(it),
+                TyDefId::TypeAliasId(it) => GenericDefId::TypeAliasId(it),
+                TyDefId::BuiltinType(_) => return Type::new(db, def, ty.skip_binders().clone()),
+            },
+        );
+        Type::new(db, def, ty.substitute(Interner, &substs))
+    }
+
+    fn from_value_def(db: &dyn HirDatabase, def: impl Into<ValueTyDefId> + HasResolver) -> Type {
+        let Some(ty) = db.value_ty(def.into()) else {
+            return Type::new(db, def, TyKind::Error.intern(Interner));
+        };
+        let substs = TyBuilder::unknown_subst(
+            db,
+            match def.into() {
+                ValueTyDefId::ConstId(it) => GenericDefId::ConstId(it),
+                ValueTyDefId::FunctionId(it) => GenericDefId::FunctionId(it),
+                ValueTyDefId::StructId(it) => GenericDefId::AdtId(AdtId::StructId(it)),
+                ValueTyDefId::UnionId(it) => GenericDefId::AdtId(AdtId::UnionId(it)),
+                ValueTyDefId::EnumVariantId(it) => GenericDefId::EnumVariantId(it),
+                ValueTyDefId::StaticId(_) => return Type::new(db, def, ty.skip_binders().clone()),
+            },
+        );
+        Type::new(db, def, ty.substitute(Interner, &substs))
+    }
+
+    pub fn new_slice(ty: Type) -> Type {
+        Type { env: ty.env, ty: TyBuilder::slice(ty.ty) }
+    }
+
+    pub fn new_tuple(krate: CrateId, tys: &[Type]) -> Type {
+        let tys = tys.iter().map(|it| it.ty.clone());
+        Type { env: TraitEnvironment::empty(krate), ty: TyBuilder::tuple_with(tys) }
+    }
+
+    pub fn is_unit(&self) -> bool {
+        matches!(self.ty.kind(Interner), TyKind::Tuple(0, ..))
+    }
+
+    pub fn is_bool(&self) -> bool {
+        matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Bool))
+    }
+
+    pub fn is_never(&self) -> bool {
+        matches!(self.ty.kind(Interner), TyKind::Never)
+    }
+
+    pub fn is_mutable_reference(&self) -> bool {
+        matches!(self.ty.kind(Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
+    }
+
+    pub fn is_reference(&self) -> bool {
+        matches!(self.ty.kind(Interner), TyKind::Ref(..))
+    }
+
+    pub fn contains_reference(&self, db: &dyn HirDatabase) -> bool {
+        return go(db, self.env.krate, &self.ty);
+
+        fn go(db: &dyn HirDatabase, krate: CrateId, ty: &Ty) -> bool {
+            match ty.kind(Interner) {
+                // Reference itself
+                TyKind::Ref(_, _, _) => true,
+
+                // For non-phantom_data adts we check variants/fields as well as generic parameters
+                TyKind::Adt(adt_id, substitution)
+                    if !db.adt_datum(krate, *adt_id).flags.phantom_data =>
+                {
+                    let adt_datum = &db.adt_datum(krate, *adt_id);
+                    let adt_datum_bound =
+                        adt_datum.binders.clone().substitute(Interner, substitution);
+                    adt_datum_bound
+                        .variants
+                        .into_iter()
+                        .flat_map(|variant| variant.fields.into_iter())
+                        .any(|ty| go(db, krate, &ty))
+                        || substitution
+                            .iter(Interner)
+                            .filter_map(|x| x.ty(Interner))
+                            .any(|ty| go(db, krate, ty))
+                }
+                // And for `PhantomData<T>`, we check `T`.
+                TyKind::Adt(_, substitution)
+                | TyKind::Tuple(_, substitution)
+                | TyKind::OpaqueType(_, substitution)
+                | TyKind::AssociatedType(_, substitution)
+                | TyKind::FnDef(_, substitution) => substitution
+                    .iter(Interner)
+                    .filter_map(|x| x.ty(Interner))
+                    .any(|ty| go(db, krate, ty)),
+
+                // For `[T]` or `*T` we check `T`
+                TyKind::Array(ty, _) | TyKind::Slice(ty) | TyKind::Raw(_, ty) => go(db, krate, ty),
+
+                // Consider everything else as not reference
+                _ => false,
+            }
+        }
+    }
+
+    pub fn as_reference(&self) -> Option<(Type, Mutability)> {
+        let (ty, _lt, m) = self.ty.as_reference()?;
+        let m = Mutability::from_mutable(matches!(m, hir_ty::Mutability::Mut));
+        Some((self.derived(ty.clone()), m))
+    }
+
+    pub fn is_slice(&self) -> bool {
+        matches!(self.ty.kind(Interner), TyKind::Slice(..))
+    }
+
+    pub fn is_usize(&self) -> bool {
+        matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Uint(UintTy::Usize)))
+    }
+
+    pub fn is_float(&self) -> bool {
+        matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Float(_)))
+    }
+
+    pub fn is_char(&self) -> bool {
+        matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Char))
+    }
+
+    pub fn is_int_or_uint(&self) -> bool {
+        matches!(self.ty.kind(Interner), TyKind::Scalar(Scalar::Int(_) | Scalar::Uint(_)))
+    }
+
+    pub fn is_scalar(&self) -> bool {
+        matches!(self.ty.kind(Interner), TyKind::Scalar(_))
+    }
+
+    pub fn is_tuple(&self) -> bool {
+        matches!(self.ty.kind(Interner), TyKind::Tuple(..))
+    }
+
+    pub fn remove_ref(&self) -> Option<Type> {
+        match &self.ty.kind(Interner) {
+            TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
+            _ => None,
+        }
+    }
+
+    pub fn as_slice(&self) -> Option<Type> {
+        match &self.ty.kind(Interner) {
+            TyKind::Slice(ty) => Some(self.derived(ty.clone())),
+            _ => None,
+        }
+    }
+
+    pub fn strip_references(&self) -> Type {
+        self.derived(self.ty.strip_references().clone())
+    }
+
+    pub fn strip_reference(&self) -> Type {
+        self.derived(self.ty.strip_reference().clone())
+    }
+
+    pub fn is_unknown(&self) -> bool {
+        self.ty.is_unknown()
+    }
+
+    /// Checks that particular type `ty` implements `std::future::IntoFuture` or
+    /// `std::future::Future`.
+    /// This function is used in `.await` syntax completion.
+    pub fn impls_into_future(&self, db: &dyn HirDatabase) -> bool {
+        let trait_ = db
+            .lang_item(self.env.krate, LangItem::IntoFutureIntoFuture)
+            .and_then(|it| {
+                let into_future_fn = it.as_function()?;
+                let assoc_item = as_assoc_item(db, AssocItem::Function, into_future_fn)?;
+                let into_future_trait = assoc_item.container_or_implemented_trait(db)?;
+                Some(into_future_trait.id)
+            })
+            .or_else(|| {
+                let future_trait = db.lang_item(self.env.krate, LangItem::Future)?;
+                future_trait.as_trait()
+            });
+
+        let trait_ = match trait_ {
+            Some(it) => it,
+            None => return false,
+        };
+
+        let canonical_ty =
+            Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(Interner) };
+        method_resolution::implements_trait(&canonical_ty, db, &self.env, trait_)
+    }
+
+    /// Checks that particular type `ty` implements `std::ops::FnOnce`.
+    ///
+    /// This function can be used to check if a particular type is callable, since FnOnce is a
+    /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
+    pub fn impls_fnonce(&self, db: &dyn HirDatabase) -> bool {
+        let fnonce_trait = match FnTrait::FnOnce.get_id(db, self.env.krate) {
+            Some(it) => it,
+            None => return false,
+        };
+
+        let canonical_ty =
+            Canonical { value: self.ty.clone(), binders: CanonicalVarKinds::empty(Interner) };
+        method_resolution::implements_trait_unique(&canonical_ty, db, &self.env, fnonce_trait)
+    }
+
+    // FIXME: Find better API that also handles const generics
+    pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
+        let mut it = args.iter().map(|t| t.ty.clone());
+        let trait_ref = TyBuilder::trait_ref(db, trait_.id)
+            .push(self.ty.clone())
+            .fill(|x| {
+                match x {
+                    ParamKind::Type => {
+                        it.next().unwrap_or_else(|| TyKind::Error.intern(Interner)).cast(Interner)
+                    }
+                    ParamKind::Const(ty) => {
+                        // FIXME: this code is not covered in tests.
+                        unknown_const_as_generic(ty.clone())
+                    }
+                    ParamKind::Lifetime => error_lifetime().cast(Interner),
+                }
+            })
+            .build();
+
+        let goal = Canonical {
+            value: hir_ty::InEnvironment::new(&self.env.env, trait_ref.cast(Interner)),
+            binders: CanonicalVarKinds::empty(Interner),
+        };
+
+        db.trait_solve(self.env.krate, self.env.block, goal).is_some()
+    }
+
+    pub fn normalize_trait_assoc_type(
+        &self,
+        db: &dyn HirDatabase,
+        args: &[Type],
+        alias: TypeAlias,
+    ) -> Option<Type> {
+        let mut args = args.iter();
+        let trait_id = match alias.id.lookup(db.upcast()).container {
+            ItemContainerId::TraitId(id) => id,
+            _ => unreachable!("non assoc type alias reached in normalize_trait_assoc_type()"),
+        };
+        let parent_subst = TyBuilder::subst_for_def(db, trait_id, None)
+            .push(self.ty.clone())
+            .fill(|it| {
+                // FIXME: this code is not covered in tests.
+                match it {
+                    ParamKind::Type => args.next().unwrap().ty.clone().cast(Interner),
+                    ParamKind::Const(ty) => unknown_const_as_generic(ty.clone()),
+                    ParamKind::Lifetime => error_lifetime().cast(Interner),
+                }
+            })
+            .build();
+        // FIXME: We don't handle GATs yet.
+        let projection = TyBuilder::assoc_type_projection(db, alias.id, Some(parent_subst)).build();
+
+        let ty = db.normalize_projection(projection, self.env.clone());
+        if ty.is_unknown() {
+            None
+        } else {
+            Some(self.derived(ty))
+        }
+    }
+
+    pub fn is_copy(&self, db: &dyn HirDatabase) -> bool {
+        let lang_item = db.lang_item(self.env.krate, LangItem::Copy);
+        let copy_trait = match lang_item {
+            Some(LangItemTarget::Trait(it)) => it,
+            _ => return false,
+        };
+        self.impls_trait(db, copy_trait.into(), &[])
+    }
+
+    pub fn as_callable(&self, db: &dyn HirDatabase) -> Option<Callable> {
+        let mut the_ty = &self.ty;
+        let callee = match self.ty.kind(Interner) {
+            TyKind::Ref(_, _, ty) if ty.as_closure().is_some() => {
+                the_ty = ty;
+                Callee::Closure(ty.as_closure().unwrap())
+            }
+            TyKind::Closure(id, _) => Callee::Closure(*id),
+            TyKind::Function(_) => Callee::FnPtr,
+            TyKind::FnDef(..) => Callee::Def(self.ty.callable_def(db)?),
+            _ => {
+                let sig = hir_ty::callable_sig_from_fnonce(&self.ty, self.env.clone(), db)?;
+                return Some(Callable {
+                    ty: self.clone(),
+                    sig,
+                    callee: Callee::Other,
+                    is_bound_method: false,
+                });
+            }
+        };
+
+        let sig = the_ty.callable_sig(db)?;
+        Some(Callable { ty: self.clone(), sig, callee, is_bound_method: false })
+    }
+
+    pub fn is_closure(&self) -> bool {
+        matches!(self.ty.kind(Interner), TyKind::Closure { .. })
+    }
+
+    pub fn as_closure(&self) -> Option<Closure> {
+        match self.ty.kind(Interner) {
+            TyKind::Closure(id, subst) => Some(Closure { id: *id, subst: subst.clone() }),
+            _ => None,
+        }
+    }
+
+    pub fn is_fn(&self) -> bool {
+        matches!(self.ty.kind(Interner), TyKind::FnDef(..) | TyKind::Function { .. })
+    }
+
+    pub fn is_array(&self) -> bool {
+        matches!(self.ty.kind(Interner), TyKind::Array(..))
+    }
+
+    pub fn is_packed(&self, db: &dyn HirDatabase) -> bool {
+        let adt_id = match *self.ty.kind(Interner) {
+            TyKind::Adt(hir_ty::AdtId(adt_id), ..) => adt_id,
+            _ => return false,
+        };
+
+        let adt = adt_id.into();
+        match adt {
+            Adt::Struct(s) => s.repr(db).unwrap_or_default().pack.is_some(),
+            _ => false,
+        }
+    }
+
+    pub fn is_raw_ptr(&self) -> bool {
+        matches!(self.ty.kind(Interner), TyKind::Raw(..))
+    }
+
+    pub fn remove_raw_ptr(&self) -> Option<Type> {
+        if let TyKind::Raw(_, ty) = self.ty.kind(Interner) {
+            Some(self.derived(ty.clone()))
+        } else {
+            None
+        }
+    }
+
+    pub fn contains_unknown(&self) -> bool {
+        // FIXME: When we get rid of `ConstScalar::Unknown`, we can just look at precomputed
+        // `TypeFlags` in `TyData`.
+        return go(&self.ty);
+
+        fn go(ty: &Ty) -> bool {
+            match ty.kind(Interner) {
+                TyKind::Error => true,
+
+                TyKind::Adt(_, substs)
+                | TyKind::AssociatedType(_, substs)
+                | TyKind::Tuple(_, substs)
+                | TyKind::OpaqueType(_, substs)
+                | TyKind::FnDef(_, substs)
+                | TyKind::Closure(_, substs) => {
+                    substs.iter(Interner).filter_map(|a| a.ty(Interner)).any(go)
+                }
+
+                TyKind::Array(_ty, len) if len.is_unknown() => true,
+                TyKind::Array(ty, _)
+                | TyKind::Slice(ty)
+                | TyKind::Raw(_, ty)
+                | TyKind::Ref(_, _, ty) => go(ty),
+
+                TyKind::Scalar(_)
+                | TyKind::Str
+                | TyKind::Never
+                | TyKind::Placeholder(_)
+                | TyKind::BoundVar(_)
+                | TyKind::InferenceVar(_, _)
+                | TyKind::Dyn(_)
+                | TyKind::Function(_)
+                | TyKind::Alias(_)
+                | TyKind::Foreign(_)
+                | TyKind::Coroutine(..)
+                | TyKind::CoroutineWitness(..) => false,
+            }
+        }
+    }
+
+    pub fn fields(&self, db: &dyn HirDatabase) -> Vec<(Field, Type)> {
+        let (variant_id, substs) = match self.ty.kind(Interner) {
+            TyKind::Adt(hir_ty::AdtId(AdtId::StructId(s)), substs) => ((*s).into(), substs),
+            TyKind::Adt(hir_ty::AdtId(AdtId::UnionId(u)), substs) => ((*u).into(), substs),
+            _ => return Vec::new(),
+        };
+
+        db.field_types(variant_id)
+            .iter()
+            .map(|(local_id, ty)| {
+                let def = Field { parent: variant_id.into(), id: local_id };
+                let ty = ty.clone().substitute(Interner, substs);
+                (def, self.derived(ty))
+            })
+            .collect()
+    }
+
+    pub fn tuple_fields(&self, _db: &dyn HirDatabase) -> Vec<Type> {
+        if let TyKind::Tuple(_, substs) = &self.ty.kind(Interner) {
+            substs
+                .iter(Interner)
+                .map(|ty| self.derived(ty.assert_ty_ref(Interner).clone()))
+                .collect()
+        } else {
+            Vec::new()
+        }
+    }
+
+    pub fn as_array(&self, db: &dyn HirDatabase) -> Option<(Type, usize)> {
+        if let TyKind::Array(ty, len) = &self.ty.kind(Interner) {
+            try_const_usize(db, len).map(|it| (self.derived(ty.clone()), it as usize))
+        } else {
+            None
+        }
+    }
+
+    pub fn fingerprint_for_trait_impl(&self) -> Option<TyFingerprint> {
+        TyFingerprint::for_trait_impl(&self.ty)
+    }
+
+    pub(crate) fn canonical(&self) -> Canonical<Ty> {
+        hir_ty::replace_errors_with_variables(&self.ty)
+    }
+
+    /// Returns types that this type dereferences to (including this type itself). The returned
+    /// iterator won't yield the same type more than once even if the deref chain contains a cycle.
+    pub fn autoderef(&self, db: &dyn HirDatabase) -> impl Iterator<Item = Type> + '_ {
+        self.autoderef_(db).map(move |ty| self.derived(ty))
+    }
+
+    fn autoderef_(&self, db: &dyn HirDatabase) -> impl Iterator<Item = Ty> {
+        // There should be no inference vars in types passed here
+        let canonical = hir_ty::replace_errors_with_variables(&self.ty);
+        autoderef(db, self.env.clone(), canonical)
+    }
+
+    // This would be nicer if it just returned an iterator, but that runs into
+    // lifetime problems, because we need to borrow temp `CrateImplDefs`.
+    pub fn iterate_assoc_items<T>(
+        &self,
+        db: &dyn HirDatabase,
+        krate: Crate,
+        mut callback: impl FnMut(AssocItem) -> Option<T>,
+    ) -> Option<T> {
+        let mut slot = None;
+        self.iterate_assoc_items_dyn(db, krate, &mut |assoc_item_id| {
+            slot = callback(assoc_item_id.into());
+            slot.is_some()
+        });
+        slot
+    }
+
+    fn iterate_assoc_items_dyn(
+        &self,
+        db: &dyn HirDatabase,
+        krate: Crate,
+        callback: &mut dyn FnMut(AssocItemId) -> bool,
+    ) {
+        let def_crates = match method_resolution::def_crates(db, &self.ty, krate.id) {
+            Some(it) => it,
+            None => return,
+        };
+        for krate in def_crates {
+            let impls = db.inherent_impls_in_crate(krate);
+
+            for impl_def in impls.for_self_ty(&self.ty) {
+                for &item in db.impl_data(*impl_def).items.iter() {
+                    if callback(item) {
+                        return;
+                    }
+                }
+            }
+        }
+    }
+
+    /// Iterates its type arguments
+    ///
+    /// It iterates the actual type arguments when concrete types are used
+    /// and otherwise the generic names.
+    /// It does not include `const` arguments.
+    ///
+    /// For code, such as:
+    /// ```text
+    /// struct Foo<T, U>
+    ///
+    /// impl<U> Foo<String, U>
+    /// ```
+    ///
+    /// It iterates:
+    /// ```text
+    /// - "String"
+    /// - "U"
+    /// ```
+    pub fn type_arguments(&self) -> impl Iterator<Item = Type> + '_ {
+        self.ty
+            .strip_references()
+            .as_adt()
+            .map(|(_, substs)| substs)
+            .or_else(|| self.ty.strip_references().as_tuple())
+            .into_iter()
+            .flat_map(|substs| substs.iter(Interner))
+            .filter_map(|arg| arg.ty(Interner).cloned())
+            .map(move |ty| self.derived(ty))
+    }
+
+    /// Iterates its type and const arguments
+    ///
+    /// It iterates the actual type and const arguments when concrete types
+    /// are used and otherwise the generic names.
+    ///
+    /// For code, such as:
+    /// ```text
+    /// struct Foo<T, const U: usize, const X: usize>
+    ///
+    /// impl<U> Foo<String, U, 12>
+    /// ```
+    ///
+    /// It iterates:
+    /// ```text
+    /// - "String"
+    /// - "U"
+    /// - "12"
+    /// ```
+    pub fn type_and_const_arguments<'a>(
+        &'a self,
+        db: &'a dyn HirDatabase,
+    ) -> impl Iterator<Item = SmolStr> + 'a {
+        self.ty
+            .strip_references()
+            .as_adt()
+            .into_iter()
+            .flat_map(|(_, substs)| substs.iter(Interner))
+            .filter_map(|arg| {
+                // arg can be either a `Ty` or `constant`
+                if let Some(ty) = arg.ty(Interner) {
+                    Some(format_smolstr!("{}", ty.display(db)))
+                } else {
+                    arg.constant(Interner).map(|const_| format_smolstr!("{}", const_.display(db)))
+                }
+            })
+    }
+
+    /// Combines lifetime indicators, type and constant parameters into a single `Iterator`
+    pub fn generic_parameters<'a>(
+        &'a self,
+        db: &'a dyn HirDatabase,
+    ) -> impl Iterator<Item = SmolStr> + 'a {
+        // iterate the lifetime
+        self.as_adt()
+            .and_then(|a| a.lifetime(db).map(|lt| lt.name.to_smol_str()))
+            .into_iter()
+            // add the type and const parameters
+            .chain(self.type_and_const_arguments(db))
+    }
+
+    pub fn iterate_method_candidates_with_traits<T>(
+        &self,
+        db: &dyn HirDatabase,
+        scope: &SemanticsScope<'_>,
+        traits_in_scope: &FxHashSet<TraitId>,
+        with_local_impls: Option<Module>,
+        name: Option<&Name>,
+        mut callback: impl FnMut(Function) -> Option<T>,
+    ) -> Option<T> {
+        let _p = tracing::span!(tracing::Level::INFO, "iterate_method_candidates");
+        let mut slot = None;
+
+        self.iterate_method_candidates_dyn(
+            db,
+            scope,
+            traits_in_scope,
+            with_local_impls,
+            name,
+            &mut |assoc_item_id| {
+                if let AssocItemId::FunctionId(func) = assoc_item_id {
+                    if let Some(res) = callback(func.into()) {
+                        slot = Some(res);
+                        return ControlFlow::Break(());
+                    }
+                }
+                ControlFlow::Continue(())
+            },
+        );
+        slot
+    }
+
+    pub fn iterate_method_candidates<T>(
+        &self,
+        db: &dyn HirDatabase,
+        scope: &SemanticsScope<'_>,
+        with_local_impls: Option<Module>,
+        name: Option<&Name>,
+        callback: impl FnMut(Function) -> Option<T>,
+    ) -> Option<T> {
+        self.iterate_method_candidates_with_traits(
+            db,
+            scope,
+            &scope.visible_traits().0,
+            with_local_impls,
+            name,
+            callback,
+        )
+    }
+
+    fn iterate_method_candidates_dyn(
+        &self,
+        db: &dyn HirDatabase,
+        scope: &SemanticsScope<'_>,
+        traits_in_scope: &FxHashSet<TraitId>,
+        with_local_impls: Option<Module>,
+        name: Option<&Name>,
+        callback: &mut dyn FnMut(AssocItemId) -> ControlFlow<()>,
+    ) {
+        let _p = tracing::span!(
+            tracing::Level::INFO,
+            "iterate_method_candidates_dyn",
+            with_local_impls = traits_in_scope.len(),
+            traits_in_scope = traits_in_scope.len(),
+            ?name,
+        )
+        .entered();
+        // There should be no inference vars in types passed here
+        let canonical = hir_ty::replace_errors_with_variables(&self.ty);
+
+        let krate = scope.krate();
+        let environment = scope
+            .resolver()
+            .generic_def()
+            .map_or_else(|| TraitEnvironment::empty(krate.id), |d| db.trait_environment(d));
+
+        method_resolution::iterate_method_candidates_dyn(
+            &canonical,
+            db,
+            environment,
+            traits_in_scope,
+            with_local_impls.and_then(|b| b.id.containing_block()).into(),
+            name,
+            method_resolution::LookupMode::MethodCall,
+            &mut |_adj, id, _| callback(id),
+        );
+    }
+
+    #[tracing::instrument(skip_all, fields(name = ?name))]
+    pub fn iterate_path_candidates<T>(
+        &self,
+        db: &dyn HirDatabase,
+        scope: &SemanticsScope<'_>,
+        traits_in_scope: &FxHashSet<TraitId>,
+        with_local_impls: Option<Module>,
+        name: Option<&Name>,
+        mut callback: impl FnMut(AssocItem) -> Option<T>,
+    ) -> Option<T> {
+        let _p = tracing::span!(tracing::Level::INFO, "iterate_path_candidates");
+        let mut slot = None;
+        self.iterate_path_candidates_dyn(
+            db,
+            scope,
+            traits_in_scope,
+            with_local_impls,
+            name,
+            &mut |assoc_item_id| {
+                if let Some(res) = callback(assoc_item_id.into()) {
+                    slot = Some(res);
+                    return ControlFlow::Break(());
+                }
+                ControlFlow::Continue(())
+            },
+        );
+        slot
+    }
+
+    #[tracing::instrument(skip_all, fields(name = ?name))]
+    fn iterate_path_candidates_dyn(
+        &self,
+        db: &dyn HirDatabase,
+        scope: &SemanticsScope<'_>,
+        traits_in_scope: &FxHashSet<TraitId>,
+        with_local_impls: Option<Module>,
+        name: Option<&Name>,
+        callback: &mut dyn FnMut(AssocItemId) -> ControlFlow<()>,
+    ) {
+        let canonical = hir_ty::replace_errors_with_variables(&self.ty);
+
+        let krate = scope.krate();
+        let environment = scope
+            .resolver()
+            .generic_def()
+            .map_or_else(|| TraitEnvironment::empty(krate.id), |d| db.trait_environment(d));
+
+        method_resolution::iterate_path_candidates(
+            &canonical,
+            db,
+            environment,
+            traits_in_scope,
+            with_local_impls.and_then(|b| b.id.containing_block()).into(),
+            name,
+            callback,
+        );
+    }
+
+    pub fn as_adt(&self) -> Option<Adt> {
+        let (adt, _subst) = self.ty.as_adt()?;
+        Some(adt.into())
+    }
+
+    pub fn as_builtin(&self) -> Option<BuiltinType> {
+        self.ty.as_builtin().map(|inner| BuiltinType { inner })
+    }
+
+    pub fn as_dyn_trait(&self) -> Option<Trait> {
+        self.ty.dyn_trait().map(Into::into)
+    }
+
+    /// If a type can be represented as `dyn Trait`, returns all traits accessible via this type,
+    /// or an empty iterator otherwise.
+    pub fn applicable_inherent_traits<'a>(
+        &'a self,
+        db: &'a dyn HirDatabase,
+    ) -> impl Iterator<Item = Trait> + 'a {
+        let _p = tracing::span!(tracing::Level::INFO, "applicable_inherent_traits");
+        self.autoderef_(db)
+            .filter_map(|ty| ty.dyn_trait())
+            .flat_map(move |dyn_trait_id| hir_ty::all_super_traits(db.upcast(), dyn_trait_id))
+            .map(Trait::from)
+    }
+
+    pub fn env_traits<'a>(&'a self, db: &'a dyn HirDatabase) -> impl Iterator<Item = Trait> + 'a {
+        let _p = tracing::span!(tracing::Level::INFO, "env_traits");
+        self.autoderef_(db)
+            .filter(|ty| matches!(ty.kind(Interner), TyKind::Placeholder(_)))
+            .flat_map(|ty| {
+                self.env
+                    .traits_in_scope_from_clauses(ty)
+                    .flat_map(|t| hir_ty::all_super_traits(db.upcast(), t))
+            })
+            .map(Trait::from)
+    }
+
+    pub fn as_impl_traits(&self, db: &dyn HirDatabase) -> Option<impl Iterator<Item = Trait>> {
+        self.ty.impl_trait_bounds(db).map(|it| {
+            it.into_iter().filter_map(|pred| match pred.skip_binders() {
+                hir_ty::WhereClause::Implemented(trait_ref) => {
+                    Some(Trait::from(trait_ref.hir_trait_id()))
+                }
+                _ => None,
+            })
+        })
+    }
+
+    pub fn as_associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<Trait> {
+        self.ty.associated_type_parent_trait(db).map(Into::into)
+    }
+
+    fn derived(&self, ty: Ty) -> Type {
+        Type { env: self.env.clone(), ty }
+    }
+
+    /// Visits every type, including generic arguments, in this type. `cb` is called with type
+    /// itself first, and then with its generic arguments.
+    pub fn walk(&self, db: &dyn HirDatabase, mut cb: impl FnMut(Type)) {
+        fn walk_substs(
+            db: &dyn HirDatabase,
+            type_: &Type,
+            substs: &Substitution,
+            cb: &mut impl FnMut(Type),
+        ) {
+            for ty in substs.iter(Interner).filter_map(|a| a.ty(Interner)) {
+                walk_type(db, &type_.derived(ty.clone()), cb);
+            }
+        }
+
+        fn walk_bounds(
+            db: &dyn HirDatabase,
+            type_: &Type,
+            bounds: &[QuantifiedWhereClause],
+            cb: &mut impl FnMut(Type),
+        ) {
+            for pred in bounds {
+                if let WhereClause::Implemented(trait_ref) = pred.skip_binders() {
+                    cb(type_.clone());
+                    // skip the self type. it's likely the type we just got the bounds from
+                    if let [self_ty, params @ ..] = trait_ref.substitution.as_slice(Interner) {
+                        for ty in
+                            params.iter().filter(|&ty| ty != self_ty).filter_map(|a| a.ty(Interner))
+                        {
+                            walk_type(db, &type_.derived(ty.clone()), cb);
+                        }
+                    }
+                }
+            }
+        }
+
+        fn walk_type(db: &dyn HirDatabase, type_: &Type, cb: &mut impl FnMut(Type)) {
+            let ty = type_.ty.strip_references();
+            match ty.kind(Interner) {
+                TyKind::Adt(_, substs) => {
+                    cb(type_.derived(ty.clone()));
+                    walk_substs(db, type_, substs, cb);
+                }
+                TyKind::AssociatedType(_, substs) => {
+                    if ty.associated_type_parent_trait(db).is_some() {
+                        cb(type_.derived(ty.clone()));
+                    }
+                    walk_substs(db, type_, substs, cb);
+                }
+                TyKind::OpaqueType(_, subst) => {
+                    if let Some(bounds) = ty.impl_trait_bounds(db) {
+                        walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
+                    }
+
+                    walk_substs(db, type_, subst, cb);
+                }
+                TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
+                    if let Some(bounds) = ty.impl_trait_bounds(db) {
+                        walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
+                    }
+
+                    walk_substs(db, type_, &opaque_ty.substitution, cb);
+                }
+                TyKind::Placeholder(_) => {
+                    if let Some(bounds) = ty.impl_trait_bounds(db) {
+                        walk_bounds(db, &type_.derived(ty.clone()), &bounds, cb);
+                    }
+                }
+                TyKind::Dyn(bounds) => {
+                    walk_bounds(
+                        db,
+                        &type_.derived(ty.clone()),
+                        bounds.bounds.skip_binders().interned(),
+                        cb,
+                    );
+                }
+
+                TyKind::Ref(_, _, ty)
+                | TyKind::Raw(_, ty)
+                | TyKind::Array(ty, _)
+                | TyKind::Slice(ty) => {
+                    walk_type(db, &type_.derived(ty.clone()), cb);
+                }
+
+                TyKind::FnDef(_, substs)
+                | TyKind::Tuple(_, substs)
+                | TyKind::Closure(.., substs) => {
+                    walk_substs(db, type_, substs, cb);
+                }
+                TyKind::Function(hir_ty::FnPointer { substitution, .. }) => {
+                    walk_substs(db, type_, &substitution.0, cb);
+                }
+
+                _ => {}
+            }
+        }
+
+        walk_type(db, self, &mut cb);
+    }
+    /// Check if type unifies with another type.
+    ///
+    /// Note that we consider placeholder types to unify with everything.
+    /// For example `Option<T>` and `Option<U>` unify although there is unresolved goal `T = U`.
+    pub fn could_unify_with(&self, db: &dyn HirDatabase, other: &Type) -> bool {
+        let tys = hir_ty::replace_errors_with_variables(&(self.ty.clone(), other.ty.clone()));
+        hir_ty::could_unify(db, self.env.clone(), &tys)
+    }
+
+    /// Check if type unifies with another type eagerly making sure there are no unresolved goals.
+    ///
+    /// This means that placeholder types are not considered to unify if there are any bounds set on
+    /// them. For example `Option<T>` and `Option<U>` do not unify as we cannot show that `T = U`
+    pub fn could_unify_with_deeply(&self, db: &dyn HirDatabase, other: &Type) -> bool {
+        let tys = hir_ty::replace_errors_with_variables(&(self.ty.clone(), other.ty.clone()));
+        hir_ty::could_unify_deeply(db, self.env.clone(), &tys)
+    }
+
+    pub fn could_coerce_to(&self, db: &dyn HirDatabase, to: &Type) -> bool {
+        let tys = hir_ty::replace_errors_with_variables(&(self.ty.clone(), to.ty.clone()));
+        hir_ty::could_coerce(db, self.env.clone(), &tys)
+    }
+
+    pub fn as_type_param(&self, db: &dyn HirDatabase) -> Option<TypeParam> {
+        match self.ty.kind(Interner) {
+            TyKind::Placeholder(p) => Some(TypeParam {
+                id: TypeParamId::from_unchecked(hir_ty::from_placeholder_idx(db, *p)),
+            }),
+            _ => None,
+        }
+    }
+
+    /// Returns unique `GenericParam`s contained in this type.
+    pub fn generic_params(&self, db: &dyn HirDatabase) -> FxHashSet<GenericParam> {
+        hir_ty::collect_placeholders(&self.ty, db)
+            .into_iter()
+            .map(|id| TypeOrConstParam { id }.split(db).either_into())
+            .collect()
+    }
+
+    pub fn layout(&self, db: &dyn HirDatabase) -> Result<Layout, LayoutError> {
+        db.layout_of_ty(self.ty.clone(), self.env.clone())
+            .map(|layout| Layout(layout, db.target_data_layout(self.env.krate).unwrap()))
+    }
+}
+
+// FIXME: Document this
+#[derive(Debug)]
+pub struct Callable {
+    ty: Type,
+    sig: CallableSig,
+    callee: Callee,
+    /// Whether this is a method that was called with method call syntax.
+    pub(crate) is_bound_method: bool,
+}
+
+#[derive(Debug)]
+enum Callee {
+    Def(CallableDefId),
+    Closure(ClosureId),
+    FnPtr,
+    Other,
+}
+
+pub enum CallableKind {
+    Function(Function),
+    TupleStruct(Struct),
+    TupleEnumVariant(Variant),
+    Closure,
+    FnPtr,
+    /// Some other type that implements `FnOnce`.
+    Other,
+}
+
+impl Callable {
+    pub fn kind(&self) -> CallableKind {
+        use Callee::*;
+        match self.callee {
+            Def(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
+            Def(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
+            Def(CallableDefId::EnumVariantId(it)) => CallableKind::TupleEnumVariant(it.into()),
+            Closure(_) => CallableKind::Closure,
+            FnPtr => CallableKind::FnPtr,
+            Other => CallableKind::Other,
+        }
+    }
+    pub fn receiver_param(&self, db: &dyn HirDatabase) -> Option<(SelfParam, Type)> {
+        let func = match self.callee {
+            Callee::Def(CallableDefId::FunctionId(it)) if self.is_bound_method => it,
+            _ => return None,
+        };
+        let func = Function { id: func };
+        Some((func.self_param(db)?, self.ty.derived(self.sig.params()[0].clone())))
+    }
+    pub fn n_params(&self) -> usize {
+        self.sig.params().len() - if self.is_bound_method { 1 } else { 0 }
+    }
+    pub fn params(
+        &self,
+        db: &dyn HirDatabase,
+    ) -> Vec<(Option<Either<ast::SelfParam, ast::Pat>>, Type)> {
+        let types = self
+            .sig
+            .params()
+            .iter()
+            .skip(if self.is_bound_method { 1 } else { 0 })
+            .map(|ty| self.ty.derived(ty.clone()));
+        let map_param = |it: ast::Param| it.pat().map(Either::Right);
+        let patterns = match self.callee {
+            Callee::Def(CallableDefId::FunctionId(func)) => {
+                let src = func.lookup(db.upcast()).source(db.upcast());
+                src.value.param_list().map(|param_list| {
+                    param_list
+                        .self_param()
+                        .map(|it| Some(Either::Left(it)))
+                        .filter(|_| !self.is_bound_method)
+                        .into_iter()
+                        .chain(param_list.params().map(map_param))
+                })
+            }
+            Callee::Closure(closure_id) => match closure_source(db, closure_id) {
+                Some(src) => src.param_list().map(|param_list| {
+                    param_list
+                        .self_param()
+                        .map(|it| Some(Either::Left(it)))
+                        .filter(|_| !self.is_bound_method)
+                        .into_iter()
+                        .chain(param_list.params().map(map_param))
+                }),
+                None => None,
+            },
+            _ => None,
+        };
+        patterns.into_iter().flatten().chain(iter::repeat(None)).zip(types).collect()
+    }
+    pub fn return_type(&self) -> Type {
+        self.ty.derived(self.sig.ret().clone())
+    }
+    pub fn sig(&self) -> &CallableSig {
+        &self.sig
+    }
+}
+
+fn closure_source(db: &dyn HirDatabase, closure: ClosureId) -> Option<ast::ClosureExpr> {
+    let InternedClosure(owner, expr_id) = db.lookup_intern_closure(closure.into());
+    let (_, source_map) = db.body_with_source_map(owner);
+    let ast = source_map.expr_syntax(expr_id).ok()?;
+    let root = ast.file_syntax(db.upcast());
+    let expr = ast.value.to_node(&root);
+    match expr {
+        ast::Expr::ClosureExpr(it) => Some(it),
+        _ => None,
+    }
+}
+
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct Layout(Arc<TyLayout>, Arc<TargetDataLayout>);
+
+impl Layout {
+    pub fn size(&self) -> u64 {
+        self.0.size.bytes()
+    }
+
+    pub fn align(&self) -> u64 {
+        self.0.align.abi.bytes()
+    }
+
+    pub fn niches(&self) -> Option<u128> {
+        Some(self.0.largest_niche?.available(&*self.1))
+    }
+
+    pub fn field_offset(&self, field: Field) -> Option<u64> {
+        match self.0.fields {
+            layout::FieldsShape::Primitive => None,
+            layout::FieldsShape::Union(_) => Some(0),
+            layout::FieldsShape::Array { stride, count } => {
+                let i = u64::try_from(field.index()).ok()?;
+                (i < count).then_some((stride * i).bytes())
+            }
+            layout::FieldsShape::Arbitrary { ref offsets, .. } => {
+                Some(offsets.get(RustcFieldIdx(field.id))?.bytes())
+            }
+        }
+    }
+
+    pub fn tuple_field_offset(&self, field: usize) -> Option<u64> {
+        match self.0.fields {
+            layout::FieldsShape::Primitive => None,
+            layout::FieldsShape::Union(_) => Some(0),
+            layout::FieldsShape::Array { stride, count } => {
+                let i = u64::try_from(field).ok()?;
+                (i < count).then_some((stride * i).bytes())
+            }
+            layout::FieldsShape::Arbitrary { ref offsets, .. } => {
+                Some(offsets.get(RustcFieldIdx::new(field))?.bytes())
+            }
+        }
+    }
+
+    pub fn enum_tag_size(&self) -> Option<usize> {
+        let tag_size =
+            if let layout::Variants::Multiple { tag, tag_encoding, .. } = &self.0.variants {
+                match tag_encoding {
+                    TagEncoding::Direct => tag.size(&*self.1).bytes_usize(),
+                    TagEncoding::Niche { .. } => 0,
+                }
+            } else {
+                return None;
+            };
+        Some(tag_size)
+    }
+}
+
+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
+pub enum BindingMode {
+    Move,
+    Ref(Mutability),
+}
+
+/// For IDE only
+#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
+pub enum ScopeDef {
+    ModuleDef(ModuleDef),
+    GenericParam(GenericParam),
+    ImplSelfType(Impl),
+    AdtSelfType(Adt),
+    Local(Local),
+    Label(Label),
+    Unknown,
+}
+
+impl ScopeDef {
+    pub fn all_items(def: PerNs) -> ArrayVec<Self, 3> {
+        let mut items = ArrayVec::new();
+
+        match (def.take_types(), def.take_values()) {
+            (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
+            (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
+            (Some(m1), Some(m2)) => {
+                // Some items, like unit structs and enum variants, are
+                // returned as both a type and a value. Here we want
+                // to de-duplicate them.
+                if m1 != m2 {
+                    items.push(ScopeDef::ModuleDef(m1.into()));
+                    items.push(ScopeDef::ModuleDef(m2.into()));
+                } else {
+                    items.push(ScopeDef::ModuleDef(m1.into()));
+                }
+            }
+            (None, None) => {}
+        };
+
+        if let Some(macro_def_id) = def.take_macros() {
+            items.push(ScopeDef::ModuleDef(ModuleDef::Macro(macro_def_id.into())));
+        }
+
+        if items.is_empty() {
+            items.push(ScopeDef::Unknown);
+        }
+
+        items
+    }
+
+    pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
+        match self {
+            ScopeDef::ModuleDef(it) => it.attrs(db),
+            ScopeDef::GenericParam(it) => Some(it.attrs(db)),
+            ScopeDef::ImplSelfType(_)
+            | ScopeDef::AdtSelfType(_)
+            | ScopeDef::Local(_)
+            | ScopeDef::Label(_)
+            | ScopeDef::Unknown => None,
+        }
+    }
+
+    pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
+        match self {
+            ScopeDef::ModuleDef(it) => it.module(db).map(|m| m.krate()),
+            ScopeDef::GenericParam(it) => Some(it.module(db).krate()),
+            ScopeDef::ImplSelfType(_) => None,
+            ScopeDef::AdtSelfType(it) => Some(it.module(db).krate()),
+            ScopeDef::Local(it) => Some(it.module(db).krate()),
+            ScopeDef::Label(it) => Some(it.module(db).krate()),
+            ScopeDef::Unknown => None,
+        }
+    }
+}
+
+impl From<ItemInNs> for ScopeDef {
+    fn from(item: ItemInNs) -> Self {
+        match item {
+            ItemInNs::Types(id) => ScopeDef::ModuleDef(id),
+            ItemInNs::Values(id) => ScopeDef::ModuleDef(id),
+            ItemInNs::Macros(id) => ScopeDef::ModuleDef(ModuleDef::Macro(id)),
+        }
+    }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Adjustment {
+    pub source: Type,
+    pub target: Type,
+    pub kind: Adjust,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum Adjust {
+    /// Go from ! to any type.
+    NeverToAny,
+    /// Dereference once, producing a place.
+    Deref(Option<OverloadedDeref>),
+    /// Take the address and produce either a `&` or `*` pointer.
+    Borrow(AutoBorrow),
+    Pointer(PointerCast),
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum AutoBorrow {
+    /// Converts from T to &T.
+    Ref(Mutability),
+    /// Converts from T to *T.
+    RawPtr(Mutability),
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct OverloadedDeref(pub Mutability);
+
+pub trait HasVisibility {
+    fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
+    fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
+        let vis = self.visibility(db);
+        vis.is_visible_from(db.upcast(), module.id)
+    }
+}
+
+/// Trait for obtaining the defining crate of an item.
+pub trait HasCrate {
+    fn krate(&self, db: &dyn HirDatabase) -> Crate;
+}
+
+impl<T: hir_def::HasModule> HasCrate for T {
+    fn krate(&self, db: &dyn HirDatabase) -> Crate {
+        self.module(db.upcast()).krate().into()
+    }
+}
+
+impl HasCrate for AssocItem {
+    fn krate(&self, db: &dyn HirDatabase) -> Crate {
+        self.module(db).krate()
+    }
+}
+
+impl HasCrate for Struct {
+    fn krate(&self, db: &dyn HirDatabase) -> Crate {
+        self.module(db).krate()
+    }
+}
+
+impl HasCrate for Union {
+    fn krate(&self, db: &dyn HirDatabase) -> Crate {
+        self.module(db).krate()
+    }
+}
+
+impl HasCrate for Enum {
+    fn krate(&self, db: &dyn HirDatabase) -> Crate {
+        self.module(db).krate()
+    }
+}
+
+impl HasCrate for Field {
+    fn krate(&self, db: &dyn HirDatabase) -> Crate {
+        self.parent_def(db).module(db).krate()
+    }
+}
+
+impl HasCrate for Variant {
+    fn krate(&self, db: &dyn HirDatabase) -> Crate {
+        self.module(db).krate()
+    }
+}
+
+impl HasCrate for Function {
+    fn krate(&self, db: &dyn HirDatabase) -> Crate {
+        self.module(db).krate()
+    }
+}
+
+impl HasCrate for Const {
+    fn krate(&self, db: &dyn HirDatabase) -> Crate {
+        self.module(db).krate()
+    }
+}
+
+impl HasCrate for TypeAlias {
+    fn krate(&self, db: &dyn HirDatabase) -> Crate {
+        self.module(db).krate()
+    }
+}
+
+impl HasCrate for Type {
+    fn krate(&self, _db: &dyn HirDatabase) -> Crate {
+        self.env.krate.into()
+    }
+}
+
+impl HasCrate for Macro {
+    fn krate(&self, db: &dyn HirDatabase) -> Crate {
+        self.module(db).krate()
+    }
+}
+
+impl HasCrate for Trait {
+    fn krate(&self, db: &dyn HirDatabase) -> Crate {
+        self.module(db).krate()
+    }
+}
+
+impl HasCrate for TraitAlias {
+    fn krate(&self, db: &dyn HirDatabase) -> Crate {
+        self.module(db).krate()
+    }
+}
+
+impl HasCrate for Static {
+    fn krate(&self, db: &dyn HirDatabase) -> Crate {
+        self.module(db).krate()
+    }
+}
+
+impl HasCrate for Adt {
+    fn krate(&self, db: &dyn HirDatabase) -> Crate {
+        self.module(db).krate()
+    }
+}
+
+impl HasCrate for Module {
+    fn krate(&self, _: &dyn HirDatabase) -> Crate {
+        Module::krate(*self)
+    }
+}
+
+pub trait HasContainer {
+    fn container(&self, db: &dyn HirDatabase) -> ItemContainer;
+}
+
+impl HasContainer for ExternCrateDecl {
+    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
+        container_id_to_hir(self.id.lookup(db.upcast()).container.into())
+    }
+}
+
+impl HasContainer for Module {
+    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
+        // FIXME: handle block expressions as modules (their parent is in a different DefMap)
+        let def_map = self.id.def_map(db.upcast());
+        match def_map[self.id.local_id].parent {
+            Some(parent_id) => ItemContainer::Module(Module { id: def_map.module_id(parent_id) }),
+            None => ItemContainer::Crate(def_map.krate()),
+        }
+    }
+}
+
+impl HasContainer for Function {
+    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
+        container_id_to_hir(self.id.lookup(db.upcast()).container)
+    }
+}
+
+impl HasContainer for Struct {
+    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
+        ItemContainer::Module(Module { id: self.id.lookup(db.upcast()).container })
+    }
+}
+
+impl HasContainer for Union {
+    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
+        ItemContainer::Module(Module { id: self.id.lookup(db.upcast()).container })
+    }
+}
+
+impl HasContainer for Enum {
+    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
+        ItemContainer::Module(Module { id: self.id.lookup(db.upcast()).container })
+    }
+}
+
+impl HasContainer for TypeAlias {
+    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
+        container_id_to_hir(self.id.lookup(db.upcast()).container)
+    }
+}
+
+impl HasContainer for Const {
+    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
+        container_id_to_hir(self.id.lookup(db.upcast()).container)
+    }
+}
+
+impl HasContainer for Static {
+    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
+        container_id_to_hir(self.id.lookup(db.upcast()).container)
+    }
+}
+
+impl HasContainer for Trait {
+    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
+        ItemContainer::Module(Module { id: self.id.lookup(db.upcast()).container })
+    }
+}
+
+impl HasContainer for TraitAlias {
+    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
+        ItemContainer::Module(Module { id: self.id.lookup(db.upcast()).container })
+    }
+}
+
+fn container_id_to_hir(c: ItemContainerId) -> ItemContainer {
+    match c {
+        ItemContainerId::ExternBlockId(_id) => ItemContainer::ExternBlock(),
+        ItemContainerId::ModuleId(id) => ItemContainer::Module(Module { id }),
+        ItemContainerId::ImplId(id) => ItemContainer::Impl(Impl { id }),
+        ItemContainerId::TraitId(id) => ItemContainer::Trait(Trait { id }),
+    }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum ItemContainer {
+    Trait(Trait),
+    Impl(Impl),
+    Module(Module),
+    ExternBlock(),
+    Crate(CrateId),
+}
+
+/// Subset of `ide_db::Definition` that doc links can resolve to.
+pub enum DocLinkDef {
+    ModuleDef(ModuleDef),
+    Field(Field),
+    SelfType(Trait),
+}
diff --git a/src/tools/rust-analyzer/crates/hir/src/semantics.rs b/src/tools/rust-analyzer/crates/hir/src/semantics.rs
new file mode 100644
index 00000000000..9796009cb45
--- /dev/null
+++ b/src/tools/rust-analyzer/crates/hir/src/semantics.rs
@@ -0,0 +1,1749 @@
+//! See `Semantics`.
+
+mod source_to_def;
+
+use std::{
+    cell::RefCell,
+    fmt, iter, mem,
+    ops::{self, ControlFlow, Not},
+};
+
+use base_db::{FileId, FileRange};
+use either::Either;
+use hir_def::{
+    hir::Expr,
+    lower::LowerCtx,
+    nameres::MacroSubNs,
+    resolver::{self, HasResolver, Resolver, TypeNs},
+    type_ref::Mutability,
+    AsMacroCall, DefWithBodyId, FunctionId, MacroId, TraitId, VariantId,
+};
+use hir_expand::{
+    attrs::collect_attrs, db::ExpandDatabase, files::InRealFile, name::AsName, ExpansionInfo,
+    InMacroFile, MacroCallId, MacroFileId, MacroFileIdExt,
+};
+use itertools::Itertools;
+use rustc_hash::{FxHashMap, FxHashSet};
+use smallvec::{smallvec, SmallVec};
+use span::{Span, SyntaxContextId, ROOT_ERASED_FILE_AST_ID};
+use stdx::TupleExt;
+use syntax::{
+    algo::skip_trivia_token,
+    ast::{self, HasAttrs as _, HasGenericParams, HasLoopBody, IsString as _},
+    match_ast, AstNode, AstToken, Direction, SyntaxKind, SyntaxNode, SyntaxNodePtr, SyntaxToken,
+    TextRange, TextSize,
+};
+
+use crate::{
+    db::HirDatabase,
+    semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx},
+    source_analyzer::{resolve_hir_path, SourceAnalyzer},
+    Access, Adjust, Adjustment, Adt, AutoBorrow, BindingMode, BuiltinAttr, Callable, Const,
+    ConstParam, Crate, DeriveHelper, Enum, Field, Function, HasSource, HirFileId, Impl, InFile,
+    Label, LifetimeParam, Local, Macro, Module, ModuleDef, Name, OverloadedDeref, Path, ScopeDef,
+    Static, Struct, ToolModule, Trait, TraitAlias, TupleField, Type, TypeAlias, TypeParam, Union,
+    Variant, VariantDef,
+};
+
+pub enum DescendPreference {
+    SameText,
+    SameKind,
+    None,
+}
+
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+pub enum PathResolution {
+    /// An item
+    Def(ModuleDef),
+    /// A local binding (only value namespace)
+    Local(Local),
+    /// A type parameter
+    TypeParam(TypeParam),
+    /// A const parameter
+    ConstParam(ConstParam),
+    SelfType(Impl),
+    BuiltinAttr(BuiltinAttr),
+    ToolModule(ToolModule),
+    DeriveHelper(DeriveHelper),
+}
+
+impl PathResolution {
+    pub(crate) fn in_type_ns(&self) -> Option<TypeNs> {
+        match self {
+            PathResolution::Def(ModuleDef::Adt(adt)) => Some(TypeNs::AdtId((*adt).into())),
+            PathResolution::Def(ModuleDef::BuiltinType(builtin)) => {
+                Some(TypeNs::BuiltinType((*builtin).into()))
+            }
+            PathResolution::Def(
+                ModuleDef::Const(_)
+                | ModuleDef::Variant(_)
+                | ModuleDef::Macro(_)
+                | ModuleDef::Function(_)
+                | ModuleDef::Module(_)
+                | ModuleDef::Static(_)
+                | ModuleDef::Trait(_)
+                | ModuleDef::TraitAlias(_),
+            ) => None,
+            PathResolution::Def(ModuleDef::TypeAlias(alias)) => {
+                Some(TypeNs::TypeAliasId((*alias).into()))
+            }
+            PathResolution::BuiltinAttr(_)
+            | PathResolution::ToolModule(_)
+            | PathResolution::Local(_)
+            | PathResolution::DeriveHelper(_)
+            | PathResolution::ConstParam(_) => None,
+            PathResolution::TypeParam(param) => Some(TypeNs::GenericParam((*param).into())),
+            PathResolution::SelfType(impl_def) => Some(TypeNs::SelfType((*impl_def).into())),
+        }
+    }
+}
+
+#[derive(Debug)]
+pub struct TypeInfo {
+    /// The original type of the expression or pattern.
+    pub original: Type,
+    /// The adjusted type, if an adjustment happened.
+    pub adjusted: Option<Type>,
+}
+
+impl TypeInfo {
+    pub fn original(self) -> Type {
+        self.original
+    }
+
+    pub fn has_adjustment(&self) -> bool {
+        self.adjusted.is_some()
+    }
+
+    /// The adjusted type, or the original in case no adjustments occurred.
+    pub fn adjusted(self) -> Type {
+        self.adjusted.unwrap_or(self.original)
+    }
+}
+
+/// Primary API to get semantic information, like types, from syntax trees.
+pub struct Semantics<'db, DB> {
+    pub db: &'db DB,
+    imp: SemanticsImpl<'db>,
+}
+
+pub struct SemanticsImpl<'db> {
+    pub db: &'db dyn HirDatabase,
+    s2d_cache: RefCell<SourceToDefCache>,
+    /// Rootnode to HirFileId cache
+    cache: RefCell<FxHashMap<SyntaxNode, HirFileId>>,
+    // These 2 caches are mainly useful for semantic highlighting as nothing else descends a lot of tokens
+    // So we might wanna move them out into something specific for semantic highlighting
+    expansion_info_cache: RefCell<FxHashMap<MacroFileId, ExpansionInfo>>,
+    /// MacroCall to its expansion's MacroFileId cache
+    macro_call_cache: RefCell<FxHashMap<InFile<ast::MacroCall>, MacroFileId>>,
+}
+
+impl<DB> fmt::Debug for Semantics<'_, DB> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        write!(f, "Semantics {{ ... }}")
+    }
+}
+
+impl<'db, DB> ops::Deref for Semantics<'db, DB> {
+    type Target = SemanticsImpl<'db>;
+
+    fn deref(&self) -> &Self::Target {
+        &self.imp
+    }
+}
+
+impl<'db, DB: HirDatabase> Semantics<'db, DB> {
+    pub fn new(db: &DB) -> Semantics<'_, DB> {
+        let impl_ = SemanticsImpl::new(db);
+        Semantics { db, imp: impl_ }
+    }
+
+    pub fn hir_file_for(&self, syntax_node: &SyntaxNode) -> HirFileId {
+        self.imp.find_file(syntax_node).file_id
+    }
+
+    pub fn token_ancestors_with_macros(
+        &self,
+        token: SyntaxToken,
+    ) -> impl Iterator<Item = SyntaxNode> + '_ {
+        token.parent().into_iter().flat_map(move |it| self.ancestors_with_macros(it))
+    }
+
+    /// Find an AstNode by offset inside SyntaxNode, if it is inside *Macrofile*,
+    /// search up until it is of the target AstNode type
+    pub fn find_node_at_offset_with_macros<N: AstNode>(
+        &self,
+        node: &SyntaxNode,
+        offset: TextSize,
+    ) -> Option<N> {
+        self.imp.ancestors_at_offset_with_macros(node, offset).find_map(N::cast)
+    }
+
+    /// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
+    /// descend it and find again
+    pub fn find_node_at_offset_with_descend<N: AstNode>(
+        &self,
+        node: &SyntaxNode,
+        offset: TextSize,
+    ) -> Option<N> {
+        self.imp.descend_node_at_offset(node, offset).flatten().find_map(N::cast)
+    }
+
+    /// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
+    /// descend it and find again
+    pub fn find_nodes_at_offset_with_descend<'slf, N: AstNode + 'slf>(
+        &'slf self,
+        node: &SyntaxNode,
+        offset: TextSize,
+    ) -> impl Iterator<Item = N> + 'slf {
+        self.imp.descend_node_at_offset(node, offset).filter_map(|mut it| it.find_map(N::cast))
+    }
+
+    pub fn resolve_await_to_poll(&self, await_expr: &ast::AwaitExpr) -> Option<Function> {
+        self.imp.resolve_await_to_poll(await_expr).map(Function::from)
+    }
+
+    pub fn resolve_prefix_expr(&self, prefix_expr: &ast::PrefixExpr) -> Option<Function> {
+        self.imp.resolve_prefix_expr(prefix_expr).map(Function::from)
+    }
+
+    pub fn resolve_index_expr(&self, index_expr: &ast::IndexExpr) -> Option<Function> {
+        self.imp.resolve_index_expr(index_expr).map(Function::from)
+    }
+
+    pub fn resolve_bin_expr(&self, bin_expr: &ast::BinExpr) -> Option<Function> {
+        self.imp.resolve_bin_expr(bin_expr).map(Function::from)
+    }
+
+    pub fn resolve_try_expr(&self, try_expr: &ast::TryExpr) -> Option<Function> {
+        self.imp.resolve_try_expr(try_expr).map(Function::from)
+    }
+
+    pub fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantDef> {
+        self.imp.resolve_variant(record_lit).map(VariantDef::from)
+    }
+
+    pub fn file_to_module_def(&self, file: FileId) -> Option<Module> {
+        self.imp.file_to_module_defs(file).next()
+    }
+
+    pub fn file_to_module_defs(&self, file: FileId) -> impl Iterator<Item = Module> {
+        self.imp.file_to_module_defs(file)
+    }
+
+    pub fn to_adt_def(&self, a: &ast::Adt) -> Option<Adt> {
+        self.imp.to_def(a).map(Adt::from)
+    }
+
+    pub fn to_const_def(&self, c: &ast::Const) -> Option<Const> {
+        self.imp.to_def(c).map(Const::from)
+    }
+
+    pub fn to_enum_def(&self, e: &ast::Enum) -> Option<Enum> {
+        self.imp.to_def(e).map(Enum::from)
+    }
+
+    pub fn to_enum_variant_def(&self, v: &ast::Variant) -> Option<Variant> {
+        self.imp.to_def(v).map(Variant::from)
+    }
+
+    pub fn to_fn_def(&self, f: &ast::Fn) -> Option<Function> {
+        self.imp.to_def(f).map(Function::from)
+    }
+
+    pub fn to_impl_def(&self, i: &ast::Impl) -> Option<Impl> {
+        self.imp.to_def(i).map(Impl::from)
+    }
+
+    pub fn to_macro_def(&self, m: &ast::Macro) -> Option<Macro> {
+        self.imp.to_def(m).map(Macro::from)
+    }
+
+    pub fn to_module_def(&self, m: &ast::Module) -> Option<Module> {
+        self.imp.to_def(m).map(Module::from)
+    }
+
+    pub fn to_static_def(&self, s: &ast::Static) -> Option<Static> {
+        self.imp.to_def(s).map(Static::from)
+    }
+
+    pub fn to_struct_def(&self, s: &ast::Struct) -> Option<Struct> {
+        self.imp.to_def(s).map(Struct::from)
+    }
+
+    pub fn to_trait_alias_def(&self, t: &ast::TraitAlias) -> Option<TraitAlias> {
+        self.imp.to_def(t).map(TraitAlias::from)
+    }
+
+    pub fn to_trait_def(&self, t: &ast::Trait) -> Option<Trait> {
+        self.imp.to_def(t).map(Trait::from)
+    }
+
+    pub fn to_type_alias_def(&self, t: &ast::TypeAlias) -> Option<TypeAlias> {
+        self.imp.to_def(t).map(TypeAlias::from)
+    }
+
+    pub fn to_union_def(&self, u: &ast::Union) -> Option<Union> {
+        self.imp.to_def(u).map(Union::from)
+    }
+}
+
+impl<'db> SemanticsImpl<'db> {
+    fn new(db: &'db dyn HirDatabase) -> Self {
+        SemanticsImpl {
+            db,
+            s2d_cache: Default::default(),
+            cache: Default::default(),
+            expansion_info_cache: Default::default(),
+            macro_call_cache: Default::default(),
+        }
+    }
+
+    pub fn parse(&self, file_id: FileId) -> ast::SourceFile {
+        let tree = self.db.parse(file_id).tree();
+        self.cache(tree.syntax().clone(), file_id.into());
+        tree
+    }
+
+    pub fn parse_or_expand(&self, file_id: HirFileId) -> SyntaxNode {
+        let node = self.db.parse_or_expand(file_id);
+        self.cache(node.clone(), file_id);
+        node
+    }
+
+    pub fn expand(&self, macro_call: &ast::MacroCall) -> Option<SyntaxNode> {
+        let sa = self.analyze_no_infer(macro_call.syntax())?;
+        let file_id = sa.expand(self.db, InFile::new(sa.file_id, macro_call))?;
+        let node = self.parse_or_expand(file_id.into());
+        Some(node)
+    }
+
+    /// If `item` has an attribute macro attached to it, expands it.
+    pub fn expand_attr_macro(&self, item: &ast::Item) -> Option<SyntaxNode> {
+        let src = self.wrap_node_infile(item.clone());
+        let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(src))?;
+        Some(self.parse_or_expand(macro_call_id.as_file()))
+    }
+
+    pub fn expand_derive_as_pseudo_attr_macro(&self, attr: &ast::Attr) -> Option<SyntaxNode> {
+        let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
+        let src = self.wrap_node_infile(attr.clone());
+        let call_id = self.with_ctx(|ctx| {
+            ctx.attr_to_derive_macro_call(src.with_value(&adt), src).map(|(_, it, _)| it)
+        })?;
+        Some(self.parse_or_expand(call_id.as_file()))
+    }
+
+    pub fn resolve_derive_macro(&self, attr: &ast::Attr) -> Option<Vec<Option<Macro>>> {
+        let calls = self.derive_macro_calls(attr)?;
+        self.with_ctx(|ctx| {
+            Some(
+                calls
+                    .into_iter()
+                    .map(|call| {
+                        macro_call_to_macro_id(ctx, self.db.upcast(), call?).map(|id| Macro { id })
+                    })
+                    .collect(),
+            )
+        })
+    }
+
+    pub fn expand_derive_macro(&self, attr: &ast::Attr) -> Option<Vec<SyntaxNode>> {
+        let res: Vec<_> = self
+            .derive_macro_calls(attr)?
+            .into_iter()
+            .flat_map(|call| {
+                let file_id = call?.as_file();
+                let node = self.db.parse_or_expand(file_id);
+                self.cache(node.clone(), file_id);
+                Some(node)
+            })
+            .collect();
+        Some(res)
+    }
+
+    fn derive_macro_calls(&self, attr: &ast::Attr) -> Option<Vec<Option<MacroCallId>>> {
+        let adt = attr.syntax().parent().and_then(ast::Adt::cast)?;
+        let file_id = self.find_file(adt.syntax()).file_id;
+        let adt = InFile::new(file_id, &adt);
+        let src = InFile::new(file_id, attr.clone());
+        self.with_ctx(|ctx| {
+            let (.., res) = ctx.attr_to_derive_macro_call(adt, src)?;
+            Some(res.to_vec())
+        })
+    }
+
+    pub fn is_derive_annotated(&self, adt: &ast::Adt) -> bool {
+        let file_id = self.find_file(adt.syntax()).file_id;
+        let adt = InFile::new(file_id, adt);
+        self.with_ctx(|ctx| ctx.has_derives(adt))
+    }
+
+    pub fn is_attr_macro_call(&self, item: &ast::Item) -> bool {
+        let file_id = self.find_file(item.syntax()).file_id;
+        let src = InFile::new(file_id, item.clone());
+        self.with_ctx(|ctx| ctx.item_to_macro_call(src).is_some())
+    }
+
+    /// Expand the macro call with a different token tree, mapping the `token_to_map` down into the
+    /// expansion. `token_to_map` should be a token from the `speculative args` node.
+    pub fn speculative_expand(
+        &self,
+        actual_macro_call: &ast::MacroCall,
+        speculative_args: &ast::TokenTree,
+        token_to_map: SyntaxToken,
+    ) -> Option<(SyntaxNode, SyntaxToken)> {
+        let SourceAnalyzer { file_id, resolver, .. } =
+            self.analyze_no_infer(actual_macro_call.syntax())?;
+        let macro_call = InFile::new(file_id, actual_macro_call);
+        let krate = resolver.krate();
+        let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| {
+            resolver.resolve_path_as_macro_def(self.db.upcast(), &path, Some(MacroSubNs::Bang))
+        })?;
+        hir_expand::db::expand_speculative(
+            self.db.upcast(),
+            macro_call_id,
+            speculative_args.syntax(),
+            token_to_map,
+        )
+    }
+
+    /// Expand the macro call with a different item as the input, mapping the `token_to_map` down into the
+    /// expansion. `token_to_map` should be a token from the `speculative args` node.
+    pub fn speculative_expand_attr_macro(
+        &self,
+        actual_macro_call: &ast::Item,
+        speculative_args: &ast::Item,
+        token_to_map: SyntaxToken,
+    ) -> Option<(SyntaxNode, SyntaxToken)> {
+        let macro_call = self.wrap_node_infile(actual_macro_call.clone());
+        let macro_call_id = self.with_ctx(|ctx| ctx.item_to_macro_call(macro_call))?;
+        hir_expand::db::expand_speculative(
+            self.db.upcast(),
+            macro_call_id,
+            speculative_args.syntax(),
+            token_to_map,
+        )
+    }
+
+    pub fn speculative_expand_derive_as_pseudo_attr_macro(
+        &self,
+        actual_macro_call: &ast::Attr,
+        speculative_args: &ast::Attr,
+        token_to_map: SyntaxToken,
+    ) -> Option<(SyntaxNode, SyntaxToken)> {
+        let attr = self.wrap_node_infile(actual_macro_call.clone());
+        let adt = actual_macro_call.syntax().parent().and_then(ast::Adt::cast)?;
+        let macro_call_id = self.with_ctx(|ctx| {
+            ctx.attr_to_derive_macro_call(attr.with_value(&adt), attr).map(|(_, it, _)| it)
+        })?;
+        hir_expand::db::expand_speculative(
+            self.db.upcast(),
+            macro_call_id,
+            speculative_args.syntax(),
+            token_to_map,
+        )
+    }
+
+    pub fn as_format_args_parts(
+        &self,
+        string: &ast::String,
+    ) -> Option<Vec<(TextRange, Option<PathResolution>)>> {
+        if let Some(quote) = string.open_quote_text_range() {
+            return self
+                .descend_into_macros(DescendPreference::SameText, string.syntax().clone())
+                .into_iter()
+                .find_map(|token| {
+                    let string = ast::String::cast(token)?;
+                    let literal =
+                        string.syntax().parent().filter(|it| it.kind() == SyntaxKind::LITERAL)?;
+                    let format_args = ast::FormatArgsExpr::cast(literal.parent()?)?;
+                    let source_analyzer = self.analyze_no_infer(format_args.syntax())?;
+                    let format_args = self.wrap_node_infile(format_args);
+                    let res = source_analyzer
+                        .as_format_args_parts(self.db, format_args.as_ref())?
+                        .map(|(range, res)| (range + quote.end(), res))
+                        .collect();
+                    Some(res)
+                });
+        }
+        None
+    }
+
+    pub fn check_for_format_args_template(
+        &self,
+        original_token: SyntaxToken,
+        offset: TextSize,
+    ) -> Option<(TextRange, Option<PathResolution>)> {
+        if let Some(original_string) = ast::String::cast(original_token.clone()) {
+            if let Some(quote) = original_string.open_quote_text_range() {
+                return self
+                    .descend_into_macros(DescendPreference::SameText, original_token)
+                    .into_iter()
+                    .find_map(|token| {
+                        self.resolve_offset_in_format_args(
+                            ast::String::cast(token)?,
+                            offset.checked_sub(quote.end())?,
+                        )
+                    })
+                    .map(|(range, res)| (range + quote.end(), res));
+            }
+        }
+        None
+    }
+
+    fn resolve_offset_in_format_args(
+        &self,
+        string: ast::String,
+        offset: TextSize,
+    ) -> Option<(TextRange, Option<PathResolution>)> {
+        debug_assert!(offset <= string.syntax().text_range().len());
+        let literal = string.syntax().parent().filter(|it| it.kind() == SyntaxKind::LITERAL)?;
+        let format_args = ast::FormatArgsExpr::cast(literal.parent()?)?;
+        let source_analyzer = &self.analyze_no_infer(format_args.syntax())?;
+        let format_args = self.wrap_node_infile(format_args);
+        source_analyzer.resolve_offset_in_format_args(self.db, format_args.as_ref(), offset)
+    }
+
+    /// Maps a node down by mapping its first and last token down.
+    pub fn descend_node_into_attributes<N: AstNode>(&self, node: N) -> SmallVec<[N; 1]> {
+        // This might not be the correct way to do this, but it works for now
+        let mut res = smallvec![];
+        let tokens = (|| {
+            // FIXME: the trivia skipping should not be necessary
+            let first = skip_trivia_token(node.syntax().first_token()?, Direction::Next)?;
+            let last = skip_trivia_token(node.syntax().last_token()?, Direction::Prev)?;
+            Some((first, last))
+        })();
+        let (first, last) = match tokens {
+            Some(it) => it,
+            None => return res,
+        };
+
+        if first == last {
+            // node is just the token, so descend the token
+            self.descend_into_macros_impl(first, &mut |InFile { value, .. }| {
+                if let Some(node) = value
+                    .parent_ancestors()
+                    .take_while(|it| it.text_range() == value.text_range())
+                    .find_map(N::cast)
+                {
+                    res.push(node)
+                }
+                ControlFlow::Continue(())
+            });
+        } else {
+            // Descend first and last token, then zip them to look for the node they belong to
+            let mut scratch: SmallVec<[_; 1]> = smallvec![];
+            self.descend_into_macros_impl(first, &mut |token| {
+                scratch.push(token);
+                ControlFlow::Continue(())
+            });
+
+            let mut scratch = scratch.into_iter();
+            self.descend_into_macros_impl(
+                last,
+                &mut |InFile { value: last, file_id: last_fid }| {
+                    if let Some(InFile { value: first, file_id: first_fid }) = scratch.next() {
+                        if first_fid == last_fid {
+                            if let Some(p) = first.parent() {
+                                let range = first.text_range().cover(last.text_range());
+                                let node = find_root(&p)
+                                    .covering_element(range)
+                                    .ancestors()
+                                    .take_while(|it| it.text_range() == range)
+                                    .find_map(N::cast);
+                                if let Some(node) = node {
+                                    res.push(node);
+                                }
+                            }
+                        }
+                    }
+                    ControlFlow::Continue(())
+                },
+            );
+        }
+        res
+    }
+
+    /// Descend the token into its macro call if it is part of one, returning the tokens in the
+    /// expansion that it is associated with.
+    pub fn descend_into_macros(
+        &self,
+        mode: DescendPreference,
+        token: SyntaxToken,
+    ) -> SmallVec<[SyntaxToken; 1]> {
+        enum Dp<'t> {
+            SameText(&'t str),
+            SameKind(SyntaxKind),
+            None,
+        }
+        let fetch_kind = |token: &SyntaxToken| match token.parent() {
+            Some(node) => match node.kind() {
+                kind @ (SyntaxKind::NAME | SyntaxKind::NAME_REF) => kind,
+                _ => token.kind(),
+            },
+            None => token.kind(),
+        };
+        let mode = match mode {
+            DescendPreference::SameText => Dp::SameText(token.text()),
+            DescendPreference::SameKind => Dp::SameKind(fetch_kind(&token)),
+            DescendPreference::None => Dp::None,
+        };
+        let mut res = smallvec![];
+        self.descend_into_macros_impl(token.clone(), &mut |InFile { value, .. }| {
+            let is_a_match = match mode {
+                Dp::SameText(text) => value.text() == text,
+                Dp::SameKind(preferred_kind) => {
+                    let kind = fetch_kind(&value);
+                    kind == preferred_kind
+                        // special case for derive macros
+                        || (preferred_kind == SyntaxKind::IDENT && kind == SyntaxKind::NAME_REF)
+                }
+                Dp::None => true,
+            };
+            if is_a_match {
+                res.push(value);
+            }
+            ControlFlow::Continue(())
+        });
+        if res.is_empty() {
+            res.push(token);
+        }
+        res
+    }
+
+    pub fn descend_into_macros_single(
+        &self,
+        mode: DescendPreference,
+        token: SyntaxToken,
+    ) -> SyntaxToken {
+        enum Dp<'t> {
+            SameText(&'t str),
+            SameKind(SyntaxKind),
+            None,
+        }
+        let fetch_kind = |token: &SyntaxToken| match token.parent() {
+            Some(node) => match node.kind() {
+                kind @ (SyntaxKind::NAME | SyntaxKind::NAME_REF) => kind,
+                _ => token.kind(),
+            },
+            None => token.kind(),
+        };
+        let mode = match mode {
+            DescendPreference::SameText => Dp::SameText(token.text()),
+            DescendPreference::SameKind => Dp::SameKind(fetch_kind(&token)),
+            DescendPreference::None => Dp::None,
+        };
+        let mut res = token.clone();
+        self.descend_into_macros_impl(token.clone(), &mut |InFile { value, .. }| {
+            let is_a_match = match mode {
+                Dp::SameText(text) => value.text() == text,
+                Dp::SameKind(preferred_kind) => {
+                    let kind = fetch_kind(&value);
+                    kind == preferred_kind
+                        // special case for derive macros
+                        || (preferred_kind == SyntaxKind::IDENT && kind == SyntaxKind::NAME_REF)
+                }
+                Dp::None => true,
+            };
+            res = value;
+            if is_a_match {
+                ControlFlow::Break(())
+            } else {
+                ControlFlow::Continue(())
+            }
+        });
+        res
+    }
+
+    // return:
+    // SourceAnalyzer(file_id that original call include!)
+    // macro file id
+    // token in include! macro mapped from token in params
+    // span for the mapped token
+    fn is_from_include_file(
+        &self,
+        token: SyntaxToken,
+    ) -> Option<(SourceAnalyzer, HirFileId, SyntaxToken, Span)> {
+        let parent = token.parent()?;
+        let file_id = self.find_file(&parent).file_id.file_id()?;
+
+        let mut cache = self.expansion_info_cache.borrow_mut();
+
+        // iterate related crates and find all include! invocations that include_file_id matches
+        for (invoc, _) in self
+            .db
+            .relevant_crates(file_id)
+            .iter()
+            .flat_map(|krate| self.db.include_macro_invoc(*krate))
+            .filter(|&(_, include_file_id)| include_file_id == file_id)
+        {
+            let macro_file = invoc.as_macro_file();
+            let expansion_info = cache.entry(macro_file).or_insert_with(|| {
+                let exp_info = macro_file.expansion_info(self.db.upcast());
+
+                let InMacroFile { file_id, value } = exp_info.expanded();
+                self.cache(value, file_id.into());
+
+                exp_info
+            });
+
+            // Create the source analyzer for the macro call scope
+            let Some(sa) = self.analyze_no_infer(&self.parse_or_expand(expansion_info.call_file()))
+            else {
+                continue;
+            };
+
+            // get mapped token in the include! macro file
+            let span = span::Span {
+                range: token.text_range(),
+                anchor: span::SpanAnchor { file_id, ast_id: ROOT_ERASED_FILE_AST_ID },
+                ctx: SyntaxContextId::ROOT,
+            };
+            let Some(InMacroFile { file_id, value: mut mapped_tokens }) =
+                expansion_info.map_range_down_exact(span)
+            else {
+                continue;
+            };
+
+            // if we find one, then return
+            if let Some(t) = mapped_tokens.next() {
+                return Some((sa, file_id.into(), t, span));
+            }
+        }
+
+        None
+    }
+
+    fn descend_into_macros_impl(
+        &self,
+        mut token: SyntaxToken,
+        f: &mut dyn FnMut(InFile<SyntaxToken>) -> ControlFlow<()>,
+    ) {
+        let _p = tracing::span!(tracing::Level::INFO, "descend_into_macros");
+        let (sa, span, file_id) =
+            match token.parent().and_then(|parent| self.analyze_no_infer(&parent)) {
+                Some(sa) => match sa.file_id.file_id() {
+                    Some(file_id) => (
+                        sa,
+                        self.db.real_span_map(file_id).span_for_range(token.text_range()),
+                        file_id.into(),
+                    ),
+                    None => {
+                        stdx::never!();
+                        return;
+                    }
+                },
+                None => {
+                    // if we cannot find a source analyzer for this token, then we try to find out
+                    // whether this file is an included file and treat that as the include input
+                    let Some((it, macro_file_id, mapped_token, s)) =
+                        self.is_from_include_file(token)
+                    else {
+                        return;
+                    };
+                    token = mapped_token;
+                    (it, s, macro_file_id)
+                }
+            };
+
+        let mut cache = self.expansion_info_cache.borrow_mut();
+        let mut mcache = self.macro_call_cache.borrow_mut();
+        let def_map = sa.resolver.def_map();
+
+        let mut stack: Vec<(_, SmallVec<[_; 2]>)> = vec![(file_id, smallvec![token])];
+        let mut process_expansion_for_token = |stack: &mut Vec<_>, macro_file| {
+            let exp_info = cache.entry(macro_file).or_insert_with(|| {
+                let exp_info = macro_file.expansion_info(self.db.upcast());
+
+                let InMacroFile { file_id, value } = exp_info.expanded();
+                self.cache(value, file_id.into());
+
+                exp_info
+            });
+
+            let InMacroFile { file_id, value: mapped_tokens } = exp_info.map_range_down(span)?;
+            let mapped_tokens: SmallVec<[_; 2]> = mapped_tokens.collect();
+
+            // we have found a mapping for the token if the vec is non-empty
+            let res = mapped_tokens.is_empty().not().then_some(());
+            // requeue the tokens we got from mapping our current token down
+            stack.push((HirFileId::from(file_id), mapped_tokens));
+            res
+        };
+
+        while let Some((file_id, mut tokens)) = stack.pop() {
+            while let Some(token) = tokens.pop() {
+                let was_not_remapped = (|| {
+                    // First expand into attribute invocations
+                    let containing_attribute_macro_call = self.with_ctx(|ctx| {
+                        token.parent_ancestors().filter_map(ast::Item::cast).find_map(|item| {
+                            // Don't force populate the dyn cache for items that don't have an attribute anyways
+                            item.attrs().next()?;
+                            Some((
+                                ctx.item_to_macro_call(InFile::new(file_id, item.clone()))?,
+                                item,
+                            ))
+                        })
+                    });
+                    if let Some((call_id, item)) = containing_attribute_macro_call {
+                        let file_id = call_id.as_macro_file();
+                        let attr_id = match self.db.lookup_intern_macro_call(call_id).kind {
+                            hir_expand::MacroCallKind::Attr { invoc_attr_index, .. } => {
+                                invoc_attr_index.ast_index()
+                            }
+                            _ => 0,
+                        };
+                        // FIXME: here, the attribute's text range is used to strip away all
+                        // entries from the start of the attribute "list" up the invoking
+                        // attribute. But in
+                        // ```
+                        // mod foo {
+                        //     #![inner]
+                        // }
+                        // ```
+                        // we don't wanna strip away stuff in the `mod foo {` range, that is
+                        // here if the id corresponds to an inner attribute we got strip all
+                        // text ranges of the outer ones, and then all of the inner ones up
+                        // to the invoking attribute so that the inbetween is ignored.
+                        let text_range = item.syntax().text_range();
+                        let start = collect_attrs(&item)
+                            .nth(attr_id)
+                            .map(|attr| match attr.1 {
+                                Either::Left(it) => it.syntax().text_range().start(),
+                                Either::Right(it) => it.syntax().text_range().start(),
+                            })
+                            .unwrap_or_else(|| text_range.start());
+                        let text_range = TextRange::new(start, text_range.end());
+                        // remove any other token in this macro input, all their mappings are the
+                        // same as this one
+                        tokens.retain(|t| !text_range.contains_range(t.text_range()));
+                        return process_expansion_for_token(&mut stack, file_id);
+                    }
+
+                    // Then check for token trees, that means we are either in a function-like macro or
+                    // secondary attribute inputs
+                    let tt = token.parent_ancestors().map_while(ast::TokenTree::cast).last()?;
+                    let parent = tt.syntax().parent()?;
+
+                    if tt.left_delimiter_token().map_or(false, |it| it == token) {
+                        return None;
+                    }
+                    if tt.right_delimiter_token().map_or(false, |it| it == token) {
+                        return None;
+                    }
+
+                    if let Some(macro_call) = ast::MacroCall::cast(parent.clone()) {
+                        let mcall: hir_expand::files::InFileWrapper<HirFileId, ast::MacroCall> =
+                            InFile::new(file_id, macro_call);
+                        let file_id = match mcache.get(&mcall) {
+                            Some(&it) => it,
+                            None => {
+                                let it = sa.expand(self.db, mcall.as_ref())?;
+                                mcache.insert(mcall, it);
+                                it
+                            }
+                        };
+                        let text_range = tt.syntax().text_range();
+                        // remove any other token in this macro input, all their mappings are the
+                        // same as this one
+                        tokens.retain(|t| !text_range.contains_range(t.text_range()));
+
+                        process_expansion_for_token(&mut stack, file_id).or(file_id
+                            .eager_arg(self.db.upcast())
+                            .and_then(|arg| {
+                                // also descend into eager expansions
+                                process_expansion_for_token(&mut stack, arg.as_macro_file())
+                            }))
+                    } else if let Some(meta) = ast::Meta::cast(parent) {
+                        // attribute we failed expansion for earlier, this might be a derive invocation
+                        // or derive helper attribute
+                        let attr = meta.parent_attr()?;
+
+                        let adt = if let Some(adt) = attr.syntax().parent().and_then(ast::Adt::cast)
+                        {
+                            // this might be a derive, or a derive helper on an ADT
+                            let derive_call = self.with_ctx(|ctx| {
+                                // so try downmapping the token into the pseudo derive expansion
+                                // see [hir_expand::builtin_attr_macro] for how the pseudo derive expansion works
+                                ctx.attr_to_derive_macro_call(
+                                    InFile::new(file_id, &adt),
+                                    InFile::new(file_id, attr.clone()),
+                                )
+                                .map(|(_, call_id, _)| call_id)
+                            });
+
+                            match derive_call {
+                                Some(call_id) => {
+                                    // resolved to a derive
+                                    let file_id = call_id.as_macro_file();
+                                    let text_range = attr.syntax().text_range();
+                                    // remove any other token in this macro input, all their mappings are the
+                                    // same as this one
+                                    tokens.retain(|t| !text_range.contains_range(t.text_range()));
+                                    return process_expansion_for_token(&mut stack, file_id);
+                                }
+                                None => Some(adt),
+                            }
+                        } else {
+                            // Otherwise this could be a derive helper on a variant or field
+                            if let Some(field) =
+                                attr.syntax().parent().and_then(ast::RecordField::cast)
+                            {
+                                field.syntax().ancestors().take(4).find_map(ast::Adt::cast)
+                            } else if let Some(field) =
+                                attr.syntax().parent().and_then(ast::TupleField::cast)
+                            {
+                                field.syntax().ancestors().take(4).find_map(ast::Adt::cast)
+                            } else if let Some(variant) =
+                                attr.syntax().parent().and_then(ast::Variant::cast)
+                            {
+                                variant.syntax().ancestors().nth(2).and_then(ast::Adt::cast)
+                            } else {
+                                None
+                            }
+                        }?;
+                        if !self.with_ctx(|ctx| ctx.has_derives(InFile::new(file_id, &adt))) {
+                            return None;
+                        }
+                        // Not an attribute, nor a derive, so it's either a builtin or a derive helper
+                        // Try to resolve to a derive helper and downmap
+                        let attr_name =
+                            attr.path().and_then(|it| it.as_single_name_ref())?.as_name();
+                        let id = self.db.ast_id_map(file_id).ast_id(&adt);
+                        let helpers = def_map.derive_helpers_in_scope(InFile::new(file_id, id))?;
+                        let mut res = None;
+                        for (.., derive) in
+                            helpers.iter().filter(|(helper, ..)| *helper == attr_name)
+                        {
+                            res = res.or(process_expansion_for_token(
+                                &mut stack,
+                                derive.as_macro_file(),
+                            ));
+                        }
+                        res
+                    } else {
+                        None
+                    }
+                })()
+                .is_none();
+
+                if was_not_remapped && f(InFile::new(file_id, token)).is_break() {
+                    break;
+                }
+            }
+        }
+    }
+
+    // Note this return type is deliberate as [`find_nodes_at_offset_with_descend`] wants to stop
+    // traversing the inner iterator when it finds a node.
+    // The outer iterator is over the tokens descendants
+    // The inner iterator is the ancestors of a descendant
+    fn descend_node_at_offset(
+        &self,
+        node: &SyntaxNode,
+        offset: TextSize,
+    ) -> impl Iterator<Item = impl Iterator<Item = SyntaxNode> + '_> + '_ {
+        node.token_at_offset(offset)
+            .map(move |token| self.descend_into_macros(DescendPreference::None, token))
+            .map(|descendants| {
+                descendants.into_iter().map(move |it| self.token_ancestors_with_macros(it))
+            })
+            // re-order the tokens from token_at_offset by returning the ancestors with the smaller first nodes first
+            // See algo::ancestors_at_offset, which uses the same approach
+            .kmerge_by(|left, right| {
+                left.clone()
+                    .map(|node| node.text_range().len())
+                    .lt(right.clone().map(|node| node.text_range().len()))
+            })
+    }
+
+    /// Attempts to map the node out of macro expanded files returning the original file range.
+    /// If upmapping is not possible, this will fall back to the range of the macro call of the
+    /// macro file the node resides in.
+    pub fn original_range(&self, node: &SyntaxNode) -> FileRange {
+        let node = self.find_file(node);
+        node.original_file_range_rooted(self.db.upcast())
+    }
+
+    /// Attempts to map the node out of macro expanded files returning the original file range.
+    pub fn original_range_opt(&self, node: &SyntaxNode) -> Option<FileRange> {
+        let node = self.find_file(node);
+        node.original_file_range_opt(self.db.upcast())
+            .filter(|(_, ctx)| ctx.is_root())
+            .map(TupleExt::head)
+    }
+
+    /// Attempts to map the node out of macro expanded files.
+    /// This only work for attribute expansions, as other ones do not have nodes as input.
+    pub fn original_ast_node<N: AstNode>(&self, node: N) -> Option<N> {
+        self.wrap_node_infile(node).original_ast_node_rooted(self.db.upcast()).map(
+            |InRealFile { file_id, value }| {
+                self.cache(find_root(value.syntax()), file_id.into());
+                value
+            },
+        )
+    }
+
+    /// Attempts to map the node out of macro expanded files.
+    /// This only work for attribute expansions, as other ones do not have nodes as input.
+    pub fn original_syntax_node_rooted(&self, node: &SyntaxNode) -> Option<SyntaxNode> {
+        let InFile { file_id, .. } = self.find_file(node);
+        InFile::new(file_id, node).original_syntax_node_rooted(self.db.upcast()).map(
+            |InRealFile { file_id, value }| {
+                self.cache(find_root(&value), file_id.into());
+                value
+            },
+        )
+    }
+
+    pub fn diagnostics_display_range(&self, src: InFile<SyntaxNodePtr>) -> FileRange {
+        let root = self.parse_or_expand(src.file_id);
+        let node = src.map(|it| it.to_node(&root));
+        node.as_ref().original_file_range_rooted(self.db.upcast())
+    }
+
+    fn token_ancestors_with_macros(
+        &self,
+        token: SyntaxToken,
+    ) -> impl Iterator<Item = SyntaxNode> + Clone + '_ {
+        token.parent().into_iter().flat_map(move |parent| self.ancestors_with_macros(parent))
+    }
+
+    /// Iterates the ancestors of the given node, climbing up macro expansions while doing so.
+    pub fn ancestors_with_macros(
+        &self,
+        node: SyntaxNode,
+    ) -> impl Iterator<Item = SyntaxNode> + Clone + '_ {
+        let node = self.find_file(&node);
+        let db = self.db.upcast();
+        iter::successors(Some(node.cloned()), move |&InFile { file_id, ref value }| {
+            match value.parent() {
+                Some(parent) => Some(InFile::new(file_id, parent)),
+                None => {
+                    let call_node = file_id.macro_file()?.call_node(db);
+                    // cache the node
+                    self.parse_or_expand(call_node.file_id);
+                    Some(call_node)
+                }
+            }
+        })
+        .map(|it| it.value)
+    }
+
+    pub fn ancestors_at_offset_with_macros(
+        &self,
+        node: &SyntaxNode,
+        offset: TextSize,
+    ) -> impl Iterator<Item = SyntaxNode> + '_ {
+        node.token_at_offset(offset)
+            .map(|token| self.token_ancestors_with_macros(token))
+            .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
+    }
+
+    pub fn resolve_lifetime_param(&self, lifetime: &ast::Lifetime) -> Option<LifetimeParam> {
+        let text = lifetime.text();
+        let lifetime_param = lifetime.syntax().ancestors().find_map(|syn| {
+            let gpl = ast::AnyHasGenericParams::cast(syn)?.generic_param_list()?;
+            gpl.lifetime_params()
+                .find(|tp| tp.lifetime().as_ref().map(|lt| lt.text()).as_ref() == Some(&text))
+        })?;
+        let src = self.wrap_node_infile(lifetime_param);
+        ToDef::to_def(self, src)
+    }
+
+    pub fn resolve_label(&self, lifetime: &ast::Lifetime) -> Option<Label> {
+        let text = lifetime.text();
+        let label = lifetime.syntax().ancestors().find_map(|syn| {
+            let label = match_ast! {
+                match syn {
+                    ast::ForExpr(it) => it.label(),
+                    ast::WhileExpr(it) => it.label(),
+                    ast::LoopExpr(it) => it.label(),
+                    ast::BlockExpr(it) => it.label(),
+                    _ => None,
+                }
+            };
+            label.filter(|l| {
+                l.lifetime()
+                    .and_then(|lt| lt.lifetime_ident_token())
+                    .map_or(false, |lt| lt.text() == text)
+            })
+        })?;
+        let src = self.wrap_node_infile(label);
+        ToDef::to_def(self, src)
+    }
+
+    pub fn resolve_type(&self, ty: &ast::Type) -> Option<Type> {
+        let analyze = self.analyze(ty.syntax())?;
+        let ctx = LowerCtx::new(self.db.upcast(), analyze.file_id);
+        let ty = hir_ty::TyLoweringContext::new_maybe_unowned(
+            self.db,
+            &analyze.resolver,
+            analyze.resolver.type_owner(),
+        )
+        .lower_ty(&crate::TypeRef::from_ast(&ctx, ty.clone()));
+        Some(Type::new_with_resolver(self.db, &analyze.resolver, ty))
+    }
+
+    pub fn resolve_trait(&self, path: &ast::Path) -> Option<Trait> {
+        let analyze = self.analyze(path.syntax())?;
+        let ctx = LowerCtx::new(self.db.upcast(), analyze.file_id);
+        let hir_path = Path::from_src(&ctx, path.clone())?;
+        match analyze.resolver.resolve_path_in_type_ns_fully(self.db.upcast(), &hir_path)? {
+            TypeNs::TraitId(id) => Some(Trait { id }),
+            _ => None,
+        }
+    }
+
+    pub fn expr_adjustments(&self, expr: &ast::Expr) -> Option<Vec<Adjustment>> {
+        let mutability = |m| match m {
+            hir_ty::Mutability::Not => Mutability::Shared,
+            hir_ty::Mutability::Mut => Mutability::Mut,
+        };
+
+        let analyzer = self.analyze(expr.syntax())?;
+
+        let (mut source_ty, _) = analyzer.type_of_expr(self.db, expr)?;
+
+        analyzer.expr_adjustments(self.db, expr).map(|it| {
+            it.iter()
+                .map(|adjust| {
+                    let target =
+                        Type::new_with_resolver(self.db, &analyzer.resolver, adjust.target.clone());
+                    let kind = match adjust.kind {
+                        hir_ty::Adjust::NeverToAny => Adjust::NeverToAny,
+                        hir_ty::Adjust::Deref(Some(hir_ty::OverloadedDeref(m))) => {
+                            // FIXME: Should we handle unknown mutability better?
+                            Adjust::Deref(Some(OverloadedDeref(
+                                m.map(mutability).unwrap_or(Mutability::Shared),
+                            )))
+                        }
+                        hir_ty::Adjust::Deref(None) => Adjust::Deref(None),
+                        hir_ty::Adjust::Borrow(hir_ty::AutoBorrow::RawPtr(m)) => {
+                            Adjust::Borrow(AutoBorrow::RawPtr(mutability(m)))
+                        }
+                        hir_ty::Adjust::Borrow(hir_ty::AutoBorrow::Ref(m)) => {
+                            Adjust::Borrow(AutoBorrow::Ref(mutability(m)))
+                        }
+                        hir_ty::Adjust::Pointer(pc) => Adjust::Pointer(pc),
+                    };
+
+                    // Update `source_ty` for the next adjustment
+                    let source = mem::replace(&mut source_ty, target.clone());
+
+                    Adjustment { source, target, kind }
+                })
+                .collect()
+        })
+    }
+
+    pub fn type_of_expr(&self, expr: &ast::Expr) -> Option<TypeInfo> {
+        self.analyze(expr.syntax())?
+            .type_of_expr(self.db, expr)
+            .map(|(ty, coerced)| TypeInfo { original: ty, adjusted: coerced })
+    }
+
+    pub fn type_of_pat(&self, pat: &ast::Pat) -> Option<TypeInfo> {
+        self.analyze(pat.syntax())?
+            .type_of_pat(self.db, pat)
+            .map(|(ty, coerced)| TypeInfo { original: ty, adjusted: coerced })
+    }
+
+    /// It also includes the changes that binding mode makes in the type. For example in
+    /// `let ref x @ Some(_) = None` the result of `type_of_pat` is `Option<T>` but the result
+    /// of this function is `&mut Option<T>`
+    pub fn type_of_binding_in_pat(&self, pat: &ast::IdentPat) -> Option<Type> {
+        self.analyze(pat.syntax())?.type_of_binding_in_pat(self.db, pat)
+    }
+
+    pub fn type_of_self(&self, param: &ast::SelfParam) -> Option<Type> {
+        self.analyze(param.syntax())?.type_of_self(self.db, param)
+    }
+
+    pub fn pattern_adjustments(&self, pat: &ast::Pat) -> SmallVec<[Type; 1]> {
+        self.analyze(pat.syntax())
+            .and_then(|it| it.pattern_adjustments(self.db, pat))
+            .unwrap_or_default()
+    }
+
+    pub fn binding_mode_of_pat(&self, pat: &ast::IdentPat) -> Option<BindingMode> {
+        self.analyze(pat.syntax())?.binding_mode_of_pat(self.db, pat)
+    }
+
+    pub fn resolve_expr_as_callable(&self, call: &ast::Expr) -> Option<Callable> {
+        self.analyze(call.syntax())?.resolve_expr_as_callable(self.db, call)
+    }
+
+    pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> {
+        self.analyze(call.syntax())?.resolve_method_call(self.db, call)
+    }
+
+    /// Attempts to resolve this call expression as a method call falling back to resolving it as a field.
+    pub fn resolve_method_call_fallback(
+        &self,
+        call: &ast::MethodCallExpr,
+    ) -> Option<Either<Function, Field>> {
+        self.analyze(call.syntax())?.resolve_method_call_fallback(self.db, call)
+    }
+
+    fn resolve_await_to_poll(&self, await_expr: &ast::AwaitExpr) -> Option<FunctionId> {
+        self.analyze(await_expr.syntax())?.resolve_await_to_poll(self.db, await_expr)
+    }
+
+    fn resolve_prefix_expr(&self, prefix_expr: &ast::PrefixExpr) -> Option<FunctionId> {
+        self.analyze(prefix_expr.syntax())?.resolve_prefix_expr(self.db, prefix_expr)
+    }
+
+    fn resolve_index_expr(&self, index_expr: &ast::IndexExpr) -> Option<FunctionId> {
+        self.analyze(index_expr.syntax())?.resolve_index_expr(self.db, index_expr)
+    }
+
+    fn resolve_bin_expr(&self, bin_expr: &ast::BinExpr) -> Option<FunctionId> {
+        self.analyze(bin_expr.syntax())?.resolve_bin_expr(self.db, bin_expr)
+    }
+
+    fn resolve_try_expr(&self, try_expr: &ast::TryExpr) -> Option<FunctionId> {
+        self.analyze(try_expr.syntax())?.resolve_try_expr(self.db, try_expr)
+    }
+
+    pub fn resolve_method_call_as_callable(&self, call: &ast::MethodCallExpr) -> Option<Callable> {
+        self.analyze(call.syntax())?.resolve_method_call_as_callable(self.db, call)
+    }
+
+    pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Either<Field, TupleField>> {
+        self.analyze(field.syntax())?.resolve_field(self.db, field)
+    }
+
+    pub fn resolve_field_fallback(
+        &self,
+        field: &ast::FieldExpr,
+    ) -> Option<Either<Either<Field, TupleField>, Function>> {
+        self.analyze(field.syntax())?.resolve_field_fallback(self.db, field)
+    }
+
+    pub fn resolve_record_field(
+        &self,
+        field: &ast::RecordExprField,
+    ) -> Option<(Field, Option<Local>, Type)> {
+        self.analyze(field.syntax())?.resolve_record_field(self.db, field)
+    }
+
+    pub fn resolve_record_pat_field(&self, field: &ast::RecordPatField) -> Option<(Field, Type)> {
+        self.analyze(field.syntax())?.resolve_record_pat_field(self.db, field)
+    }
+
+    pub fn resolve_macro_call(&self, macro_call: &ast::MacroCall) -> Option<Macro> {
+        let sa = self.analyze(macro_call.syntax())?;
+        let macro_call = self.find_file(macro_call.syntax()).with_value(macro_call);
+        sa.resolve_macro_call(self.db, macro_call)
+    }
+
+    pub fn is_proc_macro_call(&self, macro_call: &ast::MacroCall) -> bool {
+        self.resolve_macro_call(macro_call)
+            .map_or(false, |m| matches!(m.id, MacroId::ProcMacroId(..)))
+    }
+
+    pub fn is_unsafe_macro_call(&self, macro_call: &ast::MacroCall) -> bool {
+        let sa = match self.analyze(macro_call.syntax()) {
+            Some(it) => it,
+            None => return false,
+        };
+        let macro_call = self.find_file(macro_call.syntax()).with_value(macro_call);
+        sa.is_unsafe_macro_call(self.db, macro_call)
+    }
+
+    pub fn resolve_attr_macro_call(&self, item: &ast::Item) -> Option<Macro> {
+        let item_in_file = self.wrap_node_infile(item.clone());
+        let id = self.with_ctx(|ctx| {
+            let macro_call_id = ctx.item_to_macro_call(item_in_file)?;
+            macro_call_to_macro_id(ctx, self.db.upcast(), macro_call_id)
+        })?;
+        Some(Macro { id })
+    }
+
+    pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> {
+        self.analyze(path.syntax())?.resolve_path(self.db, path)
+    }
+
+    fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {
+        self.analyze(record_lit.syntax())?.resolve_variant(self.db, record_lit)
+    }
+
+    pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option<ModuleDef> {
+        self.analyze(pat.syntax())?.resolve_bind_pat_to_const(self.db, pat)
+    }
+
+    pub fn record_literal_missing_fields(&self, literal: &ast::RecordExpr) -> Vec<(Field, Type)> {
+        self.analyze(literal.syntax())
+            .and_then(|it| it.record_literal_missing_fields(self.db, literal))
+            .unwrap_or_default()
+    }
+
+    pub fn record_pattern_missing_fields(&self, pattern: &ast::RecordPat) -> Vec<(Field, Type)> {
+        self.analyze(pattern.syntax())
+            .and_then(|it| it.record_pattern_missing_fields(self.db, pattern))
+            .unwrap_or_default()
+    }
+
+    fn with_ctx<F: FnOnce(&mut SourceToDefCtx<'_, '_>) -> T, T>(&self, f: F) -> T {
+        let mut cache = self.s2d_cache.borrow_mut();
+        let mut ctx = SourceToDefCtx { db: self.db, dynmap_cache: &mut cache };
+        f(&mut ctx)
+    }
+
+    pub fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> {
+        let src = self.find_file(src.syntax()).with_value(src).cloned();
+        T::to_def(self, src)
+    }
+
+    fn file_to_module_defs(&self, file: FileId) -> impl Iterator<Item = Module> {
+        self.with_ctx(|ctx| ctx.file_to_def(file)).into_iter().map(Module::from)
+    }
+
+    pub fn scope(&self, node: &SyntaxNode) -> Option<SemanticsScope<'db>> {
+        self.analyze_no_infer(node).map(|SourceAnalyzer { file_id, resolver, .. }| SemanticsScope {
+            db: self.db,
+            file_id,
+            resolver,
+        })
+    }
+
+    pub fn scope_at_offset(
+        &self,
+        node: &SyntaxNode,
+        offset: TextSize,
+    ) -> Option<SemanticsScope<'db>> {
+        self.analyze_with_offset_no_infer(node, offset).map(
+            |SourceAnalyzer { file_id, resolver, .. }| SemanticsScope {
+                db: self.db,
+                file_id,
+                resolver,
+            },
+        )
+    }
+
+    /// Search for a definition's source and cache its syntax tree
+    pub fn source<Def: HasSource>(&self, def: Def) -> Option<InFile<Def::Ast>>
+    where
+        Def::Ast: AstNode,
+    {
+        let res = def.source(self.db)?;
+        self.cache(find_root(res.value.syntax()), res.file_id);
+        Some(res)
+    }
+
+    /// Returns none if the file of the node is not part of a crate.
+    fn analyze(&self, node: &SyntaxNode) -> Option<SourceAnalyzer> {
+        self.analyze_impl(node, None, true)
+    }
+
+    /// Returns none if the file of the node is not part of a crate.
+    fn analyze_no_infer(&self, node: &SyntaxNode) -> Option<SourceAnalyzer> {
+        self.analyze_impl(node, None, false)
+    }
+
+    fn analyze_with_offset_no_infer(
+        &self,
+        node: &SyntaxNode,
+        offset: TextSize,
+    ) -> Option<SourceAnalyzer> {
+        self.analyze_impl(node, Some(offset), false)
+    }
+
+    fn analyze_impl(
+        &self,
+        node: &SyntaxNode,
+        offset: Option<TextSize>,
+        infer_body: bool,
+    ) -> Option<SourceAnalyzer> {
+        let _p = tracing::span!(tracing::Level::INFO, "Semantics::analyze_impl");
+        let node = self.find_file(node);
+
+        let container = self.with_ctx(|ctx| ctx.find_container(node))?;
+
+        let resolver = match container {
+            ChildContainer::DefWithBodyId(def) => {
+                return Some(if infer_body {
+                    SourceAnalyzer::new_for_body(self.db, def, node, offset)
+                } else {
+                    SourceAnalyzer::new_for_body_no_infer(self.db, def, node, offset)
+                })
+            }
+            ChildContainer::TraitId(it) => it.resolver(self.db.upcast()),
+            ChildContainer::TraitAliasId(it) => it.resolver(self.db.upcast()),
+            ChildContainer::ImplId(it) => it.resolver(self.db.upcast()),
+            ChildContainer::ModuleId(it) => it.resolver(self.db.upcast()),
+            ChildContainer::EnumId(it) => it.resolver(self.db.upcast()),
+            ChildContainer::VariantId(it) => it.resolver(self.db.upcast()),
+            ChildContainer::TypeAliasId(it) => it.resolver(self.db.upcast()),
+            ChildContainer::GenericDefId(it) => it.resolver(self.db.upcast()),
+        };
+        Some(SourceAnalyzer::new_for_resolver(resolver, node))
+    }
+
+    fn cache(&self, root_node: SyntaxNode, file_id: HirFileId) {
+        assert!(root_node.parent().is_none());
+        let mut cache = self.cache.borrow_mut();
+        let prev = cache.insert(root_node, file_id);
+        assert!(prev.is_none() || prev == Some(file_id))
+    }
+
+    pub fn assert_contains_node(&self, node: &SyntaxNode) {
+        self.find_file(node);
+    }
+
+    fn lookup(&self, root_node: &SyntaxNode) -> Option<HirFileId> {
+        let cache = self.cache.borrow();
+        cache.get(root_node).copied()
+    }
+
+    fn wrap_node_infile<N: AstNode>(&self, node: N) -> InFile<N> {
+        let InFile { file_id, .. } = self.find_file(node.syntax());
+        InFile::new(file_id, node)
+    }
+
+    /// Wraps the node in a [`InFile`] with the file id it belongs to.
+    fn find_file<'node>(&self, node: &'node SyntaxNode) -> InFile<&'node SyntaxNode> {
+        let root_node = find_root(node);
+        let file_id = self.lookup(&root_node).unwrap_or_else(|| {
+            panic!(
+                "\n\nFailed to lookup {:?} in this Semantics.\n\
+                 Make sure to use only query nodes, derived from this instance of Semantics.\n\
+                 root node:   {:?}\n\
+                 known nodes: {}\n\n",
+                node,
+                root_node,
+                self.cache
+                    .borrow()
+                    .keys()
+                    .map(|it| format!("{it:?}"))
+                    .collect::<Vec<_>>()
+                    .join(", ")
+            )
+        });
+        InFile::new(file_id, node)
+    }
+
+    pub fn is_unsafe_method_call(&self, method_call_expr: &ast::MethodCallExpr) -> bool {
+        method_call_expr
+            .receiver()
+            .and_then(|expr| {
+                let field_expr = match expr {
+                    ast::Expr::FieldExpr(field_expr) => field_expr,
+                    _ => return None,
+                };
+                let ty = self.type_of_expr(&field_expr.expr()?)?.original;
+                if !ty.is_packed(self.db) {
+                    return None;
+                }
+
+                let func = self.resolve_method_call(method_call_expr)?;
+                let res = match func.self_param(self.db)?.access(self.db) {
+                    Access::Shared | Access::Exclusive => true,
+                    Access::Owned => false,
+                };
+                Some(res)
+            })
+            .unwrap_or(false)
+    }
+
+    pub fn is_unsafe_ref_expr(&self, ref_expr: &ast::RefExpr) -> bool {
+        ref_expr
+            .expr()
+            .and_then(|expr| {
+                let field_expr = match expr {
+                    ast::Expr::FieldExpr(field_expr) => field_expr,
+                    _ => return None,
+                };
+                let expr = field_expr.expr()?;
+                self.type_of_expr(&expr)
+            })
+            // Binding a reference to a packed type is possibly unsafe.
+            .map(|ty| ty.original.is_packed(self.db))
+            .unwrap_or(false)
+
+        // FIXME This needs layout computation to be correct. It will highlight
+        // more than it should with the current implementation.
+    }
+
+    pub fn is_unsafe_ident_pat(&self, ident_pat: &ast::IdentPat) -> bool {
+        if ident_pat.ref_token().is_none() {
+            return false;
+        }
+
+        ident_pat
+            .syntax()
+            .parent()
+            .and_then(|parent| {
+                // `IdentPat` can live under `RecordPat` directly under `RecordPatField` or
+                // `RecordPatFieldList`. `RecordPatField` also lives under `RecordPatFieldList`,
+                // so this tries to lookup the `IdentPat` anywhere along that structure to the
+                // `RecordPat` so we can get the containing type.
+                let record_pat = ast::RecordPatField::cast(parent.clone())
+                    .and_then(|record_pat| record_pat.syntax().parent())
+                    .or_else(|| Some(parent.clone()))
+                    .and_then(|parent| {
+                        ast::RecordPatFieldList::cast(parent)?
+                            .syntax()
+                            .parent()
+                            .and_then(ast::RecordPat::cast)
+                    });
+
+                // If this doesn't match a `RecordPat`, fallback to a `LetStmt` to see if
+                // this is initialized from a `FieldExpr`.
+                if let Some(record_pat) = record_pat {
+                    self.type_of_pat(&ast::Pat::RecordPat(record_pat))
+                } else if let Some(let_stmt) = ast::LetStmt::cast(parent) {
+                    let field_expr = match let_stmt.initializer()? {
+                        ast::Expr::FieldExpr(field_expr) => field_expr,
+                        _ => return None,
+                    };
+
+                    self.type_of_expr(&field_expr.expr()?)
+                } else {
+                    None
+                }
+            })
+            // Binding a reference to a packed type is possibly unsafe.
+            .map(|ty| ty.original.is_packed(self.db))
+            .unwrap_or(false)
+    }
+
+    /// Returns `true` if the `node` is inside an `unsafe` context.
+    pub 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 def = match &enclosing_item {
+            Either::Left(ast::Item::Fn(it)) if it.unsafe_token().is_some() => return true,
+            Either::Left(ast::Item::Fn(it)) => {
+                self.to_def(it).map(<_>::into).map(DefWithBodyId::FunctionId)
+            }
+            Either::Left(ast::Item::Const(it)) => {
+                self.to_def(it).map(<_>::into).map(DefWithBodyId::ConstId)
+            }
+            Either::Left(ast::Item::Static(it)) => {
+                self.to_def(it).map(<_>::into).map(DefWithBodyId::StaticId)
+            }
+            Either::Left(_) => None,
+            Either::Right(it) => self.to_def(it).map(<_>::into).map(DefWithBodyId::VariantId),
+        };
+        let Some(def) = def else { return false };
+        let enclosing_node = enclosing_item.as_ref().either(|i| i.syntax(), |v| v.syntax());
+
+        let (body, source_map) = self.db.body_with_source_map(def);
+
+        let file_id = self.find_file(expr.syntax()).file_id;
+
+        let Some(mut parent) = expr.syntax().parent() else { return false };
+        loop {
+            if &parent == enclosing_node {
+                break false;
+            }
+
+            if let Some(parent) = ast::Expr::cast(parent.clone()) {
+                if let Some(expr_id) = source_map.node_expr(InFile { file_id, value: &parent }) {
+                    if let Expr::Unsafe { .. } = body[expr_id] {
+                        break true;
+                    }
+                }
+            }
+
+            let Some(parent_) = parent.parent() else { break false };
+            parent = parent_;
+        }
+    }
+}
+
+fn macro_call_to_macro_id(
+    ctx: &mut SourceToDefCtx<'_, '_>,
+    db: &dyn ExpandDatabase,
+    macro_call_id: MacroCallId,
+) -> Option<MacroId> {
+    let loc = db.lookup_intern_macro_call(macro_call_id);
+    match loc.def.kind {
+        hir_expand::MacroDefKind::Declarative(it)
+        | hir_expand::MacroDefKind::BuiltIn(_, it)
+        | hir_expand::MacroDefKind::BuiltInAttr(_, it)
+        | hir_expand::MacroDefKind::BuiltInDerive(_, it)
+        | hir_expand::MacroDefKind::BuiltInEager(_, it) => {
+            ctx.macro_to_def(InFile::new(it.file_id, it.to_node(db)))
+        }
+        hir_expand::MacroDefKind::ProcMacro(_, _, it) => {
+            ctx.proc_macro_to_def(InFile::new(it.file_id, it.to_node(db)))
+        }
+    }
+}
+
+pub trait ToDef: AstNode + Clone {
+    type Def;
+
+    fn to_def(sema: &SemanticsImpl<'_>, src: InFile<Self>) -> Option<Self::Def>;
+}
+
+macro_rules! to_def_impls {
+    ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
+        impl ToDef for $ast {
+            type Def = $def;
+            fn to_def(sema: &SemanticsImpl<'_>, src: InFile<Self>) -> Option<Self::Def> {
+                sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
+            }
+        }
+    )*}
+}
+
+to_def_impls![
+    (crate::Module, ast::Module, module_to_def),
+    (crate::Module, ast::SourceFile, source_file_to_def),
+    (crate::Struct, ast::Struct, struct_to_def),
+    (crate::Enum, ast::Enum, enum_to_def),
+    (crate::Union, ast::Union, union_to_def),
+    (crate::Trait, ast::Trait, trait_to_def),
+    (crate::TraitAlias, ast::TraitAlias, trait_alias_to_def),
+    (crate::Impl, ast::Impl, impl_to_def),
+    (crate::TypeAlias, ast::TypeAlias, type_alias_to_def),
+    (crate::Const, ast::Const, const_to_def),
+    (crate::Static, ast::Static, static_to_def),
+    (crate::Function, ast::Fn, fn_to_def),
+    (crate::Field, ast::RecordField, record_field_to_def),
+    (crate::Field, ast::TupleField, tuple_field_to_def),
+    (crate::Variant, ast::Variant, enum_variant_to_def),
+    (crate::TypeParam, ast::TypeParam, type_param_to_def),
+    (crate::LifetimeParam, ast::LifetimeParam, lifetime_param_to_def),
+    (crate::ConstParam, ast::ConstParam, const_param_to_def),
+    (crate::GenericParam, ast::GenericParam, generic_param_to_def),
+    (crate::Macro, ast::Macro, macro_to_def),
+    (crate::Local, ast::IdentPat, bind_pat_to_def),
+    (crate::Local, ast::SelfParam, self_param_to_def),
+    (crate::Label, ast::Label, label_to_def),
+    (crate::Adt, ast::Adt, adt_to_def),
+    (crate::ExternCrateDecl, ast::ExternCrate, extern_crate_to_def),
+];
+
+fn find_root(node: &SyntaxNode) -> SyntaxNode {
+    node.ancestors().last().unwrap()
+}
+
+/// `SemanticsScope` encapsulates the notion of a scope (the set of visible
+/// names) at a particular program point.
+///
+/// It is a bit tricky, as scopes do not really exist inside the compiler.
+/// Rather, the compiler directly computes for each reference the definition it
+/// refers to. It might transiently compute the explicit scope map while doing
+/// so, but, generally, this is not something left after the analysis.
+///
+/// However, we do very much need explicit scopes for IDE purposes --
+/// completion, at its core, lists the contents of the current scope. The notion
+/// of scope is also useful to answer questions like "what would be the meaning
+/// of this piece of code if we inserted it into this position?".
+///
+/// So `SemanticsScope` is constructed from a specific program point (a syntax
+/// node or just a raw offset) and provides access to the set of visible names
+/// on a somewhat best-effort basis.
+///
+/// Note that if you are wondering "what does this specific existing name mean?",
+/// you'd better use the `resolve_` family of methods.
+#[derive(Debug)]
+pub struct SemanticsScope<'a> {
+    pub db: &'a dyn HirDatabase,
+    file_id: HirFileId,
+    resolver: Resolver,
+}
+
+impl SemanticsScope<'_> {
+    pub fn module(&self) -> Module {
+        Module { id: self.resolver.module() }
+    }
+
+    pub fn krate(&self) -> Crate {
+        Crate { id: self.resolver.krate() }
+    }
+
+    pub(crate) fn resolver(&self) -> &Resolver {
+        &self.resolver
+    }
+
+    /// Note: `VisibleTraits` should be treated as an opaque type, passed into `Type
+    pub fn visible_traits(&self) -> VisibleTraits {
+        let resolver = &self.resolver;
+        VisibleTraits(resolver.traits_in_scope(self.db.upcast()))
+    }
+
+    /// Calls the passed closure `f` on all names in scope.
+    pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) {
+        let scope = self.resolver.names_in_scope(self.db.upcast());
+        for (name, entries) in scope {
+            for entry in entries {
+                let def = match entry {
+                    resolver::ScopeDef::ModuleDef(it) => ScopeDef::ModuleDef(it.into()),
+                    resolver::ScopeDef::Unknown => ScopeDef::Unknown,
+                    resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()),
+                    resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()),
+                    resolver::ScopeDef::GenericParam(id) => ScopeDef::GenericParam(id.into()),
+                    resolver::ScopeDef::Local(binding_id) => match self.resolver.body_owner() {
+                        Some(parent) => ScopeDef::Local(Local { parent, binding_id }),
+                        None => continue,
+                    },
+                    resolver::ScopeDef::Label(label_id) => match self.resolver.body_owner() {
+                        Some(parent) => ScopeDef::Label(Label { parent, label_id }),
+                        None => continue,
+                    },
+                };
+                f(name.clone(), def)
+            }
+        }
+    }
+
+    /// Resolve a path as-if it was written at the given scope. This is
+    /// necessary a heuristic, as it doesn't take hygiene into account.
+    pub fn speculative_resolve(&self, path: &ast::Path) -> Option<PathResolution> {
+        let ctx = LowerCtx::new(self.db.upcast(), self.file_id);
+        let path = Path::from_src(&ctx, path.clone())?;
+        resolve_hir_path(self.db, &self.resolver, &path)
+    }
+
+    /// Iterates over associated types that may be specified after the given path (using
+    /// `Ty::Assoc` syntax).
+    pub fn assoc_type_shorthand_candidates<R>(
+        &self,
+        resolution: &PathResolution,
+        mut cb: impl FnMut(&Name, TypeAlias) -> Option<R>,
+    ) -> Option<R> {
+        let def = self.resolver.generic_def()?;
+        hir_ty::associated_type_shorthand_candidates(
+            self.db,
+            def,
+            resolution.in_type_ns()?,
+            |name, id| cb(name, id.into()),
+        )
+    }
+
+    pub fn extern_crates(&self) -> impl Iterator<Item = (Name, Module)> + '_ {
+        self.resolver.extern_crates_in_scope().map(|(name, id)| (name, Module { id }))
+    }
+
+    pub fn extern_crate_decls(&self) -> impl Iterator<Item = Name> + '_ {
+        self.resolver.extern_crate_decls_in_scope(self.db.upcast())
+    }
+
+    pub fn has_same_self_type(&self, other: &SemanticsScope<'_>) -> bool {
+        self.resolver.impl_def() == other.resolver.impl_def()
+    }
+}
+
+#[derive(Debug)]
+pub struct VisibleTraits(pub FxHashSet<TraitId>);
+
+impl ops::Deref for VisibleTraits {
+    type Target = FxHashSet<TraitId>;
+
+    fn deref(&self) -> &Self::Target {
+        &self.0
+    }
+}
diff --git a/src/tools/rust-analyzer/crates/hir/src/semantics/source_to_def.rs b/src/tools/rust-analyzer/crates/hir/src/semantics/source_to_def.rs
new file mode 100644
index 00000000000..d4d6f0b243f
--- /dev/null
+++ b/src/tools/rust-analyzer/crates/hir/src/semantics/source_to_def.rs
@@ -0,0 +1,506 @@
+//! Maps *syntax* of various definitions to their semantic ids.
+//!
+//! This is a very interesting module, and, in some sense, can be considered the
+//! heart of the IDE parts of rust-analyzer.
+//!
+//! This module solves the following problem:
+//!
+//!     Given a piece of syntax, find the corresponding semantic definition (def).
+//!
+//! This problem is a part of more-or-less every IDE feature implemented. Every
+//! IDE functionality (like goto to definition), conceptually starts with a
+//! specific cursor position in a file. Starting with this text offset, we first
+//! figure out what syntactic construct are we at: is this a pattern, an
+//! expression, an item definition.
+//!
+//! Knowing only the syntax gives us relatively little info. For example,
+//! looking at the syntax of the function we can realize that it is a part of an
+//! `impl` block, but we won't be able to tell what trait function the current
+//! function overrides, and whether it does that correctly. For that, we need to
+//! go from [`ast::Fn`] to [`crate::Function`], and that's exactly what this
+//! module does.
+//!
+//! As syntax trees are values and don't know their place of origin/identity,
+//! this module also requires [`InFile`] wrappers to understand which specific
+//! real or macro-expanded file the tree comes from.
+//!
+//! The actual algorithm to resolve syntax to def is curious in two aspects:
+//!
+//!     * It is recursive
+//!     * It uses the inverse algorithm (what is the syntax for this def?)
+//!
+//! Specifically, the algorithm goes like this:
+//!
+//!     1. Find the syntactic container for the syntax. For example, field's
+//!        container is the struct, and structs container is a module.
+//!     2. Recursively get the def corresponding to container.
+//!     3. Ask the container def for all child defs. These child defs contain
+//!        the answer and answer's siblings.
+//!     4. For each child def, ask for it's source.
+//!     5. The child def whose source is the syntax node we've started with
+//!        is the answer.
+//!
+//! It's interesting that both Roslyn and Kotlin contain very similar code
+//! shape.
+//!
+//! Let's take a look at Roslyn:
+//!
+//!   <https://github.com/dotnet/roslyn/blob/36a0c338d6621cc5fe34b79d414074a95a6a489c/src/Compilers/CSharp/Portable/Compilation/SyntaxTreeSemanticModel.cs#L1403-L1429>
+//!   <https://sourceroslyn.io/#Microsoft.CodeAnalysis.CSharp/Compilation/SyntaxTreeSemanticModel.cs,1403>
+//!
+//! The `GetDeclaredType` takes `Syntax` as input, and returns `Symbol` as
+//! output. First, it retrieves a `Symbol` for parent `Syntax`:
+//!
+//! * <https://sourceroslyn.io/#Microsoft.CodeAnalysis.CSharp/Compilation/SyntaxTreeSemanticModel.cs,1423>
+//!
+//! Then, it iterates parent symbol's children, looking for one which has the
+//! same text span as the original node:
+//!
+//!   <https://sourceroslyn.io/#Microsoft.CodeAnalysis.CSharp/Compilation/SyntaxTreeSemanticModel.cs,1786>
+//!
+//! Now, let's look at Kotlin:
+//!
+//!   <https://github.com/JetBrains/kotlin/blob/a288b8b00e4754a1872b164999c6d3f3b8c8994a/idea/idea-frontend-fir/idea-fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/FirModuleResolveStateImpl.kt#L93-L125>
+//!
+//! This function starts with a syntax node (`KtExpression` is syntax, like all
+//! `Kt` nodes), and returns a def. It uses
+//! `getNonLocalContainingOrThisDeclaration` to get syntactic container for a
+//! current node. Then, `findSourceNonLocalFirDeclaration` gets `Fir` for this
+//! parent. Finally, `findElementIn` function traverses `Fir` children to find
+//! one with the same source we originally started with.
+//!
+//! One question is left though -- where does the recursion stops? This happens
+//! when we get to the file syntax node, which doesn't have a syntactic parent.
+//! In that case, we loop through all the crates that might contain this file
+//! and look for a module whose source is the given file.
+//!
+//! Note that the logic in this module is somewhat fundamentally imprecise --
+//! due to conditional compilation and `#[path]` attributes, there's no
+//! injective mapping from syntax nodes to defs. This is not an edge case --
+//! more or less every item in a `lib.rs` is a part of two distinct crates: a
+//! library with `--cfg test` and a library without.
+//!
+//! At the moment, we don't really handle this well and return the first answer
+//! that works. Ideally, we should first let the caller to pick a specific
+//! active crate for a given position, and then provide an API to resolve all
+//! syntax nodes against this specific crate.
+
+use base_db::FileId;
+use either::Either;
+use hir_def::{
+    child_by_source::ChildBySource,
+    dyn_map::{
+        keys::{self, Key},
+        DynMap,
+    },
+    hir::{BindingId, LabelId},
+    AdtId, BlockId, ConstId, ConstParamId, DefWithBodyId, EnumId, EnumVariantId, ExternCrateId,
+    FieldId, FunctionId, GenericDefId, GenericParamId, ImplId, LifetimeParamId, MacroId, ModuleId,
+    StaticId, StructId, TraitAliasId, TraitId, TypeAliasId, TypeParamId, UnionId, UseId, VariantId,
+};
+use hir_expand::{attrs::AttrId, name::AsName, HirFileId, HirFileIdExt, MacroCallId};
+use rustc_hash::FxHashMap;
+use smallvec::SmallVec;
+use stdx::impl_from;
+use syntax::{
+    ast::{self, HasName},
+    AstNode, SyntaxNode,
+};
+
+use crate::{db::HirDatabase, InFile};
+
+pub(super) type SourceToDefCache = FxHashMap<(ChildContainer, HirFileId), DynMap>;
+
+pub(super) struct SourceToDefCtx<'a, 'b> {
+    pub(super) db: &'b dyn HirDatabase,
+    pub(super) dynmap_cache: &'a mut SourceToDefCache,
+}
+
+impl SourceToDefCtx<'_, '_> {
+    pub(super) fn file_to_def(&self, file: FileId) -> SmallVec<[ModuleId; 1]> {
+        let _p = tracing::span!(tracing::Level::INFO, "SourceBinder::file_to_module_def");
+        let mut mods = SmallVec::new();
+        for &crate_id in self.db.relevant_crates(file).iter() {
+            // FIXME: inner items
+            let crate_def_map = self.db.crate_def_map(crate_id);
+            mods.extend(
+                crate_def_map
+                    .modules_for_file(file)
+                    .map(|local_id| crate_def_map.module_id(local_id)),
+            )
+        }
+        mods
+    }
+
+    pub(super) fn module_to_def(&mut self, src: InFile<ast::Module>) -> Option<ModuleId> {
+        let _p = tracing::span!(tracing::Level::INFO, "module_to_def");
+        let parent_declaration = src
+            .syntax()
+            .ancestors_with_macros_skip_attr_item(self.db.upcast())
+            .find_map(|it| it.map(Either::<ast::Module, ast::BlockExpr>::cast).transpose())
+            .map(|it| it.transpose());
+
+        let parent_module = match parent_declaration {
+            Some(Either::Right(parent_block)) => self
+                .block_to_def(parent_block)
+                .map(|block| self.db.block_def_map(block).root_module_id()),
+            Some(Either::Left(parent_declaration)) => self.module_to_def(parent_declaration),
+            None => {
+                let file_id = src.file_id.original_file(self.db.upcast());
+                self.file_to_def(file_id).first().copied()
+            }
+        }?;
+
+        let child_name = src.value.name()?.as_name();
+        let def_map = parent_module.def_map(self.db.upcast());
+        let &child_id = def_map[parent_module.local_id].children.get(&child_name)?;
+        Some(def_map.module_id(child_id))
+    }
+
+    pub(super) fn source_file_to_def(&self, src: InFile<ast::SourceFile>) -> Option<ModuleId> {
+        let _p = tracing::span!(tracing::Level::INFO, "source_file_to_def");
+        let file_id = src.file_id.original_file(self.db.upcast());
+        self.file_to_def(file_id).first().copied()
+    }
+
+    pub(super) fn trait_to_def(&mut self, src: InFile<ast::Trait>) -> Option<TraitId> {
+        self.to_def(src, keys::TRAIT)
+    }
+    pub(super) fn trait_alias_to_def(
+        &mut self,
+        src: InFile<ast::TraitAlias>,
+    ) -> Option<TraitAliasId> {
+        self.to_def(src, keys::TRAIT_ALIAS)
+    }
+    pub(super) fn impl_to_def(&mut self, src: InFile<ast::Impl>) -> Option<ImplId> {
+        self.to_def(src, keys::IMPL)
+    }
+    pub(super) fn fn_to_def(&mut self, src: InFile<ast::Fn>) -> Option<FunctionId> {
+        self.to_def(src, keys::FUNCTION)
+    }
+    pub(super) fn struct_to_def(&mut self, src: InFile<ast::Struct>) -> Option<StructId> {
+        self.to_def(src, keys::STRUCT)
+    }
+    pub(super) fn enum_to_def(&mut self, src: InFile<ast::Enum>) -> Option<EnumId> {
+        self.to_def(src, keys::ENUM)
+    }
+    pub(super) fn union_to_def(&mut self, src: InFile<ast::Union>) -> Option<UnionId> {
+        self.to_def(src, keys::UNION)
+    }
+    pub(super) fn static_to_def(&mut self, src: InFile<ast::Static>) -> Option<StaticId> {
+        self.to_def(src, keys::STATIC)
+    }
+    pub(super) fn const_to_def(&mut self, src: InFile<ast::Const>) -> Option<ConstId> {
+        self.to_def(src, keys::CONST)
+    }
+    pub(super) fn type_alias_to_def(&mut self, src: InFile<ast::TypeAlias>) -> Option<TypeAliasId> {
+        self.to_def(src, keys::TYPE_ALIAS)
+    }
+    pub(super) fn record_field_to_def(&mut self, src: InFile<ast::RecordField>) -> Option<FieldId> {
+        self.to_def(src, keys::RECORD_FIELD)
+    }
+    pub(super) fn tuple_field_to_def(&mut self, src: InFile<ast::TupleField>) -> Option<FieldId> {
+        self.to_def(src, keys::TUPLE_FIELD)
+    }
+    pub(super) fn block_to_def(&mut self, src: InFile<ast::BlockExpr>) -> Option<BlockId> {
+        self.to_def(src, keys::BLOCK)
+    }
+    pub(super) fn enum_variant_to_def(
+        &mut self,
+        src: InFile<ast::Variant>,
+    ) -> Option<EnumVariantId> {
+        self.to_def(src, keys::ENUM_VARIANT)
+    }
+    pub(super) fn extern_crate_to_def(
+        &mut self,
+        src: InFile<ast::ExternCrate>,
+    ) -> Option<ExternCrateId> {
+        self.to_def(src, keys::EXTERN_CRATE)
+    }
+    #[allow(dead_code)]
+    pub(super) fn use_to_def(&mut self, src: InFile<ast::Use>) -> Option<UseId> {
+        self.to_def(src, keys::USE)
+    }
+    pub(super) fn adt_to_def(
+        &mut self,
+        InFile { file_id, value }: InFile<ast::Adt>,
+    ) -> Option<AdtId> {
+        match value {
+            ast::Adt::Enum(it) => self.enum_to_def(InFile::new(file_id, it)).map(AdtId::EnumId),
+            ast::Adt::Struct(it) => {
+                self.struct_to_def(InFile::new(file_id, it)).map(AdtId::StructId)
+            }
+            ast::Adt::Union(it) => self.union_to_def(InFile::new(file_id, it)).map(AdtId::UnionId),
+        }
+    }
+    pub(super) fn bind_pat_to_def(
+        &mut self,
+        src: InFile<ast::IdentPat>,
+    ) -> Option<(DefWithBodyId, BindingId)> {
+        let container = self.find_pat_or_label_container(src.syntax())?;
+        let (body, source_map) = self.db.body_with_source_map(container);
+        let src = src.map(ast::Pat::from);
+        let pat_id = source_map.node_pat(src.as_ref())?;
+        // the pattern could resolve to a constant, verify that that is not the case
+        if let crate::Pat::Bind { id, .. } = body[pat_id] {
+            Some((container, id))
+        } else {
+            None
+        }
+    }
+    pub(super) fn self_param_to_def(
+        &mut self,
+        src: InFile<ast::SelfParam>,
+    ) -> Option<(DefWithBodyId, BindingId)> {
+        let container = self.find_pat_or_label_container(src.syntax())?;
+        let body = self.db.body(container);
+        Some((container, body.self_param?))
+    }
+    pub(super) fn label_to_def(
+        &mut self,
+        src: InFile<ast::Label>,
+    ) -> Option<(DefWithBodyId, LabelId)> {
+        let container = self.find_pat_or_label_container(src.syntax())?;
+        let (_body, source_map) = self.db.body_with_source_map(container);
+        let label_id = source_map.node_label(src.as_ref())?;
+        Some((container, label_id))
+    }
+
+    pub(super) fn item_to_macro_call(&mut self, src: InFile<ast::Item>) -> Option<MacroCallId> {
+        let map = self.dyn_map(src.as_ref())?;
+        map[keys::ATTR_MACRO_CALL].get(&src.value).copied()
+    }
+
+    /// (AttrId, derive attribute call id, derive call ids)
+    pub(super) fn attr_to_derive_macro_call(
+        &mut self,
+        item: InFile<&ast::Adt>,
+        src: InFile<ast::Attr>,
+    ) -> Option<(AttrId, MacroCallId, &[Option<MacroCallId>])> {
+        let map = self.dyn_map(item)?;
+        map[keys::DERIVE_MACRO_CALL]
+            .get(&src.value)
+            .map(|&(attr_id, call_id, ref ids)| (attr_id, call_id, &**ids))
+    }
+
+    pub(super) fn has_derives(&mut self, adt: InFile<&ast::Adt>) -> bool {
+        self.dyn_map(adt).as_ref().map_or(false, |map| !map[keys::DERIVE_MACRO_CALL].is_empty())
+    }
+
+    fn to_def<Ast: AstNode + 'static, ID: Copy + 'static>(
+        &mut self,
+        src: InFile<Ast>,
+        key: Key<Ast, ID>,
+    ) -> Option<ID> {
+        self.dyn_map(src.as_ref())?[key].get(&src.value).copied()
+    }
+
+    fn dyn_map<Ast: AstNode + 'static>(&mut self, src: InFile<&Ast>) -> Option<&DynMap> {
+        let container = self.find_container(src.map(|it| it.syntax()))?;
+        Some(self.cache_for(container, src.file_id))
+    }
+
+    fn cache_for(&mut self, container: ChildContainer, file_id: HirFileId) -> &DynMap {
+        let db = self.db;
+        self.dynmap_cache
+            .entry((container, file_id))
+            .or_insert_with(|| container.child_by_source(db, file_id))
+    }
+
+    pub(super) fn type_param_to_def(&mut self, src: InFile<ast::TypeParam>) -> Option<TypeParamId> {
+        let container: ChildContainer = self.find_generic_param_container(src.syntax())?.into();
+        let dyn_map = self.cache_for(container, src.file_id);
+        dyn_map[keys::TYPE_PARAM].get(&src.value).copied().map(TypeParamId::from_unchecked)
+    }
+
+    pub(super) fn lifetime_param_to_def(
+        &mut self,
+        src: InFile<ast::LifetimeParam>,
+    ) -> Option<LifetimeParamId> {
+        let container: ChildContainer = self.find_generic_param_container(src.syntax())?.into();
+        let dyn_map = self.cache_for(container, src.file_id);
+        dyn_map[keys::LIFETIME_PARAM].get(&src.value).copied()
+    }
+
+    pub(super) fn const_param_to_def(
+        &mut self,
+        src: InFile<ast::ConstParam>,
+    ) -> Option<ConstParamId> {
+        let container: ChildContainer = self.find_generic_param_container(src.syntax())?.into();
+        let dyn_map = self.cache_for(container, src.file_id);
+        dyn_map[keys::CONST_PARAM].get(&src.value).copied().map(ConstParamId::from_unchecked)
+    }
+
+    pub(super) fn generic_param_to_def(
+        &mut self,
+        InFile { file_id, value }: InFile<ast::GenericParam>,
+    ) -> Option<GenericParamId> {
+        match value {
+            ast::GenericParam::ConstParam(it) => {
+                self.const_param_to_def(InFile::new(file_id, it)).map(GenericParamId::ConstParamId)
+            }
+            ast::GenericParam::LifetimeParam(it) => self
+                .lifetime_param_to_def(InFile::new(file_id, it))
+                .map(GenericParamId::LifetimeParamId),
+            ast::GenericParam::TypeParam(it) => {
+                self.type_param_to_def(InFile::new(file_id, it)).map(GenericParamId::TypeParamId)
+            }
+        }
+    }
+
+    pub(super) fn macro_to_def(&mut self, src: InFile<ast::Macro>) -> Option<MacroId> {
+        self.dyn_map(src.as_ref()).and_then(|it| match &src.value {
+            ast::Macro::MacroRules(value) => {
+                it[keys::MACRO_RULES].get(value).copied().map(MacroId::from)
+            }
+            ast::Macro::MacroDef(value) => it[keys::MACRO2].get(value).copied().map(MacroId::from),
+        })
+    }
+
+    pub(super) fn proc_macro_to_def(&mut self, src: InFile<ast::Fn>) -> Option<MacroId> {
+        self.dyn_map(src.as_ref())
+            .and_then(|it| it[keys::PROC_MACRO].get(&src.value).copied().map(MacroId::from))
+    }
+
+    pub(super) fn find_container(&mut self, src: InFile<&SyntaxNode>) -> Option<ChildContainer> {
+        for container in src.ancestors_with_macros_skip_attr_item(self.db.upcast()) {
+            if let Some(res) = self.container_to_def(container) {
+                return Some(res);
+            }
+        }
+
+        let def = self.file_to_def(src.file_id.original_file(self.db.upcast())).first().copied()?;
+        Some(def.into())
+    }
+
+    fn container_to_def(&mut self, container: InFile<SyntaxNode>) -> Option<ChildContainer> {
+        let cont = if let Some(item) = ast::Item::cast(container.value.clone()) {
+            match item {
+                ast::Item::Module(it) => self.module_to_def(container.with_value(it))?.into(),
+                ast::Item::Trait(it) => self.trait_to_def(container.with_value(it))?.into(),
+                ast::Item::TraitAlias(it) => {
+                    self.trait_alias_to_def(container.with_value(it))?.into()
+                }
+                ast::Item::Impl(it) => self.impl_to_def(container.with_value(it))?.into(),
+                ast::Item::Enum(it) => self.enum_to_def(container.with_value(it))?.into(),
+                ast::Item::TypeAlias(it) => {
+                    self.type_alias_to_def(container.with_value(it))?.into()
+                }
+                ast::Item::Struct(it) => {
+                    let def = self.struct_to_def(container.with_value(it))?;
+                    VariantId::from(def).into()
+                }
+                ast::Item::Union(it) => {
+                    let def = self.union_to_def(container.with_value(it))?;
+                    VariantId::from(def).into()
+                }
+                ast::Item::Fn(it) => {
+                    let def = self.fn_to_def(container.with_value(it))?;
+                    DefWithBodyId::from(def).into()
+                }
+                ast::Item::Static(it) => {
+                    let def = self.static_to_def(container.with_value(it))?;
+                    DefWithBodyId::from(def).into()
+                }
+                ast::Item::Const(it) => {
+                    let def = self.const_to_def(container.with_value(it))?;
+                    DefWithBodyId::from(def).into()
+                }
+                _ => return None,
+            }
+        } else {
+            let it = ast::Variant::cast(container.value)?;
+            let def = self.enum_variant_to_def(InFile::new(container.file_id, it))?;
+            DefWithBodyId::from(def).into()
+        };
+        Some(cont)
+    }
+
+    fn find_generic_param_container(&mut self, src: InFile<&SyntaxNode>) -> Option<GenericDefId> {
+        let ancestors = src.ancestors_with_macros_skip_attr_item(self.db.upcast());
+        for InFile { file_id, value } in ancestors {
+            let item = match ast::Item::cast(value) {
+                Some(it) => it,
+                None => continue,
+            };
+            let res: GenericDefId = match item {
+                ast::Item::Fn(it) => self.fn_to_def(InFile::new(file_id, it))?.into(),
+                ast::Item::Struct(it) => self.struct_to_def(InFile::new(file_id, it))?.into(),
+                ast::Item::Enum(it) => self.enum_to_def(InFile::new(file_id, it))?.into(),
+                ast::Item::Trait(it) => self.trait_to_def(InFile::new(file_id, it))?.into(),
+                ast::Item::TraitAlias(it) => {
+                    self.trait_alias_to_def(InFile::new(file_id, it))?.into()
+                }
+                ast::Item::TypeAlias(it) => {
+                    self.type_alias_to_def(InFile::new(file_id, it))?.into()
+                }
+                ast::Item::Impl(it) => self.impl_to_def(InFile::new(file_id, it))?.into(),
+                _ => continue,
+            };
+            return Some(res);
+        }
+        None
+    }
+
+    fn find_pat_or_label_container(&mut self, src: InFile<&SyntaxNode>) -> Option<DefWithBodyId> {
+        let ancestors = src.ancestors_with_macros_skip_attr_item(self.db.upcast());
+        for InFile { file_id, value } in ancestors {
+            let item = match ast::Item::cast(value) {
+                Some(it) => it,
+                None => continue,
+            };
+            let res: DefWithBodyId = match item {
+                ast::Item::Const(it) => self.const_to_def(InFile::new(file_id, it))?.into(),
+                ast::Item::Static(it) => self.static_to_def(InFile::new(file_id, it))?.into(),
+                ast::Item::Fn(it) => self.fn_to_def(InFile::new(file_id, it))?.into(),
+                _ => continue,
+            };
+            return Some(res);
+        }
+        None
+    }
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
+pub(crate) enum ChildContainer {
+    DefWithBodyId(DefWithBodyId),
+    ModuleId(ModuleId),
+    TraitId(TraitId),
+    TraitAliasId(TraitAliasId),
+    ImplId(ImplId),
+    EnumId(EnumId),
+    VariantId(VariantId),
+    TypeAliasId(TypeAliasId),
+    /// XXX: this might be the same def as, for example an `EnumId`. However,
+    /// here the children are generic parameters, and not, eg enum variants.
+    GenericDefId(GenericDefId),
+}
+impl_from! {
+    DefWithBodyId,
+    ModuleId,
+    TraitId,
+    TraitAliasId,
+    ImplId,
+    EnumId,
+    VariantId,
+    TypeAliasId,
+    GenericDefId
+    for ChildContainer
+}
+
+impl ChildContainer {
+    fn child_by_source(self, db: &dyn HirDatabase, file_id: HirFileId) -> DynMap {
+        let db = db.upcast();
+        match self {
+            ChildContainer::DefWithBodyId(it) => it.child_by_source(db, file_id),
+            ChildContainer::ModuleId(it) => it.child_by_source(db, file_id),
+            ChildContainer::TraitId(it) => it.child_by_source(db, file_id),
+            ChildContainer::TraitAliasId(_) => DynMap::default(),
+            ChildContainer::ImplId(it) => it.child_by_source(db, file_id),
+            ChildContainer::EnumId(it) => it.child_by_source(db, file_id),
+            ChildContainer::VariantId(it) => it.child_by_source(db, file_id),
+            ChildContainer::TypeAliasId(_) => DynMap::default(),
+            ChildContainer::GenericDefId(it) => it.child_by_source(db, file_id),
+        }
+    }
+}
diff --git a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs
new file mode 100644
index 00000000000..dc96a1b03d0
--- /dev/null
+++ b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs
@@ -0,0 +1,1283 @@
+//! Lookup hir elements using positions in the source code. This is a lossy
+//! transformation: in general, a single source might correspond to several
+//! modules, functions, etc, due to macros, cfgs and `#[path=]` attributes on
+//! modules.
+//!
+//! So, this modules should not be used during hir construction, it exists
+//! purely for "IDE needs".
+use std::iter::{self, once};
+
+use either::Either;
+use hir_def::{
+    body::{
+        scope::{ExprScopes, ScopeId},
+        Body, BodySourceMap,
+    },
+    hir::{BindingId, ExprId, Pat, PatId},
+    lang_item::LangItem,
+    lower::LowerCtx,
+    nameres::MacroSubNs,
+    path::{ModPath, Path, PathKind},
+    resolver::{resolver_for_scope, Resolver, TypeNs, ValueNs},
+    type_ref::Mutability,
+    AsMacroCall, AssocItemId, ConstId, DefWithBodyId, FieldId, FunctionId, ItemContainerId,
+    LocalFieldId, Lookup, ModuleDefId, TraitId, VariantId,
+};
+use hir_expand::{
+    builtin_fn_macro::BuiltinFnLikeExpander,
+    mod_path::path,
+    name,
+    name::{AsName, Name},
+    HirFileId, InFile, MacroFileId, MacroFileIdExt,
+};
+use hir_ty::{
+    diagnostics::{
+        record_literal_missing_fields, record_pattern_missing_fields, unsafe_expressions,
+        UnsafeExpr,
+    },
+    lang_items::lang_items_for_bin_op,
+    method_resolution, Adjustment, InferenceResult, Interner, Substitution, Ty, TyExt, TyKind,
+    TyLoweringContext,
+};
+use itertools::Itertools;
+use smallvec::SmallVec;
+use syntax::{
+    ast::{self, AstNode},
+    SyntaxKind, SyntaxNode, TextRange, TextSize,
+};
+use triomphe::Arc;
+
+use crate::{
+    db::HirDatabase, semantics::PathResolution, Adt, AssocItem, BindingMode, BuiltinAttr,
+    BuiltinType, Callable, Const, DeriveHelper, Field, Function, Local, Macro, ModuleDef, Static,
+    Struct, ToolModule, Trait, TraitAlias, TupleField, Type, TypeAlias, Variant,
+};
+
+/// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of
+/// original source files. It should not be used inside the HIR itself.
+#[derive(Debug)]
+pub(crate) struct SourceAnalyzer {
+    pub(crate) file_id: HirFileId,
+    pub(crate) resolver: Resolver,
+    def: Option<(DefWithBodyId, Arc<Body>, Arc<BodySourceMap>)>,
+    infer: Option<Arc<InferenceResult>>,
+}
+
+impl SourceAnalyzer {
+    pub(crate) fn new_for_body(
+        db: &dyn HirDatabase,
+        def: DefWithBodyId,
+        node @ InFile { file_id, .. }: InFile<&SyntaxNode>,
+        offset: Option<TextSize>,
+    ) -> SourceAnalyzer {
+        let (body, source_map) = db.body_with_source_map(def);
+        let scopes = db.expr_scopes(def);
+        let scope = match offset {
+            None => scope_for(&scopes, &source_map, node),
+            Some(offset) => scope_for_offset(db, &scopes, &source_map, node.file_id, offset),
+        };
+        let resolver = resolver_for_scope(db.upcast(), def, scope);
+        SourceAnalyzer {
+            resolver,
+            def: Some((def, body, source_map)),
+            infer: Some(db.infer(def)),
+            file_id,
+        }
+    }
+
+    pub(crate) fn new_for_body_no_infer(
+        db: &dyn HirDatabase,
+        def: DefWithBodyId,
+        node @ InFile { file_id, .. }: InFile<&SyntaxNode>,
+        offset: Option<TextSize>,
+    ) -> SourceAnalyzer {
+        let (body, source_map) = db.body_with_source_map(def);
+        let scopes = db.expr_scopes(def);
+        let scope = match offset {
+            None => scope_for(&scopes, &source_map, node),
+            Some(offset) => scope_for_offset(db, &scopes, &source_map, node.file_id, offset),
+        };
+        let resolver = resolver_for_scope(db.upcast(), def, scope);
+        SourceAnalyzer { resolver, def: Some((def, body, source_map)), infer: None, file_id }
+    }
+
+    pub(crate) fn new_for_resolver(
+        resolver: Resolver,
+        node: InFile<&SyntaxNode>,
+    ) -> SourceAnalyzer {
+        SourceAnalyzer { resolver, def: None, infer: None, file_id: node.file_id }
+    }
+
+    fn body_source_map(&self) -> Option<&BodySourceMap> {
+        self.def.as_ref().map(|(.., source_map)| &**source_map)
+    }
+    fn body(&self) -> Option<&Body> {
+        self.def.as_ref().map(|(_, body, _)| &**body)
+    }
+
+    fn expr_id(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<ExprId> {
+        let src = match expr {
+            ast::Expr::MacroExpr(expr) => {
+                self.expand_expr(db, InFile::new(self.file_id, expr.macro_call()?))?
+            }
+            _ => InFile::new(self.file_id, expr.clone()),
+        };
+        let sm = self.body_source_map()?;
+        sm.node_expr(src.as_ref())
+    }
+
+    fn pat_id(&self, pat: &ast::Pat) -> Option<PatId> {
+        // FIXME: macros, see `expr_id`
+        let src = InFile { file_id: self.file_id, value: pat };
+        self.body_source_map()?.node_pat(src)
+    }
+
+    fn binding_id_of_pat(&self, pat: &ast::IdentPat) -> Option<BindingId> {
+        let pat_id = self.pat_id(&pat.clone().into())?;
+        if let Pat::Bind { id, .. } = self.body()?.pats[pat_id] {
+            Some(id)
+        } else {
+            None
+        }
+    }
+
+    fn expand_expr(
+        &self,
+        db: &dyn HirDatabase,
+        expr: InFile<ast::MacroCall>,
+    ) -> Option<InFile<ast::Expr>> {
+        let macro_file = self.body_source_map()?.node_macro_file(expr.as_ref())?;
+        let expanded = db.parse_or_expand(macro_file);
+        let res = if let Some(stmts) = ast::MacroStmts::cast(expanded.clone()) {
+            match stmts.expr()? {
+                ast::Expr::MacroExpr(mac) => {
+                    self.expand_expr(db, InFile::new(macro_file, mac.macro_call()?))?
+                }
+                expr => InFile::new(macro_file, expr),
+            }
+        } else if let Some(call) = ast::MacroCall::cast(expanded.clone()) {
+            self.expand_expr(db, InFile::new(macro_file, call))?
+        } else {
+            InFile::new(macro_file, ast::Expr::cast(expanded)?)
+        };
+
+        Some(res)
+    }
+
+    pub(crate) fn expr_adjustments(
+        &self,
+        db: &dyn HirDatabase,
+        expr: &ast::Expr,
+    ) -> Option<&[Adjustment]> {
+        let expr_id = self.expr_id(db, expr)?;
+        let infer = self.infer.as_ref()?;
+        infer.expr_adjustments.get(&expr_id).map(|v| &**v)
+    }
+
+    pub(crate) fn type_of_expr(
+        &self,
+        db: &dyn HirDatabase,
+        expr: &ast::Expr,
+    ) -> Option<(Type, Option<Type>)> {
+        let expr_id = self.expr_id(db, expr)?;
+        let infer = self.infer.as_ref()?;
+        let coerced = infer
+            .expr_adjustments
+            .get(&expr_id)
+            .and_then(|adjusts| adjusts.last().map(|adjust| adjust.target.clone()));
+        let ty = infer[expr_id].clone();
+        let mk_ty = |ty| Type::new_with_resolver(db, &self.resolver, ty);
+        Some((mk_ty(ty), coerced.map(mk_ty)))
+    }
+
+    pub(crate) fn type_of_pat(
+        &self,
+        db: &dyn HirDatabase,
+        pat: &ast::Pat,
+    ) -> Option<(Type, Option<Type>)> {
+        let pat_id = self.pat_id(pat)?;
+        let infer = self.infer.as_ref()?;
+        let coerced =
+            infer.pat_adjustments.get(&pat_id).and_then(|adjusts| adjusts.last().cloned());
+        let ty = infer[pat_id].clone();
+        let mk_ty = |ty| Type::new_with_resolver(db, &self.resolver, ty);
+        Some((mk_ty(ty), coerced.map(mk_ty)))
+    }
+
+    pub(crate) fn type_of_binding_in_pat(
+        &self,
+        db: &dyn HirDatabase,
+        pat: &ast::IdentPat,
+    ) -> Option<Type> {
+        let binding_id = self.binding_id_of_pat(pat)?;
+        let infer = self.infer.as_ref()?;
+        let ty = infer[binding_id].clone();
+        let mk_ty = |ty| Type::new_with_resolver(db, &self.resolver, ty);
+        Some(mk_ty(ty))
+    }
+
+    pub(crate) fn type_of_self(
+        &self,
+        db: &dyn HirDatabase,
+        _param: &ast::SelfParam,
+    ) -> Option<Type> {
+        let binding = self.body()?.self_param?;
+        let ty = self.infer.as_ref()?[binding].clone();
+        Some(Type::new_with_resolver(db, &self.resolver, ty))
+    }
+
+    pub(crate) fn binding_mode_of_pat(
+        &self,
+        _db: &dyn HirDatabase,
+        pat: &ast::IdentPat,
+    ) -> Option<BindingMode> {
+        let id = self.pat_id(&pat.clone().into())?;
+        let infer = self.infer.as_ref()?;
+        infer.binding_modes.get(id).map(|bm| match bm {
+            hir_ty::BindingMode::Move => BindingMode::Move,
+            hir_ty::BindingMode::Ref(hir_ty::Mutability::Mut) => BindingMode::Ref(Mutability::Mut),
+            hir_ty::BindingMode::Ref(hir_ty::Mutability::Not) => {
+                BindingMode::Ref(Mutability::Shared)
+            }
+        })
+    }
+    pub(crate) fn pattern_adjustments(
+        &self,
+        db: &dyn HirDatabase,
+        pat: &ast::Pat,
+    ) -> Option<SmallVec<[Type; 1]>> {
+        let pat_id = self.pat_id(pat)?;
+        let infer = self.infer.as_ref()?;
+        Some(
+            infer
+                .pat_adjustments
+                .get(&pat_id)?
+                .iter()
+                .map(|ty| Type::new_with_resolver(db, &self.resolver, ty.clone()))
+                .collect(),
+        )
+    }
+
+    pub(crate) fn resolve_method_call_as_callable(
+        &self,
+        db: &dyn HirDatabase,
+        call: &ast::MethodCallExpr,
+    ) -> Option<Callable> {
+        let expr_id = self.expr_id(db, &call.clone().into())?;
+        let (func, substs) = self.infer.as_ref()?.method_resolution(expr_id)?;
+        let ty = db.value_ty(func.into())?.substitute(Interner, &substs);
+        let ty = Type::new_with_resolver(db, &self.resolver, ty);
+        let mut res = ty.as_callable(db)?;
+        res.is_bound_method = true;
+        Some(res)
+    }
+
+    pub(crate) fn resolve_method_call(
+        &self,
+        db: &dyn HirDatabase,
+        call: &ast::MethodCallExpr,
+    ) -> Option<Function> {
+        let expr_id = self.expr_id(db, &call.clone().into())?;
+        let (f_in_trait, substs) = self.infer.as_ref()?.method_resolution(expr_id)?;
+
+        Some(self.resolve_impl_method_or_trait_def(db, f_in_trait, substs).into())
+    }
+
+    pub(crate) fn resolve_method_call_fallback(
+        &self,
+        db: &dyn HirDatabase,
+        call: &ast::MethodCallExpr,
+    ) -> Option<Either<Function, Field>> {
+        let expr_id = self.expr_id(db, &call.clone().into())?;
+        let inference_result = self.infer.as_ref()?;
+        match inference_result.method_resolution(expr_id) {
+            Some((f_in_trait, substs)) => Some(Either::Left(
+                self.resolve_impl_method_or_trait_def(db, f_in_trait, substs).into(),
+            )),
+            None => inference_result
+                .field_resolution(expr_id)
+                .and_then(Either::left)
+                .map(Into::into)
+                .map(Either::Right),
+        }
+    }
+
+    pub(crate) fn resolve_expr_as_callable(
+        &self,
+        db: &dyn HirDatabase,
+        call: &ast::Expr,
+    ) -> Option<Callable> {
+        self.type_of_expr(db, &call.clone())?.0.as_callable(db)
+    }
+
+    pub(crate) fn resolve_field(
+        &self,
+        db: &dyn HirDatabase,
+        field: &ast::FieldExpr,
+    ) -> Option<Either<Field, TupleField>> {
+        let &(def, ..) = self.def.as_ref()?;
+        let expr_id = self.expr_id(db, &field.clone().into())?;
+        self.infer.as_ref()?.field_resolution(expr_id).map(|it| {
+            it.map_either(Into::into, |f| TupleField { owner: def, tuple: f.tuple, index: f.index })
+        })
+    }
+
+    pub(crate) fn resolve_field_fallback(
+        &self,
+        db: &dyn HirDatabase,
+        field: &ast::FieldExpr,
+    ) -> Option<Either<Either<Field, TupleField>, Function>> {
+        let &(def, ..) = self.def.as_ref()?;
+        let expr_id = self.expr_id(db, &field.clone().into())?;
+        let inference_result = self.infer.as_ref()?;
+        match inference_result.field_resolution(expr_id) {
+            Some(field) => Some(Either::Left(field.map_either(Into::into, |f| TupleField {
+                owner: def,
+                tuple: f.tuple,
+                index: f.index,
+            }))),
+            None => inference_result.method_resolution(expr_id).map(|(f, substs)| {
+                Either::Right(self.resolve_impl_method_or_trait_def(db, f, substs).into())
+            }),
+        }
+    }
+
+    pub(crate) fn resolve_await_to_poll(
+        &self,
+        db: &dyn HirDatabase,
+        await_expr: &ast::AwaitExpr,
+    ) -> Option<FunctionId> {
+        let mut ty = self.ty_of_expr(db, &await_expr.expr()?)?.clone();
+
+        let into_future_trait = self
+            .resolver
+            .resolve_known_trait(db.upcast(), &path![core::future::IntoFuture])
+            .map(Trait::from);
+
+        if let Some(into_future_trait) = into_future_trait {
+            let type_ = Type::new_with_resolver(db, &self.resolver, ty.clone());
+            if type_.impls_trait(db, into_future_trait, &[]) {
+                let items = into_future_trait.items(db);
+                let into_future_type = items.into_iter().find_map(|item| match item {
+                    AssocItem::TypeAlias(alias)
+                        if alias.name(db) == hir_expand::name![IntoFuture] =>
+                    {
+                        Some(alias)
+                    }
+                    _ => None,
+                })?;
+                let future_trait = type_.normalize_trait_assoc_type(db, &[], into_future_type)?;
+                ty = future_trait.ty;
+            }
+        }
+
+        let future_trait = db.lang_item(self.resolver.krate(), LangItem::Future)?.as_trait()?;
+        let poll_fn = db.lang_item(self.resolver.krate(), LangItem::FuturePoll)?.as_function()?;
+        // HACK: subst for `poll()` coincides with that for `Future` because `poll()` itself
+        // doesn't have any generic parameters, so we skip building another subst for `poll()`.
+        let substs = hir_ty::TyBuilder::subst_for_def(db, future_trait, None).push(ty).build();
+        Some(self.resolve_impl_method_or_trait_def(db, poll_fn, substs))
+    }
+
+    pub(crate) fn resolve_prefix_expr(
+        &self,
+        db: &dyn HirDatabase,
+        prefix_expr: &ast::PrefixExpr,
+    ) -> Option<FunctionId> {
+        let (op_trait, op_fn) = match prefix_expr.op_kind()? {
+            ast::UnaryOp::Deref => {
+                // This can be either `Deref::deref` or `DerefMut::deref_mut`.
+                // Since deref kind is inferenced and stored in `InferenceResult.method_resolution`,
+                // use that result to find out which one it is.
+                let (deref_trait, deref) =
+                    self.lang_trait_fn(db, LangItem::Deref, &name![deref])?;
+                self.infer
+                    .as_ref()
+                    .and_then(|infer| {
+                        let expr = self.expr_id(db, &prefix_expr.clone().into())?;
+                        let (func, _) = infer.method_resolution(expr)?;
+                        let (deref_mut_trait, deref_mut) =
+                            self.lang_trait_fn(db, LangItem::DerefMut, &name![deref_mut])?;
+                        if func == deref_mut {
+                            Some((deref_mut_trait, deref_mut))
+                        } else {
+                            None
+                        }
+                    })
+                    .unwrap_or((deref_trait, deref))
+            }
+            ast::UnaryOp::Not => self.lang_trait_fn(db, LangItem::Not, &name![not])?,
+            ast::UnaryOp::Neg => self.lang_trait_fn(db, LangItem::Neg, &name![neg])?,
+        };
+
+        let ty = self.ty_of_expr(db, &prefix_expr.expr()?)?;
+
+        // HACK: subst for all methods coincides with that for their trait because the methods
+        // don't have any generic parameters, so we skip building another subst for the methods.
+        let substs = hir_ty::TyBuilder::subst_for_def(db, op_trait, None).push(ty.clone()).build();
+
+        Some(self.resolve_impl_method_or_trait_def(db, op_fn, substs))
+    }
+
+    pub(crate) fn resolve_index_expr(
+        &self,
+        db: &dyn HirDatabase,
+        index_expr: &ast::IndexExpr,
+    ) -> Option<FunctionId> {
+        let base_ty = self.ty_of_expr(db, &index_expr.base()?)?;
+        let index_ty = self.ty_of_expr(db, &index_expr.index()?)?;
+
+        let (index_trait, index_fn) = self.lang_trait_fn(db, LangItem::Index, &name![index])?;
+        let (op_trait, op_fn) = self
+            .infer
+            .as_ref()
+            .and_then(|infer| {
+                let expr = self.expr_id(db, &index_expr.clone().into())?;
+                let (func, _) = infer.method_resolution(expr)?;
+                let (index_mut_trait, index_mut_fn) =
+                    self.lang_trait_fn(db, LangItem::IndexMut, &name![index_mut])?;
+                if func == index_mut_fn {
+                    Some((index_mut_trait, index_mut_fn))
+                } else {
+                    None
+                }
+            })
+            .unwrap_or((index_trait, index_fn));
+        // HACK: subst for all methods coincides with that for their trait because the methods
+        // don't have any generic parameters, so we skip building another subst for the methods.
+        let substs = hir_ty::TyBuilder::subst_for_def(db, op_trait, None)
+            .push(base_ty.clone())
+            .push(index_ty.clone())
+            .build();
+        Some(self.resolve_impl_method_or_trait_def(db, op_fn, substs))
+    }
+
+    pub(crate) fn resolve_bin_expr(
+        &self,
+        db: &dyn HirDatabase,
+        binop_expr: &ast::BinExpr,
+    ) -> Option<FunctionId> {
+        let op = binop_expr.op_kind()?;
+        let lhs = self.ty_of_expr(db, &binop_expr.lhs()?)?;
+        let rhs = self.ty_of_expr(db, &binop_expr.rhs()?)?;
+
+        let (op_trait, op_fn) = lang_items_for_bin_op(op)
+            .and_then(|(name, lang_item)| self.lang_trait_fn(db, lang_item, &name))?;
+        // HACK: subst for `index()` coincides with that for `Index` because `index()` itself
+        // doesn't have any generic parameters, so we skip building another subst for `index()`.
+        let substs = hir_ty::TyBuilder::subst_for_def(db, op_trait, None)
+            .push(lhs.clone())
+            .push(rhs.clone())
+            .build();
+
+        Some(self.resolve_impl_method_or_trait_def(db, op_fn, substs))
+    }
+
+    pub(crate) fn resolve_try_expr(
+        &self,
+        db: &dyn HirDatabase,
+        try_expr: &ast::TryExpr,
+    ) -> Option<FunctionId> {
+        let ty = self.ty_of_expr(db, &try_expr.expr()?)?;
+
+        let op_fn = db.lang_item(self.resolver.krate(), LangItem::TryTraitBranch)?.as_function()?;
+        let op_trait = match op_fn.lookup(db.upcast()).container {
+            ItemContainerId::TraitId(id) => id,
+            _ => return None,
+        };
+        // HACK: subst for `branch()` coincides with that for `Try` because `branch()` itself
+        // doesn't have any generic parameters, so we skip building another subst for `branch()`.
+        let substs = hir_ty::TyBuilder::subst_for_def(db, op_trait, None).push(ty.clone()).build();
+
+        Some(self.resolve_impl_method_or_trait_def(db, op_fn, substs))
+    }
+
+    pub(crate) fn resolve_record_field(
+        &self,
+        db: &dyn HirDatabase,
+        field: &ast::RecordExprField,
+    ) -> Option<(Field, Option<Local>, Type)> {
+        let record_expr = ast::RecordExpr::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
+        let expr = ast::Expr::from(record_expr);
+        let expr_id = self.body_source_map()?.node_expr(InFile::new(self.file_id, &expr))?;
+
+        let local_name = field.field_name()?.as_name();
+        let local = if field.name_ref().is_some() {
+            None
+        } else {
+            // Shorthand syntax, resolve to the local
+            let path = Path::from_known_path_with_no_generic(ModPath::from_segments(
+                PathKind::Plain,
+                once(local_name.clone()),
+            ));
+            match self.resolver.resolve_path_in_value_ns_fully(db.upcast(), &path) {
+                Some(ValueNs::LocalBinding(binding_id)) => {
+                    Some(Local { binding_id, parent: self.resolver.body_owner()? })
+                }
+                _ => None,
+            }
+        };
+        let (_, subst) = self.infer.as_ref()?.type_of_expr.get(expr_id)?.as_adt()?;
+        let variant = self.infer.as_ref()?.variant_resolution_for_expr(expr_id)?;
+        let variant_data = variant.variant_data(db.upcast());
+        let field = FieldId { parent: variant, local_id: variant_data.field(&local_name)? };
+        let field_ty =
+            db.field_types(variant).get(field.local_id)?.clone().substitute(Interner, subst);
+        Some((field.into(), local, Type::new_with_resolver(db, &self.resolver, field_ty)))
+    }
+
+    pub(crate) fn resolve_record_pat_field(
+        &self,
+        db: &dyn HirDatabase,
+        field: &ast::RecordPatField,
+    ) -> Option<(Field, Type)> {
+        let field_name = field.field_name()?.as_name();
+        let record_pat = ast::RecordPat::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
+        let pat_id = self.pat_id(&record_pat.into())?;
+        let variant = self.infer.as_ref()?.variant_resolution_for_pat(pat_id)?;
+        let variant_data = variant.variant_data(db.upcast());
+        let field = FieldId { parent: variant, local_id: variant_data.field(&field_name)? };
+        let (_, subst) = self.infer.as_ref()?.type_of_pat.get(pat_id)?.as_adt()?;
+        let field_ty =
+            db.field_types(variant).get(field.local_id)?.clone().substitute(Interner, subst);
+        Some((field.into(), Type::new_with_resolver(db, &self.resolver, field_ty)))
+    }
+
+    pub(crate) fn resolve_macro_call(
+        &self,
+        db: &dyn HirDatabase,
+        macro_call: InFile<&ast::MacroCall>,
+    ) -> Option<Macro> {
+        let ctx = LowerCtx::new(db.upcast(), macro_call.file_id);
+        let path = macro_call.value.path().and_then(|ast| Path::from_src(&ctx, ast))?;
+        self.resolver
+            .resolve_path_as_macro(db.upcast(), path.mod_path()?, Some(MacroSubNs::Bang))
+            .map(|(it, _)| it.into())
+    }
+
+    pub(crate) fn resolve_bind_pat_to_const(
+        &self,
+        db: &dyn HirDatabase,
+        pat: &ast::IdentPat,
+    ) -> Option<ModuleDef> {
+        let pat_id = self.pat_id(&pat.clone().into())?;
+        let body = self.body()?;
+        let path = match &body[pat_id] {
+            Pat::Path(path) => path,
+            _ => return None,
+        };
+        let res = resolve_hir_path(db, &self.resolver, path)?;
+        match res {
+            PathResolution::Def(def) => Some(def),
+            _ => None,
+        }
+    }
+
+    pub(crate) fn resolve_path(
+        &self,
+        db: &dyn HirDatabase,
+        path: &ast::Path,
+    ) -> Option<PathResolution> {
+        let parent = path.syntax().parent();
+        let parent = || parent.clone();
+
+        let mut prefer_value_ns = false;
+        let resolved = (|| {
+            let infer = self.infer.as_deref()?;
+            if let Some(path_expr) = parent().and_then(ast::PathExpr::cast) {
+                let expr_id = self.expr_id(db, &path_expr.into())?;
+                if let Some((assoc, subs)) = infer.assoc_resolutions_for_expr(expr_id) {
+                    let assoc = match assoc {
+                        AssocItemId::FunctionId(f_in_trait) => {
+                            match infer.type_of_expr.get(expr_id) {
+                                None => assoc,
+                                Some(func_ty) => {
+                                    if let TyKind::FnDef(_fn_def, subs) = func_ty.kind(Interner) {
+                                        self.resolve_impl_method_or_trait_def(
+                                            db,
+                                            f_in_trait,
+                                            subs.clone(),
+                                        )
+                                        .into()
+                                    } else {
+                                        assoc
+                                    }
+                                }
+                            }
+                        }
+                        AssocItemId::ConstId(const_id) => {
+                            self.resolve_impl_const_or_trait_def(db, const_id, subs).into()
+                        }
+                        assoc => assoc,
+                    };
+
+                    return Some(PathResolution::Def(AssocItem::from(assoc).into()));
+                }
+                if let Some(VariantId::EnumVariantId(variant)) =
+                    infer.variant_resolution_for_expr(expr_id)
+                {
+                    return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
+                }
+                prefer_value_ns = true;
+            } else if let Some(path_pat) = parent().and_then(ast::PathPat::cast) {
+                let pat_id = self.pat_id(&path_pat.into())?;
+                if let Some((assoc, subs)) = infer.assoc_resolutions_for_pat(pat_id) {
+                    let assoc = match assoc {
+                        AssocItemId::ConstId(const_id) => {
+                            self.resolve_impl_const_or_trait_def(db, const_id, subs).into()
+                        }
+                        assoc => assoc,
+                    };
+                    return Some(PathResolution::Def(AssocItem::from(assoc).into()));
+                }
+                if let Some(VariantId::EnumVariantId(variant)) =
+                    infer.variant_resolution_for_pat(pat_id)
+                {
+                    return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
+                }
+            } else if let Some(rec_lit) = parent().and_then(ast::RecordExpr::cast) {
+                let expr_id = self.expr_id(db, &rec_lit.into())?;
+                if let Some(VariantId::EnumVariantId(variant)) =
+                    infer.variant_resolution_for_expr(expr_id)
+                {
+                    return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
+                }
+            } else {
+                let record_pat = parent().and_then(ast::RecordPat::cast).map(ast::Pat::from);
+                let tuple_struct_pat =
+                    || parent().and_then(ast::TupleStructPat::cast).map(ast::Pat::from);
+                if let Some(pat) = record_pat.or_else(tuple_struct_pat) {
+                    let pat_id = self.pat_id(&pat)?;
+                    let variant_res_for_pat = infer.variant_resolution_for_pat(pat_id);
+                    if let Some(VariantId::EnumVariantId(variant)) = variant_res_for_pat {
+                        return Some(PathResolution::Def(ModuleDef::Variant(variant.into())));
+                    }
+                }
+            }
+            None
+        })();
+        if resolved.is_some() {
+            return resolved;
+        }
+
+        // This must be a normal source file rather than macro file.
+        let ctx = LowerCtx::new(db.upcast(), self.file_id);
+        let hir_path = Path::from_src(&ctx, path.clone())?;
+
+        // Case where path is a qualifier of a use tree, e.g. foo::bar::{Baz, Qux} where we are
+        // trying to resolve foo::bar.
+        if let Some(use_tree) = parent().and_then(ast::UseTree::cast) {
+            if use_tree.coloncolon_token().is_some() {
+                return resolve_hir_path_qualifier(db, &self.resolver, &hir_path);
+            }
+        }
+
+        let meta_path = path
+            .syntax()
+            .ancestors()
+            .take_while(|it| {
+                let kind = it.kind();
+                ast::Path::can_cast(kind) || ast::Meta::can_cast(kind)
+            })
+            .last()
+            .and_then(ast::Meta::cast);
+
+        // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we are
+        // trying to resolve foo::bar.
+        if path.parent_path().is_some() {
+            return match resolve_hir_path_qualifier(db, &self.resolver, &hir_path) {
+                None if meta_path.is_some() => {
+                    path.first_segment().and_then(|it| it.name_ref()).and_then(|name_ref| {
+                        ToolModule::by_name(db, self.resolver.krate().into(), &name_ref.text())
+                            .map(PathResolution::ToolModule)
+                    })
+                }
+                res => res,
+            };
+        } else if let Some(meta_path) = meta_path {
+            // Case where we are resolving the final path segment of a path in an attribute
+            // in this case we have to check for inert/builtin attributes and tools and prioritize
+            // resolution of attributes over other namespaces
+            if let Some(name_ref) = path.as_single_name_ref() {
+                let builtin =
+                    BuiltinAttr::by_name(db, self.resolver.krate().into(), &name_ref.text());
+                if builtin.is_some() {
+                    return builtin.map(PathResolution::BuiltinAttr);
+                }
+
+                if let Some(attr) = meta_path.parent_attr() {
+                    let adt = if let Some(field) =
+                        attr.syntax().parent().and_then(ast::RecordField::cast)
+                    {
+                        field.syntax().ancestors().take(4).find_map(ast::Adt::cast)
+                    } else if let Some(field) =
+                        attr.syntax().parent().and_then(ast::TupleField::cast)
+                    {
+                        field.syntax().ancestors().take(4).find_map(ast::Adt::cast)
+                    } else if let Some(variant) =
+                        attr.syntax().parent().and_then(ast::Variant::cast)
+                    {
+                        variant.syntax().ancestors().nth(2).and_then(ast::Adt::cast)
+                    } else {
+                        None
+                    };
+                    if let Some(adt) = adt {
+                        let ast_id = db.ast_id_map(self.file_id).ast_id(&adt);
+                        if let Some(helpers) = self
+                            .resolver
+                            .def_map()
+                            .derive_helpers_in_scope(InFile::new(self.file_id, ast_id))
+                        {
+                            // FIXME: Multiple derives can have the same helper
+                            let name_ref = name_ref.as_name();
+                            for (macro_id, mut helpers) in
+                                helpers.iter().group_by(|(_, macro_id, ..)| macro_id).into_iter()
+                            {
+                                if let Some(idx) = helpers.position(|(name, ..)| *name == name_ref)
+                                {
+                                    return Some(PathResolution::DeriveHelper(DeriveHelper {
+                                        derive: *macro_id,
+                                        idx: idx as u32,
+                                    }));
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+            return match resolve_hir_path_as_attr_macro(db, &self.resolver, &hir_path) {
+                Some(m) => Some(PathResolution::Def(ModuleDef::Macro(m))),
+                // this labels any path that starts with a tool module as the tool itself, this is technically wrong
+                // but there is no benefit in differentiating these two cases for the time being
+                None => path.first_segment().and_then(|it| it.name_ref()).and_then(|name_ref| {
+                    ToolModule::by_name(db, self.resolver.krate().into(), &name_ref.text())
+                        .map(PathResolution::ToolModule)
+                }),
+            };
+        }
+        if parent().map_or(false, |it| ast::Visibility::can_cast(it.kind())) {
+            resolve_hir_path_qualifier(db, &self.resolver, &hir_path)
+        } else {
+            resolve_hir_path_(db, &self.resolver, &hir_path, prefer_value_ns)
+        }
+    }
+
+    pub(crate) fn record_literal_missing_fields(
+        &self,
+        db: &dyn HirDatabase,
+        literal: &ast::RecordExpr,
+    ) -> Option<Vec<(Field, Type)>> {
+        let body = self.body()?;
+        let infer = self.infer.as_ref()?;
+
+        let expr_id = self.expr_id(db, &literal.clone().into())?;
+        let substs = infer.type_of_expr[expr_id].as_adt()?.1;
+
+        let (variant, missing_fields, _exhaustive) =
+            record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
+        let res = self.missing_fields(db, substs, variant, missing_fields);
+        Some(res)
+    }
+
+    pub(crate) fn record_pattern_missing_fields(
+        &self,
+        db: &dyn HirDatabase,
+        pattern: &ast::RecordPat,
+    ) -> Option<Vec<(Field, Type)>> {
+        let body = self.body()?;
+        let infer = self.infer.as_ref()?;
+
+        let pat_id = self.pat_id(&pattern.clone().into())?;
+        let substs = infer.type_of_pat[pat_id].as_adt()?.1;
+
+        let (variant, missing_fields, _exhaustive) =
+            record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
+        let res = self.missing_fields(db, substs, variant, missing_fields);
+        Some(res)
+    }
+
+    fn missing_fields(
+        &self,
+        db: &dyn HirDatabase,
+        substs: &Substitution,
+        variant: VariantId,
+        missing_fields: Vec<LocalFieldId>,
+    ) -> Vec<(Field, Type)> {
+        let field_types = db.field_types(variant);
+
+        missing_fields
+            .into_iter()
+            .map(|local_id| {
+                let field = FieldId { parent: variant, local_id };
+                let ty = field_types[local_id].clone().substitute(Interner, substs);
+                (field.into(), Type::new_with_resolver_inner(db, &self.resolver, ty))
+            })
+            .collect()
+    }
+
+    pub(crate) fn expand(
+        &self,
+        db: &dyn HirDatabase,
+        macro_call: InFile<&ast::MacroCall>,
+    ) -> Option<MacroFileId> {
+        let krate = self.resolver.krate();
+        let macro_call_id = macro_call.as_call_id(db.upcast(), krate, |path| {
+            self.resolver.resolve_path_as_macro_def(db.upcast(), &path, Some(MacroSubNs::Bang))
+        })?;
+        // why the 64?
+        Some(macro_call_id.as_macro_file()).filter(|it| it.expansion_level(db.upcast()) < 64)
+    }
+
+    pub(crate) fn resolve_variant(
+        &self,
+        db: &dyn HirDatabase,
+        record_lit: ast::RecordExpr,
+    ) -> Option<VariantId> {
+        let infer = self.infer.as_ref()?;
+        let expr_id = self.expr_id(db, &record_lit.into())?;
+        infer.variant_resolution_for_expr(expr_id)
+    }
+
+    pub(crate) fn is_unsafe_macro_call(
+        &self,
+        db: &dyn HirDatabase,
+        macro_call: InFile<&ast::MacroCall>,
+    ) -> bool {
+        // check for asm/global_asm
+        if let Some(mac) = self.resolve_macro_call(db, macro_call) {
+            let ex = match mac.id {
+                hir_def::MacroId::Macro2Id(it) => it.lookup(db.upcast()).expander,
+                hir_def::MacroId::MacroRulesId(it) => it.lookup(db.upcast()).expander,
+                _ => hir_def::MacroExpander::Declarative,
+            };
+            match ex {
+                hir_def::MacroExpander::BuiltIn(e)
+                    if e == BuiltinFnLikeExpander::Asm || e == BuiltinFnLikeExpander::GlobalAsm =>
+                {
+                    return true
+                }
+                _ => (),
+            }
+        }
+        let macro_expr = match macro_call
+            .map(|it| it.syntax().parent().and_then(ast::MacroExpr::cast))
+            .transpose()
+        {
+            Some(it) => it,
+            None => return false,
+        };
+
+        if let (Some((def, body, sm)), Some(infer)) = (&self.def, &self.infer) {
+            if let Some(expanded_expr) = sm.macro_expansion_expr(macro_expr.as_ref()) {
+                let mut is_unsafe = false;
+                unsafe_expressions(
+                    db,
+                    infer,
+                    *def,
+                    body,
+                    expanded_expr,
+                    &mut |UnsafeExpr { inside_unsafe_block, .. }| is_unsafe |= !inside_unsafe_block,
+                );
+                return is_unsafe;
+            }
+        }
+        false
+    }
+
+    pub(crate) fn resolve_offset_in_format_args(
+        &self,
+        db: &dyn HirDatabase,
+        format_args: InFile<&ast::FormatArgsExpr>,
+        offset: TextSize,
+    ) -> Option<(TextRange, Option<PathResolution>)> {
+        let implicits = self.body_source_map()?.implicit_format_args(format_args)?;
+        implicits.iter().find(|(range, _)| range.contains_inclusive(offset)).map(|(range, name)| {
+            (
+                *range,
+                resolve_hir_value_path(
+                    db,
+                    &self.resolver,
+                    self.resolver.body_owner(),
+                    &Path::from_known_path_with_no_generic(ModPath::from_segments(
+                        PathKind::Plain,
+                        Some(name.clone()),
+                    )),
+                ),
+            )
+        })
+    }
+
+    pub(crate) fn as_format_args_parts<'a>(
+        &'a self,
+        db: &'a dyn HirDatabase,
+        format_args: InFile<&ast::FormatArgsExpr>,
+    ) -> Option<impl Iterator<Item = (TextRange, Option<PathResolution>)> + 'a> {
+        Some(self.body_source_map()?.implicit_format_args(format_args)?.iter().map(
+            move |(range, name)| {
+                (
+                    *range,
+                    resolve_hir_value_path(
+                        db,
+                        &self.resolver,
+                        self.resolver.body_owner(),
+                        &Path::from_known_path_with_no_generic(ModPath::from_segments(
+                            PathKind::Plain,
+                            Some(name.clone()),
+                        )),
+                    ),
+                )
+            },
+        ))
+    }
+
+    fn resolve_impl_method_or_trait_def(
+        &self,
+        db: &dyn HirDatabase,
+        func: FunctionId,
+        substs: Substitution,
+    ) -> FunctionId {
+        let owner = match self.resolver.body_owner() {
+            Some(it) => it,
+            None => return func,
+        };
+        let env = db.trait_environment_for_body(owner);
+        db.lookup_impl_method(env, func, substs).0
+    }
+
+    fn resolve_impl_const_or_trait_def(
+        &self,
+        db: &dyn HirDatabase,
+        const_id: ConstId,
+        subs: Substitution,
+    ) -> ConstId {
+        let owner = match self.resolver.body_owner() {
+            Some(it) => it,
+            None => return const_id,
+        };
+        let env = db.trait_environment_for_body(owner);
+        method_resolution::lookup_impl_const(db, env, const_id, subs).0
+    }
+
+    fn lang_trait_fn(
+        &self,
+        db: &dyn HirDatabase,
+        lang_trait: LangItem,
+        method_name: &Name,
+    ) -> Option<(TraitId, FunctionId)> {
+        let trait_id = db.lang_item(self.resolver.krate(), lang_trait)?.as_trait()?;
+        let fn_id = db.trait_data(trait_id).method_by_name(method_name)?;
+        Some((trait_id, fn_id))
+    }
+
+    fn ty_of_expr(&self, db: &dyn HirDatabase, expr: &ast::Expr) -> Option<&Ty> {
+        self.infer.as_ref()?.type_of_expr.get(self.expr_id(db, expr)?)
+    }
+}
+
+fn scope_for(
+    scopes: &ExprScopes,
+    source_map: &BodySourceMap,
+    node: InFile<&SyntaxNode>,
+) -> Option<ScopeId> {
+    node.value
+        .ancestors()
+        .filter_map(ast::Expr::cast)
+        .filter_map(|it| source_map.node_expr(InFile::new(node.file_id, &it)))
+        .find_map(|it| scopes.scope_for(it))
+}
+
+fn scope_for_offset(
+    db: &dyn HirDatabase,
+    scopes: &ExprScopes,
+    source_map: &BodySourceMap,
+    from_file: HirFileId,
+    offset: TextSize,
+) -> Option<ScopeId> {
+    scopes
+        .scope_by_expr()
+        .iter()
+        .filter_map(|(id, scope)| {
+            let InFile { file_id, value } = source_map.expr_syntax(id).ok()?;
+            if from_file == file_id {
+                return Some((value.text_range(), scope));
+            }
+
+            // FIXME handle attribute expansion
+            let source =
+                iter::successors(file_id.macro_file().map(|it| it.call_node(db.upcast())), |it| {
+                    Some(it.file_id.macro_file()?.call_node(db.upcast()))
+                })
+                .find(|it| it.file_id == from_file)
+                .filter(|it| it.value.kind() == SyntaxKind::MACRO_CALL)?;
+            Some((source.value.text_range(), scope))
+        })
+        .filter(|(expr_range, _scope)| expr_range.start() <= offset && offset <= expr_range.end())
+        // find containing scope
+        .min_by_key(|(expr_range, _scope)| expr_range.len())
+        .map(|(expr_range, scope)| {
+            adjust(db, scopes, source_map, expr_range, from_file, offset).unwrap_or(*scope)
+        })
+}
+
+// XXX: during completion, cursor might be outside of any particular
+// expression. Try to figure out the correct scope...
+fn adjust(
+    db: &dyn HirDatabase,
+    scopes: &ExprScopes,
+    source_map: &BodySourceMap,
+    expr_range: TextRange,
+    from_file: HirFileId,
+    offset: TextSize,
+) -> Option<ScopeId> {
+    let child_scopes = scopes
+        .scope_by_expr()
+        .iter()
+        .filter_map(|(id, scope)| {
+            let source = source_map.expr_syntax(id).ok()?;
+            // FIXME: correctly handle macro expansion
+            if source.file_id != from_file {
+                return None;
+            }
+            let root = source.file_syntax(db.upcast());
+            let node = source.value.to_node(&root);
+            Some((node.syntax().text_range(), scope))
+        })
+        .filter(|&(range, _)| {
+            range.start() <= offset && expr_range.contains_range(range) && range != expr_range
+        });
+
+    child_scopes
+        .max_by(|&(r1, _), &(r2, _)| {
+            if r1.contains_range(r2) {
+                std::cmp::Ordering::Greater
+            } else if r2.contains_range(r1) {
+                std::cmp::Ordering::Less
+            } else {
+                r1.start().cmp(&r2.start())
+            }
+        })
+        .map(|(_ptr, scope)| *scope)
+}
+
+#[inline]
+pub(crate) fn resolve_hir_path(
+    db: &dyn HirDatabase,
+    resolver: &Resolver,
+    path: &Path,
+) -> Option<PathResolution> {
+    resolve_hir_path_(db, resolver, path, false)
+}
+
+#[inline]
+pub(crate) fn resolve_hir_path_as_attr_macro(
+    db: &dyn HirDatabase,
+    resolver: &Resolver,
+    path: &Path,
+) -> Option<Macro> {
+    resolver
+        .resolve_path_as_macro(db.upcast(), path.mod_path()?, Some(MacroSubNs::Attr))
+        .map(|(it, _)| it)
+        .map(Into::into)
+}
+
+fn resolve_hir_path_(
+    db: &dyn HirDatabase,
+    resolver: &Resolver,
+    path: &Path,
+    prefer_value_ns: bool,
+) -> Option<PathResolution> {
+    let types = || {
+        let (ty, unresolved) = match path.type_anchor() {
+            Some(type_ref) => {
+                let (_, res) =
+                    TyLoweringContext::new_maybe_unowned(db, resolver, resolver.type_owner())
+                        .lower_ty_ext(type_ref);
+                res.map(|ty_ns| (ty_ns, path.segments().first()))
+            }
+            None => {
+                let (ty, remaining_idx, _) = resolver.resolve_path_in_type_ns(db.upcast(), path)?;
+                match remaining_idx {
+                    Some(remaining_idx) => {
+                        if remaining_idx + 1 == path.segments().len() {
+                            Some((ty, path.segments().last()))
+                        } else {
+                            None
+                        }
+                    }
+                    None => Some((ty, None)),
+                }
+            }
+        }?;
+
+        // If we are in a TypeNs for a Trait, and we have an unresolved name, try to resolve it as a type
+        // within the trait's associated types.
+        if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) {
+            if let Some(type_alias_id) =
+                db.trait_data(trait_id).associated_type_by_name(unresolved.name)
+            {
+                return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into()));
+            }
+        }
+
+        let res = match ty {
+            TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
+            TypeNs::GenericParam(id) => PathResolution::TypeParam(id.into()),
+            TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
+                PathResolution::Def(Adt::from(it).into())
+            }
+            TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
+            TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
+            TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
+            TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
+            TypeNs::TraitAliasId(it) => PathResolution::Def(TraitAlias::from(it).into()),
+        };
+        match unresolved {
+            Some(unresolved) => resolver
+                .generic_def()
+                .and_then(|def| {
+                    hir_ty::associated_type_shorthand_candidates(
+                        db,
+                        def,
+                        res.in_type_ns()?,
+                        |name, id| (name == unresolved.name).then_some(id),
+                    )
+                })
+                .map(TypeAlias::from)
+                .map(Into::into)
+                .map(PathResolution::Def),
+            None => Some(res),
+        }
+    };
+
+    let body_owner = resolver.body_owner();
+    let values = || resolve_hir_value_path(db, resolver, body_owner, path);
+
+    let items = || {
+        resolver
+            .resolve_module_path_in_items(db.upcast(), path.mod_path()?)
+            .take_types()
+            .map(|it| PathResolution::Def(it.into()))
+    };
+
+    let macros = || {
+        resolver
+            .resolve_path_as_macro(db.upcast(), path.mod_path()?, None)
+            .map(|(def, _)| PathResolution::Def(ModuleDef::Macro(def.into())))
+    };
+
+    if prefer_value_ns { values().or_else(types) } else { types().or_else(values) }
+        .or_else(items)
+        .or_else(macros)
+}
+
+fn resolve_hir_value_path(
+    db: &dyn HirDatabase,
+    resolver: &Resolver,
+    body_owner: Option<DefWithBodyId>,
+    path: &Path,
+) -> Option<PathResolution> {
+    resolver.resolve_path_in_value_ns_fully(db.upcast(), path).and_then(|val| {
+        let res = match val {
+            ValueNs::LocalBinding(binding_id) => {
+                let var = Local { parent: body_owner?, binding_id };
+                PathResolution::Local(var)
+            }
+            ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
+            ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
+            ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
+            ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
+            ValueNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
+            ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
+            ValueNs::GenericParam(id) => PathResolution::ConstParam(id.into()),
+        };
+        Some(res)
+    })
+}
+
+/// Resolves a path where we know it is a qualifier of another path.
+///
+/// For example, if we have:
+/// ```
+/// mod my {
+///     pub mod foo {
+///         struct Bar;
+///     }
+///
+///     pub fn foo() {}
+/// }
+/// ```
+/// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
+fn resolve_hir_path_qualifier(
+    db: &dyn HirDatabase,
+    resolver: &Resolver,
+    path: &Path,
+) -> Option<PathResolution> {
+    (|| {
+        let (ty, unresolved) = match path.type_anchor() {
+            Some(type_ref) => {
+                let (_, res) =
+                    TyLoweringContext::new_maybe_unowned(db, resolver, resolver.type_owner())
+                        .lower_ty_ext(type_ref);
+                res.map(|ty_ns| (ty_ns, path.segments().first()))
+            }
+            None => {
+                let (ty, remaining_idx, _) = resolver.resolve_path_in_type_ns(db.upcast(), path)?;
+                match remaining_idx {
+                    Some(remaining_idx) => {
+                        if remaining_idx + 1 == path.segments().len() {
+                            Some((ty, path.segments().last()))
+                        } else {
+                            None
+                        }
+                    }
+                    None => Some((ty, None)),
+                }
+            }
+        }?;
+
+        // If we are in a TypeNs for a Trait, and we have an unresolved name, try to resolve it as a type
+        // within the trait's associated types.
+        if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty) {
+            if let Some(type_alias_id) =
+                db.trait_data(trait_id).associated_type_by_name(unresolved.name)
+            {
+                return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into()));
+            }
+        }
+
+        let res = match ty {
+            TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
+            TypeNs::GenericParam(id) => PathResolution::TypeParam(id.into()),
+            TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
+                PathResolution::Def(Adt::from(it).into())
+            }
+            TypeNs::EnumVariantId(it) => PathResolution::Def(Variant::from(it).into()),
+            TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
+            TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
+            TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
+            TypeNs::TraitAliasId(it) => PathResolution::Def(TraitAlias::from(it).into()),
+        };
+        match unresolved {
+            Some(unresolved) => resolver
+                .generic_def()
+                .and_then(|def| {
+                    hir_ty::associated_type_shorthand_candidates(
+                        db,
+                        def,
+                        res.in_type_ns()?,
+                        |name, id| (name == unresolved.name).then_some(id),
+                    )
+                })
+                .map(TypeAlias::from)
+                .map(Into::into)
+                .map(PathResolution::Def),
+            None => Some(res),
+        }
+    })()
+    .or_else(|| {
+        resolver
+            .resolve_module_path_in_items(db.upcast(), path.mod_path()?)
+            .take_types()
+            .map(|it| PathResolution::Def(it.into()))
+    })
+}
diff --git a/src/tools/rust-analyzer/crates/hir/src/symbols.rs b/src/tools/rust-analyzer/crates/hir/src/symbols.rs
new file mode 100644
index 00000000000..3b88836c24b
--- /dev/null
+++ b/src/tools/rust-analyzer/crates/hir/src/symbols.rs
@@ -0,0 +1,352 @@
+//! File symbol extraction.
+
+use base_db::FileRange;
+use hir_def::{
+    db::DefDatabase,
+    item_scope::ItemInNs,
+    src::{HasChildSource, HasSource},
+    AdtId, AssocItemId, DefWithBodyId, HasModule, ImplId, Lookup, MacroId, ModuleDefId, ModuleId,
+    TraitId,
+};
+use hir_expand::{HirFileId, InFile};
+use hir_ty::{db::HirDatabase, display::HirDisplay};
+use syntax::{ast::HasName, AstNode, AstPtr, SmolStr, SyntaxNode, SyntaxNodePtr};
+
+use crate::{Module, ModuleDef, Semantics};
+
+/// The actual data that is stored in the index. It should be as compact as
+/// possible.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct FileSymbol {
+    pub name: SmolStr,
+    pub def: ModuleDef,
+    pub loc: DeclarationLocation,
+    pub container_name: Option<SmolStr>,
+    /// Whether this symbol is a doc alias for the original symbol.
+    pub is_alias: bool,
+    pub is_assoc: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct DeclarationLocation {
+    /// The file id for both the `ptr` and `name_ptr`.
+    pub hir_file_id: HirFileId,
+    /// This points to the whole syntax node of the declaration.
+    pub ptr: SyntaxNodePtr,
+    /// This points to the [`syntax::ast::Name`] identifier of the declaration.
+    pub name_ptr: AstPtr<syntax::ast::Name>,
+}
+
+impl DeclarationLocation {
+    pub fn syntax<DB: HirDatabase>(&self, sema: &Semantics<'_, DB>) -> SyntaxNode {
+        let root = sema.parse_or_expand(self.hir_file_id);
+        self.ptr.to_node(&root)
+    }
+
+    pub fn original_range(&self, db: &dyn HirDatabase) -> FileRange {
+        if let Some(file_id) = self.hir_file_id.file_id() {
+            // fast path to prevent parsing
+            return FileRange { file_id, range: self.ptr.text_range() };
+        }
+        let node = resolve_node(db, self.hir_file_id, &self.ptr);
+        node.as_ref().original_file_range_rooted(db.upcast())
+    }
+}
+
+fn resolve_node(
+    db: &dyn HirDatabase,
+    file_id: HirFileId,
+    ptr: &SyntaxNodePtr,
+) -> InFile<SyntaxNode> {
+    let root = db.parse_or_expand(file_id);
+    let node = ptr.to_node(&root);
+    InFile::new(file_id, node)
+}
+
+/// Represents an outstanding module that the symbol collector must collect symbols from.
+struct SymbolCollectorWork {
+    module_id: ModuleId,
+    parent: Option<DefWithBodyId>,
+}
+
+pub struct SymbolCollector<'a> {
+    db: &'a dyn HirDatabase,
+    symbols: Vec<FileSymbol>,
+    work: Vec<SymbolCollectorWork>,
+    current_container_name: Option<SmolStr>,
+}
+
+/// Given a [`ModuleId`] and a [`HirDatabase`], use the DefMap for the module's crate to collect
+/// all symbols that should be indexed for the given module.
+impl<'a> SymbolCollector<'a> {
+    pub fn new(db: &'a dyn HirDatabase) -> Self {
+        SymbolCollector {
+            db,
+            symbols: Default::default(),
+            work: Default::default(),
+            current_container_name: None,
+        }
+    }
+
+    pub fn collect(&mut self, module: Module) {
+        // The initial work is the root module we're collecting, additional work will
+        // be populated as we traverse the module's definitions.
+        self.work.push(SymbolCollectorWork { module_id: module.into(), parent: None });
+
+        while let Some(work) = self.work.pop() {
+            self.do_work(work);
+        }
+    }
+
+    pub fn finish(self) -> Vec<FileSymbol> {
+        self.symbols
+    }
+
+    pub fn collect_module(db: &dyn HirDatabase, module: Module) -> Vec<FileSymbol> {
+        let mut symbol_collector = SymbolCollector::new(db);
+        symbol_collector.collect(module);
+        symbol_collector.finish()
+    }
+
+    fn do_work(&mut self, work: SymbolCollectorWork) {
+        self.db.unwind_if_cancelled();
+
+        let parent_name = work.parent.and_then(|id| self.def_with_body_id_name(id));
+        self.with_container_name(parent_name, |s| s.collect_from_module(work.module_id));
+    }
+
+    fn collect_from_module(&mut self, module_id: ModuleId) {
+        let def_map = module_id.def_map(self.db.upcast());
+        let scope = &def_map[module_id.local_id].scope;
+
+        for module_def_id in scope.declarations() {
+            match module_def_id {
+                ModuleDefId::ModuleId(id) => self.push_module(id),
+                ModuleDefId::FunctionId(id) => {
+                    self.push_decl(id, false);
+                    self.collect_from_body(id);
+                }
+                ModuleDefId::AdtId(AdtId::StructId(id)) => self.push_decl(id, false),
+                ModuleDefId::AdtId(AdtId::EnumId(id)) => self.push_decl(id, false),
+                ModuleDefId::AdtId(AdtId::UnionId(id)) => self.push_decl(id, false),
+                ModuleDefId::ConstId(id) => {
+                    self.push_decl(id, false);
+                    self.collect_from_body(id);
+                }
+                ModuleDefId::StaticId(id) => {
+                    self.push_decl(id, false);
+                    self.collect_from_body(id);
+                }
+                ModuleDefId::TraitId(id) => {
+                    self.push_decl(id, false);
+                    self.collect_from_trait(id);
+                }
+                ModuleDefId::TraitAliasId(id) => {
+                    self.push_decl(id, false);
+                }
+                ModuleDefId::TypeAliasId(id) => {
+                    self.push_decl(id, false);
+                }
+                ModuleDefId::MacroId(id) => match id {
+                    MacroId::Macro2Id(id) => self.push_decl(id, false),
+                    MacroId::MacroRulesId(id) => self.push_decl(id, false),
+                    MacroId::ProcMacroId(id) => self.push_decl(id, false),
+                },
+                // Don't index these.
+                ModuleDefId::BuiltinType(_) => {}
+                ModuleDefId::EnumVariantId(_) => {}
+            }
+        }
+
+        for impl_id in scope.impls() {
+            self.collect_from_impl(impl_id);
+        }
+
+        // Record renamed imports.
+        // FIXME: In case it imports multiple items under different namespaces we just pick one arbitrarily
+        // for now.
+        for id in scope.imports() {
+            let source = id.import.child_source(self.db.upcast());
+            let Some(use_tree_src) = source.value.get(id.idx) else { continue };
+            let Some(rename) = use_tree_src.rename() else { continue };
+            let Some(name) = rename.name() else { continue };
+
+            let res = scope.fully_resolve_import(self.db.upcast(), id);
+            res.iter_items().for_each(|(item, _)| {
+                let def = match item {
+                    ItemInNs::Types(def) | ItemInNs::Values(def) => def,
+                    ItemInNs::Macros(def) => ModuleDefId::from(def),
+                }
+                .into();
+                let dec_loc = DeclarationLocation {
+                    hir_file_id: source.file_id,
+                    ptr: SyntaxNodePtr::new(use_tree_src.syntax()),
+                    name_ptr: AstPtr::new(&name),
+                };
+
+                self.symbols.push(FileSymbol {
+                    name: name.text().into(),
+                    def,
+                    container_name: self.current_container_name.clone(),
+                    loc: dec_loc,
+                    is_alias: false,
+                    is_assoc: false,
+                });
+            });
+        }
+
+        for const_id in scope.unnamed_consts() {
+            self.collect_from_body(const_id);
+        }
+
+        for (_, id) in scope.legacy_macros() {
+            for &id in id {
+                if id.module(self.db.upcast()) == module_id {
+                    match id {
+                        MacroId::Macro2Id(id) => self.push_decl(id, false),
+                        MacroId::MacroRulesId(id) => self.push_decl(id, false),
+                        MacroId::ProcMacroId(id) => self.push_decl(id, false),
+                    }
+                }
+            }
+        }
+    }
+
+    fn collect_from_body(&mut self, body_id: impl Into<DefWithBodyId>) {
+        let body_id = body_id.into();
+        let body = self.db.body(body_id);
+
+        // Descend into the blocks and enqueue collection of all modules within.
+        for (_, def_map) in body.blocks(self.db.upcast()) {
+            for (id, _) in def_map.modules() {
+                self.work.push(SymbolCollectorWork {
+                    module_id: def_map.module_id(id),
+                    parent: Some(body_id),
+                });
+            }
+        }
+    }
+
+    fn collect_from_impl(&mut self, impl_id: ImplId) {
+        let impl_data = self.db.impl_data(impl_id);
+        let impl_name = Some(SmolStr::new(impl_data.self_ty.display(self.db).to_string()));
+        self.with_container_name(impl_name, |s| {
+            for &assoc_item_id in &impl_data.items {
+                s.push_assoc_item(assoc_item_id)
+            }
+        })
+    }
+
+    fn collect_from_trait(&mut self, trait_id: TraitId) {
+        let trait_data = self.db.trait_data(trait_id);
+        self.with_container_name(trait_data.name.as_text(), |s| {
+            for &(_, assoc_item_id) in &trait_data.items {
+                s.push_assoc_item(assoc_item_id);
+            }
+        });
+    }
+
+    fn with_container_name(&mut self, container_name: Option<SmolStr>, f: impl FnOnce(&mut Self)) {
+        if let Some(container_name) = container_name {
+            let prev = self.current_container_name.replace(container_name);
+            f(self);
+            self.current_container_name = prev;
+        } else {
+            f(self);
+        }
+    }
+
+    fn def_with_body_id_name(&self, body_id: DefWithBodyId) -> Option<SmolStr> {
+        match body_id {
+            DefWithBodyId::FunctionId(id) => Some(self.db.function_data(id).name.to_smol_str()),
+            DefWithBodyId::StaticId(id) => Some(self.db.static_data(id).name.to_smol_str()),
+            DefWithBodyId::ConstId(id) => Some(self.db.const_data(id).name.as_ref()?.to_smol_str()),
+            DefWithBodyId::VariantId(id) => Some(self.db.enum_variant_data(id).name.to_smol_str()),
+            DefWithBodyId::InTypeConstId(_) => Some("in type const".into()),
+        }
+    }
+
+    fn push_assoc_item(&mut self, assoc_item_id: AssocItemId) {
+        match assoc_item_id {
+            AssocItemId::FunctionId(id) => self.push_decl(id, true),
+            AssocItemId::ConstId(id) => self.push_decl(id, true),
+            AssocItemId::TypeAliasId(id) => self.push_decl(id, true),
+        }
+    }
+
+    fn push_decl<'db, L>(&mut self, id: L, is_assoc: bool)
+    where
+        L: Lookup<Database<'db> = dyn DefDatabase + 'db> + Into<ModuleDefId>,
+        <L as Lookup>::Data: HasSource,
+        <<L as Lookup>::Data as HasSource>::Value: HasName,
+    {
+        let loc = id.lookup(self.db.upcast());
+        let source = loc.source(self.db.upcast());
+        let Some(name_node) = source.value.name() else { return };
+        let def = ModuleDef::from(id.into());
+        let dec_loc = DeclarationLocation {
+            hir_file_id: source.file_id,
+            ptr: SyntaxNodePtr::new(source.value.syntax()),
+            name_ptr: AstPtr::new(&name_node),
+        };
+
+        if let Some(attrs) = def.attrs(self.db) {
+            for alias in attrs.doc_aliases() {
+                self.symbols.push(FileSymbol {
+                    name: alias,
+                    def,
+                    loc: dec_loc.clone(),
+                    container_name: self.current_container_name.clone(),
+                    is_alias: true,
+                    is_assoc,
+                });
+            }
+        }
+
+        self.symbols.push(FileSymbol {
+            name: name_node.text().into(),
+            def,
+            container_name: self.current_container_name.clone(),
+            loc: dec_loc,
+            is_alias: false,
+            is_assoc,
+        });
+    }
+
+    fn push_module(&mut self, module_id: ModuleId) {
+        let def_map = module_id.def_map(self.db.upcast());
+        let module_data = &def_map[module_id.local_id];
+        let Some(declaration) = module_data.origin.declaration() else { return };
+        let module = declaration.to_node(self.db.upcast());
+        let Some(name_node) = module.name() else { return };
+        let dec_loc = DeclarationLocation {
+            hir_file_id: declaration.file_id,
+            ptr: SyntaxNodePtr::new(module.syntax()),
+            name_ptr: AstPtr::new(&name_node),
+        };
+
+        let def = ModuleDef::Module(module_id.into());
+
+        if let Some(attrs) = def.attrs(self.db) {
+            for alias in attrs.doc_aliases() {
+                self.symbols.push(FileSymbol {
+                    name: alias,
+                    def,
+                    loc: dec_loc.clone(),
+                    container_name: self.current_container_name.clone(),
+                    is_alias: true,
+                    is_assoc: false,
+                });
+            }
+        }
+
+        self.symbols.push(FileSymbol {
+            name: name_node.text().into(),
+            def: ModuleDef::Module(module_id.into()),
+            container_name: self.current_container_name.clone(),
+            loc: dec_loc,
+            is_alias: false,
+            is_assoc: false,
+        });
+    }
+}
diff --git a/src/tools/rust-analyzer/crates/hir/src/term_search.rs b/src/tools/rust-analyzer/crates/hir/src/term_search.rs
new file mode 100644
index 00000000000..93e73004911
--- /dev/null
+++ b/src/tools/rust-analyzer/crates/hir/src/term_search.rs
@@ -0,0 +1,323 @@
+//! Term search
+
+use hir_def::type_ref::Mutability;
+use hir_ty::db::HirDatabase;
+use itertools::Itertools;
+use rustc_hash::{FxHashMap, FxHashSet};
+
+use crate::{ModuleDef, ScopeDef, Semantics, SemanticsScope, Type};
+
+mod expr;
+pub use expr::Expr;
+
+mod tactics;
+
+/// Key for lookup table to query new types reached.
+#[derive(Debug, Hash, PartialEq, Eq)]
+enum NewTypesKey {
+    ImplMethod,
+    StructProjection,
+}
+
+/// Helper enum to squash big number of alternative trees into `Many` variant as there is too many
+/// to take into account.
+#[derive(Debug)]
+enum AlternativeExprs {
+    /// There are few trees, so we keep track of them all
+    Few(FxHashSet<Expr>),
+    /// There are too many trees to keep track of
+    Many,
+}
+
+impl AlternativeExprs {
+    /// Construct alternative trees
+    ///
+    /// # Arguments
+    /// `threshold` - threshold value for many trees (more than that is many)
+    /// `exprs` - expressions iterator
+    fn new(threshold: usize, exprs: impl Iterator<Item = Expr>) -> AlternativeExprs {
+        let mut it = AlternativeExprs::Few(Default::default());
+        it.extend_with_threshold(threshold, exprs);
+        it
+    }
+
+    /// Get type trees stored in alternative trees (or `Expr::Many` in case of many)
+    ///
+    /// # Arguments
+    /// `ty` - Type of expressions queried (this is used to give type to `Expr::Many`)
+    fn exprs(&self, ty: &Type) -> Vec<Expr> {
+        match self {
+            AlternativeExprs::Few(exprs) => exprs.iter().cloned().collect(),
+            AlternativeExprs::Many => vec![Expr::Many(ty.clone())],
+        }
+    }
+
+    /// Extend alternative expressions
+    ///
+    /// # Arguments
+    /// `threshold` - threshold value for many trees (more than that is many)
+    /// `exprs` - expressions iterator
+    fn extend_with_threshold(&mut self, threshold: usize, exprs: impl Iterator<Item = Expr>) {
+        match self {
+            AlternativeExprs::Few(tts) => {
+                for it in exprs {
+                    if tts.len() > threshold {
+                        *self = AlternativeExprs::Many;
+                        break;
+                    }
+
+                    tts.insert(it);
+                }
+            }
+            AlternativeExprs::Many => (),
+        }
+    }
+
+    fn is_many(&self) -> bool {
+        matches!(self, AlternativeExprs::Many)
+    }
+}
+
+/// # Lookup table for term search
+///
+/// Lookup table keeps all the state during term search.
+/// This means it knows what types and how are reachable.
+///
+/// The secondary functionality for lookup table is to keep track of new types reached since last
+/// iteration as well as keeping track of which `ScopeDef` items have been used.
+/// Both of them are to speed up the term search by leaving out types / ScopeDefs that likely do
+/// not produce any new results.
+#[derive(Default, Debug)]
+struct LookupTable {
+    /// All the `Expr`s in "value" produce the type of "key"
+    data: FxHashMap<Type, AlternativeExprs>,
+    /// New types reached since last query by the `NewTypesKey`
+    new_types: FxHashMap<NewTypesKey, Vec<Type>>,
+    /// ScopeDefs that are not interesting any more
+    exhausted_scopedefs: FxHashSet<ScopeDef>,
+    /// ScopeDefs that were used in current round
+    round_scopedef_hits: FxHashSet<ScopeDef>,
+    /// Amount of rounds since scopedef was first used.
+    rounds_since_sopedef_hit: FxHashMap<ScopeDef, u32>,
+    /// Types queried but not present
+    types_wishlist: FxHashSet<Type>,
+    /// Threshold to squash trees to `Many`
+    many_threshold: usize,
+}
+
+impl LookupTable {
+    /// Initialize lookup table
+    fn new(many_threshold: usize, goal: Type) -> Self {
+        let mut res = Self { many_threshold, ..Default::default() };
+        res.new_types.insert(NewTypesKey::ImplMethod, Vec::new());
+        res.new_types.insert(NewTypesKey::StructProjection, Vec::new());
+        res.types_wishlist.insert(goal);
+        res
+    }
+
+    /// Find all `Expr`s that unify with the `ty`
+    fn find(&mut self, db: &dyn HirDatabase, ty: &Type) -> Option<Vec<Expr>> {
+        let res = self
+            .data
+            .iter()
+            .find(|(t, _)| t.could_unify_with_deeply(db, ty))
+            .map(|(t, tts)| tts.exprs(t));
+
+        if res.is_none() {
+            self.types_wishlist.insert(ty.clone());
+        }
+
+        res
+    }
+
+    /// Same as find but automatically creates shared reference of types in the lookup
+    ///
+    /// For example if we have type `i32` in data and we query for `&i32` it map all the type
+    /// trees we have for `i32` with `Expr::Reference` and returns them.
+    fn find_autoref(&mut self, db: &dyn HirDatabase, ty: &Type) -> Option<Vec<Expr>> {
+        let res = self
+            .data
+            .iter()
+            .find(|(t, _)| t.could_unify_with_deeply(db, ty))
+            .map(|(t, it)| it.exprs(t))
+            .or_else(|| {
+                self.data
+                    .iter()
+                    .find(|(t, _)| {
+                        Type::reference(t, Mutability::Shared).could_unify_with_deeply(db, ty)
+                    })
+                    .map(|(t, it)| {
+                        it.exprs(t)
+                            .into_iter()
+                            .map(|expr| Expr::Reference(Box::new(expr)))
+                            .collect()
+                    })
+            });
+
+        if res.is_none() {
+            self.types_wishlist.insert(ty.clone());
+        }
+
+        res
+    }
+
+    /// Insert new type trees for type
+    ///
+    /// Note that the types have to be the same, unification is not enough as unification is not
+    /// transitive. For example Vec<i32> and FxHashSet<i32> both unify with Iterator<Item = i32>,
+    /// but they clearly do not unify themselves.
+    fn insert(&mut self, ty: Type, exprs: impl Iterator<Item = Expr>) {
+        match self.data.get_mut(&ty) {
+            Some(it) => {
+                it.extend_with_threshold(self.many_threshold, exprs);
+                if it.is_many() {
+                    self.types_wishlist.remove(&ty);
+                }
+            }
+            None => {
+                self.data.insert(ty.clone(), AlternativeExprs::new(self.many_threshold, exprs));
+                for it in self.new_types.values_mut() {
+                    it.push(ty.clone());
+                }
+            }
+        }
+    }
+
+    /// Iterate all the reachable types
+    fn iter_types(&self) -> impl Iterator<Item = Type> + '_ {
+        self.data.keys().cloned()
+    }
+
+    /// Query new types reached since last query by key
+    ///
+    /// Create new key if you wish to query it to avoid conflicting with existing queries.
+    fn new_types(&mut self, key: NewTypesKey) -> Vec<Type> {
+        match self.new_types.get_mut(&key) {
+            Some(it) => std::mem::take(it),
+            None => Vec::new(),
+        }
+    }
+
+    /// Mark `ScopeDef` as exhausted meaning it is not interesting for us any more
+    fn mark_exhausted(&mut self, def: ScopeDef) {
+        self.exhausted_scopedefs.insert(def);
+    }
+
+    /// Mark `ScopeDef` as used meaning we managed to produce something useful from it
+    fn mark_fulfilled(&mut self, def: ScopeDef) {
+        self.round_scopedef_hits.insert(def);
+    }
+
+    /// Start new round (meant to be called at the beginning of iteration in `term_search`)
+    ///
+    /// This functions marks some `ScopeDef`s as exhausted if there have been
+    /// `MAX_ROUNDS_AFTER_HIT` rounds after first using a `ScopeDef`.
+    fn new_round(&mut self) {
+        for def in &self.round_scopedef_hits {
+            let hits =
+                self.rounds_since_sopedef_hit.entry(*def).and_modify(|n| *n += 1).or_insert(0);
+            const MAX_ROUNDS_AFTER_HIT: u32 = 2;
+            if *hits > MAX_ROUNDS_AFTER_HIT {
+                self.exhausted_scopedefs.insert(*def);
+            }
+        }
+        self.round_scopedef_hits.clear();
+    }
+
+    /// Get exhausted `ScopeDef`s
+    fn exhausted_scopedefs(&self) -> &FxHashSet<ScopeDef> {
+        &self.exhausted_scopedefs
+    }
+
+    /// Types queried but not found
+    fn types_wishlist(&mut self) -> &FxHashSet<Type> {
+        &self.types_wishlist
+    }
+}
+
+/// Context for the `term_search` function
+#[derive(Debug)]
+pub struct TermSearchCtx<'a, DB: HirDatabase> {
+    /// Semantics for the program
+    pub sema: &'a Semantics<'a, DB>,
+    /// Semantic scope, captures context for the term search
+    pub scope: &'a SemanticsScope<'a>,
+    /// Target / expected output type
+    pub goal: Type,
+    /// Configuration for term search
+    pub config: TermSearchConfig,
+}
+
+/// Configuration options for the term search
+#[derive(Debug, Clone, Copy)]
+pub struct TermSearchConfig {
+    /// Enable borrow checking, this guarantees the outputs of the `term_search` to borrow-check
+    pub enable_borrowcheck: bool,
+    /// Indicate when to squash multiple trees to `Many` as there are too many to keep track
+    pub many_alternatives_threshold: usize,
+    /// Depth of the search eg. number of cycles to run
+    pub depth: usize,
+}
+
+impl Default for TermSearchConfig {
+    fn default() -> Self {
+        Self { enable_borrowcheck: true, many_alternatives_threshold: 1, depth: 6 }
+    }
+}
+
+/// # Term search
+///
+/// Search for terms (expressions) that unify with the `goal` type.
+///
+/// # Arguments
+/// * `ctx` - Context for term search
+///
+/// Internally this function uses Breadth First Search to find path to `goal` type.
+/// The general idea is following:
+/// 1. Populate lookup (frontier for BFS) from values (local variables, statics, constants, etc)
+///    as well as from well knows values (such as `true/false` and `()`)
+/// 2. Iteratively expand the frontier (or contents of the lookup) by trying different type
+///    transformation tactics. For example functions take as from set of types (arguments) to some
+///    type (return type). Other transformations include methods on type, type constructors and
+///    projections to struct fields (field access).
+/// 3. Once we manage to find path to type we are interested in we continue for single round to see
+///    if we can find more paths that take us to the `goal` type.
+/// 4. Return all the paths (type trees) that take us to the `goal` type.
+///
+/// Note that there are usually more ways we can get to the `goal` type but some are discarded to
+/// reduce the memory consumption. It is also unlikely anyone is willing ti browse through
+/// thousands of possible responses so we currently take first 10 from every tactic.
+pub fn term_search<DB: HirDatabase>(ctx: &TermSearchCtx<'_, DB>) -> Vec<Expr> {
+    let module = ctx.scope.module();
+    let mut defs = FxHashSet::default();
+    defs.insert(ScopeDef::ModuleDef(ModuleDef::Module(module)));
+
+    ctx.scope.process_all_names(&mut |_, def| {
+        defs.insert(def);
+    });
+
+    let mut lookup = LookupTable::new(ctx.config.many_alternatives_threshold, ctx.goal.clone());
+
+    // Try trivial tactic first, also populates lookup table
+    let mut solutions: Vec<Expr> = tactics::trivial(ctx, &defs, &mut lookup).collect();
+    // Use well known types tactic before iterations as it does not depend on other tactics
+    solutions.extend(tactics::famous_types(ctx, &defs, &mut lookup));
+
+    for _ in 0..ctx.config.depth {
+        lookup.new_round();
+
+        solutions.extend(tactics::type_constructor(ctx, &defs, &mut lookup));
+        solutions.extend(tactics::free_function(ctx, &defs, &mut lookup));
+        solutions.extend(tactics::impl_method(ctx, &defs, &mut lookup));
+        solutions.extend(tactics::struct_projection(ctx, &defs, &mut lookup));
+        solutions.extend(tactics::impl_static_method(ctx, &defs, &mut lookup));
+        solutions.extend(tactics::make_tuple(ctx, &defs, &mut lookup));
+
+        // Discard not interesting `ScopeDef`s for speedup
+        for def in lookup.exhausted_scopedefs() {
+            defs.remove(def);
+        }
+    }
+
+    solutions.into_iter().filter(|it| !it.is_many()).unique().collect()
+}
diff --git a/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs b/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs
new file mode 100644
index 00000000000..2d0c5630e10
--- /dev/null
+++ b/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs
@@ -0,0 +1,483 @@
+//! Type tree for term search
+
+use hir_def::find_path::PrefixKind;
+use hir_expand::mod_path::ModPath;
+use hir_ty::{
+    db::HirDatabase,
+    display::{DisplaySourceCodeError, HirDisplay},
+};
+use itertools::Itertools;
+
+use crate::{
+    Adt, AsAssocItem, Const, ConstParam, Field, Function, GenericDef, Local, ModuleDef,
+    SemanticsScope, Static, Struct, StructKind, Trait, Type, Variant,
+};
+
+/// Helper function to get path to `ModuleDef`
+fn mod_item_path(
+    sema_scope: &SemanticsScope<'_>,
+    def: &ModuleDef,
+    prefer_no_std: bool,
+    prefer_prelude: bool,
+) -> Option<ModPath> {
+    let db = sema_scope.db;
+    // Account for locals shadowing items from module
+    let name_hit_count = def.name(db).map(|def_name| {
+        let mut name_hit_count = 0;
+        sema_scope.process_all_names(&mut |name, _| {
+            if name == def_name {
+                name_hit_count += 1;
+            }
+        });
+        name_hit_count
+    });
+
+    let m = sema_scope.module();
+    match name_hit_count {
+        Some(0..=1) | None => m.find_use_path(db.upcast(), *def, prefer_no_std, prefer_prelude),
+        Some(_) => m.find_use_path_prefixed(
+            db.upcast(),
+            *def,
+            PrefixKind::ByCrate,
+            prefer_no_std,
+            prefer_prelude,
+        ),
+    }
+}
+
+/// Helper function to get path to `ModuleDef` as string
+fn mod_item_path_str(
+    sema_scope: &SemanticsScope<'_>,
+    def: &ModuleDef,
+    prefer_no_std: bool,
+    prefer_prelude: bool,
+) -> Result<String, DisplaySourceCodeError> {
+    let path = mod_item_path(sema_scope, def, prefer_no_std, prefer_prelude);
+    path.map(|it| it.display(sema_scope.db.upcast()).to_string())
+        .ok_or(DisplaySourceCodeError::PathNotFound)
+}
+
+/// Helper function to get path to `Type`
+fn type_path(
+    sema_scope: &SemanticsScope<'_>,
+    ty: &Type,
+    prefer_no_std: bool,
+    prefer_prelude: bool,
+) -> Result<String, DisplaySourceCodeError> {
+    let db = sema_scope.db;
+    let m = sema_scope.module();
+
+    match ty.as_adt() {
+        Some(adt) => {
+            let ty_name = ty.display_source_code(db, m.id, true)?;
+
+            let mut path =
+                mod_item_path(sema_scope, &ModuleDef::Adt(adt), prefer_no_std, prefer_prelude)
+                    .unwrap();
+            path.pop_segment();
+            let path = path.display(db.upcast()).to_string();
+            let res = match path.is_empty() {
+                true => ty_name,
+                false => format!("{path}::{ty_name}"),
+            };
+            Ok(res)
+        }
+        None => ty.display_source_code(db, m.id, true),
+    }
+}
+
+/// Helper function to filter out generic parameters that are default
+fn non_default_generics(db: &dyn HirDatabase, def: GenericDef, generics: &[Type]) -> Vec<Type> {
+    def.type_or_const_params(db)
+        .into_iter()
+        .filter_map(|it| it.as_type_param(db))
+        .zip(generics)
+        .filter(|(tp, arg)| tp.default(db).as_ref() != Some(arg))
+        .map(|(_, arg)| arg.clone())
+        .collect()
+}
+
+/// Type tree shows how can we get from set of types to some type.
+///
+/// Consider the following code as an example
+/// ```
+/// fn foo(x: i32, y: bool) -> Option<i32> { None }
+/// fn bar() {
+///    let a = 1;
+///    let b = true;
+///    let c: Option<i32> = _;
+/// }
+/// ```
+/// If we generate type tree in the place of `_` we get
+/// ```txt
+///       Option<i32>
+///           |
+///     foo(i32, bool)
+///      /        \
+///  a: i32      b: bool
+/// ```
+/// So in short it pretty much gives us a way to get type `Option<i32>` using the items we have in
+/// scope.
+#[derive(Debug, Clone, Eq, Hash, PartialEq)]
+pub enum Expr {
+    /// Constant
+    Const(Const),
+    /// Static variable
+    Static(Static),
+    /// Local variable
+    Local(Local),
+    /// Constant generic parameter
+    ConstParam(ConstParam),
+    /// Well known type (such as `true` for bool)
+    FamousType { ty: Type, value: &'static str },
+    /// Function call (does not take self param)
+    Function { func: Function, generics: Vec<Type>, params: Vec<Expr> },
+    /// Method call (has self param)
+    Method { func: Function, generics: Vec<Type>, target: Box<Expr>, params: Vec<Expr> },
+    /// Enum variant construction
+    Variant { variant: Variant, generics: Vec<Type>, params: Vec<Expr> },
+    /// Struct construction
+    Struct { strukt: Struct, generics: Vec<Type>, params: Vec<Expr> },
+    /// Tuple construction
+    Tuple { ty: Type, params: Vec<Expr> },
+    /// Struct field access
+    Field { expr: Box<Expr>, field: Field },
+    /// Passing type as reference (with `&`)
+    Reference(Box<Expr>),
+    /// Indicates possibility of many different options that all evaluate to `ty`
+    Many(Type),
+}
+
+impl Expr {
+    /// Generate source code for type tree.
+    ///
+    /// Note that trait imports are not added to generated code.
+    /// To make sure that the code is valid, callee has to also ensure that all the traits listed
+    /// by `traits_used` method are also imported.
+    pub fn gen_source_code(
+        &self,
+        sema_scope: &SemanticsScope<'_>,
+        many_formatter: &mut dyn FnMut(&Type) -> String,
+        prefer_no_std: bool,
+        prefer_prelude: bool,
+    ) -> Result<String, DisplaySourceCodeError> {
+        let db = sema_scope.db;
+        let mod_item_path_str = |s, def| mod_item_path_str(s, def, prefer_no_std, prefer_prelude);
+        match self {
+            Expr::Const(it) => mod_item_path_str(sema_scope, &ModuleDef::Const(*it)),
+            Expr::Static(it) => mod_item_path_str(sema_scope, &ModuleDef::Static(*it)),
+            Expr::Local(it) => Ok(it.name(db).display(db.upcast()).to_string()),
+            Expr::ConstParam(it) => Ok(it.name(db).display(db.upcast()).to_string()),
+            Expr::FamousType { value, .. } => Ok(value.to_string()),
+            Expr::Function { func, params, .. } => {
+                let args = params
+                    .iter()
+                    .map(|f| {
+                        f.gen_source_code(sema_scope, many_formatter, prefer_no_std, prefer_prelude)
+                    })
+                    .collect::<Result<Vec<String>, DisplaySourceCodeError>>()?
+                    .into_iter()
+                    .join(", ");
+
+                match func.as_assoc_item(db).map(|it| it.container(db)) {
+                    Some(container) => {
+                        let container_name = match container {
+                            crate::AssocItemContainer::Trait(trait_) => {
+                                mod_item_path_str(sema_scope, &ModuleDef::Trait(trait_))?
+                            }
+                            crate::AssocItemContainer::Impl(imp) => {
+                                let self_ty = imp.self_ty(db);
+                                // Should it be guaranteed that `mod_item_path` always exists?
+                                match self_ty.as_adt().and_then(|adt| {
+                                    mod_item_path(
+                                        sema_scope,
+                                        &adt.into(),
+                                        prefer_no_std,
+                                        prefer_prelude,
+                                    )
+                                }) {
+                                    Some(path) => path.display(sema_scope.db.upcast()).to_string(),
+                                    None => self_ty.display(db).to_string(),
+                                }
+                            }
+                        };
+                        let fn_name = func.name(db).display(db.upcast()).to_string();
+                        Ok(format!("{container_name}::{fn_name}({args})"))
+                    }
+                    None => {
+                        let fn_name = mod_item_path_str(sema_scope, &ModuleDef::Function(*func))?;
+                        Ok(format!("{fn_name}({args})"))
+                    }
+                }
+            }
+            Expr::Method { func, target, params, .. } => {
+                if target.contains_many_in_illegal_pos() {
+                    return Ok(many_formatter(&target.ty(db)));
+                }
+
+                let func_name = func.name(db).display(db.upcast()).to_string();
+                let self_param = func.self_param(db).unwrap();
+                let target = target.gen_source_code(
+                    sema_scope,
+                    many_formatter,
+                    prefer_no_std,
+                    prefer_prelude,
+                )?;
+                let args = params
+                    .iter()
+                    .map(|f| {
+                        f.gen_source_code(sema_scope, many_formatter, prefer_no_std, prefer_prelude)
+                    })
+                    .collect::<Result<Vec<String>, DisplaySourceCodeError>>()?
+                    .into_iter()
+                    .join(", ");
+
+                match func.as_assoc_item(db).and_then(|it| it.container_or_implemented_trait(db)) {
+                    Some(trait_) => {
+                        let trait_name = mod_item_path_str(sema_scope, &ModuleDef::Trait(trait_))?;
+                        let target = match self_param.access(db) {
+                            crate::Access::Shared => format!("&{target}"),
+                            crate::Access::Exclusive => format!("&mut {target}"),
+                            crate::Access::Owned => target,
+                        };
+                        let res = match args.is_empty() {
+                            true => format!("{trait_name}::{func_name}({target})",),
+                            false => format!("{trait_name}::{func_name}({target}, {args})",),
+                        };
+                        Ok(res)
+                    }
+                    None => Ok(format!("{target}.{func_name}({args})")),
+                }
+            }
+            Expr::Variant { variant, generics, params } => {
+                let generics = non_default_generics(db, (*variant).into(), generics);
+                let generics_str = match generics.is_empty() {
+                    true => String::new(),
+                    false => {
+                        let generics = generics
+                            .iter()
+                            .map(|it| type_path(sema_scope, it, prefer_no_std, prefer_prelude))
+                            .collect::<Result<Vec<String>, DisplaySourceCodeError>>()?
+                            .into_iter()
+                            .join(", ");
+                        format!("::<{generics}>")
+                    }
+                };
+                let inner = match variant.kind(db) {
+                    StructKind::Tuple => {
+                        let args = params
+                            .iter()
+                            .map(|f| {
+                                f.gen_source_code(
+                                    sema_scope,
+                                    many_formatter,
+                                    prefer_no_std,
+                                    prefer_prelude,
+                                )
+                            })
+                            .collect::<Result<Vec<String>, DisplaySourceCodeError>>()?
+                            .into_iter()
+                            .join(", ");
+                        format!("{generics_str}({args})")
+                    }
+                    StructKind::Record => {
+                        let fields = variant.fields(db);
+                        let args = params
+                            .iter()
+                            .zip(fields.iter())
+                            .map(|(a, f)| {
+                                let tmp = format!(
+                                    "{}: {}",
+                                    f.name(db).display(db.upcast()),
+                                    a.gen_source_code(
+                                        sema_scope,
+                                        many_formatter,
+                                        prefer_no_std,
+                                        prefer_prelude
+                                    )?
+                                );
+                                Ok(tmp)
+                            })
+                            .collect::<Result<Vec<String>, DisplaySourceCodeError>>()?
+                            .into_iter()
+                            .join(", ");
+                        format!("{generics_str}{{ {args} }}")
+                    }
+                    StructKind::Unit => generics_str,
+                };
+
+                let prefix = mod_item_path_str(sema_scope, &ModuleDef::Variant(*variant))?;
+                Ok(format!("{prefix}{inner}"))
+            }
+            Expr::Struct { strukt, generics, params } => {
+                let generics = non_default_generics(db, (*strukt).into(), generics);
+                let inner = match strukt.kind(db) {
+                    StructKind::Tuple => {
+                        let args = params
+                            .iter()
+                            .map(|a| {
+                                a.gen_source_code(
+                                    sema_scope,
+                                    many_formatter,
+                                    prefer_no_std,
+                                    prefer_prelude,
+                                )
+                            })
+                            .collect::<Result<Vec<String>, DisplaySourceCodeError>>()?
+                            .into_iter()
+                            .join(", ");
+                        format!("({args})")
+                    }
+                    StructKind::Record => {
+                        let fields = strukt.fields(db);
+                        let args = params
+                            .iter()
+                            .zip(fields.iter())
+                            .map(|(a, f)| {
+                                let tmp = format!(
+                                    "{}: {}",
+                                    f.name(db).display(db.upcast()),
+                                    a.gen_source_code(
+                                        sema_scope,
+                                        many_formatter,
+                                        prefer_no_std,
+                                        prefer_prelude
+                                    )?
+                                );
+                                Ok(tmp)
+                            })
+                            .collect::<Result<Vec<String>, DisplaySourceCodeError>>()?
+                            .into_iter()
+                            .join(", ");
+                        format!(" {{ {args} }}")
+                    }
+                    StructKind::Unit => match generics.is_empty() {
+                        true => String::new(),
+                        false => {
+                            let generics = generics
+                                .iter()
+                                .map(|it| type_path(sema_scope, it, prefer_no_std, prefer_prelude))
+                                .collect::<Result<Vec<String>, DisplaySourceCodeError>>()?
+                                .into_iter()
+                                .join(", ");
+                            format!("::<{generics}>")
+                        }
+                    },
+                };
+
+                let prefix = mod_item_path_str(sema_scope, &ModuleDef::Adt(Adt::Struct(*strukt)))?;
+                Ok(format!("{prefix}{inner}"))
+            }
+            Expr::Tuple { params, .. } => {
+                let args = params
+                    .iter()
+                    .map(|a| {
+                        a.gen_source_code(sema_scope, many_formatter, prefer_no_std, prefer_prelude)
+                    })
+                    .collect::<Result<Vec<String>, DisplaySourceCodeError>>()?
+                    .into_iter()
+                    .join(", ");
+                let res = format!("({args})");
+                Ok(res)
+            }
+            Expr::Field { expr, field } => {
+                if expr.contains_many_in_illegal_pos() {
+                    return Ok(many_formatter(&expr.ty(db)));
+                }
+
+                let strukt = expr.gen_source_code(
+                    sema_scope,
+                    many_formatter,
+                    prefer_no_std,
+                    prefer_prelude,
+                )?;
+                let field = field.name(db).display(db.upcast()).to_string();
+                Ok(format!("{strukt}.{field}"))
+            }
+            Expr::Reference(expr) => {
+                if expr.contains_many_in_illegal_pos() {
+                    return Ok(many_formatter(&expr.ty(db)));
+                }
+
+                let inner = expr.gen_source_code(
+                    sema_scope,
+                    many_formatter,
+                    prefer_no_std,
+                    prefer_prelude,
+                )?;
+                Ok(format!("&{inner}"))
+            }
+            Expr::Many(ty) => Ok(many_formatter(ty)),
+        }
+    }
+
+    /// Get type of the type tree.
+    ///
+    /// Same as getting the type of root node
+    pub fn ty(&self, db: &dyn HirDatabase) -> Type {
+        match self {
+            Expr::Const(it) => it.ty(db),
+            Expr::Static(it) => it.ty(db),
+            Expr::Local(it) => it.ty(db),
+            Expr::ConstParam(it) => it.ty(db),
+            Expr::FamousType { ty, .. } => ty.clone(),
+            Expr::Function { func, generics, .. } => {
+                func.ret_type_with_args(db, generics.iter().cloned())
+            }
+            Expr::Method { func, generics, target, .. } => func.ret_type_with_args(
+                db,
+                target.ty(db).type_arguments().chain(generics.iter().cloned()),
+            ),
+            Expr::Variant { variant, generics, .. } => {
+                Adt::from(variant.parent_enum(db)).ty_with_args(db, generics.iter().cloned())
+            }
+            Expr::Struct { strukt, generics, .. } => {
+                Adt::from(*strukt).ty_with_args(db, generics.iter().cloned())
+            }
+            Expr::Tuple { ty, .. } => ty.clone(),
+            Expr::Field { expr, field } => field.ty_with_args(db, expr.ty(db).type_arguments()),
+            Expr::Reference(it) => it.ty(db),
+            Expr::Many(ty) => ty.clone(),
+        }
+    }
+
+    /// List the traits used in type tree
+    pub fn traits_used(&self, db: &dyn HirDatabase) -> Vec<Trait> {
+        let mut res = Vec::new();
+
+        if let Expr::Method { func, params, .. } = self {
+            res.extend(params.iter().flat_map(|it| it.traits_used(db)));
+            if let Some(it) = func.as_assoc_item(db) {
+                if let Some(it) = it.container_or_implemented_trait(db) {
+                    res.push(it);
+                }
+            }
+        }
+
+        res
+    }
+
+    /// Check in the tree contains `Expr::Many` variant in illegal place to insert `todo`,
+    /// `unimplemented` or similar macro
+    ///
+    /// Some examples are following
+    /// ```no_compile
+    /// macro!().foo
+    /// macro!().bar()
+    /// &macro!()
+    /// ```
+    fn contains_many_in_illegal_pos(&self) -> bool {
+        match self {
+            Expr::Method { target, .. } => target.contains_many_in_illegal_pos(),
+            Expr::Field { expr, .. } => expr.contains_many_in_illegal_pos(),
+            Expr::Reference(target) => target.is_many(),
+            Expr::Many(_) => true,
+            _ => false,
+        }
+    }
+
+    /// Helper function to check if outermost type tree is `Expr::Many` variant
+    pub fn is_many(&self) -> bool {
+        matches!(self, Expr::Many(_))
+    }
+}
diff --git a/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs b/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs
new file mode 100644
index 00000000000..63b2a2506f8
--- /dev/null
+++ b/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs
@@ -0,0 +1,932 @@
+//! Tactics for term search
+//!
+//! All the tactics take following arguments
+//! * `ctx` - Context for the term search
+//! * `defs` - Set of items in scope at term search target location
+//! * `lookup` - Lookup table for types
+//! And they return iterator that yields type trees that unify with the `goal` type.
+
+use std::iter;
+
+use hir_ty::db::HirDatabase;
+use hir_ty::mir::BorrowKind;
+use hir_ty::TyBuilder;
+use itertools::Itertools;
+use rustc_hash::FxHashSet;
+
+use crate::{
+    Adt, AssocItem, Enum, GenericDef, GenericParam, HasVisibility, Impl, ModuleDef, ScopeDef, Type,
+    TypeParam, Variant,
+};
+
+use crate::term_search::{Expr, TermSearchConfig};
+
+use super::{LookupTable, NewTypesKey, TermSearchCtx};
+
+/// # Trivial tactic
+///
+/// Attempts to fulfill the goal by trying items in scope
+/// Also works as a starting point to move all items in scope to lookup table.
+///
+/// # Arguments
+/// * `ctx` - Context for the term search
+/// * `defs` - Set of items in scope at term search target location
+/// * `lookup` - Lookup table for types
+///
+/// Returns iterator that yields elements that unify with `goal`.
+///
+/// _Note that there is no use of calling this tactic in every iteration as the output does not
+/// depend on the current state of `lookup`_
+pub(super) fn trivial<'a, DB: HirDatabase>(
+    ctx: &'a TermSearchCtx<'a, DB>,
+    defs: &'a FxHashSet<ScopeDef>,
+    lookup: &'a mut LookupTable,
+) -> impl Iterator<Item = Expr> + 'a {
+    let db = ctx.sema.db;
+    defs.iter().filter_map(|def| {
+        let expr = match def {
+            ScopeDef::ModuleDef(ModuleDef::Const(it)) => Some(Expr::Const(*it)),
+            ScopeDef::ModuleDef(ModuleDef::Static(it)) => Some(Expr::Static(*it)),
+            ScopeDef::GenericParam(GenericParam::ConstParam(it)) => Some(Expr::ConstParam(*it)),
+            ScopeDef::Local(it) => {
+                if ctx.config.enable_borrowcheck {
+                    let borrowck = db.borrowck(it.parent).ok()?;
+
+                    let invalid = borrowck.iter().any(|b| {
+                        b.partially_moved.iter().any(|moved| {
+                            Some(&moved.local) == b.mir_body.binding_locals.get(it.binding_id)
+                        }) || b.borrow_regions.iter().any(|region| {
+                            // Shared borrows are fine
+                            Some(&region.local) == b.mir_body.binding_locals.get(it.binding_id)
+                                && region.kind != BorrowKind::Shared
+                        })
+                    });
+
+                    if invalid {
+                        return None;
+                    }
+                }
+
+                Some(Expr::Local(*it))
+            }
+            _ => None,
+        }?;
+
+        lookup.mark_exhausted(*def);
+
+        let ty = expr.ty(db);
+        lookup.insert(ty.clone(), std::iter::once(expr.clone()));
+
+        // Don't suggest local references as they are not valid for return
+        if matches!(expr, Expr::Local(_)) && ty.contains_reference(db) {
+            return None;
+        }
+
+        ty.could_unify_with_deeply(db, &ctx.goal).then_some(expr)
+    })
+}
+
+/// # Type constructor tactic
+///
+/// Attempts different type constructors for enums and structs in scope
+///
+/// Updates lookup by new types reached and returns iterator that yields
+/// elements that unify with `goal`.
+///
+/// # Arguments
+/// * `ctx` - Context for the term search
+/// * `defs` - Set of items in scope at term search target location
+/// * `lookup` - Lookup table for types
+pub(super) fn type_constructor<'a, DB: HirDatabase>(
+    ctx: &'a TermSearchCtx<'a, DB>,
+    defs: &'a FxHashSet<ScopeDef>,
+    lookup: &'a mut LookupTable,
+) -> impl Iterator<Item = Expr> + 'a {
+    let db = ctx.sema.db;
+    let module = ctx.scope.module();
+    fn variant_helper(
+        db: &dyn HirDatabase,
+        lookup: &mut LookupTable,
+        parent_enum: Enum,
+        variant: Variant,
+        config: &TermSearchConfig,
+    ) -> Vec<(Type, Vec<Expr>)> {
+        // Ignore unstable
+        if variant.is_unstable(db) {
+            return Vec::new();
+        }
+
+        let generics = GenericDef::from(variant.parent_enum(db));
+        let Some(type_params) = generics
+            .type_or_const_params(db)
+            .into_iter()
+            .map(|it| it.as_type_param(db))
+            .collect::<Option<Vec<TypeParam>>>()
+        else {
+            // Ignore enums with const generics
+            return Vec::new();
+        };
+
+        // We currently do not check lifetime bounds so ignore all types that have something to do
+        // with them
+        if !generics.lifetime_params(db).is_empty() {
+            return Vec::new();
+        }
+
+        // Only account for stable type parameters for now, unstable params can be default
+        // tho, for example in `Box<T, #[unstable] A: Allocator>`
+        if type_params.iter().any(|it| it.is_unstable(db) && it.default(db).is_none()) {
+            return Vec::new();
+        }
+
+        let non_default_type_params_len =
+            type_params.iter().filter(|it| it.default(db).is_none()).count();
+
+        let enum_ty_shallow = Adt::from(parent_enum).ty(db);
+        let generic_params = lookup
+            .types_wishlist()
+            .clone()
+            .into_iter()
+            .filter(|ty| ty.could_unify_with(db, &enum_ty_shallow))
+            .map(|it| it.type_arguments().collect::<Vec<Type>>())
+            .chain((non_default_type_params_len == 0).then_some(Vec::new()));
+
+        generic_params
+            .filter_map(move |generics| {
+                // Insert default type params
+                let mut g = generics.into_iter();
+                let generics: Vec<_> = type_params
+                    .iter()
+                    .map(|it| it.default(db).or_else(|| g.next()))
+                    .collect::<Option<_>>()?;
+
+                let enum_ty = Adt::from(parent_enum).ty_with_args(db, generics.iter().cloned());
+
+                // Ignore types that have something to do with lifetimes
+                if config.enable_borrowcheck && enum_ty.contains_reference(db) {
+                    return None;
+                }
+
+                // Early exit if some param cannot be filled from lookup
+                let param_exprs: Vec<Vec<Expr>> = variant
+                    .fields(db)
+                    .into_iter()
+                    .map(|field| lookup.find(db, &field.ty_with_args(db, generics.iter().cloned())))
+                    .collect::<Option<_>>()?;
+
+                // Note that we need special case for 0 param constructors because of multi cartesian
+                // product
+                let variant_exprs: Vec<Expr> = if param_exprs.is_empty() {
+                    vec![Expr::Variant { variant, generics, params: Vec::new() }]
+                } else {
+                    param_exprs
+                        .into_iter()
+                        .multi_cartesian_product()
+                        .map(|params| Expr::Variant { variant, generics: generics.clone(), params })
+                        .collect()
+                };
+                lookup.insert(enum_ty.clone(), variant_exprs.iter().cloned());
+
+                Some((enum_ty, variant_exprs))
+            })
+            .collect()
+    }
+    defs.iter()
+        .filter_map(move |def| match def {
+            ScopeDef::ModuleDef(ModuleDef::Variant(it)) => {
+                let variant_exprs =
+                    variant_helper(db, lookup, it.parent_enum(db), *it, &ctx.config);
+                if variant_exprs.is_empty() {
+                    return None;
+                }
+                if GenericDef::from(it.parent_enum(db))
+                    .type_or_const_params(db)
+                    .into_iter()
+                    .filter_map(|it| it.as_type_param(db))
+                    .all(|it| it.default(db).is_some())
+                {
+                    lookup.mark_fulfilled(ScopeDef::ModuleDef(ModuleDef::Variant(*it)));
+                }
+                Some(variant_exprs)
+            }
+            ScopeDef::ModuleDef(ModuleDef::Adt(Adt::Enum(enum_))) => {
+                let exprs: Vec<(Type, Vec<Expr>)> = enum_
+                    .variants(db)
+                    .into_iter()
+                    .flat_map(|it| variant_helper(db, lookup, *enum_, it, &ctx.config))
+                    .collect();
+
+                if exprs.is_empty() {
+                    return None;
+                }
+
+                if GenericDef::from(*enum_)
+                    .type_or_const_params(db)
+                    .into_iter()
+                    .filter_map(|it| it.as_type_param(db))
+                    .all(|it| it.default(db).is_some())
+                {
+                    lookup.mark_fulfilled(ScopeDef::ModuleDef(ModuleDef::Adt(Adt::Enum(*enum_))));
+                }
+
+                Some(exprs)
+            }
+            ScopeDef::ModuleDef(ModuleDef::Adt(Adt::Struct(it))) => {
+                // Ignore unstable and not visible
+                if it.is_unstable(db) || !it.is_visible_from(db, module) {
+                    return None;
+                }
+
+                let generics = GenericDef::from(*it);
+
+                // Ignore const params for now
+                let type_params = generics
+                    .type_or_const_params(db)
+                    .into_iter()
+                    .map(|it| it.as_type_param(db))
+                    .collect::<Option<Vec<TypeParam>>>()?;
+
+                // We currently do not check lifetime bounds so ignore all types that have something to do
+                // with them
+                if !generics.lifetime_params(db).is_empty() {
+                    return None;
+                }
+
+                // Only account for stable type parameters for now, unstable params can be default
+                // tho, for example in `Box<T, #[unstable] A: Allocator>`
+                if type_params.iter().any(|it| it.is_unstable(db) && it.default(db).is_none()) {
+                    return None;
+                }
+
+                let non_default_type_params_len =
+                    type_params.iter().filter(|it| it.default(db).is_none()).count();
+
+                let struct_ty_shallow = Adt::from(*it).ty(db);
+                let generic_params = lookup
+                    .types_wishlist()
+                    .clone()
+                    .into_iter()
+                    .filter(|ty| ty.could_unify_with(db, &struct_ty_shallow))
+                    .map(|it| it.type_arguments().collect::<Vec<Type>>())
+                    .chain((non_default_type_params_len == 0).then_some(Vec::new()));
+
+                let exprs = generic_params
+                    .filter_map(|generics| {
+                        // Insert default type params
+                        let mut g = generics.into_iter();
+                        let generics: Vec<_> = type_params
+                            .iter()
+                            .map(|it| it.default(db).or_else(|| g.next()))
+                            .collect::<Option<_>>()?;
+
+                        let struct_ty = Adt::from(*it).ty_with_args(db, generics.iter().cloned());
+
+                        // Ignore types that have something to do with lifetimes
+                        if ctx.config.enable_borrowcheck && struct_ty.contains_reference(db) {
+                            return None;
+                        }
+                        let fields = it.fields(db);
+                        // Check if all fields are visible, otherwise we cannot fill them
+                        if fields.iter().any(|it| !it.is_visible_from(db, module)) {
+                            return None;
+                        }
+
+                        // Early exit if some param cannot be filled from lookup
+                        let param_exprs: Vec<Vec<Expr>> = fields
+                            .into_iter()
+                            .map(|field| lookup.find(db, &field.ty(db)))
+                            .collect::<Option<_>>()?;
+
+                        // Note that we need special case for 0 param constructors because of multi cartesian
+                        // product
+                        let struct_exprs: Vec<Expr> = if param_exprs.is_empty() {
+                            vec![Expr::Struct { strukt: *it, generics, params: Vec::new() }]
+                        } else {
+                            param_exprs
+                                .into_iter()
+                                .multi_cartesian_product()
+                                .map(|params| Expr::Struct {
+                                    strukt: *it,
+                                    generics: generics.clone(),
+                                    params,
+                                })
+                                .collect()
+                        };
+
+                        if non_default_type_params_len == 0 {
+                            // Fulfilled only if there are no generic parameters
+                            lookup.mark_fulfilled(ScopeDef::ModuleDef(ModuleDef::Adt(
+                                Adt::Struct(*it),
+                            )));
+                        }
+                        lookup.insert(struct_ty.clone(), struct_exprs.iter().cloned());
+
+                        Some((struct_ty, struct_exprs))
+                    })
+                    .collect();
+                Some(exprs)
+            }
+            _ => None,
+        })
+        .flatten()
+        .filter_map(|(ty, exprs)| ty.could_unify_with_deeply(db, &ctx.goal).then_some(exprs))
+        .flatten()
+}
+
+/// # Free function tactic
+///
+/// Attempts to call different functions in scope with parameters from lookup table.
+/// Functions that include generics are not used for performance reasons.
+///
+/// Updates lookup by new types reached and returns iterator that yields
+/// elements that unify with `goal`.
+///
+/// # Arguments
+/// * `ctx` - Context for the term search
+/// * `defs` - Set of items in scope at term search target location
+/// * `lookup` - Lookup table for types
+pub(super) fn free_function<'a, DB: HirDatabase>(
+    ctx: &'a TermSearchCtx<'a, DB>,
+    defs: &'a FxHashSet<ScopeDef>,
+    lookup: &'a mut LookupTable,
+) -> impl Iterator<Item = Expr> + 'a {
+    let db = ctx.sema.db;
+    let module = ctx.scope.module();
+    defs.iter()
+        .filter_map(move |def| match def {
+            ScopeDef::ModuleDef(ModuleDef::Function(it)) => {
+                let generics = GenericDef::from(*it);
+
+                // Ignore const params for now
+                let type_params = generics
+                    .type_or_const_params(db)
+                    .into_iter()
+                    .map(|it| it.as_type_param(db))
+                    .collect::<Option<Vec<TypeParam>>>()?;
+
+                // Ignore lifetimes as we do not check them
+                if !generics.lifetime_params(db).is_empty() {
+                    return None;
+                }
+
+                // Only account for stable type parameters for now, unstable params can be default
+                // tho, for example in `Box<T, #[unstable] A: Allocator>`
+                if type_params.iter().any(|it| it.is_unstable(db) && it.default(db).is_none()) {
+                    return None;
+                }
+
+                let non_default_type_params_len =
+                    type_params.iter().filter(|it| it.default(db).is_none()).count();
+
+                // Ignore bigger number of generics for now as they kill the performance
+                if non_default_type_params_len > 0 {
+                    return None;
+                }
+
+                let generic_params = lookup
+                    .iter_types()
+                    .collect::<Vec<_>>() // Force take ownership
+                    .into_iter()
+                    .permutations(non_default_type_params_len);
+
+                let exprs: Vec<_> = generic_params
+                    .filter_map(|generics| {
+                        // Insert default type params
+                        let mut g = generics.into_iter();
+                        let generics: Vec<_> = type_params
+                            .iter()
+                            .map(|it| match it.default(db) {
+                                Some(ty) => Some(ty),
+                                None => {
+                                    let generic = g.next().expect("Missing type param");
+                                    // Filter out generics that do not unify due to trait bounds
+                                    it.ty(db).could_unify_with(db, &generic).then_some(generic)
+                                }
+                            })
+                            .collect::<Option<_>>()?;
+
+                        let ret_ty = it.ret_type_with_args(db, generics.iter().cloned());
+                        // Filter out private and unsafe functions
+                        if !it.is_visible_from(db, module)
+                            || it.is_unsafe_to_call(db)
+                            || it.is_unstable(db)
+                            || ctx.config.enable_borrowcheck && ret_ty.contains_reference(db)
+                            || ret_ty.is_raw_ptr()
+                        {
+                            return None;
+                        }
+
+                        // Early exit if some param cannot be filled from lookup
+                        let param_exprs: Vec<Vec<Expr>> = it
+                            .params_without_self_with_args(db, generics.iter().cloned())
+                            .into_iter()
+                            .map(|field| {
+                                let ty = field.ty();
+                                match ty.is_mutable_reference() {
+                                    true => None,
+                                    false => lookup.find_autoref(db, ty),
+                                }
+                            })
+                            .collect::<Option<_>>()?;
+
+                        // Note that we need special case for 0 param constructors because of multi cartesian
+                        // product
+                        let fn_exprs: Vec<Expr> = if param_exprs.is_empty() {
+                            vec![Expr::Function { func: *it, generics, params: Vec::new() }]
+                        } else {
+                            param_exprs
+                                .into_iter()
+                                .multi_cartesian_product()
+                                .map(|params| Expr::Function {
+                                    func: *it,
+                                    generics: generics.clone(),
+
+                                    params,
+                                })
+                                .collect()
+                        };
+
+                        lookup.mark_fulfilled(ScopeDef::ModuleDef(ModuleDef::Function(*it)));
+                        lookup.insert(ret_ty.clone(), fn_exprs.iter().cloned());
+                        Some((ret_ty, fn_exprs))
+                    })
+                    .collect();
+                Some(exprs)
+            }
+            _ => None,
+        })
+        .flatten()
+        .filter_map(|(ty, exprs)| ty.could_unify_with_deeply(db, &ctx.goal).then_some(exprs))
+        .flatten()
+}
+
+/// # Impl method tactic
+///
+/// Attempts to call methods on types from lookup table.
+/// This includes both functions from direct impl blocks as well as functions from traits.
+/// Methods defined in impl blocks that are generic and methods that are themselves have
+/// generics are ignored for performance reasons.
+///
+/// Updates lookup by new types reached and returns iterator that yields
+/// elements that unify with `goal`.
+///
+/// # Arguments
+/// * `ctx` - Context for the term search
+/// * `defs` - Set of items in scope at term search target location
+/// * `lookup` - Lookup table for types
+pub(super) fn impl_method<'a, DB: HirDatabase>(
+    ctx: &'a TermSearchCtx<'a, DB>,
+    _defs: &'a FxHashSet<ScopeDef>,
+    lookup: &'a mut LookupTable,
+) -> impl Iterator<Item = Expr> + 'a {
+    let db = ctx.sema.db;
+    let module = ctx.scope.module();
+    lookup
+        .new_types(NewTypesKey::ImplMethod)
+        .into_iter()
+        .flat_map(|ty| {
+            Impl::all_for_type(db, ty.clone()).into_iter().map(move |imp| (ty.clone(), imp))
+        })
+        .flat_map(|(ty, imp)| imp.items(db).into_iter().map(move |item| (imp, ty.clone(), item)))
+        .filter_map(|(imp, ty, it)| match it {
+            AssocItem::Function(f) => Some((imp, ty, f)),
+            _ => None,
+        })
+        .filter_map(move |(imp, ty, it)| {
+            let fn_generics = GenericDef::from(it);
+            let imp_generics = GenericDef::from(imp);
+
+            // Ignore const params for now
+            let imp_type_params = imp_generics
+                .type_or_const_params(db)
+                .into_iter()
+                .map(|it| it.as_type_param(db))
+                .collect::<Option<Vec<TypeParam>>>()?;
+
+            // Ignore const params for now
+            let fn_type_params = fn_generics
+                .type_or_const_params(db)
+                .into_iter()
+                .map(|it| it.as_type_param(db))
+                .collect::<Option<Vec<TypeParam>>>()?;
+
+            // Ignore all functions that have something to do with lifetimes as we don't check them
+            if !fn_generics.lifetime_params(db).is_empty() {
+                return None;
+            }
+
+            // Ignore functions without self param
+            if !it.has_self_param(db) {
+                return None;
+            }
+
+            // Filter out private and unsafe functions
+            if !it.is_visible_from(db, module) || it.is_unsafe_to_call(db) || it.is_unstable(db) {
+                return None;
+            }
+
+            // Only account for stable type parameters for now, unstable params can be default
+            // tho, for example in `Box<T, #[unstable] A: Allocator>`
+            if imp_type_params.iter().any(|it| it.is_unstable(db) && it.default(db).is_none())
+                || fn_type_params.iter().any(|it| it.is_unstable(db) && it.default(db).is_none())
+            {
+                return None;
+            }
+
+            // Double check that we have fully known type
+            if ty.type_arguments().any(|it| it.contains_unknown()) {
+                return None;
+            }
+
+            let non_default_fn_type_params_len =
+                fn_type_params.iter().filter(|it| it.default(db).is_none()).count();
+
+            // Ignore functions with generics for now as they kill the performance
+            // Also checking bounds for generics is problematic
+            if non_default_fn_type_params_len > 0 {
+                return None;
+            }
+
+            let generic_params = lookup
+                .iter_types()
+                .collect::<Vec<_>>() // Force take ownership
+                .into_iter()
+                .permutations(non_default_fn_type_params_len);
+
+            let exprs: Vec<_> = generic_params
+                .filter_map(|generics| {
+                    // Insert default type params
+                    let mut g = generics.into_iter();
+                    let generics: Vec<_> = ty
+                        .type_arguments()
+                        .map(Some)
+                        .chain(fn_type_params.iter().map(|it| match it.default(db) {
+                            Some(ty) => Some(ty),
+                            None => {
+                                let generic = g.next().expect("Missing type param");
+                                // Filter out generics that do not unify due to trait bounds
+                                it.ty(db).could_unify_with(db, &generic).then_some(generic)
+                            }
+                        }))
+                        .collect::<Option<_>>()?;
+
+                    let ret_ty = it.ret_type_with_args(
+                        db,
+                        ty.type_arguments().chain(generics.iter().cloned()),
+                    );
+                    // Filter out functions that return references
+                    if ctx.config.enable_borrowcheck && ret_ty.contains_reference(db)
+                        || ret_ty.is_raw_ptr()
+                    {
+                        return None;
+                    }
+
+                    // Ignore functions that do not change the type
+                    if ty.could_unify_with_deeply(db, &ret_ty) {
+                        return None;
+                    }
+
+                    let self_ty = it
+                        .self_param(db)
+                        .expect("No self param")
+                        .ty_with_args(db, ty.type_arguments().chain(generics.iter().cloned()));
+
+                    // Ignore functions that have different self type
+                    if !self_ty.autoderef(db).any(|s_ty| ty == s_ty) {
+                        return None;
+                    }
+
+                    let target_type_exprs = lookup.find(db, &ty).expect("Type not in lookup");
+
+                    // Early exit if some param cannot be filled from lookup
+                    let param_exprs: Vec<Vec<Expr>> = it
+                        .params_without_self_with_args(
+                            db,
+                            ty.type_arguments().chain(generics.iter().cloned()),
+                        )
+                        .into_iter()
+                        .map(|field| lookup.find_autoref(db, field.ty()))
+                        .collect::<Option<_>>()?;
+
+                    let fn_exprs: Vec<Expr> = std::iter::once(target_type_exprs)
+                        .chain(param_exprs)
+                        .multi_cartesian_product()
+                        .map(|params| {
+                            let mut params = params.into_iter();
+                            let target = Box::new(params.next().unwrap());
+                            Expr::Method {
+                                func: it,
+                                generics: generics.clone(),
+                                target,
+                                params: params.collect(),
+                            }
+                        })
+                        .collect();
+
+                    lookup.insert(ret_ty.clone(), fn_exprs.iter().cloned());
+                    Some((ret_ty, fn_exprs))
+                })
+                .collect();
+            Some(exprs)
+        })
+        .flatten()
+        .filter_map(|(ty, exprs)| ty.could_unify_with_deeply(db, &ctx.goal).then_some(exprs))
+        .flatten()
+}
+
+/// # Struct projection tactic
+///
+/// Attempts different struct fields (`foo.bar.baz`)
+///
+/// Updates lookup by new types reached and returns iterator that yields
+/// elements that unify with `goal`.
+///
+/// # Arguments
+/// * `ctx` - Context for the term search
+/// * `defs` - Set of items in scope at term search target location
+/// * `lookup` - Lookup table for types
+pub(super) fn struct_projection<'a, DB: HirDatabase>(
+    ctx: &'a TermSearchCtx<'a, DB>,
+    _defs: &'a FxHashSet<ScopeDef>,
+    lookup: &'a mut LookupTable,
+) -> impl Iterator<Item = Expr> + 'a {
+    let db = ctx.sema.db;
+    let module = ctx.scope.module();
+    lookup
+        .new_types(NewTypesKey::StructProjection)
+        .into_iter()
+        .map(|ty| (ty.clone(), lookup.find(db, &ty).expect("Expr not in lookup")))
+        .flat_map(move |(ty, targets)| {
+            ty.fields(db).into_iter().filter_map(move |(field, filed_ty)| {
+                if !field.is_visible_from(db, module) {
+                    return None;
+                }
+                let exprs = targets
+                    .clone()
+                    .into_iter()
+                    .map(move |target| Expr::Field { field, expr: Box::new(target) });
+                Some((filed_ty, exprs))
+            })
+        })
+        .filter_map(|(ty, exprs)| ty.could_unify_with_deeply(db, &ctx.goal).then_some(exprs))
+        .flatten()
+}
+
+/// # Famous types tactic
+///
+/// Attempts different values of well known types such as `true` or `false`.
+///
+/// Updates lookup by new types reached and returns iterator that yields
+/// elements that unify with `goal`.
+///
+/// _Note that there is no point of calling it iteratively as the output is always the same_
+///
+/// # Arguments
+/// * `ctx` - Context for the term search
+/// * `defs` - Set of items in scope at term search target location
+/// * `lookup` - Lookup table for types
+pub(super) fn famous_types<'a, DB: HirDatabase>(
+    ctx: &'a TermSearchCtx<'a, DB>,
+    _defs: &'a FxHashSet<ScopeDef>,
+    lookup: &'a mut LookupTable,
+) -> impl Iterator<Item = Expr> + 'a {
+    let db = ctx.sema.db;
+    let module = ctx.scope.module();
+    [
+        Expr::FamousType { ty: Type::new(db, module.id, TyBuilder::bool()), value: "true" },
+        Expr::FamousType { ty: Type::new(db, module.id, TyBuilder::bool()), value: "false" },
+        Expr::FamousType { ty: Type::new(db, module.id, TyBuilder::unit()), value: "()" },
+    ]
+    .into_iter()
+    .map(|exprs| {
+        lookup.insert(exprs.ty(db), std::iter::once(exprs.clone()));
+        exprs
+    })
+    .filter(|expr| expr.ty(db).could_unify_with_deeply(db, &ctx.goal))
+}
+
+/// # Impl static method (without self type) tactic
+///
+/// Attempts different functions from impl blocks that take no self parameter.
+///
+/// Updates lookup by new types reached and returns iterator that yields
+/// elements that unify with `goal`.
+///
+/// # Arguments
+/// * `ctx` - Context for the term search
+/// * `defs` - Set of items in scope at term search target location
+/// * `lookup` - Lookup table for types
+pub(super) fn impl_static_method<'a, DB: HirDatabase>(
+    ctx: &'a TermSearchCtx<'a, DB>,
+    _defs: &'a FxHashSet<ScopeDef>,
+    lookup: &'a mut LookupTable,
+) -> impl Iterator<Item = Expr> + 'a {
+    let db = ctx.sema.db;
+    let module = ctx.scope.module();
+    lookup
+        .types_wishlist()
+        .clone()
+        .into_iter()
+        .chain(iter::once(ctx.goal.clone()))
+        .flat_map(|ty| {
+            Impl::all_for_type(db, ty.clone()).into_iter().map(move |imp| (ty.clone(), imp))
+        })
+        .filter(|(_, imp)| !imp.is_unsafe(db))
+        .flat_map(|(ty, imp)| imp.items(db).into_iter().map(move |item| (imp, ty.clone(), item)))
+        .filter_map(|(imp, ty, it)| match it {
+            AssocItem::Function(f) => Some((imp, ty, f)),
+            _ => None,
+        })
+        .filter_map(move |(imp, ty, it)| {
+            let fn_generics = GenericDef::from(it);
+            let imp_generics = GenericDef::from(imp);
+
+            // Ignore const params for now
+            let imp_type_params = imp_generics
+                .type_or_const_params(db)
+                .into_iter()
+                .map(|it| it.as_type_param(db))
+                .collect::<Option<Vec<TypeParam>>>()?;
+
+            // Ignore const params for now
+            let fn_type_params = fn_generics
+                .type_or_const_params(db)
+                .into_iter()
+                .map(|it| it.as_type_param(db))
+                .collect::<Option<Vec<TypeParam>>>()?;
+
+            // Ignore all functions that have something to do with lifetimes as we don't check them
+            if !fn_generics.lifetime_params(db).is_empty()
+                || !imp_generics.lifetime_params(db).is_empty()
+            {
+                return None;
+            }
+
+            // Ignore functions with self param
+            if it.has_self_param(db) {
+                return None;
+            }
+
+            // Filter out private and unsafe functions
+            if !it.is_visible_from(db, module) || it.is_unsafe_to_call(db) || it.is_unstable(db) {
+                return None;
+            }
+
+            // Only account for stable type parameters for now, unstable params can be default
+            // tho, for example in `Box<T, #[unstable] A: Allocator>`
+            if imp_type_params.iter().any(|it| it.is_unstable(db) && it.default(db).is_none())
+                || fn_type_params.iter().any(|it| it.is_unstable(db) && it.default(db).is_none())
+            {
+                return None;
+            }
+
+            // Double check that we have fully known type
+            if ty.type_arguments().any(|it| it.contains_unknown()) {
+                return None;
+            }
+
+            let non_default_fn_type_params_len =
+                fn_type_params.iter().filter(|it| it.default(db).is_none()).count();
+
+            // Ignore functions with generics for now as they kill the performance
+            // Also checking bounds for generics is problematic
+            if non_default_fn_type_params_len > 0 {
+                return None;
+            }
+
+            let generic_params = lookup
+                .iter_types()
+                .collect::<Vec<_>>() // Force take ownership
+                .into_iter()
+                .permutations(non_default_fn_type_params_len);
+
+            let exprs: Vec<_> = generic_params
+                .filter_map(|generics| {
+                    // Insert default type params
+                    let mut g = generics.into_iter();
+                    let generics: Vec<_> = ty
+                        .type_arguments()
+                        .map(Some)
+                        .chain(fn_type_params.iter().map(|it| match it.default(db) {
+                            Some(ty) => Some(ty),
+                            None => {
+                                let generic = g.next().expect("Missing type param");
+                                it.trait_bounds(db)
+                                    .into_iter()
+                                    .all(|bound| generic.impls_trait(db, bound, &[]));
+                                // Filter out generics that do not unify due to trait bounds
+                                it.ty(db).could_unify_with(db, &generic).then_some(generic)
+                            }
+                        }))
+                        .collect::<Option<_>>()?;
+
+                    let ret_ty = it.ret_type_with_args(
+                        db,
+                        ty.type_arguments().chain(generics.iter().cloned()),
+                    );
+                    // Filter out functions that return references
+                    if ctx.config.enable_borrowcheck && ret_ty.contains_reference(db)
+                        || ret_ty.is_raw_ptr()
+                    {
+                        return None;
+                    }
+
+                    // Ignore functions that do not change the type
+                    // if ty.could_unify_with_deeply(db, &ret_ty) {
+                    //     return None;
+                    // }
+
+                    // Early exit if some param cannot be filled from lookup
+                    let param_exprs: Vec<Vec<Expr>> = it
+                        .params_without_self_with_args(
+                            db,
+                            ty.type_arguments().chain(generics.iter().cloned()),
+                        )
+                        .into_iter()
+                        .map(|field| lookup.find_autoref(db, field.ty()))
+                        .collect::<Option<_>>()?;
+
+                    // Note that we need special case for 0 param constructors because of multi cartesian
+                    // product
+                    let fn_exprs: Vec<Expr> = if param_exprs.is_empty() {
+                        vec![Expr::Function { func: it, generics, params: Vec::new() }]
+                    } else {
+                        param_exprs
+                            .into_iter()
+                            .multi_cartesian_product()
+                            .map(|params| Expr::Function {
+                                func: it,
+                                generics: generics.clone(),
+                                params,
+                            })
+                            .collect()
+                    };
+
+                    lookup.insert(ret_ty.clone(), fn_exprs.iter().cloned());
+                    Some((ret_ty, fn_exprs))
+                })
+                .collect();
+            Some(exprs)
+        })
+        .flatten()
+        .filter_map(|(ty, exprs)| ty.could_unify_with_deeply(db, &ctx.goal).then_some(exprs))
+        .flatten()
+}
+
+/// # Make tuple tactic
+///
+/// Attempts to create tuple types if any are listed in types wishlist
+///
+/// Updates lookup by new types reached and returns iterator that yields
+/// elements that unify with `goal`.
+///
+/// # Arguments
+/// * `ctx` - Context for the term search
+/// * `defs` - Set of items in scope at term search target location
+/// * `lookup` - Lookup table for types
+pub(super) fn make_tuple<'a, DB: HirDatabase>(
+    ctx: &'a TermSearchCtx<'a, DB>,
+    _defs: &'a FxHashSet<ScopeDef>,
+    lookup: &'a mut LookupTable,
+) -> impl Iterator<Item = Expr> + 'a {
+    let db = ctx.sema.db;
+    let module = ctx.scope.module();
+
+    lookup
+        .types_wishlist()
+        .clone()
+        .into_iter()
+        .filter(|ty| ty.is_tuple())
+        .filter_map(move |ty| {
+            // Double check to not contain unknown
+            if ty.contains_unknown() {
+                return None;
+            }
+
+            // Ignore types that have something to do with lifetimes
+            if ctx.config.enable_borrowcheck && ty.contains_reference(db) {
+                return None;
+            }
+
+            // Early exit if some param cannot be filled from lookup
+            let param_exprs: Vec<Vec<Expr>> =
+                ty.type_arguments().map(|field| lookup.find(db, &field)).collect::<Option<_>>()?;
+
+            let exprs: Vec<Expr> = param_exprs
+                .into_iter()
+                .multi_cartesian_product()
+                .map(|params| {
+                    let tys: Vec<Type> = params.iter().map(|it| it.ty(db)).collect();
+                    let tuple_ty = Type::new_tuple(module.krate().into(), &tys);
+
+                    let expr = Expr::Tuple { ty: tuple_ty.clone(), params };
+                    lookup.insert(tuple_ty, iter::once(expr.clone()));
+                    expr
+                })
+                .collect();
+
+            Some(exprs)
+        })
+        .flatten()
+        .filter_map(|expr| expr.ty(db).could_unify_with_deeply(db, &ctx.goal).then_some(expr))
+}