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