Skip to main content

continuous_blocks/
logic.rs

1//! Digital/logic signal blocks: combinational gates ([`LogicOp`]), an SR/fault latch
2//! (level-triggered, [`LatchPriority`]), and the shared edge-detection + next-state rules
3//! edge-triggered flip-flops/counters both need ([`FlipFlopKind`]). See
4//! `book/dev-guide/src/logic-signals.md` for the full design survey this module implements.
5//!
6//! Every input/output here is an ordinary `f64` `Scalar` signal, thresholded at `>= 0.5` the
7//! same way `GateBinding`/[`crate::Hysteresis`] already read a "boolean" signal — there is no
8//! dedicated boolean `SignalValue` variant anywhere in this workspace, and this module doesn't
9//! introduce one; see the design doc's own "The type" section for why.
10
11/// Reads an ordinary `f64` signal as a logic level: `true` iff `x >= 0.5`, the same threshold
12/// `GateBinding::resolve` already uses.
13pub fn as_bool(x: f64) -> bool {
14    x >= 0.5
15}
16
17/// The inverse of [`as_bool`] — the canonical `f64` encoding of a logic level.
18pub fn from_bool(b: bool) -> f64 {
19    if b {
20        1.0
21    } else {
22        0.0
23    }
24}
25
26/// A rising edge occurred between the previous and current `clk` sample: was below threshold,
27/// is now at or above it. Shared by every edge-triggered block in this module
28/// ([`FlipFlopKind`]-driven flip-flops, and `dae-runtime`'s own `Counter` block, which reuses
29/// this same function rather than duplicating the comparison).
30pub fn rising_edge(clk: f64, prev_clk: f64) -> bool {
31    as_bool(clk) && !as_bool(prev_clk)
32}
33
34/// One of the combinational logic gates — `kind=and`/`or`/`xor`/`nand`/`nor`/`xnor` (N-input,
35/// `N >= 2`) or `kind=not` (exactly 1 input). See [`LogicOp::call`] for the reduction rule.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum LogicOp {
38    And,
39    Or,
40    Xor,
41    Nand,
42    Nor,
43    Xnor,
44    Not,
45}
46
47impl LogicOp {
48    pub fn from_name(name: &str) -> Option<Self> {
49        use LogicOp::*;
50        Some(match name {
51            "and" => And,
52            "or" => Or,
53            "xor" => Xor,
54            "nand" => Nand,
55            "nor" => Nor,
56            "xnor" => Xnor,
57            "not" => Not,
58            _ => return None,
59        })
60    }
61
62    /// The exact inverse of [`Self::from_name`] — see `MathFn1::name`'s own doc comment for why
63    /// this exists (naming *this specific* op for diagnostics, not the family as a whole).
64    pub fn name(self) -> &'static str {
65        use LogicOp::*;
66        match self {
67            And => "and",
68            Or => "or",
69            Xor => "xor",
70            Nand => "nand",
71            Nor => "nor",
72            Xnor => "xnor",
73            Not => "not",
74        }
75    }
76
77    /// `true` iff this op requires exactly one input (`Not`) rather than `N >= 2`.
78    pub fn is_unary(self) -> bool {
79        matches!(self, LogicOp::Not)
80    }
81
82    /// Reduces `inputs` (already thresholded to `bool` by the caller, via [`as_bool`]) per this
83    /// op's own rule:
84    /// - `And`/`Nand`: `true` (negated for `Nand`) iff every input is `true`.
85    /// - `Or`/`Nor`: `true` (negated for `Nor`) iff at least one input is `true`.
86    /// - `Xor`/`Xnor`: `true` (negated for `Xnor`) iff an *odd* number of inputs are `true` —
87    ///   the standard N-input generalization, not "exactly one" (which doesn't generalize past
88    ///   two inputs in a way anyone actually expects).
89    /// - `Not`: `inputs` must have exactly one element; `true` iff it's `false`.
90    ///
91    /// # Panics
92    /// If `Not` is called with a slice that isn't exactly length 1, or a non-`Not` op is called
93    /// with an empty slice — both unreachable in practice, since the caller (`dae-runtime`'s own
94    /// `evaluate_blocks`) already validates arity against [`Self::is_unary`] before calling this.
95    pub fn call(self, inputs: &[bool]) -> bool {
96        use LogicOp::*;
97        match self {
98            And => inputs.iter().all(|&b| b),
99            Nand => !inputs.iter().all(|&b| b),
100            Or => inputs.iter().any(|&b| b),
101            Nor => !inputs.iter().any(|&b| b),
102            Xor => inputs.iter().filter(|&&b| b).count() % 2 == 1,
103            Xnor => inputs.iter().filter(|&&b| b).count() % 2 == 0,
104            Not => {
105                assert_eq!(inputs.len(), 1, "LogicOp::Not requires exactly one input");
106                !inputs[0]
107            }
108        }
109    }
110}
111
112/// How an [`srlatch_next`] resolves the `set && reset` (both asserted at once) case — see
113/// `logic-signals.md`'s own Category 2 for the full reasoning behind `Set` as the default.
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115pub enum LatchPriority {
116    /// `set && reset` -> latched `true`. The default: a fault-latch use case should still latch
117    /// a fault that occurs in the same step a reset is asserted, not silently clear it.
118    Set,
119    /// `set && reset` -> latched `false`. For modeling a real reset-dominant latch chip.
120    Reset,
121}
122
123impl LatchPriority {
124    pub fn from_name(name: &str) -> Option<Self> {
125        match name {
126            "set" => Some(LatchPriority::Set),
127            "reset" => Some(LatchPriority::Reset),
128            _ => None,
129        }
130    }
131}
132
133/// One step of an SR (set/reset) latch — level-triggered, no clock: `set`/`reset` act every
134/// step, immediately. `q` is the latch's own current state (before this step); returns the new
135/// state.
136///
137/// ```text
138/// set,   reset  -> q_next
139/// false, false  -> q (hold)
140/// true,  false  -> true
141/// false, true   -> false
142/// true,  true   -> per `priority`
143/// ```
144pub fn srlatch_next(q: bool, set: bool, reset: bool, priority: LatchPriority) -> bool {
145    match (set, reset) {
146        (false, false) => q,
147        (true, false) => true,
148        (false, true) => false,
149        (true, true) => matches!(priority, LatchPriority::Set),
150    }
151}
152
153/// One of the edge-triggered flip-flop next-state rules — `kind=dff`/`jkff`/`tff`. All three
154/// share one `BlockState` shape in `dae-runtime` (`{ q: bool, prev_clk: f64 }`) and are only
155/// ever evaluated (via [`Self::next_state`]) at the instant [`rising_edge`] reports `true`;
156/// `dae-runtime` holds `q` unchanged on every other step, exactly like every other zero-order-
157/// hold block already does.
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159pub enum FlipFlopKind {
160    D,
161    Jk,
162    T,
163}
164
165impl FlipFlopKind {
166    pub fn from_name(name: &str) -> Option<Self> {
167        use FlipFlopKind::*;
168        Some(match name {
169            "dff" => D,
170            "jkff" => Jk,
171            "tff" => T,
172            _ => return None,
173        })
174    }
175
176    pub fn name(self) -> &'static str {
177        use FlipFlopKind::*;
178        match self {
179            D => "dff",
180            Jk => "jkff",
181            T => "tff",
182        }
183    }
184
185    /// How many data inputs (besides `clk`) this variant needs: `D`/`T` take one (`d`/`t`); `Jk`
186    /// takes two (`j`, `k`).
187    pub fn input_count(self) -> usize {
188        match self {
189            FlipFlopKind::D | FlipFlopKind::T => 1,
190            FlipFlopKind::Jk => 2,
191        }
192    }
193
194    /// The next-state rule, evaluated only at a detected rising edge (see [`rising_edge`]).
195    /// `inputs` has exactly [`Self::input_count`] elements, already thresholded to `bool`.
196    ///
197    /// - `D`: `q_next = inputs[0]`.
198    /// - `Jk`: the classic table — `(j,k) = (false,false)` hold, `(true,false)` set,
199    ///   `(false,true)` reset, `(true,true)` toggle.
200    /// - `T`: `q_next = q XOR inputs[0]` — toggles when asserted, holds otherwise.
201    ///
202    /// # Panics
203    /// If `inputs.len() != self.input_count()` — unreachable in practice, the caller's own
204    /// responsibility to uphold (checked once, at parse time, by `general-mna`'s own netlist
205    /// field count, not re-checked here every step).
206    pub fn next_state(self, q: bool, inputs: &[bool]) -> bool {
207        match self {
208            FlipFlopKind::D => {
209                assert_eq!(inputs.len(), 1);
210                inputs[0]
211            }
212            FlipFlopKind::T => {
213                assert_eq!(inputs.len(), 1);
214                q ^ inputs[0]
215            }
216            FlipFlopKind::Jk => {
217                assert_eq!(inputs.len(), 2);
218                let (j, k) = (inputs[0], inputs[1]);
219                match (j, k) {
220                    (false, false) => q,
221                    (true, false) => true,
222                    (false, true) => false,
223                    (true, true) => !q,
224                }
225            }
226        }
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    #[test]
235    fn as_bool_and_from_bool_round_trip_at_the_gate_binding_threshold() {
236        assert!(!as_bool(0.4));
237        assert!(as_bool(0.5));
238        assert!(as_bool(0.6));
239        assert_eq!(from_bool(true), 1.0);
240        assert_eq!(from_bool(false), 0.0);
241    }
242
243    #[test]
244    fn rising_edge_fires_only_on_the_low_to_high_transition() {
245        assert!(rising_edge(1.0, 0.0)); // low -> high: the one true case
246        assert!(!rising_edge(1.0, 1.0)); // already high: not an edge
247        assert!(!rising_edge(0.0, 0.0)); // stays low
248        assert!(!rising_edge(0.0, 1.0)); // falling, not rising
249    }
250
251    #[test]
252    fn and_or_nand_nor_match_the_truth_table() {
253        assert!(LogicOp::And.call(&[true, true, true]));
254        assert!(!LogicOp::And.call(&[true, false, true]));
255        assert!(!LogicOp::Nand.call(&[true, true, true]));
256        assert!(LogicOp::Nand.call(&[true, false, true]));
257
258        assert!(!LogicOp::Or.call(&[false, false, false]));
259        assert!(LogicOp::Or.call(&[false, true, false]));
260        assert!(LogicOp::Nor.call(&[false, false, false]));
261        assert!(!LogicOp::Nor.call(&[false, true, false]));
262    }
263
264    #[test]
265    fn xor_xnor_generalize_to_odd_parity_past_two_inputs() {
266        // 2-input, the textbook case.
267        assert!(LogicOp::Xor.call(&[true, false]));
268        assert!(!LogicOp::Xor.call(&[true, true]));
269        // 3-input: two true is even parity (false), three true is odd parity (true) -- neither
270        // is "exactly one," confirming this really is odd-parity, not a naive extension.
271        assert!(!LogicOp::Xor.call(&[true, true, false]));
272        assert!(LogicOp::Xor.call(&[true, true, true]));
273        assert!(LogicOp::Xnor.call(&[true, true, false]));
274        assert!(!LogicOp::Xnor.call(&[true, true, true]));
275    }
276
277    #[test]
278    fn not_inverts_its_one_input() {
279        assert!(!LogicOp::Not.call(&[true]));
280        assert!(LogicOp::Not.call(&[false]));
281        assert!(LogicOp::Not.is_unary());
282        assert!(!LogicOp::And.is_unary());
283    }
284
285    #[test]
286    #[should_panic]
287    fn not_panics_on_the_wrong_arity() {
288        LogicOp::Not.call(&[true, false]);
289    }
290
291    #[test]
292    fn srlatch_holds_sets_resets_and_resolves_the_priority_case() {
293        assert!(!srlatch_next(false, false, false, LatchPriority::Set)); // hold false
294        assert!(srlatch_next(true, false, false, LatchPriority::Set)); // hold true
295        assert!(srlatch_next(false, true, false, LatchPriority::Set)); // set
296        assert!(!srlatch_next(true, false, true, LatchPriority::Set)); // reset
297                                                                       // both asserted: priority decides, independent of q's own prior value.
298        assert!(srlatch_next(false, true, true, LatchPriority::Set));
299        assert!(!srlatch_next(true, true, true, LatchPriority::Reset));
300    }
301
302    #[test]
303    fn dff_next_state_is_just_d() {
304        assert!(FlipFlopKind::D.next_state(false, &[true]));
305        assert!(!FlipFlopKind::D.next_state(true, &[false]));
306    }
307
308    #[test]
309    fn jkff_matches_the_classic_four_row_table() {
310        let jk = FlipFlopKind::Jk;
311        assert!(!jk.next_state(false, &[false, false])); // hold (was false)
312        assert!(jk.next_state(true, &[false, false])); // hold (was true)
313        assert!(jk.next_state(false, &[true, false])); // set
314        assert!(!jk.next_state(true, &[false, true])); // reset
315        assert!(jk.next_state(false, &[true, true])); // toggle false->true
316        assert!(!jk.next_state(true, &[true, true])); // toggle true->false
317    }
318
319    #[test]
320    fn tff_toggles_on_t_and_holds_otherwise() {
321        let t = FlipFlopKind::T;
322        assert!(!t.next_state(false, &[false])); // hold
323        assert!(t.next_state(false, &[true])); // toggle
324        assert!(!t.next_state(true, &[true])); // toggle back
325    }
326
327    #[test]
328    fn from_name_matches_conventional_names_and_rejects_unknown() {
329        assert_eq!(LogicOp::from_name("xor"), Some(LogicOp::Xor));
330        assert_eq!(LogicOp::from_name("nope"), None);
331        assert_eq!(FlipFlopKind::from_name("jkff"), Some(FlipFlopKind::Jk));
332        assert_eq!(
333            LatchPriority::from_name("reset"),
334            Some(LatchPriority::Reset)
335        );
336    }
337}