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