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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
// For now...
#![allow(clippy::missing_safety_doc)]
#![cfg_attr(not(any(test, doctest, feature = "use-std")), no_std)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

pub mod dictionary;
pub mod fastr;
pub mod input;
pub mod output;
pub mod stack;
pub(crate) mod vm;
pub mod word;

#[cfg(any(test, doctest, feature = "use-std"))]
pub mod leakbox;

#[cfg(any(test, doctest, feature = "_force_test_utils"))]
pub mod testutil;

use core::ptr::NonNull;

use dictionary::{BuiltinEntry, DictLocation, EntryHeader, EntryKind};

#[cfg(feature = "async")]
use dictionary::AsyncBuiltinEntry;

#[cfg(feature = "async")]
pub use crate::vm::AsyncForth;
pub use crate::vm::{Buffers, Forth};
use crate::{
    dictionary::{BumpError, DictionaryEntry},
    output::OutputError,
    stack::StackError,
    word::Word,
};

#[derive(Debug)]
pub enum Mode {
    Run,
    Compile,
}

#[derive(Debug, PartialEq)]
pub enum Error {
    Stack(StackError),
    Bump(BumpError),
    Output(OutputError),
    CFANotInDict(Word),
    WordNotInDict,
    ColonCompileMissingName,
    ColonCompileMissingSemicolon,
    LookupFailed,
    WordToUsizeInvalid(i32),
    UsizeToWordInvalid(usize),
    ElseBeforeIf,
    ThenBeforeIf,
    IfWithoutThen,
    DuplicateElse,
    IfElseWithoutThen,
    CallStackCorrupted,
    InterpretingCompileOnlyWord,
    BadCfaOffset,
    LoopBeforeDo,
    DoWithoutLoop,
    BadCfaLen,
    BuiltinHasNoNextValue,
    UntaggedCFAPtr,
    LoopCountIsNegative,
    LQuoteMissingRQuote,
    LiteralStringTooLong,
    NullPointerInCFA,
    BadStrLiteral(input::StrLiteralError),
    ForgetWithoutWordName,
    ForgetNotInDict,
    CantForgetBuiltins,
    InternalError,
    BadLiteral,
    BadWordOffset,
    BadArrayLength,
    DivideByZero,
    AddrOfMissingName,
    AddrOfNotAWord,

    // Not *really* an error - but signals that a function should be called
    // again. At the moment, only used for internal interpreter functions.
    PendingCallAgain,
}

impl From<StackError> for Error {
    fn from(se: StackError) -> Self {
        Error::Stack(se)
    }
}

impl From<BumpError> for Error {
    fn from(be: BumpError) -> Self {
        Error::Bump(be)
    }
}

impl From<OutputError> for Error {
    fn from(oe: OutputError) -> Self {
        Error::Output(oe)
    }
}

impl From<core::fmt::Error> for Error {
    fn from(_oe: core::fmt::Error) -> Self {
        Error::Output(OutputError::FormattingErr)
    }
}

pub struct CallContext<T: 'static> {
    eh: NonNull<EntryHeader<T>>,
    idx: u16,
    len: u16,
}

impl<T: 'static> Clone for CallContext<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: 'static> Copy for CallContext<T> {}

