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