src/Tools/quickcheck.ML
author bulwahn
Fri, 01 Apr 2011 13:49:36 +0200
changeset 43065 bd416284a432
parent 43059 f6bc441fbf19
child 43071 ded5ba6b7bac
permissions -rw-r--r--
adding general interface for batch validators in quickcheck
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
bulwahn@38150
     9
  val setup: theory -> theory
bulwahn@38150
    10
  (* configuration *)
wenzelm@32740
    11
  val auto: bool Unsynchronized.ref
wenzelm@41765
    12
  val tester : string Config.T
bulwahn@40892
    13
  val size : int Config.T
bulwahn@40892
    14
  val iterations : int Config.T
bulwahn@40892
    15
  val no_assms : bool Config.T
bulwahn@40892
    16
  val report : bool Config.T
bulwahn@42952
    17
  val timing : bool Config.T
bulwahn@40892
    18
  val quiet : bool Config.T
bulwahn@40892
    19
  val timeout : real Config.T
bulwahn@40896
    20
  val finite_types : bool Config.T
bulwahn@40896
    21
  val finite_type_size : int Config.T
wenzelm@41765
    22
  datatype expectation = No_Expectation | No_Counterexample | Counterexample;
bulwahn@40892
    23
  datatype test_params = Test_Params of {default_type: typ list, expect : expectation};
bulwahn@40481
    24
  val test_params_of : Proof.context -> test_params
bulwahn@40892
    25
  val map_test_params : (typ list * expectation -> typ list * expectation)
bulwahn@40481
    26
    -> Context.generic -> Context.generic
bulwahn@42953
    27
  datatype report = Report of
bulwahn@42953
    28
    { iterations : int, raised_match_errors : int,
bulwahn@42953
    29
      satisfied_assms : int list, positive_concl_tests : int }
bulwahn@42953
    30
  (* registering generators *)
bulwahn@38150
    31
  val add_generator:
bulwahn@43030
    32
    string * (Proof.context -> (term * term list) list -> int list -> term list option * report option)
bulwahn@39479
    33
      -> Context.generic -> Context.generic
bulwahn@42733
    34
  val add_batch_generator:
bulwahn@42733
    35
    string * (Proof.context -> term list -> (int -> term list option) list)
bulwahn@42733
    36
      -> Context.generic -> Context.generic
bulwahn@43065
    37
  val add_batch_validator:
bulwahn@43065
    38
    string * (Proof.context -> term list -> (int -> bool) list)
bulwahn@43065
    39
      -> Context.generic -> Context.generic
