Skip to main content

rustc_type_ir/search_graph/
mod.rs

1//! The search graph is responsible for caching and cycle detection in the trait
2//! solver. Making sure that caching doesn't result in soundness bugs or unstable
3//! query results is very challenging and makes this one of the most-involved
4//! self-contained components of the compiler.
5//!
6//! We added fuzzing support to test its correctness. The fuzzers used to verify
7//! the current implementation can be found in <https://github.com/lcnr/search_graph_fuzz>.
8//!
9//! This is just a quick overview of the general design, please check out the relevant
10//! [rustc-dev-guide chapter](https://rustc-dev-guide.rust-lang.org/solve/caching.html) for
11//! more details. Caching is split between a global cache and the per-cycle `provisional_cache`.
12//! The global cache has to be completely unobservable, while the per-cycle cache may impact
13//! behavior as long as the resulting behavior is still correct.
14use std::cmp::Ordering;
15use std::collections::hash_map::Entry;
16use std::collections::{BTreeMap, btree_map};
17use std::fmt::Debug;
18use std::hash::Hash;
19use std::iter;
20use std::marker::PhantomData;
21
22use derive_where::derive_where;
23#[cfg(feature = "nightly")]
24use rustc_macros::{Decodable_NoContext, Encodable_NoContext, StableHash};
25use rustc_type_ir::data_structures::HashMap;
26use tracing::{debug, instrument, trace};
27
28mod stack;
29use stack::{Stack, StackDepth, StackEntry};
30mod global_cache;
31use global_cache::CacheData;
32pub use global_cache::GlobalCache;
33
34/// The search graph does not simply use `Interner` directly
35/// to enable its fuzzing without having to stub the rest of
36/// the interner. We don't make this a super trait of `Interner`
37/// as users of the shared type library shouldn't have to care
38/// about `Input` and `Result` as they are implementation details
39/// of the search graph.
40pub trait Cx: Copy {
41    type Input: Debug + Eq + Hash + Copy;
42    type Result: Debug + Eq + Hash + Copy;
43    type AmbiguityInfo: Debug + Eq + Hash + Copy;
44
45    type DepNodeIndex;
46    type Tracked<T: Debug + Clone>: Debug;
47    fn mk_tracked<T: Debug + Clone>(
48        self,
49        data: T,
50        dep_node_index: Self::DepNodeIndex,
51    ) -> Self::Tracked<T>;
52    fn get_tracked<T: Debug + Clone>(self, tracked: &Self::Tracked<T>) -> T;
53    fn with_cached_task<T>(self, task: impl FnOnce() -> T) -> (T, Self::DepNodeIndex);
54
55    fn with_global_cache<R>(self, f: impl FnOnce(&mut GlobalCache<Self>) -> R) -> R;
56
57    fn assert_evaluation_is_concurrent(&self);
58}
59
60pub trait Delegate: Sized {
61    type Cx: Cx;
62    /// Whether to use the provisional cache. Set to `false` by a fuzzer when
63    /// validating the search graph.
64    const ENABLE_PROVISIONAL_CACHE: bool;
65    type ValidationScope;
66    /// Returning `Some` disables the global cache for the current goal.
67    ///
68    /// The `ValidationScope` is used when fuzzing the search graph to track
69    /// for which goals the global cache has been disabled. This is necessary
70    /// as we may otherwise ignore the global cache entry for some goal `G`
71    /// only to later use it, failing to detect a cycle goal and potentially
72    /// changing the result.
73    fn enter_validation_scope(
74        cx: Self::Cx,
75        input: <Self::Cx as Cx>::Input,
76    ) -> Option<Self::ValidationScope>;
77
78    const FIXPOINT_STEP_LIMIT: usize;
79
80    type ProofTreeBuilder;
81    fn inspect_is_noop(inspect: &mut Self::ProofTreeBuilder) -> bool;
82
83    const DIVIDE_AVAILABLE_DEPTH_ON_OVERFLOW: usize;
84
85    fn initial_provisional_result(
86        cx: Self::Cx,
87        kind: PathKind,
88        input: <Self::Cx as Cx>::Input,
89    ) -> <Self::Cx as Cx>::Result;
90    fn is_initial_provisional_result(result: <Self::Cx as Cx>::Result) -> Option<PathKind>;
91    fn stack_overflow_result(
92        cx: Self::Cx,
93        input: <Self::Cx as Cx>::Input,
94    ) -> <Self::Cx as Cx>::Result;
95    fn fixpoint_overflow_result(
96        cx: Self::Cx,
97        input: <Self::Cx as Cx>::Input,
98    ) -> <Self::Cx as Cx>::Result;
99
100    fn is_ambiguous_result(
101        result: <Self::Cx as Cx>::Result,
102    ) -> Option<<Self::Cx as Cx>::AmbiguityInfo>;
103    fn propagate_ambiguity(
104        cx: Self::Cx,
105        for_input: <Self::Cx as Cx>::Input,
106        ambiguity_info: <Self::Cx as Cx>::AmbiguityInfo,
107    ) -> <Self::Cx as Cx>::Result;
108
109    fn compute_goal(
110        search_graph: &mut SearchGraph<Self>,
111        cx: Self::Cx,
112        input: <Self::Cx as Cx>::Input,
113        inspect: &mut Self::ProofTreeBuilder,
114    ) -> <Self::Cx as Cx>::Result;
115}
116
117/// In the initial iteration of a cycle, we do not yet have a provisional
118/// result. In the case we return an initial provisional result depending
119/// on the kind of cycle.
120#[derive(#[automatically_derived]
impl ::core::fmt::Debug for PathKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                PathKind::Inductive => "Inductive",
                PathKind::Unknown => "Unknown",
                PathKind::Coinductive => "Coinductive",
                PathKind::ForcedAmbiguity => "ForcedAmbiguity",
            })
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for PathKind {
    #[inline]
    fn clone(&self) -> PathKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for PathKind { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for PathKind {
    #[inline]
    fn eq(&self, other: &PathKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for PathKind {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for PathKind {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state)
    }
}Hash)]
121#[cfg_attr(feature = "nightly", derive(const _: () =
    {
        impl<__D: ::rustc_serialize::Decoder>
            ::rustc_serialize::Decodable<__D> for PathKind {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { PathKind::Inductive }
                    1usize => { PathKind::Unknown }
                    2usize => { PathKind::Coinductive }
                    3usize => { PathKind::ForcedAmbiguity }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `PathKind`, expected 0..4, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable_NoContext, const _: () =
    {
        impl<__E: ::rustc_serialize::Encoder>
            ::rustc_serialize::Encodable<__E> for PathKind {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        PathKind::Inductive => { 0usize }
                        PathKind::Unknown => { 1usize }
                        PathKind::Coinductive => { 2usize }
                        PathKind::ForcedAmbiguity => { 3usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    PathKind::Inductive => {}
                    PathKind::Unknown => {}
                    PathKind::Coinductive => {}
                    PathKind::ForcedAmbiguity => {}
                }
            }
        }
    };Encodable_NoContext, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for PathKind {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                ::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
                match *self {
                    PathKind::Inductive => {}
                    PathKind::Unknown => {}
                    PathKind::Coinductive => {}
                    PathKind::ForcedAmbiguity => {}
                }
            }
        }
    };StableHash))]
122pub enum PathKind {
123    /// A path consisting of only inductive/unproductive steps. Their initial
124    /// provisional result is `Err(NoSolution)`. We currently treat them as
125    /// `PathKind::Unknown` during coherence until we're fully confident in
126    /// our approach.
127    Inductive,
128    /// A path which is not be coinductive right now but we may want
129    /// to change of them to be so in the future. We return an ambiguous
130    /// result in this case to prevent people from relying on this.
131    Unknown,
132    /// A path with at least one coinductive step. Such cycles hold.
133    Coinductive,
134    /// A path which is treated as ambiguous. Once a path has this path kind
135    /// any other segment does not change its kind.
136    ///
137    /// This is currently only used when fuzzing to support negative reasoning.
138    /// For more details, see #143054.
139    ForcedAmbiguity,
140}
141
142impl PathKind {
143    /// Returns the path kind when merging `self` with `rest`.
144    ///
145    /// Given an inductive path `self` and a coinductive path `rest`,
146    /// the path `self -> rest` would be coinductive.
147    ///
148    /// This operation represents an ordering and would be equivalent
149    /// to `max(self, rest)`.
150    fn extend(self, rest: PathKind) -> PathKind {
151        match (self, rest) {
152            (PathKind::ForcedAmbiguity, _) | (_, PathKind::ForcedAmbiguity) => {
153                PathKind::ForcedAmbiguity
154            }
155            (PathKind::Coinductive, _) | (_, PathKind::Coinductive) => PathKind::Coinductive,
156            (PathKind::Unknown, _) | (_, PathKind::Unknown) => PathKind::Unknown,
157            (PathKind::Inductive, PathKind::Inductive) => PathKind::Inductive,
158        }
159    }
160}
161
162/// The kinds of cycles a cycle head was involved in.
163///
164/// This is used to avoid rerunning a cycle if there's
165/// just a single usage kind and the final result matches
166/// its provisional result.
167///
168/// While it tracks the amount of usages using `u32`, we only ever
169/// care whether there are any. We only count them to be able to ignore
170/// usages from irrelevant candidates while evaluating a goal.
171///
172/// This cares about how nested goals relied on a cycle head. It does
173/// not care about how frequently the nested goal relied on it.
174#[derive(#[automatically_derived]
impl ::core::default::Default for HeadUsages {
    #[inline]
    fn default() -> HeadUsages {
        HeadUsages {
            inductive: ::core::default::Default::default(),
            unknown: ::core::default::Default::default(),
            coinductive: ::core::default::Default::default(),
            forced_ambiguity: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]
impl ::core::fmt::Debug for HeadUsages {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "HeadUsages",
            "inductive", &self.inductive, "unknown", &self.unknown,
            "coinductive", &self.coinductive, "forced_ambiguity",
            &&self.forced_ambiguity)
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for HeadUsages {
    #[inline]
    fn clone(&self) -> HeadUsages {
        let _: ::core::clone::AssertParamIsClone<u32>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for HeadUsages { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for HeadUsages {
    #[inline]
    fn eq(&self, other: &HeadUsages) -> bool {
        self.inductive == other.inductive && self.unknown == other.unknown &&
                self.coinductive == other.coinductive &&
            self.forced_ambiguity == other.forced_ambiguity
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for HeadUsages {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<u32>;
    }
}Eq)]
175struct HeadUsages {
176    inductive: u32,
177    unknown: u32,
178    coinductive: u32,
179    forced_ambiguity: u32,
180}
181
182impl HeadUsages {
183    fn add_usage(&mut self, path: PathKind) {
184        match path {
185            PathKind::Inductive => self.inductive += 1,
186            PathKind::Unknown => self.unknown += 1,
187            PathKind::Coinductive => self.coinductive += 1,
188            PathKind::ForcedAmbiguity => self.forced_ambiguity += 1,
189        }
190    }
191
192    /// This adds the usages which occurred while computing a nested goal.
193    ///
194    /// We don't actually care about how frequently the nested goal relied
195    /// on its cycle heads, only whether it did.
196    fn add_usages_from_nested(&mut self, usages: HeadUsages) {
197        let HeadUsages { inductive, unknown, coinductive, forced_ambiguity } = usages;
198        self.inductive += if inductive == 0 { 0 } else { 1 };
199        self.unknown += if unknown == 0 { 0 } else { 1 };
200        self.coinductive += if coinductive == 0 { 0 } else { 1 };
201        self.forced_ambiguity += if forced_ambiguity == 0 { 0 } else { 1 };
202    }
203
204    fn ignore_usages(&mut self, usages: HeadUsages) {
205        let HeadUsages { inductive, unknown, coinductive, forced_ambiguity } = usages;
206        self.inductive = self.inductive.checked_sub(inductive).unwrap();
207        self.unknown = self.unknown.checked_sub(unknown).unwrap();
208        self.coinductive = self.coinductive.checked_sub(coinductive).unwrap();
209        self.forced_ambiguity = self.forced_ambiguity.checked_sub(forced_ambiguity).unwrap();
210    }
211
212    fn is_empty(self) -> bool {
213        let HeadUsages { inductive, unknown, coinductive, forced_ambiguity } = self;
214        inductive == 0 && unknown == 0 && coinductive == 0 && forced_ambiguity == 0
215    }
216
217    fn is_single(self, path_kind: PathKind) -> bool {
218        match path_kind {
219            PathKind::Inductive => #[allow(non_exhaustive_omitted_patterns)] match self {
    HeadUsages { inductive: _, unknown: 0, coinductive: 0, forced_ambiguity: 0
        } => true,
    _ => false,
}matches!(
220                self,
221                HeadUsages { inductive: _, unknown: 0, coinductive: 0, forced_ambiguity: 0 },
222            ),
223            PathKind::Unknown => #[allow(non_exhaustive_omitted_patterns)] match self {
    HeadUsages { inductive: 0, unknown: _, coinductive: 0, forced_ambiguity: 0
        } => true,
    _ => false,
}matches!(
224                self,
225                HeadUsages { inductive: 0, unknown: _, coinductive: 0, forced_ambiguity: 0 },
226            ),
227            PathKind::Coinductive => #[allow(non_exhaustive_omitted_patterns)] match self {
    HeadUsages { inductive: 0, unknown: 0, coinductive: _, forced_ambiguity: 0
        } => true,
    _ => false,
}matches!(
228                self,
229                HeadUsages { inductive: 0, unknown: 0, coinductive: _, forced_ambiguity: 0 },
230            ),
231            PathKind::ForcedAmbiguity => #[allow(non_exhaustive_omitted_patterns)] match self {
    HeadUsages { inductive: 0, unknown: 0, coinductive: 0, forced_ambiguity: _
        } => true,
    _ => false,
}matches!(
232                self,
233                HeadUsages { inductive: 0, unknown: 0, coinductive: 0, forced_ambiguity: _ },
234            ),
235        }
236    }
237}
238
239#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CandidateHeadUsages {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "CandidateHeadUsages", "usages", &&self.usages)
    }
}Debug, #[automatically_derived]
impl ::core::default::Default for CandidateHeadUsages {
    #[inline]
    fn default() -> CandidateHeadUsages {
        CandidateHeadUsages { usages: ::core::default::Default::default() }
    }
}Default)]
240pub struct CandidateHeadUsages {
241    usages: Option<Box<HashMap<StackDepth, HeadUsages>>>,
242}
243impl CandidateHeadUsages {
244    pub fn merge_usages(&mut self, other: CandidateHeadUsages) {
245        if let Some(other_usages) = other.usages {
246            if let Some(ref mut self_usages) = self.usages {
247                // Each head is merged independently, so the final usage counts are the same
248                // regardless of hash iteration order.
249                #[allow(rustc::potential_query_instability)]
250                for (head_index, head) in other_usages.into_iter() {
251                    let HeadUsages { inductive, unknown, coinductive, forced_ambiguity } = head;
252                    let self_usages = self_usages.entry(head_index).or_default();
253                    self_usages.inductive += inductive;
254                    self_usages.unknown += unknown;
255                    self_usages.coinductive += coinductive;
256                    self_usages.forced_ambiguity += forced_ambiguity;
257                }
258            } else {
259                self.usages = Some(other_usages);
260            }
261        }
262    }
263}
264
265/// Whether evaluating a given goal should be done with a lower available depth from
266/// its parent goal.
267///
268/// Normally, it should be `Yes`, but among rustc's predicate goals, `normalizes-to`
269/// goals are exceptions. They act like functions that used for normalizing associated
270/// terms while evaluating projection goals with fully unconstrained expected term.
271/// We don't want to lower the available depths for those function-like goals, otherwise
272/// we will encounter recursion limit overflows more often.
273#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LowerAvailableDepth {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                LowerAvailableDepth::Yes => "Yes",
                LowerAvailableDepth::No => "No",
            })
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for LowerAvailableDepth {
    #[inline]
    fn clone(&self) -> LowerAvailableDepth { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LowerAvailableDepth { }Copy)]
