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