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,
47 check_potential: bool,
52 val register_frac_type : string -> (string * string) list -> theory -> theory
53 val unregister_frac_type : string -> theory -> theory
54 val register_codatatype : typ -> string -> styp list -> theory -> theory
55 val unregister_codatatype : typ -> theory -> theory
56 val register_term_postprocessor :
57 typ -> term_postprocessor -> theory -> theory
58 val unregister_term_postprocessor : typ -> theory -> theory
59 val pick_nits_in_term :
60 Proof.state -> params -> bool -> int -> int -> int -> (term * term) list
61 -> term list -> term -> string * Proof.state
62 val pick_nits_in_subgoal :
63 Proof.state -> params -> bool -> int -> int -> string * Proof.state
66 structure Nitpick : NITPICK =
83 {cards_assigns: (typ option * int list) list,
84 maxes_assigns: (styp option * int list) list,
85 iters_assigns: (styp option * int list) list,
87 bisim_depths: int list,
88 boxes: (typ option * bool option) list,
89 finitizes: (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,
105 star_linear_preds: bool,
107 peephole_optim: bool,
108 timeout: Time.time option,
109 tac_timeout: Time.time option,
111 show_datatypes: bool,
114 formats: (term option * int list) list,
117 check_potential: bool,
122 type problem_extension =
123 {free_names: nut list,
125 nonsel_names: nut list,
126 rel_table: nut NameTable.table,
130 type rich_problem = KK.problem * problem_extension
132 fun pretties_for_formulas _ _ [] = []
133 | pretties_for_formulas ctxt s ts =
134 [Pretty.str (s ^ plural_s_for_list ts ^ ":"),
135 Pretty.indent indent_size (Pretty.chunks
136 (map2 (fn j => fn t =>
137 Pretty.block [t |> shorten_names_in_term
138 |> Syntax.pretty_term ctxt,
139 Pretty.str (if j = 1 then "." else ";")])
140 (length ts downto 1) ts))]
142 fun install_java_message () =
143 "Nitpick requires a Java 1.5 virtual machine called \"java\"."
144 fun install_kodkodi_message () =
145 "Nitpick requires the external Java program Kodkodi. To install it, download \
146 \the package from Isabelle's web page and add the \"kodkodi-x.y.z\" \
147 \directory's full path to \"" ^
148 Path.implode (Path.expand (Path.appends
149 (Path.variable "ISABELLE_HOME_USER" ::
150 map Path.basic ["etc", "components"]))) ^ "\" on a line of its own."
152 val max_unsound_delay_ms = 200
153 val max_unsound_delay_percent = 2
155 fun unsound_delay_for_timeout NONE = max_unsound_delay_ms
156 | unsound_delay_for_timeout (SOME timeout) =
157 Int.max (0, Int.min (max_unsound_delay_ms,
158 Time.toMilliseconds timeout
159 * max_unsound_delay_percent div 100))
161 fun passed_deadline NONE = false
162 | passed_deadline (SOME time) = Time.compare (Time.now (), time) <> LESS
164 fun none_true assigns = forall (not_equal (SOME true) o snd) assigns
166 val syntactic_sorts =
167 @{sort "{default,zero,one,plus,minus,uminus,times,inverse,abs,sgn,ord,eq}"} @
169 fun has_tfree_syntactic_sort (TFree (_, S as _ :: _)) =
170 subset (op =) (S, syntactic_sorts)
171 | has_tfree_syntactic_sort _ = false
172 val has_syntactic_sorts = exists_type (exists_subtype has_tfree_syntactic_sort)
174 fun plazy f = Pretty.blk (0, pstrs (f ()))
176 fun pick_them_nits_in_term deadline state (params : params) auto i n step
177 subst orig_assm_ts orig_t =
179 val timer = Timer.startRealTimer ()
180 val thy = Proof.theory_of state
181 val ctxt = Proof.context_of state
182 (* FIXME: reintroduce code before new release:
184 val nitpick_thy = ThyInfo.get_theory "Nitpick"
185 val _ = Theory.subthy (nitpick_thy, thy) orelse
186 error "You must import the theory \"Nitpick\" to use Nitpick"
188 val {cards_assigns, maxes_assigns, iters_assigns, bitss, bisim_depths,
189 boxes, finitizes, monos, stds, wfs, sat_solver, falsify, debug,
190 verbose, overlord, user_axioms, assms, merge_type_vars, binary_ints,
191 destroy_constrs, specialize, star_linear_preds, fast_descrs,
192 peephole_optim, tac_timeout, max_threads, show_datatypes, show_consts,
193 evals, formats, max_potential, max_genuine, check_potential,
194 check_genuine, batch_size, ...} = params
195 val state_ref = Unsynchronized.ref state
198 Unsynchronized.change state_ref o Proof.goal_message o K
199 o Pretty.chunks o cons (Pretty.str "") o single
200 o Pretty.mark Markup.hilite
202 (fn s => (priority s; if debug then tracing s else ()))
204 fun pprint_m f = () |> not auto ? pprint o f
205 fun pprint_v f = () |> verbose ? pprint o f
206 fun pprint_d f = () |> debug ? pprint o f
207 val print = pprint o curry Pretty.blk 0 o pstrs
208 val print_g = pprint o Pretty.str
209 val print_m = pprint_m o K o plazy
210 val print_v = pprint_v o K o plazy
212 fun check_deadline () =
213 if debug andalso passed_deadline deadline then raise TimeLimit.TimeOut
215 fun do_interrupted () =
216 if passed_deadline deadline then raise TimeLimit.TimeOut
219 val orig_assm_ts = if assms orelse auto then orig_assm_ts else []
222 print_m (fn () => "Nitpicking formula...")
224 pprint_m (fn () => Pretty.chunks (
225 pretties_for_formulas ctxt ("Nitpicking " ^
226 (if i <> 1 orelse n <> 1 then
227 "subgoal " ^ string_of_int i ^ " of " ^ string_of_int n
229 "goal")) [Logic.list_implies (orig_assm_ts, orig_t)]))
230 val neg_t = if falsify then Logic.mk_implies (orig_t, @{prop False})
232 val assms_t = Logic.mk_conjunction_list (neg_t :: orig_assm_ts)
233 val (assms_t, evals) =
234 assms_t :: evals |> merge_type_vars ? merge_type_vars_in_terms
236 val original_max_potential = max_potential
237 val original_max_genuine = max_genuine
239 val _ = print_g ("*** " ^ Syntax.string_of_term ctxt orig_t)
240 val _ = List.app (fn t => print_g ("*** " ^ Syntax.string_of_term ctxt t))
243 val max_bisim_depth = fold Integer.max bisim_depths ~1
244 val case_names = case_const_names thy stds
245 val (defs, built_in_nondefs, user_nondefs) = all_axioms_of ctxt subst
246 val def_table = const_def_table ctxt subst defs
247 val nondef_table = const_nondef_table (built_in_nondefs @ user_nondefs)
248 val simp_table = Unsynchronized.ref (const_simp_table ctxt subst)
249 val psimp_table = const_psimp_table ctxt subst
250 val choice_spec_table = const_choice_spec_table ctxt subst
252 user_nondefs |> filter_out (is_choice_spec_axiom thy choice_spec_table)
253 val intro_table = inductive_intro_table ctxt subst def_table
254 val ground_thm_table = ground_theorem_table thy
255 val ersatz_table = ersatz_table thy
256 val (hol_ctxt as {wf_cache, ...}) =
257 {thy = thy, ctxt = ctxt, max_bisim_depth = max_bisim_depth, boxes = boxes,
258 stds = stds, wfs = wfs, user_axioms = user_axioms, debug = debug,
259 binary_ints = binary_ints, destroy_constrs = destroy_constrs,
260 specialize = specialize, star_linear_preds = star_linear_preds,
261 fast_descrs = fast_descrs, tac_timeout = tac_timeout, evals = evals,
262 case_names = case_names, def_table = def_table,
263 nondef_table = nondef_table, user_nondefs = user_nondefs,
264 simp_table = simp_table, psimp_table = psimp_table,
265 choice_spec_table = choice_spec_table, intro_table = intro_table,
266 ground_thm_table = ground_thm_table, ersatz_table = ersatz_table,
267 skolems = Unsynchronized.ref [], special_funs = Unsynchronized.ref [],
268 unrolled_preds = Unsynchronized.ref [], wf_cache = Unsynchronized.ref [],
269 constr_cache = Unsynchronized.ref []}
270 val frees = Term.add_frees assms_t []
271 val _ = null (Term.add_tvars assms_t []) orelse
272 raise NOT_SUPPORTED "schematic type variables"
273 val (nondef_ts, def_ts, got_all_mono_user_axioms, no_poly_user_axioms,
274 binarize) = preprocess_term hol_ctxt finitizes monos assms_t
275 val got_all_user_axioms =
276 got_all_mono_user_axioms andalso no_poly_user_axioms
278 fun print_wf (x, (gfp, wf)) =
279 pprint (Pretty.blk (0,
280 pstrs ("The " ^ (if gfp then "co" else "") ^ "inductive predicate \"")
281 @ Syntax.pretty_term ctxt (Const x) ::
283 "\" was proved well-founded. Nitpick can compute it \
286 "\" could not be proved well-founded. Nitpick might need to \
288 val _ = if verbose then List.app print_wf (!wf_cache) else ()
290 pprint_d (fn () => Pretty.chunks
291 (pretties_for_formulas ctxt "Preprocessed formula" [hd nondef_ts] @
292 pretties_for_formulas ctxt "Relevant definitional axiom" def_ts @
293 pretties_for_formulas ctxt "Relevant nondefinitional axiom"
295 val _ = List.app (ignore o Term.type_of) (nondef_ts @ def_ts)
296 handle TYPE (_, Ts, ts) =>
297 raise TYPE ("Nitpick.pick_them_nits_in_term", Ts, ts)
299 val nondef_us = map (nut_from_term hol_ctxt Eq) nondef_ts
300 val def_us = map (nut_from_term hol_ctxt DefEq) def_ts
301 val (free_names, const_names) =
302 fold add_free_and_const_names (nondef_us @ def_us) ([], [])
303 val (sel_names, nonsel_names) =
304 List.partition (is_sel o nickname_of) const_names
305 val sound_finitizes =
306 none_true (filter_out (fn (SOME (Type (@{type_name fun}, _)), _) => true
307 | _ => false) finitizes)
308 val standard = forall snd stds
310 val _ = List.app (print_g o string_for_nut ctxt) (nondef_us @ def_us)
313 val unique_scope = forall (curry (op =) 1 o length o snd) cards_assigns
314 fun monotonicity_message Ts extra =
315 let val ss = map (quote o string_for_type ctxt) Ts in
316 "The type" ^ plural_s_for_list ss ^ " " ^
317 space_implode " " (serial_commas "and" ss) ^ " " ^
318 (if none_true monos then
319 "passed the monotonicity test"
321 (if length ss = 1 then "is" else "are") ^ " considered monotonic") ^
324 fun is_type_fundamentally_monotonic T =
325 (is_datatype ctxt stds T andalso not (is_quot_type thy T) andalso
326 (not (is_pure_typedef ctxt T) orelse is_univ_typedef ctxt T)) orelse
327 is_number_type thy T orelse is_bit_type T
328 fun is_type_actually_monotonic T =
329 formulas_monotonic hol_ctxt binarize T (nondef_ts, def_ts)
330 fun is_type_kind_of_monotonic T =
331 case triple_lookup (type_match thy) monos T of
332 SOME (SOME false) => false
333 | _ => is_type_actually_monotonic T
334 fun is_type_monotonic T =
336 case triple_lookup (type_match thy) monos T of
338 | _ => is_type_fundamentally_monotonic T orelse
339 is_type_actually_monotonic T
340 fun is_shallow_datatype_finitizable (T as Type (@{type_name fin_fun}, _)) =
341 is_type_kind_of_monotonic T
342 | is_shallow_datatype_finitizable (T as Type (@{type_name fun_box}, _)) =
343 is_type_kind_of_monotonic T
344 | is_shallow_datatype_finitizable T =
345 case triple_lookup (type_match thy) finitizes T of
347 | _ => is_type_kind_of_monotonic T
348 fun is_datatype_deep T =
349 not standard orelse T = nat_T orelse is_word_type T orelse
350 exists (curry (op =) T o domain_type o type_of) sel_names
351 val all_Ts = ground_types_in_terms hol_ctxt binarize (nondef_ts @ def_ts)
352 |> sort Term_Ord.typ_ord
353 val _ = if verbose andalso binary_ints = SOME true andalso
354 exists (member (op =) [nat_T, int_T]) all_Ts then
355 print_v (K "The option \"binary_ints\" will be ignored because \
356 \of the presence of rationals, reals, \"Suc\", \
357 \\"gcd\", or \"lcm\" in the problem or because of the \
358 \\"non_std\" option.")
361 val (mono_Ts, nonmono_Ts) = List.partition is_type_monotonic all_Ts
363 if verbose andalso not unique_scope then
364 case filter_out is_type_fundamentally_monotonic mono_Ts of
366 | interesting_mono_Ts =>
367 print_v (K (monotonicity_message interesting_mono_Ts
368 "Nitpick might be able to skip some scopes."))
371 val (deep_dataTs, shallow_dataTs) =
372 all_Ts |> filter (is_datatype ctxt stds)
373 |> List.partition is_datatype_deep
374 val finitizable_dataTs =
375 shallow_dataTs |> filter_out (is_finite_type hol_ctxt)
376 |> filter is_shallow_datatype_finitizable
378 if verbose andalso not (null finitizable_dataTs) then
379 print_v (K (monotonicity_message finitizable_dataTs
380 "Nitpick can use a more precise finite encoding."))
383 (* This detection code is an ugly hack. Fortunately, it is used only to
384 provide a hint to the user. *)
385 fun is_struct_induct_step (name, (Rule_Cases.Case {fixes, assumes, ...}, _)) =
386 not (null fixes) andalso
387 exists (String.isSuffix ".hyps" o fst) assumes andalso
388 exists (exists (curry (op =) name o shortest_name o fst)
389 o datatype_constrs hol_ctxt) deep_dataTs
390 val likely_in_struct_induct_step =
391 exists is_struct_induct_step (ProofContext.cases_of ctxt)
392 val _ = if standard andalso likely_in_struct_induct_step then
393 pprint_m (fn () => Pretty.blk (0,
394 pstrs "Hint: To check that the induction hypothesis is \
395 \general enough, try this command: " @
396 [Pretty.mark Markup.sendback (Pretty.blk (0,
397 pstrs ("nitpick [non_std, show_all]")))] @ pstrs "."))
401 val _ = print_g "Monotonic types:"
402 val _ = List.app (print_g o string_for_type ctxt) mono_Ts
403 val _ = print_g "Nonmonotonic types:"
404 val _ = List.app (print_g o string_for_type ctxt) nonmono_Ts
407 val incremental = Int.max (max_potential, max_genuine) >= 2
408 val actual_sat_solver =
409 if sat_solver <> "smart" then
410 if incremental andalso
411 not (member (op =) (Kodkod_SAT.configured_sat_solvers true)
413 (print_m (K ("An incremental SAT solver is required: \"SAT4J\" will \
414 \be used instead of " ^ quote sat_solver ^ "."));
419 Kodkod_SAT.smart_sat_solver_name incremental
421 if sat_solver = "smart" then
423 "Using SAT solver " ^ quote actual_sat_solver ^ ". The following" ^
424 (if incremental then " incremental " else " ") ^
425 "solvers are configured: " ^
426 commas_quote (Kodkod_SAT.configured_sat_solvers incremental) ^ ".")
430 val too_big_scopes = Unsynchronized.ref []
432 fun problem_for_scope unsound
433 (scope as {card_assigns, bits, bisim_depth, datatypes, ofs, ...}) =
435 val _ = not (exists (fn other => scope_less_eq other scope)
436 (!too_big_scopes)) orelse
437 raise TOO_LARGE ("Nitpick.pick_them_nits_in_term.\
438 \problem_for_scope", "too large scope")
440 val _ = print_g "Offsets:"
441 val _ = List.app (fn (T, j0) =>
442 print_g (string_for_type ctxt T ^ " = " ^
446 val all_exact = forall (is_exact_type datatypes true) all_Ts
447 val repify_consts = choose_reps_for_consts scope all_exact
448 val main_j0 = offset_of_type ofs bool_T
449 val (nat_card, nat_j0) = spec_of_type scope nat_T
450 val (int_card, int_j0) = spec_of_type scope int_T
451 val _ = (nat_j0 = main_j0 andalso int_j0 = main_j0) orelse
452 raise BAD ("Nitpick.pick_them_nits_in_term.problem_for_scope",
454 val kk = kodkod_constrs peephole_optim nat_card int_card main_j0
455 val (free_names, rep_table) =
456 choose_reps_for_free_vars scope free_names NameTable.empty
457 val (sel_names, rep_table) = choose_reps_for_all_sels scope rep_table
458 val (nonsel_names, rep_table) = repify_consts nonsel_names rep_table
459 val min_highest_arity =
460 NameTable.fold (Integer.max o arity_of_rep o snd) rep_table 1
462 NameTable.fold (Integer.max o min_univ_card_of_rep o snd) rep_table
463 (univ_card nat_card int_card main_j0 [] KK.True)
464 val _ = check_arity min_univ_card min_highest_arity
466 val def_us = map (choose_reps_in_nut scope unsound rep_table true)
468 val nondef_us = map (choose_reps_in_nut scope unsound rep_table false)
471 val _ = List.app (print_g o string_for_nut ctxt)
472 (free_names @ sel_names @ nonsel_names @
475 val (free_rels, pool, rel_table) =
476 rename_free_vars free_names initial_pool NameTable.empty
477 val (sel_rels, pool, rel_table) =
478 rename_free_vars sel_names pool rel_table
479 val (other_rels, pool, rel_table) =
480 rename_free_vars nonsel_names pool rel_table
481 val nondef_us = map (rename_vars_in_nut pool rel_table) nondef_us
482 val def_us = map (rename_vars_in_nut pool rel_table) def_us
483 val nondef_fs = map (kodkod_formula_from_nut ofs kk) nondef_us
484 val def_fs = map (kodkod_formula_from_nut ofs kk) def_us
485 val formula = fold (fold s_and) [def_fs, nondef_fs] KK.True
486 val comment = (if unsound then "unsound" else "sound") ^ "\n" ^
487 Print_Mode.setmp [] multiline_string_for_scope scope
488 val kodkod_sat_solver =
489 Kodkod_SAT.sat_solver_spec actual_sat_solver |> snd
490 val bit_width = if bits = 0 then 16 else bits + 1
493 Option.map (fn time => Time.- (time, Time.now ())) deadline
494 |> unsound_delay_for_timeout
497 val settings = [("solver", commas_quote kodkod_sat_solver),
498 ("skolem_depth", "-1"),
499 ("bit_width", string_of_int bit_width),
500 ("symmetry_breaking", "20"),
502 ("flatten", "false"),
503 ("delay", signed_string_of_int delay)]
504 val plain_rels = free_rels @ other_rels
505 val plain_bounds = map (bound_for_plain_rel ctxt debug) plain_rels
506 val plain_axioms = map (declarative_axiom_for_plain_rel kk) plain_rels
507 val sel_bounds = map (bound_for_sel_rel ctxt debug datatypes) sel_rels
509 declarative_axioms_for_datatypes hol_ctxt binarize bits ofs kk
511 val declarative_axioms = plain_axioms @ dtype_axioms
512 val univ_card = Int.max (univ_card nat_card int_card main_j0
513 (plain_bounds @ sel_bounds) formula,
514 main_j0 |> bits > 0 ? Integer.add (bits + 1))
515 val built_in_bounds = bounds_for_built_in_rels_in_formula debug
516 univ_card nat_card int_card main_j0 formula
517 val bounds = built_in_bounds @ plain_bounds @ sel_bounds
518 |> not debug ? merge_bounds
520 fold Integer.max (map (fst o fst) (maps fst bounds)) 0
521 val formula = fold_rev s_and declarative_axioms formula
522 val _ = if bits = 0 then () else check_bits bits formula
523 val _ = if formula = KK.False then ()
524 else check_arity univ_card highest_arity
526 SOME ({comment = comment, settings = settings, univ_card = univ_card,
527 tuple_assigns = [], bounds = bounds,
528 int_bounds = if bits = 0 then sequential_int_bounds univ_card
529 else pow_of_two_int_bounds bits main_j0,
530 expr_assigns = [], formula = formula},
531 {free_names = free_names, sel_names = sel_names,
532 nonsel_names = nonsel_names, rel_table = rel_table,
533 unsound = unsound, scope = scope})
535 handle TOO_LARGE (loc, msg) =>
536 if loc = "Nitpick_Kodkod.check_arity" andalso
537 not (Typtab.is_empty ofs) then
538 problem_for_scope unsound
539 {hol_ctxt = hol_ctxt, binarize = binarize,
540 card_assigns = card_assigns, bits = bits,
541 bisim_depth = bisim_depth, datatypes = datatypes,
543 else if loc = "Nitpick.pick_them_nits_in_term.\
544 \problem_for_scope" then
547 (Unsynchronized.change too_big_scopes (cons scope);
548 print_v (fn () => ("Limit reached: " ^ msg ^
549 ". Skipping " ^ (if unsound then "potential"
551 " component of scope."));
553 | TOO_SMALL (_, msg) =>
554 (print_v (fn () => ("Limit reached: " ^ msg ^
555 ". Skipping " ^ (if unsound then "potential"
557 " component of scope."));
561 (if falsify then "counterexample" else "model")
562 |> not standard ? prefix "nonstandard "
564 val scopes = Unsynchronized.ref []
565 val generated_scopes = Unsynchronized.ref []
566 val generated_problems = Unsynchronized.ref ([] : rich_problem list)
567 val checked_problems = Unsynchronized.ref (SOME [])
568 val met_potential = Unsynchronized.ref 0
570 fun update_checked_problems problems =
571 List.app (Unsynchronized.change checked_problems o Option.map o cons
573 fun show_kodkod_warning "" = ()
574 | show_kodkod_warning s = print_m (fn () => "Kodkod warning: " ^ s ^ ".")
576 fun print_and_check_model genuine bounds
577 ({free_names, sel_names, nonsel_names, rel_table, scope, ...}
578 : problem_extension) =
580 val (reconstructed_model, codatatypes_ok) =
581 reconstruct_hol_model {show_datatypes = show_datatypes,
582 show_consts = show_consts}
583 scope formats frees free_names sel_names nonsel_names rel_table
585 val genuine_means_genuine =
586 got_all_user_axioms andalso none_true wfs andalso
587 sound_finitizes andalso codatatypes_ok
589 (pprint (Pretty.chunks
591 (pstrs ("Nitpick found a" ^
592 (if not genuine then " potential "
593 else if genuine_means_genuine then " "
594 else " quasi genuine ") ^ das_wort_model) @
595 (case pretties_for_scope scope verbose of
597 | pretties => pstrs " for " @ pretties) @
598 [Pretty.str ":\n"])),
599 Pretty.indent indent_size reconstructed_model]);
601 (if check_genuine andalso standard then
602 case prove_hol_model scope tac_timeout free_names sel_names
603 rel_table bounds assms_t of
605 print ("Confirmation by \"auto\": The above " ^
606 das_wort_model ^ " is really genuine.")
608 if genuine_means_genuine then
609 error ("A supposedly genuine " ^ das_wort_model ^ " was \
610 \shown to be spurious by \"auto\".\nThis should never \
611 \happen.\nPlease send a bug report to blanchet\
614 print ("Refutation by \"auto\": The above " ^
615 das_wort_model ^ " is spurious.")
616 | NONE => print "No confirmation by \"auto\"."
619 if not standard andalso likely_in_struct_induct_step then
620 print "The existence of a nonstandard model suggests that the \
621 \induction hypothesis is not general enough or may even be \
622 \wrong. See the Nitpick manual's \"Inductive Properties\" \
623 \section for details (\"isabelle doc nitpick\")."
626 if has_syntactic_sorts orig_t then
627 print "Hint: Maybe you forgot a type constraint?"
630 if not genuine_means_genuine then
631 if no_poly_user_axioms then
634 [] |> not got_all_mono_user_axioms
635 ? cons ("user_axioms", "\"true\"")
636 |> not (none_true wfs)
637 ? cons ("wf", "\"smart\" or \"false\"")
638 |> not sound_finitizes
639 ? cons ("finitize", "\"smart\" or \"false\"")
640 |> not codatatypes_ok
641 ? cons ("bisim_depth", "a nonnegative value")
643 map (fn (name, value) => quote name ^ " set to " ^ value)
646 print ("Try again with " ^
647 space_implode " " (serial_commas "and" ss) ^
648 " to confirm that the " ^ das_wort_model ^
652 print ("Nitpick is unable to guarantee the authenticity of \
653 \the " ^ das_wort_model ^ " in the presence of \
654 \polymorphic axioms.")
660 (Unsynchronized.inc met_potential;
661 if check_potential then
663 val status = prove_hol_model scope tac_timeout free_names
664 sel_names rel_table bounds assms_t
667 SOME true => print ("Confirmation by \"auto\": The \
668 \above " ^ das_wort_model ^
670 | SOME false => print ("Refutation by \"auto\": The above " ^
671 das_wort_model ^ " is spurious.")
672 | NONE => print "No confirmation by \"auto\".");
679 |> pair genuine_means_genuine
681 fun solve_any_problem (found_really_genuine, max_potential, max_genuine,
682 donno) first_time problems =
684 val max_potential = Int.max (0, max_potential)
685 val max_genuine = Int.max (0, max_genuine)
686 fun print_and_check genuine (j, bounds) =
687 print_and_check_model genuine bounds (snd (nth problems j))
688 val max_solutions = max_potential + max_genuine
689 |> not incremental ? Integer.min 1
691 if max_solutions <= 0 then
692 (found_really_genuine, 0, 0, donno)
694 case KK.solve_any_problem overlord deadline max_threads max_solutions
695 (map fst problems) of
696 KK.JavaNotInstalled =>
697 (print_m install_java_message;
698 (found_really_genuine, max_potential, max_genuine, donno + 1))
699 | KK.KodkodiNotInstalled =>
700 (print_m install_kodkodi_message;
701 (found_really_genuine, max_potential, max_genuine, donno + 1))
702 | KK.Normal ([], unsat_js, s) =>
703 (update_checked_problems problems unsat_js; show_kodkod_warning s;
704 (found_really_genuine, max_potential, max_genuine, donno))
705 | KK.Normal (sat_ps, unsat_js, s) =>
707 val (lib_ps, con_ps) =
708 List.partition (#unsound o snd o nth problems o fst) sat_ps
710 update_checked_problems problems (unsat_js @ map fst lib_ps);
711 show_kodkod_warning s;
715 lib_ps |> take max_potential
716 |> map (print_and_check false)
717 |> filter (curry (op =) (SOME true) o snd)
718 val found_really_genuine =
719 found_really_genuine orelse exists fst genuine_codes
720 val num_genuine = length genuine_codes
721 val max_genuine = max_genuine - num_genuine
722 val max_potential = max_potential
723 - (length lib_ps - num_genuine)
725 if max_genuine <= 0 then
726 (found_really_genuine, 0, 0, donno)
729 (* "co_js" is the list of sound problems whose unsound
730 pendants couldn't be satisfied and hence that most
731 probably can't be satisfied themselves. *)
733 map (fn j => j - 1) unsat_js
737 (#scope (snd (nth problems j)),
738 #scope (snd (nth problems (j + 1)))))
739 val bye_js = sort_distinct int_ord (map fst sat_ps @
742 problems |> filter_out_indices bye_js
743 |> max_potential <= 0
744 ? filter_out (#unsound o snd)
746 solve_any_problem (found_really_genuine, max_potential,
747 max_genuine, donno) false problems
753 con_ps |> take max_genuine
754 |> map (print_and_check true)
755 val max_genuine = max_genuine - length genuine_codes
756 val found_really_genuine =
757 found_really_genuine orelse exists fst genuine_codes
759 if max_genuine <= 0 orelse not first_time then
760 (found_really_genuine, 0, max_genuine, donno)
763 val bye_js = sort_distinct int_ord
764 (map fst sat_ps @ unsat_js)
766 problems |> filter_out_indices bye_js
767 |> filter_out (#unsound o snd)
769 solve_any_problem (found_really_genuine, 0, max_genuine,
770 donno) false problems
774 | KK.TimedOut unsat_js =>
775 (update_checked_problems problems unsat_js; raise TimeLimit.TimeOut)
776 | KK.Interrupted NONE => (checked_problems := NONE; do_interrupted ())
777 | KK.Interrupted (SOME unsat_js) =>
778 (update_checked_problems problems unsat_js; do_interrupted ())
779 | KK.Error (s, unsat_js) =>
780 (update_checked_problems problems unsat_js;
781 print_v (K ("Kodkod error: " ^ s ^ "."));
782 (found_really_genuine, max_potential, max_genuine, donno + 1))
785 fun run_batch j n scopes (found_really_genuine, max_potential, max_genuine,
790 print_m (K "The scope specification is inconsistent.")
792 pprint (Pretty.chunks
794 pstrs ((if n > 1 then
795 "Batch " ^ string_of_int (j + 1) ^ " of " ^
796 signed_string_of_int n ^ ": "
799 "Trying " ^ string_of_int (length scopes) ^
800 " scope" ^ plural_s_for_list scopes ^ ":")),
801 Pretty.indent indent_size
805 (case pretties_for_scope scope true of
806 [] => [Pretty.str "Empty"]
807 | pretties => pretties) @
808 [Pretty.str (if j = 1 then "." else ";")]))
809 (length scopes downto 1) scopes))])
812 fun add_problem_for_scope (scope, unsound) (problems, donno) =
814 case problem_for_scope unsound scope of
817 |> (null problems orelse
818 not (KK.problems_equivalent (fst problem, fst (hd problems))))
819 ? cons problem, donno)
820 | NONE => (problems, donno + 1))
821 val (problems, donno) =
822 fold add_problem_for_scope
823 (map_product pair scopes
824 ((if max_genuine > 0 then [false] else []) @
825 (if max_potential > 0 then [true] else [])))
827 val _ = Unsynchronized.change generated_problems (append problems)
828 val _ = Unsynchronized.change generated_scopes (append scopes)
832 val (unsound_problems, sound_problems) =
833 List.partition (#unsound o snd) (!generated_problems)
835 if not (null sound_problems) andalso
836 forall (KK.is_problem_trivially_false o fst)
839 "Warning: The conjecture either trivially holds for the \
840 \given scopes or lies outside Nitpick's supported \
842 (if exists (not o KK.is_problem_trivially_false o fst)
843 unsound_problems then
844 " Only potential " ^ das_wort_model ^ "s may be found."
853 solve_any_problem (found_really_genuine, max_potential, max_genuine,
854 donno) true (rev problems)
857 fun scope_count (problems : rich_problem list) scope =
858 length (filter (curry scopes_equivalent scope o #scope o snd) problems)
859 fun excipit did_so_and_so =
862 if !met_potential = max_potential then filter_out (#unsound o snd)
864 val total = length (!scopes)
867 case scope_count (do_filter (!generated_problems)) scope of
870 scope_count (do_filter (these (!checked_problems)))
872 ? Integer.add 1) (!generated_scopes) 0
874 "Nitpick " ^ did_so_and_so ^
875 (if is_some (!checked_problems) andalso total > 0 then
876 " " ^ string_of_int (Int.min (total - 1, unsat)) ^ " of " ^
877 string_of_int total ^ " scope" ^ plural_s total
882 fun run_batches _ _ []
883 (found_really_genuine, max_potential, max_genuine, donno) =
884 if donno > 0 andalso max_genuine > 0 then
885 (print_m (fn () => excipit "checked"); "unknown")
886 else if max_genuine = original_max_genuine then
887 if max_potential = original_max_potential then
889 "Nitpick found no " ^ das_wort_model ^ "." ^
890 (if not standard andalso likely_in_struct_induct_step then
891 " This suggests that the induction hypothesis might be \
892 \general enough to prove this subgoal."
897 "Nitpick could not find a" ^
898 (if max_genuine = 1 then " better " ^ das_wort_model ^ "."
899 else "ny better " ^ das_wort_model ^ "s.")); "potential")
900 else if found_really_genuine then
904 | run_batches j n (batch :: batches) z =
905 let val (z as (_, _, max_genuine, _)) = run_batch j n batch z in
906 run_batches (j + 1) n (if max_genuine > 0 then batches else []) z
909 val (skipped, the_scopes) =
910 all_scopes hol_ctxt binarize cards_assigns maxes_assigns iters_assigns
911 bitss bisim_depths mono_Ts nonmono_Ts deep_dataTs
913 val _ = if skipped > 0 then
914 print_m (fn () => "Too many scopes. Skipping " ^
915 string_of_int skipped ^ " scope" ^
917 ". (Consider using \"mono\" or \
918 \\"merge_type_vars\" to prevent this.)")
921 val _ = scopes := the_scopes
923 val batches = batch_list batch_size (!scopes)
925 (run_batches 0 (length batches) batches
926 (false, max_potential, max_genuine, 0)
927 handle Exn.Interrupt => do_interrupted ())
928 handle TimeLimit.TimeOut =>
929 (print_m (fn () => excipit "ran out of time after checking");
930 if !met_potential > 0 then "potential" else "unknown")
932 if auto orelse debug then raise Interrupt
933 else error (excipit "was interrupted after checking")
934 val _ = print_v (fn () => "Total time: " ^
935 signed_string_of_int (Time.toMilliseconds
936 (Timer.checkRealTimer timer)) ^ " ms.")
937 in (outcome_code, !state_ref) end
938 handle Exn.Interrupt =>
939 if auto orelse #debug params then
942 if passed_deadline deadline then
943 (priority "Nitpick ran out of time."; ("unknown", state))
945 error "Nitpick was interrupted."
947 fun pick_nits_in_term state (params as {debug, timeout, expect, ...}) auto i n
948 step subst orig_assm_ts orig_t =
950 val warning_m = if auto then K () else warning
951 val unknown_outcome = ("unknown", state)
953 if getenv "KODKODI" = "" then
954 (warning_m (Pretty.string_of (plazy install_kodkodi_message));
958 val deadline = Option.map (curry Time.+ (Time.now ())) timeout
959 val outcome as (outcome_code, _) =
960 time_limit (if debug then NONE else timeout)
961 (pick_them_nits_in_term deadline state params auto i n step subst
963 handle TOO_LARGE (_, details) =>
964 (warning ("Limit reached: " ^ details ^ "."); unknown_outcome)
965 | TOO_SMALL (_, details) =>
966 (warning ("Limit reached: " ^ details ^ "."); unknown_outcome)
967 | Kodkod.SYNTAX (_, details) =>
968 (warning ("Ill-formed Kodkodi output: " ^ details ^ ".");
971 if expect = "" orelse outcome_code = expect then outcome
972 else error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
976 fun is_fixed_equation fixes
977 (Const (@{const_name "=="}, _) $ Free (s, _) $ Const _) =
978 member (op =) fixes s
979 | is_fixed_equation _ _ = false
980 fun extract_fixed_frees ctxt (assms, t) =
982 val fixes = Variable.fixes_of ctxt |> map snd
983 val (subst, other_assms) =
984 List.partition (is_fixed_equation fixes) assms
985 |>> map Logic.dest_equals
986 in (subst, other_assms, subst_atomic subst t) end
988 fun pick_nits_in_subgoal state params auto i step =
990 val ctxt = Proof.context_of state
991 val t = state |> Proof.raw_goal |> #goal |> prop_of
993 case Logic.count_prems t of
994 0 => (priority "No subgoal!"; ("none", state))
997 val t = Logic.goal_params t i |> fst
998 val assms = map term_of (Assumption.all_assms_of ctxt)
999 val (subst, assms, t) = extract_fixed_frees ctxt (assms, t)
1000 in pick_nits_in_term state params auto i n step subst assms t end