src/Tools/quickcheck.ML
author wenzelm
Sun Nov 09 17:04:14 2014 +0100 (2014-11-09)
changeset 58957 c9e744ea8a38
parent 58893 9e0ecb66d6a7
child 59184 830bb7ddb3ab
permissions -rw-r--r--
proper context for match_tac etc.;
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@55627
   163
val batch_tester = Attrib.setup_config_string @{binding quickcheck_batch_tester} (K "");
wenzelm@55627
   164
val size = Attrib.setup_config_int @{binding quickcheck_size} (K 10);
wenzelm@55627
   165
val iterations = Attrib.setup_config_int @{binding quickcheck_iterations} (K 100);
wenzelm@55627
   166
val depth = Attrib.setup_config_int @{binding quickcheck_depth} (K 10);
bulwahn@45213
   167
wenzelm@55627
   168
val no_assms = Attrib.setup_config_bool @{binding quickcheck_no_assms} (K false);
wenzelm@55627
   169
val locale = Attrib.setup_config_string @{binding quickcheck_locale} (K "interpret expand");
wenzelm@55627
   170
val report = Attrib.setup_config_bool @{binding quickcheck_report} (K true);
wenzelm@55627
   171
val timing = Attrib.setup_config_bool @{binding quickcheck_timing} (K false);
wenzelm@55627
   172
val timeout = Attrib.setup_config_real @{binding quickcheck_timeout} (K 30.0);
bulwahn@46565
   173
wenzelm@55627
   174
val genuine_only = Attrib.setup_config_bool @{binding quickcheck_genuine_only} (K false);
wenzelm@55627
   175
val abort_potential = Attrib.setup_config_bool @{binding quickcheck_abort_potential} (K false);
bulwahn@46565
   176
wenzelm@55627
   177
val quiet = Attrib.setup_config_bool @{binding quickcheck_quiet} (K false);
wenzelm@55627
   178
val verbose = Attrib.setup_config_bool @{binding quickcheck_verbose} (K false);
wenzelm@55627
   179
val tag = Attrib.setup_config_string @{binding quickcheck_tag} (K "");
bulwahn@46565
   180
wenzelm@55627
   181
val use_subtype = Attrib.setup_config_bool @{binding quickcheck_use_subtype} (K false);
bulwahn@46565
   182
bulwahn@45449
   183
val allow_function_inversion =
wenzelm@55627
   184
  Attrib.setup_config_bool @{binding quickcheck_allow_function_inversion} (K false);
wenzelm@55627
   185
val finite_types = Attrib.setup_config_bool @{binding quickcheck_finite_types} (K true);
wenzelm@55627
   186
val finite_type_size = Attrib.setup_config_int @{binding quickcheck_finite_type_size} (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@55627
   211
    ((string * (bool Config.T * tester)) list *
wenzelm@55627
   212
      ((string * (Proof.context -> term list -> (int -> term list option) list)) list *
wenzelm@55627
   213
      ((string * (Proof.context -> term list -> (int -> bool) list)) list))) *
wenzelm@55627
   214
      test_params;
bulwahn@43877
   215
  val empty = (([], ([], [])), Test_Params {default_type = [], expect = No_Expectation});
haftmann@28256
   216
  val extend = I;
wenzelm@55627
   217
  fun merge
wenzelm@55627
   218
   (((testers1, (batch_generators1, batch_validators1)), params1),
bulwahn@43877
   219
    ((testers2, (batch_generators2, batch_validators2)), params2)) : T =
bulwahn@43877
   220
    ((AList.merge (op =) (K true) (testers1, testers2),
bulwahn@43112
   221
      (AList.merge (op =) (K true) (batch_generators1, batch_generators2),
bulwahn@43112
   222
       AList.merge (op =) (K true) (batch_validators1, batch_validators2))),
haftmann@28309
   223
      merge_test_params (params1, params2));
wenzelm@33522
   224
);
haftmann@28256
   225
