-
Notifications
You must be signed in to change notification settings - Fork 2
/
BasicParser.js
1538 lines (1337 loc) · 47.4 KB
/
BasicParser.js
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
// BasicParser.js - BASIC Parser
// (c) Marco Vieth, 2019
// https://benchmarko.github.io/CPCBasic/
//
// BASIC parser for Locomotive BASIC 1.1 for Amstrad CPC 6128
//
"use strict";
var Utils;
if (typeof require !== "undefined") {
Utils = require("./Utils.js"); // eslint-disable-line global-require
}
// [ https://www.codeproject.com/Articles/345888/How-to-write-a-simple-interpreter-in-JavaScript ; test online: http://jsfiddle.net/h3xwj/embedded/result/ ]
//
// http://crockford.com/javascript/tdop/tdop.html
// Top Down Operator Precedence
// http://crockford.com/javascript/tdop/parse.js
// http://crockford.com/javascript/tdop/index.html
//
// http://stevehanov.ca/blog/?id=92
// http://stevehanov.ca/qb.js/qbasic.js
//
// http://www.csidata.com/custserv/onlinehelp/vbsdocs/vbs232.htm (operator precedence) ?
// How to write a simple interpreter in JavaScript
// Peter_Olson, 30 Oct 2014
function BasicParser(options) {
this.init(options);
}
BasicParser.mParameterTypes = {
c: "command",
f: "function",
o: "operator",
n: "number",
s: "string",
l: "line number", // checked
q: "line number range",
v: "variable", // checked,
r: "letter or range",
a: "any parameter",
"n0?": "optional parameter with default null",
"#": "stream"
};
// first letter: c=command, f=function, o=operator, x=additional keyword for command
// following are arguments: n=number, s=string, l=line number (checked), v=variable (checked), r=letter or range, a=any, n0?=optional parameter with default null, #=stream, #0?=optional stream with default 0; suffix ?=optional (optionals must be last); last *=any number of arguments may follow
BasicParser.mKeywords = {
abs: "f n", // ABS(<numeric expression>)
after: "c", // => afterGosub
afterGosub: "c n n?", // AFTER <timer delay>[,<timer number>] GOSUB <line number> / (special, cannot check optional first n, and line number)
and: "o", // <argument> AND <argument>
asc: "f s", // ASC(<string expression>)
atn: "f n", // ATN(<numeric expression>)
auto: "c n0? n0?", // AUTO [<line number>][,<increment>]
bin$: "f n n?", // BIN$(<unsigned integer expression>[,<integer expression>])
border: "c n n?", // BORDER <color>[,<color>]
"break": "x", // see: ON BREAK...
call: "c n *", // CALL <address expression>[,<list of: parameter>]
cat: "c", // CAT
chain: "c s n?", // CHAIN <filename>[,<line number expression>] or: => chainMerge
chainMerge: "c s n? *", // CHAIN MERGE <filename>[,<line number expression>][,DELETE <line number range>] / (special)
chr$: "f n", // CHR$(<integer expression>)
cint: "f n", // CINT(<numeric expression>)
clear: "c", // CLEAR or: => clearInput
clearInput: "c", // CLEAR INPUT
clg: "c n?", // CLG[<ink>]
closein: "c", // CLOSEIN
closeout: "c", // CLOSEOUT
cls: "c #0?", // CLS[#<stream expression>]
cont: "c", // CONT
copychr$: "f #", // COPYCHR$(#<stream expression>)
cos: "f n", // COS(<numeric expression>)
creal: "f n", // CREAL(<numeric expression>)
cursor: "c #0? n0? n?", // CURSOR [<system switch>][,<user switch>] (either parameter can be omitted but not both)
data: "c n0*", // DATA <list of: constant> (rather 0*, insert dummy null, if necessary)
dec$: "f n s", // DEC$(<numeric expression>,<format template>)
def: "c s *", // DEF FN[<space>]<function name>[(<formal parameters>)]=<expression> / (not checked from this)
defint: "c r r*", // DEFINT <list of: letter range>
defreal: "c r r*", // DEFREAL <list of: letter range>
defstr: "c r r*", // DEFSTR <list of: letter range>
deg: "c", // DEG
"delete": "c q?", // DELETE [<line number range>] / (not checked from this)
derr: "f", // DERR
di: "c", // DI
dim: "c v *", // DIM <list of: subscripted variable>
draw: "c n n n0? n?", // DRAW <x coordinate>,<y coordinate>[,[<ink>][,<ink mode>]]
drawr: "c n n n0? n?", // DRAWR <x offset>,<y offset>[,[<ink>][,<ink mode>]]
edit: "c l", // EDIT <line number>
ei: "c", // EI
"else": "c", // see: IF (else belongs to "if", but can also be used as command)
end: "c", // END
ent: "c n *", // ENT <envelope number>[,<envelope section][,<envelope section>]... (up to 5) / section: <number of steps>,<step size>,<pause time> or: =<tone period>,<pause time>
env: "c n *", // ENV <envelope number>[,<envelope section][,<envelope section>]... (up to 5) / section: <number of steps>,<step size>,<pause time> or: =<hardware envelope>,<envelope period>
eof: "f", // EOF
erase: "c v *", // ERASE <list of: variable name> (array names without indices or dimensions)
erl: "f", // ERL
err: "f", // ERR
error: "c n", // ERROR <integer expression>
every: "c", // => everyGosub
everyGosub: "c n n?", // EVERY <timer delay>[,<timer number>] GOSUB <line number> / (special, cannot check optional first n, and line number)
exp: "f n", // EXP(<numeric expression>)
fill: "c n", // FILL <ink>
fix: "f n", // FIX(<numeric expression>)
fn: "f", // see DEF FN / (FN can also be separate from <function name>)
"for": "c", // FOR <simple variable>=<start> TO <end> [STEP <size>]
frame: "c", // FRAME
fre: "f a", // FRE(<numeric expression>) or: FRE(<string expression>)
gosub: "c l", // GOSUB <line number>
"goto": "c l", // GOTO <line number>
graphics: "c", // => graphicsPaper or graphicsPen
graphicsPaper: "x n", // GRAPHICS PAPER <ink> / (special)
graphicsPen: "x n0? n?", // GRAPHICS PEN [<ink>][,<background mode>] / (either of the parameters may be omitted, but not both)
hex$: "f n n?", // HEX$(<unsigned integer expression>[,<field width>])
himem: "f", // HIMEM
"if": "c", // IF <logical expression> THEN <option part> [ELSE <option part>]
ink: "c n n n?", // INK <ink>,<color>[,<color>]
inkey: "f n", // INKEY(<integer expression>)
inkey$: "f", // INKEY$
inp: "f n", // INP(<port number>)
input: "c #0? *", // INPUT[#<stream expression>,][;][<quoted string><separator>]<list of: variable> / (special: not checked from this)
instr: "f a a a?", // INSTR([<start position>,]<searched string>,<searched for string>) / (cannot check "f n? s s")
"int": "f n", // INT(<numeric expression>)
joy: "f n", // JOY(<integer expression>)
key: "c n s", // KEY <expansion token number>,<string expression> / or: => keyDef
keyDef: "c n n n? n? n?", // KEY DEF <key number>,<repeat>[,<normal>[,<shifted>[,<control>]]]
left$: "f s n", // LEFT$(<string expression>,<required length>)
len: "f s", // LEN(<string expression>)
let: "c", // LET <variable>=<expression>
line: "c", // => lineInput / (not checked from this)
lineInput: "c #0? *", // INPUT INPUT[#<stream expression>,][;][<quoted string><separator>]<string variable> (not checked from this)
list: "c q0? #0?", // LIST [<line number range>][,#<stream expression>] (not checked from this, we cannot check multiple optional args; here we have stream as last parameter)
load: "c s n?", // LOAD <filename>[,<address expression>]
locate: "c #0? n n", // LOCATE [#<stream expression>,]<x coordinate>,<y coordinate>
log: "f n", // LOG(<numeric expression>)
log10: "f n", // LOG10(<numeric expression>)
lower$: "f s", // LOWER$(<string expression>)
mask: "c n0? n?", // MASK [<integer expression>][,<first point setting>] / (either of the parameters may be omitted, but not both)
max: "f n *", // MAX(<list of: numeric expression>)
memory: "c n", // MEMORY <address expression>
merge: "c s", // MERGE <filename>
mid$: "f s n n?", // MID$(<string expression>,<start position>[,<sub-string length>]) / (start position=1..255, sub-string length=0..255)
mid$Assign: "f s n n?", // MID$(<string variable>,<insertion point>[,<new string length>])=<new string expression> / (mid$ as assign)
min: "f n *", // MIN(<list of: numeric expression>)
mod: "o", // <argument> MOD <argument>
mode: "c n", // MODE <integer expression>
move: "c n n n0? n?", // MOVE <x coordinate>,<y coordinate>[,[<ink>][,<ink mode>]]
mover: "c n n n0? n?", // MOVER <x offset>,<y offset>[,[<ink>][,<ink mode>]]
"new": "c", // NEW
next: "c v*", // NEXT [<list of: variable>]
not: "o", // NOT <argument>
on: "c", // => onBreakCont, on break gosub, on break stop, on error goto, on <ex> gosub, on <ex> goto, on sq(n) gosub
onBreakCont: "c", // ON BREAK CONT / (special)
onBreakGosub: "c l", // ON BREAK GOSUB <line number> / (special)
onBreakStop: "c", // ON BREAK STOP / (special)
onErrorGoto: "c l", // ON ERROR GOTO <line number> / (special)
onGosub: "c l l*", // ON <selector> GOSUB <list of: line number> / (special; n not checked from this)
onGoto: "c l l*", // ON <selector> GOTO <list of: line number> / (special; n not checked from this)
onSqGosub: "c l", // ON SQ(<channel>) GOSUB <line number> / (special)
openin: "c s", // OPENIN <filename>
openout: "c s", // OPENOUT <filename>
or: "o", // <argument> OR <argument>
origin: "c n n n? n? n? n?", // ORIGIN <x>,<y>[,<left>,<right>,<top>,<bottom>]
out: "c n n", // OUT <port number>,<integer expression>
paper: "c #0? n", // PAPER[#<stream expression>,]<ink>
peek: "f n", // PEEK(<address expression>)
pen: "c #0? n0 n?", // PEN[#<stream expression>,][<ink>][,<background mode>] / ink=0..15; background mode=0..1
pi: "f", // PI
plot: "c n n n0? n?", // PLOT <x coordinate>,<y coordinate>[,[<ink>][,<ink mode>]]
plotr: "c n n n0? n?", // PLOTR <x offset>,<y offset>[,[<ink>][,<ink mode>]]
poke: "c n n", // POKE <address expression>,<integer expression>
pos: "f #", // POS(#<stream expression>)
print: "c #0? *", // PRINT[#<stream expression>,][<list of: print items>] ... [;][SPC(<integer expression>)] ... [;][TAB(<integer expression>)] ... [;][USING <format template>][<separator expression>]
rad: "c", // RAD
randomize: "c n?", // RANDOMIZE [<numeric expression>]
read: "c v v*", // READ <list of: variable>
release: "c n", // RELEASE <sound channels> / (sound channels=1..7)
rem: "c s?", // REM <rest of line>
remain: "f n", // REMAIN(<timer number>) / (timer number=0..3)
renum: "c n0? n0? n?", // RENUM [<new line number>][,<old line number>][,<increment>]
restore: "c l?", // RESTORE [<line number>]
resume: "c l?", // RESUME [<line number>] or: => resumeNext
resumeNext: "c", // RESUME NEXT
"return": "c", // RETURN
right$: "f s n", // RIGHT$(<string expression>,<required length>)
rnd: "f n?", // RND[(<numeric expression>)]
round: "f n n?", // ROUND(<numeric expression>[,<decimals>])
run: "c a?", // RUN <string expression> or: RUN [<line number>] / (cannot check "c s | l?")
save: "c s a? n? n? n?", // SAVE <filename>[,<file type>][,<binary parameters>] // <binary parameters>=<start address>,<file tength>[,<entry point>]
sgn: "f n", // SGN(<numeric expression>)
sin: "f n", // SIN(<numeric expression>)
sound: "c n n n? n0? n0? n0? n?", // SOUND <channel status>,<tone period>[,<duration>[,<volume>[,<valume envelope>[,<tone envelope>[,<noise period>]]]]]
space$: "f n", // SPACE$(<integer expression>)
spc: "f n", // SPC(<integer expression) / see: PRINT SPC
speed: "c", // => speedInk, speedKey, speedWrite
speedInk: "c n n", // SPEED INK <period1>,<period2> / (special)
speedKey: "c n n", // SPEED KEY <start delay>,<repeat period> / (special)
speedWrite: "c n", // SPEED WRITE <integer expression> / (integer expression=0..1)
sq: "f n", // SQ(<channel>) / (channel=1,2 or 4)
sqr: "f n", // SQR(<numeric expression>)
step: "x", // STEP <size> / see: FOR
stop: "c", // STOP
str$: "f n", // STR$(<numeric expression>)
string$: "f n a", // STRING$(<length>,<character specificier>) / character specificier=string character or number 0..255
swap: "x n n?", // => windowSwap
symbol: "c n n *", // SYMBOL <character number>,<list of: rows> or => symbolAfter / character number=0..255, list of 1..8 rows=0..255
symbolAfter: "c n", // SYMBOL AFTER <integer expression> / integer expression=0..256 (special)
tab: "f n", // TAB(<integer expression) / see: PRINT TAB
tag: "c #0?", // TAG[#<stream expression>]
tagoff: "c #0?", // TAGOFF[#<stream expression>]
tan: "f n", // TAN(<numeric expression>)
test: "f n n", // TEST(<x coordinate>,<y coordinate>)
testr: "f n n", // TESTR(<x offset>,<y offset>)
then: "x", // THEN <option part> / see: IF
time: "f", // TIME
to: "x", // TO <end> / see: FOR
troff: "c", // TROFF
tron: "c", // TRON
unt: "f n", // UNT(<address expression>)
upper$: "f s", // UPPER$(<string expression>)
using: "x", // USING <format template>[<separator expression>] / see: PRINT
val: "f s", // VAL (<string expression>)
vpos: "f #", // VPOS(#<stream expression>)
wait: "c n n n?", // WAIT <port number>,<mask>[,<inversion>]
wend: "c", // WEND
"while": "c n", // WHILE <logical expression>
width: "c n", // WIDTH <integer expression>
window: "c #0? n n n n", // WINDOW[#<stream expression>,]<left>,<right>,<top>,<bottom> / or: => windowSwap
windowSwap: "c n n?", // WINDOW SWAP <stream expression>,<stream expression> / (special: with numbers, not streams)
write: "c #0? *", // WRITE [#<stream expression>,][<write list>] / (not checked from this)
xor: "o", // <argument> XOR <argument>
xpos: "f", // XPOS
ypos: "f", // YPOS
zone: "c n" // ZONE <integer expression> / integer expression=1..255
};
BasicParser.mCloseTokens = {
":": 1,
"(eol)": 1,
"(end)": 1,
"else": 1,
rem: 1,
"'": 1
};
BasicParser.prototype = {
init: function (options) {
this.bQuiet = options ? Boolean(options.bQuiet) : false;
// reset:
this.sLine = "0"; // for error messages
},
composeError: function (oError, message, value, pos) {
return Utils.composeError("BasicParser", oError, message, value, pos, this.sLine);
},
// http://crockford.com/javascript/tdop/tdop.html (old: http://javascript.crockford.com/tdop/tdop.html)
// http://crockford.com/javascript/tdop/parse.js
// Operator precedence parsing
//
// Operator: With left binding power (lbp) and operational function.
// Manipulates tokens to its left (e.g: +)? => left denotative function led(), otherwise null denotative function nud()), (e.g. unary -)
// identifiers, numbers: also nud.
parse: function (aTokens, bAllowDirect) {
var that = this,
oSymbols = {},
iIndex = 0,
aParseTree = [],
oPreviousToken, oToken,
symbol = function (id, nud, lbp, led) {
var oSymbol = oSymbols[id];
if (!oSymbol) {
oSymbols[id] = {};
oSymbol = oSymbols[id];
}
if (nud) {
oSymbol.nud = nud;
}
if (lbp) {
oSymbol.lbp = lbp;
}
if (led) {
oSymbol.led = led;
}
return oSymbol;
},
advance = function (id) {
var oSym;
oPreviousToken = oToken;
if (id && oToken.type !== id) {
throw that.composeError(Error(), "Expected " + id, (oToken.value === "") ? oToken.type : oToken.value, oToken.pos);
}
if (iIndex >= aTokens.length) {
oToken = oSymbols["(end)"];
return oToken;
}
oToken = aTokens[iIndex]; // we get a lex token and reuse it as parseTree token
iIndex += 1;
if (oToken.type === "identifier" && BasicParser.mKeywords[oToken.value.toLowerCase()]) {
oToken.type = oToken.value.toLowerCase(); // modify type identifier => keyword xy
}
oSym = oSymbols[oToken.type];
if (!oSym) {
throw that.composeError(Error(), "Unknown token", oToken.type, oToken.pos);
}
return oToken;
},
expression = function (rbp) {
var left,
t = oToken,
s = oSymbols[t.type];
if (Utils.debug > 3) {
Utils.console.debug("parse: expression rbp=" + rbp + " type=" + t.type + " t=%o", t);
}
advance(t.type);
if (!s.nud) {
if (t.type === "(end)") {
throw that.composeError(Error(), "Unexpected end of file", "", t.pos);
} else {
throw that.composeError(Error(), "Unexpected token", t.type, t.pos);
}
}
left = s.nud(t); // process literals, variables, and prefix operators
while (rbp < oSymbols[oToken.type].lbp) { // as long as the right binding power is less than the left binding power of the next token...
t = oToken;
s = oSymbols[t.type];
advance(t.type);
if (!s.led) {
throw that.composeError(Error(), "Unexpected token", t.type, t.pos); // TODO: how to get this error?
}
left = s.led(left); // ...the led method is invoked on the following token (infix and suffix operators), can be recursive
}
return left;
},
assignment = function () { // "=" as assignment, similar to let
var oValue, oLeft;
if (oToken.type !== "identifier") {
throw that.composeError(Error(), "Expected identifier", oToken.type, oToken.pos);
}
oLeft = expression(90); // take it (can also be an array) and stop
oValue = oToken;
advance("="); // equal as assignment
oValue.left = oLeft;
oValue.right = expression(0);
oValue.type = "assign"; // replace "="
return oValue;
},
statement = function () {
var t = oToken,
s = oSymbols[t.type],
oValue;
if (s.std) { // statement?
advance();
return s.std();
}
if (t.type === "identifier") {
oValue = assignment();
} else {
oValue = expression(0);
}
if (oValue.type !== "assign" && oValue.type !== "fcall" && oValue.type !== "def" && oValue.type !== "(" && oValue.type !== "[") {
throw that.composeError(Error(), "Bad expression statement", t.value, t.pos);
}
return oValue;
},
statements = function (sStopType) {
var aStatements = [],
bColonExpected = false,
oStatement;
while (oToken.type !== "(end)" && oToken.type !== "(eol)") {
if (sStopType && oToken.type === sStopType) {
break;
}
if (bColonExpected || oToken.type === ":") {
if (oToken.type !== "'" && oToken.type !== "else") { // no colon required for line comment or ELSE
advance(":");
}
bColonExpected = false;
} else {
oStatement = statement();
aStatements.push(oStatement);
bColonExpected = true;
}
}
return aStatements;
},
line = function () {
var oValue;
if (oToken.type !== "number" && bAllowDirect) {
bAllowDirect = false; // allow only once
oValue = { // insert "direct" label
type: "label",
value: "direct",
pos: 0,
len: 0
};
} else {
advance("number");
oValue = oPreviousToken; // number token
oValue.type = "label"; // number => label
}
that.sLine = oValue.value; // set line number for error messages
oValue.args = statements(null);
if (oToken.type === "(eol)") {
advance("(eol)");
}
return oValue;
},
infix = function (id, lbp, rbp, led) {
rbp = rbp || lbp;
symbol(id, null, lbp, led || function (left) {
var oValue = oPreviousToken;
oValue.left = left;
oValue.right = expression(rbp);
return oValue;
});
},
infixr = function (id, lbp, rbp, led) {
rbp = rbp || lbp;
symbol(id, null, lbp, led || function (left) {
var oValue = oPreviousToken;
oValue.left = left;
oValue.right = expression(rbp - 1);
return oValue;
});
},
prefix = function (id, rbp) {
symbol(id, function () {
var oValue = oPreviousToken;
oValue.right = expression(rbp);
return oValue;
});
},
stmt = function (s, f) {
var x = symbol(s);
x.std = f;
return x;
},
fnCreateDummyArg = function (sType, sValue) {
return {
type: sType, // e.g. "null"
value: sValue || sType, // e.g. "null"
pos: 0,
len: 0
};
},
fnGetOptionalStream = function () {
var oValue;
if (oToken.type === "#") { // stream?
oValue = expression(0);
} else { // create dummy
oValue = fnCreateDummyArg("#"); // dummy stream
oValue.right = fnCreateDummyArg("null", "0"); // ...with dummy parameter
}
return oValue;
},
fnChangeNumber2LineNumber = function (oNode) {
if (oNode.type === "number") {
oNode.type = "linenumber"; // change type: number => linenumber
} else {
throw that.composeError(Error(), "Expected number type", oNode.type, oNode.pos);
}
},
fnGetLineRange = function (sTypeFirstChar) { // l1 or l1-l2 or l1- or -l2 or nothing
var oRange, oLeft, oRight;
if (oToken.type === "number") {
oLeft = oToken;
advance("number");
fnChangeNumber2LineNumber(oLeft);
}
if (oToken.type === "-") {
oRange = oToken;
advance("-");
}
if (oRange) {
if (oToken.type === "number") {
oRight = oToken;
advance("number");
fnChangeNumber2LineNumber(oRight);
}
if (!oLeft && !oRight) {
throw that.composeError(Error(), "Expected " + BasicParser.mParameterTypes[sTypeFirstChar], oPreviousToken.value, oPreviousToken.pos);
}
oRange.type = "linerange"; // change "-" => "linerange"
oRange.left = oLeft || fnCreateDummyArg("null"); // insert dummy for left
oRange.right = oRight || fnCreateDummyArg("null"); // insert dummy for right (do not skip it)
} else if (oLeft) {
oRange = oLeft; // single line number
oRange.type = "linenumber"; // change type: number => linenumber
}
return oRange;
},
fnIsSingleLetterIdentifier = function (oValue) {
return oValue.type === "identifier" && !oValue.args && oValue.value.length === 1;
},
fnGetLetterRange = function (sTypeFirstChar) { // l1 or l1-l2 or l1- or -l2 or nothing
var oExpression;
if (oToken.type !== "identifier") {
throw that.composeError(Error(), "Expected " + BasicParser.mParameterTypes[sTypeFirstChar], oToken.value, oToken.pos);
}
oExpression = expression(0); // n or n-n
if (fnIsSingleLetterIdentifier(oExpression)) { // ok
oExpression.type = "letter"; // change type: identifier -> letter
} else if (oExpression.type === "-" && fnIsSingleLetterIdentifier(oExpression.left) && fnIsSingleLetterIdentifier(oExpression.right)) { // also ok
oExpression.type = "range"; // change type: "-" => range
oExpression.left.type = "letter"; // change type: identifier -> letter
oExpression.right.type = "letter"; // change type: identifier -> letter
} else {
throw that.composeError(Error(), "Expected " + BasicParser.mParameterTypes[sTypeFirstChar], oExpression.value, oExpression.pos);
}
return oExpression;
},
fnCheckRemainingTypes = function (aTypes) {
var sType, i, sText;
for (i = 0; i < aTypes.length; i += 1) { // some more parameters expected?
sType = aTypes[i];
if (!sType.endsWith("?") && !sType.endsWith("*")) { // mandatory?
sText = BasicParser.mParameterTypes[sType] || ("parameter " + sType);
throw that.composeError(Error(), "Expected " + sText + " for " + oPreviousToken.type, oToken.value, oToken.pos);
}
}
},
fnGetArgs = function (sKeyword) { // eslint-disable-line complexity
var aArgs = [],
sSeparator = ",",
mCloseTokens = BasicParser.mCloseTokens,
bNeedMore = false,
sType = "xxx",
sTypeFirstChar, aTypes, sKeyOpts, oExpression;
if (sKeyword) {
sKeyOpts = BasicParser.mKeywords[sKeyword];
if (sKeyOpts) {
aTypes = sKeyOpts.split(" ");
aTypes.shift(); // remove keyword type
} else {
Utils.console.warn("fnGetArgs: No options for keyword", sKeyword);
}
}
while (bNeedMore || (sType && !mCloseTokens[oToken.type])) {
bNeedMore = false;
if (aTypes && sType.slice(-1) !== "*") { // "*"= any number of parameters
sType = aTypes.shift();
if (!sType) {
throw that.composeError(Error(), "Expected end of arguments", oPreviousToken.type, oPreviousToken.pos);
}
}
sTypeFirstChar = sType.charAt(0);
if (sType === "#0?") { // optional stream?
if (oToken.type === "#") { // stream?
oExpression = fnGetOptionalStream();
if (oToken.type === ",") {
advance(",");
bNeedMore = true;
}
} else {
oExpression = fnGetOptionalStream();
}
} else {
if (sTypeFirstChar === "#") { // stream expected? (for functions)
oExpression = expression(0);
if (oExpression.type !== "#") { // maybe a number
throw that.composeError(Error(), "Expected " + BasicParser.mParameterTypes[sTypeFirstChar], oExpression.value, oExpression.pos);
}
} else if (oToken.type === sSeparator && sType.substr(0, 2) === "n0") { // n0 or n0?: if parameter not specified, insert default value null?
oExpression = fnCreateDummyArg("null");
} else if (sTypeFirstChar === "l") {
oExpression = expression(0);
if (oExpression.type !== "number") { // maybe an expression and no plain number
throw that.composeError(Error(), "Expected " + BasicParser.mParameterTypes[sTypeFirstChar], oExpression.value, oExpression.pos);
}
oExpression.type = "linenumber"; // change type: number => linenumber
} else if (sTypeFirstChar === "v") { // variable (identifier)
oExpression = expression(0);
if (oExpression.type !== "identifier") {
throw that.composeError(Error(), "Expected " + BasicParser.mParameterTypes[sTypeFirstChar], oExpression.value, oExpression.pos);
}
} else if (sTypeFirstChar === "r") { // letter or range of letters (defint, defreal, defstr)
oExpression = fnGetLetterRange(sTypeFirstChar);
} else if (sTypeFirstChar === "q") { // line number range
if (sType === "q0?") { // optional line number range
if (oToken.type === "number" || oToken.type === "-") { // eslint-disable-line max-depth
oExpression = fnGetLineRange(sTypeFirstChar);
} else {
oExpression = fnCreateDummyArg("null");
if (aTypes.length) { // eslint-disable-line max-depth
bNeedMore = true; // maybe take it as next parameter
}
}
} else {
oExpression = fnGetLineRange(sTypeFirstChar);
}
} else {
oExpression = expression(0);
if (oExpression.type === "#") { // got stream?
throw that.composeError(Error(), "Unexpected stream", oExpression.value, oExpression.pos);
}
}
if (oToken.type === sSeparator) {
advance(sSeparator);
bNeedMore = true;
} else if (!bNeedMore) {
sType = ""; // stop
}
}
aArgs.push(oExpression);
}
if (aTypes && aTypes.length) { // some more parameters expected?
fnCheckRemainingTypes(aTypes); // error if remaining mandatory args
sType = aTypes[0];
if (sType === "#0?") { // null stream to add?
oExpression = fnCreateDummyArg("#"); // dummy stream with dummy arg
oExpression.right = fnCreateDummyArg("null", "0");
aArgs.push(oExpression);
}
}
return aArgs;
},
fnGetArgsSepByCommaSemi = function () {
var mCloseTokens = BasicParser.mCloseTokens,
aArgs = [];
while (!mCloseTokens[oToken.type]) {
aArgs.push(expression(0));
if (oToken.type === "," || oToken.type === ";") {
advance(oToken.type);
} else {
break;
}
}
return aArgs;
},
fnGetArgsInParenthesis = function () {
var aArgs;
advance("(");
aArgs = fnGetArgs(null); // until ")"
advance(")");
return aArgs;
},
fnGetArgsInParenthesesOrBrackets = function () {
var oBrackets = {
"(": ")",
"[": "]"
},
aArgs, oBracketOpen, oBracketClose;
if (oToken.type === "(" || oToken.type === "[") { // oBrackets[oToken.type]
oBracketOpen = oToken;
}
advance(oBracketOpen ? oBracketOpen.type : "(");
aArgs = fnGetArgs(null); // (until "]" or ")")
aArgs.unshift(oBracketOpen);
if (oToken.type === ")" || oToken.type === "]") {
oBracketClose = oToken;
}
advance(oBracketClose ? oBracketClose.type : ")");
aArgs.push(oBracketClose);
if (oBrackets[oBracketOpen.type] !== oBracketClose.type) {
if (!that.bQuiet) {
Utils.console.warn(that.composeError({}, "Inconsistent bracket style", oPreviousToken.value, oPreviousToken.pos).message);
}
}
return aArgs;
},
fnCreateCmdCall = function (sType) {
var oValue = oPreviousToken;
if (sType) {
oValue.type = sType;
}
oValue.args = fnGetArgs(oValue.type);
return oValue;
},
fnCreateFuncCall = function (sType) {
var oValue = oPreviousToken,
sKeyOpts, aTypes;
if (sType) {
oValue.type = sType;
}
if (oToken.type === "(") { // args in parenthesis?
advance("(");
oValue.args = fnGetArgs(oValue.type); // until ")"
if (oToken.type !== ")") {
throw that.composeError(Error(), "Expected closing parenthesis for argument list after", oPreviousToken.value, oToken.pos);
}
advance(")");
} else { // no parenthesis?
oValue.args = [];
// if we have a check, make sure there are no non-optional parameters left
sKeyOpts = BasicParser.mKeywords[oValue.type];
if (sKeyOpts) {
aTypes = sKeyOpts.split(" ");
aTypes.shift(); // remove key
fnCheckRemainingTypes(aTypes);
}
}
return oValue;
},
fnGenerateKeywordSymbols = function () {
var sKey, sValue,
fnFunc = function () {
return fnCreateFuncCall(null);
},
fnCmd = function () {
return fnCreateCmdCall(null);
};
for (sKey in BasicParser.mKeywords) {
if (BasicParser.mKeywords.hasOwnProperty(sKey)) {
sValue = BasicParser.mKeywords[sKey];
if (sValue.charAt(0) === "f") {
symbol(sKey, fnFunc);
} else if (sValue.charAt(0) === "c") {
stmt(sKey, fnCmd);
}
}
}
},
fnInputOrLineInput = function (oValue) {
var oValue2, oStream;
oValue.args = [];
oStream = fnGetOptionalStream();
oValue.args.push(oStream);
if (oStream.len !== 0) { // not an inserted stream?
advance(",");
}
if (oToken.type === ";") { // no newline after input?
oValue.args.push(oToken);
advance(";");
} else {
oValue.args.push(fnCreateDummyArg("null"));
}
if (oToken.type === "string") { // message
oValue.args.push(oToken);
advance("string");
if (oToken.type === ";" || oToken.type === ",") { // ";" => need to append prompt "? " , "," = no prompt
oValue.args.push(oToken);
advance(oToken.type);
} else {
throw that.composeError(Error(), "Expected ; or ,", oToken.type, oToken.pos);
}
} else {
oValue.args.push(fnCreateDummyArg("null")); // dummy message
oValue.args.push(fnCreateDummyArg("null")); // dummy prompt
}
do { // we need loop for input
oValue2 = expression(90); // we expect "identifier", no fnxx
if (oValue2.type !== "identifier") {
throw that.composeError(Error(), "Expected identifier", oPreviousToken.type, oPreviousToken.pos);
}
oValue.args.push(oValue2);
if (oValue.type === "lineInput") {
break; // no loop for lineInput (only one arg)
}
} while ((oToken.type === ",") && advance(","));
return oValue;
};
fnGenerateKeywordSymbols();
symbol(":");
symbol(";");
symbol(",");
symbol(")");
symbol("]");
// define additional statement parts
symbol("break");
symbol("spc");
symbol("step");
symbol("swap");
symbol("then");
symbol("tab");
symbol("to");
symbol("using");
symbol("(eol)");
symbol("(end)");
symbol("number", function (number) {
return number;
});
symbol("binnumber", function (number) {
return number;
});
symbol("hexnumber", function (number) {
return number;
});
symbol("linenumber", function (number) {
return number;
});
symbol("string", function (s) {
return s;
});
symbol("identifier", function (oName) {
var sName = oName.value,
bStartsWithFn = sName.toLowerCase().startsWith("fn"),
oValue;
if (bStartsWithFn) {
if (oToken.type !== "(") { // Fnxxx name without ()?
oValue = {
type: "fn",
value: sName.substr(0, 2), // fn
args: [],
left: oName, // identifier
pos: oName.pos // same pos as identifier?
};
return oValue;
}
}
if (oToken.type === "(" || oToken.type === "[") {
oValue = oPreviousToken;
if (bStartsWithFn) {
oValue.args = fnGetArgsInParenthesis();
oValue.type = "fn"; // FNxxx in e.g. print
oValue.left = {
type: "identifier",
value: oValue.value,
pos: oValue.pos
};
} else {
oValue.args = fnGetArgsInParenthesesOrBrackets();
}
} else {
oValue = oName;
}
return oValue;
});
symbol("(", function () {
var oValue = expression(0);
advance(")");
return oValue;
});
symbol("[", function () {
var oValue = expression(0);
advance("]");
return oValue;
});
prefix("@", 95); // address of
infix("^", 90, 80);
prefix("+", 80);
prefix("-", 80);
infix("*", 70);
infix("/", 70);
infix("\\", 60); // integer division
infix("mod", 50);
infix("+", 40);
infix("-", 40);
infix("=", 30); // equal for comparison, left associative
infix("<>", 30);
infix("<", 30);
infix("<=", 30);
infix(">", 30);
infix(">=", 30);
prefix("not", 23);
infixr("and", 22);
infixr("or", 21);
infixr("xor", 20);
prefix("#", 10); // priority ok?
symbol("fn", function () { // separate fn
var oValue = oPreviousToken;
if (oToken.type === "identifier") { // maybe simplify by separating in lexer
oToken.value = oPreviousToken.value + oToken.value; // "fn" + identifier
oToken.bSpace = true; //fast hack: set space for CodeGeneratorBasic
oValue.left = oToken;
advance("identifier");
} else {
throw that.composeError(Error(), "Expected identifier", oToken.type, oToken.pos);
}
if (oToken.type !== "(") { // FN xxx name without ()?
oValue.args = [];
} else {
oValue.args = fnGetArgsInParenthesis();
}
return oValue;
});
// statements ...
stmt("'", function () { // apostrophe comment => rem
return fnCreateCmdCall("rem");
});
stmt("|", function () { // rsx
var oValue = oPreviousToken;
if (oToken.type === ",") { // arguments starting with comma
advance(",");
}
oValue.args = fnGetArgs(null);
return oValue;
});
stmt("after", function () {
var oValue = fnCreateCmdCall("afterGosub"), // interval and optional timer
aLine;
if (oValue.args.length < 2) { // add default timer 0
oValue.args.push(fnCreateDummyArg("null"));
}
advance("gosub");
aLine = fnGetArgs("gosub"); // line number
oValue.args.push(aLine[0]);
return oValue;
});
stmt("chain", function () {
var sName = "chain",
bNumberExpression = false, // line number (expression) found