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