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
use crate::Nothing;

use super::guard::{Guard, PortComp};
use super::{Port, RRC};

#[derive(Debug, Copy, Clone)]
pub struct GuardRef(u32);

impl GuardRef {
    /// Check whether this refers to a `FlatGuard::True`. (We can do this because the first guard
    /// in the pool is always `True`.)
    pub fn is_true(&self) -> bool {
        self.0 == 0
    }

    /// Get the underlying number for this reference. Clients should only rely on this being unique
    /// for non-equal guards in a single pool; no other aspects of the number are relevant.
    pub fn index(&self) -> u32 {
        self.0
    }
}

#[derive(Debug, Clone)]
pub enum FlatGuard {
    Or(GuardRef, GuardRef),
    And(GuardRef, GuardRef),
    Not(GuardRef),
    True,
    CompOp(PortComp, RRC<Port>, RRC<Port>),
    Port(RRC<Port>),
}

impl FlatGuard {
    pub fn is_true(&self) -> bool {
        match self {
            FlatGuard::True => true,
            FlatGuard::Port(p) => p.borrow().is_constant(1, 1),
            _ => false,
        }
    }
}

/// A `GuardPool` is an "arena"-style storage area for `FlatGuard`s.
///
/// Some invariants for the underlying vector:
/// * `GuardRefs` are always within the same pool (obviously).
/// * The underlyings numbers in `GuardRef`s can only go "backward," in the sense that
///   they refer to smaller indices than the current `FlatGuard`.
/// * The first `FlatGuard` is always `FlatGuard::True`.
///
/// This could be used to do some interesting hash-consing/deduplication; it currently does the
/// weakest possible form of that: deduplicating `True` guards only.
pub struct GuardPool(Vec<FlatGuard>);

impl GuardPool {
    pub fn new() -> Self {
        let mut vec = Vec::<FlatGuard>::with_capacity(1024);
        vec.push(FlatGuard::True);
        Self(vec)
    }

    fn add(&mut self, guard: FlatGuard) -> GuardRef {
        // `True` is always the first guard.
        if guard.is_true() {
            return GuardRef(0);
        }

        self.0.push(guard);
        GuardRef(
            (self.0.len() - 1)
                .try_into()
                .expect("too many guards in the pool"),
        )
    }

    pub fn flatten(&mut self, old: &Guard<Nothing>) -> GuardRef {
        match old {
            Guard::Or(l, r) => {
                let flat_l = self.flatten(l);
                let flat_r = self.flatten(r);
                self.add(FlatGuard::Or(flat_l, flat_r))
            }
            Guard::And(l, r) => {
                let flat_l = self.flatten(l);
                let flat_r = self.flatten(r);
                self.add(FlatGuard::And(flat_l, flat_r))
            }
            Guard::Not(g) => {
                let flat_g = self.flatten(g);
                self.add(FlatGuard::Not(flat_g))
            }
            Guard::True => self.add(FlatGuard::True),
            Guard::CompOp(op, l, r) => {
                self.add(FlatGuard::CompOp(op.clone(), l.clone(), r.clone()))
            }
            Guard::Port(p) => self.add(FlatGuard::Port(p.clone())),
            Guard::Info(_) => {
                panic!("flat guard sees info, think about this more")
            }
        }
    }

    pub fn get(&self, guard: GuardRef) -> &FlatGuard {
        &self.0[guard.0 as usize]
    }

    #[cfg(debug_assertions)]
    pub fn display(&self, guard: &FlatGuard) -> String {
        match guard {
            FlatGuard::Or(l, r) => format!(
                "({} | {})",
                self.display(self.get(*l)),
                self.display(self.get(*r))
            ),
            FlatGuard::And(l, r) => format!(
                "({} & {})",
                self.display(self.get(*l)),
                self.display(self.get(*r))
            ),
            FlatGuard::Not(g) => format!("!{}", self.display(self.get(*g))),
            FlatGuard::True => "true".to_string(),
            FlatGuard::CompOp(op, l, r) => {
                let op_str = match op {
                    PortComp::Eq => "==",
                    PortComp::Neq => "!=",
                    PortComp::Lt => "<",
                    PortComp::Leq => "<=",
                    PortComp::Gt => ">",
                    PortComp::Geq => ">=",
                };
                format!(
                    "({} {} {})",
                    l.borrow().canonical(),
                    op_str,
                    r.borrow().canonical()
                )
            }
            FlatGuard::Port(p) => format!("{}", p.borrow().canonical()),
        }
    }

    /// Iterate over *all* the guards in the pool.
    pub fn iter(&self) -> impl Iterator<Item = (GuardRef, &FlatGuard)> {
        self.0
            .iter()
            .enumerate()
            .map(|(i, g)| (GuardRef(i.try_into().unwrap()), g))
    }
}

impl Default for GuardPool {
    fn default() -> Self {
        Self::new()
    }
}