Skip to content

Commit 1731100

Browse files
committed
Add end-to-end test for CASE/OF/ENDOF/ENDCASE defined in pure Forth
Redefines CASE/OF/ENDOF/ENDCASE using only POSTPONE and IF/ELSE/THEN, proving these words can be built from lower-level primitives. Tests basic matching, defaults, empty CASE, return values, nesting, and computed OF values.
1 parent 9b9ab5c commit 1731100

2 files changed

Lines changed: 115 additions & 0 deletions

File tree

testdata/end-to-end/case_forth.fth

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
\ Test CASE/OF/ENDOF/ENDCASE redefined in pure Forth
2+
\ This proves these words can be built on top of IF/ELSE/THEN
3+
4+
\ Redefine CASE words in pure Forth
5+
: CASE 0 ; IMMEDIATE
6+
: OF POSTPONE OVER POSTPONE = POSTPONE IF POSTPONE DROP ; IMMEDIATE
7+
: ENDOF POSTPONE ELSE ; IMMEDIATE
8+
: ENDCASE POSTPONE DROP BEGIN ?DUP WHILE POSTPONE THEN REPEAT ; IMMEDIATE
9+
10+
\ Basic CASE with multiple OFs and a default
11+
: TEST1 ( n -- )
12+
CASE
13+
1 OF ." one" ENDOF
14+
2 OF ." two" ENDOF
15+
3 OF ." three" ENDOF
16+
." other"
17+
ENDCASE
18+
;
19+
20+
\ CASE with no default (selector dropped silently)
21+
: TEST2 ( n -- )
22+
CASE
23+
1 OF ." yes" ENDOF
24+
ENDCASE
25+
;
26+
27+
\ Empty CASE (just drops the selector)
28+
: TEST3 ( n -- )
29+
CASE ENDCASE
30+
;
31+
32+
\ CASE returning values from OF branches
33+
: TEST4 ( n -- m )
34+
CASE
35+
1 OF 100 ENDOF
36+
2 OF 200 ENDOF
37+
3 OF 300 ENDOF
38+
\ default: selector still on stack, compute result and
39+
\ put it under the selector for ENDCASE to DROP
40+
DUP 1000 * SWAP
41+
ENDCASE
42+
;
43+
44+
\ Nested CASE
45+
: TEST5 ( n m -- )
46+
SWAP
47+
CASE
48+
1 OF
49+
CASE
50+
10 OF ." 1-10" ENDOF
51+
20 OF ." 1-20" ENDOF
52+
." 1-?"
53+
ENDCASE
54+
ENDOF
55+
2 OF DROP ." two" ENDOF
56+
DROP ." other"
57+
ENDCASE
58+
;
59+
60+
\ CASE with fall-through computation in OF
61+
: TEST6 ( n -- )
62+
CASE
63+
3 1+ OF ." four" ENDOF
64+
." nope"
65+
ENDCASE
66+
;
67+
68+
: MAIN
69+
\ TEST1: basic matching and default
70+
1 TEST1 CR
71+
2 TEST1 CR
72+
3 TEST1 CR
73+
4 TEST1 CR
74+
75+
\ TEST2: no default
76+
1 TEST2 CR
77+
5 TEST2 CR
78+
79+
\ TEST3: empty CASE drops selector
80+
42 TEST3
81+
82+
\ TEST4: returns values
83+
1 TEST4 . CR
84+
2 TEST4 . CR
85+
3 TEST4 . CR
86+
7 TEST4 . CR
87+
88+
\ TEST5: nested CASE
89+
1 10 TEST5 CR
90+
1 20 TEST5 CR
91+
1 99 TEST5 CR
92+
2 99 TEST5 CR
93+
3 99 TEST5 CR
94+
95+
\ TEST6: computed OF value
96+
4 TEST6 CR
97+
5 TEST6 CR
98+
;

testdata/end-to-end/case_forth.txt

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
one
2+
two
3+
three
4+
other
5+
yes
6+
7+
100
8+
200
9+
300
10+
7000
11+
1-10
12+
1-20
13+
1-?
14+
two
15+
other
16+
four
17+
nope

0 commit comments

Comments
 (0)