1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use crate::index_struct;
use crate::strand::CanonicalStrand;
use crate::tables::Tables;
use crate::{Minimums, TableIndex, TimeStamp};
use std::fmt;
use std::ops::{Index, IndexMut, Range};

use chalk_ir::interner::Interner;

/// See `Forest`.
#[derive(Debug)]
pub(crate) struct Stack<I: Interner> {
    /// Stack: as described above, stores the in-progress goals.
    stack: Vec<StackEntry<I>>,
}

impl<I: Interner> Stack<I> {
    // This isn't actually used, but it can be helpful when debugging stack issues
    #[allow(dead_code)]
    pub(crate) fn debug_with<'a>(&'a self, tables: &'a Tables<I>) -> StackDebug<'_, I> {
        StackDebug {
            stack: self,
            tables,
        }
    }
}

pub(crate) struct StackDebug<'a, I: Interner> {
    stack: &'a Stack<I>,
    tables: &'a Tables<I>,
}

impl<I: Interner> fmt::Debug for StackDebug<'_, I> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "---- Stack ----")?;
        for entry in self.stack.stack.iter() {
            writeln!(f, "  --- StackEntry ---")?;
            writeln!(
                f,
                "  Table {:?} with goal {:?}",
                entry.table, self.tables[entry.table].table_goal
            )?;
            writeln!(f, "  Active strand: {:#?}", entry.active_strand)?;
            writeln!(
                f,
                "  Additional strands: {:#?}",
                self.tables[entry.table].strands().collect::<Vec<_>>()
            )?;
        }
        write!(f, "---- End Stack ----")?;
        Ok(())
    }
}

impl<I: Interner> Default for Stack<I> {
    fn default() -> Self {
        Stack { stack: vec![] }
    }
}

index_struct! {
    /// The StackIndex identifies the position of a table's goal in the
    /// stack of goals that are actively being processed. Note that once a
    /// table is completely evaluated, it may be popped from the stack,
    /// and hence no longer have a stack index.
    pub(crate) struct StackIndex {
        value: usize,
    }
}

#[derive(Debug)]
pub(crate) struct StackEntry<I: Interner> {
    /// The goal G from the stack entry `A :- G` represented here.
    pub(super) table: TableIndex,

    /// The clock TimeStamp of this stack entry.
    pub(super) clock: TimeStamp,

    pub(super) cyclic_minimums: Minimums,

    // FIXME: should store this as an index.
    // This would mean that if we unwind,
    // we don't need to worry about losing a strand
    pub(super) active_strand: Option<CanonicalStrand<I>>,
}

impl<I: Interner> Stack<I> {
    pub(super) fn is_empty(&self) -> bool {
        self.stack.is_empty()
    }

    /// Searches the stack to see if `table` is active. If so, returns
    /// its stack index.
    pub(super) fn is_active(&self, table: TableIndex) -> Option<StackIndex> {
        self.stack
            .iter()
            .enumerate()
            .filter_map(|(index, stack_entry)| {
                if stack_entry.table == table {
                    Some(StackIndex::from(index))
                } else {
                    None
                }
            })
            .next()
    }

    pub(super) fn top_of_stack_from(&self, depth: StackIndex) -> Range<StackIndex> {
        depth..StackIndex::from(self.stack.len())
    }

    pub(super) fn push(
        &mut self,
        table: TableIndex,
        cyclic_minimums: Minimums,
        clock: TimeStamp,
    ) -> StackIndex {
        let old_len = self.stack.len();
        self.stack.push(StackEntry {
            table,
            clock,
            cyclic_minimums,
            active_strand: None,
        });
        StackIndex::from(old_len)
    }

    /// Pops the top-most entry from the stack:
    /// * If the stack is now empty, returns false.
    /// * Otherwise, returns true.
    fn pop_and_adjust_depth(&mut self) -> bool {
        self.stack.pop();
        !self.stack.is_empty()
    }

    /// Pops the top-most entry from the stack, which should have the depth `*depth`:
    /// * If the stack is now empty, returns None.
    /// * Otherwise, `take`s the active strand from the new top and returns it.
    pub(super) fn pop_and_take_caller_strand(&mut self) -> Option<CanonicalStrand<I>> {
        if self.pop_and_adjust_depth() {
            Some(self.top().active_strand.take().unwrap())
        } else {
            None
        }
    }

    /// Pops the top-most entry from the stack, which should have the depth `*depth`:
    /// * If the stack is now empty, returns None.
    /// * Otherwise, borrows the active strand (mutably) from the new top and returns it.
    pub(super) fn pop_and_borrow_caller_strand(&mut self) -> Option<&mut CanonicalStrand<I>> {
        if self.pop_and_adjust_depth() {
            Some(self.top().active_strand.as_mut().unwrap())
        } else {
            None
        }
    }

    pub(super) fn top(&mut self) -> &mut StackEntry<I> {
        self.stack.last_mut().unwrap()
    }
}

impl<I: Interner> Index<StackIndex> for Stack<I> {
    type Output = StackEntry<I>;

    fn index(&self, index: StackIndex) -> &StackEntry<I> {
        &self.stack[index.value]
    }
}

impl<I: Interner> IndexMut<StackIndex> for Stack<I> {
    fn index_mut(&mut self, index: StackIndex) -> &mut StackEntry<I> {
        &mut self.stack[index.value]
    }
}