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