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