Skip to main content

hir/
lib.rs

1//! HIR (previously known as descriptors) provides a high-level object-oriented
2//! access to Rust code.
3//!
4//! The principal difference between HIR and syntax trees is that HIR is bound
5//! to a particular crate instance. That is, it has cfg flags and features
6//! applied. So, the relation between syntax and HIR is many-to-one.
7//!
8//! HIR is the public API of the all of the compiler logic above syntax trees.
9//! It is written in "OO" style. Each type is self contained (as in, it knows its
10//! parents and full context). It should be "clean code".
11//!
12//! `hir_*` crates are the implementation of the compiler logic.
13//! They are written in "ECS" style, with relatively little abstractions.
14//! Many types are not self-contained, and explicitly use local indexes, arenas, etc.
15//!
16//! `hir` is what insulates the "we don't know how to actually write an incremental compiler"
17//! from the ide with completions, hovers, etc. It is a (soft, internal) boundary:
18//! <https://www.tedinski.com/2018/02/06/system-boundaries.html>.
19
20#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
21#![recursion_limit = "512"]
22
23extern crate ra_ap_rustc_type_ir as rustc_type_ir;
24
25mod attrs;
26mod from_id;
27mod has_source;
28mod semantics;
29mod source_analyzer;
30
31pub mod db;
32pub mod diagnostics;
33pub mod symbols;
34pub mod term_search;
35
36mod display;
37
38#[doc(hidden)]
39pub use hir_def::ModuleId;
40
41use std::{borrow::Borrow, fmt, iter, ops::ControlFlow};
42
43use arrayvec::ArrayVec;
44use base_db::{
45    CrateDisplayName, CrateOrigin, LangCrateOrigin, SourceDatabase, TargetKind, all_crates,
46};
47use either::Either;
48use hir_def::{
49    AdtId, AssocItemId, AssocItemLoc, BuiltinDeriveImplId, CallableDefId, ConstId, ConstParamId,
50    DefWithBodyId, EnumId, EnumVariantId, ExpressionStoreOwnerId, ExternBlockId, ExternCrateId,
51    FunctionId, GenericDefId, HasModule, ImplId, ItemContainerId, LifetimeParamId, LocalFieldId,
52    Lookup, MacroExpander, MacroId, StaticId, StructId, TupleId, TypeAliasId, TypeOrConstParamId,
53    TypeParamId, UnionId,
54    attrs::AttrFlags,
55    builtin_derive::BuiltinDeriveImplMethod,
56    expr_store::ExpressionStore,
57    hir::{
58        BindingAnnotation, BindingId, Expr, ExprId, ExprOrPatId, LabelId, Pat,
59        generics::{GenericParams, LifetimeParamData, TypeOrConstParamData, TypeParamProvenance},
60    },
61    item_tree::ImportAlias,
62    lang_item::LangItemTarget,
63    layout::{self, ReprOptions, TargetDataLayout},
64    per_ns::PerNs,
65    resolver::{HasResolver, Resolver},
66    signatures::{
67        ConstSignature, EnumSignature, FunctionSignature, ImplFlags, ImplSignature, StaticFlags,
68        StaticSignature, StructFlags, StructSignature, TraitFlags, TraitSignature,
69        TypeAliasSignature, UnionSignature, VariantFields,
70    },
71    src::HasSource as _,
72    unstable_features::UnstableFeatures,
73    visibility::visibility_from_ast,
74};
75use hir_expand::{builtin::BuiltinDeriveExpander, proc_macro::ProcMacroKind};
76use hir_ide::{
77    GenericPredicates, InferBodyId, InferenceResult, ParamEnvAndCrate, TyDefId, ValueTyDefId,
78    all_super_traits, autoderef, check_orphan_rules,
79    consteval::try_const_usize,
80    db::{
81        AnonConstId, InternedClosure, InternedClosureId, InternedCoroutineClosureId,
82        InternedCoroutineId,
83    },
84    direct_super_traits, known_const_to_ast,
85    layout::{Layout as TyLayout, RustcEnumVariantIdx, RustcFieldIdx, TagEncoding},
86    method_resolution::{self, InherentImpls, MethodResolutionContext},
87    mir::interpret_mir,
88    mir_pretty::{MirBodyPretty as _, MirEvalErrorPretty as _},
89    next_solver::{
90        AliasTy, AnyImplId, ClauseKind, DbInterner, EarlyBinder, ErrorGuaranteed, FnSig,
91        GenericArg, GenericArgs, ParamEnv, PolyFnSig, Region, SolverDefId, Ty, TyKind, TypingMode,
92        infer::{DbInternerInferExt, InferCtxt},
93    },
94    traits::{self, structurally_normalize_ty},
95};
96use itertools::Itertools;
97use rustc_hash::{FxHashMap, FxHashSet};
98use rustc_type_ir::{
99    AliasTyKind, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, fast_reject,
100    inherent::{AdtDef as _, GenericArgs as _, IntoKind, SliceLike, Term as _, Ty as _},
101};
102use span::{AstIdNode, Edition, FileId};
103use stdx::{format_to, impl_from, never};
104use syntax::{
105    AstNode, AstPtr, SmolStr, SyntaxNode, SyntaxNodePtr, TextRange, ToSmolStr,
106    ast::{self, HasName as _, HasVisibility as _},
107    format_smolstr,
108};
109use triomphe::{Arc, ThinArc};
110
111use crate::db::HirDatabase;
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum PredicateEvaluationStatus {
115    Holds,
116    NotProven,
117    Invalid,
118    Unsupported,
119}
120
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub struct PredicateEvaluationResult {
123    pub status: PredicateEvaluationStatus,
124    pub message: String,
125}
126
127impl PredicateEvaluationResult {
128    pub fn holds(message: impl Into<String>) -> Self {
129        Self { status: PredicateEvaluationStatus::Holds, message: message.into() }
130    }
131
132    pub fn not_proven(message: impl Into<String>) -> Self {
133        Self { status: PredicateEvaluationStatus::NotProven, message: message.into() }
134    }
135
136    pub fn invalid(message: impl Into<String>) -> Self {
137        Self { status: PredicateEvaluationStatus::Invalid, message: message.into() }
138    }
139
140    pub fn unsupported(message: impl Into<String>) -> Self {
141        Self { status: PredicateEvaluationStatus::Unsupported, message: message.into() }
142    }
143}
144
145pub use crate::{
146    attrs::{AttrsWithOwner, HasAttrs, resolve_doc_path_on},
147    diagnostics::*,
148    has_source::HasSource,
149    semantics::{
150        LintAttr, PathResolution, PathResolutionPerNs, Semantics, SemanticsImpl, SemanticsScope,
151        TypeInfo, VisibleTraits,
152    },
153};
154
155// Be careful with these re-exports.
156//
157// `hir` is the boundary between the compiler and the IDE. It should try hard to
158// isolate the compiler from the ide, to allow the two to be refactored
159// independently. Re-exporting something from the compiler is the sure way to
160// breach the boundary.
161//
162// Generally, a refactoring which *removes* a name from this list is a good
163// idea!
164pub use {
165    cfg::{CfgAtom, CfgExpr, CfgOptions},
166    hir_def::{
167        Complete,
168        FindPathConfig,
169        attrs::{Docs, IsInnerDoc},
170        expr_store::Body,
171        find_path::PrefixKind,
172        import_map,
173        lang_item::{LangItemEnum as LangItem, crate_lang_items},
174        nameres::{DefMap, ModuleSource, crate_def_map},
175        per_ns::Namespace,
176        type_ref::{Mutability, TypeRef},
177        visibility::Visibility,
178        // FIXME: This is here since some queries take it as input that are used
179        // outside of hir.
180        {GenericParamId, ModuleDefId, TraitId},
181    },
182    hir_expand::{
183        EditionedFileId, ExpandResult, HirFileId, MacroCallId, MacroKind,
184        change::ChangeWithProcMacros,
185        files::{
186            FilePosition, FilePositionWrapper, FileRange, FileRangeWrapper, HirFilePosition,
187            HirFileRange, InFile, InFileWrapper, InMacroFile, InRealFile, MacroFilePosition,
188            MacroFileRange,
189        },
190        inert_attr_macro::AttributeTemplate,
191        mod_path::{ModPath, PathKind, tool_path},
192        name::{self, Name},
193        prettify_macro_expansion,
194        proc_macro::{ProcMacros, ProcMacrosBuilder},
195        tt,
196    },
197    // FIXME: Properly encapsulate mir
198    hir_ide::mir,
199    hir_ide::{
200        CastError, PointerCast, attach_db, attach_db_allow_change,
201        consteval::ConstEvalError,
202        diagnostics::UnsafetyReason,
203        display::{ClosureStyle, DisplayTarget, HirDisplay, HirDisplayError, HirWrite},
204        drop::DropGlue,
205        dyn_compatibility::{AssocConstViolation, MethodViolation},
206        impl_hir_database,
207        layout::LayoutError,
208        mir::{MirEvalError, MirLowerError},
209        mir_pretty::ConstEvalErrorPretty,
210        next_solver::abi::Safety,
211        next_solver::{clear_tls_solver_cache, collect_ty_garbage},
212        setup_tracing,
213    },
214    // FIXME: These are needed for import assets, properly encapsulate them.
215    hir_ide::{method_resolution::TraitImpls, next_solver::SimplifiedType},
216    intern::{Symbol, sym},
217};
218
219// These are negative re-exports: pub using these names is forbidden, they
220// should remain private to hir internals.
221#[allow(unused)]
222use {
223    hir_def::expr_store::path::Path,
224    hir_expand::{
225        name::AsName,
226        span_map::{ExpansionSpanMap, RealSpanMap, SpanMap},
227    },
228    hir_ide::next_solver,
229};
230
231/// hir::Crate describes a single crate. It's the main interface with which
232/// a crate's dependencies interact. Mostly, it should be just a proxy for the
233/// root module.
234#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
235pub struct Crate {
236    pub(crate) id: base_db::Crate,
237}
238
239#[derive(Debug)]
240pub struct CrateDependency {
241    pub krate: Crate,
242    pub name: Name,
243}
244
245impl Crate {
246    pub fn base(self) -> base_db::Crate {
247        self.id
248    }
249
250    pub fn origin(self, db: &dyn HirDatabase) -> CrateOrigin {
251        self.id.data(db).origin.clone()
252    }
253
254    pub fn is_builtin(self, db: &dyn HirDatabase) -> bool {
255        matches!(self.origin(db), CrateOrigin::Lang(_))
256    }
257
258    pub fn dependencies(self, db: &dyn HirDatabase) -> Vec<CrateDependency> {
259        self.id
260            .data(db)
261            .dependencies
262            .iter()
263            .map(|dep| {
264                let krate = Crate { id: dep.crate_id };
265                let name = dep.as_name();
266                CrateDependency { krate, name }
267            })
268            .collect()
269    }
270
271    pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
272        let all_crates = all_crates(db);
273        all_crates
274            .iter()
275            .copied()
276            .filter(|&krate| krate.data(db).dependencies.iter().any(|it| it.crate_id == self.id))
277            .map(|id| Crate { id })
278            .collect()
279    }
280
281    pub fn transitive_reverse_dependencies(
282        self,
283        db: &dyn HirDatabase,
284    ) -> impl Iterator<Item = Crate> {
285        self.id.transitive_rev_deps(db).into_iter().map(|id| Crate { id })
286    }
287
288    pub fn notable_traits_in_deps(self, db: &dyn HirDatabase) -> impl Iterator<Item = &TraitId> {
289        self.id
290            .transitive_deps(db)
291            .into_iter()
292            .filter_map(|krate| hir_def::crate_notable_traits(db, krate))
293            .flatten()
294    }
295
296    pub fn root_module(self, db: &dyn HirDatabase) -> Module {
297        Module { id: crate_def_map(db, self.id).root_module_id() }
298    }
299
300    pub fn modules(self, db: &dyn HirDatabase) -> Vec<Module> {
301        let def_map = crate_def_map(db, self.id);
302        def_map.modules().map(|(id, _)| id.into()).collect()
303    }
304
305    pub fn root_file(self, db: &dyn HirDatabase) -> FileId {
306        self.id.data(db).root_file_id
307    }
308
309    pub fn edition(self, db: &dyn HirDatabase) -> Edition {
310        self.id.data(db).edition
311    }
312
313    pub fn version(self, db: &dyn HirDatabase) -> Option<String> {
314        self.id.extra_data(db).version.clone()
315    }
316
317    pub fn display_name(self, db: &dyn HirDatabase) -> Option<CrateDisplayName> {
318        self.id.extra_data(db).display_name.clone()
319    }
320
321    pub fn target_kind(self, db: &dyn HirDatabase) -> TargetKind {
322        self.id.data(db).target_kind
323    }
324
325    pub fn query_external_importables(
326        self,
327        db: &dyn SourceDatabase,
328        query: import_map::Query,
329    ) -> impl Iterator<Item = (Either<ModuleDef, Macro>, Complete)> {
330        let _p = tracing::info_span!("query_external_importables").entered();
331        import_map::search_dependencies(db, self.into(), &query).into_iter().map(
332            |(item, do_not_complete)| {
333                let item = match ItemInNs::from(item) {
334                    ItemInNs::Types(mod_id) | ItemInNs::Values(mod_id) => Either::Left(mod_id),
335                    ItemInNs::Macros(mac_id) => Either::Right(mac_id),
336                };
337                (item, do_not_complete)
338            },
339        )
340    }
341
342    pub fn all(db: &dyn HirDatabase) -> Vec<Crate> {
343        all_crates(db).iter().map(|&id| Crate { id }).collect()
344    }
345
346    /// Try to get the root URL of the documentation of a crate.
347    pub fn get_html_root_url(self, db: &dyn HirDatabase) -> Option<String> {
348        // Look for #![doc(html_root_url = "...")]
349        let doc_url = AttrFlags::doc_html_root_url(db, self.id);
350        doc_url.as_ref().map(|s| s.trim_matches('"').trim_end_matches('/').to_owned() + "/")
351    }
352
353    pub fn cfg<'db>(&self, db: &'db dyn HirDatabase) -> &'db CfgOptions {
354        self.id.cfg_options(db)
355    }
356
357    pub fn potential_cfg<'db>(&self, db: &'db dyn HirDatabase) -> &'db CfgOptions {
358        let data = self.id.extra_data(db);
359        data.potential_cfg_options.as_ref().unwrap_or_else(|| self.id.cfg_options(db))
360    }
361
362    pub fn to_display_target(self, db: &dyn HirDatabase) -> DisplayTarget {
363        DisplayTarget::from_crate(db, self.id)
364    }
365
366    fn core(db: &dyn HirDatabase) -> Option<Crate> {
367        all_crates(db)
368            .iter()
369            .copied()
370            .find(|&krate| {
371                matches!(krate.data(db).origin, CrateOrigin::Lang(LangCrateOrigin::Core))
372            })
373            .map(Crate::from)
374    }
375
376    pub fn is_unstable_feature_enabled(self, db: &dyn HirDatabase, feature: &Symbol) -> bool {
377        UnstableFeatures::query(db, self.id).is_enabled(feature)
378    }
379}
380
381#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
382pub struct Module {
383    pub(crate) id: ModuleId,
384}
385
386/// The defs which can be visible in the module.
387#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
388pub enum ModuleDef {
389    Module(Module),
390    Function(Function),
391    Adt(Adt),
392    // Can't be directly declared, but can be imported.
393    EnumVariant(EnumVariant),
394    Const(Const),
395    Static(Static),
396    Trait(Trait),
397    TypeAlias(TypeAlias),
398    BuiltinType(BuiltinType),
399    Macro(Macro),
400}
401impl_from!(
402    Module,
403    Function,
404    Adt(Struct, Enum, Union),
405    EnumVariant,
406    Const,
407    Static,
408    Trait,
409    TypeAlias,
410    BuiltinType,
411    Macro
412    for ModuleDef
413);
414
415impl_from!(
416    Variant { Struct => Adt, Union => Adt, EnumVariant => EnumVariant }
417    for ModuleDef
418);
419
420impl ModuleDef {
421    pub fn module(self, db: &dyn HirDatabase) -> Option<Module> {
422        match self {
423            ModuleDef::Module(it) => it.parent(db),
424            ModuleDef::Function(it) => Some(it.module(db)),
425            ModuleDef::Adt(it) => Some(it.module(db)),
426            ModuleDef::EnumVariant(it) => Some(it.module(db)),
427            ModuleDef::Const(it) => Some(it.module(db)),
428            ModuleDef::Static(it) => Some(it.module(db)),
429            ModuleDef::Trait(it) => Some(it.module(db)),
430            ModuleDef::TypeAlias(it) => Some(it.module(db)),
431            ModuleDef::Macro(it) => Some(it.module(db)),
432            ModuleDef::BuiltinType(_) => None,
433        }
434    }
435
436    pub fn canonical_path(&self, db: &dyn HirDatabase, edition: Edition) -> Option<String> {
437        let name = self.name(db)?;
438        let segments = self.module(db)?.path_segments(db).chain(Some(name));
439        Some(segments.map(|it| it.display(db, edition).to_string()).join("::"))
440    }
441
442    pub fn canonical_module_path(
443        &self,
444        db: &dyn HirDatabase,
445    ) -> Option<impl Iterator<Item = Module>> {
446        self.module(db).map(|it| it.path_to_root(db).into_iter().rev())
447    }
448
449    pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
450        let name = match self {
451            ModuleDef::Module(it) => it.name(db)?,
452            ModuleDef::Const(it) => it.name(db)?,
453            ModuleDef::Adt(it) => it.name(db),
454            ModuleDef::Trait(it) => it.name(db),
455            ModuleDef::Function(it) => it.name(db),
456            ModuleDef::EnumVariant(it) => it.name(db),
457            ModuleDef::TypeAlias(it) => it.name(db),
458            ModuleDef::Static(it) => it.name(db),
459            ModuleDef::Macro(it) => it.name(db),
460            ModuleDef::BuiltinType(it) => it.name(),
461        };
462        Some(name)
463    }
464
465    pub fn as_def_with_body(self) -> Option<DefWithBody> {
466        match self {
467            ModuleDef::Function(it) => Some(it.into()),
468            ModuleDef::Const(it) => Some(it.into()),
469            ModuleDef::Static(it) => Some(it.into()),
470            ModuleDef::EnumVariant(it) => Some(it.into()),
471
472            ModuleDef::Module(_)
473            | ModuleDef::Adt(_)
474            | ModuleDef::Trait(_)
475            | ModuleDef::TypeAlias(_)
476            | ModuleDef::Macro(_)
477            | ModuleDef::BuiltinType(_) => None,
478        }
479    }
480
481    /// Returns only defs that have generics from themselves, not their parent.
482    pub fn as_self_generic_def(self) -> Option<GenericDef> {
483        match self {
484            ModuleDef::Function(it) => Some(it.into()),
485            ModuleDef::Adt(it) => Some(it.into()),
486            ModuleDef::Trait(it) => Some(it.into()),
487            ModuleDef::TypeAlias(it) => Some(it.into()),
488            ModuleDef::Module(_)
489            | ModuleDef::EnumVariant(_)
490            | ModuleDef::Static(_)
491            | ModuleDef::Const(_)
492            | ModuleDef::BuiltinType(_)
493            | ModuleDef::Macro(_) => None,
494        }
495    }
496
497    pub fn as_generic_def(self) -> Option<GenericDef> {
498        match self {
499            ModuleDef::Function(it) => Some(it.into()),
500            ModuleDef::Adt(it) => Some(it.into()),
501            ModuleDef::Trait(it) => Some(it.into()),
502            ModuleDef::TypeAlias(it) => Some(it.into()),
503            ModuleDef::Static(it) => Some(it.into()),
504            ModuleDef::Const(it) => Some(it.into()),
505            ModuleDef::EnumVariant(_)
506            | ModuleDef::Module(_)
507            | ModuleDef::BuiltinType(_)
508            | ModuleDef::Macro(_) => None,
509        }
510    }
511
512    pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
513        Some(match self {
514            ModuleDef::Module(it) => it.attrs(db),
515            ModuleDef::Function(it) => HasAttrs::attrs(*it, db),
516            ModuleDef::Adt(it) => it.attrs(db),
517            ModuleDef::EnumVariant(it) => it.attrs(db),
518            ModuleDef::Const(it) => it.attrs(db),
519            ModuleDef::Static(it) => it.attrs(db),
520            ModuleDef::Trait(it) => it.attrs(db),
521            ModuleDef::TypeAlias(it) => it.attrs(db),
522            ModuleDef::Macro(it) => it.attrs(db),
523            ModuleDef::BuiltinType(_) => return None,
524        })
525    }
526}
527
528impl HasCrate for ModuleDef {
529    fn krate(&self, db: &dyn HirDatabase) -> Crate {
530        match self.module(db) {
531            Some(module) => module.krate(db),
532            None => Crate::core(db).unwrap_or_else(|| all_crates(db)[0].into()),
533        }
534    }
535}
536
537impl HasAttrs for ModuleDef {
538    fn attr_id(self, db: &dyn HirDatabase) -> attrs::AttrsOwner {
539        match self {
540            ModuleDef::Module(it) => it.attr_id(db),
541            ModuleDef::Function(it) => it.attr_id(db),
542            ModuleDef::Adt(it) => it.attr_id(db),
543            ModuleDef::EnumVariant(it) => it.attr_id(db),
544            ModuleDef::Const(it) => it.attr_id(db),
545            ModuleDef::Static(it) => it.attr_id(db),
546            ModuleDef::Trait(it) => it.attr_id(db),
547            ModuleDef::TypeAlias(it) => it.attr_id(db),
548            ModuleDef::Macro(it) => it.attr_id(db),
549            ModuleDef::BuiltinType(_) => attrs::AttrsOwner::Dummy,
550        }
551    }
552}
553
554impl HasVisibility for ModuleDef {
555    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
556        match *self {
557            ModuleDef::Module(it) => it.visibility(db),
558            ModuleDef::Function(it) => it.visibility(db),
559            ModuleDef::Adt(it) => it.visibility(db),
560            ModuleDef::Const(it) => it.visibility(db),
561            ModuleDef::Static(it) => it.visibility(db),
562            ModuleDef::Trait(it) => it.visibility(db),
563            ModuleDef::TypeAlias(it) => it.visibility(db),
564            ModuleDef::EnumVariant(it) => it.visibility(db),
565            ModuleDef::Macro(it) => it.visibility(db),
566            ModuleDef::BuiltinType(_) => Visibility::Public,
567        }
568    }
569}
570
571impl Module {
572    /// Name of this module.
573    pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
574        self.id.name(db)
575    }
576
577    /// Returns the crate this module is part of.
578    pub fn krate(self, db: &dyn HirDatabase) -> Crate {
579        Crate { id: self.id.krate(db) }
580    }
581
582    /// Topmost parent of this module. Every module has a `crate_root`, but some
583    /// might be missing `krate`. This can happen if a module's file is not included
584    /// in the module tree of any target in `Cargo.toml`.
585    pub fn crate_root(self, db: &dyn HirDatabase) -> Module {
586        let def_map = crate_def_map(db, self.id.krate(db));
587        Module { id: def_map.crate_root(db) }
588    }
589
590    pub fn is_crate_root(self, db: &dyn HirDatabase) -> bool {
591        self.crate_root(db) == self
592    }
593
594    /// Iterates over all child modules.
595    pub fn children(self, db: &dyn HirDatabase) -> impl Iterator<Item = Module> {
596        let def_map = self.id.def_map(db);
597        let children = def_map[self.id]
598            .children
599            .values()
600            .map(|module_id| Module { id: *module_id })
601            .collect::<Vec<_>>();
602        children.into_iter()
603    }
604
605    /// Finds a parent module.
606    pub fn parent(self, db: &dyn HirDatabase) -> Option<Module> {
607        let def_map = self.id.def_map(db);
608        let parent_id = def_map.containing_module(self.id)?;
609        Some(Module { id: parent_id })
610    }
611
612    /// Finds nearest non-block ancestor `Module` (`self` included).
613    pub fn nearest_non_block_module(self, db: &dyn HirDatabase) -> Module {
614        let mut id = self.id;
615        while id.is_block_module(db) {
616            id = id.containing_module(db).expect("block without parent module");
617        }
618        Module { id: unsafe { id.to_static() } }
619    }
620
621    pub fn path_to_root(self, db: &dyn HirDatabase) -> Vec<Module> {
622        let mut res = vec![self];
623        let mut curr = self;
624        while let Some(next) = curr.parent(db) {
625            res.push(next);
626            curr = next
627        }
628        res
629    }
630
631    /// Names of the modules enclosing `self`, crate root first, `self` last.
632    ///
633    /// Nameless modules — the crate root, and block modules — drop out, so this is
634    /// generally shorter than [`Module::path_to_root`]. Segments stay `Name`s rather
635    /// than rendered text because callers disagree on the edition to display with,
636    /// and some need to take the path apart rather than print it.
637    ///
638    /// [`ModuleDef::canonical_module_path`] is the same walk yielding the `Module`s
639    /// themselves, for callers that need more than the name — each module's own
640    /// edition, say.
641    pub fn path_segments(self, db: &dyn HirDatabase) -> impl Iterator<Item = Name> {
642        self.path_to_root(db).into_iter().rev().filter_map(|it| it.name(db))
643    }
644
645    pub fn modules_in_scope(&self, db: &dyn HirDatabase, pub_only: bool) -> Vec<(Name, Module)> {
646        let def_map = self.id.def_map(db);
647        let scope = &def_map[self.id].scope;
648
649        let mut res = Vec::new();
650
651        for (name, item) in scope.types() {
652            if let ModuleDefId::ModuleId(m) = item.def
653                && (!pub_only || item.vis == Visibility::Public)
654            {
655                res.push((name.clone(), Module { id: m }));
656            }
657        }
658
659        res
660    }
661
662    /// Returns a `ModuleScope`: a set of items, visible in this module.
663    pub fn scope(
664        self,
665        db: &dyn HirDatabase,
666        visible_from: Option<Module>,
667    ) -> Vec<(Name, ScopeDef<'_>)> {
668        self.id.def_map(db)[self.id]
669            .scope
670            .entries()
671            .filter_map(|(name, def)| {
672                if let Some(m) = visible_from {
673                    let filtered = def.filter_visibility(|vis| vis.is_visible_from(db, m.id));
674                    if filtered.is_none() && !def.is_none() { None } else { Some((name, filtered)) }
675                } else {
676                    Some((name, def))
677                }
678            })
679            .flat_map(|(name, def)| {
680                ScopeDef::all_items(def).into_iter().map(move |item| (name.clone(), item))
681            })
682            .collect()
683    }
684
685    pub fn resolve_mod_path(
686        &self,
687        db: &dyn HirDatabase,
688        segments: impl IntoIterator<Item = Name>,
689    ) -> Option<impl Iterator<Item = ItemInNs>> {
690        let items = self
691            .id
692            .resolver(db)
693            .resolve_module_path_in_items(db, &ModPath::from_segments(PathKind::Plain, segments));
694        Some(items.iter_items().map(|(item, _)| item.into()))
695    }
696
697    /// Fills `acc` with the module's diagnostics.
698    pub fn diagnostics<'db>(
699        self,
700        db: &'db dyn HirDatabase,
701        acc: &mut Vec<AnyDiagnostic<'db>>,
702        style_lints: bool,
703    ) {
704        crate::diagnostics::DiagnosticsCollector::collect(db, self.id, acc, style_lints);
705    }
706
707    pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
708        let def_map = self.id.def_map(db);
709        let scope = &def_map[self.id].scope;
710        scope
711            .declarations()
712            .map(ModuleDef::from)
713            .chain(scope.unnamed_consts().map(|id| ModuleDef::Const(Const::from(id))))
714            .collect()
715    }
716
717    pub fn legacy_macros(self, db: &dyn HirDatabase) -> Vec<Macro> {
718        let def_map = self.id.def_map(db);
719        let scope = &def_map[self.id].scope;
720        scope.legacy_macros().flat_map(|(_, it)| it).map(|&it| it.into()).collect()
721    }
722
723    pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec<Impl> {
724        let def_map = self.id.def_map(db);
725        let scope = &def_map[self.id].scope;
726        scope.impls().map(Impl::from).chain(scope.builtin_derive_impls().map(Impl::from)).collect()
727    }
728
729    /// Finds a path that can be used to refer to the given item from within
730    /// this module, if possible.
731    pub fn find_path(
732        self,
733        db: &dyn SourceDatabase,
734        item: impl Into<ItemInNs>,
735        cfg: FindPathConfig,
736    ) -> Option<ModPath> {
737        hir_def::find_path::find_path(
738            db,
739            item.into().try_into().ok()?,
740            self.into(),
741            PrefixKind::Plain,
742            false,
743            cfg,
744        )
745    }
746
747    /// Finds a path that can be used to refer to the given item from within
748    /// this module, if possible. This is used for returning import paths for use-statements.
749    pub fn find_use_path(
750        self,
751        db: &dyn SourceDatabase,
752        item: impl Into<ItemInNs>,
753        prefix_kind: PrefixKind,
754        cfg: FindPathConfig,
755    ) -> Option<ModPath> {
756        hir_def::find_path::find_path(
757            db,
758            item.into().try_into().ok()?,
759            self.into(),
760            prefix_kind,
761            true,
762            cfg,
763        )
764    }
765
766    #[inline]
767    pub fn doc_keyword(self, db: &dyn HirDatabase) -> Option<Symbol> {
768        AttrFlags::doc_keyword(db, self.id)
769    }
770
771    /// Whether it has `#[path = "..."]` attribute.
772    #[inline]
773    pub fn has_path(&self, db: &dyn HirDatabase) -> bool {
774        self.attrs(db).attrs.contains(AttrFlags::HAS_PATH)
775    }
776}
777
778impl HasVisibility for Module {
779    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
780        let def_map = self.id.def_map(db);
781        let module_data = &def_map[self.id];
782        module_data.visibility
783    }
784}
785
786#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
787pub struct Field {
788    pub(crate) parent: Variant,
789    pub(crate) id: LocalFieldId,
790}
791
792#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)]
793pub struct TupleField<'db> {
794    pub owner: InferBodyId<'db>,
795    pub tuple: TupleId,
796    pub index: u32,
797}
798
799impl<'db> TupleField<'db> {
800    pub fn name(&self) -> Name {
801        Name::new_tuple_field(self.index as usize)
802    }
803
804    pub fn ty(&self, db: &'db dyn HirDatabase) -> Type<'db> {
805        let interner = DbInterner::new_no_crate(db);
806        let ty = InferenceResult::of(db, self.owner)
807            .tuple_field_access_type(self.tuple)
808            .as_slice()
809            .get(self.index as usize)
810            .copied()
811            .unwrap_or_else(|| Ty::new_error(interner, ErrorGuaranteed));
812        Type::new_body(db, self.owner.expression_store_owner(db), ty)
813    }
814}
815
816#[derive(Debug, PartialEq, Eq)]
817pub enum FieldSource {
818    Named(ast::RecordField),
819    Pos(ast::TupleField),
820}
821
822impl AstNode for FieldSource {
823    fn can_cast(kind: syntax::SyntaxKind) -> bool
824    where
825        Self: Sized,
826    {
827        ast::RecordField::can_cast(kind) || ast::TupleField::can_cast(kind)
828    }
829
830    fn cast(syntax: SyntaxNode) -> Option<Self>
831    where
832        Self: Sized,
833    {
834        if ast::RecordField::can_cast(syntax.kind()) {
835            <ast::RecordField as AstNode>::cast(syntax).map(FieldSource::Named)
836        } else if ast::TupleField::can_cast(syntax.kind()) {
837            <ast::TupleField as AstNode>::cast(syntax).map(FieldSource::Pos)
838        } else {
839            None
840        }
841    }
842
843    fn syntax(&self) -> &SyntaxNode {
844        match self {
845            FieldSource::Named(it) => it.syntax(),
846            FieldSource::Pos(it) => it.syntax(),
847        }
848    }
849}
850
851impl Field {
852    pub fn name(&self, db: &dyn HirDatabase) -> Name {
853        VariantId::from(self.parent).fields(db).fields()[self.id].name.clone()
854    }
855
856    pub fn index(&self) -> usize {
857        u32::from(self.id.into_raw()) as usize
858    }
859
860    /// Returns the type as in the signature of the struct. Only use this in the
861    /// context of the field definition.
862    pub fn ty<'db>(&self, db: &'db dyn HirDatabase) -> Type<'db> {
863        let var_id = self.parent.into();
864        let ty = db.field_types(var_id)[self.id].ty().instantiate_identity().skip_norm_wip();
865        Type::new(var_id.adt_id(db).into(), ty)
866    }
867
868    pub fn layout<'db>(&self, db: &'db dyn HirDatabase) -> Result<Layout<'db>, LayoutError> {
869        self.ty(db).layout(db)
870    }
871
872    pub fn parent_def(&self, _db: &dyn HirDatabase) -> Variant {
873        self.parent
874    }
875}
876
877impl HasVisibility for Field {
878    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
879        let variant_data = VariantId::from(self.parent).fields(db);
880        let visibility = &variant_data.fields()[self.id].visibility;
881        let parent_id: hir_def::VariantId = self.parent.into();
882        // FIXME: RawVisibility::Public doesn't need to construct a resolver
883        Visibility::resolve(db, &parent_id.resolver(db), visibility)
884    }
885}
886
887#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
888pub struct Struct {
889    pub(crate) id: StructId,
890}
891
892impl Struct {
893    pub fn module(self, db: &dyn HirDatabase) -> Module {
894        Module { id: self.id.lookup(db).container }
895    }
896
897    pub fn name(self, db: &dyn HirDatabase) -> Name {
898        StructSignature::of(db, self.id).name.clone()
899    }
900
901    pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
902        self.id
903            .fields(db)
904            .fields()
905            .iter()
906            .map(|(id, _)| Field { parent: self.into(), id })
907            .collect()
908    }
909
910    pub fn ty(self, db: &dyn HirDatabase) -> Type<'_> {
911        Type::from_def(db, self.id)
912    }
913
914    pub fn constructor_ty(self, db: &dyn HirDatabase) -> Type<'_> {
915        Type::from_value_def(db, self.id)
916    }
917
918    pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprOptions> {
919        AttrFlags::repr(db, self.id.into())
920    }
921
922    pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
923        match self.variant_fields(db).shape {
924            hir_def::item_tree::FieldsShape::Record => StructKind::Record,
925            hir_def::item_tree::FieldsShape::Tuple => StructKind::Tuple,
926            hir_def::item_tree::FieldsShape::Unit => StructKind::Unit,
927        }
928    }
929
930    fn variant_fields(self, db: &dyn HirDatabase) -> &VariantFields {
931        self.id.fields(db)
932    }
933
934    pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
935        AttrFlags::query(db, self.id.into()).contains(AttrFlags::IS_UNSTABLE)
936    }
937}
938
939impl HasVisibility for Struct {
940    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
941        let loc = self.id.lookup(db);
942        let source = loc.source(db);
943        visibility_from_ast(db, self.id, source.map(|src| src.visibility()))
944    }
945}
946
947#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
948pub struct Union {
949    pub(crate) id: UnionId,
950}
951
952impl Union {
953    pub fn name(self, db: &dyn HirDatabase) -> Name {
954        UnionSignature::of(db, self.id).name.clone()
955    }
956
957    pub fn module(self, db: &dyn HirDatabase) -> Module {
958        Module { id: self.id.lookup(db).container }
959    }
960
961    pub fn ty(self, db: &dyn HirDatabase) -> Type<'_> {
962        Type::from_def(db, self.id)
963    }
964
965    pub fn constructor_ty(self, db: &dyn HirDatabase) -> Type<'_> {
966        Type::from_value_def(db, self.id)
967    }
968
969    pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
970        match self.id.fields(db).shape {
971            hir_def::item_tree::FieldsShape::Record => StructKind::Record,
972            hir_def::item_tree::FieldsShape::Tuple => StructKind::Tuple,
973            hir_def::item_tree::FieldsShape::Unit => StructKind::Unit,
974        }
975    }
976
977    pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
978        self.id
979            .fields(db)
980            .fields()
981            .iter()
982            .map(|(id, _)| Field { parent: self.into(), id })
983            .collect()
984    }
985    pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
986        AttrFlags::query(db, self.id.into()).contains(AttrFlags::IS_UNSTABLE)
987    }
988}
989
990impl HasVisibility for Union {
991    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
992        let loc = self.id.lookup(db);
993        let source = loc.source(db);
994        visibility_from_ast(db, self.id, source.map(|src| src.visibility()))
995    }
996}
997
998#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
999pub struct Enum {
1000    pub(crate) id: EnumId,
1001}
1002
1003impl Enum {
1004    pub fn module(self, db: &dyn HirDatabase) -> Module {
1005        Module { id: self.id.lookup(db).container }
1006    }
1007
1008    pub fn name(self, db: &dyn HirDatabase) -> Name {
1009        EnumSignature::of(db, self.id).name.clone()
1010    }
1011
1012    pub fn variants(self, db: &dyn HirDatabase) -> Vec<EnumVariant> {
1013        self.id.enum_variants(db).variants.values().map(|&(id, _)| EnumVariant { id }).collect()
1014    }
1015
1016    pub fn num_variants(self, db: &dyn HirDatabase) -> usize {
1017        self.id.enum_variants(db).variants.len()
1018    }
1019
1020    pub fn repr(self, db: &dyn HirDatabase) -> Option<ReprOptions> {
1021        AttrFlags::repr(db, self.id.into())
1022    }
1023
1024    pub fn ty<'db>(self, db: &'db dyn HirDatabase) -> Type<'db> {
1025        Type::from_def(db, self.id)
1026    }
1027
1028    /// The type of the enum variant bodies.
1029    pub fn variant_body_ty<'db>(self, db: &'db dyn HirDatabase) -> Type<'db> {
1030        let interner = DbInterner::new_no_crate(db);
1031        Type::no_params(
1032            Type::builtin_type_crate(db),
1033            match EnumSignature::variant_body_type(db, self.id) {
1034                layout::IntegerType::Pointer(sign) => match sign {
1035                    true => Ty::new_int(interner, rustc_type_ir::IntTy::Isize),
1036                    false => Ty::new_uint(interner, rustc_type_ir::UintTy::Usize),
1037                },
1038                layout::IntegerType::Fixed(i, sign) => match sign {
1039                    true => Ty::new_int(
1040                        interner,
1041                        match i {
1042                            layout::Integer::I8 => rustc_type_ir::IntTy::I8,
1043                            layout::Integer::I16 => rustc_type_ir::IntTy::I16,
1044                            layout::Integer::I32 => rustc_type_ir::IntTy::I32,
1045                            layout::Integer::I64 => rustc_type_ir::IntTy::I64,
1046                            layout::Integer::I128 => rustc_type_ir::IntTy::I128,
1047                        },
1048                    ),
1049                    false => Ty::new_uint(
1050                        interner,
1051                        match i {
1052                            layout::Integer::I8 => rustc_type_ir::UintTy::U8,
1053                            layout::Integer::I16 => rustc_type_ir::UintTy::U16,
1054                            layout::Integer::I32 => rustc_type_ir::UintTy::U32,
1055                            layout::Integer::I64 => rustc_type_ir::UintTy::U64,
1056                            layout::Integer::I128 => rustc_type_ir::UintTy::U128,
1057                        },
1058                    ),
1059                },
1060            },
1061        )
1062    }
1063
1064    /// Returns true if at least one variant of this enum is a non-unit variant.
1065    pub fn is_data_carrying(self, db: &dyn HirDatabase) -> bool {
1066        self.variants(db).iter().any(|v| !matches!(v.kind(db), StructKind::Unit))
1067    }
1068
1069    pub fn layout<'db>(self, db: &'db dyn HirDatabase) -> Result<Layout<'db>, LayoutError> {
1070        Adt::from(self).layout(db)
1071    }
1072
1073    pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
1074        AttrFlags::query(db, self.id.into()).contains(AttrFlags::IS_UNSTABLE)
1075    }
1076}
1077
1078impl HasVisibility for Enum {
1079    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1080        let loc = self.id.lookup(db);
1081        let source = loc.source(db);
1082        visibility_from_ast(db, self.id, source.map(|src| src.visibility()))
1083    }
1084}
1085
1086#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1087pub struct EnumVariant {
1088    pub(crate) id: EnumVariantId,
1089}
1090
1091impl EnumVariant {
1092    pub fn module(self, db: &dyn HirDatabase) -> Module {
1093        Module { id: self.id.module(db) }
1094    }
1095
1096    pub fn parent_enum(self, db: &dyn HirDatabase) -> Enum {
1097        self.id.lookup(db).parent.into()
1098    }
1099
1100    pub fn constructor_ty(self, db: &dyn HirDatabase) -> Type<'_> {
1101        Type::from_value_def(db, self.id)
1102    }
1103
1104    pub fn name(self, db: &dyn HirDatabase) -> Name {
1105        self.id.lookup(db).name.clone()
1106    }
1107
1108    pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
1109        self.id
1110            .fields(db)
1111            .fields()
1112            .iter()
1113            .map(|(id, _)| Field { parent: self.into(), id })
1114            .collect()
1115    }
1116
1117    pub fn kind(self, db: &dyn HirDatabase) -> StructKind {
1118        match self.id.fields(db).shape {
1119            hir_def::item_tree::FieldsShape::Record => StructKind::Record,
1120            hir_def::item_tree::FieldsShape::Tuple => StructKind::Tuple,
1121            hir_def::item_tree::FieldsShape::Unit => StructKind::Unit,
1122        }
1123    }
1124
1125    pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
1126        self.source(db)?.value.const_arg()?.expr()
1127    }
1128
1129    pub fn eval(self, db: &dyn HirDatabase) -> Result<i128, ConstEvalError<'_>> {
1130        db.const_eval_discriminant(self.into())
1131    }
1132
1133    pub fn layout<'db>(&self, db: &'db dyn HirDatabase) -> Result<Layout<'db>, LayoutError> {
1134        let parent_enum = self.parent_enum(db);
1135        let parent_layout = parent_enum.layout(db)?;
1136        Ok(match &parent_layout.0.variants {
1137            layout::Variants::Multiple { variants, .. } => Layout(
1138                {
1139                    let lookup = self.id.lookup(db);
1140                    let rustc_enum_variant_idx = RustcEnumVariantIdx(lookup.index(db));
1141                    Arc::new(variants[rustc_enum_variant_idx].clone())
1142                },
1143                db.target_data_layout(parent_enum.krate(db).into()).unwrap(),
1144            ),
1145            _ => parent_layout,
1146        })
1147    }
1148
1149    pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
1150        AttrFlags::query(db, self.id.into()).contains(AttrFlags::IS_UNSTABLE)
1151    }
1152}
1153
1154#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1155pub enum StructKind {
1156    Record,
1157    Tuple,
1158    Unit,
1159}
1160
1161/// Variants inherit visibility from the parent enum.
1162impl HasVisibility for EnumVariant {
1163    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1164        self.parent_enum(db).visibility(db)
1165    }
1166}
1167
1168/// A Data Type
1169#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1170pub enum Adt {
1171    Struct(Struct),
1172    Union(Union),
1173    Enum(Enum),
1174}
1175impl_from!(Struct, Union, Enum for Adt);
1176
1177impl Adt {
1178    pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
1179        has_non_default_type_params(db, self.into())
1180    }
1181
1182    pub fn layout<'db>(self, db: &'db dyn HirDatabase) -> Result<Layout<'db>, LayoutError> {
1183        let interner = DbInterner::new_no_crate(db);
1184        let adt_id = AdtId::from(self);
1185        let args = GenericArgs::for_item_with_defaults(interner, adt_id.into(), |_, id, _| {
1186            GenericArg::error_from_id(interner, id)
1187        });
1188        db.layout_of_adt(adt_id, args.store(), param_env_from_has_crate(db, adt_id).store())
1189            .map(|layout| Layout(layout, db.target_data_layout(self.krate(db).id).unwrap()))
1190    }
1191
1192    /// Turns this ADT into a type. Any type parameters of the ADT will be
1193    /// turned into unknown types, which is good for e.g. finding the most
1194    /// general set of completions, but will not look very nice when printed.
1195    pub fn ty(self, db: &dyn HirDatabase) -> Type<'_> {
1196        let id = AdtId::from(self);
1197        Type::from_def(db, id)
1198    }
1199
1200    pub fn module(self, db: &dyn HirDatabase) -> Module {
1201        match self {
1202            Adt::Struct(s) => s.module(db),
1203            Adt::Union(s) => s.module(db),
1204            Adt::Enum(e) => e.module(db),
1205        }
1206    }
1207
1208    pub fn name(self, db: &dyn HirDatabase) -> Name {
1209        match self {
1210            Adt::Struct(s) => s.name(db),
1211            Adt::Union(u) => u.name(db),
1212            Adt::Enum(e) => e.name(db),
1213        }
1214    }
1215
1216    /// Returns the lifetime of the DataType
1217    pub fn lifetime(&self, db: &dyn HirDatabase) -> Option<LifetimeParamData> {
1218        let resolver = match self {
1219            Adt::Struct(s) => s.id.resolver(db),
1220            Adt::Union(u) => u.id.resolver(db),
1221            Adt::Enum(e) => e.id.resolver(db),
1222        };
1223        resolver
1224            .generic_params()
1225            .and_then(|gp| {
1226                gp.iter_early_bound_lt()
1227                    // there should only be a single lifetime
1228                    // but `Arena` requires to use an iterator
1229                    .nth(0)
1230            })
1231            .map(|arena| arena.1.clone())
1232    }
1233
1234    pub fn as_struct(&self) -> Option<Struct> {
1235        if let Self::Struct(v) = self { Some(*v) } else { None }
1236    }
1237
1238    pub fn as_enum(&self) -> Option<Enum> {
1239        if let Self::Enum(v) = self { Some(*v) } else { None }
1240    }
1241}
1242
1243impl HasVisibility for Adt {
1244    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1245        match self {
1246            Adt::Struct(it) => it.visibility(db),
1247            Adt::Union(it) => it.visibility(db),
1248            Adt::Enum(it) => it.visibility(db),
1249        }
1250    }
1251}
1252
1253#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1254pub enum Variant {
1255    Struct(Struct),
1256    Union(Union),
1257    EnumVariant(EnumVariant),
1258}
1259impl_from!(Struct, Union, EnumVariant for Variant);
1260
1261impl Variant {
1262    pub fn fields(self, db: &dyn HirDatabase) -> Vec<Field> {
1263        match self {
1264            Variant::Struct(it) => it.fields(db),
1265            Variant::Union(it) => it.fields(db),
1266            Variant::EnumVariant(it) => it.fields(db),
1267        }
1268    }
1269
1270    pub fn module(self, db: &dyn HirDatabase) -> Module {
1271        match self {
1272            Variant::Struct(it) => it.module(db),
1273            Variant::Union(it) => it.module(db),
1274            Variant::EnumVariant(it) => it.module(db),
1275        }
1276    }
1277
1278    pub fn name(&self, db: &dyn HirDatabase) -> Name {
1279        match self {
1280            Variant::Struct(s) => (*s).name(db),
1281            Variant::Union(u) => (*u).name(db),
1282            Variant::EnumVariant(e) => (*e).name(db),
1283        }
1284    }
1285
1286    pub fn adt(&self, db: &dyn HirDatabase) -> Adt {
1287        match *self {
1288            Variant::Struct(it) => it.into(),
1289            Variant::Union(it) => it.into(),
1290            Variant::EnumVariant(it) => it.parent_enum(db).into(),
1291        }
1292    }
1293}
1294
1295#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1296pub struct AnonConst<'db> {
1297    id: AnonConstId<'db>,
1298}
1299
1300impl<'db> AnonConst<'db> {
1301    pub fn owner(self, db: &dyn HirDatabase) -> ExpressionStoreOwner {
1302        self.id.loc(db).owner.into()
1303    }
1304
1305    pub fn ty(self, db: &'db dyn HirDatabase) -> Type<'db> {
1306        let loc = self.id.loc(db);
1307        Type { owner: TypeOwnerId::from_anon_const(self.id, db), ty: loc.ty.get() }
1308    }
1309
1310    pub fn eval(
1311        self,
1312        db: &'db dyn HirDatabase,
1313    ) -> Result<EvaluatedConst<'db>, ConstEvalError<'db>> {
1314        let ty = self.id.loc(db).ty.get().instantiate_identity().skip_norm_wip();
1315        db.anon_const_eval(self.id, GenericArgs::empty(), None).map(|it| EvaluatedConst {
1316            allocation: it,
1317            def: self.id.into(),
1318            ty,
1319        })
1320    }
1321}
1322
1323#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1324pub enum InferBody<'db> {
1325    Body(DefWithBody),
1326    AnonConst(AnonConst<'db>),
1327}
1328
1329#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1330pub enum ExpressionStoreOwner {
1331    Body(DefWithBody),
1332    Signature(GenericDef),
1333    VariantFields(Variant),
1334}
1335
1336impl From<GenericDef> for ExpressionStoreOwner {
1337    fn from(v: GenericDef) -> Self {
1338        Self::Signature(v)
1339    }
1340}
1341
1342impl From<DefWithBody> for ExpressionStoreOwner {
1343    fn from(v: DefWithBody) -> Self {
1344        Self::Body(v)
1345    }
1346}
1347
1348impl_from!(
1349    ExpressionStoreOwnerId {
1350        Signature => Signature,
1351        Body => Body,
1352        VariantFields => VariantFields,
1353    }
1354    for ExpressionStoreOwner
1355);
1356
1357impl ExpressionStoreOwner {
1358    pub fn module(self, db: &dyn HirDatabase) -> Module {
1359        match self {
1360            Self::Body(body) => body.module(db),
1361            Self::Signature(generic_def) => generic_def.module(db),
1362            Self::VariantFields(variant) => variant.module(db),
1363        }
1364    }
1365}
1366
1367/// The defs which have a body.
1368#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1369pub enum DefWithBody {
1370    Function(Function),
1371    Static(Static),
1372    Const(Const),
1373    EnumVariant(EnumVariant),
1374}
1375impl_from!(Function, Const, Static, EnumVariant for DefWithBody);
1376
1377impl DefWithBody {
1378    pub fn module(self, db: &dyn HirDatabase) -> Module {
1379        match self {
1380            DefWithBody::Const(c) => c.module(db),
1381            DefWithBody::Function(f) => f.module(db),
1382            DefWithBody::Static(s) => s.module(db),
1383            DefWithBody::EnumVariant(v) => v.module(db),
1384        }
1385    }
1386
1387    pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
1388        match self {
1389            DefWithBody::Function(f) => Some(f.name(db)),
1390            DefWithBody::Static(s) => Some(s.name(db)),
1391            DefWithBody::Const(c) => c.name(db),
1392            DefWithBody::EnumVariant(v) => Some(v.name(db)),
1393        }
1394    }
1395
1396    /// Returns the type this def's body has to evaluate to.
1397    pub fn body_type(self, db: &dyn HirDatabase) -> Type<'_> {
1398        match self {
1399            DefWithBody::Function(it) => it.ret_type(db),
1400            DefWithBody::Static(it) => it.ty(db),
1401            DefWithBody::Const(it) => it.ty(db),
1402            DefWithBody::EnumVariant(it) => it.parent_enum(db).variant_body_ty(db),
1403        }
1404    }
1405
1406    fn id(&self) -> Option<DefWithBodyId> {
1407        Some(match self {
1408            DefWithBody::Function(it) => match it.id {
1409                AnyFunctionId::FunctionId(id) => id.into(),
1410                AnyFunctionId::BuiltinDeriveImplMethod { .. } => return None,
1411            },
1412            DefWithBody::Static(it) => it.id.into(),
1413            DefWithBody::Const(it) => it.id.into(),
1414            DefWithBody::EnumVariant(it) => it.id.into(),
1415        })
1416    }
1417
1418    #[deprecated = "you should really not use this, this is exported for analysis-stats only"]
1419    pub fn run_mir_body(self, db: &dyn HirDatabase) -> Result<(), MirLowerError<'_>> {
1420        let Some(id) = self.id() else { return Ok(()) };
1421        db.mir_body(id.into()).map(drop)
1422    }
1423
1424    /// A textual representation of the HIR of this def's body for debugging purposes.
1425    pub fn debug_hir(self, db: &dyn HirDatabase) -> String {
1426        let Some(id) = self.id() else {
1427            return String::new();
1428        };
1429        let body = Body::of(db, id);
1430        body.pretty_print(db, id, Edition::CURRENT)
1431    }
1432
1433    /// A textual representation of the MIR of this def's body for debugging purposes.
1434    pub fn debug_mir(self, db: &dyn HirDatabase) -> String {
1435        let Some(id) = self.id() else {
1436            return String::new();
1437        };
1438        let body = db.mir_body(id.into());
1439        match body {
1440            Ok(body) => body.pretty_print(db, self.module(db).krate(db).to_display_target(db)),
1441            Err(e) => format!("error:\n{e:?}"),
1442        }
1443    }
1444
1445    /// Returns an iterator over the inferred types of all expressions in this body.
1446    pub fn expression_types<'db>(
1447        self,
1448        db: &'db dyn HirDatabase,
1449    ) -> impl Iterator<Item = Type<'db>> {
1450        self.id().into_iter().flat_map(move |def_id| {
1451            let infer = InferenceResult::of(db, def_id);
1452            let def_id = def_id.generic_def(db);
1453
1454            infer.expression_types().map(move |(_, ty)| Type::new(def_id, ty))
1455        })
1456    }
1457
1458    /// Returns an iterator over the inferred types of all patterns in this body.
1459    pub fn pattern_types<'db>(self, db: &'db dyn HirDatabase) -> impl Iterator<Item = Type<'db>> {
1460        self.id().into_iter().flat_map(move |def_id| {
1461            let infer = InferenceResult::of(db, def_id);
1462            let def_id = def_id.generic_def(db);
1463
1464            infer.pattern_types().map(move |(_, ty)| Type::new(def_id, ty))
1465        })
1466    }
1467
1468    /// Returns an iterator over the inferred types of all bindings in this body.
1469    pub fn binding_types<'db>(self, db: &'db dyn HirDatabase) -> impl Iterator<Item = Type<'db>> {
1470        self.id().into_iter().flat_map(move |def_id| {
1471            let infer = InferenceResult::of(db, def_id);
1472            let def_id = def_id.generic_def(db);
1473
1474            infer.binding_types().map(move |(_, ty)| Type::new(def_id, ty))
1475        })
1476    }
1477}
1478
1479#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1480enum AnyFunctionId {
1481    FunctionId(FunctionId),
1482    BuiltinDeriveImplMethod { method: BuiltinDeriveImplMethod, impl_: BuiltinDeriveImplId },
1483}
1484
1485#[derive(Clone, Copy, PartialEq, Eq, Hash)]
1486pub struct Function {
1487    pub(crate) id: AnyFunctionId,
1488}
1489
1490impl fmt::Debug for Function {
1491    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1492        fmt::Debug::fmt(&self.id, f)
1493    }
1494}
1495
1496impl Function {
1497    pub fn lang(db: &dyn HirDatabase, krate: Crate, lang_item: LangItem) -> Option<Function> {
1498        let lang_items = hir_def::lang_item::lang_items(db, krate.id);
1499        match lang_item.from_lang_items(lang_items)? {
1500            LangItemTarget::FunctionId(it) => Some(it.into()),
1501            _ => None,
1502        }
1503    }
1504
1505    pub fn module(self, db: &dyn HirDatabase) -> Module {
1506        match self.id {
1507            AnyFunctionId::FunctionId(id) => id.module(db).into(),
1508            AnyFunctionId::BuiltinDeriveImplMethod { impl_, .. } => impl_.module(db).into(),
1509        }
1510    }
1511
1512    pub fn name(self, db: &dyn HirDatabase) -> Name {
1513        match self.id {
1514            AnyFunctionId::FunctionId(id) => FunctionSignature::of(db, id).name.clone(),
1515            AnyFunctionId::BuiltinDeriveImplMethod { method, .. } => {
1516                Name::new_symbol_root(method.name())
1517            }
1518        }
1519    }
1520
1521    pub fn ty(self, db: &dyn HirDatabase) -> Type<'_> {
1522        match self.id {
1523            AnyFunctionId::FunctionId(id) => Type::from_value_def(db, id),
1524            AnyFunctionId::BuiltinDeriveImplMethod { method, impl_ } => {
1525                // Get the type for the trait function, as we can't get the type for the impl function
1526                // because it has not `CallableDefId`.
1527                // FIXME: This does not account for replacing `Self`. Do we really need that?
1528                let Some(trait_method) = method.trait_method(db, impl_) else {
1529                    return Type::unknown(db);
1530                };
1531                Function::from(trait_method).ty(db)
1532            }
1533        }
1534    }
1535
1536    pub fn fn_ptr_type(self, db: &dyn HirDatabase) -> Type<'_> {
1537        match self.id {
1538            AnyFunctionId::FunctionId(id) => {
1539                let interner = DbInterner::new_no_crate(db);
1540                let callable_sig =
1541                    db.callable_item_signature(id.into()).instantiate_identity().skip_norm_wip();
1542                let ty = Ty::new_fn_ptr(interner, callable_sig);
1543                Type::new(id.into(), ty)
1544            }
1545            AnyFunctionId::BuiltinDeriveImplMethod { method, impl_ } => {
1546                // Get the type for the trait function, as we can't get the type for the impl function
1547                // because it has not `CallableDefId`.
1548                // FIXME: This does not account for replacing `Self`. Do we really need that?
1549                let Some(trait_method) = method.trait_method(db, impl_) else {
1550                    return Type::unknown(db);
1551                };
1552                Function::from(trait_method).fn_ptr_type(db)
1553            }
1554        }
1555    }
1556
1557    fn fn_sig<'db>(self, db: &'db dyn HirDatabase) -> (TypeOwnerId, PolyFnSig<'db>) {
1558        let fn_ptr = self.fn_ptr_type(db);
1559        let TyKind::FnPtr(sig_tys, hdr) = fn_ptr.ty.skip_binder().kind() else {
1560            unreachable!();
1561        };
1562        (fn_ptr.owner, sig_tys.with(hdr))
1563    }
1564
1565    fn erased_fn_sig<'db>(self, db: &'db dyn HirDatabase) -> (TypeOwnerId, FnSig<'db>) {
1566        let (owner, sig) = self.fn_sig(db);
1567        let sig = DbInterner::new_no_crate(db).instantiate_bound_regions_with_erased(sig);
1568        (owner, sig)
1569    }
1570
1571    /// Get this function's return type
1572    pub fn ret_type(self, db: &dyn HirDatabase) -> Type<'_> {
1573        let (owner, sig) = self.erased_fn_sig(db);
1574        Type { owner, ty: EarlyBinder::bind(sig.output()) }
1575    }
1576
1577    pub fn async_ret_type<'db>(self, db: &'db dyn HirDatabase) -> Option<Type<'db>> {
1578        let AnyFunctionId::FunctionId(id) = self.id else {
1579            return None;
1580        };
1581        if !self.is_async(db) {
1582            return None;
1583        }
1584        let interner = DbInterner::new_no_crate(db);
1585        let sig = db.callable_item_signature(id.into()).instantiate_identity().skip_norm_wip();
1586        let ret_ty = interner.instantiate_bound_regions_with_erased(sig).output();
1587        for pred in ret_ty.impl_trait_bounds(db).into_iter().flatten() {
1588            let clause = interner.instantiate_bound_regions_with_erased(pred.kind());
1589            if let ClauseKind::Projection(projection) = clause
1590                && let Some(output_ty) = projection.term.as_type()
1591            {
1592                return Some(Type::new(id.into(), output_ty));
1593            }
1594        }
1595        None
1596    }
1597
1598    pub fn has_self_param(self, db: &dyn HirDatabase) -> bool {
1599        match self.id {
1600            AnyFunctionId::FunctionId(id) => FunctionSignature::of(db, id).has_self_param(),
1601            AnyFunctionId::BuiltinDeriveImplMethod { method, .. } => match method {
1602                BuiltinDeriveImplMethod::clone
1603                | BuiltinDeriveImplMethod::fmt
1604                | BuiltinDeriveImplMethod::hash
1605                | BuiltinDeriveImplMethod::cmp
1606                | BuiltinDeriveImplMethod::partial_cmp
1607                | BuiltinDeriveImplMethod::eq => true,
1608                BuiltinDeriveImplMethod::default => false,
1609            },
1610        }
1611    }
1612
1613    pub fn self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
1614        self.has_self_param(db).then_some(SelfParam { func: self })
1615    }
1616
1617    pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec<Param<'_>> {
1618        let (owner, sig) = self.erased_fn_sig(db);
1619        let func = match self.id {
1620            AnyFunctionId::FunctionId(id) => Callee::Def(CallableDefId::FunctionId(id)),
1621            AnyFunctionId::BuiltinDeriveImplMethod { method, impl_ } => {
1622                Callee::BuiltinDeriveImplMethod { method, impl_ }
1623            }
1624        };
1625        sig.inputs()
1626            .iter()
1627            .enumerate()
1628            .map(|(idx, &ty)| Param {
1629                func: func.clone(),
1630                ty: Type { owner, ty: EarlyBinder::bind(ty) },
1631                idx,
1632            })
1633            .collect()
1634    }
1635
1636    pub fn num_params(self, db: &dyn HirDatabase) -> usize {
1637        match self.id {
1638            AnyFunctionId::FunctionId(id) => FunctionSignature::of(db, id).params.len(),
1639            AnyFunctionId::BuiltinDeriveImplMethod { .. } => {
1640                self.fn_sig(db).1.skip_binder().inputs().len()
1641            }
1642        }
1643    }
1644
1645    pub fn method_params(self, db: &dyn HirDatabase) -> Option<Vec<Param<'_>>> {
1646        self.self_param(db)?;
1647        Some(self.params_without_self(db))
1648    }
1649
1650    pub fn params_without_self(self, db: &dyn HirDatabase) -> Vec<Param<'_>> {
1651        let mut params = self.assoc_fn_params(db);
1652        if self.has_self_param(db) {
1653            params.remove(0);
1654        }
1655        params
1656    }
1657
1658    pub fn is_const(self, db: &dyn HirDatabase) -> bool {
1659        match self.id {
1660            AnyFunctionId::FunctionId(id) => FunctionSignature::of(db, id).is_const(),
1661            AnyFunctionId::BuiltinDeriveImplMethod { .. } => false,
1662        }
1663    }
1664
1665    pub fn is_async(self, db: &dyn HirDatabase) -> bool {
1666        match self.id {
1667            AnyFunctionId::FunctionId(id) => FunctionSignature::of(db, id).is_async(),
1668            AnyFunctionId::BuiltinDeriveImplMethod { .. } => false,
1669        }
1670    }
1671
1672    pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
1673        match self.id {
1674            AnyFunctionId::FunctionId(id) => FunctionSignature::of(db, id).is_unsafe(),
1675            AnyFunctionId::BuiltinDeriveImplMethod { .. } => false,
1676        }
1677    }
1678
1679    pub fn is_varargs(self, db: &dyn HirDatabase) -> bool {
1680        match self.id {
1681            AnyFunctionId::FunctionId(id) => FunctionSignature::of(db, id).is_varargs(),
1682            AnyFunctionId::BuiltinDeriveImplMethod { .. } => false,
1683        }
1684    }
1685
1686    pub fn extern_block(self, db: &dyn HirDatabase) -> Option<ExternBlock> {
1687        match self.id {
1688            AnyFunctionId::FunctionId(id) => match id.lookup(db).container {
1689                ItemContainerId::ExternBlockId(id) => Some(ExternBlock { id }),
1690                _ => None,
1691            },
1692            AnyFunctionId::BuiltinDeriveImplMethod { .. } => None,
1693        }
1694    }
1695
1696    pub fn returns_impl_future(self, db: &dyn HirDatabase) -> bool {
1697        if self.is_async(db) {
1698            return true;
1699        }
1700
1701        let ret_type = self.ret_type(db);
1702        let Some(impl_traits) = ret_type.as_impl_traits(db) else { return false };
1703        let lang_items = hir_def::lang_item::lang_items(db, self.krate(db).id);
1704        let Some(future_trait_id) = lang_items.Future else {
1705            return false;
1706        };
1707        let Some(sized_trait_id) = lang_items.Sized else {
1708            return false;
1709        };
1710
1711        let mut has_impl_future = false;
1712        impl_traits
1713            .filter(|t| {
1714                let fut = t.id == future_trait_id;
1715                has_impl_future |= fut;
1716                !fut && t.id != sized_trait_id
1717            })
1718            // all traits but the future trait must be auto traits
1719            .all(|t| t.is_auto(db))
1720            && has_impl_future
1721    }
1722
1723    /// Does this function have `#[test]` attribute?
1724    pub fn is_test(self, db: &dyn HirDatabase) -> bool {
1725        self.attrs(db).contains(AttrFlags::IS_TEST)
1726    }
1727
1728    /// is this a `fn main` or a function with an `export_name` of `main`?
1729    pub fn is_main(self, db: &dyn HirDatabase) -> bool {
1730        match self.id {
1731            AnyFunctionId::FunctionId(id) => {
1732                self.exported_main(db)
1733                    || self.module(db).is_crate_root(db)
1734                        && FunctionSignature::of(db, id).name == sym::main
1735            }
1736            AnyFunctionId::BuiltinDeriveImplMethod { .. } => false,
1737        }
1738    }
1739
1740    fn attrs(self, db: &dyn HirDatabase) -> AttrFlags {
1741        match self.id {
1742            AnyFunctionId::FunctionId(id) => AttrFlags::query(db, id.into()),
1743            AnyFunctionId::BuiltinDeriveImplMethod { .. } => AttrFlags::empty(),
1744        }
1745    }
1746
1747    /// Is this a function with an `export_name` of `main`?
1748    pub fn exported_main(self, db: &dyn HirDatabase) -> bool {
1749        self.attrs(db).contains(AttrFlags::IS_EXPORT_NAME_MAIN)
1750    }
1751
1752    /// Does this function have the ignore attribute?
1753    pub fn is_ignore(self, db: &dyn HirDatabase) -> bool {
1754        self.attrs(db).contains(AttrFlags::IS_IGNORE)
1755    }
1756
1757    /// Does this function have `#[bench]` attribute?
1758    pub fn is_bench(self, db: &dyn HirDatabase) -> bool {
1759        self.attrs(db).contains(AttrFlags::IS_BENCH)
1760    }
1761
1762    /// Is this function marked as unstable with `#[feature]` attribute?
1763    pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
1764        self.attrs(db).contains(AttrFlags::IS_UNSTABLE)
1765    }
1766
1767    pub fn is_unsafe_to_call(
1768        self,
1769        db: &dyn HirDatabase,
1770        caller: Option<Function>,
1771        call_edition: Edition,
1772    ) -> bool {
1773        let AnyFunctionId::FunctionId(id) = self.id else {
1774            return false;
1775        };
1776        let (target_features, target_feature_is_safe_in_target) = caller
1777            .map(|caller| {
1778                let target_features = match caller.id {
1779                    AnyFunctionId::FunctionId(id) => hir_ide::TargetFeatures::from_fn(db, id),
1780                    AnyFunctionId::BuiltinDeriveImplMethod { .. } => {
1781                        hir_ide::TargetFeatures::default()
1782                    }
1783                };
1784                let target_feature_is_safe_in_target =
1785                    match &caller.krate(db).id.workspace_data(db).target {
1786                        Ok(target) => hir_ide::target_feature_is_safe_in_target(target),
1787                        Err(_) => hir_ide::TargetFeatureIsSafeInTarget::No,
1788                    };
1789                (target_features, target_feature_is_safe_in_target)
1790            })
1791            .unwrap_or_else(|| {
1792                (hir_ide::TargetFeatures::default(), hir_ide::TargetFeatureIsSafeInTarget::No)
1793            });
1794        matches!(
1795            hir_ide::is_fn_unsafe_to_call(
1796                db,
1797                id,
1798                &target_features,
1799                call_edition,
1800                target_feature_is_safe_in_target
1801            ),
1802            hir_ide::Unsafety::Unsafe
1803        )
1804    }
1805
1806    /// Whether this function declaration has a definition.
1807    ///
1808    /// This is false in the case of required (not provided) trait methods.
1809    pub fn has_body(self, db: &dyn HirDatabase) -> bool {
1810        match self.id {
1811            AnyFunctionId::FunctionId(id) => FunctionSignature::of(db, id).has_body(),
1812            AnyFunctionId::BuiltinDeriveImplMethod { .. } => true,
1813        }
1814    }
1815
1816    pub fn as_proc_macro(self, db: &dyn HirDatabase) -> Option<Macro> {
1817        let AnyFunctionId::FunctionId(id) = self.id else {
1818            return None;
1819        };
1820        let def_map = crate_def_map(db, HasModule::krate(&id, db));
1821        def_map.fn_as_proc_macro(id).map(|id| Macro { id: id.into() })
1822    }
1823
1824    pub fn eval(
1825        self,
1826        db: &dyn HirDatabase,
1827        span_formatter: impl Fn(FileId, TextRange) -> String,
1828    ) -> Result<String, ConstEvalError<'_>> {
1829        let AnyFunctionId::FunctionId(id) = self.id else {
1830            return Err(ConstEvalError::MirEvalError(MirEvalError::NotSupported(
1831                "evaluation of builtin derive impl methods is not supported".to_owned(),
1832            )));
1833        };
1834        let body = db.monomorphized_mir_body(
1835            id.into(),
1836            GenericArgs::empty().store(),
1837            ParamEnvAndCrate {
1838                param_env: db.trait_environment(id.into()),
1839                krate: id.module(db).krate(db),
1840            }
1841            .store(),
1842        )?;
1843        let (result, output) = interpret_mir(db, body, false, None)?;
1844        let mut text = match result {
1845            Ok(_) => "pass".to_owned(),
1846            Err(e) => {
1847                let mut r = String::new();
1848                _ = e.pretty_print(
1849                    &mut r,
1850                    db,
1851                    &span_formatter,
1852                    self.krate(db).to_display_target(db),
1853                );
1854                r
1855            }
1856        };
1857        let stdout = output.stdout().into_owned();
1858        if !stdout.is_empty() {
1859            text += "\n--------- stdout ---------\n";
1860            text += &stdout;
1861        }
1862        let stderr = output.stdout().into_owned();
1863        if !stderr.is_empty() {
1864            text += "\n--------- stderr ---------\n";
1865            text += &stderr;
1866        }
1867        Ok(text)
1868    }
1869}
1870
1871// Note: logically, this belongs to `hir_ide`, but we are not using it there yet.
1872#[derive(Clone, Copy, PartialEq, Eq)]
1873pub enum Access {
1874    Shared,
1875    Exclusive,
1876    Owned,
1877}
1878
1879impl From<hir_ide::next_solver::Mutability> for Access {
1880    fn from(mutability: hir_ide::next_solver::Mutability) -> Access {
1881        match mutability {
1882            hir_ide::next_solver::Mutability::Not => Access::Shared,
1883            hir_ide::next_solver::Mutability::Mut => Access::Exclusive,
1884        }
1885    }
1886}
1887
1888#[derive(Clone, PartialEq, Eq, Hash, Debug)]
1889pub struct Param<'db> {
1890    func: Callee<'db>,
1891    /// The index in parameter list, including self parameter.
1892    idx: usize,
1893    ty: Type<'db>,
1894}
1895
1896impl<'db> Param<'db> {
1897    pub fn parent_fn(&self) -> Option<Function> {
1898        match self.func {
1899            Callee::Def(CallableDefId::FunctionId(f)) => Some(f.into()),
1900            Callee::BuiltinDeriveImplMethod { method, impl_ } => {
1901                Some(Function { id: AnyFunctionId::BuiltinDeriveImplMethod { method, impl_ } })
1902            }
1903            _ => None,
1904        }
1905    }
1906
1907    // pub fn parent_closure(&self) -> Option<Closure> {
1908    //     self.func.as_ref().right().cloned()
1909    // }
1910
1911    pub fn index(&self) -> usize {
1912        self.idx
1913    }
1914
1915    pub fn ty(&self) -> &Type<'db> {
1916        &self.ty
1917    }
1918
1919    pub fn name(&self, db: &dyn HirDatabase) -> Option<Name> {
1920        Some(self.as_local(db)?.name(db))
1921    }
1922
1923    pub fn as_local(&self, db: &'db dyn HirDatabase) -> Option<Local<'db>> {
1924        match self.func {
1925            Callee::Def(CallableDefId::FunctionId(it)) => {
1926                let parent = DefWithBodyId::FunctionId(it);
1927                let body = Body::of(db, parent);
1928                if let Some(self_param) = body.self_param.filter(|_| self.idx == 0) {
1929                    Some(Local {
1930                        parent: parent.into(),
1931                        parent_infer: parent.into(),
1932                        binding_id: self_param.user_written,
1933                    })
1934                } else if let Pat::Bind { id, .. } =
1935                    &body[body.params[self.idx - body.self_param.is_some() as usize].user_written]
1936                {
1937                    Some(Local {
1938                        parent: parent.into(),
1939                        parent_infer: parent.into(),
1940                        binding_id: *id,
1941                    })
1942                } else {
1943                    None
1944                }
1945            }
1946            Callee::Closure(closure, _) => {
1947                let c = closure.loc(db);
1948                let body_infer_owner = c.owner;
1949                let body_owner = c.owner.expression_store_owner(db);
1950                let store = ExpressionStore::of(db, body_owner);
1951
1952                if let Expr::Closure { args, .. } = &store[c.expr]
1953                    && let Pat::Bind { id, .. } = &store[args[self.idx]]
1954                {
1955                    return Some(Local {
1956                        parent: body_owner,
1957                        parent_infer: body_infer_owner,
1958                        binding_id: *id,
1959                    });
1960                }
1961                None
1962            }
1963            _ => None,
1964        }
1965    }
1966
1967    pub fn pattern_source(self, db: &dyn HirDatabase) -> Option<ast::Pat> {
1968        self.source(db).and_then(|p| p.value.right()?.pat())
1969    }
1970}
1971
1972#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1973pub struct SelfParam {
1974    func: Function,
1975}
1976
1977impl SelfParam {
1978    pub fn access(self, db: &dyn HirDatabase) -> Access {
1979        match self.func.id {
1980            AnyFunctionId::FunctionId(id) => {
1981                let func_data = FunctionSignature::of(db, id);
1982                func_data
1983                    .params
1984                    .first()
1985                    .map(|&param| match &func_data.store[param] {
1986                        TypeRef::Reference(ref_) => match ref_.mutability {
1987                            hir_def::type_ref::Mutability::Shared => Access::Shared,
1988                            hir_def::type_ref::Mutability::Mut => Access::Exclusive,
1989                        },
1990                        _ => Access::Owned,
1991                    })
1992                    .unwrap_or(Access::Owned)
1993            }
1994            AnyFunctionId::BuiltinDeriveImplMethod { method, .. } => match method {
1995                BuiltinDeriveImplMethod::clone
1996                | BuiltinDeriveImplMethod::fmt
1997                | BuiltinDeriveImplMethod::hash
1998                | BuiltinDeriveImplMethod::cmp
1999                | BuiltinDeriveImplMethod::partial_cmp
2000                | BuiltinDeriveImplMethod::eq => Access::Shared,
2001                BuiltinDeriveImplMethod::default => {
2002                    unreachable!("this function does not have a self param")
2003                }
2004            },
2005        }
2006    }
2007
2008    pub fn parent_fn(&self) -> Function {
2009        self.func
2010    }
2011
2012    pub fn ty<'db>(&self, db: &'db dyn HirDatabase) -> Type<'db> {
2013        let (owner, sig) = self.func.erased_fn_sig(db);
2014        Type { owner, ty: EarlyBinder::bind(sig.inputs()[0]) }
2015    }
2016}
2017
2018impl HasVisibility for Function {
2019    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
2020        match self.id {
2021            AnyFunctionId::FunctionId(id) => AssocItemId::from(id).assoc_visibility(db),
2022            AnyFunctionId::BuiltinDeriveImplMethod { .. } => Visibility::Public,
2023        }
2024    }
2025}
2026
2027#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2028pub struct ExternCrateDecl {
2029    pub(crate) id: ExternCrateId,
2030}
2031
2032impl ExternCrateDecl {
2033    pub fn module(self, db: &dyn HirDatabase) -> Module {
2034        self.id.module(db).into()
2035    }
2036
2037    pub fn resolved_crate(self, db: &dyn HirDatabase) -> Option<Crate> {
2038        let loc = self.id.lookup(db);
2039        let krate = loc.container.krate(db);
2040        let name = self.name(db);
2041        if name == sym::self_ {
2042            Some(krate.into())
2043        } else {
2044            krate.data(db).dependencies.iter().find_map(|dep| {
2045                if dep.name.symbol() == name.symbol() { Some(dep.crate_id.into()) } else { None }
2046            })
2047        }
2048    }
2049
2050    pub fn name(self, db: &dyn HirDatabase) -> Name {
2051        let loc = self.id.lookup(db);
2052        let source = loc.source(db);
2053        as_name_opt(source.value.name_ref())
2054    }
2055
2056    pub fn alias(self, db: &dyn HirDatabase) -> Option<ImportAlias> {
2057        let loc = self.id.lookup(db);
2058        let source = loc.source(db);
2059        let rename = source.value.rename()?;
2060        if let Some(name) = rename.name() {
2061            Some(ImportAlias::Alias(name.as_name()))
2062        } else if rename.underscore_token().is_some() {
2063            Some(ImportAlias::Underscore)
2064        } else {
2065            None
2066        }
2067    }
2068
2069    /// Returns the name under which this crate is made accessible, taking `_` into account.
2070    pub fn alias_or_name(self, db: &dyn HirDatabase) -> Option<Name> {
2071        match self.alias(db) {
2072            Some(ImportAlias::Underscore) => None,
2073            Some(ImportAlias::Alias(alias)) => Some(alias),
2074            None => Some(self.name(db)),
2075        }
2076    }
2077}
2078
2079impl HasVisibility for ExternCrateDecl {
2080    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
2081        let loc = self.id.lookup(db);
2082        let source = loc.source(db);
2083        visibility_from_ast(db, self.id, source.map(|src| src.visibility()))
2084    }
2085}
2086
2087#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2088pub struct Const {
2089    pub(crate) id: ConstId,
2090}
2091
2092impl Const {
2093    pub fn module(self, db: &dyn HirDatabase) -> Module {
2094        Module { id: self.id.module(db) }
2095    }
2096
2097    pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
2098        ConstSignature::of(db, self.id).name.clone()
2099    }
2100
2101    pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
2102        self.source(db)?.value.body()
2103    }
2104
2105    pub fn ty(self, db: &dyn HirDatabase) -> Type<'_> {
2106        Type::from_value_def(db, self.id)
2107    }
2108
2109    pub fn has_body(self, db: &dyn HirDatabase) -> bool {
2110        ConstSignature::of(db, self.id).has_body()
2111    }
2112
2113    /// Evaluate the constant.
2114    pub fn eval(self, db: &dyn HirDatabase) -> Result<EvaluatedConst<'_>, ConstEvalError<'_>> {
2115        let ty = db.value_ty(self.id.into()).unwrap().instantiate_identity().skip_norm_wip();
2116        db.const_eval(self.id, GenericArgs::empty(), None).map(|it| EvaluatedConst {
2117            allocation: it,
2118            def: self.id.into(),
2119            ty,
2120        })
2121    }
2122}
2123
2124impl HasVisibility for Const {
2125    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
2126        AssocItemId::from(self.id).assoc_visibility(db)
2127    }
2128}
2129
2130pub struct EvaluatedConst<'db> {
2131    def: InferBodyId<'db>,
2132    allocation: hir_ide::next_solver::Allocation<'db>,
2133    ty: Ty<'db>,
2134}
2135
2136impl<'db> EvaluatedConst<'db> {
2137    pub fn render(&self, db: &dyn HirDatabase, display_target: DisplayTarget) -> String {
2138        format!("{}", self.allocation.display(db, display_target))
2139    }
2140
2141    pub fn render_debug(&self, db: &'db dyn HirDatabase) -> Result<String, MirEvalError<'db>> {
2142        let ty = self.allocation.ty.kind();
2143        if let TyKind::Int(_) | TyKind::Uint(_) = ty {
2144            let b = &self.allocation.memory;
2145            let value = u128::from_le_bytes(mir::pad16(b, mir::IsSigned::No));
2146            let is_signed = matches!(ty, TyKind::Int(_)).into();
2147            let value_signed = i128::from_le_bytes(mir::pad16(b, is_signed));
2148            let mut result =
2149                if let TyKind::Int(_) = ty { value_signed.to_string() } else { value.to_string() };
2150            if value >= 10 {
2151                format_to!(result, " ({value:#X})");
2152                return Ok(result);
2153            } else {
2154                return Ok(result);
2155            }
2156        }
2157        mir::render_const_using_debug_impl(db, self.def, self.allocation, self.ty)
2158    }
2159}
2160
2161#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2162pub struct Static {
2163    pub(crate) id: StaticId,
2164}
2165
2166impl Static {
2167    pub fn module(self, db: &dyn HirDatabase) -> Module {
2168        Module { id: self.id.module(db) }
2169    }
2170
2171    pub fn name(self, db: &dyn HirDatabase) -> Name {
2172        StaticSignature::of(db, self.id).name.clone()
2173    }
2174
2175    pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
2176        StaticSignature::of(db, self.id).flags.contains(StaticFlags::MUTABLE)
2177    }
2178
2179    pub fn value(self, db: &dyn HirDatabase) -> Option<ast::Expr> {
2180        self.source(db)?.value.body()
2181    }
2182
2183    pub fn ty(self, db: &dyn HirDatabase) -> Type<'_> {
2184        Type::from_value_def(db, self.id)
2185    }
2186
2187    pub fn extern_block(self, db: &dyn HirDatabase) -> Option<ExternBlock> {
2188        match self.id.lookup(db).container {
2189            ItemContainerId::ExternBlockId(id) => Some(ExternBlock { id }),
2190            _ => None,
2191        }
2192    }
2193
2194    /// Evaluate the static initializer.
2195    pub fn eval(self, db: &dyn HirDatabase) -> Result<EvaluatedConst<'_>, ConstEvalError<'_>> {
2196        let ty = db.value_ty(self.id.into()).unwrap().instantiate_identity().skip_norm_wip();
2197        db.const_eval_static(self.id).map(|it| EvaluatedConst {
2198            allocation: it,
2199            def: self.id.into(),
2200            ty,
2201        })
2202    }
2203}
2204
2205impl HasVisibility for Static {
2206    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
2207        let loc = self.id.lookup(db);
2208        let source = loc.source(db);
2209        visibility_from_ast(db, self.id, source.map(|src| src.visibility()))
2210    }
2211}
2212
2213#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2214pub struct Trait {
2215    pub(crate) id: TraitId,
2216}
2217
2218impl Trait {
2219    pub fn lang(db: &dyn HirDatabase, krate: Crate, lang_item: LangItem) -> Option<Trait> {
2220        let lang_items = hir_def::lang_item::lang_items(db, krate.id);
2221        match lang_item.from_lang_items(lang_items)? {
2222            LangItemTarget::TraitId(it) => Some(it.into()),
2223            _ => None,
2224        }
2225    }
2226
2227    pub fn module(self, db: &dyn HirDatabase) -> Module {
2228        Module { id: self.id.lookup(db).container }
2229    }
2230
2231    pub fn name(self, db: &dyn HirDatabase) -> Name {
2232        TraitSignature::of(db, self.id).name.clone()
2233    }
2234
2235    pub fn direct_supertraits(self, db: &dyn HirDatabase) -> Vec<Trait> {
2236        let traits = direct_super_traits(db, self.into());
2237        traits.iter().map(|tr| Trait::from(*tr)).collect()
2238    }
2239
2240    pub fn all_supertraits(self, db: &dyn HirDatabase) -> Vec<Trait> {
2241        let traits = all_super_traits(db, self.into());
2242        traits.iter().map(|tr| Trait::from(*tr)).collect()
2243    }
2244
2245    pub fn function(self, db: &dyn HirDatabase, name: impl PartialEq<Name>) -> Option<Function> {
2246        self.id.trait_items(db).items.iter().find(|(n, _)| name == *n).and_then(|&(_, it)| match it
2247        {
2248            AssocItemId::FunctionId(id) => Some(id.into()),
2249            _ => None,
2250        })
2251    }
2252
2253    pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
2254        self.id.trait_items(db).items.iter().map(|(_name, it)| (*it).into()).collect()
2255    }
2256
2257    pub fn items_with_supertraits(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
2258        self.all_supertraits(db).into_iter().flat_map(|tr| tr.items(db)).collect()
2259    }
2260
2261    pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
2262        TraitSignature::of(db, self.id).flags.contains(TraitFlags::AUTO)
2263    }
2264
2265    pub fn is_unsafe(&self, db: &dyn HirDatabase) -> bool {
2266        TraitSignature::of(db, self.id).flags.contains(TraitFlags::UNSAFE)
2267    }
2268
2269    pub fn type_or_const_param_count(
2270        &self,
2271        db: &dyn HirDatabase,
2272        count_required_only: bool,
2273    ) -> usize {
2274        GenericParams::of(db,self.id.into())
2275            .iter_type_or_consts()
2276            .filter(|(_, ty)| !matches!(ty, TypeOrConstParamData::TypeParamData(ty) if ty.provenance != TypeParamProvenance::TypeParamList))
2277            .filter(|(_, ty)| !count_required_only || !ty.has_default())
2278            .count()
2279    }
2280
2281    pub fn dyn_compatibility_violations(
2282        &self,
2283        db: &dyn HirDatabase,
2284    ) -> Vec<DynCompatibilityViolation> {
2285        match hir_ide::dyn_compatibility::dyn_compatibility_violations(db, self.id) {
2286            Some(violations) => DynCompatibilityViolation::multiple_from_hir(violations),
2287            None => Vec::new(),
2288        }
2289    }
2290
2291    /// `#[rust_analyzer::completions(...)]` mode.
2292    pub fn complete(self, db: &dyn HirDatabase) -> Complete {
2293        Complete::extract(true, self.attrs(db).attrs)
2294    }
2295
2296    // Feature: Prefer Underscore Import Attribute
2297    // Crate authors can declare that their trait prefers to be imported `as _`. This can be used
2298    // for example for extension traits. To do that, a trait has to include the attribute
2299    // `#[rust_analyzer::prefer_underscore_import]`
2300    //
2301    // When a trait includes this attribute, flyimport will import it `as _`, and the quickfix
2302    // to import it will prefer to import it `as _` (but allow to import it normally as well).
2303    //
2304    // Malformed attributes will be ignored without warnings.
2305    pub fn prefer_underscore_import(self, db: &dyn HirDatabase) -> bool {
2306        AttrFlags::query(db, self.id.into()).contains(AttrFlags::PREFER_UNDERSCORE_IMPORT)
2307    }
2308
2309    pub fn must_implement_one_of(self, db: &dyn HirDatabase) -> Option<&[Name]> {
2310        AttrFlags::must_implement_one_of(db, self.id)
2311    }
2312}
2313
2314#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2315pub enum DynCompatibilityViolation {
2316    ExplicitlyDynIncompatible,
2317    SizedSelf,
2318    SupertraitSelf,
2319    SupertraitNonLifetimeBinder,
2320    SupertraitConst,
2321    Method(Function, MethodViolation),
2322    AssocConst(Const, AssocConstViolation),
2323    GenericAssocTy(TypeAlias),
2324    HasNonCompatibleSuperTrait(Trait, Vec<DynCompatibilityViolation>),
2325}
2326
2327impl DynCompatibilityViolation {
2328    fn from_hir(violation: &hir_ide::dyn_compatibility::DynCompatibilityViolation) -> Self {
2329        use hir_ide::dyn_compatibility::DynCompatibilityViolation::*;
2330        match violation {
2331            ExplicitlyDynIncompatible => Self::ExplicitlyDynIncompatible,
2332            SizedSelf => Self::SizedSelf,
2333            SupertraitSelf => Self::SupertraitSelf,
2334            SupertraitNonLifetimeBinder => Self::SupertraitNonLifetimeBinder,
2335            SupertraitConst => Self::SupertraitConst,
2336            &Method(id, violation) => Self::Method(id.into(), violation),
2337            &AssocConst(id, violation) => Self::AssocConst(id.into(), violation),
2338            &GenericAssocTy(id) => Self::GenericAssocTy(id.into()),
2339            HasNonCompatibleSuperTrait(id, violations) => {
2340                Self::HasNonCompatibleSuperTrait((*id).into(), Self::multiple_from_hir(violations))
2341            }
2342        }
2343    }
2344
2345    fn multiple_from_hir(
2346        violations: &ThinArc<(), hir_ide::dyn_compatibility::DynCompatibilityViolation>,
2347    ) -> Vec<Self> {
2348        violations.slice.iter().map(Self::from_hir).collect()
2349    }
2350}
2351
2352impl HasVisibility for Trait {
2353    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
2354        let loc = self.id.lookup(db);
2355        let source = loc.source(db);
2356        visibility_from_ast(db, self.id, source.map(|src| src.visibility()))
2357    }
2358}
2359
2360#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2361pub struct TypeAlias {
2362    pub(crate) id: TypeAliasId,
2363}
2364
2365impl TypeAlias {
2366    pub fn has_non_default_type_params(self, db: &dyn HirDatabase) -> bool {
2367        has_non_default_type_params(db, self.id.into())
2368    }
2369
2370    pub fn module(self, db: &dyn HirDatabase) -> Module {
2371        Module { id: self.id.module(db) }
2372    }
2373
2374    pub fn ty(self, db: &dyn HirDatabase) -> Type<'_> {
2375        Type::from_def(db, self.id)
2376    }
2377
2378    pub fn name(self, db: &dyn HirDatabase) -> Name {
2379        TypeAliasSignature::of(db, self.id).name.clone()
2380    }
2381
2382    pub fn has_type(self, db: &dyn HirDatabase) -> bool {
2383        TypeAliasSignature::of(db, self.id).ty.is_some()
2384    }
2385}
2386
2387impl HasVisibility for TypeAlias {
2388    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
2389        AssocItemId::from(self.id).assoc_visibility(db)
2390    }
2391}
2392
2393#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2394pub struct ExternBlock {
2395    pub(crate) id: ExternBlockId,
2396}
2397
2398impl ExternBlock {
2399    pub fn module(self, db: &dyn HirDatabase) -> Module {
2400        Module { id: self.id.module(db) }
2401    }
2402}
2403
2404#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2405pub struct StaticLifetime;
2406
2407impl StaticLifetime {
2408    pub fn name(self) -> Name {
2409        Name::new_symbol_root(sym::tick_static)
2410    }
2411}
2412
2413#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2414pub struct BuiltinType {
2415    pub(crate) inner: hir_def::builtin_type::BuiltinType,
2416}
2417
2418impl BuiltinType {
2419    // Constructors are added on demand, feel free to add more.
2420    pub fn str() -> BuiltinType {
2421        BuiltinType { inner: hir_def::builtin_type::BuiltinType::Str }
2422    }
2423
2424    pub fn i32() -> BuiltinType {
2425        BuiltinType {
2426            inner: hir_def::builtin_type::BuiltinType::Int(hir_ide::primitive::BuiltinInt::I32),
2427        }
2428    }
2429
2430    pub fn bool() -> BuiltinType {
2431        BuiltinType { inner: hir_def::builtin_type::BuiltinType::Bool }
2432    }
2433
2434    pub fn ty<'db>(self, db: &'db dyn HirDatabase) -> Type<'db> {
2435        let interner = DbInterner::new_no_crate(db);
2436        Type::no_params(Type::builtin_type_crate(db), Ty::from_builtin_type(interner, self.inner))
2437    }
2438
2439    pub fn name(self) -> Name {
2440        self.inner.as_name()
2441    }
2442
2443    pub fn is_int(&self) -> bool {
2444        matches!(self.inner, hir_def::builtin_type::BuiltinType::Int(_))
2445    }
2446
2447    pub fn is_uint(&self) -> bool {
2448        matches!(self.inner, hir_def::builtin_type::BuiltinType::Uint(_))
2449    }
2450
2451    pub fn is_float(&self) -> bool {
2452        matches!(self.inner, hir_def::builtin_type::BuiltinType::Float(_))
2453    }
2454
2455    pub fn is_f16(&self) -> bool {
2456        matches!(
2457            self.inner,
2458            hir_def::builtin_type::BuiltinType::Float(hir_def::builtin_type::BuiltinFloat::F16)
2459        )
2460    }
2461
2462    pub fn is_f32(&self) -> bool {
2463        matches!(
2464            self.inner,
2465            hir_def::builtin_type::BuiltinType::Float(hir_def::builtin_type::BuiltinFloat::F32)
2466        )
2467    }
2468
2469    pub fn is_f64(&self) -> bool {
2470        matches!(
2471            self.inner,
2472            hir_def::builtin_type::BuiltinType::Float(hir_def::builtin_type::BuiltinFloat::F64)
2473        )
2474    }
2475
2476    pub fn is_f128(&self) -> bool {
2477        matches!(
2478            self.inner,
2479            hir_def::builtin_type::BuiltinType::Float(hir_def::builtin_type::BuiltinFloat::F128)
2480        )
2481    }
2482
2483    pub fn is_char(&self) -> bool {
2484        matches!(self.inner, hir_def::builtin_type::BuiltinType::Char)
2485    }
2486
2487    pub fn is_bool(&self) -> bool {
2488        matches!(self.inner, hir_def::builtin_type::BuiltinType::Bool)
2489    }
2490
2491    pub fn is_str(&self) -> bool {
2492        matches!(self.inner, hir_def::builtin_type::BuiltinType::Str)
2493    }
2494}
2495
2496#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2497pub struct Macro {
2498    pub(crate) id: MacroId,
2499}
2500
2501impl Macro {
2502    pub fn module(self, db: &dyn HirDatabase) -> Module {
2503        Module { id: self.id.module(db) }
2504    }
2505
2506    pub fn name(self, db: &dyn HirDatabase) -> Name {
2507        match self.id {
2508            MacroId::Macro2Id(id) => {
2509                let loc = id.lookup(db);
2510                let source = loc.source(db);
2511                as_name_opt(source.value.name())
2512            }
2513            MacroId::MacroRulesId(id) => {
2514                let loc = id.lookup(db);
2515                let source = loc.source(db);
2516                as_name_opt(source.value.name())
2517            }
2518            MacroId::ProcMacroId(id) => {
2519                let loc = id.lookup(db);
2520                let source = loc.source(db);
2521                match loc.kind {
2522                    ProcMacroKind::CustomDerive => AttrFlags::derive_info(db, self.id).map_or_else(
2523                        || as_name_opt(source.value.name()),
2524                        |info| Name::new_symbol_root(info.trait_name.clone()),
2525                    ),
2526                    ProcMacroKind::Bang | ProcMacroKind::Attr => as_name_opt(source.value.name()),
2527                }
2528            }
2529        }
2530    }
2531
2532    pub fn is_proc_macro(self) -> bool {
2533        matches!(self.id, MacroId::ProcMacroId(_))
2534    }
2535
2536    pub fn kind(&self, db: &dyn HirDatabase) -> MacroKind {
2537        match self.id {
2538            MacroId::Macro2Id(it) => match it.lookup(db).expander {
2539                MacroExpander::Declarative { .. } => MacroKind::Declarative,
2540                MacroExpander::BuiltIn(_) | MacroExpander::BuiltInEager(_) => {
2541                    MacroKind::DeclarativeBuiltIn
2542                }
2543                MacroExpander::BuiltInAttr(_) => MacroKind::AttrBuiltIn,
2544                MacroExpander::BuiltInDerive(_) => MacroKind::DeriveBuiltIn,
2545                MacroExpander::UnimplementedBuiltIn => MacroKind::Declarative,
2546            },
2547            MacroId::MacroRulesId(it) => match it.lookup(db).expander {
2548                MacroExpander::Declarative { .. } => MacroKind::Declarative,
2549                MacroExpander::BuiltIn(_) | MacroExpander::BuiltInEager(_) => {
2550                    MacroKind::DeclarativeBuiltIn
2551                }
2552                MacroExpander::BuiltInAttr(_) => MacroKind::AttrBuiltIn,
2553                MacroExpander::BuiltInDerive(_) => MacroKind::DeriveBuiltIn,
2554                MacroExpander::UnimplementedBuiltIn => MacroKind::Declarative,
2555            },
2556            MacroId::ProcMacroId(it) => match it.lookup(db).kind {
2557                ProcMacroKind::CustomDerive => MacroKind::Derive,
2558                ProcMacroKind::Bang => MacroKind::ProcMacro,
2559                ProcMacroKind::Attr => MacroKind::Attr,
2560            },
2561        }
2562    }
2563
2564    pub fn is_fn_like(&self, db: &dyn HirDatabase) -> bool {
2565        matches!(
2566            self.kind(db),
2567            MacroKind::Declarative | MacroKind::DeclarativeBuiltIn | MacroKind::ProcMacro
2568        )
2569    }
2570
2571    pub fn builtin_derive_kind(&self, db: &dyn HirDatabase) -> Option<BuiltinDeriveMacroKind> {
2572        let expander = match self.id {
2573            MacroId::Macro2Id(it) => it.lookup(db).expander,
2574            MacroId::MacroRulesId(it) => it.lookup(db).expander,
2575            MacroId::ProcMacroId(_) => return None,
2576        };
2577        match expander {
2578            MacroExpander::BuiltInDerive(kind) => Some(BuiltinDeriveMacroKind(kind)),
2579            _ => None,
2580        }
2581    }
2582
2583    pub fn is_env_or_option_env(&self, db: &dyn HirDatabase) -> bool {
2584        match self.id {
2585            MacroId::Macro2Id(it) => {
2586                matches!(it.lookup(db).expander, MacroExpander::BuiltInEager(eager) if eager.is_env_or_option_env())
2587            }
2588            MacroId::MacroRulesId(it) => {
2589                matches!(it.lookup(db).expander, MacroExpander::BuiltInEager(eager) if eager.is_env_or_option_env())
2590            }
2591            MacroId::ProcMacroId(_) => false,
2592        }
2593    }
2594
2595    /// Is this `asm!()`, or a variant of it (e.g. `global_asm!()`)?
2596    pub fn is_asm_like(&self, db: &dyn HirDatabase) -> bool {
2597        match self.id {
2598            MacroId::Macro2Id(it) => {
2599                matches!(it.lookup(db).expander, MacroExpander::BuiltIn(m) if m.is_asm())
2600            }
2601            MacroId::MacroRulesId(it) => {
2602                matches!(it.lookup(db).expander, MacroExpander::BuiltIn(m) if m.is_asm())
2603            }
2604            MacroId::ProcMacroId(_) => false,
2605        }
2606    }
2607
2608    pub fn is_attr(&self, db: &dyn HirDatabase) -> bool {
2609        matches!(self.kind(db), MacroKind::Attr | MacroKind::AttrBuiltIn)
2610    }
2611
2612    pub fn is_derive(&self, db: &dyn HirDatabase) -> bool {
2613        matches!(self.kind(db), MacroKind::Derive | MacroKind::DeriveBuiltIn)
2614    }
2615
2616    pub fn preferred_brace_style(&self, db: &dyn HirDatabase) -> Option<MacroBraces> {
2617        let attrs = self.attrs(db);
2618        MacroBraces::extract(attrs.attrs)
2619    }
2620}
2621
2622// Feature: Macro Brace Style Attribute
2623// Crate authors can declare the preferred brace style for their macro. This will affect how completion
2624// insert calls to it.
2625//
2626// This is only supported on function-like macros.
2627//
2628// To do that, insert the `#[rust_analyzer::macro_style(style)]` attribute on the macro (for proc macros,
2629// insert it for the macro's function). `style` can be one of:
2630//
2631//  - `braces` for `{...}` style.
2632//  - `brackets` for `[...]` style.
2633//  - `parentheses` for `(...)` style.
2634//
2635// Malformed attributes will be ignored without warnings.
2636//
2637// Note that users have no way to override this attribute, so be careful and only include things
2638// users definitely do not want to be completed!
2639
2640#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2641pub enum MacroBraces {
2642    Braces,
2643    Brackets,
2644    Parentheses,
2645}
2646
2647impl MacroBraces {
2648    fn extract(attrs: AttrFlags) -> Option<Self> {
2649        if attrs.contains(AttrFlags::MACRO_STYLE_BRACES) {
2650            Some(Self::Braces)
2651        } else if attrs.contains(AttrFlags::MACRO_STYLE_BRACKETS) {
2652            Some(Self::Brackets)
2653        } else if attrs.contains(AttrFlags::MACRO_STYLE_PARENTHESES) {
2654            Some(Self::Parentheses)
2655        } else {
2656            None
2657        }
2658    }
2659}
2660
2661#[derive(Clone, Copy, PartialEq, Eq, Hash)]
2662pub struct BuiltinDeriveMacroKind(BuiltinDeriveExpander);
2663
2664impl HasVisibility for Macro {
2665    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
2666        match self.id {
2667            MacroId::Macro2Id(id) => {
2668                let loc = id.lookup(db);
2669                let source = loc.source(db);
2670                visibility_from_ast(db, id, source.map(|src| src.visibility()))
2671            }
2672            MacroId::MacroRulesId(id) => {
2673                if AttrFlags::query(db, id.into()).contains(AttrFlags::IS_MACRO_EXPORT) {
2674                    Visibility::Public
2675                } else {
2676                    Visibility::PubCrate(self.krate(db).id)
2677                }
2678            }
2679            MacroId::ProcMacroId(_) => Visibility::Public,
2680        }
2681    }
2682}
2683
2684#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
2685pub enum ItemInNs {
2686    Types(ModuleDef),
2687    Values(ModuleDef),
2688    Macros(Macro),
2689}
2690
2691impl From<Macro> for ItemInNs {
2692    fn from(it: Macro) -> Self {
2693        Self::Macros(it)
2694    }
2695}
2696
2697impl_from!(
2698    ModuleDef {
2699        Module => Types,
2700        Function => Values,
2701        Adt => Types,
2702        EnumVariant => Types,
2703        Const => Values,
2704        Static => Values,
2705        Trait => Types,
2706        TypeAlias => Types,
2707        BuiltinType => Types,
2708        Macro => Macros,
2709    }
2710    for ItemInNs
2711);
2712
2713impl ItemInNs {
2714    pub fn into_module_def(self) -> ModuleDef {
2715        match self {
2716            ItemInNs::Types(id) | ItemInNs::Values(id) => id,
2717            ItemInNs::Macros(id) => ModuleDef::Macro(id),
2718        }
2719    }
2720
2721    /// Returns the crate defining this item (or `None` if `self` is built-in).
2722    pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
2723        match self {
2724            ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate(db)),
2725            ItemInNs::Macros(id) => Some(id.module(db).krate(db)),
2726        }
2727    }
2728
2729    pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
2730        match self {
2731            ItemInNs::Types(it) | ItemInNs::Values(it) => it.attrs(db),
2732            ItemInNs::Macros(it) => Some(it.attrs(db)),
2733        }
2734    }
2735}
2736
2737/// Invariant: `inner.as_extern_assoc_item(db).is_some()`
2738/// We do not actively enforce this invariant.
2739#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2740pub enum ExternAssocItem {
2741    Function(Function),
2742    Static(Static),
2743    TypeAlias(TypeAlias),
2744}
2745
2746pub trait AsExternAssocItem {
2747    fn as_extern_assoc_item(self, db: &dyn HirDatabase) -> Option<ExternAssocItem>;
2748}
2749
2750impl AsExternAssocItem for Function {
2751    fn as_extern_assoc_item(self, db: &dyn HirDatabase) -> Option<ExternAssocItem> {
2752        let AnyFunctionId::FunctionId(id) = self.id else {
2753            return None;
2754        };
2755        as_extern_assoc_item(db, ExternAssocItem::Function, id)
2756    }
2757}
2758
2759impl AsExternAssocItem for Static {
2760    fn as_extern_assoc_item(self, db: &dyn HirDatabase) -> Option<ExternAssocItem> {
2761        as_extern_assoc_item(db, ExternAssocItem::Static, self.id)
2762    }
2763}
2764
2765impl AsExternAssocItem for TypeAlias {
2766    fn as_extern_assoc_item(self, db: &dyn HirDatabase) -> Option<ExternAssocItem> {
2767        as_extern_assoc_item(db, ExternAssocItem::TypeAlias, self.id)
2768    }
2769}
2770
2771/// Invariant: `inner.as_assoc_item(db).is_some()`
2772/// We do not actively enforce this invariant.
2773#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
2774pub enum AssocItem {
2775    Function(Function),
2776    Const(Const),
2777    TypeAlias(TypeAlias),
2778}
2779
2780impl From<method_resolution::CandidateId> for AssocItem {
2781    fn from(value: method_resolution::CandidateId) -> Self {
2782        match value {
2783            method_resolution::CandidateId::FunctionId(id) => AssocItem::Function(id.into()),
2784            method_resolution::CandidateId::ConstId(id) => AssocItem::Const(Const { id }),
2785        }
2786    }
2787}
2788
2789#[derive(Debug, Clone)]
2790pub enum AssocItemContainer {
2791    Trait(Trait),
2792    Impl(Impl),
2793}
2794
2795pub trait AsAssocItem {
2796    fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem>;
2797}
2798
2799impl AsAssocItem for Function {
2800    fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2801        match self.id {
2802            AnyFunctionId::FunctionId(id) => as_assoc_item(db, AssocItem::Function, id),
2803            AnyFunctionId::BuiltinDeriveImplMethod { .. } => Some(AssocItem::Function(self)),
2804        }
2805    }
2806}
2807
2808impl AsAssocItem for Const {
2809    fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2810        as_assoc_item(db, AssocItem::Const, self.id)
2811    }
2812}
2813
2814impl AsAssocItem for TypeAlias {
2815    fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2816        as_assoc_item(db, AssocItem::TypeAlias, self.id)
2817    }
2818}
2819
2820impl AsAssocItem for ModuleDef {
2821    fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2822        match self {
2823            ModuleDef::Function(it) => it.as_assoc_item(db),
2824            ModuleDef::Const(it) => it.as_assoc_item(db),
2825            ModuleDef::TypeAlias(it) => it.as_assoc_item(db),
2826            _ => None,
2827        }
2828    }
2829}
2830
2831impl AsAssocItem for DefWithBody {
2832    fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2833        match self {
2834            DefWithBody::Function(it) => it.as_assoc_item(db),
2835            DefWithBody::Const(it) => it.as_assoc_item(db),
2836            DefWithBody::Static(_) | DefWithBody::EnumVariant(_) => None,
2837        }
2838    }
2839}
2840
2841impl AsAssocItem for GenericDef {
2842    fn as_assoc_item(self, db: &dyn HirDatabase) -> Option<AssocItem> {
2843        match self {
2844            GenericDef::Function(it) => it.as_assoc_item(db),
2845            GenericDef::Const(it) => it.as_assoc_item(db),
2846            GenericDef::TypeAlias(it) => it.as_assoc_item(db),
2847            _ => None,
2848        }
2849    }
2850}
2851
2852fn as_assoc_item<'db, ID, DEF, LOC>(
2853    db: &(dyn HirDatabase + 'db),
2854    ctor: impl FnOnce(DEF) -> AssocItem,
2855    id: ID,
2856) -> Option<AssocItem>
2857where
2858    ID: Lookup<Data = AssocItemLoc<LOC>>,
2859    DEF: From<ID>,
2860    LOC: AstIdNode,
2861{
2862    match id.lookup(db).container {
2863        ItemContainerId::TraitId(_) | ItemContainerId::ImplId(_) => Some(ctor(DEF::from(id))),
2864        ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => None,
2865    }
2866}
2867
2868fn as_extern_assoc_item<'db, ID, DEF, LOC>(
2869    db: &(dyn HirDatabase + 'db),
2870    ctor: impl FnOnce(DEF) -> ExternAssocItem,
2871    id: ID,
2872) -> Option<ExternAssocItem>
2873where
2874    ID: Lookup<Data = AssocItemLoc<LOC>>,
2875    DEF: From<ID>,
2876    LOC: AstIdNode,
2877{
2878    match id.lookup(db).container {
2879        ItemContainerId::ExternBlockId(_) => Some(ctor(DEF::from(id))),
2880        ItemContainerId::TraitId(_) | ItemContainerId::ImplId(_) | ItemContainerId::ModuleId(_) => {
2881            None
2882        }
2883    }
2884}
2885
2886impl ExternAssocItem {
2887    pub fn name(self, db: &dyn HirDatabase) -> Name {
2888        match self {
2889            Self::Function(it) => it.name(db),
2890            Self::Static(it) => it.name(db),
2891            Self::TypeAlias(it) => it.name(db),
2892        }
2893    }
2894
2895    pub fn module(self, db: &dyn HirDatabase) -> Module {
2896        match self {
2897            Self::Function(f) => f.module(db),
2898            Self::Static(c) => c.module(db),
2899            Self::TypeAlias(t) => t.module(db),
2900        }
2901    }
2902
2903    pub fn as_function(self) -> Option<Function> {
2904        match self {
2905            Self::Function(v) => Some(v),
2906            _ => None,
2907        }
2908    }
2909
2910    pub fn as_static(self) -> Option<Static> {
2911        match self {
2912            Self::Static(v) => Some(v),
2913            _ => None,
2914        }
2915    }
2916
2917    pub fn as_type_alias(self) -> Option<TypeAlias> {
2918        match self {
2919            Self::TypeAlias(v) => Some(v),
2920            _ => None,
2921        }
2922    }
2923}
2924
2925impl AssocItem {
2926    pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
2927        match self {
2928            AssocItem::Function(it) => Some(it.name(db)),
2929            AssocItem::Const(it) => it.name(db),
2930            AssocItem::TypeAlias(it) => Some(it.name(db)),
2931        }
2932    }
2933
2934    pub fn module(self, db: &dyn HirDatabase) -> Module {
2935        match self {
2936            AssocItem::Function(f) => f.module(db),
2937            AssocItem::Const(c) => c.module(db),
2938            AssocItem::TypeAlias(t) => t.module(db),
2939        }
2940    }
2941
2942    pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer {
2943        let container = match self {
2944            AssocItem::Function(it) => match it.id {
2945                AnyFunctionId::FunctionId(id) => id.lookup(db).container,
2946                AnyFunctionId::BuiltinDeriveImplMethod { impl_, .. } => {
2947                    return AssocItemContainer::Impl(Impl {
2948                        id: AnyImplId::BuiltinDeriveImplId(impl_),
2949                    });
2950                }
2951            },
2952            AssocItem::Const(it) => it.id.lookup(db).container,
2953            AssocItem::TypeAlias(it) => it.id.lookup(db).container,
2954        };
2955        match container {
2956            ItemContainerId::TraitId(id) => AssocItemContainer::Trait(id.into()),
2957            ItemContainerId::ImplId(id) => AssocItemContainer::Impl(id.into()),
2958            ItemContainerId::ModuleId(_) | ItemContainerId::ExternBlockId(_) => {
2959                panic!("invalid AssocItem")
2960            }
2961        }
2962    }
2963
2964    pub fn container_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
2965        match self.container(db) {
2966            AssocItemContainer::Trait(t) => Some(t),
2967            _ => None,
2968        }
2969    }
2970
2971    pub fn implemented_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
2972        match self.container(db) {
2973            AssocItemContainer::Impl(i) => i.trait_(db),
2974            _ => None,
2975        }
2976    }
2977
2978    pub fn container_or_implemented_trait(self, db: &dyn HirDatabase) -> Option<Trait> {
2979        match self.container(db) {
2980            AssocItemContainer::Trait(t) => Some(t),
2981            AssocItemContainer::Impl(i) => i.trait_(db),
2982        }
2983    }
2984
2985    pub fn implementing_ty(self, db: &dyn HirDatabase) -> Option<Type<'_>> {
2986        match self.container(db) {
2987            AssocItemContainer::Impl(i) => Some(i.self_ty(db)),
2988            _ => None,
2989        }
2990    }
2991
2992    pub fn as_function(self) -> Option<Function> {
2993        match self {
2994            Self::Function(v) => Some(v),
2995            _ => None,
2996        }
2997    }
2998
2999    pub fn as_const(self) -> Option<Const> {
3000        match self {
3001            Self::Const(v) => Some(v),
3002            _ => None,
3003        }
3004    }
3005
3006    pub fn as_type_alias(self) -> Option<TypeAlias> {
3007        match self {
3008            Self::TypeAlias(v) => Some(v),
3009            _ => None,
3010        }
3011    }
3012}
3013
3014impl HasVisibility for AssocItem {
3015    fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
3016        match self {
3017            AssocItem::Function(f) => f.visibility(db),
3018            AssocItem::Const(c) => c.visibility(db),
3019            AssocItem::TypeAlias(t) => t.visibility(db),
3020        }
3021    }
3022}
3023
3024impl_from!(AssocItem { Function, Const, TypeAlias } for ModuleDef);
3025
3026#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
3027pub enum GenericDef {
3028    Function(Function),
3029    Adt(Adt),
3030    Trait(Trait),
3031    TypeAlias(TypeAlias),
3032    Impl(Impl),
3033    // consts can have type parameters from their parents (i.e. associated consts of traits)
3034    Const(Const),
3035    Static(Static),
3036}
3037impl_from!(
3038    Function,
3039    Adt(Struct, Enum, Union),
3040    Trait,
3041    TypeAlias,
3042    Impl,
3043    Const,
3044    Static
3045    for GenericDef
3046);
3047
3048impl GenericDef {
3049    pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
3050        match self {
3051            GenericDef::Function(it) => Some(it.name(db)),
3052            GenericDef::Adt(it) => Some(it.name(db)),
3053            GenericDef::Trait(it) => Some(it.name(db)),
3054            GenericDef::TypeAlias(it) => Some(it.name(db)),
3055            GenericDef::Impl(_) => None,
3056            GenericDef::Const(it) => it.name(db),
3057            GenericDef::Static(it) => Some(it.name(db)),
3058        }
3059    }
3060
3061    pub fn module(self, db: &dyn HirDatabase) -> Module {
3062        match self {
3063            GenericDef::Function(it) => it.module(db),
3064            GenericDef::Adt(it) => it.module(db),
3065            GenericDef::Trait(it) => it.module(db),
3066            GenericDef::TypeAlias(it) => it.module(db),
3067            GenericDef::Impl(it) => it.module(db),
3068            GenericDef::Const(it) => it.module(db),
3069            GenericDef::Static(it) => it.module(db),
3070        }
3071    }
3072
3073    pub fn params(self, db: &dyn HirDatabase) -> Vec<GenericParam> {
3074        let Ok(id) = self.try_into() else {
3075            // Let's pretend builtin derive impls don't have generic parameters.
3076            return Vec::new();
3077        };
3078        let generics = GenericParams::of(db, id);
3079        let ty_params = generics.iter_type_or_consts().map(|(local_id, _)| {
3080            let toc = TypeOrConstParam { id: TypeOrConstParamId { parent: id, local_id } };
3081            match toc.split(db) {
3082                Either::Left(it) => GenericParam::ConstParam(it),
3083                Either::Right(it) => GenericParam::TypeParam(it),
3084            }
3085        });
3086        self.lifetime_params(db)
3087            .into_iter()
3088            .map(GenericParam::LifetimeParam)
3089            .chain(ty_params)
3090            .collect()
3091    }
3092
3093    pub fn lifetime_params(self, db: &dyn HirDatabase) -> Vec<LifetimeParam> {
3094        let Ok(id) = self.try_into() else {
3095            // Let's pretend builtin derive impls don't have generic parameters.
3096            return Vec::new();
3097        };
3098        let generics = GenericParams::of(db, id);
3099        generics
3100            .iter_lt()
3101            .map(|(local_id, _)| LifetimeParam { id: LifetimeParamId { parent: id, local_id } })
3102            .collect()
3103    }
3104
3105    pub fn type_or_const_params(self, db: &dyn HirDatabase) -> Vec<TypeOrConstParam> {
3106        let Ok(id) = self.try_into() else {
3107            // Let's pretend builtin derive impls don't have generic parameters.
3108            return Vec::new();
3109        };
3110        let generics = GenericParams::of(db, id);
3111        generics
3112            .iter_type_or_consts()
3113            .map(|(local_id, _)| TypeOrConstParam {
3114                id: TypeOrConstParamId { parent: id, local_id },
3115            })
3116            .collect()
3117    }
3118
3119    fn id(self) -> Option<GenericDefId> {
3120        Some(match self {
3121            GenericDef::Function(it) => match it.id {
3122                AnyFunctionId::FunctionId(it) => it.into(),
3123                AnyFunctionId::BuiltinDeriveImplMethod { .. } => return None,
3124            },
3125            GenericDef::Adt(it) => it.into(),
3126            GenericDef::Trait(it) => it.id.into(),
3127            GenericDef::TypeAlias(it) => it.id.into(),
3128            GenericDef::Impl(it) => match it.id {
3129                AnyImplId::ImplId(it) => it.into(),
3130                AnyImplId::BuiltinDeriveImplId(_) => return None,
3131            },
3132            GenericDef::Const(it) => it.id.into(),
3133            GenericDef::Static(it) => it.id.into(),
3134        })
3135    }
3136
3137    /// Returns a string describing the kind of this type.
3138    #[inline]
3139    pub fn description(self) -> &'static str {
3140        match self {
3141            GenericDef::Function(_) => "function",
3142            GenericDef::Adt(Adt::Struct(_)) => "struct",
3143            GenericDef::Adt(Adt::Enum(_)) => "enum",
3144            GenericDef::Adt(Adt::Union(_)) => "union",
3145            GenericDef::Trait(_) => "trait",
3146            GenericDef::TypeAlias(_) => "type alias",
3147            GenericDef::Impl(_) => "impl",
3148            GenericDef::Const(_) => "constant",
3149            GenericDef::Static(_) => "static",
3150        }
3151    }
3152}
3153
3154// We cannot call this `Substitution` unfortunately...
3155#[derive(Debug)]
3156pub struct GenericSubstitution<'db> {
3157    owner: TypeOwnerId,
3158    def: GenericDefId,
3159    subst: GenericArgs<'db>,
3160}
3161
3162impl<'db> GenericSubstitution<'db> {
3163    fn new(def: GenericDefId, subst: GenericArgs<'db>, owner: TypeOwnerId) -> Self {
3164        Self { owner, def, subst }
3165    }
3166
3167    fn new_from_fn(def: Function, subst: GenericArgs<'db>, owner: TypeOwnerId) -> Option<Self> {
3168        match def.id {
3169            AnyFunctionId::FunctionId(def) => Some(Self::new(def.into(), subst, owner)),
3170            AnyFunctionId::BuiltinDeriveImplMethod { .. } => None,
3171        }
3172    }
3173
3174    fn types_impl(
3175        &self,
3176        db: &'db dyn HirDatabase,
3177    ) -> impl Iterator<Item = (Ty<'db>, Option<Name>)> {
3178        let container = match self.def {
3179            GenericDefId::ConstId(id) => Some(id.lookup(db).container),
3180            GenericDefId::FunctionId(id) => Some(id.lookup(db).container),
3181            GenericDefId::TypeAliasId(id) => Some(id.lookup(db).container),
3182            _ => None,
3183        };
3184        let container_type_params = container
3185            .and_then(|container| match container {
3186                ItemContainerId::ImplId(container) => Some(container.into()),
3187                ItemContainerId::TraitId(container) => Some(container.into()),
3188                _ => None,
3189            })
3190            .map(|container| {
3191                GenericParams::of(db, container)
3192                    .iter_type_or_consts()
3193                    .filter_map(|param| match param.1 {
3194                        TypeOrConstParamData::TypeParamData(param) => Some(param.name.clone()),
3195                        TypeOrConstParamData::ConstParamData(_) => None,
3196                    })
3197                    .collect::<Vec<_>>()
3198            });
3199        let generics = GenericParams::of(db, self.def);
3200        let type_params = generics.iter_type_or_consts().filter_map(|param| match param.1 {
3201            TypeOrConstParamData::TypeParamData(param) => Some(param.name.clone()),
3202            TypeOrConstParamData::ConstParamData(_) => None,
3203        });
3204        self.subst.types().zip(container_type_params.into_iter().flatten().chain(type_params))
3205    }
3206
3207    /// Returns type arguments with type parameter names.
3208    pub fn types(&self, db: &'db dyn HirDatabase) -> Vec<(Symbol, Type<'db>)> {
3209        self.types_impl(db)
3210            .filter_map(|(ty, name)| {
3211                Some((
3212                    name?.symbol().clone(),
3213                    Type { ty: EarlyBinder::bind(ty), owner: self.owner },
3214                ))
3215            })
3216            .collect()
3217    }
3218
3219    /// Returns all type arguments, including unnamed ones such as implicit `impl Trait` parameters.
3220    ///
3221    /// Unlike [`Self::types`], this does not filter out arguments that have no
3222    /// corresponding type parameter name.
3223    // Note: this method is not used by rust-analyzer itself as of writing, but is
3224    // used by external tools, so please do not remove it even if it appears unused.
3225    pub fn all_types(&self, db: &'db dyn HirDatabase) -> Vec<Type<'db>> {
3226        self.types_impl(db)
3227            .map(|(ty, _)| Type { ty: EarlyBinder::bind(ty), owner: self.owner })
3228            .collect()
3229    }
3230}
3231
3232/// A single local definition.
3233#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3234pub struct Local<'db> {
3235    pub(crate) parent: ExpressionStoreOwnerId,
3236    pub(crate) parent_infer: InferBodyId<'db>,
3237    pub(crate) binding_id: BindingId,
3238}
3239
3240pub struct LocalSource<'db> {
3241    pub local: Local<'db>,
3242    pub source: InFile<Either<ast::IdentPat, ast::SelfParam>>,
3243}
3244
3245impl<'db> LocalSource<'db> {
3246    pub fn as_ident_pat(&self) -> Option<&ast::IdentPat> {
3247        match &self.source.value {
3248            Either::Left(it) => Some(it),
3249            Either::Right(_) => None,
3250        }
3251    }
3252
3253    pub fn into_ident_pat(self) -> Option<ast::IdentPat> {
3254        match self.source.value {
3255            Either::Left(it) => Some(it),
3256            Either::Right(_) => None,
3257        }
3258    }
3259
3260    pub fn original_file(&self, db: &dyn HirDatabase) -> EditionedFileId {
3261        self.source.file_id.original_file(db)
3262    }
3263
3264    pub fn file(&self) -> HirFileId {
3265        self.source.file_id
3266    }
3267
3268    pub fn name(&self) -> Option<InFile<ast::Name>> {
3269        self.source.as_ref().map(|it| it.name()).transpose()
3270    }
3271
3272    pub fn syntax(&self) -> &SyntaxNode {
3273        self.source.value.syntax()
3274    }
3275
3276    pub fn syntax_ptr(self) -> InFile<SyntaxNodePtr> {
3277        self.source.map(|it| SyntaxNodePtr::new(it.syntax()))
3278    }
3279}
3280
3281impl<'db> Local<'db> {
3282    pub fn is_param(self, db: &dyn HirDatabase) -> bool {
3283        // FIXME: This parses!
3284        let src = self.primary_source(db);
3285        match src.source.value {
3286            Either::Left(pat) => pat
3287                .syntax()
3288                .ancestors()
3289                .map(|it| it.kind())
3290                .take_while(|&kind| ast::Pat::can_cast(kind) || ast::Param::can_cast(kind))
3291                .any(ast::Param::can_cast),
3292            Either::Right(_) => true,
3293        }
3294    }
3295
3296    pub fn as_self_param(self, db: &dyn HirDatabase) -> Option<SelfParam> {
3297        match self.parent {
3298            ExpressionStoreOwnerId::Body(DefWithBodyId::FunctionId(func)) if self.is_self(db) => {
3299                Some(SelfParam { func: func.into() })
3300            }
3301            _ => None,
3302        }
3303    }
3304
3305    pub fn name(self, db: &dyn HirDatabase) -> Name {
3306        ExpressionStore::of(db, self.parent)[self.binding_id].name.clone()
3307    }
3308
3309    pub fn is_self(self, db: &dyn HirDatabase) -> bool {
3310        self.name(db) == sym::self_
3311    }
3312
3313    pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
3314        ExpressionStore::of(db, self.parent)[self.binding_id].mode == BindingAnnotation::Mutable
3315    }
3316
3317    pub fn is_ref(self, db: &dyn HirDatabase) -> bool {
3318        matches!(
3319            ExpressionStore::of(db, self.parent)[self.binding_id].mode,
3320            BindingAnnotation::Ref | BindingAnnotation::RefMut
3321        )
3322    }
3323
3324    pub fn parent(self, _db: &dyn HirDatabase) -> ExpressionStoreOwner {
3325        self.parent.into()
3326    }
3327
3328    pub fn module(self, db: &dyn HirDatabase) -> Module {
3329        self.parent(db).module(db)
3330    }
3331
3332    pub fn as_id(self) -> u32 {
3333        self.binding_id.into_raw().into_u32()
3334    }
3335
3336    pub fn ty(self, db: &'db dyn HirDatabase) -> Type<'db> {
3337        let def = self.parent;
3338        let infer = InferenceResult::of(db, self.parent_infer);
3339        let ty = infer.binding_ty(self.binding_id);
3340        Type::new_body(db, def, ty)
3341    }
3342
3343    /// All definitions for this local. Example: `let (a$0, _) | (_, a$0) = it;`
3344    pub fn sources(self, db: &dyn HirDatabase) -> Vec<LocalSource<'db>> {
3345        let b;
3346        let (_, source_map) = match self.parent {
3347            ExpressionStoreOwnerId::Signature(generic_def_id) => {
3348                ExpressionStore::with_source_map(db, generic_def_id.into())
3349            }
3350            ExpressionStoreOwnerId::Body(def_with_body_id) => {
3351                b = Body::with_source_map(db, def_with_body_id);
3352                if b.0.is_any_self_param(self.binding_id)
3353                    && let Some(source) = b.1.self_param_syntax()
3354                {
3355                    let root = source.file_syntax(db);
3356                    return vec![LocalSource {
3357                        local: self,
3358                        source: source.map(|ast| Either::Right(ast.to_node(&root))),
3359                    }];
3360                }
3361                (&b.0.store, &b.1.store)
3362            }
3363            ExpressionStoreOwnerId::VariantFields(def) => {
3364                ExpressionStore::with_source_map(db, def.into())
3365            }
3366        };
3367        source_map
3368            .patterns_for_binding(self.binding_id)
3369            .iter()
3370            .map(|&definition| {
3371                let src = source_map.pat_syntax(definition).unwrap(); // Hmm...
3372                let root = src.file_syntax(db);
3373                LocalSource {
3374                    local: self,
3375                    source: src.map(|ast| match ast.to_node(&root) {
3376                        Either::Right(ast::Pat::IdentPat(it)) => Either::Left(it),
3377                        _ => unreachable!("local with non ident-pattern"),
3378                    }),
3379                }
3380            })
3381            .collect()
3382    }
3383
3384    /// The leftmost definition for this local. Example: `let (a$0, _) | (_, a) = it;`
3385    pub fn primary_source(self, db: &dyn HirDatabase) -> LocalSource<'db> {
3386        let b;
3387        let (_, source_map) = match self.parent {
3388            ExpressionStoreOwnerId::Signature(generic_def_id) => {
3389                ExpressionStore::with_source_map(db, generic_def_id.into())
3390            }
3391            ExpressionStoreOwnerId::Body(def_with_body_id) => {
3392                b = Body::with_source_map(db, def_with_body_id);
3393                if b.0.is_any_self_param(self.binding_id)
3394                    && let Some(source) = b.1.self_param_syntax()
3395                {
3396                    let root = source.file_syntax(db);
3397                    return LocalSource {
3398                        local: self,
3399                        source: source.map(|ast| Either::Right(ast.to_node(&root))),
3400                    };
3401                }
3402                (&b.0.store, &b.1.store)
3403            }
3404            ExpressionStoreOwnerId::VariantFields(def) => {
3405                ExpressionStore::with_source_map(db, def.into())
3406            }
3407        };
3408        source_map
3409            .patterns_for_binding(self.binding_id)
3410            .first()
3411            .map(|&definition| {
3412                let src = source_map.pat_syntax(definition).unwrap(); // Hmm...
3413                let root = src.file_syntax(db);
3414                LocalSource {
3415                    local: self,
3416                    source: src.map(|ast| match ast.to_node(&root) {
3417                        Either::Right(ast::Pat::IdentPat(it)) => Either::Left(it),
3418                        _ => unreachable!("local with non ident-pattern"),
3419                    }),
3420                }
3421            })
3422            .unwrap()
3423    }
3424}
3425
3426impl PartialOrd for Local<'_> {
3427    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
3428        Some(self.cmp(other))
3429    }
3430}
3431
3432impl Ord for Local<'_> {
3433    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
3434        self.binding_id.cmp(&other.binding_id)
3435    }
3436}
3437
3438#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3439pub struct DeriveHelper {
3440    pub(crate) derive: MacroId,
3441    pub(crate) idx: u32,
3442}
3443
3444impl DeriveHelper {
3445    pub fn derive(&self) -> Macro {
3446        Macro { id: self.derive }
3447    }
3448
3449    pub fn name(&self, db: &dyn HirDatabase) -> Name {
3450        AttrFlags::derive_info(db, self.derive)
3451            .and_then(|it| it.helpers.get(self.idx as usize))
3452            .map(|helper| Name::new_symbol_root(helper.clone()))
3453            .unwrap_or_else(Name::missing)
3454    }
3455}
3456
3457#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3458pub struct BuiltinAttr {
3459    idx: u32,
3460}
3461
3462impl BuiltinAttr {
3463    fn builtin(name: &str) -> Option<Self> {
3464        hir_expand::inert_attr_macro::find_builtin_attr_idx(&Symbol::intern(name))
3465            .map(|idx| BuiltinAttr { idx: idx as u32 })
3466    }
3467
3468    pub fn name(&self) -> Name {
3469        Name::new_symbol_root(Symbol::intern(
3470            hir_expand::inert_attr_macro::INERT_ATTRIBUTES[self.idx as usize].name,
3471        ))
3472    }
3473
3474    pub fn template(&self) -> Option<AttributeTemplate> {
3475        Some(hir_expand::inert_attr_macro::INERT_ATTRIBUTES[self.idx as usize].template)
3476    }
3477}
3478
3479#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3480pub struct ToolModule {
3481    krate: base_db::Crate,
3482    idx: u32,
3483}
3484
3485impl ToolModule {
3486    pub(crate) fn by_name(db: &dyn HirDatabase, krate: Crate, name: &str) -> Option<Self> {
3487        let krate = krate.id;
3488        let idx =
3489            crate_def_map(db, krate).registered_tools().iter().position(|it| it.as_str() == name)?
3490                as u32;
3491        Some(ToolModule { krate, idx })
3492    }
3493
3494    pub fn name(&self, db: &dyn HirDatabase) -> Name {
3495        Name::new_symbol_root(
3496            crate_def_map(db, self.krate).registered_tools()[self.idx as usize].clone(),
3497        )
3498    }
3499
3500    pub fn krate(&self) -> Crate {
3501        Crate { id: self.krate }
3502    }
3503}
3504
3505#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3506pub struct Label {
3507    pub(crate) parent: ExpressionStoreOwnerId,
3508    pub(crate) label_id: LabelId,
3509}
3510
3511impl Label {
3512    pub fn module(self, db: &dyn HirDatabase) -> Module {
3513        self.parent(db).module(db)
3514    }
3515
3516    pub fn parent(self, _db: &dyn HirDatabase) -> ExpressionStoreOwner {
3517        self.parent.into()
3518    }
3519
3520    pub fn name(self, db: &dyn HirDatabase) -> Name {
3521        ExpressionStore::of(db, self.parent)[self.label_id].name.clone()
3522    }
3523}
3524
3525#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3526pub enum GenericParam {
3527    TypeParam(TypeParam),
3528    ConstParam(ConstParam),
3529    LifetimeParam(LifetimeParam),
3530}
3531impl_from!(TypeParam, ConstParam, LifetimeParam for GenericParam);
3532
3533impl GenericParam {
3534    pub fn module(self, db: &dyn HirDatabase) -> Module {
3535        match self {
3536            GenericParam::TypeParam(it) => it.module(db),
3537            GenericParam::ConstParam(it) => it.module(db),
3538            GenericParam::LifetimeParam(it) => it.module(db),
3539        }
3540    }
3541
3542    pub fn name(self, db: &dyn HirDatabase) -> Name {
3543        match self {
3544            GenericParam::TypeParam(it) => it.name(db),
3545            GenericParam::ConstParam(it) => it.name(db),
3546            GenericParam::LifetimeParam(it) => it.name(db),
3547        }
3548    }
3549
3550    pub fn parent(self) -> GenericDef {
3551        match self {
3552            GenericParam::TypeParam(it) => it.id.parent().into(),
3553            GenericParam::ConstParam(it) => it.id.parent().into(),
3554            GenericParam::LifetimeParam(it) => it.id.parent.into(),
3555        }
3556    }
3557
3558    pub fn variance(self, db: &dyn HirDatabase) -> Option<Variance> {
3559        let parent = match self {
3560            GenericParam::TypeParam(it) => it.id.parent(),
3561            // const parameters are always invariant
3562            GenericParam::ConstParam(_) => return None,
3563            GenericParam::LifetimeParam(it) => it.id.parent,
3564        };
3565        let index = match self {
3566            GenericParam::TypeParam(it) => hir_ide::type_or_const_param_idx(db, it.id.into()),
3567            GenericParam::ConstParam(_) => return None,
3568            GenericParam::LifetimeParam(it) => hir_ide::lifetime_param_idx(db, it.id),
3569        };
3570        db.variances_of(parent).get(index as usize).map(Into::into)
3571    }
3572}
3573
3574#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3575pub enum Variance {
3576    Bivariant,
3577    Covariant,
3578    Contravariant,
3579    Invariant,
3580}
3581
3582impl From<rustc_type_ir::Variance> for Variance {
3583    #[inline]
3584    fn from(value: rustc_type_ir::Variance) -> Self {
3585        match value {
3586            rustc_type_ir::Variance::Covariant => Variance::Covariant,
3587            rustc_type_ir::Variance::Invariant => Variance::Invariant,
3588            rustc_type_ir::Variance::Contravariant => Variance::Contravariant,
3589            rustc_type_ir::Variance::Bivariant => Variance::Bivariant,
3590        }
3591    }
3592}
3593
3594impl fmt::Display for Variance {
3595    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3596        let description = match self {
3597            Variance::Bivariant => "bivariant",
3598            Variance::Covariant => "covariant",
3599            Variance::Contravariant => "contravariant",
3600            Variance::Invariant => "invariant",
3601        };
3602        f.pad(description)
3603    }
3604}
3605
3606#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3607pub struct TypeParam {
3608    pub(crate) id: TypeParamId,
3609}
3610
3611impl TypeParam {
3612    pub fn merge(self) -> TypeOrConstParam {
3613        TypeOrConstParam { id: self.id.into() }
3614    }
3615
3616    pub fn name(self, db: &dyn HirDatabase) -> Name {
3617        self.merge().name(db)
3618    }
3619
3620    pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
3621        self.id.parent().into()
3622    }
3623
3624    pub fn module(self, db: &dyn HirDatabase) -> Module {
3625        self.id.parent().module(db).into()
3626    }
3627
3628    /// Is this type parameter implicitly introduced (eg. `Self` in a trait or an `impl Trait`
3629    /// argument)?
3630    pub fn is_implicit(self, db: &dyn HirDatabase) -> bool {
3631        let params = GenericParams::of(db, self.id.parent());
3632        let data = &params[self.id.local_id()];
3633        match data.type_param().unwrap().provenance {
3634            TypeParamProvenance::TypeParamList => false,
3635            TypeParamProvenance::TraitSelf | TypeParamProvenance::ArgumentImplTrait => true,
3636        }
3637    }
3638
3639    pub fn ty(self, db: &dyn HirDatabase) -> Type<'_> {
3640        let interner = DbInterner::new_no_crate(db);
3641        let index = hir_ide::type_or_const_param_idx(db, self.id.into());
3642        let ty = Ty::new_param(interner, self.id, index);
3643        Type::new(self.id.parent(), ty)
3644    }
3645
3646    /// FIXME: this only lists trait bounds from the item defining the type
3647    /// parameter, not additional bounds that might be added e.g. by a method if
3648    /// the parameter comes from an impl!
3649    pub fn trait_bounds(self, db: &dyn HirDatabase) -> Vec<Trait> {
3650        let self_ty = self.ty(db).ty.instantiate_identity().skip_norm_wip();
3651        GenericPredicates::query_explicit(db, self.id.parent())
3652            .iter_identity()
3653            .filter_map(|pred| match &pred.kind().skip_binder() {
3654                ClauseKind::Trait(trait_ref) if trait_ref.self_ty() == self_ty => {
3655                    Some(Trait::from(trait_ref.def_id().0))
3656                }
3657                _ => None,
3658            })
3659            .collect()
3660    }
3661
3662    pub fn default(self, db: &dyn HirDatabase) -> Option<Type<'_>> {
3663        let ty = generic_arg_from_param(db, self.id.into())?;
3664        match ty.kind() {
3665            rustc_type_ir::GenericArgKind::Type(it) if !it.is_ty_error() => {
3666                Some(Type::new(self.id.parent(), it))
3667            }
3668            _ => None,
3669        }
3670    }
3671
3672    pub fn is_unstable(self, db: &dyn HirDatabase) -> bool {
3673        self.attrs(db).is_unstable()
3674    }
3675}
3676
3677#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3678pub struct LifetimeParam {
3679    pub(crate) id: LifetimeParamId,
3680}
3681
3682impl LifetimeParam {
3683    pub fn name(self, db: &dyn HirDatabase) -> Name {
3684        let params = GenericParams::of(db, self.id.parent);
3685        params[self.id.local_id].name.clone()
3686    }
3687
3688    pub fn module(self, db: &dyn HirDatabase) -> Module {
3689        self.id.parent.module(db).into()
3690    }
3691
3692    pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
3693        self.id.parent.into()
3694    }
3695}
3696
3697#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3698pub struct ConstParam {
3699    pub(crate) id: ConstParamId,
3700}
3701
3702impl ConstParam {
3703    pub fn merge(self) -> TypeOrConstParam {
3704        TypeOrConstParam { id: self.id.into() }
3705    }
3706
3707    pub fn name(self, db: &dyn HirDatabase) -> Name {
3708        let params = GenericParams::of(db, self.id.parent());
3709        match params[self.id.local_id()].name() {
3710            Some(it) => it.clone(),
3711            None => {
3712                never!();
3713                Name::missing()
3714            }
3715        }
3716    }
3717
3718    pub fn module(self, db: &dyn HirDatabase) -> Module {
3719        self.id.parent().module(db).into()
3720    }
3721
3722    pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
3723        self.id.parent().into()
3724    }
3725
3726    pub fn ty(self, db: &dyn HirDatabase) -> Type<'_> {
3727        Type::new(self.id.parent(), db.const_param_ty(self.id))
3728    }
3729
3730    pub fn default(self, db: &dyn HirDatabase, display_target: DisplayTarget) -> Option<String> {
3731        let arg = generic_arg_from_param(db, self.id.into())?;
3732        Some(arg.display(db, display_target).to_string())
3733    }
3734
3735    pub fn default_source_code(
3736        self,
3737        db: &dyn HirDatabase,
3738        target_module: Module,
3739    ) -> Option<ast::ConstArg> {
3740        let arg = generic_arg_from_param(db, self.id.into())?;
3741        known_const_to_ast(arg.konst()?, db, target_module.id)
3742    }
3743}
3744
3745fn generic_arg_from_param(db: &dyn HirDatabase, id: TypeOrConstParamId) -> Option<GenericArg<'_>> {
3746    let local_idx = hir_ide::type_or_const_param_idx(db, id);
3747    let defaults = db.generic_defaults(id.parent);
3748    let ty = defaults.get(local_idx as usize)?;
3749    // FIXME: This shouldn't be `instantiate_identity()`, we shouldn't leak `TyKind::Param`s.
3750    Some(ty.instantiate_identity().skip_norm_wip())
3751}
3752
3753#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3754pub struct TypeOrConstParam {
3755    pub(crate) id: TypeOrConstParamId,
3756}
3757
3758impl TypeOrConstParam {
3759    pub fn name(self, db: &dyn HirDatabase) -> Name {
3760        let params = GenericParams::of(db, self.id.parent);
3761        match params[self.id.local_id].name() {
3762            Some(n) => n.clone(),
3763            _ => Name::missing(),
3764        }
3765    }
3766
3767    pub fn module(self, db: &dyn HirDatabase) -> Module {
3768        self.id.parent.module(db).into()
3769    }
3770
3771    pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef {
3772        self.id.parent.into()
3773    }
3774
3775    pub fn split(self, db: &dyn HirDatabase) -> Either<ConstParam, TypeParam> {
3776        let params = GenericParams::of(db, self.id.parent);
3777        match &params[self.id.local_id] {
3778            TypeOrConstParamData::TypeParamData(_) => {
3779                Either::Right(TypeParam { id: TypeParamId::from_unchecked(self.id) })
3780            }
3781            TypeOrConstParamData::ConstParamData(_) => {
3782                Either::Left(ConstParam { id: ConstParamId::from_unchecked(self.id) })
3783            }
3784        }
3785    }
3786
3787    pub fn ty(self, db: &dyn HirDatabase) -> Type<'_> {
3788        match self.split(db) {
3789            Either::Left(it) => it.ty(db),
3790            Either::Right(it) => it.ty(db),
3791        }
3792    }
3793
3794    pub fn as_type_param(self, db: &dyn HirDatabase) -> Option<TypeParam> {
3795        let params = GenericParams::of(db, self.id.parent);
3796        match &params[self.id.local_id] {
3797            TypeOrConstParamData::TypeParamData(_) => {
3798                Some(TypeParam { id: TypeParamId::from_unchecked(self.id) })
3799            }
3800            TypeOrConstParamData::ConstParamData(_) => None,
3801        }
3802    }
3803
3804    pub fn as_const_param(self, db: &dyn HirDatabase) -> Option<ConstParam> {
3805        let params = GenericParams::of(db, self.id.parent);
3806        match &params[self.id.local_id] {
3807            TypeOrConstParamData::TypeParamData(_) => None,
3808            TypeOrConstParamData::ConstParamData(_) => {
3809                Some(ConstParam { id: ConstParamId::from_unchecked(self.id) })
3810            }
3811        }
3812    }
3813}
3814
3815#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3816pub struct Impl {
3817    pub(crate) id: AnyImplId,
3818}
3819
3820impl Impl {
3821    pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec<Impl> {
3822        let mut result = Vec::new();
3823        extend_with_def_map(db, crate_def_map(db, krate.id), &mut result);
3824        return result;
3825
3826        fn extend_with_def_map(db: &dyn HirDatabase, def_map: &DefMap, result: &mut Vec<Impl>) {
3827            for (_, module) in def_map.modules() {
3828                result.extend(module.scope.impls().map(Impl::from));
3829                result.extend(module.scope.builtin_derive_impls().map(Impl::from));
3830
3831                for unnamed_const in module.scope.unnamed_consts() {
3832                    for (_, block_def_map) in Body::of(db, unnamed_const.into()).blocks(db) {
3833                        extend_with_def_map(db, block_def_map, result);
3834                    }
3835                }
3836            }
3837        }
3838    }
3839
3840    pub fn all_in_module(db: &dyn HirDatabase, module: Module) -> Vec<Impl> {
3841        module.impl_defs(db)
3842    }
3843
3844    /// **Note:** This is an **approximation** that strives to give the *human-perceived notion* of an "impl for type",
3845    /// **not** answer the technical question "what are all impls applying to this type". In particular, it excludes
3846    /// blanket impls, and only does a shallow type constructor check. In fact, this should've probably been on `Adt`
3847    /// etc., and not on `Type`. If you would want to create a precise list of all impls applying to a type,
3848    /// you would need to include blanket impls, and try to prove to predicates for each candidate.
3849    pub fn all_for_type<'db>(db: &'db dyn HirDatabase, ty: Type<'db>) -> Vec<Impl> {
3850        let mut result = Vec::new();
3851        let interner = DbInterner::new_no_crate(db);
3852        let Some(simplified_ty) = fast_reject::simplify_type(
3853            interner,
3854            ty.ty.skip_binder(),
3855            fast_reject::TreatParams::AsRigid,
3856        ) else {
3857            return Vec::new();
3858        };
3859        let mut extend_with_impls = |impls: Either<&[ImplId], &[BuiltinDeriveImplId]>| match impls {
3860            Either::Left(impls) => result.extend(impls.iter().copied().map(Impl::from)),
3861            Either::Right(impls) => result.extend(impls.iter().copied().map(Impl::from)),
3862        };
3863        method_resolution::with_incoherent_inherent_impls(
3864            db,
3865            ty.krate(db),
3866            &simplified_ty,
3867            |impls| extend_with_impls(Either::Left(impls)),
3868        );
3869        if let Some(module) = method_resolution::simplified_type_module(db, &simplified_ty) {
3870            InherentImpls::for_each_crate_and_block(
3871                db,
3872                module.krate(db),
3873                module.block(db),
3874                &mut |impls| extend_with_impls(Either::Left(impls.for_self_ty(&simplified_ty))),
3875            );
3876            std::iter::successors(module.block(db), |block| block.module(db).block(db))
3877                .filter_map(|block| TraitImpls::for_block(db, block))
3878                .for_each(|impls| impls.for_self_ty(&simplified_ty, &mut extend_with_impls));
3879            for &krate in &*all_crates(db) {
3880                TraitImpls::for_crate(db, krate)
3881                    .for_self_ty(&simplified_ty, &mut extend_with_impls);
3882            }
3883        } else {
3884            for &krate in &*all_crates(db) {
3885                TraitImpls::for_crate(db, krate)
3886                    .for_self_ty(&simplified_ty, &mut extend_with_impls);
3887            }
3888        }
3889        result
3890    }
3891
3892    pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
3893        let module = trait_.module(db).id;
3894        let mut all = Vec::new();
3895        let mut handle_impls = |impls: &TraitImpls<'_>| {
3896            impls.for_trait(trait_.id, |impls| match impls {
3897                Either::Left(impls) => all.extend(impls.iter().copied().map(Impl::from)),
3898                Either::Right(impls) => all.extend(impls.iter().copied().map(Impl::from)),
3899            });
3900        };
3901        for krate in module.krate(db).transitive_rev_deps(db) {
3902            handle_impls(TraitImpls::for_crate(db, krate));
3903        }
3904        if let Some(block) = module.block(db)
3905            && let Some(impls) = TraitImpls::for_block(db, block)
3906        {
3907            handle_impls(impls);
3908        }
3909        all
3910    }
3911
3912    pub fn trait_(self, db: &dyn HirDatabase) -> Option<Trait> {
3913        match self.id {
3914            AnyImplId::ImplId(id) => {
3915                let trait_ref = db.impl_trait(id)?;
3916                let id = trait_ref.skip_binder().def_id;
3917                Some(Trait { id: id.0 })
3918            }
3919            AnyImplId::BuiltinDeriveImplId(id) => {
3920                let loc = id.loc(db);
3921                let lang_items = hir_def::lang_item::lang_items(db, loc.adt.module(db).krate(db));
3922                loc.trait_.get_id(lang_items).map(Trait::from)
3923            }
3924        }
3925    }
3926
3927    pub fn trait_ref(self, db: &dyn HirDatabase) -> Option<TraitRef<'_>> {
3928        match self.id {
3929            AnyImplId::ImplId(id) => {
3930                let trait_ref = db.impl_trait(id)?.instantiate_identity().skip_norm_wip();
3931                Some(TraitRef::new(id.into(), trait_ref))
3932            }
3933            AnyImplId::BuiltinDeriveImplId(id) => {
3934                let loc = id.loc(db);
3935                let krate = loc.module(db).krate(db);
3936                let interner = DbInterner::new_with(db, krate);
3937                let trait_ref = hir_ide::builtin_derive::impl_trait(interner, id)
3938                    .instantiate_identity()
3939                    .skip_norm_wip();
3940                Some(TraitRef { owner: TypeOwnerId::BuiltinDeriveImplId(id), trait_ref })
3941            }
3942        }
3943    }
3944
3945    pub fn self_ty(self, db: &dyn HirDatabase) -> Type<'_> {
3946        match self.id {
3947            AnyImplId::ImplId(id) => {
3948                let ty = db.impl_self_ty(id).instantiate_identity().skip_norm_wip();
3949                Type::new(id.into(), ty)
3950            }
3951            AnyImplId::BuiltinDeriveImplId(id) => {
3952                let loc = id.loc(db);
3953                let krate = loc.module(db).krate(db);
3954                let interner = DbInterner::new_with(db, krate);
3955                let ty =
3956                    hir_ide::builtin_derive::impl_trait(interner, id).map_bound(|it| it.self_ty());
3957                Type { owner: TypeOwnerId::BuiltinDeriveImplId(id), ty }
3958            }
3959        }
3960    }
3961
3962    pub fn items(self, db: &dyn HirDatabase) -> Vec<AssocItem> {
3963        match self.id {
3964            AnyImplId::ImplId(id) => {
3965                id.impl_items(db).items.iter().map(|&(_, it)| it.into()).collect()
3966            }
3967            AnyImplId::BuiltinDeriveImplId(impl_) => impl_
3968                .loc(db)
3969                .trait_
3970                .all_methods()
3971                .iter()
3972                .map(|&method| {
3973                    AssocItem::Function(Function {
3974                        id: AnyFunctionId::BuiltinDeriveImplMethod { method, impl_ },
3975                    })
3976                })
3977                .collect(),
3978        }
3979    }
3980
3981    pub fn is_negative(self, db: &dyn HirDatabase) -> bool {
3982        match self.id {
3983            AnyImplId::ImplId(id) => ImplSignature::of(db, id).flags.contains(ImplFlags::NEGATIVE),
3984            AnyImplId::BuiltinDeriveImplId(_) => false,
3985        }
3986    }
3987
3988    pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
3989        match self.id {
3990            AnyImplId::ImplId(id) => ImplSignature::of(db, id).flags.contains(ImplFlags::UNSAFE),
3991            AnyImplId::BuiltinDeriveImplId(_) => false,
3992        }
3993    }
3994
3995    pub fn module(self, db: &dyn HirDatabase) -> Module {
3996        match self.id {
3997            AnyImplId::ImplId(id) => id.module(db).into(),
3998            AnyImplId::BuiltinDeriveImplId(id) => id.module(db).into(),
3999        }
4000    }
4001
4002    pub fn check_orphan_rules(self, db: &dyn HirDatabase) -> bool {
4003        match self.id {
4004            AnyImplId::ImplId(id) => check_orphan_rules(db, id),
4005            AnyImplId::BuiltinDeriveImplId(_) => true,
4006        }
4007    }
4008}
4009
4010#[derive(Clone, PartialEq, Eq, Debug, Hash)]
4011pub struct TraitRef<'db> {
4012    owner: TypeOwnerId,
4013    trait_ref: hir_ide::next_solver::TraitRef<'db>,
4014}
4015
4016impl<'db> TraitRef<'db> {
4017    fn new(owner: GenericDefId, trait_ref: hir_ide::next_solver::TraitRef<'db>) -> Self {
4018        Self { owner: TypeOwnerId::GenericDefId(owner), trait_ref }
4019    }
4020
4021    pub fn trait_(&self) -> Trait {
4022        Trait { id: self.trait_ref.def_id.0 }
4023    }
4024
4025    pub fn self_ty(&self) -> Type<'_> {
4026        let ty = self.trait_ref.self_ty();
4027        Type { owner: self.owner, ty: EarlyBinder::bind(ty) }
4028    }
4029
4030    /// Returns `idx`-th argument of this trait reference if it is a type argument. Note that the
4031    /// first argument is the `Self` type.
4032    pub fn get_type_argument(&self, idx: usize) -> Option<Type<'db>> {
4033        self.trait_ref
4034            .args
4035            .as_slice()
4036            .get(idx)
4037            .and_then(|arg| arg.ty())
4038            .map(|ty| Type { owner: self.owner, ty: EarlyBinder::bind(ty) })
4039    }
4040}
4041
4042#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4043enum AnyClosureId<'db> {
4044    ClosureId(InternedClosureId<'db>),
4045    CoroutineClosureId(InternedCoroutineClosureId<'db>),
4046}
4047
4048#[derive(Clone, Debug, PartialEq, Eq, Hash)]
4049pub struct Closure<'db> {
4050    owner: TypeOwnerId,
4051    id: AnyClosureId<'db>,
4052    subst: GenericArgs<'db>,
4053}
4054
4055impl<'db> Closure<'db> {
4056    fn as_ty(&self, db: &'db dyn HirDatabase) -> Ty<'db> {
4057        let interner = DbInterner::new_no_crate(db);
4058        match self.id {
4059            AnyClosureId::ClosureId(id) => Ty::new_closure(interner, id.into(), self.subst),
4060            AnyClosureId::CoroutineClosureId(id) => {
4061                Ty::new_coroutine_closure(interner, id.into(), self.subst)
4062            }
4063        }
4064    }
4065
4066    pub fn display_with_id(&self, db: &dyn HirDatabase, display_target: DisplayTarget) -> String {
4067        self.as_ty(db)
4068            .display(db, display_target)
4069            .with_closure_style(ClosureStyle::ClosureWithId)
4070            .to_string()
4071    }
4072
4073    pub fn display_with_impl(&self, db: &dyn HirDatabase, display_target: DisplayTarget) -> String {
4074        self.as_ty(db)
4075            .display(db, display_target)
4076            .with_closure_style(ClosureStyle::ImplFn)
4077            .to_string()
4078    }
4079
4080    pub fn captured_items(&self, db: &'db dyn HirDatabase) -> Vec<ClosureCapture<'db>> {
4081        let closure = match self.id {
4082            AnyClosureId::ClosureId(it) => it.loc(db),
4083            AnyClosureId::CoroutineClosureId(it) => it.loc(db),
4084        };
4085        captured_items(db, closure)
4086    }
4087
4088    pub fn fn_trait(&self, _db: &dyn HirDatabase) -> FnTrait {
4089        match self.id {
4090            AnyClosureId::ClosureId(_) => match self.subst.as_closure().kind() {
4091                rustc_type_ir::ClosureKind::Fn => FnTrait::Fn,
4092                rustc_type_ir::ClosureKind::FnMut => FnTrait::FnMut,
4093                rustc_type_ir::ClosureKind::FnOnce => FnTrait::FnOnce,
4094            },
4095            AnyClosureId::CoroutineClosureId(_) => match self.subst.as_coroutine_closure().kind() {
4096                rustc_type_ir::ClosureKind::Fn => FnTrait::AsyncFn,
4097                rustc_type_ir::ClosureKind::FnMut => FnTrait::AsyncFnMut,
4098                rustc_type_ir::ClosureKind::FnOnce => FnTrait::AsyncFnOnce,
4099            },
4100        }
4101    }
4102}
4103
4104/// A coroutine expression, including async, generator, and async-generator coroutines.
4105#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4106pub struct Coroutine<'db> {
4107    id: InternedCoroutineId<'db>,
4108}
4109
4110impl<'db> Coroutine<'db> {
4111    /// Returns the values captured by this coroutine.
4112    pub fn captured_items(&self, db: &'db dyn HirDatabase) -> Vec<ClosureCapture<'db>> {
4113        captured_items(db, self.id.loc(db))
4114    }
4115}
4116
4117fn captured_items<'db>(
4118    db: &'db dyn HirDatabase,
4119    closure: InternedClosure<'db>,
4120) -> Vec<ClosureCapture<'db>> {
4121    let InternedClosure { owner: infer_owner, expr: closure, .. } = closure;
4122    let infer = InferenceResult::of(db, infer_owner);
4123    let owner = infer_owner.expression_store_owner(db);
4124    infer.closures_data[&closure]
4125        .min_captures
4126        .values()
4127        .flatten()
4128        .map(|capture| ClosureCapture { owner, infer_owner, closure, capture })
4129        .collect()
4130}
4131
4132#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4133pub enum FnTrait {
4134    FnOnce,
4135    FnMut,
4136    Fn,
4137
4138    AsyncFnOnce,
4139    AsyncFnMut,
4140    AsyncFn,
4141}
4142
4143impl From<traits::FnTrait> for FnTrait {
4144    fn from(value: traits::FnTrait) -> Self {
4145        match value {
4146            traits::FnTrait::FnOnce => FnTrait::FnOnce,
4147            traits::FnTrait::FnMut => FnTrait::FnMut,
4148            traits::FnTrait::Fn => FnTrait::Fn,
4149            traits::FnTrait::AsyncFnOnce => FnTrait::AsyncFnOnce,
4150            traits::FnTrait::AsyncFnMut => FnTrait::AsyncFnMut,
4151            traits::FnTrait::AsyncFn => FnTrait::AsyncFn,
4152        }
4153    }
4154}
4155
4156impl fmt::Display for FnTrait {
4157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4158        match self {
4159            FnTrait::FnOnce => write!(f, "FnOnce"),
4160            FnTrait::FnMut => write!(f, "FnMut"),
4161            FnTrait::Fn => write!(f, "Fn"),
4162            FnTrait::AsyncFnOnce => write!(f, "AsyncFnOnce"),
4163            FnTrait::AsyncFnMut => write!(f, "AsyncFnMut"),
4164            FnTrait::AsyncFn => write!(f, "AsyncFn"),
4165        }
4166    }
4167}
4168
4169impl FnTrait {
4170    pub const fn function_name(&self) -> &'static str {
4171        match self {
4172            FnTrait::FnOnce => "call_once",
4173            FnTrait::FnMut => "call_mut",
4174            FnTrait::Fn => "call",
4175            FnTrait::AsyncFnOnce => "async_call_once",
4176            FnTrait::AsyncFnMut => "async_call_mut",
4177            FnTrait::AsyncFn => "async_call",
4178        }
4179    }
4180
4181    pub fn lang_item(self) -> LangItem {
4182        match self {
4183            FnTrait::FnOnce => LangItem::FnOnce,
4184            FnTrait::FnMut => LangItem::FnMut,
4185            FnTrait::Fn => LangItem::Fn,
4186            FnTrait::AsyncFnOnce => LangItem::AsyncFnOnce,
4187            FnTrait::AsyncFnMut => LangItem::AsyncFnMut,
4188            FnTrait::AsyncFn => LangItem::AsyncFn,
4189        }
4190    }
4191
4192    pub fn get_id(self, db: &dyn HirDatabase, krate: Crate) -> Option<Trait> {
4193        Trait::lang(db, krate, self.lang_item())
4194    }
4195}
4196
4197#[derive(Clone, Debug, PartialEq, Eq)]
4198pub struct ClosureCapture<'db> {
4199    owner: ExpressionStoreOwnerId,
4200    infer_owner: InferBodyId<'db>,
4201    closure: ExprId,
4202    capture: &'db hir_ide::closure_analysis::CapturedPlace,
4203}
4204
4205impl<'db> ClosureCapture<'db> {
4206    pub fn local(&self) -> Local<'db> {
4207        Local {
4208            parent: self.owner,
4209            parent_infer: self.infer_owner,
4210            binding_id: self.capture.captured_local(),
4211        }
4212    }
4213
4214    /// Returns whether this place has any field (aka. non-deref) projections.
4215    pub fn has_field_projections(&self) -> bool {
4216        self.capture.place.projections.iter().any(|proj| {
4217            matches!(proj.kind, hir_ide::closure_analysis::ProjectionKind::Field { .. })
4218        })
4219    }
4220
4221    pub fn usages(&self) -> CaptureUsages<'db> {
4222        CaptureUsages { parent: self.owner, sources: &self.capture.info.sources }
4223    }
4224
4225    pub fn kind(&self) -> CaptureKind {
4226        match self.capture.info.capture_kind {
4227            hir_ide::closure_analysis::UpvarCapture::ByValue => CaptureKind::Move,
4228            hir_ide::closure_analysis::UpvarCapture::ByUse => CaptureKind::SharedRef, // Good enough?
4229            hir_ide::closure_analysis::UpvarCapture::ByRef(
4230                hir_ide::closure_analysis::BorrowKind::Immutable,
4231            ) => CaptureKind::SharedRef,
4232            hir_ide::closure_analysis::UpvarCapture::ByRef(
4233                hir_ide::closure_analysis::BorrowKind::UniqueImmutable,
4234            ) => CaptureKind::UniqueSharedRef,
4235            hir_ide::closure_analysis::UpvarCapture::ByRef(
4236                hir_ide::closure_analysis::BorrowKind::Mutable,
4237            ) => CaptureKind::MutableRef,
4238        }
4239    }
4240
4241    /// Converts the place to a name that can be inserted into source code.
4242    pub fn place_to_name(&self, db: &dyn HirDatabase, edition: Edition) -> String {
4243        let mut result = self.local().name(db).display(db, edition).to_string();
4244        for (i, proj) in self.capture.place.projections.iter().enumerate() {
4245            match proj.kind {
4246                hir_ide::closure_analysis::ProjectionKind::Deref => {}
4247                hir_ide::closure_analysis::ProjectionKind::Field { field_idx, variant_idx } => {
4248                    let ty = self.capture.place.ty_before_projection(i);
4249                    match ty.kind() {
4250                        TyKind::Tuple(_) => format_to!(result, "_{field_idx}"),
4251                        TyKind::Adt(adt_def, _) => {
4252                            let variant = match adt_def.def_id() {
4253                                AdtId::StructId(id) => VariantId::from(id),
4254                                AdtId::UnionId(id) => id.into(),
4255                                AdtId::EnumId(id) => {
4256                                    id.enum_variants(db).variants[variant_idx as usize].0.into()
4257                                }
4258                            };
4259                            let field = &variant.fields(db).fields()
4260                                [LocalFieldId::from_raw(la_arena::RawIdx::from_u32(field_idx))];
4261                            format_to!(result, "_{}", field.name.display(db, edition));
4262                        }
4263                        _ => never!("mismatching projection type"),
4264                    }
4265                }
4266                _ => never!("unexpected projection kind"),
4267            }
4268        }
4269        result
4270    }
4271
4272    pub fn display_place_source_code(&self, db: &dyn HirDatabase, edition: Edition) -> String {
4273        let mut result = self.local().name(db).display(db, edition).to_string();
4274        // We only need the derefs that have no field access after them, autoderef will do the rest.
4275        let mut last_derefs = 0;
4276        for (i, proj) in self.capture.place.projections.iter().enumerate() {
4277            match proj.kind {
4278                hir_ide::closure_analysis::ProjectionKind::Deref => last_derefs += 1,
4279                hir_ide::closure_analysis::ProjectionKind::Field { field_idx, variant_idx } => {
4280                    last_derefs = 0;
4281
4282                    let ty = self.capture.place.ty_before_projection(i);
4283                    match ty.kind() {
4284                        TyKind::Tuple(_) => format_to!(result, ".{field_idx}"),
4285                        TyKind::Adt(adt_def, _) => {
4286                            let variant = match adt_def.def_id() {
4287                                AdtId::StructId(id) => VariantId::from(id),
4288                                AdtId::UnionId(id) => id.into(),
4289                                AdtId::EnumId(id) => {
4290                                    // Can't really do that for an enum, unfortunately, so try to do something alike.
4291                                    id.enum_variants(db).variants[variant_idx as usize].0.into()
4292                                }
4293                            };
4294                            let field = &variant.fields(db).fields()
4295                                [LocalFieldId::from_raw(la_arena::RawIdx::from_u32(field_idx))];
4296                            format_to!(result, ".{}", field.name.display(db, edition));
4297                        }
4298                        _ => never!("mismatching projection type"),
4299                    }
4300                }
4301                _ => never!("unexpected projection kind"),
4302            }
4303        }
4304        result.insert_str(0, &"*".repeat(last_derefs));
4305        result
4306    }
4307
4308    pub fn ty(&self, db: &'db dyn HirDatabase) -> Type<'db> {
4309        Type::new_body(db, self.owner, self.capture.place.ty())
4310    }
4311
4312    /// The type that is stored in the closure, which is different from [`Self::ty()`], representing
4313    /// the place's type, when the capture is by ref.
4314    pub fn captured_ty(&self, db: &'db dyn HirDatabase) -> Type<'db> {
4315        Type::new_body(db, self.owner, self.capture.captured_ty(db))
4316    }
4317}
4318
4319#[derive(Clone, Copy, PartialEq, Eq)]
4320pub enum CaptureKind {
4321    SharedRef,
4322    UniqueSharedRef,
4323    MutableRef,
4324    Move,
4325}
4326
4327#[derive(Debug, Clone)]
4328pub struct CaptureUsages<'db> {
4329    parent: ExpressionStoreOwnerId,
4330    sources: &'db [hir_ide::closure_analysis::CaptureSourceStack],
4331}
4332
4333impl CaptureUsages<'_> {
4334    fn is_ref(store: &ExpressionStore, id: ExprOrPatId) -> bool {
4335        match id {
4336            ExprOrPatId::ExprId(expr) => matches!(store[expr], Expr::Ref { .. }),
4337            // FIXME: Figure out if this is correct wrt. match ergonomics.
4338            ExprOrPatId::PatId(pat) => match store[pat] {
4339                Pat::Bind { id: binding, .. } => matches!(
4340                    store[binding].mode,
4341                    BindingAnnotation::Ref | BindingAnnotation::RefMut
4342                ),
4343                _ => false,
4344            },
4345        }
4346    }
4347
4348    pub fn sources(&self, db: &dyn HirDatabase) -> Vec<CaptureUsageSource> {
4349        let (store, source_map) = ExpressionStore::with_source_map(db, self.parent);
4350        let mut result = Vec::with_capacity(self.sources.len());
4351        for source in self.sources {
4352            let source = source.final_source();
4353            let is_ref = Self::is_ref(store, source.unpack());
4354            match source.unpack() {
4355                ExprOrPatId::ExprId(expr) => {
4356                    if let Ok(expr) = source_map.expr_syntax(expr) {
4357                        result.push(CaptureUsageSource { is_ref, source: expr })
4358                    }
4359                }
4360                ExprOrPatId::PatId(pat) => {
4361                    if let Ok(pat) = source_map.pat_syntax(pat) {
4362                        result.push(CaptureUsageSource { is_ref, source: pat });
4363                    }
4364                }
4365            }
4366        }
4367        result
4368    }
4369}
4370
4371#[derive(Debug)]
4372pub struct CaptureUsageSource {
4373    is_ref: bool,
4374    source: InFile<AstPtr<Either<ast::Expr, ast::Pat>>>,
4375}
4376
4377impl CaptureUsageSource {
4378    pub fn source(&self) -> AstPtr<Either<ast::Expr, ast::Pat>> {
4379        self.source.value
4380    }
4381
4382    pub fn file_id(&self) -> HirFileId {
4383        self.source.file_id
4384    }
4385
4386    pub fn is_ref(&self) -> bool {
4387        self.is_ref
4388    }
4389}
4390
4391#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
4392enum TypeOwnerId {
4393    GenericDefId(GenericDefId),
4394    BuiltinDeriveImplId(BuiltinDeriveImplId),
4395    // FIXME: What do when we unify two different crates? Currently we just randomly keep one.
4396    NoParams(base_db::Crate),
4397}
4398
4399impl_from!(
4400    GenericDefId,
4401    BuiltinDeriveImplId
4402    for TypeOwnerId
4403);
4404
4405impl TypeOwnerId {
4406    /// We associated anon consts with their parent, because they can never have generics of their own.
4407    /// It can have *less* than the parent, but providing more generic args is not a problem.
4408    fn from_anon_const<'db>(id: AnonConstId<'db>, db: &'db dyn HirDatabase) -> TypeOwnerId {
4409        TypeOwnerId::GenericDefId(id.loc(db).owner.generic_def(db))
4410    }
4411
4412    fn unify(self, other: Self) -> Option<Self> {
4413        match (self, other) {
4414            (TypeOwnerId::NoParams(_), owner) => Some(owner),
4415            (owner, TypeOwnerId::NoParams(_)) => Some(owner),
4416            (_, _) => {
4417                if self == other {
4418                    Some(self)
4419                } else {
4420                    None
4421                }
4422            }
4423        }
4424    }
4425
4426    #[track_caller]
4427    fn must_unify(self, other: Self) -> Self {
4428        self.unify(other).expect("failed to unify type owners")
4429    }
4430
4431    fn can_rebase_into(
4432        self,
4433        db: &dyn HirDatabase,
4434        rebase_into: Self,
4435        self_ty: EarlyBinder<'_, Ty<'_>>,
4436    ) -> bool {
4437        if self == rebase_into || !self_ty.skip_binder().has_param() {
4438            return true;
4439        }
4440        let self_def = match self {
4441            TypeOwnerId::GenericDefId(def) => def,
4442            TypeOwnerId::BuiltinDeriveImplId(_) => return false,
4443            TypeOwnerId::NoParams(_) => return true,
4444        };
4445        let self_def = match self_def {
4446            GenericDefId::ImplId(def) => ItemContainerId::ImplId(def),
4447            GenericDefId::TraitId(def) => ItemContainerId::TraitId(def),
4448            GenericDefId::AdtId(_)
4449            | GenericDefId::ConstId(_)
4450            | GenericDefId::FunctionId(_)
4451            | GenericDefId::StaticId(_)
4452            | GenericDefId::TypeAliasId(_) => return false,
4453        };
4454        let rebase_into_def = match rebase_into {
4455            TypeOwnerId::GenericDefId(def) => def,
4456            TypeOwnerId::BuiltinDeriveImplId(_) | TypeOwnerId::NoParams(_) => return false,
4457        };
4458        let rebase_into_parent = match rebase_into_def {
4459            GenericDefId::ConstId(def) => def.loc(db).container,
4460            GenericDefId::FunctionId(def) => def.loc(db).container,
4461            GenericDefId::TypeAliasId(def) => def.loc(db).container,
4462            GenericDefId::AdtId(_)
4463            | GenericDefId::ImplId(_)
4464            | GenericDefId::StaticId(_)
4465            | GenericDefId::TraitId(_) => return false,
4466        };
4467        self_def == rebase_into_parent
4468    }
4469}
4470
4471/// Note: A [`Type`] remembers its origin. Trying to do anything (except comparing)
4472/// with types of different origins will cause errors or panics. Instead, use the `instantiate` methods.
4473#[derive(Clone, Debug)]
4474pub struct Type<'db> {
4475    owner: TypeOwnerId,
4476    ty: EarlyBinder<'db, Ty<'db>>,
4477}
4478
4479impl<'db> std::hash::Hash for Type<'db> {
4480    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
4481        // Do not hash the owner as different owners can compare the same.
4482        // self.owner.hash(state);
4483        self.ty.hash(state);
4484    }
4485}
4486
4487impl<'db> PartialEq for Type<'db> {
4488    fn eq(&self, other: &Self) -> bool {
4489        if self.ty != other.ty {
4490            return false;
4491        }
4492        hir_ide::with_attached_db(|db| {
4493            self.owner.can_rebase_into(db, other.owner, self.ty)
4494                || other.owner.can_rebase_into(db, self.owner, other.ty)
4495        })
4496    }
4497}
4498
4499impl<'db> Eq for Type<'db> {}
4500
4501impl<'db> Type<'db> {
4502    fn new(owner: GenericDefId, ty: Ty<'db>) -> Self {
4503        Type { owner: TypeOwnerId::GenericDefId(owner), ty: EarlyBinder::bind(ty) }
4504    }
4505
4506    fn new_body(db: &dyn HirDatabase, owner: ExpressionStoreOwnerId, ty: Ty<'db>) -> Self {
4507        Self::new(owner.generic_def(db), ty)
4508    }
4509
4510    fn no_params(krate: base_db::Crate, ty: Ty<'db>) -> Self {
4511        Type { owner: TypeOwnerId::NoParams(krate), ty: EarlyBinder::bind(ty) }
4512    }
4513
4514    fn builtin_type_crate(db: &'db dyn HirDatabase) -> base_db::Crate {
4515        // It doesn't really matter.
4516        all_crates(db)[0]
4517    }
4518
4519    fn from_def(db: &'db dyn HirDatabase, def: impl Into<TyDefId>) -> Self {
4520        let def = def.into();
4521        let ty = db.ty(def);
4522        let owner = match def {
4523            TyDefId::AdtId(it) => TypeOwnerId::GenericDefId(GenericDefId::AdtId(it)),
4524            TyDefId::TypeAliasId(it) => TypeOwnerId::GenericDefId(GenericDefId::TypeAliasId(it)),
4525            TyDefId::BuiltinType(_) => TypeOwnerId::NoParams(Self::builtin_type_crate(db)),
4526        };
4527        Type { owner, ty }
4528    }
4529
4530    fn from_value_def(db: &'db dyn HirDatabase, def: impl Into<ValueTyDefId>) -> Self {
4531        let def = def.into();
4532        let Some(ty) = db.value_ty(def) else {
4533            return Type::unknown(db);
4534        };
4535        let def = match def {
4536            ValueTyDefId::ConstId(it) => GenericDefId::ConstId(it),
4537            ValueTyDefId::FunctionId(it) => GenericDefId::FunctionId(it),
4538            ValueTyDefId::StructId(it) => GenericDefId::AdtId(AdtId::StructId(it)),
4539            ValueTyDefId::UnionId(it) => GenericDefId::AdtId(AdtId::UnionId(it)),
4540            ValueTyDefId::EnumVariantId(it) => {
4541                GenericDefId::AdtId(AdtId::EnumId(it.lookup(db).parent))
4542            }
4543            ValueTyDefId::StaticId(it) => {
4544                return Type::no_params(hir_def::HasModule::krate(&it, db), ty.skip_binder());
4545            }
4546        };
4547        Type::new(def, ty.instantiate_identity().skip_norm_wip())
4548    }
4549
4550    /// Replace any generic parameters with error types.
4551    pub fn instantiate_with_errors(&self, db: &'db dyn HirDatabase) -> Self {
4552        let interner = DbInterner::new_no_crate(db);
4553        let krate = self.krate(interner.db());
4554        let args = match self.owner {
4555            TypeOwnerId::GenericDefId(def) => GenericArgs::error_for_item(interner, def.into()),
4556            TypeOwnerId::BuiltinDeriveImplId(def) => {
4557                GenericArgs::error_for_item(interner, def.into())
4558            }
4559            TypeOwnerId::NoParams(_) => GenericArgs::empty(),
4560        };
4561        Type::no_params(krate, self.ty.instantiate(interner, args).skip_norm_wip())
4562    }
4563
4564    // FIXME: Find some way with const params, maybe even lifetimes?
4565    pub fn instantiate(
4566        &self,
4567        db: &'db dyn HirDatabase,
4568        args: impl IntoIterator<Item: Borrow<Type<'db>>>,
4569    ) -> Type<'db> {
4570        let interner = DbInterner::new_no_crate(db);
4571        let (args, owner) = match self.owner {
4572            TypeOwnerId::GenericDefId(def) => generic_args_from_tys(interner, def.into(), args),
4573            TypeOwnerId::BuiltinDeriveImplId(def) => {
4574                generic_args_from_tys(interner, def.into(), args)
4575            }
4576            TypeOwnerId::NoParams(krate) => (GenericArgs::empty(), TypeOwnerId::NoParams(krate)),
4577        };
4578        Type { owner, ty: EarlyBinder::bind(self.ty.instantiate(interner, args).skip_norm_wip()) }
4579    }
4580
4581    /// Instantiates multiple types with infer vars, keeping the same infer vars for the same owners.
4582    fn instantiate_many_with_infer(
4583        tys: impl IntoIterator<Item: Borrow<Type<'db>>>,
4584        infcx: &InferCtxt<'db>,
4585    ) -> impl Iterator<Item = Ty<'db>> {
4586        let mut var_for_param = FxHashMap::default();
4587        tys.into_iter().map(move |ty| {
4588            let ty = ty.borrow();
4589            let owner = match ty.owner {
4590                TypeOwnerId::GenericDefId(def) => def.into(),
4591                TypeOwnerId::BuiltinDeriveImplId(def) => def.into(),
4592                TypeOwnerId::NoParams(_) => return ty.ty.skip_binder(),
4593            };
4594            let args = GenericArgs::for_item(infcx.interner, owner, |_, param, _, _| {
4595                *var_for_param
4596                    .entry(param)
4597                    .or_insert_with(|| infcx.var_for_def(param, hir_ide::Span::Dummy))
4598            });
4599
4600            ty.ty.instantiate(infcx.interner, args).skip_norm_wip()
4601        })
4602    }
4603
4604    /// Tries to put this type as-is in the context of `rebase_into`. This will return `Some(_)` if:
4605    ///
4606    ///  - The type does not reference generic parameters, or
4607    ///  - `rebase_into` is in the context of a child of our context (for example, a function in an impl).
4608    pub fn try_rebase_into(
4609        &self,
4610        db: &'db dyn HirDatabase,
4611        rebase_into: &Type<'db>,
4612    ) -> Option<Self> {
4613        if self.owner.can_rebase_into(db, rebase_into.owner, self.ty) {
4614            Some(Type { owner: rebase_into.owner, ty: self.ty })
4615        } else {
4616            None
4617        }
4618    }
4619
4620    /// If `self` can be rebased into `rebase_into`, returns that. Otherwise, instantiates `self` with errors
4621    /// and returns that.
4622    pub fn rebase_into_or_error(
4623        &self,
4624        db: &'db dyn HirDatabase,
4625        rebase_into: &Type<'db>,
4626    ) -> Type<'db> {
4627        self.try_rebase_into(db, rebase_into).unwrap_or_else(|| self.instantiate_with_errors(db))
4628    }
4629
4630    pub fn try_rebase_into_owner(
4631        &self,
4632        db: &'db dyn HirDatabase,
4633        new_owner: GenericDef,
4634    ) -> Option<Self> {
4635        let new_owner = new_owner.id()?.into();
4636        if self.owner.can_rebase_into(db, new_owner, self.ty) {
4637            Some(Type { owner: new_owner, ty: self.ty })
4638        } else {
4639            None
4640        }
4641    }
4642
4643    pub fn rebase_into_owner_or_error(
4644        &self,
4645        db: &'db dyn HirDatabase,
4646        new_owner: GenericDef,
4647    ) -> Self {
4648        self.try_rebase_into_owner(db, new_owner)
4649            .unwrap_or_else(|| self.instantiate_with_errors(db))
4650    }
4651
4652    pub fn unknown(db: &'db dyn HirDatabase) -> Self {
4653        let interner = DbInterner::new_no_crate(db);
4654        Type::no_params(Self::builtin_type_crate(db), Ty::new_error(interner, ErrorGuaranteed))
4655    }
4656
4657    pub fn new_slice(db: &'db dyn HirDatabase, ty: Self) -> Self {
4658        let interner = DbInterner::new_no_crate(db);
4659        Type { owner: ty.owner, ty: ty.ty.map_bound(|ty| Ty::new_slice(interner, ty)) }
4660    }
4661
4662    pub fn new_tuple(
4663        db: &'db dyn HirDatabase,
4664        tys: impl IntoIterator<Item: Borrow<Type<'db>>>,
4665    ) -> Self {
4666        let interner = DbInterner::new_no_crate(db);
4667        let mut owner = None::<TypeOwnerId>;
4668        let ty = EarlyBinder::bind(Ty::new_tup_from_iter(
4669            interner,
4670            tys.into_iter().map(|ty| {
4671                let ty = ty.borrow();
4672
4673                match &mut owner {
4674                    Some(owner) => *owner = owner.must_unify(ty.owner),
4675                    None => owner = Some(ty.owner),
4676                }
4677
4678                ty.ty.skip_binder()
4679            }),
4680        ));
4681        let owner =
4682            owner.unwrap_or_else(|| TypeOwnerId::NoParams(Self::builtin_type_crate(interner.db())));
4683        Type { owner, ty }
4684    }
4685
4686    pub fn new_unit(db: &'db dyn HirDatabase) -> Self {
4687        let interner = DbInterner::new_no_crate(db);
4688        Type::no_params(Self::builtin_type_crate(db), Ty::new_unit(interner))
4689    }
4690
4691    pub fn is_unit(&self) -> bool {
4692        self.ty.skip_binder().is_unit()
4693    }
4694
4695    pub fn is_bool(&self) -> bool {
4696        matches!(self.ty.skip_binder().kind(), TyKind::Bool)
4697    }
4698
4699    pub fn is_str(&self) -> bool {
4700        matches!(self.ty.skip_binder().kind(), TyKind::Str)
4701    }
4702
4703    pub fn is_never(&self) -> bool {
4704        matches!(self.ty.skip_binder().kind(), TyKind::Never)
4705    }
4706
4707    pub fn is_mutable_reference(&self) -> bool {
4708        matches!(
4709            self.ty.skip_binder().kind(),
4710            TyKind::Ref(.., hir_ide::next_solver::Mutability::Mut)
4711        )
4712    }
4713
4714    pub fn is_reference(&self) -> bool {
4715        matches!(self.ty.skip_binder().kind(), TyKind::Ref(..))
4716    }
4717
4718    pub fn contains_reference(&self, db: &'db dyn HirDatabase) -> bool {
4719        let interner = DbInterner::new_no_crate(db);
4720        return self
4721            .ty
4722            .instantiate_identity()
4723            .skip_norm_wip()
4724            .visit_with(&mut Visitor { interner })
4725            .is_break();
4726
4727        fn is_phantom_data(db: &dyn HirDatabase, adt_id: AdtId) -> bool {
4728            match adt_id {
4729                AdtId::StructId(s) => {
4730                    let flags = StructSignature::of(db, s).flags;
4731                    flags.contains(StructFlags::IS_PHANTOM_DATA)
4732                }
4733                AdtId::UnionId(_) | AdtId::EnumId(_) => false,
4734            }
4735        }
4736
4737        struct Visitor<'db> {
4738            interner: DbInterner<'db>,
4739        }
4740
4741        impl<'db> TypeVisitor<DbInterner<'db>> for Visitor<'db> {
4742            type Result = ControlFlow<()>;
4743
4744            fn visit_ty(&mut self, ty: Ty<'db>) -> Self::Result {
4745                match ty.kind() {
4746                    // Reference itself
4747                    TyKind::Ref(..) => ControlFlow::Break(()),
4748
4749                    // For non-phantom_data adts we check variants/fields as well as generic parameters
4750                    TyKind::Adt(adt_def, args)
4751                        if !is_phantom_data(self.interner.db(), adt_def.def_id()) =>
4752                    {
4753                        let _variant_id_to_fields = |id: VariantId| {
4754                            let variant_data = &id.fields(self.interner.db());
4755                            if variant_data.fields().is_empty() {
4756                                vec![]
4757                            } else {
4758                                let field_types = self.interner.db().field_types(id);
4759                                variant_data
4760                                    .fields()
4761                                    .iter()
4762                                    .map(|(idx, _)| {
4763                                        field_types[idx]
4764                                            .ty()
4765                                            .instantiate(self.interner, args)
4766                                            .skip_norm_wip()
4767                                    })
4768                                    .filter(|it| !it.references_non_lt_error())
4769                                    .collect()
4770                            }
4771                        };
4772                        let variant_id_to_fields = |_: VariantId| vec![];
4773
4774                        let variants: Vec<Vec<Ty<'db>>> = match adt_def.def_id() {
4775                            AdtId::StructId(id) => {
4776                                vec![variant_id_to_fields(id.into())]
4777                            }
4778                            AdtId::EnumId(id) => id
4779                                .enum_variants(self.interner.db())
4780                                .variants
4781                                .values()
4782                                .map(|&(variant_id, _)| variant_id_to_fields(variant_id.into()))
4783                                .collect(),
4784                            AdtId::UnionId(id) => {
4785                                vec![variant_id_to_fields(id.into())]
4786                            }
4787                        };
4788
4789                        variants
4790                            .into_iter()
4791                            .flat_map(|variant| variant.into_iter())
4792                            .try_for_each(|ty| ty.visit_with(self))?;
4793                        args.visit_with(self)
4794                    }
4795                    // And for `PhantomData<T>`, we check `T`.
4796                    _ => ty.super_visit_with(self),
4797                }
4798            }
4799        }
4800    }
4801
4802    pub fn as_reference(&self) -> Option<(Type<'db>, Mutability)> {
4803        let TyKind::Ref(_lt, ty, m) = self.ty.skip_binder().kind() else { return None };
4804        let m = Mutability::from_mutable(matches!(m, hir_ide::next_solver::Mutability::Mut));
4805        Some((self.derived(ty), m))
4806    }
4807
4808    pub fn as_reference_inner(&self) -> Option<Type<'db>> {
4809        self.as_reference().map(|(inner, _)| inner)
4810    }
4811
4812    pub fn add_reference(&self, db: &'db dyn HirDatabase, mutability: Mutability) -> Self {
4813        let interner = DbInterner::new_no_crate(db);
4814        let ty_mutability = match mutability {
4815            Mutability::Shared => hir_ide::next_solver::Mutability::Not,
4816            Mutability::Mut => hir_ide::next_solver::Mutability::Mut,
4817        };
4818        self.derived(Ty::new_ref(
4819            interner,
4820            Region::error(interner),
4821            self.ty.skip_binder(),
4822            ty_mutability,
4823        ))
4824    }
4825
4826    pub fn is_slice(&self) -> bool {
4827        matches!(self.ty.skip_binder().kind(), TyKind::Slice(..))
4828    }
4829
4830    pub fn is_usize(&self) -> bool {
4831        matches!(self.ty.skip_binder().kind(), TyKind::Uint(rustc_type_ir::UintTy::Usize))
4832    }
4833
4834    pub fn is_float(&self) -> bool {
4835        matches!(self.ty.skip_binder().kind(), TyKind::Float(_))
4836    }
4837
4838    pub fn is_char(&self) -> bool {
4839        matches!(self.ty.skip_binder().kind(), TyKind::Char)
4840    }
4841
4842    pub fn is_int_or_uint(&self) -> bool {
4843        matches!(self.ty.skip_binder().kind(), TyKind::Int(_) | TyKind::Uint(_))
4844    }
4845
4846    pub fn is_scalar(&self) -> bool {
4847        matches!(
4848            self.ty.skip_binder().kind(),
4849            TyKind::Bool | TyKind::Char | TyKind::Int(_) | TyKind::Uint(_) | TyKind::Float(_)
4850        )
4851    }
4852
4853    pub fn is_tuple(&self) -> bool {
4854        matches!(self.ty.skip_binder().kind(), TyKind::Tuple(..))
4855    }
4856
4857    pub fn as_slice(&self) -> Option<Type<'db>> {
4858        match self.ty.skip_binder().kind() {
4859            TyKind::Slice(ty) => Some(self.derived(ty)),
4860            _ => None,
4861        }
4862    }
4863
4864    pub fn strip_references(&self) -> Self {
4865        self.derived(self.ty.skip_binder().strip_references())
4866    }
4867
4868    // FIXME: This is the same as `remove_ref()`, remove one of these methods.
4869    pub fn strip_reference(&self) -> Self {
4870        self.derived(self.ty.skip_binder().strip_reference())
4871    }
4872
4873    pub fn is_unknown(&self) -> bool {
4874        self.ty.skip_binder().is_ty_error()
4875    }
4876
4877    fn krate(&self, db: &'db dyn HirDatabase) -> base_db::Crate {
4878        match self.owner {
4879            TypeOwnerId::GenericDefId(def) => hir_def::HasModule::krate(&def, db),
4880            TypeOwnerId::BuiltinDeriveImplId(def) => {
4881                hir_def::HasModule::krate(&def.loc(db).adt, db)
4882            }
4883            TypeOwnerId::NoParams(krate) => krate,
4884        }
4885    }
4886
4887    fn param_env(&self, db: &'db dyn HirDatabase) -> ParamEnvAndCrate<'db> {
4888        let krate = self.krate(db);
4889        match self.owner {
4890            TypeOwnerId::GenericDefId(def) => {
4891                ParamEnvAndCrate { param_env: db.trait_environment(def), krate }
4892            }
4893            TypeOwnerId::BuiltinDeriveImplId(def) => ParamEnvAndCrate {
4894                param_env: hir_ide::builtin_derive::param_env(DbInterner::new_with(db, krate), def),
4895                krate,
4896            },
4897            TypeOwnerId::NoParams(_) => ParamEnvAndCrate { param_env: ParamEnv::empty(), krate },
4898        }
4899    }
4900
4901    /// Checks that particular type `ty` implements `std::future::IntoFuture` or
4902    /// `std::future::Future` and returns the `Output` associated type.
4903    /// This function is used in `.await` syntax completion.
4904    pub fn into_future_output(&self, db: &'db dyn HirDatabase) -> Option<Type<'db>> {
4905        let env = self.param_env(db);
4906        let lang_items = hir_def::lang_item::lang_items(db, env.krate);
4907        let (trait_, output_assoc_type) = lang_items
4908            .IntoFuture
4909            .zip(lang_items.IntoFutureOutput)
4910            .or(lang_items.Future.zip(lang_items.FutureOutput))?;
4911
4912        if !traits::implements_trait_unique(
4913            self.ty.instantiate_identity().skip_norm_wip(),
4914            db,
4915            env,
4916            trait_,
4917        ) {
4918            return None;
4919        }
4920
4921        self.normalize_trait_assoc_type(db, &[], output_assoc_type.into())
4922    }
4923
4924    /// This does **not** resolve `IntoFuture`, only `Future`.
4925    pub fn future_output(self, db: &'db dyn HirDatabase) -> Option<Type<'db>> {
4926        let krate = self.krate(db);
4927        let lang_items = hir_def::lang_item::lang_items(db, krate);
4928        let future_output = lang_items.FutureOutput?;
4929        self.normalize_trait_assoc_type(db, &[], future_output.into())
4930    }
4931
4932    /// This does **not** resolve `IntoIterator`, only `Iterator`.
4933    pub fn iterator_item(self, db: &'db dyn HirDatabase) -> Option<Type<'db>> {
4934        let krate = self.krate(db);
4935        let lang_items = hir_def::lang_item::lang_items(db, krate);
4936        let iterator_item = lang_items.IteratorItem?;
4937        self.normalize_trait_assoc_type(db, &[], iterator_item.into())
4938    }
4939
4940    pub fn impls_iterator(self, db: &'db dyn HirDatabase) -> bool {
4941        let env = self.param_env(db);
4942        let lang_items = hir_def::lang_item::lang_items(db, env.krate);
4943        let Some(iterator_trait) = lang_items.Iterator else {
4944            return false;
4945        };
4946        traits::implements_trait_unique(
4947            self.ty.instantiate_identity().skip_norm_wip(),
4948            db,
4949            env,
4950            iterator_trait,
4951        )
4952    }
4953
4954    /// Resolves the projection `<Self as IntoIterator>::IntoIter` and returns the resulting type
4955    pub fn into_iterator_iter(self, db: &'db dyn HirDatabase) -> Option<Type<'db>> {
4956        let env = self.param_env(db);
4957        let lang_items = hir_def::lang_item::lang_items(db, env.krate);
4958        let trait_ = lang_items.IntoIterator?;
4959
4960        if !traits::implements_trait_unique(
4961            self.ty.instantiate_identity().skip_norm_wip(),
4962            db,
4963            env,
4964            trait_,
4965        ) {
4966            return None;
4967        }
4968
4969        let into_iter_assoc_type = lang_items.IntoIterIntoIterType?;
4970        self.normalize_trait_assoc_type(db, &[], into_iter_assoc_type.into())
4971    }
4972
4973    /// Checks that particular type `ty` implements `std::ops::FnOnce`.
4974    ///
4975    /// This function can be used to check if a particular type is callable, since FnOnce is a
4976    /// supertrait of Fn and FnMut, so all callable types implements at least FnOnce.
4977    pub fn impls_fnonce(&self, db: &'db dyn HirDatabase) -> bool {
4978        let env = self.param_env(db);
4979        let lang_items = hir_def::lang_item::lang_items(db, env.krate);
4980        let fnonce_trait = match lang_items.FnOnce {
4981            Some(it) => it,
4982            None => return false,
4983        };
4984
4985        traits::implements_trait_unique(
4986            self.ty.instantiate_identity().skip_norm_wip(),
4987            db,
4988            env,
4989            fnonce_trait,
4990        )
4991    }
4992
4993    // FIXME: Find better API that also handles const generics
4994    pub fn impls_trait(&self, db: &'db dyn HirDatabase, trait_: Trait, args: &[Type<'db>]) -> bool {
4995        let env = self.param_env(db);
4996        let interner = DbInterner::new_no_crate(db);
4997        let (args, _owner) =
4998            generic_args_from_tys(interner, trait_.id.into(), iter::once(self).chain(args));
4999        traits::implements_trait_unique_with_args(db, env, trait_.id, args)
5000    }
5001
5002    /// Unlike [`Type::impls_trait()`], which checks whether the type always implements the trait,
5003    /// this check whether there are any generic args substitution for `args`` that will cause the
5004    /// trait to be implemented.
5005    ///
5006    /// For example, suppose we're there's `struct Foo<T>` and we're checking `Foo<T>: Trait`.
5007    /// `impls_trait()` will return true only if there is `impl<T> Trait for Foo<T>`, while this
5008    /// method will also return true if there is only `impl Trait for Foo<i32>`.
5009    ///
5010    /// Note that you can of course instantiate `Foo<T>` with `<i32>` and then the checks will
5011    /// be the same, but this check for *any* substitution.
5012    ///
5013    /// Unlike almost anything that takes more than one type, you *can* pass types from different origins
5014    /// to this function.
5015    pub fn has_any_impl(
5016        &self,
5017        db: &'db dyn HirDatabase,
5018        trait_: Trait,
5019        args: &[Type<'db>],
5020    ) -> bool {
5021        let env = ParamEnvAndCrate { param_env: ParamEnv::empty(), krate: self.krate(db) };
5022        traits::implements_trait_unique_with_infcx(db, env, trait_.id, &mut |infcx| {
5023            let mut args = Self::instantiate_many_with_infer(iter::once(self).chain(args), infcx);
5024            GenericArgs::for_item(infcx.interner, trait_.id.into(), |_, param, _, _| {
5025                if let GenericParamId::TypeParamId(_) = param
5026                    && let Some(arg) = args.next()
5027                {
5028                    arg.into()
5029                } else {
5030                    infcx.var_for_def(param, hir_ide::Span::Dummy)
5031                }
5032            })
5033        })
5034    }
5035
5036    pub fn normalize_trait_assoc_type(
5037        &self,
5038        db: &'db dyn HirDatabase,
5039        args: &[Type<'db>],
5040        alias: TypeAlias,
5041    ) -> Option<Type<'db>> {
5042        let env = self.param_env(db);
5043        let interner = DbInterner::new_with(db, env.krate);
5044        let (args, owner) =
5045            generic_args_from_tys(interner, alias.id.into(), iter::once(self).chain(args));
5046        // FIXME: We don't handle GATs yet.
5047        let projection = Ty::new_alias(
5048            interner,
5049            AliasTy::new_from_args(
5050                interner,
5051                AliasTyKind::Projection { def_id: alias.id.into() },
5052                args,
5053            ),
5054        );
5055
5056        let infcx = interner.infer_ctxt().build(TypingMode::PostAnalysis);
5057        let ty = structurally_normalize_ty(&infcx, projection, env.param_env);
5058        if ty.is_ty_error() { None } else { Some(Type { owner, ty: EarlyBinder::bind(ty) }) }
5059    }
5060
5061    pub fn is_copy(&self, db: &'db dyn HirDatabase) -> bool {
5062        let env = self.param_env(db);
5063        let lang_items = hir_def::lang_item::lang_items(db, env.krate);
5064        let Some(copy_trait) = lang_items.Copy else {
5065            return false;
5066        };
5067        self.impls_trait(db, copy_trait.into(), &[])
5068    }
5069
5070    pub fn as_callable(&self, db: &'db dyn HirDatabase) -> Option<Callable<'db>> {
5071        let interner = DbInterner::new_no_crate(db);
5072        let callee = match self.ty.skip_binder().kind() {
5073            TyKind::Closure(id, subst) => Callee::Closure(id.0, subst),
5074            TyKind::CoroutineClosure(id, subst) => Callee::CoroutineClosure(id.0, subst),
5075            TyKind::FnPtr(..) => Callee::FnPtr,
5076            TyKind::FnDef(id, _) => Callee::Def(id.0),
5077            // This will happen when it implements fn or fn mut, since we add an autoborrow adjustment
5078            TyKind::Ref(_, inner_ty, _) => return self.derived(inner_ty).as_callable(db),
5079            _ => {
5080                let env = self.param_env(db);
5081                let (fn_trait, sig) =
5082                    hir_ide::callable_sig_from_fn_trait(self.ty.skip_binder(), env, db)?;
5083                return Some(Callable {
5084                    ty: self.clone(),
5085                    sig,
5086                    callee: Callee::FnImpl(fn_trait),
5087                    is_bound_method: false,
5088                });
5089            }
5090        };
5091
5092        let sig = self.ty.skip_binder().callable_sig(interner)?;
5093        Some(Callable { ty: self.clone(), sig, callee, is_bound_method: false })
5094    }
5095
5096    pub fn is_closure(&self) -> bool {
5097        matches!(self.ty.skip_binder().kind(), TyKind::Closure { .. })
5098    }
5099
5100    pub fn as_closure(&self) -> Option<Closure<'db>> {
5101        match self.ty.skip_binder().kind() {
5102            TyKind::Closure(id, subst) => {
5103                Some(Closure { id: AnyClosureId::ClosureId(id.0), subst, owner: self.owner })
5104            }
5105            TyKind::CoroutineClosure(id, subst) => Some(Closure {
5106                id: AnyClosureId::CoroutineClosureId(id.0),
5107                subst,
5108                owner: self.owner,
5109            }),
5110            _ => None,
5111        }
5112    }
5113
5114    /// Returns this type as a coroutine.
5115    pub fn as_coroutine(&self) -> Option<Coroutine<'db>> {
5116        match self.ty.skip_binder().kind() {
5117            TyKind::Coroutine(id, _) => Some(Coroutine { id: id.0 }),
5118            _ => None,
5119        }
5120    }
5121
5122    pub fn is_fn(&self) -> bool {
5123        matches!(self.ty.skip_binder().kind(), TyKind::FnDef(..) | TyKind::FnPtr { .. })
5124    }
5125
5126    pub fn is_array(&self) -> bool {
5127        matches!(self.ty.skip_binder().kind(), TyKind::Array(..))
5128    }
5129
5130    pub fn is_packed(&self, _db: &'db dyn HirDatabase) -> bool {
5131        match self.ty.skip_binder().kind() {
5132            TyKind::Adt(adt_def, ..) => adt_def.is_packed(),
5133            _ => false,
5134        }
5135    }
5136
5137    pub fn is_raw_ptr(&self) -> bool {
5138        matches!(self.ty.skip_binder().kind(), TyKind::RawPtr(..))
5139    }
5140
5141    pub fn is_mutable_raw_ptr(&self) -> bool {
5142        // Used outside of rust-analyzer (e.g. by `ra_ap_hir` consumers).
5143        matches!(
5144            self.ty.skip_binder().kind(),
5145            TyKind::RawPtr(.., hir_ide::next_solver::Mutability::Mut)
5146        )
5147    }
5148
5149    pub fn as_raw_ptr(&self) -> Option<(Type<'db>, Mutability)> {
5150        // Used outside of rust-analyzer (e.g. by `ra_ap_hir` consumers).
5151        let TyKind::RawPtr(ty, m) = self.ty.skip_binder().kind() else { return None };
5152        let m = Mutability::from_mutable(matches!(m, hir_ide::next_solver::Mutability::Mut));
5153        Some((self.derived(ty), m))
5154    }
5155
5156    pub fn remove_raw_ptr(&self) -> Option<Type<'db>> {
5157        if let TyKind::RawPtr(ty, _) = self.ty.skip_binder().kind() {
5158            Some(self.derived(ty))
5159        } else {
5160            None
5161        }
5162    }
5163
5164    pub fn contains_unknown(&self) -> bool {
5165        self.ty.skip_binder().references_non_lt_error()
5166    }
5167
5168    pub fn fields(&self, db: &'db dyn HirDatabase) -> Vec<(Field, Self)> {
5169        let interner = DbInterner::new_no_crate(db);
5170        let (variant_id, substs) = match self.ty.skip_binder().kind() {
5171            TyKind::Adt(adt_def, substs) => {
5172                let id = match adt_def.def_id() {
5173                    AdtId::StructId(id) => id.into(),
5174                    AdtId::UnionId(id) => id.into(),
5175                    AdtId::EnumId(_) => return Vec::new(),
5176                };
5177                (id, substs)
5178            }
5179            _ => return Vec::new(),
5180        };
5181
5182        db.field_types(variant_id)
5183            .iter()
5184            .map(|(local_id, field)| {
5185                let def = Field { parent: variant_id.into(), id: local_id };
5186                let ty = field.ty().instantiate(interner, substs).skip_norm_wip();
5187                (def, self.derived(ty))
5188            })
5189            .collect()
5190    }
5191
5192    pub fn tuple_fields(&self, _db: &'db dyn HirDatabase) -> Vec<Self> {
5193        if let TyKind::Tuple(substs) = self.ty.skip_binder().kind() {
5194            substs.iter().map(|ty| self.derived(ty)).collect()
5195        } else {
5196            Vec::new()
5197        }
5198    }
5199
5200    pub fn as_array(&self, db: &'db dyn HirDatabase) -> Option<(Self, usize)> {
5201        if let TyKind::Array(ty, len) = self.ty.skip_binder().kind() {
5202            try_const_usize(db, len).map(|it| (self.derived(ty), it as usize))
5203        } else {
5204            None
5205        }
5206    }
5207
5208    // FIXME: We should probably remove this.
5209    pub fn fingerprint_for_trait_impl(
5210        &self,
5211        db: &'db dyn HirDatabase,
5212    ) -> Option<SimplifiedType<'db>> {
5213        fast_reject::simplify_type(
5214            DbInterner::new_no_crate(db),
5215            self.ty.skip_binder(),
5216            fast_reject::TreatParams::AsRigid,
5217        )
5218    }
5219
5220    /// Returns types that this type dereferences to (including this type itself). The returned
5221    /// iterator won't yield the same type more than once even if the deref chain contains a cycle.
5222    pub fn autoderef(
5223        &self,
5224        db: &'db dyn HirDatabase,
5225    ) -> impl Iterator<Item = Type<'db>> + use<'_, 'db> {
5226        self.autoderef_(db).map(move |ty| self.derived(ty))
5227    }
5228
5229    fn autoderef_(&self, db: &'db dyn HirDatabase) -> impl Iterator<Item = Ty<'db>> {
5230        let interner = DbInterner::new_no_crate(db);
5231        let env = self.param_env(db);
5232        // There should be no inference vars in types passed here
5233        let canonical = hir_ide::replace_errors_with_variables(interner, &self.ty.skip_binder());
5234        autoderef(db, env, canonical)
5235    }
5236
5237    // This would be nicer if it just returned an iterator, but that runs into
5238    // lifetime problems, because we need to borrow temp `CrateImplDefs`.
5239    pub fn iterate_assoc_items<T>(
5240        &self,
5241        db: &'db dyn HirDatabase,
5242        mut callback: impl FnMut(AssocItem) -> Option<T>,
5243    ) -> Option<T> {
5244        let mut slot = None;
5245        self.iterate_assoc_items_dyn(db, &mut |assoc_item_id| {
5246            slot = callback(assoc_item_id.into());
5247            slot.is_some()
5248        });
5249        slot
5250    }
5251
5252    fn iterate_assoc_items_dyn(
5253        &self,
5254        db: &'db dyn HirDatabase,
5255        callback: &mut dyn FnMut(AssocItemId) -> bool,
5256    ) {
5257        let mut handle_impls = |impls: &[ImplId]| {
5258            for &impl_def in impls {
5259                for &(_, item) in impl_def.impl_items(db).items.iter() {
5260                    if callback(item) {
5261                        return;
5262                    }
5263                }
5264            }
5265        };
5266        let krate = self.krate(db);
5267
5268        let interner = DbInterner::new_no_crate(db);
5269        let Some(simplified_type) = fast_reject::simplify_type(
5270            interner,
5271            self.ty.skip_binder(),
5272            fast_reject::TreatParams::AsRigid,
5273        ) else {
5274            return;
5275        };
5276
5277        method_resolution::with_incoherent_inherent_impls(
5278            db,
5279            krate,
5280            &simplified_type,
5281            &mut handle_impls,
5282        );
5283
5284        if let Some(module) = method_resolution::simplified_type_module(db, &simplified_type) {
5285            InherentImpls::for_each_crate_and_block(
5286                db,
5287                module.krate(db),
5288                module.block(db),
5289                &mut |impls| {
5290                    handle_impls(impls.for_self_ty(&simplified_type));
5291                },
5292            );
5293        }
5294    }
5295
5296    /// Iterates its type arguments
5297    ///
5298    /// It iterates the actual type arguments when concrete types are used
5299    /// and otherwise the generic names.
5300    /// It does not include `const` arguments.
5301    ///
5302    /// For code, such as:
5303    /// ```text
5304    /// struct Foo<T, U>
5305    ///
5306    /// impl<U> Foo<String, U>
5307    /// ```
5308    ///
5309    /// It iterates:
5310    /// ```text
5311    /// - "String"
5312    /// - "U"
5313    /// ```
5314    pub fn type_arguments(&self) -> impl Iterator<Item = Type<'db>> + '_ {
5315        match self.ty.skip_binder().strip_references().kind() {
5316            TyKind::Adt(_, substs) => Either::Left(substs.types().map(move |ty| self.derived(ty))),
5317            TyKind::Tuple(substs) => {
5318                Either::Right(Either::Left(substs.iter().map(move |ty| self.derived(ty))))
5319            }
5320            _ => Either::Right(Either::Right(iter::empty())),
5321        }
5322    }
5323
5324    /// Iterates its type and const arguments
5325    ///
5326    /// It iterates the actual type and const arguments when concrete types
5327    /// are used and otherwise the generic names.
5328    ///
5329    /// For code, such as:
5330    /// ```text
5331    /// struct Foo<T, const U: usize, const X: usize>
5332    ///
5333    /// impl<U> Foo<String, U, 12>
5334    /// ```
5335    ///
5336    /// It iterates:
5337    /// ```text
5338    /// - "String"
5339    /// - "U"
5340    /// - "12"
5341    /// ```
5342    pub fn type_and_const_arguments<'a>(
5343        &'a self,
5344        db: &'a dyn HirDatabase,
5345        display_target: DisplayTarget,
5346    ) -> impl Iterator<Item = SmolStr> + 'a {
5347        self.ty
5348            .skip_binder()
5349            .strip_references()
5350            .as_adt()
5351            .into_iter()
5352            .flat_map(|(_, substs)| substs.iter())
5353            .filter_map(move |arg| match arg.kind() {
5354                rustc_type_ir::GenericArgKind::Type(ty) => {
5355                    Some(format_smolstr!("{}", ty.display(db, display_target)))
5356                }
5357                rustc_type_ir::GenericArgKind::Const(const_) => {
5358                    Some(format_smolstr!("{}", const_.display(db, display_target)))
5359                }
5360                rustc_type_ir::GenericArgKind::Lifetime(_) => None,
5361            })
5362    }
5363
5364    /// Combines lifetime indicators, type and constant parameters into a single `Iterator`
5365    pub fn generic_parameters<'a>(
5366        &'a self,
5367        db: &'a dyn HirDatabase,
5368        display_target: DisplayTarget,
5369    ) -> impl Iterator<Item = SmolStr> + 'a {
5370        // iterate the lifetime
5371        self.as_adt()
5372            .and_then(|a| {
5373                // Lifetimes do not need edition-specific handling as they cannot be escaped.
5374                a.lifetime(db).map(|lt| lt.name.display_no_db(Edition::Edition2015).to_smolstr())
5375            })
5376            .into_iter()
5377            // add the type and const parameters
5378            .chain(self.type_and_const_arguments(db, display_target))
5379    }
5380
5381    pub fn iterate_method_candidates_with_traits<T>(
5382        &self,
5383        db: &'db dyn HirDatabase,
5384        scope: &SemanticsScope<'_>,
5385        traits_in_scope: &FxHashSet<TraitId>,
5386        name: Option<&Name>,
5387        mut callback: impl FnMut(Function) -> Option<T>,
5388    ) -> Option<T> {
5389        let _p = tracing::info_span!("iterate_method_candidates_with_traits").entered();
5390        let mut slot = None;
5391        self.iterate_method_candidates_split_inherent(db, scope, traits_in_scope, name, |f| {
5392            match callback(f) {
5393                it @ Some(_) => {
5394                    slot = it;
5395                    ControlFlow::Break(())
5396                }
5397                None => ControlFlow::Continue(()),
5398            }
5399        });
5400        slot
5401    }
5402
5403    pub fn iterate_method_candidates<T>(
5404        &self,
5405        db: &'db dyn HirDatabase,
5406        scope: &SemanticsScope<'_>,
5407        name: Option<&Name>,
5408        callback: impl FnMut(Function) -> Option<T>,
5409    ) -> Option<T> {
5410        self.iterate_method_candidates_with_traits(
5411            db,
5412            scope,
5413            &scope.visible_traits().0,
5414            name,
5415            callback,
5416        )
5417    }
5418
5419    fn with_method_resolution<R>(
5420        &self,
5421        db: &'db dyn HirDatabase,
5422        resolver: &Resolver<'db>,
5423        traits_in_scope: &FxHashSet<TraitId>,
5424        f: impl FnOnce(&MethodResolutionContext<'_, 'db>) -> R,
5425    ) -> R {
5426        let module = resolver.module();
5427        let interner = DbInterner::new_with(db, module.krate(db));
5428        // Most IDE operations want to operate in PostAnalysis mode, revealing opaques. This makes
5429        // for a nicer IDE experience. However, method resolution is always done on real code (either
5430        // existing code or code to be inserted), and there using PostAnalysis is dangerous - we may
5431        // suggest invalid methods. So we're using the TypingMode of the body we're in.
5432        let typing_mode = if let Some(store_owner) = resolver.expression_store_owner() {
5433            TypingMode::analysis_in_body(interner, store_owner.into())
5434        } else {
5435            TypingMode::non_body_analysis()
5436        };
5437        let infcx = interner.infer_ctxt().build(typing_mode);
5438        let features = resolver.top_level_def_map().features();
5439        let environment = self.param_env(db);
5440        let ctx = MethodResolutionContext {
5441            infcx: &infcx,
5442            resolver,
5443            param_env: environment.param_env,
5444            traits_in_scope,
5445            edition: resolver.krate().data(db).edition,
5446            features,
5447            call_span: hir_ide::Span::Dummy,
5448            receiver_span: hir_ide::Span::Dummy,
5449        };
5450        f(&ctx)
5451    }
5452
5453    /// Allows you to treat inherent and non-inherent methods differently.
5454    ///
5455    /// Note that inherent methods may actually be trait methods! For example, in `dyn Trait`, the trait's methods
5456    /// are considered inherent methods.
5457    pub fn iterate_method_candidates_split_inherent(
5458        &self,
5459        db: &'db dyn HirDatabase,
5460        scope: &SemanticsScope<'_>,
5461        traits_in_scope: &FxHashSet<TraitId>,
5462        name: Option<&Name>,
5463        mut callback: impl MethodCandidateCallback,
5464    ) {
5465        let _p = tracing::info_span!(
5466            "iterate_method_candidates_split_inherent",
5467            traits_in_scope = traits_in_scope.len(),
5468            ?name,
5469        )
5470        .entered();
5471
5472        self.with_method_resolution(db, scope.resolver(), traits_in_scope, |ctx| {
5473            // There should be no inference vars in types passed here
5474            let canonical =
5475                hir_ide::replace_errors_with_variables(ctx.infcx.interner, &self.ty.skip_binder());
5476            let (self_ty, _) = ctx.infcx.instantiate_canonical(hir_ide::Span::Dummy, &canonical);
5477
5478            match name {
5479                Some(name) => {
5480                    match ctx.probe_for_name(
5481                        method_resolution::Mode::MethodCall,
5482                        name.clone(),
5483                        self_ty,
5484                    ) {
5485                        Ok(candidate)
5486                        | Err(method_resolution::MethodError::PrivateMatch(candidate)) => {
5487                            let method_resolution::CandidateId::FunctionId(id) = candidate.item
5488                            else {
5489                                unreachable!("`Mode::MethodCall` can only return functions");
5490                            };
5491                            let id = Function { id: AnyFunctionId::FunctionId(id) };
5492                            match candidate.kind {
5493                                method_resolution::PickKind::InherentImplPick(_)
5494                                | method_resolution::PickKind::ObjectPick(..)
5495                                | method_resolution::PickKind::WhereClausePick(..) => {
5496                                    // Candidates from where clauses and trait objects are considered inherent.
5497                                    _ = callback.on_inherent_method(id);
5498                                }
5499                                method_resolution::PickKind::TraitPick(..) => {
5500                                    _ = callback.on_trait_method(id);
5501                                }
5502                            }
5503                        }
5504                        Err(_) => {}
5505                    };
5506                }
5507                None => {
5508                    _ = ctx.probe_all(method_resolution::Mode::MethodCall, self_ty).try_for_each(
5509                        |candidate| {
5510                            let method_resolution::CandidateId::FunctionId(id) =
5511                                candidate.candidate.item
5512                            else {
5513                                unreachable!("`Mode::MethodCall` can only return functions");
5514                            };
5515                            let id = Function { id: AnyFunctionId::FunctionId(id) };
5516                            match candidate.candidate.kind {
5517                                method_resolution::CandidateKind::InherentImplCandidate {
5518                                    ..
5519                                }
5520                                | method_resolution::CandidateKind::ObjectCandidate(..)
5521                                | method_resolution::CandidateKind::WhereClauseCandidate(..) => {
5522                                    // Candidates from where clauses and trait objects are considered inherent.
5523                                    callback.on_inherent_method(id)
5524                                }
5525                                method_resolution::CandidateKind::TraitCandidate(..) => {
5526                                    callback.on_trait_method(id)
5527                                }
5528                            }
5529                        },
5530                    );
5531                }
5532            }
5533        })
5534    }
5535
5536    #[tracing::instrument(skip_all, fields(name = ?name))]
5537    pub fn iterate_path_candidates<T>(
5538        &self,
5539        db: &'db dyn HirDatabase,
5540        scope: &SemanticsScope<'_>,
5541        traits_in_scope: &FxHashSet<TraitId>,
5542        name: Option<&Name>,
5543        mut callback: impl FnMut(AssocItem) -> Option<T>,
5544    ) -> Option<T> {
5545        let _p = tracing::info_span!("iterate_path_candidates").entered();
5546        let mut slot = None;
5547
5548        self.iterate_path_candidates_split_inherent(db, scope, traits_in_scope, name, |item| {
5549            match callback(item) {
5550                it @ Some(_) => {
5551                    slot = it;
5552                    ControlFlow::Break(())
5553                }
5554                None => ControlFlow::Continue(()),
5555            }
5556        });
5557        slot
5558    }
5559
5560    /// Iterates over inherent methods.
5561    ///
5562    /// In some circumstances, inherent methods methods may actually be trait methods!
5563    /// For example, when `dyn Trait` is a receiver, _trait_'s methods would be considered
5564    /// to be inherent methods.
5565    #[tracing::instrument(skip_all, fields(name = ?name))]
5566    pub fn iterate_path_candidates_split_inherent(
5567        &self,
5568        db: &'db dyn HirDatabase,
5569        scope: &SemanticsScope<'_>,
5570        traits_in_scope: &FxHashSet<TraitId>,
5571        name: Option<&Name>,
5572        mut callback: impl PathCandidateCallback,
5573    ) {
5574        let _p = tracing::info_span!(
5575            "iterate_path_candidates_split_inherent",
5576            traits_in_scope = traits_in_scope.len(),
5577            ?name,
5578        )
5579        .entered();
5580
5581        self.with_method_resolution(db, scope.resolver(), traits_in_scope, |ctx| {
5582            // There should be no inference vars in types passed here
5583            let canonical =
5584                hir_ide::replace_errors_with_variables(ctx.infcx.interner, &self.ty.skip_binder());
5585            let (self_ty, _) = ctx.infcx.instantiate_canonical(hir_ide::Span::Dummy, &canonical);
5586
5587            match name {
5588                Some(name) => {
5589                    match ctx.probe_for_name(method_resolution::Mode::Path, name.clone(), self_ty) {
5590                        Ok(candidate)
5591                        | Err(method_resolution::MethodError::PrivateMatch(candidate)) => {
5592                            let id = candidate.item.into();
5593                            match candidate.kind {
5594                                method_resolution::PickKind::InherentImplPick(_)
5595                                | method_resolution::PickKind::ObjectPick(..)
5596                                | method_resolution::PickKind::WhereClausePick(..) => {
5597                                    // Candidates from where clauses and trait objects are considered inherent.
5598                                    _ = callback.on_inherent_item(id);
5599                                }
5600                                method_resolution::PickKind::TraitPick(..) => {
5601                                    _ = callback.on_trait_item(id);
5602                                }
5603                            }
5604                        }
5605                        Err(_) => {}
5606                    };
5607                }
5608                None => {
5609                    _ = ctx.probe_all(method_resolution::Mode::Path, self_ty).try_for_each(
5610                        |candidate| {
5611                            let id = candidate.candidate.item.into();
5612                            match candidate.candidate.kind {
5613                                method_resolution::CandidateKind::InherentImplCandidate {
5614                                    ..
5615                                }
5616                                | method_resolution::CandidateKind::ObjectCandidate(..)
5617                                | method_resolution::CandidateKind::WhereClauseCandidate(..) => {
5618                                    // Candidates from where clauses and trait objects are considered inherent.
5619                                    callback.on_inherent_item(id)
5620                                }
5621                                method_resolution::CandidateKind::TraitCandidate(..) => {
5622                                    callback.on_trait_item(id)
5623                                }
5624                            }
5625                        },
5626                    );
5627                }
5628            }
5629        })
5630    }
5631
5632    pub fn as_adt(&self) -> Option<Adt> {
5633        let (adt, _subst) = self.ty.skip_binder().as_adt()?;
5634        Some(adt.into())
5635    }
5636
5637    /// Holes in the args can come from lifetime/const params.
5638    pub fn as_adt_with_args(&self) -> Option<(Adt, Vec<Option<Type<'db>>>)> {
5639        let (adt, args) = self.ty.skip_binder().as_adt()?;
5640        let args = args.iter().map(|arg| Some(self.derived(arg.ty()?))).collect();
5641        Some((adt.into(), args))
5642    }
5643
5644    pub fn as_builtin(&self) -> Option<BuiltinType> {
5645        self.ty.skip_binder().as_builtin().map(|inner| BuiltinType { inner })
5646    }
5647
5648    pub fn as_dyn_trait(&self) -> Option<Trait> {
5649        self.ty.skip_binder().dyn_trait().map(Into::into)
5650    }
5651
5652    /// If a type can be represented as `dyn Trait`, returns all traits accessible via this type,
5653    /// or an empty iterator otherwise.
5654    pub fn applicable_inherent_traits(
5655        &self,
5656        db: &'db dyn HirDatabase,
5657    ) -> impl Iterator<Item = Trait> {
5658        let _p = tracing::info_span!("applicable_inherent_traits").entered();
5659        self.autoderef_(db)
5660            .filter_map(|ty| ty.dyn_trait())
5661            .flat_map(move |dyn_trait_id| hir_ide::all_super_traits(db, dyn_trait_id))
5662            .copied()
5663            .map(Trait::from)
5664    }
5665
5666    pub fn env_traits(&self, db: &'db dyn HirDatabase) -> impl Iterator<Item = Trait> {
5667        let _p = tracing::info_span!("env_traits").entered();
5668        let env = self.param_env(db);
5669        self.autoderef_(db)
5670            .filter(|ty| matches!(ty.kind(), TyKind::Param(_)))
5671            .flat_map(move |ty| {
5672                env.param_env
5673                    .clauses()
5674                    .iter()
5675                    .filter_map(move |pred| match pred.kind().skip_binder() {
5676                        ClauseKind::Trait(tr) if tr.self_ty() == ty => Some(tr.def_id().0),
5677                        _ => None,
5678                    })
5679                    .flat_map(|t| hir_ide::all_super_traits(db, t))
5680                    .copied()
5681            })
5682            .map(Trait::from)
5683    }
5684
5685    pub fn as_impl_traits(&self, db: &'db dyn HirDatabase) -> Option<impl Iterator<Item = Trait>> {
5686        self.ty.skip_binder().impl_trait_bounds(db).map(|it| {
5687            it.into_iter().filter_map(|pred| match pred.kind().skip_binder() {
5688                ClauseKind::Trait(trait_ref) => Some(Trait::from(trait_ref.def_id().0)),
5689                _ => None,
5690            })
5691        })
5692    }
5693
5694    pub fn as_associated_type_parent_trait(&self, db: &'db dyn HirDatabase) -> Option<Trait> {
5695        let TyKind::Alias(AliasTy { kind: AliasTyKind::Projection { def_id }, .. }) =
5696            self.ty.skip_binder().kind()
5697        else {
5698            return None;
5699        };
5700        match def_id.0.loc(db).container {
5701            ItemContainerId::TraitId(id) => Some(Trait { id }),
5702            _ => None,
5703        }
5704    }
5705
5706    fn derived(&self, ty: Ty<'db>) -> Self {
5707        Type { owner: self.owner, ty: EarlyBinder::bind(ty) }
5708    }
5709
5710    /// Visits every type, including generic arguments, in this type. `callback` is called with type
5711    /// itself first, and then with its generic arguments.
5712    pub fn walk(&self, db: &'db dyn HirDatabase, callback: impl FnMut(Type<'db>)) {
5713        struct Visitor<'db, F> {
5714            db: &'db dyn HirDatabase,
5715            owner: TypeOwnerId,
5716            callback: F,
5717            visited: FxHashSet<Ty<'db>>,
5718        }
5719        impl<'db, F> TypeVisitor<DbInterner<'db>> for Visitor<'db, F>
5720        where
5721            F: FnMut(Type<'db>),
5722        {
5723            type Result = ();
5724
5725            fn visit_ty(&mut self, ty: Ty<'db>) -> Self::Result {
5726                if !self.visited.insert(ty) {
5727                    return;
5728                }
5729
5730                (self.callback)(Type { owner: self.owner, ty: EarlyBinder::bind(ty) });
5731
5732                if let Some(bounds) = ty.impl_trait_bounds(self.db) {
5733                    bounds.visit_with(self);
5734                }
5735
5736                ty.super_visit_with(self);
5737            }
5738        }
5739
5740        let mut visitor =
5741            Visitor { db, owner: self.owner, callback, visited: FxHashSet::default() };
5742        self.ty.skip_binder().visit_with(&mut visitor);
5743    }
5744    /// Check if type unifies with another type.
5745    ///
5746    /// Note that we consider placeholder types to unify with everything.
5747    /// For example `Option<T>` and `Option<U>` unify although there is unresolved goal `T = U`.
5748    pub fn could_unify_with(&self, db: &'db dyn HirDatabase, other: &Type<'db>) -> bool {
5749        self.owner.must_unify(other.owner);
5750        let env = self.param_env(db);
5751        let interner = DbInterner::new_no_crate(db);
5752        let tys = hir_ide::replace_errors_with_variables(
5753            interner,
5754            &(self.ty.skip_binder(), other.ty.skip_binder()),
5755        );
5756        hir_ide::could_unify(db, env, &tys)
5757    }
5758
5759    /// Check if type unifies with another type eagerly making sure there are no unresolved goals.
5760    ///
5761    /// This means that placeholder types are not considered to unify if there are any bounds set on
5762    /// them. For example `Option<T>` and `Option<U>` do not unify as we cannot show that `T = U`
5763    pub fn could_unify_with_deeply(&self, db: &'db dyn HirDatabase, other: &Type<'db>) -> bool {
5764        self.owner.must_unify(other.owner);
5765        let env = self.param_env(db);
5766        let interner = DbInterner::new_no_crate(db);
5767        let tys = hir_ide::replace_errors_with_variables(
5768            interner,
5769            &(self.ty.skip_binder(), other.ty.skip_binder()),
5770        );
5771        hir_ide::could_unify_deeply(db, env, &tys)
5772    }
5773
5774    pub fn could_coerce_to(&self, db: &'db dyn HirDatabase, to: &Type<'db>) -> bool {
5775        self.owner.must_unify(to.owner);
5776        let env = self.param_env(db);
5777        let interner = DbInterner::new_no_crate(db);
5778        let tys = hir_ide::replace_errors_with_variables(
5779            interner,
5780            &(self.ty.skip_binder(), to.ty.skip_binder()),
5781        );
5782        hir_ide::could_coerce(db, env, &tys)
5783    }
5784
5785    pub fn as_type_param(&self, _db: &'db dyn HirDatabase) -> Option<TypeParam> {
5786        match self.ty.skip_binder().kind() {
5787            TyKind::Param(param) => Some(TypeParam { id: param.id }),
5788            _ => None,
5789        }
5790    }
5791
5792    /// Returns unique `GenericParam`s contained in this type.
5793    pub fn generic_params(&self, db: &'db dyn HirDatabase) -> FxHashSet<GenericParam> {
5794        hir_ide::collect_params(&self.ty.skip_binder())
5795            .into_iter()
5796            .map(|id| TypeOrConstParam { id }.split(db).either_into())
5797            .collect()
5798    }
5799
5800    pub fn layout(&self, db: &'db dyn HirDatabase) -> Result<Layout<'db>, LayoutError> {
5801        let env = self.param_env(db);
5802        db.layout_of_ty(self.ty.skip_binder().store(), env.store())
5803            .map(|layout| Layout(layout, db.target_data_layout(env.krate).unwrap()))
5804    }
5805
5806    pub fn drop_glue(&self, db: &'db dyn HirDatabase) -> DropGlue {
5807        let env = self.param_env(db);
5808        let interner = DbInterner::new_with(db, env.krate);
5809        let infcx = interner.infer_ctxt().build(TypingMode::PostAnalysis);
5810        hir_ide::drop::has_drop_glue(&infcx, self.ty.skip_binder(), env.param_env)
5811    }
5812}
5813
5814#[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)]
5815pub struct InlineAsmOperand {
5816    owner: ExpressionStoreOwnerId,
5817    expr: ExprId,
5818    index: usize,
5819}
5820
5821impl InlineAsmOperand {
5822    pub fn parent(self, _db: &dyn HirDatabase) -> ExpressionStoreOwner {
5823        self.owner.into()
5824    }
5825
5826    pub fn name(&self, db: &dyn HirDatabase) -> Option<Name> {
5827        let body = ExpressionStore::of(db, self.owner);
5828        match &body[self.expr] {
5829            hir_def::hir::Expr::InlineAsm(e) => e.operands.get(self.index)?.0.clone(),
5830            _ => None,
5831        }
5832    }
5833}
5834
5835// FIXME: Document this
5836#[derive(Debug)]
5837pub struct Callable<'db> {
5838    ty: Type<'db>,
5839    sig: PolyFnSig<'db>,
5840    callee: Callee<'db>,
5841    /// Whether this is a method that was called with method call syntax.
5842    is_bound_method: bool,
5843}
5844
5845#[derive(Clone, PartialEq, Eq, Hash, Debug)]
5846enum Callee<'db> {
5847    Def(CallableDefId),
5848    Closure(InternedClosureId<'db>, GenericArgs<'db>),
5849    CoroutineClosure(InternedCoroutineClosureId<'db>, GenericArgs<'db>),
5850    FnPtr,
5851    FnImpl(traits::FnTrait),
5852    BuiltinDeriveImplMethod { method: BuiltinDeriveImplMethod, impl_: BuiltinDeriveImplId },
5853}
5854
5855pub enum CallableKind<'db> {
5856    Function(Function),
5857    TupleStruct(Struct),
5858    TupleEnumVariant(EnumVariant),
5859    Closure(Closure<'db>),
5860    FnPtr,
5861    FnImpl(FnTrait),
5862}
5863
5864impl<'db> Callable<'db> {
5865    fn erased_sig(&self, db: &'db dyn HirDatabase) -> FnSig<'db> {
5866        DbInterner::new_no_crate(db).instantiate_bound_regions_with_erased(self.sig)
5867    }
5868
5869    pub fn kind(&self) -> CallableKind<'db> {
5870        match self.callee {
5871            Callee::Def(CallableDefId::FunctionId(it)) => CallableKind::Function(it.into()),
5872            Callee::BuiltinDeriveImplMethod { method, impl_ } => CallableKind::Function(Function {
5873                id: AnyFunctionId::BuiltinDeriveImplMethod { method, impl_ },
5874            }),
5875            Callee::Def(CallableDefId::StructId(it)) => CallableKind::TupleStruct(it.into()),
5876            Callee::Def(CallableDefId::EnumVariantId(it)) => {
5877                CallableKind::TupleEnumVariant(it.into())
5878            }
5879            Callee::Closure(id, subst) => CallableKind::Closure(Closure {
5880                id: AnyClosureId::ClosureId(id),
5881                subst,
5882                owner: self.ty.owner,
5883            }),
5884            Callee::CoroutineClosure(id, subst) => CallableKind::Closure(Closure {
5885                id: AnyClosureId::CoroutineClosureId(id),
5886                subst,
5887                owner: self.ty.owner,
5888            }),
5889            Callee::FnPtr => CallableKind::FnPtr,
5890            Callee::FnImpl(fn_) => CallableKind::FnImpl(fn_.into()),
5891        }
5892    }
5893
5894    pub fn as_function(&self) -> Option<Function> {
5895        match self.callee {
5896            Callee::Def(CallableDefId::FunctionId(it)) => Some(it.into()),
5897            Callee::BuiltinDeriveImplMethod { method, impl_ } => {
5898                Some(Function { id: AnyFunctionId::BuiltinDeriveImplMethod { method, impl_ } })
5899            }
5900            _ => None,
5901        }
5902    }
5903
5904    pub fn receiver_param(&self, db: &'db dyn HirDatabase) -> Option<(SelfParam, Type<'db>)> {
5905        if !self.is_bound_method {
5906            return None;
5907        }
5908        let func = self.as_function()?;
5909        Some((func.self_param(db)?, self.ty.derived(self.erased_sig(db).inputs()[0])))
5910    }
5911    pub fn n_params(&self) -> usize {
5912        self.sig.skip_binder().inputs_and_output.inputs().len()
5913            - if self.is_bound_method { 1 } else { 0 }
5914    }
5915    pub fn params(&self, db: &'db dyn HirDatabase) -> Vec<Param<'db>> {
5916        self.erased_sig(db)
5917            .inputs()
5918            .iter()
5919            .enumerate()
5920            .skip(if self.is_bound_method { 1 } else { 0 })
5921            .map(|(idx, ty)| (idx, self.ty.derived(*ty)))
5922            .map(|(idx, ty)| Param { func: self.callee.clone(), idx, ty })
5923            .collect()
5924    }
5925    pub fn return_type(&self, db: &'db dyn HirDatabase) -> Type<'db> {
5926        self.ty.derived(self.erased_sig(db).output())
5927    }
5928    pub fn sig(&self) -> impl Eq {
5929        &self.sig
5930    }
5931
5932    pub fn ty(&self) -> &Type<'db> {
5933        &self.ty
5934    }
5935}
5936
5937#[derive(Clone, Debug, Eq, PartialEq)]
5938pub struct Layout<'db>(Arc<TyLayout>, &'db TargetDataLayout);
5939
5940impl<'db> Layout<'db> {
5941    pub fn size(&self) -> u64 {
5942        self.0.size.bytes()
5943    }
5944
5945    pub fn align(&self) -> u64 {
5946        self.0.align.bytes()
5947    }
5948
5949    pub fn niches(&self) -> Option<u128> {
5950        Some(self.0.largest_niche?.available(self.1))
5951    }
5952
5953    pub fn field_offset(&self, field: Field) -> Option<u64> {
5954        match self.0.fields {
5955            layout::FieldsShape::Primitive => None,
5956            layout::FieldsShape::Union(_) => Some(0),
5957            layout::FieldsShape::Array { stride, count } => {
5958                let i = u64::try_from(field.index()).ok()?;
5959                (i < count).then_some((stride * i).bytes())
5960            }
5961            layout::FieldsShape::Arbitrary { ref offsets, .. } => {
5962                Some(offsets.get(RustcFieldIdx(field.id))?.bytes())
5963            }
5964        }
5965    }
5966
5967    pub fn tuple_field_offset(&self, field: usize) -> Option<u64> {
5968        match self.0.fields {
5969            layout::FieldsShape::Primitive => None,
5970            layout::FieldsShape::Union(_) => Some(0),
5971            layout::FieldsShape::Array { stride, count } => {
5972                let i = u64::try_from(field).ok()?;
5973                (i < count).then_some((stride * i).bytes())
5974            }
5975            layout::FieldsShape::Arbitrary { ref offsets, .. } => {
5976                Some(offsets.get(RustcFieldIdx::new(field))?.bytes())
5977            }
5978        }
5979    }
5980
5981    pub fn tail_padding(&self, field_size: &mut impl FnMut(usize) -> Option<u64>) -> Option<u64> {
5982        match self.0.fields {
5983            layout::FieldsShape::Primitive => None,
5984            layout::FieldsShape::Union(_) => None,
5985            layout::FieldsShape::Array { stride, count } => count.checked_sub(1).and_then(|tail| {
5986                let tail_field_size = field_size(tail as usize)?;
5987                let offset = stride.bytes() * tail;
5988                self.0.size.bytes().checked_sub(offset)?.checked_sub(tail_field_size)
5989            }),
5990            layout::FieldsShape::Arbitrary { ref offsets, ref in_memory_order } => {
5991                let tail = in_memory_order[in_memory_order.len().checked_sub(1)? as u32];
5992                let tail_field_size = field_size(tail.0.into_raw().into_u32() as usize)?;
5993                let offset = offsets.get(tail)?.bytes();
5994                self.0.size.bytes().checked_sub(offset)?.checked_sub(tail_field_size)
5995            }
5996        }
5997    }
5998
5999    pub fn largest_padding(
6000        &self,
6001        field_size: &mut impl FnMut(usize) -> Option<u64>,
6002    ) -> Option<u64> {
6003        match self.0.fields {
6004            layout::FieldsShape::Primitive => None,
6005            layout::FieldsShape::Union(_) => None,
6006            layout::FieldsShape::Array { stride: _, count: 0 } => None,
6007            layout::FieldsShape::Array { stride, .. } => {
6008                let size = field_size(0)?;
6009                stride.bytes().checked_sub(size)
6010            }
6011            layout::FieldsShape::Arbitrary { ref offsets, ref in_memory_order } => {
6012                let mut reverse_index = vec![None; in_memory_order.len()];
6013                for (mem, src) in in_memory_order.iter().enumerate() {
6014                    reverse_index[mem] =
6015                        Some((src.0.into_raw().into_u32() as usize, offsets[*src].bytes()));
6016                }
6017                if reverse_index.iter().any(|it| it.is_none()) {
6018                    stdx::never!();
6019                    return None;
6020                }
6021                reverse_index
6022                    .into_iter()
6023                    .flatten()
6024                    .chain(iter::once((0, self.0.size.bytes())))
6025                    .array_windows()
6026                    .filter_map(|[(i, start), (_, end)]| {
6027                        let size = field_size(i)?;
6028                        end.checked_sub(start)?.checked_sub(size)
6029                    })
6030                    .max()
6031            }
6032        }
6033    }
6034
6035    pub fn enum_tag_size(&self) -> Option<usize> {
6036        let tag_size =
6037            if let layout::Variants::Multiple { tag, tag_encoding, .. } = &self.0.variants {
6038                match tag_encoding {
6039                    TagEncoding::Direct => tag.size(self.1).bytes_usize(),
6040                    TagEncoding::Niche { .. } => 0,
6041                }
6042            } else {
6043                return None;
6044            };
6045        Some(tag_size)
6046    }
6047}
6048
6049#[derive(Copy, Clone, Debug, Eq, PartialEq)]
6050pub enum BindingMode {
6051    Move,
6052    Ref(Mutability),
6053}
6054
6055/// For IDE only
6056#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
6057pub enum ScopeDef<'db> {
6058    ModuleDef(ModuleDef),
6059    GenericParam(GenericParam),
6060    ImplSelfType(Impl),
6061    AdtSelfType(Adt),
6062    Local(Local<'db>),
6063    Label(Label),
6064    Unknown,
6065}
6066
6067impl ScopeDef<'_> {
6068    pub fn all_items(def: PerNs) -> ArrayVec<Self, 3> {
6069        let mut items = ArrayVec::new();
6070
6071        match (def.take_types(), def.take_values()) {
6072            (Some(m1), None) => items.push(ScopeDef::ModuleDef(m1.into())),
6073            (None, Some(m2)) => items.push(ScopeDef::ModuleDef(m2.into())),
6074            (Some(m1), Some(m2)) => {
6075                // Some items, like unit structs and enum variants, are
6076                // returned as both a type and a value. Here we want
6077                // to de-duplicate them.
6078                if m1 != m2 {
6079                    items.push(ScopeDef::ModuleDef(m1.into()));
6080                    items.push(ScopeDef::ModuleDef(m2.into()));
6081                } else {
6082                    items.push(ScopeDef::ModuleDef(m1.into()));
6083                }
6084            }
6085            (None, None) => {}
6086        };
6087
6088        if let Some(macro_def_id) = def.take_macros() {
6089            items.push(ScopeDef::ModuleDef(ModuleDef::Macro(macro_def_id.into())));
6090        }
6091
6092        if items.is_empty() {
6093            items.push(ScopeDef::Unknown);
6094        }
6095
6096        items
6097    }
6098
6099    pub fn attrs(&self, db: &dyn HirDatabase) -> Option<AttrsWithOwner> {
6100        match self {
6101            ScopeDef::ModuleDef(it) => it.attrs(db),
6102            ScopeDef::GenericParam(it) => Some(it.attrs(db)),
6103            ScopeDef::ImplSelfType(_)
6104            | ScopeDef::AdtSelfType(_)
6105            | ScopeDef::Local(_)
6106            | ScopeDef::Label(_)
6107            | ScopeDef::Unknown => None,
6108        }
6109    }
6110
6111    pub fn krate(&self, db: &dyn HirDatabase) -> Option<Crate> {
6112        match self {
6113            ScopeDef::ModuleDef(it) => it.module(db).map(|m| m.krate(db)),
6114            ScopeDef::GenericParam(it) => Some(it.module(db).krate(db)),
6115            ScopeDef::ImplSelfType(_) => None,
6116            ScopeDef::AdtSelfType(it) => Some(it.module(db).krate(db)),
6117            ScopeDef::Local(it) => Some(it.module(db).krate(db)),
6118            ScopeDef::Label(it) => Some(it.module(db).krate(db)),
6119            ScopeDef::Unknown => None,
6120        }
6121    }
6122}
6123
6124impl_from!(
6125    impl<'db>
6126    ItemInNs { Types => ModuleDef, Values => ModuleDef, Macros => ModuleDef }
6127    for ScopeDef<'db>
6128);
6129
6130#[derive(Clone, Debug, PartialEq, Eq)]
6131pub struct Adjustment<'db> {
6132    pub source: Type<'db>,
6133    pub target: Type<'db>,
6134    pub kind: Adjust,
6135}
6136
6137#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
6138pub enum Adjust {
6139    /// Go from ! to any type.
6140    NeverToAny,
6141    /// Dereference once, producing a place.
6142    Deref(Option<OverloadedDeref>),
6143    /// Take the address and produce either a `&` or `*` pointer.
6144    Borrow(AutoBorrow),
6145    Pointer(PointerCast),
6146}
6147
6148#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
6149pub enum AutoBorrow {
6150    /// Converts from T to &T.
6151    Ref(Mutability),
6152    /// Converts from T to *T.
6153    RawPtr(Mutability),
6154}
6155
6156#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
6157pub struct OverloadedDeref(pub Mutability);
6158
6159pub trait HasVisibility {
6160    fn visibility(&self, db: &dyn HirDatabase) -> Visibility;
6161    fn is_visible_from(&self, db: &dyn HirDatabase, module: Module) -> bool {
6162        let vis = self.visibility(db);
6163        vis.is_visible_from(db, module.id)
6164    }
6165}
6166
6167#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6168pub enum PredicatePolarity {
6169    /// `T: Trait`
6170    Positive,
6171    /// `T: !Trait`
6172    Negative,
6173}
6174
6175#[derive(Debug, Clone, PartialEq, Eq)]
6176pub struct TraitPredicate<'db> {
6177    inner: hir_ide::next_solver::TraitPredicate<'db>,
6178    owner: TypeOwnerId,
6179}
6180
6181impl<'db> TraitPredicate<'db> {
6182    pub fn polarity(&self) -> PredicatePolarity {
6183        match self.inner.polarity {
6184            rustc_type_ir::PredicatePolarity::Positive => PredicatePolarity::Positive,
6185            rustc_type_ir::PredicatePolarity::Negative => PredicatePolarity::Negative,
6186        }
6187    }
6188
6189    pub fn trait_ref(&self) -> TraitRef<'db> {
6190        TraitRef { owner: self.owner, trait_ref: self.inner.trait_ref }
6191    }
6192}
6193
6194/// Trait for obtaining the defining crate of an item.
6195pub trait HasCrate {
6196    fn krate(&self, db: &dyn HirDatabase) -> Crate;
6197}
6198
6199impl<T: hir_def::HasModule> HasCrate for T {
6200    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6201        self.module(db).krate(db).into()
6202    }
6203}
6204
6205impl HasCrate for AssocItem {
6206    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6207        self.module(db).krate(db)
6208    }
6209}
6210
6211impl HasCrate for Struct {
6212    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6213        self.module(db).krate(db)
6214    }
6215}
6216
6217impl HasCrate for Union {
6218    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6219        self.module(db).krate(db)
6220    }
6221}
6222
6223impl HasCrate for Enum {
6224    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6225        self.module(db).krate(db)
6226    }
6227}
6228
6229impl HasCrate for Field {
6230    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6231        self.parent_def(db).module(db).krate(db)
6232    }
6233}
6234
6235impl HasCrate for EnumVariant {
6236    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6237        self.module(db).krate(db)
6238    }
6239}
6240
6241impl HasCrate for Function {
6242    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6243        self.module(db).krate(db)
6244    }
6245}
6246
6247impl HasCrate for Const {
6248    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6249        self.module(db).krate(db)
6250    }
6251}
6252
6253impl HasCrate for TypeAlias {
6254    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6255        self.module(db).krate(db)
6256    }
6257}
6258
6259impl HasCrate for Type<'_> {
6260    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6261        self.krate(db).into()
6262    }
6263}
6264
6265impl HasCrate for Macro {
6266    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6267        self.module(db).krate(db)
6268    }
6269}
6270
6271impl HasCrate for Trait {
6272    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6273        self.module(db).krate(db)
6274    }
6275}
6276
6277impl HasCrate for Static {
6278    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6279        self.module(db).krate(db)
6280    }
6281}
6282
6283impl HasCrate for Adt {
6284    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6285        self.module(db).krate(db)
6286    }
6287}
6288
6289impl HasCrate for Impl {
6290    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6291        self.module(db).krate(db)
6292    }
6293}
6294
6295impl HasCrate for Module {
6296    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6297        Module::krate(*self, db)
6298    }
6299}
6300
6301impl<'db> HasCrate for AnonConst<'db> {
6302    fn krate(&self, db: &dyn HirDatabase) -> Crate {
6303        hir_def::HasModule::krate(&self.id.loc(db).owner, db).into()
6304    }
6305}
6306
6307pub trait HasContainer {
6308    fn container(&self, db: &dyn HirDatabase) -> ItemContainer;
6309}
6310
6311impl HasContainer for ExternCrateDecl {
6312    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
6313        container_id_to_hir(self.id.lookup(db).container.into())
6314    }
6315}
6316
6317impl HasContainer for Module {
6318    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
6319        // FIXME: handle block expressions as modules (their parent is in a different DefMap)
6320        let def_map = self.id.def_map(db);
6321        match def_map[self.id].parent {
6322            Some(parent_id) => ItemContainer::Module(Module { id: parent_id }),
6323            None => ItemContainer::Crate(def_map.krate().into()),
6324        }
6325    }
6326}
6327
6328impl HasContainer for Function {
6329    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
6330        match self.id {
6331            AnyFunctionId::FunctionId(id) => container_id_to_hir(id.lookup(db).container),
6332            AnyFunctionId::BuiltinDeriveImplMethod { impl_, .. } => {
6333                ItemContainer::Impl(Impl { id: AnyImplId::BuiltinDeriveImplId(impl_) })
6334            }
6335        }
6336    }
6337}
6338
6339impl HasContainer for Struct {
6340    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
6341        ItemContainer::Module(Module { id: self.id.lookup(db).container })
6342    }
6343}
6344
6345impl HasContainer for Union {
6346    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
6347        ItemContainer::Module(Module { id: self.id.lookup(db).container })
6348    }
6349}
6350
6351impl HasContainer for Enum {
6352    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
6353        ItemContainer::Module(Module { id: self.id.lookup(db).container })
6354    }
6355}
6356
6357impl HasContainer for TypeAlias {
6358    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
6359        container_id_to_hir(self.id.lookup(db).container)
6360    }
6361}
6362
6363impl HasContainer for Const {
6364    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
6365        container_id_to_hir(self.id.lookup(db).container)
6366    }
6367}
6368
6369impl HasContainer for Static {
6370    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
6371        container_id_to_hir(self.id.lookup(db).container)
6372    }
6373}
6374
6375impl HasContainer for Trait {
6376    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
6377        ItemContainer::Module(Module { id: self.id.lookup(db).container })
6378    }
6379}
6380
6381impl HasContainer for ExternBlock {
6382    fn container(&self, db: &dyn HirDatabase) -> ItemContainer {
6383        ItemContainer::Module(Module { id: self.id.lookup(db).container })
6384    }
6385}
6386
6387pub trait HasName {
6388    fn name(&self, db: &dyn HirDatabase) -> Option<Name>;
6389}
6390
6391macro_rules! impl_has_name {
6392    ( $( $ty:ident ),* $(,)? ) => {
6393        $(
6394            impl HasName for $ty {
6395                fn name(&self, db: &dyn HirDatabase) -> Option<Name> {
6396                    (*self).name(db).into()
6397                }
6398            }
6399        )*
6400    };
6401}
6402
6403impl_has_name!(
6404    ModuleDef,
6405    Module,
6406    Field,
6407    Struct,
6408    Union,
6409    Enum,
6410    EnumVariant,
6411    Adt,
6412    Variant,
6413    DefWithBody,
6414    Function,
6415    ExternCrateDecl,
6416    Const,
6417    Static,
6418    Trait,
6419    TypeAlias,
6420    Macro,
6421    ExternAssocItem,
6422    AssocItem,
6423    DeriveHelper,
6424    ToolModule,
6425    Label,
6426    GenericParam,
6427    TypeParam,
6428    LifetimeParam,
6429    ConstParam,
6430    TypeOrConstParam,
6431    InlineAsmOperand,
6432);
6433
6434macro_rules! impl_has_name_no_db {
6435    ( $( $ty:ident ),* $(,)? ) => {
6436        $(
6437            impl HasName for $ty {
6438                fn name(&self, _db: &dyn HirDatabase) -> Option<Name> {
6439                    (*self).name().into()
6440                }
6441            }
6442        )*
6443    };
6444}
6445
6446impl_has_name_no_db!(StaticLifetime, BuiltinType, BuiltinAttr);
6447
6448impl HasName for Local<'_> {
6449    fn name(&self, db: &dyn HirDatabase) -> Option<Name> {
6450        (*self).name(db).into()
6451    }
6452}
6453
6454impl HasName for TupleField<'_> {
6455    fn name(&self, _db: &dyn HirDatabase) -> Option<Name> {
6456        (*self).name().into()
6457    }
6458}
6459
6460impl HasName for Param<'_> {
6461    fn name(&self, db: &dyn HirDatabase) -> Option<Name> {
6462        self.name(db)
6463    }
6464}
6465
6466fn container_id_to_hir(c: ItemContainerId) -> ItemContainer {
6467    match c {
6468        ItemContainerId::ExternBlockId(id) => ItemContainer::ExternBlock(ExternBlock { id }),
6469        ItemContainerId::ModuleId(id) => ItemContainer::Module(Module { id }),
6470        ItemContainerId::ImplId(id) => ItemContainer::Impl(id.into()),
6471        ItemContainerId::TraitId(id) => ItemContainer::Trait(Trait { id }),
6472    }
6473}
6474
6475#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6476pub enum ItemContainer {
6477    Trait(Trait),
6478    Impl(Impl),
6479    Module(Module),
6480    ExternBlock(ExternBlock),
6481    Crate(Crate),
6482}
6483
6484/// Subset of `ide_db::Definition` that doc links can resolve to.
6485pub enum DocLinkDef {
6486    ModuleDef(ModuleDef),
6487    Field(Field),
6488    SelfType(Trait),
6489}
6490
6491pub trait MethodCandidateCallback {
6492    fn on_inherent_method(&mut self, f: Function) -> ControlFlow<()>;
6493
6494    fn on_trait_method(&mut self, f: Function) -> ControlFlow<()>;
6495}
6496
6497impl<F> MethodCandidateCallback for F
6498where
6499    F: FnMut(Function) -> ControlFlow<()>,
6500{
6501    fn on_inherent_method(&mut self, f: Function) -> ControlFlow<()> {
6502        self(f)
6503    }
6504
6505    fn on_trait_method(&mut self, f: Function) -> ControlFlow<()> {
6506        self(f)
6507    }
6508}
6509
6510pub trait PathCandidateCallback {
6511    fn on_inherent_item(&mut self, item: AssocItem) -> ControlFlow<()>;
6512
6513    fn on_trait_item(&mut self, item: AssocItem) -> ControlFlow<()>;
6514}
6515
6516impl<F> PathCandidateCallback for F
6517where
6518    F: FnMut(AssocItem) -> ControlFlow<()>,
6519{
6520    fn on_inherent_item(&mut self, item: AssocItem) -> ControlFlow<()> {
6521        self(item)
6522    }
6523
6524    fn on_trait_item(&mut self, item: AssocItem) -> ControlFlow<()> {
6525        self(item)
6526    }
6527}
6528
6529pub fn resolve_absolute_path<'a, I: Iterator<Item = Symbol> + Clone + 'a>(
6530    db: &'a dyn HirDatabase,
6531    mut segments: I,
6532) -> impl Iterator<Item = ItemInNs> + use<'a, I> {
6533    segments
6534        .next()
6535        .into_iter()
6536        .flat_map(move |crate_name| {
6537            all_crates(db)
6538                .iter()
6539                .filter(|&krate| {
6540                    krate
6541                        .extra_data(db)
6542                        .display_name
6543                        .as_ref()
6544                        .is_some_and(|name| *name.crate_name().symbol() == crate_name)
6545                })
6546                .filter_map(|&krate| {
6547                    let segments = segments.clone();
6548                    let mut def_map = crate_def_map(db, krate);
6549                    let mut module = &def_map[def_map.root_module_id()];
6550                    let mut segments = segments.with_position().peekable();
6551                    while let Some((_, segment)) =
6552                        segments.next_if(|&(position, _)| !position.is_last)
6553                    {
6554                        let res = module
6555                            .scope
6556                            .get(&Name::new_symbol_root(segment))
6557                            .take_types()
6558                            .and_then(|res| match res {
6559                                ModuleDefId::ModuleId(it) => Some(it),
6560                                _ => None,
6561                            })?;
6562                        def_map = res.def_map(db);
6563                        module = &def_map[res];
6564                    }
6565                    let (_, item_name) = segments.next()?;
6566                    let res = module.scope.get(&Name::new_symbol_root(item_name));
6567                    Some(res.iter_items().map(|(item, _)| item.into()))
6568                })
6569                .collect::<Vec<_>>()
6570        })
6571        .flatten()
6572}
6573
6574fn as_name_opt(name: Option<impl AsName>) -> Name {
6575    name.map_or_else(Name::missing, |name| name.as_name())
6576}
6577
6578#[track_caller]
6579fn generic_args_from_tys<'db>(
6580    interner: DbInterner<'db>,
6581    def_id: SolverDefId<'db>,
6582    args: impl IntoIterator<Item: Borrow<Type<'db>>>,
6583) -> (GenericArgs<'db>, TypeOwnerId) {
6584    let mut owner = None::<TypeOwnerId>;
6585    let mut args = args.into_iter();
6586    let args = GenericArgs::for_item(interner, def_id, |_, id, _, _| {
6587        if matches!(id, GenericParamId::TypeParamId(_))
6588            && let Some(arg) = args.next()
6589        {
6590            let arg = arg.borrow();
6591
6592            match &mut owner {
6593                Some(owner) => *owner = owner.must_unify(arg.owner),
6594                None => owner = Some(arg.owner),
6595            }
6596
6597            arg.ty.skip_binder().into()
6598        } else {
6599            next_solver::GenericArg::error_from_id(interner, id)
6600        }
6601    });
6602    let owner =
6603        owner.unwrap_or_else(|| TypeOwnerId::NoParams(Type::builtin_type_crate(interner.db())));
6604    (args, owner)
6605}
6606
6607fn has_non_default_type_params(db: &dyn HirDatabase, generic_def: GenericDefId) -> bool {
6608    let params = GenericParams::of(db, generic_def);
6609    let defaults = db.generic_defaults(generic_def);
6610    params
6611        .iter_type_or_consts()
6612        .filter(|(_, param)| matches!(param, TypeOrConstParamData::TypeParamData(_)))
6613        .map(|(local_id, _)| TypeOrConstParamId { parent: generic_def, local_id })
6614        .any(|param| {
6615            let param = hir_ide::type_or_const_param_idx(db, param);
6616            defaults.get(param as usize).is_none()
6617        })
6618}
6619
6620fn param_env_from_has_crate<'db>(
6621    db: &'db dyn HirDatabase,
6622    id: impl hir_def::HasModule + Into<GenericDefId> + Copy,
6623) -> ParamEnvAndCrate<'db> {
6624    ParamEnvAndCrate { param_env: db.trait_environment(id.into()), krate: id.krate(db) }
6625}
6626
6627// FIXME: We probably don't want to expose this.
6628pub trait MacroCallIdExt {
6629    fn loc(self, db: &dyn HirDatabase) -> &hir_expand::MacroCallLoc;
6630}
6631impl MacroCallIdExt for span::MacroCallId {
6632    #[inline]
6633    fn loc(self, db: &dyn HirDatabase) -> &hir_expand::MacroCallLoc {
6634        hir_expand::MacroCallId::from(self).loc(db)
6635    }
6636}
6637
6638// Like https://github.com/rust-lang/rust/blob/7c3c88f42ad444f4688b865591d84660be4ece2f/compiler/rustc_middle/src/ty/util.rs#L254-L310
6639fn struct_tail_raw<'db>(
6640    db: &'db dyn HirDatabase,
6641    interner: DbInterner<'db>,
6642    mut ty: Ty<'db>,
6643    mut normalize: impl FnMut(Ty<'db>) -> Ty<'db>,
6644) -> Ty<'db> {
6645    let recursion_limit = 16;
6646    for iteration in 0.. {
6647        if iteration >= recursion_limit {
6648            return Ty::new_error(interner, ErrorGuaranteed);
6649        }
6650        match ty.kind() {
6651            TyKind::Adt(def, args) => {
6652                let AdtId::StructId(def_id) = def.def_id() else { break };
6653                let last_field = db.field_types(def_id.into()).iter().next_back();
6654                match last_field {
6655                    Some((_, field)) => {
6656                        ty = normalize(field.ty().instantiate(interner, args).skip_norm_wip())
6657                    }
6658                    None => break,
6659                }
6660            }
6661            TyKind::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
6662                ty = last_ty;
6663            }
6664            TyKind::Tuple(_) => break,
6665            TyKind::Pat(inner, _) => {
6666                ty = inner;
6667            }
6668            _ => {
6669                break;
6670            }
6671        }
6672    }
6673    ty
6674}