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
11 type term_postprocessor = Nitpick_Model.term_postprocessor
13 {cards_assigns: (typ option * int list) list,
14 maxes_assigns: (styp option * int list) list,
15 iters_assigns: (styp option * int list) list,
17 bisim_depths: int list,
18 boxes: (typ option * bool option) list,
19 finitizes: (typ option * bool option) list,
20 monos: (typ option * bool option) list,
21 stds: (typ option * bool) list,
22 wfs: (styp option * bool option) list,
29 user_axioms: bool option,
31 merge_type_vars: bool,
32 binary_ints: bool option,
33 destroy_constrs: bool,
35 star_linear_preds: bool,
38 timeout: Time.time option,
39 tac_timeout: Time.time option,
44 formats: (term option * int list) list,
45 atomss: (typ option * string list) list,
48 check_potential: bool,
53 val register_frac_type : string -> (string * string) list -> theory -> theory
54 val unregister_frac_type : string -> theory -> theory
55 val register_codatatype : typ -> string -> styp list -> theory -> theory
56 val unregister_codatatype : typ -> theory -> theory
57 val register_term_postprocessor :
58 typ -> term_postprocessor -> theory -> theory
59 val unregister_term_postprocessor : typ -> theory -> theory
60 val pick_nits_in_term :
61 Proof.state -> params -> bool -> int -> int -> int -> (term * term) list
62 -> term list -> term -> 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 finitizes: (typ option * bool option) list,
91 monos: (typ option * bool option) list,
92 stds: (typ option * bool) list,
93 wfs: (styp option * bool option) list,
100 user_axioms: bool option,
102 merge_type_vars: bool,
103 binary_ints: bool option,
104 destroy_constrs: bool,
106 star_linear_preds: bool,
108 peephole_optim: bool,
109 timeout: Time.time option,
110 tac_timeout: Time.time option,
112 show_datatypes: bool,
115 formats: (term option * int list) list,
116 atomss: (typ option * string list) list,
119 check_potential: bool,
124 type problem_extension =
125 {free_names: nut list,
127 nonsel_names: nut list,
128 rel_table: nut NameTable.table,
132 type rich_problem = KK.problem * problem_extension
134 fun pretties_for_formulas _ _ [] = []
135 | pretties_for_formulas ctxt s ts =
136 [Pretty.str (s ^ plural_s_for_list ts ^ ":"),
137 Pretty.indent indent_size (Pretty.chunks
138 (map2 (fn j => fn t =>
139 Pretty.block [t |> shorten_names_in_term
140 |> Syntax.pretty_term ctxt,
141 Pretty.str (if j = 1 then "." else ";")])
142 (length ts downto 1) ts))]
144 fun install_java_message () =
145 "Nitpick requires a Java 1.5 virtual machine called \"java\"."
146 fun install_kodkodi_message () =
147 "Nitpick requires the external Java program Kodkodi. To install it, download \
148 \the package from Isabelle's web page and add the \"kodkodi-x.y.z\" \
149 \directory's full path to \"" ^
150 Path.implode (Path.expand (Path.appends
151 (Path.variable "ISABELLE_HOME_USER" ::
152 map Path.basic ["etc", "components"]))) ^ "\" on a line of its own."
154 val max_unsound_delay_ms = 200
155 val max_unsound_delay_percent = 2
157 fun unsound_delay_for_timeout NONE = max_unsound_delay_ms
158 | unsound_delay_for_timeout (SOME timeout) =
159 Int.max (0, Int.min (max_unsound_delay_ms,
160 Time.toMilliseconds timeout
161 * max_unsound_delay_percent div 100))
163 fun passed_deadline NONE = false
164 | passed_deadline (SOME time) = Time.compare (Time.now (), time) <> LESS
166 fun none_true assigns = forall (not_equal (SOME true) o snd) assigns
168 val syntactic_sorts =
169 @{sort "{default,zero,one,plus,minus,uminus,times,inverse,abs,sgn,ord,eq}"} @
171 fun has_tfree_syntactic_sort (TFree (_, S as _ :: _)) =
172 subset (op =) (S, syntactic_sorts)
173 | has_tfree_syntactic_sort _ = false
174 val has_syntactic_sorts = exists_type (exists_subtype has_tfree_syntactic_sort)
176 fun plazy f = Pretty.blk (0, pstrs (f ()))
178 fun pick_them_nits_in_term deadline state (params : params) auto i n step
179 subst orig_assm_ts orig_t =
181 val timer = Timer.startRealTimer ()
182 val thy = Proof.theory_of state
183 val ctxt = Proof.context_of state
184 (* FIXME: reintroduce code before new release:
186 val nitpick_thy = Thy_Info.get_theory "Nitpick"
187 val _ = Theory.subthy (nitpick_thy, thy) orelse
188 error "You must import the theory \"Nitpick\" to use Nitpick"
190 val {cards_assigns, maxes_assigns, iters_assigns, bitss, bisim_depths,
191 boxes, finitizes, monos, stds, wfs, sat_solver, falsify, debug,
192 verbose, overlord, user_axioms, assms, merge_type_vars, binary_ints,
193 destroy_constrs, specialize, star_linear_preds, fast_descrs,
194 peephole_optim, tac_timeout, max_threads, show_datatypes, show_consts,
195 evals, formats, atomss, max_potential, max_genuine, check_potential,
196 check_genuine, batch_size, ...} = params
197 val state_ref = Unsynchronized.ref state
200 Unsynchronized.change state_ref o Proof.goal_message o K
201 o Pretty.chunks o cons (Pretty.str "") o single
202 o Pretty.mark Markup.hilite
204 (fn s => (priority s; if debug then tracing s else ()))
206 fun pprint_m f = () |> not auto ? pprint o f
207 fun pprint_v f = () |> verbose ? pprint o f
208 fun pprint_d f = () |> debug ? pprint o f
209 val print = pprint o curry Pretty.blk 0 o pstrs
210 val print_g = pprint o Pretty.str
211 val print_m = pprint_m o K o plazy
212 val print_v = pprint_v o K o plazy
214 fun check_deadline () =
215 if debug andalso passed_deadline deadline then raise TimeLimit.TimeOut
217 fun do_interrupted () =
218 if passed_deadline deadline then raise TimeLimit.TimeOut
221 val orig_assm_ts = if assms orelse auto then orig_assm_ts else []
224 print_m (fn () => "Nitpicking formula...")
226 pprint_m (fn () => Pretty.chunks (
227 pretties_for_formulas ctxt ("Nitpicking " ^
228 (if i <> 1 orelse n <> 1 then
229 "subgoal " ^ string_of_int i ^ " of " ^ string_of_int n
231 "goal")) [Logic.list_implies (orig_assm_ts, orig_t)]))
232 val neg_t = if falsify then Logic.mk_implies (orig_t, @{prop False})
234 val assms_t = Logic.mk_conjunction_list (neg_t :: orig_assm_ts)
235 val (assms_t, evals) =
236 assms_t :: evals |> merge_type_vars ? merge_type_vars_in_terms
238 val original_max_potential = max_potential
239 val original_max_genuine = max_genuine
240 val max_bisim_depth = fold Integer.max bisim_depths ~1
241 val case_names = case_const_names thy stds
242 val (defs, built_in_nondefs, user_nondefs) = all_axioms_of ctxt subst
243 val def_table = const_def_table ctxt subst defs
244 val nondef_table = const_nondef_table (built_in_nondefs @ user_nondefs)
245 val simp_table = Unsynchronized.ref (const_simp_table ctxt subst)
246 val psimp_table = const_psimp_table ctxt subst
247 val choice_spec_table = const_choice_spec_table ctxt subst
249 user_nondefs |> filter_out (is_choice_spec_axiom thy choice_spec_table)
250 val intro_table = inductive_intro_table ctxt subst def_table
251 val ground_thm_table = ground_theorem_table thy
252 val ersatz_table = ersatz_table thy
253 val (hol_ctxt as {wf_cache, ...}) =
254 {thy = thy, ctxt = ctxt, max_bisim_depth = max_bisim_depth, boxes = boxes,
255 stds = stds, wfs = wfs, user_axioms = user_axioms, debug = debug,
256 binary_ints = binary_ints, destroy_constrs = destroy_constrs,
257 specialize = specialize, star_linear_preds = star_linear_preds,
258 fast_descrs = fast_descrs, tac_timeout = tac_timeout, evals = evals,
259 case_names = case_names, def_table = def_table,
260 nondef_table = nondef_table, user_nondefs = user_nondefs,
261 simp_table = simp_table, psimp_table = psimp_table,
262 choice_spec_table = choice_spec_table, intro_table = intro_table,
263 ground_thm_table = ground_thm_table, ersatz_table = ersatz_table,
264 skolems = Unsynchronized.ref [], special_funs = Unsynchronized.ref [],
265 unrolled_preds = Unsynchronized.ref [], wf_cache = Unsynchronized.ref [],
266 constr_cache = Unsynchronized.ref []}
267 val frees = Term.add_frees assms_t []
268 val _ = null (Term.add_tvars assms_t []) orelse
269 raise NOT_SUPPORTED "schematic type variables"
270 val (nondef_ts, def_ts, got_all_mono_user_axioms, no_poly_user_axioms,
271 binarize) = preprocess_term hol_ctxt finitizes monos assms_t
272 val got_all_user_axioms =
273 got_all_mono_user_axioms andalso no_poly_user_axioms
275 fun print_wf (x, (gfp, wf)) =
276 pprint (Pretty.blk (0,
277 pstrs ("The " ^ (if gfp then "co" else "") ^ "inductive predicate \"")
278 @ Syntax.pretty_term ctxt (Const x) ::
280 "\" was proved well-founded. Nitpick can compute it \
283 "\" could not be proved well-founded. Nitpick might need to \
285 val _ = if verbose then List.app print_wf (!wf_cache) else ()
287 pprint_d (fn () => Pretty.chunks
288 (pretties_for_formulas ctxt "Preprocessed formula" [hd nondef_ts] @
289 pretties_for_formulas ctxt "Relevant definitional axiom" def_ts @
290 pretties_for_formulas ctxt "Relevant nondefinitional axiom"
292 val _ = List.app (ignore o Term.type_of) (nondef_ts @ def_ts)
293 handle TYPE (_, Ts, ts) =>
294 raise TYPE ("Nitpick.pick_them_nits_in_term", Ts, ts)
296 val nondef_us = map (nut_from_term hol_ctxt Eq) nondef_ts
297 val def_us = map (nut_from_term hol_ctxt DefEq) def_ts
298 val (free_names, const_names) =
299 fold add_free_and_const_names (nondef_us @ def_us) ([], [])
300 val (sel_names, nonsel_names) =
301 List.partition (is_sel o nickname_of) const_names
302 val sound_finitizes =
303 none_true (filter_out (fn (SOME (Type (@{type_name fun}, _)), _) => true
304 | _ => false) finitizes)
305 val standard = forall snd stds
307 val _ = List.app (print_g o string_for_nut ctxt) (nondef_us @ def_us)
310 val unique_scope = forall (curry (op =) 1 o length o snd) cards_assigns
311 fun monotonicity_message Ts extra =
312 let val ss = map (quote o string_for_type ctxt) Ts in
313 "The type" ^ plural_s_for_list ss ^ " " ^
314 space_implode " " (serial_commas "and" ss) ^ " " ^
315 (if none_true monos then
316 "passed the monotonicity test"
318 (if length ss = 1 then "is" else "are") ^ " considered monotonic") ^
321 fun is_type_fundamentally_monotonic T =
322 (is_datatype ctxt stds T andalso not (is_quot_type thy T) andalso
323 (not (is_pure_typedef ctxt T) orelse is_univ_typedef ctxt T)) orelse
324 is_number_type thy T orelse is_bit_type T
325 fun is_type_actually_monotonic T =
326 formulas_monotonic hol_ctxt binarize T (nondef_ts, def_ts)
327 fun is_type_kind_of_monotonic T =
328 case triple_lookup (type_match thy) monos T of
329 SOME (SOME false) => false
330 | _ => is_type_actually_monotonic T
331 fun is_type_monotonic T =
333 case triple_lookup (type_match thy) monos T of
335 | _ => is_type_fundamentally_monotonic T orelse
336 is_type_actually_monotonic T
337 fun is_shallow_datatype_finitizable (T as Type (@{type_name fin_fun}, _)) =
338 is_type_kind_of_monotonic T
339 | is_shallow_datatype_finitizable (T as Type (@{type_name fun_box}, _)) =
340 is_type_kind_of_monotonic T
341 | is_shallow_datatype_finitizable T =
342 case triple_lookup (type_match thy) finitizes T of
344 | _ => is_type_kind_of_monotonic T
345 fun is_datatype_deep T =
346 not standard orelse T = nat_T orelse is_word_type T orelse
347 exists (curry (op =) T o domain_type o type_of) sel_names
348 val all_Ts = ground_types_in_terms hol_ctxt binarize (nondef_ts @ def_ts)
349 |> sort Term_Ord.typ_ord
350 val _ = if verbose andalso binary_ints = SOME true andalso
351 exists (member (op =) [nat_T, int_T]) all_Ts then
352 print_v (K "The option \"binary_ints\" will be ignored because \
353 \of the presence of rationals, reals, \"Suc\", \
354 \\"gcd\", or \"lcm\" in the problem or because of the \
355 \\"non_std\" option.")
358 val (mono_Ts, nonmono_Ts) = List.partition is_type_monotonic all_Ts
360 if verbose andalso not unique_scope then
361 case filter_out is_type_fundamentally_monotonic mono_Ts of
363 | interesting_mono_Ts =>
364 print_v (K (monotonicity_message interesting_mono_Ts
365 "Nitpick might be able to skip some scopes."))
368 val (deep_dataTs, shallow_dataTs) =
369 all_Ts |> filter (is_datatype ctxt stds)
370 |> List.partition is_datatype_deep
371 val finitizable_dataTs =
372 shallow_dataTs |> filter_out (is_finite_type hol_ctxt)
373 |> filter is_shallow_datatype_finitizable
375 if verbose andalso not (null finitizable_dataTs) then
376 print_v (K (monotonicity_message finitizable_dataTs
377 "Nitpick can use a more precise finite encoding."))
380 (* This detection code is an ugly hack. Fortunately, it is used only to
381 provide a hint to the user. *)
382 fun is_struct_induct_step (name, (Rule_Cases.Case {fixes, assumes, ...}, _)) =
383 not (null fixes) andalso
384 exists (String.isSuffix ".hyps" o fst) assumes andalso
385 exists (exists (curry (op =) name o shortest_name o fst)
386 o datatype_constrs hol_ctxt) deep_dataTs
387 val likely_in_struct_induct_step =
388 exists is_struct_induct_step (ProofContext.cases_of ctxt)
389 val _ = if standard andalso likely_in_struct_induct_step then
390 pprint_m (fn () => Pretty.blk (0,
391 pstrs "Hint: To check that the induction hypothesis is \
392 \general enough, try this command: " @
393 [Pretty.mark Markup.sendback (Pretty.blk (0,
394 pstrs ("nitpick [non_std, show_all]")))] @ pstrs "."))
398 val _ = print_g "Monotonic types:"
399 val _ = List.app (print_g o string_for_type ctxt) mono_Ts
400 val _ = print_g "Nonmonotonic types:"
401 val _ = List.app (print_g o string_for_type ctxt) nonmono_Ts
404 val incremental = Int.max (max_potential, max_genuine) >= 2
405 val actual_sat_solver =
406 if sat_solver <> "smart" then
407 if incremental andalso
408 not (member (op =) (Kodkod_SAT.configured_sat_solvers true)
410 (print_m (K ("An incremental SAT solver is required: \"SAT4J\" will \
411 \be used instead of " ^ quote sat_solver ^ "."));
416 Kodkod_SAT.smart_sat_solver_name incremental
418 if sat_solver = "smart" then
420 "Using SAT solver " ^ quote actual_sat_solver ^ ". The following" ^
421 (if incremental then " incremental " else " ") ^
422 "solvers are configured: " ^
423 commas_quote (Kodkod_SAT.configured_sat_solvers incremental) ^ ".")
427 val too_big_scopes = Unsynchronized.ref []
429 fun problem_for_scope unsound
430 (scope as {card_assigns, bits, bisim_depth, datatypes, ofs, ...}) =
432 val _ = not (exists (fn other => scope_less_eq other scope)
433 (!too_big_scopes)) orelse
434 raise TOO_LARGE ("Nitpick.pick_them_nits_in_term.\
435 \problem_for_scope", "too large scope")
437 val _ = print_g "Offsets:"
438 val _ = List.app (fn (T, j0) =>
439 print_g (string_for_type ctxt T ^ " = " ^
443 val all_exact = forall (is_exact_type datatypes true) all_Ts
444 val repify_consts = choose_reps_for_consts scope all_exact
445 val main_j0 = offset_of_type ofs bool_T
446 val (nat_card, nat_j0) = spec_of_type scope nat_T
447 val (int_card, int_j0) = spec_of_type scope int_T
448 val _ = (nat_j0 = main_j0 andalso int_j0 = main_j0) orelse
449 raise BAD ("Nitpick.pick_them_nits_in_term.problem_for_scope",
451 val kk = kodkod_constrs peephole_optim nat_card int_card main_j0
452 val (free_names, rep_table) =
453 choose_reps_for_free_vars scope free_names NameTable.empty
454 val (sel_names, rep_table) = choose_reps_for_all_sels scope rep_table
455 val (nonsel_names, rep_table) = repify_consts nonsel_names rep_table
456 val min_highest_arity =
457 NameTable.fold (Integer.max o arity_of_rep o snd) rep_table 1
459 NameTable.fold (Integer.max o min_univ_card_of_rep o snd) rep_table
460 (univ_card nat_card int_card main_j0 [] KK.True)
461 val _ = check_arity min_univ_card min_highest_arity
463 val def_us = map (choose_reps_in_nut scope unsound rep_table true)
465 val nondef_us = map (choose_reps_in_nut scope unsound rep_table false)
468 val _ = List.app (print_g o string_for_nut ctxt)
469 (free_names @ sel_names @ nonsel_names @
472 val (free_rels, pool, rel_table) =
473 rename_free_vars free_names initial_pool NameTable.empty
474 val (sel_rels, pool, rel_table) =
475 rename_free_vars sel_names pool rel_table
476 val (other_rels, pool, rel_table) =
477 rename_free_vars nonsel_names pool rel_table
478 val nondef_us = map (rename_vars_in_nut pool rel_table) nondef_us
479 val def_us = map (rename_vars_in_nut pool rel_table) def_us
480 val nondef_fs = map (kodkod_formula_from_nut ofs kk) nondef_us
481 val def_fs = map (kodkod_formula_from_nut ofs kk) def_us
482 val formula = fold (fold s_and) [def_fs, nondef_fs] KK.True
483 val comment = (if unsound then "unsound" else "sound") ^ "\n" ^
484 Print_Mode.setmp [] multiline_string_for_scope scope
485 val kodkod_sat_solver =
486 Kodkod_SAT.sat_solver_spec actual_sat_solver |> snd
487 val bit_width = if bits = 0 then 16 else bits + 1
490 Option.map (fn time => Time.- (time, Time.now ())) deadline
491 |> unsound_delay_for_timeout
494 val settings = [("solver", commas_quote kodkod_sat_solver),
495 ("skolem_depth", "-1"),
496 ("bit_width", string_of_int bit_width),
497 ("symmetry_breaking", "20"),
499 ("flatten", "false"),
500 ("delay", signed_string_of_int delay)]
501 val plain_rels = free_rels @ other_rels
502 val plain_bounds = map (bound_for_plain_rel ctxt debug) plain_rels
503 val plain_axioms = map (declarative_axiom_for_plain_rel kk) plain_rels
504 val sel_bounds = map (bound_for_sel_rel ctxt debug datatypes) sel_rels
506 declarative_axioms_for_datatypes hol_ctxt binarize bits ofs kk
508 val declarative_axioms = plain_axioms @ dtype_axioms
509 val univ_card = Int.max (univ_card nat_card int_card main_j0
510 (plain_bounds @ sel_bounds) formula,
511 main_j0 |> bits > 0 ? Integer.add (bits + 1))
512 val built_in_bounds = bounds_for_built_in_rels_in_formula debug
513 univ_card nat_card int_card main_j0 formula
514 val bounds = built_in_bounds @ plain_bounds @ sel_bounds
515 |> not debug ? merge_bounds
517 fold Integer.max (map (fst o fst) (maps fst bounds)) 0
518 val formula = fold_rev s_and declarative_axioms formula
519 val _ = if bits = 0 then () else check_bits bits formula
520 val _ = if formula = KK.False then ()
521 else check_arity univ_card highest_arity
523 SOME ({comment = comment, settings = settings, univ_card = univ_card,
524 tuple_assigns = [], bounds = bounds,
525 int_bounds = if bits = 0 then sequential_int_bounds univ_card
526 else pow_of_two_int_bounds bits main_j0,
527 expr_assigns = [], formula = formula},
528 {free_names = free_names, sel_names = sel_names,
529 nonsel_names = nonsel_names, rel_table = rel_table,
530 unsound = unsound, scope = scope})
532 handle TOO_LARGE (loc, msg) =>
533 if loc = "Nitpick_Kodkod.check_arity" andalso
534 not (Typtab.is_empty ofs) then
535 problem_for_scope unsound
536 {hol_ctxt = hol_ctxt, binarize = binarize,
537 card_assigns = card_assigns, bits = bits,
538 bisim_depth = bisim_depth, datatypes = datatypes,
540 else if loc = "Nitpick.pick_them_nits_in_term.\
541 \problem_for_scope" then
544 (Unsynchronized.change too_big_scopes (cons scope);
545 print_v (fn () => ("Limit reached: " ^ msg ^
546 ". Skipping " ^ (if unsound then "potential"
548 " component of scope."));
550 | TOO_SMALL (_, msg) =>
551 (print_v (fn () => ("Limit reached: " ^ msg ^
552 ". Skipping " ^ (if unsound then "potential"
554 " component of scope."));
558 (if falsify then "counterexample" else "model")
559 |> not standard ? prefix "nonstandard "
561 val scopes = Unsynchronized.ref []
562 val generated_scopes = Unsynchronized.ref []
563 val generated_problems = Unsynchronized.ref ([] : rich_problem list)
564 val checked_problems = Unsynchronized.ref (SOME [])
565 val met_potential = Unsynchronized.ref 0
567 fun update_checked_problems problems =
568 List.app (Unsynchronized.change checked_problems o Option.map o cons
570 fun show_kodkod_warning "" = ()
571 | show_kodkod_warning s = print_m (fn () => "Kodkod warning: " ^ s ^ ".")
573 fun print_and_check_model genuine bounds
574 ({free_names, sel_names, nonsel_names, rel_table, scope, ...}
575 : problem_extension) =
577 val (reconstructed_model, codatatypes_ok) =
578 reconstruct_hol_model {show_datatypes = show_datatypes,
579 show_consts = show_consts}
580 scope formats atomss frees free_names sel_names nonsel_names
582 val genuine_means_genuine =
583 got_all_user_axioms andalso none_true wfs andalso
584 sound_finitizes andalso codatatypes_ok
586 (pprint (Pretty.chunks
588 (pstrs ("Nitpick found a" ^
589 (if not genuine then " potential "
590 else if genuine_means_genuine then " "
591 else " quasi genuine ") ^ das_wort_model) @
592 (case pretties_for_scope scope verbose of
594 | pretties => pstrs " for " @ pretties) @
595 [Pretty.str ":\n"])),
596 Pretty.indent indent_size reconstructed_model]);
598 (if check_genuine andalso standard then
599 case prove_hol_model scope tac_timeout free_names sel_names
600 rel_table bounds assms_t of
602 print ("Confirmation by \"auto\": The above " ^
603 das_wort_model ^ " is really genuine.")
605 if genuine_means_genuine then
606 error ("A supposedly genuine " ^ das_wort_model ^ " was \
607 \shown to be spurious by \"auto\".\nThis should never \
608 \happen.\nPlease send a bug report to blanchet\
611 print ("Refutation by \"auto\": The above " ^
612 das_wort_model ^ " is spurious.")
613 | NONE => print "No confirmation by \"auto\"."
616 if not standard andalso likely_in_struct_induct_step then
617 print "The existence of a nonstandard model suggests that the \
618 \induction hypothesis is not general enough or may even be \
619 \wrong. See the Nitpick manual's \"Inductive Properties\" \
620 \section for details (\"isabelle doc nitpick\")."
623 if has_syntactic_sorts orig_t then
624 print "Hint: Maybe you forgot a type constraint?"
627 if not genuine_means_genuine then
628 if no_poly_user_axioms then
631 [] |> not got_all_mono_user_axioms
632 ? cons ("user_axioms", "\"true\"")
633 |> not (none_true wfs)
634 ? cons ("wf", "\"smart\" or \"false\"")
635 |> not sound_finitizes
636 ? cons ("finitize", "\"smart\" or \"false\"")
637 |> not codatatypes_ok
638 ? cons ("bisim_depth", "a nonnegative value")
640 map (fn (name, value) => quote name ^ " set to " ^ value)
643 print ("Try again with " ^
644 space_implode " " (serial_commas "and" ss) ^
645 " to confirm that the " ^ das_wort_model ^
649 print ("Nitpick is unable to guarantee the authenticity of \
650 \the " ^ das_wort_model ^ " in the presence of \
651 \polymorphic axioms.")
657 (Unsynchronized.inc met_potential;
658 if check_potential then
660 val status = prove_hol_model scope tac_timeout free_names
661 sel_names rel_table bounds assms_t
664 SOME true => print ("Confirmation by \"auto\": The \
665 \above " ^ das_wort_model ^
667 | SOME false => print ("Refutation by \"auto\": The above " ^
668 das_wort_model ^ " is spurious.")
669 | NONE => print "No confirmation by \"auto\".");
676 |> pair genuine_means_genuine
678 fun solve_any_problem (found_really_genuine, max_potential, max_genuine,
679 donno) first_time problems =
681 val max_potential = Int.max (0, max_potential)
682 val max_genuine = Int.max (0, max_genuine)
683 fun print_and_check genuine (j, bounds) =
684 print_and_check_model genuine bounds (snd (nth problems j))
685 val max_solutions = max_potential + max_genuine
686 |> not incremental ? Integer.min 1
688 if max_solutions <= 0 then
689 (found_really_genuine, 0, 0, donno)
691 case KK.solve_any_problem overlord deadline max_threads max_solutions
692 (map fst problems) of
693 KK.JavaNotInstalled =>
694 (print_m install_java_message;
695 (found_really_genuine, max_potential, max_genuine, donno + 1))
696 | KK.KodkodiNotInstalled =>
697 (print_m install_kodkodi_message;
698 (found_really_genuine, max_potential, max_genuine, donno + 1))
699 | KK.Normal ([], unsat_js, s) =>
700 (update_checked_problems problems unsat_js; show_kodkod_warning s;
701 (found_really_genuine, max_potential, max_genuine, donno))
702 | KK.Normal (sat_ps, unsat_js, s) =>
704 val (lib_ps, con_ps) =
705 List.partition (#unsound o snd o nth problems o fst) sat_ps
707 update_checked_problems problems (unsat_js @ map fst lib_ps);
708 show_kodkod_warning s;
712 lib_ps |> take max_potential
713 |> map (print_and_check false)
714 |> filter (curry (op =) (SOME true) o snd)
715 val found_really_genuine =
716 found_really_genuine orelse exists fst genuine_codes
717 val num_genuine = length genuine_codes
718 val max_genuine = max_genuine - num_genuine
719 val max_potential = max_potential
720 - (length lib_ps - num_genuine)
722 if max_genuine <= 0 then
723 (found_really_genuine, 0, 0, donno)
726 (* "co_js" is the list of sound problems whose unsound
727 pendants couldn't be satisfied and hence that most
728 probably can't be satisfied themselves. *)
730 map (fn j => j - 1) unsat_js
734 (#scope (snd (nth problems j)),
735 #scope (snd (nth problems (j + 1)))))
736 val bye_js = sort_distinct int_ord (map fst sat_ps @
739 problems |> filter_out_indices bye_js
740 |> max_potential <= 0
741 ? filter_out (#unsound o snd)
743 solve_any_problem (found_really_genuine, max_potential,
744 max_genuine, donno) false problems
750 con_ps |> take max_genuine
751 |> map (print_and_check true)
752 val max_genuine = max_genuine - length genuine_codes
753 val found_really_genuine =
754 found_really_genuine orelse exists fst genuine_codes
756 if max_genuine <= 0 orelse not first_time then
757 (found_really_genuine, 0, max_genuine, donno)
760 val bye_js = sort_distinct int_ord
761 (map fst sat_ps @ unsat_js)
763 problems |> filter_out_indices bye_js
764 |> filter_out (#unsound o snd)
766 solve_any_problem (found_really_genuine, 0, max_genuine,
767 donno) false problems
771 | KK.TimedOut unsat_js =>
772 (update_checked_problems problems unsat_js; raise TimeLimit.TimeOut)
773 | KK.Interrupted NONE => (checked_problems := NONE; do_interrupted ())
774 | KK.Interrupted (SOME unsat_js) =>
775 (update_checked_problems problems unsat_js; do_interrupted ())
776 | KK.Error (s, unsat_js) =>
777 (update_checked_problems problems unsat_js;
778 print_v (K ("Kodkod error: " ^ s ^ "."));
779 (found_really_genuine, max_potential, max_genuine, donno + 1))
782 fun run_batch j n scopes (found_really_genuine, max_potential, max_genuine,
787 print_m (K "The scope specification is inconsistent.")
789 pprint (Pretty.chunks
791 pstrs ((if n > 1 then
792 "Batch " ^ string_of_int (j + 1) ^ " of " ^
793 signed_string_of_int n ^ ": "
796 "Trying " ^ string_of_int (length scopes) ^
797 " scope" ^ plural_s_for_list scopes ^ ":")),
798 Pretty.indent indent_size
802 (case pretties_for_scope scope true of
803 [] => [Pretty.str "Empty"]
804 | pretties => pretties) @
805 [Pretty.str (if j = 1 then "." else ";")]))
806 (length scopes downto 1) scopes))])
809 fun add_problem_for_scope (scope, unsound) (problems, donno) =
811 case problem_for_scope unsound scope of
814 |> (null problems orelse
815 not (KK.problems_equivalent (fst problem, fst (hd problems))))
816 ? cons problem, donno)
817 | NONE => (problems, donno + 1))
818 val (problems, donno) =
819 fold add_problem_for_scope
820 (map_product pair scopes
821 ((if max_genuine > 0 then [false] else []) @
822 (if max_potential > 0 then [true] else [])))
824 val _ = Unsynchronized.change generated_problems (append problems)
825 val _ = Unsynchronized.change generated_scopes (append scopes)
829 val (unsound_problems, sound_problems) =
830 List.partition (#unsound o snd) (!generated_problems)
832 if not (null sound_problems) andalso
833 forall (KK.is_problem_trivially_false o fst)
836 "Warning: The conjecture either trivially holds for the \
837 \given scopes or lies outside Nitpick's supported \
839 (if exists (not o KK.is_problem_trivially_false o fst)
840 unsound_problems then
841 " Only potential " ^ das_wort_model ^ "s may be found."
850 solve_any_problem (found_really_genuine, max_potential, max_genuine,
851 donno) true (rev problems)
854 fun scope_count (problems : rich_problem list) scope =
855 length (filter (curry scopes_equivalent scope o #scope o snd) problems)
856 fun excipit did_so_and_so =
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
873 " " ^ string_of_int (Int.min (total - 1, unsat)) ^ " of " ^
874 string_of_int total ^ " scope" ^ plural_s total
879 fun run_batches _ _ []
880 (found_really_genuine, max_potential, max_genuine, donno) =
881 if donno > 0 andalso max_genuine > 0 then
882 (print_m (fn () => excipit "checked"); "unknown")
883 else if max_genuine = original_max_genuine then
884 if max_potential = original_max_potential then
886 "Nitpick found no " ^ das_wort_model ^ "." ^
887 (if not standard andalso likely_in_struct_induct_step then
888 " This suggests that the induction hypothesis might be \
889 \general enough to prove this subgoal."
894 "Nitpick could not find a" ^
895 (if max_genuine = 1 then " better " ^ das_wort_model ^ "."
896 else "ny better " ^ das_wort_model ^ "s.")); "potential")
897 else if found_really_genuine then
901 | run_batches j n (batch :: batches) z =
902 let val (z as (_, _, max_genuine, _)) = run_batch j n batch z in
903 run_batches (j + 1) n (if max_genuine > 0 then batches else []) z
906 val (skipped, the_scopes) =
907 all_scopes hol_ctxt binarize cards_assigns maxes_assigns iters_assigns
908 bitss bisim_depths mono_Ts nonmono_Ts deep_dataTs
910 val _ = if skipped > 0 then
911 print_m (fn () => "Too many scopes. Skipping " ^
912 string_of_int skipped ^ " scope" ^
914 ". (Consider using \"mono\" or \
915 \\"merge_type_vars\" to prevent this.)")
918 val _ = scopes := the_scopes
920 val batches = batch_list batch_size (!scopes)
922 (run_batches 0 (length batches) batches
923 (false, max_potential, max_genuine, 0)
924 handle Exn.Interrupt => do_interrupted ())
925 handle TimeLimit.TimeOut =>
926 (print_m (fn () => excipit "ran out of time after checking");
927 if !met_potential > 0 then "potential" else "unknown")
929 if auto orelse debug then raise Interrupt
930 else error (excipit "was interrupted after checking")
931 val _ = print_v (fn () => "Total time: " ^
932 signed_string_of_int (Time.toMilliseconds
933 (Timer.checkRealTimer timer)) ^ " ms.")
934 in (outcome_code, !state_ref) end
935 handle Exn.Interrupt =>
936 if auto orelse #debug params then
939 if passed_deadline deadline then
940 (priority "Nitpick ran out of time."; ("unknown", state))
942 error "Nitpick was interrupted."
944 fun pick_nits_in_term state (params as {debug, timeout, expect, ...}) auto i n
945 step subst orig_assm_ts orig_t =
947 val warning_m = if auto then K () else warning
948 val unknown_outcome = ("unknown", state)
950 if getenv "KODKODI" = "" then
951 (warning_m (Pretty.string_of (plazy install_kodkodi_message));
955 val deadline = Option.map (curry Time.+ (Time.now ())) timeout
956 val outcome as (outcome_code, _) =
957 time_limit (if debug then NONE else timeout)
958 (pick_them_nits_in_term deadline state params auto i n step subst
960 handle TOO_LARGE (_, details) =>
961 (warning ("Limit reached: " ^ details ^ "."); unknown_outcome)
962 | TOO_SMALL (_, details) =>
963 (warning ("Limit reached: " ^ details ^ "."); unknown_outcome)
964 | Kodkod.SYNTAX (_, details) =>
965 (warning ("Ill-formed Kodkodi output: " ^ details ^ ".");
968 if expect = "" orelse outcome_code = expect then outcome
969 else error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
973 fun is_fixed_equation fixes
974 (Const (@{const_name "=="}, _) $ Free (s, _) $ Const _) =
975 member (op =) fixes s
976 | is_fixed_equation _ _ = false
977 fun extract_fixed_frees ctxt (assms, t) =
979 val fixes = Variable.fixes_of ctxt |> map snd
980 val (subst, other_assms) =
981 List.partition (is_fixed_equation fixes) assms
982 |>> map Logic.dest_equals
983 in (subst, other_assms, subst_atomic subst t) end
985 fun pick_nits_in_subgoal state params auto i step =
987 val ctxt = Proof.context_of state
988 val t = state |> Proof.raw_goal |> #goal |> prop_of
990 case Logic.count_prems t of
991 0 => (priority "No subgoal!"; ("none", state))
994 val t = Logic.goal_params t i |> fst
995 val assms = map term_of (Assumption.all_assms_of ctxt)
996 val (subst, assms, t) = extract_fixed_frees ctxt (assms, t)
997 in pick_nits_in_term state params auto i n step subst assms t end