impl<T: 'static> CallContext<T> {
    pub(crate) fn get_next_n_words(&self, n: u16) -> Result<&[Word], Error> {
        let req_start = self.idx;
        let req_end = req_start + n;
        if req_end > self.len {
            return Err(Error::BadCfaOffset);
        }
        let eh = unsafe { self.eh.as_ref() };
        match eh.kind {
            EntryKind::StaticBuiltin => Err(Error::BuiltinHasNoNextValue),
            EntryKind::RuntimeBuiltin => Err(Error::BuiltinHasNoNextValue),
            #[cfg(feature = "async")]
            EntryKind::AsyncBuiltin => Err(Error::BuiltinHasNoNextValue),
            EntryKind::Dictionary => unsafe {
                let de = self.eh.cast::<DictionaryEntry<T>>();
                let start = DictionaryEntry::pfa(de).as_ptr().add(req_start as usize);
                Ok(core::slice::from_raw_parts(start, n as usize))
            },
        }
    }

    fn get_current_val(&self) -> Result<i32, Error> {
        let w = self.get_current_word()?;
        Ok(w.into_data())
    }

    fn get_current_word(&self) -> Result<Word, Error> {
        if self.idx >= self.len {
            return Err(Error::BadCfaOffset);
        }
        let eh = unsafe { self.eh.as_ref() };
        match eh.kind {
            EntryKind::StaticBuiltin => Err(Error::BuiltinHasNoNextValue),
            EntryKind::RuntimeBuiltin => Err(Error::BuiltinHasNoNextValue),
            #[cfg(feature = "async")]
            EntryKind::AsyncBuiltin => Err(Error::BuiltinHasNoNextValue),
            EntryKind::Dictionary => unsafe {
                let de = self.eh.cast::<DictionaryEntry<T>>();
                let val_ptr = DictionaryEntry::pfa(de).as_ptr().add(self.idx as usize);
                let val = val_ptr.read();
                Ok(val)
            },
        }
    }

    fn offset(&mut self, offset: i32) -> Result<(), Error> {
        let new_idx = i32::from(self.idx).wrapping_add(offset);
        self.idx = match u16::try_from(new_idx) {
            Ok(new) => new,
            Err(_) => return Err(Error::BadCfaOffset),
        };
        Ok(())
    }

    fn get_word_at_cur_idx(&self) -> Option<&Word> {
        if self.idx >= self.len {
            return None;
        }
        let eh = unsafe { self.eh.as_ref() };
        match eh.kind {
            EntryKind::StaticBuiltin => None,
            EntryKind::RuntimeBuiltin => None,
            #[cfg(feature = "async")]
            EntryKind::AsyncBuiltin => None,
            EntryKind::Dictionary => unsafe {
                let de = self.eh.cast::<DictionaryEntry<T>>();
                Some(&*DictionaryEntry::pfa(de).as_ptr().add(self.idx as usize))
            },
        }
    }
}

/// `WordFunc` represents a function that can be used as part of a dictionary word.
///
/// It takes the current "full context" (e.g. `Fif`), as well as the CFA pointer
/// to the dictionary entry.
type WordFunc<T> = fn(&mut Forth<T>) -> Result<(), Error>;

pub enum Lookup<T: 'static> {
    Dict(DictLocation<T>),
    Literal {
        val: i32,
    },
    #[cfg(feature = "floats")]
    LiteralF {
        val: f32,
    },
    Builtin {
        bi: NonNull<BuiltinEntry<T>>,
    },
    #[cfg(feature = "async")]
    Async {
        bi: NonNull<AsyncBuiltinEntry<T>>,
    },
    LQuote,
    LParen,
    Semicolon,
    If,
    Else,
    Then,
    Do,
    Loop,
    Constant,
    Variable,
    Array,
}

trait ReplaceErr {
    type OK;
    fn replace_err<NE>(self, t: NE) -> Result<Self::OK, NE>;
}

impl<T, OE> ReplaceErr for Result<T, OE> {
    type OK = T;
    #[inline]
    fn replace_err<NE>(self, e: NE) -> Result<Self::OK, NE> {
        match self {
            Ok(t) => Ok(t),
            Err(_e) => Err(e),
        }
    }
}

#[cfg(test)]
pub mod test {
    use core::{cmp::Ordering, future::Future, task::Poll};

    use crate::{
        dictionary::DictionaryEntry,
        leakbox::{LBForth, LBForthParams},
        testutil::{all_runtest, blocking_runtest_with},
        word::Word,
        Error, Forth,
    };

    #[derive(Default)]
    struct TestContext {
        contents: Vec<i32>,
    }

    fn assert_send<T: Send>() {}

    #[test]
    #[allow(clippy::identity_op)]
    fn sizes() {
        use core::mem::{align_of, size_of};
        assert_eq!(5 * size_of::<usize>(), size_of::<DictionaryEntry<()>>());
        assert_eq!(5 * size_of::<usize>(), size_of::<DictionaryEntry<()>>());
        assert_eq!(1 * size_of::<usize>(), align_of::<Word>());
    }

