-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic.clj
More file actions
1933 lines (1827 loc) · 78.3 KB
/
basic.clj
File metadata and controls
1933 lines (1827 loc) · 78.3 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
; Tomas Enrique Botalla - Padron 96356
; https://porkrind.org/a2
; https://www.calormen.com/jsbasic
; https://www.scullinsteel.com/apple2/
; https://fjkraan.home.xs4all.nl/comp/apple2faq/app2asoftfaq.html
; https://www.landsnail.com/a2ref.htm
; https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book.html
(declare driver-loop) ; NO TOCAR
(declare string-a-tokens) ; NO TOCAR
(declare evaluar-linea) ; NO TOCAR
(declare buscar-mensaje) ; NO TOCAR
(declare seleccionar-destino-de-on) ; NO TOCAR
(declare leer-data) ; NO TOCAR
(declare leer-con-enter) ; NO TOCAR
(declare retornar-al-for) ; NO TOCAR
(declare continuar-programa) ; NO TOCAR
(declare ejecutar-programa) ; NO TOCAR
(declare mostrar-listado) ; NO TOCAR
(declare cargar-arch) ; NO TOCAR
(declare grabar-arch) ; NO TOCAR
(declare calcular-expresion) ; NO TOCAR
(declare desambiguar-mas-menos) ; NO TOCAR
(declare desambiguar-mid) ; NO TOCAR
(declare shunting-yard) ; NO TOCAR
(declare calcular-rpn) ; NO TOCAR
(declare imprimir) ; NO TOCAR
(declare desambiguar-comas) ; NO TOCAR
(declare evaluar) ; COMPLETAR
(declare aplicar) ; COMPLETAR
(declare palabra-reservada?) ; IMPLEMENTAR x
(declare operador?) ; IMPLEMENTAR x
(declare anular-invalidos) ; IMPLEMENTAR x
(declare cargar-linea) ; IMPLEMENTAR xx
(declare expandir-nexts) ; IMPLEMENTAR x
(declare dar-error) ; IMPLEMENTAR x
(declare variable-float?) ; IMPLEMENTAR x
(declare variable-integer?) ; IMPLEMENTAR x
(declare variable-string?) ; IMPLEMENTAR x
(declare contar-sentencias) ; IMPLEMENTAR x
(declare buscar-lineas-restantes) ; IMPLEMENTAR x
(declare continuar-linea) ; IMPLEMENTAR x
(declare extraer-data) ; IMPLEMENTAR x
(declare ejecutar-asignacion) ; IMPLEMENTAR x
(declare preprocesar-expresion) ; IMPLEMENTAR x
(declare desambiguar) ; IMPLEMENTAR x
(declare precedencia) ; IMPLEMENTAR x
(declare aridad) ; IMPLEMENTAR x
(declare eliminar-cero-decimal) ; IMPLEMENTAR x
(declare eliminar-cero-entero) ; IMPLEMENTAR x
(defn spy [x] (prn x) x)
(defn spy2 [msg x] (prn (pr-str msg x)) x)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; driver-loop: el REPL del interprete de Applesoft BASIC
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn driver-loop
([]
(println)
(println "Interprete de Applesoft II BASIC en Clojure")
(println "Trabajo Practico de 75.14/95.48 Lenguajes Formales - 2020")
(println)
(println "Inspirado en: ****************************************")
(println " * APPLESOFT ][ FLOATING POINT BASIC *")
(println " * APRIL 1978 *")
(println " ****************************************")
(println " COPYRIGHT 1978 APPLE COMPUTER")
(println " COPYRIGHT 1976 BY MICROSOFT")
(println " ALL RIGHTS RESERVED")
(println)
(println "Corriendo en: APPLE II")
(println " DOS VERSION 3.3 SYSTEM MASTER")
(println " JANUARY 1, 1983")
(println " COPYRIGHT APPLE COMPUTER, INC. 1980,1982")
(flush)
(driver-loop ['() [:ejecucion-inmediata 0] [] [] [] 0 {}])) ; [(prog-mem) [prog-ptrs] [gosub-return-stack] [for-next-stack] [data-mem] data-ptr {var-mem}]
([amb]
(prn) (print "] ") (flush)
(try (let [linea (string-a-tokens (read-line)), cabeza (first linea)]
(cond (= cabeza '(EXIT)) 'GOODBYE
(= cabeza '(ENV)) (do (prn amb) (flush) (driver-loop amb))
(integer? cabeza) (if (and (>= cabeza 0) (<= cabeza 63999))
(driver-loop (cargar-linea linea amb))
(do (dar-error 16 (amb 1)) (driver-loop amb))) ; Syntax error
(empty? linea) (driver-loop amb)
:else (driver-loop (second (evaluar-linea linea (assoc amb 1 [:ejecucion-inmediata (count (expandir-nexts linea))]))))))
(catch Exception e (dar-error (str "?ERROR " (clojure.string/trim (clojure.string/upper-case (get (Throwable->map e) :cause)))) (amb 1)) (driver-loop amb))))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; string-a-tokens: analisis lexico y traduccion del codigo a la
; representacion intermedia (listas de listas de simbolos) que
; sera ejecutada (o vuelta atras cuando deba ser mostrada)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn string-a-tokens [s]
(let [nueva (str s ":"),
mayu (clojure.string/upper-case nueva),
sin-cad (clojure.string/replace mayu #"\"(.*?)\"" #(clojure.string/join (take (+ (count (% 1)) 2) (repeat "@")))),
ini-rem (clojure.string/index-of sin-cad "REM"),
pre-rem (subs mayu 0 (if (nil? ini-rem) (count mayu) ini-rem)),
pos-rem (subs mayu (if (nil? ini-rem) (- (count mayu) 1) (+ ini-rem 3)) (- (count mayu) 1)),
sin-rem (->> pre-rem
(re-seq #"EXIT|ENV|DATA[^\:]*?\:|REM|NEW|CLEAR|LIST|RUN|LOAD|SAVE|LET|AND|OR|INT|SIN|ATN|LEN|MID\$|STR\$|CHR\$|ASC|GOTO|ON|IF|THEN|FOR|TO|STEP|NEXT|GOSUB|RETURN|END|INPUT|READ|RESTORE|PRINT|\<\=|\>\=|\<\>|\<|\>|\=|\(|\)|\?|\;|\:|\,|\+|\-|\*|\/|\^|\"[^\"]*\"|\d+\.\d+E[+-]?\d+|\d+\.E[+-]?\d+|\.\d+E[+-]?\d+|\d+E[+-]?\d+|\d+\.\d+|\d+\.|\.\d+|\.|\d+|[A-Z][A-Z0-9]*[\%\$]?|[A-Z]|\!|\"|\#|\$|\%|\&|\'|\@|\[|\\|\]|\_|\{|\||\}|\~")
(map #(if (and (> (count %) 4) (= "DATA" (subs % 0 4))) (clojure.string/split % #":") [%]))
(map first)
(remove nil?)
(replace '{"?" "PRINT"})
(map #(if (and (> (count %) 1) (clojure.string/starts-with? % ".")) (str 0 %) %))
(map #(if (and (>= (count %) 4) (= "DATA" (subs % 0 4))) (let [provisorio (interpose "," (clojure.string/split (clojure.string/triml (subs % 4)) #",[ ]*"))] (list "DATA" (if (= ((frequencies %) \,) ((frequencies provisorio) ",")) provisorio (list provisorio ",")) ":")) %))
(flatten)
(map #(let [aux (try (clojure.edn/read-string %) (catch Exception e (symbol %)))] (if (or (number? aux) (string? aux)) aux (symbol %))))
(#(let [aux (first %)] (if (and (integer? aux) (not (neg? aux))) (concat (list aux) (list (symbol ":")) (rest %)) %)))
(partition-by #(= % (symbol ":")))
(remove #(.contains % (symbol ":")))
(#(if (and (= (count (first %)) 1) (number? (ffirst %))) (concat (first %) (rest %)) %)))]
(if (empty? pos-rem)
sin-rem
(concat sin-rem (list (list 'REM (symbol (clojure.string/trim pos-rem)))))))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; evaluar-linea: recibe una lista de sentencias y las evalua
; mientras sea posible hacerlo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn evaluar-linea
([sentencias amb]
;; (prn (pr-str "evaluar-linea diadico: sentencias=" sentencias " amb=" amb)) ;
(let [sentencias-con-nexts-expandidos (expandir-nexts sentencias)]
(evaluar-linea sentencias-con-nexts-expandidos sentencias-con-nexts-expandidos amb)))
([linea sentencias amb]
;; (prn (pr-str "evaluar-linea triadico: sentencias=" sentencias " amb=" amb " linea=" linea)) ; @TBOTALLA BORRAR
(if (empty? sentencias)
[:sin-errores amb]
(let [sentencia (anular-invalidos (first sentencias)), par-resul (evaluar sentencia amb)]
;; (prn (pr-str "evaluar-linea triadico: sentencia=" sentencia " par-resul=" par-resul)) ; @tbotalla borrar
(if (or (nil? (first par-resul)) (contains? #{:omitir-restante, :error-parcial, :for-inconcluso} (first par-resul)))
(if (and (= (first (amb 1)) :ejecucion-inmediata) (= (first par-resul) :for-inconcluso))
(recur linea (take-last (second (second (second par-resul))) linea) (second par-resul))
par-resul)
(recur linea (next sentencias) (assoc (par-resul 1) 1 [(first (amb 1)) (count (next sentencias))]))))))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; buscar-mensaje: retorna el mensaje correspondiente a un error
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn buscar-mensaje [cod]
(case cod
0 "?NEXT WITHOUT FOR ERROR"
6 "FILE NOT FOUND"
15 "NOT DIRECT COMMAND"
16 "?SYNTAX ERROR"
22 "?RETURN WITHOUT GOSUB ERROR"
42 "?OUT OF DATA ERROR"
53 "?ILLEGAL QUANTITY ERROR"
69 "?OVERFLOW ERROR"
90 "?UNDEF'D STATEMENT ERROR"
100 "?ILLEGAL DIRECT ERROR"
133 "?DIVISION BY ZERO ERROR"
163 "?TYPE MISMATCH ERROR"
176 "?STRING TOO LONG ERROR"
200 "?LOAD WITHIN PROGRAM ERROR"
201 "?SAVE WITHIN PROGRAM ERROR"
cod)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; seleccionar-destino-de-on: recibe una lista de numeros
; separados por comas, un indice y el ambiente, y retorna el
; numero a que hace referencia el indice (se cuenta desde 1)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn seleccionar-destino-de-on
([destinos indice amb]
(cond
(or (neg? indice) (> indice 255)) (do (dar-error 53 (amb 1)) nil) ; Illegal quantity error
(zero? indice) :omitir-restante
:else (seleccionar-destino-de-on (if (= (last destinos) (symbol ",")) (concat destinos [0]) destinos) indice amb 1)))
([destinos indice amb contador]
(cond
(nil? destinos) :omitir-restante
(= contador indice) (if (= (first destinos) (symbol ",")) 0 (first destinos))
(= (first destinos) (symbol ",")) (recur (next destinos) indice amb (inc contador))
(or (= (count destinos) 1)
(and (> (count destinos) 1) (= (second destinos) (symbol ",")))) (recur (nnext destinos) indice amb (inc contador))
:else (do (dar-error 16 (amb 1)) nil))) ; Syntax error
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; leer-data: recibe una lista de variables separadas por comas
; y un ambiente, y returna una dupla (un vector) con un
; resultado (usado luego por evaluar-linea) y un ambiente
; actualizado incluyendo las variables cargadas con los valores
; definidos en la(s) sentencia(s) DATA
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn leer-data
([param-de-read amb]
;; (spy2 "leer-data diadico respuesta="
(cond
(= (first (amb 1)) :ejecucion-inmediata) (do (dar-error 15 (amb 1)) [nil amb]) ; Not direct command
(empty? param-de-read) (do (dar-error 16 (amb 1)) [nil amb]) ; Syntax error
:else (leer-data param-de-read (drop (amb 5) (amb 4)) amb))
;; )
)
([variables entradas amb]
;; (prn (pr-str "leer-data triadico: variables=" variables " entradas=" entradas " amb=" amb))
(cond
(empty? variables) [:sin-errores amb]
(empty? entradas) (do (dar-error 42 (amb 1)) [:error-parcial amb]) ; Out of data error
:else (let [res (ejecutar-asignacion (list (first variables) '= (if (variable-string? (first variables)) (str (first entradas)) (if (= (first entradas) "") 0 (first entradas)))) amb)]
(if (nil? res)
[nil amb]
(if (or (= (count (next variables)) 1)
(and (> (count (next variables)) 1) (not= (fnext variables) (symbol ","))))
(do (dar-error 16 (amb 1)) [:error-parcial res]) ; Syntax error
(recur (nnext variables) (next entradas) (assoc res 5 (inc (res 5))))))))
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; leer-con-enter: recibe una lista con una cadena opcional
; seguida de variables separadas por comas y un ambiente, y
; retorna una dupla (un vector) con un resultado (usado luego
; por evaluar-linea) y un ambiente actualizado incluyendo las
; variables cargadas con los valores leidos del teclado
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn leer-con-enter
([param-de-input amb]
(leer-con-enter param-de-input param-de-input amb))
([param-orig param-actualizados amb]
(let [prim-arg (first param-actualizados), es-cadena (string? prim-arg)]
(if (and es-cadena (not= (second param-actualizados) (symbol ";")))
(do (dar-error 16 (amb 1)) [nil amb]) ; Syntax error
(do (if es-cadena
(print prim-arg)
(print "? "))
(flush)
(if (= (first (amb 1)) :ejecucion-inmediata)
(do (dar-error 100 (amb 1)) [nil amb]) ; Illegal direct error
(let [variables (if es-cadena (nnext param-actualizados) param-actualizados),
valores (butlast (map clojure.string/trim (.split (apply str (.concat (read-line) ",.")) ","))),
entradas (map #(let [entr (try (clojure.edn/read-string %) (catch Exception e (str %)))] (if (number? entr) entr (clojure.string/upper-case (str %)))) valores)]
(if (empty? variables)
(do (dar-error 16 (amb 1)) [nil amb]) ; Syntax error
(leer-con-enter variables entradas param-orig param-actualizados amb amb))))))))
([variables entradas param-orig param-actualizados amb-orig amb-actualizado]
(cond
(and (empty? variables) (empty? entradas)) [:sin-errores amb-actualizado]
(and (empty? variables) (not (empty? entradas))) (do (println "?EXTRA IGNORED") (flush) [:sin-errores amb-actualizado])
(and (not (empty? variables)) (empty? entradas)) (leer-con-enter param-orig (concat (list "?? " (symbol ";")) variables) amb-actualizado)
(and (not (variable-string? (first variables))) (string? (first entradas))) (do (println "?REENTER") (flush) (leer-con-enter param-orig param-orig amb-orig))
:else (let [res (ejecutar-asignacion (list (first variables) '= (if (variable-string? (first variables)) (str (first entradas)) (first entradas))) amb-actualizado)]
(if (nil? res)
[nil amb-actualizado]
(if (or (= (count (next variables)) 1)
(and (> (count (next variables)) 1) (not= (fnext variables) (symbol ","))))
(do (dar-error 16 (amb-actualizado 1)) [:error-parcial res]) ; Syntax error
(recur (nnext variables) (next entradas) param-orig param-actualizados amb-orig res))))))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; retornar-al-for: implementa la sentencia NEXT, retornando una
; dupla (un vector) con un resultado (usado luego por
; evaluar-linea) y un ambiente actualizado con el nuevo valor
; de la variable de control
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn retornar-al-for [amb var-next]
;; (prn (pr-str "retornar-al-for: amb=" amb " var-next=" var-next))
(if (empty? (amb 3))
(do (dar-error 0 (amb 1)) [nil amb]) ; Next without for error
(let [datos-for (peek (amb 3)),
var-for (nth datos-for 0),
valor-final (nth datos-for 1),
valor-step (nth datos-for 2),
origen (nth datos-for 3)]
(if (and (some? var-next) (not= var-next var-for))
(retornar-al-for (assoc amb 3 (pop (amb 3))) var-next)
(let [var-actualizada (+ (calcular-expresion (list var-for) amb) valor-step),
res (ejecutar-asignacion (list var-for '= var-actualizada) amb)]
(if (or (and (neg? valor-step) (>= var-actualizada valor-final))
(and (pos? valor-step) (<= var-actualizada valor-final)))
[:for-inconcluso (assoc res 1 [(origen 0) (dec (origen 1))])]
[:sin-errores (assoc res 3 (pop (amb 3)))])))))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; continuar-programa: recibe un ambiente que fue modificado por
; GOTO o GOSUB y continua la ejecucion del programa a partir de
; ese ambiente
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn continuar-programa [amb]
(ejecutar-programa amb (buscar-lineas-restantes amb))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ejecutar-programa: recibe un ambiente e inicia la ejecucion
; del programa a partir de ese ambiente
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn ejecutar-programa
([amb]
(let [ini [(amb 0) (amb 1) [] [] (vec (extraer-data (amb 0))) 0 {}]] ; [(prog-mem) [prog-ptrs] [gosub-return-stack] [for-next-stack] [data-mem] data-ptr {var-mem}]
(ejecutar-programa ini (buscar-lineas-restantes ini))))
([amb prg]
(if (or (nil? prg) (= (first (amb 1)) :ejecucion-inmediata))
[:sin-errores amb]
(let [antes (assoc amb 1 [(ffirst prg) (second (amb 1))]), res (evaluar-linea (nfirst prg) antes), nuevo-amb (second res)]
(cond (nil? (first res)) [nil amb] ; hubo error total
(= (first res) :error-parcial) [nil (second res)] ; hubo error parcial
:else (let [proximo (if (and (= (first (antes 1)) (first (nuevo-amb 1))) (not= (first res) :for-inconcluso))
(next prg) ; no hubo quiebre de secuencia
(buscar-lineas-restantes nuevo-amb)),
nueva-posic (if (nil? proximo) (nuevo-amb 1) [(ffirst proximo) (count (expandir-nexts (nfirst proximo)))])]
(recur (assoc nuevo-amb 1 nueva-posic) proximo))))))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; mostrar-listado: recibe la representacion intermedia de un
; programa y lo lista usando la representacion normal
; (usualmente mas legible que la ingresada originalmente)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn mostrar-listado
([lineas]
(if (empty? lineas)
nil
(mostrar-listado (next lineas) (first lineas))))
([lineas sentencias]
(if (empty? sentencias)
(do (prn) (mostrar-listado lineas))
(mostrar-listado lineas (next sentencias) (first sentencias))))
([lineas sentencias elementos]
(if (and (not (seq? elementos)) (integer? elementos))
(do (pr elementos) (print " ") (mostrar-listado lineas sentencias))
(if (empty? elementos)
(do (if (not (empty? sentencias)) (print ": "))
(mostrar-listado lineas sentencias))
(do (pr (first elementos))
(if (not (or (contains? #{(symbol "(") (symbol ",") (symbol ";")} (first elementos))
(contains? #{(symbol ")") (symbol ",") (symbol ";")} (fnext elementos))
(nil? (fnext elementos)))) (print " "))
(recur lineas sentencias (next elementos))))))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; cargar-arch: recibe un nombre de archivo y retorna la
; representacion intermedia del codigo contenido en el
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn cargar-arch [nom nro-linea]
(if (.exists (clojure.java.io/file nom))
(remove empty? (with-open [rdr (clojure.java.io/reader nom)] (doall (map string-a-tokens (line-seq rdr)))))
(dar-error 6 nro-linea)) ; File not found
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; grabar-arch: recibe un nombre de archivo, graba en el
; el listado del programa usando la representacion normal y
; retorna el ambiente
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn grabar-arch [nom amb]
(let [arch (clojure.java.io/writer nom)]
(do (binding [*out* arch] (mostrar-listado (amb 0)))
(.close arch)
amb))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; calcular-expresion: recibe una expresion y un ambiente, y
; retorna el valor de la expresion, por ejemplo:
; user=> (calcular-expresion '(X + 5) ['((10 (PRINT X))) [10 1] [] [] [] 0 '{X 2}])
; 7
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn calcular-expresion [expr amb]
;; (prn (pr-str "calcular-expresion: expr=" expr " amb=" amb)) ;@tbotalla
;; (spy2 "calcular-expresion respuesta=" (calcular-rpn (spy (shunting-yard (spy (desambiguar (spy (preprocesar-expresion expr amb) ) ) ) ) ) (amb 1)) )
;; (spy2 "calcular-expresion respuesta=" (calcular-rpn (shunting-yard (desambiguar (preprocesar-expresion expr amb))) (amb 1)) )
(calcular-rpn (shunting-yard (desambiguar (preprocesar-expresion expr amb))) (amb 1))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; desambiguar-mas-menos: recibe una expresion y la retorna sin
; los + unarios y con los - unarios reemplazados por -u
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn desambiguar-mas-menos
([expr] (desambiguar-mas-menos expr nil []))
([expr ant res]
(if (nil? expr)
(remove nil? res)
(let [act (first expr), nuevo (if (or (nil? ant) (and (symbol? ant) (operador? ant)) (= (str ant) "(") (= (str ant) ","))
(case act
+ nil
- '-u
act)
act)]
(recur (next expr) act (conj res nuevo)))))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; desambiguar-mid: recibe una expresion y la retorna con los
; MID$ ternarios reemplazados por MID3$
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn desambiguar-mid
([expr]
(cond
(contains? (set expr) 'MID$) (desambiguar-mid expr 0 (count expr) 0 0 0 true)
(contains? (set expr) 'MID2$) (apply list (replace '{MID2$ MID$} expr))
:else (apply list expr)))
([expr act fin pos cont-paren cont-comas buscando]
(if (= act fin)
(desambiguar-mid expr)
(let [nuevo (nth expr act)]
(cond
(and (= nuevo 'MID$) buscando) (recur expr (inc act) fin act cont-paren cont-comas false)
(and (= nuevo (symbol "(")) (not buscando)) (recur expr (inc act) fin pos (inc cont-paren) cont-comas buscando)
(and (= nuevo (symbol ")")) (not buscando))
(if (= cont-paren 1)
(if (= cont-comas 2)
(recur (assoc (vec expr) pos 'MID3$) (inc act) fin 0 0 0 true)
(recur (assoc (vec expr) pos 'MID2$) (inc act) fin 0 0 0 true))
(recur expr (inc act) fin pos (dec cont-paren) cont-comas buscando))
(and (= nuevo (symbol ",")) (= cont-paren 1)) (recur expr (inc act) fin pos cont-paren (inc cont-comas) buscando)
:else (recur expr (inc act) fin pos cont-paren cont-comas buscando)))))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; shunting-yard: implementa el algoritmo del Patio de Maniobras
; de Dijkstra que convierte una expresion a RPN (Reverse Polish
; Notation), por ejemplo:
; user=> (shunting-yard '(1 + 2))
; (1 2 +)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn shunting-yard [tokens]
(remove #(= % (symbol ","))
(flatten
(reduce
(fn [[rpn pila] token]
(let [op-mas? #(and (some? (precedencia %)) (>= (precedencia %) (precedencia token)))
no-abre-paren? #(not= (str %) "(")]
(cond
(= (str token) "(") [rpn (cons token pila)]
(= (str token) ")") [(vec (concat rpn (take-while no-abre-paren? pila))) (rest (drop-while no-abre-paren? pila))]
(some? (precedencia token)) [(vec (concat rpn (take-while op-mas? pila))) (cons token (drop-while op-mas? pila))]
:else [(conj rpn token) pila])))
[[] ()]
tokens)))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; calcular-rpn: Recibe una expresion en RPN y un numero de linea
; y retorna el valor de la expresion o un mensaje de error en la
; linea indicada
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn calcular-rpn [tokens nro-linea]
;; (prn "calcular-rpn: tokens=" tokens " nro-linea=" nro-linea)
(try
;; (spy2 "resultado calcular-rpn="
(let [resu-redu
(reduce
(fn [pila token]
(let [ari (aridad token),
resu (eliminar-cero-decimal
(case ari
1 (aplicar token (first pila) nro-linea)
2 (aplicar token (second pila) (first pila) nro-linea)
3 (aplicar token (nth pila 2) (nth pila 1) (nth pila 0) nro-linea)
token))]
(if (nil? resu)
(reduced resu)
(cons resu (drop ari pila)))))
[] tokens)]
(if (> (count resu-redu) 1)
(dar-error 16 nro-linea) ; Syntax error
(first resu-redu)))
;; )
(catch NumberFormatException e 0)
(catch ClassCastException e (dar-error 163 nro-linea)) ; Type mismatch error
(catch UnsupportedOperationException e (dar-error 163 nro-linea)) ; Type mismatch error
(catch IllegalArgumentException e (dar-error 69 nro-linea)) ; Overflow error
(catch Exception e (dar-error 16 nro-linea))) ; Syntax error
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; imprimir: recibe una lista de expresiones (separadas o no
; mediante puntos y comas o comas) y un ambiente, y las muestra
; interpretando los separadores como tabulaciones (las comas) o
; concatenaciones (los puntos y comas). Salvo cuando la lista
; termina en punto y coma, imprime un salto de linea al terminar
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn imprimir
([v]
(let [expresiones (v 0), amb (v 1)]
;; (prn (pr-str "imprimir monadico: expresiones=" expresiones " amb=" amb)) ;@tbotalla
(cond
(empty? expresiones) (do (prn) (flush) :sin-errores)
(and (empty? (next expresiones)) (= (first expresiones) (list (symbol ";")))) (do (pr) (flush) :sin-errores)
(and (empty? (next expresiones)) (= (first expresiones) (list (symbol ",t")))) (do (printf "\t\t") (flush) :sin-errores)
(= (first expresiones) (list (symbol ";"))) (do (pr) (flush) (recur [(next expresiones) amb]))
(= (first expresiones) (list (symbol ",t"))) (do (printf "\t\t") (flush) (recur [(next expresiones) amb]))
:else (let [resu (eliminar-cero-entero (calcular-expresion (first expresiones) amb))]
;; (prn (pr-str "imprimir monadico: resultado calcular-expresion=" (calcular-expresion (first expresiones) amb))) ;@tbotalla
;; (prn (pr-str "imprimir monadico: resu=" resu)) ;@tbotalla
(if (nil? resu)
resu
(do (print resu) (flush) (recur [(next expresiones) amb])))))))
([lista-expr amb]
;; (prn (pr-str "imprimir diadico: lista-expr=" lista-expr " amb=" amb)) ;@tbotalla
(let [nueva (cons (conj [] (first lista-expr)) (rest lista-expr)),
variable? #(or (variable-integer? %) (variable-float? %) (variable-string? %)),
funcion? #(and (> (aridad %) 0) (not (operador? %))),
interc (reduce #(if (and (or (number? (last %1)) (string? (last %1)) (variable? (last %1)) (= (symbol ")") (last %1)))
(or (number? %2) (string? %2) (variable? %2) (funcion? %2) (= (symbol "(") %2)))
(conj (conj %1 (symbol ";")) %2) (conj %1 %2)) nueva),
ex (partition-by #(= % (symbol ",t")) (desambiguar-comas interc)),
expresiones (apply concat (map #(partition-by (fn [x] (= x (symbol ";"))) %) ex))]
;; (prn (pr-str "imprimir diadico: nueva=" nueva " variable?=" variable? " funcion?=" funcion? " interc=" interc " ex=" ex " expresiones=" expresiones)) ;@tbotalla
(imprimir [expresiones amb])))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; desambiguar-comas: recibe una expresion en forma de lista y
; la devuelve con las comas que esten afuera de los pares de
; parentesis remplazadas por el simbolo ,t (las demas, que se
; usan para separar argumentos, se mantienen intactas)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn desambiguar-comas
([lista-expr]
(desambiguar-comas lista-expr 0 []))
([lista-expr cont-paren res]
(if (nil? lista-expr)
res
(let [act (first lista-expr),
paren (cond
(= act (symbol "(")) (inc cont-paren)
(= act (symbol ")")) (dec cont-paren)
:else cont-paren),
nuevo (if (and (= act (symbol ",")) (zero? paren)) (symbol ",t") act)]
(recur (next lista-expr) paren (conj res nuevo)))))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A PARTIR DE ESTE PUNTO HAY QUE COMPLETAR LAS FUNCIONES DADAS ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; evaluar: ejecuta una sentencia y retorna una dupla (un vector)
; con un resultado (usado luego por evaluar-linea) y un ambiente
; actualizado
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn evaluar [sentencia amb]
;; (prn (pr-str "evaluar: sentencia=" sentencia " amb=" amb))
(if (or (contains? (set sentencia) nil) (and (palabra-reservada? (first sentencia)) (= (second sentencia) '=)))
(do (dar-error 16 (amb 1)) [nil amb]) ; Syntax error
(case (first sentencia)
PRINT (let [args (next sentencia), resu (imprimir args amb)]
(if (and (nil? resu) (some? args))
[nil amb]
[:sin-errores amb]))
LOAD (if (= (first (amb 1)) :ejecucion-inmediata)
(let [nuevo-amb (cargar-arch (apply str (next sentencia)) (amb 1))]
(if (nil? nuevo-amb)
[nil amb]
[:sin-errores [nuevo-amb [:ejecucion-inmediata 0] [] [] [] 0 {}]])) ; [(prog-mem) [prog-ptrs] [gosub-return-stack] [for-next-stack] [data-mem] data-ptr {var-mem}]
(do (dar-error 200 (amb 1)) [nil amb])) ; Load within program error
SAVE (if (= (first (amb 1)) :ejecucion-inmediata)
(let [resu (grabar-arch (apply str (next sentencia)) amb)]
(if (nil? resu)
[nil amb]
[:sin-errores amb]))
(do (dar-error 201 (amb 1)) [nil amb])) ; Save within program error
REM [:omitir-restante amb]
NEW [:sin-errores ['() [:ejecucion-inmediata 0] [] [] [] 0 {}]] ; [(prog-mem) [prog-ptrs] [gosub-return-stack] [for-next-stack] [data-mem] data-ptr {var-mem}]
RUN (cond
(empty? (amb 0)) [:sin-errores amb] ; no hay programa
(= (count sentencia) 1) (ejecutar-programa (assoc amb 1 [(ffirst (amb 0)) (count (expandir-nexts (nfirst (amb 0))))])) ; no hay argumentos
(= (count (next sentencia)) 1) (ejecutar-programa (assoc amb 1 [(fnext sentencia) (contar-sentencias (fnext sentencia) amb)])) ; hay solo un argumento
:else (do (dar-error 16 (amb 1)) [nil amb])) ; Syntax error
GOTO (let [num-linea (if (some? (second sentencia)) (second sentencia) 0)]
;; GOTO (let [num-linea (spy2 "evaluar(GOTO):" (if (some? (second sentencia)) (second sentencia) 0) )]
(if (not (contains? (into (hash-set) (map first (amb 0))) num-linea))
(do (dar-error 90 (amb 1)) [nil amb]) ; Undef'd statement error
(let [nuevo-amb (assoc amb 1 [num-linea (contar-sentencias num-linea amb)])]
(if (= (first (amb 1)) :ejecucion-inmediata)
(continuar-programa nuevo-amb)
[:omitir-restante nuevo-amb]))))
IF (let [separados (split-with #(not (contains? #{"THEN" "GOTO"} (str %))) (next sentencia)),
condicion-de-if (first separados),
resto-if (second separados),
sentencia-de-if (cond
(= (first resto-if) 'GOTO) resto-if
(= (first resto-if) 'THEN) (if (number? (second resto-if))
(cons 'GOTO (next resto-if))
(next resto-if))
:else (do (dar-error 16 (amb 1)) nil)), ; Syntax error
resu (calcular-expresion condicion-de-if amb)]
;; resu (spy2 "evaluar(IF): resu=" (calcular-expresion condicion-de-if amb) ) ]
(if (zero? resu)
[:omitir-restante amb]
(recur sentencia-de-if amb)))
INPUT (leer-con-enter (next sentencia) amb)
ON (let [separados (split-with #(not (contains? #{"GOTO" "GOSUB"} (str %))) (next sentencia)),
indice-de-on (calcular-expresion (first separados) amb),
sentencia-de-on (first (second separados)),
destino-de-on (seleccionar-destino-de-on (next (second separados)) indice-de-on amb)]
(cond
(nil? destino-de-on) [nil amb]
(= destino-de-on :omitir-restante) [:sin-errores amb]
:else (recur (list sentencia-de-on destino-de-on) amb)))
GOSUB (let [num-linea (if (some? (second sentencia)) (second sentencia) 0)]
(if (not (contains? (into (hash-set) (map first (amb 0))) num-linea))
(do (dar-error 90 (amb 1)) [nil amb]) ; Undef'd statement error
(let [pos-actual (amb 1),
nuevo-amb (assoc (assoc amb 1 [num-linea (contar-sentencias num-linea amb)]) 2 (conj (amb 2) pos-actual))]
(if (= (first (amb 1)) :ejecucion-inmediata)
(continuar-programa nuevo-amb)
[:omitir-restante nuevo-amb]))))
RETURN (continuar-linea amb)
FOR (let [separados (partition-by #(contains? #{"TO" "STEP"} (str %)) (next sentencia))]
(if (not (or (and (= (count separados) 3) (variable-float? (ffirst separados)) (= (nth separados 1) '(TO)))
(and (= (count separados) 5) (variable-float? (ffirst separados)) (= (nth separados 1) '(TO)) (= (nth separados 3) '(STEP)))))
(do (dar-error 16 (amb 1)) [nil amb]) ; Syntax error
(let [valor-final (calcular-expresion (nth separados 2) amb),
valor-step (if (= (count separados) 5) (calcular-expresion (nth separados 4) amb) 1)]
(if (or (nil? valor-final) (nil? valor-step))
[nil amb]
(recur (first separados) (assoc amb 3 (conj (amb 3) [(ffirst separados) valor-final valor-step (amb 1)])))))))
NEXT (if (<= (count (next sentencia)) 1)
(retornar-al-for amb (fnext sentencia))
(do (dar-error 16 (amb 1)) [nil amb])) ; Syntax error
LIST (mostrar-listado (amb 0)) ; Muestra las sentencias del programa, las cuales estan en la 1° posicion del ambiente
LET (evaluar (next sentencia) amb) ; Para el LET simplemente excluye la palabra y evalua la asignacion
END [nil amb] ; Mantiene el ambiente e ignora la sentencia
;; END [:sin-errores amb] ; Mantiene el ambiente e ignora la sentencia
;; READ (prn "evaluar(READ):") ; leer-data recibe los valores separados por "," despues del DATA
;; READ (spy2 "evaluar(READ): respuesta=" (leer-data (spy (next sentencia) ) amb) ) ; leer-data recibe los valores separados por "," despues del DATA
READ (leer-data (next sentencia) amb) ; leer-data recibe los valores separados por "," despues del DATA
;; READ (leer-data (rest sentencia) amb)
;; RESTORE (assoc amb 5 0) ; Retorna el puntero del DATA (data-ptr === amb[5]) al principio
RESTORE [:sin-errores (assoc amb 5 0)]
CLEAR (assoc amb 6 {}); Borra por completo el mapa de variables (var-mem === amb[6])
;; DATA (prn (pr-str "evaluar(DATA) amb=" amb " sentencia=" sentencia)) ; NUEVO
;; DATA [:sin-errores amb] ; NUEVO
(if (= (second sentencia) '=)
(let [resu (ejecutar-asignacion sentencia amb)]
(if (nil? resu)
[nil amb]
[:sin-errores resu]))
(do (dar-error 16 (amb 1)) [nil amb]))
)
) ; Syntax error
; Faltantes identificadas:
; LIST (hecha), LET (hecha), END (hecha), READ (hecha), RESTORE (hecha), CLEAR (hecha, no se usa en los ejemplos), DATA, ? (ver si hay que incluirlo al ?)
; [(prog-mem) [prog-ptrs] [gosub-return-stack] [for-next-stack] [data-mem] data-ptr {var-mem}]
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; aplicar: aplica un operador a sus operandos y retorna el valor
; resultante (si ocurre un error, muestra un mensaje y retorna
; nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn aplicar
([operador operando nro-linea]
(if (nil? operando)
(dar-error 16 nro-linea) ; Syntax error
(case operador
-u (- operando)
LEN (count operando)
STR$ (if (not (number? operando)) (dar-error 163 nro-linea) (eliminar-cero-entero operando)) ; Type mismatch error
CHR$ (if (or (< operando 0) (> operando 255)) (dar-error 53 nro-linea) (str (char operando)))
;; ATN (if (not (number? operando)) (dar-error 163 nro-linea) (Math/atan operando)) ; Type mismatch error ; Llama a la funcion de java atan del package Math
ATN (if (not (number? operando)) (dar-error 163 nro-linea) (Math/atan operando)) ; Type mismatch error ; Llama a la funcion de java atan del package Math
INT (if (not (number? operando)) (dar-error 163 nro-linea) (int operando)) ; Type mismatch error
SIN (if (not (number? operando)) (dar-error 163 nro-linea) (Math/sin operando)) ; Type mismatch error ; Llama a la funcion de java sin del package Math
ASC (if (not (string? operando)) (dar-error 163 nro-linea) (int (first operando))) ; Type mismatch error ; int convierte ya al ASCII a partir de un string
))) ; Illegal quantity error
;; (def funciones_aridad_1
;; #{
;; "ATN" hecha
;; "INT" hecha
;; "SIN" hecha
;; "LEN" no tocar
;; "ASC" hecha
;; "CHR$" no tocar
;; "STR$" no tocar
;; }
;; )
([operador operando1 operando2 nro-linea]
(if (or (nil? operando1) (nil? operando2))
(dar-error 16 nro-linea) ; Syntax error
(if (= operador (symbol "^"))
(Math/pow operando1 operando2)
(case operador
= (if (and (string? operando1) (string? operando2))
(if (= operando1 operando2) 1 0)
(if (= (+ 0 operando1) (+ 0 operando2)) 1 0))
+ (if (and (string? operando1) (string? operando2))
(str operando1 operando2)
(+ operando1 operando2))
/ (if (= operando2 0) (dar-error 133 nro-linea) (float (/ operando1 operando2))) ; Division by zero error
AND (let [op1 (+ 0 operando1), op2 (+ 0 operando2)] (if (and (not= op1 0) (not= op2 0)) 1 0))
MID$ (if (< operando2 1)
(dar-error 53 nro-linea) ; Illegal quantity error
(let [ini (dec operando2)] (if (>= ini (count operando1)) "" (subs operando1 ini))))
* (if (and (number? operando1) (number? operando2))
(* operando1 operando2)
(dar-error 163 nro-linea))
;; * (if (and (number? operando1) (number? operando2))
;; (* operando1 operando2)
;; (dar-error 163 nro-linea))
- (if (and (number? operando1) (number? operando2))
(- operando1 operando2)
(dar-error 163 nro-linea))
(symbol "^") (if (and (number? operando1) (number? operando2)) ; TODO: revisar esto
(Math/pow operando1 operando2)
(dar-error 163 nro-linea))
OR (let [op1 (+ 0 operando1), op2 (+ 0 operando2)] (if (or (not= op1 0) (not= op2 0)) 1 0))
<> (if (and (string? operando1) (string? operando2))
(if (not= operando1 operando2) 1 0)
(if (not= (+ 0 operando1) (+ 0 operando2)) 1 0))
< (if (and (number? operando1) (number? operando2))
(if (< operando1 operando2) 1 0)
(dar-error 163 nro-linea))
<= (if (and (number? operando1) (number? operando2))
(if (<= operando1 operando2) 1 0)
(dar-error 163 nro-linea))
> (if (and (number? operando1) (number? operando2))
(if (> operando1 operando2) 1 0)
(dar-error 163 nro-linea))
>= (if (and (number? operando1) (number? operando2))
(if (>= operando1 operando2) 1 0)
(dar-error 163 nro-linea))
))
)
)
;; (def funciones_aridad_2
;; #{
;; "*" hecha
;; "/" no tocar
;; "+" no tocar
;; "-" hecha
;; "^" hecha
;; "OR" hecha
;; "AND" no tocar
;; "=" no tocar
;; "<>" hecha
;; "<" hecha
;; "<=" hecha
;; ">" hecha
;; ">=" hecha
;; "MID$" no tocar
;; }
;; )
([operador operando1 operando2 operando3 nro-linea]
(if (or (nil? operando1) (nil? operando2) (nil? operando3)) (dar-error 16 nro-linea) ; Syntax error
(case operador
MID3$ (let [tam (count operando1), ini (dec operando2), fin (+ (dec operando2) operando3)]
(cond
(or (< operando2 1) (< operando3 0)) (dar-error 53 nro-linea) ; Illegal quantity error
(>= ini tam) ""
(>= fin tam) (subs operando1 ini tam)
:else (subs operando1 ini fin)
)
)
)
)
)
;; (def funciones_aridad_3
;; #{
;; "MID3$" no tocar
;; }
;; )
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; A PARTIR DE ESTE PUNTO HAY QUE IMPLEMENTAR LAS FUNCIONES DADAS ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; @tbotalla
;; Conjunto de palabras reservadas
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def palabras_reservadas
#{
"INPUT" ;
"PRINT" ;
;; "?" ; TODO: verificar
"DATA" ;
"READ" ;
"REM" ;
"RESTORE" ;
"CLEAR" ;
"LET" ;
"LIST" ;
"NEW" ;
"RUN" ;
"END" ;
"FOR" ;
"TO" ;
"NEXT" ;
"STEP" ;
"GOSUB" ;
"RETURN" ;
"GOTO" ;
"IF" ;
"THEN" ;
"ON" ;
;; "ENV" Son del interprete
;; "EXIT" Son del interprete
"ATN" ;
"INT" ;
"SIN" ;
"LEN" ;
"MID$" ;
"MID3$" ;
"ASC" ;
"CHR$" ;
"STR$" ;
"OR" ;
"AND" ;
"LOAD" ;
"SAVE" ;
}
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; @tbotalla
;; Conjunto de operadores
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def operadores
#{
'+ ;
'- ;
'* ;
'/ ;
(symbol "^") ;
'= ;
'<> ;
'< ;
'<= ;
'> ;
'>= ;
'AND ;
'OR ;
'?
}
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; @tbotalla
;; Simbolos invalidos
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; #"\!|\"|\#|\&|\'|\:|\{|\}|\[|\]|\_|\|\~|\%|\$"]
(def simbolos_invalidos
#{
"!"
"&"
"\\"
"_"
"{"
"}"
"|"
"~"
}
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; palabra-reservada?: predicado para determinar si un
; identificador es una palabra reservada, por ejemplo:
; user=> (palabra-reservada? 'REM)
; true
; user=> (palabra-reservada? 'SPACE)
; false
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn palabra-reservada? [x]
;; (prn (pr-str "palabra-reservada: x=" x))
;; (spy2 "respuesta palabra-reservada? :"
(contains? palabras_reservadas (clojure.string/upper-case x))
;; )
;; (case x
;; ;; LOAD true ; Son de Apple DOS 3.3
;; ;; SAVE true ; Son de Apple DOS 3.3
;; INPUT true ;
;; PRINT true ;
;; ? true ;
;; DATA true
;; READ true ;
;; REM true ;
;; RESTORE true ;
;; CLEAR true ;
;; LET true ;
;; LIST true ;
;; NEW true ;
;; RUN true ;
;; END true ;
;; FOR true ;
;; TO true ;
;; NEXT true ;
;; STEP true ;
;; GOSUB true ;
;; RETURN true ;
;; GOTO true ;
;; IF true ;
;; THEN true ;
;; ON true ;
;; ;; ENV true ; Son del interprete
;; ;; EXIT true ; Son del interprete
;; ATN true
;; INT true
;; SIN true
;; LEN true
;; MID$ true
;; ASC true
;; CHR$ true
;; STR$ true
;; ;; + true
;; ;; - true
;; ;; * true
;; ;; / true
;; ;; ; ^ true
;; ;; = true
;; ;; <> true
;; ;; < true
;; ;; <= true
;; ;; > true
;; ;; >= true
;; ;; AND true
;; ;; OR true
;; false
;; )
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; operador?: predicado para determinar si un identificador es un
; operador, por ejemplo:
; user=> (operador? '+)
; true
; user=> (operador? (symbol "+"))
; true
; user=> (operador? (symbol "%"))
; false
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn operador? [x]
;; (prn "operador? : x=" x)
;; (spy2 "resultado operador?: "
;; (contains? operadores (clojure.string/upper-case x))
;; (if
;; (nil? x)
;; false
(contains? operadores x)
;; )
;; (contains? operadores x)
;; )
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; @tbotalla
; Devuelve nil si el parametro recibido es un simbolo invalido,
; en otro caso devuelve el parametro recibido
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn es-invalido? [simbolo]
;; (prn (pr-str "es-invalido?: simbolo=" simbolo))
(if
(nil? simbolo)
nil
(if
(contains? simbolos_invalidos (clojure.string/upper-case simbolo))
nil
simbolo
)
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; @tbotalla
; Devuelve true si el simbolo es una variable
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn es-variable? [simbolo]
(or
(variable-float? simbolo)
(variable-integer? simbolo)
(variable-string? simbolo)
false
)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; anular-invalidos: recibe una lista de simbolos y la retorna con
; aquellos que son invalidos reemplazados por nil, por ejemplo:
; user=> (anular-invalidos '(IF X & * Y < 12 THEN LET ! X = 0))
; (IF X nil * Y < 12 THEN LET nil X = 0)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn anular-invalidos [sentencia]
;; (prn (pr-str "anular-invalidos: sentencia=" sentencia))
(map es-invalido? sentencia) ; Solo borra los caracteres no aceptados
)