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 finitizes: (typ option * bool option) list,
19 monos: (typ option * bool option) list,
20 stds: (typ option * bool) list,
21 wfs: (styp option * bool option) list,
28 user_axioms: bool option,
30 merge_type_vars: bool,
31 binary_ints: bool option,
32 destroy_constrs: bool,
35 star_linear_preds: bool,
39 timeout: Time.time option,
40 tac_timeout: Time.time option,
49 formats: (term option * int list) list,
52 check_potential: bool,
57 val register_frac_type : string -> (string * string) list -> theory -> theory
58 val unregister_frac_type : string -> theory -> theory
59 val register_codatatype : typ -> string -> styp list -> theory -> theory
60 val unregister_codatatype : typ -> theory -> theory
61 val pick_nits_in_term :
62 Proof.state -> params -> bool -> int -> int -> int -> (term * term) list
63 -> term list -> term -> string * Proof.state
64 val pick_nits_in_subgoal :
65 Proof.state -> params -> bool -> int -> int -> string * Proof.state
68 structure Nitpick : NITPICK =
85 cards_assigns: (typ option * int list) list,
86 maxes_assigns: (styp option * int list) list,
87 iters_assigns: (styp option * int list) list,
89 bisim_depths: int list,
90 boxes: (typ option * bool option) list,
91 finitizes: (typ option * bool option) list,
92 monos: (typ option * bool option) list,
93 stds: (typ option * bool) list,
94 wfs: (styp option * bool option) list,
101 user_axioms: bool option,
103 merge_type_vars: bool,
104 binary_ints: bool option,
105 destroy_constrs: bool,
108 star_linear_preds: bool,
111 peephole_optim: bool,
112 timeout: Time.time option,
113 tac_timeout: Time.time option,
119 show_datatypes: bool,
122 formats: (term option * int list) list,
125 check_potential: bool,
130 type problem_extension = {
131 free_names: nut list,
133 nonsel_names: nut list,
134 rel_table: nut NameTable.table,
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
191 -> (term * term) list -> term list -> term -> string * Proof.state *)
192 fun pick_them_nits_in_term deadline state (params : params) auto i n step
193 subst 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:
200 val nitpick_thy = ThyInfo.get_theory "Nitpick"
201 val _ = Theory.subthy (nitpick_thy, thy) orelse
202 error "You must import the theory \"Nitpick\" to use Nitpick"
204 val {cards_assigns, maxes_assigns, iters_assigns, bitss, bisim_depths,
205 boxes, finitizes, monos, stds, wfs, sat_solver, falsify, debug,
206 verbose, overlord, user_axioms, assms, merge_type_vars, binary_ints,
207 destroy_constrs, specialize, skolemize, star_linear_preds, uncurry,
208 fast_descrs, peephole_optim, tac_timeout, sym_break, sharing_depth,
209 flatten_props, max_threads, show_skolems, show_datatypes, show_consts,
210 evals, formats, max_potential, max_genuine, check_potential,
211 check_genuine, batch_size, ...} =
213 val state_ref = Unsynchronized.ref state
214 (* Pretty.T -> unit *)
217 Unsynchronized.change state_ref o Proof.goal_message o K
218 o Pretty.chunks o cons (Pretty.str "") o single
219 o Pretty.mark Markup.hilite
221 priority o Pretty.string_of
222 (* (unit -> Pretty.T) -> unit *)
223 fun pprint_m f = () |> not auto ? pprint o f
224 fun pprint_v f = () |> verbose ? pprint o f
225 fun pprint_d f = () |> debug ? pprint o f
227 val print = pprint o curry Pretty.blk 0 o pstrs
228 (* (unit -> string) -> unit *)
229 val print_m = pprint_m o K o plazy
230 val print_v = pprint_v o K o plazy
233 fun check_deadline () =
234 if debug andalso passed_deadline deadline then raise TimeLimit.TimeOut
237 fun do_interrupted () =
238 if passed_deadline deadline then raise TimeLimit.TimeOut
241 val orig_assm_ts = if assms orelse auto then orig_assm_ts else []
244 print_m (fn () => "Nitpicking formula...")
246 pprint_m (fn () => Pretty.chunks (
247 pretties_for_formulas ctxt ("Nitpicking " ^
248 (if i <> 1 orelse n <> 1 then
249 "subgoal " ^ string_of_int i ^ " of " ^ string_of_int n
251 "goal")) [Logic.list_implies (orig_assm_ts, orig_t)]))
252 val neg_t = if falsify then Logic.mk_implies (orig_t, @{prop False})
254 val assms_t = Logic.mk_conjunction_list (neg_t :: orig_assm_ts)
255 val (assms_t, evals) =
256 assms_t :: evals |> merge_type_vars ? merge_type_vars_in_terms
258 val original_max_potential = max_potential
259 val original_max_genuine = max_genuine
261 val _ = priority ("*** " ^ Syntax.string_of_term ctxt orig_t)
262 val _ = List.app (fn t => priority ("*** " ^ Syntax.string_of_term ctxt t))
265 val max_bisim_depth = fold Integer.max bisim_depths ~1
266 val case_names = case_const_names thy stds
267 val (defs, built_in_nondefs, user_nondefs) = all_axioms_of thy subst
268 val def_table = const_def_table ctxt subst defs
269 val nondef_table = const_nondef_table (built_in_nondefs @ user_nondefs)
270 val simp_table = Unsynchronized.ref (const_simp_table ctxt subst)
271 val psimp_table = const_psimp_table ctxt subst
272 val intro_table = inductive_intro_table ctxt subst def_table
273 val ground_thm_table = ground_theorem_table thy
274 val ersatz_table = ersatz_table thy
275 val (hol_ctxt as {wf_cache, ...}) =
276 {thy = thy, ctxt = ctxt, max_bisim_depth = max_bisim_depth, boxes = boxes,
277 stds = stds, wfs = wfs, user_axioms = user_axioms, debug = debug,
278 binary_ints = binary_ints, destroy_constrs = destroy_constrs,
279 specialize = specialize, skolemize = skolemize,
280 star_linear_preds = star_linear_preds, uncurry = uncurry,
281 fast_descrs = fast_descrs, tac_timeout = tac_timeout, evals = evals,
282 case_names = case_names, def_table = def_table,
283 nondef_table = nondef_table, user_nondefs = user_nondefs,
284 simp_table = simp_table, psimp_table = psimp_table,
285 intro_table = intro_table, ground_thm_table = ground_thm_table,
286 ersatz_table = ersatz_table, skolems = Unsynchronized.ref [],
287 special_funs = Unsynchronized.ref [],
288 unrolled_preds = Unsynchronized.ref [], wf_cache = Unsynchronized.ref [],
289 constr_cache = Unsynchronized.ref []}
290 val frees = Term.add_frees assms_t []
291 val _ = null (Term.add_tvars assms_t []) orelse
292 raise NOT_SUPPORTED "schematic type variables"
293 val (nondef_ts, def_ts, got_all_mono_user_axioms, no_poly_user_axioms,
294 binarize) = preprocess_term hol_ctxt finitizes monos assms_t
295 val got_all_user_axioms =
296 got_all_mono_user_axioms andalso no_poly_user_axioms
298 (* styp * (bool * bool) -> unit *)
299 fun print_wf (x, (gfp, wf)) =
300 pprint (Pretty.blk (0,
301 pstrs ("The " ^ (if gfp then "co" else "") ^ "inductive predicate \"")
302 @ Syntax.pretty_term ctxt (Const x) ::
304 "\" was proved well-founded. Nitpick can compute it \
307 "\" could not be proved well-founded. Nitpick might need to \
309 val _ = if verbose then List.app print_wf (!wf_cache) else ()
311 pprint_d (fn () => Pretty.chunks
312 (pretties_for_formulas ctxt "Preprocessed formula" [hd nondef_ts] @
313 pretties_for_formulas ctxt "Relevant definitional axiom" def_ts @
314 pretties_for_formulas ctxt "Relevant nondefinitional axiom"
316 val _ = List.app (ignore o Term.type_of) (nondef_ts @ def_ts)
317 handle TYPE (_, Ts, ts) =>
318 raise TYPE ("Nitpick.pick_them_nits_in_term", Ts, ts)
320 val nondef_us = map (nut_from_term hol_ctxt Eq) nondef_ts
321 val def_us = map (nut_from_term hol_ctxt DefEq) def_ts
322 val (free_names, const_names) =
323 fold add_free_and_const_names (nondef_us @ def_us) ([], [])
324 val (sel_names, nonsel_names) =
325 List.partition (is_sel o nickname_of) const_names
326 val sound_finitizes =
327 none_true (filter_out (fn (SOME (Type (@{type_name fun}, _)), _) => true
328 | _ => false) finitizes)
329 val genuine_means_genuine =
330 got_all_user_axioms andalso none_true wfs andalso sound_finitizes
331 val standard = forall snd stds
333 val _ = List.app (priority o string_for_nut ctxt) (nondef_us @ def_us)
336 val unique_scope = forall (curry (op =) 1 o length o snd) cards_assigns
337 (* typ list -> string -> string *)
338 fun monotonicity_message Ts extra =
339 let val ss = map (quote o string_for_type ctxt) Ts in
340 "The type" ^ plural_s_for_list ss ^ " " ^
341 space_implode " " (serial_commas "and" ss) ^ " " ^
342 (if none_true monos then
343 "passed the monotonicity test"
345 (if length ss = 1 then "is" else "are") ^ " considered monotonic") ^
349 fun is_type_fundamentally_monotonic T =
350 (is_datatype thy stds T andalso not (is_quot_type thy T) andalso
351 (not (is_pure_typedef thy T) orelse is_univ_typedef thy T)) orelse
352 is_number_type thy T orelse is_bit_type T
353 fun is_type_actually_monotonic T =
354 formulas_monotonic hol_ctxt binarize T (nondef_ts, def_ts)
355 fun is_type_kind_of_monotonic T =
356 case triple_lookup (type_match thy) monos T of
357 SOME (SOME false) => false
358 | _ => is_type_actually_monotonic T
359 fun is_type_monotonic T =
361 case triple_lookup (type_match thy) monos T of
363 | _ => is_type_fundamentally_monotonic T orelse
364 is_type_actually_monotonic T
365 fun is_shallow_datatype_finitizable (T as Type (@{type_name fin_fun}, _)) =
366 is_type_kind_of_monotonic T
367 | is_shallow_datatype_finitizable (T as Type (@{type_name fun_box}, _)) =
368 is_type_kind_of_monotonic T
369 | is_shallow_datatype_finitizable T =
370 case triple_lookup (type_match thy) finitizes T of
372 | _ => is_type_kind_of_monotonic T
373 fun is_datatype_deep T =
374 not standard orelse T = nat_T orelse is_word_type T orelse
375 exists (curry (op =) T o domain_type o type_of) sel_names
376 val all_Ts = ground_types_in_terms hol_ctxt binarize (nondef_ts @ def_ts)
377 |> sort Term_Ord.typ_ord
378 val _ = if verbose andalso binary_ints = SOME true andalso
379 exists (member (op =) [nat_T, int_T]) all_Ts then
380 print_v (K "The option \"binary_ints\" will be ignored because \
381 \of the presence of rationals, reals, \"Suc\", \
382 \\"gcd\", or \"lcm\" in the problem or because of the \
383 \\"non_std\" option.")
386 val (mono_Ts, nonmono_Ts) = List.partition is_type_monotonic all_Ts
388 if verbose andalso not unique_scope then
389 case filter_out is_type_fundamentally_monotonic mono_Ts of
391 | interesting_mono_Ts =>
392 print_v (K (monotonicity_message interesting_mono_Ts
393 "Nitpick might be able to skip some scopes."))
396 val (deep_dataTs, shallow_dataTs) =
397 all_Ts |> filter (is_datatype thy stds) |> List.partition is_datatype_deep
398 val finitizable_dataTs =
399 shallow_dataTs |> filter_out (is_finite_type hol_ctxt)
400 |> filter is_shallow_datatype_finitizable
402 if verbose andalso not (null finitizable_dataTs) then
403 print_v (K (monotonicity_message finitizable_dataTs
404 "Nitpick can use a more precise finite encoding."))
407 (* This detection code is an ugly hack. Fortunately, it is used only to
408 provide a hint to the user. *)
409 (* string * (Rule_Cases.T * bool) -> bool *)
410 fun is_struct_induct_step (name, (Rule_Cases.Case {fixes, assumes, ...}, _)) =
411 not (null fixes) andalso
412 exists (String.isSuffix ".hyps" o fst) assumes andalso
413 exists (exists (curry (op =) name o shortest_name o fst)
414 o datatype_constrs hol_ctxt) deep_dataTs
415 val likely_in_struct_induct_step =
416 exists is_struct_induct_step (ProofContext.cases_of ctxt)
417 val _ = if standard andalso likely_in_struct_induct_step then
418 pprint_m (fn () => Pretty.blk (0,
419 pstrs "Hint: To check that the induction hypothesis is \
420 \general enough, try this command: " @
421 [Pretty.mark Markup.sendback (Pretty.blk (0,
422 pstrs ("nitpick [non_std, show_all]")))] @ pstrs "."))
426 val _ = priority "Monotonic types:"
427 val _ = List.app (priority o string_for_type ctxt) mono_Ts
428 val _ = priority "Nonmonotonic types:"
429 val _ = List.app (priority o string_for_type ctxt) nonmono_Ts
432 val need_incremental = Int.max (max_potential, max_genuine) >= 2
433 val effective_sat_solver =
434 if sat_solver <> "smart" then
435 if need_incremental andalso
436 not (member (op =) (Kodkod_SAT.configured_sat_solvers true)
438 (print_m (K ("An incremental SAT solver is required: \"SAT4J\" will \
439 \be used instead of " ^ quote sat_solver ^ "."));
444 Kodkod_SAT.smart_sat_solver_name need_incremental
446 if sat_solver = "smart" then
447 print_v (fn () => "Using SAT solver " ^ quote effective_sat_solver ^
449 (if need_incremental then " incremental " else " ") ^
450 "solvers are configured: " ^
451 commas (map quote (Kodkod_SAT.configured_sat_solvers
452 need_incremental)) ^ ".")
456 val too_big_scopes = Unsynchronized.ref []
458 (* bool -> scope -> rich_problem option *)
459 fun problem_for_scope unsound
460 (scope as {card_assigns, bits, bisim_depth, datatypes, ofs, ...}) =
462 val _ = not (exists (fn other => scope_less_eq other scope)
463 (!too_big_scopes)) orelse
464 raise TOO_LARGE ("Nitpick.pick_them_nits_in_term.\
465 \problem_for_scope", "too large scope")
467 val _ = priority "Offsets:"
468 val _ = List.app (fn (T, j0) =>
469 priority (string_for_type ctxt T ^ " = " ^
473 val all_exact = forall (is_exact_type datatypes true) all_Ts
474 (* nut list -> rep NameTable.table -> nut list * rep NameTable.table *)
475 val repify_consts = choose_reps_for_consts scope all_exact
476 val main_j0 = offset_of_type ofs bool_T
477 val (nat_card, nat_j0) = spec_of_type scope nat_T
478 val (int_card, int_j0) = spec_of_type scope int_T
479 val _ = (nat_j0 = main_j0 andalso int_j0 = main_j0) orelse
480 raise BAD ("Nitpick.pick_them_nits_in_term.problem_for_scope",
482 val kk = kodkod_constrs peephole_optim nat_card int_card main_j0
483 val (free_names, rep_table) =
484 choose_reps_for_free_vars scope free_names NameTable.empty
485 val (sel_names, rep_table) = choose_reps_for_all_sels scope rep_table
486 val (nonsel_names, rep_table) = repify_consts nonsel_names rep_table
487 val min_highest_arity =
488 NameTable.fold (curry Int.max o arity_of_rep o snd) rep_table 1
490 NameTable.fold (curry Int.max o min_univ_card_of_rep o snd) rep_table
491 (univ_card nat_card int_card main_j0 [] KK.True)
492 val _ = check_arity min_univ_card min_highest_arity
494 val def_us = map (choose_reps_in_nut scope unsound rep_table true)
496 val nondef_us = map (choose_reps_in_nut scope unsound rep_table false)
499 val _ = List.app (priority o string_for_nut ctxt)
500 (free_names @ sel_names @ nonsel_names @
503 val (free_rels, pool, rel_table) =
504 rename_free_vars free_names initial_pool NameTable.empty
505 val (sel_rels, pool, rel_table) =
506 rename_free_vars sel_names pool rel_table
507 val (other_rels, pool, rel_table) =
508 rename_free_vars nonsel_names pool rel_table
509 val nondef_us = map (rename_vars_in_nut pool rel_table) nondef_us
510 val def_us = map (rename_vars_in_nut pool rel_table) def_us
511 val nondef_fs = map (kodkod_formula_from_nut ofs kk) nondef_us
512 val def_fs = map (kodkod_formula_from_nut ofs kk) def_us
513 val formula = fold (fold s_and) [def_fs, nondef_fs] KK.True
514 val comment = (if unsound then "unsound" else "sound") ^ "\n" ^
515 PrintMode.setmp [] multiline_string_for_scope scope
516 val kodkod_sat_solver =
517 Kodkod_SAT.sat_solver_spec effective_sat_solver |> snd
518 val bit_width = if bits = 0 then 16 else bits + 1
519 val delay = if unsound then
520 Option.map (fn time => Time.- (time, Time.now ()))
522 |> unsound_delay_for_timeout
525 val settings = [("solver", commas (map quote kodkod_sat_solver)),
526 ("skolem_depth", "-1"),
527 ("bit_width", string_of_int bit_width),
528 ("symmetry_breaking", signed_string_of_int sym_break),
529 ("sharing", signed_string_of_int sharing_depth),
530 ("flatten", Bool.toString flatten_props),
531 ("delay", signed_string_of_int delay)]
532 val plain_rels = free_rels @ other_rels
533 val plain_bounds = map (bound_for_plain_rel ctxt debug) plain_rels
534 val plain_axioms = map (declarative_axiom_for_plain_rel kk) plain_rels
535 val sel_bounds = map (bound_for_sel_rel ctxt debug datatypes) sel_rels
537 declarative_axioms_for_datatypes hol_ctxt binarize bits ofs kk
539 val declarative_axioms = plain_axioms @ dtype_axioms
540 val univ_card = Int.max (univ_card nat_card int_card main_j0
541 (plain_bounds @ sel_bounds) formula,
542 main_j0 |> bits > 0 ? Integer.add (bits + 1))
543 val built_in_bounds = bounds_for_built_in_rels_in_formula debug
544 univ_card nat_card int_card main_j0 formula
545 val bounds = built_in_bounds @ plain_bounds @ sel_bounds
546 |> not debug ? merge_bounds
548 fold Integer.max (map (fst o fst) (maps fst bounds)) 0
549 val formula = fold_rev s_and declarative_axioms formula
550 val _ = if bits = 0 then () else check_bits bits formula
551 val _ = if formula = KK.False then ()
552 else check_arity univ_card highest_arity
554 SOME ({comment = comment, settings = settings, univ_card = univ_card,
555 tuple_assigns = [], bounds = bounds,
556 int_bounds = if bits = 0 then sequential_int_bounds univ_card
557 else pow_of_two_int_bounds bits main_j0,
558 expr_assigns = [], formula = formula},
559 {free_names = free_names, sel_names = sel_names,
560 nonsel_names = nonsel_names, rel_table = rel_table,
561 unsound = unsound, scope = scope})
563 handle TOO_LARGE (loc, msg) =>
564 if loc = "Nitpick_Kodkod.check_arity" andalso
565 not (Typtab.is_empty ofs) then
566 problem_for_scope unsound
567 {hol_ctxt = hol_ctxt, binarize = binarize,
568 card_assigns = card_assigns, bits = bits,
569 bisim_depth = bisim_depth, datatypes = datatypes,
571 else if loc = "Nitpick.pick_them_nits_in_term.\
572 \problem_for_scope" then
575 (Unsynchronized.change too_big_scopes (cons scope);
576 print_v (fn () => ("Limit reached: " ^ msg ^
577 ". Skipping " ^ (if unsound then "potential"
579 " component of scope."));
581 | TOO_SMALL (_, msg) =>
582 (print_v (fn () => ("Limit reached: " ^ msg ^
583 ". Skipping " ^ (if unsound then "potential"
585 " component of scope."));
589 (if falsify then "counterexample" else "model")
590 |> not standard ? prefix "nonstandard "
592 val scopes = Unsynchronized.ref []
593 val generated_scopes = Unsynchronized.ref []
594 val generated_problems = Unsynchronized.ref ([] : rich_problem list)
595 val checked_problems = Unsynchronized.ref (SOME [])
596 val met_potential = Unsynchronized.ref 0
598 (* rich_problem list -> int list -> unit *)
599 fun update_checked_problems problems =
600 List.app (Unsynchronized.change checked_problems o Option.map o cons
603 fun show_kodkod_warning "" = ()
604 | show_kodkod_warning s = print_m (fn () => "Kodkod warning: " ^ s ^ ".")
606 (* bool -> KK.raw_bound list -> problem_extension -> bool option *)
607 fun print_and_check_model genuine bounds
608 ({free_names, sel_names, nonsel_names, rel_table, scope, ...}
609 : problem_extension) =
611 val (reconstructed_model, codatatypes_ok) =
612 reconstruct_hol_model {show_skolems = show_skolems,
613 show_datatypes = show_datatypes,
614 show_consts = show_consts}
615 scope formats frees free_names sel_names nonsel_names rel_table
617 val genuine_means_genuine = genuine_means_genuine andalso codatatypes_ok
619 pprint (Pretty.chunks
621 (pstrs ("Nitpick found a" ^
622 (if not genuine then " potential "
623 else if genuine_means_genuine then " "
624 else " likely genuine ") ^ das_wort_model) @
625 (case pretties_for_scope scope verbose of
627 | pretties => pstrs " for " @ pretties) @
628 [Pretty.str ":\n"])),
629 Pretty.indent indent_size reconstructed_model]);
631 (if check_genuine andalso standard then
632 (case prove_hol_model scope tac_timeout free_names sel_names
633 rel_table bounds assms_t of
634 SOME true => print ("Confirmation by \"auto\": The above " ^
635 das_wort_model ^ " is really genuine.")
637 if genuine_means_genuine then
638 error ("A supposedly genuine " ^ das_wort_model ^ " was \
639 \shown to be spurious by \"auto\".\nThis should never \
640 \happen.\nPlease send a bug report to blanchet\
643 print ("Refutation by \"auto\": The above " ^ das_wort_model ^
645 | NONE => print "No confirmation by \"auto\".")
648 if not standard andalso likely_in_struct_induct_step then
649 print "The existence of a nonstandard model suggests that the \
650 \induction hypothesis is not general enough or perhaps even \
651 \wrong. See the \"Inductive Properties\" section of the \
652 \Nitpick manual for details (\"isabelle doc nitpick\")."
655 if has_syntactic_sorts orig_t then
656 print "Hint: Maybe you forgot a type constraint?"
659 if not genuine_means_genuine then
660 if no_poly_user_axioms then
663 [] |> not got_all_mono_user_axioms
664 ? cons ("user_axioms", "\"true\"")
665 |> not (none_true wfs)
666 ? cons ("wf", "\"smart\" or \"false\"")
667 |> not sound_finitizes
668 ? cons ("finitize", "\"smart\" or \"false\"")
669 |> not codatatypes_ok
670 ? cons ("bisim_depth", "a nonnegative value")
672 map (fn (name, value) => quote name ^ " set to " ^ value)
675 print ("Try again with " ^
676 space_implode " " (serial_commas "and" ss) ^
677 " to confirm that the " ^ das_wort_model ^
681 print ("Nitpick is unable to guarantee the authenticity of \
682 \the " ^ das_wort_model ^ " in the presence of \
683 \polymorphic axioms.")
689 (Unsynchronized.inc met_potential;
690 if check_potential then
692 val status = prove_hol_model scope tac_timeout free_names
693 sel_names rel_table bounds assms_t
696 SOME true => print ("Confirmation by \"auto\": The above " ^
697 das_wort_model ^ " is genuine.")
698 | SOME false => print ("Refutation by \"auto\": The above " ^
699 das_wort_model ^ " is spurious.")
700 | NONE => print "No confirmation by \"auto\".");
708 (* int -> int -> int -> bool -> rich_problem list -> int * int * int *)
709 fun solve_any_problem max_potential max_genuine donno first_time problems =
711 val max_potential = Int.max (0, max_potential)
712 val max_genuine = Int.max (0, max_genuine)
713 (* bool -> int * KK.raw_bound list -> bool option *)
714 fun print_and_check genuine (j, bounds) =
715 print_and_check_model genuine bounds (snd (nth problems j))
716 val max_solutions = max_potential + max_genuine
717 |> not need_incremental ? curry Int.min 1
719 if max_solutions <= 0 then
722 case KK.solve_any_problem overlord deadline max_threads max_solutions
723 (map fst problems) of
725 (print_m install_kodkodi_message;
726 (max_potential, max_genuine, donno + 1))
727 | KK.Normal ([], unsat_js, s) =>
728 (update_checked_problems problems unsat_js; show_kodkod_warning s;
729 (max_potential, max_genuine, donno))
730 | KK.Normal (sat_ps, unsat_js, s) =>
732 val (lib_ps, con_ps) =
733 List.partition (#unsound o snd o nth problems o fst) sat_ps
735 update_checked_problems problems (unsat_js @ map fst lib_ps);
736 show_kodkod_warning s;
739 val num_genuine = take max_potential lib_ps
740 |> map (print_and_check false)
741 |> filter (curry (op =) (SOME true))
743 val max_genuine = max_genuine - num_genuine
744 val max_potential = max_potential
745 - (length lib_ps - num_genuine)
747 if max_genuine <= 0 then
751 (* "co_js" is the list of sound problems whose unsound
752 pendants couldn't be satisfied and hence that most
753 probably can't be satisfied themselves. *)
755 map (fn j => j - 1) unsat_js
759 (#scope (snd (nth problems j)))
760 (#scope (snd (nth problems (j + 1)))))
761 val bye_js = sort_distinct int_ord (map fst sat_ps @
764 problems |> filter_out_indices bye_js
765 |> max_potential <= 0
766 ? filter_out (#unsound o snd)
768 solve_any_problem max_potential max_genuine donno false
774 val _ = take max_genuine con_ps
775 |> List.app (ignore o print_and_check true)
776 val max_genuine = max_genuine - length con_ps
778 if max_genuine <= 0 orelse not first_time then
779 (0, max_genuine, donno)
782 val bye_js = sort_distinct int_ord
783 (map fst sat_ps @ unsat_js)
785 problems |> filter_out_indices bye_js
786 |> filter_out (#unsound o snd)
787 in solve_any_problem 0 max_genuine donno false problems end
790 | KK.TimedOut unsat_js =>
791 (update_checked_problems problems unsat_js; raise TimeLimit.TimeOut)
792 | KK.Interrupted NONE => (checked_problems := NONE; do_interrupted ())
793 | KK.Interrupted (SOME unsat_js) =>
794 (update_checked_problems problems unsat_js; do_interrupted ())
795 | KK.Error (s, unsat_js) =>
796 (update_checked_problems problems unsat_js;
797 print_v (K ("Kodkod error: " ^ s ^ "."));
798 (max_potential, max_genuine, donno + 1))
801 (* int -> int -> scope list -> int * int * int -> int * int * int *)
802 fun run_batch j n scopes (max_potential, max_genuine, donno) =
806 print_m (K "The scope specification is inconsistent.")
808 pprint (Pretty.chunks
810 pstrs ((if n > 1 then
811 "Batch " ^ string_of_int (j + 1) ^ " of " ^
812 signed_string_of_int n ^ ": "
815 "Trying " ^ string_of_int (length scopes) ^
816 " scope" ^ plural_s_for_list scopes ^ ":")),
817 Pretty.indent indent_size
821 (case pretties_for_scope scope true of
822 [] => [Pretty.str "Empty"]
823 | pretties => pretties) @
824 [Pretty.str (if j = 1 then "." else ";")]))
825 (length scopes downto 1) scopes))])
828 (* scope * bool -> rich_problem list * bool
829 -> rich_problem list * bool *)
830 fun add_problem_for_scope (scope, unsound) (problems, donno) =
832 case problem_for_scope unsound scope of
835 |> (null problems orelse
836 not (KK.problems_equivalent (fst problem)
837 (fst (hd problems))))
838 ? cons problem, donno)
839 | NONE => (problems, donno + 1))
840 val (problems, donno) =
841 fold add_problem_for_scope
842 (map_product pair scopes
843 ((if max_genuine > 0 then [false] else []) @
844 (if max_potential > 0 then [true] else [])))
846 val _ = Unsynchronized.change generated_problems (append problems)
847 val _ = Unsynchronized.change generated_scopes (append scopes)
851 val (unsound_problems, sound_problems) =
852 List.partition (#unsound o snd) (!generated_problems)
854 if not (null sound_problems) andalso
855 forall (KK.is_problem_trivially_false o fst)
858 "Warning: The conjecture either trivially holds for the \
859 \given scopes or lies outside Nitpick's supported \
861 (if exists (not o KK.is_problem_trivially_false o fst)
862 unsound_problems then
863 " Only potential counterexamples may be found."
872 solve_any_problem max_potential max_genuine donno true (rev problems)
875 (* rich_problem list -> scope -> int *)
876 fun scope_count (problems : rich_problem list) scope =
877 length (filter (scopes_equivalent scope o #scope o snd) problems)
878 (* string -> string *)
879 fun excipit did_so_and_so =
881 (* rich_problem list -> rich_problem list *)
883 if !met_potential = max_potential then filter_out (#unsound o snd)
885 val total = length (!scopes)
888 case scope_count (do_filter (!generated_problems)) scope of
891 scope_count (do_filter (these (!checked_problems)))
893 ? Integer.add 1) (!generated_scopes) 0
895 "Nitpick " ^ did_so_and_so ^
896 (if is_some (!checked_problems) andalso total > 0 then
898 string_of_int (Int.min (total - 1, unsat)) ^ " of " ^
899 string_of_int total ^ " scope" ^ plural_s total
904 (* int -> int -> scope list -> int * int * int -> KK.outcome *)
905 fun run_batches _ _ [] (max_potential, max_genuine, donno) =
906 if donno > 0 andalso max_genuine > 0 then
907 (print_m (fn () => excipit "ran out of some resource"); "unknown")
908 else if max_genuine = original_max_genuine then
909 if max_potential = original_max_potential then
911 "Nitpick found no " ^ das_wort_model ^ "." ^
912 (if not standard andalso likely_in_struct_induct_step then
913 " This suggests that the induction hypothesis might be \
914 \general enough to prove this subgoal."
919 "Nitpick could not find a" ^
920 (if max_genuine = 1 then " better " ^ das_wort_model ^ "."
921 else "ny better " ^ das_wort_model ^ "s.")); "potential")
923 if genuine_means_genuine then "genuine" else "likely_genuine"
924 | run_batches j n (batch :: batches) z =
925 let val (z as (_, max_genuine, _)) = run_batch j n batch z in
926 run_batches (j + 1) n (if max_genuine > 0 then batches else []) z
929 val (skipped, the_scopes) =
930 all_scopes hol_ctxt binarize sym_break cards_assigns maxes_assigns
931 iters_assigns bitss bisim_depths mono_Ts nonmono_Ts deep_dataTs
933 val _ = if skipped > 0 then
934 print_m (fn () => "Too many scopes. Skipping " ^
935 string_of_int skipped ^ " scope" ^
937 ". (Consider using \"mono\" or \
938 \\"merge_type_vars\" to prevent this.)")
941 val _ = scopes := the_scopes
943 val batches = batch_list batch_size (!scopes)
945 (run_batches 0 (length batches) batches (max_potential, max_genuine, 0)
946 handle Exn.Interrupt => do_interrupted ())
947 handle TimeLimit.TimeOut =>
948 (print_m (fn () => excipit "ran out of time");
949 if !met_potential > 0 then "potential" else "unknown")
950 | Exn.Interrupt => if auto orelse debug then raise Interrupt
951 else error (excipit "was interrupted")
952 val _ = print_v (fn () => "Total time: " ^
953 signed_string_of_int (Time.toMilliseconds
954 (Timer.checkRealTimer timer)) ^ " ms.")
955 in (outcome_code, !state_ref) end
956 handle Exn.Interrupt =>
957 if auto orelse #debug params then
960 if passed_deadline deadline then
961 (priority "Nitpick ran out of time."; ("unknown", state))
963 error "Nitpick was interrupted."
965 (* Proof.state -> params -> bool -> int -> int -> int -> (term * term) list
966 -> term list -> term -> string * Proof.state *)
967 fun pick_nits_in_term state (params as {debug, timeout, expect, ...}) auto i n
968 step subst orig_assm_ts orig_t =
969 if getenv "KODKODI" = "" then
971 else warning (Pretty.string_of (plazy install_kodkodi_message));
975 val deadline = Option.map (curry Time.+ (Time.now ())) timeout
976 val outcome as (outcome_code, _) =
977 time_limit (if debug then NONE else timeout)
978 (pick_them_nits_in_term deadline state params auto i n step subst
981 if expect = "" orelse outcome_code = expect then outcome
982 else error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
985 (* string list -> term -> bool *)
986 fun is_fixed_equation fixes
987 (Const (@{const_name "=="}, _) $ Free (s, _) $ Const _) =
988 member (op =) fixes s
989 | is_fixed_equation _ _ = false
990 (* Proof.context -> term list * term -> (term * term) list * term list * term *)
991 fun extract_fixed_frees ctxt (assms, t) =
993 val fixes = Variable.fixes_of ctxt |> map snd
994 val (subst, other_assms) =
995 List.partition (is_fixed_equation fixes) assms
996 |>> map Logic.dest_equals
997 in (subst, other_assms, subst_atomic subst t) end
999 (* Proof.state -> params -> bool -> int -> int -> string * Proof.state *)
1000 fun pick_nits_in_subgoal state params auto i step =
1002 val ctxt = Proof.context_of state
1003 val t = state |> Proof.raw_goal |> #goal |> prop_of
1005 case Logic.count_prems t of
1006 0 => (priority "No subgoal!"; ("none", state))
1009 val (t, frees) = Logic.goal_params t i
1010 val t = subst_bounds (frees, t)
1011 val assms = map term_of (Assumption.all_assms_of ctxt)
1012 val (subst, assms, t) = extract_fixed_frees ctxt (assms, t)
1013 in pick_nits_in_term state params auto i n step subst assms t end