bulwahn@42953
    40
  (* quickcheck's result *)
bulwahn@42952
    41
  datatype result =
bulwahn@42952
    42
    Result of
bulwahn@42952
    43
     {counterexample : (string * term) list option,
bulwahn@42952
    44
      evaluation_terms : (term * term) list option,
bulwahn@42952
    45
      timings : (string * int) list,
bulwahn@42952
    46
      reports : (int * report) list}
bulwahn@42953
    47
  val counterexample_of : result -> (string * term) list option
bulwahn@42953
    48
  val timings_of : result -> (string * int) list
bulwahn@38150
    49
  (* testing terms and proof states *)
bulwahn@42952
    50
  val test_term: Proof.context -> bool * bool -> term * term list -> result
bulwahn@40896
    51
  val test_goal_terms:
bulwahn@42897
    52
    Proof.context -> bool * bool -> (string * typ) list -> (term * term list) list  
bulwahn@42952
    53
      -> result list
bulwahn@38149
    54
  val quickcheck: (string * string list) list -> int -> Proof.state -> (string * term) list option
bulwahn@42733
    55
  (* testing a batch of terms *)
bulwahn@43059
    56
  val test_terms:
bulwahn@43059
    57
    Proof.context -> term list -> (string * term) list option list option * (string * int) list
bulwahn@43065
    58
  val validate_terms: Proof.context -> term list -> bool list option * (string * int) list
haftmann@28256
    59
end;
haftmann@28256
    60
haftmann@28256
    61
structure Quickcheck : QUICKCHECK =
haftmann@28256
    62
struct
haftmann@28256
    63
wenzelm@30981
    64
(* preferences *)
wenzelm@30981
    65
wenzelm@32740
    66
val auto = Unsynchronized.ref false;
wenzelm@30981
    67
wenzelm@30981
    68
val _ =
wenzelm@30981
    69
  ProofGeneralPgip.add_preference Preferences.category_tracing
wenzelm@39862
    70
  (Unsynchronized.setmp auto true (fn () =>
wenzelm@30981
    71
    Preferences.bool_pref auto
wenzelm@30981
    72
      "auto-quickcheck"
blanchet@39575
    73
      "Run Quickcheck automatically.") ());
wenzelm@30981
    74
bulwahn@35378
    75
(* quickcheck report *)
bulwahn@35378
    76
bulwahn@35378
    77
datatype report = Report of
bulwahn@35378
    78
  { iterations : int, raised_match_errors : int,
bulwahn@35378
    79
    satisfied_assms : int list, positive_concl_tests : int }
bulwahn@35378
    80
bulwahn@42952
    81
(* Quickcheck Result *)
bulwahn@42952
    82
bulwahn@42952
    83
datatype result = Result of
bulwahn@42952
    84
  { counterexample : (string * term) list option, evaluation_terms : (term * term) list option,
bulwahn@42952
    85
    timings : (string * int) list, reports : (int * report) list}
bulwahn@42952
    86
bulwahn@42952
    87
val empty_result =
bulwahn@42952
    88
  Result {counterexample = NONE, evaluation_terms = NONE, timings = [], reports = []}
bulwahn@42952
    89
bulwahn@42952
    90
fun counterexample_of (Result r) = #counterexample r
bulwahn@42952
    91
bulwahn@42952
    92
fun found_counterexample (Result r) = is_some (#counterexample r)
bulwahn@42952
    93
bulwahn@42952
    94
fun response_of (Result r) = case (#counterexample r, #evaluation_terms r) of
bulwahn@42952
    95
    (SOME ts, SOME evals) => SOME (ts, evals)
bulwahn@42952
    96
  | (NONE, NONE) => NONE
bulwahn@42952
    97
bulwahn@42952
    98
fun timings_of (Result r) = #timings r
bulwahn@42952
    99
bulwahn@42952
   100
fun set_reponse names eval_terms (SOME ts) (Result r) =
bulwahn@42952
   101
  let
bulwahn@42952
   102
    val (ts1, ts2) = chop (length names) ts
bulwahn@42952
   103
  in
bulwahn@42952
   104
    Result {counterexample = SOME (names ~~ ts1), evaluation_terms = SOME (eval_terms ~~ ts2),
bulwahn@42952
   105
      timings = #timings r, reports = #reports r}
bulwahn@42952
   106
  end
bulwahn@42952
   107
  | set_reponse _ _ NONE result = result
bulwahn@42952
   108
bulwahn@42952
   109
fun cons_timing timing (Result r) =
bulwahn@42952
   110
  Result {counterexample = #counterexample r, evaluation_terms = #evaluation_terms r,
bulwahn@42952
   111
    timings = cons timing (#timings r), reports = #reports r}
bulwahn@42952
   112
bulwahn@42952
   113
fun cons_report size (SOME report) (Result r) =
bulwahn@42952
   114
  Result {counterexample = #counterexample r, evaluation_terms = #evaluation_terms r,
bulwahn@42952
   115
    timings = #timings r, reports = cons (size, report) (#reports r)}
bulwahn@42952
   116
  | cons_report _ NONE result = result
bulwahn@42952
   117
bulwahn@42952
   118
fun add_timing timing result_ref = (result_ref := cons_timing timing (!result_ref))
bulwahn@42952
   119
bulwahn@42952
   120
fun add_report size report result_ref = (result_ref := cons_report size report (!result_ref))
bulwahn@42952
   121
bulwahn@42952
   122
fun add_response names eval_terms response result_ref =
bulwahn@42952
   123
  (result_ref := set_reponse names eval_terms response (!result_ref))
bulwahn@42952
   124
bulwahn@38169
   125
(* expectation *)
bulwahn@38169
   126
wenzelm@41765
   127
datatype expectation = No_Expectation | No_Counterexample | Counterexample;
bulwahn@38169
   128
bulwahn@38169
   129
fun merge_expectation (expect1, expect2) =
bulwahn@38169
   130
  if expect1 = expect2 then expect1 else No_Expectation
bulwahn@38169
   131
haftmann@28315
   132
(* quickcheck configuration -- default parameters, test generators *)
bulwahn@41152
   133
val (tester, setup_tester) = Attrib.config_string "quickcheck_tester" (K "")
bulwahn@40892
   134
val (size, setup_size) = Attrib.config_int "quickcheck_size" (K 10)
bulwahn@40892
   135
val (iterations, setup_iterations) = Attrib.config_int "quickcheck_iterations" (K 100)
bulwahn@40892
   136
val (no_assms, setup_no_assms) = Attrib.config_bool "quickcheck_no_assms" (K false)
bulwahn@40892
   137
val (report, setup_report) = Attrib.config_bool "quickcheck_report" (K true)
bulwahn@42952
   138
val (timing, setup_timing) = Attrib.config_bool "quickcheck_timing" (K false)
bulwahn@40892
   139
val (quiet, setup_quiet) = Attrib.config_bool "quickcheck_quiet" (K false)
bulwahn@40892
   140
val (timeout, setup_timeout) = Attrib.config_real "quickcheck_timeout" (K 30.0)
bulwahn@40894
   141
val (finite_types, setup_finite_types) = Attrib.config_bool "quickcheck_finite_types" (K true)
wenzelm@41765
   142
val (finite_type_size, setup_finite_type_size) =
wenzelm@41765
   143
  Attrib.config_int "quickcheck_finite_type_size" (K 3)
haftmann@28315
   144
bulwahn@40892
   145
val setup_config =
bulwahn@42952
   146
  setup_tester #> setup_size #> setup_iterations #> setup_no_assms #> setup_report #> setup_timing
bulwahn@42952
   147
    #> setup_quiet #> setup_timeout #> setup_finite_types #> setup_finite_type_size
bulwahn@40894
   148
haftmann@28309
   149
datatype test_params = Test_Params of
bulwahn@40892
   150
  {default_type: typ list, expect : expectation};
haftmann@28309
   151
bulwahn@40892
   152
fun dest_test_params (Test_Params {default_type, expect}) = (default_type, expect);
wenzelm@39034
   153
wenzelm@41765
   154
fun make_test_params (default_type, expect) =
wenzelm@41765
   155
  Test_Params {default_type = default_type, expect = expect};
wenzelm@39034
   156
wenzelm@41765
   157
fun map_test_params' f (Test_Params {default_type, expect}) =
wenzelm@41765
   158
  make_test_params (f (default_type, expect));
wenzelm@39034
   159
wenzelm@39034
   160
fun merge_test_params
wenzelm@41720
   161
  (Test_Params {default_type = default_type1, expect = expect1},
wenzelm@41720
   162
    Test_Params {default_type = default_type2, expect = expect2}) =
wenzelm@41720
   163
  make_test_params
wenzelm@41720
   164
    (merge (op =) (default_type1, default_type2), merge_expectation (expect1, expect2));
haftmann@28309
   165
bulwahn@39479
   166
structure Data = Generic_Data
wenzelm@33522
   167
(
wenzelm@39034
   168
  type T =
bulwahn@43030
   169
    ((string * (Proof.context -> (term * term list) list -> int list -> term list option * report option)) list
bulwahn@43065
   170
      * ((string * (Proof.context -> term list -> (int -> term list option) list)) list
bulwahn@43065
   171
      * ((string * (Proof.context -> term list -> (int -> bool) list)) list)))
wenzelm@39034
   172
      * test_params;
bulwahn@43065
   173
  val empty = (([], ([], [])), Test_Params {default_type = [], expect = No_Expectation});
haftmann@28256
   174
  val extend = I;
bulwahn@43065
   175
  fun merge (((generators1, (batch_generators1, batch_validators1)), params1),
bulwahn@43065
   176
    ((generators2, (batch_generators2, batch_validators2)), params2)) : T =
bulwahn@42733
   177
    ((AList.merge (op =) (K true) (generators1, generators2),
bulwahn@43065
   178
     (AList.merge (op =) (K true) (batch_generators1, batch_generators2),
bulwahn@43065
   179
      AList.merge (op =) (K true) (batch_validators1, batch_validators2))),
haftmann@28309
   180
      merge_test_params (params1, params2));
wenzelm@33522
   181
);
haftmann@28256
   182
bulwahn@39479
   183
val test_params_of = snd o Data.get o Context.Proof;
bulwahn@38150
   184
bulwahn@40892
   185
val default_type = fst o dest_test_params o test_params_of
bulwahn@40481
   186
bulwahn@40892
   187
val expect = snd o dest_test_params o test_params_of
bulwahn@40481
   188
bulwahn@40481
   189
val map_test_params = Data.map o apsnd o map_test_params'
bulwahn@39480
   190
bulwahn@42733
   191
val add_generator = Data.map o apfst o apfst o AList.update (op =);
bulwahn@42733
   192
bulwahn@43065
   193
val add_batch_generator = Data.map o apfst o apsnd o apfst o AList.update (op =);
bulwahn@43065
   194
bulwahn@43065
   195
val add_batch_validator = Data.map o apfst o apsnd o apsnd o AList.update (op =);
haftmann@28256
   196
haftmann@28315
   197
(* generating tests *)
haftmann@28315
   198
bulwahn@42733
   199
fun gen_mk_tester lookup ctxt v =
haftmann@28309
   200
  let
bulwahn@41153
   201
    val name = Config.get ctxt tester
bulwahn@42733
   202
    val tester = case lookup ctxt name
bulwahn@41153
   203
      of NONE => error ("No such quickcheck tester: " ^ name)
bulwahn@41153
   204
      | SOME tester => tester ctxt;
wenzelm@40491
   205
  in
bulwahn@41153
   206
    if Config.get ctxt quiet then
bulwahn@42733
   207
      try tester v
bulwahn@41153
   208
    else
bulwahn@41153
   209
      let
bulwahn@42733
   210
        val tester = Exn.interruptible_capture tester v
bulwahn@41153
   211
      in case Exn.get_result tester of
bulwahn@41153
   212
          NONE => SOME (Exn.release tester)
bulwahn@41153
   213
        | SOME tester => SOME tester
bulwahn@41153
   214
      end
bulwahn@41153
   215
  end
haftmann@28315
   216
bulwahn@43065
   217
val mk_tester =
bulwahn@43065
   218
  gen_mk_tester (fn ctxt => AList.lookup (op =) ((fst o fst o Data.get o Context.Proof) ctxt))
bulwahn@43065
   219
val mk_batch_tester =
bulwahn@43065
   220
  gen_mk_tester (fn ctxt => AList.lookup (op =) ((fst o snd o fst o Data.get o Context.Proof) ctxt))
bulwahn@43065
   221
val mk_batch_validator =
bulwahn@43065
   222
  gen_mk_tester (fn ctxt => AList.lookup (op =) ((snd o snd o fst o Data.get o Context.Proof) ctxt))
bulwahn@43065
   223
haftmann@28315
   224
(* testing propositions *)
haftmann@28315
   225
bulwahn@42899
   226
fun check_test_term t =
haftmann@28309
   227
  let
wenzelm@29266
   228
    val _ = (null (Term.add_tvars t []) andalso null (Term.add_tfrees t [])) orelse
haftmann@28309
   229
      error "Term to be tested contains type variables";
wenzelm@29266
   230
    val _ = null (Term.add_vars t []) orelse
haftmann@28309
   231
      error "Term to be tested contains schematic variables";
bulwahn@42899
   232
  in () end
haftmann@28309
   233
wenzelm@42885
   234
fun cpu_time description e =
wenzelm@42885
   235
  let val ({cpu, ...}, result) = Timing.timing e ()
wenzelm@42885
   236
  in (result, (description, Time.toMilliseconds cpu)) end
wenzelm@41765
   237
bulwahn@42625
   238
fun limit ctxt (limit_time, is_interactive) f exc () =
bulwahn@42625
   239
  if limit_time then
bulwahn@42625
   240
      TimeLimit.timeLimit (seconds (Config.get ctxt timeout)) f ()
bulwahn@42625
   241
    handle TimeLimit.TimeOut =>
bulwahn@42625
   242
      if is_interactive then exc () else raise TimeLimit.TimeOut
bulwahn@42625
   243
  else
bulwahn@42625
   244
    f ()
bulwahn@42624
   245
bulwahn@42897
   246
fun test_term ctxt (limit_time, is_interactive) (t, eval_terms) =
bulwahn@42733
   247
  let
bulwahn@42952
   248
    fun message s = if Config.get ctxt quiet then () else Output.urgent_message s
bulwahn@42899
   249
    val _ = check_test_term t
bulwahn@42899
   250
    val names = Term.add_free_names t []
bulwahn@40612
   251
    val current_size = Unsynchronized.ref 0
bulwahn@42952
   252
    val current_result = Unsynchronized.ref empty_result 
bulwahn@42951
   253
    fun excipit () =
bulwahn@42951
   254
      "Quickcheck ran out of time while testing at size " ^ string_of_int (!current_size)
bulwahn@42952
   255
    fun with_size test_fun k =
bulwahn@41155
   256
      if k > Config.get ctxt size then
bulwahn@42952
   257
        NONE
bulwahn@41155
   258
      else
bulwahn@35378
   259
        let
bulwahn@42952
   260
          val _ = message ("Test data size: " ^ string_of_int k)
bulwahn@40896
   261
          val _ = current_size := k
bulwahn@42952
   262
          val ((result, report), timing) =
bulwahn@43030
   263
            cpu_time ("size " ^ string_of_int k) (fn () => test_fun [1, k - 1])
bulwahn@42952
   264
          val _ = add_timing timing current_result
bulwahn@42952
   265
          val _ = add_report k report current_result
wenzelm@41765
   266
        in
bulwahn@42952
   267
          case result of NONE => with_size test_fun (k + 1) | SOME q => SOME q
wenzelm@41765
   268
        end;
bulwahn@34935
   269
  in
bulwahn@43033
   270
    limit ctxt (limit_time, is_interactive) (fn () =>
bulwahn@43033
   271
      let
bulwahn@43033
   272
        val (test_fun, comp_time) = cpu_time "quickcheck compilation"
bulwahn@43033
   273
          (fn () => mk_tester ctxt [(t, eval_terms)]);
bulwahn@43033
   274
        val _ = add_timing comp_time current_result
bulwahn@43033
   275
      in
bulwahn@43033
   276
        case test_fun of NONE => !current_result
bulwahn@43033
   277
          | SOME test_fun =>
bulwahn@43033
   278
            let
bulwahn@43033
   279
              val (response, exec_time) =
bulwahn@43033
   280
                cpu_time "quickcheck execution" (fn () => with_size test_fun 1)
bulwahn@43033
   281
              val _ = add_response names eval_terms response current_result
bulwahn@43033
   282
              val _ = add_timing exec_time current_result
bulwahn@43033
   283
            in
bulwahn@43033
   284
              !current_result
bulwahn@43033
   285
            end
bulwahn@43033
   286
       end)
bulwahn@43033
   287
     (fn () => (message (excipit ()); !current_result)) ()
haftmann@28309
   288
  end;
haftmann@28309
   289
bulwahn@43065
   290
fun validate_terms ctxt ts =
bulwahn@43065
   291
  let
bulwahn@43065
   292
    val _ = map check_test_term ts
bulwahn@43065
   293
    val size = Config.get ctxt size
bulwahn@43065
   294
    val (test_funs, comp_time) = cpu_time "quickcheck batch compilation"
bulwahn@43065
   295
      (fn () => mk_batch_validator ctxt ts) 
bulwahn@43065
   296
    fun with_size tester k =
bulwahn@43065
   297
      if k > size then true
bulwahn@43065
   298
      else if tester k then with_size tester (k + 1) else false
bulwahn@43065
   299
    val (results, exec_time) = cpu_time "quickcheck batch execution" (fn () =>
bulwahn@43065
   300
        Option.map (map (fn test_fun => TimeLimit.timeLimit (seconds (Config.get ctxt timeout))
bulwahn@43065
   301
              (fn () => with_size test_fun 1) ()
bulwahn@43065
   302
             handle TimeLimit.TimeOut => true)) test_funs)
bulwahn@43065
   303
  in
bulwahn@43065
   304
    (results, [comp_time, exec_time])
bulwahn@43065
   305
  end
bulwahn@43065
   306
  
bulwahn@42733
   307
fun test_terms ctxt ts =
bulwahn@42733
   308
  let
bulwahn@42899
   309
    val _ = map check_test_term ts
bulwahn@43065
   310
    val size = Config.get ctxt size
bulwahn@42899
   311
    val namess = map (fn t => Term.add_free_names t []) ts
bulwahn@43059
   312
    val (test_funs, comp_time) = cpu_time "quickcheck batch compilation" (fn () => mk_batch_tester ctxt ts) 
bulwahn@42733
   313
    fun with_size tester k =
bulwahn@43065
   314
      if k > size then NONE
bulwahn@42733
   315
      else case tester k of SOME ts => SOME ts | NONE => with_size tester (k + 1)
bulwahn@43059
   316
    val (results, exec_time) = cpu_time "quickcheck batch execution" (fn () =>
bulwahn@43059
   317
        Option.map (map (fn test_fun => TimeLimit.timeLimit (seconds (Config.get ctxt timeout))
bulwahn@43065
   318
              (fn () => with_size test_fun 1) ()
bulwahn@43059
   319
             handle TimeLimit.TimeOut => NONE)) test_funs)
bulwahn@42733
   320
  in
bulwahn@43059
   321
    (Option.map (map2 (fn names => Option.map (fn ts => names ~~ ts)) namess) results,
bulwahn@43059
   322
      [comp_time, exec_time])
bulwahn@42733
   323
  end
bulwahn@42733
   324
bulwahn@41334
   325
(* FIXME: this function shows that many assumptions are made upon the generation *)
bulwahn@41334
   326
(* In the end there is probably no generic quickcheck interface left... *)
bulwahn@41334
   327
bulwahn@42625
   328
fun test_term_with_increasing_cardinality ctxt (limit_time, is_interactive) ts =
bulwahn@41291
   329
  let
bulwahn@41334
   330
    val thy = ProofContext.theory_of ctxt
bulwahn@42952
   331
    fun message s = if Config.get ctxt quiet then () else Output.urgent_message s
bulwahn@43030
   332
    val (ts', eval_terms) = split_list ts
bulwahn@43030
   333
    val _ = map check_test_term ts'
bulwahn@43030
   334
    val names = Term.add_free_names (hd ts') []
bulwahn@43030
   335
    val Ts = map snd (Term.add_frees (hd ts') [])
bulwahn@43033
   336
    val current_result = Unsynchronized.ref empty_result
bulwahn@43033
   337
    fun test_card_size test_fun (card, size) =
bulwahn@41291
   338
      (* FIXME: why decrement size by one? *)
bulwahn@42952
   339
      let
bulwahn@42952
   340
        val (ts, timing) = cpu_time ("size " ^ string_of_int size ^ " and card " ^ string_of_int card)
bulwahn@43033
   341
          (fn () => fst (test_fun [card - 1, size - 1]))
bulwahn@42952
   342
        val _ = add_timing timing current_result
bulwahn@42952
   343
      in
bulwahn@42952
   344
        Option.map (pair card) ts
bulwahn@42952
   345
      end
bulwahn@41291
   346
    val enumeration_card_size =
bulwahn@41334
   347
      if forall (fn T => Sign.of_sort thy (T,  ["Enum.enum"])) Ts then
bulwahn@41334
   348
        (* size does not matter *)
bulwahn@41334
   349
        map (rpair 0) (1 upto (length ts))
bulwahn@41334
   350
      else
bulwahn@41334
   351
        (* size does matter *)
bulwahn@41334
   352
        map_product pair (1 upto (length ts)) (1 upto (Config.get ctxt size))
bulwahn@41334
   353
        |> sort (fn ((c1, s1), (c2, s2)) => int_ord ((c1 + s1), (c2 + s2)))
bulwahn@43033
   354
  in
bulwahn@43033
   355
    limit ctxt (limit_time, is_interactive) (fn () =>
bulwahn@43033
   356
      let
bulwahn@43033
   357
        val (test_fun, comp_time) = cpu_time "quickcheck compilation" (fn () => mk_tester ctxt ts)
bulwahn@43033
   358
        val _ = add_timing comp_time current_result
bulwahn@43033
   359
      in
bulwahn@43033
   360
        case test_fun of
bulwahn@43030
   361
          NONE => !current_result
bulwahn@43030
   362
        | SOME test_fun =>
bulwahn@42952
   363
          let
bulwahn@43033
   364
            val _ = case get_first (test_card_size test_fun) enumeration_card_size of
bulwahn@42952
   365
              SOME (card, ts) => add_response names (nth eval_terms (card - 1)) (SOME ts) current_result
bulwahn@42952
   366
            | NONE => ()
bulwahn@43033
   367
          in !current_result end
bulwahn@43033
   368
      end)
bulwahn@43033
   369
      (fn () => (message "Quickcheck ran out of time"; !current_result)) ()
bulwahn@43033
   370
  end
bulwahn@41291
   371
bulwahn@40895
   372
fun get_finite_types ctxt =
bulwahn@40895
   373
  fst (chop (Config.get ctxt finite_type_size)
bulwahn@40895
   374
    (map (Type o rpair []) ["Enum.finite_1", "Enum.finite_2", "Enum.finite_3",
wenzelm@41765
   375
     "Enum.finite_4", "Enum.finite_5"]))
bulwahn@40895
   376
bulwahn@38153
   377
exception WELLSORTED of string
bulwahn@38153
   378
wenzelm@41765
   379
fun monomorphic_term thy insts default_T =
haftmann@28309
   380
  let
haftmann@28309
   381
    fun subst (T as TFree (v, S)) =
bulwahn@41147
   382
      let
bulwahn@41147
   383
        val T' = AList.lookup (op =) insts v
bulwahn@41147
   384
          |> the_default default_T
bulwahn@41147
   385
      in if Sign.of_sort thy (T', S) then T'
wenzelm@41765
   386
        else raise (WELLSORTED ("For instantiation with default_type " ^
wenzelm@41765
   387
          Syntax.string_of_typ_global thy default_T ^
bulwahn@41147
   388
          ":\n" ^ Syntax.string_of_typ_global thy T' ^
bulwahn@41147
   389
          " to be substituted for variable " ^
bulwahn@41147
   390
          Syntax.string_of_typ_global thy T ^ " does not have sort " ^
bulwahn@41147
   391
          Syntax.string_of_sort_global thy S))
bulwahn@41147
   392
      end
haftmann@28309
   393
      | subst T = T;
haftmann@28309
   394
  in (map_types o map_atyps) subst end;
haftmann@28309
   395
bulwahn@42897
   396
datatype wellsorted_error = Wellsorted_Error of string | Term of term * term list
bulwahn@38153
   397
bulwahn@42625
   398
fun test_goal_terms lthy (limit_time, is_interactive) insts check_goals =
haftmann@28309
   399
  let
bulwahn@42897
   400
    fun map_goal_and_eval_terms f (check_goal, eval_terms) = (f check_goal, map f eval_terms)
wenzelm@41765
   401
    val thy = ProofContext.theory_of lthy
bulwahn@41170
   402
    val default_insts =
bulwahn@41170
   403
      if Config.get lthy finite_types then (get_finite_types lthy) else (default_type lthy)
bulwahn@40895
   404
    val inst_goals =
bulwahn@42897
   405
      map (fn (check_goal, eval_terms) =>
bulwahn@41170
   406
        if not (null (Term.add_tfree_names check_goal [])) then
bulwahn@41170
   407
          map (fn T =>
bulwahn@42897
   408
            (pair (SOME T) o Term o apfst (Object_Logic.atomize_term thy))
bulwahn@42897
   409
              (map_goal_and_eval_terms (monomorphic_term thy insts T) (check_goal, eval_terms))
bulwahn@41291
   410
              handle WELLSORTED s => (SOME T, Wellsorted_Error s)) default_insts
bulwahn@41170
   411
        else
bulwahn@42897
   412
          [(NONE, Term (Object_Logic.atomize_term thy check_goal, eval_terms))]) check_goals
wenzelm@41765
   413
    val error_msg =
wenzelm@41765
   414
      cat_lines
wenzelm@41765
   415
        (maps (map_filter (fn (_, Term t) => NONE | (_, Wellsorted_Error s) => SOME s)) inst_goals)
bulwahn@41291
   416
    fun is_wellsorted_term (T, Term t) = SOME (T, t)
bulwahn@41291
   417
      | is_wellsorted_term (_, Wellsorted_Error s) = NONE
bulwahn@38153
   418
    val correct_inst_goals =
bulwahn@41291
   419
      case map (map_filter is_wellsorted_term) inst_goals of
bulwahn@41291
   420
        [[]] => error error_msg
bulwahn@38153
   421
      | xs => xs
bulwahn@40892
   422
    val _ = if Config.get lthy quiet then () else warning error_msg
bulwahn@42952
   423
    fun collect_results f [] results = results
bulwahn@42952
   424
      | collect_results f (t :: ts) results =
bulwahn@42952
   425
        let
bulwahn@42952
   426
          val result = f t
bulwahn@42952
   427
        in
bulwahn@42952
   428
          if found_counterexample result then
bulwahn@42952
   429
            (result :: results)
bulwahn@42952
   430
          else
bulwahn@42952
   431
            collect_results f ts (result :: results)
bulwahn@42952
   432
        end
bulwahn@41291
   433
    fun test_term' goal =
bulwahn@41291
   434
      case goal of
bulwahn@42625
   435
        [(NONE, t)] => test_term lthy (limit_time, is_interactive) t
bulwahn@42625
   436
      | ts => test_term_with_increasing_cardinality lthy (limit_time, is_interactive) (map snd ts)
bulwahn@41291
   437
  in
bulwahn@41291
   438
    if Config.get lthy finite_types then
bulwahn@42952
   439
      collect_results test_term' correct_inst_goals []
bulwahn@41291
   440
    else
bulwahn@42952
   441
      collect_results (test_term lthy (limit_time, is_interactive)) (maps (map snd) correct_inst_goals) []
bulwahn@41291
   442
  end;
bulwahn@38152
   443
bulwahn@42897
   444
fun test_goal (time_limit, is_interactive) (insts, eval_terms) i state =
bulwahn@40896
   445
  let
bulwahn@40896
   446
    val lthy = Proof.context_of state;
bulwahn@40896
   447
    val thy = Proof.theory_of state;
bulwahn@40896
   448
    fun strip (Const ("all", _) $ Abs (_, _, t)) = strip t
bulwahn@40896
   449
      | strip t = t;
bulwahn@40896
   450
    val {goal = st, ...} = Proof.raw_goal state;
bulwahn@40896
   451
    val (gi, frees) = Logic.goal_params (prop_of st) i;
bulwahn@40896
   452
    val some_locale = case (Option.map #target o Named_Target.peek) lthy
bulwahn@40896
   453
     of NONE => NONE
bulwahn@40896
   454
      | SOME "" => NONE
bulwahn@40896
   455
      | SOME locale => SOME locale;
bulwahn@40896
   456
    val assms = if Config.get lthy no_assms then [] else case some_locale
bulwahn@40896
   457
     of NONE => Assumption.all_assms_of lthy
bulwahn@40896
   458
      | SOME locale => Assumption.local_assms_of lthy (Locale.init locale thy);
bulwahn@40896
   459
    val proto_goal = Logic.list_implies (map Thm.term_of assms, subst_bounds (frees, strip gi));
bulwahn@40896
   460
    val check_goals = case some_locale
bulwahn@42897
   461
     of NONE => [(proto_goal, eval_terms)]
bulwahn@42897
   462
      | SOME locale =>
bulwahn@42897
   463
        map (fn (_, phi) => (Morphism.term phi proto_goal, map (Morphism.term phi) eval_terms))
bulwahn@42897
   464
          (Locale.registrations_of (Context.Theory thy) (*FIXME*) locale);
bulwahn@40896
   465
  in
bulwahn@42625
   466
    test_goal_terms lthy (time_limit, is_interactive) insts check_goals
bulwahn@40896
   467
  end
bulwahn@40896
   468
bulwahn@38152
   469
(* pretty printing *)
haftmann@28315
   470
blanchet@40466
   471
fun tool_name auto = (if auto then "Auto " else "") ^ "Quickcheck"
blanchet@40466
   472
blanchet@40466
   473
fun pretty_counterex ctxt auto NONE = Pretty.str (tool_name auto ^ " found no counterexample.")
bulwahn@42899
   474
  | pretty_counterex ctxt auto (SOME (cex, eval_terms)) =
bulwahn@42899
   475
      Pretty.chunks ((Pretty.str (tool_name auto ^ " found a counterexample:\n") ::
haftmann@28315
   476
        map (fn (s, t) =>
bulwahn@42899
   477
          Pretty.block [Pretty.str (s ^ " ="), Pretty.brk 1, Syntax.pretty_term ctxt t]) (rev cex))
bulwahn@42899
   478
        @ (Pretty.str ("Evaluated terms:\n") ::
bulwahn@42899
   479
        map (fn (t, u) =>
bulwahn@42899
   480
          Pretty.block [Syntax.pretty_term ctxt t, Pretty.str " =", Pretty.brk 1, Syntax.pretty_term ctxt u])
bulwahn@42899
   481
          (rev eval_terms)));
haftmann@28315
   482
bulwahn@35378
   483
fun pretty_report (Report {iterations = iterations, raised_match_errors = raised_match_errors,
bulwahn@35378
   484
    satisfied_assms = satisfied_assms, positive_concl_tests = positive_concl_tests}) =
bulwahn@35378
   485
  let
bulwahn@35378
   486
    fun pretty_stat s i = Pretty.block ([Pretty.str (s ^ ": " ^ string_of_int i)])
bulwahn@35378
   487
  in
bulwahn@35378
   488
     ([pretty_stat "iterations" iterations,
bulwahn@35378
   489
     pretty_stat "match exceptions" raised_match_errors]
wenzelm@41765
   490
     @ map_index
wenzelm@41765
   491
       (fn (i, n) => pretty_stat ("satisfied " ^ string_of_int (i + 1) ^ ". assumption") n)
bulwahn@35378
   492
       satisfied_assms
bulwahn@35378
   493
     @ [pretty_stat "positive conclusion tests" positive_concl_tests])
bulwahn@35378
   494
  end
bulwahn@35378
   495
bulwahn@35380
   496
fun pretty_reports ctxt (SOME reports) =
bulwahn@41160
   497
  Pretty.chunks (Pretty.fbrk :: Pretty.str "Quickcheck report:" ::
bulwahn@41153
   498
    maps (fn (size, report) =>
bulwahn@41153
   499
      Pretty.str ("size " ^ string_of_int size ^ ":") :: pretty_report report @ [Pretty.brk 1])
bulwahn@35378
   500
      (rev reports))
bulwahn@35380
   501
  | pretty_reports ctxt NONE = Pretty.str ""
bulwahn@35378
   502
bulwahn@42952
   503
fun pretty_timings timings =
bulwahn@42952
   504
  Pretty.chunks (Pretty.fbrk :: Pretty.str "timings:" ::
bulwahn@42952
   505
    maps (fn (label, time) =>
bulwahn@42952
   506
      Pretty.str (label ^ ": " ^ string_of_int time ^ " ms") :: Pretty.brk 1 :: []) (rev timings))
bulwahn@42952
   507
bulwahn@42952
   508
fun pretty_counterex_and_reports ctxt auto (result :: _) =
bulwahn@42952
   509
  Pretty.chunks (pretty_counterex ctxt auto (response_of result) ::
bulwahn@42952
   510
    (* map (pretty_reports ctxt) (reports_of result) :: *)
bulwahn@42952
   511
    (if Config.get ctxt timing then cons (pretty_timings (timings_of result)) else I) [])
haftmann@28315
   512
haftmann@28315
   513
(* automatic testing *)
haftmann@28309
   514
blanchet@33552
   515
fun auto_quickcheck state =
blanchet@41175
   516
  let
blanchet@41175
   517
    val ctxt = Proof.context_of state;
blanchet@41175
   518
    val res =
blanchet@41175
   519
      state
blanchet@41175
   520
      |> Proof.map_context (Config.put report false #> Config.put quiet true)
bulwahn@42897
   521
      |> try (test_goal (false, false) ([], []) 1);
blanchet@41175
   522
  in
blanchet@41175
   523
    case res of
blanchet@41175
   524
      NONE => (false, state)
bulwahn@42952
   525
    | SOME (result :: _) => if found_counterexample result then
bulwahn@42952
   526
        (true, Proof.goal_message (K (Pretty.chunks [Pretty.str "",
bulwahn@42952
   527
          Pretty.mark Markup.hilite (pretty_counterex ctxt true (response_of result))])) state)
bulwahn@42952
   528
      else
bulwahn@42952
   529
        (false, state)
blanchet@41175
   530
  end
blanchet@33552
   531
blanchet@41175
   532
val setup = Auto_Tools.register_tool (auto, auto_quickcheck)
bulwahn@40892
   533
  #> setup_config
haftmann@28309
   534
wenzelm@30981
   535
(* Isar commands *)
haftmann@28315
   536
haftmann@28336
   537
fun read_nat s = case (Library.read_int o Symbol.explode) s
haftmann@28336
   538
 of (k, []) => if k >= 0 then k
haftmann@28336
   539
      else error ("Not a natural number: " ^ s)
haftmann@28336
   540
  | (_, _ :: _) => error ("Not a natural number: " ^ s);
bulwahn@38149
   541
blanchet@34125
   542
fun read_bool "false" = false
blanchet@34125
   543
  | read_bool "true" = true
blanchet@34125
   544
  | read_bool s = error ("Not a Boolean value: " ^ s)
haftmann@28315
   545
bulwahn@40612
   546
fun read_real s =
bulwahn@40612
   547
  case (Real.fromString s) of
bulwahn@40612
   548
    SOME s => s
bulwahn@40612
   549
  | NONE => error ("Not a real number: " ^ s)
bulwahn@40612
   550
bulwahn@38169
   551
fun read_expectation "no_expectation" = No_Expectation
wenzelm@41765
   552
  | read_expectation "no_counterexample" = No_Counterexample
bulwahn@38169
   553
  | read_expectation "counterexample" = Counterexample
wenzelm@41765
   554
  | read_expectation s = error ("Not an expectation value: " ^ s)
bulwahn@38169
   555
bulwahn@42733
   556
fun valid_tester_name genctxt = AList.defined (op =) (fst (fst (Data.get genctxt)))
bulwahn@41156
   557
bulwahn@41156
   558
fun parse_tester name genctxt =
bulwahn@41156
   559
  if valid_tester_name genctxt name then
bulwahn@41156
   560
    Config.put_generic tester name genctxt
bulwahn@41156
   561
  else
bulwahn@41156
   562
    error ("Unknown tester: " ^ name)
bulwahn@41156
   563
bulwahn@41156
   564
fun parse_test_param ("tester", [arg]) = parse_tester arg
bulwahn@41153
   565
  | parse_test_param ("size", [arg]) = Config.put_generic size (read_nat arg)
bulwahn@40892
   566
  | parse_test_param ("iterations", [arg]) = Config.put_generic iterations (read_nat arg)
bulwahn@40892
   567
  | parse_test_param ("default_type", arg) = (fn gen_ctxt =>
wenzelm@41765
   568
    map_test_params
wenzelm@41765
   569
      ((apfst o K) (map (ProofContext.read_typ (Context.proof_of gen_ctxt)) arg)) gen_ctxt)
bulwahn@40892
   570
  | parse_test_param ("no_assms", [arg]) = Config.put_generic no_assms (read_bool arg)
bulwahn@40892
   571
  | parse_test_param ("expect", [arg]) = map_test_params ((apsnd o K) (read_expectation arg))
bulwahn@40892
   572
  | parse_test_param ("report", [arg]) = Config.put_generic report (read_bool arg)
bulwahn@40892
   573
  | parse_test_param ("quiet", [arg]) = Config.put_generic quiet (read_bool arg)
bulwahn@40892
   574
  | parse_test_param ("timeout", [arg]) = Config.put_generic timeout (read_real arg)
bulwahn@40894
   575
  | parse_test_param ("finite_types", [arg]) = Config.put_generic finite_types (read_bool arg)
wenzelm@41765
   576
  | parse_test_param ("finite_type_size", [arg]) =
wenzelm@41765
   577
    Config.put_generic finite_type_size (read_nat arg)
bulwahn@41156
   578
  | parse_test_param (name, _) = fn genctxt =>
bulwahn@41156
   579
    if valid_tester_name genctxt name then
bulwahn@41156
   580
      Config.put_generic tester name genctxt
bulwahn@41156
   581
    else error ("Unknown tester or test parameter: " ^ name);
haftmann@28315
   582
bulwahn@42896
   583
fun parse_test_param_inst (name, arg) ((insts, eval_terms), ctxt) =
haftmann@28336
   584
      case try (ProofContext.read_typ ctxt) name
bulwahn@42896
   585
       of SOME (TFree (v, _)) =>
bulwahn@42896
   586
         ((AList.update (op =) (v, ProofContext.read_typ ctxt (the_single arg)) insts, eval_terms), ctxt)
bulwahn@42896
   587
        | NONE => (case name of
bulwahn@42896
   588
            "eval" => ((insts, eval_terms @ map (Syntax.read_term ctxt) arg), ctxt)
bulwahn@42896
   589
          | _ => ((insts, eval_terms), Context.proof_map (parse_test_param (name, arg)) ctxt));
haftmann@28315
   590
bulwahn@40892
   591
fun quickcheck_params_cmd args = Context.theory_map (fold parse_test_param args);
wenzelm@41765
   592
bulwahn@42952
   593
fun check_expectation state results =
bulwahn@42952
   594
  (if found_counterexample (hd results) andalso expect (Proof.context_of state) = No_Counterexample
bulwahn@42952
   595
  then
bulwahn@42952
   596
    error ("quickcheck expected to find no counterexample but found one")
bulwahn@42952
   597
  else
bulwahn@42952
   598
    (if not (found_counterexample (hd results)) andalso expect (Proof.context_of state) = Counterexample
bulwahn@42952
   599
    then
bulwahn@42952
   600
      error ("quickcheck expected to find a counterexample but did not find one")
bulwahn@42952
   601
    else ()))
bulwahn@42952
   602
bulwahn@35378
   603
fun gen_quickcheck args i state =
bulwahn@40892
   604
  state
bulwahn@42896
   605
  |> Proof.map_context_result (fn ctxt => fold parse_test_param_inst args (([], []), ctxt))
bulwahn@42897
   606
  |> (fn ((insts, eval_terms), state') => test_goal (true, true) (insts, eval_terms) i state'
bulwahn@42952
   607
  |> tap (check_expectation state'))
boehmes@32295
   608
bulwahn@42952
   609
fun quickcheck args i state = counterexample_of (hd (gen_quickcheck args i state))
bulwahn@35378
   610
boehmes@32295
   611
fun quickcheck_cmd args i state =
bulwahn@35378
   612
  gen_quickcheck args i (Toplevel.proof_of state)
blanchet@40466
   613
  |> Pretty.writeln o pretty_counterex_and_reports (Toplevel.context_of state) false;
haftmann@28309
   614
wenzelm@41765
   615
val parse_arg =
wenzelm@41765
   616
  Parse.name --
wenzelm@41765
   617
    (Scan.optional (Parse.$$$ "=" |--
wenzelm@41765
   618
      (((Parse.name || Parse.float_number) >> single) ||
wenzelm@41765
   619
        (Parse.$$$ "[" |-- Parse.list1 Parse.name --| Parse.$$$ "]"))) ["true"]);
haftmann@28309
   620
wenzelm@41765
   621
val parse_args =
wenzelm@41765
   622
  Parse.$$$ "[" |-- Parse.list1 parse_arg --| Parse.$$$ "]" || Scan.succeed [];
haftmann@28336
   623
wenzelm@36970
   624
val _ =
wenzelm@36970
   625
  Outer_Syntax.command "quickcheck_params" "set parameters for random testing" Keyword.thy_decl
wenzelm@36970
   626
    (parse_args >> (fn args => Toplevel.theory (quickcheck_params_cmd args)));
haftmann@28309
   627
wenzelm@36970
   628
val _ =
wenzelm@36970
   629
  Outer_Syntax.improper_command "quickcheck" "try to find counterexample for subgoal" Keyword.diag
wenzelm@36970
   630
    (parse_args -- Scan.optional Parse.nat 1
wenzelm@36970
   631
      >> (fn (args, i) => Toplevel.no_timing o Toplevel.keep (quickcheck_cmd args i)));
haftmann@28309
   632
haftmann@28309
   633
end;
haftmann@28256
   634
haftmann@28315
   635
haftmann@28315
   636
val auto_quickcheck = Quickcheck.auto;