Skip to main content

cbcl_core/
pattern.rs

1//! Pattern matching for message dispatch.
2//!
3//! Mirrors `PatternMatch.lean` from the Lean 4 proof library.
4
5#![forbid(unsafe_code)]
6
7use crate::msg_tag::{msg_tag, MsgTag};
8use crate::sexpr::SExpr;
9
10/// A pattern match arm: tag to match and associated handler index.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct MatchArm {
13    pub tag: MsgTag,
14    pub handler_index: usize,
15}
16
17/// Dispatch an expression to the first matching arm.
18///
19/// Returns the handler index of the first matching arm, or None.
20pub fn dispatch(expr: &SExpr, arms: &[MatchArm]) -> Option<usize> {
21    let tag = msg_tag(expr);
22    arms.iter()
23        .find(|arm| arm.tag == tag)
24        .map(|arm| arm.handler_index)
25}
26
27#[cfg(test)]
28mod tests {
29    use super::*;
30    use crate::sexpr::Atom;
31    use alloc::vec;
32
33    #[test]
34    fn dispatch_matches_head() {
35        let expr = SExpr::List(vec![
36            SExpr::Atom(Atom::Symbol("tell".into())),
37            SExpr::Atom(Atom::Str("data".into())),
38        ]);
39        let arms = vec![
40            MatchArm {
41                tag: MsgTag::Head("ask".into()),
42                handler_index: 0,
43            },
44            MatchArm {
45                tag: MsgTag::Head("tell".into()),
46                handler_index: 1,
47            },
48        ];
49        assert_eq!(dispatch(&expr, &arms), Some(1));
50    }
51
52    #[test]
53    fn dispatch_returns_none_for_no_match() {
54        let expr = SExpr::List(vec![SExpr::Atom(Atom::Symbol("bye".into()))]);
55        let arms = vec![MatchArm {
56            tag: MsgTag::Head("tell".into()),
57            handler_index: 0,
58        }];
59        assert_eq!(dispatch(&expr, &arms), None);
60    }
61}