src/HOL/Tools/Nitpick/nitpick.ML
author blanchet
Tue, 08 Dec 2009 18:38:08 +0100
changeset 34039 1fba360b5443
parent 34038 a2736debeabd
child 34118 5e831d805118
permissions -rw-r--r--
made Nitpick work also for people who import "Plain" instead of "Main"
     1 (*  Title:      HOL/Tools/Nitpick/nitpick.ML
     2     Author:     Jasmin Blanchette, TU Muenchen
     3     Copyright   2008, 2009
     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     bisim_depths: int list,
    16     boxes: (typ option * bool option) list,
    17     monos: (typ option * bool option) list,
    18     wfs: (styp option * bool option) list,
    19     sat_solver: string,
    20     blocking: bool,
    21     falsify: bool,
    22     debug: bool,
    23     verbose: bool,
    24     overlord: bool,
    25     user_axioms: bool option,
    26     assms: bool,
    27     merge_type_vars: bool,
    28     destroy_constrs: bool,
    29     specialize: bool,
    30     skolemize: bool,
    31     star_linear_preds: bool,
    32     uncurry: bool,
    33     fast_descrs: bool,
    34     peephole_optim: bool,
    35     timeout: Time.time option,
    36     tac_timeout: Time.time option,
    37     sym_break: int,
    38     sharing_depth: int,
    39     flatten_props: bool,
    40     max_threads: int,
    41     show_skolems: bool,
    42     show_datatypes: bool,
    43     show_consts: bool,
    44     evals: term list,
    45     formats: (term option * int list) list,
    46     max_potential: int,
    47     max_genuine: int,
    48     check_potential: bool,
    49     check_genuine: bool,
    50     batch_size: int,
    51     expect: string}
    52 
    53   val register_frac_type : string -> (string * string) list -> theory -> theory
    54   val unregister_frac_type : string -> theory -> theory
    55   val register_codatatype : typ -> string -> styp list -> theory -> theory
    56   val unregister_codatatype : typ -> theory -> theory
    57   val pick_nits_in_term :
    58     Proof.state -> params -> bool -> term list -> term -> string * Proof.state
    59   val pick_nits_in_subgoal :
    60     Proof.state -> params -> bool -> int -> string * Proof.state
    61 end;
    62 
    63 structure Nitpick : NITPICK =
    64 struct
    65 
    66 open Nitpick_Util
    67 open Nitpick_HOL
    68 open Nitpick_Mono
    69 open Nitpick_Scope
    70 open Nitpick_Peephole
    71 open Nitpick_Rep
    72 open Nitpick_Nut
    73 open Nitpick_Kodkod
    74 open Nitpick_Model
    75 
    76 type params = {
    77   cards_assigns: (typ option * int list) list,
    78   maxes_assigns: (styp option * int list) list,
    79   iters_assigns: (styp option * int list) list,
    80   bisim_depths: int list,
    81   boxes: (typ option * bool option) list,
    82   monos: (typ option * bool option) list,
    83   wfs: (styp option * bool option) list,
    84   sat_solver: string,
    85   blocking: bool,
    86   falsify: bool,
    87   debug: bool,
    88   verbose: bool,
    89   overlord: bool,
    90   user_axioms: bool option,
    91   assms: bool,
    92   merge_type_vars: bool,
    93   destroy_constrs: bool,
    94   specialize: bool,
    95   skolemize: bool,
    96   star_linear_preds: bool,
    97   uncurry: bool,
    98   fast_descrs: bool,
    99   peephole_optim: bool,
   100   timeout: Time.time option,
   101   tac_timeout: Time.time option,
   102   sym_break: int,
   103   sharing_depth: int,
   104   flatten_props: bool,
   105   max_threads: int,
   106   show_skolems: bool,
   107   show_datatypes: bool,
   108   show_consts: bool,
   109   evals: term list,
   110   formats: (term option * int list) list,
   111   max_potential: int,
   112   max_genuine: int,
   113   check_potential: bool,
   114   check_genuine: bool,
   115   batch_size: int,
   116   expect: string}
   117 
   118 type problem_extension = {
   119   free_names: nut list,
   120   sel_names: nut list,
   121   nonsel_names: nut list,
   122   rel_table: nut NameTable.table,
   123   liberal: bool,
   124   scope: scope,
   125   core: Kodkod.formula,
   126   defs: Kodkod.formula list}
   127 
   128 type rich_problem = Kodkod.problem * problem_extension
   129 
   130 (* Proof.context -> string -> term list -> Pretty.T list *)
   131 fun pretties_for_formulas _ _ [] = []
   132   | pretties_for_formulas ctxt s ts =
   133     [Pretty.str (s ^ plural_s_for_list ts ^ ":"),
   134      Pretty.indent indent_size (Pretty.chunks
   135          (map2 (fn j => fn t =>
   136                    Pretty.block [t |> shorten_const_names_in_term
   137                                    |> Syntax.pretty_term ctxt,
   138                                  Pretty.str (if j = 1 then "." else ";")])
   139                (length ts downto 1) ts))]
   140 
   141 (* unit -> string *)
   142 fun install_kodkodi_message () =
   143   "Nitpick requires the external Java program Kodkodi. To install it, download \
   144   \the package from Isabelle's web page and add the \"kodkodi-x.y.z\" \
   145   \directory's full path to \"" ^
   146   Path.implode (Path.expand (Path.appends
   147       (Path.variable "ISABELLE_HOME_USER" ::
   148        map Path.basic ["etc", "components"]))) ^ "\"."
   149 
   150 val max_liberal_delay_ms = 200
   151 val max_liberal_delay_percent = 2
   152 
   153 (* Time.time option -> int *)
   154 fun liberal_delay_for_timeout NONE = max_liberal_delay_ms
   155   | liberal_delay_for_timeout (SOME timeout) =
   156     Int.max (0, Int.min (max_liberal_delay_ms,
   157                          Time.toMilliseconds timeout
   158                          * max_liberal_delay_percent div 100))
   159 
   160 (* Time.time option -> bool *)
   161 fun passed_deadline NONE = false
   162   | passed_deadline (SOME time) = Time.compare (Time.now (), time) <> LESS
   163 
   164 (* ('a * bool option) list -> bool *)
   165 fun none_true asgns = forall (not_equal (SOME true) o snd) asgns
   166 
   167 val syntactic_sorts =
   168   @{sort "{default,zero,one,plus,minus,uminus,times,inverse,abs,sgn,ord,eq}"} @
   169   @{sort number}
   170 (* typ -> bool *)
   171 fun has_tfree_syntactic_sort (TFree (_, S as _ :: _)) =
   172     subset (op =) (S, syntactic_sorts)
   173   | has_tfree_syntactic_sort _ = false
   174 (* term -> bool *)
   175 val has_syntactic_sorts = exists_type (exists_subtype has_tfree_syntactic_sort)
   176 
   177 (* (unit -> string) -> Pretty.T *)
   178 fun plazy f = Pretty.blk (0, pstrs (f ()))
   179 
   180 (* Time.time -> Proof.state -> params -> bool -> term -> string * Proof.state *)
   181 fun pick_them_nits_in_term deadline state (params : params) auto orig_assm_ts
   182                            orig_t =
   183   let
   184     val timer = Timer.startRealTimer ()
   185     val user_thy = Proof.theory_of state
   186     val nitpick_thy = ThyInfo.get_theory "Nitpick"
   187     val nitpick_thy_missing = not (Theory.subthy (nitpick_thy, user_thy))
   188     val thy = if nitpick_thy_missing then
   189                 Theory.begin_theory "Nitpick_Internal" [nitpick_thy, user_thy]
   190                 |> Theory.checkpoint
   191               else
   192                 user_thy
   193     val ctxt = Proof.context_of state
   194                |> nitpick_thy_missing ? Context.raw_transfer thy
   195     val {cards_assigns, maxes_assigns, iters_assigns, bisim_depths, boxes,
   196          monos, wfs, sat_solver, blocking, falsify, debug, verbose, overlord,
   197          user_axioms, assms, merge_type_vars, destroy_constrs, specialize,
   198          skolemize, star_linear_preds, uncurry, fast_descrs, peephole_optim,
   199          tac_timeout, sym_break, sharing_depth, flatten_props, max_threads,
   200          show_skolems, show_datatypes, show_consts, evals, formats,
   201          max_potential, max_genuine, check_potential, check_genuine, batch_size,
   202          ...} =
   203       params
   204     val state_ref = Unsynchronized.ref state
   205     (* Pretty.T -> unit *)
   206     val pprint =
   207       if auto then
   208         Unsynchronized.change state_ref o Proof.goal_message o K
   209         o Pretty.chunks o cons (Pretty.str "") o single
   210         o Pretty.mark Markup.hilite
   211       else
   212         priority o Pretty.string_of
   213     (* (unit -> Pretty.T) -> unit *)
   214     fun pprint_m f = () |> not auto ? pprint o f
   215     fun pprint_v f = () |> verbose ? pprint o f
   216     fun pprint_d f = () |> debug ? pprint o f
   217     (* string -> unit *)
   218     val print = pprint o curry Pretty.blk 0 o pstrs
   219     (* (unit -> string) -> unit *)
   220     val print_m = pprint_m o K o plazy
   221     val print_v = pprint_v o K o plazy
   222     val print_d = pprint_d o K o plazy
   223 
   224     (* unit -> unit *)
   225     fun check_deadline () =
   226       if debug andalso passed_deadline deadline then raise TimeLimit.TimeOut
   227       else ()
   228     (* unit -> 'a *)
   229     fun do_interrupted () =
   230       if passed_deadline deadline then raise TimeLimit.TimeOut
   231       else raise Interrupt
   232 
   233     val _ = print_m (K "Nitpicking...")
   234     val neg_t = if falsify then Logic.mk_implies (orig_t, @{prop False})
   235                 else orig_t
   236     val assms_t = if assms orelse auto then
   237                     Logic.mk_conjunction_list (neg_t :: orig_assm_ts)
   238                   else
   239                     neg_t
   240     val (assms_t, evals) =
   241       assms_t :: evals |> merge_type_vars ? merge_type_vars_in_terms
   242                        |> pairf hd tl
   243     val original_max_potential = max_potential
   244     val original_max_genuine = max_genuine
   245 (*
   246     val _ = priority ("*** " ^ Syntax.string_of_term ctxt orig_t)
   247     val _ = List.app (fn t => priority ("*** " ^ Syntax.string_of_term ctxt t))
   248                      orig_assm_ts
   249 *)
   250     val max_bisim_depth = fold Integer.max bisim_depths ~1
   251     val case_names = case_const_names thy
   252     val (defs, built_in_nondefs, user_nondefs) = all_axioms_of thy
   253     val def_table = const_def_table ctxt defs
   254     val nondef_table = const_nondef_table (built_in_nondefs @ user_nondefs)
   255     val simp_table = Unsynchronized.ref (const_simp_table ctxt)
   256     val psimp_table = const_psimp_table ctxt
   257     val intro_table = inductive_intro_table ctxt def_table
   258     val ground_thm_table = ground_theorem_table thy
   259     val ersatz_table = ersatz_table thy
   260     val (ext_ctxt as {wf_cache, ...}) =
   261       {thy = thy, ctxt = ctxt, max_bisim_depth = max_bisim_depth, boxes = boxes,
   262        user_axioms = user_axioms, debug = debug, wfs = wfs,
   263        destroy_constrs = destroy_constrs, specialize = specialize,
   264        skolemize = skolemize, star_linear_preds = star_linear_preds,
   265        uncurry = uncurry, fast_descrs = fast_descrs, tac_timeout = tac_timeout,
   266        evals = evals, case_names = case_names, def_table = def_table,
   267        nondef_table = nondef_table, user_nondefs = user_nondefs,
   268        simp_table = simp_table, psimp_table = psimp_table,
   269        intro_table = intro_table, ground_thm_table = ground_thm_table,
   270        ersatz_table = ersatz_table, skolems = Unsynchronized.ref [],
   271        special_funs = Unsynchronized.ref [],
   272        unrolled_preds = Unsynchronized.ref [], wf_cache = Unsynchronized.ref [],
   273        constr_cache = Unsynchronized.ref []}
   274     val frees = Term.add_frees assms_t []
   275     val _ = null (Term.add_tvars assms_t [])
   276             orelse raise NOT_SUPPORTED "schematic type variables"
   277     val (((def_ts, nondef_ts), (got_all_mono_user_axioms, no_poly_user_axioms)),
   278          core_t) = preprocess_term ext_ctxt assms_t
   279     val got_all_user_axioms =
   280       got_all_mono_user_axioms andalso no_poly_user_axioms
   281 
   282     (* styp * (bool * bool) -> unit *)
   283     fun print_wf (x, (gfp, wf)) =
   284       pprint (Pretty.blk (0,
   285           pstrs ("The " ^ (if gfp then "co" else "") ^ "inductive predicate \"")
   286           @ Syntax.pretty_term ctxt (Const x) ::
   287           pstrs (if wf then
   288                    "\" was proved well-founded. Nitpick can compute it \
   289                    \efficiently."
   290                  else
   291                    "\" could not be proved well-founded. Nitpick might need to \
   292                    \unroll it.")))
   293     val _ = if verbose then List.app print_wf (!wf_cache) else ()
   294     val _ =
   295       pprint_d (fn () =>
   296           Pretty.chunks
   297               (pretties_for_formulas ctxt "Preprocessed formula" [core_t] @
   298                pretties_for_formulas ctxt "Relevant definitional axiom" def_ts @
   299                pretties_for_formulas ctxt "Relevant nondefinitional axiom"
   300                                      nondef_ts))
   301     val _ = List.app (ignore o Term.type_of) (core_t :: def_ts @ nondef_ts)
   302             handle TYPE (_, Ts, ts) =>
   303                    raise TYPE ("Nitpick.pick_them_nits_in_term", Ts, ts)
   304 
   305     val core_u = nut_from_term ext_ctxt Eq core_t
   306     val def_us = map (nut_from_term ext_ctxt DefEq) def_ts
   307     val nondef_us = map (nut_from_term ext_ctxt Eq) nondef_ts
   308     val (free_names, const_names) =
   309       fold add_free_and_const_names (core_u :: def_us @ nondef_us) ([], [])
   310     val (sel_names, nonsel_names) =
   311       List.partition (is_sel o nickname_of) const_names
   312     val would_be_genuine = got_all_user_axioms andalso none_true wfs
   313 (*
   314     val _ = List.app (priority o string_for_nut ctxt)
   315                      (core_u :: def_us @ nondef_us)
   316 *)
   317 
   318     val unique_scope = forall (equal 1 o length o snd) cards_assigns
   319     (* typ -> bool *)
   320     fun is_free_type_monotonic T =
   321       unique_scope orelse
   322       case triple_lookup (type_match thy) monos T of
   323         SOME (SOME b) => b
   324       | _ => formulas_monotonic ext_ctxt T def_ts nondef_ts core_t
   325     fun is_datatype_monotonic T =
   326       unique_scope orelse
   327       case triple_lookup (type_match thy) monos T of
   328         SOME (SOME b) => b
   329       | _ =>
   330         not (is_pure_typedef thy T) orelse is_univ_typedef thy T
   331         orelse is_number_type thy T
   332         orelse formulas_monotonic ext_ctxt T def_ts nondef_ts core_t
   333     fun is_datatype_shallow T =
   334       not (exists (equal T o domain_type o type_of) sel_names)
   335     val Ts = ground_types_in_terms ext_ctxt (core_t :: def_ts @ nondef_ts)
   336              |> sort TermOrd.typ_ord
   337     val (all_dataTs, all_free_Ts) =
   338       List.partition (is_integer_type orf is_datatype thy) Ts
   339     val (mono_dataTs, nonmono_dataTs) =
   340       List.partition is_datatype_monotonic all_dataTs
   341     val (mono_free_Ts, nonmono_free_Ts) =
   342       List.partition is_free_type_monotonic all_free_Ts
   343 
   344     val _ =
   345       if not unique_scope andalso not (null mono_free_Ts) then
   346         print_v (fn () =>
   347                     let
   348                       val ss = map (quote o string_for_type ctxt) mono_free_Ts
   349                     in
   350                       "The type" ^ plural_s_for_list ss ^ " " ^
   351                       space_implode " " (serial_commas "and" ss) ^ " " ^
   352                       (if none_true monos then
   353                          "passed the monotonicity test"
   354                        else
   355                          (if length ss = 1 then "is" else "are") ^
   356                          " considered monotonic") ^
   357                       ". Nitpick might be able to skip some scopes."
   358                     end)
   359       else
   360         ()
   361     val mono_Ts = mono_dataTs @ mono_free_Ts
   362     val nonmono_Ts = nonmono_dataTs @ nonmono_free_Ts
   363     val shallow_dataTs = filter is_datatype_shallow mono_dataTs
   364 (*
   365     val _ = priority "Monotonic datatypes:"
   366     val _ = List.app (priority o string_for_type ctxt) mono_dataTs
   367     val _ = priority "Nonmonotonic datatypes:"
   368     val _ = List.app (priority o string_for_type ctxt) nonmono_dataTs
   369     val _ = priority "Monotonic free types:"
   370     val _ = List.app (priority o string_for_type ctxt) mono_free_Ts
   371     val _ = priority "Nonmonotonic free types:"
   372     val _ = List.app (priority o string_for_type ctxt) nonmono_free_Ts
   373 *)
   374 
   375     val need_incremental = Int.max (max_potential, max_genuine) >= 2
   376     val effective_sat_solver =
   377       if sat_solver <> "smart" then
   378         if need_incremental andalso
   379            not (sat_solver mem Kodkod_SAT.configured_sat_solvers true) then
   380           (print_m (K ("An incremental SAT solver is required: \"SAT4J\" will \
   381                        \be used instead of " ^ quote sat_solver ^ "."));
   382            "SAT4J")
   383         else
   384           sat_solver
   385       else
   386         Kodkod_SAT.smart_sat_solver_name need_incremental
   387     val _ =
   388       if sat_solver = "smart" then
   389         print_v (fn () => "Using SAT solver " ^ quote effective_sat_solver ^
   390                           ". The following" ^
   391                           (if need_incremental then " incremental " else " ") ^
   392                           "solvers are configured: " ^
   393                           commas (map quote (Kodkod_SAT.configured_sat_solvers
   394                                                        need_incremental)) ^ ".")
   395       else
   396         ()
   397 
   398     val too_big_scopes = Unsynchronized.ref []
   399 
   400     (* bool -> scope -> rich_problem option *)
   401     fun problem_for_scope liberal
   402             (scope as {card_assigns, bisim_depth, datatypes, ofs, ...}) =
   403       let
   404         val _ = not (exists (fn other => scope_less_eq other scope)
   405                             (!too_big_scopes))
   406                 orelse raise LIMIT ("Nitpick.pick_them_nits_in_term.\
   407                                     \problem_for_scope", "too big scope")
   408 (*
   409         val _ = priority "Offsets:"
   410         val _ = List.app (fn (T, j0) =>
   411                              priority (string_for_type ctxt T ^ " = " ^
   412                                        string_of_int j0))
   413                          (Typtab.dest ofs)
   414 *)
   415         val all_precise = forall (is_precise_type datatypes) Ts
   416         (* nut list -> rep NameTable.table -> nut list * rep NameTable.table *)
   417         val repify_consts = choose_reps_for_consts scope all_precise
   418         val main_j0 = offset_of_type ofs bool_T
   419         val (nat_card, nat_j0) = spec_of_type scope nat_T
   420         val (int_card, int_j0) = spec_of_type scope int_T
   421         val _ = forall (equal main_j0) [nat_j0, int_j0]
   422                 orelse raise BAD ("Nitpick.pick_them_nits_in_term.\
   423                                   \problem_for_scope", "bad offsets")
   424         val kk = kodkod_constrs peephole_optim nat_card int_card main_j0
   425         val (free_names, rep_table) =
   426           choose_reps_for_free_vars scope free_names NameTable.empty
   427         val (sel_names, rep_table) = choose_reps_for_all_sels scope rep_table
   428         val (nonsel_names, rep_table) = repify_consts nonsel_names rep_table
   429         val min_highest_arity =
   430           NameTable.fold (curry Int.max o arity_of_rep o snd) rep_table 1
   431         val min_univ_card =
   432           NameTable.fold (curry Int.max o min_univ_card_of_rep o snd) rep_table
   433                          (univ_card nat_card int_card main_j0 [] Kodkod.True)
   434         val _ = check_arity min_univ_card min_highest_arity
   435 
   436         val core_u = choose_reps_in_nut scope liberal rep_table false core_u
   437         val def_us = map (choose_reps_in_nut scope liberal rep_table true)
   438                          def_us
   439         val nondef_us = map (choose_reps_in_nut scope liberal rep_table false)
   440                             nondef_us
   441 (*
   442         val _ = List.app (priority o string_for_nut ctxt)
   443                          (free_names @ sel_names @ nonsel_names @
   444                           core_u :: def_us @ nondef_us)
   445 *)
   446         val (free_rels, pool, rel_table) =
   447           rename_free_vars free_names initial_pool NameTable.empty
   448         val (sel_rels, pool, rel_table) =
   449           rename_free_vars sel_names pool rel_table
   450         val (other_rels, pool, rel_table) =
   451           rename_free_vars nonsel_names pool rel_table
   452         val core_u = rename_vars_in_nut pool rel_table core_u
   453         val def_us = map (rename_vars_in_nut pool rel_table) def_us
   454         val nondef_us = map (rename_vars_in_nut pool rel_table) nondef_us
   455         (* nut -> Kodkod.formula *)
   456         val to_f = kodkod_formula_from_nut ofs liberal kk
   457         val core_f = to_f core_u
   458         val def_fs = map to_f def_us
   459         val nondef_fs = map to_f nondef_us
   460         val formula = fold (fold s_and) [def_fs, nondef_fs] core_f
   461         val comment = (if liberal then "liberal" else "conservative") ^ "\n" ^
   462                       PrintMode.setmp [] multiline_string_for_scope scope
   463         val kodkod_sat_solver = Kodkod_SAT.sat_solver_spec effective_sat_solver
   464                                 |> snd
   465         val delay = if liberal then
   466                       Option.map (fn time => Time.- (time, Time.now ()))
   467                                  deadline
   468                       |> liberal_delay_for_timeout
   469                     else
   470                       0
   471         val settings = [("solver", commas (map quote kodkod_sat_solver)),
   472                         ("skolem_depth", "-1"),
   473                         ("bit_width", "16"),
   474                         ("symmetry_breaking", signed_string_of_int sym_break),
   475                         ("sharing", signed_string_of_int sharing_depth),
   476                         ("flatten", Bool.toString flatten_props),
   477                         ("delay", signed_string_of_int delay)]
   478         val plain_rels = free_rels @ other_rels
   479         val plain_bounds = map (bound_for_plain_rel ctxt debug) plain_rels
   480         val plain_axioms = map (declarative_axiom_for_plain_rel kk) plain_rels
   481         val sel_bounds = map (bound_for_sel_rel ctxt debug datatypes) sel_rels
   482         val dtype_axioms = declarative_axioms_for_datatypes ext_ctxt ofs kk
   483                                                             rel_table datatypes
   484         val declarative_axioms = plain_axioms @ dtype_axioms
   485         val univ_card = univ_card nat_card int_card main_j0
   486                                   (plain_bounds @ sel_bounds) formula
   487         val built_in_bounds = bounds_for_built_in_rels_in_formula debug
   488                                   univ_card nat_card int_card main_j0 formula
   489         val bounds = built_in_bounds @ plain_bounds @ sel_bounds
   490                      |> not debug ? merge_bounds
   491         val highest_arity =
   492           fold Integer.max (map (fst o fst) (maps fst bounds)) 0
   493         val formula = fold_rev s_and declarative_axioms formula
   494         val _ = if formula = Kodkod.False then ()
   495                 else check_arity univ_card highest_arity
   496       in
   497         SOME ({comment = comment, settings = settings, univ_card = univ_card,
   498                tuple_assigns = [], bounds = bounds,
   499                int_bounds = sequential_int_bounds univ_card,
   500                expr_assigns = [], formula = formula},
   501               {free_names = free_names, sel_names = sel_names,
   502                nonsel_names = nonsel_names, rel_table = rel_table,
   503                liberal = liberal, scope = scope, core = core_f,
   504                defs = nondef_fs @ def_fs @ declarative_axioms})
   505       end
   506       handle LIMIT (loc, msg) =>
   507              if loc = "Nitpick_Kodkod.check_arity"
   508                 andalso not (Typtab.is_empty ofs) then
   509                problem_for_scope liberal
   510                    {ext_ctxt = ext_ctxt, card_assigns = card_assigns,
   511                     bisim_depth = bisim_depth, datatypes = datatypes,
   512                     ofs = Typtab.empty}
   513              else if loc = "Nitpick.pick_them_nits_in_term.\
   514                            \problem_for_scope" then
   515                NONE
   516              else
   517                (Unsynchronized.change too_big_scopes (cons scope);
   518                 print_v (fn () => ("Limit reached: " ^ msg ^
   519                                    ". Dropping " ^ (if liberal then "potential"
   520                                                     else "genuine") ^
   521                                    " component of scope."));
   522                 NONE)
   523 
   524     (* int -> (''a * int list list) list -> ''a -> Kodkod.tuple_set *)
   525     fun tuple_set_for_rel univ_card =
   526       Kodkod.TupleSet o map (kk_tuple debug univ_card) o the
   527       oo AList.lookup (op =)
   528 
   529     val word_model = if falsify then "counterexample" else "model"
   530 
   531     val scopes = Unsynchronized.ref []
   532     val generated_scopes = Unsynchronized.ref []
   533     val generated_problems = Unsynchronized.ref []
   534     val checked_problems = Unsynchronized.ref (SOME [])
   535     val met_potential = Unsynchronized.ref 0
   536 
   537     (* rich_problem list -> int list -> unit *)
   538     fun update_checked_problems problems =
   539       List.app (Unsynchronized.change checked_problems o Option.map o cons
   540                 o nth problems)
   541 
   542     (* bool -> Kodkod.raw_bound list -> problem_extension -> bool option *)
   543     fun print_and_check_model genuine bounds
   544             ({free_names, sel_names, nonsel_names, rel_table, scope, ...}
   545              : problem_extension) =
   546       let
   547         val (reconstructed_model, codatatypes_ok) =
   548           reconstruct_hol_model {show_skolems = show_skolems,
   549                                  show_datatypes = show_datatypes,
   550                                  show_consts = show_consts}
   551               scope formats frees free_names sel_names nonsel_names rel_table
   552               bounds
   553         val would_be_genuine = would_be_genuine andalso codatatypes_ok
   554       in
   555         pprint (Pretty.chunks
   556             [Pretty.blk (0,
   557                  (pstrs ("Nitpick found a" ^
   558                          (if not genuine then " potential "
   559                           else if would_be_genuine then " "
   560                           else " likely genuine ") ^ word_model) @
   561                   (case pretties_for_scope scope verbose of
   562                      [] => []
   563                    | pretties => pstrs " for " @ pretties) @
   564                   [Pretty.str ":\n"])),
   565              Pretty.indent indent_size reconstructed_model]);
   566         if genuine then
   567           (if check_genuine then
   568              (case prove_hol_model scope tac_timeout free_names sel_names
   569                                    rel_table bounds assms_t of
   570                 SOME true => print ("Confirmation by \"auto\": The above " ^
   571                                     word_model ^ " is really genuine.")
   572               | SOME false =>
   573                 if would_be_genuine then
   574                   error ("A supposedly genuine " ^ word_model ^ " was shown to\
   575                          \be spurious by \"auto\".\nThis should never happen.\n\
   576                          \Please send a bug report to blanchet\
   577                          \te@in.tum.de.")
   578                 else
   579                   print ("Refutation by \"auto\": The above " ^ word_model ^
   580                          " is spurious.")
   581               | NONE => print "No confirmation by \"auto\".")
   582            else
   583              ();
   584            if has_syntactic_sorts orig_t then
   585              print "Hint: Maybe you forgot a type constraint?"
   586            else
   587              ();
   588            if not would_be_genuine then
   589              if no_poly_user_axioms then
   590                let
   591                  val options =
   592                    [] |> not got_all_mono_user_axioms
   593                          ? cons ("user_axioms", "\"true\"")
   594                       |> not (none_true wfs)
   595                          ? cons ("wf", "\"smart\" or \"false\"")
   596                       |> not codatatypes_ok
   597                          ? cons ("bisim_depth", "a nonnegative value")
   598                  val ss =
   599                    map (fn (name, value) => quote name ^ " set to " ^ value)
   600                        options
   601                in
   602                  print ("Try again with " ^
   603                         space_implode " " (serial_commas "and" ss) ^
   604                         " to confirm that the " ^ word_model ^ " is genuine.")
   605                end
   606              else
   607                print ("Nitpick is unable to guarantee the authenticity of \
   608                       \the " ^ word_model ^ " in the presence of polymorphic \
   609                       \axioms.")
   610            else
   611              ();
   612            NONE)
   613         else
   614           if not genuine then
   615             (Unsynchronized.inc met_potential;
   616              if check_potential then
   617                let
   618                  val status = prove_hol_model scope tac_timeout free_names
   619                                               sel_names rel_table bounds assms_t
   620                in
   621                  (case status of
   622                     SOME true => print ("Confirmation by \"auto\": The above " ^
   623                                         word_model ^ " is genuine.")
   624                   | SOME false => print ("Refutation by \"auto\": The above " ^
   625                                          word_model ^ " is spurious.")
   626                   | NONE => print "No confirmation by \"auto\".");
   627                  status
   628                end
   629              else
   630                NONE)
   631           else
   632             NONE
   633       end
   634     (* int -> int -> int -> bool -> rich_problem list -> int * int * int *)
   635     fun solve_any_problem max_potential max_genuine donno first_time problems =
   636       let
   637         val max_potential = Int.max (0, max_potential)
   638         val max_genuine = Int.max (0, max_genuine)
   639         (* bool -> int * Kodkod.raw_bound list -> bool option *)
   640         fun print_and_check genuine (j, bounds) =
   641           print_and_check_model genuine bounds (snd (nth problems j))
   642         val max_solutions = max_potential + max_genuine
   643                             |> not need_incremental ? curry Int.min 1
   644       in
   645         if max_solutions <= 0 then
   646           (0, 0, donno)
   647         else
   648           case Kodkod.solve_any_problem overlord deadline max_threads
   649                                         max_solutions (map fst problems) of
   650             Kodkod.NotInstalled =>
   651             (print_m install_kodkodi_message;
   652              (max_potential, max_genuine, donno + 1))
   653           | Kodkod.Normal ([], unsat_js) =>
   654             (update_checked_problems problems unsat_js;
   655              (max_potential, max_genuine, donno))
   656           | Kodkod.Normal (sat_ps, unsat_js) =>
   657             let
   658               val (lib_ps, con_ps) =
   659                 List.partition (#liberal o snd o nth problems o fst) sat_ps
   660             in
   661               update_checked_problems problems (unsat_js @ map fst lib_ps);
   662               if null con_ps then
   663                 let
   664                   val num_genuine = take max_potential lib_ps
   665                                     |> map (print_and_check false)
   666                                     |> filter (equal (SOME true)) |> length
   667                   val max_genuine = max_genuine - num_genuine
   668                   val max_potential = max_potential
   669                                       - (length lib_ps - num_genuine)
   670                 in
   671                   if max_genuine <= 0 then
   672                     (0, 0, donno)
   673                   else
   674                     let
   675                       (* "co_js" is the list of conservative problems whose
   676                          liberal pendants couldn't be satisfied and hence that
   677                          most probably can't be satisfied themselves. *)
   678                       val co_js =
   679                         map (fn j => j - 1) unsat_js
   680                         |> filter (fn j =>
   681                                       j >= 0 andalso
   682                                       scopes_equivalent
   683                                           (#scope (snd (nth problems j)))
   684                                           (#scope (snd (nth problems (j + 1)))))
   685                       val bye_js = sort_distinct int_ord (map fst sat_ps @
   686                                                           unsat_js @ co_js)
   687                       val problems =
   688                         problems |> filter_out_indices bye_js
   689                                  |> max_potential <= 0
   690                                     ? filter_out (#liberal o snd)
   691                     in
   692                       solve_any_problem max_potential max_genuine donno false
   693                                         problems
   694                     end
   695                 end
   696               else
   697                 let
   698                   val _ = take max_genuine con_ps
   699                           |> List.app (ignore o print_and_check true)
   700                   val max_genuine = max_genuine - length con_ps
   701                 in
   702                   if max_genuine <= 0 orelse not first_time then
   703                     (0, max_genuine, donno)
   704                   else
   705                     let
   706                       val bye_js = sort_distinct int_ord
   707                                                  (map fst sat_ps @ unsat_js)
   708                       val problems =
   709                         problems |> filter_out_indices bye_js
   710                                  |> filter_out (#liberal o snd)
   711                     in solve_any_problem 0 max_genuine donno false problems end
   712                 end
   713             end
   714           | Kodkod.TimedOut unsat_js =>
   715             (update_checked_problems problems unsat_js; raise TimeLimit.TimeOut)
   716           | Kodkod.Interrupted NONE =>
   717             (checked_problems := NONE; do_interrupted ())
   718           | Kodkod.Interrupted (SOME unsat_js) =>
   719             (update_checked_problems problems unsat_js; do_interrupted ())
   720           | Kodkod.Error (s, unsat_js) =>
   721             (update_checked_problems problems unsat_js;
   722              print_v (K ("Kodkod error: " ^ s ^ "."));
   723              (max_potential, max_genuine, donno + 1))
   724       end
   725 
   726     (* int -> int -> scope list -> int * int * int -> int * int * int *)
   727     fun run_batch j n scopes (max_potential, max_genuine, donno) =
   728       let
   729         val _ =
   730           if null scopes then
   731             print_m (K "The scope specification is inconsistent.")
   732           else if verbose then
   733             pprint (Pretty.chunks
   734                 [Pretty.blk (0,
   735                      pstrs ((if n > 1 then
   736                                "Batch " ^ string_of_int (j + 1) ^ " of " ^
   737                                signed_string_of_int n ^ ": "
   738                              else
   739                                "") ^
   740                             "Trying " ^ string_of_int (length scopes) ^
   741                             " scope" ^ plural_s_for_list scopes ^ ":")),
   742                  Pretty.indent indent_size
   743                      (Pretty.chunks (map2
   744                           (fn j => fn scope =>
   745                               Pretty.block (
   746                                   (case pretties_for_scope scope true of
   747                                      [] => [Pretty.str "Empty"]
   748                                    | pretties => pretties) @
   749                                   [Pretty.str (if j = 1 then "." else ";")]))
   750                           (length scopes downto 1) scopes))])
   751           else
   752             ()
   753         (* scope * bool -> rich_problem list * bool
   754            -> rich_problem list * bool *)
   755         fun add_problem_for_scope (scope as {datatypes, ...}, liberal)
   756                                   (problems, donno) =
   757           (check_deadline ();
   758            case problem_for_scope liberal scope of
   759              SOME problem =>
   760              (problems
   761               |> (null problems orelse
   762                   not (Kodkod.problems_equivalent (fst problem)
   763                                                   (fst (hd problems))))
   764                   ? cons problem, donno)
   765            | NONE => (problems, donno + 1))
   766         val (problems, donno) =
   767           fold add_problem_for_scope
   768                (map_product pair scopes
   769                     ((if max_genuine > 0 then [false] else []) @
   770                      (if max_potential > 0 then [true] else [])))
   771                ([], donno)
   772         val _ = Unsynchronized.change generated_problems (append problems)
   773         val _ = Unsynchronized.change generated_scopes (append scopes)
   774       in
   775         solve_any_problem max_potential max_genuine donno true (rev problems)
   776       end
   777 
   778     (* rich_problem list -> scope -> int *)
   779     fun scope_count (problems : rich_problem list) scope =
   780       length (filter (scopes_equivalent scope o #scope o snd) problems)
   781     (* string -> string *)
   782     fun excipit did_so_and_so =
   783       let
   784         (* rich_problem list -> rich_problem list *)
   785         val do_filter =
   786           if !met_potential = max_potential then filter_out (#liberal o snd)
   787           else I
   788         val total = length (!scopes)
   789         val unsat =
   790           fold (fn scope =>
   791                    case scope_count (do_filter (!generated_problems)) scope of
   792                      0 => I
   793                    | n =>
   794                      scope_count (do_filter (these (!checked_problems)))
   795                                  scope = n
   796                      ? Integer.add 1) (!generated_scopes) 0
   797       in
   798         "Nitpick " ^ did_so_and_so ^
   799         (if is_some (!checked_problems) andalso total > 0 then
   800            " after checking " ^
   801            string_of_int (Int.min (total - 1, unsat)) ^ " of " ^
   802            string_of_int total ^ " scope" ^ plural_s total
   803          else
   804            "") ^ "."
   805       end
   806 
   807     (* int -> int -> scope list -> int * int * int -> Kodkod.outcome *)
   808     fun run_batches _ _ [] (max_potential, max_genuine, donno) =
   809         if donno > 0 andalso max_genuine > 0 then
   810           (print_m (fn () => excipit "ran out of juice"); "unknown")
   811         else if max_genuine = original_max_genuine then
   812           if max_potential = original_max_potential then
   813             (print_m (K ("Nitpick found no " ^ word_model ^ ".")); "none")
   814           else
   815             (print_m (K ("Nitpick could not find " ^
   816                          (if max_genuine = 1 then "a better " ^ word_model ^ "."
   817                           else "any better " ^ word_model ^ "s.")));
   818              "potential")
   819         else
   820           if would_be_genuine then "genuine" else "likely_genuine"
   821       | run_batches j n (batch :: batches) z =
   822         let val (z as (_, max_genuine, _)) = run_batch j n batch z in
   823           run_batches (j + 1) n (if max_genuine > 0 then batches else []) z
   824         end
   825 
   826     val (skipped, the_scopes) =
   827       all_scopes ext_ctxt sym_break cards_assigns maxes_assigns iters_assigns
   828                  bisim_depths mono_Ts nonmono_Ts shallow_dataTs
   829     val _ = if skipped > 0 then
   830               print_m (fn () => "Too many scopes. Dropping " ^
   831                                 string_of_int skipped ^ " scope" ^
   832                                 plural_s skipped ^
   833                                 ". (Consider using \"mono\" or \
   834                                 \\"merge_type_vars\" to prevent this.)")
   835             else
   836               ()
   837     val _ = scopes := the_scopes
   838 
   839     val batches = batch_list batch_size (!scopes)
   840     val outcome_code =
   841       (run_batches 0 (length batches) batches (max_potential, max_genuine, 0)
   842        handle Exn.Interrupt => do_interrupted ())
   843       handle TimeLimit.TimeOut =>
   844              (print_m (fn () => excipit "ran out of time");
   845               if !met_potential > 0 then "potential" else "unknown")
   846            | Exn.Interrupt => if auto orelse debug then raise Interrupt
   847                               else error (excipit "was interrupted")
   848     val _ = print_v (fn () => "Total time: " ^
   849                               signed_string_of_int (Time.toMilliseconds
   850                                     (Timer.checkRealTimer timer)) ^ " ms.")
   851   in (outcome_code, !state_ref) end
   852   handle Exn.Interrupt =>
   853          if auto orelse #debug params then
   854            raise Interrupt
   855          else
   856            if passed_deadline deadline then
   857              (priority "Nitpick ran out of time."; ("unknown", state))
   858            else
   859              error "Nitpick was interrupted."
   860 
   861 (* Proof.state -> params -> bool -> term -> string * Proof.state *)
   862 fun pick_nits_in_term state (params as {debug, timeout, expect, ...})
   863                       auto orig_assm_ts orig_t =
   864   if getenv "KODKODI" = "" then
   865     (if auto then ()
   866      else warning (Pretty.string_of (plazy install_kodkodi_message));
   867      ("unknown", state))
   868   else
   869     let
   870       val deadline = Option.map (curry Time.+ (Time.now ())) timeout
   871       val outcome as (outcome_code, _) =
   872         time_limit (if debug then NONE else timeout)
   873             (pick_them_nits_in_term deadline state params auto orig_assm_ts)
   874             orig_t
   875     in
   876       if expect = "" orelse outcome_code = expect then outcome
   877       else error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
   878     end
   879 
   880 (* Proof.state -> params -> thm -> int -> string * Proof.state *)
   881 fun pick_nits_in_subgoal state params auto subgoal =
   882   let
   883     val ctxt = Proof.context_of state
   884     val t = state |> Proof.raw_goal |> #goal |> prop_of
   885   in
   886     if Logic.count_prems t = 0 then
   887       (priority "No subgoal!"; ("none", state))
   888     else
   889       let
   890         val assms = map term_of (Assumption.all_assms_of ctxt)
   891         val (t, frees) = Logic.goal_params t subgoal
   892       in pick_nits_in_term state params auto assms (subst_bounds (frees, t)) end
   893   end
   894 
   895 end;