274pub enum LowerAvailableDepth {
275    Yes,
276    No,
277}
278
279#[derive(#[automatically_derived]
impl ::core::fmt::Debug for AvailableDepth {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "AvailableDepth",
            &&self.0)
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for AvailableDepth {
    #[inline]
    fn clone(&self) -> AvailableDepth {
        let _: ::core::clone::AssertParamIsClone<usize>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AvailableDepth { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for AvailableDepth {
    #[inline]
    fn eq(&self, other: &AvailableDepth) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AvailableDepth {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<usize>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for AvailableDepth {
    #[inline]
    fn partial_cmp(&self, other: &AvailableDepth)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for AvailableDepth {
    #[inline]
    fn cmp(&self, other: &AvailableDepth) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&self.0, &other.0)
    }
}Ord)]
280struct AvailableDepth(usize);
281impl AvailableDepth {
282    /// Returns the remaining depth allowed for nested goals.
283    ///
284    /// This is generally simply one less than the current depth.
285    /// However, if we encountered overflow, we significantly reduce
286    /// the remaining depth of all nested goals to prevent hangs
287    /// in case there is exponential blowup.
288    fn allowed_depth_for_nested<D: Delegate>(
289        root_depth: AvailableDepth,
290        stack: &Stack<D::Cx>,
291        lower_available_depth: LowerAvailableDepth,
292    ) -> Option<AvailableDepth> {
293        if let Some(last) = stack.last() {
294            match lower_available_depth {
295                LowerAvailableDepth::Yes => {}
296                LowerAvailableDepth::No => {
297                    return Some(last.available_depth);
298                }
299            }
300
301            if last.available_depth.0 == 0 {
302                return None;
303            }
304
305            Some(if last.encountered_overflow {
306                AvailableDepth(last.available_depth.0 / D::DIVIDE_AVAILABLE_DEPTH_ON_OVERFLOW)
307            } else {
308                AvailableDepth(last.available_depth.0 - 1)
309            })
310        } else {
311            Some(root_depth)
312        }
313    }
314
315    /// Whether we're allowed to use a global cache entry which required
316    /// the given depth.
317    fn cache_entry_is_applicable(self, additional_depth: usize) -> bool {
318        self.0 >= additional_depth
319    }
320}
321
322#[derive(#[automatically_derived]
impl ::core::clone::Clone for CycleHead {
    #[inline]
    fn clone(&self) -> CycleHead {
        let _: ::core::clone::AssertParamIsClone<PathsToNested>;
        let _: ::core::clone::AssertParamIsClone<HeadUsages>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for CycleHead { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for CycleHead {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "CycleHead",
            "paths_to_head", &self.paths_to_head, "usages", &&self.usages)
    }
}Debug)]
323struct CycleHead {
324    paths_to_head: PathsToNested,
325    /// If the `usages` are empty, the result of that head does not matter
326    /// for the current goal. However, we still don't completely drop this
327    /// cycle head as whether or not it exists impacts which queries we
328    /// access, so ignoring it would cause incremental compilation verification
329    /// failures or hide query cycles.
330    usages: HeadUsages,
331}
332
333/// All cycle heads a given goal depends on, ordered by their stack depth.
334///
335/// We also track all paths from this goal to that head. This is necessary
336/// when rebasing provisional cache results.
337#[derive(#[automatically_derived]
impl ::core::clone::Clone for CycleHeads {
    #[inline]
    fn clone(&self) -> CycleHeads {
        CycleHeads { heads: ::core::clone::Clone::clone(&self.heads) }
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for CycleHeads {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "CycleHeads",
            "heads", &&self.heads)
    }
}Debug, #[automatically_derived]
impl ::core::default::Default for CycleHeads {
    #[inline]
    fn default() -> CycleHeads {
        CycleHeads { heads: ::core::default::Default::default() }
    }
}Default)]
338struct CycleHeads {
339    heads: BTreeMap<StackDepth, CycleHead>,
340}
341
342impl CycleHeads {
343    fn is_empty(&self) -> bool {
344        self.heads.is_empty()
345    }
346
347    fn highest_cycle_head(&self) -> (StackDepth, CycleHead) {
348        self.heads.last_key_value().map(|(k, v)| (*k, *v)).unwrap()
349    }
350
351    fn highest_cycle_head_index(&self) -> StackDepth {
352        self.opt_highest_cycle_head_index().unwrap()
353    }
354
355    fn opt_highest_cycle_head_index(&self) -> Option<StackDepth> {
356        self.heads.last_key_value().map(|(k, _)| *k)
357    }
358
359    fn opt_lowest_cycle_head_index(&self) -> Option<StackDepth> {
360        self.heads.first_key_value().map(|(k, _)| *k)
361    }
362
363    fn remove_highest_cycle_head(&mut self) -> CycleHead {
364        let last = self.heads.pop_last();
365        last.unwrap().1
366    }
367
368    fn insert(
369        &mut self,
370        head_index: StackDepth,
371        path_from_entry: impl Into<PathsToNested> + Copy,
372        usages: HeadUsages,
373    ) {
374        match self.heads.entry(head_index) {
375            btree_map::Entry::Vacant(entry) => {
376                entry.insert(CycleHead { paths_to_head: path_from_entry.into(), usages });
377            }
378            btree_map::Entry::Occupied(entry) => {
379                let head = entry.into_mut();
380                head.paths_to_head |= path_from_entry.into();
381                head.usages.add_usages_from_nested(usages);
382            }
383        }
384    }
385
386    fn ignore_usages(&mut self, head_index: StackDepth, usages: HeadUsages) {
387        self.heads.get_mut(&head_index).unwrap().usages.ignore_usages(usages)
388    }
389
390    fn iter(&self) -> impl Iterator<Item = (StackDepth, CycleHead)> + '_ {
391        self.heads.iter().map(|(k, v)| (*k, *v))
392    }
393}
394
395#[doc =
r" Tracks how nested goals have been accessed. This is necessary to disable"]
#[doc =
r" global cache entries if computing them would otherwise result in a cycle or"]
#[doc = r" access a provisional cache entry."]
pub struct PathsToNested(<PathsToNested as
    ::bitflags::__private::PublicFlags>::Internal);
