src/Tools/quickcheck.ML
author bulwahn
Fri, 02 Mar 2012 09:35:39 +0100
changeset 47629 a6ea1c68fa52
parent 47436 ad21900e0ee9
child 47726 56376f6be74f
permissions -rw-r--r--
collecting all axioms in a locale context in quickcheck;
adding some verbose output;
wenzelm@30826
     1
(*  Title:      Tools/quickcheck.ML
bulwahn@40481
     2
    Author:     Stefan Berghofer, Florian Haftmann, Lukas Bulwahn, TU Muenchen
haftmann@28256
     3
haftmann@28256
     4
Generic counterexample search engine.
haftmann@28256
     5
*)
haftmann@28256
     6
haftmann@28256
     7
signature QUICKCHECK =
haftmann@28256
     8
sig
blanchet@43861
     9
  val quickcheckN: string
blanchet@43861
    10
  val genuineN: string
blanchet@43861
    11
  val noneN: string
blanchet@43861
    12
  val unknownN: string
bulwahn@38150
    13
  val setup: theory -> theory
bulwahn@38150
    14
  (* configuration *)
wenzelm@32740
    15
  val auto: bool Unsynchronized.ref
bulwahn@44753
    16
  val batch_tester : string Config.T
bulwahn@40892
    17
  val size : int Config.T
bulwahn@40892
    18
  val iterations : int Config.T
bulwahn@46084
    19
  val depth : int Config.T
bulwahn@40892
    20
  val no_assms : bool Config.T
bulwahn@40892
    21
  val report : bool Config.T
bulwahn@47436
    22
  val timeout : real Config.T
bulwahn@42952
    23
  val timing : bool Config.T
bulwahn@46628
    24
  val genuine_only : bool Config.T
bulwahn@47329
    25
  val abort_potential : bool Config.T  
bulwahn@40892
    26
  val quiet : bool Config.T
bulwahn@46635
    27
  val verbose : bool Config.T
bulwahn@47436
    28
  val use_subtype : bool Config.T
bulwahn@47436
    29
  val allow_function_inversion : bool Config.T
bulwahn@40896
    30
  val finite_types : bool Config.T
bulwahn@40896
    31
  val finite_type_size : int Config.T
bulwahn@44783
    32
  val set_active_testers: string list -> Context.generic -> Context.generic
wenzelm@41765
    33
  datatype expectation = No_Expectation | No_Counterexample | Counterexample;
bulwahn@40892
    34
  datatype test_params = Test_Params of {default_type: typ list, expect : expectation};
bulwahn@40481
    35
  val test_params_of : Proof.context -> test_params
bulwahn@40892
    36
  val map_test_params : (typ list * expectation -> typ list * expectation)
bulwahn@40481
    37
    -> Context.generic -> Context.generic
bulwahn@46029
    38
  val default_type : Proof.context -> typ list
bulwahn@42953
    39
  datatype report = Report of
bulwahn@42953
    40
    { iterations : int, raised_match_errors : int,
bulwahn@42953
    41
      satisfied_assms : int list, positive_concl_tests : int }
