src/Tools/quickcheck.ML
author bulwahn
Thu Feb 25 14:01:34 2010 +0100 (2010-02-25)
changeset 35380 6ac5b81a763d
parent 35379 d0c779d012dc
child 35625 9c818cab0dd0
permissions -rw-r--r--
adopting Mutabelle to quickcheck reporting; improving quickcheck reporting
wenzelm@30824
     1
(*  Title:      Tools/quickcheck.ML
haftmann@28256
     2
    Author:     Stefan Berghofer, Florian Haftmann, 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
wenzelm@32740
     9
  val auto: bool Unsynchronized.ref
bulwahn@34948
    10
  val timing : bool Unsynchronized.ref
bulwahn@35378
    11
  datatype report = Report of
bulwahn@35378
    12
    { iterations : int, raised_match_errors : int,
bulwahn@35378
    13
      satisfied_assms : int list, positive_concl_tests : int }
bulwahn@35378
    14
  val gen_test_term: Proof.context -> bool -> bool -> string option -> int -> int -> term ->
bulwahn@35380
    15
    (string * term) list option * ((string * int) list * ((int * report list) list) option)
wenzelm@30980
    16
  val test_term: Proof.context -> bool -> string option -> int -> int -> term ->
wenzelm@30980
    17
    (string * term) list option
bulwahn@35378
    18
  val add_generator:
bulwahn@35378
    19
    string * (Proof.context -> bool -> term -> int -> term list option * (bool list * bool))
bulwahn@35378
    20
      -> theory -> theory
blanchet@33561
    21
  val setup: theory -> theory
boehmes@32297
    22
  val quickcheck: (string * string) list -> int -> Proof.state -> (string * term) list option
haftmann@28256
    23
end;
haftmann@28256
    24
haftmann@28256
    25
structure Quickcheck : QUICKCHECK =
haftmann@28256
    26
struct
haftmann@28256
    27
wenzelm@30980
    28
(* preferences *)
wenzelm@30980
    29
wenzelm@32740
    30
val auto = Unsynchronized.ref false;
wenzelm@30980
    31
bulwahn@34948
    32
val timing = Unsynchronized.ref false;
bulwahn@34948
    33
wenzelm@30980
    34
val _ =
wenzelm@30980
    35
  ProofGeneralPgip.add_preference Preferences.category_tracing
wenzelm@32966
    36
  (setmp_CRITICAL auto true (fn () =>
wenzelm@30980
    37
    Preferences.bool_pref auto
wenzelm@30980
    38
      "auto-quickcheck"
blanchet@33561
    39
      "Whether to run Quickcheck automatically.") ());
wenzelm@30980
    40
bulwahn@35378
    41
(* quickcheck report *)
bulwahn@35378
    42
bulwahn@35378
    43
datatype single_report = Run of bool list * bool | MatchExc
bulwahn@35378
    44
bulwahn@35378
    45
datatype report = Report of
bulwahn@35378
    46
  { iterations : int, raised_match_errors : int,
bulwahn@35378
    47
    satisfied_assms : int list, positive_concl_tests : int }
bulwahn@35378
    48
bulwahn@35378
    49
fun collect_single_report single_report
bulwahn@35378
    50
    (Report {iterations = iterations, raised_match_errors = raised_match_errors,
bulwahn@35378
    51
    satisfied_assms = satisfied_assms, positive_concl_tests = positive_concl_tests}) =
bulwahn@35378
    52
  case single_report
bulwahn@35378
    53
  of MatchExc =>
bulwahn@35378
    54
    Report {iterations = iterations + 1, raised_match_errors = raised_match_errors + 1,
bulwahn@35378
    55
      satisfied_assms = satisfied_assms, positive_concl_tests = positive_concl_tests}
bulwahn@35378
    56
   | Run (assms, concl) =>
bulwahn@35378
    57
    Report {iterations = iterations + 1, raised_match_errors = raised_match_errors,
bulwahn@35378
    58
      satisfied_assms =
bulwahn@35378
    59
        map2 (fn b => fn s => if b then s + 1 else s) assms
bulwahn@35378
    60
         (if null satisfied_assms then replicate (length assms) 0 else satisfied_assms),
bulwahn@35378
    61
      positive_concl_tests = if concl then positive_concl_tests + 1 else positive_concl_tests}
haftmann@30973
    62
haftmann@28315
    63
(* quickcheck configuration -- default parameters, test generators *)
haftmann@28315
    64
haftmann@28309
    65
datatype test_params = Test_Params of
bulwahn@35379
    66
  { size: int, iterations: int, default_type: typ option, no_assms: bool, report: bool, quiet : bool};
haftmann@28309
    67
bulwahn@35379
    68
fun dest_test_params (Test_Params { size, iterations, default_type, no_assms, report, quiet }) =
bulwahn@35379
    69
  ((size, iterations), ((default_type, no_assms), (report, quiet)));
bulwahn@35379
    70
fun make_test_params ((size, iterations), ((default_type, no_assms), (report, quiet))) =
blanchet@34128
    71
  Test_Params { size = size, iterations = iterations, default_type = default_type,
bulwahn@35379
    72
                no_assms = no_assms, report = report, quiet = quiet };
bulwahn@35379
    73
fun map_test_params f (Test_Params { size, iterations, default_type, no_assms, report, quiet }) =
bulwahn@35379
    74
  make_test_params (f ((size, iterations), ((default_type, no_assms), (report, quiet))));
blanchet@34128
    75
fun merge_test_params (Test_Params { size = size1, iterations = iterations1, default_type = default_type1,
bulwahn@35379
    76
                                     no_assms = no_assms1, report = report1, quiet = quiet1 },
blanchet@34128
    77
  Test_Params { size = size2, iterations = iterations2, default_type = default_type2,
bulwahn@35379
    78
                no_assms = no_assms2, report = report2, quiet = quiet2 }) =
haftmann@31599
    79
  make_test_params ((Int.max (size1, size2), Int.max (iterations1, iterations2)),
bulwahn@35378
    80
    ((case default_type1 of NONE => default_type2 | _ => default_type1, no_assms1 orelse no_assms2),
bulwahn@35379
    81
    (report1 orelse report2, quiet1 orelse quiet2)));
haftmann@28309
    82
wenzelm@33522
    83
structure Data = Theory_Data
wenzelm@33522
    84
(
bulwahn@35378
    85
  type T = (string * (Proof.context -> bool -> term -> int -> term list option * (bool list * bool))) list
haftmann@28309
    86
    * test_params;
bulwahn@35378
    87
  val empty = ([], Test_Params
bulwahn@35379
    88
    { size = 10, iterations = 100, default_type = NONE, no_assms = false, report = false, quiet = false});
haftmann@28256
    89
  val extend = I;
wenzelm@33522
    90
  fun merge ((generators1, params1), (generators2, params2)) : T =
wenzelm@33522
    91
    (AList.merge (op =) (K true) (generators1, generators2),
haftmann@28309
    92
      merge_test_params (params1, params2));
wenzelm@33522
    93
);
haftmann@28256
    94
haftmann@28309
    95
val add_generator = Data.map o apfst o AList.update (op =);
haftmann@28309
    96
haftmann@28315
    97
(* generating tests *)
haftmann@28315
    98
haftmann@28309
    99
fun mk_tester_select name ctxt =
haftmann@28309
   100
  case AList.lookup (op =) ((fst o Data.get o ProofContext.theory_of) ctxt) name
haftmann@28309
   101
   of NONE => error ("No such quickcheck generator: " ^ name)
haftmann@28309
   102
    | SOME generator => generator ctxt;
haftmann@28309
   103
bulwahn@35378
   104
fun mk_testers ctxt report t =
haftmann@28309
   105
  (map snd o fst o Data.get o ProofContext.theory_of) ctxt
bulwahn@35378
   106
  |> map_filter (fn generator => try (generator ctxt report) t);
haftmann@28309
   107
bulwahn@35378
   108
fun mk_testers_strict ctxt report t =
haftmann@28309
   109
  let
haftmann@28309
   110
    val generators = ((map snd o fst o Data.get o ProofContext.theory_of) ctxt)
bulwahn@35378
   111
    val testers = map (fn generator => Exn.capture (generator ctxt report) t) generators;
haftmann@28309
   112
  in if forall (is_none o Exn.get_result) testers
haftmann@28309
   113
    then [(Exn.release o snd o split_last) testers]
haftmann@28309
   114
    else map_filter Exn.get_result testers
haftmann@28309
   115
  end;
haftmann@28309
   116
haftmann@28315
   117
haftmann@28315
   118
(* testing propositions *)
haftmann@28315
   119
haftmann@28309
   120
fun prep_test_term t =
haftmann@28309
   121
  let
wenzelm@29266
   122
    val _ = (null (Term.add_tvars t []) andalso null (Term.add_tfrees t [])) orelse
haftmann@28309
   123
      error "Term to be tested contains type variables";
wenzelm@29266
   124
    val _ = null (Term.add_vars t []) orelse
haftmann@28309
   125
      error "Term to be tested contains schematic variables";
haftmann@31138
   126
    val frees = Term.add_frees t [];
haftmann@28309
   127
  in (map fst frees, list_abs_free (frees, t)) end
haftmann@28256
   128
bulwahn@35324
   129
fun cpu_time description f =
bulwahn@35324
   130
  let
bulwahn@35324
   131
    val start = start_timing ()
bulwahn@35324
   132
    val result = Exn.capture f ()
bulwahn@35324
   133
    val time = Time.toMilliseconds (#cpu (end_timing start))
bulwahn@35324
   134
  in (Exn.release result, (description, time)) end
bulwahn@35324
   135
bulwahn@35378
   136
fun gen_test_term ctxt quiet report generator_name size i t =
haftmann@28309
   137
  let
haftmann@28309
   138
    val (names, t') = prep_test_term t;
bulwahn@35324
   139
    val (testers, comp_time) = cpu_time "quickcheck compilation"
bulwahn@35324
   140
      (fn () => (case generator_name
bulwahn@35378
   141
       of NONE => if quiet then mk_testers ctxt report t' else mk_testers_strict ctxt report t'
bulwahn@35378
   142
        | SOME name => [mk_tester_select name ctxt report t']));
bulwahn@35378
   143
    fun iterate f 0 report = (NONE, report)
bulwahn@35378
   144
      | iterate f j report =
bulwahn@35378
   145
        let
bulwahn@35378
   146
          val (test_result, single_report) = apsnd Run (f ()) handle Match => (if quiet then ()
bulwahn@35378
   147
             else warning "Exception Match raised during quickcheck"; (NONE, MatchExc))
bulwahn@35378
   148
          val report = collect_single_report single_report report
bulwahn@35378
   149
        in
bulwahn@35378
   150
          case test_result of NONE => iterate f (j - 1) report | SOME q => (SOME q, report)
bulwahn@35378
   151
        end
bulwahn@35378
   152
    val empty_report = Report { iterations = 0, raised_match_errors = 0,
bulwahn@35378
   153
      satisfied_assms = [], positive_concl_tests = 0 }
bulwahn@35378
   154
    fun with_testers k [] = (NONE, [])
haftmann@28309
   155
      | with_testers k (tester :: testers) =
bulwahn@35378
   156
          case iterate (fn () => tester (k - 1)) i empty_report
bulwahn@35378
   157
           of (NONE, report) => apsnd (cons report) (with_testers k testers)
bulwahn@35378
   158
            | (SOME q, report) => (SOME q, [report]);
bulwahn@35378
   159
    fun with_size k reports = if k > size then (NONE, reports)
haftmann@28309
   160
      else (if quiet then () else priority ("Test data size: " ^ string_of_int k);
bulwahn@35378
   161
        let
bulwahn@35378
   162
          val (result, new_report) = with_testers k testers
bulwahn@35378
   163
          val reports = ((k, new_report) :: reports)
bulwahn@35378
   164
        in case result of NONE => with_size (k + 1) reports | SOME q => (SOME q, reports) end);
bulwahn@35378
   165
    val ((result, reports), exec_time) = cpu_time "quickcheck execution"
bulwahn@35378
   166
      (fn () => apfst
bulwahn@35378
   167
         (fn result => case result of NONE => NONE
bulwahn@35378
   168
        | SOME ts => SOME (names ~~ ts)) (with_size 1 []))
bulwahn@34948
   169
  in
bulwahn@35380
   170
    (result, ([exec_time, comp_time], if report then SOME reports else NONE))
haftmann@28309
   171
  end;
haftmann@28309
   172
bulwahn@35324
   173
fun test_term ctxt quiet generator_name size i t =
bulwahn@35378
   174
  fst (gen_test_term ctxt quiet false generator_name size i t)
bulwahn@35324
   175
haftmann@28309
   176
fun monomorphic_term thy insts default_T = 
haftmann@28309
   177
  let
haftmann@28309
   178
    fun subst (T as TFree (v, S)) =
haftmann@28309
   179
          let
haftmann@28309
   180
            val T' = AList.lookup (op =) insts v
haftmann@28309
   181
              |> the_default (the_default T default_T)
haftmann@28315
   182
          in if Sign.of_sort thy (T, S) then T'
haftmann@28309
   183
            else error ("Type " ^ Syntax.string_of_typ_global thy T ^
haftmann@28309
   184
              " to be substituted for variable " ^
haftmann@28309
   185
              Syntax.string_of_typ_global thy T ^ "\ndoes not have sort " ^
haftmann@28309
   186
              Syntax.string_of_sort_global thy S)
haftmann@28309
   187
          end
haftmann@28309
   188
      | subst T = T;
haftmann@28309
   189
  in (map_types o map_atyps) subst end;
haftmann@28309
   190
bulwahn@35378
   191
fun test_goal quiet report generator_name size iterations default_T no_assms insts i assms state =
haftmann@28309
   192
  let
haftmann@28309
   193
    val ctxt = Proof.context_of state;
haftmann@28309
   194
    val thy = Proof.theory_of state;
haftmann@28309
   195
    fun strip (Const ("all", _) $ Abs (_, _, t)) = strip t
haftmann@28309
   196
      | strip t = t;
wenzelm@33291
   197
    val {goal = st, ...} = Proof.raw_goal state;
haftmann@28309
   198
    val (gi, frees) = Logic.goal_params (prop_of st) i;
blanchet@34128
   199
    val gi' = Logic.list_implies (if no_assms then [] else assms,
blanchet@34128
   200
                                  subst_bounds (frees, strip gi))
haftmann@28309
   201
      |> monomorphic_term thy insts default_T
haftmann@28309
   202
      |> ObjectLogic.atomize_term thy;
bulwahn@35378
   203
  in gen_test_term ctxt quiet report generator_name size iterations gi' end;
haftmann@28315
   204
blanchet@35077
   205
fun pretty_counterex ctxt NONE = Pretty.str "Quickcheck found no counterexample."
haftmann@28315
   206
  | pretty_counterex ctxt (SOME cex) =
blanchet@35077
   207
      Pretty.chunks (Pretty.str "Quickcheck found a counterexample:\n" ::
haftmann@28315
   208
        map (fn (s, t) =>
haftmann@28315
   209
          Pretty.block [Pretty.str (s ^ " ="), Pretty.brk 1, Syntax.pretty_term ctxt t]) cex);
haftmann@28315
   210
bulwahn@35378
   211
fun pretty_report (Report {iterations = iterations, raised_match_errors = raised_match_errors,
bulwahn@35378
   212
    satisfied_assms = satisfied_assms, positive_concl_tests = positive_concl_tests}) =
bulwahn@35378
   213
  let
bulwahn@35378
   214
    fun pretty_stat s i = Pretty.block ([Pretty.str (s ^ ": " ^ string_of_int i)])
bulwahn@35378
   215
  in
bulwahn@35378
   216
     ([pretty_stat "iterations" iterations,
bulwahn@35378
   217
     pretty_stat "match exceptions" raised_match_errors]
bulwahn@35378
   218
     @ map_index (fn (i, n) => pretty_stat ("satisfied " ^ string_of_int (i + 1) ^ ". assumption") n)
bulwahn@35378
   219
       satisfied_assms
bulwahn@35378
   220
     @ [pretty_stat "positive conclusion tests" positive_concl_tests])
bulwahn@35378
   221
  end
bulwahn@35378
   222
bulwahn@35378
   223
fun pretty_reports' [report] = [Pretty.chunks (pretty_report report)]
bulwahn@35378
   224
  | pretty_reports' reports =
bulwahn@35378
   225
  map_index (fn (i, report) =>
bulwahn@35378
   226
    Pretty.chunks (Pretty.str (string_of_int (i + 1) ^ ". generator:\n") :: pretty_report report))
bulwahn@35378
   227
    reports
bulwahn@35378
   228
bulwahn@35380
   229
fun pretty_reports ctxt (SOME reports) =
bulwahn@35378
   230
  Pretty.chunks (Pretty.str "Quickcheck report:" ::
bulwahn@35378
   231
    maps (fn (size, reports) =>
bulwahn@35378
   232
      Pretty.str ("size " ^ string_of_int size ^ ":") :: pretty_reports' reports @ [Pretty.brk 1])
bulwahn@35378
   233
      (rev reports))
bulwahn@35380
   234
  | pretty_reports ctxt NONE = Pretty.str ""
bulwahn@35378
   235
bulwahn@35378
   236
fun pretty_counterex_and_reports ctxt (cex, (timing, reports)) =
bulwahn@35378
   237
  Pretty.chunks [pretty_counterex ctxt cex, pretty_reports ctxt reports]
haftmann@28315
   238
haftmann@28315
   239
(* automatic testing *)
haftmann@28309
   240
blanchet@33561
   241
fun auto_quickcheck state =
blanchet@33561
   242
  if not (!auto) then
blanchet@33561
   243
    (false, state)
blanchet@33561
   244
  else
blanchet@33561
   245
    let
blanchet@33561
   246
      val ctxt = Proof.context_of state;
blanchet@33561
   247
      val assms = map term_of (Assumption.all_assms_of ctxt);
bulwahn@35379
   248
      val Test_Params { size, iterations, default_type, no_assms, report, quiet } =
blanchet@33561
   249
        (snd o Data.get o Proof.theory_of) state;
blanchet@33561
   250
      val res =
bulwahn@35378
   251
        try (test_goal true false NONE size iterations default_type no_assms [] 1 assms) state;
blanchet@33561
   252
    in
blanchet@33561
   253
      case res of
blanchet@33561
   254
        NONE => (false, state)
bulwahn@35378
   255
      | SOME (NONE, report) => (false, state)
bulwahn@35378
   256
      | SOME (cex, report) => (true, Proof.goal_message (K (Pretty.chunks [Pretty.str "",
blanchet@33561
   257
          Pretty.mark Markup.hilite (pretty_counterex ctxt cex)])) state)
blanchet@33561
   258
    end
blanchet@33561
   259
blanchet@33561
   260
val setup = Auto_Counterexample.register_tool ("quickcheck", auto_quickcheck)
haftmann@28315
   261
haftmann@28315
   262
wenzelm@30980
   263
(* Isar commands *)
haftmann@28315
   264
haftmann@28336
   265
fun read_nat s = case (Library.read_int o Symbol.explode) s
haftmann@28336
   266
 of (k, []) => if k >= 0 then k
haftmann@28336
   267
      else error ("Not a natural number: " ^ s)
haftmann@28336
   268
  | (_, _ :: _) => error ("Not a natural number: " ^ s);
blanchet@34128
   269
fun read_bool "false" = false
blanchet@34128
   270
  | read_bool "true" = true
blanchet@34128
   271
  | read_bool s = error ("Not a Boolean value: " ^ s)
haftmann@28315
   272
haftmann@28336
   273
fun parse_test_param ctxt ("size", arg) =
haftmann@28336
   274
      (apfst o apfst o K) (read_nat arg)
haftmann@28336
   275
  | parse_test_param ctxt ("iterations", arg) =
haftmann@28336
   276
      (apfst o apsnd o K) (read_nat arg)
haftmann@28336
   277
  | parse_test_param ctxt ("default_type", arg) =
bulwahn@35378
   278
      (apsnd o apfst o apfst o K o SOME) (ProofContext.read_typ ctxt arg)
blanchet@34128
   279
  | parse_test_param ctxt ("no_assms", arg) =
bulwahn@35378
   280
      (apsnd o apfst o apsnd o K) (read_bool arg)
bulwahn@35378
   281
  | parse_test_param ctxt ("report", arg) =
bulwahn@35379
   282
      (apsnd o apsnd o apfst o K) (read_bool arg)
bulwahn@35379
   283
  | parse_test_param ctxt ("quiet", arg) =
bulwahn@35379
   284
      (apsnd o apsnd o apsnd o K) (read_bool arg)
haftmann@28336
   285
  | parse_test_param ctxt (name, _) =
blanchet@34128
   286
      error ("Unknown test parameter: " ^ name);
haftmann@28315
   287
haftmann@28336
   288
fun parse_test_param_inst ctxt ("generator", arg) =
haftmann@28336
   289
      (apsnd o apfst o K o SOME) arg
haftmann@28336
   290
  | parse_test_param_inst ctxt (name, arg) =
haftmann@28336
   291
      case try (ProofContext.read_typ ctxt) name
haftmann@28336
   292
       of SOME (TFree (v, _)) => (apsnd o apsnd o AList.update (op =))
haftmann@28336
   293
              (v, ProofContext.read_typ ctxt arg)
haftmann@28336
   294
        | _ => (apfst o parse_test_param ctxt) (name, arg);
haftmann@28309
   295
haftmann@28336
   296
fun quickcheck_params_cmd args thy =
haftmann@28315
   297
  let
haftmann@28315
   298
    val ctxt = ProofContext.init thy;
haftmann@28336
   299
    val f = fold (parse_test_param ctxt) args;
haftmann@28315
   300
  in
haftmann@28315
   301
    thy
haftmann@28336
   302
    |> (Data.map o apsnd o map_test_params) f
haftmann@28315
   303
  end;
haftmann@28315
   304
bulwahn@35378
   305
fun gen_quickcheck args i state =
haftmann@28315
   306
  let
boehmes@32297
   307
    val thy = Proof.theory_of state;
boehmes@32297
   308
    val ctxt = Proof.context_of state;
blanchet@34128
   309
    val assms = map term_of (Assumption.all_assms_of ctxt);
haftmann@28315
   310
    val default_params = (dest_test_params o snd o Data.get) thy;
haftmann@28336
   311
    val f = fold (parse_test_param_inst ctxt) args;
bulwahn@35379
   312
    val (((size, iterations), ((default_type, no_assms), (report, quiet))), (generator_name, insts)) =
haftmann@28336
   313
      f (default_params, (NONE, []));
boehmes@32297
   314
  in
bulwahn@35379
   315
    test_goal quiet report generator_name size iterations default_type no_assms insts i assms state
boehmes@32297
   316
  end;
boehmes@32297
   317
bulwahn@35378
   318
fun quickcheck args i state = fst (gen_quickcheck args i state)
bulwahn@35378
   319
boehmes@32297
   320
fun quickcheck_cmd args i state =
bulwahn@35378
   321
  gen_quickcheck args i (Toplevel.proof_of state)
bulwahn@35378
   322
  |> Pretty.writeln o pretty_counterex_and_reports (Toplevel.context_of state);
haftmann@28309
   323
haftmann@28309
   324
local structure P = OuterParse and K = OuterKeyword in
haftmann@28309
   325
blanchet@34128
   326
val parse_arg = P.name -- (Scan.optional (P.$$$ "=" |-- P.name) "true")
blanchet@34128
   327
haftmann@28336
   328
val parse_args = P.$$$ "[" |-- P.list1 parse_arg --| P.$$$ "]"
haftmann@28336
   329
  || Scan.succeed [];
haftmann@28336
   330
haftmann@28315
   331
val _ = OuterSyntax.command "quickcheck_params" "set parameters for random testing" K.thy_decl
haftmann@28336
   332
  (parse_args >> (fn args => Toplevel.theory (quickcheck_params_cmd args)));
haftmann@28309
   333
haftmann@28315
   334
val _ = OuterSyntax.improper_command "quickcheck" "try to find counterexample for subgoal" K.diag
haftmann@28336
   335
  (parse_args -- Scan.optional P.nat 1
haftmann@28336
   336
    >> (fn (args, i) => Toplevel.no_timing o Toplevel.keep (quickcheck_cmd args i)));
haftmann@28309
   337
haftmann@28309
   338
end; (*local*)
haftmann@28309
   339
haftmann@28315
   340
end;
haftmann@28309
   341
haftmann@28309
   342
haftmann@28315
   343
val auto_quickcheck = Quickcheck.auto;