-
Notifications
You must be signed in to change notification settings - Fork 1
/
asmproc.ts
2455 lines (2018 loc) · 66.5 KB
/
asmproc.ts
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
#!/usr/bin/env node
// TODO fix bug no build long basic line with {}
// TODO split table word
// TODO define function ?
// TODO ifdef ... then include
// TODO dim as byte/word/bytes[]/words absolute
// TODO sintax for eliminating #0 ?
// TODO simulate AST parsing
// TODO lo/hi tables
// TODO locate and use Basic V2 variables
// TODO ELSE IF
// TODO --version
// TODO macro in if single
// TODO dim/zeropage
// TODO bye/word in #const
// TODO slowly convert to nearley
// TODO peephole optimizer
// TODO on goto
// TODO switch case
// TODO parse line with nearley
// TODO zero page pool ?
// TODO uses/preserve/lock?
// TODO input in sub
// TODO conditional include
// TODO test suite with 6502.js and Z80.js
// TODO float compiler with nearley
// TODO DIV, HIBYTE, LOBYTE functions
// TODO ' hypen comments?
// TODO "/*" comments when in quoted text
// TODO JMP simulate BRA branch always
// TODO self modifying code
// TODO WHILE, LOOP, UNTIL check no condition or loop forever
// TODO SUB nomesub = Identifier
// TODO SUB then rts or then exit sub ?
// TODO SUB implement RETURN
// TODO IF THEN GOTO move into IF SINGLE
// TODO bitmap, output as comment
// TODO float, output as comment
// TODO change float into cbmfloat, output as comment
// TODO basic compact by default // preserve
// TODO first char space in DASM?
// TODO #define ?
// TODO Z80 if then ret / return
// TODO Z80 FOR
// TODO Z80 Macro
// TODO Z80 Condition
// TODO macro fix literal value call
// TODO bitmap for c64 sprites
// TODO cc65
// TODO if then macro on single line
// TODO basic tokenizer: {cm } as {cbm}
// TODO basic tokenizer: ? as print
// TODO basic tokenizer: c64 colors
// TODO basic tokenizer: alternate names (wht -> white)
// TODO basic tokenizer: {rev shift} ?
// TODO basic tokenizer: {cbm } shortcuts
// TODO document preferences: DO LOOP vs WHILE/FOR, IF on single line etc.
/*
TO DO
=====
- loop forever
- dim
- float
- float expr compiler
- line numbers
- else if
- then statement con endif automatico
- (...) in sub
- inline sub / call sub
- inline sub / call
- controllare operatori signed <,>,
*/
/*
DASM
include
IF ELSE ENDIF IFDEF IFNDEF
byte
word
equ (define)
parens: []
ca65
.include
.if .else .endif .ifdef .ifndef
.byte
.word
.define
parens: ()
Z80ASM
include
IF ELSE ENDIF IFDEF IFNDEF
defb
defw
define
defl, defm, defs size, fill
parens: ?
6502 Z80
===========================
C C carry
V V overflow
N S negative / sign
Z Z zero
*/
import fs from "fs";
import path from "path";
import commandLineArgs, { OptionDefinition } from 'command-line-args';
function parseOptions(optionDefinitions: OptionDefinition[]) {
try {
return commandLineArgs(optionDefinitions);
} catch(ex) {
console.log(ex.message);
process.exit(-1);
}
}
interface Macro
{
Name: string;
Id: string;
Parameters: string[];
Code: string;
}
class TStack<T=number>
{
Strings: T[];
constructor() {
this.Strings = [];
}
get Count() {
return this.Strings.length;
}
Add(s: T) {
this.Strings.push(s);
}
Pop() {
if(this.Strings.length === 0) throw `stack empty`;
return this.Strings.pop() as T;
}
Last() {
return this.Strings[this.Strings.length-1];
}
get IsEmpty() {
return this.Strings.length === 0;
}
}
export class TStringList extends TStack<string>
{
SaveToFile(fname: string) {
const content = this.Text();
fs.writeFileSync(fname, content);
}
LoadFromFile(fname: string) {
const text = fs.readFileSync(fname).toString();
this.SetText(text);
}
Text(): string {
return this.Strings.join("\n");
}
SetText(text: string): void {
(this.Strings as unknown as string[]) = text.split("\n");
}
}
function ChangeFileExt(name: string, ext: string): string
{
// taken from https://stackoverflow.com/questions/5953239/how-do-i-change-file-extension-with-javascript
return name.replace(/\.[^\.]+$/, ext);
}
function FileExists(name: string): boolean
{
return fs.existsSync(name);
}
function RemoveQuote(S: string) {
return S.substr(1, S.length-2);
}
function RemoveHash(S: string) {
if(S.startsWith("#")) return S.substr(1);
else return S;
}
declare global
{
interface String
{
AnsiPos(text: string): number;
SubString(start: number, count?: number): string;
Length(): number;
ToInt(): number;
CharCodeAt(index: number): number;
CharAt(index: number): string;
SetCharAt(index: number, ch: string): string;
}
}
String.prototype.AnsiPos = function(text: string): number {
const pos = this.indexOf(text);
return pos + 1; // Borland strings are 1-based
}
String.prototype.SubString = function(start: number, count?: number): string {
// Borland strings are 1-based
return this.substr(start-1, count);
}
String.prototype.Length = function(): number {
return this.length;
}
String.prototype.ToInt = function(): number {
return Number(this);
}
String.prototype.CharAt = function(index: number) {
// Borland strings are 1-based
return this.charAt(index-1);
}
String.prototype.CharCodeAt = function(index: number) {
// Borland strings are 1-based
return this.charCodeAt(index-1);
}
String.prototype.SetCharAt = function(index: number, chr: string): string {
// Borland strings are 1-based
if(index-1 > this.length-1) return this as string;
return this.substr(0,index-1) + chr + this.substr(index-1+1);
}
let L = new TStringList();
let StackIf: TStack;
let StackRepeat: TStack;
let StackDo: TStack;
let StackWhile: TStack;
let StackFor: TStack;
let StackSub: TStack;
let StackIf_U = new TStringList();
let StackFor_U = new TStringList();
let AllMacros: Macro[] = [];
let Ferr: string;
let Dims_at_end: string[] = [];
let Dims_at_start: string[] = [];
function emitConstDim(t: number) {
L.SetText(L.Text().replace(/§/g, "\n"));
}
import { target, Jump, MOD, define, BYTE, WORD, BYTESPACE, WORDSPACE } from "./cross";
import { GetParm, GetToken, Trim, UpperCase } from "./utils";
import { IsBasicStart, IsBasic, IsBasicEnd } from "./basic";
let defines: string[];
export function error(msg: string, cline?: number)
{
if(cline !== undefined) {
error(msg + " in line " + cline + " of " + Ferr);
return;
}
msg = "? " + msg;
console.log(`${msg}`);
if(Ferr!="") L.SaveToFile(Ferr);
process.exit(-1);
}
function main()
{
const options = parseOptions([
{ name: 'input', alias: 'i', type: String },
{ name: 'output', alias: 'o', type: String },
{ name: 'target', alias: 't', type: String, defaultValue: 'dasm' },
{ name: 'define', alias: 'd', type: String }
]);
if(options === undefined || options.input === undefined || options.output === undefined)
{
console.log("Usage: asmproc -i <inputfile> -o <outputfile>");
process.exit(-1);
return;
}
// set target
target.dasm = options.target === "dasm";
target.ca65 = options.target === "ca65";
target.z80asm = options.target === "z80asm";
target.cpu6502 = target.dasm || target.ca65;
target.cpuz80 = target.z80asm;
defines = options.define === undefined ? [] : options.define.split(",");
L = new TStringList();
let FName = options.input;
let FOut = options.output;
Ferr = ChangeFileExt(FOut, ".err");
if(FName == FOut)
{
error("file names must be different");
}
if(!FileExists(FName))
{
error("can't find file");
}
StackIf = new TStack();
StackRepeat = new TStack();
StackDo = new TStack();
StackWhile = new TStack();
StackFor = new TStack();
StackSub = new TStack();
StackIf_U = new TStringList();
StackFor_U = new TStringList();
L.LoadFromFile(FName);
ProcessFile();
L.SaveToFile(FOut);
console.log(`asmproc OK, created: "${FOut}"`);
process.exit(0);
}
/*
function GlobalConstants() {
let Linea = L.Strings[0];
if(dasm) {
Linea = "DASM EQU 1§"+Linea;
}
else if(ca65) {
Linea = "DEFINE CA65 1§"+Linea;
}
}
*/
function RemoveComments()
{
// remove C comments
let Whole = L.Text();
let x,y;
for(;;)
{
x = Whole.AnsiPos("/*");
if(x==0) break;
y = Whole.AnsiPos("*/");
if(y<x)
{
error("unmatched /* */ comment");
}
for(let t=x; t<=y+1; t++)
{
let c = Whole.CharCodeAt(t);
if(c != 13 && c != 10) Whole = Whole.SetCharAt(t, ' ');
}
}
L.SetText(Whole);
// remove // comments
for(let t=0; t<L.Count; t++)
{
const R = new RegExp(/(.*)\/\/(?=(?:[^"]*"[^"]*")*[^"]*$)(.*)/gmi);
const Linea = L.Strings[t];
const match = R.exec(Linea);
if(match !== null) {
const [all, purged, comment] = match;
L.Strings[t] = purged;
}
}
// remove ; comments
let inbasic = false;
for(let t=0; t<L.Count; t++)
{
// repeat on the same line for multiple ;
while(true) {
//const R = new RegExp(/(.*);(?=(?:[^"]*"[^"]*")*[^"]*$)(.*)/gmi);
const R = new RegExp(/(.*);(?=(?:[^"']*["'][^"']*["'])*[^"']*$)(.*)/gmi);
const Linea = L.Strings[t];
const match = R.exec(Linea);
if(match !== null) {
const [all, purged, comment] = match;
// special case of ; comment in BASIC START / BASIC END
if(IsBasicStart(purged)) {
inbasic = true;
L.Strings[t] = purged;
}
else if(IsBasicEnd(purged)) {
inbasic = false;
L.Strings[t] = purged;
}
if(!inbasic) L.Strings[t] = purged;
else break;
}
else
{
if(IsBasicStart(Linea)) inbasic = true;
if(IsBasicEnd(Linea)) inbasic = false;
break;
}
}
}
}
function ModOperator()
{
// transform MOD
for(let t=0; t<L.Count; t++)
{
while(true)
{
const R = new RegExp(/(.*)\sMOD\s(?=(?:[^"]*"[^"]*")*[^"]*$)(.*)/gmi);
const Linea = L.Strings[t];
const match = R.exec(Linea);
if(match !== null) {
const [all, left, right] = match;
L.Strings[t] = MOD(left, right);
}
else break;
}
}
}
function ResolveInclude(): boolean
{
for(let t=0; t<L.Count; t++)
{
let Linea = L.Strings[t];
const ReplaceTo = ResolveIncludeInner(Linea);
if(ReplaceTo !== undefined) {
L.Strings[t] = ReplaceTo;
return true;
}
}
return false;
}
function ResolveIncludeInner(Linea: string): string | undefined
{
const R = new RegExp(/\s*include(\s+binary)?\s+([\"<])(.*)([\">])\s*/ig);
const match = R.exec(Linea);
if(match === null) return undefined;
const [all, binary, openquota, nf, closequota] = match;
if(openquota === '<' && closequota !== '>') return undefined;
const nomefile = openquota === '"' ? nf : path.join(__dirname, "include", nf);
if(!FileExists(nomefile)) {
error(`include file "${nomefile}" not found`);
}
const file = fs.readFileSync(nomefile);
let content;
if(binary !== undefined)
{
content = Array.from(file).map((e,i) => {
const initial = i % 16 === 0 ? "§ byte " : "";
const comma = i % 16 !== 15 ? "," : "";
return `${initial} ${e}${comma}`;
}).join("");
}
else
{
content = file.toString();
}
return content;
}
/*
function ResolveInclude(): boolean
{
for(let t=0; t<L.Count; t++)
{
let Linea = UpperCase(Trim(L.Strings[t]))+" ";
let Include = GetParm(Linea, " ", 0);
if(Include=="INCLUDE")
{
let NomeFile = GetParm(Linea, " ", 1);
if(NomeFile.length < 2)
{
error(`invalid file name "${NomeFile}" in include`, t);
}
NomeFile = RemoveQuote(NomeFile);
if(!FileExists(NomeFile))
{
error(`include file "${NomeFile}" not found`, t);
}
let IF = new TStringList();
IF.LoadFromFile(NomeFile);
L.Strings[t] = IF.Text();
return true;
}
}
return false;
}
*/
function IsIdentifier(s: string)
{
const R = new RegExp(/^\s*[_a-zA-Z]+[_a-zA-Z0-9]*$/gmi);
const match = R.exec(s);
if(match === null) return false;
return true;
}
function RemoveColon()
{
// remove : colon
for(let t=0; t<L.Count; t++)
{
while(true)
{
const Linea = L.Strings[t];
//const R = new RegExp(/(.*):(?=(?:[^"]*"[^"]*")*[^"]*$)(.*)/gmi);
const R = new RegExp(/(.*):(?=(?:[^"']*["'][^"']*["'])*[^"']*$)(.*)/gmi);
const match = R.exec(Linea);
if(match !== null) {
const [all, leftpart, rightpart] = match;
if(IsIdentifier(leftpart)) break;
L.Strings[t] = `${leftpart}§ ${rightpart}`;
}
else break;
}
}
}
function MakeAllUpperCase()
{
let Whole = L.Text();
L.SetText(UpperCase(Whole));
}
// dim x as byte
// dim x as integer
// dim x as byte at $3000
// dim x as byte in zero page
// dim x as byte init 5
function IsDim(Linea: string, nl: number): string | undefined
{
// senza (size)
// const R = new RegExp(/\s*dim\s+([_a-zA-Z]+[_a-zA-Z0-9]*)\s+as\s+(byte|word|integer|char)((\s+at\s+(.*))|(\s+in\s+zero\s+page)|(\s+init)\s+(.*))?\s*/i);
const R = new RegExp(/\s*dim\s+([_a-zA-Z]+[_a-zA-Z0-9]*)(\s*\((.*)\))?\s+as\s+(byte|word|integer|char)((\s+at\s+(.*))|(\s+in\s+zero\s+page)|(\s+init)\s+(.*))?\s*/i);
const match = R.exec(Linea);
if(match === null) return undefined;
const [ all, id, size, part1, tipo, part, atstring, atvalue, zeropage, initstring, initvalue ] = match;
//console.log({all, id, part1, size, tipo, part, atstring, atvalue, zeropage, initstring, initvalue});
let Result = "";
let ival = initvalue == undefined ? "0" : initvalue;
if(zeropage !== undefined) throw `dim at zero page not implemented`;
if(atstring !== undefined) {
Dims_at_start.push(define(id,atvalue));
}
else if(tipo=="BYTE" || tipo=="CHAR") {
if(size==undefined) Dims_at_end.push(BYTE(id,ival));
else Dims_at_end.push(BYTESPACE(id,size,ival));
}
else if(tipo=="WORD" || tipo=="INTEGER") {
if(size==undefined) Dims_at_end.push(WORD(id,ival));
else Dims_at_end.push(WORDSPACE(id,size,ival));
}
else throw `unknown type ${tipo} in dim`;
return Result;
}
function IsIFDEFIncludeSingle(Linea: string, nl: number): string | undefined
{
// "_ #ifdef _ {cond} _ then _ include {file}";
const R = new RegExp(/\s*#ifdef\s+([_a-zA-Z]+[_a-zA-Z0-9]*)\s+then\s+include\s+(.*)/i);
const match = R.exec(Linea);
if(match === null) return undefined;
const [ all, id, includeFile ] = match;
const upperDefines = defines.map(e=>e.toUpperCase());
const upperId = id.toUpperCase();
const defined = upperDefines.indexOf(upperId) !== -1;
const Result = defined ? `include ${includeFile}` : "";
return Result;
}
// spezza su piu linee #IFDEF / #IFNDEF su singola linea
function IsIFDEFSingle(Linea: string, nl: number): string | undefined
{
// "_ #ifdef|#ifndef _ {cond} _ then {statement}";
const R = new RegExp(/\s*(#ifdef|#ifndef)\s+(.*)\s+then\s+(.*)/i);
const match = R.exec(Linea);
if(match === null) return undefined;
const [ all, ifdef, cond, statement ] = match;
return `${ifdef} ${cond}§ ${statement}§#ENDIF`;
}
// change assembler reserved keywords
function IsReservedKeywords(Linea: string, nl: number): string|undefined
{
Linea = Trim(Linea);
if(Linea.startsWith("#"))
{
if(target.dasm || target.z80asm)
{
Linea = Linea.replace("#IFDEF","IFCONST");
Linea = Linea.replace("#IFNDEF","IFNCONST");
Linea = Linea.replace("#IF","IF");
Linea = Linea.replace("#ELSE","ELSE");
Linea = Linea.replace("#ENDIF","ENDIF");
Linea = Linea.replace("#END IF","ENDIF");
//Linea = Linea.replace("#INCLUDE","INCLUDE");
let ReplaceTo = " " + Linea;
return ReplaceTo;
}
else if(target.ca65)
{
Linea = Linea.replace("#IFDEF",".IFDEF");
Linea = Linea.replace("#IFNDEF",".IFNDEF");
Linea = Linea.replace("#IF",".IF");
Linea = Linea.replace("#ELSE",".ELSE");
Linea = Linea.replace("#ENDIF",".ENDIF");
Linea = Linea.replace("#END IF",".ENDIF");
//Linea = Linea.replace("#INCLUDE","INCLUDE");
let ReplaceTo = " " + Linea;
return ReplaceTo;
}
}
return undefined;
}
function RemoveCommentInclude()
{
for(;;)
{
RemoveComments();
RemoveIfDefIncludeSingle();
let hasinclude = ResolveInclude();
if(!hasinclude) break;
}
}
function RemoveIfDefIncludeSingle()
{
// substitute DASM IF THEN on single line
for(let t=0; t<L.Count; t++)
{
let Dummy = L.Strings[t];
let ReplaceTo = IsIFDEFIncludeSingle(Dummy, t);
if(ReplaceTo !== undefined)
{
L.Strings[t] = ReplaceTo;
}
}
}
function RemoveIfDefSingle()
{
// substitute DASM IF THEN on single line
for(let t=0; t<L.Count; t++)
{
let Dummy = L.Strings[t];
let ReplaceTo = IsIFDEFSingle(Dummy, t);
if(ReplaceTo !== undefined)
{
L.Strings[t] = ReplaceTo;
}
}
}
function ProcessFile()
{
let t;
RemoveCommentInclude();
// remove \r new lines and tabs
L.SetText(L.Text().replace(/\r/g, ""));
L.SetText(L.Text().replace(/\t/g, " "));
// scan for basic, needs to be done first before of semicolon replacement
for(t=0;t<L.Count;t++)
{
let Dummy = L.Strings[t];
let ReplaceTo = IsBasic(L, Dummy, t);
// IsBasic does replace by itself
// if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
}
ModOperator();
RemoveColon();
MakeAllUpperCase();
RemoveIfDefSingle();
// change § into newlines (needed for DASM IF-THENs)
L.SetText(L.Text().replace(/§/g, "\n"));
// self modifying labels
for(t=0; t<L.Count; t++)
{
let Dummy = L.Strings[t];
let ReplaceTo;
ReplaceTo = IsSelfModLabel(Dummy, t);
if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
}
// scan for sub...end sub, need before macro to avoid conflicts with "sub"
for(t=0;t<L.Count;t++)
{
let Dummy = L.Strings[t];
let ReplaceTo;
ReplaceTo = IsSUB(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
ReplaceTo = IsEXITSUB(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
ReplaceTo = IsENDSUB(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
}
if(!StackSub.IsEmpty) error("SUB without END SUB");
// pre-process macros and build macro list
for(t=0; t<L.Count; t++)
{
let Dummy = L.Strings[t];
let ReplaceTo;
ReplaceTo = IsMACRO(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
ReplaceTo = IsENDMACRO(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
}
substitute_macro(L);
// scan for repeat ... until then
for(t=0; t<L.Count; t++)
{
let Dummy = L.Strings[t];
let ReplaceTo;
ReplaceTo = IsREPEAT(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
ReplaceTo = IsEXITREPEAT(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
ReplaceTo = IsUNTIL(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
}
if(!StackRepeat.IsEmpty) error("REPEAT without UNTIL");
// scan for do ... loop then
for(t=0;t<L.Count;t++)
{
let Dummy = L.Strings[t];
let ReplaceTo;
ReplaceTo = IsDO(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
ReplaceTo = IsEXITDO(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
ReplaceTo = IsLOOP(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
}
if(!StackDo.IsEmpty) error("DO without LOOP");
// scan for while ... wend then
for(t=0;t<L.Count;t++)
{
let Dummy = L.Strings[t];
let ReplaceTo;
ReplaceTo = IsWHILE(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
ReplaceTo = IsEXITWHILE(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
ReplaceTo = IsWEND(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
}
if(!StackWhile.IsEmpty) error("WHILE without WEND");
// scan for for ... next then
for(t=0;t<L.Count;t++)
{
let Dummy = L.Strings[t];
let ReplaceTo;
ReplaceTo = IsFOR(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
ReplaceTo = IsEXITFOR(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
ReplaceTo = IsNEXT(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
}
if(!StackFor.IsEmpty) error("FOR without NEXT");
// scan for on single line: "if then <statement>"
for(t=0;t<L.Count;t++)
{
let Dummy = L.Strings[t];
let ReplaceTo;
ReplaceTo = IsIFSINGLE(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
}
// change § into newlines (needed after IF-THEN <statement>)
L.SetText(L.Text().replace(/§/g, "\n"));
// do another macro substitition for macro in if-single
substitute_macro(L);
// scan for if then
for(t=0;t<L.Count;t++)
{
let Dummy = L.Strings[t];
let ReplaceTo;
ReplaceTo = IsIF(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
ReplaceTo = IsENDIF(Dummy, t); if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
ReplaceTo = IsELSE(Dummy, t);
if(ReplaceTo !== undefined)
{
L.Strings[t] = ReplaceTo;
StackIf_U.Pop();
StackIf_U.Add("true");
}
}
if(!StackIf.IsEmpty) error("malformed IF");
// substitute DIM (before const)
for(t=0;t<L.Count;t++)
{
let Dummy = L.Strings[t];
let ReplaceTo = IsDim(Dummy, t);
if(ReplaceTo !== undefined)
{
L.Strings[t] = ReplaceTo;
}
}
/*
// bitmap values
for(t=0;t<L.Count;t++)
{
let Dummy = L.Strings[t];
let ReplaceTo = IsBitmap(Dummy, t);
if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
}
*/
/*
// sprite values
for(t=0;t<L.Count;t++)
{
let Dummy = L.Strings[t];
let ReplaceTo = IsSprite(Dummy, t);
if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
}
*/
for(t=0;t<L.Count;t++)
{
let Dummy = L.Strings[t];
let ReplaceTo = IsCombined(Dummy, t);
if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
}
/*
// floating point values
for(t=0;t<L.Count;t++)
{
let Dummy = L.Strings[t];
let ReplaceTo = IsFloat(Dummy, t);
if(ReplaceTo !== undefined) L.Strings[t] = ReplaceTo;
}
// substitute const
for(t=0; t<L.Count; t++)
{
let Dummy = L.Strings[t];
let ReplaceTo = IsConst(Dummy, t);
if(ReplaceTo !== undefined)
{
L.Strings[t] = ReplaceTo;
}
}
*/
// add defines on top of the file
const definecode = defines.map(e=>{
const R = new RegExp(/\s*([_a-zA-Z]+[_a-zA-Z0-9]*)(\s*=\s*(.*))?\s*/ig);
const match = R.exec(e);
if(match != null) {
const [ all, id, eqpart, value ] = match;
if(value !== undefined) return define(id,value);
else return define(id,"1");
}
else return "";
}).join("§");
L.Strings[0] = definecode + "§" + L.Strings[0];
// add global variables created with DIM
L.SetText(Dims_at_start.join("§")+"§"+L.Text());
L.Add(Dims_at_end.join("§"));
Dims_at_start = [];
Dims_at_end = [];
// change § into newlines
L.SetText(L.Text().replace(/§/g,"\n"));
// substitute reserved keywords
for(t=0;t<L.Count;t++)
{
let Dummy = L.Strings[t];
let ReplaceTo = IsReservedKeywords(Dummy, t);
if(ReplaceTo !== undefined)
{
L.Strings[t] = ReplaceTo;
}
}
}
function Label(Header: string, nr: number, suffix: string)
{
return `${Header}_${nr}_${suffix}`;
}
function substitute_macro(L: TStringList) {
// substitute macros. substitution is repeated until all macro are expanded (recursively)
let replaced;
do
{
replaced = false;
for(let t=0; t<L.Count; t++)
{
let Dummy = L.Strings[t];
let ReplaceTo = IsMacroCall(Dummy, t);
if(ReplaceTo !== undefined) {
L.Strings[t] = ReplaceTo;
replaced = true;
}
}