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