bulwahn@39252
   226
val test_params_of = snd o Data.get o Context.Proof;
bulwahn@37910
   227
wenzelm@55627
   228
val default_type = fst o dest_test_params o test_params_of;
bulwahn@40246
   229
wenzelm@55627
   230
val expect = snd o dest_test_params o test_params_of;
bulwahn@40246
   231
wenzelm@55627
   232
val map_test_params = Data.map o apsnd o map_test_params';
bulwahn@39253
   233
bulwahn@43877
   234
val add_tester = Data.map o apfst o apfst o AList.update (op =);
bulwahn@41862
   235
bulwahn@42194
   236
val add_batch_generator = Data.map o apfst o apsnd o apfst o AList.update (op =);
bulwahn@42194
   237
bulwahn@42194
   238
val add_batch_validator = Data.map o apfst o apsnd o apsnd o AList.update (op =);
haftmann@28309
   239
bulwahn@43881
   240
fun active_testers ctxt =
bulwahn@43881
   241
  let
wenzelm@55627
   242
    val testers = map snd (fst (fst (Data.get (Context.Proof ctxt))));
bulwahn@43881
   243
  in
bulwahn@43881
   244
    map snd (filter (fn (active, _) => Config.get ctxt active) testers)
wenzelm@55627
   245
  end;
wenzelm@51302
   246
wenzelm@55629
   247
fun set_active_testers [] context = context
wenzelm@55629
   248
  | set_active_testers testers context =
wenzelm@51302
   249
      let
wenzelm@55629
   250
        val registered_testers = fst (fst (Data.get context));
wenzelm@51302
   251
      in
wenzelm@51302
   252
        fold (fn (name, (config, _)) => Config.put_generic config (member (op =) testers name))
wenzelm@55629
   253
          registered_testers context
wenzelm@51302
   254
      end;
wenzelm@51302
   255
wenzelm@51302
   256
haftmann@28315
   257
(* generating tests *)
haftmann@28315
   258
bulwahn@41862
   259
fun gen_mk_tester lookup ctxt v =
haftmann@28309
   260
  let
bulwahn@43882
   261
    val name = Config.get ctxt batch_tester
wenzelm@51302
   262
    val tester =
wenzelm@51302
   263
      (case lookup ctxt name of
wenzelm@51302
   264
        NONE => error ("No such quickcheck batch-tester: " ^ name)
wenzelm@51302
   265
      | SOME tester => tester ctxt);
wenzelm@40235
   266
  in
bulwahn@40909
   267
    if Config.get ctxt quiet then
bulwahn@41862
   268
      try tester v
bulwahn@40909
   269
    else
wenzelm@43761
   270
      let (* FIXME !?!? *)
bulwahn@41862
   271
        val tester = Exn.interruptible_capture tester v
wenzelm@51302
   272
      in
wenzelm@51302
   273
        (case Exn.get_res tester of
bulwahn@40909
   274
          NONE => SOME (Exn.release tester)
wenzelm@51302
   275
        | SOME tester => SOME tester)
bulwahn@40909
   276
      end
wenzelm@51302
   277
  end;
bulwahn@43882
   278
bulwahn@42194
   279
val mk_batch_tester =
wenzelm@55627
   280
  gen_mk_tester (AList.lookup (op =) o fst o snd o fst o Data.get o Context.Proof);
bulwahn@42194
   281
val mk_batch_validator =
wenzelm@55627
   282
  gen_mk_tester (AList.lookup (op =) o snd o snd o fst o Data.get o Context.Proof);
wenzelm@51302
   283
wenzelm@51302
   284
haftmann@28315
   285
(* testing propositions *)
haftmann@28315
   286
bulwahn@43876
   287
type compile_generator =
wenzelm@51302
   288
  Proof.context -> (term * term list) list -> int list -> term list option * report option;
