src/HOL/Tools/Nitpick/nitpick.ML
author wenzelm
Wed Mar 04 19:53:18 2015 +0100 (2015-03-04 ago)
changeset 59582 0fbed69ff081
parent 59432 42b7b76b37b8
child 59970 e9f73d87d904
permissions -rw-r--r--
tuned signature -- prefer qualified names;
     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 term_postprocessor = Nitpick_Model.term_postprocessor
    11 
    12   datatype mode = Auto_Try | Try | Normal | TPTP
    13 
    14   type params =
    15     {cards_assigns: (typ option * int list) list,
    16      maxes_assigns: ((string * typ) option * int list) list,
    17      iters_assigns: ((string * typ) option * int list) list,
    18      bitss: int list,
    19      bisim_depths: int list,
    20      boxes: (typ option * bool option) list,
    21      finitizes: (typ option * bool option) list,
    22      monos: (typ option * bool option) list,
    23      wfs: ((string * typ) option * bool option) list,
    24      sat_solver: string,
    25      blocking: bool,
    26      falsify: bool,
    27      debug: bool,
    28      verbose: bool,
    29      overlord: bool,
    30      spy: bool,
    31      user_axioms: bool option,
    32      assms: bool,
    33      whacks: term list,
    34      merge_type_vars: bool,
    35      binary_ints: bool option,
    36      destroy_constrs: bool,
    37      specialize: bool,
    38      star_linear_preds: bool,
    39      total_consts: bool option,
    40      needs: term list option,
    41      peephole_optim: bool,
    42      datatype_sym_break: int,
    43      kodkod_sym_break: int,
    44      timeout: Time.time,
    45      tac_timeout: Time.time,
    46      max_threads: int,
    47      show_types: bool,
    48      show_skolems: bool,
    49      show_consts: bool,
    50      evals: term list,
    51      formats: (term option * int list) list,
    52      atomss: (typ option * string list) list,
    53      max_potential: int,
    54      max_genuine: int,
    55      check_potential: bool,
    56      check_genuine: bool,
    57      batch_size: int,
    58      expect: string}
    59 
    60   val genuineN : string
    61   val quasi_genuineN : string
    62   val potentialN : string
    63   val noneN : string
    64   val unknownN : string
    65   val register_frac_type : string -> (string * string) list -> theory -> theory
    66   val unregister_frac_type : string -> theory -> theory
    67   val register_codatatype : typ -> string -> (string * typ) list -> theory ->
    68     theory
    69   val unregister_codatatype : typ -> theory -> theory
    70   val register_term_postprocessor :
    71     typ -> term_postprocessor -> theory -> theory
    72   val unregister_term_postprocessor : typ -> theory -> theory
    73   val pick_nits_in_term :
    74     Proof.state -> params -> mode -> int -> int -> int -> (term * term) list
    75     -> term list -> term list -> term -> string * string list
    76   val pick_nits_in_subgoal :
    77     Proof.state -> params -> mode -> int -> int -> string * string list
    78 end;
    79 
    80 structure Nitpick : NITPICK =
    81 struct
    82 
    83 open Nitpick_Util
    84 open Nitpick_HOL
    85 open Nitpick_Preproc
    86 open Nitpick_Mono
    87 open Nitpick_Scope
    88 open Nitpick_Peephole
    89 open Nitpick_Rep
    90 open Nitpick_Nut
    91 open Nitpick_Kodkod
    92 open Nitpick_Model
    93 
    94 structure KK = Kodkod
    95 
    96 datatype mode = Auto_Try | Try | Normal | TPTP
    97 
    98 fun is_mode_nt mode = (mode = Normal orelse mode = TPTP)
    99 
   100 type params =
   101   {cards_assigns: (typ option * int list) list,
   102    maxes_assigns: ((string * typ) option * int list) list,
   103    iters_assigns: ((string * typ) option * int list) list,
   104    bitss: int list,
   105    bisim_depths: int list,
   106    boxes: (typ option * bool option) list,
   107    finitizes: (typ option * bool option) list,
   108    monos: (typ option * bool option) list,
   109    wfs: ((string * typ) option * bool option) list,
   110    sat_solver: string,
   111    blocking: bool,
   112    falsify: bool,
   113    debug: bool,
   114    verbose: bool,
   115    overlord: bool,
   116    spy: bool,
   117    user_axioms: bool option,
   118    assms: bool,
   119    whacks: term list,
   120    merge_type_vars: bool,
   121    binary_ints: bool option,
   122    destroy_constrs: bool,
   123    specialize: bool,
   124    star_linear_preds: bool,
   125    total_consts: bool option,
   126    needs: term list option,
   127    peephole_optim: bool,
   128    datatype_sym_break: int,
   129    kodkod_sym_break: int,
   130    timeout: Time.time,
   131    tac_timeout: Time.time,
   132    max_threads: int,
   133    show_types: bool,
   134    show_skolems: bool,
   135    show_consts: bool,
   136    evals: term list,
   137    formats: (term option * int list) list,
   138    atomss: (typ option * string list) list,
   139    max_potential: int,
   140    max_genuine: int,
   141    check_potential: bool,
   142    check_genuine: bool,
   143    batch_size: int,
   144    expect: string}
   145 
   146 val genuineN = "genuine"
   147 val quasi_genuineN = "quasi_genuine"
   148 val potentialN = "potential"
   149 val noneN = "none"
   150 val unknownN = "unknown"
   151 
   152 (* TODO: eliminate these historical aliases *)
   153 val register_frac_type = Nitpick_HOL.register_frac_type_global
   154 val unregister_frac_type = Nitpick_HOL.unregister_frac_type_global
   155 val register_codatatype = Nitpick_HOL.register_codatatype_global
   156 val unregister_codatatype = Nitpick_HOL.unregister_codatatype_global
   157 val register_term_postprocessor =
   158   Nitpick_Model.register_term_postprocessor_global
   159 val unregister_term_postprocessor =
   160   Nitpick_Model.unregister_term_postprocessor_global
   161 
   162 type problem_extension =
   163   {free_names: nut list,
   164    sel_names: nut list,
   165    nonsel_names: nut list,
   166    rel_table: nut NameTable.table,
   167    unsound: bool,
   168    scope: scope}
   169 
   170 type rich_problem = KK.problem * problem_extension
   171 
   172 fun pretties_for_formulas _ _ [] = []
   173   | pretties_for_formulas ctxt s ts =
   174     [Pretty.str (s ^ plural_s_for_list ts ^ ":"),
   175      Pretty.indent indent_size (Pretty.chunks
   176          (map2 (fn j => fn t =>
   177                    Pretty.block [t |> shorten_names_in_term
   178                                    |> Syntax.pretty_term ctxt,
   179                                  Pretty.str (if j = 1 then "." else ";")])
   180                (length ts downto 1) ts))]
   181 
   182 val isabelle_wrong_message =
   183   "Something appears to be wrong with your Isabelle installation."
   184 val java_not_found_message =
   185   "Java could not be launched. " ^ isabelle_wrong_message
   186 val java_too_old_message =
   187   "The Java version is too old. " ^ isabelle_wrong_message
   188 val kodkodi_not_installed_message =
   189   "Nitpick requires the external Java program Kodkodi."
   190 val kodkodi_too_old_message = "The installed Kodkodi version is too old."
   191 
   192 val max_unsound_delay_ms = 200
   193 val max_unsound_delay_percent = 2
   194 
   195 fun unsound_delay_for_timeout timeout =
   196   Int.max (0, Int.min (max_unsound_delay_ms,
   197                        Time.toMilliseconds timeout
   198                        * max_unsound_delay_percent div 100))
   199 
   200 fun none_true assigns = forall (not_equal (SOME true) o snd) assigns
   201 
   202 fun has_lonely_bool_var (@{const Pure.conjunction}
   203                          $ (@{const Trueprop} $ Free _) $ _) = true
   204   | has_lonely_bool_var _ = false
   205 
   206 val syntactic_sorts =
   207   @{sort "{default,zero,one,plus,minus,uminus,times,inverse,abs,sgn,ord,equal}"} @
   208   @{sort numeral}
   209 
   210 fun has_tfree_syntactic_sort (TFree (_, S as _ :: _)) =
   211     subset (op =) (S, syntactic_sorts)
   212   | has_tfree_syntactic_sort _ = false
   213 val has_syntactic_sorts = exists_type (exists_subtype has_tfree_syntactic_sort)
   214 
   215 fun plazy f = Pretty.para (f ())
   216 
   217 fun pick_them_nits_in_term deadline state (params : params) mode i n step
   218                            subst def_assm_ts nondef_assm_ts orig_t =
   219   let
   220     val timer = Timer.startRealTimer ()
   221     val thy = Proof.theory_of state
   222     val ctxt = Proof.context_of state
   223     val keywords = Thy_Header.get_keywords thy
   224 (* FIXME: reintroduce code before new release:
   225 
   226     val nitpick_thy = Thy_Info.get_theory "Nitpick"
   227     val _ = Theory.subthy (nitpick_thy, thy) orelse
   228             error "You must import the theory \"Nitpick\" to use Nitpick"
   229 *)
   230     val {cards_assigns, maxes_assigns, iters_assigns, bitss, bisim_depths,
   231          boxes, finitizes, monos, wfs, sat_solver, falsify, debug, verbose,
   232          overlord, spy, user_axioms, assms, whacks, merge_type_vars,
   233          binary_ints, destroy_constrs, specialize, star_linear_preds,
   234          total_consts, needs, peephole_optim, datatype_sym_break,
   235          kodkod_sym_break, tac_timeout, max_threads, show_types, show_skolems,
   236          show_consts, evals, formats, atomss, max_potential, max_genuine,
   237          check_potential, check_genuine, batch_size, ...} = params
   238     val outcome = Synchronized.var "Nitpick.outcome" (Queue.empty: string Queue.T)
   239     fun pprint print prt =
   240       if mode = Auto_Try then
   241         Synchronized.change outcome (Queue.enqueue (Pretty.string_of prt))
   242       else
   243         print (Pretty.string_of prt)
   244     val pprint_a = pprint writeln
   245     fun pprint_nt f = () |> is_mode_nt mode ? pprint writeln o f
   246     fun pprint_v f = () |> verbose ? pprint writeln o f
   247     fun pprint_d f = () |> debug ? pprint tracing o f
   248     val print = pprint writeln o Pretty.para
   249     fun print_t f = () |> mode = TPTP ? print o f
   250 (*
   251     val print_g = pprint tracing o Pretty.str
   252 *)
   253     val print_nt = pprint_nt o K o plazy
   254     val print_v = pprint_v o K o plazy
   255 
   256     fun check_deadline () =
   257       if Time.compare (Time.now (), deadline) <> LESS then
   258         raise TimeLimit.TimeOut
   259       else
   260         ()
   261 
   262     val (def_assm_ts, nondef_assm_ts) =
   263       if assms orelse mode <> Normal then (def_assm_ts, nondef_assm_ts)
   264       else ([], [])
   265     val _ =
   266       if step = 0 then
   267         print_nt (fn () => "Nitpicking formula...")
   268       else
   269         pprint_nt (fn () => Pretty.chunks (
   270             pretties_for_formulas ctxt ("Nitpicking " ^
   271                 (if i <> 1 orelse n <> 1 then
   272                    "subgoal " ^ string_of_int i ^ " of " ^ string_of_int n
   273                  else
   274                    "goal")) [Logic.list_implies (nondef_assm_ts, orig_t)]))
   275     val _ = spying spy (fn () => (state, i, "starting " ^ @{make_string} mode ^ " mode"))
   276     val _ = print_v (enclose "Timestamp: " "." o Date.fmt "%H:%M:%S"
   277                      o Date.fromTimeLocal o Time.now)
   278     val neg_t = if falsify then Logic.mk_implies (orig_t, @{prop False})
   279                 else orig_t
   280     val conj_ts = neg_t :: def_assm_ts @ nondef_assm_ts @ evals @ these needs
   281     val tfree_table =
   282       if merge_type_vars then merged_type_var_table_for_terms thy conj_ts
   283       else []
   284     val merge_tfrees = merge_type_vars_in_term thy merge_type_vars tfree_table
   285     val neg_t = neg_t |> merge_tfrees
   286     val def_assm_ts = def_assm_ts |> map merge_tfrees
   287     val nondef_assm_ts = nondef_assm_ts |> map merge_tfrees
   288     val evals = evals |> map merge_tfrees
   289     val needs = needs |> Option.map (map merge_tfrees)
   290     val conj_ts = neg_t :: def_assm_ts @ nondef_assm_ts @ evals @ these needs
   291     val original_max_potential = max_potential
   292     val original_max_genuine = max_genuine
   293     val max_bisim_depth = fold Integer.max bisim_depths ~1
   294     val case_names = case_const_names ctxt
   295     val defs = def_assm_ts @ all_defs_of thy subst
   296     val nondefs = all_nondefs_of ctxt subst
   297     val def_tables = const_def_tables ctxt subst defs
   298     val nondef_table = const_nondef_table nondefs
   299     val simp_table = Unsynchronized.ref (const_simp_table ctxt subst)
   300     val psimp_table = const_psimp_table ctxt subst
   301     val choice_spec_table = const_choice_spec_table ctxt subst
   302     val nondefs =
   303       nondefs |> filter_out (is_choice_spec_axiom thy choice_spec_table)
   304     val intro_table = inductive_intro_table ctxt subst def_tables
   305     val ground_thm_table = ground_theorem_table thy
   306     val ersatz_table = ersatz_table ctxt
   307     val hol_ctxt as {wf_cache, ...} =
   308       {thy = thy, ctxt = ctxt, max_bisim_depth = max_bisim_depth, boxes = boxes,
   309        wfs = wfs, user_axioms = user_axioms, debug = debug, whacks = whacks,
   310        binary_ints = binary_ints, destroy_constrs = destroy_constrs,
   311        specialize = specialize, star_linear_preds = star_linear_preds,
   312        total_consts = total_consts, needs = needs, tac_timeout = tac_timeout,
   313        evals = evals, case_names = case_names, def_tables = def_tables,
   314        nondef_table = nondef_table, nondefs = nondefs, simp_table = simp_table,
   315        psimp_table = psimp_table, choice_spec_table = choice_spec_table,
   316        intro_table = intro_table, ground_thm_table = ground_thm_table,
   317        ersatz_table = ersatz_table, skolems = Unsynchronized.ref [],
   318        special_funs = Unsynchronized.ref [],
   319        unrolled_preds = Unsynchronized.ref [], wf_cache = Unsynchronized.ref [],
   320        constr_cache = Unsynchronized.ref []}
   321     val pseudo_frees = []
   322     val real_frees = fold Term.add_frees conj_ts []
   323     val _ = null (fold Term.add_tvars conj_ts []) orelse
   324             error "Nitpick cannot handle goals with schematic type variables."
   325     val (nondef_ts, def_ts, need_ts, got_all_mono_user_axioms,
   326          no_poly_user_axioms, binarize) =
   327       preprocess_formulas hol_ctxt nondef_assm_ts neg_t
   328     val got_all_user_axioms =
   329       got_all_mono_user_axioms andalso no_poly_user_axioms
   330 
   331     fun print_wf (x, (gfp, wf)) =
   332       pprint_nt (fn () => Pretty.blk (0,
   333           Pretty.text ("The " ^ (if gfp then "co" else "") ^ "inductive predicate \"")
   334           @ Syntax.pretty_term ctxt (Const x) ::
   335           Pretty.text (if wf then
   336                    "\" was proved well-founded. Nitpick can compute it \
   337                    \efficiently."
   338                  else
   339                    "\" could not be proved well-founded. Nitpick might need to \
   340                    \unroll it.")))
   341     val _ = if verbose then List.app print_wf (!wf_cache) else ()
   342     val das_wort_formula = if falsify then "Negated conjecture" else "Formula"
   343     val _ =
   344       pprint_d (fn () => Pretty.chunks
   345           (pretties_for_formulas ctxt das_wort_formula [hd nondef_ts] @
   346            pretties_for_formulas ctxt "Relevant definitional axiom" def_ts @
   347            pretties_for_formulas ctxt "Relevant nondefinitional axiom"
   348                                  (tl nondef_ts)))
   349     val _ = List.app (ignore o Term.type_of) (nondef_ts @ def_ts)
   350             handle TYPE (_, Ts, ts) =>
   351                    raise TYPE ("Nitpick.pick_them_nits_in_term", Ts, ts)
   352 
   353     val nondef_us = nondef_ts |> map (nut_from_term hol_ctxt Eq)
   354     val def_us = def_ts |> map (nut_from_term hol_ctxt DefEq)
   355     val need_us = need_ts |> map (nut_from_term hol_ctxt Eq)
   356     val (free_names, const_names) =
   357       fold add_free_and_const_names (nondef_us @ def_us @ need_us) ([], [])
   358     val (sel_names, nonsel_names) =
   359       List.partition (is_sel o nickname_of) const_names
   360     val sound_finitizes = none_true finitizes
   361 (*
   362     val _ =
   363       List.app (print_g o string_for_nut ctxt) (nondef_us @ def_us @ need_us)
   364 *)
   365 
   366     val unique_scope = forall (curry (op =) 1 o length o snd) cards_assigns
   367     fun monotonicity_message Ts extra =
   368       let val pretties = map (pretty_maybe_quote keywords o pretty_for_type ctxt) Ts in
   369         Pretty.blk (0,
   370           Pretty.text ("The type" ^ plural_s_for_list pretties ^ " ") @
   371           pretty_serial_commas "and" pretties @
   372           Pretty.text (" " ^
   373                  (if none_true monos then
   374                     "passed the monotonicity test"
   375                   else
   376                     (if length pretties = 1 then "is" else "are") ^
   377                     " considered monotonic") ^
   378                  ". " ^ extra))
   379       end
   380     fun is_type_fundamentally_monotonic T =
   381       (is_data_type ctxt T andalso not (is_quot_type ctxt T) andalso
   382        (not (is_pure_typedef ctxt T) orelse is_univ_typedef ctxt T)) orelse
   383       is_number_type ctxt T orelse is_bit_type T
   384     fun is_type_actually_monotonic T =
   385       TimeLimit.timeLimit tac_timeout (formulas_monotonic hol_ctxt binarize T)
   386                           (nondef_ts, def_ts)
   387       handle TimeLimit.TimeOut => false
   388     fun is_type_kind_of_monotonic T =
   389       case triple_lookup (type_match thy) monos T of
   390         SOME (SOME false) => false
   391       | _ => is_type_actually_monotonic T
   392     fun is_type_monotonic T =
   393       unique_scope orelse
   394       case triple_lookup (type_match thy) monos T of
   395         SOME (SOME b) => b
   396       | _ => is_type_fundamentally_monotonic T orelse
   397              is_type_actually_monotonic T
   398     fun is_deep_data_type_finitizable T =
   399       triple_lookup (type_match thy) finitizes T = SOME (SOME true)
   400     fun is_shallow_data_type_finitizable (T as Type (@{type_name fun_box}, _)) =
   401         is_type_kind_of_monotonic T
   402       | is_shallow_data_type_finitizable T =
   403         case triple_lookup (type_match thy) finitizes T of
   404           SOME (SOME b) => b
   405         | _ => is_type_kind_of_monotonic T
   406     fun is_data_type_deep T =
   407       T = @{typ unit} orelse T = nat_T orelse is_word_type T orelse
   408       exists (curry (op =) T o domain_type o type_of) sel_names
   409     val all_Ts = ground_types_in_terms hol_ctxt binarize (nondef_ts @ def_ts)
   410                  |> sort Term_Ord.typ_ord
   411     val _ =
   412       if verbose andalso binary_ints = SOME true andalso
   413          exists (member (op =) [nat_T, int_T]) all_Ts then
   414         print_v (K "The option \"binary_ints\" will be ignored because of the \
   415                    \presence of rationals, reals, \"Suc\", \"gcd\", or \"lcm\" \
   416                    \in the problem.")
   417       else
   418         ()
   419     val (mono_Ts, nonmono_Ts) = List.partition is_type_monotonic all_Ts
   420     val _ =
   421       if verbose andalso not unique_scope then
   422         case filter_out is_type_fundamentally_monotonic mono_Ts of
   423           [] => ()
   424         | interesting_mono_Ts =>
   425           pprint_v (K (monotonicity_message interesting_mono_Ts
   426                           "Nitpick might be able to skip some scopes."))
   427       else
   428         ()
   429     val (deep_dataTs, shallow_dataTs) =
   430       all_Ts |> filter (is_data_type ctxt)
   431              |> List.partition is_data_type_deep
   432     val finitizable_dataTs =
   433       (deep_dataTs |> filter_out (is_finite_type hol_ctxt)
   434                    |> filter is_deep_data_type_finitizable) @
   435       (shallow_dataTs |> filter_out (is_finite_type hol_ctxt)
   436                       |> filter is_shallow_data_type_finitizable)
   437     val _ =
   438       if verbose andalso not (null finitizable_dataTs) then
   439         pprint_v (K (monotonicity_message finitizable_dataTs
   440                          "Nitpick can use a more precise finite encoding."))
   441       else
   442         ()
   443 (*
   444     val _ = print_g "Monotonic types:"
   445     val _ = List.app (print_g o string_for_type ctxt) mono_Ts
   446     val _ = print_g "Nonmonotonic types:"
   447     val _ = List.app (print_g o string_for_type ctxt) nonmono_Ts
   448 *)
   449 
   450     val incremental = Int.max (max_potential, max_genuine) >= 2
   451     val actual_sat_solver =
   452       if sat_solver <> "smart" then
   453         if incremental andalso
   454            not (member (op =) (Kodkod_SAT.configured_sat_solvers true)
   455                        sat_solver) then
   456           (print_nt (K ("An incremental SAT solver is required: \"SAT4J\" will \
   457                         \be used instead of " ^ quote sat_solver ^ "."));
   458            "SAT4J")
   459         else
   460           sat_solver
   461       else
   462         Kodkod_SAT.smart_sat_solver_name incremental
   463     val _ =
   464       if sat_solver = "smart" then
   465         print_v (fn () =>
   466             "Using SAT solver " ^ quote actual_sat_solver ^ ". The following" ^
   467             (if incremental then " incremental " else " ") ^
   468             "solvers are configured: " ^
   469             commas_quote (Kodkod_SAT.configured_sat_solvers incremental) ^ ".")
   470       else
   471         ()
   472 
   473     val too_big_scopes = Unsynchronized.ref []
   474 
   475     fun problem_for_scope unsound
   476             (scope as {card_assigns, bits, bisim_depth, data_types, ofs, ...}) =
   477       let
   478         val _ = not (exists (fn other => scope_less_eq other scope)
   479                             (!too_big_scopes)) orelse
   480                 raise TOO_LARGE ("Nitpick.pick_them_nits_in_term.\
   481                                  \problem_for_scope", "too large scope")
   482 (*
   483         val _ = print_g "Offsets:"
   484         val _ = List.app (fn (T, j0) =>
   485                              print_g (string_for_type ctxt T ^ " = " ^
   486                                     string_of_int j0))
   487                          (Typtab.dest ofs)
   488 *)
   489         val effective_total_consts =
   490           case total_consts of
   491             SOME b => b
   492           | NONE => forall (is_exact_type data_types true) all_Ts
   493         val main_j0 = offset_of_type ofs bool_T
   494         val (nat_card, nat_j0) = spec_of_type scope nat_T
   495         val (int_card, int_j0) = spec_of_type scope int_T
   496         val _ = (nat_j0 = main_j0 andalso int_j0 = main_j0) orelse
   497                 raise BAD ("Nitpick.pick_them_nits_in_term.problem_for_scope",
   498                            "bad offsets")
   499         val kk = kodkod_constrs peephole_optim nat_card int_card main_j0
   500         val (free_names, rep_table) =
   501           choose_reps_for_free_vars scope pseudo_frees free_names
   502                                     NameTable.empty
   503         val (sel_names, rep_table) = choose_reps_for_all_sels scope rep_table
   504         val (nonsel_names, rep_table) =
   505           choose_reps_for_consts scope effective_total_consts nonsel_names
   506                                  rep_table
   507         val (guiltiest_party, min_highest_arity) =
   508           NameTable.fold (fn (name, R) => fn (s, n) =>
   509                              let val n' = arity_of_rep R in
   510                                if n' > n then (nickname_of name, n') else (s, n)
   511                              end) rep_table ("", 1)
   512         val min_univ_card =
   513           NameTable.fold (Integer.max o min_univ_card_of_rep o snd) rep_table
   514                          (univ_card nat_card int_card main_j0 [] KK.True)
   515         val _ = check_arity guiltiest_party min_univ_card min_highest_arity
   516 
   517         val def_us =
   518           def_us |> map (choose_reps_in_nut scope unsound rep_table true)
   519         val nondef_us =
   520           nondef_us |> map (choose_reps_in_nut scope unsound rep_table false)
   521         val need_us =
   522           need_us |> map (choose_reps_in_nut scope unsound rep_table false)
   523 (*
   524         val _ = List.app (print_g o string_for_nut ctxt)
   525                          (free_names @ sel_names @ nonsel_names @
   526                           nondef_us @ def_us @ need_us)
   527 *)
   528         val (free_rels, pool, rel_table) =
   529           rename_free_vars free_names initial_pool NameTable.empty
   530         val (sel_rels, pool, rel_table) =
   531           rename_free_vars sel_names pool rel_table
   532         val (other_rels, pool, rel_table) =
   533           rename_free_vars nonsel_names pool rel_table
   534         val nondef_us = nondef_us |> map (rename_vars_in_nut pool rel_table)
   535         val def_us = def_us |> map (rename_vars_in_nut pool rel_table)
   536         val need_us = need_us |> map (rename_vars_in_nut pool rel_table)
   537         val nondef_fs = map (kodkod_formula_from_nut ofs kk) nondef_us
   538         val def_fs = map (kodkod_formula_from_nut ofs kk) def_us
   539         val formula = fold (fold s_and) [def_fs, nondef_fs] KK.True
   540         val comment = (if unsound then "unsound" else "sound") ^ "\n" ^
   541                       Print_Mode.setmp [] multiline_string_for_scope scope
   542         val kodkod_sat_solver =
   543           Kodkod_SAT.sat_solver_spec actual_sat_solver |> snd
   544         val bit_width = if bits = 0 then 16 else bits + 1
   545         val delay =
   546           if unsound then
   547             unsound_delay_for_timeout (Time.- (deadline, Time.now ()))
   548           else
   549             0
   550         val settings = [("solver", commas_quote kodkod_sat_solver),
   551                         ("bit_width", string_of_int bit_width),
   552                         ("symmetry_breaking", string_of_int kodkod_sym_break),
   553                         ("sharing", "3"),
   554                         ("flatten", "false"),
   555                         ("delay", signed_string_of_int delay)]
   556         val plain_rels = free_rels @ other_rels
   557         val plain_bounds = map (bound_for_plain_rel ctxt debug) plain_rels
   558         val plain_axioms = map (declarative_axiom_for_plain_rel kk) plain_rels
   559         val need_vals =
   560           map (fn dtype as {typ, ...} =>
   561                   (typ, needed_values_for_data_type need_us ofs dtype))
   562               data_types
   563         val sel_bounds =
   564           map (bound_for_sel_rel ctxt debug need_vals data_types) sel_rels
   565         val dtype_axioms =
   566           declarative_axioms_for_data_types hol_ctxt binarize need_us need_vals
   567               datatype_sym_break bits ofs kk rel_table data_types
   568         val declarative_axioms = plain_axioms @ dtype_axioms
   569         val univ_card = Int.max (univ_card nat_card int_card main_j0
   570                                      (plain_bounds @ sel_bounds) formula,
   571                                  main_j0 |> bits > 0 ? Integer.add (bits + 1))
   572         val (built_in_bounds, built_in_axioms) =
   573           bounds_and_axioms_for_built_in_rels_in_formulas debug univ_card
   574               nat_card int_card main_j0 (formula :: declarative_axioms)
   575         val bounds = built_in_bounds @ plain_bounds @ sel_bounds
   576                      |> not debug ? merge_bounds
   577         val axioms = built_in_axioms @ declarative_axioms
   578         val highest_arity =
   579           fold Integer.max (map (fst o fst) (maps fst bounds)) 0
   580         val formula = fold_rev s_and axioms formula
   581         val _ = if bits = 0 then () else check_bits bits formula
   582         val _ = if formula = KK.False then ()
   583                 else check_arity "" univ_card highest_arity
   584       in
   585         SOME ({comment = comment, settings = settings, univ_card = univ_card,
   586                tuple_assigns = [], bounds = bounds,
   587                int_bounds = if bits = 0 then sequential_int_bounds univ_card
   588                             else pow_of_two_int_bounds bits main_j0,
   589                expr_assigns = [], formula = formula},
   590               {free_names = free_names, sel_names = sel_names,
   591                nonsel_names = nonsel_names, rel_table = rel_table,
   592                unsound = unsound, scope = scope})
   593       end
   594       handle TOO_LARGE (loc, msg) =>
   595              if loc = "Nitpick_Kodkod.check_arity" andalso
   596                 not (Typtab.is_empty ofs) then
   597                problem_for_scope unsound
   598                    {hol_ctxt = hol_ctxt, binarize = binarize,
   599                     card_assigns = card_assigns, bits = bits,
   600                     bisim_depth = bisim_depth, data_types = data_types,
   601                     ofs = Typtab.empty}
   602              else if loc = "Nitpick.pick_them_nits_in_term.\
   603                            \problem_for_scope" then
   604                NONE
   605              else
   606                (Unsynchronized.change too_big_scopes (cons scope);
   607                 print_v (fn () =>
   608                     "Limit reached: " ^ msg ^ ". Skipping " ^
   609                     (if unsound then "potential component of " else "") ^
   610                     "scope.");
   611                 NONE)
   612            | TOO_SMALL (_, msg) =>
   613              (print_v (fn () =>
   614                   "Limit reached: " ^ msg ^ ". Skipping " ^
   615                   (if unsound then "potential component of " else "") ^
   616                   "scope.");
   617               NONE)
   618 
   619     val das_wort_model = if falsify then "counterexample" else "model"
   620 
   621     val scopes = Unsynchronized.ref []
   622     val generated_scopes = Unsynchronized.ref []
   623     val generated_problems = Unsynchronized.ref ([] : rich_problem list)
   624     val checked_problems = Unsynchronized.ref (SOME [])
   625     val met_potential = Unsynchronized.ref 0
   626 
   627     fun update_checked_problems problems =
   628       List.app (Unsynchronized.change checked_problems o Option.map o cons
   629                 o nth problems)
   630     fun show_kodkod_warning "" = ()
   631       | show_kodkod_warning s = print_nt (fn () => "Kodkod warning: " ^ s ^ ".")
   632 
   633     fun print_and_check_model genuine bounds
   634             ({free_names, sel_names, nonsel_names, rel_table, scope, ...}
   635              : problem_extension) =
   636       let
   637         val _ =
   638           print_t (fn () =>
   639                "% SZS status " ^
   640                (if genuine then
   641                   if falsify then "CounterSatisfiable" else "Satisfiable"
   642                 else
   643                   "Unknown") ^ "\n" ^
   644                "% SZS output start FiniteModel")
   645         val (reconstructed_model, codatatypes_ok) =
   646           reconstruct_hol_model
   647               {show_types = show_types, show_skolems = show_skolems,
   648                show_consts = show_consts}
   649               scope formats atomss real_frees pseudo_frees free_names sel_names
   650               nonsel_names rel_table bounds
   651         val genuine_means_genuine =
   652           got_all_user_axioms andalso none_true wfs andalso
   653           sound_finitizes andalso total_consts <> SOME true andalso
   654           codatatypes_ok
   655         fun assms_prop () =
   656           Logic.mk_conjunction_list (neg_t :: def_assm_ts @ nondef_assm_ts)
   657       in
   658         (pprint_a (Pretty.chunks
   659              [Pretty.blk (0,
   660                   (Pretty.text ((if mode = Auto_Try then "Auto " else "") ^
   661                           "Nitpick found a" ^
   662                           (if not genuine then " potentially spurious "
   663                            else if genuine_means_genuine then " "
   664                            else " quasi genuine ") ^ das_wort_model) @
   665                    (case pretties_for_scope scope verbose of
   666                       [] => []
   667                     | pretties => Pretty.text " for " @ pretties) @
   668                    [Pretty.str ":", Pretty.fbrk])),
   669               Pretty.indent indent_size reconstructed_model]);
   670          print_t (K "% SZS output end FiniteModel");
   671          if genuine then
   672            (if check_genuine then
   673               case prove_hol_model scope tac_timeout free_names sel_names
   674                                    rel_table bounds (assms_prop ()) of
   675                 SOME true =>
   676                 print ("Confirmation by \"auto\": The above " ^
   677                        das_wort_model ^ " is really genuine.")
   678               | SOME false =>
   679                 if genuine_means_genuine then
   680                   error ("A supposedly genuine " ^ das_wort_model ^ " was \
   681                          \shown to be spurious by \"auto\".\nThis should never \
   682                          \happen.\nPlease send a bug report to blanchet\
   683                          \te@in.tum.de.")
   684                  else
   685                    print ("Refutation by \"auto\": The above " ^
   686                           das_wort_model ^ " is spurious.")
   687                | NONE => print "No confirmation by \"auto\"."
   688             else
   689               ();
   690             if has_lonely_bool_var orig_t then
   691               print "Hint: Maybe you forgot a colon after the lemma's name?"
   692             else if has_syntactic_sorts orig_t then
   693               print "Hint: Maybe you forgot a type constraint?"
   694             else
   695               ();
   696             if not genuine_means_genuine then
   697               if no_poly_user_axioms then
   698                 let
   699                   val options =
   700                     [] |> not got_all_mono_user_axioms
   701                           ? cons ("user_axioms", "\"true\"")
   702                        |> not (none_true wfs)
   703                           ? cons ("wf", "\"smart\" or \"false\"")
   704                        |> not sound_finitizes
   705                           ? cons ("finitize", "\"smart\" or \"false\"")
   706                        |> total_consts = SOME true
   707                           ? cons ("total_consts", "\"smart\" or \"false\"")
   708                        |> not codatatypes_ok
   709                           ? cons ("bisim_depth", "a nonnegative value")
   710                   val ss =
   711                     map (fn (name, value) => quote name ^ " set to " ^ value)
   712                         options
   713                 in
   714                   print ("Try again with " ^
   715                          space_implode " " (serial_commas "and" ss) ^
   716                          " to confirm that the " ^ das_wort_model ^
   717                          " is genuine.")
   718                 end
   719               else
   720                 print ("Nitpick is unable to guarantee the authenticity of \
   721                        \the " ^ das_wort_model ^ " in the presence of \
   722                        \polymorphic axioms.")
   723             else
   724               ();
   725             NONE)
   726          else
   727            if not genuine then
   728              (Unsynchronized.inc met_potential;
   729               if check_potential then
   730                 let
   731                   val status = prove_hol_model scope tac_timeout free_names
   732                                                sel_names rel_table bounds
   733                                                (assms_prop ())
   734                 in
   735                   (case status of
   736                      SOME true => print ("Confirmation by \"auto\": The \
   737                                          \above " ^ das_wort_model ^
   738                                          " is genuine.")
   739                    | SOME false => print ("Refutation by \"auto\": The above " ^
   740                                           das_wort_model ^ " is spurious.")
   741                    | NONE => print "No confirmation by \"auto\".");
   742                   status
   743                 end
   744               else
   745                 NONE)
   746            else
   747              NONE)
   748         |> pair genuine_means_genuine
   749       end
   750     fun solve_any_problem (found_really_genuine, max_potential, max_genuine,
   751                            donno) first_time problems =
   752       let
   753         val max_potential = Int.max (0, max_potential)
   754         val max_genuine = Int.max (0, max_genuine)
   755         fun print_and_check genuine (j, bounds) =
   756           print_and_check_model genuine bounds (snd (nth problems j))
   757         val max_solutions = max_potential + max_genuine
   758                             |> not incremental ? Integer.min 1
   759       in
   760         if max_solutions <= 0 then
   761           (found_really_genuine, 0, 0, donno)
   762         else
   763           case KK.solve_any_problem debug overlord deadline max_threads
   764                                     max_solutions (map fst problems) of
   765             KK.JavaNotFound =>
   766             (print_nt (K java_not_found_message);
   767              (found_really_genuine, max_potential, max_genuine, donno + 1))
   768           | KK.JavaTooOld =>
   769             (print_nt (K java_too_old_message);
   770              (found_really_genuine, max_potential, max_genuine, donno + 1))
   771           | KK.KodkodiNotInstalled =>
   772             (print_nt (K kodkodi_not_installed_message);
   773              (found_really_genuine, max_potential, max_genuine, donno + 1))
   774           | KK.KodkodiTooOld =>
   775             (print_nt (K kodkodi_too_old_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_nt (K "The scope specification is inconsistent.")
   863           else if verbose then
   864             pprint_nt (fn () => Pretty.chunks
   865                 [Pretty.blk (0,
   866                      Pretty.text ((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_nt (fn () =>
   911                     "Warning: The conjecture " ^
   912                     (if falsify then "either trivially holds"
   913                      else "is either trivially unsatisfiable") ^
   914                     " for the given scopes or lies outside Nitpick's supported \
   915                     \fragment." ^
   916                     (if exists (not o KK.is_problem_trivially_false o fst)
   917                                unsound_problems then
   918                        " Only potentially spurious " ^ das_wort_model ^
   919                        "s may be found."
   920                      else
   921                        ""))
   922               else
   923                 ()
   924             end
   925           else
   926             ()
   927       in
   928         solve_any_problem (found_really_genuine, max_potential, max_genuine,
   929                            donno) true (rev problems)
   930       end
   931 
   932     fun scope_count (problems : rich_problem list) scope =
   933       length (filter (curry scopes_equivalent scope o #scope o snd) problems)
   934     fun excipit did_so_and_so =
   935       let
   936         val do_filter =
   937           if !met_potential = max_potential then filter_out (#unsound o snd)
   938           else I
   939         val total = length (!scopes)
   940         val unsat =
   941           fold (fn scope =>
   942                    case scope_count (do_filter (!generated_problems)) scope of
   943                      0 => I
   944                    | n =>
   945                      scope_count (do_filter (these (!checked_problems)))
   946                                  scope = n
   947                      ? Integer.add 1) (!generated_scopes) 0
   948       in
   949         (if mode = TPTP then "% SZS status Unknown\n" else "") ^
   950         "Nitpick " ^ did_so_and_so ^
   951         (if is_some (!checked_problems) andalso total > 0 then
   952            " " ^ string_of_int unsat ^ " of " ^ string_of_int total ^ " scope"
   953            ^ plural_s total
   954          else
   955            "") ^ "."
   956       end
   957 
   958     val (skipped, the_scopes) =
   959       all_scopes hol_ctxt binarize cards_assigns maxes_assigns iters_assigns
   960                  bitss bisim_depths mono_Ts nonmono_Ts deep_dataTs
   961                  finitizable_dataTs
   962     val _ = if skipped > 0 then
   963               print_nt (fn () => "Too many scopes. Skipping " ^
   964                                  string_of_int skipped ^ " scope" ^
   965                                  plural_s skipped ^
   966                                  ". (Consider using \"mono\" or \
   967                                  \\"merge_type_vars\" to prevent this.)")
   968             else
   969               ()
   970     val _ = scopes := the_scopes
   971 
   972     fun run_batches _ _ []
   973                     (found_really_genuine, max_potential, max_genuine, donno) =
   974         if donno > 0 andalso max_genuine > 0 then
   975           (print_nt (fn () => excipit "checked"); unknownN)
   976         else if max_genuine = original_max_genuine then
   977           if max_potential = original_max_potential then
   978             (print_t (K "% SZS status Unknown");
   979              print_nt (fn () => "Nitpick found no " ^ das_wort_model ^ ".");
   980              if skipped > 0 then unknownN else noneN)
   981           else
   982             (print_nt (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              potentialN)
   990         else if found_really_genuine then
   991           genuineN
   992         else
   993           quasi_genuineN
   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 = chunk_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_nt (fn () => excipit "ran out of time after checking");
  1005               if !met_potential > 0 then potentialN else unknownN)
  1006     val _ = print_v (fn () =>
  1007                 "Total time: " ^ string_of_time (Timer.checkRealTimer timer) ^
  1008                 ".")
  1009     val _ = spying spy (fn () => (state, i, "outcome: " ^ outcome_code))
  1010   in (outcome_code, Queue.content (Synchronized.value outcome)) end
  1011 
  1012 (* Give the inner timeout a chance. *)
  1013 val timeout_bonus = seconds 1.0
  1014 
  1015 fun pick_nits_in_term state (params as {timeout, expect, ...}) mode i n step
  1016                       subst def_assm_ts nondef_assm_ts orig_t =
  1017   let
  1018     val print_nt = if is_mode_nt mode then writeln else K ()
  1019     val print_t = if mode = TPTP then writeln else K ()
  1020   in
  1021     if getenv "KODKODI" = "" then
  1022       (* The "expect" argument is deliberately ignored if Kodkodi is missing so
  1023          that the "Nitpick_Examples" can be processed on any machine. *)
  1024       (print_nt (Pretty.string_of (plazy (K kodkodi_not_installed_message)));
  1025        ("no_kodkodi", []))
  1026     else
  1027       let
  1028         val unknown_outcome = (unknownN, [])
  1029         val deadline = Time.+ (Time.now (), timeout)
  1030         val outcome as (outcome_code, _) =
  1031           TimeLimit.timeLimit (Time.+ (timeout, timeout_bonus))
  1032               (pick_them_nits_in_term deadline state params mode i n step subst
  1033                                       def_assm_ts nondef_assm_ts) orig_t
  1034           handle TOO_LARGE (_, details) =>
  1035                  (print_t "% SZS status Unknown";
  1036                   print_nt ("Limit reached: " ^ details ^ "."); unknown_outcome)
  1037                | TOO_SMALL (_, details) =>
  1038                  (print_t "% SZS status Unknown";
  1039                   print_nt ("Limit reached: " ^ details ^ "."); unknown_outcome)
  1040                | Kodkod.SYNTAX (_, details) =>
  1041                  (print_t "% SZS status Unknown";
  1042                   print_nt ("Malformed Kodkodi output: " ^ details ^ ".");
  1043                   unknown_outcome)
  1044                | TimeLimit.TimeOut =>
  1045                  (print_t "% SZS status TimedOut";
  1046                   print_nt "Nitpick ran out of time."; unknown_outcome)
  1047       in
  1048         if expect = "" orelse outcome_code = expect then outcome
  1049         else error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
  1050       end
  1051   end
  1052 
  1053 fun is_fixed_equation ctxt
  1054                       (Const (@{const_name Pure.eq}, _) $ Free (s, _) $ Const _) =
  1055     Variable.is_fixed ctxt s
  1056   | is_fixed_equation _ _ = false
  1057 
  1058 fun extract_fixed_frees ctxt (assms, t) =
  1059   let
  1060     val (subst, other_assms) =
  1061       List.partition (is_fixed_equation ctxt) assms
  1062       |>> map Logic.dest_equals
  1063   in (subst, other_assms, subst_atomic subst t) end
  1064 
  1065 fun pick_nits_in_subgoal state params mode i step =
  1066   let
  1067     val ctxt = Proof.context_of state
  1068     val t = state |> Proof.raw_goal |> #goal |> Thm.prop_of
  1069   in
  1070     case Logic.count_prems t of
  1071       0 => (writeln "No subgoal!"; (noneN, []))
  1072     | n =>
  1073       let
  1074         val t = Logic.goal_params t i |> fst
  1075         val assms = map Thm.term_of (Assumption.all_assms_of ctxt)
  1076         val (subst, assms, t) = extract_fixed_frees ctxt (assms, t)
  1077       in pick_nits_in_term state params mode i n step subst [] assms t end
  1078   end
  1079 
  1080 end;