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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
pub mod corelib;
pub mod prompt;

use crate::corelib::RailOp;
pub use corelib::operate;
use corelib::{new_dictionary, Dictionary};

#[derive(Clone, Debug)]
pub struct RailState {
    stack: Stack,
    dictionary: Dictionary,
    context: Context,
}

impl RailState {
    pub fn new(context: Context) -> RailState {
        let stack = Stack::new();
        let dictionary = new_dictionary();
        RailState {
            stack,
            dictionary,
            context,
        }
    }

    pub fn update_stack(self, stack: Stack) -> RailState {
        RailState {
            stack,
            dictionary: self.dictionary,
            context: self.context,
        }
    }

    pub fn deeper(self) -> RailState {
        let context = Context::Quotation {
            context: Box::new(self.context),
            parent: Box::new(self.stack),
        };
        RailState {
            stack: Stack::new(),
            dictionary: self.dictionary,
            context,
        }
    }

    pub fn higher(self) -> RailState {
        let (context, mut stack) = match self.context {
            Context::Quotation { context, parent } => (*context, *parent),
            Context::Main => panic!("Can't escape main"),
        };

        stack.push_quotation(self.stack);

        RailState {
            stack,
            dictionary: self.dictionary,
            context,
        }
    }
}

impl Default for RailState {
    fn default() -> Self {
        Self::new(Context::Main)
    }
}

#[derive(Clone, Debug)]
pub enum Context {
    Main,
    Quotation {
        context: Box<Context>,
        parent: Box<Stack>,
    },
}

#[derive(Clone, Debug)]
pub enum RailVal {
    Boolean(bool),
    // TODO: Make a "Numeric" typeclass. (And floating-point/rational numbers)
    I64(i64),
    Operator(RailOp<'static>),
    Quotation(Stack),
    String(String),
}

impl std::fmt::Display for RailVal {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        use RailVal::*;
        match self {
            Boolean(b) => write!(fmt, "{}", if *b { "true" } else { "false" }),
            I64(n) => write!(fmt, "{:?}", n),
            Operator(o) => write!(fmt, "{:?}", o),
            Quotation(q) => write!(fmt, "{:?}", q),
            String(s) => write!(fmt, "\"{}\"", s),
        }
    }
}

#[derive(Clone, Debug)]
pub struct Stack {
    terms: Vec<RailVal>,
}

impl Stack {
    fn new() -> Self {
        Stack { terms: vec![] }
    }

    fn len(&self) -> usize {
        self.terms.len()
    }

    fn is_empty(&self) -> bool {
        self.terms.is_empty()
    }

    fn push(&mut self, term: RailVal) {
        self.terms.push(term)
    }

    fn push_bool(&mut self, b: bool) {
        self.terms.push(RailVal::Boolean(b))
    }

    fn push_i64(&mut self, i: i64) {
        self.terms.push(RailVal::I64(i))
    }

    fn push_operator(&mut self, op: RailOp<'static>) {
        self.terms.push(RailVal::Operator(op))
    }

    fn push_quotation(&mut self, quot: Stack) {
        self.terms.push(RailVal::Quotation(quot))
    }

    fn push_string(&mut self, s: String) {
        self.terms.push(RailVal::String(s))
    }

    fn pop(&mut self) -> Option<RailVal> {
        self.terms.pop()
    }

    fn pop_bool(&mut self, context: &str) -> bool {
        match self.terms.pop().unwrap() {
            RailVal::Boolean(b) => b,
            rail_val => panic!("{}", type_panic_msg(context, "boolean", rail_val)),
        }
    }

    fn pop_i64(&mut self, context: &str) -> i64 {
        match self.terms.pop().unwrap() {
            RailVal::I64(n) => n,
            rail_val => panic!("{}", type_panic_msg(context, "i64", rail_val)),
        }
    }

    fn _pop_operator(&mut self, context: &str) -> RailOp<'static> {
        match self.terms.pop().unwrap() {
            RailVal::Operator(op) => op,
            rail_val => panic!("{}", type_panic_msg(context, "operator", rail_val)),
        }
    }

    fn pop_quotation(&mut self, context: &str) -> Stack {
        match self.terms.pop().unwrap() {
            RailVal::Quotation(quot) => quot,
            rail_val => panic!("{}", type_panic_msg(context, "quotation", rail_val)),
        }
    }

    fn pop_string(&mut self, context: &str) -> String {
        match self.terms.pop().unwrap() {
            RailVal::String(s) => s,
            rail_val => panic!("{}", type_panic_msg(context, "string", rail_val)),
        }
    }
}

impl std::fmt::Display for Stack {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        for term in &self.terms {
            term.fmt(f).unwrap();
            write!(f, " ").unwrap();
        }
        Ok(())
    }
}

fn type_panic_msg(context: &str, expected: &str, actual: RailVal) -> String {
    format!(
        "[Context: {}] Wanted {}, but got {:?}",
        context, expected, actual
    )
}