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