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