bulwahn@43876
   289
bulwahn@43585
   290
fun limit timeout (limit_time, is_interactive) f exc () =
bulwahn@41754
   291
  if limit_time then
wenzelm@55627
   292
    TimeLimit.timeLimit timeout f ()
wenzelm@55627
   293
      handle TimeLimit.TimeOut =>
wenzelm@55627
   294
        if is_interactive then exc () else raise TimeLimit.TimeOut
wenzelm@55627
   295
  else f ();
wenzelm@51302
   296
wenzelm@58843
   297
fun message ctxt s = if Config.get ctxt quiet then () else writeln s;
bulwahn@41753
   298
wenzelm@51302
   299
fun verbose_message ctxt s =
wenzelm@51302
   300
  if not (Config.get ctxt quiet) andalso Config.get ctxt verbose
wenzelm@58843
   301
  then writeln s else ();
bulwahn@45765
   302
bulwahn@45159
   303
fun test_terms ctxt (limit_time, is_interactive) insts goals =
wenzelm@51302
   304
  (case active_testers ctxt of
bulwahn@43881
   305
    [] => error "No active testers for quickcheck"
bulwahn@45765
   306
  | testers =>
wenzelm@55627
   307
      limit (seconds (Config.get ctxt timeout)) (limit_time, is_interactive)
wenzelm@55627
   308
        (fn () =>
wenzelm@55627
   309
          Par_List.get_some (fn tester =>
wenzelm@55627
   310
            tester ctxt (length testers > 1) insts goals |>
wenzelm@55627
   311
            (fn result => if exists found_counterexample result then SOME result else NONE))
wenzelm@55627
   312
          testers)
wenzelm@55627
   313
        (fn () => (message ctxt "Quickcheck ran out of time"; NONE)) ());
bulwahn@46759
   314
bulwahn@46759
   315
fun all_axioms_of ctxt t =
bulwahn@46759
   316
  let
wenzelm@51302
   317
    val intros = Locale.get_intros ctxt;
wenzelm@51302
   318
    val unfolds = Locale.get_unfolds ctxt;
wenzelm@51302
   319
    fun retrieve_prems thms t =
wenzelm@51302
   320
       (case filter (fn th => Term.could_unify (Thm.concl_of th, t)) thms of
wenzelm@51302
   321
         [] => NONE
bulwahn@46759
   322
       | [th] =>
wenzelm@51302
   323
           let
wenzelm@51302
   324
             val (tyenv, tenv) =
wenzelm@51302
   325
               Pattern.match (Proof_Context.theory_of ctxt)
wenzelm@51302
   326
                (Thm.concl_of th, t) (Vartab.empty, Vartab.empty)
wenzelm@51302
   327
           in SOME (map (Envir.subst_term (tyenv, tenv)) (Thm.prems_of th)) end);
bulwahn@46759
   328
    fun all t =
wenzelm@51302
   329
      (case retrieve_prems intros t of
bulwahn@46759
   330
        NONE => retrieve_prems unfolds t
wenzelm@51302
   331
      | SOME ts => SOME (maps (fn t => the_default [t] (all t)) ts));
bulwahn@46759
   332
  in
bulwahn@46759
   333
    all t
wenzelm@51302
   334
  end;
bulwahn@46759
   335
bulwahn@47348
   336
fun locale_config_of s =
bulwahn@47348
   337
  let
wenzelm@51302
   338
    val cs = space_explode " " s;
bulwahn@47348
   339
  in
bulwahn@47348
   340
    if forall (fn c => c = "expand" orelse c = "interpret") cs then cs
wenzelm@55627
   341
    else
wenzelm@55627
   342
     (warning ("Invalid quickcheck_locale setting: falling back to the default setting.");
bulwahn@47348
   343
      ["interpret", "expand"])
wenzelm@51302
   344
  end;
bulwahn@47348
   345
bulwahn@42026
   346
