-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathminiforth.c
1809 lines (1569 loc) · 51.2 KB
/
miniforth.c
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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ===========================================================================
MF:
The virtual MinForth machine in ANSI-C, executes the image specified
in the command line.
Command line:
mf [/i imagefile] [Forth command line]
Files:
<image.i> compiled MinForth binary image file
If imagefile is not specified the default image file mf.i is used.
If you rename mf to xy the default imagefiel xy.i is used.
Copyright (C) 2003 Andreas Kochenburger ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
===========================================================================
*/
#include <stdlib.h> /* standard libraries */
#include <stdio.h>
#include "mfcomp.h" /* compiler-specific flags and libraries */
#include "mfptoken.h"
#if _OSTYPE <= 2
#include <sys\stat.h>
#include <io.h>
#include <conio.h>
#endif
#if _OSTYPE == 2
#define _CONSOLE
#include <windows.h>
#endif
#if _OSTYPE == 3
#include <sys/time.h>
#endif
#if _OSTYPE >= 3
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <termios.h>
#endif
#include <setjmp.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <math.h>
/* ---------------------------------------------------------------------------
Declarations
*/
jmp_buf fvm_buf; /* buffer to jump to FVM after exceptions */
void ExecuteToken(); /* prototypes as forward declaration */
void Throw(int i); /* declaration of exception handler */
int returncode=0; /* return value to calling OS */
FILE* imagefile; /* MinForth imagefile control block */
char fname[128]=""; /* MinForth commandline and filenames */
char imagename[32]; /* imagefile name */
#define Cell signed long /* 32 bit cell */
#define Addr unsigned long /* 32 bit address */
#define Int unsigned int /* 16 bit address or offset */
#define Char unsigned char /* 8 bit character */
#define Float double /* 64 bit float */
#if MATH_64 == 0
struct ds { Addr Lo; Addr Hi; };
typedef struct ds DAddr;
#endif
Addr W; /* MinForth Working Register */
Addr IP=0; /* MinForth Instruction Pointer */
Char Mfar* Forthspace; /* MinForth image space */
#define NAMES 16 /* Namespace address */
#define HEAP 20 /* Heapspace address */
#define LIMIT 24 /* last Forthspace adress */
#define THROW_CFA 40 /* Hilevel-Throw-CFA */
#define DEBUG_CFA 44 /* Debug-Trace-CFA */
#define HL_CLOCK 48 /* Hilevel clock for multitasking */
#define CODE_DP 52 /* Hilevel HERE */
#define NAME_DP 56 /* Hilevel HERE-N */
int debugging=0; /* flag, check debug state when on */
int tracing=0; /* flag, show tracing dialog when on */
Cell* trcrst; /* actual returnstack level to trace */
int vectnesting=0; /* used to detect cycling through vectors */
int xccode=0; /* holds exccode after exceptions */
Cell* Datastack; /* Datastack array */
Float* Floatstack; /* Floatstack array */
Cell* Returnstack; /* Returnstack array */
Char Mfar* Codespace; /* codespace start */
Char Mfar* Namespace; /* namespace start */
Char Mfar* Heapspace; /* heapspace start */
Addr codespacesize; /* codespace size in bytes */
Addr namespacesize; /* namespace size in bytes */
Addr heapspacesize; /* heapspace size in bytes */
Addr totalsize; /* total forthspace size */
Int stackcells; /* max. depth of datastack */
Cell* stk; /* currrent stackpointer */
Cell* stk_max; /* lowest datastack position */
Cell* stk_min; /* highest datastack position */
Int floatstackcells; /* max. depth of floatstack */
Float* flt; /* current floatstackpointer */
Float* flt_max; /* lowest floatstack position */
Float* flt_min; /* highest floatstack position */
Int returnstackcells; /* max. depth of returnstack */
Cell* rst; /* current returnstackpointer */
Cell* rst_max; /* lowest returnstack position */
Cell* rst_min; /* highest returnstack position */
#define MTRUE -1 /* MinForth's boolean flags */
#define MFALSE 0
int tasking=0; /* tasking flag */
Addr lastclock; /* remember latest ticker time */
Addr period; /* msecs per ticker period */
/* ---------------------------------------------------------------------------
Macros without any parameter checks
*/
#define NEXTW W+4
#define IP_NEXT IP+=4
#define SETIP(x) IP=(x)
#define PTR(x) Forthspace+(x)
#define CAT(x) *(PTR(x))
#define AT(x) *(Cell Mfar*)(PTR(x))
#define DROP stk++
#define POP() *stk++
#define PUSH(x) *--stk=(x)
#define FPOP() *flt++
#define FPUSH(x) *--flt=(x)
#define RPOP() *rst++
#define RPUSH(x) *--rst=(x)
#define TOS *stk
#define SECOND stk[1]
#define THIRD stk[2]
#define TOFS *flt
#define TORS *rst
/* ---------------------------------------------------------------------------
Some useful subroutines
*/
Addr Milliseconds()
{ return((Addr)(1000*clock()/CLOCKS_PER_SEC)); }
/* ---------------------------------------------------------------------------
Terminal raw mode setup
*/
#if _OSTYPE >= 3
struct termios newtset, oldtset; /* terminal settings */
static int pending = -1; /* holds character */
#endif
void SaveTerminal()
{
#if _OSTYPE >= 3
tcgetattr(STDIN_FILENO, &oldtset);
#endif
}
void SetTerminal()
{
#if _OSTYPE >= 3
newtset = oldtset;
newtset.c_lflag &= ~(ECHO | ICANON);
newtset.c_iflag &= ~ICRNL;
newtset.c_cc[VTIME] = 0;
newtset.c_cc[VMIN] = 0;
tcsetattr(STDIN_FILENO, TCSANOW, &newtset);
#else
setmode(STDIN_FILENO, O_BINARY);
#endif
}
void RestoreTerminal()
{
#if _OSTYPE >= 3
tcsetattr(STDIN_FILENO, TCSANOW, &oldtset);
#else
setmode(STDIN_FILENO, O_TEXT);
#endif
}
int WaitKey(void) /* return true when keyboard event is in queue */
{
#if _OSTYPE >= 3
char key;
if (pending == -1)
{ if (0 == read(STDIN_FILENO, &key, 1)) return(0);
if (key == 127) key = '\b';
pending = key; }
return(-1);
#else
return(kbhit());
#endif
}
char GetKey(void) /* get or wait for next keyboard event */
{
#if _OSTYPE >= 3
char key;
if (pending == -1)
do
usleep(50000); /* for Linux ok, but for Minix? */
while (WaitKey() == 0);
key = pending, pending = -1;
return(key);
#else
return((char)getch());
#endif
}
/* ---------------------------------------------------------------------------
Release allocated memory before leaving MinForth
*/
void FreeAllocatedMemory()
{ if (Forthspace != NULL) Mfree(Forthspace);
if (Datastack != NULL) free(Datastack);
if (Floatstack != NULL) free(Floatstack);
if (Returnstack != NULL) free(Returnstack);
}
/* ---------------------------------------------------------------------------
Immediate system stop
*/
void Terminate(char *msg)
{ fflush(stdout);
RestoreTerminal();
FreeAllocatedMemory();
fprintf(stderr,"\nMinForth terminated: %s\007",msg);
fprintf(stderr,"\n(hit return)");
getchar();
exit(-1);
}
/* ---------------------------------------------------------------------------
Read next cell from imagefile
*/
Cell ReadCell()
{ Cell value;
fread(&value,4,1,imagefile);
return(value);
}
/* ---------------------------------------------------------------------------
Read imagefile cells and set up forthspace and stacks
*/
void ReadImageFile()
{ Addr codeimagesize, nameimagesize;
codeimagesize = ReadCell();
nameimagesize = ReadCell();
fseek(imagefile,(12+16),SEEK_SET);
codespacesize = ReadCell(); /* read NAMES, HEAP, LIMIT */
namespacesize = ReadCell() - codespacesize;
heapspacesize = ReadCell() - codespacesize - namespacesize;
totalsize = codespacesize + namespacesize + heapspacesize;
stackcells = (Int)ReadCell();
floatstackcells = (Int)ReadCell();
returnstackcells = (Int)ReadCell();
Forthspace = (Char Mfar*)Mcalloc(totalsize+4,sizeof(Char));
Datastack = (Cell*)calloc(stackcells+2,sizeof(Cell));
Floatstack = (Float*)calloc(floatstackcells+2,sizeof(Float));
Returnstack = (Cell*)calloc(returnstackcells+2,sizeof(Cell));
if (Forthspace==NULL)
Terminate("Can't allocate Forthspace");
if ((Datastack==NULL)||(Floatstack==NULL)||(Returnstack==NULL))
Terminate("Can't allocate stacks");
stk_max = Datastack+1, stk_min = Datastack+stackcells;
stk = stk_min;
flt_max = Floatstack+1, flt_min = Floatstack+floatstackcells;
flt = flt_min;
rst_max = Returnstack+1, rst_min = Returnstack+returnstackcells;
rst = rst_min;
Codespace = Forthspace;
Namespace = Codespace + codespacesize;
Heapspace = Namespace + namespacesize;
fseek(imagefile,12,SEEK_SET); /* set fptr to start of codeimage */
if (codeimagesize != fread(Codespace,1,codeimagesize,imagefile))
Terminate("Can't read codeimage");
if (nameimagesize != fread(Namespace,1,nameimagesize,imagefile))
Terminate("Can't read nameimage");
}
/* ---------------------------------------------------------------------------
Open and read MinForth imagefile and commandline
NOTE: If mfi was used in an embedded (say as an extention to u-boot then
this function would be replaced with run which read from a memory device.
*/
void OpenReadImageFile(int argc, char **argv) {
int i,st; Addr adr; char *np1, *np2;
if ((argc >=3)&&(argv[1][0]=='-')&&(toupper(argv[1][1])=='I')) {
strcpy(imagename,argv[2]);
if (NULL == strchr(imagename,'.'))
strcat(imagename,".i");
st = 3;
} else {
np1 = strrchr(argv[0],'/');
if (np1 == NULL) np1 = argv[0];
np2 = strrchr(argv[0],'\\');
if (np2 == NULL)
np2 = argv[0];
if (np2 > np1)
np1 = np2;
if ((*np1 == '/')||(*np1 == '\\'))
np1++; /* fname with ext isolated */
np2 = strchr(np1,'.');
if (np2 == NULL)
np2 = argv[0]+strlen(argv[0]);
strcpy(imagename,np1);
imagename[np2-np1] = 0;
strcat(imagename,".i");
st = 1;
}
strcpy(fname,imagename);
#if _OSTYPE <= 2
imagefile = fopen(imagename,"rb");
#else
imagefile = fopen(imagename,"r");
#endif
if (imagefile == NULL)
{ strcat(fname," imagefile open failed");
Terminate(fname); }
if ((Cell)0xe8f4b4bd != ReadCell()) /* check magic number */
strcat(fname," is no MinForth imagefile"), Terminate(fname);
ReadImageFile();
fname[0]='\0';
for (i=st; i<argc; i++) {
strcat(fname,argv[i]); strcat(fname," "); }
adr = AT(CODE_DP);
CAT(adr) = (Char)strlen(fname); /* copy commandline to hilevel HERE */
strcpy((char Mfar*)PTR(adr+1),fname);
}
/* ---------------------------------------------------------------------------
Close imagefile before starting MinForth interpreter
*/
void CloseImageFile()
{ if (fclose(imagefile) == EOF)
Terminate("Can't close imagefile");
}
/* ---------------------------------------------------------------------------
Find the name belonging to a given address
*/
Addr SearchNames(Addr ca) /* find the word whose code includes address a */
{ Addr hdr, hdrmax, cfa, clen;
hdr = AT(NAMES) + 4, hdrmax = AT(NAMES) + AT(NAME_DP);
while (hdr < hdrmax)
{ cfa = (Addr)AT(hdr+4), clen = 0xffff & (AT(hdr+8));
if (((clen==0)&&(cfa==ca))||((ca>=cfa-4)&&(ca<cfa-4+clen)))
return(hdr);
hdr += ((0x1f & (CAT(hdr+12))) + 17) & -4l; }
return(0);
}
/* ---------------------------------------------------------------------------
Abort MinForth with stack dump
*/
void Abort(char *msg)
{ Int stkd, fltd, rstd, i; Addr r, hdr; Char Mfar* na;
fflush(stdout); RestoreTerminal();
fprintf(stderr,"\nMinForth VM exception %d at %lX: %s",(int)W,IP,msg);
stkd = stk_min - stk, fltd = flt_min - flt, rstd = rst_min - rst;
fprintf(stderr,"\nDatastack [%d cell(s)]",stkd);
if (stkd != 0 ) fprintf(stderr,"\n");
if (stkd > 8) { stkd = 8; fprintf(stderr,"<< "); }
while (stkd-- > 0) fprintf(stderr,"%ld ",stk[stkd]);
fprintf(stderr,"\nFloatstack [%d float(s)]",fltd);
if (fltd != 0 ) fprintf(stderr,"\n");
if (fltd > 8) { fltd = 8; fprintf(stderr,"<< "); }
while (fltd-- > 0) fprintf(stderr,"%G ",flt[fltd]);
fprintf(stderr,"\nReturnstack [%d cell(s)]",rstd);
if (rstd > 8) rstd = 8;
for (i=0; i<rstd; i++)
{ r = rst[i];
fprintf(stderr,"\n$%lX = %ld",r,(Cell)r);
hdr = SearchNames(r);
if (hdr)
{ na = PTR(hdr+13);
if (*na) fprintf(stderr," --> %s + %ld",na,r-AT(hdr+4));
else fprintf(stderr," --> XT%ld + %ld",AT(hdr+4),r-AT(hdr+4));
hdr = SearchNames(AT(r-4));
na = PTR(hdr+13);
if (*na) fprintf(stderr," --> %s",na);
else fprintf(stderr," --> XT%ld",AT(hdr+4)); } }
fprintf(stderr,"\n(press Return)");
getchar();
returncode = W; longjmp(fvm_buf,1);
}
/* ---------------------------------------------------------------------------
Signal handling / Attention: Can cause problems with Win32 and WinNT
*/
#if _OSTYPE == 2
BOOL WINAPI WinBreakHandler(DWORD type)
{ if ((CTRL_C_EVENT == type)||(CTRL_BREAK_EVENT == type))
{ xccode = -259, debugging = MTRUE;
return(TRUE); }
return(FALSE);
}
#else
void BreakSignal()
{ signal(SIGINT, BreakSignal);
xccode = -259, debugging = MTRUE;
}
#endif
void SegVSignal()
{ signal(SIGSEGV, SegVSignal);
xccode = -9, debugging = MTRUE;
}
/* ---------------------------------------------------------------------------
Throw mechanism
*/
#define THROWCODES 61
struct errasgn { int xc; char* msg; };
struct errasgn throwcode[THROWCODES] = {
/* ANS Throw code assignments */
{-3, "Stack overflow"},
{-4, "Stack underflow"},
{-5, "Return stack overflow"},
{-6, "Return stack underflow"},
{-7, "Stack overflow"},
{-8, "Dictionary overflow"},
{-9, "Invalid memory address"},
{-10, "Division by zero"},
{-11, "Result out of range"},
{-12, "Argument type mismatch"},
{-13, "Undefined word"},
{-14, "Interpreting a compile-only word"},
{-15, "Invalid FORGET"},
{-16, "Attempt to use zero-length string as a name"},
{-17, "Pictured numeric output string overflow"},
{-18, "Parsed string overflow"},
{-19, "Definition name too long"},
{-20, "Write to read-only location"},
{-21, "Unsupported operation"},
{-22, "Control structure mismatch"},
{-23, "Address alignment exception"},
{-24, "Invalid numeric argument"},
{-25, "Return stack imbalance"},
{-26, "Loop parameter unavailable"},
{-27, "Invalid recursion"},
{-28, "User interrupt"},
{-29, "Compiler nesting"},
{-30, "Obsolescent feature"},
{-31, ">BODY used on non-CREATEd definition"},
{-32, "Invalid name argument"},
{-33, "Block read exception"},
{-34, "Block write exception"},
{-35, "Invalid block number"},
{-36, "Invalid file position"},
{-37, "File I/O exception"},
{-38, "Non-existent file"},
{-39, "Unexpected end of file"},
{-40, "Invalid base for floating-point conversion"},
{-41, "Loss of precision"},
{-42, "Floating-point divide by zero"},
{-43, "Floating-point result out of range"},
{-44, "Floating-point stack overflow"},
{-45, "Floating-point stack underflow"},
{-46, "Floating-point invalid argument"},
{-47, "Compilation word list deleted"},
{-48, "Invalid POSTPONE"},
{-49, "Search-oder overflow"},
{-50, "Search-oder underflow"},
{-51, "Compilation word list changed"},
{-52, "Control-flow stack overflow"},
{-53, "Exception stack overflow"},
{-54, "Floating-point underflow"},
{-55, "Floating-point unidentified fault"},
{-57, "Exception in sending or receiving a character"},
{-58, "[IF], [ELSE] or [THEN] exception"},
/* MinForth's special error messages */
{-256, "Unsupported execution token"},
{-257, "Invalid code field address"},
{-258, "Unreferred execution vector"},
{-259, "Terminal break"},
{-260, "Memory allocation problem"},
{-261, "External reference not found"}
};
char* GetErrorMessage(int xc)
{ int i;
for (i=0; i<THROWCODES; i++)
if (xc == throwcode[i].xc) return(throwcode[i].msg);
return(NULL);
}
void Throw(int code)
{ Addr A; char* errmsg;
tracing = vectnesting = 0;
A = AT(THROW_CFA), W = code; /* store code for Abort() */
if (stk-stk_max < 4) stk = stk_max+4;
if (rst-rst_max < 4) rst = rst_max+4;
if ((A >= 256) && (A < totalsize)) {
PUSH(code), W = A;
AT(THROW_CFA)=0;
ExecuteToken();
AT(THROW_CFA)=A;
longjmp(fvm_buf,code); }
errmsg = GetErrorMessage(code);
if (errmsg != NULL) Abort(errmsg);
else Abort("THROW with unknown exception code");
}
/* ------------------------------------------------------------------------
Memory check and support functions
*/
void SetIP(Addr a)
{ if (a >= totalsize) Throw(-8);
if (a & 3) Throw(-23);
IP = a;
}
void Indepth(Int d)
{ if (stk+d > stk_min) Throw(-4);
}
void FIndepth(Int d)
{ if (flt+d > flt_min) Throw(-45);
}
void Inrange(Addr a, Int u)
{ if ((a >= totalsize)||((a+u) >= totalsize)) Throw(-9);
}
Cell At(Addr a)
{ if (a >= totalsize) Throw(-9);
return(AT(a));
}
Char ChAt(Addr a)
{ if (a >= totalsize) Throw(-9);
return(CAT(a));
}
Cell Pop()
{ if (stk >= stk_min) Throw(-4);
return(POP());
}
void Push(Cell x)
{ if (stk < stk_max) Throw(-3);
PUSH(x);
}
Cell RPop()
{ if (rst >= rst_min) Throw(-6);
return(RPOP());
}
void RPush(Cell x)
{ if (rst < rst_max) Throw(-5);
RPUSH(x);
}
void FPush(Float x)
{ if (flt < flt_max) Throw(-44);
FPUSH(x);
}
Float FPop()
{ if (flt >= flt_min) Throw(-45);
return(FPOP());
}
#if MATH_64
#define DLo(x) (Addr)(x)
#define DHi(x) (Addr)((x)>>32)
#else
#define DLo(x) (x).Lo
#define DHi(x) (x).Hi
#endif
void DStore(DAddr *dvar, Addr hi, Addr lo)
{
#if MATH_64
*dvar = ((DAddr)hi << 32) + lo;
#else
dvar->Lo = lo, dvar->Hi = hi;
#endif
}
void DNegate(DAddr* dv)
{
#if MATH_64
*dv = 0 - (*dv);
#else
dv->Lo = 0 - (dv->Lo); if (dv->Lo) dv->Hi += 1;
dv->Hi = 0 - (dv->Hi);
#endif
}
/* ------------------------------------------------------------------------
Hilevel program flow affecting functions
*/
void pPOTHOLE() /* ( -- ) abort whenever IP hits an empty cell */
{ fprintf(stderr," ? Bumped at IP=0x%lX",IP);
Throw(-1);
}
void pDOCONST() /* ( -- x ) push a constant */
{ Push(AT(NEXTW));
}
void pDOVALUE() /* ( -- x ) push a value */
{ Push(At(NEXTW));
}
void pDOVAR() /* ( -- adr ) push variable address */
{ Push(NEXTW);
}
void pDOUSER() /* ( -- adr ) push user variable address */
{ Addr A = At(NEXTW);
if ((A < 16)||(A >= 256)) Throw(-9);
Push(A);
}
/* is this ok? */
void pDOVECT() /* ( -- ) defer execution to address in body */
{ Addr A = At(NEXTW);
if ((A == 0)||(vectnesting > 10)) Throw(-258);
vectnesting++, W = A, ExecuteToken(); /* nest vector executions */
vectnesting--;
}
void pNEST() /* (R -- ip ) nest to hilevel cfa in colon definition */
{ RPush(IP);
SetIP(NEXTW);
}
/* check nesting level up down */
void pUNNEST() /* (R ip -- ) unnest back to hilevel caller */
{ if (tracing)
if (rst == trcrst) tracing = 0;
SetIP(RPop());
}
void pEXECUTE() /* ( xt -- ) execute xt on TOS */
{ Addr XT = Pop();
if (XT == (Addr)-1) longjmp(fvm_buf,1); /* ends MinForth */
if (XT >= totalsize) Throw(-256);
W = XT, ExecuteToken();
}
void pTRACE() /* ( -- ) start lolevel tracer/debugger */
{ debugging = -1;
if (AT(DEBUG_CFA) == 0l)
trcrst = rst, tracing = -1;
}
/* ------------------------------------------------------------------------
Inline literals
*/
void pLIT() /* ( -- n ) push inline value onto data stack */
{ Push(AT(IP)), IP_NEXT;
}
void pFLIT() /* ( f: -- r ) push unline float onto float stack */
{ FPush(*(Float Mfar*)(PTR(IP))), IP += 8;
}
void pSLIT() /* ( -- adr len ) push inline string address and length */
{ Char Len = CAT(IP);
Push(IP+1), Push(Len);
SETIP((IP+Len+5) & -4l);
}
void pTICK() /* ( -- xt ) push inline cfa */
{ Addr XT = AT(IP);
if (XT >= totalsize) Throw(-257);
Push(XT), IP_NEXT;
}
/* ------------------------------------------------------------------------
Branching and looping
*/
void pJMP() /* ( -- ) unconditional absolute jump */
{ SetIP(AT(IP));
}
void pJMPZ() /* ( flag -- ) jump absolute if flag is zero */
{ if (Pop()) IP_NEXT; else SetIP(AT(IP));
}
void pJMPV() /* ( incr | i lim adr) add incr to i, jump when crossing */
{ int flag; Cell Incr = Pop();
if (rst-rst_max < 3) Throw(-5);
flag = (TORS < 0), TORS += Incr;
if (flag ^ (TORS < 0)) SetIP(AT(IP)); else IP_NEXT;
}
/* ------------------------------------------------------------------------
Memory access
*/
void pAT() /* ( adr -- n ) read value n from address adr */
{ Indepth(1);
TOS = At(TOS);
}
void pSTORE() /* ( n adr -- ) store value n at address adr */
{ Addr A; Cell n;
Indepth(2); A = POP(), n = POP();
if (A >= totalsize) Throw(-9);
AT(A) = n;
}
void pCAT() /* ( adr -- c ) read char c from address adr */
{ Indepth(1);
TOS = ChAt(TOS);
}
void pCSTORE() /* ( c adr -- ) store char c at address adr */
{ Addr A; Char c;
Indepth(2); A = (Addr)POP(), c = (Char)POP();
if (A >= totalsize) Throw(-9);
CAT(A) = c;
}
void pFILL() /* ( adr u c -- ) fill u chars c beginning at adr */
{ Addr A; Int u; Char c;
Indepth(3); c = (Char)POP(), u = POP(), A = POP();
Inrange(A,u);
memset(PTR(A),c,u);
}
void pMOVE() /* ( from to u -- ) move u chars */
{ Addr From, To; Int u;
Indepth(3); u = POP(), To = POP(), From = POP();
Inrange(From,u); Inrange(To,u);
memmove(PTR(To),PTR(From),u);
}
void pFSTORE() /* ( a -- f: r -- ) store float */
{ Addr A; Float Mfar* FPtr;
A=Pop(); if (A >= totalsize) Throw(-9);
FPtr = (Float Mfar*)(PTR(A));
*FPtr = FPop();
}
void pFAT() /* ( a -- f: -- r ) read float from adr */
{ Addr A; Float Mfar* FPtr;
A = Pop(); if (A >= totalsize) Throw(-9);
FPtr = (Float Mfar*)(PTR(A));
FPush(*FPtr);
}
void pSFSTORE()
{ Addr A; float Mfar* FPtr;
A=Pop(); if (A >= totalsize) Throw(-9);
FPtr = (float Mfar*)(PTR(A));
*FPtr = (float)FPop();
}
void pSFAT()
{ Addr A; float Mfar* FPtr;
A = Pop(); if (A >= totalsize) Throw(-9);
FPtr = (float Mfar*)(PTR(A));
FPush((Float)(*FPtr));
}
/* ------------------------------------------------------------------------
Returnstack operations
*/
void pRDEPTH() /* ( -- u ) number of elements on returnstack */
{ Push(rst_min - rst);
}
void pRPSTORE() /* ( u -- ) set new returnstack depth */
{ Int u = Pop();
if (u > returnstackcells) Throw(-5);
rst = rst_min - u;
if (tracing) trcrst = rst;
}
void pTOR() /* ( x -- |R -- x ) move TOS to returnstack */
{ RPush(Pop());
if (tracing) trcrst-- ;
}
void pRFROM() /* ( -- x |R x -- ) move TORS to datastack */
{ Push(RPop());
if (tracing) trcrst++;
}
void pRPICK() /* ( i -- ri ) copy i-th element onto returnstack */
{ Int i;
Indepth(1); i = TOS;
if (rst+i >= rst_min) Throw(-6);
TOS = rst[i];
}
/* ------------------------------------------------------------------------
Datastack operations
*/
void pDEPTH() /* ( -- u ) number of elements on datastack */
{ Push(stk_min - stk);
}
void pSPSTORE() /* ( u -- ) set new datastack depth */
{ Int u = Pop();
if (u > stackcells) Throw(-3);
stk = stk_min - u;
}
void pDROP() /* ( n -- ) drop the TOS */
{ Indepth(1); DROP;
}
void pSWAP() /* ( a b -- b a ) swap the top 2 stack elements */
{ Cell X;
Indepth(2); X = TOS, TOS = SECOND, SECOND = X;
}
void pROT() /* ( a b c -- b c a ) rotate the top 3 stack elements */
{ Cell X;
Indepth(3); X = THIRD, THIRD = SECOND, SECOND = TOS, TOS = X;
}
void pROLL() /* ( ni..n0 i -- ni-1..n0 ni ) */
{ Cell ni; Int i = Pop();
Indepth(i+1); ni = stk[i];
memmove(stk+1,stk,4*i); TOS = ni;
}
void pDUP() /* ( n -- n n ) push a TOS copy */
{ Indepth(1);
Push(TOS);
}
void pOVER() /* ( a b -- a b a ) push a SECOND copy */
{ Indepth(2);
Push(SECOND);
}
void pPICK() /* ( ni..n0 i -- ni..n0 ni ) copy i-th element onto stack */
{ Int i;
Indepth(1); i = TOS; Indepth(i+2);
TOS = stk[i+1];
}
void pFDEPTH() /* ( -- d ) number of elements in floatstack */
{ Push(flt_min - flt);
}
void pFPSTORE() /* ( u -- ) set new floatstack depth */
{ int u = Pop();
if (u < 0 ) Throw(-45);
if (u > (int)floatstackcells) Throw(-44);
flt = flt_min - u;
}
void pFPICK() /* ( d: i -- f: fi..f0 -- fi..f0 fi ) pick ith float */
{ Int i;
i = Pop(); FIndepth(i+1);
FPush(flt[i]);
}
void pFROLL() /* ( d: i -- f: fi..f0 -- fi-1..f0 fi ) roll i floats */
{ Int i; Float fi;
i = Pop(); FIndepth(i+1);
fi = flt[i];
memmove(flt+1,flt,8*i); TOFS = fi;
}
/* ------------------------------------------------------------------------
Bit operations
*/
void pAND() /* ( a b -- a&b ) */
{ Cell i;
Indepth(2); i = POP();
TOS &= i;
}
void pOR() /* ( a b -- a | b ) */
{ Cell i;
Indepth(2); i = POP();
TOS |= i;
}
void pXOR() /* ( a b -- a^b ) */
{ Cell i;
Indepth(2); i = POP();
TOS ^= i;
}
void pLSHIFT() /* ( a b -- a<<b ) */
{ Int i;
Indepth(2); i = (Int)POP();
TOS <<= i;
}
void pRSHIFT() /* ( a b -- a>>b ) unsigned */
{ Int i;
Indepth(2); i = (Int)POP();
TOS = (Addr)TOS >> i;
}
/* ------------------------------------------------------------------------
Logic operations
*/
void pLESS() /* ( a b -- flag ) */
{ Cell i;
Indepth(2); i = POP();
TOS = (TOS < i ? MTRUE : MFALSE);
}
void pEQUAL() /* ( a b -- flag ) */
{ Cell i;
Indepth(2); i = POP();
TOS = (TOS == i ? MTRUE : MFALSE);
}
void pULESS() /* ( a b -- flag ) unsigned */
{ Addr i;
Indepth(2); i = (Addr)POP();
TOS = ((Addr)TOS < i ? MTRUE : MFALSE);
}
void pFZLESS() /* ( f: r -- d: -- flag ) float < zero ? */
{ Push(FPop() < 0.0 ? MTRUE : MFALSE );
}
void pFZEQUAL() /* ( f: r -- d: -- flag ) float = zero ? */
{ Push(FPop() == 0.0 ? MTRUE : MFALSE );
}
/* ------------------------------------------------------------------------
Arithmetics
*/
void pPLUS() /* ( a b -- sum ) */
{ Cell i;