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