bulwahn@42953
    42
  (* quickcheck's result *)
bulwahn@42952
    43
  datatype result =
bulwahn@42952
    44
    Result of
bulwahn@46598
    45
     {counterexample : (bool * (string * term) list) option,
bulwahn@42952
    46
      evaluation_terms : (term * term) list option,
bulwahn@42952
    47
      timings : (string * int) list,
bulwahn@42952
    48
      reports : (int * report) list}
bulwahn@44185
    49
  val empty_result : result
bulwahn@46029
    50
  val found_counterexample : result -> bool
bulwahn@44456
    51
  val add_timing : (string * int) -> result Unsynchronized.ref -> unit
bulwahn@46598
    52
  val add_response : string list -> term list -> (bool * term list) option -> result Unsynchronized.ref -> unit
bulwahn@46029
    53
  val add_report : int -> report option -> result Unsynchronized.ref -> unit
bulwahn@46598
    54
  val counterexample_of : result -> (bool * (string * term) list) option
bulwahn@42953
    55
  val timings_of : result -> (string * int) list
bulwahn@44749
    56
  (* registering testers & generators *) 
bulwahn@44749
    57
  type tester =
bulwahn@46290
    58
    Proof.context -> bool -> (string * typ) list -> (term * term list) list -> result list
bulwahn@44749
    59
  val add_tester : string * (bool Config.T * tester) -> Context.generic -> Context.generic
bulwahn@44749
    60
  val add_batch_generator :
bulwahn@43953
    61
    string * (Proof.context -> term list -> (int -> term list option) list)
bulwahn@43953
    62
      -> Context.generic -> Context.generic
bulwahn@44749
    63
  val add_batch_validator :
bulwahn@43953
    64
    string * (Proof.context -> term list -> (int -> bool) list)
bulwahn@43953
    65
      -> Context.generic -> Context.generic
bulwahn@43954
    66
  (* basic operations *)
bulwahn@46029
    67
  val message : Proof.context -> string -> unit
bulwahn@46636
    68
  val verbose_message : Proof.context -> string -> unit
bulwahn@46029
    69
  val limit : Time.time -> (bool * bool) -> (unit -> 'a) -> (unit -> 'a) -> unit -> 'a
bulwahn@46626
    70
  val pretty_counterex : Proof.context -> bool ->
bulwahn@46626
    71
    ((bool * (string * term) list) * (term * term) list) option -> Pretty.T
bulwahn@38150
    72
  (* testing terms and proof states *)
bulwahn@46029
    73
  val mk_batch_validator : Proof.context -> term list -> (int -> bool) list option
bulwahn@46029
    74
  val mk_batch_tester : Proof.context -> term list -> (int -> term list option) list option
bulwahn@46029
    75
  val active_testers : Proof.context -> tester list
bulwahn@46029
    76
  val test_terms :
bulwahn@44754
    77
    Proof.context -> bool * bool -> (string * typ) list -> (term * term list) list -> result list option
bulwahn@46598
    78
  val quickcheck: (string * string list) list -> int -> Proof.state -> (bool * (string * term) list) option
haftmann@28256
    79
end;
haftmann@28256
    80
haftmann@28256
    81
structure Quickcheck : QUICKCHECK =
haftmann@28256
    82
struct
haftmann@28256
    83
blanchet@43861
    84
val quickcheckN = "quickcheck"
blanchet@43861
    85
val quickcheck_paramsN = "quickcheck_params"
blanchet@43861
    86
blanchet@43861
    87
val genuineN = "genuine"
blanchet@43861
    88
val noneN = "none"
blanchet@43861
    89
val unknownN = "unknown"
blanchet@43861
    90
wenzelm@30981
    91
(* preferences *)
wenzelm@30981
    92
wenzelm@32740
    93
val auto = Unsynchronized.ref false;
wenzelm@30981
    94
wenzelm@30981
    95
val _ =
wenzelm@30981
    96
  ProofGeneralPgip.add_preference Preferences.category_tracing
wenzelm@39862
    97
  (Unsynchronized.setmp auto true (fn () =>
wenzelm@30981
    98
    Preferences.bool_pref auto
wenzelm@30981
    99
      "auto-quickcheck"
blanchet@39575
   100
      "Run Quickcheck automatically.") ());
wenzelm@30981
   101
bulwahn@35378
   102
(* quickcheck report *)
bulwahn@35378
   103
bulwahn@35378
   104
datatype report = Report of
bulwahn@35378
   105
  { iterations : int, raised_match_errors : int,
bulwahn@35378
   106
    satisfied_assms : int list, positive_concl_tests : int }
bulwahn@35378
   107
bulwahn@42952
   108
(* Quickcheck Result *)
bulwahn@42952
   109
bulwahn@42952
   110
datatype result = Result of
bulwahn@46598
   111
  { counterexample : (bool * (string * term) list) option, evaluation_terms : (term * term) list option,
bulwahn@42952
   112
    timings : (string * int) list, reports : (int * report) list}
bulwahn@42952
   113
bulwahn@42952
   114
val empty_result =
bulwahn@42952
   115
  Result {counterexample = NONE, evaluation_terms = NONE, timings = [], reports = []}
bulwahn@42952
   116
bulwahn@42952
   117
fun counterexample_of (Result r) = #counterexample r
bulwahn@42952
   118
bulwahn@42952
   119
fun found_counterexample (Result r) = is_some (#counterexample r)
bulwahn@42952
   120
bulwahn@42952
   121
fun response_of (Result r) = case (#counterexample r, #evaluation_terms r) of
bulwahn@46601
   122
    (SOME ts, SOME evals) => SOME (ts, evals)
bulwahn@42952
   123
  | (NONE, NONE) => NONE
bulwahn@42952
   124
bulwahn@42952
   125
fun timings_of (Result r) = #timings r
bulwahn@42952
   126
bulwahn@46598
   127
fun set_response names eval_terms (SOME (genuine, ts)) (Result r) =
bulwahn@42952
   128
  let
bulwahn@42952
   129
    val (ts1, ts2) = chop (length names) ts
bulwahn@46029
   130
    val (eval_terms', _) = chop (length ts2) eval_terms
bulwahn@42952
   131
  in
bulwahn@46598
   132
    Result {counterexample = SOME (genuine, (names ~~ ts1)),
bulwahn@46598
   133
      evaluation_terms = SOME (eval_terms' ~~ ts2),
bulwahn@42952
   134
      timings = #timings r, reports = #reports r}
bulwahn@42952
   135
  end
bulwahn@46029
   136
  | set_response _ _ NONE result = result
bulwahn@42952
   137
bulwahn@44456
   138
bulwahn@44456
   139
fun set_counterexample counterexample (Result r) =
bulwahn@44456
   140
  Result {counterexample = counterexample,  evaluation_terms = #evaluation_terms r,
bulwahn@44456
   141
    timings = #timings r, reports = #reports r}
bulwahn@44456
   142
bulwahn@44456
   143
fun set_evaluation_terms evaluation_terms (Result r) =
bulwahn@44456
   144
  Result {counterexample = #counterexample r,  evaluation_terms = evaluation_terms,
bulwahn@44456
   145
    timings = #timings r, reports = #reports r}
bulwahn@44456
   146
bulwahn@42952
   147
fun cons_timing timing (Result r) =
bulwahn@42952
   148
  Result {counterexample = #counterexample r, evaluation_terms = #evaluation_terms r,
bulwahn@42952
   149
    timings = cons timing (#timings r), reports = #reports r}
bulwahn@42952
   150
bulwahn@42952
   151
fun cons_report size (SOME report) (Result r) =
bulwahn@42952
   152
  Result {counterexample = #counterexample r, evaluation_terms = #evaluation_terms r,
bulwahn@42952
   153
    timings = #timings r, reports = cons (size, report) (#reports r)}
bulwahn@42952
   154
  | cons_report _ NONE result = result
bulwahn@42952
   155
wenzelm@43071
   156
fun add_timing timing result_ref =
wenzelm@43071
   157
  Unsynchronized.change result_ref (cons_timing timing)
bulwahn@42952
   158
wenzelm@43071
   159
fun add_report size report result_ref =
wenzelm@43071
   160
  Unsynchronized.change result_ref (cons_report size report)
bulwahn@42952
   161
bulwahn@42952
   162
fun add_response names eval_terms response result_ref =
bulwahn@46029
   163
  Unsynchronized.change result_ref (set_response names eval_terms response)
bulwahn@42952
   164
bulwahn@38169
   165
(* expectation *)
bulwahn@38169
   166
wenzelm@41765
   167
datatype expectation = No_Expectation | No_Counterexample | Counterexample;
bulwahn@38169
   168
bulwahn@38169
   169
fun merge_expectation (expect1, expect2) =
bulwahn@38169
   170
  if expect1 = expect2 then expect1 else No_Expectation
bulwahn@38169
   171
haftmann@28315
   172
(* quickcheck configuration -- default parameters, test generators *)
bulwahn@44753
   173
val batch_tester = Attrib.setup_config_string @{binding quickcheck_batch_tester} (K "")
wenzelm@43487
   174
val size = Attrib.setup_config_int @{binding quickcheck_size} (K 10)
wenzelm@43487
   175
val iterations = Attrib.setup_config_int @{binding quickcheck_iterations} (K 100)
bulwahn@46084
   176
val depth = Attrib.setup_config_int @{binding quickcheck_depth} (K 10)
bulwahn@46084
   177
wenzelm@43487
   178
val no_assms = Attrib.setup_config_bool @{binding quickcheck_no_assms} (K false)
wenzelm@43487
   179
val report = Attrib.setup_config_bool @{binding quickcheck_report} (K true)
wenzelm@43487
   180
val timing = Attrib.setup_config_bool @{binding quickcheck_timing} (K false)
bulwahn@47436
   181
val timeout = Attrib.setup_config_real @{binding quickcheck_timeout} (K 30.0)
bulwahn@47436
   182
bulwahn@46628
   183
val genuine_only = Attrib.setup_config_bool @{binding quickcheck_genuine_only} (K false)
bulwahn@47329
   184
val abort_potential = Attrib.setup_config_bool @{binding quickcheck_abort_potential} (K false)
bulwahn@47436
   185
wenzelm@43487
   186
val quiet = Attrib.setup_config_bool @{binding quickcheck_quiet} (K false)
bulwahn@46635
   187
val verbose = Attrib.setup_config_bool @{binding quickcheck_verbose} (K false)
bulwahn@47436
   188
bulwahn@47436
   189
val use_subtype = Attrib.setup_config_bool @{binding quickcheck_use_subtype} (K false)
bulwahn@47436
   190
bulwahn@46320
   191
val allow_function_inversion =
bulwahn@46320
   192
  Attrib.setup_config_bool @{binding quickcheck_allow_function_inversion} (K false)
wenzelm@43487
   193
val finite_types = Attrib.setup_config_bool @{binding quickcheck_finite_types} (K true)
wenzelm@43487
   194
val finite_type_size = Attrib.setup_config_int @{binding quickcheck_finite_type_size} (K 3)
bulwahn@40894
   195
haftmann@28309
   196
datatype test_params = Test_Params of
bulwahn@40892
   197
  {default_type: typ list, expect : expectation};
haftmann@28309
   198
bulwahn@40892
   199
fun dest_test_params (Test_Params {default_type, expect}) = (default_type, expect);
wenzelm@39034
   200
wenzelm@41765
   201
fun make_test_params (default_type, expect) =
wenzelm@41765
   202
  Test_Params {default_type = default_type, expect = expect};
wenzelm@39034
   203
wenzelm@41765
   204
fun map_test_params' f (Test_Params {default_type, expect}) =
wenzelm@41765
   205
  make_test_params (f (default_type, expect));
wenzelm@39034
   206
wenzelm@39034
   207
fun merge_test_params
wenzelm@41720
   208
  (Test_Params {default_type = default_type1, expect = expect1},
wenzelm@41720
   209
    Test_Params {default_type = default_type2, expect = expect2}) =
wenzelm@41720
   210
  make_test_params
wenzelm@41720
   211
    (merge (op =) (default_type1, default_type2), merge_expectation (expect1, expect2));
haftmann@28309
   212
bulwahn@44749
   213
type tester =
bulwahn@46290
   214
  Proof.context -> bool -> (string * typ) list -> (term * term list) list -> result list
bulwahn@44749
   215
bulwahn@39479
   216
structure Data = Generic_Data
wenzelm@33522
   217
(
wenzelm@39034
   218
  type T =
bulwahn@44749
   219
    ((string * (bool Config.T * tester)) list
bulwahn@43065
   220
      * ((string * (Proof.context -> term list -> (int -> term list option) list)) list
bulwahn@43065
   221
      * ((string * (Proof.context -> term list -> (int -> bool) list)) list)))
wenzelm@39034
   222
      * test_params;
bulwahn@44748
   223
  val empty = (([], ([], [])), Test_Params {default_type = [], expect = No_Expectation});
haftmann@28256
   224
  val extend = I;
bulwahn@44748
   225
  fun merge (((testers1, (batch_generators1, batch_validators1)), params1),
bulwahn@44748
   226
    ((testers2, (batch_generators2, batch_validators2)), params2)) : T =
bulwahn@44748
   227
    ((AList.merge (op =) (K true) (testers1, testers2),
bulwahn@43953
   228
      (AList.merge (op =) (K true) (batch_generators1, batch_generators2),
bulwahn@43953
   229
       AList.merge (op =) (K true) (batch_validators1, batch_validators2))),
haftmann@28309
   230
      merge_test_params (params1, params2));
wenzelm@33522
   231
);
haftmann@28256
   232
bulwahn@39479
   233
val test_params_of = snd o Data.get o Context.Proof;
bulwahn@38150
   234
bulwahn@40892
   235
val default_type = fst o dest_test_params o test_params_of
bulwahn@40481
   236
bulwahn@40892
   237
val expect = snd o dest_test_params o test_params_of
bulwahn@40481
   238
bulwahn@40481
   239
val map_test_params = Data.map o apsnd o map_test_params'
bulwahn@39480
   240
bulwahn@44748
   241
val add_tester = Data.map o apfst o apfst o AList.update (op =);
bulwahn@42733
   242
bulwahn@43065
   243
val add_batch_generator = Data.map o apfst o apsnd o apfst o AList.update (op =);
bulwahn@43065
   244
bulwahn@43065
   245
val add_batch_validator = Data.map o apfst o apsnd o apsnd o AList.update (op =);
haftmann@28256
   246
bulwahn@44752
   247
fun active_testers ctxt =
bulwahn@44752
   248
  let
bulwahn@44752
   249
    val testers = (map snd o fst o fst o Data.get o Context.Proof) ctxt
bulwahn@44752
   250
  in
bulwahn@44752
   251
    map snd (filter (fn (active, _) => Config.get ctxt active) testers)
bulwahn@44752
   252
  end
bulwahn@44752
   253
  
bulwahn@44755
   254
fun set_active_testers [] gen_ctxt = gen_ctxt
bulwahn@44755
   255
  | set_active_testers testers gen_ctxt =
bulwahn@44752
   256
  let
bulwahn@44752
   257
    val registered_testers = (fst o fst o Data.get) gen_ctxt
bulwahn@44752
   258
  in
bulwahn@44752
   259
    fold (fn (name, (config, _)) => Config.put_generic config (member (op =) testers name))
bulwahn@44752
   260
      registered_testers gen_ctxt
bulwahn@44752
   261
  end
bulwahn@44752
   262
    
haftmann@28315
   263
(* generating tests *)
haftmann@28315
   264
bulwahn@42733
   265
fun gen_mk_tester lookup ctxt v =
haftmann@28309
   266
  let
bulwahn@44753
   267
    val name = Config.get ctxt batch_tester
bulwahn@42733
   268
    val tester = case lookup ctxt name
bulwahn@44753
   269
      of NONE => error ("No such quickcheck batch-tester: " ^ name)
bulwahn@41153
   270
      | SOME tester => tester ctxt;
wenzelm@40491
   271
  in
bulwahn@41153
   272
    if Config.get ctxt quiet then
bulwahn@42733
   273
      try tester v
bulwahn@41153
   274
    else
wenzelm@44633
   275
      let (* FIXME !?!? *)
bulwahn@42733
   276
        val tester = Exn.interruptible_capture tester v
wenzelm@44633
   277
      in case Exn.get_res tester of
bulwahn@41153
   278
          NONE => SOME (Exn.release tester)
bulwahn@41153
   279
        | SOME tester => SOME tester
bulwahn@41153
   280
      end
bulwahn@41153
   281
  end
bulwahn@44753
   282
bulwahn@43065
   283
val mk_batch_tester =
bulwahn@43065
   284
  gen_mk_tester (fn ctxt => AList.lookup (op =) ((fst o snd o fst o Data.get o Context.Proof) ctxt))
bulwahn@43065
   285
val mk_batch_validator =
bulwahn@43065
   286
  gen_mk_tester (fn ctxt => AList.lookup (op =) ((snd o snd o fst o Data.get o Context.Proof) ctxt))
bulwahn@43953
   287
  
bulwahn@44748
   288
fun lookup_tester ctxt = AList.lookup (op =) ((fst o fst o Data.get o Context.Proof) ctxt)
bulwahn@43953
   289
haftmann@28315
   290
(* testing propositions *)
haftmann@28315
   291
bulwahn@44747
   292
type compile_generator =
bulwahn@44747
   293
  Proof.context -> (term * term list) list -> int list -> term list option * report option
bulwahn@44747
   294
bulwahn@44456
   295
fun limit timeout (limit_time, is_interactive) f exc () =
bulwahn@42625
   296
  if limit_time then
bulwahn@44456
   297
      TimeLimit.timeLimit timeout f ()
bulwahn@42625
   298
    handle TimeLimit.TimeOut =>
bulwahn@42625
   299
      if is_interactive then exc () else raise TimeLimit.TimeOut
bulwahn@42625
   300
  else
bulwahn@42625
   301
    f ()
bulwahn@42624
   302
bulwahn@44786
   303
fun message ctxt s = if Config.get ctxt quiet then () else Output.urgent_message s
bulwahn@46636
   304
bulwahn@46636
   305
fun verbose_message ctxt s = if not (Config.get ctxt quiet) andalso Config.get ctxt verbose
bulwahn@46636
   306
  then Output.urgent_message s else ()
bulwahn@46636
   307
bulwahn@46029
   308
fun test_terms ctxt (limit_time, is_interactive) insts goals =
bulwahn@44749
   309
  case active_testers ctxt of
bulwahn@44752
   310
    [] => error "No active testers for quickcheck"
bulwahn@46636
   311
  | testers =>
bulwahn@46636
   312
    limit (seconds (Config.get ctxt timeout)) (limit_time, is_interactive)
bulwahn@44786
   313
      (fn () => Par_List.get_some (fn tester =>
bulwahn@46290
   314
      tester ctxt (length testers > 1) insts goals |>
bulwahn@44786
   315
      (fn result => if exists found_counterexample result then SOME result else NONE)) testers)
bulwahn@44786
   316
      (fn () => (message ctxt "Quickcheck ran out of time"; NONE)) ();
bulwahn@47629
   317
bulwahn@47629
   318
fun all_axioms_of ctxt t =
bulwahn@47629
   319
  let
bulwahn@47629
   320
    val intros = Locale.get_intros ctxt
bulwahn@47629
   321
    val unfolds = Locale.get_unfolds ctxt
bulwahn@47629
   322
    fun retrieve_prems thms t = 
bulwahn@47629
   323
       case filter (fn th => Term.could_unify (Thm.concl_of th, t)) thms of
bulwahn@47629
   324
         [] => NONE 
bulwahn@47629
   325
       | [th] =>
bulwahn@47629
   326
         let
bulwahn@47629
   327
           val (tyenv, tenv) =
bulwahn@47629
   328
             Pattern.match (Proof_Context.theory_of ctxt) (Thm.concl_of th, t) (Vartab.empty, Vartab.empty)
bulwahn@47629
   329
         in SOME (map (Envir.subst_term (tyenv, tenv)) (Thm.prems_of th)) end
bulwahn@47629
   330
    fun all t =
bulwahn@47629
   331
      case retrieve_prems intros t of
bulwahn@47629
   332
        NONE => retrieve_prems unfolds t
bulwahn@47629
   333
      | SOME ts => SOME (maps (fn t => the_default [t] (all t)) ts)
bulwahn@47629
   334
  in
bulwahn@47629
   335
    all t
bulwahn@47629
   336
  end
bulwahn@47629
   337
bulwahn@42897
   338
fun test_goal (time_limit, is_interactive) (insts, eval_terms) i state =
bulwahn@40896
   339
  let
bulwahn@40896
   340
    val lthy = Proof.context_of state;
bulwahn@40896
   341
    val thy = Proof.theory_of state;
bulwahn@46636
   342
    val _ = message lthy "Quickchecking..."
bulwahn@40896
   343
    fun strip (Const ("all", _) $ Abs (_, _, t)) = strip t
bulwahn@40896
   344
      | strip t = t;
bulwahn@40896
   345
    val {goal = st, ...} = Proof.raw_goal state;
bulwahn@40896
   346
    val (gi, frees) = Logic.goal_params (prop_of st) i;
bulwahn@40896
   347
    val some_locale = case (Option.map #target o Named_Target.peek) lthy
bulwahn@40896
   348
     of NONE => NONE
bulwahn@40896
   349
      | SOME "" => NONE
bulwahn@40896
   350
      | SOME locale => SOME locale;
bulwahn@40896
   351
    val assms = if Config.get lthy no_assms then [] else case some_locale
bulwahn@40896
   352
     of NONE => Assumption.all_assms_of lthy
bulwahn@40896
   353
      | SOME locale => Assumption.local_assms_of lthy (Locale.init locale thy);
bulwahn@40896
   354
    val proto_goal = Logic.list_implies (map Thm.term_of assms, subst_bounds (frees, strip gi));
bulwahn@47629
   355
    fun axioms_of locale = case fst (Locale.specification_of thy locale) of
bulwahn@47629
   356
        NONE => []
bulwahn@47629
   357
      | SOME t => the_default [] (all_axioms_of lthy t)
bulwahn@43954
   358
    val goals = case some_locale
bulwahn@42897
   359
     of NONE => [(proto_goal, eval_terms)]
bulwahn@42897
   360
      | SOME locale =>
bulwahn@47629
   361
          (Logic.list_implies (axioms_of locale, proto_goal), eval_terms) ::
bulwahn@47171
   362
          map (fn (_, phi) => (Morphism.term phi proto_goal, map (Morphism.term phi) eval_terms))
bulwahn@42897
   363
          (Locale.registrations_of (Context.Theory thy) (*FIXME*) locale);
bulwahn@47629
   364
    val _ = verbose_message lthy (Pretty.string_of
bulwahn@47629
   365
      (Pretty.big_list ("Checking goals: ") (map (Syntax.pretty_term lthy o fst) goals)))
bulwahn@40896
   366
  in
bulwahn@46029
   367
    test_terms lthy (time_limit, is_interactive) insts goals
bulwahn@40896
   368
  end
bulwahn@40896
   369
bulwahn@38152
   370
(* pretty printing *)
haftmann@28315
   371
blanchet@40466
   372
fun tool_name auto = (if auto then "Auto " else "") ^ "Quickcheck"
blanchet@40466
   373
blanchet@40466
   374
fun pretty_counterex ctxt auto NONE = Pretty.str (tool_name auto ^ " found no counterexample.")
bulwahn@46601
   375
  | pretty_counterex ctxt auto (SOME ((genuine, cex), eval_terms)) =
bulwahn@46601
   376
      Pretty.chunks ((Pretty.str (tool_name auto ^ " found a " ^
bulwahn@46601
   377
        (if genuine then "counterexample:" else  "potentially spurious counterexample due to underspecified functions:") ^ "\n") ::
haftmann@28315
   378
        map (fn (s, t) =>
bulwahn@42899
   379
          Pretty.block [Pretty.str (s ^ " ="), Pretty.brk 1, Syntax.pretty_term ctxt t]) (rev cex))
blanchet@43861
   380
        @ (if null eval_terms then []
bulwahn@46029
   381
           else (Pretty.fbrk :: Pretty.str ("Evaluated terms:") ::
blanchet@43861
   382
             map (fn (t, u) =>
bulwahn@44752
   383
               Pretty.block [Syntax.pretty_term ctxt t, Pretty.str " =", Pretty.brk 1,
bulwahn@44752
   384
                 Syntax.pretty_term ctxt u]) (rev eval_terms))));
haftmann@28315
   385
bulwahn@35378
   386
fun pretty_report (Report {iterations = iterations, raised_match_errors = raised_match_errors,
bulwahn@35378
   387
    satisfied_assms = satisfied_assms, positive_concl_tests = positive_concl_tests}) =
bulwahn@35378
   388
  let
bulwahn@35378
   389
    fun pretty_stat s i = Pretty.block ([Pretty.str (s ^ ": " ^ string_of_int i)])
bulwahn@35378
   390
  in
bulwahn@35378
   391
     ([pretty_stat "iterations" iterations,
bulwahn@35378
   392
     pretty_stat "match exceptions" raised_match_errors]
wenzelm@41765
   393
     @ map_index
wenzelm@41765
   394
       (fn (i, n) => pretty_stat ("satisfied " ^ string_of_int (i + 1) ^ ". assumption") n)
bulwahn@35378
   395
       satisfied_assms
bulwahn@35378
   396
     @ [pretty_stat "positive conclusion tests" positive_concl_tests])
bulwahn@35378
   397
  end
bulwahn@35378
   398
bulwahn@35380
   399
fun pretty_reports ctxt (SOME reports) =
bulwahn@41160
   400
  Pretty.chunks (Pretty.fbrk :: Pretty.str "Quickcheck report:" ::
bulwahn@41153
   401
    maps (fn (size, report) =>
bulwahn@41153
   402
      Pretty.str ("size " ^ string_of_int size ^ ":") :: pretty_report report @ [Pretty.brk 1])
bulwahn@35378
   403
      (rev reports))
bulwahn@35380
   404
  | pretty_reports ctxt NONE = Pretty.str ""
bulwahn@35378
   405
bulwahn@42952
   406
fun pretty_timings timings =
bulwahn@42952
   407
  Pretty.chunks (Pretty.fbrk :: Pretty.str "timings:" ::
bulwahn@42952
   408
    maps (fn (label, time) =>
bulwahn@42952
   409
      Pretty.str (label ^ ": " ^ string_of_int time ^ " ms") :: Pretty.brk 1 :: []) (rev timings))
bulwahn@42952
   410
bulwahn@43299
   411
fun pretty_counterex_and_reports ctxt auto [] =
bulwahn@43299
   412
    Pretty.chunks [Pretty.strs (tool_name auto ::
bulwahn@43299
   413
        space_explode " " "is used in a locale where no interpretation is provided."),
bulwahn@43299
   414
      Pretty.strs (space_explode " " "Please provide an executable interpretation for the locale.")]
bulwahn@43299
   415
  | pretty_counterex_and_reports ctxt auto (result :: _) =
bulwahn@43299
   416
    Pretty.chunks (pretty_counterex ctxt auto (response_of result) ::
bulwahn@43299
   417
      (* map (pretty_reports ctxt) (reports_of result) :: *)
bulwahn@43299
   418
      (if Config.get ctxt timing then cons (pretty_timings (timings_of result)) else I) [])
haftmann@28315
   419
wenzelm@30981
   420
(* Isar commands *)
haftmann@28315
   421
haftmann@28336
   422
fun read_nat s = case (Library.read_int o Symbol.explode) s
haftmann@28336
   423
 of (k, []) => if k >= 0 then k
haftmann@28336
   424
      else error ("Not a natural number: " ^ s)
haftmann@28336
   425
  | (_, _ :: _) => error ("Not a natural number: " ^ s);
bulwahn@38149
   426
blanchet@34125
   427
fun read_bool "false" = false
blanchet@34125
   428
  | read_bool "true" = true
blanchet@34125
   429
  | read_bool s = error ("Not a Boolean value: " ^ s)
haftmann@28315
   430
bulwahn@40612
   431
fun read_real s =
bulwahn@40612
   432
  case (Real.fromString s) of
bulwahn@40612
   433
    SOME s => s
bulwahn@40612
   434
  | NONE => error ("Not a real number: " ^ s)
bulwahn@40612
   435
bulwahn@38169
   436
fun read_expectation "no_expectation" = No_Expectation
wenzelm@41765
   437
  | read_expectation "no_counterexample" = No_Counterexample
bulwahn@38169
   438
  | read_expectation "counterexample" = Counterexample
wenzelm@41765
   439
  | read_expectation s = error ("Not an expectation value: " ^ s)
bulwahn@38169
   440
bulwahn@44748
   441
fun valid_tester_name genctxt name = AList.defined (op =) (fst (fst (Data.get genctxt))) name
bulwahn@44748
   442
  
bulwahn@44752
   443
fun parse_tester name (testers, genctxt) =
bulwahn@41156
   444
  if valid_tester_name genctxt name then
bulwahn@44752
   445
    (insert (op =) name testers, genctxt)  
bulwahn@41156
   446
  else
bulwahn@41156
   447
    error ("Unknown tester: " ^ name)
bulwahn@41156
   448
bulwahn@44752
   449
fun parse_test_param ("tester", args) = fold parse_tester args
bulwahn@44752
   450
  | parse_test_param ("size", [arg]) = apsnd (Config.put_generic size (read_nat arg))
bulwahn@44752
   451
  | parse_test_param ("iterations", [arg]) = apsnd (Config.put_generic iterations (read_nat arg))
bulwahn@46084
   452
  | parse_test_param ("depth", [arg]) = apsnd (Config.put_generic depth (read_nat arg))  
bulwahn@44752
   453
  | parse_test_param ("default_type", arg) = (fn (testers, gen_ctxt) =>
bulwahn@44752
   454
    (testers, map_test_params
bulwahn@44752
   455
      ((apfst o K) (map (Proof_Context.read_typ (Context.proof_of gen_ctxt)) arg)) gen_ctxt))
bulwahn@44752
   456
  | parse_test_param ("no_assms", [arg]) = apsnd (Config.put_generic no_assms (read_bool arg))
bulwahn@44752
   457
  | parse_test_param ("expect", [arg]) = apsnd (map_test_params ((apsnd o K) (read_expectation arg)))
bulwahn@44752
   458
  | parse_test_param ("report", [arg]) = apsnd (Config.put_generic report (read_bool arg))
bulwahn@46628
   459
  | parse_test_param ("genuine_only", [arg]) = apsnd (Config.put_generic genuine_only (read_bool arg))
bulwahn@47329
   460
  | parse_test_param ("abort_potential", [arg]) = apsnd (Config.put_generic abort_potential (read_bool arg))
bulwahn@44752
   461
  | parse_test_param ("quiet", [arg]) = apsnd (Config.put_generic quiet (read_bool arg))
bulwahn@46635
   462
  | parse_test_param ("verbose", [arg]) = apsnd (Config.put_generic verbose (read_bool arg))
bulwahn@47436
   463
  | parse_test_param ("use_subtype", [arg]) = apsnd (Config.put_generic use_subtype (read_bool arg))  
bulwahn@44752
   464
  | parse_test_param ("timeout", [arg]) = apsnd (Config.put_generic timeout (read_real arg))
bulwahn@44752
   465
  | parse_test_param ("finite_types", [arg]) = apsnd (Config.put_generic finite_types (read_bool arg))
bulwahn@46320
   466
  | parse_test_param ("allow_function_inversion", [arg]) =
bulwahn@46320
   467
      apsnd (Config.put_generic allow_function_inversion (read_bool arg))
wenzelm@41765
   468
  | parse_test_param ("finite_type_size", [arg]) =
bulwahn@44752
   469
    apsnd (Config.put_generic finite_type_size (read_nat arg))
bulwahn@44752
   470
  | parse_test_param (name, _) = (fn (testers, genctxt) =>
bulwahn@41156
   471
    if valid_tester_name genctxt name then
bulwahn@44752
   472
      (insert (op =) name testers, genctxt)  
bulwahn@44752
   473
    else error ("Unknown tester or test parameter: " ^ name));
haftmann@28315
   474
bulwahn@44752
   475
fun proof_map_result f = apsnd Context.the_proof o f o Context.Proof;
bulwahn@44752
   476
bulwahn@44752
   477
fun parse_test_param_inst (name, arg) ((insts, eval_terms), (testers, ctxt)) =
wenzelm@43232
   478
      case try (Proof_Context.read_typ ctxt) name
bulwahn@42896
   479
       of SOME (TFree (v, _)) =>
bulwahn@44752
   480
         ((AList.update (op =) (v, Proof_Context.read_typ ctxt (the_single arg)) insts, eval_terms),
bulwahn@44752
   481
           (testers, ctxt))
bulwahn@42896
   482
        | NONE => (case name of
bulwahn@44752
   483
            "eval" => ((insts, eval_terms @ map (Syntax.read_term ctxt) arg), (testers, ctxt))
bulwahn@44752
   484
          | _ => ((insts, eval_terms),
bulwahn@44752
   485
            proof_map_result (fn gen_ctxt => parse_test_param (name, arg) (testers, gen_ctxt)) ctxt));
haftmann@28315
   486
bulwahn@44752
   487
fun quickcheck_params_cmd args = Context.theory_map
bulwahn@44752
   488
  (fn gen_ctxt => uncurry set_active_testers (fold parse_test_param args ([], gen_ctxt)));
wenzelm@41765
   489
bulwahn@42952
   490
fun check_expectation state results =
bulwahn@44750
   491
  (if is_some results andalso expect (Proof.context_of state) = No_Counterexample
bulwahn@42952
   492
  then
bulwahn@42952
   493
    error ("quickcheck expected to find no counterexample but found one")
bulwahn@42952
   494
  else
bulwahn@44750
   495
    (if is_none results andalso expect (Proof.context_of state) = Counterexample
bulwahn@42952
   496
    then
bulwahn@42952
   497
      error ("quickcheck expected to find a counterexample but did not find one")
bulwahn@42952
   498
    else ()))
bulwahn@42952
   499
bulwahn@35378
   500
fun gen_quickcheck args i state =
bulwahn@40892
   501
  state
bulwahn@44752
   502
  |> Proof.map_context_result (fn ctxt =>
bulwahn@44752
   503
    apsnd (fn (testers, ctxt) => Context.proof_map (set_active_testers testers) ctxt)
bulwahn@44752
   504
      (fold parse_test_param_inst args (([], []), ([], ctxt))))
bulwahn@42897
   505
  |> (fn ((insts, eval_terms), state') => test_goal (true, true) (insts, eval_terms) i state'
bulwahn@42952
   506
  |> tap (check_expectation state'))
boehmes@32295
   507
bulwahn@44750
   508
fun quickcheck args i state =
bulwahn@44750
   509
  Option.map (the o get_first counterexample_of) (gen_quickcheck args i state)
bulwahn@35378
   510
boehmes@32295
   511
fun quickcheck_cmd args i state =
bulwahn@35378
   512
  gen_quickcheck args i (Toplevel.proof_of state)
bulwahn@44750
   513
  |> Option.map (the o get_first response_of)
blanchet@43861
   514
  |> Output.urgent_message o Pretty.string_of
bulwahn@44750
   515
     o pretty_counterex (Toplevel.context_of state) false;
haftmann@28309
   516
wenzelm@41765
   517
val parse_arg =
wenzelm@41765
   518
  Parse.name --
wenzelm@41765
   519
    (Scan.optional (Parse.$$$ "=" |--
wenzelm@41765
   520
      (((Parse.name || Parse.float_number) >> single) ||
wenzelm@41765
   521
        (Parse.$$$ "[" |-- Parse.list1 Parse.name --| Parse.$$$ "]"))) ["true"]);
haftmann@28309
   522
wenzelm@41765
   523
val parse_args =
wenzelm@41765
   524
  Parse.$$$ "[" |-- Parse.list1 parse_arg --| Parse.$$$ "]" || Scan.succeed [];
haftmann@28336
   525
wenzelm@36970
   526
val _ =
blanchet@43861
   527
  Outer_Syntax.command quickcheck_paramsN "set parameters for random testing" Keyword.thy_decl
wenzelm@36970
   528
    (parse_args >> (fn args => Toplevel.theory (quickcheck_params_cmd args)));
haftmann@28309
   529
wenzelm@36970
   530
val _ =
blanchet@43861
   531
  Outer_Syntax.improper_command quickcheckN "try to find counterexample for subgoal" Keyword.diag
wenzelm@36970
   532
    (parse_args -- Scan.optional Parse.nat 1
wenzelm@36970
   533
      >> (fn (args, i) => Toplevel.no_timing o Toplevel.keep (quickcheck_cmd args i)));
haftmann@28309
   534
blanchet@43861
   535
(* automatic testing *)
blanchet@43861
   536
blanchet@43861
   537
fun try_quickcheck auto state =
blanchet@43861
   538
  let
blanchet@43861
   539
    val ctxt = Proof.context_of state;
blanchet@43861
   540
    val i = 1;
blanchet@43861
   541
    val res =
blanchet@43861
   542
      state
blanchet@43861
   543
      |> Proof.map_context (Config.put report false #> Config.put quiet true)
blanchet@43861
   544
      |> try (test_goal (false, false) ([], []) i);
blanchet@43861
   545
  in
blanchet@43861
   546
    case res of
blanchet@43861
   547
      NONE => (unknownN, state)
blanchet@43861
   548
    | SOME results =>
blanchet@43861
   549
        let
bulwahn@44750
   550
          val msg = pretty_counterex ctxt auto (Option.map (the o get_first response_of) results)
blanchet@43861
   551
        in
bulwahn@44750
   552
          if is_some results then
blanchet@43861
   553
            (genuineN,
blanchet@43870
   554
             state
blanchet@43870
   555
             |> (if auto then
blanchet@43870
   556
                   Proof.goal_message (K (Pretty.chunks [Pretty.str "",
wenzelm@46537
   557
                       Pretty.mark Isabelle_Markup.hilite msg]))
blanchet@43870
   558
                 else
blanchet@43870
   559
                   tap (fn _ => Output.urgent_message (Pretty.string_of msg))))
blanchet@43861
   560
          else
blanchet@43861
   561
            (noneN, state)
blanchet@43861
   562
        end
blanchet@43861
   563
  end
blanchet@43861
   564
  |> `(fn (outcome_code, _) => outcome_code = genuineN)
blanchet@43861
   565
blanchet@43870
   566
val setup = Try.register_tool (quickcheckN, (20, auto, try_quickcheck))
blanchet@43861
   567
haftmann@28309
   568
end;
haftmann@28256
   569
haftmann@28315
   570
val auto_quickcheck = Quickcheck.auto;