fun test_goal (time_limit, is_interactive) (insts, eval_terms) i state =
bulwahn@40648
   347
  let
bulwahn@40648
   348
    val lthy = Proof.context_of state;
bulwahn@40648
   349
    val thy = Proof.theory_of state;
bulwahn@45765
   350
    val _ = message lthy "Quickchecking..."
wenzelm@56245
   351
    fun strip (Const (@{const_name Pure.all}, _) $ Abs (_, _, t)) = strip t
bulwahn@40648
   352
      | strip t = t;
bulwahn@40648
   353
    val {goal = st, ...} = Proof.raw_goal state;
bulwahn@40648
   354
    val (gi, frees) = Logic.goal_params (prop_of st) i;
haftmann@57195
   355
    val some_locale = Named_Target.bottom_locale_of lthy;
wenzelm@51302
   356
    val assms =
wenzelm@51302
   357
      if Config.get lthy no_assms then []
wenzelm@51302
   358
      else
wenzelm@51302
   359
        (case some_locale of
wenzelm@51302
   360
          NONE => Assumption.all_assms_of lthy
wenzelm@51302
   361
        | SOME locale => Assumption.local_assms_of lthy (Locale.init locale thy));
bulwahn@40648
   362
    val proto_goal = Logic.list_implies (map Thm.term_of assms, subst_bounds (frees, strip gi));
wenzelm@51302
   363
    fun axioms_of locale =
wenzelm@51302
   364
      (case fst (Locale.specification_of thy locale) of
bulwahn@46759
   365
        NONE => []
wenzelm@51302
   366
      | SOME t => the_default [] (all_axioms_of lthy t));
wenzelm@55627
   367
    val config = locale_config_of (Config.get lthy locale);
wenzelm@55627
   368
    val goals =
wenzelm@55627
   369
      (case some_locale of
wenzelm@55627
   370
        NONE => [(proto_goal, eval_terms)]
wenzelm@55627
   371
      | SOME locale =>
wenzelm@55627
   372
          fold (fn c =>
wenzelm@55627
   373
            if c = "expand" then
wenzelm@55627
   374
              cons (Logic.list_implies (axioms_of locale, proto_goal), eval_terms)
wenzelm@55627
   375
            else if c = "interpret" then
wenzelm@55627
   376
              append (map (fn (_, phi) =>
wenzelm@55627
   377
                  (Morphism.term phi proto_goal, map (Morphism.term phi) eval_terms))
wenzelm@55627
   378
                (Locale.registrations_of (Context.Theory thy) (* FIXME !? *) locale))
wenzelm@55627
   379
            else I) config []);
wenzelm@51302
   380
    val _ =
wenzelm@51302
   381
      verbose_message lthy
wenzelm@51302
   382
        (Pretty.string_of
wenzelm@51302
   383
          (Pretty.big_list ("Checking goals: ") (map (Syntax.pretty_term lthy o fst) goals)));
bulwahn@40648
   384
  in
bulwahn@45159
   385
    test_terms lthy (time_limit, is_interactive) insts goals
wenzelm@51302
   386
  end;
wenzelm@51302
   387
bulwahn@40648
   388
bulwahn@37912
   389
(* pretty printing *)
haftmann@28315
   390
wenzelm@51302
   391
fun tool_name auto = (if auto then "Auto " else "") ^ "Quickcheck";
blanchet@40225
   392
bulwahn@46863
   393
fun pretty_counterex ctxt auto NONE =
wenzelm@55627
   394
      Pretty.str (tool_name auto ^ " found no counterexample." ^ Config.get ctxt tag)
bulwahn@45730
   395
  | pretty_counterex ctxt auto (SOME ((genuine, cex), eval_terms)) =
wenzelm@52694
   396
      (Pretty.text_fold o Pretty.fbreaks)