    #[test]
    fn is_send() {
        assert_send::<Forth<()>>();
    }

    #[test]
    #[cfg(feature = "async")]
    fn async_forth_is_send() {
        use crate::AsyncForth;
        assert_send::<AsyncForth<(), ()>>();
    }

    #[test]
    fn forth() {
        let mut lbforth = LBForth::from_params(
            LBForthParams::default(),
            TestContext::default(),
            Forth::<TestContext>::FULL_BUILTINS,
        );

        let forth = &mut lbforth.forth;

        assert_eq!(0, forth.dict.alloc.used());

        blocking_runtest_with(
            forth,
            r#"
            > : yay 2 3 + . ;
            > : boop yay yay ;
        "#,
        );

        blocking_runtest_with(
            forth,
            r#"
            x : derp boop yay
        "#,
        );
        assert!(forth.return_stack.is_empty());

        blocking_runtest_with(
            forth,
            r#"
            x : doot yay yaay
        "#,
        );
        assert!(forth.return_stack.is_empty());

        blocking_runtest_with(
            forth,
            r#"
            > boop yay
            < 5 5 5 ok.
        "#,
        );
        assert!(forth.data_stack.is_empty());
        assert!(forth.call_stack.is_empty());

        // Uncomment if you want to check how much of the dictionary
        // was used during a test run.
        //
        // assert_eq!(176, forth.dict_alloc.used());

        // Takes one value off the stack, and stores it in the vec
        fn squirrel(forth: &mut Forth<TestContext>) -> Result<(), crate::Error> {
            let val = forth.data_stack.try_pop()?;
            forth.host_ctxt.contents.push(val.into_data());
            Ok(())
        }
        forth.add_builtin("squirrel", squirrel).unwrap();

        blocking_runtest_with(
            forth,
            r#"
            > 5 6 squirrel squirrel
            < ok.
            > : sqloop 10 0 do i squirrel loop ;
            < ok.
            > sqloop
            < ok.
        "#,
        );

        let expected = [6, 5, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        assert_eq!(&expected, forth.host_ctxt.contents.as_slice());
    }

    // TODO: This test puns the heap-allocated cell into an array of bytes. This causes
    // miri to complain that the write is without provenance, which, fair. We might want
    // to look into some way of handling this particularly to be able to safely deal with
    // ALLOT and other alloca-style bump allocations of variable-sized data.
    #[cfg(not(miri))]
    #[test]
    fn ptr_math() {
        all_runtest(
            r#"
            ( declare a variable )
            > variable ptrword
            < ok.

            ( write an initial value `0x76543210` -> 1985229328 )
            > 1985229328 ptrword !
            < ok.

            ( Make sure it worked )
            > ptrword @ .
            < 1985229328 ok.

            ( this assumes little endian lol sorry )
            > : reader 4 0 do ptrword i + b@ . loop ;
            < ok.

            ( 0x10, 0x32, 0x54, 0x76 )
            > reader
            < 16 50 84 118 ok.

            (                 |------------|                    x = ptrword[i] )
            (                                |-|                x += i         )
            (                                    | -----------| ptrword[i] = x )
            > : writer 4 0 do i ptrword + b@ i + ptrword i + b! loop ;
            < ok.
            > writer
            < ok.
            ( 0x10, 0x33, 0x56, 0x79 )
            > reader
            < 16 51 86 121 ok.
        "#,
        );
    }

    #[test]
    fn loop_leave() {
        all_runtest(
            r#"
            > : test 10 0 do i . 43 emit i 5 = if leave then 10 0 do 42 emit i 5 = if leave then loop cr loop ;
            < ok.
            > test
            < 0 +******
            < 1 +******
            < 2 +******
            < 3 +******
            < 4 +******
            < 5 +ok.
            "#,
        )
    }

    #[test]
    fn execute() {
        all_runtest(
            r#"
            ( define two words )
            > : hello ." hello, world!" ;
            < ok.
            > : goodbye ." goodbye, world!" ;
            < ok.

            ( take their addresses )
            > ' goodbye
            < ok.
            > ' hello
            < ok.

            ( and exec them! )
            > execute
            < hello, world!ok.
            > execute
            < goodbye, world!ok.
        "#,
        );
    }

    #[test]
    fn it_still_works_when_forked() {
        let mut lbforth1 = LBForth::from_params(
            LBForthParams::default(),
            TestContext::default(),
            Forth::<TestContext>::FULL_BUILTINS,
        );

        // run all the tests on the first forth VM
        println!("\n --- testing first forth VM --- \n");
        blocking_runtest_with(
            &mut lbforth1.forth,
            r#"
            > 2 3 + .
            < 5 ok.
            > : yay 2 3 + . ;
            < ok.
            > yay yay yay
            < 5 5 5 ok.
            > : boop yay yay ;
            < ok.
            > boop
            < 5 5 ok.
            > : err if boop boop boop else yay yay then ;
            < ok.
            > : erf if boop boop boop then yay yay ;
            < ok.
            > 0 err
            < 5 5 ok.
            > 1 err
            < 5 5 5 5 5 5 ok.
            > 0 erf
            < 5 5 ok.
            > 1 erf
            < 5 5 5 5 5 5 5 5 ok.
            > : one 1 . ;
            < ok.
            > : two 2 . ;
            < ok.
            > : six 6 . ;
            < ok.
            > : nif if one if two two else six then one then ;
            < ok.
            >   0 nif
            < ok.
            > 0 1 nif
            < 1 6 1 ok.
            > 1 1 nif
            < 1 2 2 1 ok.
            > 42 emit
            < *ok.
            > : star 42 emit ;
            < ok.
            > star star star
            < ***ok.
            > : sloop one 5 0 do star star loop six ;
            < ok.
            > sloop
            < 1 **********6 ok.
            > : count 10 0 do i . loop ;
            < ok.
            > count
            < 0 1 2 3 4 5 6 7 8 9 ok.
            > : smod 10 0 do i 3 mod not if star then loop ;
            < ok.
            > smod
            < ****ok.
            > : beep ." hello, world! " ;
            < ok.
            > beep
            < hello, world! ok.
            > constant x 123
            < ok.
            > x .
            < 123 ok.
            > 4 x + .
            < 127 ok.
            > variable y
            < ok.
            > y @ .
            < 0 ok.
            > 10 y !
            < ok.
            > y @ .
            < 10 ok.
            > array z 4
            < ok.
            > z @ . z 1 w+ @ . z 2 w+ @ . z 3 w+ @ .
            < 0 0 0 0 ok.
            > 10 z ! 20 z 1 w+ ! 30 z 2 w+ ! 40 z 3 w+ !
            < ok.
            > z @ . z 1 w+ @ . z 2 w+ @ . z 3 w+ @ .
            < 10 20 30 40 ok.
            > forget z
            < ok.
            > variable a
            < ok.
            > 100 a !
            < ok.
            > array z 4
            < ok.
            > z @ . z 1 w+ @ . z 2 w+ @ . z 3 w+ @ .
            < 0 0 0 0 ok.
            "#,
        );
        print_dict("forth1", &mut lbforth1.forth);

        // create a new forth VM, and deep copy the first VM's dictionary into
        // the second.
        let mut lbforth2 =
            lbforth1.fork_with_params(LBForthParams::default(), TestContext::default());

        println!("\n --- testing second forth VM --- \n");
        blocking_runtest_with(
            &mut lbforth2.forth,
            r#"
            ( all the bindings in the old VM's dictionary should be present in the
              new VM, and, it shouldn't segfault... :D )
            > yay yay yay
            < 5 5 5 ok.
            > boop
            < 5 5 ok.
            > 0 err
            < 5 5 ok.
            > 1 err
            < 5 5 5 5 5 5 ok.
            > 0 erf
            < 5 5 ok.
            > 1 erf
            < 5 5 5 5 5 5 5 5 ok.
            >   0 nif
            < ok.
            > 0 1 nif
            < 1 6 1 ok.
            > 1 1 nif
            < 1 2 2 1 ok.
            > star star star
            < ***ok.
            > sloop
            < 1 **********6 ok.
            > count
            < 0 1 2 3 4 5 6 7 8 9 ok.
            > smod
            < ****ok.
            > beep
            < hello, world! ok.
            > x .
            < 123 ok.
            > 4 x + .
            < 127 ok.

            ( the existing `y` variable should have its second value from the
              first test. )
            > y @ .
            < 10 ok.

            ( reassigning `y` is okay )
            > 100 y !
            < ok.
            > y @ .
            < 100 ok.

            ( also reassign `a` )
            > 500 a !
            < ok.

            > z @ . z 1 w+ @ . z 2 w+ @ . z 3 w+ @ .
            < 0 0 0 0 ok.

            ( define a new word in `forth2`. )
            > : star3 star star star ;
            < ok.
            > star3
            < ***ok.

            ( define a new variable in forth2 )
            > variable foo
            < ok.
            > foo @ .
            < 0 ok.
            > 123 foo !
            < ok.
            > foo @ .
            < 123 ok.
        "#,
        );
        print_dict("forth2", &mut lbforth2.forth);

        // check that forth1's bindings aren't clobbered
        println!("\n --- retesting first VM's bindings --- \n");
        blocking_runtest_with(
            &mut lbforth1.forth,
            r#"
            ( the existing `y` variable should have its second value from the
              first test. )
            > y @ .
            < 10 ok.
            > a @ .
            < 100 ok.
        "#,
        );
        // new words defined in forth2 don't exist in forth1
        blocking_runtest_with(&mut lbforth1.forth, "x star3");
        // and neither do new variables.
        blocking_runtest_with(&mut lbforth1.forth, "x foo @ .");

        // have forth1 change some of its bindings
        blocking_runtest_with(
            &mut lbforth1.forth,
            r#"
            ( change the value of `y` )
            > 666 y !
            < ok.
            > y @ .
            < 666 ok.

            (redefine `beep` )
            > : beep ." goodbye, world! " ;
            < ok.
            > beep
            < goodbye, world! ok.

            ( define a new var )
            > variable q
            < ok.
            > q @ .
            < 0 ok.
            > 123 q !
            < ok.
            > q @ .
            < 123 ok.
        "#,
        );

        print_dict("forth1", &mut lbforth1.forth);

        // the new changes should not effect forth2
        println!("\n --- retesting second VM's bindings --- \n");
        blocking_runtest_with(
            &mut lbforth2.forth,
            r#"
            > y @ .
            < 100 ok.
            > beep
            < hello, world! ok.
        "#,
        );

        // variables defined in forth1 after forking should not be present.
        blocking_runtest_with(&mut lbforth2.forth, "x q @ .");

        print_dict("forth2", &mut lbforth2.forth);
    }

    fn print_dict(name: &str, forth: &mut Forth<TestContext>) {
        forth.input.fill("dict").unwrap();
        forth.process_line().unwrap();
        println!("{name} {}", forth.output.as_str());
        forth.output.clear();
    }

    struct CountingFut<'forth> {
        target: usize,
        ctr: usize,
        forth: &'forth mut Forth<TestContext>,
    }

    impl<'forth> Future for CountingFut<'forth> {
        type Output = Result<(), Error>;

        fn poll(
            mut self: core::pin::Pin<&mut Self>,
            cx: &mut core::task::Context<'_>,
        ) -> core::task::Poll<Self::Output> {
            match self.ctr.cmp(&self.target) {
                Ordering::Less => {
                    self.ctr += 1;
                    cx.waker().wake_by_ref();
                    Poll::Pending
                }
                Ordering::Equal => {
                    let word = Word::data(self.ctr as i32);
                    self.forth.data_stack.push(word)?;
                    self.ctr += 1;
                    Poll::Ready(Ok(()))
                }
                Ordering::Greater => Poll::Ready(Err(Error::InternalError)),
            }
        }
    }

    #[cfg(feature = "async")]
    #[test]
    fn async_forth() {
        use crate::{
            async_builtin,
            dictionary::{AsyncBuiltinEntry, AsyncBuiltins},
            fastr::FaStr,
            testutil::async_blockon_runtest_with_dispatcher,
        };

        struct TestAsyncDispatcher;
        impl<'forth> AsyncBuiltins<'forth, TestContext> for TestAsyncDispatcher {
            type Future = CountingFut<'forth>;

            const BUILTINS: &'static [AsyncBuiltinEntry<TestContext>] =
                &[async_builtin!("counter")];

            fn dispatch_async(
                &self,
                id: &FaStr,
                forth: &'forth mut Forth<TestContext>,
            ) -> Self::Future {
                match id.as_str() {
                    "counter" => {
                        // Get value from top of stack
                        let val: usize = forth.data_stack.pop().unwrap().try_into().unwrap();
                        CountingFut {
                            ctr: 0,
                            target: val,
                            forth,
                        }
                    }
                    id => panic!("Unknown async builtin {id}"),
                }
            }
        }

        async_blockon_runtest_with_dispatcher(
            TestContext::default(),
            TestAsyncDispatcher,
            r#"
                ( stack is empty... )
                x .

                ( async builtin... )
                > 5 counter
                < ok.

                ( exactly 5 placed back on the stack )
                > .
                < 5 ok.
                x .
            "#,
        );
    }

    #[test]
    fn compile() {
        all_runtest(
            r#"
            > 2 3 + .
            < 5 ok.
            > : yay 2 3 + . ;
            < ok.
            > yay yay yay
            < 5 5 5 ok.
            > : boop yay yay ;
            < ok.
            > boop
            x 5 5 ok.
            > : err if boop boop boop else yay yay then ;
            < ok.
            > : erf if boop boop boop then yay yay ;
            < ok.
            > 0 err
            < 5 5 ok.
            > 1 err
            < 5 5 5 5 5 5 ok.
            > 0 erf
            < 5 5 ok.
            > 1 erf
            < 5 5 5 5 5 5 5 5 ok.
        "#,
        );
    }

    #[test]
    fn nested_if_else() {
        all_runtest(
            r#"
            > : one 1 . ;
            < ok.
            > : two 2 . ;
            < ok.
            > : six 6 . ;
            < ok.
            > : nif if one if two two else six then one then ;
            < ok.
            >   0 nif
            < ok.
            > 0 1 nif
            < 1 6 1 ok.
            > 1 1 nif
            < 1 2 2 1 ok.
        "#,
        );
    }

    #[test]
    fn do_loop() {
        all_runtest(
            r#"
            > : one 1 . ;
            < ok.
            > : six 6 . ;
            < ok.
            > 42 emit
            < *ok.
            > : star 42 emit ;
            < ok.
            > star star star
            < ***ok.
            > : sloop one 5 0 do star star loop six ;
            < ok.
            > sloop
            < 1 **********6 ok.
            > : count 10 0 do i . loop ;
            < ok.
            > count
            < 0 1 2 3 4 5 6 7 8 9 ok.
            > : smod 10 0 do i 3 mod not if star then loop ;
            < ok.
            > smod
            < ****ok.
        "#,
        );
    }

    #[test]
    fn strings() {
        all_runtest(
            r#"
            > : beep ." hello, world!" ;
            < ok.
            > beep
            < hello, world!ok.
        "#,
        );
    }

    #[test]
    fn constants() {
        all_runtest(
            r#"
            > constant x 123
            < ok.
            > x .
            < 123 ok.
            > 4 x + .
            < 127 ok.
        "#,
        );
    }

    #[test]
    fn variables_and_arrays() {
        all_runtest(
            r#"
            > variable y
            < ok.
            > y @ .
            < 0 ok.
            > 10 y !
            < ok.
            > y @ .
            < 10 ok.
            > array z 4
            < ok.
            > z @ . z 1 w+ @ . z 2 w+ @ . z 3 w+ @ .
            < 0 0 0 0 ok.
            > 10 z ! 20 z 1 w+ ! 30 z 2 w+ ! 40 z 3 w+ !
            < ok.
            > z @ . z 1 w+ @ . z 2 w+ @ . z 3 w+ @ .
            < 10 20 30 40 ok.
            > forget z
            < ok.
            > variable a
            < ok.
            > 100 a !
            < ok.
            > array z 4
            < ok.
            > z @ . z 1 w+ @ . z 2 w+ @ . z 3 w+ @ .
            < 0 0 0 0 ok.
        "#,
        );
    }
}