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