-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbasic.ms
More file actions
3473 lines (3236 loc) · 112 KB
/
basic.ms
File metadata and controls
3473 lines (3236 loc) · 112 KB
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
// BASIC interpreter for Mini Micro
import "stringUtil"
import "listUtil"
import "mapUtil"
import "mathUtil"
//======================================================================
// Constants
//======================================================================
// Keywords, including all BASIC commands (but not including functions,
// which are defined as part of the Machine class):
keywords = "PRINT INPUT ON GOTO IF THEN ELSE FOR TO STEP NEXT END LET DIM REDIM DEF FN".split +
"GOSUB RETURN DATA READ RESTORE REM STOP USING".split +
"BREAK CALL CLEAR CLS HOME HTAB VTAB OFF GET WAIT SOUND OPEN CLOSE PRINT# INPUT# GET#".split +
"COLOR LINE PLOT FILL RECT ELLIPSE POLY IMAGE PEN".split +
"NEW LIST LISTREM CD PWD DIR CAT CATALOG LOAD SAVE RUN RENUMBER EDIT".split
// BASIC operators:
operators = "( ) EQV IMP XOR OR AND NOT = <> < > <= >= + - * / \ MOD ^".split
// Color palette: same as the C-64:
palette = ("#000000 #FFFFFF #880000 #AAFFEE #CC44CC #00CC55 #0000AA #EEEE77 " +
"#DD8855 #664400 #FF7777 #333333 #777777 #AAFF66 #0088FF #BBBBBB").split
//======================================================================
// Small Helper Functions
//======================================================================
isNumericChar = function(c)
return (c >= "0" and c <= "9")
end function
isIdentifierChar = function(c)
return (c >= "0" and c <= "9") or
(c >= "A" and c <= "Z") or
(c >= "a" and c <= "z") or
c == "_" or code(c) > 127
end function
isWhitespaceChar = function(c)
return stringUtil.whitespace.indexOf(c) != null
end function
stripQuotes = function(s)
if s isa string and s.len > 1 and s[0] == """" and s[-1] == """" then return s[1:-1]
return s
end function
// int: lops of the decimal portion of the given number.
// This means rounding down for positive numbers, but
// rounding up for negative numbers.
int = function(x)
if x >= 0 then return floor(x) else return ceil(x)
end function
// indexOfAny: return the smallest index of any of the options
// that occurs after the given startIdx;
// if none are found, return the given default.
list.indexOfAny = function(options, afterIdx=-1, defaultIfNotFound=null)
bestResult = null
for opt in options
idx = self.indexOf(opt, afterIdx)
if idx != null and (bestResult == null or idx < bestResult) then
bestResult = idx
end if
end for
if bestResult != null then return bestResult
return defaultIfNotFound
end function
string.indexOfAny = @list.indexOfAny // works for both! :)
// findCloser: find the closing element that comes after the given
// opening position, properly skipping over nested pairs. Note
// that we assume the opener is *before* startIdx.
list.findCloser = function(startIdx=0, opener="(", closer=")", endIndex=null)
if endIndex == null then endIndex = self.len
pos = startIdx
numOpen = 0
while pos < endIndex
if self[pos] == opener then
numOpen += 1
else if self[pos] == closer then
numOpen -= 1
if numOpen < 0 then return pos
end if
pos += 1
end while
end function
string.findCloser = @list.findCloser // works for strings, too!
// findCloseParen: like findCloser, but special in that it checks for
// opening parens at the end of tokens, e.g. "A(".
list.findCloseParen = function(startIdx=0, endIndex=null)
if endIndex == null then endIndex = self.len
pos = startIdx
numOpen = 0
while pos < endIndex
if isOpenParen(self[pos]) then
numOpen += 1
else if self[pos] == ")" then
numOpen -= 1
if numOpen < 0 then return pos
end if
pos += 1
end while
end function
// indexOfAnyParenSavvy: just like indexOfAny, except that this method
// ignores anything within pairs of parentheses (including tokens that
// end with an opening paren, like "ABS("). This is often the right
// way to find the comma that delineates the next argument to a function
// or whatever, as it will properly grab the entire expression, even
// if that expression contains function calls with commas in them.
list.indexOfAnyParenSavvy = function(options, afterIdx=-1, endIndex=null, defaultIfNotFound=null)
if not options isa list then options = [options]
if endIndex == null then endIndex = self.len
pos = afterIdx + 1
numOpen = 0
while pos < endIndex
item = self[pos]
if numOpen == 0 and options.contains(item) then return pos
if isOpenParen(item) then
numOpen += 1
else if item == ")" then
numOpen -= 1
end if
pos += 1
end while
return defaultIfNotFound
end function
isIdentifier = function(s)
if not s isa string or not s then return false
if keywords.contains(s) then return false
return isIdentifierChar(s[0])
end function
isNumericId = function(s)
return isIdentifier(s) and s[-1] != "$"
end function
isStringId = function(s)
return isIdentifier(s) and s[-1] == "$"
end function
isStringLiteral = function(s)
return s isa string and s and s[0] == """" and s[-1] == """"
end function
isOpenParen = function(tok)
return tok isa string and tok and tok[-1] == "("
end function
// Make a multidimensional array, whose dimensions are defined
// by the given list. E.g. when dims == [10,20,30], then the
// top-level resulting list has 11 elements (index 0 through 10),
// each of those has 21 elements, and each of *those* has 31
// elements initially set to the given defaultValue.
makeMultiDimArray = function(dims, defaultValue)
if dims.len == 1 then return [defaultValue] * (dims[0] + 1)
result = []
remainingDims = dims[1:]
for idx in range(0, dims[0])
result.push makeMultiDimArray(remainingDims, defaultValue)
end for
return result
end function
// Check tokens starting at startPos for one of these patterns:
// fromNum, "-", toNum
// "-", toNum
// fromNum, "-"
// fromAndToNum
// Return a little map with "from" and "to" keys set to the
// corresponding number, or null.
getRange = function(tokens, startPos=0)
result = {"from":null, "to":null}
if startPos >= tokens.len then return result
if tokens.len == startPos+1 and tokens[-1] isa number and tokens[-1] < 0 then
// special case: a pattern like "-42" has been lexed as a negative number.
// But we want to treat it like ["-", 42]
tokens.push abs(tokens[-1])
tokens[-2] = "-"
end if
if tokens[startPos] == "-" then
if tokens.len > startPos+1 then result.to = val(tokens[startPos+1])
return result
end if
result.from = val(tokens[startPos])
if tokens.len == startPos+1 then
result.to = result.from
return result
end if
if tokens.len <= startPos+2 or tokens[startPos+1] != "-" then return result
result.to = val(tokens[startPos+2])
return result
end function
controlCPressed = function
return key.pressed("c") and (key.pressed("left ctrl") or key.pressed("right ctrl"))
end function
inputOrControlC = function(prompt="")
print prompt, ""
// flash cursor until control-C pressed, or some other key is available
t0 = time
cursorOn = false
showCursor = char(134) + " " + char(135) + char(8)
hideCursor = " " + char(8)
while true
if controlCPressed then
if cursorOn then print hideCursor, ""
key.clear
return char(3)
end if
if key.available then
if cursorOn then print hideCursor, ""
return input
end if
if time - t0 < 0.8 and not cursorOn then
print showCursor, ""
cursorOn = true
end if
if time - t0 >= 0.8 and cursorOn then
print hideCursor, ""
cursorOn = false
end if
if time - t0 > 1 then t0 += 1
yield
end while
end function
formatUsing = function(format, values)
result = []
valueIndex = 0
i = 0
while i < format.len
c = format[i]
// Check for string format specifiers
if c == "&" then
// Print entire string
if valueIndex < values.len then
result.push str(values[valueIndex])
valueIndex = valueIndex + 1
end if
i = i + 1
else if c == "!" then
// Print first character only
if valueIndex < values.len then
s = str(values[valueIndex])
if s.len > 0 then result.push s[0] else result.push " "
valueIndex = valueIndex + 1
end if
i = i + 1
else if c == "\" then
// Fixed-width string field: \ \ means 4 chars (backslashes plus spaces)
j = i + 1
while j < format.len and format[j] == " "
j = j + 1
end while
if j < format.len and format[j] == "\" then
// Found closing backslash
fieldWidth = j - i + 1
if valueIndex < values.len then
s = str(values[valueIndex])
// Center string in field (or truncate if too long)
if s.len < fieldWidth then
padding = fieldWidth - s.len
s += " " * padding
else if s.len > fieldWidth then
s = s[:fieldWidth]
end if
result.push s
valueIndex = valueIndex + 1
else
result.push " " * fieldWidth
end if
i = j + 1
else
// No closing backslash, treat as literal
result.push c
i = i + 1
end if
else if c == "#" or c == "0" or c == "+" or c == "$" or c == "*" then
// Numeric format - scan the whole format pattern
formatStart = i
formatEnd = i
// Scan for the extent of this numeric format
// A comma is only part of the format if followed by more digits
while formatEnd < format.len
ch = format[formatEnd]
if ch == "#" or ch == "0" or ch == "." or ch == "+" or ch == "$" or ch == "*" or ch == "^" then
formatEnd = formatEnd + 1
else if ch == "," or ch == "-" then
// Check if this is within the number format or a separator/trailing sign
// Look ahead to see if there are more digit chars
hasMoreDigits = 0
for j in range(formatEnd + 1, format.len - 1, 1)
if format[j] == "#" or format[j] == "0" then
hasMoreDigits = 1
break
else if format[j] != "." and format[j] != "," and format[j] != " " then
break
end if
end for
if hasMoreDigits then
formatEnd = formatEnd + 1
else if ch == "-" and formatEnd == format.len - 1 then
// Trailing minus sign - include it in the format
formatEnd = formatEnd + 1
break
else
break
end if
else
break
end if
end while
numFormat = format[formatStart:formatEnd]
if valueIndex < values.len then
result.push formatNumber(numFormat, values[valueIndex])
valueIndex = valueIndex + 1
end if
i = formatEnd
else
// Literal character
result.push c
i = i + 1
end if
end while
return result.join("")
end function
formatNumber = function(format, value)
// Parse format string
leadingSign = (format.indexOf("+") == 0)
trailingSign = (format.indexOf("-") == format.len - 1)
dollarSign = format.indexOf("$$") != null
asteriskFill = format.indexOf("**") != null
// Remove special prefix/suffix chars to find digit pattern
digitPattern = format
if leadingSign then digitPattern = digitPattern[1:]
if trailingSign then digitPattern = digitPattern[:-1]
// Check for fixed dollar sign (single $ at start, after removing +/-)
fixedDollarSign = (digitPattern.len > 0 and digitPattern[0] == "$" and not dollarSign)
if fixedDollarSign then digitPattern = digitPattern[1:]
digitPattern = digitPattern.replace("$$", "")
digitPattern = digitPattern.replace("**", "")
// Find decimal point
decimalPos = digitPattern.indexOf(".")
if decimalPos == null then decimalPos = digitPattern.len
// Count decimal places
decimalPlaces = 0
if decimalPos < digitPattern.len then
decimalPlaces = digitPattern.len - decimalPos - 1
end if
// Format the number
num = value
isNegative = (num < 0)
if isNegative then num = -num
// Round to decimal places
if decimalPlaces > 0 then
multiplier = 10 ^ decimalPlaces
num = round(num * multiplier) / multiplier
else
num = round(num)
end if
// Split into integer and decimal parts
numStr = str(num)
parts = numStr.split(".")
intPart = parts[0]
decPart = ""
if parts.len > 1 then decPart = parts[1]
// Pad decimal part
while decPart.len < decimalPlaces
decPart = decPart + "0"
end while
// Determine how many integer digit positions we need (excluding commas)
intDigits = 0
for i in range(0, decimalPos - 1, 1)
if digitPattern[i] == "#" or digitPattern[i] == "0" then
intDigits = intDigits + 1
end if
end for
// Reserve space for leading sign (reduce digits to make room)
if leadingSign and intDigits > 0 then intDigits = intDigits - 1
// For $$ and **, handle based on combination
if dollarSign and asteriskFill then
// Combined: $$ (2 chars) + ** (2 chars) = 4 chars in format
// Output: $ + * + digits, so add 2 positions total
intDigits = intDigits + 2
else if dollarSign then
// $$ alone: add 1 position ($ replaces one fill char)
intDigits = intDigits + 1
else if asteriskFill then
// ** alone: add 2 positions (asterisks are fill, need full width)
intDigits = intDigits + 2
end if
// Note: trailing sign doesn't reduce intDigits since it comes after the number
// Determine fill character (first # or 0 in integer part)
fillChar = " "
for i in range(0, decimalPos - 1, 1)
if digitPattern[i] == "#" then
fillChar = " "
break
else if digitPattern[i] == "0" then
fillChar = "0"
break
end if
end for
if asteriskFill then fillChar = "*"
// Pad integer part
while intPart.len < intDigits
intPart = fillChar + intPart
end while
// Add commas if needed
if digitPattern.indexOf(",") != null then
newIntPart = ""
digitCount = 0
for i in range(intPart.len - 1, 0, -1)
if digitCount > 0 and digitCount % 3 == 0 then
newIntPart = "," + newIntPart
end if
newIntPart = intPart[i] + newIntPart
digitCount = digitCount + 1
end for
intPart = newIntPart
end if
// Combine parts
if decimalPlaces > 0 then numStr = intPart + "." + decPart else numStr = intPart
// Add fixed dollar sign (goes at the very beginning)
if fixedDollarSign then numStr = "$" + numStr
// Add floating dollar sign (goes before first digit or before asterisks)
if dollarSign then
idx = 0
// When combined with **, the $ goes before the *, so only skip spaces and zeros
if asteriskFill then
while idx < numStr.len and (numStr[idx] == " " or numStr[idx] == "0")
idx += 1
end while
else
while idx < numStr.len and (numStr[idx] == " " or numStr[idx] == "*" or numStr[idx] == "0")
idx += 1
end while
end if
if idx > 0 then
numStr = numStr[:idx-1] + "$" + numStr[idx:]
else
numStr = "$" + numStr
end if
end if
// Add sign
if leadingSign then
if isNegative then numStr = "-" + numStr else numStr = "+" + numStr
else if trailingSign then
// Trailing sign format - always add a character
if isNegative then numStr = numStr + "-" else numStr = numStr + " "
else if isNegative then
// Floating minus sign - insert before first digit
idx = 0
while idx < numStr.len and (numStr[idx] == " " or numStr[idx] == "*" or numStr[idx] == "0" or numStr[idx] == "$")
idx = idx + 1
end while
if idx > 0 then
numStr = numStr[:idx-1] + "-" + numStr[idx:]
else
numStr = "-" + numStr
end if
end if
return numStr
end function
//======================================================================
// A little class to represent a "statement address" we can jump to
// (i.e., a line and statement index within that line)
//======================================================================
Address = {}; Address._name = "Address"
Address.lineIndex = 0
Address.statementIndex = 0
Address.make = function(lineIndex, statementIndex=0)
result = new Address
result.lineIndex = lineIndex
result.statementIndex = statementIndex
return result
end function
Address.next = function
return Address.make(self.lineIndex, self.statementIndex + 1)
end function
Address.str = function
return self.lineIndex + "#" + self.statementIndex
end function
Address.displayStr = function
s = machine.lineNums[self.lineIndex]
if self.statementIndex > 0 then s += ":" + (self.statementIndex+1)
return s
end function
//======================================================================
// Lexer (i.e. tokenizer)
//======================================================================
// Special-case tokens which, once encountered, cause the rest of the
// line up to ":" to be parsed as a single string:
stringArgTriggers = ["CD", "CAT", "CATALOG", "DIR", "LOAD", "SAVE"]
// tokenize: take the given line af BASIC code and return a
// list of tokens. Numbers will be actual numbers in the token
// list; all others will be strings, with string literals
// enclosed in quotes. In case of a REMark, the text part
// of the remark will be an unquoted string.
tokenize = function(line)
tokens = []
p0 = 0
lineLen = line.len
isData = false
while p0 < lineLen
c = line[p0]
if isWhitespaceChar(c) then
p0 += 1
else if c >= "0" and c <= "9" or c == "." then
// lex a number
p1 = p0 + 1
while p1 < lineLen and (isNumericChar(line[p1]) or line[p1] == ".")
p1 += 1
end while
if isData then // for DATA, continue to next comma or EOL
isNumeric = true
while p1 < lineLen and line[p1] != ","
if not isWhitespaceChar(line[p1]) then isNumeric=false
p1 +=1
end while
tok = line[p0:p1].trimRight
if isNumeric then tok = tok.val
tokens.push tok
else
tokens.push line[p0:p1].val
end if
p0 = p1
else if isIdentifierChar(c) then
// lex an identifier or keyword
p1 = p0 + 1
while p1 < lineLen and isIdentifierChar(line[p1])
p1 += 1
end while
if isData then // for DATA, continue to next comma or EOL
while p1 < lineLen and line[p1] != ","; p1 +=1; end while
tok = line[p0:p1]
else
if p1 < lineLen and (line[p1] == "$" or line[p1] == "#") then p1 += 1
tok = line[p0:p1]
upperTok = tok.upper
if keywords.contains(upperTok) or operators.contains(upperTok) or
machine.fn.hasIndex(upperTok) then tok = upperTok
end if
tokens.push tok
p0 = p1
if tok == "REM" then
// special case: rest of the line is a remark
if p0 < lineLen and line[p0] == " " then p0 += 1
if p0 < lineLen then tokens.push line[p0:]
p0 = lineLen
else if tok == "DATA" then
// another special case: after DATA, we do very limited tokenizing,
// taking everything between commas as a string (ignoring only
// commas in quotes)
isData = true
else if stringArgTriggers.contains(tok) then
// final special case: after CD, DIR, LOAD, etc.,
// load everything up to EOL or a colon as a single string
while p1 < lineLen and line[p1] != ":"
p1 += 1
end while
arg = line[p0:p1].trim
if arg then tokens.push arg
p0 = p1
end if
else if c == """" then
// lex a quoted string literal
p1 = p0 + 1
while p1 < lineLen and line[p1] != """"
p1 += 1
end while
if p1 >= lineLen then
print "Unterminated string literal"
return null
end if
tokens.push line[p0:p1+1]
p0 = p1+1
else if c == "?" and not isData then
tokens.push "PRINT"
p0 += 1
else
// unknown -- maybe an operator?
if p0+1 < lineLen and operators.contains(line[p0:p0+2]) then
tokens.push line[p0:p0+2]
p0 += 2
else
tokens.push line[p0]
p0 += 1
end if
end if
end while
if tokens.len > 1 then
// As a final pass, check for "-" before a number and after anything
// except an identifier, number, or right paren. In that case, combine it
// with the number (making it negative). Also combine "FN" with the following
// identifier (these are user-defined functions). Also, combine '(' with a
// previous identifier (this is a function call), and look for two-operator
// combos (like "<" ">") which should be combined ("<>").
for i in range(tokens.len-2, 0)
toki = tokens[i]
tokj = tokens[i+1]
if toki == "-" and tokj isa number and
not (i > 0 and (tokens[i-1] isa number or tokens[i-1]==")" or isIdentifier(tokens[i-1]))) then
tokens[i+1] = -tokens[i+1]
tokens.remove i
else if toki == "FN" and tokj isa string then
tokens[i] = toki + " " + tokj
tokens.remove i+1
end if
if i+1 >= tokens.len then continue
tokj = tokens[i+1]
if tokens[i+1] == "(" and isIdentifier(toki) and not operators.contains(toki) then
tokens[i] = toki + "("
tokens.remove i+1
else if (toki == ">" or toki == "<") and "<>=".contains(tokj) then
tokens[i] = toki + tokj
tokens.remove i+1
else if toki == "=" and tokj == "=" then
// == is not actually a valid BASIC operator, but we'll
// combine them here and throw an error further on
tokens[i] = "=="
tokens.remove i+1
end if
end for
end if
return tokens
end function
//======================================================================
// Syntax Tree Nodes (can be evaluated efficiently once built)
//======================================================================
SyntaxNode = {}
SyntaxNode.str = function
return mapName(self.__isa)
end function
SNLiteral = new SyntaxNode
SNLiteral.value = null // number or string, or null
SNLiteral.eval = function(customLocals); return self.value; end function
SNLiteral.str = function; return super.str + "(" + self.toCode + ")"; end function
SNLiteral.toCode = function
if self.value isa number then return str(self.value)
if self.value isa string then return """" + self.value.replace("""", """""") + """"
return str(self.value)
end function
SNLiteral.make = function(value)
result = new SNLiteral
result.value = value
return result
end function
SNLiteral.zero = SNLiteral.make(0)
SNLiteral.one = SNLiteral.make(1)
SNIdentifier = new SyntaxNode
SNIdentifier.ident = "" // actual identifier, e.g. "X"
SNIdentifier.eval = function(customLocals); return getValue(self.ident, customLocals); end function
SNIdentifier.str = function; return self.ident.upper; end function
SNIdentifier.toCode = @SNIdentifier.str
SNIdentifier.make = function(ident)
result = new SNIdentifier
result.ident = ident
return result
end function
SNBinop = new SyntaxNode
SNBinop.op = "?"
SNBinop.lhs = null
SNBinop.rhs = null
SNBinop.str = function
return super.str + "(" + self.lhs.str + ", " + self.rhs.str + ")"
end function
SNBinop.make = function(class, a, op, b)
result = new class
result.lhs = a; result.op = op; result.rhs = b
return result
end function
SNAdd = new SNBinop
SNAdd.eval = function(c); return self.lhs.eval(c) + self.rhs.eval(c); end function
SNAdd.make = function(a,b); return SNBinop.make(SNAdd, a, "+", b); end function
SNMult = new SNBinop
SNMult.eval = function(c); return self.lhs.eval(c) * self.rhs.eval(c); end function
SNMult.make = function(a,b); return SNBinop.make(SNMult, a, "*", b); end function
SNSub = new SNBinop
SNSub.eval = function(c); return self.lhs.eval(c) - self.rhs.eval(c); end function
SNSub.make = function(a,b); return SNBinop.make(SNSub, a, "-", b); end function
SNDiv = new SNBinop
SNDiv.eval = function(c); return self.lhs.eval(c) / self.rhs.eval(c); end function
SNDiv.make = function(a,b); return SNBinop.make(SNDiv, a, "/", b); end function
SNIDiv = new SNBinop
SNIDiv.eval = function(c); return int(int(self.lhs.eval) / int(self.rhs.eval)); end function
SNIDiv.make = function(a,b); return SNBinop.make(SNIDiv, a, "\", b); end function
SNMod = new SNBinop
SNMod.eval = function(c); return self.lhs.eval(c) % self.rhs.eval(c); end function
SNMod.make = function(a,b); return SNBinop.make(SNMod, a, "%", b); end function
SNPow = new SNBinop;
SNPow.eval = function(c); return self.lhs.eval(c) ^ self.rhs.eval(c); end function
SNPow.make = function(a,b); return SNBinop.make(SNPow, a, "^", b); end function
SNEq = new SNBinop
SNEq.eval = function(c); return self.lhs.eval(c) == self.rhs.eval(c); end function
SNEq.make = function(a,b); return SNBinop.make(SNEq, a, "=", b); end function
SNNotEq = new SNBinop
SNNotEq.eval = function(c); return self.lhs.eval(c) != self.rhs.eval(c); end function
SNNotEq.make = function(a,b); return SNBinop.make(SNNotEq, a, "<>", b); end function
SNLT = new SNBinop
SNLT.eval = function(c); return self.lhs.eval(c) < self.rhs.eval(c); end function
SNLT.make = function(a,b); return SNBinop.make(SNLT, a, "<", b); end function
SNGT = new SNBinop
SNGT.eval = function(c); return self.lhs.eval(c) > self.rhs.eval(c); end function
SNGT.make = function(a,b); return SNBinop.make(SNGT, a, ">", b); end function
SNLE = new SNBinop
SNLE.eval = function(c); return self.lhs.eval(c) <= self.rhs.eval(c); end function
SNLE.make = function(a,b); return SNBinop.make(SNLE, a, "<=", b); end function
SNGE = new SNBinop
SNGE.eval = function(c); return self.lhs.eval(c) >= self.rhs.eval(c); end function
SNGE.make = function(a,b); return SNBinop.make(SNGE, a, ">=", b); end function
SNEQV = new SNBinop
SNEQV.eval = function(c)
opA = self.lhs.eval(c); opB = self.rhs.eval
return (opA != 0) == (opB != 0)
end function
SNEQV.make = function(a,b); return SNBinop.make(SNEQV, a, "EQV", b); end function
SNIMP = new SNBinop
SNIMP.eval = function(c)
opA = self.lhs.eval(c); opB = self.rhs.eval
return (opA == 0) or (opA != 0 and opB != 0)
end function
SNIMP.make = function(a,b); return SNBinop.make(SNIMP, a, "IMP", b); end function
SNXOR = new SNBinop
SNXOR.eval = function(c)
opA = self.lhs.eval(c); opB = self.rhs.eval
return (opA == 0) != (opB == 0)
end function
SNXOR.make = function(a,b); return SNBinop.make(SNXOR, a, "XOR", b); end function
SNOR = new SNBinop
SNOR.eval = function(c)
opA = self.lhs.eval(c); opB = self.rhs.eval
return (opA != 0) or (opB != 0)
end function
SNOR.make = function(a,b); return SNBinop.make(SNOR, a, "OR", b); end function
SNAND = new SNBinop
SNAND.eval = function(c)
opA = self.lhs.eval(c); opB = self.rhs.eval
return (opA != 0) and (opB != 0)
end function
SNAND.make = function(a,b); return SNBinop.make(SNAND, a, "AND", b); end function
SNNOT = new SyntaxNode
SNNOT.eval = function(c)
opA = self.operand.eval
return not (opA != 0)
end function
SNNOT.str = function
return super.str + "(" + self.operand.str + ")"
end function
SNNOT.make = function(x)
result = new SNNOT
result.operand = x
return result
end function
SNArrayOrCall = new SyntaxNode
SNArrayOrCall.allowArrayRefs = false
SNArrayOrCall.eval = function(c)
Parser.debugPrint "Evaluating a call: " + self.name
funcOrArrayName = self.name
args = []
for n in self.args; args.push n.eval(c); end for
f = machine.fn.get(funcOrArrayName)
array = machine.arrs.get(funcOrArrayName)
if @f == null and array == null then
// Make sure the user isn't trying an invalid custom FN.
if funcOrArrayName.len > 2 and funcOrArrayName[:2] == "FN" then
printErr "Unknown custom function:" + funcOrArrayName
return
end if
// old-BASIC quirk: even arrays exist automatically, as soon as they are
// referenced, with 1 dimension and a size of 10.
if isNumericId(funcOrArrayName) then array = [0]*11 else array = [""]*11
machine.arrs[funcOrArrayName] = array
end if
if @f then
// it's a function — invoke it!
if not args then return printErr("argument required for function call")
if args.len == 1 then args = args[0] // (pass single argument as scalar)
result = f(args)
if machine.halt then return
return result
else if array != null then
// it's an array; look up the value (walking through dimensions
// of the array one at a time, until we have just a scalar left)
for idx in args
if not array isa list then return printErr("too many array indexes")
if not idx isa number then return printErr("array index must be numeric")
if idx < 0 or idx >= array.len then return printErr("out of bounds error on " + funcOrArrayName)
array = array[idx]
end for
if array isa list and not self.allowArrayRefs then return printErr("not enough array indexes")
return array
else
return printErr("unknown function or array " + funcOrArrayName)
end if
end function
SNArrayOrCall.str = function
strArgs = []
for n in self.args; strArgs.push n.str; end for
return self.name + "(" + join(strArgs, ",") + ")"
end function
SNArrayOrCall.make = function(name, indexNodes, allowArrayRefs=false)
result = new SNArrayOrCall
if name.len > 2 and name[:2] == "FN" and name[2] != " " then
// normalize, e.g., FNSQ --> FN SQ
name = "FN " + name[2:]
end if
result.name = name
result.args = indexNodes
if allowArrayRefs then result.allowArrayRefs = true
return result
end function
//======================================================================
// Expression parser
//======================================================================
// SE (Stack Entry) class: represents one item (typically a SyntaxNode,
// raw value, operator, or identifier) in our stack.
SE = {} // class to represent an operator (including `(` and `)`) on the stack
SE.content = null // actual value or identifier or whatever
SE.type = null // one of the following:
SE.node = "node"
SE.identifier = "identifier"
SE.number = "number"
SE.string = "string"
SE.list = "list"
SE.operator = "operator"
SE.paren = "paren" // includes both '(' and ')', but not, e.g., 'ABS('.
SE.comma = "comma"
SE.make = function(content, type)
result = new SE
result.type = type
result.content = content
return result
end function
SE.makeVal = function(v)
result = new SE
se.type = se.node
se.content = SNLiteral.make(v)
end function
SE.isValue = function
return self.type == SE.node // ...or SE.number or self.type == SE.string or self.type == SE.list
end function
SE.isOpenParen = function
return (self.type == SE.paren and self.content == "(") or
(self.type == SE.identifier and self.content[-1] == "(")
end function
SE.isOperator = function(op=null)
if self.type != SE.operator then return false
return op == null or self.content == op
end function
SE.toString = function
if self.type == SE.node then return self.content.str
return self.type + "(" + self.content + ")"
end function
Parser = {}
Parser.tokens = []
Parser.nextTokIdx = 0
Parser.endIdx = 0
Parser.done = function; return self.nextTokIdx >= self.endIdx; end function
Parser.stack = null // list of SE
Parser.allowArrayRefs = false // if true, let user pass entire array, e.g. A()
Parser.make = function(tokens, startIdx=0, endIdx=null)
eval = new Parser
eval.tokens = tokens
eval.nextTokIdx = startIdx
if endIdx == null then eval.endIdx = tokens.len else eval.endIdx = endIdx
eval.stack = []
return eval
end function
Parser.debugPrint = function(s)
// Uncomment this line to see lots of helpful debugging output:
// text.color = "#008800"; print s; text.color = gfx.color
end function
Parser.stackStr = function
result = []
for item in self.stack; result.push item.toString; end for
return "[" + result.join(", ") + "]"
end function
Parser.push = function(content, type)
if type == null then
print "Invalid call to Parser.push"
pprint stackTrace
exit
end if
se = new SE
se.content = content
se.type = type
self.stack.push se
end function
Parser.pushValue = function(value)
if value isa number or value isa string then
return self.push(SNLiteral.make(value), SE.node)
else if value isa SyntaxNode then
return self.push(value, SE.node)
end if
print "Invalid call to Parser.pushValue; got " + value
pprint stackTrace
exit
end function
Parser.popValue = function
if not self.stack then return printErr("stack underflow")
se = self.stack.pop
if se.type == SE.node or se.type == SE.identifier then return se.content
if se.type == SE.comma then return printErr("missing argument")
print "Type mismatch in popValue; got: " + se
pprint stackTrace
exit
end function
Parser.popOperator = function
if not self.stack then return printErr("stack underflow")
se = self.stack.pop
if se.type == SE.operator then return se.content
print "Expected operator, got " + se.type + " in popOperator"
pprint stackTrace
exit
end function
Parser.doBinop = function
opB = self.popValue
if machine.halt then return
op = self.popOperator
if machine.halt then return
opA = self.popValue
if op == "+" then
self.pushValue SNAdd.make(opA, opB)
else if op == "-" then
self.pushValue SNSub.make(opA, opB)