/
ISMT.thy
1825 lines (1665 loc) · 83.4 KB
/
ISMT.thy
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
(*
Copyright (c) 2007-2011.
Authors: Levent Erkok (erkokl@gmail.com)
John Matthews (matthews.r.john@gmail.com)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the developers nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
(*
Version history:
Version 1.0 [Nov 2007]: Initial release, works with Isabelle 2007
Version 1.1 [Jun 2008]: Updated to work with Isabelle 2008
Version 1.2 [Jul 2008]: More careful handling of nat's
Version 1.3 [Sep 2010]: Updated to work with Isabelle 2009-2
Version 1.4 [Mar 2011]: Updated to work with Isabelle 2011
*)
theory ISMT
imports Main
begin
ML
{*
signature PIPE_PROCESS =
sig
type Process;
val launch : string * string list -> Process;
val kill : Process -> unit;
val instream_of : Process -> TextIO.instream;
val outstream_of : Process -> TextIO.outstream;
val charReady : Process -> bool;
val flush : Process -> unit;
(* Doesn't flush output pipe *)
val outputList : Process * string * string * string *
('a -> string) * 'a list -> unit;
(* Flushes output pipe *)
val outputLines : Process * string list -> unit;
(* Reads the next line from instream. This is
** a blocking operation.
*)
val readLine : Process -> string
val readLinesUntilChar : Process * char *
(string * 'a -> 'a) *
(string * 'a -> 'a) *
'a -> 'a;
val linesUntilChar : Process * char -> string list
val linesUntilResponse : Process * string -> string list
val linesUntilOneOf : Process * string list -> string list
(* same as linesUntilOneOf, except last line doesn't have to end with '\n' *)
val linesUntilOneOfPartial : Process * string list -> string list
(* Read lines that are currently queued up on the input stream.
** This is (supposed to be) a non-blocking operation, provided
** that the final pending character (if any) in the input stream
** is a newline.
*)
val pendingLines : Process -> string list
end;
structure PipeProcess : PIPE_PROCESS =
struct
type Process = (TextIO.instream, TextIO.outstream) Unix.proc *
TextIO.instream *
TextIO.outstream;
fun launch (processName,args)
= let val mp = Unix.execute (processName,args);
val (inStream,outStream) = Unix.streamsOf mp
in (mp, inStream, outStream)
end;
fun kill proc
= let val p = #1 proc;
val _ = Unix.kill (p, Posix.Signal.quit);
val _ = Unix.reap p in (* Waits until process has terminated,
** then removes the zombie process
** from the process id table.
*)
()
end;
fun instream_of proc = #2 proc;
fun outstream_of proc = #3 proc;
(** Checks to see whether at least one character is available to read from
** the input stream.
**)
fun charReady proc
= case TextIO.canInput (instream_of proc, 1) of
NONE => false
| SOME _ => true;
fun flush proc
= TextIO.flushOut (outstream_of proc);
fun outputList (proc, beginStr, sepStr, endStr, elemToStr, xs)
= let val ostrm = outstream_of proc
fun outLines []
= if endStr <> "" then TextIO.output (ostrm,endStr) else ()
| outLines [x]
= (TextIO.output (ostrm, elemToStr x);
outLines [])
| outLines (x::xs)
= (TextIO.output (ostrm, elemToStr x);
(if sepStr <> "" then TextIO.output (ostrm,sepStr) else ());
outLines xs);
val _ = (if beginStr <> "" then TextIO.output (ostrm, beginStr)
else ()) in
outLines xs
end;
fun outputLines (proc, lines)
= let val newline = str #"\n";
fun id str = str;
val _ = outputList (proc, "", newline, newline, id, lines) in
flush proc
end;
fun readLine proc
= case TextIO.inputLine (instream_of proc) of
NONE => ""
| SOME s => s
fun readAllPending proc
= case TextIO.canInput (instream_of proc, 1) of
NONE => ""
| SOME 0 => ""
| SOME i => TextIO.inputN (instream_of proc, i) ^ readAllPending proc
(** Read lines from instr, applying lnFn to each line read until
** it reads a line that satisfies the 'final' predicate.
**)
fun readLinesUntil (proc, final, lnFn, lastFn, init)
= let fun readLines x
= let val line = readLine proc in
if final line then lastFn (line,x)
else readLines (lnFn (line,x))
end
in readLines init
end;
(** Specialized version where all we look for is a beginning character **)
fun readLinesUntilChar (proc, char, lnFn, lastFn, init)
= readLinesUntil (proc, (fn ln => String.sub (ln, 0) = char), lnFn, lastFn, init);
(** part of user interface; read until a line that starts with a char: **)
fun linesUntilChar (proc,char)
= readLinesUntilChar (proc, char, (op ::), (fn (l,ls) => rev (l::ls)),[]);
(** OR, read until a line looks exactly like: **)
fun linesUntilResponse (proc, str)
= readLinesUntil (proc, (fn ln => ln = str), (op ::), (fn (l, ls) => rev (l::ls)), []);
(** OR, read until a line looks exactly like one of: **)
fun linesUntilOneOf (proc, strs)
= readLinesUntil (proc, (fn ln => List.exists (fn s => ln = s) strs), (op ::), (fn (l, ls) => rev (l::ls)), []);
fun pendingLines proc
= let fun plines lines
= if charReady proc then plines (readLine proc :: lines)
else lines in
rev (plines [])
end;
(* same as linesUntilOneOf, however, the last line doesn't have to end with '\n'. Note that this
will eat-up all the available input, and it will block until it gets the desired output! *)
fun linesUntilOneOfPartial (proc, strs)
= let fun rl sofar = let val lines = Library.filter (fn s => s <> "") (Library.split_lines (readAllPending proc))
val patterns = map String.explode strs
in if lines = []
then rl sofar
else let val lastLine = String.explode (List.last lines)
in if Library.exists (fn s => Library.is_prefix (op =) s lastLine) patterns
then sofar @ lines
else rl (sofar @ lines)
end
end
in rl []
end
end;
*}
ML
{*
(** TermUtils.Ml: util functions for various term related goodies
** Date: Mar 6th, 2007.
**)
structure TermUtils =
struct
fun conc_of (t : Term.term) : Term.term
= case t of
(Const ("==>", _) $ _ $ r) => conc_of r
| t => t;
local
fun wrap b a i = b ^ i ^ a
val quote = wrap "\"" "\""
val paren = wrap "(" ")"
val sqparen = wrap "[" "]"
val pList = paren o commas
val sList = sqparen o commas
in
fun showSrt ss = sList (map quote ss)
fun showTyp (Type (s, ts)) = "Type " ^ pList [quote s, sList (map showTyp ts)]
| showTyp (TFree (s, srt)) = "TFree " ^ pList [quote s, showSrt srt]
| showTyp (TVar (i, srt)) = "TVar " ^ pList [Term.string_of_vname i, showSrt srt]
and showTerm (Const (s, t)) = "Const " ^ pList [quote s, showTyp t]
| showTerm (Free (s, t)) = "Free " ^ pList [quote s, showTyp t]
| showTerm (Var (i, t)) = "Var " ^ pList [Term.string_of_vname i, showTyp t]
| showTerm (Bound i) = "Bound " ^ Int.toString i
| showTerm (Abs (s, T, t)) = "Abs " ^ pList [quote s, showTyp T, showTerm t]
| showTerm (t1 $ t2) = paren (showTerm t1) ^ " $ " ^ paren (showTerm t2)
end
end; (* struct TermUtils *)
*}
ML
{*
(* ResourceTimer.ML: A general structure for measuring (nested) elapsed time *)
(* A timer can properly be nested, with no problem, i.e., *)
(* It's OK to say: *)
(* withTimer1 t f a *)
(* where f itself starts/stops the timer t as well. *)
(* *)
(* Date: Jan. 8th, 2007 *)
signature RESOURCE_TIMER =
sig
type T;
val newTimer : unit -> T;
val reset : T -> unit;
val elapsed : T -> LargeInt.int; (* turn it into milliseconds *)
val withTimer1 : T -> ('a -> 'b) -> ('a -> 'b);
val withTimer2 : T -> ('a -> 'b -> 'c) -> ('a -> 'b -> 'c);
val withTimer3 : T -> ('a -> 'b -> 'c -> 'd) -> ('a -> 'b -> 'c -> 'd);
val withTimer4 : T -> ('a -> 'b -> 'c -> 'd -> 'e) -> ('a -> 'b -> 'c -> 'd -> 'e);
(* one-shot measurements, with no explicit timer creation needed: *)
val runWithTimer : ('a -> 'b) -> ('a -> (LargeInt.int * 'b));
end; (* signature RESOURCE_TIMER *)
structure ResourceTimer : RESOURCE_TIMER =
struct
open Unsynchronized
type T = Time.time ref * Time.time ref * int ref; (* Accumulated time * current time * nesting *)
fun newTimer () = (ref Time.zeroTime, ref (Time.now()), ref 0);
fun start (_, t0, n) = if !n = 0 then (t0 := Time.now(); n := 1) else n := !n + 1;
fun stop (acc, t0, n) = if !n = 1
then let val t1 = Time.now()
in acc := !acc + t1 - !t0;
t0 := t1;
n := 0
end
else if !n < 0
then error ("ResourceTimer.stop: impossible happened, n < 0!")
else n := !n - 1;
fun reset (acc, t0, n) = if !n <> 0
then error ("ResourceTimer.reset: Cannot reset a running timer!")
else (acc := Time.zeroTime; t0 := Time.now());
fun elapsed (acc, _, _) = Time.toMilliseconds (!acc);
fun withTimer1 t f a = (start t; let val r = f a; in stop t; r end) handle e => (stop t; raise e);
fun withTimer2 t f a b = (start t; let val r = f a b; in stop t; r end) handle e => (stop t; raise e);
fun withTimer3 t f a b c = (start t; let val r = f a b c; in stop t; r end) handle e => (stop t; raise e);
fun withTimer4 t f a b c d = (start t; let val r = f a b c d; in stop t; r end) handle e => (stop t; raise e);
fun runWithTimer f a = let val t = newTimer ();
val res = withTimer1 t f a;
in stop t;
(elapsed t, res)
end;
end; (* structure ResourceTimer *)
*}
ML
{*
(* ISMTInterface.ML: Tactics for using incremental SMT solvers from Isabelle
** Date: Mar. 9th, 2007
*)
datatype 'model Result = UNSAT | SAT of 'model | UNKNOWN of 'model
open Unsynchronized
signature ISMT_SIG =
sig
type Options
(* Configuration *)
val ismt_trace : bool ref (* Print debugging data *)
val ismt_tcheck : bool ref (* Enable backend-type checking *)
val ismt_stats : bool ref (* Enable statistics collection/printing *)
val ismt_debug : bool ref (* Run in debug mode *)
val ismt_addAccessor : Term.term -> unit (* Install an accessor function *)
(* Entry point *)
val ismtSolver : Context.theory -> Options * Term.term -> Term.term
end (* signature ISMT_SIG *)
signature ISMTBackend_SIG =
sig
type Script
type Model
type Options = Context.theory (* theory to interpret things in *)
* string option (* dump file *)
* bool (* should type check? *)
* bool (* should turn debugging on? *)
val addAccessor : Term.term -> unit
val identifier : string
val init : Options -> unit;
val fromIsabelle : Term.term -> Script
val explainModel : Model -> string * string
val decide : Script -> Model Result
end (* signature ISMTSolver_SIG *)
functor ISMTInterface(structure backend : ISMTBackend_SIG) : ISMT_SIG =
struct
open Unsynchronized
type Options = string option * bool option * bool option * bool option
(* Initial configuration *)
val ismt_trace = ref false
val ismt_tcheck = ref true
val ismt_stats = ref false
val ismt_debug = ref false
val ismt_addAccessor = backend.addAccessor
fun reportStats (yices, total)
= let val trans = total - yices
val rtotal = Real.fromInt total
val ptrans = 100.0 * (Real.fromInt trans / rtotal)
val pyices = 100.0 * (Real.fromInt yices / rtotal)
fun ppt r = StringCvt.padLeft #" " 6 (LargeInt.toString r)
fun ppc r = StringCvt.padLeft #" " 6 (Real.fmt (StringCvt.FIX (SOME 2)) r)
val solver = backend.identifier
fun ppl s = StringCvt.padLeft #" " (size solver + 4) s
in
writeln "STATISTICS: (in milliseconds)";
writeln (ppl "Trans: " ^ ppt trans ^ "\t(" ^ ppc ptrans ^ "%)");
writeln (ppl (solver ^ ": ") ^ ppt yices ^ "\t(" ^ ppc pyices ^ "%)");
writeln (ppl "Total: " ^ ppt total ^ "\t(100.00%)")
end
fun ismtSolver thy ((mbDump, mbTC, mbStats, mbDebug), trm) =
let fun explain model = let val (ce, ui) = backend.explainModel model
in Library.prefix_lines " " ce ^ "\nUninterpreted Constants of the counter-example:\n" ^ Library.prefix_lines " " ui
end
fun run () = let val script = (backend.init (thy, mbDump, Option.getOpt (mbTC, !ismt_tcheck), Option.getOpt (mbDebug, !ismt_debug));
backend.fromIsabelle trm)
val (solverTime, res) = ResourceTimer.runWithTimer backend.decide script
in (solverTime, res)
end
val (totalTime, (solverTime, res)) = ResourceTimer.runWithTimer run ()
val statsMode = Option.getOpt (mbStats, !ismt_stats)
in
(case res of
UNSAT => (if statsMode then reportStats (solverTime, totalTime) else (); trm)
| SAT model => raise THM ("A counter-example is found:\n" ^ explain model, 0, [])
| UNKNOWN model => raise THM (backend.identifier ^ " couldn't decide the subgoal! Potential counter-example:\n"
^ explain model, 0, [])
)
handle e => (if statsMode then reportStats (solverTime, totalTime) else ();
raise e)
end
end (* struct ISMT *)
*}
ML
{*
(* A version of Pretty that ensures everything is plain *)
structure PPR =
struct
val mode = []
fun plainPrint printer d = Print_Mode.setmp mode printer d
val string_of = plainPrint Pretty.string_of
val keyword = plainPrint Pretty.keyword
val brk = plainPrint Pretty.brk
val blk = plainPrint Pretty.blk
val str = plainPrint Pretty.str
val breaks = plainPrint Pretty.breaks
val enclose = plainPrint Pretty.enclose
end
*}
ML
{*
structure Util =
struct
open List
fun concatMap f = foldr (op @) [] o map f
fun stringyMap f = Library.space_implode " " o map f
fun splitAt n lst
= let fun s 0 lst = ([], lst)
| s _ [] = ([], [])
| s n (x::xs) = let val (xs', xs'') = s (n-1) xs in (x::xs', xs'') end
in if n < 0 then error ("splitAt called with negative argument: " ^ Int.toString n)
else s n lst
end
fun butLast xs = #1 (Library.split_last xs)
fun last xs = List.last xs
val currentTheory : Context.theory ref = ref (@{theory});
val shouldTypeCheck : bool ref = ref true
val mbDumpFile : (string option) ref = ref NONE
val shouldDebug : bool ref = ref false
fun trace f = if (!shouldDebug) then tracing ("### " ^ f ()) else ()
fun initGlobals (thy, mbFile, tc, debug) =
(currentTheory := thy;
mbDumpFile := mbFile;
shouldTypeCheck := tc;
shouldDebug := debug)
fun interfaceMessage s
= case !mbDumpFile of
NONE => ()
| SOME "-" => ()
| SOME f => let val stream = TextIO.openAppend f
in TextIO.output (stream, "\n" ^ Library.prefix_lines ";;; " s);
TextIO.output (stream, "\n");
TextIO.flushOut stream;
TextIO.closeOut stream
end
handle _ => warning ("Unable to write to the dump file! (" ^ s ^ ")")
fun interfaceError s = (interfaceMessage s; raise (Fail s))
fun interfaceWarning s = (interfaceMessage s; if (!shouldDebug) then warning s else ())
fun dumpScript script
= case !mbDumpFile of
NONE => ()
| SOME "-" => List.app writeln (split_lines script)
| SOME f => let val stream = TextIO.openOut f
in TextIO.output (stream, script);
TextIO.flushOut stream;
TextIO.closeOut stream
end
handle _ => warning ("Failed to write the Yices output to the file: " ^ f)
fun dumpResults res explainModel
= let fun outModel stream msg1 msg2 model
= let val pref = Library.prefix_lines ";;; "
fun explain [] = ["(No explicit model returned from Yices.)"]
| explain mods = map #1 mods
val mods = pref (Library.space_implode "\n" (explain (fst model)))
val (hmods, hunints) = let val (m, u) = explainModel model in (pref m, pref u) end
in TextIO.output(stream, ";;; " ^ msg1 ^ ":\n" ^ mods ^ "\n;;;\n");
TextIO.output(stream, ";;; " ^ msg2 ^ ":\n" ^ hmods ^ "\n;;;\n");
TextIO.output(stream, ";;; Uninterpreted Constants of the counter-example:\n" ^ hunints ^ "\n")
end
in case !mbDumpFile of
NONE => ()
| SOME "-" => ()
| SOME f => let val stream = TextIO.openAppend f
in (case res of
UNSAT => TextIO.output (stream, ";;; Status: Theorem\n")
| UNKNOWN model => outModel stream "Unknown, Potential counter-example follows" "Potential HOL Counter-example" model
| SAT model => outModel stream "Falsifiable" "HOL Counter-example" model);
TextIO.flushOut stream;
TextIO.closeOut stream
end
handle _ => warning ("Failed to write results to the Yices output file: " ^ f)
end
end (* Util *)
signature NAME =
sig
eqtype name
val toString : name -> string
val toName : string -> name
val lift : string -> name
val incrIndex : name -> name
val prefixOf : name -> string
val indexOf : name -> int
val construct : (string * int) -> name
end (* NAME *)
structure Name : NAME =
struct
type name = string * int
fun toString (s, 0) = s
| toString (s, i) = s ^ "_" ^ Int.toString i
fun lift s = (s, 0)
val construct = I
fun toName s
= let val sl = String.explode s
val pos = Library.find_index (fn c => c = #"_") (List.rev sl)
in if pos < 0 then (s, 0)
else let val (nm_, i) = Library.take_suffix (fn c => c <> #"_") sl
val nm = Util.butLast nm_
in if i <> [] andalso List.all Char.isDigit i
then (String.implode nm, Option.valOf (Int.fromString (String.implode i)))
else (s, 0)
end
end
fun incrIndex (s, i) = (s, i+1)
val prefixOf = #1
val indexOf = #2
end (* Name *)
signature YICESBRIDGE =
sig
val issue : PipeProcess.Process -> string option -> string list
val sendWhileOK : PipeProcess.Process -> string list -> bool
val check : PipeProcess.Process -> string list Result
end (* YICESBRIDGE *)
structure YicesBridge : YICESBRIDGE =
struct
(* Yices configuration *)
structure YicesParams =
struct
val prompt = "yices > "
val statusCmd = "(status)"
val statusOK = "ok"
val statusNotOK = "unsat"
val checkCmd = "(check)"
val checkSAT = "sat"
val checkUnSAT = "unsat"
val checkOther = "unknown"
val echoPrompt = "(echo \"" ^ prompt ^ "\")"
val errorLine = "Error:"
end
fun issue yices mbCmd
= let val (cmd, toYices) =
case mbCmd of
SOME s => (Util.trace (fn _ => "---> Yices: [" ^ s ^ "]"); (s, [s, YicesParams.echoPrompt]))
| NONE => ("(none)", [YicesParams.echoPrompt])
val _ = (PipeProcess.outputLines (yices, toYices);
PipeProcess.flush yices)
fun trimS [] = []
| trimS (s as (c::cs)) = if Char.isSpace c then trimS cs else s
fun trim s = String.implode (List.rev (trimS (List.rev (trimS (String.explode s)))))
val lines = List.filter (fn s => s <> "")
(List.map trim (PipeProcess.linesUntilOneOfPartial (yices, [YicesParams.prompt, YicesParams.errorLine])))
val WARNINGL = String.explode "WARNING"
val ERRORL = String.explode YicesParams.errorLine
fun isWarning s = if Library.is_prefix (op =) WARNINGL (String.explode s) then (Util.interfaceWarning s; true) else false
fun isError s = Library.is_prefix (op =) ERRORL (String.explode s)
in if Library.exists isError lines
then lines
else case lines of
[] => Util.interfaceError ("No valid responses received for command " ^ cmd)
| lst => let val res = Util.butLast lst (* get rid of the final prompt *)
in if res <> [] then Util.trace (fn _ => "<--- Yices: [" ^ commas res ^ "]") else ();
List.filter (not o isWarning) res
end
end
fun issueAndCheck yices c
= let val resp = issue yices (SOME c)
in if resp = [] then true
else if resp = [YicesParams.checkUnSAT] then false
else if resp = [YicesParams.checkSAT] then true
else Util.interfaceError ("Unexpected response received for command " ^ c ^ ": " ^ commas (List.filter (fn l => l <> "") resp))
end
fun sendWhileOK yices cmds
= let fun swok [] = true
| swok (c::cs) = if issueAndCheck yices c then swok cs else false
in swok cmds
end
(* sometimes Yices prints counter-examples over multiple lines; this routine joins the lines appropriately
so that we have one counter-example per line *)
fun combine lines
= let fun count [] sofar = sofar
| count (x::xs) sofar = count xs (if x = #"(" then (sofar + 1) else if x = #")" then (sofar - 1) else sofar)
fun isBalanced line = count (String.explode line) 0 = 0
fun comb [] = []
| comb [l] = [l]
| comb (x::y::ys) = if isBalanced x then x :: comb (y::ys)
else comb ((x ^ " " ^ y)::ys)
in comb lines
end
fun check yices
= let val resp = issue yices (SOME YicesParams.checkCmd)
in if resp = [YicesParams.checkUnSAT]
then UNSAT
else case resp of
[] => Util.interfaceError ("Yices didn't respond to the check command")
| (ans::rest) => if ans = YicesParams.checkSAT
then SAT (combine rest)
else UNKNOWN (combine rest)
end
end (* YicesBridge *)
(* Intermediate language of s-expressions and types *)
structure IL =
struct
open List
datatype Stype = BasicType of Name.name
| Uninterpreted of Name.name
| FuncType of Stype list
| TupleType of Stype list
| RecordType of (Name.name * Stype) list
| DataType of (bool * (Name.name * (Name.name * Stype) list) list) (* bool: true if scalar *)
datatype Sexp = S_Con of Name.name
| S_Num of int
| S_App of Sexp list
| S_Upd of Sexp * Sexp * Sexp
| S_Lam of (Name.name * Stype) list * Sexp
| S_Qnt of string * (Name.name * Stype) list * Sexp
| S_Let of (Name.name * Stype * Sexp) list * Sexp
| S_MkR of (Name.name * Sexp) list
(* smart constructors *)
fun mk_Con s = S_Con (Name.lift s)
fun mk_App [] = Util.interfaceError "Internal: mk_App passed an empty list!"
| mk_App [t] = t
| mk_App xs = S_App xs
fun mk_BasicType s = BasicType (Name.lift s)
fun arityOf (FuncType ts) = length ts - 1
| arityOf _ = 0
fun namesOf (BasicType n) = [n]
| namesOf (Uninterpreted n) = [n]
| namesOf (FuncType ts) = Util.concatMap namesOf ts
| namesOf (TupleType ts) = Util.concatMap namesOf ts
| namesOf (RecordType ts) = Util.concatMap (fn (n, t) => n :: namesOf t) ts
| namesOf (DataType (_, cs)) = let fun namesOfArgs (n, t) = n :: namesOf t
fun namesOfCs (n, lst) = n :: Util.concatMap namesOfArgs lst
in Util.concatMap namesOfCs cs
end
val ppName = PPR.str o Name.toString
val parens = PPR.enclose "(" ")"
fun block ps = PPR.blk (1, ps)
fun ppApp [] = parens []
| ppApp [f] = parens [f]
| ppApp (f::fs) = parens [f, PPR.brk 1, PPR.blk (0, PPR.breaks fs)]
val parens = PPR.enclose "(" ")"
fun mapB f xs = PPR.breaks (map f xs)
fun ppVT (n, t) = block [ppName n, PPR.keyword "::", ppType t]
and ppVTE (n, t, e) = parens [block [ppName n, PPR.keyword "::", ppType t, PPR.brk 1, ppExp e]]
and ppVE (n, e) = block [ppName n, PPR.keyword "::", ppExp e]
and ppType stype
= let fun shC (n, []) = ppName n
| shC (n, args) = ppApp (ppName n :: map ppVT args)
fun shT (BasicType t) = ppName t
| shT (Uninterpreted t) = ppName t
| shT (FuncType args) = ppApp (PPR.keyword "->" :: map shT args)
| shT (TupleType args) = ppApp (PPR.keyword "tuple" :: map shT args)
| shT (RecordType args) = ppApp (PPR.keyword "record" :: map ppVT args)
| shT (DataType (true, args)) = ppApp (PPR.keyword "scalar" :: map shC args)
| shT (DataType (false, args)) = ppApp (PPR.keyword "datatype" :: map shC args)
in shT stype
end
and ppExp (S_Con n) = ppName n
| ppExp (S_Num i) = PPR.str (if i < 0 then "-" ^ Int.toString (abs i) else Int.toString i)
| ppExp (S_App args) = ppApp (map ppExp args)
| ppExp (S_MkR args) = ppApp [PPR.keyword "mk-record", PPR.blk (0, mapB ppVE args)]
| ppExp (S_Upd (f, p, nv)) = ppApp [PPR.keyword "update", ppExp f, parens [ppExp p], ppExp nv]
| ppExp (S_Lam (args, e)) = ppApp [PPR.keyword "lambda", parens (mapB ppVT args), ppExp e]
| ppExp (S_Qnt (n, args, e)) = ppApp [PPR.keyword n , parens (mapB ppVT args), ppExp e]
| ppExp (S_Let (bndgs, b)) = ppApp [PPR.keyword "let" , parens (mapB ppVTE bndgs), ppExp b]
val showStype = PPR.string_of o ppType
val showSexp = PPR.string_of o ppExp
fun assembleScript printer (setup, tps, defs, hyps, sexp)
= let val typedefs = map (fn n => parens [PPR.keyword "define-type", PPR.brk 1, ppName n])
(Library.map_filter (fn (x, mb0) => case mb0 of NONE => SOME x | _ => NONE) tps)
val optTyps = map (fn (n, t) => parens [PPR.keyword "define-type", PPR.brk 1, PPR.blk (0, [ppName n, PPR.brk 1, PPR.blk (0, [ppType t])])])
(Library.map_filter (fn (x, mbO) => case mbO of NONE => NONE | _ => SOME (x, the mbO)) tps)
val defines = map (fn (v, t) => parens [PPR.keyword "define", PPR.brk 1, ppName v, PPR.keyword "::", ppType t]) defs
fun asrt s = ppApp [PPR.keyword "assert", s]
val hypExprs = map (asrt o ppExp) hyps
val sexpr = asrt (ppExp sexp)
in ( setup
, map printer typedefs
, map printer optTyps
, map printer defines
, map printer hypExprs
, printer sexpr)
end
fun showScript termStr script
= let val (setup, types, optTyps, defines, asserts, sexpr) = assembleScript (PPR.plainPrint PPR.string_of) script
fun line [] = ";;; none\n"
| line xs = foldr (fn (x, y) => x ^ "\n" ^ y) "" xs
in ";;; Automatically generated by the ismt tactic, do not edit!\n"
^ ";;; Generated from the HOL term:\n"
^ Library.prefix_lines ";;; " termStr ^ "\n\n"
^ ";;; Yices set-up\n"
^ line setup
^ "\n;;; Uninterpreted types:\n"
^ line types
^ "\n;;; Type declarations:\n"
^ line optTyps
^ "\n;;; Constants:\n"
^ line defines
^ "\n;;; Hypotheses:\n"
^ line asserts
^ "\n;;; Negated goal:\n"
^ sexpr
^ "\n\n(check)"
^ "\n;;; End of generated Yices file.\n"
end
end (* IL *)
structure YicesInternals =
struct
type Typ = IL.Stype
type Exp = IL.Sexp
val boolT = IL.mk_BasicType "bool"
val natT = IL.mk_BasicType "nat"
val intT = IL.mk_BasicType "int"
val true_const = IL.mk_Con "true"
val false_const = IL.mk_Con "false"
val plus_const = IL.mk_Con "+"
val minus_const = IL.mk_Con "-"
val times_const = IL.mk_Con "*"
val divide_const = IL.mk_Con "/"
val eq_const = IL.mk_Con "="
val neq_const = IL.mk_Con "/="
val lessEq_const = IL.mk_Con "<="
val less_const = IL.mk_Con "<"
val imp_const = IL.mk_Con "=>"
val and_const = IL.mk_Con "and"
val or_const = IL.mk_Con "or"
val not_const = IL.mk_Con "not"
val if_const = IL.mk_Con "if"
val pair_const = IL.mk_Con "mk-tuple"
val select_const = IL.mk_Con "select"
val update_const = IL.mk_Con "update"
val div_const = IL.mk_Con "div"
val mod_const = IL.mk_Con "mod"
fun isYicesNumericType t = t = natT orelse t = intT
val basicTypesList = [ (HOLogic.boolT, boolT), (HOLogic.natT, natT)
, (HOLogic.intT, intT), (Type ("prop", []), boolT)]
fun holTypeOf t = case List.find (fn (_, y) => y = t) basicTypesList of
SOME (h, _) => h
| NONE => Util.interfaceError ("holTypeOf called on unknown type:" ^ IL.showStype t)
fun yicesTypeOf t = case List.find (fn (h, _) => h = t) basicTypesList of
SOME (_, y) => y
| NONE => Util.interfaceError ("yicesTypeOf called on unknown type.")
val yicesReserved = [ "true", "false", "define-type", "define", "subtype", "subrange", "tuple", "record", "datatype"
, "scalar", "bitvector", "and", "or", "not", "=>", "=", "/=", "::", "if", "ite", "let"
, "forall", "exists", "lambda", "mk-tuple", "select", "mk-record", "update", "mk-bv"
, "bv-concat", "bv-extract", "bv-shift-left0", "bv-shift-left1", "bv-shift-right0", "bv-shift-right1"
, "bv-sign-extend", "bv-and", "bv-or", "bv-xor", "bv-not", "bv-add", "bv-sub", "bv-mul", "bv-neg"
, "bv-lt", "bv-le", "bv-gt", "bv-ge", "bv-slt", "bv-sle", "bv-sgt", "bv-sge"
, "bool", "nat", "int", "status", "assert", "assert+", "check", "retract", "check"
, "set-evidence!", "set-verbosity!", "set-arith-only!", "push", "pop", "echo", "include", "reset"
, "dump-context", "+", "-", "*", "/", "<=", "div", "mod"
]
fun isReserved nm = member (op =) yicesReserved (Name.toString nm)
fun unreserve nm = if isReserved nm
then unreserve (Name.incrIndex nm)
else nm
(* drop not-not; not-= becomes /=, not-/= becomes =, anything else gets a not in front *)
fun negate y = case y of
IL.S_App (f :: rest) => if f = not_const
then IL.mk_App rest
else if f = eq_const
then IL.mk_App (neq_const :: rest)
else if f = neq_const
then IL.mk_App (eq_const :: rest)
else IL.mk_App [not_const, y]
| _ => if y = true_const then false_const
else if y = false_const then true_const
else IL.mk_App [not_const, y]
val yicesSetup = ["(set-evidence! true)"]
end (* YicesInternals *)
structure Isa2Yices =
struct
val allowMutualRecursion = false (* Yices doesn't support mutual recursion; set this flag
* to true to experiment; should be left false normally. *)
structure Y = YicesInternals
fun varifyTerm t = #2 (Type.varify_global [] t)
datatype FieldType = F_Function | F_Selector | F_Updater of Name.name | F_Case of (Name.name * (string * string list) list)
fun showFieldType F_Function = "function"
| showFieldType F_Selector = "selector"
| showFieldType (F_Updater n) = "updater (" ^ Name.toString n ^ ")"
| showFieldType (F_Case _) = "case-expression"
fun isFieldFunction ft = case ft of F_Function => true | _ => false
fun isFieldSelector ft = case ft of F_Selector => true | _ => false
fun isFieldUpdater ft = case ft of (F_Updater _) => true | _ => false
fun isFieldCase ft = case ft of (F_Case _) => true | _ => false
val termTab : ((Term.term * (Y.Exp * int * FieldType)) list) ref = ref [];
val newTypTab : (Term.typ * (Name.name * Y.Typ option)) list ref = ref [];
val defineTab : ((Name.name * Y.Typ) list) ref = ref [];
val hypTab : (Y.Exp list) ref = ref [];
val recordTab : (((string * Term.typ) * (string * Term.typ) list * (Y.Exp list -> Y.Exp) * int) list) ref = ref []
val genSymTab : (Name.name list) ref = ref []
val accessorTab : (Term.term list) ref = ref (map varifyTerm
[ @{term "Option.the"}
, @{term "List.hd"}
, @{term "List.tl"}
])
val topLevel : bool ref = ref true;
fun lookupTermTab comp = List.find comp (!termTab)
local
fun addToTab tab entry = tab := entry :: (!tab)
in
fun addToTermTab (h, (y, a)) = addToTab termTab (h, (y, a, F_Function))
fun addToTermTabSel (h, (y, a)) = addToTab termTab (h, (y, a, F_Selector))
fun addToTermTabUpd f (h, (y, a)) = addToTab termTab (h, (y, a, F_Updater f))
fun addToTermTabCase d (h, (y, a)) = addToTab termTab (h, (y, a, F_Case d))
val addToHypTab = addToTab hypTab
val addToDefineTab = addToTab defineTab
val addToNewTypTab = addToTab newTypTab
val addToRecordTab = addToTab recordTab
val addToGenSymTab = addToTab genSymTab
fun addAccessor t = addToTab accessorTab (varifyTerm t)
end
(* Note that "equality" and "if" has to be treated specifically, due to their truly polymorphic nature,
* so we cannot just add them to the table and be done!
*)
fun initTermTab ()
= let fun binOp T = Type ("fun", [T, Type ("fun", [T, T])])
fun relOp T = Type ("fun", [T, Type ("fun", [T, HOLogic.boolT])])
in addToTermTab (HOLogic.true_const, (Y.true_const, 0));
addToTermTab (HOLogic.false_const, (Y.false_const, 0));
addToTermTab (Const (@{const_name plus_class.plus}, binOp HOLogic.intT), (Y.plus_const, 2));
addToTermTab (Const (@{const_name plus_class.plus}, binOp HOLogic.natT), (Y.plus_const, 2));
addToTermTab (Const (@{const_name minus_class.minus}, binOp HOLogic.intT), (Y.minus_const, 2));
(*
The following is *not* sound since 2-3=0 for naturals! Yices would do the wrong thing..
addToTermTab (Const (@{const_name HOL.minus_class.minus}, binOp HOLogic.natT), (Y.minus_const, 2));
*)
addToTermTab (Const (@{const_name times_class.times}, binOp HOLogic.intT), (Y.times_const, 2));
addToTermTab (Const (@{const_name times_class.times}, binOp HOLogic.natT), (Y.times_const, 2));
(* don't define divide; Isabelle doesn't define them!
addToTermTab (Const (@{const_name HOL.divide}, binOp HOLogic.intT), (Y.divide_const, 2));
addToTermTab (Const (@{const_name HOL.divide}, binOp HOLogic.natT), (Y.divide_const, 2));
*)
addToTermTab (Const (@{const_name ord_class.less_eq}, relOp HOLogic.intT), (Y.lessEq_const, 2));
addToTermTab (Const (@{const_name ord_class.less_eq}, relOp HOLogic.natT), (Y.lessEq_const, 2));
addToTermTab (Const (@{const_name ord_class.less}, relOp HOLogic.intT), (Y.less_const, 2));
addToTermTab (Const (@{const_name ord_class.less}, relOp HOLogic.natT), (Y.less_const, 2));
addToTermTab (Const (@{const_name HOL.implies}, relOp HOLogic.boolT), (Y.imp_const, 2));
addToTermTab (Const (@{const_name HOL.conj}, relOp HOLogic.boolT), (Y.and_const, 2));
addToTermTab (Const (@{const_name HOL.disj}, relOp HOLogic.boolT), (Y.or_const, 2))
(* div and mod requires special attention since in Isabelle:
x mod 0 = x
x div 0 = 0
which is not the case in Yices
addToTermTab (Const (@{const_name Divides.div_class.div}, binOp HOLogic.intT), (Y.div_const, 2));
addToTermTab (Const (@{const_name Divides.div_class.div}, binOp HOLogic.natT), (Y.div_const, 2));
addToTermTab (Const (@{const_name Divides.div_class.mod}, binOp HOLogic.intT), (Y.mod_const, 2));
addToTermTab (Const (@{const_name Divides.div_class.mod}, binOp HOLogic.natT), (Y.mod_const, 2))
*)
end
(* These are the numeric types we understand and support. All others will go uninterpreted. *)
fun isHOLNatType t = t = HOLogic.natT
fun isHOLIntType t = t = HOLogic.intT
fun isHOLNumericType t = isHOLNatType t orelse isHOLIntType t
(* Recognizes HOL records *)
fun isHOLRecordType t = Record.dest_recTs t <> []
(* expToHOL is only a "poor man"'s version; supposed to convert only those s-expressions
* that Yices will use in printing it's counter examples! It's not a full-fledged
* expression to HOL converter by any means!
*)
fun expToHOL uninterpretedConstants s
= let val unints = ref uninterpretedConstants
fun addUnint n ht =
let val mbS = case ht of
Const (hn, _) => SOME (Long_Name.base_name hn)
| Free (hn, _) => SOME (Long_Name.base_name hn)
| Var (hin, _) => SOME (Long_Name.base_name (Library.string_of_indexname hin))
| _ => NONE
in case mbS of
NONE => ()
| SOME s => if member (op =) (!unints) s orelse not (member (op =) (map #1 (!defineTab)) n)
then ()
else unints := s :: (!unints)
end
fun bailOut msg = Util.interfaceError ("e2h: " ^ msg ^ ", while processing: " ^ IL.showSexp s)
fun mkSMTConst i = @{term "ismt_const"} $ (HOLogic.mk_number HOLogic.intT i)
fun getTypeOf ht = fastype_of ht handle _ => Util.interfaceError ("Failed to correctly type: " ^ Syntax.string_of_term_global (!Util.currentTheory) ht)
fun flatten (Type ("fun", [x, y])) = x :: flatten y
| flatten t = [t]
fun mkRecord args
= let val sep = IL.mk_Con "::"
fun collect [] = []
| collect (IL.S_Con nm::s::v::r) = if s = sep then ((Name.toString nm, v) :: collect r)
else bailOut "Expected record separator ::, but didn't find one!"
| collect _ = bailOut "Expected Yices record constructor syntax, but didn't find one!"
val params = collect args
val fields = map #1 params
in case List.find (fn (_, fts, _, _) => map #1 fts = fields) (!recordTab) of
NONE => bailOut ("Cannot find the HOL record with fields: " ^ commas fields)
| SOME (c, fts, _, _) =>
let val hts = map #2 fts
val values = map (Library.uncurry e2h) (ListPair.zip (map #2 params, map SOME hts))
in SOME (Library.foldl (op $) (Const c, values @ [Const ("Product_Type.Unity", Type ("Product_Type.unit", []))]))
end
end
and special (IL.S_Con nm) args eT
= (case Name.toString nm of
"select" => (case args of (* could be a tuple or a record *)
[t, IL.S_Num i] => if i = 1 then SOME (@{term "fst"} $ e2h t eT)
else if i = 2 then SOME (@{term "snd"} $ e2h t eT)
else NONE
| [t, IL.S_Con n] => SOME (e2h (IL.mk_App [IL.S_Con n, t]) eT)
| _ => NONE)
| "mk-tuple" => (case args of
[e1, e2] => let val (t1, t2) = case eT of
SOME (Type ("*", [t1, t2])) => (SOME t1, SOME t2)
| _ => (NONE, NONE)
in SOME (Library.foldl (op $) (@{term "Pair"}, [e2h e1 t1, e2h e2 t2]))
end
| _ => NONE)
| "mk-record" => mkRecord args
| _ => NONE)
| special _ _ _ = NONE
and e2h (IL.S_Con n) mbType
= (case lookupTermTab (fn (_, (IL.S_Con y, _, _)) => y = n | _ => false) of
NONE => (let fun binOp T = Type ("fun", [T, Type ("fun", [T, T])])
val t = (case mbType of
NONE => HOLogic.intT (* take a guess! *)
| SOME ht => ht)
in (case Name.toString n of