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