#[automatically_derived]
impl ::core::fmt::Debug for PathsToNested {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "PathsToNested",
            &&self.0)
    }
}
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for PathsToNested { }
#[automatically_derived]
impl ::core::clone::Clone for PathsToNested {
    #[inline]
    fn clone(&self) -> PathsToNested {
        let _:
                ::core::clone::AssertParamIsClone<<PathsToNested as
                ::bitflags::__private::PublicFlags>::Internal>;
        *self
    }
}
#[automatically_derived]
impl ::core::marker::Copy for PathsToNested { }
#[automatically_derived]
impl ::core::marker::StructuralPartialEq for PathsToNested { }
#[automatically_derived]
impl ::core::cmp::PartialEq for PathsToNested {
    #[inline]
    fn eq(&self, other: &PathsToNested) -> bool { self.0 == other.0 }
}
#[automatically_derived]
impl ::core::cmp::Eq for PathsToNested {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _:
                ::core::cmp::AssertParamIsEq<<PathsToNested as
                ::bitflags::__private::PublicFlags>::Internal>;
    }
}
impl PathsToNested {
    #[doc = r" The initial value when adding a goal to its own nested goals."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const EMPTY: Self = Self::from_bits_retain(1 << 0);
    #[allow(deprecated, non_upper_case_globals,)]
    pub const INDUCTIVE: Self = Self::from_bits_retain(1 << 1);
    #[allow(deprecated, non_upper_case_globals,)]
    pub const UNKNOWN: Self = Self::from_bits_retain(1 << 2);
    #[allow(deprecated, non_upper_case_globals,)]
    pub const COINDUCTIVE: Self = Self::from_bits_retain(1 << 3);
    #[allow(deprecated, non_upper_case_globals,)]
    pub const FORCED_AMBIGUITY: Self = Self::from_bits_retain(1 << 4);
}
impl ::bitflags::Flags for PathsToNested {
    const FLAGS: &'static [::bitflags::Flag<PathsToNested>] =
        &[{

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("EMPTY", PathsToNested::EMPTY)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("INDUCTIVE", PathsToNested::INDUCTIVE)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("UNKNOWN", PathsToNested::UNKNOWN)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("COINDUCTIVE",
                            PathsToNested::COINDUCTIVE)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("FORCED_AMBIGUITY",
                            PathsToNested::FORCED_AMBIGUITY)
                    }];
    type Bits = u8;
    fn bits(&self) -> u8 { PathsToNested::bits(self) }
    fn from_bits_retain(bits: u8) -> PathsToNested {
        PathsToNested::from_bits_retain(bits)
    }
}
#[allow(dead_code, deprecated, unused_doc_comments, unused_attributes,
unused_mut, unused_imports, non_upper_case_globals, clippy ::
assign_op_pattern, clippy :: indexing_slicing, clippy :: same_name_method,
clippy :: iter_without_into_iter,)]
const _: () =
    {
        #[repr(transparent)]
        pub struct InternalBitFlags(u8);
        #[automatically_derived]
        #[doc(hidden)]
        unsafe impl ::core::clone::TrivialClone for InternalBitFlags { }
        #[automatically_derived]
        impl ::core::clone::Clone for InternalBitFlags {
            #[inline]
            fn clone(&self) -> InternalBitFlags {
                let _: ::core::clone::AssertParamIsClone<u8>;
                *self
            }
        }
        #[automatically_derived]
        impl ::core::marker::Copy for InternalBitFlags { }
        #[automatically_derived]
        impl ::core::marker::StructuralPartialEq for InternalBitFlags { }
        #[automatically_derived]
        impl ::core::cmp::PartialEq for InternalBitFlags {
            #[inline]
            fn eq(&self, other: &InternalBitFlags) -> bool {
                self.0 == other.0
            }
        }
        #[automatically_derived]
        impl ::core::cmp::Eq for InternalBitFlags {
            #[inline]
            #[doc(hidden)]
            #[coverage(off)]
            fn assert_fields_are_eq(&self) {
                let _: ::core::cmp::AssertParamIsEq<u8>;
            }
        }
        #[automatically_derived]
        impl ::core::cmp::PartialOrd for InternalBitFlags {
            #[inline]
            fn partial_cmp(&self, other: &InternalBitFlags)
                -> ::core::option::Option<::core::cmp::Ordering> {
                ::core::option::Option::Some(::core::cmp::Ord::cmp(self,
                        other))
            }
        }
        #[automatically_derived]
        impl ::core::cmp::Ord for InternalBitFlags {
            #[inline]
            fn cmp(&self, other: &InternalBitFlags) -> ::core::cmp::Ordering {
                ::core::cmp::Ord::cmp(&self.0, &other.0)
            }
        }
        #[automatically_derived]
        impl ::core::hash::Hash for InternalBitFlags {
            #[inline]
            fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
                ::core::hash::Hash::hash(&self.0, state)
            }
        }
        impl ::bitflags::__private::PublicFlags for PathsToNested {
            type Primitive = u8;
            type Internal = InternalBitFlags;
        }
        impl ::bitflags::__private::core::default::Default for
            InternalBitFlags {
            #[inline]
            fn default() -> Self { InternalBitFlags::empty() }
        }
        impl ::bitflags::__private::core::fmt::Debug for InternalBitFlags {
            fn fmt(&self,
                f: &mut ::bitflags::__private::core::fmt::Formatter<'_>)
                -> ::bitflags::__private::core::fmt::Result {
                if self.is_empty() {
                    f.write_fmt(format_args!("{0:#x}",
                            <u8 as ::bitflags::Bits>::EMPTY))
                } else {
                    ::bitflags::__private::core::fmt::Display::fmt(self, f)
                }
            }
        }
        impl ::bitflags::__private::core::fmt::Display for InternalBitFlags {
            fn fmt(&self,
                f: &mut ::bitflags::__private::core::fmt::Formatter<'_>)
                -> ::bitflags::__private::core::fmt::Result {
                ::bitflags::parser::to_writer(&PathsToNested(*self), f)
            }
        }
        impl ::bitflags::__private::core::str::FromStr for InternalBitFlags {
            type Err = ::bitflags::parser::ParseError;
            fn from_str(s: &str)
                ->
                    ::bitflags::__private::core::result::Result<Self,
                    Self::Err> {
                ::bitflags::parser::from_str::<PathsToNested>(s).map(|flags|
                        flags.0)
            }
        }
        impl ::bitflags::__private::core::convert::AsRef<u8> for
            InternalBitFlags {
            fn as_ref(&self) -> &u8 { &self.0 }
        }
        impl ::bitflags::__private::core::convert::From<u8> for
            InternalBitFlags {
            fn from(bits: u8) -> Self { Self::from_bits_retain(bits) }
        }
        #[allow(dead_code, deprecated, unused_attributes)]
        impl InternalBitFlags {
            /// Get a flags value with all bits unset.
            #[inline]
            pub const fn empty() -> Self {
                Self(<u8 as ::bitflags::Bits>::EMPTY)
            }
            /// Get a flags value with all known bits set.
            #[inline]
            pub const fn all() -> Self {
                let mut truncated = <u8 as ::bitflags::Bits>::EMPTY;
                let mut i = 0;
                {
                    {
                        let flag =
                            <PathsToNested as
                                            ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <PathsToNested as
                                            ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <PathsToNested as
                                            ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <PathsToNested as
                                            ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                {
                    {
                        let flag =
                            <PathsToNested as
                                            ::bitflags::Flags>::FLAGS[i].value().bits();
                        truncated = truncated | flag;
                        i += 1;
                    }
                };
                let _ = i;
                Self(truncated)
            }
            /// Get the underlying bits value.
            ///
            /// The returned value is exactly the bits set in this flags value.
            #[inline]
            pub const fn bits(&self) -> u8 { self.0 }
            /// Convert from a bits value.
            ///
            /// This method will return `None` if any unknown bits are set.
            #[inline]
            pub const fn from_bits(bits: u8)
                -> ::bitflags::__private::core::option::Option<Self> {
                let truncated = Self::from_bits_truncate(bits).0;
                if truncated == bits {
                    ::bitflags::__private::core::option::Option::Some(Self(bits))
                } else { ::bitflags::__private::core::option::Option::None }
            }
            /// Convert from a bits value, unsetting any unknown bits.
            #[inline]
            pub const fn from_bits_truncate(bits: u8) -> Self {
                Self(bits & Self::all().0)
            }
            /// Convert from a bits value exactly.
            #[inline]
            pub const fn from_bits_retain(bits: u8) -> Self { Self(bits) }
            /// Get a flags value with the bits of a flag with the given name set.
            ///
            /// This method will return `None` if `name` is empty or doesn't
            /// correspond to any named flag.
            #[inline]
            pub fn from_name(name: &str)
                -> ::bitflags::__private::core::option::Option<Self> {
                {
                    if name == "EMPTY" {
                        return ::bitflags::__private::core::option::Option::Some(Self(PathsToNested::EMPTY.bits()));
                    }
                };
                ;
                {
                    if name == "INDUCTIVE" {
                        return ::bitflags::__private::core::option::Option::Some(Self(PathsToNested::INDUCTIVE.bits()));
                    }
                };
                ;
                {
                    if name == "UNKNOWN" {
                        return ::bitflags::__private::core::option::Option::Some(Self(PathsToNested::UNKNOWN.bits()));
                    }
                };
                ;
                {
                    if name == "COINDUCTIVE" {
                        return ::bitflags::__private::core::option::Option::Some(Self(PathsToNested::COINDUCTIVE.bits()));
                    }
                };
                ;
                {
                    if name == "FORCED_AMBIGUITY" {
                        return ::bitflags::__private::core::option::Option::Some(Self(PathsToNested::FORCED_AMBIGUITY.bits()));
                    }
                };
                ;
                let _ = name;
                ::bitflags::__private::core::option::Option::None
            }
            /// Whether all bits in this flags value are unset.
            #[inline]
            pub const fn is_empty(&self) -> bool {
                self.0 == <u8 as ::bitflags::Bits>::EMPTY
            }
            /// Whether all known bits in this flags value are set.
            #[inline]
            pub const fn is_all(&self) -> bool {
                Self::all().0 | self.0 == self.0
            }
            /// Whether any set bits in a source flags value are also set in a target flags value.
            #[inline]
            pub const fn intersects(&self, other: Self) -> bool {
                self.0 & other.0 != <u8 as ::bitflags::Bits>::EMPTY
            }
            /// Whether all set bits in a source flags value are also set in a target flags value.
            #[inline]
            pub const fn contains(&self, other: Self) -> bool {
                self.0 & other.0 == other.0
            }
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            pub fn insert(&mut self, other: Self) {
                *self = Self(self.0).union(other);
            }
            /// The intersection of a source flags value with the complement of a target flags
            /// value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `remove` won't truncate `other`, but the `!` operator will.
            #[inline]
            pub fn remove(&mut self, other: Self) {
                *self = Self(self.0).difference(other);
            }
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            pub fn toggle(&mut self, other: Self) {
                *self = Self(self.0).symmetric_difference(other);
            }
            /// Call `insert` when `value` is `true` or `remove` when `value` is `false`.
            #[inline]
            pub fn set(&mut self, other: Self, value: bool) {
                if value { self.insert(other); } else { self.remove(other); }
            }
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn intersection(self, other: Self) -> Self {
                Self(self.0 & other.0)
            }
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn union(self, other: Self) -> Self {
                Self(self.0 | other.0)
            }
            /// The intersection of a source flags value with the complement of a target flags
            /// value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            #[must_use]
            pub const fn difference(self, other: Self) -> Self {
                Self(self.0 & !other.0)
            }
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn symmetric_difference(self, other: Self) -> Self {
                Self(self.0 ^ other.0)
            }
            /// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
            #[inline]
            #[must_use]
            pub const fn complement(self) -> Self {
                Self::from_bits_truncate(!self.0)
            }
        }
        impl ::bitflags::__private::core::fmt::Binary for InternalBitFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::Binary::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::Octal for InternalBitFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::Octal::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::LowerHex for InternalBitFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::LowerHex::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::UpperHex for InternalBitFlags {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::UpperHex::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::ops::BitOr for InternalBitFlags {
            type Output = Self;
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            fn bitor(self, other: InternalBitFlags) -> Self {
                self.union(other)
            }
        }
        impl ::bitflags::__private::core::ops::BitOrAssign for
            InternalBitFlags {
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            fn bitor_assign(&mut self, other: Self) { self.insert(other); }
        }
        impl ::bitflags::__private::core::ops::BitXor for InternalBitFlags {
            type Output = Self;
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            fn bitxor(self, other: Self) -> Self {
                self.symmetric_difference(other)
            }
        }
        impl ::bitflags::__private::core::ops::BitXorAssign for
            InternalBitFlags {
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            fn bitxor_assign(&mut self, other: Self) { self.toggle(other); }
        }
        impl ::bitflags::__private::core::ops::BitAnd for InternalBitFlags {
            type Output = Self;
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            fn bitand(self, other: Self) -> Self { self.intersection(other) }
        }
        impl ::bitflags::__private::core::ops::BitAndAssign for
            InternalBitFlags {
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            fn bitand_assign(&mut self, other: Self) {
                *self =
                    Self::from_bits_retain(self.bits()).intersection(other);
            }
        }
        impl ::bitflags::__private::core::ops::Sub for InternalBitFlags {
            type Output = Self;
            /// The intersection of a source flags value with the complement of a target flags value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            fn sub(self, other: Self) -> Self { self.difference(other) }
        }
        impl ::bitflags::__private::core::ops::SubAssign for InternalBitFlags
            {
            /// The intersection of a source flags value with the complement of a target flags value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            fn sub_assign(&mut self, other: Self) { self.remove(other); }
        }
        impl ::bitflags::__private::core::ops::Not for InternalBitFlags {
            type Output = Self;
            /// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
            #[inline]
            fn not(self) -> Self { self.complement() }
        }
        impl ::bitflags::__private::core::iter::Extend<InternalBitFlags> for
            InternalBitFlags {
            /// The bitwise or (`|`) of the bits in each flags value.
            fn extend<T: ::bitflags::__private::core::iter::IntoIterator<Item
                = Self>>(&mut self, iterator: T) {
                for item in iterator { self.insert(item) }
            }
        }
        impl ::bitflags::__private::core::iter::FromIterator<InternalBitFlags>
            for InternalBitFlags {
            /// The bitwise or (`|`) of the bits in each flags value.
            fn from_iter<T: ::bitflags::__private::core::iter::IntoIterator<Item
                = Self>>(iterator: T) -> Self {
                use ::bitflags::__private::core::iter::Extend;
                let mut result = Self::empty();
                result.extend(iterator);
                result
            }
        }
        impl InternalBitFlags {
            /// Yield a set of contained flags values.
            ///
            /// Each yielded flags value will correspond to a defined named flag. Any unknown bits
            /// will be yielded together as a final flags value.
            #[inline]
            pub const fn iter(&self)
                -> ::bitflags::iter::Iter<PathsToNested> {
                ::bitflags::iter::Iter::__private_const_new(<PathsToNested as
                        ::bitflags::Flags>::FLAGS,
                    PathsToNested::from_bits_retain(self.bits()),
                    PathsToNested::from_bits_retain(self.bits()))
            }
            /// Yield a set of contained named flags values.
            ///
            /// This method is like [`iter`](#method.iter), except only yields bits in contained named flags.
            /// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
            #[inline]
            pub const fn iter_names(&self)
                -> ::bitflags::iter::IterNames<PathsToNested> {
                ::bitflags::iter::IterNames::__private_const_new(<PathsToNested
                        as ::bitflags::Flags>::FLAGS,
                    PathsToNested::from_bits_retain(self.bits()),
                    PathsToNested::from_bits_retain(self.bits()))
            }
        }
        impl ::bitflags::__private::core::iter::IntoIterator for
            InternalBitFlags {
            type Item = PathsToNested;
            type IntoIter = ::bitflags::iter::Iter<PathsToNested>;
            fn into_iter(self) -> Self::IntoIter { self.iter() }
        }
        impl InternalBitFlags {
            /// Returns a mutable reference to the raw value of the flags currently stored.
            #[inline]
            pub fn bits_mut(&mut self) -> &mut u8 { &mut self.0 }
        }
        #[allow(dead_code, deprecated, unused_attributes)]
        impl PathsToNested {
            /// Get a flags value with all bits unset.
            #[inline]
            pub const fn empty() -> Self { Self(InternalBitFlags::empty()) }
            /// Get a flags value with all known bits set.
            #[inline]
            pub const fn all() -> Self { Self(InternalBitFlags::all()) }
            /// Get the underlying bits value.
            ///
            /// The returned value is exactly the bits set in this flags value.
            #[inline]
            pub const fn bits(&self) -> u8 { self.0.bits() }
            /// Convert from a bits value.
            ///
            /// This method will return `None` if any unknown bits are set.
            #[inline]
            pub const fn from_bits(bits: u8)
                -> ::bitflags::__private::core::option::Option<Self> {
                match InternalBitFlags::from_bits(bits) {
                    ::bitflags::__private::core::option::Option::Some(bits) =>
                        ::bitflags::__private::core::option::Option::Some(Self(bits)),
                    ::bitflags::__private::core::option::Option::None =>
                        ::bitflags::__private::core::option::Option::None,
                }
            }
            /// Convert from a bits value, unsetting any unknown bits.
            #[inline]
            pub const fn from_bits_truncate(bits: u8) -> Self {
                Self(InternalBitFlags::from_bits_truncate(bits))
            }
            /// Convert from a bits value exactly.
            #[inline]
            pub const fn from_bits_retain(bits: u8) -> Self {
                Self(InternalBitFlags::from_bits_retain(bits))
            }
            /// Get a flags value with the bits of a flag with the given name set.
            ///
            /// This method will return `None` if `name` is empty or doesn't
            /// correspond to any named flag.
            #[inline]
            pub fn from_name(name: &str)
                -> ::bitflags::__private::core::option::Option<Self> {
                match InternalBitFlags::from_name(name) {
                    ::bitflags::__private::core::option::Option::Some(bits) =>
                        ::bitflags::__private::core::option::Option::Some(Self(bits)),
                    ::bitflags::__private::core::option::Option::None =>
                        ::bitflags::__private::core::option::Option::None,
                }
            }
            /// Whether all bits in this flags value are unset.
            #[inline]
            pub const fn is_empty(&self) -> bool { self.0.is_empty() }
            /// Whether all known bits in this flags value are set.
            #[inline]
            pub const fn is_all(&self) -> bool { self.0.is_all() }
            /// Whether any set bits in a source flags value are also set in a target flags value.
            #[inline]
            pub const fn intersects(&self, other: Self) -> bool {
                self.0.intersects(other.0)
            }
            /// Whether all set bits in a source flags value are also set in a target flags value.
            #[inline]
            pub const fn contains(&self, other: Self) -> bool {
                self.0.contains(other.0)
            }
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            pub fn insert(&mut self, other: Self) { self.0.insert(other.0) }
            /// The intersection of a source flags value with the complement of a target flags
            /// value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `remove` won't truncate `other`, but the `!` operator will.
            #[inline]
            pub fn remove(&mut self, other: Self) { self.0.remove(other.0) }
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            pub fn toggle(&mut self, other: Self) { self.0.toggle(other.0) }
            /// Call `insert` when `value` is `true` or `remove` when `value` is `false`.
            #[inline]
            pub fn set(&mut self, other: Self, value: bool) {
                self.0.set(other.0, value)
            }
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn intersection(self, other: Self) -> Self {
                Self(self.0.intersection(other.0))
            }
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn union(self, other: Self) -> Self {
                Self(self.0.union(other.0))
            }
            /// The intersection of a source flags value with the complement of a target flags
            /// value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            #[must_use]
            pub const fn difference(self, other: Self) -> Self {
                Self(self.0.difference(other.0))
            }
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            #[must_use]
            pub const fn symmetric_difference(self, other: Self) -> Self {
                Self(self.0.symmetric_difference(other.0))
            }
            /// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
            #[inline]
            #[must_use]
            pub const fn complement(self) -> Self {
                Self(self.0.complement())
            }
        }
        impl ::bitflags::__private::core::fmt::Binary for PathsToNested {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::Binary::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::Octal for PathsToNested {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::Octal::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::LowerHex for PathsToNested {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::LowerHex::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::fmt::UpperHex for PathsToNested {
            fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
                -> ::bitflags::__private::core::fmt::Result {
                let inner = self.0;
                ::bitflags::__private::core::fmt::UpperHex::fmt(&inner, f)
            }
        }
        impl ::bitflags::__private::core::ops::BitOr for PathsToNested {
            type Output = Self;
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            fn bitor(self, other: PathsToNested) -> Self { self.union(other) }
        }
        impl ::bitflags::__private::core::ops::BitOrAssign for PathsToNested {
            /// The bitwise or (`|`) of the bits in two flags values.
            #[inline]
            fn bitor_assign(&mut self, other: Self) { self.insert(other); }
        }
        impl ::bitflags::__private::core::ops::BitXor for PathsToNested {
            type Output = Self;
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            fn bitxor(self, other: Self) -> Self {
                self.symmetric_difference(other)
            }
        }
        impl ::bitflags::__private::core::ops::BitXorAssign for PathsToNested
            {
            /// The bitwise exclusive-or (`^`) of the bits in two flags values.
            #[inline]
            fn bitxor_assign(&mut self, other: Self) { self.toggle(other); }
        }
        impl ::bitflags::__private::core::ops::BitAnd for PathsToNested {
            type Output = Self;
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            fn bitand(self, other: Self) -> Self { self.intersection(other) }
        }
        impl ::bitflags::__private::core::ops::BitAndAssign for PathsToNested
            {
            /// The bitwise and (`&`) of the bits in two flags values.
            #[inline]
            fn bitand_assign(&mut self, other: Self) {
                *self =
                    Self::from_bits_retain(self.bits()).intersection(other);
            }
        }
        impl ::bitflags::__private::core::ops::Sub for PathsToNested {
            type Output = Self;
            /// The intersection of a source flags value with the complement of a target flags value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            fn sub(self, other: Self) -> Self { self.difference(other) }
        }
        impl ::bitflags::__private::core::ops::SubAssign for PathsToNested {
            /// The intersection of a source flags value with the complement of a target flags value (`&!`).
            ///
            /// This method is not equivalent to `self & !other` when `other` has unknown bits set.
            /// `difference` won't truncate `other`, but the `!` operator will.
            #[inline]
            fn sub_assign(&mut self, other: Self) { self.remove(other); }
        }
        impl ::bitflags::__private::core::ops::Not for PathsToNested {
            type Output = Self;
            /// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
            #[inline]
            fn not(self) -> Self { self.complement() }
        }
        impl ::bitflags::__private::core::iter::Extend<PathsToNested> for
            PathsToNested {
            /// The bitwise or (`|`) of the bits in each flags value.
            fn extend<T: ::bitflags::__private::core::iter::IntoIterator<Item
                = Self>>(&mut self, iterator: T) {
                for item in iterator { self.insert(item) }
            }
        }
        impl ::bitflags::__private::core::iter::FromIterator<PathsToNested>
            for PathsToNested {
            /// The bitwise or (`|`) of the bits in each flags value.
            fn from_iter<T: ::bitflags::__private::core::iter::IntoIterator<Item
                = Self>>(iterator: T) -> Self {
                use ::bitflags::__private::core::iter::Extend;
                let mut result = Self::empty();
                result.extend(iterator);
                result
            }
        }
        impl PathsToNested {
            /// Yield a set of contained flags values.
            ///
            /// Each yielded flags value will correspond to a defined named flag. Any unknown bits
            /// will be yielded together as a final flags value.
            #[inline]
            pub const fn iter(&self)
                -> ::bitflags::iter::Iter<PathsToNested> {
                ::bitflags::iter::Iter::__private_const_new(<PathsToNested as
                        ::bitflags::Flags>::FLAGS,
                    PathsToNested::from_bits_retain(self.bits()),
                    PathsToNested::from_bits_retain(self.bits()))
            }
            /// Yield a set of contained named flags values.
            ///
            /// This method is like [`iter`](#method.iter), except only yields bits in contained named flags.
            /// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
            #[inline]
            pub const fn iter_names(&self)
                -> ::bitflags::iter::IterNames<PathsToNested> {
                ::bitflags::iter::IterNames::__private_const_new(<PathsToNested
                        as ::bitflags::Flags>::FLAGS,
                    PathsToNested::from_bits_retain(self.bits()),
                    PathsToNested::from_bits_retain(self.bits()))
            }
        }
        impl ::bitflags::__private::core::iter::IntoIterator for PathsToNested
            {
            type Item = PathsToNested;
            type IntoIter = ::bitflags::iter::Iter<PathsToNested>;
            fn into_iter(self) -> Self::IntoIter { self.iter() }
        }
    };bitflags::bitflags! {
396    /// Tracks how nested goals have been accessed. This is necessary to disable
397    /// global cache entries if computing them would otherwise result in a cycle or
398    /// access a provisional cache entry.
399    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
400    pub struct PathsToNested: u8 {
401        /// The initial value when adding a goal to its own nested goals.
402        const EMPTY                      = 1 << 0;
403        const INDUCTIVE                  = 1 << 1;
404        const UNKNOWN                    = 1 << 2;
405        const COINDUCTIVE                = 1 << 3;
406        const FORCED_AMBIGUITY           = 1 << 4;
407    }
408}
409impl From<PathKind> for PathsToNested {
410    fn from(path: PathKind) -> PathsToNested {
411        match path {
412            PathKind::Inductive => PathsToNested::INDUCTIVE,
413            PathKind::Unknown => PathsToNested::UNKNOWN,
414            PathKind::Coinductive => PathsToNested::COINDUCTIVE,
415            PathKind::ForcedAmbiguity => PathsToNested::FORCED_AMBIGUITY,
416        }
417    }
418}
419impl PathsToNested {
420    /// The implementation of this function is kind of ugly. We check whether
421    /// there currently exist 'weaker' paths in the set, if so we upgrade these
422    /// paths to at least `path`.
423    #[must_use]
424    fn extend_with(mut self, path: PathKind) -> Self {
425        match path {
426            PathKind::Inductive => {
427                if self.intersects(PathsToNested::EMPTY) {
428                    self.remove(PathsToNested::EMPTY);
429                    self.insert(PathsToNested::INDUCTIVE);
430                }
431            }
432            PathKind::Unknown => {
433                if self.intersects(PathsToNested::EMPTY | PathsToNested::INDUCTIVE) {
434                    self.remove(PathsToNested::EMPTY | PathsToNested::INDUCTIVE);
435                    self.insert(PathsToNested::UNKNOWN);
436                }
437            }
438            PathKind::Coinductive => {
439                if self.intersects(
440                    PathsToNested::EMPTY | PathsToNested::INDUCTIVE | PathsToNested::UNKNOWN,
441                ) {
442                    self.remove(
443                        PathsToNested::EMPTY | PathsToNested::INDUCTIVE | PathsToNested::UNKNOWN,
444                    );
445                    self.insert(PathsToNested::COINDUCTIVE);
446                }
447            }
448            PathKind::ForcedAmbiguity => {
449                if self.intersects(
450                    PathsToNested::EMPTY
451                        | PathsToNested::INDUCTIVE
452                        | PathsToNested::UNKNOWN
453                        | PathsToNested::COINDUCTIVE,
454                ) {
455                    self.remove(
456                        PathsToNested::EMPTY
457                            | PathsToNested::INDUCTIVE
458                            | PathsToNested::UNKNOWN
459                            | PathsToNested::COINDUCTIVE,
460                    );
461                    self.insert(PathsToNested::FORCED_AMBIGUITY);
462                }
463            }
464        }
465
466        self
467    }
468
469    #[must_use]
470    fn extend_with_paths(self, path: PathsToNested) -> Self {
471        let mut new = PathsToNested::empty();
472        for p in path.iter_paths() {
473            new |= self.extend_with(p);
474        }
475        new
476    }
477
478    fn iter_paths(self) -> impl Iterator<Item = PathKind> {
479        let (PathKind::Inductive
480        | PathKind::Unknown
481        | PathKind::Coinductive
482        | PathKind::ForcedAmbiguity);
483        [PathKind::Inductive, PathKind::Unknown, PathKind::Coinductive, PathKind::ForcedAmbiguity]
484            .into_iter()
485            .filter(move |&p| self.contains(p.into()))
486    }
487}
488
489/// The nested goals of each stack entry and the path from the
490/// stack entry to that nested goal.
491///
492/// They are used when checking whether reevaluating a global cache
493/// would encounter a cycle or use a provisional cache entry given the
494/// current search graph state. We need to disable the global cache
495/// in this case as it could otherwise result in behavioral differences.
496/// Cycles can impact behavior. The cycle ABA may have different final
497/// results from a the cycle BAB depending on the cycle root.
498///
499/// We only start tracking nested goals once we've either encountered
500/// overflow or a solver cycle. This is a performance optimization to
501/// avoid tracking nested goals on the happy path.
502#[automatically_derived]
impl<X: Cx> ::core::clone::Clone for NestedGoals<X> where X: Cx {
    #[inline]
    fn clone(&self) -> Self {
        match self {
            NestedGoals { nested_goals: ref __field_nested_goals } =>
                NestedGoals {
                    nested_goals: ::core::clone::Clone::clone(__field_nested_goals),
                },
        }
    }
}#[derive_where(Debug, Default, Clone; X: Cx)]
503struct NestedGoals<X: Cx> {
504    nested_goals: HashMap<X::Input, PathsToNested>,
505}
506impl<X: Cx> NestedGoals<X> {
507    fn is_empty(&self) -> bool {
508        self.nested_goals.is_empty()
509    }
510
511    fn insert(&mut self, input: X::Input, paths_to_nested: PathsToNested) {
512        match self.nested_goals.entry(input) {
513            Entry::Occupied(mut entry) => *entry.get_mut() |= paths_to_nested,
514            Entry::Vacant(entry) => drop(entry.insert(paths_to_nested)),
515        }
516    }
517
518    /// Adds the nested goals of a nested goal, given that the path `step_kind` from this goal
519    /// to the parent goal.
520    ///
521    /// If the path from this goal to the nested goal is inductive, the paths from this goal
522    /// to all nested goals of that nested goal are also inductive. Otherwise the paths are
523    /// the same as for the child.
524    fn extend_from_child(&mut self, step_kind: PathKind, nested_goals: &NestedGoals<X>) {
525        // Each nested goal is updated independently, and `insert` only unions paths for that
526        // goal, so traversal order cannot affect the result.
527        #[allow(rustc::potential_query_instability)]
528        for (input, paths_to_nested) in nested_goals.iter() {
529            let paths_to_nested = paths_to_nested.extend_with(step_kind);
530            self.insert(input, paths_to_nested);
531        }
532    }
533
534    // This helper intentionally exposes unstable hash iteration so each caller must opt in
535    // locally and justify why its traversal is order-insensitive.
536    #[cfg_attr(feature = "nightly", rustc_lint_query_instability)]
537    #[allow(rustc::potential_query_instability)]
538    fn iter(&self) -> impl Iterator<Item = (X::Input, PathsToNested)> + '_ {
539        self.nested_goals.iter().map(|(i, p)| (*i, *p))
540    }
541
542    fn contains(&self, input: X::Input) -> bool {
543        self.nested_goals.contains_key(&input)
544    }
545}
546
547/// A provisional result of an already computed goals which depends on other
548/// goals still on the stack.
549#[automatically_derived]
impl<X: Cx> ::core::fmt::Debug for ProvisionalCacheEntry<X> where X: Cx {
    fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>)
        -> ::core::fmt::Result {
        match self {
            ProvisionalCacheEntry {
                encountered_overflow: ref __field_encountered_overflow,
                heads: ref __field_heads,
                path_from_head: ref __field_path_from_head,
                result: ref __field_result } => {
                let mut __builder =
                    ::core::fmt::Formatter::debug_struct(__f,
                        "ProvisionalCacheEntry");
                ::core::fmt::DebugStruct::field(&mut __builder,
                    "encountered_overflow", __field_encountered_overflow);
                ::core::fmt::DebugStruct::field(&mut __builder, "heads",
                    __field_heads);
                ::core::fmt::DebugStruct::field(&mut __builder,
                    "path_from_head", __field_path_from_head);
                ::core::fmt::DebugStruct::field(&mut __builder, "result",
                    __field_result);
                ::core::fmt::DebugStruct::finish(&mut __builder)
            }
        }
    }
}#[derive_where(Debug; X: Cx)]
550struct ProvisionalCacheEntry<X: Cx> {
551    /// Whether evaluating the goal encountered overflow. This is used to
552    /// disable the cache entry except if the last goal on the stack is
553    /// already involved in this cycle.
554    encountered_overflow: bool,
555    /// All cycle heads this cache entry depends on.
556    heads: CycleHeads,
557    /// The path from the highest cycle head to this goal. This differs from
558    /// `heads` which tracks the path to the cycle head *from* this goal.
559    path_from_head: PathKind,
560    result: X::Result,
561}
562
563/// The final result of evaluating a goal.
564///
565/// We reset `encountered_overflow` when reevaluating a goal,
566/// but need to track whether we've hit the recursion limit at
567/// all for correctness.
568///
569/// We've previously simply returned the final `StackEntry` but this
570/// made it easy to accidentally drop information from the previous
571/// evaluation.
572#[automatically_derived]
impl<X: Cx> ::core::fmt::Debug for EvaluationResult<X> where X: Cx {
    fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>)
        -> ::core::fmt::Result {
        match self {
            EvaluationResult {
                encountered_overflow: ref __field_encountered_overflow,
                required_depth: ref __field_required_depth,
                heads: ref __field_heads,
                nested_goals: ref __field_nested_goals,
                result: ref __field_result } => {
                let mut __builder =
                    ::core::fmt::Formatter::debug_struct(__f,
                        "EvaluationResult");
                ::core::fmt::DebugStruct::field(&mut __builder,
                    "encountered_overflow", __field_encountered_overflow);
                ::core::fmt::DebugStruct::field(&mut __builder,
                    "required_depth", __field_required_depth);
                ::core::fmt::DebugStruct::field(&mut __builder, "heads",
                    __field_heads);
                ::core::fmt::DebugStruct::field(&mut __builder,
                    "nested_goals", __field_nested_goals);
                ::core::fmt::DebugStruct::field(&mut __builder, "result",
                    __field_result);
                ::core::fmt::DebugStruct::finish(&mut __builder)
            }
        }
    }
}#[derive_where(Debug; X: Cx)]
573struct EvaluationResult<X: Cx> {
574    encountered_overflow: bool,
575    required_depth: usize,
576    heads: CycleHeads,
577    nested_goals: NestedGoals<X>,
578    result: X::Result,
579}
580
581impl<X: Cx> EvaluationResult<X> {
582    fn finalize(
583        final_entry: StackEntry<X>,
584        encountered_overflow: bool,
585        result: X::Result,
586    ) -> EvaluationResult<X> {
587        EvaluationResult {
588            encountered_overflow,
589            // Unlike `encountered_overflow`, we share `heads`, `required_depth`,
590            // and `nested_goals` between evaluations.
591            required_depth: final_entry.required_depth(),
592            heads: final_entry.heads,
593            nested_goals: final_entry.nested_goals,
594            // We only care about the final result.
595            result,
596        }
597    }
598}
599
600pub struct SearchGraph<D: Delegate<Cx = X>, X: Cx = <D as Delegate>::Cx> {
601    root_depth: AvailableDepth,
602    stack: Stack<X>,
603    /// The provisional cache contains entries for already computed goals which
604    /// still depend on goals higher-up in the stack. We don't move them to the
605    /// global cache and track them locally instead. A provisional cache entry
606    /// is only valid until the result of one of its cycle heads changes.
607    provisional_cache: HashMap<X::Input, Vec<ProvisionalCacheEntry<X>>>,
608
609    _marker: PhantomData<D>,
610}
611
612/// While [`SearchGraph::update_parent_goal`] can be mostly shared between
613/// ordinary nested goals/global cache hits and provisional cache hits,
614/// using the provisional cache should not add any nested goals.
615///
616/// `nested_goals` are only used when checking whether global cache entries
617/// are applicable. This only cares about whether a goal is actually accessed.
618/// Given that the usage of the provisional cache is fully deterministic, we
619/// don't need to track the nested goals used while computing a provisional
620/// cache entry.
621enum UpdateParentGoalCtxt<'a, X: Cx> {
622    Ordinary { nested_goals: &'a NestedGoals<X>, min_reachable_available_depth: AvailableDepth },
623    CycleOnStack(X::Input),
624    ProvisionalCacheHit,
625}
626
627impl<D: Delegate<Cx = X>, X: Cx> SearchGraph<D> {
628    pub fn new(root_depth: usize) -> SearchGraph<D> {
629        Self {
630            root_depth: AvailableDepth(root_depth),
631            stack: Default::default(),
632            provisional_cache: Default::default(),
633            _marker: PhantomData,
634        }
635    }
636
637    /// Lazily update the stack entry for the parent goal.
638    /// This behavior is shared between actually evaluating goals
639    /// and using existing global cache entries to make sure they
640    /// have the same impact on the remaining evaluation.
641    fn update_parent_goal(
642        stack: &mut Stack<X>,
643        step_kind_from_parent: PathKind,
644        heads: impl Iterator<Item = (StackDepth, CycleHead)>,
645        encountered_overflow: bool,
646        context: UpdateParentGoalCtxt<'_, X>,
647    ) {
648        if let Some((parent_index, parent)) = stack.last_mut_with_index() {
649            parent.encountered_overflow |= encountered_overflow;
650
651            for (head_index, head) in heads {
652                if let Some(candidate_usages) = &mut parent.candidate_usages {
653                    candidate_usages
654                        .usages
655                        .get_or_insert_default()
656                        .entry(head_index)
657                        .or_default()
658                        .add_usages_from_nested(head.usages);
659                }
660                match head_index.cmp(&parent_index) {
661                    Ordering::Less => parent.heads.insert(
662                        head_index,
663                        head.paths_to_head.extend_with(step_kind_from_parent),
664                        head.usages,
665                    ),
666                    Ordering::Equal => {
667                        parent.usages.get_or_insert_default().add_usages_from_nested(head.usages);
668                    }
669                    Ordering::Greater => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
670                }
671            }
672            let parent_depends_on_cycle = match context {
673                UpdateParentGoalCtxt::Ordinary { nested_goals, min_reachable_available_depth } => {
674                    parent.min_reached_available_depth =
675                        parent.min_reached_available_depth.min(min_reachable_available_depth);
676                    parent.nested_goals.extend_from_child(step_kind_from_parent, nested_goals);
677                    !nested_goals.is_empty()
678                }
679                UpdateParentGoalCtxt::CycleOnStack(head) => {
680                    // We lookup provisional cache entries before detecting cycles.
681                    // We therefore can't use a global cache entry if it contains a cycle
682                    // whose head is in the provisional cache.
683                    parent.nested_goals.insert(head, step_kind_from_parent.into());
684                    true
685                }
686                UpdateParentGoalCtxt::ProvisionalCacheHit => true,
687            };
688            // Once we've got goals which encountered overflow or a cycle,
689            // we track all goals whose behavior may depend depend on these
690            // goals as this change may cause them to now depend on additional
691            // goals, resulting in new cycles. See the dev-guide for examples.
692            if parent_depends_on_cycle {
693                parent.nested_goals.insert(parent.input, PathsToNested::EMPTY);
694            }
695        }
696    }
697
698    pub fn is_empty(&self) -> bool {
699        if self.stack.is_empty() {
700            if true {
    if !self.provisional_cache.is_empty() {
        ::core::panicking::panic("assertion failed: self.provisional_cache.is_empty()")
    };
};debug_assert!(self.provisional_cache.is_empty());
701            true
702        } else {
703            false
704        }
705    }
706
707    /// The number of goals currently in the search graph. This should only be
708    /// used for debugging purposes.
709    pub fn debug_current_depth(&self) -> usize {
710        self.stack.len()
711    }
712
713    /// Whether the path from `head` to the current stack entry is inductive or coinductive.
714    ///
715    /// The `step_kind_to_head` is used to add a single additional path segment to the path on
716    /// the stack which completes the cycle. This given an inductive step AB which then cycles
717    /// coinductively with A, we need to treat this cycle as coinductive.
718    fn cycle_path_kind(
719        stack: &Stack<X>,
720        step_kind_to_head: PathKind,
721        head: StackDepth,
722    ) -> PathKind {
723        stack.cycle_step_kinds(head).fold(step_kind_to_head, |curr, step| curr.extend(step))
724    }
725
726    pub fn enter_single_candidate(&mut self) {
727        let prev = self.stack.last_mut().unwrap().candidate_usages.replace(Default::default());
728        if true {
    if !prev.is_none() {
        {
            ::core::panicking::panic_fmt(format_args!("existing candidate_usages: {0:?}",
                    prev));
        }
    };
};debug_assert!(prev.is_none(), "existing candidate_usages: {prev:?}");
729    }
730
731    pub fn finish_single_candidate(&mut self) -> CandidateHeadUsages {
732        self.stack.last_mut().unwrap().candidate_usages.take().unwrap()
733    }
734
735    pub fn ignore_candidate_head_usages(&mut self, usages: CandidateHeadUsages) {
736        if let Some(usages) = usages.usages {
737            let (entry_index, entry) = self.stack.last_mut_with_index().unwrap();
738            // Ignoring usages only mutates the state for the current `head_index`, so the
739            // resulting per-head state is unchanged by iteration order.
740            #[allow(rustc::potential_query_instability)]
741            for (head_index, usages) in usages.into_iter() {
742                if head_index == entry_index {
743                    entry.usages.unwrap().ignore_usages(usages);
744                } else {
745                    entry.heads.ignore_usages(head_index, usages);
746                }
747            }
748        }
749    }
750
751    pub fn evaluate_root_goal_for_proof_tree(
752        cx: X,
753        root_depth: usize,
754        input: X::Input,
755        inspect: &mut D::ProofTreeBuilder,
756    ) -> X::Result {
757        let mut this = SearchGraph::<D>::new(root_depth);
758        let available_depth = AvailableDepth(root_depth);
759        let step_kind_from_parent = PathKind::Inductive; // is never used
760        this.stack.push(StackEntry {
761            input,
762            step_kind_from_parent,
763            available_depth,
764            min_reached_available_depth: available_depth,
765            provisional_result: None,
766            heads: Default::default(),
767            encountered_overflow: false,
768            usages: None,
769            candidate_usages: None,
770            nested_goals: Default::default(),
771        });
772        let evaluation_result = this.evaluate_goal_in_task(cx, input, inspect);
773        evaluation_result.result
774    }
775
776    /// Probably the most involved method of the whole solver.
777    ///
778    /// While goals get computed via `D::compute_goal`, this function handles
779    /// caching, overflow, and cycles.
780    x;#[instrument(level = "debug", skip(self, cx, inspect), ret)]
781    pub fn evaluate_goal(
782        &mut self,
783        cx: X,
784        input: X::Input,
785        step_kind_from_parent: PathKind,
786        lower_available_depth: LowerAvailableDepth,
787        inspect: &mut D::ProofTreeBuilder,
788    ) -> X::Result {
789        let Some(available_depth) = AvailableDepth::allowed_depth_for_nested::<D>(
790            self.root_depth,
791            &self.stack,
792            lower_available_depth,
793        ) else {
794            return self.handle_overflow(cx, input);
795        };
796
797        // We check the provisional cache before checking the global cache. This simplifies
798        // the implementation as we can avoid worrying about cases where both the global and
799        // provisional cache may apply, e.g. consider the following example
800        //
801        // - xxBA overflow
802        // - A
803        //     - BA cycle
804        //     - CB :x:
805        if let Some(result) = self.lookup_provisional_cache(input, step_kind_from_parent) {
806            return result;
807        }
808
809        // Lookup the global cache unless we're building proof trees or are currently
810        // fuzzing.
811        let validate_cache = if !D::inspect_is_noop(inspect) {
812            None
813        } else if let Some(scope) = D::enter_validation_scope(cx, input) {
814            // When validating the global cache we need to track the goals for which the
815            // global cache has been disabled as it may otherwise change the result for
816            // cyclic goals. We don't care about goals which are not on the current stack
817            // so it's fine to drop their scope eagerly.
818            self.lookup_global_cache_untracked(cx, input, step_kind_from_parent, available_depth)
819                .inspect(|expected| debug!(?expected, "validate cache entry"))
820                .map(|r| (scope, r))
821        } else if let Some(result) =
822            self.lookup_global_cache(cx, input, step_kind_from_parent, available_depth)
823        {
824            return result;
825        } else {
826            None
827        };
828
829        // Detect cycles on the stack. We do this after the global cache lookup to
830        // avoid iterating over the stack in case a goal has already been computed.
831        // This may not have an actual performance impact and we could reorder them
832        // as it may reduce the number of `nested_goals` we need to track.
833        if let Some(result) = self.check_cycle_on_stack(cx, input, step_kind_from_parent) {
834            debug_assert!(validate_cache.is_none(), "global cache and cycle on stack: {input:?}");
835            return result;
836        }
837
838        // Unfortunate, it looks like we actually have to compute this goal.
839        self.stack.push(StackEntry {
840            input,
841            step_kind_from_parent,
842            available_depth,
843            provisional_result: None,
844            min_reached_available_depth: available_depth,
845            heads: Default::default(),
846            encountered_overflow: false,
847            usages: None,
848            candidate_usages: None,
849            nested_goals: Default::default(),
850        });
851
852        // This is for global caching, so we properly track query dependencies.
853        // Everything that affects the `result` should be performed within this
854        // `with_cached_task` closure. If computing this goal depends on something
855        // not tracked by the cache key and from outside of this anon task, it
856        // must not be added to the global cache. Notably, this is the case for
857        // trait solver cycles participants.
858        let (evaluation_result, dep_node) =
859            cx.with_cached_task(|| self.evaluate_goal_in_task(cx, input, inspect));
860
861        // We've finished computing the goal and have popped it from the stack,
862        // lazily update its parent goal.
863        Self::update_parent_goal(
864            &mut self.stack,
865            step_kind_from_parent,
866            evaluation_result.heads.iter(),
867            evaluation_result.encountered_overflow,
868            UpdateParentGoalCtxt::Ordinary {
869                nested_goals: &evaluation_result.nested_goals,
870                min_reachable_available_depth: AvailableDepth(
871                    available_depth.0 - evaluation_result.required_depth,
872                ),
873            },
874        );
875        let result = evaluation_result.result;
876
877        // We're now done with this goal. We only add the root of cycles to the global cache.
878        // In case this goal is involved in a larger cycle add it to the provisional cache.
879        if evaluation_result.heads.is_empty() {
880            if let Some((_scope, expected)) = validate_cache {
881                // Do not try to move a goal into the cache again if we're testing
882                // the global cache.
883                assert_eq!(expected, result, "input={input:?}");
884            } else if D::inspect_is_noop(inspect) {
885                self.insert_global_cache(cx, input, evaluation_result, dep_node)
886            }
887        } else if D::ENABLE_PROVISIONAL_CACHE {
888            debug_assert!(validate_cache.is_none(), "unexpected non-root: {input:?}");
889            let entry = self.provisional_cache.entry(input).or_default();
890            let EvaluationResult {
891                encountered_overflow,
892                required_depth: _,
893                heads,
894                nested_goals: _,
895                result,
896            } = evaluation_result;
897            let path_from_head = Self::cycle_path_kind(
898                &self.stack,
899                step_kind_from_parent,
900                heads.highest_cycle_head_index(),
901            );
902            let provisional_cache_entry =
903                ProvisionalCacheEntry { encountered_overflow, heads, path_from_head, result };
904            debug!(?provisional_cache_entry);
905            entry.push(provisional_cache_entry);
906        } else {
907            debug_assert!(validate_cache.is_none(), "unexpected non-root: {input:?}");
908        }
909
910        result
911    }
912
913    fn handle_overflow(&mut self, cx: X, input: X::Input) -> X::Result {
914        if let Some(last) = self.stack.last_mut() {
915            last.encountered_overflow = true;
916            // If computing a goal `B` depends on another goal `A` and
917            // `A` has a nested goal which overflows, then computing `B`
918            // at the same depth, but with `A` already on the stack,
919            // would encounter a solver cycle instead, potentially
920            // changing the result.
921            //
922            // We must therefore not use the global cache entry for `B` in that case.
923            // See tests/ui/traits/next-solver/cycles/hidden-by-overflow.rs
924            last.nested_goals.insert(last.input, PathsToNested::EMPTY);
925        }
926
927        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_type_ir/src/search_graph/mod.rs:927",
                        "rustc_type_ir::search_graph", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_type_ir/src/search_graph/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(927u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_type_ir::search_graph"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("encountered stack overflow")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("encountered stack overflow");
928        D::stack_overflow_result(cx, input)
929    }
930
931    /// When reevaluating a goal with a changed provisional result, all provisional cache entry
932    /// which depend on this goal get invalidated.
933    ///
934    /// Note that we keep provisional cache entries which accessed this goal as a cycle head, but
935    /// don't depend on its value.
936    fn clear_dependent_provisional_results_for_rerun(&mut self) {
937        let rerun_index = self.stack.next_index();
938        // Each cached entry is filtered independently based on whether it depends on
939        // `rerun_index`, so bucket traversal order does not matter.
940        #[allow(rustc::potential_query_instability)]
941        self.provisional_cache.retain(|_, entries| {
942            entries.retain(|entry| {
943                let (head_index, head) = entry.heads.highest_cycle_head();
944                head_index != rerun_index || head.usages.is_empty()
945            });
946            !entries.is_empty()
947        });
948    }
949}
950
951/// We need to rebase provisional cache entries when popping one of their cycle
952/// heads from the stack. This may not necessarily mean that we've actually
953/// reached a fixpoint for that cycle head, which impacts the way we rebase
954/// provisional cache entries.
955#[automatically_derived]
impl<X: Cx> ::core::fmt::Debug for RebaseReason<X> where X: Cx {
    fn fmt(&self, __f: &mut ::core::fmt::Formatter<'_>)
        -> ::core::fmt::Result {
        match self {
            RebaseReason::NoCycleUsages =>
                ::core::fmt::Formatter::write_str(__f, "NoCycleUsages"),
            RebaseReason::Ambiguity(ref __field_0) => {
                let mut __builder =
                    ::core::fmt::Formatter::debug_tuple(__f, "Ambiguity");
                ::core::fmt::DebugTuple::field(&mut __builder, __field_0);
                ::core::fmt::DebugTuple::finish(&mut __builder)
            }
            RebaseReason::Overflow =>
                ::core::fmt::Formatter::write_str(__f, "Overflow"),
            RebaseReason::ReachedFixpoint(ref __field_0) => {
                let mut __builder =
                    ::core::fmt::Formatter::debug_tuple(__f, "ReachedFixpoint");
                ::core::fmt::DebugTuple::field(&mut __builder, __field_0);
                ::core::fmt::DebugTuple::finish(&mut __builder)
            }
        }
    }
}#[derive_where(Debug; X: Cx)]
956enum RebaseReason<X: Cx> {
957    NoCycleUsages,
958    Ambiguity(X::AmbiguityInfo),
959    Overflow,
960    /// We've actually reached a fixpoint.
961    ///
962    /// This either happens in the first evaluation step for the cycle head.
963    /// In this case the used provisional result depends on the cycle `PathKind`.
964    /// We store this path kind to check whether the provisional cache entry
965    /// we're rebasing relied on the same cycles.
966    ///
967    /// In later iterations cycles always return `stack_entry.provisional_result`
968    /// so we no longer depend on the `PathKind`. We store `None` in that case.
969    ReachedFixpoint(Option<PathKind>),
970}
971
972impl<D: Delegate<Cx = X>, X: Cx> SearchGraph<D, X> {
973    /// A necessary optimization to handle complex solver cycles. A provisional cache entry
974    /// relies on a set of cycle heads and the path towards these heads. When popping a cycle
975    /// head from the stack after we've finished computing it, we can't be sure that the
976    /// provisional cache entry is still applicable. We need to keep the cache entries to
977    /// prevent hangs.
978    ///
979    /// This can be thought of as pretending to reevaluate the popped head as nested goals
980    /// of this provisional result. For this to be correct, all cycles encountered while
981    /// we'd reevaluate the cycle head as a nested goal must keep the same cycle kind.
982    /// [rustc-dev-guide chapter](https://rustc-dev-guide.rust-lang.org/solve/caching.html).
983    ///
984    /// In case the popped cycle head failed to reach a fixpoint anything which depends on
985    /// its provisional result is invalid. Actually discarding provisional cache entries in
986    /// this case would cause hangs, so we instead change the result of dependant provisional
987    /// cache entries to also be ambiguous. This causes some undesirable ambiguity for nested
988    /// goals whose result doesn't actually depend on this cycle head, but that's acceptable
989    /// to me.
990    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("rebase_provisional_cache_entries",
                                    "rustc_type_ir::search_graph", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_type_ir/src/search_graph/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(990u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_type_ir::search_graph"),
                                    ::tracing_core::field::FieldSet::new(&["stack_entry",
                                                    "rebase_reason"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&stack_entry)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rebase_reason)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let popped_head_index = self.stack.next_index();

            #[allow(rustc::potential_query_instability)]
            self.provisional_cache.retain(|&input, entries|
                    {
                        entries.retain_mut(|entry|
                                {
                                    let ProvisionalCacheEntry {
                                            encountered_overflow: _, heads, path_from_head, result } =
                                        entry;
                                    let popped_head =
                                        if heads.highest_cycle_head_index() == popped_head_index {
                                            heads.remove_highest_cycle_head()
                                        } else {
                                            if true {
                                                if !(heads.highest_cycle_head_index() < popped_head_index) {
                                                    ::core::panicking::panic("assertion failed: heads.highest_cycle_head_index() < popped_head_index")
                                                };
                                            };
                                            return true;
                                        };
                                    if popped_head.usages.is_empty() {
                                        for (head_index, _) in stack_entry.heads.iter() {
                                            heads.insert(head_index, PathsToNested::EMPTY,
                                                HeadUsages::default());
                                        }
                                    } else {
                                        let ep = popped_head.paths_to_head;
                                        for (head_index, head) in stack_entry.heads.iter() {
                                            let ph = head.paths_to_head;
                                            let hp =
                                                Self::cycle_path_kind(&self.stack,
                                                    stack_entry.step_kind_from_parent, head_index);
                                            let he = hp.extend(*path_from_head);
                                            for ph in ph.iter_paths() {
                                                let hph = hp.extend(ph);
                                                for ep in ep.iter_paths() {
                                                    let hep = ep.extend(he);
                                                    let heph = hep.extend(ph);
                                                    if hph != heph { return false; }
                                                }
                                            }
                                            let eph = ep.extend_with_paths(ph);
                                            heads.insert(head_index, eph, head.usages);
                                        }
                                        match rebase_reason {
                                            RebaseReason::NoCycleUsages => return false,
                                            RebaseReason::Ambiguity(info) => {
                                                *result = D::propagate_ambiguity(cx, input, info);
                                            }
                                            RebaseReason::Overflow =>
                                                *result = D::fixpoint_overflow_result(cx, input),
                                            RebaseReason::ReachedFixpoint(None) => {}
                                            RebaseReason::ReachedFixpoint(Some(path_kind)) => {
                                                if !popped_head.usages.is_single(path_kind) {
                                                    return false;
                                                }
                                            }
                                        };
                                    }
                                    let Some(new_highest_head_index) =
                                        heads.opt_highest_cycle_head_index() else { return false; };
                                    *path_from_head =
                                        path_from_head.extend(Self::cycle_path_kind(&self.stack,
                                                stack_entry.step_kind_from_parent, new_highest_head_index));
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_type_ir/src/search_graph/mod.rs:1101",
                                                            "rustc_type_ir::search_graph", ::tracing::Level::TRACE,
                                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_type_ir/src/search_graph/mod.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(1101u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_type_ir::search_graph"),
                                                            ::tracing_core::field::FieldSet::new(&["message", "input",
                                                                            "entry"],
                                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                            ::tracing::metadata::Kind::EVENT)
                                                    };
                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                            };
                                        let enabled =
                                            ::tracing::Level::TRACE <=
                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                    ::tracing::Level::TRACE <=
                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                {
                                                    let interest = __CALLSITE.interest();
                                                    !interest.is_never() &&
                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                            interest)
                                                };
                                        if enabled {
                                            (|value_set: ::tracing::field::ValueSet|
                                                        {
                                                            let meta = __CALLSITE.metadata();
                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                            ;
                                                        })({
                                                    #[allow(unused_imports)]
                                                    use ::tracing::field::{debug, display, Value};
                                                    let mut iter = __CALLSITE.metadata().fields().iter();
                                                    __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                        ::tracing::__macro_support::Option::Some(&format_args!("rebased provisional cache entry")
                                                                                as &dyn Value)),
                                                                    (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                        ::tracing::__macro_support::Option::Some(&debug(&input) as
                                                                                &dyn Value)),
                                                                    (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                        ::tracing::__macro_support::Option::Some(&debug(&entry) as
                                                                                &dyn Value))])
                                                });
                                        } else { ; }
                                    };
                                    true
                                });
                        !entries.is_empty()
                    });
        }
    }
}#[instrument(level = "trace", skip(self, cx))]
991    fn rebase_provisional_cache_entries(
992        &mut self,
993        cx: X,
994        stack_entry: &StackEntry<X>,
995        rebase_reason: RebaseReason<X>,
996    ) {
997        let popped_head_index = self.stack.next_index();
998        // Rebasing decisions depend only on each provisional entry and the current stack state,
999        // so traversing the cache in hash order cannot change the final cache contents.
1000        #[allow(rustc::potential_query_instability)]
1001        self.provisional_cache.retain(|&input, entries| {
1002            entries.retain_mut(|entry| {
1003                let ProvisionalCacheEntry {
1004                    encountered_overflow: _,
1005                    heads,
1006                    path_from_head,
1007                    result,
1008                } = entry;
1009                let popped_head = if heads.highest_cycle_head_index() == popped_head_index {
1010                    heads.remove_highest_cycle_head()
1011                } else {
1012                    debug_assert!(heads.highest_cycle_head_index() < popped_head_index);
1013                    return true;
1014                };
1015
1016                // We're rebasing an entry `e` over a head `p`. This head
1017                // has a number of own heads `h` it depends on.
1018                //
1019                // This causes our provisional result to depend on the heads
1020                // of `p` to avoid moving any goal which uses this cache entry to
1021                // the global cache.
1022                if popped_head.usages.is_empty() {
1023                    // The result of `e` does not depend on the value of `p`. This we can
1024                    // keep using the result of this provisional cache entry even if evaluating
1025                    // `p` as a nested goal of `e` would have a different result.
1026                    for (head_index, _) in stack_entry.heads.iter() {
1027                        heads.insert(head_index, PathsToNested::EMPTY, HeadUsages::default());
1028                    }
1029                } else {
1030                    // The entry `e` actually depends on the value of `p`. We need
1031                    // to make sure that the value of `p` wouldn't change even if we
1032                    // were to reevaluate it as a nested goal of `e` instead. For this
1033                    // we check that the path kind of all paths `hph` remain the
1034                    // same after rebasing.
1035                    //
1036                    // After rebasing the cycles `hph` will go through `e`. We need to make
1037                    // sure that forall possible paths `hep`, `heph` is equal to `hph.`
1038                    let ep = popped_head.paths_to_head;
1039                    for (head_index, head) in stack_entry.heads.iter() {
1040                        let ph = head.paths_to_head;
1041                        let hp = Self::cycle_path_kind(
1042                            &self.stack,
1043                            stack_entry.step_kind_from_parent,
1044                            head_index,
1045                        );
1046                        // We first validate that all cycles while computing `p` would stay
1047                        // the same if we were to recompute it as a nested goal of `e`.
1048                        let he = hp.extend(*path_from_head);
1049                        for ph in ph.iter_paths() {
1050                            let hph = hp.extend(ph);
1051                            for ep in ep.iter_paths() {
1052                                let hep = ep.extend(he);
1053                                let heph = hep.extend(ph);
1054                                if hph != heph {
1055                                    return false;
1056                                }
1057                            }
1058                        }
1059
1060                        // If so, all paths reached while computing `p` have to get added
1061                        // the heads of `e` to make sure that rebasing `e` again also considers
1062                        // them.
1063                        let eph = ep.extend_with_paths(ph);
1064                        heads.insert(head_index, eph, head.usages);
1065                    }
1066
1067                    // The provisional cache entry does depend on the provisional result
1068                    // of the popped cycle head. We need to mutate the result of our
1069                    // provisional cache entry in case we did not reach a fixpoint.
1070                    match rebase_reason {
1071                        // If the cycle head does not actually depend on itself, then
1072                        // the provisional result used by the provisional cache entry
1073                        // is not actually equal to the final provisional result. We
1074                        // need to discard the provisional cache entry in this case.
1075                        RebaseReason::NoCycleUsages => return false,
1076                        RebaseReason::Ambiguity(info) => {
1077                            *result = D::propagate_ambiguity(cx, input, info);
1078                        }
1079                        RebaseReason::Overflow => *result = D::fixpoint_overflow_result(cx, input),
1080                        RebaseReason::ReachedFixpoint(None) => {}
1081                        RebaseReason::ReachedFixpoint(Some(path_kind)) => {
1082                            if !popped_head.usages.is_single(path_kind) {
1083                                return false;
1084                            }
1085                        }
1086                    };
1087                }
1088
1089                let Some(new_highest_head_index) = heads.opt_highest_cycle_head_index() else {
1090                    return false;
1091                };
1092
1093                // We now care about the path from the next highest cycle head to the
1094                // provisional cache entry.
1095                *path_from_head = path_from_head.extend(Self::cycle_path_kind(
1096                    &self.stack,
1097                    stack_entry.step_kind_from_parent,
1098                    new_highest_head_index,
1099                ));
1100
1101                trace!(?input, ?entry, "rebased provisional cache entry");
1102
1103                true
1104            });
1105            !entries.is_empty()
1106        });
1107    }
1108
1109    fn lookup_provisional_cache(
1110        &mut self,
1111        input: X::Input,
1112        step_kind_from_parent: PathKind,
1113    ) -> Option<X::Result> {
1114        if !D::ENABLE_PROVISIONAL_CACHE {
1115            return None;
1116        }
1117
1118        let entries = self.provisional_cache.get(&input)?;
1119        for &ProvisionalCacheEntry { encountered_overflow, ref heads, path_from_head, result } in
1120            entries
1121        {
1122            let head_index = heads.highest_cycle_head_index();
1123            if encountered_overflow {
1124                // This check is overly strict and very subtle. We need to make sure that if
1125                // a global cache entry depends on some goal without adding it to its
1126                // `nested_goals`, that goal must never have an applicable provisional
1127                // cache entry to avoid incorrectly applying the cache entry.
1128                //
1129                // As we'd have to otherwise track literally all nested goals, we only
1130                // apply provisional cache entries which encountered overflow once the
1131                // current goal is already part of the same cycle. This check could be
1132                // improved but seems to be good enough for now.
1133                let last = self.stack.last().unwrap();
1134                if last.heads.opt_lowest_cycle_head_index().is_none_or(|lowest| lowest > head_index)
1135                {
1136                    continue;
1137                }
1138            }
1139
1140            // A provisional cache entry is only valid if the current path from its
1141            // highest cycle head to the goal is the same.
1142            if path_from_head
1143                == Self::cycle_path_kind(&self.stack, step_kind_from_parent, head_index)
1144            {
1145                Self::update_parent_goal(
1146                    &mut self.stack,
1147                    step_kind_from_parent,
1148                    heads.iter(),
1149                    encountered_overflow,
1150                    UpdateParentGoalCtxt::ProvisionalCacheHit,
1151                );
1152                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_type_ir/src/search_graph/mod.rs:1152",
                        "rustc_type_ir::search_graph", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_type_ir/src/search_graph/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1152u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_type_ir::search_graph"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "head_index", "path_from_head"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("provisional cache hit")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&head_index)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&path_from_head)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?head_index, ?path_from_head, "provisional cache hit");
1153                return Some(result);
1154            }
1155        }
1156
1157        None
1158    }
1159
1160    /// Even if there is a global cache entry for a given goal, we need to make sure
1161    /// evaluating this entry would not have ended up depending on either a goal
1162    /// already on the stack or a provisional cache entry.
1163    fn candidate_is_applicable(
1164        &self,
1165        step_kind_from_parent: PathKind,
1166        nested_goals: &NestedGoals<X>,
1167    ) -> bool {
1168        // If the global cache entry didn't depend on any nested goals, it always
1169        // applies.
1170        if nested_goals.is_empty() {
1171            return true;
1172        }
1173
1174        // If a nested goal of the global cache entry is on the stack, we would
1175        // definitely encounter a cycle.
1176        if self.stack.iter().any(|e| nested_goals.contains(e.input)) {
1177            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_type_ir/src/search_graph/mod.rs:1177",
                        "rustc_type_ir::search_graph", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_type_ir/src/search_graph/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1177u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_type_ir::search_graph"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("cache entry not applicable due to stack")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("cache entry not applicable due to stack");
1178            return false;
1179        }
1180
1181        // The global cache entry is also invalid if there's a provisional cache entry
1182        // would apply for any of its nested goals.
1183        // Any matching provisional entry rejects the candidate,
1184        // so iteration order only affects when we return `false`, not the final answer.
1185        #[allow(rustc::potential_query_instability)]
1186        for (input, path_from_global_entry) in nested_goals.iter() {
1187            let Some(entries) = self.provisional_cache.get(&input) else {
1188                continue;
1189            };
1190
1191            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_type_ir/src/search_graph/mod.rs:1191",
                        "rustc_type_ir::search_graph", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_type_ir/src/search_graph/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1191u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_type_ir::search_graph"),
                        ::tracing_core::field::FieldSet::new(&["message", "input",
                                        "path_from_global_entry", "entries"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("candidate_is_applicable")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&input) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&path_from_global_entry)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&entries) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?input, ?path_from_global_entry, ?entries, "candidate_is_applicable");
