src/HOL/Tools/Nitpick/nitpick.ML
author blanchet
Wed, 10 Mar 2010 15:06:40 +0100
changeset 35696 17ae461d6133
parent 35666 ed2c3830d881
child 35711 548d3f16404b
permissions -rw-r--r--
show nice error message in Nitpick when "java" is not available
     1 (*  Title:      HOL/Tools/Nitpick/nitpick.ML
     2     Author:     Jasmin Blanchette, TU Muenchen
     3     Copyright   2008, 2009, 2010
     4 
     5 Finite model generation for HOL formulas using Kodkod.
     6 *)
     7 
     8 signature NITPICK =
     9 sig
    10   type styp = Nitpick_Util.styp
    11   type params = {
    12     cards_assigns: (typ option * int list) list,
    13     maxes_assigns: (styp option * int list) list,
    14     iters_assigns: (styp option * int list) list,
    15     bitss: int 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,
    22     sat_solver: string,
    23     blocking: bool,
    24     falsify: bool,
    25     debug: bool,
    26     verbose: bool,
    27     overlord: bool,
    28     user_axioms: bool option,
    29     assms: bool,
    30     merge_type_vars: bool,
    31     binary_ints: bool option,
    32     destroy_constrs: bool,
    33     specialize: bool,
    34     skolemize: bool,
    35     star_linear_preds: bool,
    36     uncurry: bool,
    37     fast_descrs: bool,
    38     peephole_optim: bool,
    39     timeout: Time.time option,
    40     tac_timeout: Time.time option,
    41     sym_break: int,
    42     sharing_depth: int,
    43     flatten_props: bool,
    44     max_threads: int,
    45     show_skolems: bool,
    46     show_datatypes: bool,
    47     show_consts: bool,
    48     evals: term list,
    49     formats: (term option * int list) list,
    50     max_potential: int,
    51     max_genuine: int,
    52     check_potential: bool,
    53     check_genuine: bool,
    54     batch_size: int,
    55     expect: string}
    56 
    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
    66 end;
    67 
    68 structure Nitpick : NITPICK =
    69 struct
    70 
    71 open Nitpick_Util
    72 open Nitpick_HOL
    73 open Nitpick_Preproc
    74 open Nitpick_Mono
    75 open Nitpick_Scope
    76 open Nitpick_Peephole
    77 open Nitpick_Rep
    78 open Nitpick_Nut
    79 open Nitpick_Kodkod
    80 open Nitpick_Model
    81 
    82 structure KK = Kodkod
    83 
    84 type params = {
    85   cards_assigns: (typ option * int list) list,
    86   maxes_assigns: (styp option * int list) list,
    87   iters_assigns: (styp option * int list) list,
    88   bitss: int 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,
    95   sat_solver: string,
    96   blocking: bool,
    97   falsify: bool,
    98   debug: bool,
    99   verbose: bool,
   100   overlord: bool,
   101   user_axioms: bool option,
   102   assms: bool,
   103   merge_type_vars: bool,
   104   binary_ints: bool option,
   105   destroy_constrs: bool,
   106   specialize: bool,
   107   skolemize: bool,
   108   star_linear_preds: bool,
   109   uncurry: bool,
   110   fast_descrs: bool,
   111   peephole_optim: bool,
   112   timeout: Time.time option,
   113   tac_timeout: Time.time option,
   114   sym_break: int,
   115   sharing_depth: int,
   116   flatten_props: bool,
   117   max_threads: int,
   118   show_skolems: bool,
   119   show_datatypes: bool,
   120   show_consts: bool,
   121   evals: term list,
   122   formats: (term option * int list) list,
   123   max_potential: int,
   124   max_genuine: int,
   125   check_potential: bool,
   126   check_genuine: bool,
   127   batch_size: int,
   128   expect: string}
   129 
   130 type problem_extension = {
   131   free_names: nut list,
   132   sel_names: nut list,
   133   nonsel_names: nut list,
   134   rel_table: nut NameTable.table,
   135   unsound: bool,
   136   scope: scope}
   137 
   138 type rich_problem = KK.problem * problem_extension
   139 
   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))]
   150 
   151 (* unit -> string *)
   152 fun install_java_message () =
   153   "Nitpick requires a Java 1.5 virtual machine called \"java\"."
   154 (* unit -> string *)
   155 fun install_kodkodi_message () =
   156   "Nitpick requires the external Java program Kodkodi. To install it, download \
   157   \the package from Isabelle's web page and add the \"kodkodi-x.y.z\" \
   158   \directory's full path to \"" ^
   159   Path.implode (Path.expand (Path.appends
   160       (Path.variable "ISABELLE_HOME_USER" ::
   161        map Path.basic ["etc", "components"]))) ^ "\"."
   162 
   163 val max_unsound_delay_ms = 200
   164 val max_unsound_delay_percent = 2
   165 
   166 (* Time.time option -> int *)
   167 fun unsound_delay_for_timeout NONE = max_unsound_delay_ms
   168   | unsound_delay_for_timeout (SOME timeout) =
   169     Int.max (0, Int.min (max_unsound_delay_ms,
   170                          Time.toMilliseconds timeout
   171                          * max_unsound_delay_percent div 100))
   172 
   173 (* Time.time option -> bool *)
   174 fun passed_deadline NONE = false
   175   | passed_deadline (SOME time) = Time.compare (Time.now (), time) <> LESS
   176 
   177 (* ('a * bool option) list -> bool *)
   178 fun none_true assigns = forall (not_equal (SOME true) o snd) assigns
   179 
   180 val syntactic_sorts =
   181   @{sort "{default,zero,one,plus,minus,uminus,times,inverse,abs,sgn,ord,eq}"} @
   182   @{sort number}
   183 (* typ -> bool *)
   184 fun has_tfree_syntactic_sort (TFree (_, S as _ :: _)) =
   185     subset (op =) (S, syntactic_sorts)
   186   | has_tfree_syntactic_sort _ = false
   187 (* term -> bool *)
   188 val has_syntactic_sorts = exists_type (exists_subtype has_tfree_syntactic_sort)
   189 
   190 (* (unit -> string) -> Pretty.T *)
   191 fun plazy f = Pretty.blk (0, pstrs (f ()))
   192 
   193 (* Time.time -> Proof.state -> params -> bool -> int -> int -> int
   194    -> (term * term) list -> term list -> term -> string * Proof.state *)
   195 fun pick_them_nits_in_term deadline state (params : params) auto i n step
   196                            subst orig_assm_ts orig_t =
   197   let
   198     val timer = Timer.startRealTimer ()
   199     val thy = Proof.theory_of state
   200     val ctxt = Proof.context_of state
   201 (* FIXME: reintroduce code before new release:
   202 
   203     val nitpick_thy = ThyInfo.get_theory "Nitpick"
   204     val _ = Theory.subthy (nitpick_thy, thy) orelse
   205             error "You must import the theory \"Nitpick\" to use Nitpick"
   206 *)
   207     val {cards_assigns, maxes_assigns, iters_assigns, bitss, bisim_depths,
   208          boxes, finitizes, monos, stds, wfs, sat_solver, falsify, debug,
   209          verbose, overlord, user_axioms, assms, merge_type_vars, binary_ints,
   210          destroy_constrs, specialize, skolemize, star_linear_preds, uncurry,
   211          fast_descrs, peephole_optim, tac_timeout, sym_break, sharing_depth,
   212          flatten_props, max_threads, show_skolems, show_datatypes, show_consts,
   213          evals, formats, max_potential, max_genuine, check_potential,
   214          check_genuine, batch_size, ...} =
   215       params
   216     val state_ref = Unsynchronized.ref state
   217     (* Pretty.T -> unit *)
   218     val pprint =
   219       if auto then
   220         Unsynchronized.change state_ref o Proof.goal_message o K
   221         o Pretty.chunks o cons (Pretty.str "") o single
   222         o Pretty.mark Markup.hilite
   223       else
   224         priority o Pretty.string_of
   225     (* (unit -> Pretty.T) -> unit *)
   226     fun pprint_m f = () |> not auto ? pprint o f
   227     fun pprint_v f = () |> verbose ? pprint o f
   228     fun pprint_d f = () |> debug ? pprint o f
   229     (* string -> unit *)
   230     val print = pprint o curry Pretty.blk 0 o pstrs
   231     (* (unit -> string) -> unit *)
   232     val print_m = pprint_m o K o plazy
   233     val print_v = pprint_v o K o plazy
   234 
   235     (* unit -> unit *)
   236     fun check_deadline () =
   237       if debug andalso passed_deadline deadline then raise TimeLimit.TimeOut
   238       else ()
   239     (* unit -> 'a *)
   240     fun do_interrupted () =
   241       if passed_deadline deadline then raise TimeLimit.TimeOut
   242       else raise Interrupt
   243 
   244     val orig_assm_ts = if assms orelse auto then orig_assm_ts else []
   245     val _ =
   246       if step = 0 then
   247         print_m (fn () => "Nitpicking formula...")
   248       else
   249         pprint_m (fn () => Pretty.chunks (
   250             pretties_for_formulas ctxt ("Nitpicking " ^
   251                 (if i <> 1 orelse n <> 1 then
   252                    "subgoal " ^ string_of_int i ^ " of " ^ string_of_int n
   253                  else
   254                    "goal")) [Logic.list_implies (orig_assm_ts, orig_t)]))
   255     val neg_t = if falsify then Logic.mk_implies (orig_t, @{prop False})
   256                 else orig_t
   257     val assms_t = Logic.mk_conjunction_list (neg_t :: orig_assm_ts)
   258     val (assms_t, evals) =
   259       assms_t :: evals |> merge_type_vars ? merge_type_vars_in_terms
   260                        |> pairf hd tl
   261     val original_max_potential = max_potential
   262     val original_max_genuine = max_genuine
   263 (*
   264     val _ = priority ("*** " ^ Syntax.string_of_term ctxt orig_t)
   265     val _ = List.app (fn t => priority ("*** " ^ Syntax.string_of_term ctxt t))
   266                      orig_assm_ts
   267 *)
   268     val max_bisim_depth = fold Integer.max bisim_depths ~1
   269     val case_names = case_const_names thy stds
   270     val (defs, built_in_nondefs, user_nondefs) = all_axioms_of thy subst
   271     val def_table = const_def_table ctxt subst defs
   272     val nondef_table = const_nondef_table (built_in_nondefs @ user_nondefs)
   273     val simp_table = Unsynchronized.ref (const_simp_table ctxt subst)
   274     val psimp_table = const_psimp_table ctxt subst
   275     val intro_table = inductive_intro_table ctxt subst def_table
   276     val ground_thm_table = ground_theorem_table thy
   277     val ersatz_table = ersatz_table thy
   278     val (hol_ctxt as {wf_cache, ...}) =
   279       {thy = thy, ctxt = ctxt, max_bisim_depth = max_bisim_depth, boxes = boxes,
   280        stds = stds, wfs = wfs, user_axioms = user_axioms, debug = debug,
   281        binary_ints = binary_ints, destroy_constrs = destroy_constrs,
   282        specialize = specialize, skolemize = skolemize,
   283        star_linear_preds = star_linear_preds, uncurry = uncurry,
   284        fast_descrs = fast_descrs, tac_timeout = tac_timeout, evals = evals,
   285        case_names = case_names, def_table = def_table,
   286        nondef_table = nondef_table, user_nondefs = user_nondefs,
   287        simp_table = simp_table, psimp_table = psimp_table,
   288        intro_table = intro_table, ground_thm_table = ground_thm_table,
   289        ersatz_table = ersatz_table, skolems = Unsynchronized.ref [],
   290        special_funs = Unsynchronized.ref [],
   291        unrolled_preds = Unsynchronized.ref [], wf_cache = Unsynchronized.ref [],
   292        constr_cache = Unsynchronized.ref []}
   293     val frees = Term.add_frees assms_t []
   294     val _ = null (Term.add_tvars assms_t []) orelse
   295             raise NOT_SUPPORTED "schematic type variables"
   296     val (nondef_ts, def_ts, got_all_mono_user_axioms, no_poly_user_axioms,
   297          binarize) = preprocess_term hol_ctxt finitizes monos assms_t
   298     val got_all_user_axioms =
   299       got_all_mono_user_axioms andalso no_poly_user_axioms
   300 
   301     (* styp * (bool * bool) -> unit *)
   302     fun print_wf (x, (gfp, wf)) =
   303       pprint (Pretty.blk (0,
   304           pstrs ("The " ^ (if gfp then "co" else "") ^ "inductive predicate \"")
   305           @ Syntax.pretty_term ctxt (Const x) ::
   306           pstrs (if wf then
   307                    "\" was proved well-founded. Nitpick can compute it \
   308                    \efficiently."
   309                  else
   310                    "\" could not be proved well-founded. Nitpick might need to \
   311                    \unroll it.")))
   312     val _ = if verbose then List.app print_wf (!wf_cache) else ()
   313     val _ =
   314       pprint_d (fn () => Pretty.chunks
   315           (pretties_for_formulas ctxt "Preprocessed formula" [hd nondef_ts] @
   316            pretties_for_formulas ctxt "Relevant definitional axiom" def_ts @
   317            pretties_for_formulas ctxt "Relevant nondefinitional axiom"
   318                                  (tl nondef_ts)))
   319     val _ = List.app (ignore o Term.type_of) (nondef_ts @ def_ts)
   320             handle TYPE (_, Ts, ts) =>
   321                    raise TYPE ("Nitpick.pick_them_nits_in_term", Ts, ts)
   322 
   323     val nondef_us = map (nut_from_term hol_ctxt Eq) nondef_ts
   324     val def_us = map (nut_from_term hol_ctxt DefEq) def_ts
   325     val (free_names, const_names) =
   326       fold add_free_and_const_names (nondef_us @ def_us) ([], [])
   327     val (sel_names, nonsel_names) =
   328       List.partition (is_sel o nickname_of) const_names
   329     val sound_finitizes =
   330       none_true (filter_out (fn (SOME (Type (@{type_name fun}, _)), _) => true
   331                           | _ => false) finitizes)
   332     val standard = forall snd stds
   333 (*
   334     val _ = List.app (priority o string_for_nut ctxt) (nondef_us @ def_us)
   335 *)
   336 
   337     val unique_scope = forall (curry (op =) 1 o length o snd) cards_assigns
   338     (* typ list -> string -> string *)
   339     fun monotonicity_message Ts extra =
   340       let val ss = map (quote o string_for_type ctxt) Ts in
   341         "The type" ^ plural_s_for_list ss ^ " " ^
   342         space_implode " " (serial_commas "and" ss) ^ " " ^
   343         (if none_true monos then
   344            "passed the monotonicity test"
   345          else
   346            (if length ss = 1 then "is" else "are") ^ " considered monotonic") ^
   347         ". " ^ extra
   348       end
   349     (* typ -> bool *)
   350     fun is_type_fundamentally_monotonic T =
   351       (is_datatype thy stds T andalso not (is_quot_type thy T) andalso
   352        (not (is_pure_typedef thy T) orelse is_univ_typedef thy T)) orelse
   353       is_number_type thy T orelse is_bit_type T
   354     fun is_type_actually_monotonic T =
   355       formulas_monotonic hol_ctxt binarize T (nondef_ts, def_ts)
   356     fun is_type_kind_of_monotonic T =
   357       case triple_lookup (type_match thy) monos T of
   358         SOME (SOME false) => false
   359       | _ => is_type_actually_monotonic T
   360     fun is_type_monotonic T =
   361       unique_scope orelse
   362       case triple_lookup (type_match thy) monos T of
   363         SOME (SOME b) => b
   364       | _ => is_type_fundamentally_monotonic T orelse
   365              is_type_actually_monotonic T
   366     fun is_shallow_datatype_finitizable (T as Type (@{type_name fin_fun}, _)) =
   367         is_type_kind_of_monotonic T
   368       | is_shallow_datatype_finitizable (T as Type (@{type_name fun_box}, _)) =
   369         is_type_kind_of_monotonic T
   370       | is_shallow_datatype_finitizable T =
   371         case triple_lookup (type_match thy) finitizes T of
   372           SOME (SOME b) => b
   373         | _ => is_type_kind_of_monotonic T
   374     fun is_datatype_deep T =
   375       not standard orelse T = nat_T orelse is_word_type T orelse
   376       exists (curry (op =) T o domain_type o type_of) sel_names
   377     val all_Ts = ground_types_in_terms hol_ctxt binarize (nondef_ts @ def_ts)
   378                  |> sort Term_Ord.typ_ord
   379     val _ = if verbose andalso binary_ints = SOME true andalso
   380                exists (member (op =) [nat_T, int_T]) all_Ts then
   381               print_v (K "The option \"binary_ints\" will be ignored because \
   382                          \of the presence of rationals, reals, \"Suc\", \
   383                          \\"gcd\", or \"lcm\" in the problem or because of the \
   384                          \\"non_std\" option.")
   385             else
   386               ()
   387     val (mono_Ts, nonmono_Ts) = List.partition is_type_monotonic all_Ts
   388     val _ =
   389       if verbose andalso not unique_scope then
   390         case filter_out is_type_fundamentally_monotonic mono_Ts of
   391           [] => ()
   392         | interesting_mono_Ts =>
   393           print_v (K (monotonicity_message interesting_mono_Ts
   394                          "Nitpick might be able to skip some scopes."))
   395       else
   396         ()
   397     val (deep_dataTs, shallow_dataTs) =
   398       all_Ts |> filter (is_datatype thy stds) |> List.partition is_datatype_deep
   399     val finitizable_dataTs =
   400       shallow_dataTs |> filter_out (is_finite_type hol_ctxt)
   401                      |> filter is_shallow_datatype_finitizable
   402     val _ =
   403       if verbose andalso not (null finitizable_dataTs) then
   404         print_v (K (monotonicity_message finitizable_dataTs
   405                         "Nitpick can use a more precise finite encoding."))
   406       else
   407         ()
   408     (* This detection code is an ugly hack. Fortunately, it is used only to
   409        provide a hint to the user. *)
   410     (* string * (Rule_Cases.T * bool) -> bool *)
   411     fun is_struct_induct_step (name, (Rule_Cases.Case {fixes, assumes, ...}, _)) =
   412       not (null fixes) andalso
   413       exists (String.isSuffix ".hyps" o fst) assumes andalso
   414       exists (exists (curry (op =) name o shortest_name o fst)
   415               o datatype_constrs hol_ctxt) deep_dataTs
   416     val likely_in_struct_induct_step =
   417       exists is_struct_induct_step (ProofContext.cases_of ctxt)
   418     val _ = if standard andalso likely_in_struct_induct_step then
   419               pprint_m (fn () => Pretty.blk (0,
   420                   pstrs "Hint: To check that the induction hypothesis is \
   421                         \general enough, try this command: " @
   422                   [Pretty.mark Markup.sendback (Pretty.blk (0,
   423                        pstrs ("nitpick [non_std, show_all]")))] @ pstrs "."))
   424             else
   425               ()
   426 (*
   427     val _ = priority "Monotonic types:"
   428     val _ = List.app (priority o string_for_type ctxt) mono_Ts
   429     val _ = priority "Nonmonotonic types:"
   430     val _ = List.app (priority o string_for_type ctxt) nonmono_Ts
   431 *)
   432 
   433     val need_incremental = Int.max (max_potential, max_genuine) >= 2
   434     val effective_sat_solver =
   435       if sat_solver <> "smart" then
   436         if need_incremental andalso
   437            not (member (op =) (Kodkod_SAT.configured_sat_solvers true)
   438                        sat_solver) then
   439           (print_m (K ("An incremental SAT solver is required: \"SAT4J\" will \
   440                        \be used instead of " ^ quote sat_solver ^ "."));
   441            "SAT4J")
   442         else
   443           sat_solver
   444       else
   445         Kodkod_SAT.smart_sat_solver_name need_incremental
   446     val _ =
   447       if sat_solver = "smart" then
   448         print_v (fn () => "Using SAT solver " ^ quote effective_sat_solver ^
   449                           ". The following" ^
   450                           (if need_incremental then " incremental " else " ") ^
   451                           "solvers are configured: " ^
   452                           commas (map quote (Kodkod_SAT.configured_sat_solvers
   453                                                        need_incremental)) ^ ".")
   454       else
   455         ()
   456 
   457     val too_big_scopes = Unsynchronized.ref []
   458 
   459     (* bool -> scope -> rich_problem option *)
   460     fun problem_for_scope unsound
   461             (scope as {card_assigns, bits, bisim_depth, datatypes, ofs, ...}) =
   462       let
   463         val _ = not (exists (fn other => scope_less_eq other scope)
   464                             (!too_big_scopes)) orelse
   465                 raise TOO_LARGE ("Nitpick.pick_them_nits_in_term.\
   466                                  \problem_for_scope", "too large scope")
   467 (*
   468         val _ = priority "Offsets:"
   469         val _ = List.app (fn (T, j0) =>
   470                              priority (string_for_type ctxt T ^ " = " ^
   471                                        string_of_int j0))
   472                          (Typtab.dest ofs)
   473 *)
   474         val all_exact = forall (is_exact_type datatypes true) all_Ts
   475         (* nut list -> rep NameTable.table -> nut list * rep NameTable.table *)
   476         val repify_consts = choose_reps_for_consts scope all_exact
   477         val main_j0 = offset_of_type ofs bool_T
   478         val (nat_card, nat_j0) = spec_of_type scope nat_T
   479         val (int_card, int_j0) = spec_of_type scope int_T
   480         val _ = (nat_j0 = main_j0 andalso int_j0 = main_j0) orelse
   481                 raise BAD ("Nitpick.pick_them_nits_in_term.problem_for_scope",
   482                            "bad offsets")
   483         val kk = kodkod_constrs peephole_optim nat_card int_card main_j0
   484         val (free_names, rep_table) =
   485           choose_reps_for_free_vars scope free_names NameTable.empty
   486         val (sel_names, rep_table) = choose_reps_for_all_sels scope rep_table
   487         val (nonsel_names, rep_table) = repify_consts nonsel_names rep_table
   488         val min_highest_arity =
   489           NameTable.fold (curry Int.max o arity_of_rep o snd) rep_table 1
   490         val min_univ_card =
   491           NameTable.fold (curry Int.max o min_univ_card_of_rep o snd) rep_table
   492                          (univ_card nat_card int_card main_j0 [] KK.True)
   493         val _ = check_arity min_univ_card min_highest_arity
   494 
   495         val def_us = map (choose_reps_in_nut scope unsound rep_table true)
   496                          def_us
   497         val nondef_us = map (choose_reps_in_nut scope unsound rep_table false)
   498                             nondef_us
   499 (*
   500         val _ = List.app (priority o string_for_nut ctxt)
   501                          (free_names @ sel_names @ nonsel_names @
   502                           nondef_us @ def_us)
   503 *)
   504         val (free_rels, pool, rel_table) =
   505           rename_free_vars free_names initial_pool NameTable.empty
   506         val (sel_rels, pool, rel_table) =
   507           rename_free_vars sel_names pool rel_table
   508         val (other_rels, pool, rel_table) =
   509           rename_free_vars nonsel_names pool rel_table
   510         val nondef_us = map (rename_vars_in_nut pool rel_table) nondef_us
   511         val def_us = map (rename_vars_in_nut pool rel_table) def_us
   512         val nondef_fs = map (kodkod_formula_from_nut ofs kk) nondef_us
   513         val def_fs = map (kodkod_formula_from_nut ofs kk) def_us
   514         val formula = fold (fold s_and) [def_fs, nondef_fs] KK.True
   515         val comment = (if unsound then "unsound" else "sound") ^ "\n" ^
   516                       PrintMode.setmp [] multiline_string_for_scope scope
   517         val kodkod_sat_solver =
   518           Kodkod_SAT.sat_solver_spec effective_sat_solver |> snd
   519         val bit_width = if bits = 0 then 16 else bits + 1
   520         val delay = if unsound then
   521                       Option.map (fn time => Time.- (time, Time.now ()))
   522                                  deadline
   523                       |> unsound_delay_for_timeout
   524                     else
   525                       0
   526         val settings = [("solver", commas (map quote kodkod_sat_solver)),
   527                         ("skolem_depth", "-1"),
   528                         ("bit_width", string_of_int bit_width),
   529                         ("symmetry_breaking", signed_string_of_int sym_break),
   530                         ("sharing", signed_string_of_int sharing_depth),
   531                         ("flatten", Bool.toString flatten_props),
   532                         ("delay", signed_string_of_int delay)]
   533         val plain_rels = free_rels @ other_rels
   534         val plain_bounds = map (bound_for_plain_rel ctxt debug) plain_rels
   535         val plain_axioms = map (declarative_axiom_for_plain_rel kk) plain_rels
   536         val sel_bounds = map (bound_for_sel_rel ctxt debug datatypes) sel_rels
   537         val dtype_axioms =
   538           declarative_axioms_for_datatypes hol_ctxt binarize bits ofs kk
   539                                            rel_table datatypes
   540         val declarative_axioms = plain_axioms @ dtype_axioms
   541         val univ_card = Int.max (univ_card nat_card int_card main_j0
   542                                      (plain_bounds @ sel_bounds) formula,
   543                                  main_j0 |> bits > 0 ? Integer.add (bits + 1))
   544         val built_in_bounds = bounds_for_built_in_rels_in_formula debug
   545                                   univ_card nat_card int_card main_j0 formula
   546         val bounds = built_in_bounds @ plain_bounds @ sel_bounds
   547                      |> not debug ? merge_bounds
   548         val highest_arity =
   549           fold Integer.max (map (fst o fst) (maps fst bounds)) 0
   550         val formula = fold_rev s_and declarative_axioms formula
   551         val _ = if bits = 0 then () else check_bits bits formula
   552         val _ = if formula = KK.False then ()
   553                 else check_arity univ_card highest_arity
   554       in
   555         SOME ({comment = comment, settings = settings, univ_card = univ_card,
   556                tuple_assigns = [], bounds = bounds,
   557                int_bounds = if bits = 0 then sequential_int_bounds univ_card
   558                             else pow_of_two_int_bounds bits main_j0,
   559                expr_assigns = [], formula = formula},
   560               {free_names = free_names, sel_names = sel_names,
   561                nonsel_names = nonsel_names, rel_table = rel_table,
   562                unsound = unsound, scope = scope})
   563       end
   564       handle TOO_LARGE (loc, msg) =>
   565              if loc = "Nitpick_Kodkod.check_arity" andalso
   566                 not (Typtab.is_empty ofs) then
   567                problem_for_scope unsound
   568                    {hol_ctxt = hol_ctxt, binarize = binarize,
   569                     card_assigns = card_assigns, bits = bits,
   570                     bisim_depth = bisim_depth, datatypes = datatypes,
   571                     ofs = Typtab.empty}
   572              else if loc = "Nitpick.pick_them_nits_in_term.\
   573                            \problem_for_scope" then
   574                NONE
   575              else
   576                (Unsynchronized.change too_big_scopes (cons scope);
   577                 print_v (fn () => ("Limit reached: " ^ msg ^
   578                                    ". Skipping " ^ (if unsound then "potential"
   579                                                     else "genuine") ^
   580                                    " component of scope."));
   581                 NONE)
   582            | TOO_SMALL (_, msg) =>
   583              (print_v (fn () => ("Limit reached: " ^ msg ^
   584                                  ". Skipping " ^ (if unsound then "potential"
   585                                                   else "genuine") ^
   586                                  " component of scope."));
   587               NONE)
   588 
   589     val das_wort_model =
   590       (if falsify then "counterexample" else "model")
   591       |> not standard ? prefix "nonstandard "
   592 
   593     val scopes = Unsynchronized.ref []
   594     val generated_scopes = Unsynchronized.ref []
   595     val generated_problems = Unsynchronized.ref ([] : rich_problem list)
   596     val checked_problems = Unsynchronized.ref (SOME [])
   597     val met_potential = Unsynchronized.ref 0
   598 
   599     (* rich_problem list -> int list -> unit *)
   600     fun update_checked_problems problems =
   601       List.app (Unsynchronized.change checked_problems o Option.map o cons
   602                 o nth problems)
   603     (* string -> unit *)
   604     fun show_kodkod_warning "" = ()
   605       | show_kodkod_warning s = print_m (fn () => "Kodkod warning: " ^ s ^ ".")
   606 
   607     (* bool -> KK.raw_bound list -> problem_extension -> bool * bool option *)
   608     fun print_and_check_model genuine bounds
   609             ({free_names, sel_names, nonsel_names, rel_table, scope, ...}
   610              : problem_extension) =
   611       let
   612         val (reconstructed_model, codatatypes_ok) =
   613           reconstruct_hol_model {show_skolems = show_skolems,
   614                                  show_datatypes = show_datatypes,
   615                                  show_consts = show_consts}
   616               scope formats frees free_names sel_names nonsel_names rel_table
   617               bounds
   618         val genuine_means_genuine =
   619           got_all_user_axioms andalso none_true wfs andalso
   620           sound_finitizes andalso codatatypes_ok
   621       in
   622         (pprint (Pretty.chunks
   623              [Pretty.blk (0,
   624                   (pstrs ("Nitpick found a" ^
   625                           (if not genuine then " potential "
   626                            else if genuine_means_genuine then " "
   627                            else " quasi genuine ") ^ das_wort_model) @
   628                    (case pretties_for_scope scope verbose of
   629                       [] => []
   630                     | pretties => pstrs " for " @ pretties) @
   631                    [Pretty.str ":\n"])),
   632               Pretty.indent indent_size reconstructed_model]);
   633          if genuine then
   634            (if check_genuine andalso standard then
   635               case prove_hol_model scope tac_timeout free_names sel_names
   636                                    rel_table bounds assms_t of
   637                 SOME true =>
   638                 print ("Confirmation by \"auto\": The above " ^
   639                        das_wort_model ^ " is really genuine.")
   640               | SOME false =>
   641                 if genuine_means_genuine then
   642                   error ("A supposedly genuine " ^ das_wort_model ^ " was \
   643                          \shown to be spurious by \"auto\".\nThis should never \
   644                          \happen.\nPlease send a bug report to blanchet\
   645                          \te@in.tum.de.")
   646                  else
   647                    print ("Refutation by \"auto\": The above " ^
   648                           das_wort_model ^ " is spurious.")
   649                | NONE => print "No confirmation by \"auto\"."
   650             else
   651               ();
   652             if not standard andalso likely_in_struct_induct_step then
   653               print "The existence of a nonstandard model suggests that the \
   654                     \induction hypothesis is not general enough or perhaps \
   655                     \even wrong. See the \"Inductive Properties\" section of \
   656                     \the Nitpick manual for details (\"isabelle doc nitpick\")."
   657             else
   658               ();
   659             if has_syntactic_sorts orig_t then
   660               print "Hint: Maybe you forgot a type constraint?"
   661             else
   662               ();
   663             if not genuine_means_genuine then
   664               if no_poly_user_axioms then
   665                 let
   666                   val options =
   667                     [] |> not got_all_mono_user_axioms
   668                           ? cons ("user_axioms", "\"true\"")
   669                        |> not (none_true wfs)
   670                           ? cons ("wf", "\"smart\" or \"false\"")
   671                        |> not sound_finitizes
   672                           ? cons ("finitize", "\"smart\" or \"false\"")
   673                        |> not codatatypes_ok
   674                           ? cons ("bisim_depth", "a nonnegative value")
   675                   val ss =
   676                     map (fn (name, value) => quote name ^ " set to " ^ value)
   677                         options
   678                 in
   679                   print ("Try again with " ^
   680                          space_implode " " (serial_commas "and" ss) ^
   681                          " to confirm that the " ^ das_wort_model ^
   682                          " is genuine.")
   683                 end
   684               else
   685                 print ("Nitpick is unable to guarantee the authenticity of \
   686                        \the " ^ das_wort_model ^ " in the presence of \
   687                        \polymorphic axioms.")
   688             else
   689               ();
   690             NONE)
   691          else
   692            if not genuine then
   693              (Unsynchronized.inc met_potential;
   694               if check_potential then
   695                 let
   696                   val status = prove_hol_model scope tac_timeout free_names
   697                                               sel_names rel_table bounds assms_t
   698                 in
   699                   (case status of
   700                      SOME true => print ("Confirmation by \"auto\": The \
   701                                          \above " ^ das_wort_model ^
   702                                          " is genuine.")
   703                    | SOME false => print ("Refutation by \"auto\": The above " ^
   704                                           das_wort_model ^ " is spurious.")
   705                    | NONE => print "No confirmation by \"auto\".");
   706                   status
   707                 end
   708               else
   709                 NONE)
   710            else
   711              NONE)
   712         |> pair genuine_means_genuine
   713       end
   714     (* bool * int * int * int -> bool -> rich_problem list
   715        -> bool * int * int * int *)
   716     fun solve_any_problem (found_really_genuine, max_potential, max_genuine,
   717                            donno) first_time problems =
   718       let
   719         val max_potential = Int.max (0, max_potential)
   720         val max_genuine = Int.max (0, max_genuine)
   721         (* bool -> int * KK.raw_bound list -> bool * bool option *)
   722         fun print_and_check genuine (j, bounds) =
   723           print_and_check_model genuine bounds (snd (nth problems j))
   724         val max_solutions = max_potential + max_genuine
   725                             |> not need_incremental ? curry Int.min 1
   726       in
   727         if max_solutions <= 0 then
   728           (found_really_genuine, 0, 0, donno)
   729         else
   730           case KK.solve_any_problem overlord deadline max_threads max_solutions
   731                                     (map fst problems) of
   732             KK.JavaNotInstalled =>
   733             (print_m install_java_message;
   734              (found_really_genuine, max_potential, max_genuine, donno + 1))
   735           | KK.KodkodiNotInstalled =>
   736             (print_m install_kodkodi_message;
   737              (found_really_genuine, max_potential, max_genuine, donno + 1))
   738           | KK.Normal ([], unsat_js, s) =>
   739             (update_checked_problems problems unsat_js; show_kodkod_warning s;
   740              (found_really_genuine, max_potential, max_genuine, donno))
   741           | KK.Normal (sat_ps, unsat_js, s) =>
   742             let
   743               val (lib_ps, con_ps) =
   744                 List.partition (#unsound o snd o nth problems o fst) sat_ps
   745             in
   746               update_checked_problems problems (unsat_js @ map fst lib_ps);
   747               show_kodkod_warning s;
   748               if null con_ps then
   749                 let
   750                   val genuine_codes =
   751                     lib_ps |> take max_potential
   752                            |> map (print_and_check false)
   753                            |> filter (curry (op =) (SOME true) o snd)
   754                   val found_really_genuine =
   755                     found_really_genuine orelse exists fst genuine_codes
   756                   val num_genuine = length genuine_codes
   757                   val max_genuine = max_genuine - num_genuine
   758                   val max_potential = max_potential
   759                                       - (length lib_ps - num_genuine)
   760                 in
   761                   if max_genuine <= 0 then
   762                     (found_really_genuine, 0, 0, donno)
   763                   else
   764                     let
   765                       (* "co_js" is the list of sound problems whose unsound
   766                          pendants couldn't be satisfied and hence that most
   767                          probably can't be satisfied themselves. *)
   768                       val co_js =
   769                         map (fn j => j - 1) unsat_js
   770                         |> filter (fn j =>
   771                                       j >= 0 andalso
   772                                       scopes_equivalent
   773                                           (#scope (snd (nth problems j)))
   774                                           (#scope (snd (nth problems (j + 1)))))
   775                       val bye_js = sort_distinct int_ord (map fst sat_ps @
   776                                                           unsat_js @ co_js)
   777                       val problems =
   778                         problems |> filter_out_indices bye_js
   779                                  |> max_potential <= 0
   780                                     ? filter_out (#unsound o snd)
   781                     in
   782                       solve_any_problem (found_really_genuine, max_potential,
   783                                          max_genuine, donno) false problems
   784                     end
   785                 end
   786               else
   787                 let
   788                   val genuine_codes =
   789                     con_ps |> take max_genuine
   790                            |> map (print_and_check true)
   791                   val max_genuine = max_genuine - length genuine_codes
   792                   val found_really_genuine =
   793                     found_really_genuine orelse exists fst genuine_codes
   794                 in
   795                   if max_genuine <= 0 orelse not first_time then
   796                     (found_really_genuine, 0, max_genuine, donno)
   797                   else
   798                     let
   799                       val bye_js = sort_distinct int_ord
   800                                                  (map fst sat_ps @ unsat_js)
   801                       val problems =
   802                         problems |> filter_out_indices bye_js
   803                                  |> filter_out (#unsound o snd)
   804                     in
   805                       solve_any_problem (found_really_genuine, 0, max_genuine,
   806                                          donno) false problems
   807                     end
   808                 end
   809             end
   810           | KK.TimedOut unsat_js =>
   811             (update_checked_problems problems unsat_js; raise TimeLimit.TimeOut)
   812           | KK.Interrupted NONE => (checked_problems := NONE; do_interrupted ())
   813           | KK.Interrupted (SOME unsat_js) =>
   814             (update_checked_problems problems unsat_js; do_interrupted ())
   815           | KK.Error (s, unsat_js) =>
   816             (update_checked_problems problems unsat_js;
   817              print_v (K ("Kodkod error: " ^ s ^ "."));
   818              (found_really_genuine, max_potential, max_genuine, donno + 1))
   819       end
   820 
   821     (* int -> int -> scope list -> bool * int * int * int
   822        -> bool * int * int * int *)
   823     fun run_batch j n scopes (found_really_genuine, max_potential, max_genuine,
   824                               donno) =
   825       let
   826         val _ =
   827           if null scopes then
   828             print_m (K "The scope specification is inconsistent.")
   829           else if verbose then
   830             pprint (Pretty.chunks
   831                 [Pretty.blk (0,
   832                      pstrs ((if n > 1 then
   833                                "Batch " ^ string_of_int (j + 1) ^ " of " ^
   834                                signed_string_of_int n ^ ": "
   835                              else
   836                                "") ^
   837                             "Trying " ^ string_of_int (length scopes) ^
   838                             " scope" ^ plural_s_for_list scopes ^ ":")),
   839                  Pretty.indent indent_size
   840                      (Pretty.chunks (map2
   841                           (fn j => fn scope =>
   842                               Pretty.block (
   843                                   (case pretties_for_scope scope true of
   844                                      [] => [Pretty.str "Empty"]
   845                                    | pretties => pretties) @
   846                                   [Pretty.str (if j = 1 then "." else ";")]))
   847                           (length scopes downto 1) scopes))])
   848           else
   849             ()
   850         (* scope * bool -> rich_problem list * bool
   851            -> rich_problem list * bool *)
   852         fun add_problem_for_scope (scope, unsound) (problems, donno) =
   853           (check_deadline ();
   854            case problem_for_scope unsound scope of
   855              SOME problem =>
   856              (problems
   857               |> (null problems orelse
   858                   not (KK.problems_equivalent (fst problem)
   859                                               (fst (hd problems))))
   860                   ? cons problem, donno)
   861            | NONE => (problems, donno + 1))
   862         val (problems, donno) =
   863           fold add_problem_for_scope
   864                (map_product pair scopes
   865                     ((if max_genuine > 0 then [false] else []) @
   866                      (if max_potential > 0 then [true] else [])))
   867                ([], donno)
   868         val _ = Unsynchronized.change generated_problems (append problems)
   869         val _ = Unsynchronized.change generated_scopes (append scopes)
   870         val _ =
   871           if j + 1 = n then
   872             let
   873               val (unsound_problems, sound_problems) =
   874                 List.partition (#unsound o snd) (!generated_problems)
   875             in
   876               if not (null sound_problems) andalso
   877                  forall (KK.is_problem_trivially_false o fst)
   878                         sound_problems then
   879                 print_m (fn () =>
   880                     "Warning: The conjecture either trivially holds for the \
   881                     \given scopes or lies outside Nitpick's supported \
   882                     \fragment." ^
   883                     (if exists (not o KK.is_problem_trivially_false o fst)
   884                                unsound_problems then
   885                        " Only potential counterexamples may be found."
   886                      else
   887                        ""))
   888               else
   889                 ()
   890             end
   891           else
   892             ()
   893       in
   894         solve_any_problem (found_really_genuine, max_potential, max_genuine,
   895                            donno) true (rev problems)
   896       end
   897 
   898     (* rich_problem list -> scope -> int *)
   899     fun scope_count (problems : rich_problem list) scope =
   900       length (filter (scopes_equivalent scope o #scope o snd) problems)
   901     (* string -> string *)
   902     fun excipit did_so_and_so =
   903       let
   904         (* rich_problem list -> rich_problem list *)
   905         val do_filter =
   906           if !met_potential = max_potential then filter_out (#unsound o snd)
   907           else I
   908         val total = length (!scopes)
   909         val unsat =
   910           fold (fn scope =>
   911                    case scope_count (do_filter (!generated_problems)) scope of
   912                      0 => I
   913                    | n =>
   914                      scope_count (do_filter (these (!checked_problems)))
   915                                  scope = n
   916                      ? Integer.add 1) (!generated_scopes) 0
   917       in
   918         "Nitpick " ^ did_so_and_so ^
   919         (if is_some (!checked_problems) andalso total > 0 then
   920            " " ^ string_of_int (Int.min (total - 1, unsat)) ^ " of " ^
   921            string_of_int total ^ " scope" ^ plural_s total
   922          else
   923            "") ^ "."
   924       end
   925 
   926     (* int -> int -> scope list -> bool * int * int * int -> KK.outcome *)
   927     fun run_batches _ _ []
   928                     (found_really_genuine, max_potential, max_genuine, donno) =
   929         if donno > 0 andalso max_genuine > 0 then
   930           (print_m (fn () => excipit "checked"); "unknown")
   931         else if max_genuine = original_max_genuine then
   932           if max_potential = original_max_potential then
   933             (print_m (fn () =>
   934                  "Nitpick found no " ^ das_wort_model ^ "." ^
   935                  (if not standard andalso likely_in_struct_induct_step then
   936                     " This suggests that the induction hypothesis might be \
   937                     \general enough to prove this subgoal."
   938                   else
   939                     "")); "none")
   940           else
   941             (print_m (fn () =>
   942                  "Nitpick could not find a" ^
   943                  (if max_genuine = 1 then " better " ^ das_wort_model ^ "."
   944                   else "ny better " ^ das_wort_model ^ "s.")); "potential")
   945         else if found_really_genuine then
   946           "genuine"
   947         else
   948           "quasi_genuine"
   949       | run_batches j n (batch :: batches) z =
   950         let val (z as (_, _, max_genuine, _)) = run_batch j n batch z in
   951           run_batches (j + 1) n (if max_genuine > 0 then batches else []) z
   952         end
   953 
   954     val (skipped, the_scopes) =
   955       all_scopes hol_ctxt binarize sym_break cards_assigns maxes_assigns
   956                  iters_assigns bitss bisim_depths mono_Ts nonmono_Ts deep_dataTs
   957                  finitizable_dataTs
   958     val _ = if skipped > 0 then
   959               print_m (fn () => "Too many scopes. Skipping " ^
   960                                 string_of_int skipped ^ " scope" ^
   961                                 plural_s skipped ^
   962                                 ". (Consider using \"mono\" or \
   963                                 \\"merge_type_vars\" to prevent this.)")
   964             else
   965               ()
   966     val _ = scopes := the_scopes
   967 
   968     val batches = batch_list batch_size (!scopes)
   969     val outcome_code =
   970       (run_batches 0 (length batches) batches
   971                    (false, max_potential, max_genuine, 0)
   972        handle Exn.Interrupt => do_interrupted ())
   973       handle TimeLimit.TimeOut =>
   974              (print_m (fn () => excipit "ran out of time after checking");
   975               if !met_potential > 0 then "potential" else "unknown")
   976            | Exn.Interrupt =>
   977              if auto orelse debug then raise Interrupt
   978              else error (excipit "was interrupted after checking")
   979     val _ = print_v (fn () => "Total time: " ^
   980                               signed_string_of_int (Time.toMilliseconds
   981                                     (Timer.checkRealTimer timer)) ^ " ms.")
   982   in (outcome_code, !state_ref) end
   983   handle Exn.Interrupt =>
   984          if auto orelse #debug params then
   985            raise Interrupt
   986          else
   987            if passed_deadline deadline then
   988              (priority "Nitpick ran out of time."; ("unknown", state))
   989            else
   990              error "Nitpick was interrupted."
   991 
   992 (* Proof.state -> params -> bool -> int -> int -> int -> (term * term) list
   993    -> term list -> term -> string * Proof.state *)
   994 fun pick_nits_in_term state (params as {debug, timeout, expect, ...}) auto i n
   995                       step subst orig_assm_ts orig_t =
   996   if getenv "KODKODI" = "" then
   997     (if auto then ()
   998      else warning (Pretty.string_of (plazy install_kodkodi_message));
   999      ("unknown", state))
  1000   else
  1001     let
  1002       val deadline = Option.map (curry Time.+ (Time.now ())) timeout
  1003       val outcome as (outcome_code, _) =
  1004         time_limit (if debug then NONE else timeout)
  1005             (pick_them_nits_in_term deadline state params auto i n step subst
  1006                                     orig_assm_ts) orig_t
  1007     in
  1008       if expect = "" orelse outcome_code = expect then outcome
  1009       else error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
  1010     end
  1011 
  1012 (* string list -> term -> bool *)
  1013 fun is_fixed_equation fixes
  1014                       (Const (@{const_name "=="}, _) $ Free (s, _) $ Const _) =
  1015     member (op =) fixes s
  1016   | is_fixed_equation _ _ = false
  1017 (* Proof.context -> term list * term -> (term * term) list * term list * term *)
  1018 fun extract_fixed_frees ctxt (assms, t) =
  1019   let
  1020     val fixes = Variable.fixes_of ctxt |> map snd
  1021     val (subst, other_assms) =
  1022       List.partition (is_fixed_equation fixes) assms
  1023       |>> map Logic.dest_equals
  1024   in (subst, other_assms, subst_atomic subst t) end
  1025 
  1026 (* Proof.state -> params -> bool -> int -> int -> string * Proof.state *)
  1027 fun pick_nits_in_subgoal state params auto i step =
  1028   let
  1029     val ctxt = Proof.context_of state
  1030     val t = state |> Proof.raw_goal |> #goal |> prop_of
  1031   in
  1032     case Logic.count_prems t of
  1033       0 => (priority "No subgoal!"; ("none", state))
  1034     | n =>
  1035       let
  1036         val (t, frees) = Logic.goal_params t i
  1037         val t = subst_bounds (frees, t)
  1038         val assms = map term_of (Assumption.all_assms_of ctxt)
  1039         val (subst, assms, t) = extract_fixed_frees ctxt (assms, t)
  1040       in pick_nits_in_term state params auto i n step subst assms t end
  1041   end
  1042 
  1043 end;