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