This file is indexed.

/usr/share/hol88-2.02.19940316/lisp/f-tml.l is in hol88-source 2.02.19940316-28.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;                             HOL 88 Version 2.0                          ;;;
;;;                                                                         ;;;
;;;   FILE NAME:        f-tml.l                                             ;;;
;;;                                                                         ;;;
;;;   DESCRIPTION:      Top level ML read-eval-print loop                   ;;;
;;;                                                                         ;;;
;;;   USES FILES:       f-franz.l (or f-cl.l), f-constants.l, f-macro.l     ;;;
;;;                                                                         ;;;
;;;                     University of Cambridge                             ;;;
;;;                     Hardware Verification Group                         ;;;
;;;                     Computer Laboratory                                 ;;;
;;;                     New Museums Site                                    ;;;
;;;                     Pembroke Street                                     ;;;
;;;                     Cambridge  CB2 3QG                                  ;;;
;;;                     England                                             ;;;
;;;                                                                         ;;;
;;;   COPYRIGHT:        University of Edinburgh                             ;;;
;;;   COPYRIGHT:        University of Cambridge                             ;;;
;;;   COPYRIGHT:        INRIA                                               ;;;
;;;                                                                         ;;;
;;;   REVISION HISTORY: Original code: tml (lisp 1.6) part of Edinburgh     ;;;
;;;                     LCF by M. Gordon, R. Milner and C. Wadsworth (1978) ;;;
;;;                     Transported by G. Huet in Maclisp on Multics, Fall  ;;;
;;;                     1981                                                ;;;
;;;                                                                         ;;;
;;;                     V2.1 : begin and end renamed as ml-begin and ml-end ;;;
;;;                                                                         ;;;
;;;                     V2.2 : errset and err replaced with tag and new-exit;;;
;;;                         top1, ctrlgfn no more used                      ;;;
;;;                                                                         ;;;
;;;                     V2.3 : compiler added  July 82   GH                 ;;;
;;;                                                                         ;;;
;;;                     V3.1 : optimization of lisp code L. Paulson         ;;;
;;;                                                                         ;;;
;;;                     V3.2 : compatibility VAX-Unix/Multics               ;;;
;;;                                                                         ;;;
;;;                     V4.2 : message functions gone                       ;;;
;;;                                                                         ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(eval-when (compile) 
   #+franz (include "lisp/f-franz")
   (include "lisp/f-constants")
   (include "lisp/f-macro")
   (special %char-buffer %parse-tree-buffer |%abort_when_fail-flag| %turnstile
      |%print_lib-flag| %prompt-string %libraries |%print_load-flag|
      |%compile_on_the_fly-flag| |%file_load_msg-flag| %lib-dir
      %pt1 |%print_parse_trees-flag| 
      %search-path %help-search-path %library-search-path))


#+franz
(declare
   (localf top%f
      istmlop
      isdefty
      isdecl
      istydecl
      okpass
      typechpt
      tranpt
      evalpr
      tmlloop
      extend-env
      setbindings
      updatevalues
      printresults
      printtime
      ml-begin
      ml-end
      compiloop
      parseml0))

;;;  Uses Manifests:  eof  [iox/din]
;;;                   nullty  [typeml]
;;;                   nill  [tran]

;;;  Sets Manifests:  initsection, initenv, nosecname

;;;  Uses Globals:  %f
;;;                 %emt, %temt  [typeml]
;;;                 |%print_load-flag|  [System load]
;;;                 ibase, base, *nopoint , %prompt-string [lisp/tml]
;;;  Globals:  %pt, %pt1, %ty, %pr, %val  [in top1/okpass]
;;;                 %sections, %dump

;;;  Specials:  %p, %thisdec, %thistydec, tenv


