1 (* Title: HOL/Tools/Nitpick/nitpick.ML
2 Author: Jasmin Blanchette, TU Muenchen
3 Copyright 2008, 2009, 2010
5 Finite model generation for HOL formulas using Kodkod.
10 type styp = Nitpick_Util.styp
12 cards_assigns: (typ option * int list) list,
13 maxes_assigns: (styp option * int list) list,
14 iters_assigns: (styp option * int list) list,
16 bisim_depths: int list,
17 boxes: (typ option * bool option) list,
18 monos: (typ option * bool option) list,
19 stds: (typ option * bool) list,
20 wfs: (styp option * bool option) list,
27 user_axioms: bool option,
29 merge_type_vars: bool,
30 binary_ints: bool option,
31 destroy_constrs: bool,
34 star_linear_preds: bool,
38 timeout: Time.time option,
39 tac_timeout: Time.time option,
48 formats: (term option * int list) list,
51 check_potential: bool,
56 val register_frac_type : string -> (string * string) list -> theory -> theory
57 val unregister_frac_type : string -> theory -> theory
58 val register_codatatype : typ -> string -> styp list -> theory -> theory
59 val unregister_codatatype : typ -> theory -> theory
60 val pick_nits_in_term :
61 Proof.state -> params -> bool -> int -> int -> int -> term list -> term
62 -> string * Proof.state
63 val pick_nits_in_subgoal :
64 Proof.state -> params -> bool -> int -> int -> string * Proof.state
67 structure Nitpick : NITPICK =
84 cards_assigns: (typ option * int list) list,
85 maxes_assigns: (styp option * int list) list,
86 iters_assigns: (styp option * int list) list,
88 bisim_depths: int list,
89 boxes: (typ option * bool option) list,
90 monos: (typ option * bool option) list,
91 stds: (typ option * bool) list,
92 wfs: (styp option * bool option) list,
99 user_axioms: bool option,
101 merge_type_vars: bool,
102 binary_ints: bool option,
103 destroy_constrs: bool,
106 star_linear_preds: bool,
109 peephole_optim: bool,
110 timeout: Time.time option,
111 tac_timeout: Time.time option,
117 show_datatypes: bool,
120 formats: (term option * int list) list,
123 check_potential: bool,
128 type problem_extension = {
129 free_names: nut list,
131 nonsel_names: nut list,
132 rel_table: nut NameTable.table,
136 defs: KK.formula list}
138 type rich_problem = KK.problem * problem_extension
140 (* Proof.context -> string -> term list -> Pretty.T list *)
141 fun pretties_for_formulas _ _ [] = []
142 | pretties_for_formulas ctxt s ts =
143 [Pretty.str (s ^ plural_s_for_list ts ^ ":"),
144 Pretty.indent indent_size (Pretty.chunks
145 (map2 (fn j => fn t =>
146 Pretty.block [t |> shorten_names_in_term
147 |> Syntax.pretty_term ctxt,
148 Pretty.str (if j = 1 then "." else ";")])
149 (length ts downto 1) ts))]
152 fun install_kodkodi_message () =
153 "Nitpick requires the external Java program Kodkodi. To install it, download \
154 \the package from Isabelle's web page and add the \"kodkodi-x.y.z\" \
155 \directory's full path to \"" ^
156 Path.implode (Path.expand (Path.appends
157 (Path.variable "ISABELLE_HOME_USER" ::
158 map Path.basic ["etc", "components"]))) ^ "\"."
160 val max_unsound_delay_ms = 200
161 val max_unsound_delay_percent = 2
163 (* Time.time option -> int *)
164 fun unsound_delay_for_timeout NONE = max_unsound_delay_ms
165 | unsound_delay_for_timeout (SOME timeout) =
166 Int.max (0, Int.min (max_unsound_delay_ms,
167 Time.toMilliseconds timeout
168 * max_unsound_delay_percent div 100))
170 (* Time.time option -> bool *)
171 fun passed_deadline NONE = false
172 | passed_deadline (SOME time) = Time.compare (Time.now (), time) <> LESS
174 (* ('a * bool option) list -> bool *)
175 fun none_true assigns = forall (not_equal (SOME true) o snd) assigns
177 val syntactic_sorts =
178 @{sort "{default,zero,one,plus,minus,uminus,times,inverse,abs,sgn,ord,eq}"} @
181 fun has_tfree_syntactic_sort (TFree (_, S as _ :: _)) =
182 subset (op =) (S, syntactic_sorts)
183 | has_tfree_syntactic_sort _ = false
185 val has_syntactic_sorts = exists_type (exists_subtype has_tfree_syntactic_sort)
187 (* (unit -> string) -> Pretty.T *)
188 fun plazy f = Pretty.blk (0, pstrs (f ()))
190 (* Time.time -> Proof.state -> params -> bool -> int -> int -> int -> term
191 -> string * Proof.state *)
192 fun pick_them_nits_in_term deadline state (params : params) auto i n step
193 orig_assm_ts orig_t =
195 val timer = Timer.startRealTimer ()
196 val thy = Proof.theory_of state
197 val ctxt = Proof.context_of state
198 (* FIXME: reintroduce code before new release
199 val nitpick_thy = ThyInfo.get_theory "Nitpick"
200 val _ = Theory.subthy (nitpick_thy, thy) orelse
201 error "You must import the theory \"Nitpick\" to use Nitpick"
203 val {cards_assigns, maxes_assigns, iters_assigns, bitss, bisim_depths,
204 boxes, monos, stds, wfs, sat_solver, falsify, debug, verbose, overlord,
205 user_axioms, assms, merge_type_vars, binary_ints, destroy_constrs,
206 specialize, skolemize, star_linear_preds, uncurry, fast_descrs,
207 peephole_optim, tac_timeout, sym_break, sharing_depth, flatten_props,
208 max_threads, show_skolems, show_datatypes, show_consts, evals, formats,
209 max_potential, max_genuine, check_potential, check_genuine, batch_size,
212 val state_ref = Unsynchronized.ref state
213 (* Pretty.T -> unit *)
216 Unsynchronized.change state_ref o Proof.goal_message o K
217 o Pretty.chunks o cons (Pretty.str "") o single
218 o Pretty.mark Markup.hilite
220 priority o Pretty.string_of
221 (* (unit -> Pretty.T) -> unit *)
222 fun pprint_m f = () |> not auto ? pprint o f
223 fun pprint_v f = () |> verbose ? pprint o f
224 fun pprint_d f = () |> debug ? pprint o f
226 val print = pprint o curry Pretty.blk 0 o pstrs
227 (* (unit -> string) -> unit *)
228 val print_m = pprint_m o K o plazy
229 val print_v = pprint_v o K o plazy
232 fun check_deadline () =
233 if debug andalso passed_deadline deadline then raise TimeLimit.TimeOut
236 fun do_interrupted () =
237 if passed_deadline deadline then raise TimeLimit.TimeOut
242 print_m (fn () => "Nitpicking formula...")
244 pprint_m (fn () => Pretty.chunks (
245 pretties_for_formulas ctxt ("Nitpicking " ^
246 (if i <> 1 orelse n <> 1 then
247 "subgoal " ^ string_of_int i ^ " of " ^ string_of_int n
249 "goal")) [Logic.list_implies (orig_assm_ts, orig_t)]))
250 val neg_t = if falsify then Logic.mk_implies (orig_t, @{prop False})
252 val assms_t = if assms orelse auto then
253 Logic.mk_conjunction_list (neg_t :: orig_assm_ts)
256 val (assms_t, evals) =
257 assms_t :: evals |> merge_type_vars ? merge_type_vars_in_terms
259 val original_max_potential = max_potential
260 val original_max_genuine = max_genuine
262 val _ = priority ("*** " ^ Syntax.string_of_term ctxt orig_t)
263 val _ = List.app (fn t => priority ("*** " ^ Syntax.string_of_term ctxt t))
266 val max_bisim_depth = fold Integer.max bisim_depths ~1
267 val case_names = case_const_names thy stds
268 val (defs, built_in_nondefs, user_nondefs) = all_axioms_of thy
269 val def_table = const_def_table ctxt defs
270 val nondef_table = const_nondef_table (built_in_nondefs @ user_nondefs)
271 val simp_table = Unsynchronized.ref (const_simp_table ctxt)
272 val psimp_table = const_psimp_table ctxt
273 val intro_table = inductive_intro_table ctxt def_table
274 val ground_thm_table = ground_theorem_table thy
275 val ersatz_table = ersatz_table thy
276 val (hol_ctxt as {wf_cache, ...}) =
277 {thy = thy, ctxt = ctxt, max_bisim_depth = max_bisim_depth, boxes = boxes,
278 stds = stds, wfs = wfs, user_axioms = user_axioms, debug = debug,
279 binary_ints = binary_ints, destroy_constrs = destroy_constrs,
280 specialize = specialize, skolemize = skolemize,
281 star_linear_preds = star_linear_preds, uncurry = uncurry,
282 fast_descrs = fast_descrs, tac_timeout = tac_timeout, evals = evals,
283 case_names = case_names, def_table = def_table,
284 nondef_table = nondef_table, user_nondefs = user_nondefs,
285 simp_table = simp_table, psimp_table = psimp_table,
286 intro_table = intro_table, ground_thm_table = ground_thm_table,
287 ersatz_table = ersatz_table, skolems = Unsynchronized.ref [],
288 special_funs = Unsynchronized.ref [],
289 unrolled_preds = Unsynchronized.ref [], wf_cache = Unsynchronized.ref [],
290 constr_cache = Unsynchronized.ref []}
291 val frees = Term.add_frees assms_t []
292 val _ = null (Term.add_tvars assms_t []) orelse
293 raise NOT_SUPPORTED "schematic type variables"
294 val (((def_ts, nondef_ts), (got_all_mono_user_axioms, no_poly_user_axioms)),
295 core_t, binarize) = preprocess_term hol_ctxt assms_t
296 val got_all_user_axioms =
297 got_all_mono_user_axioms andalso no_poly_user_axioms
299 (* styp * (bool * bool) -> unit *)
300 fun print_wf (x, (gfp, wf)) =
301 pprint (Pretty.blk (0,
302 pstrs ("The " ^ (if gfp then "co" else "") ^ "inductive predicate \"")
303 @ Syntax.pretty_term ctxt (Const x) ::
305 "\" was proved well-founded. Nitpick can compute it \
308 "\" could not be proved well-founded. Nitpick might need to \
310 val _ = if verbose then List.app print_wf (!wf_cache) else ()
314 (pretties_for_formulas ctxt "Preprocessed formula" [core_t] @
315 pretties_for_formulas ctxt "Relevant definitional axiom" def_ts @
316 pretties_for_formulas ctxt "Relevant nondefinitional axiom"
318 val _ = List.app (ignore o Term.type_of) (core_t :: def_ts @ nondef_ts)
319 handle TYPE (_, Ts, ts) =>
320 raise TYPE ("Nitpick.pick_them_nits_in_term", Ts, ts)
322 val core_u = nut_from_term hol_ctxt Eq core_t
323 val def_us = map (nut_from_term hol_ctxt DefEq) def_ts
324 val nondef_us = map (nut_from_term hol_ctxt Eq) nondef_ts
325 val (free_names, const_names) =
326 fold add_free_and_const_names (core_u :: def_us @ nondef_us) ([], [])
327 val (sel_names, nonsel_names) =
328 List.partition (is_sel o nickname_of) const_names
329 val genuine_means_genuine = got_all_user_axioms andalso none_true wfs
330 val standard = forall snd stds
332 val _ = List.app (priority o string_for_nut ctxt)
333 (core_u :: def_us @ nondef_us)
336 val unique_scope = forall (curry (op =) 1 o length o snd) cards_assigns
338 fun is_type_always_monotonic T =
339 (is_datatype thy stds T andalso not (is_quot_type thy T) andalso
340 (not (is_pure_typedef thy T) orelse is_univ_typedef thy T)) orelse
341 is_number_type thy T orelse is_bit_type T
342 fun is_type_monotonic T =
344 case triple_lookup (type_match thy) monos T of
346 | _ => is_type_always_monotonic T orelse
347 formulas_monotonic hol_ctxt binarize T Plus def_ts nondef_ts core_t
348 fun is_deep_datatype T =
349 is_datatype thy stds T andalso
350 (not standard orelse T = nat_T orelse is_word_type T orelse
351 exists (curry (op =) T o domain_type o type_of) sel_names)
352 val all_Ts = ground_types_in_terms hol_ctxt binarize
353 (core_t :: def_ts @ nondef_ts)
354 |> sort TermOrd.typ_ord
355 val _ = if verbose andalso binary_ints = SOME true andalso
356 exists (member (op =) [nat_T, int_T]) all_Ts then
357 print_v (K "The option \"binary_ints\" will be ignored because \
358 \of the presence of rationals, reals, \"Suc\", \
359 \\"gcd\", or \"lcm\" in the problem.")
362 val (mono_Ts, nonmono_Ts) = List.partition is_type_monotonic all_Ts
364 if verbose andalso not unique_scope then
365 case filter_out is_type_always_monotonic mono_Ts of
367 | interesting_mono_Ts =>
370 val ss = map (quote o string_for_type ctxt)
373 "The type" ^ plural_s_for_list ss ^ " " ^
374 space_implode " " (serial_commas "and" ss) ^ " " ^
375 (if none_true monos then
376 "passed the monotonicity test"
378 (if length ss = 1 then "is" else "are") ^
379 " considered monotonic") ^
380 ". Nitpick might be able to skip some scopes."
384 val deep_dataTs = filter is_deep_datatype all_Ts
385 (* This detection code is an ugly hack. Fortunately, it is used only to
386 provide a hint to the user. *)
387 (* string * (Rule_Cases.T * bool) -> bool *)
388 fun is_struct_induct_step (name, (Rule_Cases.Case {fixes, assumes, ...}, _)) =
389 not (null fixes) andalso
390 exists (String.isSuffix ".hyps" o fst) assumes andalso
391 exists (exists (curry (op =) name o shortest_name o fst)
392 o datatype_constrs hol_ctxt) deep_dataTs
393 val likely_in_struct_induct_step =
394 exists is_struct_induct_step (ProofContext.cases_of ctxt)
395 val _ = if standard andalso likely_in_struct_induct_step then
396 pprint_m (fn () => Pretty.blk (0,
397 pstrs "Hint: To check that the induction hypothesis is \
398 \general enough, try this command: " @
399 [Pretty.mark Markup.sendback (Pretty.blk (0,
400 pstrs ("nitpick [non_std, show_all]")))] @ pstrs "."))
404 val _ = priority "Monotonic types:"
405 val _ = List.app (priority o string_for_type ctxt) mono_Ts
406 val _ = priority "Nonmonotonic types:"
407 val _ = List.app (priority o string_for_type ctxt) nonmono_Ts
410 val need_incremental = Int.max (max_potential, max_genuine) >= 2
411 val effective_sat_solver =
412 if sat_solver <> "smart" then
413 if need_incremental andalso
414 not (member (op =) (Kodkod_SAT.configured_sat_solvers true)
416 (print_m (K ("An incremental SAT solver is required: \"SAT4J\" will \
417 \be used instead of " ^ quote sat_solver ^ "."));
422 Kodkod_SAT.smart_sat_solver_name need_incremental
424 if sat_solver = "smart" then
425 print_v (fn () => "Using SAT solver " ^ quote effective_sat_solver ^
427 (if need_incremental then " incremental " else " ") ^
428 "solvers are configured: " ^
429 commas (map quote (Kodkod_SAT.configured_sat_solvers
430 need_incremental)) ^ ".")
434 val too_big_scopes = Unsynchronized.ref []
436 (* bool -> scope -> rich_problem option *)
437 fun problem_for_scope unsound
438 (scope as {card_assigns, bits, bisim_depth, datatypes, ofs, ...}) =
440 val _ = not (exists (fn other => scope_less_eq other scope)
441 (!too_big_scopes)) orelse
442 raise TOO_LARGE ("Nitpick.pick_them_nits_in_term.\
443 \problem_for_scope", "too large scope")
445 val _ = priority "Offsets:"
446 val _ = List.app (fn (T, j0) =>
447 priority (string_for_type ctxt T ^ " = " ^
451 val all_exact = forall (is_exact_type datatypes) all_Ts
452 (* nut list -> rep NameTable.table -> nut list * rep NameTable.table *)
453 val repify_consts = choose_reps_for_consts scope all_exact
454 val main_j0 = offset_of_type ofs bool_T
455 val (nat_card, nat_j0) = spec_of_type scope nat_T
456 val (int_card, int_j0) = spec_of_type scope int_T
457 val _ = (nat_j0 = main_j0 andalso int_j0 = main_j0) orelse
458 raise BAD ("Nitpick.pick_them_nits_in_term.problem_for_scope",
460 val kk = kodkod_constrs peephole_optim nat_card int_card main_j0
461 val (free_names, rep_table) =
462 choose_reps_for_free_vars scope free_names NameTable.empty
463 val (sel_names, rep_table) = choose_reps_for_all_sels scope rep_table
464 val (nonsel_names, rep_table) = repify_consts nonsel_names rep_table
465 val min_highest_arity =
466 NameTable.fold (curry Int.max o arity_of_rep o snd) rep_table 1
468 NameTable.fold (curry Int.max o min_univ_card_of_rep o snd) rep_table
469 (univ_card nat_card int_card main_j0 [] KK.True)
470 val _ = check_arity min_univ_card min_highest_arity
472 val core_u = choose_reps_in_nut scope unsound rep_table false core_u
473 val def_us = map (choose_reps_in_nut scope unsound rep_table true)
475 val nondef_us = map (choose_reps_in_nut scope unsound rep_table false)
478 val _ = List.app (priority o string_for_nut ctxt)
479 (free_names @ sel_names @ nonsel_names @
480 core_u :: def_us @ nondef_us)
482 val (free_rels, pool, rel_table) =
483 rename_free_vars free_names initial_pool NameTable.empty
484 val (sel_rels, pool, rel_table) =
485 rename_free_vars sel_names pool rel_table
486 val (other_rels, pool, rel_table) =
487 rename_free_vars nonsel_names pool rel_table
488 val core_u = rename_vars_in_nut pool rel_table core_u
489 val def_us = map (rename_vars_in_nut pool rel_table) def_us
490 val nondef_us = map (rename_vars_in_nut pool rel_table) nondef_us
491 val core_f = kodkod_formula_from_nut ofs kk core_u
492 val def_fs = map (kodkod_formula_from_nut ofs kk) def_us
493 val nondef_fs = map (kodkod_formula_from_nut ofs kk) nondef_us
494 val formula = fold (fold s_and) [def_fs, nondef_fs] core_f
495 val comment = (if unsound then "unsound" else "sound") ^ "\n" ^
496 PrintMode.setmp [] multiline_string_for_scope scope
497 val kodkod_sat_solver =
498 Kodkod_SAT.sat_solver_spec effective_sat_solver |> snd
499 val bit_width = if bits = 0 then 16 else bits + 1
500 val delay = if unsound then
501 Option.map (fn time => Time.- (time, Time.now ()))
503 |> unsound_delay_for_timeout
506 val settings = [("solver", commas (map quote kodkod_sat_solver)),
507 ("skolem_depth", "-1"),
508 ("bit_width", string_of_int bit_width),
509 ("symmetry_breaking", signed_string_of_int sym_break),
510 ("sharing", signed_string_of_int sharing_depth),
511 ("flatten", Bool.toString flatten_props),
512 ("delay", signed_string_of_int delay)]
513 val plain_rels = free_rels @ other_rels
514 val plain_bounds = map (bound_for_plain_rel ctxt debug) plain_rels
515 val plain_axioms = map (declarative_axiom_for_plain_rel kk) plain_rels
516 val sel_bounds = map (bound_for_sel_rel ctxt debug datatypes) sel_rels
518 declarative_axioms_for_datatypes hol_ctxt binarize bits ofs kk
520 val declarative_axioms = plain_axioms @ dtype_axioms
521 val univ_card = Int.max (univ_card nat_card int_card main_j0
522 (plain_bounds @ sel_bounds) formula,
523 main_j0 |> bits > 0 ? Integer.add (bits + 1))
524 val built_in_bounds = bounds_for_built_in_rels_in_formula debug
525 univ_card nat_card int_card main_j0 formula
526 val bounds = built_in_bounds @ plain_bounds @ sel_bounds
527 |> not debug ? merge_bounds
529 fold Integer.max (map (fst o fst) (maps fst bounds)) 0
530 val formula = fold_rev s_and declarative_axioms formula
531 val _ = if bits = 0 then () else check_bits bits formula
532 val _ = if formula = KK.False then ()
533 else check_arity univ_card highest_arity
535 SOME ({comment = comment, settings = settings, univ_card = univ_card,
536 tuple_assigns = [], bounds = bounds,
537 int_bounds = if bits = 0 then sequential_int_bounds univ_card
538 else pow_of_two_int_bounds bits main_j0,
539 expr_assigns = [], formula = formula},
540 {free_names = free_names, sel_names = sel_names,
541 nonsel_names = nonsel_names, rel_table = rel_table,
542 unsound = unsound, scope = scope, core = core_f,
543 defs = nondef_fs @ def_fs @ declarative_axioms})
545 handle TOO_LARGE (loc, msg) =>
546 if loc = "Nitpick_Kodkod.check_arity" andalso
547 not (Typtab.is_empty ofs) then
548 problem_for_scope unsound
549 {hol_ctxt = hol_ctxt, binarize = binarize,
550 card_assigns = card_assigns, bits = bits,
551 bisim_depth = bisim_depth, datatypes = datatypes,
553 else if loc = "Nitpick.pick_them_nits_in_term.\
554 \problem_for_scope" then
557 (Unsynchronized.change too_big_scopes (cons scope);
558 print_v (fn () => ("Limit reached: " ^ msg ^
559 ". Skipping " ^ (if unsound then "potential"
561 " component of scope."));
563 | TOO_SMALL (_, msg) =>
564 (print_v (fn () => ("Limit reached: " ^ msg ^
565 ". Skipping " ^ (if unsound then "potential"
567 " component of scope."));
571 (if falsify then "counterexample" else "model")
572 |> not standard ? prefix "nonstandard "
574 val scopes = Unsynchronized.ref []
575 val generated_scopes = Unsynchronized.ref []
576 val generated_problems = Unsynchronized.ref ([] : rich_problem list)
577 val checked_problems = Unsynchronized.ref (SOME [])
578 val met_potential = Unsynchronized.ref 0
580 (* rich_problem list -> int list -> unit *)
581 fun update_checked_problems problems =
582 List.app (Unsynchronized.change checked_problems o Option.map o cons
585 (* bool -> KK.raw_bound list -> problem_extension -> bool option *)
586 fun print_and_check_model genuine bounds
587 ({free_names, sel_names, nonsel_names, rel_table, scope, ...}
588 : problem_extension) =
590 val (reconstructed_model, codatatypes_ok) =
591 reconstruct_hol_model {show_skolems = show_skolems,
592 show_datatypes = show_datatypes,
593 show_consts = show_consts}
594 scope formats frees free_names sel_names nonsel_names rel_table
596 val genuine_means_genuine = genuine_means_genuine andalso codatatypes_ok
598 pprint (Pretty.chunks
600 (pstrs ("Nitpick found a" ^
601 (if not genuine then " potential "
602 else if genuine_means_genuine then " "
603 else " likely genuine ") ^ das_wort_model) @
604 (case pretties_for_scope scope verbose of
606 | pretties => pstrs " for " @ pretties) @
607 [Pretty.str ":\n"])),
608 Pretty.indent indent_size reconstructed_model]);
610 (if check_genuine andalso standard then
611 (case prove_hol_model scope tac_timeout free_names sel_names
612 rel_table bounds assms_t of
613 SOME true => print ("Confirmation by \"auto\": The above " ^
614 das_wort_model ^ " is really genuine.")
616 if genuine_means_genuine then
617 error ("A supposedly genuine " ^ das_wort_model ^ " was \
618 \shown to be spurious by \"auto\".\nThis should never \
619 \happen.\nPlease send a bug report to blanchet\
622 print ("Refutation by \"auto\": The above " ^ das_wort_model ^
624 | NONE => print "No confirmation by \"auto\".")
627 if not standard andalso likely_in_struct_induct_step then
628 print "The existence of a nonstandard model suggests that the \
629 \induction hypothesis is not general enough or perhaps even \
630 \wrong. See the \"Inductive Properties\" section of the \
631 \Nitpick manual for details (\"isabelle doc nitpick\")."
634 if has_syntactic_sorts orig_t then
635 print "Hint: Maybe you forgot a type constraint?"
638 if not genuine_means_genuine then
639 if no_poly_user_axioms then
642 [] |> not got_all_mono_user_axioms
643 ? cons ("user_axioms", "\"true\"")
644 |> not (none_true wfs)
645 ? cons ("wf", "\"smart\" or \"false\"")
646 |> not codatatypes_ok
647 ? cons ("bisim_depth", "a nonnegative value")
649 map (fn (name, value) => quote name ^ " set to " ^ value)
652 print ("Try again with " ^
653 space_implode " " (serial_commas "and" ss) ^
654 " to confirm that the " ^ das_wort_model ^
658 print ("Nitpick is unable to guarantee the authenticity of \
659 \the " ^ das_wort_model ^ " in the presence of \
660 \polymorphic axioms.")
666 (Unsynchronized.inc met_potential;
667 if check_potential then
669 val status = prove_hol_model scope tac_timeout free_names
670 sel_names rel_table bounds assms_t
673 SOME true => print ("Confirmation by \"auto\": The above " ^
674 das_wort_model ^ " is genuine.")
675 | SOME false => print ("Refutation by \"auto\": The above " ^
676 das_wort_model ^ " is spurious.")
677 | NONE => print "No confirmation by \"auto\".");
685 (* int -> int -> int -> bool -> rich_problem list -> int * int * int *)
686 fun solve_any_problem max_potential max_genuine donno first_time problems =
688 val max_potential = Int.max (0, max_potential)
689 val max_genuine = Int.max (0, max_genuine)
690 (* bool -> int * KK.raw_bound list -> bool option *)
691 fun print_and_check genuine (j, bounds) =
692 print_and_check_model genuine bounds (snd (nth problems j))
693 val max_solutions = max_potential + max_genuine
694 |> not need_incremental ? curry Int.min 1
696 if max_solutions <= 0 then
699 case KK.solve_any_problem overlord deadline max_threads max_solutions
700 (map fst problems) of
702 (print_m install_kodkodi_message;
703 (max_potential, max_genuine, donno + 1))
704 | KK.Normal ([], unsat_js) =>
705 (update_checked_problems problems unsat_js;
706 (max_potential, max_genuine, donno))
707 | KK.Normal (sat_ps, unsat_js) =>
709 val (lib_ps, con_ps) =
710 List.partition (#unsound o snd o nth problems o fst) sat_ps
712 update_checked_problems problems (unsat_js @ map fst lib_ps);
715 val num_genuine = take max_potential lib_ps
716 |> map (print_and_check false)
717 |> filter (curry (op =) (SOME true))
719 val max_genuine = max_genuine - num_genuine
720 val max_potential = max_potential
721 - (length lib_ps - num_genuine)
723 if max_genuine <= 0 then
727 (* "co_js" is the list of sound problems whose unsound
728 pendants couldn't be satisfied and hence that most
729 probably can't be satisfied themselves. *)
731 map (fn j => j - 1) unsat_js
735 (#scope (snd (nth problems j)))
736 (#scope (snd (nth problems (j + 1)))))
737 val bye_js = sort_distinct int_ord (map fst sat_ps @
740 problems |> filter_out_indices bye_js
741 |> max_potential <= 0
742 ? filter_out (#unsound o snd)
744 solve_any_problem max_potential max_genuine donno false
750 val _ = take max_genuine con_ps
751 |> List.app (ignore o print_and_check true)
752 val max_genuine = max_genuine - length con_ps
754 if max_genuine <= 0 orelse not first_time then
755 (0, max_genuine, donno)
758 val bye_js = sort_distinct int_ord
759 (map fst sat_ps @ unsat_js)
761 problems |> filter_out_indices bye_js
762 |> filter_out (#unsound o snd)
763 in solve_any_problem 0 max_genuine donno false problems end
766 | KK.TimedOut unsat_js =>
767 (update_checked_problems problems unsat_js; raise TimeLimit.TimeOut)
768 | KK.Interrupted NONE => (checked_problems := NONE; do_interrupted ())
769 | KK.Interrupted (SOME unsat_js) =>
770 (update_checked_problems problems unsat_js; do_interrupted ())
771 | KK.Error (s, unsat_js) =>
772 (update_checked_problems problems unsat_js;
773 print_v (K ("Kodkod error: " ^ s ^ "."));
774 (max_potential, max_genuine, donno + 1))
777 (* int -> int -> scope list -> int * int * int -> int * int * int *)
778 fun run_batch j n scopes (max_potential, max_genuine, donno) =
782 print_m (K "The scope specification is inconsistent.")
784 pprint (Pretty.chunks
786 pstrs ((if n > 1 then
787 "Batch " ^ string_of_int (j + 1) ^ " of " ^
788 signed_string_of_int n ^ ": "
791 "Trying " ^ string_of_int (length scopes) ^
792 " scope" ^ plural_s_for_list scopes ^ ":")),
793 Pretty.indent indent_size
797 (case pretties_for_scope scope true of
798 [] => [Pretty.str "Empty"]
799 | pretties => pretties) @
800 [Pretty.str (if j = 1 then "." else ";")]))
801 (length scopes downto 1) scopes))])
804 (* scope * bool -> rich_problem list * bool
805 -> rich_problem list * bool *)
806 fun add_problem_for_scope (scope, unsound) (problems, donno) =
808 case problem_for_scope unsound scope of
811 |> (null problems orelse
812 not (KK.problems_equivalent (fst problem)
813 (fst (hd problems))))
814 ? cons problem, donno)
815 | NONE => (problems, donno + 1))
816 val (problems, donno) =
817 fold add_problem_for_scope
818 (map_product pair scopes
819 ((if max_genuine > 0 then [false] else []) @
820 (if max_potential > 0 then [true] else [])))
822 val _ = Unsynchronized.change generated_problems (append problems)
823 val _ = Unsynchronized.change generated_scopes (append scopes)
827 val (unsound_problems, sound_problems) =
828 List.partition (#unsound o snd) (!generated_problems)
830 if not (null sound_problems) andalso
831 forall (KK.is_problem_trivially_false o fst)
834 "Warning: The conjecture either trivially holds for the \
835 \given scopes or (more likely) lies outside Nitpick's \
836 \supported fragment." ^
837 (if exists (not o KK.is_problem_trivially_false o fst)
838 unsound_problems then
839 " Only potential counterexamples may be found."
848 solve_any_problem max_potential max_genuine donno true (rev problems)
851 (* rich_problem list -> scope -> int *)
852 fun scope_count (problems : rich_problem list) scope =
853 length (filter (scopes_equivalent scope o #scope o snd) problems)
854 (* string -> string *)
855 fun excipit did_so_and_so =
857 (* rich_problem list -> rich_problem list *)
859 if !met_potential = max_potential then filter_out (#unsound o snd)
861 val total = length (!scopes)
864 case scope_count (do_filter (!generated_problems)) scope of
867 scope_count (do_filter (these (!checked_problems)))
869 ? Integer.add 1) (!generated_scopes) 0
871 "Nitpick " ^ did_so_and_so ^
872 (if is_some (!checked_problems) andalso total > 0 then
874 string_of_int (Int.min (total - 1, unsat)) ^ " of " ^
875 string_of_int total ^ " scope" ^ plural_s total
880 (* int -> int -> scope list -> int * int * int -> KK.outcome *)
881 fun run_batches _ _ [] (max_potential, max_genuine, donno) =
882 if donno > 0 andalso max_genuine > 0 then
883 (print_m (fn () => excipit "ran out of some resource"); "unknown")
884 else if max_genuine = original_max_genuine then
885 if max_potential = original_max_potential then
887 "Nitpick found no " ^ das_wort_model ^ "." ^
888 (if not standard andalso likely_in_struct_induct_step then
889 " This suggests that the induction hypothesis might be \
890 \general enough to prove this subgoal."
895 "Nitpick could not find a" ^
896 (if max_genuine = 1 then " better " ^ das_wort_model ^ "."
897 else "ny better " ^ das_wort_model ^ "s.")); "potential")
899 if genuine_means_genuine then "genuine" else "likely_genuine"
900 | run_batches j n (batch :: batches) z =
901 let val (z as (_, max_genuine, _)) = run_batch j n batch z in
902 run_batches (j + 1) n (if max_genuine > 0 then batches else []) z
905 val (skipped, the_scopes) =
906 all_scopes hol_ctxt binarize sym_break cards_assigns maxes_assigns
907 iters_assigns bitss bisim_depths mono_Ts nonmono_Ts deep_dataTs
908 val _ = if skipped > 0 then
909 print_m (fn () => "Too many scopes. Skipping " ^
910 string_of_int skipped ^ " scope" ^
912 ". (Consider using \"mono\" or \
913 \\"merge_type_vars\" to prevent this.)")
916 val _ = scopes := the_scopes
918 val batches = batch_list batch_size (!scopes)
920 (run_batches 0 (length batches) batches (max_potential, max_genuine, 0)
921 handle Exn.Interrupt => do_interrupted ())
922 handle TimeLimit.TimeOut =>
923 (print_m (fn () => excipit "ran out of time");
924 if !met_potential > 0 then "potential" else "unknown")
925 | Exn.Interrupt => if auto orelse debug then raise Interrupt
926 else error (excipit "was interrupted")
927 val _ = print_v (fn () => "Total time: " ^
928 signed_string_of_int (Time.toMilliseconds
929 (Timer.checkRealTimer timer)) ^ " ms.")
930 in (outcome_code, !state_ref) end
931 handle Exn.Interrupt =>
932 if auto orelse #debug params then
935 if passed_deadline deadline then
936 (priority "Nitpick ran out of time."; ("unknown", state))
938 error "Nitpick was interrupted."
940 (* Proof.state -> params -> bool -> int -> int -> int -> term
941 -> string * Proof.state *)
942 fun pick_nits_in_term state (params as {debug, timeout, expect, ...}) auto i n
943 step orig_assm_ts orig_t =
944 if getenv "KODKODI" = "" then
946 else warning (Pretty.string_of (plazy install_kodkodi_message));
950 val deadline = Option.map (curry Time.+ (Time.now ())) timeout
951 val outcome as (outcome_code, _) =
952 time_limit (if debug then NONE else timeout)
953 (pick_them_nits_in_term deadline state params auto i n step
956 if expect = "" orelse outcome_code = expect then outcome
957 else error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
960 (* Proof.state -> params -> bool -> int -> int -> string * Proof.state *)
961 fun pick_nits_in_subgoal state params auto i step =
963 val ctxt = Proof.context_of state
964 val t = state |> Proof.raw_goal |> #goal |> prop_of
966 case Logic.count_prems t of
967 0 => (priority "No subgoal!"; ("none", state))
970 val assms = map term_of (Assumption.all_assms_of ctxt)
971 val (t, frees) = Logic.goal_params t i
973 pick_nits_in_term state params auto i n step assms
974 (subst_bounds (frees, t))