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