(eval-when (compile load eval)
   (defconstant initsection '%mustbeatom)
   (defconstant initenv (cons initsection nill))
   (defconstant nosecname '|<noname>|))         ; Value printed by begin/end

(eval-when (load)
   (when initial%load                              ;  Globals
      (setq global%env ())
      (setq %f nil)
      (setq %sections ())
      (setq %dump ())
      (setq |%timing-flag| nil)
      (setq %outport nil)
      (setq |%print_parse_trees-flag| nil)
      (setq |%abort_when_fail-flag| t)
      (setq |%compile_on_the_fly-flag| nil)))

;;;                  Error and message functions

;;; Added by MJCG on 7/4/1987

(defun hol-err (x) (throw-from tmllooptag "System"))

(defun lcferror (x)
   (let (#+franz (poport nil) #-franz (*standard-output* *terminal-io*))
      (llterpri) 
      (llprinc "Error in HOL system, please report it.")
      (llterpri)
      (llprinc (list "Diagnostic:" x))
      (llterpri)
      #+franz (baktrace)
      (hol-err %f)))                            ;lcferror

;;;                  Top level of ml interpreter

(defun top%f () (memq %f '(() load compile)))   ;top%f

(defun istmlop () (memq %head '(mk-begin mk-end)))      ;istmlop

(defun isdefty () (eq %head 'mk-deftype))               ;isdefty

(defun isdecl ()
   (memq %head
      '(mk-let mk-letref mk-letrec mk-abstype mk-absrectype))) ;isdecl

(defun istydecl ()
   (memq %head '(mk-type mk-rectype)))         ;isdecl

;;; MJCG 10.12.90 for Centaur:
;;; The parse tree in %pt seems to get corrupted destructively
;;; So a copy of the original is retained in %pt1
(defun okpass (pass)
   (catch-throw okpass  ; must be catch since throw may come from inside errset
      (let
         ((b
               (errortrap #'(lambda (errtok) "lisp error")
                  (case pass
                     (parse
                        (catch-throw parse
                           (setq %pt (parseml0))
                           (if |%print_parse_trees-flag| ; for Centaur!
                               (setq %pt1 (copy-tree %pt))) ; for Centaur!
                           (throw-from okpass nil)))
                     (typecheck
                        (catch-throw typecheck
                           (setq %ty (typechpt)) (throw-from okpass nil)))
                     (translation
                        (catch-throw translation
                           (setq %pr (tranpt)) (throw-from okpass nil)))
                     (evaluation
                        (catch-throw evaluation
                           (setq %val (evalpr)) (throw-from okpass nil)))
                     (evtmlop
                        (catch-throw evaluation
                           (setq %val (evtmlop %pt)) (throw-from okpass nil)))
                     (t (lcferror (cons pass '(unknown pass))))))))
         ;;; Fall through here if pass failed
         (llprinc
            (case pass
               (parse "parse")
               (typecheck "typecheck")
               (translation "translation")
               (evaluation "evaluation")
               (evtmlop "evaluation")))
         (llprinc " failed     ")
         (if b (llprinc b))
         (llterpri)
         (cond
            ((memq %f '(load compile))
               ;; Propagate failure if performing load or compile
               (putprop lastvalname () 'mlval)        ;to prevent abscope type
               (putprop lastvalname nullty 'mltype)   ;fix for automatic ending
               (throw-from loaderror nil))
            (|%abort_when_fail-flag|
               (quit 1))                              ; to abort when building
            (t (throw-from tmllooptag %f))))))


;;; Redefined below to cope with ML generated declarations
;;; (defun parseml0 () (gnt) (parseml 0))               ;parsml0

(defun typechpt () (typecheck %pt))             ;typechpt

(defun tranpt () (let ((%p ())) (tran %pt)))    ;tranpt


(defun evalpr ()
   (mapc #'eval %compfns)    ; perform the definitions
   ;; Compile the functions - unless the eval has compiled them already
   ;; No in-core compiler in franz
   #-franz
   (if (and %compfns |%compile_on_the_fly-flag|)
      (compile-functions-if-needed %compfns))
   ;; Retain compatibility with old franz versions. Do proper thing for CL
   #+franz (funcall `(lambda (%e) ,%pr) nil)
   #-franz
   (funcall
      ;; may not attempt to compile already-compiled functions in ANSI
      ;; standard CL. Check added - JAC 19.06.92
      (if (and (not (compiled-function-p %pr)) |%compile_on_the_fly-flag|)
         (compile nil %pr)
         %pr)
      nil))


;;; MJCG 29/11/88 for HOL88
;;; ML function for setting prompt string

(setq %prompt-string '|#|)

(defun ml-set_prompt (s)
   (prog1 %prompt-string (setq %prompt-string s)))

(dml |set_prompt| 1 ml-set_prompt (|string| -> |string|))


;;; MJCG 4/1/89 for HOL88
;;; ML function for changing theorem printing character (|-)

(setq %turnstile "|- ")
   
(defun ml-set_turnstile (s)
   (prog1 %turnstile (setq %turnstile s)))

(dml |set_turnstile| 1 ml-set_turnstile (|string| -> |string|))


;;; MJCG 5/2/89 for HOL88
;;; Function to load in hol-init.ml
;;; Sticks loadt`hol-init.ml` in the input buffer

(defun load-hol-init ()
   (let ((file (find-file "hol-init.ml")))
      (if (probe-file file)
         (setq
            %parse-tree-buffer 
            (list '(mk-appn (mk-var |loadt|) (mk-tokconst |hol-init|)))))))

;;; JVT 29/5/92 for HOL88
;;; read-HOLPATH reads in the environment variable HOLPATH (if present)
;;; to get a new root directory for the system without recourse to hol-init
;;; or a rebuild.

(defun read-HOLPATH ()
   #+unix (let ((varble #+franz (getenv 'HOLPATH)
                        #+kcl   (system:getenv "HOLPATH")
                        #+lucid (environment-variable "HOLPATH")
                        #+allegro (system:getenv "HOLPATH")))
               (cond ((or (eq varble '||) (null varble)) nil)
                     (t (setq %hol-dir varble)
                        (setq %lib-dir (concat varble "/Library"))
                        (setq %search-path (list '|| '|~/| (concat varble "/theories/")))
                        (setq %library-search-path (list (concat varble "/Library/")))
                        (setq %help-search-path (list (concat varble "/help/ENTRIES/")))))) 
                        
   #-unix nil
)

;;; Top-level entry to ML
;;; Sets time stamp to allow the generation of symbols unique to this session
;;; Necessary to avoid conflict when loading ML code
;;;    compiled in different sessions
;;; MJCG 29/11/88 for HOL88
;;; Made prompt the global %prompt-string, rather than local hard-wired #
;;; MJCG 5/2/89 for HOL88
;;; Added load-hol-init
;;; JVT 29/5/92 for HOL88
;;; Added read-HOLPATH

(defun tml ()
   (let ((base 10)
         (ibase 10)
         (*nopoint t)
         (%timestamp (mod (clock) 10000)))
      (setq fin-ligne t)
      (init-io)
      (banner)
      (incf %symcount (mod %timestamp 100))
      (read-HOLPATH)
      (load-hol-init)
      (catch-throw eof (tmlloop))
      (finalize-tml)))          ; before exiting from tml command loop


;;; Drop out of tml or a load back to tml - useful if you can't send eofs

(defun ml-dropout () (throw-from eof nil))

(dml |dropout| 0 ml-dropout (|void| -> |void|))


(dml |quit| 0 quit (|void| -> |void|))            ; quit


(defun tmlloop ()                                       ; Also used by load
   (while t (ml-read-eval-print)))


(defun ml-read-eval-print ()
   (errortrap
      #'(lambda (errtok) errtok)
      (catch-throw tmllooptag
         (and |%print_load-flag| (top%f) (llterpri))
         (let ((%thisdec ()) (%thistydec ()))
            (initlean)
            (okpass 'parse)
            (setq %head (car %pt))
            (if (istmlop)
               (okpass 'evtmlop)
               (progn
                  (okpass 'typecheck)
                  (okpass 'translation)
                  (let ((init-time (runtime10th))
                        (init-thms %thm-count))
                     (okpass 'evaluation)
                     (let ((final-time (runtime10th))
                           (final-thms %thm-count))
                        (updatetypes)    ;Uses %thisdec, %thistydec [typeml]
                        (updatevalues)
                        (printresults)
                        (printtime 
                           final-time init-time final-thms init-thms)))
                  ))))))                        ;tmlloop


;;; Insert new (mlname . lispname) pairs onto an alist
;;; For extending global environment

(defun extend-env (bvs lbpat env)
   (if (atom bvs)
      (if (eq bvs '%con)
         env
         (cons (cons bvs lbpat) env))
      (extend-env (cdr bvs) (cdr lbpat) 
         (extend-env (car bvs) (car lbpat) env))))      ;extend-env

;;; Execute set's to maintain top-level environment

(defun setbindings (newlb val)
   (if (atom newlb)
      (ifn (eq newlb '%con) (set newlb val))
      (progn
         (setbindings (car newlb) (car val))
         (setbindings (cdr newlb) (cdr val))))) ;setbindings

;;; Enter bindings in environment and store values in their Lisp atoms
;;; MJCG 9 November 1992. 
;;; Added check to suppress binding of "it" if it has been let-bound.

(defun updatevalues ()
   (cond
      ((isdefty))
      ((isdecl)
         (setq global%env (extend-env (car %val) new%%lb global%env))
         (setbindings new%%lb (cdr %val)))
      ((not(get-lisp-binding lastvalname))
         (putprop lastvalname %val 'mlval)
         (putprop lastvalname %ty 'mltype))))   ;updatevalues

;;; MJCG 11 May 1992. Eliminated third argument (ty) of prlet.
;;; This fixes a bug discovered by JG.
;;; prlet is defined in f-writml.l.
(defun printresults ()
   (cond
      ((not |%print_load-flag|)
         (unless %outport (llprinc '|.|)))
      ((isdefty) (prdefty %thistydec))
      ((istydecl) (prconstrs (cdr %thisdec)))
      ((isdecl) (prlet (car %val) (cdr %val)))
      (t (prvalty %val %ty))))          ;printresults

;;; Print runtime and GC time if |%timing-flag|

(defun printtime (final-times init-times final-thms init-thms)  
   (when |%print_load-flag|
      (let ((runtime (- (car final-times) (car init-times)))
            (gctime (- (cdr final-times) (cdr init-times))))
         (let ((seconds (truncate runtime 10)))
            (when |%timing-flag|
               (llprinc "Run time: ") (llprinc seconds)
               (llprinc ".") (llprinc (- runtime (* seconds 10)))
               (llprinc "s") (llterpri)))
         (ifn (zerop gctime)
            (let ((seconds (truncate gctime 10)))
               (when |%timing-flag|
                  (llprinc "Garbage collection time: ")
                  (llprinc seconds)
                  (llprinc ".") (llprinc (- gctime (* seconds 10)))
                  (llprinc "s") (llterpri))))
         (let ((thms (- final-thms init-thms)))
            (cond
               ((and |%timing-flag| (not (zerop thms)))
                  (llprinc "Intermediate theorems generated: ")
                  (llprinc thms)
                  (llterpri))))))) ; printtime

(defun evtmlop (pt)
   (case (car pt)
      (mk-begin (ml-begin (if (cdr pt) (cadr pt) nosecname)))
      (mk-end
         (ml-end
            (cond
               ((null (cdr pt))
                  (if %dump (car %dump)
                     (msg-failwith '|end| " not in a section")))
               ((assoc-equal (cadr pt) %dump))
               (t (msg-failwith '|end| "no section " (cadr pt))))))
      (t (lcferror (cons (car pt) '(not a tmlop))))))   ;evtmlop

(defun ml-begin (tok)
   (push (list tok %sections global%env %emt %temt %dump) %dump)
   (setq %sections t)
   (ifn %outport
      (when |%print_load-flag|
         (llprinc '|Section |) (llprinc tok)
         (llprinc '| begun|) (llterpri))))  ;ml-begin

(defun ml-end (x)
   (let
      ((tok (car x))
         (new-sections (cadr x))
         (new-global-env (caddr x))
         (new-emt (cadddr x))
         (new-temt (cadddr (cdr x)))
         (new-dump (cadddr (cddr x)))
         (tenv ()))
      (setq tenv new-temt)                    ;  for absscopechk
      (unless
         (catch-throw typecheck (typescopechk (get lastvalname 'mltype)))
         (failwith '|end|))     ; prevents result of section of local type
      (setq %sections new-sections)
      (setq global%env new-global-env)
      (setq %emt new-emt)
      (setq %temt new-temt)
      (setq %dump new-dump)
      (ifn %outport
         (when |%print_load-flag|
            (llprinc '|Section |) (llprinc tok)
            (llprinc '| ended|) (llterpri)))
      ))                                    ;ml-end


;;; MJCG 31/10/88 for HOL88
;;; Test whether a file name ends in `.ml`

(defun ends-in-ml (tok)
   (let ((l (nreverse (exploden tok))))
      (and (> (length l) 2)
         (= (car l) #/l)
         (= (cadr l) #/m)
         (= (caddr l) #/.))))


;;; Load one ml file. If there exists a compiled version, it will load
;;; it rather than the source version.
;;; Caution: even if the source is more recent.
;;;
;;; MJCG 31/10/88 for HOL88
;;; (fileexists '|m*| tok) case added
;;; find-file wrapped around fileof
;;; code to support loadt`foo.ml` added
;;; the resulting definition is inefficient, but disturbs the original
;;; code as little as possible (may optimise later)
;;; MJCG 10/2/90 for HOL88.1.12
;;; Test on |%file_load_msg-flag| added.

(setq |%file_load_msg-flag| t)

;;; Old version. Replaced on 6 April 1991 by
;;; Mark van der Voort's bugfix to handle .s in file names
;;; (See below)
;;; (defun ml-load (tok |%print_load-flag|)
;;;    (let
;;;       ((initial-nesting (length inputstack)) (%f 'load) (%dump ()))
;;;       (catch-throw eof
;;;          (catch-throw loaderror               ; catch failures inside load
;;;             (cond
;;;                ((not (filetokp 'ml tok))
;;;                   (msg-failwith '|load| tok " cannot be file name"))
;;;                ((and (not (ends-in-ml tok)) 
;;;                      (eq (file-ext (fileexists '|m*| tok)) '|o|))
;;;                   (throw-from eof
;;;                      (load (find-file (fileof 'code tok)))))
;;;                ((or (fileexists 'ml tok)
;;;                      (and (ends-in-ml tok)
;;;                         (fileexists 'ml (file-name tok))))
;;;                   (let ((%pt ()) (%ty ()) (%pr ()) (%val ()) (%head ()))
;;;                      (infilepush (find-file (fileof 'ml (file-name tok))))
;;;                      (tmlloop)))
;;;                (t
;;;                   (msg-failwith '|load| tok " ml file not found"))))
;;;          ;; an error occurred (before eof encountered) during file load
;;;          (if (> (length inputstack) initial-nesting) (infilepop))
;;;          (if %dump (ml-end (car (last %dump)))) ;close dangling sections
;;;          (msg-failwith '|load| tok))
;;;       ;; reached end of file without errors
;;;       (if %dump (ml-end (car (last %dump))))    ;close dangling sections
;;;       (if (> (length inputstack) initial-nesting) (infilepop))
;;;       (when (and |%print_load-flag| |%file_load_msg-flag|)
;;;          (llterpri) (llprinc "File ") (llprinc tok)
;;;          (llprinc " loaded") (llterpri))))     ;ml-load

;;; Following bugfix installed by MJCG for HOL88.1.13 (6 April 1991)
;;; Revised code supplied by Mark van der Voort.

;;; MvdV 04/02/91 for HOL88.1.11
;;; whenever a extensionless filename is given
;;; at the end of a path containing dots
;;; file-name will destruct this path instead of 
;;; delivering the whole file-name
;;;
;;; So the last two cases in the cond have been split

(defun ml-load (tok |%print_load-flag|)
   (let
      ((initial-nesting (length inputstack)) (%f 'load) (%dump ()))
      (catch-throw eof
         (catch-throw loaderror                 ; catch failures inside load
            (cond
	     ((not (filetokp 'ml tok))
	        (msg-failwith '|load| tok " cannot be file name"))
	     ((and (not (ends-in-ml tok)) 
              (eq (file-ext (fileexists '|m*| tok)) '|o|))
           (throw-from eof
              ;; tidied up conditional code and added :print nil and
              ;; :verbose nil to load - JAC 19.06.92
              #+lucid
              (let ((*load-binary-pathname-types*
                       (cons "o" *load-binary-pathname-types*)))
                 (fasload (find-file (fileof 'code tok))))
              #-lucid
              #-franz (load (find-file (fileof 'code tok)) :print nil :verbose nil)
              #+franz (load (find-file (fileof 'code tok)))
              ))
	     ((fileexists 'ml tok)
	         (let ((%pt ()) (%ty ()) (%pr ()) (%val ()) (%head ()))
		      (infilepush (find-file (fileof 'ml tok)))
;;;			                                ^place of bug
		      (tmlloop)))
	     ((and (ends-in-ml tok)
		   (fileexists 'ml (file-name tok)))
	         (let ((%pt ()) (%ty ()) (%pr ()) (%val ()) (%head ()))
		      (infilepush (find-file (fileof 'ml (file-name tok))))
		      (tmlloop)))
	     (t
	      (msg-failwith '|load| tok " ml file not found"))))
         ;; an error occurred (before eof encountered) during file load
         (if (> (length inputstack) initial-nesting) (infilepop))
         (if %dump (ml-end (car (last %dump)))) ;close dangling sections
         (msg-failwith '|load| tok))
      ;; reached end of file without errors
      (if %dump (ml-end (car (last %dump))))    ;close dangling sections
      (if (> (length inputstack) initial-nesting) (infilepop))
      (when |%print_load-flag|
         (llterpri) (llprinc "File ") (llprinc tok)
         (llprinc " loaded") (llterpri))))     ;ml-load

(dml |load| 2 ml-load ((|string| |#| |bool|) -> |void|))        ;load


;;; Boolean argument restored V5-1 GH.
;;; Changed for HOL88 by MJCG to return old value

(defun ml-timer (flag)
   (prog1 |%timing-flag| (setq |%timing-flag| flag)))       ;ml-timer

(dml |timer| 1 ml-timer (|bool| -> |bool|))     ;timer


(defun ml-lisp (tok)
   (errortrap
      #'(lambda (errtok) (msg-failwith '|lisp| errtok))
      (eval
         #+franz (readlist (explodec tok))
         #-franz (read-from-string (string tok)))))   ;ml-lisp

(dml |lisp| 1 ml-lisp (|string| -> |void|))             ;lisp


;;; Compiler

(dml |compile| 2 ml-compile ((|string| |#| |bool|) -> |void|))  ;compile

;;; MJCG 31/10/88 for HOL88
;;; find-file wrapped around fileof
;;; name-ext added and following let
;;; MJCG 10/2/90 for HOL88.1.12
;;; Test on |%file_load_msg-flag| added.

(defun ml-compile (tok |%print_load-flag|)
   (let ((%f 'compile)
         (%dump ())
         ($gcprint ())
         (name-ext (dest-file-name (find-file (fileof 'ml tok)))))
      (let ((filename (fileof 'lisp (car name-ext))))
         (catch-throw eof 
            (catch-throw loaderror
               (cond
                  ((not (filetokp 'ml tok))
                     (msg-failwith '|compile| tok " cannot be file name"))
                  ((fileexists 'ml tok)
                     (let ((%pt ()) (%ty ()) (%pr ()) (%val ()) (%head ())) 
                        (infilepush (find-file (fileof 'ml tok)))
                        (setq %outport (outfile filename))
                        ;; Franz compiler cannot know about any specials
                        #+franz (hol-print-file '(declare (special %vtyl)))
                        (compiloop)))
                  (t
                     (msg-failwith '|compile| tok " ml file not found"))))
            ;; an error occurred (before eof happened) during compilation
            (infilepop)
            (close %outport)
            (setq %outport nil)
            (when %dump (ml-end (car (last %dump)))) ;close dangling sections
            (msg-failwith '|compile| tok))
         ;; no error occurred
         (infilepop)
         (close %outport)
         (setq %outport nil)
         (when %dump (ml-end (car (last %dump))))  ;close dangling sections
         (compile-lisp filename)        ;call Lisp compiler
         (when (and |%print_load-flag| |%file_load_msg-flag|)
            (llterpri) (llprinc "File ") (llprinc tok)
            (llprinc " compiled") (llterpri)))))       ;ml-compile

;;; lisp function compiloop: 
;;; llprint at line labelled "***" changed to hol-print-file [TFM 90.06.01] 

(defun compiloop ()
   (while t
      (let ((%thisdec ()) (%thistydec ()))
         (and |%print_load-flag| (top%f) (llterpri))
         (initlean)
         (okpass 'parse)
         (setq %head (car %pt))
         (cond
            ((istmlop)
               (okpass 'evtmlop) (hol-print-file `(evtmlop ',%pt)))  ; ***
            ;; this ugly special case should disappear soon
            (t 
               (okpass 'typecheck)
               (okpass 'translation)
               (okpass 'evaluation)
               (updatetypes)
               (updatevalues)
               (printresults)
               (mapc
                  #'(lambda (form)
                     (hol-print-file `(eval-when (load) ,form)))
                  %compfns)
               (hol-print-file 
                  `(eval-when (load)
                     (execute
                        ',%ty ',%thisdec ',%thistydec ',%head ',new%%lb
                        ;; Retain compatibility with old franz versions.
                        ;; Do proper thing for CL
                        #+franz ',%pr
                        #-franz (function ,%pr))))
               )))))                    ;compiloop


;;; Evaluate an expression and also write it onto %outport
;;; For example, the putprops used to store abstract type information

(defun eval-remember (x)
   (when %outport (hol-print-file `(eval-when (load) ,x)))
   (eval x))                                    ;eval-remember


;;; Execute a compiled ML statement

(defun execute (%ty %thisdec %thistydec %head new%%lb %pr)
   (and |%print_load-flag| (top%f) (llterpri))
   (let ((init-time (runtime10th))
         (init-thms %thm-count))
      (okpass 'evaluation)
      (let ((final-time (runtime10th))
            (final-thms %thm-count))
         (updatetypes)
         (updatevalues)
         (printresults)
         (printtime final-time init-time final-thms init-thms)))) ;execute


;;; NEW  Saves a core image of a session
;;;
;;; caution: this should be invoked only from top-level of ml, and never from
;;; load/mlin (otherwise %f = load, and ml errors are not trapped properly).
;;; ml-save is system-dependent

(dml |save| 1 ml-save (|string| -> |void|))


;;; The code that follows supports ML generated top-level declarations
;;; of the form:  let x = f[`t1`;...;`tn`]. This works by maintaining
;;; pending declarations in the list %parse-tree-buffer. The top-level read
;;; loop checks to see if anything is in the buffer before reading from
;;; the input stream (see parsml0 below).

;;; (setq %parse-tree-buffer nil) 
;;; Now set in F-parsml.l (MJCG 5/2/89 for HOL88)

;;; The function parsml0 was previously defined by
;;; (defun parseml0 () (gnt) (parseml 0))
;;; MJCG 5/2/89 for HOL88
;;; Modified to return the front of %parse-tree-buffer

(defun parseml0 () 
   (prog (pt (*standard-input* *standard-input*))
      (if %parse-tree-buffer (go exit))
      (gnt)
      (setq pt (parseml 0))
      (setq %parse-tree-buffer
         (append %parse-tree-buffer (list pt)))
      exit (return
         (prog1 (car %parse-tree-buffer) 
            (setq %parse-tree-buffer (cdr %parse-tree-buffer))))))


;;; Make an object corresponding to the parse tree for `let mlname = fn tokl'.

(defun mk-let (mlname fn tokl)
   `(mk-let 
      ((mk-var ,mlname)
         mk-appn 
         (mk-var ,fn)
         ,(cons
            'mk-list
            (mapcar
               (function (lambda (x) (list 'mk-tokconst x))) tokl)))))


;;; and put it on the end of %parse-tree-buffer.
;;; The ML function let_after can be used to put it on at the beginning.

(dml |let_after| 3 ml-let_after
   ((|tok| |#| (|tok| |#| (|tok| |list|))) -> |void|))

(defun ml-let_after (mlname fn tokl)
   (prog (ob)
      (setq ob (mk-let mlname fn tokl))
      (setq %parse-tree-buffer
         (append %parse-tree-buffer (list ob)))
      (return '(mk-empty))))


;;; ml-let_before and let_before are like ml-let_after and let_after, except that
;;; the generated parse tree is put on the front of %parse-tree-buffer

(defun ml-let_before (mlname fn tokl)
   (prog (ob)
      (setq ob (mk-let mlname fn tokl))
      (setq %parse-tree-buffer (cons ob %parse-tree-buffer))
      (return '(mk-empty))))

(dml |let_before| 3 ml-let_before
   ((|tok| |#| (|tok| |#| (|tok| |list|))) -> |void|))


;;; MJCG 5/2/89 for HOL88
;;; (ml-autoload s fn (s1 ... sn) primes a string s so that if it is parsed
;;; as a variable (see the function mk-var-fun in F-parser.l) then the 
;;; autoload action fn[s1; ... ;sn] is put into %parse-tree-buffer
;;; The hol-autoload property has the form (eval . <ML parse tree>)

(defun ml-autoload (name fn args)
   (putprop 
      name 
      `(eval . (mk-appn 
            (mk-var ,fn)
            ,(cons
               'mk-list
               (mapcar (function (lambda (x) (list 'mk-tokconst x))) args))))
      'hol-autoload))

(dml |autoload| 3 ml-autoload
   ((|tok| |#| (|tok| |#| (|tok| |list|))) -> |void|))

;;; MJCG 5/2/88 for HOL88
;;; Functions to remove autoload actions

(defun ml-undo_autoload (name)
   (not (null (remprop name 'hol-autoload))))

(dml |undo_autoload| 1 ml-undo_autoload (|string| -> |bool|))


;;; MJCG 6/2/89 for HOL88
;;; Code for autoloading axioms, definitions and theorems.
;;; autoload takes a dotted pair whose car is
;;; a sort ('eval, 'axiom, 'definition or 'theorem)
;;; and whose cdr is either an ML parse tree (in the case of 'eval)
;;; or a theory-name pair in the other three cases.
;;; It then returns the parse tree to be put at the front
;;; of %parse-tree-buffer.
;;; In the 'eval case this tree is just the cdr of the argument; 
;;; in the other cases it is constructed using mk-let.

(defun autoload (p)
   (if (eq (car p) 'eval)
      (cdr p)
      (let ((sort (car p))
            (thy  (cadr p))
            (name (cddr p)))
         (case sort 
            (|axiom|
               (mk-let name '|axiom_msg_lfn| (list thy name)))
            (|definition|
               (mk-let name '|definition_msg_lfn| (list thy name)))
            (|theorem|
               (mk-let name '|theorem_msg_lfn| (list thy name)))
            (t (failwith '|autoload|))))))


;;; MJCG 6/2/89 for HOL88
;;; Function to set up hol-autoload properties for theory retrieval

(defun ml-autoload_theory (sort thy name)
   (cond ((memq sort '(|axiom| |definition| |theorem|))
         (putprop name (cons sort (cons thy name)) 'hol-autoload)
         nil)
      (t (failwith (concat "autoload: " sort)))))

(dml |autoload_theory|
   3
   ml-autoload_theory
   ((|string| |#| (|string| |#| |string|)) -> |void|))


;;; The code that follows enables ML functions to inject sequences of ascii
;;; characters onto the front of the input character stream.
;;; It works by concatenating onto the front of %char-buffer.

(defun inject-input (l) (setq %char-buffer (append l %char-buffer)))

(dml |inject_input| 1 inject-input ((|int| |list|) -> |void|))


;;; MJCG 2/3/89 for HOL88.1.01
;;; Function for loading a library
;;; %libraries holds the libraries already loaded

(setq %libraries nil)

;;; ml-load-library takes a print flag [no longer, see below] 
;;; and a library name.
;;; MJCG 23/3/89 for HOL88.1.02
;;; Instead of an explicit print flag argument, the printing
;;; during library loading is now controlled by the
;;; ML setable flag |%print_lib-flag|.

;;; load_library now sets up the search path. 

;;; (defun ml-load_library (tok)
;;;    (cond ((memq tok %libraries)
;;;          (princ (concat tok " already loaded"))
;;;          (terpri))
;;;       (t (princ (concat "Loading library `" tok "` ..."))
;;;          (terpri)
;;;          (let
;;;             ((dir-sep
;;;                   ;; guess a reasonable directory separator char
;;;                   (if (member #// (exploden %lib-dir)) "/"  ":")))
;;;             (ml-load
;;;                (catenate %lib-dir dir-sep tok dir-sep tok)
;;;                |%print_lib-flag|))
;;;          (setq %libraries (cons tok %libraries))
;;;          (terpri)
;;;          (princ (concat "Library `" tok "` loaded."))
;;;          (terpri)
;;;          nil)))

;;; New implementation of load_library for version 2.01:
;;;
;;;    * finds library using %library-search-path
;;;    * multi-section libraries:
;;;        - load_library `foo` loads <path>/foo/foo.ml
;;;        - load_library `foo:bar` loads <path>/foo/bar.ml
;;;
;;; Auxiliary functions:
;;;
;;;    * get-path : return the library pathname
;;;    * mk-fname : make load file name
;;;    * look-for-lib : search for library loadfile.
;;;
;;; [TFM 91.11.27]

(defun get-path (path sep)
  (let ((snum (car (exploden sep))))
   (prog (chars found)
      (setq chars (reverse (exploden path)))
      (setq found nil)
      loop
      (if (null chars) (return ""))
      (if found
	  (cond ((= (car chars) snum)
		 (return (imploden (reverse (cdr chars)))))
		(t (setq chars (cdr chars)) (go loop)))
	   (cond ((= (car chars) snum)
		  (setq found t) (setq chars (cdr chars)) (go loop))
		 (t (setq chars (cdr chars)) (go loop)))))))

(defun mk-fname (tok dir-sep)
   (prog (chars ext)
      (setq chars (reverse (exploden tok)))
      (setq ext nil)
      loop
       (if (null chars) (return(catenate tok dir-sep tok)))
       (cond
         ((not (= (car chars) colon))
            (setq ext (cons (car chars) ext))
            (setq chars (cdr chars))
            (go loop))
         (t (return
             (catenate
	       (imploden (reverse (cdr chars)))
	       dir-sep
	       (imploden ext)))))))

(defun look-for-lib (name tok)
   (let
      ((file
            (find-file
               (if (ends-in-ml name) name (catenate name '|.m*|)))))
      (if (probe-file file) file
	(failwith (catenate '|load_library: | tok '| not found|)))))


(defun ml-load_library (tok)
   (cond ((memq tok %libraries)
	  (princ (concat tok " already loaded"))
	  (terpri))
	 (t (let
             ((dir-sep
                  ;; guess a reasonable directory separator char
                  ;; JAC 19.02.92 for pc - was
                  ;; (if (member #// (exploden %lib-dir)) "/"  ":")
                  #+(or franz unix) "/"
                  #+pc "\\"
                  #-(or franz unix pc) ":"))
	     (let ((loadfile (mk-fname tok dir-sep)))
	     (let ((pathfile
		    (let ((%search-path %library-search-path))
		      (look-for-lib loadfile tok))))
             (princ (concat "Loading library " tok " ..."))
             (terpri)
	     (let ((%lib-dir (get-path pathfile dir-sep)))
                 (ml-load (catenate %lib-dir dir-sep loadfile)
			  |%print_lib-flag|)))))
         (setq %libraries (cons tok %libraries))
         (terpri)
         (princ (concat "Library " tok " loaded."))
         (terpri)
         nil)))

(dml |load_library| 1 ml-load_library (|string| -> |void|))

(defun ml-libraries () %libraries)

(dml |libraries| 0 ml-libraries (|void| -> (|string| |list|)))


;;; Go from ML to Lisp - was previously in Makefile

(dml |lsp| 0 ml-break (|void| -> |void|))


;;; Reset %hol-dir and %lib-dir from ML (used in install)
;;; no longer used
;;; (defun ml-set_hol_lib_dir (s)
;;; (setq %hol-dir s)
;;; (setq %lib-dir (concat s "/Library"))
;;; nil)
;;;(dml |set_hol_lib_dir| 1 ml-set_hol_lib_dir (|string| -> |void|))

;;; Return the library pathname. 	[TFM 90.12.01]
(defun ml-library_pathname () %lib-dir)
(dml |library_pathname| 0 ml-library_pathname (|void| -> |string|))

;;; Return the pathname to the HOL system directory. 	[TFM 91.05.17]
(defun ml-hol_pathname () %hol-dir)
(dml |hol_pathname| 0 ml-hol_pathname (|void| -> |string|))