1192            // A provisional cache entry is applicable if the path to
1193            // its highest cycle head is equal to the expected path.
1194            for &ProvisionalCacheEntry {
1195                encountered_overflow,
1196                ref heads,
1197                path_from_head: head_to_provisional,
1198                result: _,
1199            } in entries.iter()
1200            {
1201                // We don't have to worry about provisional cache entries which encountered
1202                // overflow, see the relevant comment in `lookup_provisional_cache`.
1203                if encountered_overflow {
1204                    continue;
1205                }
1206
1207                // A provisional cache entry only applies if the path from its highest head
1208                // matches the path when encountering the goal.
1209                //
1210                // We check if any of the paths taken while computing the global goal
1211                // would end up with an applicable provisional cache entry.
1212                let head_index = heads.highest_cycle_head_index();
1213                let head_to_curr =
1214                    Self::cycle_path_kind(&self.stack, step_kind_from_parent, head_index);
1215                let full_paths = path_from_global_entry.extend_with(head_to_curr);
1216                if full_paths.contains(head_to_provisional.into()) {
1217                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_type_ir/src/search_graph/mod.rs:1217",
                        "rustc_type_ir::search_graph", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_type_ir/src/search_graph/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1217u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_type_ir::search_graph"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "full_paths", "head_to_provisional"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("cache entry not applicable due to matching paths")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&full_paths)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&head_to_provisional)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(
1218                        ?full_paths,
1219                        ?head_to_provisional,
1220                        "cache entry not applicable due to matching paths"
1221                    );
1222                    return false;
1223                }
1224            }
1225        }
1226
1227        true
1228    }
1229
1230    /// Used when fuzzing the global cache. Accesses the global cache without
1231    /// updating the state of the search graph.
1232    fn lookup_global_cache_untracked(
1233        &self,
1234        cx: X,
1235        input: X::Input,
1236        step_kind_from_parent: PathKind,
1237        available_depth: AvailableDepth,
1238    ) -> Option<X::Result> {
1239        cx.with_global_cache(|cache| {
1240            cache
1241                .get(cx, input, available_depth, |nested_goals| {
1242                    self.candidate_is_applicable(step_kind_from_parent, nested_goals)
1243                })
1244                .map(|c| c.result)
1245        })
1246    }
1247
1248    /// Try to fetch a previously computed result from the global cache,
1249    /// making sure to only do so if it would match the result of reevaluating
1250    /// this goal.
1251    fn lookup_global_cache(
1252        &mut self,
1253        cx: X,
1254        input: X::Input,
1255        step_kind_from_parent: PathKind,
1256        available_depth: AvailableDepth,
1257    ) -> Option<X::Result> {
1258        cx.with_global_cache(|cache| {
1259            let CacheData { result, required_depth, encountered_overflow, nested_goals } = cache
1260                .get(cx, input, available_depth, |nested_goals| {
1261                    self.candidate_is_applicable(step_kind_from_parent, nested_goals)
1262                })?;
1263
1264            // We don't move cycle participants to the global cache, so the
1265            // cycle heads are always empty.
1266            let heads = iter::empty();
1267            Self::update_parent_goal(
1268                &mut self.stack,
1269                step_kind_from_parent,
1270                heads,
1271                encountered_overflow,
1272                UpdateParentGoalCtxt::Ordinary {
1273                    nested_goals,
1274                    min_reachable_available_depth: AvailableDepth(
1275                        available_depth.0 - required_depth,
1276                    ),
1277                },
1278            );
1279
1280            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_type_ir/src/search_graph/mod.rs:1280",
                        "rustc_type_ir::search_graph", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_type_ir/src/search_graph/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1280u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_type_ir::search_graph"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "required_depth"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("global cache hit")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&required_depth)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?required_depth, "global cache hit");
1281            Some(result)
1282        })
1283    }
1284
1285    fn check_cycle_on_stack(
1286        &mut self,
1287        cx: X,
1288        input: X::Input,
1289        step_kind_from_parent: PathKind,
1290    ) -> Option<X::Result> {
1291        let head_index = self.stack.find(input)?;
1292        // We have a nested goal which directly relies on a goal deeper in the stack.
1293        //
1294        // We start by tagging all cycle participants, as that's necessary for caching.
1295        //
1296        // Finally we can return either the provisional response or the initial response
1297        // in case we're in the first fixpoint iteration for this goal.
1298        let path_kind = Self::cycle_path_kind(&self.stack, step_kind_from_parent, head_index);
1299        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_type_ir/src/search_graph/mod.rs:1299",
                        "rustc_type_ir::search_graph", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_type_ir/src/search_graph/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1299u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_type_ir::search_graph"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "path_kind"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("encountered cycle with depth {0:?}",
                                                    head_index) as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&path_kind)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?path_kind, "encountered cycle with depth {head_index:?}");
