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