summaryrefslogtreecommitdiffstats
path: root/src/lib.rs
blob: 4860ddc24680c62ee743e085fc069f0e996544bc (plain)
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
use log::{Level, error, info};
use wasm_bindgen::prelude::*;
use web_sys::js_sys;

pub mod forth;
pub mod robo;

enum Error {
    NoVM,
}
impl From<Error> for String {
    fn from(err: Error) -> Self {
        match err {
            Error::NoVM => "no vm".to_string().into(),
        }
    }
}

impl From<forth::vm::RuntimeError> for String {
    fn from(err: forth::vm::RuntimeError) -> Self {
        format!("runtime error: {}", err)
    }
}

fn tr_op(op: &forth::vm::OpCode) -> String {
    use forth::vm::OpCode::*;
    let s = match op {
        If(t, None) => format!("If({t}, none)"),
        If(t, Some(f)) => format!("If({t}, {f})"),
        TIf(t, None) => format!("TIf({t}, none)"),
        TIf(t, Some(f)) => format!("TIf({t}, {f})"),
        other => format!("{other:?}"),
    };
    s.to_string()
}

fn map_set<T: Into::<JsValue>>(m: &js_sys::Map, k: &str, v: T) {
    let jk: js_sys::JsString = k.to_string().into();
    let jv = v.into();
    m.set(&jk, &jv);
}

impl From<&forth::vm::InstructionPointer> for js_sys::Map {
    fn from(ip: &forth::vm::InstructionPointer) -> Self {
        let res = Self::new();

        let w: js_sys::JsString = "word".to_string().into();
        let wv = (ip.word as i32).into();
        res.set(&w, &wv);

        let o: js_sys::JsString = "offset".to_string().into();
        let ov = (ip.offset as i32).into();
        res.set(&o, &ov);

        res
    }
}

impl From<&forth::compiler::Annotation> for js_sys::Map {
    fn from(anno: &forth::compiler::Annotation) -> Self {
        let res = Self::new();

        let w: js_sys::JsString = "start".to_string().into();
        let wv = (anno.loc.0 as i32).into();
        res.set(&w, &wv);

        let o: js_sys::JsString = "end".to_string().into();
        let ov = (anno.loc.1 as i32).into();
        res.set(&o, &ov);

        res
    }
}

#[wasm_bindgen]
pub struct ExportedVM {
    vm: Option<forth::vm::VM>,
    annos: Vec<Vec<forth::compiler::Annotation>>,
}

#[wasm_bindgen]
impl ExportedVM {
    fn new() -> Self {
        Self {
            vm: None,
            annos: vec![],
        }
    }

    pub fn compile(&mut self, text: &str) -> bool {
        let mut comp = forth::compiler::Compiler::new(text);
        if let Err(e) = comp.compile() {
            error!("couldn't compile program text: {e:?}");
            return false;
        }

        let vm = forth::vm::VM::new(comp.wordlist);
        let _ = self.vm.insert(vm);
        self.annos = comp.annotations;
        true
    }

    pub fn tick(&mut self) -> Result<bool, String> {
        let vm = (&mut self.vm).as_mut().ok_or(Error::NoVM)?;
        Ok(vm.tick()?)
    }

    pub fn run(&mut self) -> Result<usize, String> {
        self.reset_ip();
        let vm = (&mut self.vm).as_mut().ok_or(Error::NoVM)?;
        Ok(vm.run()?)
    }

    pub fn reset_ip(&mut self) {
        let Some(vm) = &mut self.vm else {
            return;
        };
        vm.ip.word = 0;
        vm.ip.offset = 0;
    }

    pub fn trans(&mut self) -> Result<js_sys::Object, String> {
        let vm = (&mut self.vm).as_mut().ok_or(Error::NoVM)?;
        let res = js_sys::Map::new();

        // wordlist
        let wl = vm.wordlist.iter().map(
                |dfn| {
                    let ops =
                        dfn.iter()
                            .map(|op| {
                                Into::<js_sys::JsString>::into(tr_op(op))
                            });
                    js_sys::Array::from_iter(ops)
                }
            );
        map_set(&res, "wordlist", js_sys::Array::from_iter(wl));

        // annotations
        let annos = self.annos.iter().map(
            |dfn| {
                let ops =
                    dfn.iter()
                        .map(|anno| {
                            let a: js_sys::Map = anno.into();
                            let o: js_sys::Object = js_sys::Object::from_entries(&a).expect("can't make object from anno map");
                            o
                        });
                js_sys::Array::from_iter(ops)
            }
        );
        map_set(&res, "annos", js_sys::Array::from_iter(annos));

        // instruction pointer
        let ip: js_sys::Map = (&vm.ip).into();
        let o: js_sys::Object = js_sys::Object::from_entries(&ip).expect("can't make object from ip map");
        map_set(&res, "ip", o);

        // stack
        let s = vm.stack.0.iter().map(|v| Into::<JsValue>::into(*v as i32));
        map_set(&res, "stack", js_sys::Array::from_iter(s));

        // callstack
        let cs = vm.callstack.0.iter().map(|v| {
            let ip: js_sys::Map = v.into();
            let o: js_sys::Object = js_sys::Object::from_entries(&ip).expect("can't make object from ip map");
            o
        });
        map_set(&res, "callstack", js_sys::Array::from_iter(cs));

        let vars = js_sys::Map::new();
        let mut out = vec![];
        std::mem::swap(&mut out, &mut vm.out);
        map_set(&vars, "out", out);
        map_set::<isize>(&vars, "heading", vm.heading.into());
        map_set::<isize>(&vars, "speed", vm.speed.into());
        map_set::<isize>(&vars, "doppler", vm.doppler.into());
        map_set(&res, "vars", js_sys::Object::from_entries(&vars).expect("can't make object from vars map"));

        Ok(js_sys::Object::from_entries(&res).expect("can't make object from results map"))
    }
}

#[wasm_bindgen]
pub fn make_vm() -> ExportedVM {
    ExportedVM::new()
}

#[wasm_bindgen(start)]
pub fn init() -> Result<(), JsValue> {
    console_log::init_with_level(Level::Debug).expect("couldn't init console log");
    info!("wasm init");

    Ok(())
}