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