~jojo/microcrisp

aaaa676e8069534a9674f20ad9dbbf60a5a987a9 — JoJo 8 months ago 1800016
match with string literals and str() patterns
2 files changed, 34 insertions(+), 0 deletions(-)

M src/lib.rs
M src/matching.rs
M src/lib.rs => src/lib.rs +16 -0
@@ 244,6 244,22 @@ impl PartialEq<i64> for Lisp {
        }
    }
}
impl PartialEq<Symbol> for Lisp {
    fn eq(&self, rhs: &Symbol) -> bool {
        match self {
            Lisp::Symbol(lhs) => lhs == rhs,
            _ => false,
        }
    }
}
impl PartialEq<&str> for Lisp {
    fn eq(&self, rhs: &&str) -> bool {
        match self {
            Lisp::String(lhs) => lhs == rhs,
            _ => false,
        }
    }
}

impl fmt::Display for Lisp {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {

M src/matching.rs => src/matching.rs +18 -0
@@ 30,6 30,12 @@ macro_rules! match_case {
            _ => $else
        }
    };
    ($e:expr, @go {str($lhs:pat)}, $body:expr, $else:expr) => {
        match $e {
            $crate::Lisp::String($lhs) => $body,
            _ => $else
        }
    };
    ($e:expr, @go {($($lhs:tt)*)}, $body:expr, $else:expr) => {{
        let r = match $e {
            $crate::Lisp::List(xs) => $crate::match_case!(xs, @munch {} {$($lhs)*}, Some($body), None),


@@ 135,6 141,18 @@ mod test {
        assert_eq!(try_match_expr!(parse(b"foo").unwrap(), { sy(_) => () }), Some(()));
        assert!(match_expr!(parse(b"foo-bar").unwrap(), { 'foo_bar => true, _ => false }));

        assert_eq!(
            try_match_expr!(Lisp::String("foo bar".to_owned()), { "hello world" => 123, "foo bar" => 1337 }),
            Some(1337)
        );
        assert_eq!(
            &match_expr!(parse(r#" ("labas" as "krabas") "#.as_bytes()).unwrap(), {
                (str(s1), 'as, str(s2)) => s1.clone() + s2,
                e => e.to_string()
            }),
            "labaskrabas"
        );

        assert_eq!(try_match_expr!(parse(b"(foo 123)").unwrap(), { ('foo, i(x)) => *x }), Some(123));

        #[derive(Debug, PartialEq)]