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
pub trait SameType<T>: Sized {
    fn is_same_type_as(&self, _other: &T) -> bool {
        false
    }
}

impl<T, U> SameType<T> for U {
    fn is_same_type_as(&self, _other: &T) -> bool {
        true
    }
}

#[macro_export]
macro_rules! r_macro_stringify {
    // evaluate a single token directly
    {{ $expr:literal }} => {{
        {
            // test if token is a string literal and evaluate directly
            if let Some(s) = (&$expr as &dyn std::any::Any).downcast_ref::<&str>() {
                s

            // otherwise stringify token before evaluating
            } else {
                stringify!($expr)
            }
        }
    }};

    // evaluate a token stream by first stringifying. This can affect whitespace,
    // so consider using `r!{{" .. "}}` syntax when whitespace is meaningful
    { $($expr:tt)+ } => {{
        {
            stringify!($($expr)+)
        }
    }};
}

#[macro_export]
macro_rules! formals {
    ( $what:ident, $args:literal ) => {
        impl CallableFormals for $what {
            fn formals(&self) -> ExprList {
                static FORMALS: std::sync::LazyLock<ExprList> = std::sync::LazyLock::new(|| {
                    use $crate::object::{Expr, ExprList};

                    let signature = $crate::r_parse! {{ $args }};
                    let Ok($crate::object::Expr::Call(_, signature)) = signature else {
                        panic!("unexpected formal definition")
                    };

                    signature
                        .into_iter()
                        .map(|pair| match pair {
                            (None, Expr::Symbol(name)) => (Some(name), Expr::Missing),
                            pair => pair,
                        })
                        .collect::<ExprList>()
                });

                (*FORMALS).clone()
            }
        }
    };
}

#[macro_export]
macro_rules! r_parse {
    { $($expr:tt)+ } => {{
        let expr = $crate::r_macro_stringify!($($expr)+);
        $crate::lang::CallStack::default().parse(expr)
    }};
}

#[macro_export]
macro_rules! r {
    { $($expr:tt)+ } => {{
        use $crate::context::Context;
        ($crate::r_parse! { $($expr)+ })
            .and_then(|x| $crate::lang::CallStack::default().eval_and_finalize(x))

    }};
}

#[macro_export]
macro_rules! r_expect {
    { $($expr:tt)+ } => {{
        let res = $crate::r! { $($expr)+ };
        assert_eq!(res, r! { true })
    }};
}