src/HOL/Tools/Nitpick/nitpick.ML
author blanchet
Mon Feb 28 17:53:10 2011 +0100 (2011-02-28 ago)
changeset 41858 37ce158d6266
parent 41856 7244589c8ccc
child 41868 a4fb98eb0edf
permissions -rw-r--r--
if "total_consts" is set, report cex's as quasi-genuine
     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      preconstrs: (term option * bool option) list,
    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    preconstrs: (term option * bool option) list,
   114    peephole_optim: bool,
   115    datatype_sym_break: int,
   116    kodkod_sym_break: int,
   117    timeout: Time.time option,
   118    tac_timeout: Time.time option,
   119    max_threads: int,
   120    show_datatypes: bool,
   121    show_consts: bool,
   122    evals: term list,
   123    formats: (term option * int list) list,
   124    atomss: (typ option * string list) list,
   125    max_potential: int,
   126    max_genuine: int,
   127    check_potential: bool,
   128    check_genuine: bool,
   129    batch_size: int,
   130    expect: string}
   131 
   132 (* TODO: eliminate these historical aliases *)
   133 val register_frac_type = Nitpick_HOL.register_frac_type_global
   134 val unregister_frac_type = Nitpick_HOL.unregister_frac_type_global
   135 val register_codatatype = Nitpick_HOL.register_codatatype_global
   136 val unregister_codatatype = Nitpick_HOL.unregister_codatatype_global
   137 val register_term_postprocessor =
   138   Nitpick_Model.register_term_postprocessor_global
   139 val unregister_term_postprocessor =
   140   Nitpick_Model.unregister_term_postprocessor_global
   141 
   142 type problem_extension =
   143   {free_names: nut list,
   144    sel_names: nut list,
   145    nonsel_names: nut list,
   146    rel_table: nut NameTable.table,
   147    unsound: bool,
   148    scope: scope}
   149 
   150 type rich_problem = KK.problem * problem_extension
   151 
   152 fun pretties_for_formulas _ _ [] = []
   153   | pretties_for_formulas ctxt s ts =
   154     [Pretty.str (s ^ plural_s_for_list ts ^ ":"),
   155      Pretty.indent indent_size (Pretty.chunks
   156          (map2 (fn j => fn t =>
   157                    Pretty.block [t |> shorten_names_in_term
   158                                    |> Syntax.pretty_term ctxt,
   159                                  Pretty.str (if j = 1 then "." else ";")])
   160                (length ts downto 1) ts))]
   161 
   162 fun install_java_message () =
   163   "Nitpick requires a Java 1.5 virtual machine called \"java\"."
   164 fun install_kodkodi_message () =
   165   "Nitpick requires the external Java program Kodkodi. To install it, download \
   166   \the package from Isabelle's web page and add the \"kodkodi-x.y.z\" \
   167   \directory's full path to \"" ^
   168   Path.implode (Path.expand (Path.appends
   169       (Path.variable "ISABELLE_HOME_USER" ::
   170        map Path.basic ["etc", "components"]))) ^ "\" on a line of its own."
   171 
   172 val max_unsound_delay_ms = 200
   173 val max_unsound_delay_percent = 2
   174 
   175 fun unsound_delay_for_timeout NONE = max_unsound_delay_ms
   176   | unsound_delay_for_timeout (SOME timeout) =
   177     Int.max (0, Int.min (max_unsound_delay_ms,
   178                          Time.toMilliseconds timeout
   179                          * max_unsound_delay_percent div 100))
   180 
   181 fun passed_deadline NONE = false
   182   | passed_deadline (SOME time) = Time.compare (Time.now (), time) <> LESS
   183 
   184 fun none_true assigns = forall (not_equal (SOME true) o snd) assigns
   185 
   186 fun has_lonely_bool_var (@{const Pure.conjunction}
   187                          $ (@{const Trueprop} $ Free _) $ _) = true
   188   | has_lonely_bool_var _ = false
   189 
   190 val syntactic_sorts =
   191   @{sort "{default,zero,one,plus,minus,uminus,times,inverse,abs,sgn,ord,equal}"} @
   192   @{sort number}
   193 fun has_tfree_syntactic_sort (TFree (_, S as _ :: _)) =
   194     subset (op =) (S, syntactic_sorts)
   195   | has_tfree_syntactic_sort _ = false
   196 val has_syntactic_sorts = exists_type (exists_subtype has_tfree_syntactic_sort)
   197 
   198 fun plazy f = Pretty.blk (0, pstrs (f ()))
   199 
   200 fun 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, preconstrs, 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 tfree_table =
   258       if merge_type_vars then
   259         merged_type_var_table_for_terms thy (neg_t :: assm_ts @ evals)
   260       else
   261         []
   262     val neg_t = merge_type_vars_in_term thy merge_type_vars tfree_table neg_t
   263     val assm_ts = map (merge_type_vars_in_term thy merge_type_vars tfree_table)
   264                       assm_ts
   265     val evals = map (merge_type_vars_in_term thy merge_type_vars tfree_table)
   266                     evals
   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, preconstrs = preconstrs,
   288        tac_timeout = tac_timeout, evals = evals, case_names = case_names,
   289        def_tables = def_tables, nondef_table = nondef_table,
   290        user_nondefs = user_nondefs, simp_table = simp_table,
   291        psimp_table = psimp_table, choice_spec_table = choice_spec_table,
   292        intro_table = intro_table, ground_thm_table = ground_thm_table,
   293        ersatz_table = ersatz_table, skolems = Unsynchronized.ref [],
   294        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 (neg_t :: assm_ts) []
   299     val _ = null (fold Term.add_tvars (neg_t :: assm_ts) []) orelse
   300             raise NOT_SUPPORTED "schematic type variables"
   301     val (nondef_ts, def_ts, preconstr_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 preconstr_us = preconstr_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) ([], [])
   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 _ = List.app (print_g o string_for_nut ctxt) (nondef_us @ def_us)
   342 *)
   343 
   344     val unique_scope = forall (curry (op =) 1 o length o snd) cards_assigns
   345     fun monotonicity_message Ts extra =
   346       let val pretties = map (pretty_maybe_quote o pretty_for_type ctxt) Ts in
   347         Pretty.blk (0,
   348           pstrs ("The type" ^ plural_s_for_list pretties ^ " ") @
   349           pretty_serial_commas "and" pretties @
   350           pstrs (" " ^
   351           (if none_true monos then
   352              "passed the monotonicity test"
   353            else
   354              (if length pretties = 1 then "is" else "are") ^ " considered monotonic") ^
   355           ". " ^ extra))
   356       end
   357     fun is_type_fundamentally_monotonic T =
   358       (is_datatype ctxt stds T andalso not (is_quot_type ctxt T) andalso
   359        (not (is_pure_typedef ctxt T) orelse is_univ_typedef ctxt T)) orelse
   360       is_number_type ctxt T orelse is_bit_type T
   361     fun is_type_actually_monotonic T =
   362       formulas_monotonic hol_ctxt binarize T (nondef_ts, def_ts)
   363     fun is_type_kind_of_monotonic T =
   364       case triple_lookup (type_match thy) monos T of
   365         SOME (SOME false) => false
   366       | _ => is_type_actually_monotonic T
   367     fun is_type_monotonic T =
   368       unique_scope orelse
   369       case triple_lookup (type_match thy) monos T of
   370         SOME (SOME b) => b
   371       | _ => is_type_fundamentally_monotonic T orelse
   372              is_type_actually_monotonic T
   373     fun is_deep_datatype_finitizable T =
   374       triple_lookup (type_match thy) finitizes T = SOME (SOME true)
   375     fun is_shallow_datatype_finitizable (T as Type (@{type_name fun_box}, _)) =
   376         is_type_kind_of_monotonic T
   377       | is_shallow_datatype_finitizable T =
   378         case triple_lookup (type_match thy) finitizes T of
   379           SOME (SOME b) => b
   380         | _ => is_type_kind_of_monotonic T
   381     fun is_datatype_deep T =
   382       not standard orelse T = nat_T orelse is_word_type T orelse
   383       exists (curry (op =) T o domain_type o type_of) sel_names
   384     val all_Ts = ground_types_in_terms hol_ctxt binarize (nondef_ts @ def_ts)
   385                  |> sort Term_Ord.typ_ord
   386     val _ =
   387       if verbose andalso binary_ints = SOME true andalso
   388          exists (member (op =) [nat_T, int_T]) all_Ts then
   389         print_v (K "The option \"binary_ints\" will be ignored because of the \
   390                    \presence of rationals, reals, \"Suc\", \"gcd\", or \"lcm\" \
   391                    \in the problem or because of the \"non_std\" option.")
   392       else
   393         ()
   394     val _ =
   395       if not auto andalso
   396          exists (fn Type (@{type_name Datatype.node}, _) => true | _ => false)
   397                 all_Ts then
   398         print_m (K ("Warning: The problem involves directly or indirectly the \
   399                     \internal type " ^ quote @{type_name Datatype.node} ^
   400                     ". This type is very Nitpick-unfriendly, and its presence \
   401                     \usually indicates either a failure of abstraction or a \
   402                     \quirk in Nitpick."))
   403       else
   404         ()
   405     val (mono_Ts, nonmono_Ts) = List.partition is_type_monotonic all_Ts
   406     val _ =
   407       if verbose andalso not unique_scope then
   408         case filter_out is_type_fundamentally_monotonic mono_Ts of
   409           [] => ()
   410         | interesting_mono_Ts =>
   411           pprint_v (K (monotonicity_message interesting_mono_Ts
   412                           "Nitpick might be able to skip some scopes."))
   413       else
   414         ()
   415     val (deep_dataTs, shallow_dataTs) =
   416       all_Ts |> filter (is_datatype ctxt stds)
   417              |> List.partition is_datatype_deep
   418     val finitizable_dataTs =
   419       (deep_dataTs |> filter_out (is_finite_type hol_ctxt)
   420                    |> filter is_deep_datatype_finitizable) @
   421       (shallow_dataTs |> filter_out (is_finite_type hol_ctxt)
   422                       |> filter is_shallow_datatype_finitizable)
   423     val _ =
   424       if verbose andalso not (null finitizable_dataTs) then
   425         pprint_v (K (monotonicity_message finitizable_dataTs
   426                          "Nitpick can use a more precise finite encoding."))
   427       else
   428         ()
   429     (* This detection code is an ugly hack. Fortunately, it is used only to
   430        provide a hint to the user. *)
   431     fun is_struct_induct_step (name, (Rule_Cases.Case {fixes, assumes, ...}, _)) =
   432       not (null fixes) andalso
   433       exists (String.isSuffix ".hyps" o fst) assumes andalso
   434       exists (exists (curry (op =) name o shortest_name o fst)
   435               o datatype_constrs hol_ctxt) deep_dataTs
   436     val likely_in_struct_induct_step =
   437       exists is_struct_induct_step (ProofContext.cases_of ctxt)
   438     val _ = if standard andalso likely_in_struct_induct_step then
   439               pprint_m (fn () => Pretty.blk (0,
   440                   pstrs "Hint: To check that the induction hypothesis is \
   441                         \general enough, try this command: " @
   442                   [Pretty.mark Markup.sendback (Pretty.blk (0,
   443                        pstrs ("nitpick [non_std, show_all]")))] @ pstrs "."))
   444             else
   445               ()
   446 (*
   447     val _ = print_g "Monotonic types:"
   448     val _ = List.app (print_g o string_for_type ctxt) mono_Ts
   449     val _ = print_g "Nonmonotonic types:"
   450     val _ = List.app (print_g o string_for_type ctxt) nonmono_Ts
   451 *)
   452 
   453     val incremental = Int.max (max_potential, max_genuine) >= 2
   454     val actual_sat_solver =
   455       if sat_solver <> "smart" then
   456         if incremental andalso
   457            not (member (op =) (Kodkod_SAT.configured_sat_solvers true)
   458                        sat_solver) then
   459           (print_m (K ("An incremental SAT solver is required: \"SAT4J\" will \
   460                        \be used instead of " ^ quote sat_solver ^ "."));
   461            "SAT4J")
   462         else
   463           sat_solver
   464       else
   465         Kodkod_SAT.smart_sat_solver_name incremental
   466     val _ =
   467       if sat_solver = "smart" then
   468         print_v (fn () =>
   469             "Using SAT solver " ^ quote actual_sat_solver ^ ". The following" ^
   470             (if incremental then " incremental " else " ") ^
   471             "solvers are configured: " ^
   472             commas_quote (Kodkod_SAT.configured_sat_solvers incremental) ^ ".")
   473       else
   474         ()
   475 
   476     val too_big_scopes = Unsynchronized.ref []
   477 
   478     fun problem_for_scope unsound
   479             (scope as {card_assigns, bits, bisim_depth, datatypes, ofs, ...}) =
   480       let
   481         val _ = not (exists (fn other => scope_less_eq other scope)
   482                             (!too_big_scopes)) orelse
   483                 raise TOO_LARGE ("Nitpick.pick_them_nits_in_term.\
   484                                  \problem_for_scope", "too large scope")
   485 (*
   486         val _ = print_g "Offsets:"
   487         val _ = List.app (fn (T, j0) =>
   488                              print_g (string_for_type ctxt T ^ " = " ^
   489                                     string_of_int j0))
   490                          (Typtab.dest ofs)
   491 *)
   492         val effective_total_consts =
   493           case total_consts of
   494             SOME b => b
   495           | NONE => forall (is_exact_type datatypes true) all_Ts
   496         val main_j0 = offset_of_type ofs bool_T
   497         val (nat_card, nat_j0) = spec_of_type scope nat_T
   498         val (int_card, int_j0) = spec_of_type scope int_T
   499         val _ = (nat_j0 = main_j0 andalso int_j0 = main_j0) orelse
   500                 raise BAD ("Nitpick.pick_them_nits_in_term.problem_for_scope",
   501                            "bad offsets")
   502         val kk = kodkod_constrs peephole_optim nat_card int_card main_j0
   503         val (free_names, rep_table) =
   504           choose_reps_for_free_vars scope pseudo_frees free_names
   505                                     NameTable.empty
   506         val (sel_names, rep_table) = choose_reps_for_all_sels scope rep_table
   507         val (nonsel_names, rep_table) =
   508           choose_reps_for_consts scope effective_total_consts nonsel_names
   509                                  rep_table
   510         val (guiltiest_party, min_highest_arity) =
   511           NameTable.fold (fn (name, R) => fn (s, n) =>
   512                              let val n' = arity_of_rep R in
   513                                if n' > n then (nickname_of name, n') else (s, n)
   514                              end) rep_table ("", 1)
   515         val min_univ_card =
   516           NameTable.fold (Integer.max o min_univ_card_of_rep o snd) rep_table
   517                          (univ_card nat_card int_card main_j0 [] KK.True)
   518         val _ = check_arity guiltiest_party min_univ_card min_highest_arity
   519 
   520         val def_us =
   521           def_us |> map (choose_reps_in_nut scope unsound rep_table true)
   522         val nondef_us =
   523           nondef_us |> map (choose_reps_in_nut scope unsound rep_table false)
   524         val preconstr_us =
   525           preconstr_us |> map (choose_reps_in_nut scope unsound rep_table false)
   526 (*
   527         val _ = List.app (print_g o string_for_nut ctxt)
   528                          (free_names @ sel_names @ nonsel_names @
   529                           nondef_us @ def_us)
   530 *)
   531         val (free_rels, pool, rel_table) =
   532           rename_free_vars free_names initial_pool NameTable.empty
   533         val (sel_rels, pool, rel_table) =
   534           rename_free_vars sel_names pool rel_table
   535         val (other_rels, pool, rel_table) =
   536           rename_free_vars nonsel_names pool rel_table
   537         val nondef_us = nondef_us |> map (rename_vars_in_nut pool rel_table)
   538         val def_us = def_us |> map (rename_vars_in_nut pool rel_table)
   539         val preconstr_us =
   540           preconstr_us |> map (rename_vars_in_nut pool rel_table)
   541         val nondef_fs = map (kodkod_formula_from_nut ofs kk) nondef_us
   542         val def_fs = map (kodkod_formula_from_nut ofs kk) def_us
   543         val formula = fold (fold s_and) [def_fs, nondef_fs] KK.True
   544         val comment = (if unsound then "unsound" else "sound") ^ "\n" ^
   545                       Print_Mode.setmp [] multiline_string_for_scope scope
   546         val kodkod_sat_solver =
   547           Kodkod_SAT.sat_solver_spec actual_sat_solver |> snd
   548         val bit_width = if bits = 0 then 16 else bits + 1
   549         val delay =
   550           if unsound then
   551             Option.map (fn time => Time.- (time, Time.now ())) deadline
   552             |> unsound_delay_for_timeout
   553           else
   554             0
   555         val settings = [("solver", commas_quote kodkod_sat_solver),
   556                         ("bit_width", string_of_int bit_width),
   557                         ("symmetry_breaking", string_of_int kodkod_sym_break),
   558                         ("sharing", "3"),
   559                         ("flatten", "false"),
   560                         ("delay", signed_string_of_int delay)]
   561         val plain_rels = free_rels @ other_rels
   562         val plain_bounds = map (bound_for_plain_rel ctxt debug) plain_rels
   563         val plain_axioms = map (declarative_axiom_for_plain_rel kk) plain_rels
   564         val sel_bounds = map (bound_for_sel_rel ctxt debug datatypes) sel_rels
   565         val dtype_axioms =
   566           declarative_axioms_for_datatypes hol_ctxt binarize preconstr_us
   567               datatype_sym_break bits ofs kk rel_table datatypes
   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, datatypes = datatypes,
   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 () => ("Limit reached: " ^ msg ^
   608                                    ". Skipping " ^ (if unsound then "potential"
   609                                                     else "genuine") ^
   610                                    " component of scope."));
   611                 NONE)
   612            | TOO_SMALL (_, msg) =>
   613              (print_v (fn () => ("Limit reached: " ^ msg ^
   614                                  ". Skipping " ^ (if unsound then "potential"
   615                                                   else "genuine") ^
   616                                  " component of scope."));
   617               NONE)
   618 
   619     val das_wort_model =
   620       (if falsify then "counterexample" else "model")
   621       |> not standard ? prefix "nonstandard "
   622 
   623     val scopes = Unsynchronized.ref []
   624     val generated_scopes = Unsynchronized.ref []
   625     val generated_problems = Unsynchronized.ref ([] : rich_problem list)
   626     val checked_problems = Unsynchronized.ref (SOME [])
   627     val met_potential = Unsynchronized.ref 0
   628 
   629     fun update_checked_problems problems =
   630       List.app (Unsynchronized.change checked_problems o Option.map o cons
   631                 o nth problems)
   632     fun show_kodkod_warning "" = ()
   633       | show_kodkod_warning s = print_m (fn () => "Kodkod warning: " ^ s ^ ".")
   634 
   635     fun print_and_check_model genuine bounds
   636             ({free_names, sel_names, nonsel_names, rel_table, scope, ...}
   637              : problem_extension) =
   638       let
   639         val (reconstructed_model, codatatypes_ok) =
   640           reconstruct_hol_model {show_datatypes = show_datatypes,
   641                                  show_consts = show_consts}
   642               scope formats atomss real_frees pseudo_frees free_names sel_names
   643               nonsel_names rel_table bounds
   644         val genuine_means_genuine =
   645           got_all_user_axioms andalso none_true wfs andalso
   646           sound_finitizes andalso total_consts <> SOME true andalso
   647           codatatypes_ok
   648         fun assms_prop () = Logic.mk_conjunction_list (neg_t :: assm_ts)
   649       in
   650         (pprint (Pretty.chunks
   651              [Pretty.blk (0,
   652                   (pstrs ((if auto then "Auto " else "") ^ "Nitpick found a" ^
   653                           (if not genuine then " potential "
   654                            else if genuine_means_genuine then " "
   655                            else " quasi genuine ") ^ das_wort_model) @
   656                    (case pretties_for_scope scope verbose of
   657                       [] => []
   658                     | pretties => pstrs " for " @ pretties) @
   659                    [Pretty.str ":\n"])),
   660               Pretty.indent indent_size reconstructed_model]);
   661          if genuine then
   662            (if check_genuine andalso standard then
   663               case prove_hol_model scope tac_timeout free_names sel_names
   664                                    rel_table bounds (assms_prop ()) of
   665                 SOME true =>
   666                 print ("Confirmation by \"auto\": The above " ^
   667                        das_wort_model ^ " is really genuine.")
   668               | SOME false =>
   669                 if genuine_means_genuine then
   670                   error ("A supposedly genuine " ^ das_wort_model ^ " was \
   671                          \shown to be spurious by \"auto\".\nThis should never \
   672                          \happen.\nPlease send a bug report to blanchet\
   673                          \te@in.tum.de.")
   674                  else
   675                    print ("Refutation by \"auto\": The above " ^
   676                           das_wort_model ^ " is spurious.")
   677                | NONE => print "No confirmation by \"auto\"."
   678             else
   679               ();
   680             if not standard andalso likely_in_struct_induct_step then
   681               print "The existence of a nonstandard model suggests that the \
   682                     \induction hypothesis is not general enough or may even be \
   683                     \wrong. See the Nitpick manual's \"Inductive Properties\" \
   684                     \section for details (\"isabelle doc nitpick\")."
   685             else
   686               ();
   687             if has_lonely_bool_var orig_t then
   688               print "Hint: Maybe you forgot a colon after the lemma's name?"
   689             else if has_syntactic_sorts orig_t then
   690               print "Hint: Maybe you forgot a type constraint?"
   691             else
   692               ();
   693             if not genuine_means_genuine then
   694               if no_poly_user_axioms then
   695                 let
   696                   val options =
   697                     [] |> not got_all_mono_user_axioms
   698                           ? cons ("user_axioms", "\"true\"")
   699                        |> not (none_true wfs)
   700                           ? cons ("wf", "\"smart\" or \"false\"")
   701                        |> not sound_finitizes
   702                           ? cons ("finitize", "\"smart\" or \"false\"")
   703                        |> total_consts = SOME true
   704                           ? cons ("total_consts", "\"smart\" or \"false\"")
   705                        |> not codatatypes_ok
   706                           ? cons ("bisim_depth", "a nonnegative value")
   707                   val ss =
   708                     map (fn (name, value) => quote name ^ " set to " ^ value)
   709                         options
   710                 in
   711                   print ("Try again with " ^
   712                          implode (serial_commas "and" ss) ^
   713                          " to confirm that the " ^ das_wort_model ^
   714                          " is genuine.")
   715                 end
   716               else
   717                 print ("Nitpick is unable to guarantee the authenticity of \
   718                        \the " ^ das_wort_model ^ " in the presence of \
   719                        \polymorphic axioms.")
   720             else
   721               ();
   722             NONE)
   723          else
   724            if not genuine then
   725              (Unsynchronized.inc met_potential;
   726               if check_potential then
   727                 let
   728                   val status = prove_hol_model scope tac_timeout free_names
   729                                                sel_names rel_table bounds
   730                                                (assms_prop ())
   731                 in
   732                   (case status of
   733                      SOME true => print ("Confirmation by \"auto\": The \
   734                                          \above " ^ das_wort_model ^
   735                                          " is genuine.")
   736                    | SOME false => print ("Refutation by \"auto\": The above " ^
   737                                           das_wort_model ^ " is spurious.")
   738                    | NONE => print "No confirmation by \"auto\".");
   739                   status
   740                 end
   741               else
   742                 NONE)
   743            else
   744              NONE)
   745         |> pair genuine_means_genuine
   746       end
   747     fun solve_any_problem (found_really_genuine, max_potential, max_genuine,
   748                            donno) first_time problems =
   749       let
   750         val max_potential = Int.max (0, max_potential)
   751         val max_genuine = Int.max (0, max_genuine)
   752         fun print_and_check genuine (j, bounds) =
   753           print_and_check_model genuine bounds (snd (nth problems j))
   754         val max_solutions = max_potential + max_genuine
   755                             |> not incremental ? Integer.min 1
   756       in
   757         if max_solutions <= 0 then
   758           (found_really_genuine, 0, 0, donno)
   759         else
   760           case KK.solve_any_problem debug overlord deadline max_threads
   761                                     max_solutions (map fst problems) of
   762             KK.JavaNotInstalled =>
   763             (print_m install_java_message;
   764              (found_really_genuine, max_potential, max_genuine, donno + 1))
   765           | KK.JavaTooOld =>
   766             (print_m install_java_message;
   767              (found_really_genuine, max_potential, max_genuine, donno + 1))
   768           | KK.KodkodiNotInstalled =>
   769             (print_m install_kodkodi_message;
   770              (found_really_genuine, max_potential, max_genuine, donno + 1))
   771           | KK.Normal ([], unsat_js, s) =>
   772             (update_checked_problems problems unsat_js; show_kodkod_warning s;
   773              (found_really_genuine, max_potential, max_genuine, donno))
   774           | KK.Normal (sat_ps, unsat_js, s) =>
   775             let
   776               val (lib_ps, con_ps) =
   777                 List.partition (#unsound o snd o nth problems o fst) sat_ps
   778             in
   779               update_checked_problems problems (unsat_js @ map fst lib_ps);
   780               show_kodkod_warning s;
   781               if null con_ps then
   782                 let
   783                   val genuine_codes =
   784                     lib_ps |> take max_potential
   785                            |> map (print_and_check false)
   786                            |> filter (curry (op =) (SOME true) o snd)
   787                   val found_really_genuine =
   788                     found_really_genuine orelse exists fst genuine_codes
   789                   val num_genuine = length genuine_codes
   790                   val max_genuine = max_genuine - num_genuine
   791                   val max_potential = max_potential
   792                                       - (length lib_ps - num_genuine)
   793                 in
   794                   if max_genuine <= 0 then
   795                     (found_really_genuine, 0, 0, donno)
   796                   else
   797                     let
   798                       (* "co_js" is the list of sound problems whose unsound
   799                          pendants couldn't be satisfied and hence that most
   800                          probably can't be satisfied themselves. *)
   801                       val co_js =
   802                         map (fn j => j - 1) unsat_js
   803                         |> filter (fn j =>
   804                                       j >= 0 andalso
   805                                       scopes_equivalent
   806                                           (#scope (snd (nth problems j)),
   807                                            #scope (snd (nth problems (j + 1)))))
   808                       val bye_js = sort_distinct int_ord (map fst sat_ps @
   809                                                           unsat_js @ co_js)
   810                       val problems =
   811                         problems |> filter_out_indices bye_js
   812                                  |> max_potential <= 0
   813                                     ? filter_out (#unsound o snd)
   814                     in
   815                       solve_any_problem (found_really_genuine, max_potential,
   816                                          max_genuine, donno) false problems
   817                     end
   818                 end
   819               else
   820                 let
   821                   val genuine_codes =
   822                     con_ps |> take max_genuine
   823                            |> map (print_and_check true)
   824                   val max_genuine = max_genuine - length genuine_codes
   825                   val found_really_genuine =
   826                     found_really_genuine orelse exists fst genuine_codes
   827                 in
   828                   if max_genuine <= 0 orelse not first_time then
   829                     (found_really_genuine, 0, max_genuine, donno)
   830                   else
   831                     let
   832                       val bye_js = sort_distinct int_ord
   833                                                  (map fst sat_ps @ unsat_js)
   834                       val problems =
   835                         problems |> filter_out_indices bye_js
   836                                  |> filter_out (#unsound o snd)
   837                     in
   838                       solve_any_problem (found_really_genuine, 0, max_genuine,
   839                                          donno) false problems
   840                     end
   841                 end
   842             end
   843           | KK.TimedOut unsat_js =>
   844             (update_checked_problems problems unsat_js; raise TimeLimit.TimeOut)
   845           | KK.Error (s, unsat_js) =>
   846             (update_checked_problems problems unsat_js;
   847              print_v (K ("Kodkod error: " ^ s ^ "."));
   848              (found_really_genuine, max_potential, max_genuine, donno + 1))
   849       end
   850 
   851     fun run_batch j n scopes (found_really_genuine, max_potential, max_genuine,
   852                               donno) =
   853       let
   854         val _ =
   855           if null scopes then
   856             print_m (K "The scope specification is inconsistent.")
   857           else if verbose then
   858             pprint (Pretty.chunks
   859                 [Pretty.blk (0,
   860                      pstrs ((if n > 1 then
   861                                "Batch " ^ string_of_int (j + 1) ^ " of " ^
   862                                signed_string_of_int n ^ ": "
   863                              else
   864                                "") ^
   865                             "Trying " ^ string_of_int (length scopes) ^
   866                             " scope" ^ plural_s_for_list scopes ^ ":")),
   867                  Pretty.indent indent_size
   868                      (Pretty.chunks (map2
   869                           (fn j => fn scope =>
   870                               Pretty.block (
   871                                   (case pretties_for_scope scope true of
   872                                      [] => [Pretty.str "Empty"]
   873                                    | pretties => pretties) @
   874                                   [Pretty.str (if j = 1 then "." else ";")]))
   875                           (length scopes downto 1) scopes))])
   876           else
   877             ()
   878         fun add_problem_for_scope (scope, unsound) (problems, donno) =
   879           (check_deadline ();
   880            case problem_for_scope unsound scope of
   881              SOME problem =>
   882              (problems
   883               |> (null problems orelse
   884                   not (KK.problems_equivalent (fst problem, fst (hd problems))))
   885                   ? cons problem, donno)
   886            | NONE => (problems, donno + 1))
   887         val (problems, donno) =
   888           fold add_problem_for_scope
   889                (map_product pair scopes
   890                     ((if max_genuine > 0 then [false] else []) @
   891                      (if max_potential > 0 then [true] else [])))
   892                ([], donno)
   893         val _ = Unsynchronized.change generated_problems (append problems)
   894         val _ = Unsynchronized.change generated_scopes (append scopes)
   895         val _ =
   896           if j + 1 = n then
   897             let
   898               val (unsound_problems, sound_problems) =
   899                 List.partition (#unsound o snd) (!generated_problems)
   900             in
   901               if not (null sound_problems) andalso
   902                  forall (KK.is_problem_trivially_false o fst)
   903                         sound_problems then
   904                 print_m (fn () =>
   905                     "Warning: The conjecture either trivially holds for the \
   906                     \given scopes or lies outside Nitpick's supported \
   907                     \fragment." ^
   908                     (if exists (not o KK.is_problem_trivially_false o fst)
   909                                unsound_problems then
   910                        " Only potential " ^ das_wort_model ^ "s may be found."
   911                      else
   912                        ""))
   913               else
   914                 ()
   915             end
   916           else
   917             ()
   918       in
   919         solve_any_problem (found_really_genuine, max_potential, max_genuine,
   920                            donno) true (rev problems)
   921       end
   922 
   923     fun scope_count (problems : rich_problem list) scope =
   924       length (filter (curry scopes_equivalent scope o #scope o snd) problems)
   925     fun excipit did_so_and_so =
   926       let
   927         val do_filter =
   928           if !met_potential = max_potential then filter_out (#unsound o snd)
   929           else I
   930         val total = length (!scopes)
   931         val unsat =
   932           fold (fn scope =>
   933                    case scope_count (do_filter (!generated_problems)) scope of
   934                      0 => I
   935                    | n =>
   936                      scope_count (do_filter (these (!checked_problems)))
   937                                  scope = n
   938                      ? Integer.add 1) (!generated_scopes) 0
   939       in
   940         "Nitpick " ^ did_so_and_so ^
   941         (if is_some (!checked_problems) andalso total > 0 then
   942            " " ^ string_of_int unsat ^ " of " ^ string_of_int total ^ " scope"
   943            ^ plural_s total
   944          else
   945            "") ^ "."
   946       end
   947 
   948     val (skipped, the_scopes) =
   949       all_scopes hol_ctxt binarize cards_assigns maxes_assigns iters_assigns
   950                  bitss bisim_depths mono_Ts nonmono_Ts deep_dataTs
   951                  finitizable_dataTs
   952     val _ = if skipped > 0 then
   953               print_m (fn () => "Too many scopes. Skipping " ^
   954                                 string_of_int skipped ^ " scope" ^
   955                                 plural_s skipped ^
   956                                 ". (Consider using \"mono\" or \
   957                                 \\"merge_type_vars\" to prevent this.)")
   958             else
   959               ()
   960     val _ = scopes := the_scopes
   961 
   962     fun run_batches _ _ []
   963                     (found_really_genuine, max_potential, max_genuine, donno) =
   964         if donno > 0 andalso max_genuine > 0 then
   965           (print_m (fn () => excipit "checked"); "unknown")
   966         else if max_genuine = original_max_genuine then
   967           if max_potential = original_max_potential then
   968             (print_m (fn () =>
   969                  "Nitpick found no " ^ das_wort_model ^ "." ^
   970                  (if not standard andalso likely_in_struct_induct_step then
   971                     " This suggests that the induction hypothesis might be \
   972                     \general enough to prove this subgoal."
   973                   else
   974                     "")); if skipped > 0 then "unknown" else "none")
   975           else
   976             (print_m (fn () =>
   977                  excipit ("could not find a" ^
   978                           (if max_genuine = 1 then
   979                              " better " ^ das_wort_model ^ "."
   980                            else
   981                              "ny better " ^ das_wort_model ^ "s.") ^
   982                           " It checked"));
   983              "potential")
   984         else if found_really_genuine then
   985           "genuine"
   986         else
   987           "quasi_genuine"
   988       | run_batches j n (batch :: batches) z =
   989         let val (z as (_, _, max_genuine, _)) = run_batch j n batch z in
   990           run_batches (j + 1) n (if max_genuine > 0 then batches else []) z
   991         end
   992 
   993     val batches = batch_list batch_size (!scopes)
   994     val outcome_code =
   995       run_batches 0 (length batches) batches
   996                   (false, max_potential, max_genuine, 0)
   997       handle TimeLimit.TimeOut =>
   998              (print_m (fn () => excipit "ran out of time after checking");
   999               if !met_potential > 0 then "potential" else "unknown")
  1000     val _ = print_v (fn () =>
  1001                 "Total time: " ^ string_from_time (Timer.checkRealTimer timer) ^
  1002                 ".")
  1003   in (outcome_code, !state_ref) end
  1004 
  1005 (* Give the inner timeout a chance. *)
  1006 val timeout_bonus = seconds 1.0
  1007 
  1008 fun pick_nits_in_term state (params as {debug, timeout, expect, ...}) auto i n
  1009                       step subst assm_ts orig_t =
  1010   let val print_m = if auto then K () else Output.urgent_message in
  1011     if getenv "KODKODI" = "" then
  1012       (* The "expect" argument is deliberately ignored if Kodkodi is missing so
  1013          that the "Nitpick_Examples" can be processed on any machine. *)
  1014       (print_m (Pretty.string_of (plazy install_kodkodi_message));
  1015        ("no_kodkodi", state))
  1016     else
  1017       let
  1018         val unknown_outcome = ("unknown", state)
  1019         val deadline = Option.map (curry Time.+ (Time.now ())) timeout
  1020         val outcome as (outcome_code, _) =
  1021           time_limit (if debug orelse is_none timeout then NONE
  1022                       else SOME (Time.+ (the timeout, timeout_bonus)))
  1023               (pick_them_nits_in_term deadline state params auto i n step subst
  1024                                       assm_ts) orig_t
  1025           handle TOO_LARGE (_, details) =>
  1026                  (print_m ("Limit reached: " ^ details ^ "."); unknown_outcome)
  1027                | TOO_SMALL (_, details) =>
  1028                  (print_m ("Limit reached: " ^ details ^ "."); unknown_outcome)
  1029                | Kodkod.SYNTAX (_, details) =>
  1030                  (print_m ("Malformed Kodkodi output: " ^ details ^ ".");
  1031                   unknown_outcome)
  1032                | TimeLimit.TimeOut =>
  1033                  (print_m "Nitpick ran out of time."; unknown_outcome)
  1034       in
  1035         if expect = "" orelse outcome_code = expect then outcome
  1036         else error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
  1037       end
  1038   end
  1039 
  1040 fun is_fixed_equation fixes
  1041                       (Const (@{const_name "=="}, _) $ Free (s, _) $ Const _) =
  1042     member (op =) fixes s
  1043   | is_fixed_equation _ _ = false
  1044 fun extract_fixed_frees ctxt (assms, t) =
  1045   let
  1046     val fixes = Variable.fixes_of ctxt |> map snd
  1047     val (subst, other_assms) =
  1048       List.partition (is_fixed_equation fixes) assms
  1049       |>> map Logic.dest_equals
  1050   in (subst, other_assms, subst_atomic subst t) end
  1051 
  1052 fun pick_nits_in_subgoal state params auto i step =
  1053   let
  1054     val ctxt = Proof.context_of state
  1055     val t = state |> Proof.raw_goal |> #goal |> prop_of
  1056   in
  1057     case Logic.count_prems t of
  1058       0 => (Output.urgent_message "No subgoal!"; ("none", state))
  1059     | n =>
  1060       let
  1061         val t = Logic.goal_params t i |> fst
  1062         val assms = map term_of (Assumption.all_assms_of ctxt)
  1063         val (subst, assms, t) = extract_fixed_frees ctxt (assms, t)
  1064       in pick_nits_in_term state params auto i n step subst assms t end
  1065   end
  1066 
  1067 end;