-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathba.cxx
13052 lines (11532 loc) · 599 KB
/
ba.cxx
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
// A very basic BASIC interpreter.
// Also, compilers for x64 on Windows, arm64 on Apple Silicon and Windows, 8080 on cp/m 2.2,
// Arm32 for Linux (tested on Raspberry PI 3B and 4), 6502 for the Apple 1, 8086 for DOS,
// 32-bit x86 for Windows, and 64-bit RISC-V for the Maixduino SiPeed Kendryte K210.
// implements a small subset of gw-basic; just enough to run a tic-tac-toe proof of failure app.
// a few of the many limitations:
// -- based on TRS-80 Model 100 gw-basic. Equivalent to MBasic on CP/M.
// -- only integer variables (4 byte) (2 bytes for 8080 and 6502 compilers) are supported
// -- for loop start and end values must be constants
// -- variables can only be two characters long plus a mandatory %
// -- string values work in PRINT statements and nowhere else
// -- a new token ELAP$ for PRINT that shows elapsed time milliseconds or microseconds
// -- keywords supported: (see "Operators" below).
// -- Not supported: DEF, PLAY, OPEN, INKEY$, DATA, READ, and a very long list of others.
// -- only arrays of 1 or 2 dimensions are supported
// Notes about 8086/DOS WATCOM builds
// -- The watcom compiler generates code when it sees "if (false) something;". A bunch of
// the tracing and range checking code assumes this is optimized away like other compilers do.
// -- No codegen on DOS because the binary gets too big.
// -- no execution time tracking on DOS
//
// The expression grammar for assigment and IF statements: (parens are literal and square brackets are to show options)
//
// expression = term [additive]*
// additive = [ + | - ] term
// factor = ( expression ) | variable | constant
// constant = (0-9)+
// variable = varname | varname( expression )
// varname = (a-z)+%
// term = factor [multiplicative]*
// multiplicative = [ * | / ] factor
// relationalexpression = expression [relational]*
// relational = [ < | > | <= | >= | = ] expression
// logicalexpression = relationalexpression [logical]*
// logical = [ AND | OR | XOR ] relationalexpression
#include <stdio.h>
#include <assert.h>
#include <algorithm>
#include <string>
#include <cstring>
#include <sstream>
#include <cctype>
#include <map>
#include <cstdint>
#include <vector>
#include <chrono>
using namespace std;
#ifndef WATCOM
#define BA_ENABLE_COMPILER // this makes the app too big for WATCOM
using namespace std::chrono;
#endif
bool g_Tracing = false;
bool g_ExpressionOptimization = true;
bool g_Quiet = false;
bool g_GenerateAppleDollar = false;
int g_pc = 0;
// this does not work with WATCOM / 8086 builds
//#define BA_ENABLE_INTERPRETER_EXECUTION_TIME
#ifdef DEBUG
const bool RangeCheckArrays = true;
const bool EnableTracing = true;
#define __makeinline __declspec(noinline)
//#define __makeinline
#else
const bool RangeCheckArrays = false; // oh how I wish C# supported turning off bounds checking
const bool EnableTracing = false; // makes eveything 10% slower
#define __makeinline __forceinline
//#define __makeinline
#endif
#ifdef __APPLE__
// On an M1 Mac, this yields much faster/better results than on Windows and Linux x64 machines.
uint64_t __rdtsc( void )
{
uint64_t val;
asm volatile("mrs %0, cntvct_el0" : "=r" (val ));
return val;
}
#endif
#ifdef _MSC_VER
#include <intrin.h>
#ifdef __GNUC__
#define __assume( x )
#endif
#else // g++, clang++
#define __assume( x )
#undef __makeinline
#define __makeinline inline
#ifdef WATCOM
#include <dos.h>
uint32_t DosTimeInMS()
{
struct dostime_t tNow;
_dos_gettime( &tNow );
uint32_t t = (uint32_t) tNow.hour * 60 * 60 * 100;
t += (uint32_t) tNow.minute * 60 * 100;
t += (uint32_t) tNow.second * 100;
t += (uint32_t) tNow.hsecond;
return t * 10;
} //DosTimeInMS
int _strnicmp( const char * a, const char * b, int len )
{
for ( int i = 0; i < len; i++ )
{
char la = tolower( a[i] );
char lb = tolower( b[i] );
if ( !la && !lb )
return 0;
if ( !la )
return -1;
if ( !lb )
return 1;
if ( la != lb )
return la - lb;
}
return 0;
}
#else
#define _strnicmp strncasecmp
#define _stricmp strcasecmp
#endif
#ifndef _countof
#ifdef WATCOM
#define _countof( x ) ( sizeof( x ) / sizeof( x[0] ) )
#else
template < typename T, size_t N > size_t _countof( T ( & arr )[ N ] ) { return std::extent< T[ N ] >::value; }
#endif
#endif
void strcpy_s( char * pto, size_t size, const char * pfrom )
{
strcpy( pto, pfrom );
}
#endif
int stcmp( const string & a, const string & b )
{
return strcmp( a.c_str(), b.c_str() );
} //stcmp
enum AssemblyTarget { x86Win, x64Win, arm64Mac, arm64Win, i8080CPM, arm32Linux, mos6502Apple1, i8086DOS, riscv64, oiOS };
AssemblyTarget g_AssemblyTarget = x64Win;
bool g_i386Target686 = true; // true for Pentium 686 cmovX instructions, false for generic 386
enum Token_Enum {
Token_VARIABLE, Token_GOSUB, Token_GOTO, Token_PRINT, Token_RETURN, Token_END, // statements
Token_REM, Token_DIM, Token_CONSTANT, Token_OPENPAREN, Token_CLOSEPAREN,
Token_MULT, Token_DIV, Token_PLUS, Token_MINUS, Token_EQ, Token_NE, Token_LE, Token_GE, Token_LT, Token_GT, Token_AND, Token_OR, Token_XOR, // operators in order of precedence
Token_FOR, Token_NEXT, Token_IF, Token_THEN, Token_ELSE, Token_LINENUM, Token_STRING, Token_TO, Token_COMMA,
Token_COLON, Token_SEMICOLON, Token_EXPRESSION, Token_TIME, Token_ELAP, Token_TRON, Token_TROFF,
Token_ATOMIC, Token_INC, Token_DEC, Token_NOT, Token_INVALID };
#define Token int
const char * Tokens[] = {
"VARIABLE", "GOSUB", "GOTO", "PRINT", "RETURN", "END",
"REM", "DIM", "CONSTANT", "OPENPAREN", "CLOSEPAREN",
"MULT", "DIV", "PLUS", "MINUS", "EQ", "NE", "LE", "GE", "LT", "GT", "AND", "OR", "XOR",
"FOR", "NEXT", "IF", "THEN", "ELSE", "LINENUM", "STRING", "TO", "COMMA",
"COLON", "SEMICOLON", "EXPRESSION", "TIME$", "ELAP$", "TRON", "TROFF",
"ATOMIC", "INC", "DEC", "NOT", "INVALID" };
const char * Operators[] = {
"VARIABLE", "GOSUB", "GOTO", "PRINT", "RETURN", "END",
"REM", "DIM", "CONSTANT", "(", ")",
"*", "/", "+", "-", "=", "<>", "<=", ">=", "<", ">", "&", "|", "^",
"FOR", "NEXT", "IF", "THEN", "ELSE", "LINENUM", "STRING", "TO", "COMMA",
"COLON", "SEMICOLON", "EXPRESSION", "TIME$", "ELAP$", "TRON", "TROFF",
"ATOMIC", "INC", "DEC", "NOT", "INVALID" };
#ifdef BA_ENABLE_COMPILER
const char * OperatorInstructionX64[] = {
0, 0, 0, 0, 0, 0, // filler
0, 0, 0, 0, 0, // filler
"imul", "idiv", "add", "sub", "sete", "setne", "setle", "setge", "setl", "setg", "and", "or", "xor", };
// most only used and work on Arm64
const char * OperatorInstructionArm[] = {
0, 0, 0, 0, 0, 0, // filler
0, 0, 0, 0, 0, // filler
"mul", "sdiv", "add", "sub", "sete", "setne", "setle", "setge", "setl", "setg", "and", "orr", "eor", };
// only the last 3 are used
const char * OperatorInstructioni8080[] = {
0, 0, 0, 0, 0, 0, // filler
0, 0, 0, 0, 0, // filler
"mul", "sdiv", "add", "sub", "sete", "setne", "setle", "setge", "setl", "setg", "ana", "ora", "xra", };
// only the last 3 are used
const char * OperatorInstruction6502[] = {
0, 0, 0, 0, 0, 0, // filler
0, 0, 0, 0, 0, // filler
"mul", "sdiv", "add", "sub", "sete", "setne", "setle", "setge", "setl", "setg", "and", "ora", "eor", };
// only the last 3 are used
const char * OperatorInstructionRiscV64[] = {
0, 0, 0, 0, 0, 0, // filler
0, 0, 0, 0, 0, // filler
"mul", "sdiv", "add", "sub", "sete", "setne", "setle", "setge", "setl", "setg", "and", "or", "xor", };
const char * ConditionsArm[] = {
0, 0, 0, 0, 0, 0, // filler
0, 0, 0, 0, 0, // filler
0, 0, 0, 0, "eq", "ne", "le", "ge", "lt", "gt", 0, 0, 0 };
const char * ConditionsNotArm[] = {
0, 0, 0, 0, 0, 0, // filler
0, 0, 0, 0, 0, // filler
0, 0, 0, 0, "ne", "eq", "gt", "lt", "ge", "le", 0, 0, 0 };
const char * ConditionsRiscV[] = {
0, 0, 0, 0, 0, 0, // filler
0, 0, 0, 0, 0, // filler
0, 0, 0, 0, "eq", "ne", "le", "ge", "lt", "gt", 0, 0, 0 };
// jump instruction if the condition is true
const char * RelationalInstructionX64[] = {
0, 0, 0, 0, 0, 0, // filler
0, 0, 0, 0, 0, // filler
0, 0, 0, 0, "je", "jne", "jle", "jge", "jl", "jg", 0, 0, 0, };
// jump instruction if the condition is false
const char * RelationalNotInstructionX64[] = {
0, 0, 0, 0, 0, 0, // filler
0, 0, 0, 0, 0, // filler
0, 0, 0, 0, "jne", "je", "jg", "jl", "jge", "jle", 0, 0, 0, };
const char * CMovInstructionX64[] = {
0, 0, 0, 0, 0, 0, // filler
0, 0, 0, 0, 0, // filler
0, 0, 0, 0, "cmove", "cmovne", "cmovle", "cmovge", "cmovl", "cmovg", 0, 0, 0, };
// the most frequently used variables are mapped to these registers
const char * MappedRegistersX64[] = { "esi", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d" };
const char * MappedRegistersX64_64[] = { "rsi", "r9", "r10", "r11", "r12", "r13", "r14", "r15" };
// Use of x10-x15 is dangerous since these aren't preserved during function calls.
// Whenever a call happens (to printf, time, etc.) use the macros save_volatile_registers and restore_volatile_registers.
// The macros are slow, but calling out is very uncommon and it's generally to slow functions.
// Use of the extra registers results in about a 3% overall benefit for tp.bas.
// Note that x16, x17, x18, x29, and x30 are reserved.
const char * MappedRegistersArm64[] = { "w10", "w11", "w12", "w13", "w14", "w15", "w19", "w20", "w21", "w22", "w23", "w24", "w25", "w26", "w27", "w28" };
const char * MappedRegistersArm64_64[] = { "x10", "x11", "x12", "x13", "x14", "x15", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28" };
// r9 may or not be volatile depending on the Linux ABI
// r3 is volatile; use save_volatile_registers on external calls. To reduce the probability of bugs, I'm leaving r3 out.
const char * MappedRegistersArm32[] = { /*"r3",*/ "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11" };
// x86 registers are a sparse commodity. Make sure no generated code uses these aside from variables.
const char * MappedRegistersX86[] = { "ecx", "esi", "edi" };
const char * MappedRegistersOIOS[] = { "rframe", "rarg1", "rarg2" };
const char * MappedRegistersRiscV64[] = { "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11" };
void RiscVPush( FILE * fp, char const * pcreg )
{
// stacks must be 16-byte aligned
fprintf( fp, " addi sp, sp, -16\n" );
fprintf( fp, " sd %s, 0(sp)\n", pcreg );
} //RiscVPush
void RiscVPop( FILE * fp, char const * pcreg )
{
// stacks must be 16-byte aligned
fprintf( fp, " ld %s, 0(sp)\n", pcreg );
fprintf( fp, " addi sp, sp, 16\n" );
} //RiscVPop
// For 6502 there are no mapped registers, but there are variables allocated on the Zero Page. Each of these consumes 2 bytes.
const int Max6502ZeroPageVariables = 16;
#endif //BA_ENABLE_COMPILER
__makeinline const char * TokenStr( Token i )
{
if ( i < 0 || i > Token_INVALID )
{
printf( "token %d is malformed\n", i );
return Tokens[ _countof( Tokens ) - 1 ];
}
return Tokens[ i ];
} //TokenStr
__makeinline bool isTokenOperator( Token t )
{
return ( t >= Token_MULT && t <= Token_XOR );
} //isTokenOperator
__makeinline bool isTokenSimpleValue( Token t )
{
return ( Token_CONSTANT == t || Token_VARIABLE == t );
} //isTokenSimpleValue
__makeinline bool isTokenStatement( Token t )
{
return ( t >= Token_VARIABLE && t <= Token_END );
} //isTokenStatement
__makeinline bool isOperatorRelational( Token t )
{
return ( t >= Token_EQ && t <= Token_GT );
} //isOperatorRelational
__makeinline bool isOperatorLogical( Token t )
{
return ( t >= Token_AND && t <= Token_XOR );
} //isOperatorLogical
__makeinline bool isOperatorAdditive( Token t )
{
return ( Token_PLUS == t || Token_MINUS == t );
} //isOperatorAdditive
__makeinline bool isOperatorMultiplicative( Token t )
{
return ( Token_MULT == t || Token_DIV == t );
} //isOperatorMultiplicative
__makeinline bool FailsRangeCheck( int offset, size_t high )
{
// check if an array access is outside the array. BASIC arrays are 0-based.
return ( ( offset < 0 ) || ( offset >= high ) );
} //FailsRangeCheck
char * my_strlwr( char * str )
{
unsigned char *p = (unsigned char *) str;
while ( *p )
{
*p = (unsigned char) tolower( *p );
p++;
}
return str;
}//my_strlwr
string UnescapeBASICString( string & str )
{
// change two consecutive quotes to one
string result;
for ( const char * p = str.c_str(); *p; p++ )
{
result += *p;
if ( '"' == *p && '"' == * (p + 1) )
p++;
}
return result;
} //UnescapeBASICString
struct Variable
{
Variable( const char * v )
{
memset( this, 0, sizeof *this );
assert( strlen( v ) <= 3 );
strcpy_s( name, _countof( name ), v );
my_strlwr( name );
}
int value; // when a scalar
char name[4]; // variables can only be 2 chars + type (%) + null
int dimensions; // 0 for scalar. 1 or 2 for arrays.
int dims[ 2 ]; // only support up to 2 dimensional arrays.
vector<int> array; // actual array values
int references; // when generating assembler: how many references in the basic app?
string reg; // when generating assembler: register mapped to this variable, if any
bool mos6502ZeroPage; // true if allocated in the zero page for 6502
};
struct TokenValue
{
void Clear()
{
token = Token_INVALID;
pVariable = 0;
value = 0;
strValue = "";
dimensions = 0;
dims[ 0 ] = 0;
dims[ 1 ] = 0;
extra = 0;
}
TokenValue( Token t )
{
Clear();
token = t;
} //TokenValue
#ifdef WATCOM
TokenValue()
{
Clear();
} //TokenValue
#endif
// note: 64 bytes in size, which is good because the compiler can use shl 6 for array lookups
Token token;
int value; // value's definition varies depending on the token.
int dimensions; // 0 for scalar or 1-2 if an array. Only non-0 for DIM statements
int dims[ 2 ]; // only support up to 2 dimensional arrays. Only used for DIM statements
int extra; // filler for now. unused.
Variable * pVariable; // pointer to the actual variable where the value is stored
string strValue; // strValue's definition varies depending on the token.
#ifdef __APPLE__ // make structure size 64 bytes on mac/clang. Not needed for linux or Windows
size_t extra2;
#endif
};
int stcmp( TokenValue const & a, TokenValue const & b )
{
return stcmp( a.strValue, b.strValue );
} //stcmp
// maps to a line of BASIC
struct LineOfCode
{
LineOfCode( int line, const char * code ) :
lineNumber( line ), firstToken( Token_INVALID ), sourceCode( code ), goTarget( false )
#ifdef BA_ENABLE_INTERPRETER_EXECUTION_TIME
, timesExecuted( 0 ), duration( 0 )
#endif
{
tokenValues.reserve( 8 );
}
#ifdef WATCOM
LineOfCode() {}
#endif
// These tokens will be scattered through memory. I tried making them all contiguous
// and there was no performance benefit
Token firstToken; // optimization: first token in tokenValues.
vector<TokenValue> tokenValues; // vector of tokens on the line of code
string sourceCode; // the original BASIC line of code
int lineNumber; // line number in BASIC
bool goTarget; // true if a goto/gosub points at this line.
#ifdef BA_ENABLE_INTERPRETER_EXECUTION_TIME
uint64_t timesExecuted; // # of times this line is executed
uint64_t duration; // execution time so far on this line of code
#endif
};
vector<LineOfCode> g_linesOfCode;
#define g_lineno ( g_linesOfCode[ g_pc ].lineNumber )
struct ForGosubItem
{
ForGosubItem( int f, int p )
{
isFor = f;
pcReturn = p;
}
#ifdef WATCOM
ForGosubItem() {}
#endif
int isFor; // true if FOR, false if GOSUB
int pcReturn; // where to return in a NEXT or RETURN statment
};
// this is faster than both <stack> and Stack using <vector> to implement a stack because there are no memory allocations.
const int maxStack = 60;
template <class T> class Stack
{
int current;
#ifdef WATCOM
T items[ maxStack ];
#else
union { T items[ maxStack ]; }; // avoid constructors and destructors on each T by using a union
#endif
public:
__makeinline Stack() : current( 0 ) {}
__makeinline void push( T const & x ) { assert( current < maxStack ); items[ current++ ] = x; }
__makeinline size_t size() { return current; }
__makeinline void pop() { assert( current > 0 ); current--; }
__makeinline T & top() { assert( current > 0 ); return items[ current - 1 ]; }
__makeinline T & operator[] ( size_t i ) { return items[ i ]; }
};
class CFile
{
private:
FILE * fp;
public:
CFile( FILE * file ) : fp( file ) {}
~CFile() { Close(); }
FILE * get() { return fp; }
void Close()
{
if ( NULL != fp )
{
fclose( fp );
fp = NULL;
}
}
};
static void Usage()
{
printf( "Usage: ba [-a] [-e] [-l] [-m] [-p] [-t] [-x] [-8] filename.bas [argvalue]\n" );
printf( " Basic interpreter\n" );
printf( " Arguments: filename.bas Subset of TRS-80 compatible BASIC\n" );
printf( " argvalue One optional integer argument to the app referenced in basic as av%%\n" );
#ifdef BA_ENABLE_COMPILER
printf( " -a:X Generate assembly code, where X is one of:\n" );
printf( " 6 -- Generate 8-bit Apple 1 'sbasm30306\\sbasm.py' compatible assembler code to filename.s\n" );
printf( " 8 -- Generate 8-bit CP/M 2.2 i8080 'asm' compatible assembler code to filename.asm\n" );
printf( " a -- Generate 64-bit arm64 Windows armasm64 compatible assembler code to filename.asm\n" );
printf( " d -- Generate 16-bit 8086 DOS ml /AT /omf /c compatible assembler code to filename.asm\n" );
printf( " 3 -- Generate 32-bit Linux arm32 armv8 'gcc / as' compatible assembler code to filename.s\n" );
printf( " i -- Generate 32-bit i386 (686) Windows x86 'ml' compatible assembler code to filename.asm\n" );
printf( " I -- Generate 32-bit i386 (386) Windows 98 'ml' compatible assembler code to filename.asm\n" );
printf( " m -- Generate 64-bit MacOS 'as -arch arm64' compatible assembler code to filename.s\n" );
printf( " o -- Generate OneImage 'oia' compatible assembler code to filename.s\n" );
printf( " r -- Generate 64-bit RISC-V 64-bit GNU 'as' compatible assembler code to filename.s\n" );
printf( " x -- Generate 64-bit Windows x64 'ml64' compatible assembler code to filename.asm\n" );
printf( " -d Generate a dollar sign $ at the end of execution for Apple 1 apps\n" );
#endif
#ifdef BA_ENABLE_INTERPRETER_EXECUTION_TIME
printf( " -e Show interpreter execution count and time for each line\n" );
#endif
printf( " -l Show tokenized listing\n" );
#ifdef BA_ENABLE_COMPILER
printf( " -o Don't do expression optimization for assembly code\n" );
#endif
printf( " -p Show parse time for input file\n" );
printf( " -q Quiet. Don't show start and end messages in interpreter or compiled code\n" );
#ifdef BA_ENABLE_COMPILER
printf( " -r Don't use registers for variables in assembly code\n" );
#endif
printf( " -t Show debug tracing\n" );
printf( " -x Parse only; don't execute the code\n" );
#ifdef BA_ENABLE_COMPILER
printf( " notes: -- Assembly instructions are located at the top of generated files\n" );
#endif
exit( 1 );
} //Usage
const char * YesNo( bool f )
{
return f ? "yes" : "no";
} //YesNo
long portable_filelen( FILE * fp )
{
long current = ftell( fp );
fseek( fp, 0, SEEK_END );
long len = ftell( fp );
fseek( fp, current, SEEK_SET );
return len;
} //portable_filelen
bool isDigit( char c ) { return c >= '0' && c <= '9'; }
bool isAlpha( char c ) { return ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ); }
bool isWhite( char c ) { return ' ' == c || 9 /* tab */ == c; }
bool isToken( char c ) { return isAlpha( c ) || ( '%' == c ); }
bool isOperator( char c ) { return '<' == c || '>' == c || '=' == c; }
__makeinline const char * pastNum( const char * p )
{
while ( isDigit( *p ) )
p++;
return p;
} //pastNum
__makeinline void makelower( string & sl )
{
#ifdef WATCOM
char * p = (char *) sl.data();
size_t len = sl.length();
for ( size_t i = 0; i < len; i++ )
p[ i ] = tolower( p[ i ] );
#else
std::transform( sl.begin(), sl.end(), sl.begin(),
[](unsigned char c){ return std::tolower(c); });
#endif
} //makelower
Token readTokenInner( const char * p, int & len )
{
if ( 0 == *p )
{
len = 0;
return Token_INVALID;
}
if ( '(' == *p )
{
len = 1;
return Token_OPENPAREN;
}
if ( ')' == *p )
{
len = 1;
return Token_CLOSEPAREN;
}
if ( ',' == *p )
{
len = 1;
return Token_COMMA;
}
if ( ':' == *p )
{
len = 1;
return Token_COLON;
}
if ( ';' == *p )
{
len = 1;
return Token_SEMICOLON;
}
if ( '*' == *p )
{
len = 1;
return Token_MULT;
}
if ( '/' == *p )
{
len = 1;
return Token_DIV;
}
if ( '+' == *p )
{
len = 1;
return Token_PLUS;
}
if ( '-' == *p )
{
len = 1;
return Token_MINUS;
}
if ( '^' == *p )
{
len = 1;
return Token_XOR;
}
if ( isDigit( *p ) )
{
len = (int) ( pastNum( p ) - p );
return Token_CONSTANT;
}
if ( isOperator( *p ) )
{
if ( isOperator( * ( p + 1 ) ) )
{
len = 2;
char c1 = *p;
char c2 = * ( p + 1 );
if ( c1 == '<' && c2 == '=' )
return Token_LE;
if ( c1 == '>' && c2 == '=' )
return Token_GE;
if ( c1 == '<' && c2 == '>' )
return Token_NE;
return Token_INVALID;
}
else
{
len = 1;
if ( '<' == *p )
return Token_LT;
if ( '=' == *p )
return Token_EQ;
if ( '>' == *p )
return Token_GT;
return Token_INVALID;
}
}
if ( *p == '"' )
{
const char * pend = strchr( p + 1, '"' );
while ( pend && '"' == * ( pend + 1 ) )
pend = strchr( pend + 2, '"' );
if ( pend )
{
len = 1 + (int) ( pend - p );
return Token_STRING;
}
return Token_INVALID;
}
if ( !_strnicmp( p, "TIME$", 5 ) )
{
len = 5;
return Token_TIME;
}
if ( !_strnicmp( p, "ELAP$", 5 ) )
{
len = 5;
return Token_ELAP;
}
len = 0;
while ( ( isToken( * ( p + len ) ) ) && len < 10 )
len++;
if ( 1 == len && isAlpha( *p ) )
return Token_VARIABLE; // in the future, this will be true
if ( 2 == len )
{
if ( !_strnicmp( p, "OR", 2 ) )
return Token_OR;
if ( !_strnicmp( p, "IF", 2 ) )
return Token_IF;
if ( !_strnicmp( p, "TO", 2 ) )
return Token_TO;
if ( isAlpha( *p ) && ( '%' == * ( p + 1 ) ) )
return Token_VARIABLE;
}
else if ( 3 == len )
{
if ( !_strnicmp( p, "REM", 3 ) )
return Token_REM;
if ( !_strnicmp( p, "DIM", 3 ) )
return Token_DIM;
if ( !_strnicmp( p, "AND", 3 ) )
return Token_AND;
if ( !_strnicmp( p, "FOR", 3 ) )
return Token_FOR;
if ( !_strnicmp( p, "END", 3 ) )
return Token_END;
if ( isAlpha( *p ) && isAlpha( * ( p + 1 ) ) && ( '%' == * ( p + 2 ) ) )
return Token_VARIABLE;
}
else if ( 4 == len )
{
if ( !_strnicmp( p, "GOTO", 4 ) )
return Token_GOTO;
if ( !_strnicmp( p, "NEXT", 4 ) )
return Token_NEXT;
if ( !_strnicmp( p, "THEN", 4 ) )
return Token_THEN;
if ( !_strnicmp( p, "ELSE", 4 ) )
return Token_ELSE;
if ( !_strnicmp( p, "TRON", 4 ) )
return Token_TRON;
}
else if ( 5 == len )
{
if ( !_strnicmp( p, "GOSUB", 5 ) )
return Token_GOSUB;
if ( !_strnicmp( p, "PRINT", 5 ) )
return Token_PRINT;
if ( !_strnicmp( p, "TROFF", 5 ) )
return Token_TROFF;
}
else if ( 6 == len )
{
if ( !_strnicmp( p, "RETURN", 5 ) )
return Token_RETURN;
if ( !_strnicmp( p, "SYSTEM", 5 ) ) // system is the same as end; both exit execution
return Token_END;
}
return Token_INVALID;
} //readTokenInner
__makeinline Token readToken( const char * p, int & len )
{
Token t = readTokenInner( p, len );
if ( EnableTracing && g_Tracing )
printf( " read token %s from string '%s', length %d\n", TokenStr( t ), p, len );
return t;
} //readToken
__makeinline int readNum( const char * p )
{
if ( !isDigit( *p ) )
return -1;
return atoi( p );
} //readNum
void Fail( const char * error, size_t line, size_t column, const char * code )
{
printf( "Error: %s at line %zd column %zd: %s\n", error, line, column, code );
exit( 1 );
} //Fail
void RuntimeFail( const char * error, size_t line )
{
printf( "Runtime Error: %s at line %zd\n", error, line );
exit( 1 );
} //RuntimeFail
__makeinline const char * pastWhite( const char * p )
{
while ( isWhite( *p ) )
p++;
return p;
} //PastWhite
const char * ParseExpression( vector<TokenValue> & lineTokens, const char * pline, const char * line, int fileLine )
{
if ( EnableTracing && g_Tracing )
printf( " parsing expression from '%s'\n", pline );
bool first = true;
int parens = 0;
int tokenCount = 0;
TokenValue expToken( Token_EXPRESSION );
expToken.value = 666;
lineTokens.push_back( expToken );
size_t exp = lineTokens.size() - 1;
bool isNegative = false;
Token prevToken = Token_INVALID;
do
{
int tokenLen = 0;
pline = pastWhite( pline );
Token token = readToken( pline, tokenLen );
Token firstToken = token;
TokenValue tokenValue( token );
tokenCount++;
bool resetFirst = false;
if ( Token_MINUS == token && first )
{
isNegative = true;
pline += tokenLen;
}
else if ( Token_CONSTANT == token )
{
tokenValue.value = atoi( pline );
if ( isNegative )
{
tokenValue.value = -tokenValue.value;
tokenCount--;
isNegative = false;
}
if ( Token_CONSTANT == prevToken )
Fail( "consecutive constants are a syntax error", fileLine, pline - line, line );
lineTokens.push_back( tokenValue );
pline += tokenLen;
}
else if ( Token_VARIABLE == token )
{
if ( isNegative )
{
TokenValue neg( Token_MINUS );
lineTokens.push_back( neg );
isNegative = false;
}
if ( Token_VARIABLE == prevToken )
Fail( "consecutive variables are a syntax error", fileLine, pline - line, line );
tokenValue.strValue.insert( 0, pline, tokenLen );
if ( '%' != tokenValue.strValue[ tokenValue.strValue.length() - 1 ] )
Fail( "integer variables must end with a % symbol", fileLine, pline - line, line );
makelower( tokenValue.strValue );
lineTokens.push_back( tokenValue );
pline = pastWhite( pline + tokenLen );
token = readToken( pline, tokenLen );
if ( Token_OPENPAREN == token )
{
size_t iVarToken = lineTokens.size() - 1;
lineTokens[ iVarToken ].dimensions = 1;
tokenCount++;
tokenValue.Clear();
tokenValue.token = token;
lineTokens.push_back( tokenValue );
pline += tokenLen;
size_t expression = lineTokens.size();
pline = ParseExpression( lineTokens, pline, line, fileLine );
tokenCount += lineTokens[ expression ].value;
token = readToken( pline, tokenLen );
if ( Token_COMMA == token )
{
lineTokens[ iVarToken ].dimensions = 2;
tokenCount++;
tokenValue.Clear();
tokenValue.token = token;
lineTokens.push_back( tokenValue );
pline = pastWhite( pline + tokenLen );
size_t subexpression = lineTokens.size();
pline = ParseExpression( lineTokens, pline, line, fileLine );
tokenCount += lineTokens[ subexpression ].value;
pline = pastWhite( pline );
token = readToken( pline, tokenLen );
}
if ( Token_CLOSEPAREN != token )
Fail( "close parenthesis expected", fileLine, pline - line, line );
tokenCount++;
tokenValue.Clear();
tokenValue.token = token;
lineTokens.push_back( tokenValue );
pline += tokenLen;
}
}
else if ( Token_STRING == token )
{
if ( 1 != tokenCount )
Fail( "string not expected", fileLine, 0, line );
tokenValue.strValue.insert( 0, pline + 1, tokenLen - 2 );
tokenValue.strValue = UnescapeBASICString( tokenValue.strValue );
lineTokens.push_back( tokenValue );
pline += tokenLen;