-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
429 lines (363 loc) · 12 KB
/
lib.rs
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#![cfg_attr(not(any(test, feature = "std")), no_std)]
use core::{fmt::Write, marker::PhantomData};
pub mod builtins;
#[cfg(any(test, feature = "std"))]
pub mod std_rt;
pub mod nostd_rt;
#[derive(Debug, Clone)]
pub enum Error {
/// Failed to write to the "stdout" style output
OutputFormat,
/// Failed to read from the "stdin" style input
Input,
/// Data stack underflowed
DataStackUnderflow,
/// Data stack was empty
DataStackEmpty,
/// Return stack was empty
RetStackEmpty,
/// Flow/Execution stack was empty
FlowStackEmpty,
/// Some kind of checked math failed
BadMath,
/// We found an "if" without an appropriate pair
MissingIfPair,
/// We found an "else" without an appropriate pair
MissingElsePair,
/// We found a "loop" without an appropriate pair
MissingLoopPair,
/// We found a "do" without an appropriate pair
MissingDoPair,
/// Something has gone *terribly* wrong
InternalError,
}
impl From<core::fmt::Error> for Error {
fn from(_other: core::fmt::Error) -> Self {
Self::OutputFormat
}
}
pub trait FuncSeq<T, F>
where
F: FuncSeq<T, F>,
T: Clone,
F: Clone,
{
fn get(&self, _idx: usize) -> Option<RuntimeWord<T, F>>;
}
#[derive(Debug, Clone)]
pub enum RuntimeWord<T, F>
where
F: FuncSeq<T, F> + Clone,
T: Clone,
{
LiteralVal(i32),
// TODO: Blend these somehow?
Verb(T),
VerbSeq(F),
UncondRelativeJump { offset: i32 },
CondRelativeJump { offset: i32, jump_on: bool },
}
pub struct RuntimeSeqCtx<T, F>
where
F: FuncSeq<T, F> + Clone,
T: Clone,
{
pub idx: usize,
pub word: RuntimeWord<T, F>,
}
pub struct Runtime<T, F, Sdata, Sexec, O>
where
Sdata: Stack<Item = i32>,
Sexec: ExecutionStack<T, F>,
F: FuncSeq<T, F> + Clone,
T: Clone,
O: Write,
{
pub data_stk: Sdata,
pub ret_stk: Sdata,
pub flow_stk: Sexec,
pub _pd_ty_t_f: PhantomData<(T, F)>,
cur_output: O,
}
impl<Sdata, Sexec, T, F, O> Runtime<T, F, Sdata, Sexec, O>
where
Sdata: Stack<Item = i32>,
Sexec: ExecutionStack<T, F>,
F: FuncSeq<T, F> + Clone,
T: Clone,
O: Write,
{
pub fn step(&mut self) -> Result<StepResult<T>, Error> {
match self.step_inner() {
Ok(r) => Ok(r),
Err(e) => {
while let Ok(_) = self.flow_stk.pop() {}
while let Ok(_) = self.data_stk.pop() {}
while let Ok(_) = self.ret_stk.pop() {}
Err(e)
}
}
}
fn step_inner(&mut self) -> Result<StepResult<T>, Error> {
let ret = 'oloop: loop {
// TODO: I should set a limit to the max number of loop
// iterations that are made here! Or maybe go back to
// yielding at each step
let cur = match self.flow_stk.last_mut() {
Ok(frame) => frame,
Err(_) => return Ok(StepResult::Done),
};
let mut jump = None;
enum WhichToken<T, F>
where
F: FuncSeq<T, F> + Clone,
T: Clone,
{
Single(T),
Ref(RuntimeWord<T, F>),
}
let to_push = match cur.word.clone() {
RuntimeWord::LiteralVal(lit) => {
// println!("lit");
self.data_stk.push(lit);
None
}
RuntimeWord::Verb(ft) => {
// println!("verb");
Some(WhichToken::Single(ft))
}
RuntimeWord::VerbSeq(seq) => {
// println!("verbseq->{}", cur.idx);
// TODO: I should probably check for a difference
// between exactly one over-bounds (jump to end of seq),
// and overshooting (probably an engine error)
let ret = seq.get(cur.idx).map(WhichToken::Ref);
// println!("\tgot? {}", ret.is_some());
cur.idx += 1;
ret
}
RuntimeWord::UncondRelativeJump { offset } => {
// println!("ucrj");
jump = Some(offset);
None
}
RuntimeWord::CondRelativeJump { offset, jump_on } => {
// println!("crj");
let topvar = self.data_stk.pop()?;
// Truth table:
// tv == 0 | jump_on | jump
// ========|=========|=======
// false | false | no
// true | false | yes
// false | true | yes
// true | true | no
let do_jump = (topvar == 0) ^ jump_on;
// println!("topvar: {}, jump_on: {}", topvar, jump_on);
if do_jump {
// println!("Jumping!");
jump = Some(offset);
} else {
// println!("Not Jumping!");
}
None
}
};
match to_push {
Some(WhichToken::Single(ft)) => {
// println!("BREAK");
self.flow_stk.pop()?;
break 'oloop ft;
}
Some(WhichToken::Ref(rf)) => {
// println!("FLOWPUSH");
self.flow_stk.push(RuntimeSeqCtx { idx: 0, word: rf });
}
None => {
// println!("FLOWPOP");
self.flow_stk.pop()?;
}
}
if let Some(jump) = jump {
// We just popped off the jump command, so now we are back in
// the "parent" frame.
let new_cur = self.flow_stk.last_mut()?;
if jump < 0 {
let abs = jump.abs() as usize;
assert!(abs <= new_cur.idx);
new_cur.idx -= abs;
} else {
let abs = jump as usize;
assert_ne!(abs, 0);
new_cur.idx = new_cur.idx.checked_add(abs).ok_or(Error::BadMath)?;
}
}
};
Ok(StepResult::Working(ret))
}
pub fn push_exec(&mut self, word: RuntimeWord<T, F>) {
self.flow_stk.push(RuntimeSeqCtx { idx: 0, word });
}
}
impl<Sdata, Sexec, T, F, O> Runtime<T, F, Sdata, Sexec, O>
where
Sdata: Stack<Item = i32>,
Sexec: ExecutionStack<T, F>,
F: FuncSeq<T, F> + Clone,
T: Clone,
O: Write + Default,
{
pub fn exchange_output(&mut self) -> O {
let mut new = O::default();
core::mem::swap(&mut new, &mut self.cur_output);
new
}
}
pub trait Stack {
type Item;
fn push(&mut self, data: Self::Item);
fn pop(&mut self) -> Result<Self::Item, Error>;
// Needed for builtins
fn last(&self) -> Result<&Self::Item, Error>;
}
pub trait ExecutionStack<T, F>
where
F: FuncSeq<T, F> + Clone,
T: Clone,
{
fn push(&mut self, data: RuntimeSeqCtx<T, F>);
fn pop(&mut self) -> Result<RuntimeSeqCtx<T, F>, Error>;
fn last_mut(&mut self) -> Result<&mut RuntimeSeqCtx<T, F>, Error>;
}
pub enum StepResult<T> {
Done,
Working(T),
}
#[cfg(test)]
mod std_test {
use super::*;
use crate::std_rt::*;
use std::sync::Arc;
#[test]
fn foo() {
let mut x = new_runtime();
// Manually craft a word, roughly:
// : star 42 emit ;
let pre_seq = StdFuncSeq {
inner: Arc::new(vec![
NamedStdRuntimeWord {
word: RuntimeWord::LiteralVal(42),
name: "42".into(),
},
NamedStdRuntimeWord {
word: RuntimeWord::Verb(BuiltinToken::new(builtins::bi_emit)),
name: "emit".into(),
},
]),
};
// Manually craft another word, roughly:
// : mstar star -1 if star star then ;
let seq = StdFuncSeq {
inner: Arc::new(vec![
NamedStdRuntimeWord {
word: RuntimeWord::VerbSeq(pre_seq.clone()),
name: "star".into(),
},
NamedStdRuntimeWord {
word: RuntimeWord::LiteralVal(-1),
name: "-1".into(),
},
NamedStdRuntimeWord {
word: RuntimeWord::CondRelativeJump {
offset: 2,
jump_on: false,
},
name: "UCRJ".into(),
},
NamedStdRuntimeWord {
word: RuntimeWord::VerbSeq(pre_seq.clone()),
name: "star".into(),
},
NamedStdRuntimeWord {
word: RuntimeWord::VerbSeq(pre_seq.clone()),
name: "star".into(),
},
]),
};
// In the future, these words will be obtained from deserialized output,
// rather than being crafted manually. I'll probably need GhostCell for
// the self-referential parts
// Push `mstar` into the execution context, basically
// treating it as an "entry point"
x.push_exec(RuntimeWord::VerbSeq(seq));
loop {
match x.step() {
Ok(StepResult::Done) => break,
Ok(StepResult::Working(ft)) => {
// The runtime yields back at every call to a "builtin". Here, I
// call the builtin immediately, but I could also yield further up,
// to be resumed at a later time
ft.exec(&mut x).unwrap();
}
Err(_e) => todo!(),
}
}
let output = x.exchange_output();
assert_eq!("***", &output);
}
}
#[cfg(test)]
mod nostd_test {
use super::*;
use crate::nostd_rt::*;
#[test]
fn foo() {
// Manually craft a word, roughly:
// : star 42 emit ;
let pre_seq = NoStdFuncSeq {
inner: &[
RuntimeWord::LiteralVal(42),
RuntimeWord::Verb(BuiltinToken::new(builtins::bi_emit)),
],
};
// Manually craft another word, roughly:
// : mstar star -1 if star star then ;
let seq = NoStdFuncSeq {
inner: &[
RuntimeWord::VerbSeq(pre_seq.clone()),
RuntimeWord::LiteralVal(-1),
RuntimeWord::CondRelativeJump {
offset: 2,
jump_on: false,
},
RuntimeWord::VerbSeq(pre_seq.clone()),
RuntimeWord::VerbSeq(pre_seq.clone()),
],
};
let mut x = new_runtime::<32, 16, 256>();
// let sz = core::mem::size_of::<RuntimeWord<BuiltinToken<1, 1, 1>, NoStdFuncSeq<1, 1, 1>>>();
// // <1, 1, 1> -> 112
// // <16, 1, 1> -> 224
// // <1, 32, 1> -> 1104
// assert_eq!(856, sz);
// In the future, these words will be obtained from deserialized output,
// rather than being crafted manually. I'll probably need GhostCell for
// the self-referential parts
// Push `mstar` into the execution context, basically
// treating it as an "entry point"
x.push_exec(RuntimeWord::VerbSeq(seq));
loop {
match x.step() {
Ok(StepResult::Done) => break,
Ok(StepResult::Working(ft)) => {
// The runtime yields back at every call to a "builtin". Here, I
// call the builtin immediately, but I could also yield further up,
// to be resumed at a later time
ft.exec(&mut x).unwrap();
}
Err(_e) => todo!(),
}
}
let output = x.exchange_output();
assert_eq!("***", &output);
}
}