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