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