Skip to main content

hir_ty/
lib.rs

1//! The type system. We currently use this to infer types for completion, hover
2//! information and various assists.
3
4#![cfg_attr(feature = "in-rust-tree", feature(rustc_private))]
5// It's useful to refer to code that is private in doc comments.
6#![allow(rustdoc::private_intra_doc_links)]
7
8// FIXME: We used to import `rustc_*` deps from `rustc_private` with `feature = "in-rust-tree" but
9// temporarily switched to crates.io versions due to hardships that working on them from rustc
10// demands corresponding changes on rust-analyzer at the same time.
11// For details, see the zulip discussion below:
12// https://rust-lang.zulipchat.com/#narrow/channel/185405-t-compiler.2Frust-analyzer/topic/relying.20on.20in-tree.20.60rustc_type_ir.60.2F.60rustc_next_trait_solver.60/with/541055689
13
14extern crate ra_ap_rustc_index as rustc_index;
15
16extern crate ra_ap_rustc_abi as rustc_abi;
17
18extern crate ra_ap_rustc_pattern_analysis as rustc_pattern_analysis;
19
20extern crate ra_ap_rustc_ast_ir as rustc_ast_ir;
21
22extern crate ra_ap_rustc_type_ir as rustc_type_ir;
23
24extern crate ra_ap_rustc_next_trait_solver as rustc_next_trait_solver;
25
26extern crate self as hir_ty;
27
28pub mod builtin_derive;
29mod generics;
30mod infer;
31mod inhabitedness;
32mod lower;
33pub mod next_solver;
34mod opaques;
35mod representability;
36mod specialization;
37mod target_feature;
38mod utils;
39mod variance;
40
41pub mod autoderef;
42pub mod consteval;
43pub mod db;
44pub mod diagnostics;
45pub mod display;
46pub mod drop;
47pub mod dyn_compatibility;
48pub mod lang_items;
49pub mod layout;
50pub mod method_resolution;
51pub mod mir;
52pub mod primitive;
53pub mod solver_errors;
54pub mod traits;
55pub mod upvars;
56
57#[cfg(test)]
58mod test_db;
59#[cfg(test)]
60mod tests;
61
62use std::{hash::Hash, ops::ControlFlow};
63
64use base_db::SourceDatabase;
65use hir_def::{
66    CallableDefId, ConstId, DefWithBodyId, EnumVariantId, ExpressionStoreOwnerId, FunctionId,
67    GenericDefId, HasModule, LifetimeParamId, ModuleId, StaticId, TypeAliasId, TypeOrConstParamId,
68    TypeParamId,
69    expr_store::{Body, ExpressionStore},
70    hir::{BindingId, ExprId, ExprOrPatId, ExprOrPatIdPacked, PatId},
71    resolver::{HasResolver, Resolver, TypeNs},
72    type_ref::{Rawness, TypeRefId},
73};
74use hir_expand::name::Name;
75use indexmap::{IndexMap, map::Entry};
76use macros::GenericTypeVisitable;
77use mir::{MirEvalError, VTableMap};
78use rustc_abi::ExternAbi;
79use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
80use rustc_type_ir::{
81    BoundVarIndexKind, TypeSuperVisitable, TypeVisitableExt,
82    inherent::{IntoKind, Ty as _},
83};
84use salsa::SalsaValue;
85use stdx::impl_from;
86use syntax::ast::{ConstArg, make};
87use traits::FnTrait;
88
89use crate::{
90    db::{AnonConstId, HirDatabase},
91    display::HirDisplay,
92    lower::SupertraitsInfo,
93    next_solver::{
94        AliasTy, Binder, BoundConst, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, Canonical,
95        CanonicalVarKind, CanonicalVarKinds, ClauseKind, Const, ConstKind, DbInterner, GenericArgs,
96        PolyFnSig, Region, RegionKind, TraitRef, Ty, TyKind, TypingMode,
97        abi::Safety,
98        infer::{
99            DbInternerInferExt,
100            traits::{Obligation, ObligationCause},
101        },
102        obligation_ctxt::ObligationCtxt,
103    },
104};
105
106pub use autoderef::autoderef;
107pub use infer::{
108    Adjust, Adjustment, AutoBorrow, BindingMode, ByRef, ExplicitDropMethodUseKind,
109    InferenceDiagnostic, InferenceResult, OverloadedDeref, PointerCast, ReturnKind,
110    cast::CastError, could_coerce, could_unify, could_unify_deeply, infer_query_with_inspect,
111};
112pub use lower::{
113    FieldType, GenericDefaults, GenericDefaultsRef, GenericPredicates, LifetimeElisionKind,
114    LifetimeLoweringMode, LoweringMode, TyDefId, TyLoweringContext, TyLoweringInferVarsCtx,
115    TyLoweringResult, ValueTyDefId, diagnostics::*,
116};
117pub use next_solver::interner::{attach_db, attach_db_allow_change, with_attached_db};
118pub use target_feature::TargetFeatures;
119pub use traits::{ParamEnvAndCrate, check_orphan_rules};
120pub use utils::{
121    TargetFeatureIsSafeInTarget, Unsafety, all_super_traits, direct_super_traits,
122    is_fn_unsafe_to_call, target_feature_is_safe_in_target,
123};
124
125pub mod closure_analysis {
126    pub use crate::infer::{
127        CaptureInfo, CaptureSourceStack, CapturedPlace, ClosureData, UpvarCapture,
128        closure::analysis::{
129            BorrowKind,
130            expr_use_visitor::{FakeReadCause, Place, PlaceBase, Projection, ProjectionKind},
131        },
132    };
133}
134
135/// A constant can have reference to other things. Memory map job is holding
136/// the necessary bits of memory of the const eval session to keep the constant
137/// meaningful.
138#[derive(Debug, Default, Clone, PartialEq, Eq, GenericTypeVisitable)]
139pub enum MemoryMap<'db> {
140    #[default]
141    Empty,
142    Simple(Box<[u8]>),
143    Complex(Box<ComplexMemoryMap<'db>>),
144}
145
146#[derive(Debug, Default, Clone, PartialEq, Eq, GenericTypeVisitable)]
147pub struct ComplexMemoryMap<'db> {
148    memory: IndexMap<usize, Box<[u8]>, FxBuildHasher>,
149    vtable: VTableMap<'db>,
150}
151
152impl ComplexMemoryMap<'_> {
153    fn insert(&mut self, addr: usize, val: Box<[u8]>) {
154        match self.memory.entry(addr) {
155            Entry::Occupied(mut e) => {
156                if e.get().len() < val.len() {
157                    e.insert(val);
158                }
159            }
160            Entry::Vacant(e) => {
161                e.insert(val);
162            }
163        }
164    }
165}
166
167impl<'db> MemoryMap<'db> {
168    pub fn vtable_ty(&self, id: usize) -> Result<Ty<'db>, MirEvalError<'db>> {
169        match self {
170            MemoryMap::Empty | MemoryMap::Simple(_) => Err(MirEvalError::InvalidVTableId(id)),
171            MemoryMap::Complex(cm) => cm.vtable.ty(id),
172        }
173    }
174
175    fn simple(v: Box<[u8]>) -> Self {
176        MemoryMap::Simple(v)
177    }
178
179    /// This functions convert each address by a function `f` which gets the byte intervals and assign an address
180    /// to them. It is useful when you want to load a constant with a memory map in a new memory. You can pass an
181    /// allocator function as `f` and it will return a mapping of old addresses to new addresses.
182    fn transform_addresses(
183        &self,
184        mut f: impl FnMut(&[u8], usize) -> Result<usize, MirEvalError<'db>>,
185    ) -> Result<FxHashMap<usize, usize>, MirEvalError<'db>> {
186        let mut transform = |(addr, val): (&usize, &[u8])| {
187            let addr = *addr;
188            let align = if addr == 0 { 64 } else { (addr - (addr & (addr - 1))).min(64) };
189            f(val, align).map(|it| (addr, it))
190        };
191        match self {
192            MemoryMap::Empty => Ok(Default::default()),
193            MemoryMap::Simple(m) => transform((&0, m)).map(|(addr, val)| {
194                let mut map = FxHashMap::with_capacity_and_hasher(1, rustc_hash::FxBuildHasher);
195                map.insert(addr, val);
196                map
197            }),
198            MemoryMap::Complex(cm) => {
199                cm.memory.iter().map(|(addr, val)| transform((addr, val))).collect()
200            }
201        }
202    }
203
204    fn get(&self, addr: usize, size: usize) -> Option<&[u8]> {
205        if size == 0 {
206            Some(&[])
207        } else {
208            match self {
209                MemoryMap::Empty => Some(&[]),
210                MemoryMap::Simple(m) if addr == 0 => m.get(0..size),
211                MemoryMap::Simple(_) => None,
212                MemoryMap::Complex(cm) => cm.memory.get(&addr)?.get(0..size),
213            }
214        }
215    }
216}
217
218/// Returns the index of a parameter in the generic type parameter list by its id.
219pub fn type_or_const_param_idx(db: &dyn HirDatabase, id: TypeOrConstParamId) -> u32 {
220    generics::generics(db, id.parent).type_or_const_param_idx(id)
221}
222
223pub fn lifetime_param_idx(db: &dyn HirDatabase, id: LifetimeParamId) -> u32 {
224    generics::generics(db, id.parent).lifetime_param_idx(id, false).0
225}
226
227#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
228pub enum ImplTraitId {
229    ReturnTypeImplTrait(hir_def::FunctionId, next_solver::ImplTraitIdx),
230    TypeAliasImplTrait(hir_def::TypeAliasId, next_solver::ImplTraitIdx),
231}
232
233/// 'Canonicalizes' the `t` by replacing any errors with new variables. Also
234/// ensures there are no unbound variables or inference variables anywhere in
235/// the `t`.
236pub fn replace_errors_with_variables<'db, T>(interner: DbInterner<'db>, t: &T) -> Canonical<'db, T>
237where
238    T: rustc_type_ir::TypeFoldable<DbInterner<'db>> + Clone,
239{
240    use rustc_type_ir::{FallibleTypeFolder, TypeSuperFoldable};
241    struct ErrorReplacer<'db> {
242        interner: DbInterner<'db>,
243        vars: Vec<CanonicalVarKind<'db>>,
244        binder: rustc_type_ir::DebruijnIndex,
245    }
246    impl<'db> FallibleTypeFolder<DbInterner<'db>> for ErrorReplacer<'db> {
247        #[cfg(debug_assertions)]
248        type Error = ();
249        #[cfg(not(debug_assertions))]
250        type Error = std::convert::Infallible;
251
252        fn cx(&self) -> DbInterner<'db> {
253            self.interner
254        }
255
256        fn try_fold_binder<T>(&mut self, t: Binder<'db, T>) -> Result<Binder<'db, T>, Self::Error>
257        where
258            T: rustc_type_ir::TypeFoldable<DbInterner<'db>>,
259        {
260            self.binder.shift_in(1);
261            let result = t.try_super_fold_with(self);
262            self.binder.shift_out(1);
263            result
264        }
265
266        fn try_fold_ty(&mut self, t: Ty<'db>) -> Result<Ty<'db>, Self::Error> {
267            if !t.has_type_flags(
268                rustc_type_ir::TypeFlags::HAS_ERROR
269                    | rustc_type_ir::TypeFlags::HAS_TY_INFER
270                    | rustc_type_ir::TypeFlags::HAS_CT_INFER
271                    | rustc_type_ir::TypeFlags::HAS_RE_INFER,
272            ) {
273                return Ok(t);
274            }
275
276            #[cfg(debug_assertions)]
277            let error = || Err(());
278            #[cfg(not(debug_assertions))]
279            let error = || Ok(Ty::new_error(self.interner, crate::next_solver::ErrorGuaranteed));
280
281            match t.kind() {
282                TyKind::Error(_) => {
283                    let var = rustc_type_ir::BoundVar::from_usize(self.vars.len());
284                    self.vars.push(CanonicalVarKind::Ty {
285                        ui: rustc_type_ir::UniverseIndex::ZERO,
286                        sub_root: var,
287                    });
288                    Ok(Ty::new_bound(
289                        self.interner,
290                        self.binder,
291                        BoundTy { var, kind: BoundTyKind::Anon },
292                    ))
293                }
294                TyKind::Infer(_) => error(),
295                TyKind::Bound(BoundVarIndexKind::Bound(index), _) if index > self.binder => error(),
296                _ => t.try_super_fold_with(self),
297            }
298        }
299
300        fn try_fold_const(&mut self, ct: Const<'db>) -> Result<Const<'db>, Self::Error> {
301            if !ct.has_type_flags(
302                rustc_type_ir::TypeFlags::HAS_ERROR
303                    | rustc_type_ir::TypeFlags::HAS_TY_INFER
304                    | rustc_type_ir::TypeFlags::HAS_CT_INFER
305                    | rustc_type_ir::TypeFlags::HAS_RE_INFER,
306            ) {
307                return Ok(ct);
308            }
309
310            #[cfg(debug_assertions)]
311            let error = || Err(());
312            #[cfg(not(debug_assertions))]
313            let error = || Ok(Const::error(self.interner));
314
315            match ct.kind() {
316                ConstKind::Error(_) => {
317                    let var = rustc_type_ir::BoundVar::from_usize(self.vars.len());
318                    self.vars.push(CanonicalVarKind::Const(rustc_type_ir::UniverseIndex::ZERO));
319                    Ok(Const::new_bound(self.interner, self.binder, BoundConst::new(var)))
320                }
321                ConstKind::Infer(_) => error(),
322                ConstKind::Bound(BoundVarIndexKind::Bound(index), _) if index > self.binder => {
323                    error()
324                }
325                _ => ct.try_super_fold_with(self),
326            }
327        }
328
329        fn try_fold_region(&mut self, region: Region<'db>) -> Result<Region<'db>, Self::Error> {
330            #[cfg(debug_assertions)]
331            let error = || Err(());
332            #[cfg(not(debug_assertions))]
333            let error = || Ok(Region::error(self.interner));
334
335            match region.kind() {
336                RegionKind::ReError(_) => {
337                    let var = rustc_type_ir::BoundVar::from_usize(self.vars.len());
338                    self.vars.push(CanonicalVarKind::Region(rustc_type_ir::UniverseIndex::ZERO));
339                    Ok(Region::new_bound(
340                        self.interner,
341                        self.binder,
342                        BoundRegion { var, kind: BoundRegionKind::Anon },
343                    ))
344                }
345                RegionKind::ReVar(_) => error(),
346                RegionKind::ReBound(BoundVarIndexKind::Bound(index), _) if index > self.binder => {
347                    error()
348                }
349                _ => Ok(region),
350            }
351        }
352    }
353
354    let mut error_replacer =
355        ErrorReplacer { vars: Vec::new(), binder: rustc_type_ir::DebruijnIndex::ZERO, interner };
356    let value = match t.clone().try_fold_with(&mut error_replacer) {
357        Ok(t) => t,
358        Err(_) => panic!("Encountered unbound or inference vars in {t:?}"),
359    };
360    Canonical {
361        value,
362        max_universe: rustc_type_ir::UniverseIndex::ZERO,
363        var_kinds: CanonicalVarKinds::new_from_slice(&error_replacer.vars),
364    }
365}
366
367/// To be used from `hir` only.
368pub fn associated_type_shorthand_candidates(
369    db: &dyn HirDatabase,
370    def: GenericDefId,
371    res: TypeNs,
372    mut cb: impl FnMut(&Name, TypeAliasId) -> bool,
373) -> Option<TypeAliasId> {
374    let interner = DbInterner::new_no_crate(db);
375    let (def, param) = match res {
376        TypeNs::GenericParam(param) => (def, param),
377        TypeNs::SelfType(impl_) => {
378            let impl_trait = db.impl_trait(impl_)?.skip_binder().def_id.0;
379            let param = TypeParamId::trait_self(impl_trait);
380            (impl_trait.into(), param)
381        }
382        _ => return None,
383    };
384
385    let mut dedup_map = FxHashSet::default();
386    let param_ty = Ty::new_param(interner, param, type_or_const_param_idx(db, param.into()));
387    // We use the ParamEnv and not the predicates because the ParamEnv elaborates bounds.
388    let param_env = db.trait_environment(def);
389    for clause in param_env.clauses {
390        let ClauseKind::Trait(trait_clause) = clause.kind().skip_binder() else { continue };
391        if trait_clause.self_ty() != param_ty {
392            continue;
393        }
394        let trait_id = trait_clause.def_id().0;
395        dedup_map.extend(
396            SupertraitsInfo::query(db, trait_id)
397                .defined_assoc_types
398                .iter()
399                .map(|(name, id)| (name, *id)),
400        );
401    }
402
403    dedup_map
404        .into_iter()
405        .try_for_each(
406            |(name, id)| {
407                if cb(name, id) { ControlFlow::Break(id) } else { ControlFlow::Continue(()) }
408            },
409        )
410        .break_value()
411}
412
413/// To be used from `hir` only.
414pub fn callable_sig_from_fn_trait<'db>(
415    self_ty: Ty<'db>,
416    param_env: ParamEnvAndCrate<'db>,
417    db: &'db dyn HirDatabase,
418) -> Option<(FnTrait, PolyFnSig<'db>)> {
419    let ParamEnvAndCrate { param_env, krate } = param_env;
420    let interner = DbInterner::new_with(db, krate);
421    let infcx = interner.infer_ctxt().build(TypingMode::PostAnalysis);
422    let lang_items = interner.lang_items();
423    let cause = ObligationCause::dummy();
424
425    let impls_trait = |trait_: FnTrait| {
426        let mut ocx = ObligationCtxt::new(&infcx);
427        let tupled_args = infcx.next_ty_var(Span::Dummy);
428        let args = GenericArgs::new_from_slice(&[self_ty.into(), tupled_args.into()]);
429        let trait_id = trait_.get_id(lang_items)?;
430        let trait_ref = TraitRef::new_from_args(interner, trait_id.into(), args);
431        let obligation = Obligation::new(interner, cause, param_env, trait_ref);
432        ocx.register_obligation(obligation);
433        if !ocx.try_evaluate_obligations().is_empty() {
434            return None;
435        }
436        let tupled_args =
437            infcx.resolve_vars_if_possible(tupled_args).replace_infer_with_error(interner);
438        if tupled_args.is_tuple() { Some(tupled_args) } else { None }
439    };
440
441    let (trait_, args) = 'find_trait: {
442        for trait_ in [FnTrait::Fn, FnTrait::FnMut, FnTrait::FnOnce] {
443            if let Some(args) = impls_trait(trait_) {
444                break 'find_trait (trait_, args);
445            }
446        }
447        return None;
448    };
449
450    let output_assoc_type = lang_items.FnOnceOutput?;
451    let output_projection = Ty::new_alias(
452        interner,
453        AliasTy::new(
454            interner,
455            rustc_type_ir::Projection { def_id: output_assoc_type.into() },
456            [self_ty, args],
457        ),
458    );
459    let mut ocx = ObligationCtxt::new(&infcx);
460    let ret = ocx.structurally_normalize_ty(&cause, param_env, output_projection).ok()?;
461    let ret = ret.replace_infer_with_error(interner);
462
463    let sig = Binder::dummy(interner.mk_fn_sig(
464        args.tuple_fields(),
465        ret,
466        false,
467        // FIXME(splat): handle splatted arguments
468        Safety::Safe,
469        ExternAbi::Rust,
470    ));
471    Some((trait_, sig))
472}
473
474struct ParamCollector {
475    params: FxHashSet<TypeOrConstParamId>,
476}
477
478impl<'db> rustc_type_ir::TypeVisitor<DbInterner<'db>> for ParamCollector {
479    type Result = ();
480
481    fn visit_ty(&mut self, ty: Ty<'db>) -> Self::Result {
482        if let TyKind::Param(param) = ty.kind() {
483            self.params.insert(param.id.into());
484        }
485
486        ty.super_visit_with(self);
487    }
488
489    fn visit_const(&mut self, konst: Const<'db>) -> Self::Result {
490        if let ConstKind::Param(param) = konst.kind() {
491            self.params.insert(param.id.into());
492        }
493
494        konst.super_visit_with(self);
495    }
496}
497
498/// Returns unique params for types and consts contained in `value`.
499pub fn collect_params<'db, T>(value: &T) -> Vec<TypeOrConstParamId>
500where
501    T: ?Sized + rustc_type_ir::TypeVisitable<DbInterner<'db>>,
502{
503    let mut collector = ParamCollector { params: FxHashSet::default() };
504    value.visit_with(&mut collector);
505    Vec::from_iter(collector.params)
506}
507
508pub fn known_const_to_ast<'db>(
509    konst: Const<'db>,
510    db: &'db dyn HirDatabase,
511    target_module: ModuleId,
512) -> Option<ConstArg> {
513    Some(make::expr_const_value(
514        &konst.display_source_code(db, target_module, true).unwrap_or_else(|_| "_".to_owned()),
515    ))
516}
517
518/// A `Span` represents some location in lowered code - a type, expression or pattern.
519///
520/// It has no meaning outside its body therefore it should not exit the pass it was created in
521/// (e.g. inference). It is usually associated with a solver obligation or an infer var, which
522/// should also not cross the pass they were created in.
523#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
524pub enum Span {
525    ExprId(ExprId),
526    PatId(PatId),
527    BindingId(BindingId),
528    TypeRefId(TypeRefId),
529    /// An unimportant location. Errors on this will be suppressed.
530    Dummy,
531}
532impl_from!(ExprId, PatId, BindingId, TypeRefId for Span);
533
534impl From<ExprOrPatIdPacked> for Span {
535    fn from(value: ExprOrPatIdPacked) -> Self {
536        match value.unpack() {
537            ExprOrPatId::ExprId(idx) => idx.into(),
538            ExprOrPatId::PatId(idx) => idx.into(),
539        }
540    }
541}
542
543impl Span {
544    pub(crate) fn pick_best(a: Span, b: Span) -> Span {
545        // We prefer dummy spans to minimize the risk of false errors.
546        if b.is_dummy() { b } else { a }
547    }
548
549    #[inline]
550    pub fn is_dummy(&self) -> bool {
551        matches!(self, Self::Dummy)
552    }
553}
554
555/// A [`DefWithBodyId`], or an anon const.
556#[derive(
557    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, salsa::Supertype, SalsaValue,
558)]
559pub enum InferBodyId<'db> {
560    DefWithBodyId(DefWithBodyId),
561    AnonConstId(AnonConstId<'db>),
562}
563impl_from!(
564    impl<'db>
565    DefWithBodyId(FunctionId, ConstId, StaticId),
566    AnonConstId<'db>
567    for InferBodyId<'db>
568);
569impl<'db> From<EnumVariantId> for InferBodyId<'db> {
570    fn from(id: EnumVariantId) -> Self {
571        InferBodyId::DefWithBodyId(DefWithBodyId::VariantId(id))
572    }
573}
574
575impl HasModule for InferBodyId<'_> {
576    fn module(&self, db: &dyn SourceDatabase) -> ModuleId {
577        match self {
578            InferBodyId::DefWithBodyId(id) => id.module(db),
579            InferBodyId::AnonConstId(id) => id.module(db),
580        }
581    }
582}
583
584impl HasResolver for InferBodyId<'_> {
585    fn resolver(self, db: &dyn SourceDatabase) -> Resolver<'_> {
586        match self {
587            InferBodyId::DefWithBodyId(id) => id.resolver(db),
588            InferBodyId::AnonConstId(id) => id.resolver(db),
589        }
590    }
591}
592
593impl InferBodyId<'_> {
594    pub fn expression_store_owner(self, db: &dyn HirDatabase) -> ExpressionStoreOwnerId {
595        match self {
596            InferBodyId::DefWithBodyId(id) => id.into(),
597            InferBodyId::AnonConstId(id) => id.loc(db).owner,
598        }
599    }
600
601    pub fn generic_def(self, db: &dyn HirDatabase) -> GenericDefId {
602        match self {
603            InferBodyId::DefWithBodyId(id) => id.generic_def(db),
604            InferBodyId::AnonConstId(id) => id.loc(db).owner.generic_def(db),
605        }
606    }
607
608    #[inline]
609    pub fn as_function(self) -> Option<FunctionId> {
610        match self {
611            InferBodyId::DefWithBodyId(DefWithBodyId::FunctionId(it)) => Some(it),
612            _ => None,
613        }
614    }
615
616    #[inline]
617    pub fn as_variant(self) -> Option<EnumVariantId> {
618        match self {
619            InferBodyId::DefWithBodyId(DefWithBodyId::VariantId(it)) => Some(it),
620            _ => None,
621        }
622    }
623
624    pub fn store_and_root_expr(self, db: &dyn HirDatabase) -> (&ExpressionStore, ExprId) {
625        match self {
626            InferBodyId::DefWithBodyId(id) => {
627                let body = Body::of(db, id);
628                (body, body.root_expr())
629            }
630            InferBodyId::AnonConstId(id) => {
631                let loc = id.loc(db);
632                let store = ExpressionStore::of(db, loc.owner);
633                (store, loc.expr)
634            }
635        }
636    }
637}
638
639pub fn setup_tracing() -> Option<tracing::subscriber::DefaultGuard> {
640    use std::env;
641    use tracing_subscriber::{Registry, layer::SubscriberExt};
642    use tracing_tree::HierarchicalLayer;
643
644    let filter: tracing_subscriber::filter::Targets =
645        env::var("SOLVER_DEBUG").ok().and_then(|it| it.parse().ok()).unwrap_or_default();
646    let layer = HierarchicalLayer::default()
647        .with_indent_lines(true)
648        .with_ansi(false)
649        .with_indent_amount(2)
650        .with_writer(std::io::stderr);
651    let subscriber = Registry::default().with(filter).with(layer);
652    Some(tracing::subscriber::set_default(subscriber))
653}