wenzelm@55627
   397
       (Pretty.str (tool_name auto ^ " found a " ^
wenzelm@52694
   398
         (if genuine then "counterexample:"
wenzelm@52694
   399
          else "potentially spurious counterexample due to underspecified functions:") ^
wenzelm@55627
   400
        Config.get ctxt tag) ::
wenzelm@55627
   401
        Pretty.str "" ::
wenzelm@55627
   402
        map (fn (s, t) =>
wenzelm@52694
   403
          Pretty.block [Pretty.str (s ^ " ="), Pretty.brk 1, Syntax.pretty_term ctxt t]) (rev cex) @
wenzelm@55627
   404
        (if null eval_terms then []
wenzelm@55627
   405
         else
wenzelm@55627
   406
          Pretty.str "" :: Pretty.str "Evaluated terms:" ::
wenzelm@55627
   407
            map (fn (t, u) =>
wenzelm@55627
   408
              Pretty.block [Syntax.pretty_term ctxt t, Pretty.str " =", Pretty.brk 1,
wenzelm@55627
   409
                Syntax.pretty_term ctxt u]) (rev eval_terms)));
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@55627
   435
fun valid_tester_name genctxt name =
wenzelm@55627
   436
  AList.defined (op =) (fst (fst (Data.get genctxt))) name;
wenzelm@51302
   437
bulwahn@43881
   438
fun parse_tester name (testers, genctxt) =
bulwahn@40912
   439
  if valid_tester_name genctxt name then
wenzelm@51302
   440
    (insert (op =) name testers, genctxt)
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@51302
   472
      (fn (testers, genctxt) =>
wenzelm@51302
   473
        if valid_tester_name genctxt name then
wenzelm@51302
   474
          (insert (op =) name testers, genctxt)
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
boehmes@32297
   516
fun quickcheck_cmd args i state =
bulwahn@35378
   517
  gen_quickcheck args i (Toplevel.proof_of state)
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@46949
   525
    (Scan.optional (@{keyword "="} |--
wenzelm@41517
   526
      (((Parse.name || Parse.float_number) >> single) ||
wenzelm@46949
   527
        (@{keyword "["} |-- Parse.list1 Parse.name --| @{keyword "]"}))) ["true"]);
haftmann@28309
   528
wenzelm@41517
   529
val parse_args =
wenzelm@46949
   530
  @{keyword "["} |-- Parse.list1 parse_arg --| @{keyword "]"} || Scan.succeed [];
haftmann@28336
   531
wenzelm@36960
   532
val _ =
wenzelm@46961
   533
  Outer_Syntax.command @{command_spec "quickcheck_params"} "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@58893
   537
  Outer_Syntax.command @{command_spec "quickcheck"}
wenzelm@46961
   538
    "try to find counterexample for subgoal"
wenzelm@51557
   539
    (parse_args -- Scan.optional Parse.nat 1 >> (fn (args, i) =>
wenzelm@51658
   540
      Toplevel.unknown_proof o Toplevel.keep (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
bulwahn@43879
   558
          val msg = pretty_counterex ctxt auto (Option.map (the o get_first response_of) results)
blanchet@43020
   559
        in
bulwahn@43879
   560
          if is_some results then
blanchet@43020
   561
            (genuineN,
wenzelm@58892
   562
              if auto then [Pretty.string_of (Pretty.mark Markup.information msg)]
wenzelm@58892
   563
              else (writeln (Pretty.string_of msg); []))
wenzelm@58892
   564
          else (noneN, [])
wenzelm@51302
   565
        end)
blanchet@43020
   566
  end
wenzelm@51302
   567
  |> `(fn (outcome_code, _) => outcome_code = genuineN);
blanchet@43020
   568
wenzelm@56467
   569
val _ = Try.tool_setup (quickcheckN, (20, @{system_option auto_quickcheck}, try_quickcheck));
blanchet@43020
   570
haftmann@28315
   571
end;
haftmann@28309
   572