src/HOL/Tools/Nitpick/nitpick.ML
author wenzelm
Sun Mar 13 16:01:00 2011 +0100 (2011-03-13 ago)
changeset 41944 b97091ae583a
parent 41897 c24e7fd17464
child 41985 09b75d55008f
permissions -rw-r--r--
Path.print is the official way to show file-system paths to users -- note that Path.implode often indicates violation of the abstract datatype;
     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.print (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 _ = if debug then ()
   525                 else check_arity guiltiest_party min_univ_card min_highest_arity
   526 
   527         val def_us =
   528           def_us |> map (choose_reps_in_nut scope unsound rep_table true)
   529         val nondef_us =
   530           nondef_us |> map (choose_reps_in_nut scope unsound rep_table false)
   531         val need_us =
   532           need_us |> map (choose_reps_in_nut scope unsound rep_table false)
   533 (*
   534         val _ = List.app (print_g o string_for_nut ctxt)
   535                          (free_names @ sel_names @ nonsel_names @
   536                           nondef_us @ def_us @ need_us)
   537 *)
   538         val (free_rels, pool, rel_table) =
   539           rename_free_vars free_names initial_pool NameTable.empty
   540         val (sel_rels, pool, rel_table) =
   541           rename_free_vars sel_names pool rel_table
   542         val (other_rels, pool, rel_table) =
   543           rename_free_vars nonsel_names pool rel_table
   544         val nondef_us = nondef_us |> map (rename_vars_in_nut pool rel_table)
   545         val def_us = def_us |> map (rename_vars_in_nut pool rel_table)
   546         val need_us = need_us |> map (rename_vars_in_nut pool rel_table)
   547         val nondef_fs = map (kodkod_formula_from_nut ofs kk) nondef_us
   548         val def_fs = map (kodkod_formula_from_nut ofs kk) def_us
   549         val formula = fold (fold s_and) [def_fs, nondef_fs] KK.True
   550         val comment = (if unsound then "unsound" else "sound") ^ "\n" ^
   551                       Print_Mode.setmp [] multiline_string_for_scope scope
   552         val kodkod_sat_solver =
   553           Kodkod_SAT.sat_solver_spec actual_sat_solver |> snd
   554         val bit_width = if bits = 0 then 16 else bits + 1
   555         val delay =
   556           if unsound then
   557             Option.map (fn time => Time.- (time, Time.now ())) deadline
   558             |> unsound_delay_for_timeout
   559           else
   560             0
   561         val settings = [("solver", commas_quote kodkod_sat_solver),
   562                         ("bit_width", string_of_int bit_width),
   563                         ("symmetry_breaking", string_of_int kodkod_sym_break),
   564                         ("sharing", "3"),
   565                         ("flatten", "false"),
   566                         ("delay", signed_string_of_int delay)]
   567         val plain_rels = free_rels @ other_rels
   568         val plain_bounds = map (bound_for_plain_rel ctxt debug) plain_rels
   569         val plain_axioms = map (declarative_axiom_for_plain_rel kk) plain_rels
   570         val sel_bounds = map (bound_for_sel_rel ctxt debug datatypes) sel_rels
   571         val dtype_axioms =
   572           declarative_axioms_for_datatypes hol_ctxt binarize need_us
   573               datatype_sym_break bits ofs kk rel_table datatypes
   574         val declarative_axioms = plain_axioms @ dtype_axioms
   575         val univ_card = Int.max (univ_card nat_card int_card main_j0
   576                                      (plain_bounds @ sel_bounds) formula,
   577                                  main_j0 |> bits > 0 ? Integer.add (bits + 1))
   578         val (built_in_bounds, built_in_axioms) =
   579           bounds_and_axioms_for_built_in_rels_in_formulas debug univ_card
   580               nat_card int_card main_j0 (formula :: declarative_axioms)
   581         val bounds = built_in_bounds @ plain_bounds @ sel_bounds
   582                      |> not debug ? merge_bounds
   583         val axioms = built_in_axioms @ declarative_axioms
   584         val highest_arity =
   585           fold Integer.max (map (fst o fst) (maps fst bounds)) 0
   586         val formula = fold_rev s_and axioms formula
   587         val _ = if bits = 0 then () else check_bits bits formula
   588         val _ = if debug orelse formula = KK.False then ()
   589                 else check_arity "" univ_card highest_arity
   590       in
   591         SOME ({comment = comment, settings = settings, univ_card = univ_card,
   592                tuple_assigns = [], bounds = bounds,
   593                int_bounds = if bits = 0 then sequential_int_bounds univ_card
   594                             else pow_of_two_int_bounds bits main_j0,
   595                expr_assigns = [], formula = formula},
   596               {free_names = free_names, sel_names = sel_names,
   597                nonsel_names = nonsel_names, rel_table = rel_table,
   598                unsound = unsound, scope = scope})
   599       end
   600       handle TOO_LARGE (loc, msg) =>
   601              if loc = "Nitpick_Kodkod.check_arity" andalso
   602                 not (Typtab.is_empty ofs) then
   603                problem_for_scope unsound
   604                    {hol_ctxt = hol_ctxt, binarize = binarize,
   605                     card_assigns = card_assigns, bits = bits,
   606                     bisim_depth = bisim_depth, datatypes = datatypes,
   607                     ofs = Typtab.empty}
   608              else if loc = "Nitpick.pick_them_nits_in_term.\
   609                            \problem_for_scope" then
   610                NONE
   611              else
   612                (Unsynchronized.change too_big_scopes (cons scope);
   613                 print_v (fn () => ("Limit reached: " ^ msg ^
   614                                    ". Skipping " ^ (if unsound then "potential"
   615                                                     else "genuine") ^
   616                                    " component of scope."));
   617                 NONE)
   618            | TOO_SMALL (_, msg) =>
   619              (print_v (fn () => ("Limit reached: " ^ msg ^
   620                                  ". Skipping " ^ (if unsound then "potential"
   621                                                   else "genuine") ^
   622                                  " component of scope."));
   623               NONE)
   624 
   625     val das_wort_model =
   626       (if falsify then "counterexample" else "model")
   627       |> not standard ? prefix "nonstandard "
   628 
   629     val scopes = Unsynchronized.ref []
   630     val generated_scopes = Unsynchronized.ref []
   631     val generated_problems = Unsynchronized.ref ([] : rich_problem list)
   632     val checked_problems = Unsynchronized.ref (SOME [])
   633     val met_potential = Unsynchronized.ref 0
   634 
   635     fun update_checked_problems problems =
   636       List.app (Unsynchronized.change checked_problems o Option.map o cons
   637                 o nth problems)
   638     fun show_kodkod_warning "" = ()
   639       | show_kodkod_warning s = print_m (fn () => "Kodkod warning: " ^ s ^ ".")
   640 
   641     fun print_and_check_model genuine bounds
   642             ({free_names, sel_names, nonsel_names, rel_table, scope, ...}
   643              : problem_extension) =
   644       let
   645         val (reconstructed_model, codatatypes_ok) =
   646           reconstruct_hol_model {show_datatypes = show_datatypes,
   647                                  show_consts = show_consts}
   648               scope formats atomss real_frees pseudo_frees free_names sel_names
   649               nonsel_names rel_table bounds
   650         val genuine_means_genuine =
   651           got_all_user_axioms andalso none_true wfs andalso
   652           sound_finitizes andalso total_consts <> SOME true andalso
   653           codatatypes_ok
   654         fun assms_prop () = Logic.mk_conjunction_list (neg_t :: assm_ts)
   655       in
   656         (pprint (Pretty.chunks
   657              [Pretty.blk (0,
   658                   (pstrs ((if auto then "Auto " else "") ^ "Nitpick found a" ^
   659                           (if not genuine then " potential "
   660                            else if genuine_means_genuine then " "
   661                            else " quasi genuine ") ^ das_wort_model) @
   662                    (case pretties_for_scope scope verbose of
   663                       [] => []
   664                     | pretties => pstrs " for " @ pretties) @
   665                    [Pretty.str ":\n"])),
   666               Pretty.indent indent_size reconstructed_model]);
   667          if genuine then
   668            (if check_genuine andalso standard then
   669               case prove_hol_model scope tac_timeout free_names sel_names
   670                                    rel_table bounds (assms_prop ()) of
   671                 SOME true =>
   672                 print ("Confirmation by \"auto\": The above " ^
   673                        das_wort_model ^ " is really genuine.")
   674               | SOME false =>
   675                 if genuine_means_genuine then
   676                   error ("A supposedly genuine " ^ das_wort_model ^ " was \
   677                          \shown to be spurious by \"auto\".\nThis should never \
   678                          \happen.\nPlease send a bug report to blanchet\
   679                          \te@in.tum.de.")
   680                  else
   681                    print ("Refutation by \"auto\": The above " ^
   682                           das_wort_model ^ " is spurious.")
   683                | NONE => print "No confirmation by \"auto\"."
   684             else
   685               ();
   686             if not standard andalso likely_in_struct_induct_step then
   687               print "The existence of a nonstandard model suggests that the \
   688                     \induction hypothesis is not general enough or may even be \
   689                     \wrong. See the Nitpick manual's \"Inductive Properties\" \
   690                     \section for details (\"isabelle doc nitpick\")."
   691             else
   692               ();
   693             if has_lonely_bool_var orig_t then
   694               print "Hint: Maybe you forgot a colon after the lemma's name?"
   695             else if has_syntactic_sorts orig_t then
   696               print "Hint: Maybe you forgot a type constraint?"
   697             else
   698               ();
   699             if not genuine_means_genuine then
   700               if no_poly_user_axioms then
   701                 let
   702                   val options =
   703                     [] |> not got_all_mono_user_axioms
   704                           ? cons ("user_axioms", "\"true\"")
   705                        |> not (none_true wfs)
   706                           ? cons ("wf", "\"smart\" or \"false\"")
   707                        |> not sound_finitizes
   708                           ? cons ("finitize", "\"smart\" or \"false\"")
   709                        |> total_consts = SOME true
   710                           ? cons ("total_consts", "\"smart\" or \"false\"")
   711                        |> not codatatypes_ok
   712                           ? cons ("bisim_depth", "a nonnegative value")
   713                   val ss =
   714                     map (fn (name, value) => quote name ^ " set to " ^ value)
   715                         options
   716                 in
   717                   print ("Try again with " ^
   718                          space_implode " " (serial_commas "and" ss) ^
   719                          " to confirm that the " ^ das_wort_model ^
   720                          " is genuine.")
   721                 end
   722               else
   723                 print ("Nitpick is unable to guarantee the authenticity of \
   724                        \the " ^ das_wort_model ^ " in the presence of \
   725                        \polymorphic axioms.")
   726             else
   727               ();
   728             NONE)
   729          else
   730            if not genuine then
   731              (Unsynchronized.inc met_potential;
   732               if check_potential then
   733                 let
   734                   val status = prove_hol_model scope tac_timeout free_names
   735                                                sel_names rel_table bounds
   736                                                (assms_prop ())
   737                 in
   738                   (case status of
   739                      SOME true => print ("Confirmation by \"auto\": The \
   740                                          \above " ^ das_wort_model ^
   741                                          " is genuine.")
   742                    | SOME false => print ("Refutation by \"auto\": The above " ^
   743                                           das_wort_model ^ " is spurious.")
   744                    | NONE => print "No confirmation by \"auto\".");
   745                   status
   746                 end
   747               else
   748                 NONE)
   749            else
   750              NONE)
   751         |> pair genuine_means_genuine
   752       end
   753     fun solve_any_problem (found_really_genuine, max_potential, max_genuine,
   754                            donno) first_time problems =
   755       let
   756         val max_potential = Int.max (0, max_potential)
   757         val max_genuine = Int.max (0, max_genuine)
   758         fun print_and_check genuine (j, bounds) =
   759           print_and_check_model genuine bounds (snd (nth problems j))
   760         val max_solutions = max_potential + max_genuine
   761                             |> not incremental ? Integer.min 1
   762       in
   763         if max_solutions <= 0 then
   764           (found_really_genuine, 0, 0, donno)
   765         else
   766           case KK.solve_any_problem debug overlord deadline max_threads
   767                                     max_solutions (map fst problems) of
   768             KK.JavaNotInstalled =>
   769             (print_m install_java_message;
   770              (found_really_genuine, max_potential, max_genuine, donno + 1))
   771           | KK.JavaTooOld =>
   772             (print_m install_java_message;
   773              (found_really_genuine, max_potential, max_genuine, donno + 1))
   774           | KK.KodkodiNotInstalled =>
   775             (print_m install_kodkodi_message;
   776              (found_really_genuine, max_potential, max_genuine, donno + 1))
   777           | KK.Normal ([], unsat_js, s) =>
   778             (update_checked_problems problems unsat_js; show_kodkod_warning s;
   779              (found_really_genuine, max_potential, max_genuine, donno))
   780           | KK.Normal (sat_ps, unsat_js, s) =>
   781             let
   782               val (lib_ps, con_ps) =
   783                 List.partition (#unsound o snd o nth problems o fst) sat_ps
   784             in
   785               update_checked_problems problems (unsat_js @ map fst lib_ps);
   786               show_kodkod_warning s;
   787               if null con_ps then
   788                 let
   789                   val genuine_codes =
   790                     lib_ps |> take max_potential
   791                            |> map (print_and_check false)
   792                            |> filter (curry (op =) (SOME true) o snd)
   793                   val found_really_genuine =
   794                     found_really_genuine orelse exists fst genuine_codes
   795                   val num_genuine = length genuine_codes
   796                   val max_genuine = max_genuine - num_genuine
   797                   val max_potential = max_potential
   798                                       - (length lib_ps - num_genuine)
   799                 in
   800                   if max_genuine <= 0 then
   801                     (found_really_genuine, 0, 0, donno)
   802                   else
   803                     let
   804                       (* "co_js" is the list of sound problems whose unsound
   805                          pendants couldn't be satisfied and hence that most
   806                          probably can't be satisfied themselves. *)
   807                       val co_js =
   808                         map (fn j => j - 1) unsat_js
   809                         |> filter (fn j =>
   810                                       j >= 0 andalso
   811                                       scopes_equivalent
   812                                           (#scope (snd (nth problems j)),
   813                                            #scope (snd (nth problems (j + 1)))))
   814                       val bye_js = sort_distinct int_ord (map fst sat_ps @
   815                                                           unsat_js @ co_js)
   816                       val problems =
   817                         problems |> filter_out_indices bye_js
   818                                  |> max_potential <= 0
   819                                     ? filter_out (#unsound o snd)
   820                     in
   821                       solve_any_problem (found_really_genuine, max_potential,
   822                                          max_genuine, donno) false problems
   823                     end
   824                 end
   825               else
   826                 let
   827                   val genuine_codes =
   828                     con_ps |> take max_genuine
   829                            |> map (print_and_check true)
   830                   val max_genuine = max_genuine - length genuine_codes
   831                   val found_really_genuine =
   832                     found_really_genuine orelse exists fst genuine_codes
   833                 in
   834                   if max_genuine <= 0 orelse not first_time then
   835                     (found_really_genuine, 0, max_genuine, donno)
   836                   else
   837                     let
   838                       val bye_js = sort_distinct int_ord
   839                                                  (map fst sat_ps @ unsat_js)
   840                       val problems =
   841                         problems |> filter_out_indices bye_js
   842                                  |> filter_out (#unsound o snd)
   843                     in
   844                       solve_any_problem (found_really_genuine, 0, max_genuine,
   845                                          donno) false problems
   846                     end
   847                 end
   848             end
   849           | KK.TimedOut unsat_js =>
   850             (update_checked_problems problems unsat_js; raise TimeLimit.TimeOut)
   851           | KK.Error (s, unsat_js) =>
   852             (update_checked_problems problems unsat_js;
   853              print_v (K ("Kodkod error: " ^ s ^ "."));
   854              (found_really_genuine, max_potential, max_genuine, donno + 1))
   855       end
   856 
   857     fun run_batch j n scopes (found_really_genuine, max_potential, max_genuine,
   858                               donno) =
   859       let
   860         val _ =
   861           if null scopes then
   862             print_m (K "The scope specification is inconsistent.")
   863           else if verbose then
   864             pprint (Pretty.chunks
   865                 [Pretty.blk (0,
   866                      pstrs ((if n > 1 then
   867                                "Batch " ^ string_of_int (j + 1) ^ " of " ^
   868                                signed_string_of_int n ^ ": "
   869                              else
   870                                "") ^
   871                             "Trying " ^ string_of_int (length scopes) ^
   872                             " scope" ^ plural_s_for_list scopes ^ ":")),
   873                  Pretty.indent indent_size
   874                      (Pretty.chunks (map2
   875                           (fn j => fn scope =>
   876                               Pretty.block (
   877                                   (case pretties_for_scope scope true of
   878                                      [] => [Pretty.str "Empty"]
   879                                    | pretties => pretties) @
   880                                   [Pretty.str (if j = 1 then "." else ";")]))
   881                           (length scopes downto 1) scopes))])
   882           else
   883             ()
   884         fun add_problem_for_scope (scope, unsound) (problems, donno) =
   885           (check_deadline ();
   886            case problem_for_scope unsound scope of
   887              SOME problem =>
   888              (problems
   889               |> (null problems orelse
   890                   not (KK.problems_equivalent (fst problem, fst (hd problems))))
   891                   ? cons problem, donno)
   892            | NONE => (problems, donno + 1))
   893         val (problems, donno) =
   894           fold add_problem_for_scope
   895                (map_product pair scopes
   896                     ((if max_genuine > 0 then [false] else []) @
   897                      (if max_potential > 0 then [true] else [])))
   898                ([], donno)
   899         val _ = Unsynchronized.change generated_problems (append problems)
   900         val _ = Unsynchronized.change generated_scopes (append scopes)
   901         val _ =
   902           if j + 1 = n then
   903             let
   904               val (unsound_problems, sound_problems) =
   905                 List.partition (#unsound o snd) (!generated_problems)
   906             in
   907               if not (null sound_problems) andalso
   908                  forall (KK.is_problem_trivially_false o fst)
   909                         sound_problems then
   910                 print_m (fn () =>
   911                     "Warning: The conjecture either trivially holds for the \
   912                     \given scopes or lies outside Nitpick's supported \
   913                     \fragment." ^
   914                     (if exists (not o KK.is_problem_trivially_false o fst)
   915                                unsound_problems then
   916                        " Only potential " ^ das_wort_model ^ "s may be found."
   917                      else
   918                        ""))
   919               else
   920                 ()
   921             end
   922           else
   923             ()
   924       in
   925         solve_any_problem (found_really_genuine, max_potential, max_genuine,
   926                            donno) true (rev problems)
   927       end
   928 
   929     fun scope_count (problems : rich_problem list) scope =
   930       length (filter (curry scopes_equivalent scope o #scope o snd) problems)
   931     fun excipit did_so_and_so =
   932       let
   933         val do_filter =
   934           if !met_potential = max_potential then filter_out (#unsound o snd)
   935           else I
   936         val total = length (!scopes)
   937         val unsat =
   938           fold (fn scope =>
   939                    case scope_count (do_filter (!generated_problems)) scope of
   940                      0 => I
   941                    | n =>
   942                      scope_count (do_filter (these (!checked_problems)))
   943                                  scope = n
   944                      ? Integer.add 1) (!generated_scopes) 0
   945       in
   946         "Nitpick " ^ did_so_and_so ^
   947         (if is_some (!checked_problems) andalso total > 0 then
   948            " " ^ string_of_int unsat ^ " of " ^ string_of_int total ^ " scope"
   949            ^ plural_s total
   950          else
   951            "") ^ "."
   952       end
   953 
   954     val (skipped, the_scopes) =
   955       all_scopes hol_ctxt binarize cards_assigns maxes_assigns iters_assigns
   956                  bitss bisim_depths mono_Ts nonmono_Ts deep_dataTs
   957                  finitizable_dataTs
   958     val _ = if skipped > 0 then
   959               print_m (fn () => "Too many scopes. Skipping " ^
   960                                 string_of_int skipped ^ " scope" ^
   961                                 plural_s skipped ^
   962                                 ". (Consider using \"mono\" or \
   963                                 \\"merge_type_vars\" to prevent this.)")
   964             else
   965               ()
   966     val _ = scopes := the_scopes
   967 
   968     fun run_batches _ _ []
   969                     (found_really_genuine, max_potential, max_genuine, donno) =
   970         if donno > 0 andalso max_genuine > 0 then
   971           (print_m (fn () => excipit "checked"); "unknown")
   972         else if max_genuine = original_max_genuine then
   973           if max_potential = original_max_potential then
   974             (print_m (fn () =>
   975                  "Nitpick found no " ^ das_wort_model ^ "." ^
   976                  (if not standard andalso likely_in_struct_induct_step then
   977                     " This suggests that the induction hypothesis might be \
   978                     \general enough to prove this subgoal."
   979                   else
   980                     "")); if skipped > 0 then "unknown" else "none")
   981           else
   982             (print_m (fn () =>
   983                  excipit ("could not find a" ^
   984                           (if max_genuine = 1 then
   985                              " better " ^ das_wort_model ^ "."
   986                            else
   987                              "ny better " ^ das_wort_model ^ "s.") ^
   988                           " It checked"));
   989              "potential")
   990         else if found_really_genuine then
   991           "genuine"
   992         else
   993           "quasi_genuine"
   994       | run_batches j n (batch :: batches) z =
   995         let val (z as (_, _, max_genuine, _)) = run_batch j n batch z in
   996           run_batches (j + 1) n (if max_genuine > 0 then batches else []) z
   997         end
   998 
   999     val batches = batch_list batch_size (!scopes)
  1000     val outcome_code =
  1001       run_batches 0 (length batches) batches
  1002                   (false, max_potential, max_genuine, 0)
  1003       handle TimeLimit.TimeOut =>
  1004              (print_m (fn () => excipit "ran out of time after checking");
  1005               if !met_potential > 0 then "potential" else "unknown")
  1006     val _ = print_v (fn () =>
  1007                 "Total time: " ^ string_from_time (Timer.checkRealTimer timer) ^
  1008                 ".")
  1009   in (outcome_code, !state_ref) end
  1010 
  1011 (* Give the inner timeout a chance. *)
  1012 val timeout_bonus = seconds 1.0
  1013 
  1014 fun pick_nits_in_term state (params as {debug, timeout, expect, ...}) auto i n
  1015                       step subst assm_ts orig_t =
  1016   let val print_m = if auto then K () else Output.urgent_message in
  1017     if getenv "KODKODI" = "" then
  1018       (* The "expect" argument is deliberately ignored if Kodkodi is missing so
  1019          that the "Nitpick_Examples" can be processed on any machine. *)
  1020       (print_m (Pretty.string_of (plazy install_kodkodi_message));
  1021        ("no_kodkodi", state))
  1022     else
  1023       let
  1024         val unknown_outcome = ("unknown", state)
  1025         val deadline = Option.map (curry Time.+ (Time.now ())) timeout
  1026         val outcome as (outcome_code, _) =
  1027           time_limit (if debug orelse is_none timeout then NONE
  1028                       else SOME (Time.+ (the timeout, timeout_bonus)))
  1029               (pick_them_nits_in_term deadline state params auto i n step subst
  1030                                       assm_ts) orig_t
  1031           handle TOO_LARGE (_, details) =>
  1032                  (print_m ("Limit reached: " ^ details ^ "."); unknown_outcome)
  1033                | TOO_SMALL (_, details) =>
  1034                  (print_m ("Limit reached: " ^ details ^ "."); unknown_outcome)
  1035                | Kodkod.SYNTAX (_, details) =>
  1036                  (print_m ("Malformed Kodkodi output: " ^ details ^ ".");
  1037                   unknown_outcome)
  1038                | TimeLimit.TimeOut =>
  1039                  (print_m "Nitpick ran out of time."; unknown_outcome)
  1040       in
  1041         if expect = "" orelse outcome_code = expect then outcome
  1042         else error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
  1043       end
  1044   end
  1045 
  1046 fun is_fixed_equation fixes
  1047                       (Const (@{const_name "=="}, _) $ Free (s, _) $ Const _) =
  1048     member (op =) fixes s
  1049   | is_fixed_equation _ _ = false
  1050 fun extract_fixed_frees ctxt (assms, t) =
  1051   let
  1052     val fixes = Variable.fixes_of ctxt |> map snd
  1053     val (subst, other_assms) =
  1054       List.partition (is_fixed_equation fixes) assms
  1055       |>> map Logic.dest_equals
  1056   in (subst, other_assms, subst_atomic subst t) end
  1057 
  1058 fun pick_nits_in_subgoal state params auto i step =
  1059   let
  1060     val ctxt = Proof.context_of state
  1061     val t = state |> Proof.raw_goal |> #goal |> prop_of
  1062   in
  1063     case Logic.count_prems t of
  1064       0 => (Output.urgent_message "No subgoal!"; ("none", state))
  1065     | n =>
  1066       let
  1067         val t = Logic.goal_params t i |> fst
  1068         val assms = map term_of (Assumption.all_assms_of ctxt)
  1069         val (subst, assms, t) = extract_fixed_frees ctxt (assms, t)
  1070       in pick_nits_in_term state params auto i n step subst assms t end
  1071   end
  1072 
  1073 end;