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