1300        let mut usages = HeadUsages::default();
1301        usages.add_usage(path_kind);
1302        let head = CycleHead { paths_to_head: step_kind_from_parent.into(), usages };
1303        Self::update_parent_goal(
1304            &mut self.stack,
1305            step_kind_from_parent,
1306            iter::once((head_index, head)),
1307            false,
1308            UpdateParentGoalCtxt::CycleOnStack(input),
1309        );
1310
1311        // Return the provisional result or, if we're in the first iteration,
1312        // start with no constraints.
1313        if let Some(result) = self.stack[head_index].provisional_result {
1314            Some(result)
1315        } else {
1316            Some(D::initial_provisional_result(cx, path_kind, input))
1317        }
1318    }
1319
1320    /// Whether we've reached a fixpoint when evaluating a cycle head.
1321    x;#[instrument(level = "trace", skip(self, stack_entry), ret)]
1322    fn reached_fixpoint(
1323        &mut self,
1324        stack_entry: &StackEntry<X>,
1325        usages: HeadUsages,
1326        result: X::Result,
1327    ) -> Result<Option<PathKind>, ()> {
1328        let provisional_result = stack_entry.provisional_result;
1329        if let Some(provisional_result) = provisional_result {
1330            if provisional_result == result { Ok(None) } else { Err(()) }
1331        } else if let Some(path_kind) = D::is_initial_provisional_result(result)
1332            .filter(|&path_kind| usages.is_single(path_kind))
1333        {
1334            Ok(Some(path_kind))
1335        } else {
1336            Err(())
1337        }
1338    }
1339
1340    /// When we encounter a coinductive cycle, we have to fetch the
1341    /// result of that cycle while we are still computing it. Because
1342    /// of this we continuously recompute the cycle until the result
1343    /// of the previous iteration is equal to the final result, at which
1344    /// point we are done.
1345    fn evaluate_goal_in_task(
1346        &mut self,
1347        cx: X,
1348        input: X::Input,
1349        inspect: &mut D::ProofTreeBuilder,
1350    ) -> EvaluationResult<X> {
1351        // We reset `encountered_overflow` each time we rerun this goal
1352        // but need to make sure we currently propagate it to the global
1353        // cache even if only some of the evaluations actually reach the
1354        // recursion limit.
1355        let mut encountered_overflow = false;
1356        let mut i = 0;
1357        loop {
1358            let result = D::compute_goal(self, cx, input, inspect);
1359            let stack_entry = self.stack.pop();
1360            encountered_overflow |= stack_entry.encountered_overflow;
1361            if true {
    {
        match (&stack_entry.input, &input) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(stack_entry.input, input);
1362
1363            // If the current goal is not a cycle head, we are done.
1364            //
1365            // There are no provisional cache entries which depend on this goal.
1366            let Some(usages) = stack_entry.usages else {
1367                return EvaluationResult::finalize(stack_entry, encountered_overflow, result);
1368            };
1369
1370            // If it is a cycle head, we have to keep trying to prove it until
1371            // we reach a fixpoint. We need to do so for all cycle heads,
1372            // not only for the root.
1373            //
1374            // See tests/ui/traits/next-solver/cycles/fixpoint-rerun-all-cycle-heads.rs
1375            // for an example.
1376            //
1377            // Check whether we reached a fixpoint, either because the final result
1378            // is equal to the provisional result of the previous iteration, or because
1379            // this was only the head of either coinductive or inductive cycles, and the
1380            // final result is equal to the initial response for that case.
1381            if let Ok(fixpoint) = self.reached_fixpoint(&stack_entry, usages, result) {
1382                self.rebase_provisional_cache_entries(
1383                    cx,
1384                    &stack_entry,
1385                    RebaseReason::ReachedFixpoint(fixpoint),
1386                );
1387                return EvaluationResult::finalize(stack_entry, encountered_overflow, result);
1388            } else if usages.is_empty() {
1389                self.rebase_provisional_cache_entries(
1390                    cx,
1391                    &stack_entry,
1392                    RebaseReason::NoCycleUsages,
1393                );
1394                return EvaluationResult::finalize(stack_entry, encountered_overflow, result);
1395            }
1396
1397            // If computing this goal results in ambiguity with no constraints,
1398            // we do not rerun it. It's incredibly difficult to get a different
1399            // response in the next iteration in this case. These changes would
1400            // likely either be caused by incompleteness or can change the maybe
1401            // cause from ambiguity to overflow. Returning ambiguity always
1402            // preserves soundness and completeness even if the goal is be known
1403            // to succeed or fail.
1404            //
1405            // This prevents exponential blowup affecting multiple major crates.
1406            // As we only get to this branch if we haven't yet reached a fixpoint,
1407            // we also taint all provisional cache entries which depend on the
1408            // current goal.
1409            if let Some(info) = D::is_ambiguous_result(result) {
1410                self.rebase_provisional_cache_entries(
1411                    cx,
1412                    &stack_entry,
1413                    RebaseReason::Ambiguity(info),
1414                );
1415                return EvaluationResult::finalize(stack_entry, encountered_overflow, result);
1416            };
1417
1418            // If we've reached the fixpoint step limit, we bail with overflow and taint all
1419            // provisional cache entries which depend on the current goal.
1420            i += 1;
1421            if i >= D::FIXPOINT_STEP_LIMIT {
1422                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_type_ir/src/search_graph/mod.rs:1422",
                        "rustc_type_ir::search_graph", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_type_ir/src/search_graph/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1422u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_type_ir::search_graph"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("canonical cycle overflow")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("canonical cycle overflow");
1423                let result = D::fixpoint_overflow_result(cx, input);
1424                self.rebase_provisional_cache_entries(cx, &stack_entry, RebaseReason::Overflow);
1425                return EvaluationResult::finalize(stack_entry, encountered_overflow, result);
1426            }
1427
1428            // Clear all provisional cache entries which depend on a previous provisional
1429            // result of this goal and rerun. This does not remove goals which accessed this
1430            // goal without depending on its result.
1431            self.clear_dependent_provisional_results_for_rerun();
1432
1433            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_type_ir/src/search_graph/mod.rs:1433",
                        "rustc_type_ir::search_graph", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_type_ir/src/search_graph/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1433u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_type_ir::search_graph"),
                        ::tracing_core::field::FieldSet::new(&["message", "result"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("fixpoint changed provisional results")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&result) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?result, "fixpoint changed provisional results");
1434            self.stack.push(StackEntry {
1435                input,
1436                step_kind_from_parent: stack_entry.step_kind_from_parent,
1437                available_depth: stack_entry.available_depth,
1438                provisional_result: Some(result),
1439                // We can keep these goals from previous iterations as they are only
1440                // ever read after finalizing this evaluation.
1441                min_reached_available_depth: stack_entry.min_reached_available_depth,
1442                heads: stack_entry.heads,
1443                nested_goals: stack_entry.nested_goals,
1444                // We reset these two fields when rerunning this goal. We could
1445                // keep `encountered_overflow` as it's only used as a performance
1446                // optimization. However, given that the proof tree will likely look
1447                // similar to the previous iterations when reevaluating, it's better
1448                // for caching if the reevaluation also starts out with `false`.
1449                encountered_overflow: false,
1450                // We keep provisional cache entries around if they used this goal
1451                // without depending on its result.
1452                //
1453                // We still need to drop or rebase these cache entries once we've
1454                // finished evaluating this goal.
1455                usages: Some(HeadUsages::default()),
1456                candidate_usages: None,
1457            });
1458        }
1459    }
1460
1461    /// When encountering a cycle, both inductive and coinductive, we only
1462    /// move the root into the global cache. We also store all other cycle
1463    /// participants involved.
1464    ///
1465    /// We must not use the global cache entry of a root goal if a cycle
1466    /// participant is on the stack. This is necessary to prevent unstable
1467    /// results. See the comment of `StackEntry::nested_goals` for
1468    /// more details.
1469    fn insert_global_cache(
1470        &mut self,
1471        cx: X,
1472        input: X::Input,
1473        evaluation_result: EvaluationResult<X>,
1474        dep_node: X::DepNodeIndex,
1475    ) {
1476        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_type_ir/src/search_graph/mod.rs:1476",
                        "rustc_type_ir::search_graph", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_type_ir/src/search_graph/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1476u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_type_ir::search_graph"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "evaluation_result"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("insert global cache")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&evaluation_result)
                                            as &dyn Value))])
            });
    } else { ; }
};debug!(?evaluation_result, "insert global cache");
1477        cx.with_global_cache(|cache| cache.insert(cx, input, evaluation_result, dep_node))
1478    }
1479}