src/Tools/quickcheck.ML
author wenzelm
Mon Mar 12 11:17:59 2018 +0100 (18 months ago)
changeset 67835 c8e4ee2b5482
parent 67149 e61557884799
permissions -rw-r--r--
tuned imports;
wenzelm@30824
     1
(*  Title:      Tools/quickcheck.ML
bulwahn@40246
     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@43020
     9
  val quickcheckN: string
blanchet@43020
    10
  val genuineN: string
blanchet@43020
    11
  val noneN: string
blanchet@43020
    12
  val unknownN: string
wenzelm@51302
    13
  (*configuration*)
bulwahn@43882
    14
  val batch_tester : string Config.T
bulwahn@40644
    15
  val size : int Config.T
bulwahn@40644
    16
  val iterations : int Config.T
bulwahn@45213
    17
  val depth : int Config.T
bulwahn@40644
    18
  val no_assms : bool Config.T
bulwahn@40644
    19
  val report : bool Config.T
bulwahn@46565
    20
  val timeout : real Config.T
bulwahn@42088
    21
  val timing : bool Config.T
bulwahn@45757
    22
  val genuine_only : bool Config.T
wenzelm@51302
    23
  val abort_potential : bool Config.T
bulwahn@40644
    24
  val quiet : bool Config.T
bulwahn@45764
    25
  val verbose : bool Config.T
bulwahn@46565
    26
  val use_subtype : bool Config.T
bulwahn@46565
    27
  val allow_function_inversion : bool Config.T
bulwahn@40648
    28
  val finite_types : bool Config.T
bulwahn@40648
    29
  val finite_type_size : int Config.T
bulwahn@46863
    30
  val tag : string Config.T
bulwahn@47348
    31
  val locale : string Config.T
bulwahn@43912
    32
  val set_active_testers: string list -> Context.generic -> Context.generic
wenzelm@41517
    33
  datatype expectation = No_Expectation | No_Counterexample | Counterexample;
bulwahn@40644
    34
  datatype test_params = Test_Params of {default_type: typ list, expect : expectation};
bulwahn@40246
    35
  val test_params_of : Proof.context -> test_params
bulwahn@40644
    36
  val map_test_params : (typ list * expectation -> typ list * expectation)
bulwahn@40246
    37
    -> Context.generic -> Context.generic
bulwahn@45159
    38
  val default_type : Proof.context -> typ list
bulwahn@42089
    39
  datatype report = Report of
bulwahn@42089
    40
    { iterations : int, raised_match_errors : int,
bulwahn@42089
    41
      satisfied_assms : int list, positive_concl_tests : int }
wenzelm@51302
    42
  (*quickcheck's result*)
bulwahn@42088
    43
  datatype result =
bulwahn@42088
    44
    Result of
bulwahn@45727
    45
     {counterexample : (bool * (string * term) list) option,
bulwahn@42088
    46
      evaluation_terms : (term * term) list option,
bulwahn@42088
    47
      timings : (string * int) list,
bulwahn@42088
    48
      reports : (int * report) list}
bulwahn@43314
    49
  val empty_result : result
bulwahn@45159
    50
  val found_counterexample : result -> bool
bulwahn@43585
    51
  val add_timing : (string * int) -> result Unsynchronized.ref -> unit
wenzelm@51302
    52
  val add_response : string list -> term list -> (bool * term list) option ->
wenzelm@51302
    53
    result Unsynchronized.ref -> unit
bulwahn@45159
    54
  val add_report : int -> report option -> result Unsynchronized.ref -> unit
bulwahn@45727
    55
  val counterexample_of : result -> (bool * (string * term) list) option
bulwahn@42089
    56
  val timings_of : result -> (string * int) list
wenzelm@51302
    57
  (*registering testers & generators*)
bulwahn@43878
    58
  type tester =
bulwahn@45419
    59
    Proof.context -> bool -> (string * typ) list -> (term * term list) list -> result list
bulwahn@43878
    60
  val add_tester : string * (bool Config.T * tester) -> Context.generic -> Context.generic
bulwahn@43878
    61
  val add_batch_generator :
bulwahn@43112
    62
    string * (Proof.context -> term list -> (int -> term list option) list)
bulwahn@43112
    63
      -> Context.generic -> Context.generic
bulwahn@43878
    64
  val add_batch_validator :
bulwahn@43112
    65
    string * (Proof.context -> term list -> (int -> bool) list)
bulwahn@43112
    66
      -> Context.generic -> Context.generic
wenzelm@51302
    67
  (*basic operations*)
bulwahn@45159
    68
  val message : Proof.context -> string -> unit
bulwahn@45765
    69
  val verbose_message : Proof.context -> string -> unit
bulwahn@45159
    70
  val limit : Time.time -> (bool * bool) -> (unit -> 'a) -> (unit -> 'a) -> unit -> 'a
bulwahn@45755
    71
  val pretty_counterex : Proof.context -> bool ->
bulwahn@45755
    72
    ((bool * (string * term) list) * (term * term) list) option -> Pretty.T
wenzelm@51302
    73
  (*testing terms and proof states*)
bulwahn@45159
    74
  val mk_batch_validator : Proof.context -> term list -> (int -> bool) list option
bulwahn@45159
    75
  val mk_batch_tester : Proof.context -> term list -> (int -> term list option) list option
bulwahn@45159
    76
  val active_testers : Proof.context -> tester list
wenzelm@51302
    77
  val test_terms : Proof.context -> bool * bool -> (string * typ) list ->
wenzelm@51302
    78
    (term * term list) list -> result list option
wenzelm@51302
    79
  val quickcheck: (string * string list) list -> int -> Proof.state ->
wenzelm@51302
    80
    (bool * (string * term) list) option
haftmann@28256
    81
end;
haftmann@28256
    82
haftmann@28256
    83
structure Quickcheck : QUICKCHECK =
haftmann@28256
    84
struct
haftmann@28256
    85
wenzelm@55627
    86
val quickcheckN = "quickcheck";
blanchet@43020
    87
wenzelm@55627
    88
val genuineN = "genuine";
wenzelm@55627
    89
val noneN = "none";
wenzelm@55627
    90
val unknownN = "unknown";
blanchet@43020
    91
wenzelm@51302
    92
bulwahn@35378
    93
(* quickcheck report *)
bulwahn@35378
    94
bulwahn@35378
    95
datatype report = Report of
wenzelm@55627
    96
 {iterations : int,
wenzelm@55627
    97
  raised_match_errors : int,
wenzelm@55627
    98
  satisfied_assms : int list,
wenzelm@55627
    99
  positive_concl_tests : int};
bulwahn@35378
   100
wenzelm@51302
   101
bulwahn@42088
   102
(* Quickcheck Result *)
bulwahn@42088
   103
bulwahn@42088
   104
datatype result = Result of
wenzelm@55627
   105
 {counterexample : (bool * (string * term) list) option,
wenzelm@55627
   106
  evaluation_terms : (term * term) list option,
wenzelm@55627
   107
  timings : (string * int) list,
wenzelm@55627
   108
  reports : (int * report) list};
bulwahn@42088
   109
bulwahn@42088
   110
val empty_result =
wenzelm@55627
   111
  Result {counterexample = NONE, evaluation_terms = NONE, timings = [], reports = []};
bulwahn@42088
   112
wenzelm@55627
   113
fun counterexample_of (Result r) = #counterexample r;
bulwahn@42088
   114
wenzelm@55627
   115
fun found_counterexample (Result r) = is_some (#counterexample r);
bulwahn@42088
   116
wenzelm@55627
   117
fun response_of (Result r) =
wenzelm@55627
   118
  (case (#counterexample r, #evaluation_terms r) of
bulwahn@45730
   119
    (SOME ts, SOME evals) => SOME (ts, evals)
wenzelm@55627
   120
  | (NONE, NONE) => NONE);
bulwahn@42088
   121
wenzelm@55627
   122
fun timings_of (Result r) = #timings r;
bulwahn@42088
   123
bulwahn@45727
   124
fun set_response names eval_terms (SOME (genuine, ts)) (Result r) =
wenzelm@55627
   125
      let
wenzelm@55627
   126
        val (ts1, ts2) = chop (length names) ts
wenzelm@55627
   127
        val (eval_terms', _) = chop (length ts2) eval_terms
wenzelm@55627
   128
      in
wenzelm@55627
   129
        Result {counterexample = SOME (genuine, (names ~~ ts1)),
wenzelm@55627
   130
          evaluation_terms = SOME (eval_terms' ~~ ts2),
wenzelm@55627
   131
          timings = #timings r, reports = #reports r}
wenzelm@55627
   132
      end
wenzelm@55627
   133
  | set_response _ _ NONE result = result;
bulwahn@42088
   134
bulwahn@43585
   135
bulwahn@42088
   136
fun cons_timing timing (Result r) =
bulwahn@42088
   137
  Result {counterexample = #counterexample r, evaluation_terms = #evaluation_terms r,
wenzelm@55627
   138
    timings = cons timing (#timings r), reports = #reports r};
bulwahn@42088
   139
bulwahn@42088
   140
fun cons_report size (SOME report) (Result r) =
wenzelm@55627
   141
      Result {counterexample = #counterexample r, evaluation_terms = #evaluation_terms r,
wenzelm@55627
   142
        timings = #timings r, reports = cons (size, report) (#reports r)}
wenzelm@55627
   143
  | cons_report _ NONE result = result;
bulwahn@42088
   144
wenzelm@42198
   145
fun add_timing timing result_ref =
wenzelm@55627
   146
  Unsynchronized.change result_ref (cons_timing timing);
bulwahn@42088
   147
wenzelm@42198
   148
fun add_report size report result_ref =
wenzelm@55627
   149
  Unsynchronized.change result_ref (cons_report size report);
bulwahn@42088
   150
bulwahn@42088
   151
fun add_response names eval_terms response result_ref =
wenzelm@55627
   152
  Unsynchronized.change result_ref (set_response names eval_terms response);
bulwahn@42088
   153
wenzelm@51302
   154
bulwahn@37929
   155
(* expectation *)
bulwahn@37929
   156
wenzelm@41517
   157
datatype expectation = No_Expectation | No_Counterexample | Counterexample;
bulwahn@37929
   158
bulwahn@37929
   159
fun merge_expectation (expect1, expect2) =
wenzelm@55627
   160
  if expect1 = expect2 then expect1 else No_Expectation;
bulwahn@37929
   161
wenzelm@51302
   162
(*quickcheck configuration -- default parameters, test generators*)
wenzelm@67149
   163
val batch_tester = Attrib.setup_config_string \<^binding>\<open>quickcheck_batch_tester\<close> (K "");
wenzelm@67149
   164
val size = Attrib.setup_config_int \<^binding>\<open>quickcheck_size\<close> (K 10);
wenzelm@67149
   165
val iterations = Attrib.setup_config_int \<^binding>\<open>quickcheck_iterations\<close> (K 100);
wenzelm@67149
   166
val depth = Attrib.setup_config_int \<^binding>\<open>quickcheck_depth\<close> (K 10);
bulwahn@45213
   167
wenzelm@67149
   168
val no_assms = Attrib.setup_config_bool \<^binding>\<open>quickcheck_no_assms\<close> (K false);
wenzelm@67149
   169
val locale = Attrib.setup_config_string \<^binding>\<open>quickcheck_locale\<close> (K "interpret expand");
wenzelm@67149
   170
val report = Attrib.setup_config_bool \<^binding>\<open>quickcheck_report\<close> (K true);
wenzelm@67149
   171
val timing = Attrib.setup_config_bool \<^binding>\<open>quickcheck_timing\<close> (K false);
wenzelm@67149
   172
val timeout = Attrib.setup_config_real \<^binding>\<open>quickcheck_timeout\<close> (K 30.0);
bulwahn@46565
   173
wenzelm@67149
   174
val genuine_only = Attrib.setup_config_bool \<^binding>\<open>quickcheck_genuine_only\<close> (K false);
wenzelm@67149
   175
val abort_potential = Attrib.setup_config_bool \<^binding>\<open>quickcheck_abort_potential\<close> (K false);
bulwahn@46565
   176
wenzelm@67149
   177
val quiet = Attrib.setup_config_bool \<^binding>\<open>quickcheck_quiet\<close> (K false);
wenzelm@67149
   178
val verbose = Attrib.setup_config_bool \<^binding>\<open>quickcheck_verbose\<close> (K false);
wenzelm@67149
   179
val tag = Attrib.setup_config_string \<^binding>\<open>quickcheck_tag\<close> (K "");
bulwahn@46565
   180
wenzelm@67149
   181
val use_subtype = Attrib.setup_config_bool \<^binding>\<open>quickcheck_use_subtype\<close> (K false);
bulwahn@46565
   182
bulwahn@45449
   183
val allow_function_inversion =
wenzelm@67149
   184
  Attrib.setup_config_bool \<^binding>\<open>quickcheck_allow_function_inversion\<close> (K false);
wenzelm@67149
   185
val finite_types = Attrib.setup_config_bool \<^binding>\<open>quickcheck_finite_types\<close> (K true);
wenzelm@67149
   186
val finite_type_size = Attrib.setup_config_int \<^binding>\<open>quickcheck_finite_type_size\<close> (K 3);
bulwahn@40646
   187
bulwahn@40644
   188
datatype test_params = Test_Params of
bulwahn@40644
   189
  {default_type: typ list, expect : expectation};
wenzelm@38759
   190
bulwahn@40644
   191
fun dest_test_params (Test_Params {default_type, expect}) = (default_type, expect);
bulwahn@40644
   192
wenzelm@41517
   193
fun make_test_params (default_type, expect) =
wenzelm@41517
   194
  Test_Params {default_type = default_type, expect = expect};
bulwahn@40644
   195
wenzelm@41517
   196
fun map_test_params' f (Test_Params {default_type, expect}) =
wenzelm@41517
   197
  make_test_params (f (default_type, expect));
wenzelm@38759
   198
wenzelm@38759
   199
fun merge_test_params
wenzelm@41472
   200
  (Test_Params {default_type = default_type1, expect = expect1},
wenzelm@41472
   201
    Test_Params {default_type = default_type2, expect = expect2}) =
wenzelm@41472
   202
  make_test_params
wenzelm@41472
   203
    (merge (op =) (default_type1, default_type2), merge_expectation (expect1, expect2));
haftmann@28309
   204
bulwahn@43878
   205
type tester =
wenzelm@51302
   206
  Proof.context -> bool -> (string * typ) list -> (term * term list) list -> result list;
bulwahn@43878
   207
bulwahn@39252
   208
structure Data = Generic_Data
wenzelm@33522
   209
(
wenzelm@38759
   210
  type T =
wenzelm@59436
   211
    (string * (bool Config.T * tester)) list *
wenzelm@59436
   212
    (string * (Proof.context -> term list -> (int -> term list option) list)) list *
wenzelm@59436
   213
    (string * (Proof.context -> term list -> (int -> bool) list)) list *
wenzelm@59436
   214
    test_params;
wenzelm@59436
   215
  val empty = ([], [], [], Test_Params {default_type = [], expect = No_Expectation});
haftmann@28256
   216
  val extend = I;
wenzelm@55627
   217
  fun merge
wenzelm@59436
   218
   ((testers1, batch_generators1, batch_validators1, params1),
wenzelm@59436
   219
    (testers2, batch_generators2, batch_validators2, params2)) : T =
wenzelm@59436
   220
    (AList.merge (op =) (K true) (testers1, testers2),
wenzelm@59436
   221
     AList.merge (op =) (K true) (batch_generators1, batch_generators2),
wenzelm@59436
   222
     AList.merge (op =) (K true) (batch_validators1, batch_validators2),
wenzelm@59436
   223
     merge_test_params (params1, params2));
wenzelm@33522
   224
);
haftmann@28256
   225
wenzelm@59436
   226
val test_params_of = #4 o Data.get o Context.Proof;
wenzelm@55627
   227
val default_type = fst o dest_test_params o test_params_of;
wenzelm@55627
   228
val expect = snd o dest_test_params o test_params_of;
wenzelm@59436
   229
val map_test_params = Data.map o @{apply 4(4)} o map_test_params';
bulwahn@40246
   230
wenzelm@59436
   231
val add_tester = Data.map o @{apply 4(1)} o AList.update (op =);
wenzelm@59436
   232
val add_batch_generator = Data.map o @{apply 4(2)} o AList.update (op =);
wenzelm@59436
   233
val add_batch_validator = Data.map o @{apply 4(3)} o AList.update (op =);
haftmann@28309
   234
bulwahn@43881
   235
fun active_testers ctxt =
bulwahn@43881
   236
  let
wenzelm@59436
   237
    val testers = map snd (#1 (Data.get (Context.Proof ctxt)));
bulwahn@43881
   238
  in
bulwahn@43881
   239
    map snd (filter (fn (active, _) => Config.get ctxt active) testers)
wenzelm@55627
   240
  end;
wenzelm@51302
   241
wenzelm@55629
   242
fun set_active_testers [] context = context
wenzelm@55629
   243
  | set_active_testers testers context =
wenzelm@51302
   244
      let
wenzelm@59436
   245
        val registered_testers = #1 (Data.get context);
wenzelm@51302
   246
      in
wenzelm@51302
   247
        fold (fn (name, (config, _)) => Config.put_generic config (member (op =) testers name))
wenzelm@55629
   248
          registered_testers context
wenzelm@51302
   249
      end;
wenzelm@51302
   250
wenzelm@51302
   251
haftmann@28315
   252
(* generating tests *)
haftmann@28315
   253
bulwahn@41862
   254
fun gen_mk_tester lookup ctxt v =
haftmann@28309
   255
  let
bulwahn@43882
   256
    val name = Config.get ctxt batch_tester
wenzelm@51302
   257
    val tester =
wenzelm@51302
   258
      (case lookup ctxt name of
wenzelm@51302
   259
        NONE => error ("No such quickcheck batch-tester: " ^ name)
wenzelm@51302
   260
      | SOME tester => tester ctxt);
wenzelm@40235
   261
  in
bulwahn@40909
   262
    if Config.get ctxt quiet then
bulwahn@41862
   263
      try tester v
bulwahn@40909
   264
    else
wenzelm@43761
   265
      let (* FIXME !?!? *)
bulwahn@41862
   266
        val tester = Exn.interruptible_capture tester v
wenzelm@51302
   267
      in
wenzelm@51302
   268
        (case Exn.get_res tester of
bulwahn@40909
   269
          NONE => SOME (Exn.release tester)
wenzelm@51302
   270
        | SOME tester => SOME tester)
bulwahn@40909
   271
      end
wenzelm@51302
   272
  end;
bulwahn@43882
   273
wenzelm@59436
   274
val mk_batch_tester = gen_mk_tester (AList.lookup (op =) o #2 o Data.get o Context.Proof);
wenzelm@59436
   275
val mk_batch_validator = gen_mk_tester (AList.lookup (op =) o #3 o Data.get o Context.Proof);
wenzelm@51302
   276
wenzelm@51302
   277
haftmann@28315
   278
(* testing propositions *)
haftmann@28315
   279
bulwahn@43876
   280
type compile_generator =
wenzelm@51302
   281
  Proof.context -> (term * term list) list -> int list -> term list option * report option;
bulwahn@43876
   282
bulwahn@43585
   283
fun limit timeout (limit_time, is_interactive) f exc () =
bulwahn@41754
   284
  if limit_time then
wenzelm@62519
   285
    Timeout.apply timeout f ()
wenzelm@62519
   286
      handle timeout_exn as Timeout.TIMEOUT _ =>
wenzelm@62519
   287
        if is_interactive then exc () else Exn.reraise timeout_exn
wenzelm@55627
   288
  else f ();
wenzelm@51302
   289
wenzelm@58843
   290
fun message ctxt s = if Config.get ctxt quiet then () else writeln s;
bulwahn@41753
   291
wenzelm@51302
   292
fun verbose_message ctxt s =
wenzelm@51302
   293
  if not (Config.get ctxt quiet) andalso Config.get ctxt verbose
wenzelm@58843
   294
  then writeln s else ();
bulwahn@45765
   295
wenzelm@62983
   296
fun test_terms ctxt0 (limit_time, is_interactive) insts goals =
wenzelm@62983
   297
  let val ctxt = Simplifier_Trace.disable ctxt0 in
wenzelm@62983
   298
    (case active_testers ctxt of
wenzelm@62983
   299
      [] => error "No active testers for quickcheck"
wenzelm@62983
   300
    | testers =>
wenzelm@62983
   301
        limit (seconds (Config.get ctxt timeout)) (limit_time, is_interactive)
wenzelm@62983
   302
          (fn () =>
wenzelm@62983
   303
            Par_List.get_some (fn tester =>
wenzelm@62983
   304
              tester ctxt (length testers > 1) insts goals |>
wenzelm@62983
   305
              (fn result => if exists found_counterexample result then SOME result else NONE))
wenzelm@62983
   306
            testers)
wenzelm@62983
   307
          (fn () => (message ctxt "Quickcheck ran out of time"; NONE)) ())
wenzelm@62983
   308
  end
bulwahn@46759
   309
bulwahn@46759
   310
fun all_axioms_of ctxt t =
bulwahn@46759
   311
  let
wenzelm@51302
   312
    val intros = Locale.get_intros ctxt;
wenzelm@51302
   313
    val unfolds = Locale.get_unfolds ctxt;
wenzelm@51302
   314
    fun retrieve_prems thms t =
wenzelm@51302
   315
       (case filter (fn th => Term.could_unify (Thm.concl_of th, t)) thms of
wenzelm@51302
   316
         [] => NONE
bulwahn@46759
   317
       | [th] =>
wenzelm@51302
   318
           let
wenzelm@51302
   319
             val (tyenv, tenv) =
wenzelm@51302
   320
               Pattern.match (Proof_Context.theory_of ctxt)
wenzelm@51302
   321
                (Thm.concl_of th, t) (Vartab.empty, Vartab.empty)
wenzelm@51302
   322
           in SOME (map (Envir.subst_term (tyenv, tenv)) (Thm.prems_of th)) end);
bulwahn@46759
   323
    fun all t =
wenzelm@51302
   324
      (case retrieve_prems intros t of
bulwahn@46759
   325
        NONE => retrieve_prems unfolds t
wenzelm@51302
   326
      | SOME ts => SOME (maps (fn t => the_default [t] (all t)) ts));
bulwahn@46759
   327
  in
bulwahn@46759
   328
    all t
wenzelm@51302
   329
  end;
bulwahn@46759
   330
bulwahn@47348
   331
fun locale_config_of s =
bulwahn@47348
   332
  let
wenzelm@51302
   333
    val cs = space_explode " " s;
bulwahn@47348
   334
  in
bulwahn@47348
   335
    if forall (fn c => c = "expand" orelse c = "interpret") cs then cs
wenzelm@55627
   336
    else
wenzelm@55627
   337
     (warning ("Invalid quickcheck_locale setting: falling back to the default setting.");
bulwahn@47348
   338
      ["interpret", "expand"])
wenzelm@51302
   339
  end;
bulwahn@47348
   340
bulwahn@42026
   341
fun test_goal (time_limit, is_interactive) (insts, eval_terms) i state =
bulwahn@40648
   342
  let
wenzelm@62982
   343
    val ctxt = Proof.context_of state;
bulwahn@40648
   344
    val thy = Proof.theory_of state;
wenzelm@62982
   345
wenzelm@67149
   346
    fun strip (Const (\<^const_name>\<open>Pure.all\<close>, _) $ Abs (_, _, t)) = strip t
bulwahn@40648
   347
      | strip t = t;
bulwahn@40648
   348
    val {goal = st, ...} = Proof.raw_goal state;
wenzelm@59582
   349
    val (gi, frees) = Logic.goal_params (Thm.prop_of st) i;
wenzelm@62982
   350
    val opt_locale = Named_Target.bottom_locale_of ctxt;
wenzelm@51302
   351
    val assms =
wenzelm@62982
   352
      if Config.get ctxt no_assms then []
wenzelm@51302
   353
      else
wenzelm@62982
   354
        (case opt_locale of
wenzelm@62982
   355
          NONE => Assumption.all_assms_of ctxt
wenzelm@62982
   356
        | SOME locale => Assumption.local_assms_of ctxt (Locale.init locale thy));
bulwahn@40648
   357
    val proto_goal = Logic.list_implies (map Thm.term_of assms, subst_bounds (frees, strip gi));
wenzelm@51302
   358
    fun axioms_of locale =
wenzelm@51302
   359
      (case fst (Locale.specification_of thy locale) of
bulwahn@46759
   360
        NONE => []
wenzelm@62982
   361
      | SOME t => the_default [] (all_axioms_of ctxt t));
wenzelm@62982
   362
    val config = locale_config_of (Config.get ctxt locale);
wenzelm@55627
   363
    val goals =
wenzelm@62982
   364
      (case opt_locale of
wenzelm@55627
   365
        NONE => [(proto_goal, eval_terms)]
wenzelm@55627
   366
      | SOME locale =>
wenzelm@55627
   367
          fold (fn c =>
wenzelm@55627
   368
            if c = "expand" then
wenzelm@55627
   369
              cons (Logic.list_implies (axioms_of locale, proto_goal), eval_terms)
wenzelm@55627
   370
            else if c = "interpret" then
wenzelm@55627
   371
              append (map (fn (_, phi) =>
wenzelm@55627
   372
                  (Morphism.term phi proto_goal, map (Morphism.term phi) eval_terms))
wenzelm@55627
   373
                (Locale.registrations_of (Context.Theory thy) (* FIXME !? *) locale))
wenzelm@55627
   374
            else I) config []);
wenzelm@51302
   375
    val _ =
wenzelm@62982
   376
      verbose_message ctxt
wenzelm@51302
   377
        (Pretty.string_of
wenzelm@62982
   378
          (Pretty.big_list ("Checking goals: ") (map (Syntax.pretty_term ctxt o fst) goals)));
bulwahn@40648
   379
  in
wenzelm@62982
   380
    test_terms ctxt (time_limit, is_interactive) insts goals
wenzelm@51302
   381
  end;
wenzelm@51302
   382
bulwahn@40648
   383
bulwahn@37912
   384
(* pretty printing *)
haftmann@28315
   385
wenzelm@59435
   386
fun tool_name auto = if auto then "Auto Quickcheck" else "Quickcheck";
blanchet@40225
   387
bulwahn@46863
   388
fun pretty_counterex ctxt auto NONE =
wenzelm@59435
   389
      Pretty.para (tool_name auto ^ " found no counterexample." ^ Config.get ctxt tag)
bulwahn@45730
   390
  | pretty_counterex ctxt auto (SOME ((genuine, cex), eval_terms)) =
wenzelm@59438
   391
      let
wenzelm@59438
   392
        val header =
wenzelm@59438
   393
          Pretty.para
wenzelm@59438
   394
            (tool_name auto ^ " found a " ^
wenzelm@60666
   395
              (if genuine then "counterexample"
wenzelm@60666
   396
               else "potentially spurious counterexample due to underspecified functions") ^
wenzelm@60666
   397
              (if null cex then "." else ":") ^
wenzelm@59438
   398
              Config.get ctxt tag);
wenzelm@59439
   399
        fun pretty_cex (x, t) =
wenzelm@59439
   400
          Pretty.block [Pretty.str (x ^ " ="), Pretty.brk 1, Syntax.pretty_term ctxt t];
wenzelm@59438
   401
      in
wenzelm@59439
   402
        Pretty.chunks (Pretty.block (Pretty.fbreaks (header :: map pretty_cex (rev cex))) ::
wenzelm@59438
   403
          (if null eval_terms then []
wenzelm@59438
   404
           else
wenzelm@59438
   405
            [Pretty.big_list "Evaluated terms:"
wenzelm@59438
   406
              (map (fn (t, u) =>
wenzelm@59438
   407
                Pretty.block [Syntax.pretty_term ctxt t, Pretty.str " =", Pretty.brk 1,
wenzelm@59438
   408
                  Syntax.pretty_term ctxt u]) (rev eval_terms))]))
wenzelm@59438
   409
      end;
haftmann@28315
   410
wenzelm@51302
   411
wenzelm@30980
   412
(* Isar commands *)
haftmann@28315
   413
wenzelm@51302
   414
fun read_nat s =
wenzelm@55627
   415
  (case Library.read_int (Symbol.explode s) of
wenzelm@51302
   416
    (k, []) =>
wenzelm@51302
   417
      if k >= 0 then k
haftmann@28336
   418
      else error ("Not a natural number: " ^ s)
wenzelm@55627
   419
  | _ => error ("Not a natural number: " ^ s));
bulwahn@37909
   420
blanchet@34128
   421
fun read_bool "false" = false
blanchet@34128
   422
  | read_bool "true" = true
wenzelm@51302
   423
  | read_bool s = error ("Not a Boolean value: " ^ s);
haftmann@28315
   424
bulwahn@40366
   425
fun read_real s =
wenzelm@55627
   426
  (case Real.fromString s of
bulwahn@40366
   427
    SOME s => s
wenzelm@51302
   428
  | NONE => error ("Not a real number: " ^ s));
bulwahn@40366
   429
bulwahn@37929
   430
fun read_expectation "no_expectation" = No_Expectation
wenzelm@41517
   431
  | read_expectation "no_counterexample" = No_Counterexample
bulwahn@37929
   432
  | read_expectation "counterexample" = Counterexample
wenzelm@51302
   433
  | read_expectation s = error ("Not an expectation value: " ^ s);
bulwahn@37929
   434
wenzelm@59437
   435
fun valid_tester_name context name =
wenzelm@59437
   436
  AList.defined (op =) (#1 (Data.get context)) name;
wenzelm@51302
   437
wenzelm@59437
   438
fun parse_tester name (testers, context) =
wenzelm@59437
   439
  if valid_tester_name context name then
wenzelm@59437
   440
    (insert (op =) name testers, context)
wenzelm@55627
   441
  else error ("Unknown tester: " ^ name);
bulwahn@40912
   442
bulwahn@43881
   443
fun parse_test_param ("tester", args) = fold parse_tester args
bulwahn@43881
   444
  | parse_test_param ("size", [arg]) = apsnd (Config.put_generic size (read_nat arg))
bulwahn@43881
   445
  | parse_test_param ("iterations", [arg]) = apsnd (Config.put_generic iterations (read_nat arg))
wenzelm@51302
   446
  | parse_test_param ("depth", [arg]) = apsnd (Config.put_generic depth (read_nat arg))
wenzelm@55627
   447
  | parse_test_param ("default_type", arg) =
wenzelm@55629
   448
      (fn (testers, context) =>
wenzelm@55627
   449
        (testers, map_test_params
wenzelm@55629
   450
          (apfst (K (map (Proof_Context.read_typ (Context.proof_of context)) arg))) context))
bulwahn@43881
   451
  | parse_test_param ("no_assms", [arg]) = apsnd (Config.put_generic no_assms (read_bool arg))
wenzelm@55627
   452
  | parse_test_param ("expect", [arg]) = apsnd (map_test_params (apsnd (K (read_expectation arg))))
bulwahn@43881
   453
  | parse_test_param ("report", [arg]) = apsnd (Config.put_generic report (read_bool arg))
wenzelm@55627
   454
  | parse_test_param ("genuine_only", [arg]) =
wenzelm@55627
   455
      apsnd (Config.put_generic genuine_only (read_bool arg))
wenzelm@55627
   456
  | parse_test_param ("abort_potential", [arg]) =
wenzelm@55627
   457
      apsnd (Config.put_generic abort_potential (read_bool arg))
bulwahn@43881
   458
  | parse_test_param ("quiet", [arg]) = apsnd (Config.put_generic quiet (read_bool arg))
bulwahn@45764
   459
  | parse_test_param ("verbose", [arg]) = apsnd (Config.put_generic verbose (read_bool arg))
bulwahn@46863
   460
  | parse_test_param ("tag", [arg]) = apsnd (Config.put_generic tag arg)
wenzelm@55627
   461
  | parse_test_param ("use_subtype", [arg]) =
wenzelm@55627
   462
      apsnd (Config.put_generic use_subtype (read_bool arg))
wenzelm@55627
   463
  | parse_test_param ("timeout", [arg]) =
wenzelm@55627
   464
      apsnd (Config.put_generic timeout (read_real arg))
wenzelm@55627
   465
  | parse_test_param ("finite_types", [arg]) =
wenzelm@55627
   466
      apsnd (Config.put_generic finite_types (read_bool arg))
bulwahn@45449
   467
  | parse_test_param ("allow_function_inversion", [arg]) =
bulwahn@45449
   468
      apsnd (Config.put_generic allow_function_inversion (read_bool arg))
wenzelm@41517
   469
  | parse_test_param ("finite_type_size", [arg]) =
wenzelm@55627
   470
      apsnd (Config.put_generic finite_type_size (read_nat arg))
wenzelm@51302
   471
  | parse_test_param (name, _) =
wenzelm@59437
   472
      (fn (testers, context) =>
wenzelm@59437
   473
        if valid_tester_name context name then
wenzelm@59437
   474
          (insert (op =) name testers, context)
wenzelm@51302
   475
        else error ("Unknown tester or test parameter: " ^ name));
haftmann@28315
   476
bulwahn@43881
   477
fun parse_test_param_inst (name, arg) ((insts, eval_terms), (testers, ctxt)) =
wenzelm@51302
   478
  (case try (Proof_Context.read_typ ctxt) name of
wenzelm@51302
   479
    SOME (TFree (v, _)) =>
wenzelm@51302
   480
      ((AList.update (op =) (v, Proof_Context.read_typ ctxt (the_single arg)) insts, eval_terms),
wenzelm@51302
   481
        (testers, ctxt))
wenzelm@51302
   482
  | NONE =>
wenzelm@51302
   483
      (case name of
wenzelm@51302
   484
        "eval" => ((insts, eval_terms @ map (Syntax.read_term ctxt) arg), (testers, ctxt))
wenzelm@51302
   485
      | _ =>
wenzelm@51302
   486
        ((insts, eval_terms),
wenzelm@55630
   487
          let
wenzelm@55630
   488
            val (testers', Context.Proof ctxt') =
wenzelm@55630
   489
              parse_test_param (name, arg) (testers, Context.Proof ctxt);
wenzelm@55630
   490
          in (testers', ctxt') end)));
haftmann@28309
   491
wenzelm@55627
   492
fun quickcheck_params_cmd args =
wenzelm@55627
   493
  Context.theory_map
wenzelm@55629
   494
    (fn context => uncurry set_active_testers (fold parse_test_param args ([], context)));
wenzelm@41517
   495
bulwahn@42088
   496
fun check_expectation state results =
wenzelm@51302
   497
  if is_some results andalso expect (Proof.context_of state) = No_Counterexample then
wenzelm@51302
   498
    error "quickcheck expected to find no counterexample but found one"
wenzelm@51302
   499
  else if is_none results andalso expect (Proof.context_of state) = Counterexample then
wenzelm@51302
   500
    error "quickcheck expected to find a counterexample but did not find one"
wenzelm@51302
   501
  else ();
bulwahn@42088
   502
bulwahn@35378
   503
fun gen_quickcheck args i state =
bulwahn@40644
   504
  state
bulwahn@43881
   505
  |> Proof.map_context_result (fn ctxt =>
bulwahn@43881
   506
    apsnd (fn (testers, ctxt) => Context.proof_map (set_active_testers testers) ctxt)
bulwahn@43881
   507
      (fold parse_test_param_inst args (([], []), ([], ctxt))))
wenzelm@55627
   508
  |> (fn ((insts, eval_terms), state') =>
wenzelm@55627
   509
      test_goal (true, true) (insts, eval_terms) i state'
wenzelm@55627
   510
      |> tap (check_expectation state')
wenzelm@55627
   511
      |> rpair state');
boehmes@32297
   512
bulwahn@43879
   513
fun quickcheck args i state =
wenzelm@51302
   514
  Option.map (the o get_first counterexample_of) (fst (gen_quickcheck args i state));
bulwahn@35378
   515
wenzelm@60190
   516
fun quickcheck_cmd args i st =
wenzelm@60190
   517
  gen_quickcheck args i (Toplevel.proof_of st)
bulwahn@46863
   518
  |> apfst (Option.map (the o get_first response_of))
wenzelm@51302
   519
  |> (fn (r, state) =>
wenzelm@58843
   520
      writeln (Pretty.string_of
wenzelm@51302
   521
        (pretty_counterex (Proof.context_of state) false r)));
haftmann@28309
   522
wenzelm@41517
   523
val parse_arg =
wenzelm@41517
   524
  Parse.name --
wenzelm@67149
   525
    (Scan.optional (\<^keyword>\<open>=\<close> |--
wenzelm@41517
   526
      (((Parse.name || Parse.float_number) >> single) ||
wenzelm@67149
   527
        (\<^keyword>\<open>[\<close> |-- Parse.list1 Parse.name --| \<^keyword>\<open>]\<close>))) ["true"]);
haftmann@28309
   528
wenzelm@41517
   529
val parse_args =
wenzelm@67149
   530
  \<^keyword>\<open>[\<close> |-- Parse.list1 parse_arg --| \<^keyword>\<open>]\<close> || Scan.succeed [];
haftmann@28336
   531
wenzelm@36960
   532
val _ =
wenzelm@67149
   533
  Outer_Syntax.command \<^command_keyword>\<open>quickcheck_params\<close> "set parameters for random testing"
wenzelm@36960
   534
    (parse_args >> (fn args => Toplevel.theory (quickcheck_params_cmd args)));
haftmann@28309
   535
wenzelm@36960
   536
val _ =
wenzelm@67149
   537
  Outer_Syntax.command \<^command_keyword>\<open>quickcheck\<close>
wenzelm@46961
   538
    "try to find counterexample for subgoal"
wenzelm@60094
   539
    (parse_args -- Scan.optional Parse.nat 1 >>
wenzelm@60190
   540
      (fn (args, i) => Toplevel.keep_proof (quickcheck_cmd args i)));
haftmann@28309
   541
wenzelm@51302
   542
blanchet@43020
   543
(* automatic testing *)
blanchet@43020
   544
blanchet@43020
   545
fun try_quickcheck auto state =
blanchet@43020
   546
  let
blanchet@43020
   547
    val ctxt = Proof.context_of state;
blanchet@43020
   548
    val i = 1;
blanchet@43020
   549
    val res =
blanchet@43020
   550
      state
blanchet@43020
   551
      |> Proof.map_context (Config.put report false #> Config.put quiet true)
blanchet@43020
   552
      |> try (test_goal (false, false) ([], []) i);
blanchet@43020
   553
  in
wenzelm@51302
   554
    (case res of
wenzelm@58892
   555
      NONE => (unknownN, [])
blanchet@43020
   556
    | SOME results =>
blanchet@43020
   557
        let
wenzelm@59184
   558
          val msg =
wenzelm@59184
   559
            Pretty.string_of
wenzelm@59184
   560
              (pretty_counterex ctxt auto (Option.map (the o get_first response_of) results))
blanchet@43020
   561
        in
wenzelm@59184
   562
          if is_some results then (genuineN, if auto then [msg] else (writeln msg; []))
wenzelm@58892
   563
          else (noneN, [])
wenzelm@51302
   564
        end)
blanchet@43020
   565
  end
wenzelm@51302
   566
  |> `(fn (outcome_code, _) => outcome_code = genuineN);
blanchet@43020
   567
wenzelm@67149
   568
val _ = Try.tool_setup (quickcheckN, (20, \<^system_option>\<open>auto_quickcheck\<close>, try_quickcheck));
blanchet@43020
   569
haftmann@28315
   570
end;
haftmann@28309
   571