-
Notifications
You must be signed in to change notification settings - Fork 6
/
basic-orig.ms
2475 lines (2299 loc) · 81.1 KB
/
basic-orig.ms
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".split +
"BREAK 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
//======================================================================
// Lexer (i.e. tokenizer)
//======================================================================
// 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
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
end if
end for
end if
return tokens
end function
//======================================================================
// Expression evaluator
//======================================================================
// SE (Stack Entry) class: represents one item (typically a 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.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.value
se.content = v
end function
SE.isValue = function
return self.type == 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; return self.type + "(" + self.content + ")"; end function
Evaluator = {}
Evaluator.tokens = []
Evaluator.nextTokIdx = 0
Evaluator.endIdx = 0
Evaluator.done = function; return self.nextTokIdx >= self.endIdx; end function
Evaluator.stack = null // list of SE
Evaluator.allowArrayRefs = false // if true, let user pass entire array, e.g. A()
Evaluator.make = function(tokens, startIdx=0, endIdx=null)
eval = new Evaluator
eval.tokens = tokens
eval.nextTokIdx = startIdx
if endIdx == null then eval.endIdx = tokens.len else eval.endIdx = endIdx
eval.stack = []
return eval
end function
Evaluator.debugPrint = function(s)
// Uncomment this line to see lots of helpful debugging output:
//text.color = "#008800"; print s; text.color = gfx.color
end function
Evaluator.stackStr = function
result = []
for item in self.stack; result.push item.toString; end for
return "[" + result.join(", ") + "]"
end function
Evaluator.push = function(content, type)
if type == null then
print "Invalid call to Evaluator.push"
pprint stackTrace
exit
end if
se = new SE
se.content = content
se.type = type
self.stack.push se
end function
Evaluator.pushValue = function(value)
if value isa number then return self.push(value, SE.number)
if value isa string then return self.push(value, SE.string)
print "Invalid call to Evaluator.pushValue; got " + value
pprint stackTrace
exit
end function
Evaluator.popValue = function
if not self.stack then return printErr("stack underflow")
se = self.stack.pop
if se.type == SE.number or se.type == SE.string or se.type == SE.list 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
Evaluator.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
Evaluator.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 opA + opB
else if op == "-" then
self.pushValue opA - opB
else if op == "*" then
self.pushValue opA * opB
else if op == "/" then
self.pushValue opA / opB
else if op == "\" then
self.pushValue int(int(opA) / int(opB))
else if op == "MOD" then
self.pushValue opA % opB
else if op == "^" then
self.pushValue opA ^ opB
else if op == "=" then
self.pushValue opA == opB
else if op == "<>" then
self.pushValue opA != opB
else if op == "<" then
self.pushValue opA < opB
else if op == ">" then
self.pushValue opA > opB
else if op == "<=" then
self.pushValue opA <= opB
else if op == ">=" then
self.pushValue opA >= opB
else if op == "EQV" then
self.pushValue (opA != 0) == (opB != 0)
else if op == "IMP" then
self.pushValue (opA == 0) or (opA != 0 and opB != 0)
else if op == "XOR" then
self.pushValue (opA == 0) != (opB == 0)
else if op == "OR" then
self.pushValue (opA != 0) or (opB != 0)
else if op == "AND" then
self.pushValue (opA != 0) and (opB != 0)
else
return printErr("Unknown operator: " + op)
end if
self.debugPrint "Applied " + op + " to " + opA + " and " + opB + " to get " + self.stack[-1]
end function
Evaluator.doUnaryOp = function
opA = self.popValue
if machine.halt then return
op = self.popOperator
if op == "-" then
self.pushValue -opA
else if op == "NOT" then
self.pushValue not (opA != 0)
end if
self.debugPrint "Applied " + op + " to " + opA + " to get " + self.stack[-1]
end function
// Find the function call (or array lookup) in the stack; it will
// be the thing closest to the top that looks like "ABC(". Return
// that, along with its arguments (stuff on stack above that),
// pulling all of these off the stack. If no such thing is found
// (before we get to an operator or start of stack), return null.
Evaluator.pullCall = function
pos = self.stack.len - 1
while pos >= 0
if self.stack[pos].isOpenParen then
// found it! Grab the function and arguments, with commas...
result = self.stack[pos:]
// strip out the commas, and extract the values...
if result.len > 1 then
for i in range(result.len-1, 1)
if result[i].type == SE.comma then
result.remove i
else if result[i].isValue then
result[i] = result[i].content
else
return printErr("Unexpected type in call argument: " + result[i])
end if
end for
end if
// clear all that stuff off stack
while self.stack.len > pos; self.stack.pop; end while
// and we're done
return result
end if
pos -= 1
end while
return null
end function
// Evaluate a function call or array lookup, represented as a
// list of the sort returned by pullCall (above). Push the
// result onto the stack.
Evaluator.doCallOrArray = function(call)
self.debugPrint "Evaluating a call: " + call
funcOrArrayName = call[0].content[:-1].upper
args = call[1:]
f = machine.fn.get(funcOrArrayName)
array = machine.arrs.get(funcOrArrayName)
if @f == null and array == null then
// 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
self.pushValue 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")
self.push array, SE.list
else
return printErr("unknown function or array " + funcOrArrayName)
end if
end function
// Collapse any binary and unary operators on the top of
// the stack. This should proceed until we hit either the
// bottom of the stack, or an open paren, or a comma.
Evaluator.collapseStack = function
self.debugPrint "Collapsing self.stack: " + self.stackStr
while self.stack.len > 1 and not machine.halt
if self.stack[-2].type == SE.comma then return
if self.stack[-2].isOpenParen then return
if self.stack[-2].isOperator("NOT") or (self.stack.len > 2 and self.stack[-3].isOpenParen) then
self.doUnaryOp
else if self.stack.len > 2 then
self.doBinop
else if self.stack[-2].isOperator("-") then
self.doUnaryOp
else
break
end if
end while
self.debugPrint "...collapsed to: " + self.stackStr
end function
// evaluate: evaluate a tokenized expression.
// For example, given [6, "*", 7], return 42.
Evaluator.evaluate = function(customLocals=null)
self.debugPrint "evalTokens(" + self.tokens[self.nextTokIdx:self.endIdx] + ")"
self.stack = []
canBail = false // marks points where we can bail out if we start a new value
pos = self.nextTokIdx
while pos < self.endIdx
tok = self.tokens[pos]
self.debugPrint self.stack + " <-- " + tok
if tok == "(" then
if canBail then break
self.push tok, SE.paren
canBail = false
else if tok isa string and tok.endsWith("(") then // e.g. ABS(
if canBail then break
self.push tok, SE.identifier
canBail = false
else if tok == "," then
// we've gotten a comma, which is a top-level grouper;
// go ahead and collapse anything on stack back to
// the previous comma or open-paren
self.collapseStack
self.push tok, SE.comma
canBail = false
else if tok == ")" then
// collapse last argument, i.e. collapse self.stack back to opening "(" or ","
self.collapseStack
// Now, there are two cases. Either this is a plain parenthesized
// sub-expression, or it is a function/array call.
// If it's a sub-expression, then the open paren must be the next-
// to-last item in stack.
nextToLast = self.stack[self.stack.len-2]
if nextToLast.type == SE.paren and nextToLast.content == "(" then
self.debugPrint "Ordinary parenthesized sub-expression found"
// ...in this case, we just remove the open paren and we're done
self.stack.remove self.stack.len-2
else
// otherwise, it should be a call (or array lookup)
call = self.pullCall
if call then
self.doCallOrArray call
else if self.stack.len < 3 then
return printErr("unmatched parentheses")
end if
end if
canBail = true
else if tok isa number then
// push a numeric operand
if canBail then break
self.pushValue tok
if self.stack.len > 1 and self.stack[-2] == "-" and
(self.stack.len == 2 or (self.stack[-3] isa string and
self.stack[-3].isOpenParen)) then
self.doUnaryOp
end if
canBail = true
else if tok[0] == """" then
// push a string literal
if canBail then break
self.pushValue stripQuotes(tok)
canBail = true
else if operators.contains(tok) then
// get an operator...
opIdx = operators.indexOf(tok)
if self.stack and not self.stack[-1].isOpenParen then
while self.stack.len >= 2 and self.stack[-2].isOperator
// process any higher-precedence operators already on stack
prevOp = self.stack[-2].content
prevOpIdx = -1
if self.stack.len > 1 then prevOpIdx = operators.indexOf(prevOp)
self.debugPrint "at op " + opIdx + ", considering " + prevOpIdx
if opIdx > prevOpIdx then break
if prevOp == "NOT" then self.doUnaryOp else self.doBinop
end while
end if
// then push the new operator
self.push tok, SE.operator
canBail = false
self.debugPrint "Pushed operator: " + tok
else
// push the value of identifier
if canBail then break
if customLocals != null and customLocals.hasIndex(tok) then
value = customLocals[tok]
else
value = getValue(tok)
if value == null then return null
end if
self.pushValue value
if self.stack.len > 1 and self.stack[-2] == "-" and
(self.stack.len == 2 or (self.stack[-3] isa string and
self.stack[-3].endsWith("("))) then
self.doUnaryOp
end if
canBail = true
end if
if machine.halt then return null
self.debugPrint "After handling " + self.tokens[pos] + ", self.stack is now: " + self.stackStr
pos += 1
self.nextTokIdx = pos
end while
// finally, collapse stack (which should be in precedence order)
self.collapseStack
if self.stack.len > 1 then
printErr "Syntax error -- extra stuff on self.stack: " + self.stackStr
end if
if self.stack then return self.popValue
end function
// Evaluate the given string of tokens, which should comprise a single expression.
evalTokens = function(tokens, customLocals=null)
eval = Evaluator.make(tokens)
return eval.evaluate(customLocals)
end function
// Evaluate the given string of tokens, assuming that is a comma-separated
// list of expressions of unknown length. Stop when we hit the end of the
// token list, or a ":" (statement separator). This is commonly used to get
// the arguments to a BASIC command. Return argument values as a list.
getArguments = function(tokens, startIdx, allowArrayRefs = false)
result = []
pos = startIdx
eval = Evaluator.make(tokens)
eval.allowArrayRefs = allowArrayRefs
while pos < tokens.len
if tokens[pos] == ":" then break
argEndPos = tokens.indexOfAnyParenSavvy([":",","], pos-1, tokens.len, tokens.len)
eval.nextTokIdx = pos
eval.endIdx = argEndPos
result.push eval.evaluate
if argEndPos == tokens.len or tokens[argEndPos] == ":" then break
pos = argEndPos + 1
end while
return result
end function
// A special version of getArguments used for LINE, RECT, and ELLIPSE,
// where we expect args of the form: x1,y1 TO x2,y2
// (but allow another comma to replace the TO), or just [TO] x2, y2
// (and x1,y1 is then fetched from machine.plotPos).
// Returns null in case of invalid syntax.
getDrawingArgs = function(tokens, startIdx, allowArrayRefs = false, assumeFrom = true)
result = []
pos = startIdx
eval = Evaluator.make(tokens)
eval.allowArrayRefs = allowArrayRefs
toPos = null
if tokens[startIdx] == "TO" then
toPos = 0
pos += 1
assumeFrom = true
end if
while pos < tokens.len
if tokens[pos] == ":" then break
argEndPos = tokens.indexOfAnyParenSavvy([":",",","TO"], pos-1, tokens.len, tokens.len)
if argEndPos < tokens.len and tokens[argEndPos] == "TO" then
if toPos != null then return null // syntax error to have more than one TO
toPos = result.len + 1 // remember where we saw the TO
end if
eval.nextTokIdx = pos
eval.endIdx = argEndPos
result.push eval.evaluate
if argEndPos == tokens.len or tokens[argEndPos] == ":" then break
pos = argEndPos + 1
end while
// validate the syntax
if result.len == 2 then
if toPos != null and toPos != 0 then return null
if assumeFrom then result = machine.plotPos + result
else if result.len == 4 then
if toPos != null and toPos != 2 then return null
else
return null
end if
return result
end function
// Helper function to find the file handle for a PRINT#, INPUT#, or GET# command.
// Look for a "#" at the end of the token at startIdx. If not found, return [null,startIdx+1].
// If found, return the file ID and the new startIdx after the ID token(s) as
// [file, newStart]. In case of error, print error and return null.
getFile = function(tokens, startIdx)
if startIdx >= tokens.len or tokens[startIdx][-1] != "#" then return [null, startIdx+1]
if startIdx+1 == tokens.len then return printErr("syntax error")
tok = tokens[startIdx+1]
result = null
if tok isa number then
result = [tok, startIdx+2]
else if isOpenParen(tok) then
closePos = tokens.findCloseParen(startIdx+2)
if closePos == null then return printErr("unbalanced parentheses")
fileId = evalTokens(tokens[startIdx+2:closePos])
if not fileId isa number then return printErr("file ID must be numeric")
result = [fileId, closePos+1]
else if isIdentifier(tok) then
fileId = getValue(tok)
if not fileId isa number then return printErr("file ID must be numeric")
result = [fileId, startIdx+2]
end if
if result == null or not machine.files.hasIndex(result[0]) then return printErr("invalid file ID")
result[0] = machine.files[result[0]]
if result[1] < tokens.len and tokens[result[1]] == "," then result[1] += 1
return result
end function
//======================================================================
// Functions that use and/or modify the state of the virtual machine.
// (Includes the Machine class, but also some global helper methods.)
//======================================================================
printErr = function(err)
loc = ""
if machine.lineIdx >= 0 and machine.lineNums.hasIndex(machine.lineIdx) and
machine.lineNums[machine.lineIdx] >= 0 then
loc = " in line " + machine.lineNums[machine.lineIdx]
end if
print char(7) + "Error: " + err + loc
machine.halt = true
// pprint stackTrace; exit
end function
getValue = function(identifier)
upperId = identifier.upper
if machine.vars.hasIndex(upperId) then
return machine.vars[upperId]
else if identifier.len < 3 then
if isNumericId(identifier) then return 0 else return ""
else
return printErr("undefined identifier '" + identifier + "'")
end if
end function
requireNum = function(value)
if not value isa number then return printErr("type mismatch")
return true
end function
requireStr = function(value)
if not value isa string then return printErr("type mismatch")
return true
end function
// Assign a value to the given lvar. Returns true on success,
// false if failed.
setValue = function(lvar, value)
upperId = lvar.id.upper
if isNumericId(lvar.id) != (value isa number) then return printErr("type mismatch")
if lvar.isArrayElem then
if not machine.arrs.hasIndex(upperId) then
// old-BASIC quirk: even arrays exist automatically, as soon as they are
// referenced, with 1 dimension and a size of 10. But we do this only
// for identifiers less than 3 characters long.
if lvar.id.len > 2 then return printErr("Undefined identifier")
if isNumericId(lvar.id) then arr = [0]*11 else arr = [""]*11
machine.arrs[upperId] = arr
end if
arr = machine.arrs[upperId]
index = lvar.index
if index isa list then
// dereference all but the LAST index
// (which we'll use to assign the new value)
for idx in index[:-1]
if idx < 0 or idx >= arr.len then
printErr "array index (" + idx + ") out of bounds (0-" + (arr.len-1) + ")"
return false
end if
arr = arr[idx]
end for
index = index[-1]
end if
if not index isa number then
printErr "array index must be a number"
return false
end if
if index < 0 or index >= arr.len then
printErr "array index (" + index + ") out of bounds (0-" + (arr.len-1) + ")"
return false
end if
arr[index] = value
else
machine.vars[upperId] = value
end if
return true
end function
syntaxColor = {}
syntaxColor.number = "#AAAAFF"
syntaxColor.string = "#88FF88"
syntaxColor.operator = "#FFFF88"
syntaxColor.punctuation = "#88FFFF"
syntaxColor.lineNum = "#888888"
syntaxColor.lineNumTarget = "#BBBBBB"
syntaxColor.rem = "#666666"
syntaxColor.comment = "#FFFFFF"
syntaxColor.keyword = "#FF88FF"
syntaxColor.colon = syntaxColor.lineNum
// Convert the given line of the program to plain text. This is similar
// to listOneLine, but without syntax coloring (and it returns the string
// instead of printing it.
getLineAsText = function(lineNum, tokens)
result = []
result.push str(lineNum) + " "
space = ""
for tok in tokens
if tok == "REM" then
result.push space + tok + " "
if tokens.len > 1 then result.push tokens[-1]
break
else if keywords.contains(tok) then
result.push space + tok + " "
space = ""
else if tok == ":" then
result.push space + tok + " "
space = ""
else if tok == "," or tok == ";" or tok == "(" or tok == ")" then
result.push tok
space = " " * (tok != "(")
else if tok[-1] == "(" then
id = tok[:-1]
result.push space + id
tok = tok[-1]
result.push tok
space = ""
else if operators.contains(tok) then
result.push space + tok
space = " "
else if tok isa number or isNumericId(tok) then
result.push space + tok
space = " "
else if tok.startsWith("""") or isStringId(tok) then
result.push space + tok
space = " "
else
result.push space + tok
space = " "
end if
end for
return result.join("")
end function
// Print the given line of the program, with syntax coloring.
listOneLine = function(lineNum, tokens)
if machine.comeFrom.hasIndex(lineNum) then
text.color = syntaxColor.lineNumTarget
else
text.color = syntaxColor.lineNum
end if
print lineNum, " "
space = ""
for tok in tokens
if tok == "REM" then
text.color = syntaxColor.rem
print space + tok, " "
text.color = syntaxColor.comment
if tokens.len > 1 then print tokens[-1], ""
break
else if keywords.contains(tok) then
text.color = syntaxColor.keyword
print space + tok, " "
space = ""
else if tok == ":" then
text.color = syntaxColor.colon
print space + tok + " ", ""
space = ""
else if tok == "," or tok == ";" or tok == "(" or tok == ")" then
text.color = syntaxColor.punctuation
print tok, ""
space = " " * (tok != "(")
else if tok[-1] == "(" then
id = tok[:-1]
if isStringId(id) then text.color = syntaxColor.string else text.color = syntaxColor.number
print space + id, ""
tok = tok[-1]
text.color = syntaxColor.punctuation
print tok, ""
space = ""
else if operators.contains(tok) then
text.color = syntaxColor.operator