src/Tools/quickcheck.ML
author haftmann
Thu, 19 Apr 2012 10:16:51 +0200
changeset 48447 b32aae03e3d6
parent 48254 003189cebf12
child 48472 b3dab1892cda
permissions -rw-r--r--
dropped dead code;
tuned
     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 cons_timing timing (Result r) =
   141   Result {counterexample = #counterexample r, evaluation_terms = #evaluation_terms r,
   142     timings = cons timing (#timings r), reports = #reports r}
   143 
   144 fun cons_report size (SOME report) (Result r) =
   145   Result {counterexample = #counterexample r, evaluation_terms = #evaluation_terms r,
   146     timings = #timings r, reports = cons (size, report) (#reports r)}
   147   | cons_report _ NONE result = result
   148 
   149 fun add_timing timing result_ref =
   150   Unsynchronized.change result_ref (cons_timing timing)
   151 
   152 fun add_report size report result_ref =
   153   Unsynchronized.change result_ref (cons_report size report)
   154 
   155 fun add_response names eval_terms response result_ref =
   156   Unsynchronized.change result_ref (set_response names eval_terms response)
   157 
   158 (* expectation *)
   159 
   160 datatype expectation = No_Expectation | No_Counterexample | Counterexample;
   161 
   162 fun merge_expectation (expect1, expect2) =
   163   if expect1 = expect2 then expect1 else No_Expectation
   164 
   165 (* quickcheck configuration -- default parameters, test generators *)
   166 val batch_tester = Attrib.setup_config_string @{binding quickcheck_batch_tester} (K "")
   167 val size = Attrib.setup_config_int @{binding quickcheck_size} (K 10)
   168 val iterations = Attrib.setup_config_int @{binding quickcheck_iterations} (K 100)
   169 val depth = Attrib.setup_config_int @{binding quickcheck_depth} (K 10)
   170 
   171 val no_assms = Attrib.setup_config_bool @{binding quickcheck_no_assms} (K false)
   172 val locale = Attrib.setup_config_string @{binding quickcheck_locale} (K "interpret expand")
   173 val report = Attrib.setup_config_bool @{binding quickcheck_report} (K true)
   174 val timing = Attrib.setup_config_bool @{binding quickcheck_timing} (K false)
   175 val timeout = Attrib.setup_config_real @{binding quickcheck_timeout} (K 30.0)
   176 
   177 val genuine_only = Attrib.setup_config_bool @{binding quickcheck_genuine_only} (K false)
   178 val abort_potential = Attrib.setup_config_bool @{binding quickcheck_abort_potential} (K false)
   179 
   180 val quiet = Attrib.setup_config_bool @{binding quickcheck_quiet} (K false)
   181 val verbose = Attrib.setup_config_bool @{binding quickcheck_verbose} (K false)
   182 val tag = Attrib.setup_config_string @{binding quickcheck_tag} (K "")
   183 
   184 val use_subtype = Attrib.setup_config_bool @{binding quickcheck_use_subtype} (K false)
   185 
   186 val allow_function_inversion =
   187   Attrib.setup_config_bool @{binding quickcheck_allow_function_inversion} (K false)
   188 val finite_types = Attrib.setup_config_bool @{binding quickcheck_finite_types} (K true)
   189 val finite_type_size = Attrib.setup_config_int @{binding quickcheck_finite_type_size} (K 3)
   190 
   191 datatype test_params = Test_Params of
   192   {default_type: typ list, expect : expectation};
   193 
   194 fun dest_test_params (Test_Params {default_type, expect}) = (default_type, expect);
   195 
   196 fun make_test_params (default_type, expect) =
   197   Test_Params {default_type = default_type, expect = expect};
   198 
   199 fun map_test_params' f (Test_Params {default_type, expect}) =
   200   make_test_params (f (default_type, expect));
   201 
   202 fun merge_test_params
   203   (Test_Params {default_type = default_type1, expect = expect1},
   204     Test_Params {default_type = default_type2, expect = expect2}) =
   205   make_test_params
   206     (merge (op =) (default_type1, default_type2), merge_expectation (expect1, expect2));
   207 
   208 type tester =
   209   Proof.context -> bool -> (string * typ) list -> (term * term list) list -> result list
   210 
   211 structure Data = Generic_Data
   212 (
   213   type T =
   214     ((string * (bool Config.T * tester)) list
   215       * ((string * (Proof.context -> term list -> (int -> term list option) list)) list
   216       * ((string * (Proof.context -> term list -> (int -> bool) list)) list)))
   217       * test_params;
   218   val empty = (([], ([], [])), Test_Params {default_type = [], expect = No_Expectation});
   219   val extend = I;
   220   fun merge (((testers1, (batch_generators1, batch_validators1)), params1),
   221     ((testers2, (batch_generators2, batch_validators2)), params2)) : T =
   222     ((AList.merge (op =) (K true) (testers1, testers2),
   223       (AList.merge (op =) (K true) (batch_generators1, batch_generators2),
   224        AList.merge (op =) (K true) (batch_validators1, batch_validators2))),
   225       merge_test_params (params1, params2));
   226 );
   227 
   228 val test_params_of = snd o Data.get o Context.Proof;
   229 
   230 val default_type = fst o dest_test_params o test_params_of
   231 
   232 val expect = snd o dest_test_params o test_params_of
   233 
   234 val map_test_params = Data.map o apsnd o map_test_params'
   235 
   236 val add_tester = Data.map o apfst o apfst o AList.update (op =);
   237 
   238 val add_batch_generator = Data.map o apfst o apsnd o apfst o AList.update (op =);
   239 
   240 val add_batch_validator = Data.map o apfst o apsnd o apsnd o AList.update (op =);
   241 
   242 fun active_testers ctxt =
   243   let
   244     val testers = (map snd o fst o fst o Data.get o Context.Proof) ctxt
   245   in
   246     map snd (filter (fn (active, _) => Config.get ctxt active) testers)
   247   end
   248   
   249 fun set_active_testers [] gen_ctxt = gen_ctxt
   250   | set_active_testers testers gen_ctxt =
   251   let
   252     val registered_testers = (fst o fst o Data.get) gen_ctxt
   253   in
   254     fold (fn (name, (config, _)) => Config.put_generic config (member (op =) testers name))
   255       registered_testers gen_ctxt
   256   end
   257     
   258 (* generating tests *)
   259 
   260 fun gen_mk_tester lookup ctxt v =
   261   let
   262     val name = Config.get ctxt batch_tester
   263     val tester = case lookup ctxt name
   264       of NONE => error ("No such quickcheck batch-tester: " ^ name)
   265       | SOME tester => tester ctxt;
   266   in
   267     if Config.get ctxt quiet then
   268       try tester v
   269     else
   270       let (* FIXME !?!? *)
   271         val tester = Exn.interruptible_capture tester v
   272       in case Exn.get_res tester of
   273           NONE => SOME (Exn.release tester)
   274         | SOME tester => SOME tester
   275       end
   276   end
   277 
   278 val mk_batch_tester =
   279   gen_mk_tester (fn ctxt => AList.lookup (op =) ((fst o snd o fst o Data.get o Context.Proof) ctxt))
   280 val mk_batch_validator =
   281   gen_mk_tester (fn ctxt => AList.lookup (op =) ((snd o snd o fst o Data.get o Context.Proof) ctxt))
   282   
   283 (* testing propositions *)
   284 
   285 type compile_generator =
   286   Proof.context -> (term * term list) list -> int list -> term list option * report option
   287 
   288 fun limit timeout (limit_time, is_interactive) f exc () =
   289   if limit_time then
   290       TimeLimit.timeLimit timeout f ()
   291     handle TimeLimit.TimeOut =>
   292       if is_interactive then exc () else raise TimeLimit.TimeOut
   293   else
   294     f ()
   295 
   296 fun message ctxt s = if Config.get ctxt quiet then () else Output.urgent_message s
   297 
   298 fun verbose_message ctxt s = if not (Config.get ctxt quiet) andalso Config.get ctxt verbose
   299   then Output.urgent_message s else ()
   300 
   301 fun test_terms ctxt (limit_time, is_interactive) insts goals =
   302   case active_testers ctxt of
   303     [] => error "No active testers for quickcheck"
   304   | testers =>
   305     limit (seconds (Config.get ctxt timeout)) (limit_time, is_interactive)
   306       (fn () => Par_List.get_some (fn tester =>
   307       tester ctxt (length testers > 1) insts goals |>
   308       (fn result => if exists found_counterexample result then SOME result else NONE)) testers)
   309       (fn () => (message ctxt "Quickcheck ran out of time"; NONE)) ();
   310 
   311 fun all_axioms_of ctxt t =
   312   let
   313     val intros = Locale.get_intros ctxt
   314     val unfolds = Locale.get_unfolds ctxt
   315     fun retrieve_prems thms t = 
   316        case filter (fn th => Term.could_unify (Thm.concl_of th, t)) thms of
   317          [] => NONE 
   318        | [th] =>
   319          let
   320            val (tyenv, tenv) =
   321              Pattern.match (Proof_Context.theory_of ctxt) (Thm.concl_of th, t) (Vartab.empty, Vartab.empty)
   322          in SOME (map (Envir.subst_term (tyenv, tenv)) (Thm.prems_of th)) end
   323     fun all t =
   324       case retrieve_prems intros t of
   325         NONE => retrieve_prems unfolds t
   326       | SOME ts => SOME (maps (fn t => the_default [t] (all t)) ts)
   327   in
   328     all t
   329   end
   330 
   331 fun locale_config_of s =
   332   let
   333     val cs = space_explode " " s
   334   in
   335     if forall (fn c => c = "expand" orelse c = "interpret") cs then cs
   336     else (warning ("Invalid quickcheck_locale setting: falling back to the default setting.");
   337       ["interpret", "expand"])
   338   end
   339 
   340 fun test_goal (time_limit, is_interactive) (insts, eval_terms) i state =
   341   let
   342     val lthy = Proof.context_of state;
   343     val thy = Proof.theory_of state;
   344     val _ = message lthy "Quickchecking..."
   345     fun strip (Const ("all", _) $ Abs (_, _, t)) = strip t
   346       | strip t = t;
   347     val {goal = st, ...} = Proof.raw_goal state;
   348     val (gi, frees) = Logic.goal_params (prop_of st) i;
   349     val some_locale = case (Option.map #target o Named_Target.peek) lthy
   350      of NONE => NONE
   351       | SOME "" => NONE
   352       | SOME locale => SOME locale;
   353     val assms = if Config.get lthy no_assms then [] else case some_locale
   354      of NONE => Assumption.all_assms_of lthy
   355       | SOME locale => Assumption.local_assms_of lthy (Locale.init locale thy);
   356     val proto_goal = Logic.list_implies (map Thm.term_of assms, subst_bounds (frees, strip gi));
   357     fun axioms_of locale = case fst (Locale.specification_of thy locale) of
   358         NONE => []
   359       | SOME t => the_default [] (all_axioms_of lthy t)
   360    val config = locale_config_of (Config.get lthy locale) 
   361    val goals = case some_locale
   362      of NONE => [(proto_goal, eval_terms)]
   363       | SOME locale => fold (fn c =>
   364           if c = "expand" then cons (Logic.list_implies (axioms_of locale, proto_goal), eval_terms) else
   365           if c = "interpret" then
   366             append (map (fn (_, phi) => (Morphism.term phi proto_goal, map (Morphism.term phi) eval_terms))
   367           (Locale.registrations_of (Context.Theory thy) (*FIXME*) locale)) else I) config [];
   368     val _ = verbose_message lthy (Pretty.string_of
   369       (Pretty.big_list ("Checking goals: ") (map (Syntax.pretty_term lthy o fst) goals)))
   370   in
   371     test_terms lthy (time_limit, is_interactive) insts goals
   372   end
   373 
   374 (* pretty printing *)
   375 
   376 fun tool_name auto = (if auto then "Auto " else "") ^ "Quickcheck"
   377 
   378 fun pretty_counterex ctxt auto NONE =
   379     Pretty.str (tool_name auto ^ " found no counterexample." ^ Config.get ctxt tag)
   380   | pretty_counterex ctxt auto (SOME ((genuine, cex), eval_terms)) =
   381       Pretty.chunks ((Pretty.str (tool_name auto ^ " found a " ^
   382         (if genuine then "counterexample:"
   383           else "potentially spurious counterexample due to underspecified functions:")
   384           ^ Config.get ctxt tag ^ "\n") ::
   385         map (fn (s, t) =>
   386           Pretty.block [Pretty.str (s ^ " ="), Pretty.brk 1, Syntax.pretty_term ctxt t]) (rev cex))
   387         @ (if null eval_terms then []
   388            else (Pretty.fbrk :: Pretty.str ("Evaluated terms:") ::
   389              map (fn (t, u) =>
   390                Pretty.block [Syntax.pretty_term ctxt t, Pretty.str " =", Pretty.brk 1,
   391                  Syntax.pretty_term ctxt u]) (rev eval_terms))));
   392 
   393 fun pretty_report (Report {iterations = iterations, raised_match_errors = raised_match_errors,
   394     satisfied_assms = satisfied_assms, positive_concl_tests = positive_concl_tests}) =
   395   let
   396     fun pretty_stat s i = Pretty.block ([Pretty.str (s ^ ": " ^ string_of_int i)])
   397   in
   398      ([pretty_stat "iterations" iterations,
   399      pretty_stat "match exceptions" raised_match_errors]
   400      @ map_index
   401        (fn (i, n) => pretty_stat ("satisfied " ^ string_of_int (i + 1) ^ ". assumption") n)
   402        satisfied_assms
   403      @ [pretty_stat "positive conclusion tests" positive_concl_tests])
   404   end
   405 
   406 fun pretty_timings timings =
   407   Pretty.chunks (Pretty.fbrk :: Pretty.str "timings:" ::
   408     maps (fn (label, time) =>
   409       Pretty.str (label ^ ": " ^ string_of_int time ^ " ms") :: Pretty.brk 1 :: []) (rev timings))
   410 
   411 (* Isar commands *)
   412 
   413 fun read_nat s = case (Library.read_int o Symbol.explode) s
   414  of (k, []) => if k >= 0 then k
   415       else error ("Not a natural number: " ^ s)
   416   | (_, _ :: _) => error ("Not a natural number: " ^ s);
   417 
   418 fun read_bool "false" = false
   419   | read_bool "true" = true
   420   | read_bool s = error ("Not a Boolean value: " ^ s)
   421 
   422 fun read_real s =
   423   case (Real.fromString s) of
   424     SOME s => s
   425   | NONE => error ("Not a real number: " ^ s)
   426 
   427 fun read_expectation "no_expectation" = No_Expectation
   428   | read_expectation "no_counterexample" = No_Counterexample
   429   | read_expectation "counterexample" = Counterexample
   430   | read_expectation s = error ("Not an expectation value: " ^ s)
   431 
   432 fun valid_tester_name genctxt name = AList.defined (op =) (fst (fst (Data.get genctxt))) name
   433   
   434 fun parse_tester name (testers, genctxt) =
   435   if valid_tester_name genctxt name then
   436     (insert (op =) name testers, genctxt)  
   437   else
   438     error ("Unknown tester: " ^ name)
   439 
   440 fun parse_test_param ("tester", args) = fold parse_tester args
   441   | parse_test_param ("size", [arg]) = apsnd (Config.put_generic size (read_nat arg))
   442   | parse_test_param ("iterations", [arg]) = apsnd (Config.put_generic iterations (read_nat arg))
   443   | parse_test_param ("depth", [arg]) = apsnd (Config.put_generic depth (read_nat arg))  
   444   | parse_test_param ("default_type", arg) = (fn (testers, gen_ctxt) =>
   445     (testers, map_test_params
   446       ((apfst o K) (map (Proof_Context.read_typ (Context.proof_of gen_ctxt)) arg)) gen_ctxt))
   447   | parse_test_param ("no_assms", [arg]) = apsnd (Config.put_generic no_assms (read_bool arg))
   448   | parse_test_param ("expect", [arg]) = apsnd (map_test_params ((apsnd o K) (read_expectation arg)))
   449   | parse_test_param ("report", [arg]) = apsnd (Config.put_generic report (read_bool arg))
   450   | parse_test_param ("genuine_only", [arg]) = apsnd (Config.put_generic genuine_only (read_bool arg))
   451   | parse_test_param ("abort_potential", [arg]) = apsnd (Config.put_generic abort_potential (read_bool arg))
   452   | parse_test_param ("quiet", [arg]) = apsnd (Config.put_generic quiet (read_bool arg))
   453   | parse_test_param ("verbose", [arg]) = apsnd (Config.put_generic verbose (read_bool arg))
   454   | parse_test_param ("tag", [arg]) = apsnd (Config.put_generic tag arg)
   455   | parse_test_param ("use_subtype", [arg]) = apsnd (Config.put_generic use_subtype (read_bool arg))  
   456   | parse_test_param ("timeout", [arg]) = apsnd (Config.put_generic timeout (read_real arg))
   457   | parse_test_param ("finite_types", [arg]) = apsnd (Config.put_generic finite_types (read_bool arg))
   458   | parse_test_param ("allow_function_inversion", [arg]) =
   459       apsnd (Config.put_generic allow_function_inversion (read_bool arg))
   460   | parse_test_param ("finite_type_size", [arg]) =
   461     apsnd (Config.put_generic finite_type_size (read_nat arg))
   462   | parse_test_param (name, _) = (fn (testers, genctxt) =>
   463     if valid_tester_name genctxt name then
   464       (insert (op =) name testers, genctxt)  
   465     else error ("Unknown tester or test parameter: " ^ name));
   466 
   467 fun proof_map_result f = apsnd Context.the_proof o f o Context.Proof;
   468 
   469 fun parse_test_param_inst (name, arg) ((insts, eval_terms), (testers, ctxt)) =
   470       case try (Proof_Context.read_typ ctxt) name
   471        of SOME (TFree (v, _)) =>
   472          ((AList.update (op =) (v, Proof_Context.read_typ ctxt (the_single arg)) insts, eval_terms),
   473            (testers, ctxt))
   474         | NONE => (case name of
   475             "eval" => ((insts, eval_terms @ map (Syntax.read_term ctxt) arg), (testers, ctxt))
   476           | _ => ((insts, eval_terms),
   477             proof_map_result (fn gen_ctxt => parse_test_param (name, arg) (testers, gen_ctxt)) ctxt));
   478 
   479 fun quickcheck_params_cmd args = Context.theory_map
   480   (fn gen_ctxt => uncurry set_active_testers (fold parse_test_param args ([], gen_ctxt)));
   481 
   482 fun check_expectation state results =
   483   (if is_some results andalso expect (Proof.context_of state) = No_Counterexample
   484   then
   485     error ("quickcheck expected to find no counterexample but found one")
   486   else
   487     (if is_none results andalso expect (Proof.context_of state) = Counterexample
   488     then
   489       error ("quickcheck expected to find a counterexample but did not find one")
   490     else ()))
   491 
   492 fun gen_quickcheck args i state =
   493   state
   494   |> Proof.map_context_result (fn ctxt =>
   495     apsnd (fn (testers, ctxt) => Context.proof_map (set_active_testers testers) ctxt)
   496       (fold parse_test_param_inst args (([], []), ([], ctxt))))
   497   |> (fn ((insts, eval_terms), state') => test_goal (true, true) (insts, eval_terms) i state'
   498   |> tap (check_expectation state') |> rpair state')
   499 
   500 fun quickcheck args i state =
   501   Option.map (the o get_first counterexample_of) (fst (gen_quickcheck args i state))
   502 
   503 fun quickcheck_cmd args i state =
   504   gen_quickcheck args i (Toplevel.proof_of state)
   505   |> apfst (Option.map (the o get_first response_of))
   506   |> (fn (r, state) => Output.urgent_message (Pretty.string_of
   507        (pretty_counterex (Proof.context_of state) false r)));
   508 
   509 val parse_arg =
   510   Parse.name --
   511     (Scan.optional (@{keyword "="} |--
   512       (((Parse.name || Parse.float_number) >> single) ||
   513         (@{keyword "["} |-- Parse.list1 Parse.name --| @{keyword "]"}))) ["true"]);
   514 
   515 val parse_args =
   516   @{keyword "["} |-- Parse.list1 parse_arg --| @{keyword "]"} || Scan.succeed [];
   517 
   518 val _ =
   519   Outer_Syntax.command @{command_spec "quickcheck_params"} "set parameters for random testing"
   520     (parse_args >> (fn args => Toplevel.theory (quickcheck_params_cmd args)));
   521 
   522 val _ =
   523   Outer_Syntax.improper_command @{command_spec "quickcheck"}
   524     "try to find counterexample for subgoal"
   525     (parse_args -- Scan.optional Parse.nat 1
   526       >> (fn (args, i) => Toplevel.no_timing o Toplevel.keep (quickcheck_cmd args i)));
   527 
   528 (* automatic testing *)
   529 
   530 fun try_quickcheck auto state =
   531   let
   532     val ctxt = Proof.context_of state;
   533     val i = 1;
   534     val res =
   535       state
   536       |> Proof.map_context (Config.put report false #> Config.put quiet true)
   537       |> try (test_goal (false, false) ([], []) i);
   538   in
   539     case res of
   540       NONE => (unknownN, state)
   541     | SOME results =>
   542         let
   543           val msg = pretty_counterex ctxt auto (Option.map (the o get_first response_of) results)
   544         in
   545           if is_some results then
   546             (genuineN,
   547              state
   548              |> (if auto then
   549                    Proof.goal_message (K (Pretty.chunks [Pretty.str "",
   550                        Pretty.mark Isabelle_Markup.hilite msg]))
   551                  else
   552                    tap (fn _ => Output.urgent_message (Pretty.string_of msg))))
   553           else
   554             (noneN, state)
   555         end
   556   end
   557   |> `(fn (outcome_code, _) => outcome_code = genuineN)
   558 
   559 val setup = Try.register_tool (quickcheckN, (20, auto, try_quickcheck))
   560 
   561 end;
   562 
   563 val auto_quickcheck = Quickcheck.auto;