Source file Basic_run.ml
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
open Talk
open Basic_parse
module IMap = Map.Make (Int)
type dialect = Integer | Applesoft
type program = (string * stmt list) IMap.t
let empty = IMap.empty
let add (p : program) n text stmts = IMap.add n (text, stmts) p
let remove (p : program) n = IMap.remove n p
let listing (p : program) : string = IMap.fold (fun n (text, _) acc -> acc ^ Printf.sprintf "%d %s\n" n text) p ""
let text_of (line : string) : string =
let s = String.trim (capitals line) in
let i = ref 0 in
while !i < String.length s && s.[!i] >= '0' && s.[!i] <= '9' do
incr i
done;
String.trim (String.sub s !i (String.length s - !i))
let of_lines (lines : string list) : (program, string) result =
List.fold_left
(fun acc line ->
match acc, parse_line line with
| Error _, _ -> acc
| Ok p, Ok (Numbered (n, Some stmts)) -> Ok (add p n (text_of line) stmts)
| Ok _, Ok _ -> Error ("NOT A NUMBERED LINE: " ^ line)
| Ok _, Error msg -> Error (msg ^ ": " ^ line))
(Ok empty) lines
type value = N of float | S of string
let wrap (x : float) : float =
let n = int_of_float (Float.trunc x) in
float_of_int (((n + 32768) land 0xFFFF) - 32768)
let show_number (d : dialect) (x : float) : string =
if Float.is_integer x && Float.abs x < 1e9 then Printf.sprintf "%.0f" x
else if d = Integer then Printf.sprintf "%.0f" (wrap x)
else
let s = Printf.sprintf "%.9g" x |> String.map (fun c -> if c = 'e' then 'E' else c) in
if String.length s > 1 && s.[0] = '0' && s.[1] = '.' then String.sub s 1 (String.length s - 1)
else if String.length s > 2 && String.sub s 0 3 = "-0." then "-" ^ String.sub s 2 (String.length s - 2)
else s
let key (name : string) : string =
let base = if is_string name then String.sub name 0 (String.length name - 1) else name in
let base = if String.length base > 2 then String.sub base 0 2 else base in
if is_string name then base ^ "$" else base
let default (name : string) : value = if is_string name then S "" else N 0.
type loop = { var : string; limit : float; step_by : float; back : int * int }
type machine = {
dialect : dialect;
code : (int * stmt array) array;
lines : int;
index : (int, int) Hashtbl.t;
vars : (string, value) Hashtbl.t;
arrays : (string, int list * value array) Hashtbl.t;
fns : (string, string * expr) Hashtbl.t;
mutable gosubs : (int * int) list;
mutable loops : loop list;
data : datum array;
mutable next_datum : int;
mutable col : int;
}
exception Error of string
let fail msg = raise (Error msg)
let create (dialect : dialect) (p : program) (direct : stmt list option) : machine =
let lines = IMap.fold (fun n (_, s) acc -> (n, Array.of_list s) :: acc) p [] |> List.rev in
let code = Array.of_list (lines @ match direct with Some s -> [ (-1, Array.of_list s) ] | None -> []) in
let index = Hashtbl.create 64 in
Array.iteri (fun i (n, _) -> if n >= 0 then Hashtbl.replace index n i) code;
let data = List.concat_map (fun (_, s) -> Array.to_list s |> List.concat_map (function Data d -> d | _ -> [])) lines in
{ dialect; code; lines = List.length lines; index; vars = Hashtbl.create 32; arrays = Hashtbl.create 8; fns = Hashtbl.create 4;
gosubs = []; loops = []; data = Array.of_list data; next_datum = 0; col = 0 }
let num (m : machine) (x : float) : value = N (if m.dialect = Integer then wrap x else x)
let number_of (v : value) : float = match v with N x -> x | S _ -> fail "TYPE MISMATCH"
let string_of (v : value) : string = match v with S s -> s | N _ -> fail "TYPE MISMATCH"
let element (m : machine) (name : string) (subs : int list) : value array * int =
let k = key name in
let dims, cells =
match Hashtbl.find_opt m.arrays k with
| Some a -> a
| None ->
let dims = List.map (fun _ -> 10) subs in
let a = (dims, Array.make (List.fold_left (fun n d -> n * (d + 1)) 1 dims) (default name)) in
Hashtbl.replace m.arrays k a;
a
in
if List.length dims <> List.length subs then fail "BAD SUBSCRIPT";
let i = List.fold_left2 (fun acc d s -> if s < 0 || s > d then fail "BAD SUBSCRIPT" else (acc * (d + 1)) + s) 0 dims subs in
(cells, i)
let ( let+ ) (m : 'a talk) (f : 'a -> 'b) : 'b talk =
let* x = m in
return (f x)
let rec eval (m : machine) (e : expr) : value talk =
match e with
| Num x -> return (num m x)
| Str s -> return (S s)
| Var v -> return (Option.value (Hashtbl.find_opt m.vars (key v)) ~default:(default v))
| Index (a, subs) ->
let+ subs = eval_ints m subs in
let cells, i = element m a subs in
cells.(i)
| Neg e ->
let+ v = eval m e in
num m (-.number_of v)
| Not e ->
let+ v = eval m e in
N (if number_of v = 0. then 1. else 0.)
| Bin (op, a, b) ->
let* x = eval m a in
let* y = eval m b in
return (binary m op x y)
| Fn (f, arg) -> (
match Hashtbl.find_opt m.fns (key f) with
| None -> fail "UNDEF'D FUNCTION"
| Some (x, body) ->
let* v = eval m arg in
let saved = Hashtbl.find_opt m.vars (key x) in
Hashtbl.replace m.vars (key x) v;
let+ r = eval m body in
(match saved with Some s -> Hashtbl.replace m.vars (key x) s | None -> Hashtbl.remove m.vars (key x));
r)
| Call ("RND", [ a ]) -> (
let* v = eval m a in
match m.dialect, v with
| Integer, N n when n >= 1. ->
let+ r = random (int_of_float n) in
N (float_of_int (r + 1))
| Applesoft, N _ ->
let+ r = random 16777216 in
N (float_of_int r /. 16777216.)
| _ -> fail "ILLEGAL QUANTITY")
| Call (f, args) ->
let* vs = eval_all m args in
return (call m f vs)
and eval_all (m : machine) (es : expr list) : value list talk =
match es with
| [] -> return []
| e :: rest ->
let* v = eval m e in
let+ vs = eval_all m rest in
v :: vs
and eval_ints (m : machine) (es : expr list) : int list talk =
let+ vs = eval_all m es in
List.map (fun v -> int_of_float (number_of v)) vs
and binary (m : machine) (op : op) (x : value) (y : value) : value =
let truth b = N (if b then 1. else 0.) in
match op, x, y with
| Add, S a, S b -> S (a ^ b)
| (Eq | Ne | Lt | Le | Gt | Ge), S a, S b ->
let c = compare a b in
truth (match op with Eq -> c = 0 | Ne -> c <> 0 | Lt -> c < 0 | Le -> c <= 0 | Gt -> c > 0 | _ -> c >= 0)
| _ -> (
let a = number_of x and b = number_of y in
match op with
| Add -> num m (a +. b)
| Sub -> num m (a -. b)
| Mul -> num m (a *. b)
| Div -> if b = 0. then fail "DIVISION BY ZERO" else num m (a /. b)
| Pow -> num m (Float.pow a b)
| Eq -> truth (a = b)
| Ne -> truth (a <> b)
| Lt -> truth (a < b)
| Le -> truth (a <= b)
| Gt -> truth (a > b)
| Ge -> truth (a >= b)
| And -> truth (a <> 0. && b <> 0.)
| Or -> truth (a <> 0. || b <> 0.))
and call (m : machine) (f : string) (vs : value list) : value =
let n1 () = match vs with [ v ] -> number_of v | _ -> fail "SYNTAX" in
let s1 () = match vs with [ v ] -> string_of v | _ -> fail "SYNTAX" in
let positive x = if x < 0. then fail "ILLEGAL QUANTITY" else x in
match f, vs with
| "INT", _ -> num m (Float.floor (n1 ()))
| "ABS", _ -> num m (Float.abs (n1 ()))
| "SGN", _ -> N (let x = n1 () in if x > 0. then 1. else if x < 0. then -1. else 0.)
| "SQR", _ -> num m (Float.sqrt (positive (n1 ())))
| "SIN", _ -> num m (Float.sin (n1 ()))
| "COS", _ -> num m (Float.cos (n1 ()))
| "TAN", _ -> num m (Float.tan (n1 ()))
| "ATN", _ -> num m (Float.atan (n1 ()))
| "EXP", _ -> num m (Float.exp (n1 ()))
| "LOG", _ -> let x = n1 () in if x <= 0. then fail "ILLEGAL QUANTITY" else num m (Float.log x)
| "LEN", _ -> N (float_of_int (String.length (s1 ())))
| "VAL", _ ->
let s = String.trim (s1 ()) in
let rec longest n = if n = 0 then 0. else match float_of_string_opt (String.sub s 0 n) with Some x -> x | None -> longest (n - 1) in
num m (longest (String.length s))
| "ASC", _ -> let s = s1 () in if s = "" then fail "ILLEGAL QUANTITY" else N (float_of_int (Char.code s.[0]))
| "CHR$", _ -> let x = int_of_float (n1 ()) in if x < 0 || x > 255 then fail "ILLEGAL QUANTITY" else S (String.make 1 (Char.chr x))
| "STR$", _ -> S (show_number m.dialect (n1 ()))
| "LEFT$", [ s; n ] -> let s = string_of s and n = int_of_float (positive (number_of n)) in S (String.sub s 0 (min n (String.length s)))
| "RIGHT$", [ s; n ] ->
let s = string_of s and n = int_of_float (positive (number_of n)) in
let n = min n (String.length s) in
S (String.sub s (String.length s - n) n)
| "MID$", s :: start :: len ->
let s = string_of s and start = int_of_float (number_of start) in
if start < 1 then fail "ILLEGAL QUANTITY";
let from = min (start - 1) (String.length s) in
let len = match len with [ l ] -> int_of_float (positive (number_of l)) | _ -> String.length s in
S (String.sub s from (min len (String.length s - from)))
| _ -> fail "SYNTAX"
let value (m : machine) (e : expr) : (value, string) result talk =
let rec guard (t : value talk) : (value, string) result talk =
match t with
| Done v -> return (Ok v)
| Print (s, k) -> Print (s, guard k)
| Random (n, k) -> Random (n, fun i -> try guard (k i) with Error msg -> return (Result.Error msg))
| Step k -> Step (fun () -> try guard (k ()) with Error msg -> return (Result.Error msg))
| Read_line k -> Read_line (fun l -> try guard (k l) with Error msg -> return (Result.Error msg))
| Read_key k -> Read_key (fun l -> try guard (k l) with Error msg -> return (Result.Error msg))
| Spawn (c, k) -> Spawn (c, fun st -> try guard (k st) with Error msg -> return (Result.Error msg))
in
try guard (eval m e) with Error msg -> return (Result.Error msg)
let line_of (m : machine) (li : int) : int option = if li < m.lines then Some (fst m.code.(li)) else None
let report (m : machine) (li : int) (msg : string) : unit talk =
let at = match line_of m li with Some n -> Printf.sprintf " IN %d" n | None -> "" in
let text = match m.dialect with Integer -> Printf.sprintf "*** %s ERR%s\n" msg at | Applesoft -> Printf.sprintf "?%s ERROR%s\n" msg at in
let fresh_line = if m.col > 0 then "\n" else "" in
m.col <- 0;
print (fresh_line ^ text)
let assign (m : machine) (lv : lvalue) (subs : int list) (v : value) : unit =
let name = match lv with Scalar n | Elem (n, _) -> n in
(match is_string name, v with true, N _ | false, S _ -> fail "TYPE MISMATCH" | _ -> ());
match lv with
| Scalar n -> Hashtbl.replace m.vars (key n) v
| Elem (n, _) ->
let cells, i = element m n subs in
cells.(i) <- v
let field_value (name : string) (field : string) : value option =
let f = String.trim field in
let f = if String.length f >= 2 && f.[0] = '"' && f.[String.length f - 1] = '"' then String.sub f 1 (String.length f - 2) else f in
if is_string name then Some (S f) else match float_of_string_opt f with Some x when f <> "" -> Some (N x) | _ -> None
let rec go (m : machine) (li : int) (si : int) : unit talk =
let* () = step in
if li >= Array.length m.code then return ()
else
let _, stmts = m.code.(li) in
if si >= Array.length stmts then
if li + 1 < m.lines then go m (li + 1) 0 else return ()
else try exec m li si stmts.(si) with Error msg -> report m li msg
and exec (m : machine) (li : int) (si : int) (s : stmt) : unit talk =
let next () = go m li (si + 1) in
let next_line () = if li + 1 < m.lines then go m (li + 1) 0 else return () in
let with_value e (f : value -> unit talk) : unit talk =
let* r = value m e in
match r with Ok v -> (try f v with Error msg -> report m li msg) | Result.Error msg -> report m li msg
in
let with_values es (f : value list -> unit talk) : unit talk =
let rec all es acc = match es with [] -> f (List.rev acc) | e :: rest -> with_value e (fun v -> all rest (v :: acc)) in
all es []
in
let jump (target : int) (m : machine) : unit talk =
match Hashtbl.find_opt m.index target with Some i -> go m i 0 | None -> report m li (Printf.sprintf "NO LINE %d" target)
in
let zone = match m.dialect with Integer -> 8 | Applesoft -> 16 in
match s with
| Print items ->
let rec items_out (items : (item * sep) list) (acc : string) : unit talk =
match items with
| [] ->
let* () = print acc in
next ()
| (item, sep) :: rest ->
let text_of_item (f : string -> unit talk) : unit talk =
match item with
| Expr e -> with_value e (fun v -> f (match v with N x -> show_number m.dialect x | S s -> s))
| Tab e -> with_value e (fun v -> f (String.make (max 0 (int_of_float (number_of v) - 1 - m.col)) ' '))
| Spc e -> with_value e (fun v -> f (String.make (max 0 (int_of_float (number_of v))) ' '))
in
text_of_item (fun text ->
m.col <- m.col + String.length text;
let after =
match sep with
| Semi -> ""
| Newline ->
m.col <- 0;
"\n"
| Comma ->
let pad = zone - (m.col mod zone) in
m.col <- m.col + pad;
String.make pad ' '
in
items_out rest (acc ^ text ^ after))
in
if items = [] then begin
m.col <- 0;
let* () = print "\n" in
next ()
end
else items_out items ""
| Input (prompt, lvs) ->
let subs_of lv = match lv with Scalar _ -> [] | Elem (_, es) -> es in
with_values (List.concat_map subs_of lvs) (fun subs ->
let subs = List.map (fun v -> int_of_float (number_of v)) subs in
let rec split lvs subs =
match lvs with
| [] -> []
| lv :: rest ->
let n = List.length (subs_of lv) in
(lv, List.filteri (fun i _ -> i < n) subs) :: split rest (List.filteri (fun i _ -> i >= n) subs)
in
let targets = split lvs subs in
let rec ask_for (question : string) (targets : (lvalue * int list) list) : unit talk =
let* line = ask question in
let fields = String.split_on_char ',' line in
let rec take targets fields =
match targets, fields with
| [], [] -> next ()
| [], _ :: _ ->
let* () = print "?EXTRA IGNORED\n" in
next ()
| _ :: _, [] -> ask_for "?? " targets
| (lv, s) :: trest, f :: frest -> (
let name = match lv with Scalar n | Elem (n, _) -> n in
match field_value name f with
| Some v -> (
match assign m lv s v with
| () -> take trest frest
| exception Error msg -> report m li msg)
| None ->
let* () = print "?REENTER\n" in
ask_for "? " targets)
in
m.col <- 0;
take targets fields
in
ask_for (match prompt with Some p -> p ^ "? " | None -> "? ") targets)
| Let (lv, e) ->
let subs = match lv with Scalar _ -> [] | Elem (_, es) -> es in
with_values subs (fun subs ->
with_value e (fun v ->
assign m lv (List.map (fun v -> int_of_float (number_of v)) subs) v;
next ()))
| If c -> with_value c (fun v -> if (match v with N x -> x <> 0. | S s -> s <> "") then next () else next_line ())
| Goto e -> with_value e (fun v -> jump (int_of_float (number_of v)) m)
| Gosub e ->
with_value e (fun v ->
m.gosubs <- (li, si + 1) :: m.gosubs;
jump (int_of_float (number_of v)) m)
| On (e, sub, targets) ->
with_value e (fun v ->
let k = int_of_float (number_of v) in
if k < 0 then fail "ILLEGAL QUANTITY"
else if k = 0 || k > List.length targets then next ()
else begin
if sub then m.gosubs <- (li, si + 1) :: m.gosubs;
jump (List.nth targets (k - 1)) m
end)
| Return -> (
match m.gosubs with
| (l, s) :: rest ->
m.gosubs <- rest;
go m l s
| [] -> fail "RETURN WITHOUT GOSUB")
| For (v, a, b, step_by) ->
with_values (a :: b :: Option.to_list step_by) (fun vs ->
let start, limit, by =
match vs with [ a; b ] -> (a, number_of b, 1.) | [ a; b; c ] -> (a, number_of b, number_of c) | _ -> assert false
in
assign m (Scalar v) [] start;
let rec drop = function [] -> [] | l :: rest -> if l.var = key v then rest else drop rest in
let others = if List.exists (fun l -> l.var = key v) m.loops then drop m.loops else m.loops in
m.loops <- { var = key v; limit; step_by = by; back = (li, si + 1) } :: others;
next ())
| Next vs ->
let rec each (vs : string list) : unit talk =
let rec find = function
| [] -> fail "NEXT WITHOUT FOR"
| l :: rest -> (match vs with [] -> (l, rest) | v :: _ -> if l.var = key v then (l, rest) else find rest)
in
let l, outer = find m.loops in
let x = number_of (Option.value (Hashtbl.find_opt m.vars l.var) ~default:(N 0.)) +. l.step_by in
Hashtbl.replace m.vars l.var (num m x);
if (l.step_by >= 0. && x <= l.limit) || (l.step_by < 0. && x >= l.limit) then begin
m.loops <- l :: outer;
go m (fst l.back) (snd l.back)
end
else begin
m.loops <- outer;
match vs with _ :: (_ :: _ as rest) -> each rest | _ -> next ()
end
in
each vs
| Dim arrays ->
let rec each = function
| [] -> next ()
| (name, dims) :: rest ->
with_values dims (fun ds ->
let ds = List.map (fun v -> int_of_float (number_of v)) ds in
if Hashtbl.mem m.arrays (key name) then fail "REDIM'D ARRAY";
if List.exists (fun d -> d < 0) ds then fail "ILLEGAL QUANTITY";
Hashtbl.replace m.arrays (key name) (ds, Array.make (List.fold_left (fun n d -> n * (d + 1)) 1 ds) (default name));
each rest)
in
each arrays
| Data _ | Rem -> next ()
| Read lvs ->
let rec each = function
| [] -> next ()
| lv :: rest ->
let subs = match lv with Scalar _ -> [] | Elem (_, es) -> es in
with_values subs (fun subs ->
if m.next_datum >= Array.length m.data then fail "OUT OF DATA";
let d = m.data.(m.next_datum) in
m.next_datum <- m.next_datum + 1;
let name = match lv with Scalar n | Elem (n, _) -> n in
let v = match d, is_string name with D_num x, false -> num m x | D_str s, true -> S s | D_num x, true -> S (show_number m.dialect x) | D_str _, false -> fail "TYPE MISMATCH" in
assign m lv (List.map (fun v -> int_of_float (number_of v)) subs) v;
each rest)
in
each lvs
| Restore ->
m.next_datum <- 0;
next ()
| Def (f, x, body) ->
Hashtbl.replace m.fns (key f) (x, body);
next ()
| End -> return ()
| Stop -> print (Printf.sprintf "%sBREAK%s\n" (if m.col > 0 then "\n" else "") (match line_of m li with Some n -> Printf.sprintf " IN %d" n | None -> ""))
| List | Run | New | Bye | Fp | Int | Catalog | Load _ | Save _ | Run_file _ -> fail "NOT IN A PROGRAM"
let run (d : dialect) (p : program) : unit talk =
let m = create d p None in
if m.lines = 0 then return () else go m 0 0
let direct (d : dialect) (p : program) (stmts : stmt list) : unit talk =
let m = create d p (Some stmts) in
go m m.lines 0