src/Tools/quickcheck.ML
author blanchet
Fri, 27 May 2011 10:30:08 +0200
changeset 43865 58150aa44941
parent 43861 abb5d1f907e4
child 43870 3e060b1c844b
permissions -rw-r--r--
prioritize try and auto try's tools, with fast ones first, with a slight preference for provers vs. counterexample generators
     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 tester : string Config.T
    17   val size : int Config.T
    18   val iterations : int Config.T
    19   val no_assms : bool Config.T
    20   val report : bool Config.T
    21   val timing : bool Config.T
    22   val quiet : bool Config.T
    23   val timeout : real Config.T
    24   val finite_types : bool Config.T
    25   val finite_type_size : int Config.T
    26   datatype expectation = No_Expectation | No_Counterexample | Counterexample;
    27   datatype test_params = Test_Params of {default_type: typ list, expect : expectation};
    28   val test_params_of : Proof.context -> test_params
    29   val map_test_params : (typ list * expectation -> typ list * expectation)
    30     -> Context.generic -> Context.generic
    31   datatype report = Report of
    32     { iterations : int, raised_match_errors : int,
    33       satisfied_assms : int list, positive_concl_tests : int }
    34   (* registering generators *)
    35   val add_generator:
    36     string * (Proof.context -> (term * term list) list -> int list -> term list option * report option)
    37       -> Context.generic -> Context.generic
    38   val add_batch_generator:
    39     string * (Proof.context -> term list -> (int -> term list option) list)
    40       -> Context.generic -> Context.generic
    41   val add_batch_validator:
    42     string * (Proof.context -> term list -> (int -> bool) list)
    43       -> Context.generic -> Context.generic
    44   (* quickcheck's result *)
    45   datatype result =
    46     Result of
    47      {counterexample : (string * term) list option,
    48       evaluation_terms : (term * term) list option,
    49       timings : (string * int) list,
    50       reports : (int * report) list}
    51   val counterexample_of : result -> (string * term) list option
    52   val timings_of : result -> (string * int) list
    53   (* testing terms and proof states *)
    54   val test_term: Proof.context -> bool * bool -> term * term list -> result
    55   val test_goal_terms:
    56     Proof.context -> bool * bool -> (string * typ) list -> (term * term list) list  
    57       -> result list
    58   val quickcheck: (string * string list) list -> int -> Proof.state -> (string * term) list option
    59   (* testing a batch of terms *)
    60   val test_terms:
    61     Proof.context -> term list -> (string * term) list option list option * (string * int) list
    62   val validate_terms: Proof.context -> term list -> bool list option * (string * int) list
    63 end;
    64 
    65 structure Quickcheck : QUICKCHECK =
    66 struct
    67 
    68 val quickcheckN = "quickcheck"
    69 val quickcheck_paramsN = "quickcheck_params"
    70 
    71 val genuineN = "genuine"
    72 val noneN = "none"
    73 val unknownN = "unknown"
    74 
    75 (* preferences *)
    76 
    77 val auto = Unsynchronized.ref false;
    78 
    79 val _ =
    80   ProofGeneralPgip.add_preference Preferences.category_tracing
    81   (Unsynchronized.setmp auto true (fn () =>
    82     Preferences.bool_pref auto
    83       "auto-quickcheck"
    84       "Run Quickcheck automatically.") ());
    85 
    86 (* quickcheck report *)
    87 
    88 datatype report = Report of
    89   { iterations : int, raised_match_errors : int,
    90     satisfied_assms : int list, positive_concl_tests : int }
    91 
    92 (* Quickcheck Result *)
    93 
    94 datatype result = Result of
    95   { counterexample : (string * term) list option, evaluation_terms : (term * term) list option,
    96     timings : (string * int) list, reports : (int * report) list}
    97 
    98 val empty_result =
    99   Result {counterexample = NONE, evaluation_terms = NONE, timings = [], reports = []}
   100 
   101 fun counterexample_of (Result r) = #counterexample r
   102 
   103 fun found_counterexample (Result r) = is_some (#counterexample r)
   104 
   105 fun response_of (Result r) = case (#counterexample r, #evaluation_terms r) of
   106     (SOME ts, SOME evals) => SOME (ts, evals)
   107   | (NONE, NONE) => NONE
   108 
   109 fun timings_of (Result r) = #timings r
   110 
   111 fun set_reponse names eval_terms (SOME ts) (Result r) =
   112   let
   113     val (ts1, ts2) = chop (length names) ts
   114   in
   115     Result {counterexample = SOME (names ~~ ts1), evaluation_terms = SOME (eval_terms ~~ ts2),
   116       timings = #timings r, reports = #reports r}
   117   end
   118   | set_reponse _ _ NONE result = result
   119 
   120 fun cons_timing timing (Result r) =
   121   Result {counterexample = #counterexample r, evaluation_terms = #evaluation_terms r,
   122     timings = cons timing (#timings r), reports = #reports r}
   123 
   124 fun cons_report size (SOME report) (Result r) =
   125   Result {counterexample = #counterexample r, evaluation_terms = #evaluation_terms r,
   126     timings = #timings r, reports = cons (size, report) (#reports r)}
   127   | cons_report _ NONE result = result
   128 
   129 fun add_timing timing result_ref =
   130   Unsynchronized.change result_ref (cons_timing timing)
   131 
   132 fun add_report size report result_ref =
   133   Unsynchronized.change result_ref (cons_report size report)
   134 
   135 fun add_response names eval_terms response result_ref =
   136   Unsynchronized.change result_ref (set_reponse names eval_terms response)
   137 
   138 (* expectation *)
   139 
   140 datatype expectation = No_Expectation | No_Counterexample | Counterexample;
   141 
   142 fun merge_expectation (expect1, expect2) =
   143   if expect1 = expect2 then expect1 else No_Expectation
   144 
   145 (* quickcheck configuration -- default parameters, test generators *)
   146 val tester = Attrib.setup_config_string @{binding quickcheck_tester} (K "")
   147 val size = Attrib.setup_config_int @{binding quickcheck_size} (K 10)
   148 val iterations = Attrib.setup_config_int @{binding quickcheck_iterations} (K 100)
   149 val no_assms = Attrib.setup_config_bool @{binding quickcheck_no_assms} (K false)
   150 val report = Attrib.setup_config_bool @{binding quickcheck_report} (K true)
   151 val timing = Attrib.setup_config_bool @{binding quickcheck_timing} (K false)
   152 val quiet = Attrib.setup_config_bool @{binding quickcheck_quiet} (K false)
   153 val timeout = Attrib.setup_config_real @{binding quickcheck_timeout} (K 30.0)
   154 val finite_types = Attrib.setup_config_bool @{binding quickcheck_finite_types} (K true)
   155 val finite_type_size = Attrib.setup_config_int @{binding quickcheck_finite_type_size} (K 3)
   156 
   157 datatype test_params = Test_Params of
   158   {default_type: typ list, expect : expectation};
   159 
   160 fun dest_test_params (Test_Params {default_type, expect}) = (default_type, expect);
   161 
   162 fun make_test_params (default_type, expect) =
   163   Test_Params {default_type = default_type, expect = expect};
   164 
   165 fun map_test_params' f (Test_Params {default_type, expect}) =
   166   make_test_params (f (default_type, expect));
   167 
   168 fun merge_test_params
   169   (Test_Params {default_type = default_type1, expect = expect1},
   170     Test_Params {default_type = default_type2, expect = expect2}) =
   171   make_test_params
   172     (merge (op =) (default_type1, default_type2), merge_expectation (expect1, expect2));
   173 
   174 structure Data = Generic_Data
   175 (
   176   type T =
   177     ((string * (Proof.context -> (term * term list) list -> int list -> term list option * report option)) list
   178       * ((string * (Proof.context -> term list -> (int -> term list option) list)) list
   179       * ((string * (Proof.context -> term list -> (int -> bool) list)) list)))
   180       * test_params;
   181   val empty = (([], ([], [])), Test_Params {default_type = [], expect = No_Expectation});
   182   val extend = I;
   183   fun merge (((generators1, (batch_generators1, batch_validators1)), params1),
   184     ((generators2, (batch_generators2, batch_validators2)), params2)) : T =
   185     ((AList.merge (op =) (K true) (generators1, generators2),
   186      (AList.merge (op =) (K true) (batch_generators1, batch_generators2),
   187       AList.merge (op =) (K true) (batch_validators1, batch_validators2))),
   188       merge_test_params (params1, params2));
   189 );
   190 
   191 val test_params_of = snd o Data.get o Context.Proof;
   192 
   193 val default_type = fst o dest_test_params o test_params_of
   194 
   195 val expect = snd o dest_test_params o test_params_of
   196 
   197 val map_test_params = Data.map o apsnd o map_test_params'
   198 
   199 val add_generator = Data.map o apfst o apfst o AList.update (op =);
   200 
   201 val add_batch_generator = Data.map o apfst o apsnd o apfst o AList.update (op =);
   202 
   203 val add_batch_validator = Data.map o apfst o apsnd o apsnd o AList.update (op =);
   204 
   205 (* generating tests *)
   206 
   207 fun gen_mk_tester lookup ctxt v =
   208   let
   209     val name = Config.get ctxt tester
   210     val tester = case lookup ctxt name
   211       of NONE => error ("No such quickcheck tester: " ^ name)
   212       | SOME tester => tester ctxt;
   213   in
   214     if Config.get ctxt quiet then
   215       try tester v
   216     else
   217       let
   218         val tester = Exn.interruptible_capture tester v
   219       in case Exn.get_result tester of
   220           NONE => SOME (Exn.release tester)
   221         | SOME tester => SOME tester
   222       end
   223   end
   224 
   225 val mk_tester =
   226   gen_mk_tester (fn ctxt => AList.lookup (op =) ((fst o fst o Data.get o Context.Proof) ctxt))
   227 val mk_batch_tester =
   228   gen_mk_tester (fn ctxt => AList.lookup (op =) ((fst o snd o fst o Data.get o Context.Proof) ctxt))
   229 val mk_batch_validator =
   230   gen_mk_tester (fn ctxt => AList.lookup (op =) ((snd o snd o fst o Data.get o Context.Proof) ctxt))
   231 
   232 (* testing propositions *)
   233 
   234 fun check_test_term t =
   235   let
   236     val _ = (null (Term.add_tvars t []) andalso null (Term.add_tfrees t [])) orelse
   237       error "Term to be tested contains type variables";
   238     val _ = null (Term.add_vars t []) orelse
   239       error "Term to be tested contains schematic variables";
   240   in () end
   241 
   242 fun cpu_time description e =
   243   let val ({cpu, ...}, result) = Timing.timing e ()
   244   in (result, (description, Time.toMilliseconds cpu)) end
   245 
   246 fun limit ctxt (limit_time, is_interactive) f exc () =
   247   if limit_time then
   248       TimeLimit.timeLimit (seconds (Config.get ctxt timeout)) f ()
   249     handle TimeLimit.TimeOut =>
   250       if is_interactive then exc () else raise TimeLimit.TimeOut
   251   else
   252     f ()
   253 
   254 fun test_term ctxt (limit_time, is_interactive) (t, eval_terms) =
   255   let
   256     fun message s = if Config.get ctxt quiet then () else Output.urgent_message s
   257     val _ = check_test_term t
   258     val names = Term.add_free_names t []
   259     val current_size = Unsynchronized.ref 0
   260     val current_result = Unsynchronized.ref empty_result 
   261     fun excipit () =
   262       "Quickcheck ran out of time while testing at size " ^ string_of_int (!current_size)
   263     fun with_size test_fun k =
   264       if k > Config.get ctxt size then
   265         NONE
   266       else
   267         let
   268           val _ = message ("Test data size: " ^ string_of_int k)
   269           val _ = current_size := k
   270           val ((result, report), timing) =
   271             cpu_time ("size " ^ string_of_int k) (fn () => test_fun [1, k - 1])
   272           val _ = add_timing timing current_result
   273           val _ = add_report k report current_result
   274         in
   275           case result of NONE => with_size test_fun (k + 1) | SOME q => SOME q
   276         end;
   277   in
   278     limit ctxt (limit_time, is_interactive) (fn () =>
   279       let
   280         val (test_fun, comp_time) = cpu_time "quickcheck compilation"
   281           (fn () => mk_tester ctxt [(t, eval_terms)]);
   282         val _ = add_timing comp_time current_result
   283       in
   284         case test_fun of NONE => !current_result
   285           | SOME test_fun =>
   286             let
   287               val (response, exec_time) =
   288                 cpu_time "quickcheck execution" (fn () => with_size test_fun 1)
   289               val _ = add_response names eval_terms response current_result
   290               val _ = add_timing exec_time current_result
   291             in
   292               !current_result
   293             end
   294        end)
   295      (fn () => (message (excipit ()); !current_result)) ()
   296   end;
   297 
   298 fun validate_terms ctxt ts =
   299   let
   300     val _ = map check_test_term ts
   301     val size = Config.get ctxt size
   302     val (test_funs, comp_time) = cpu_time "quickcheck batch compilation"
   303       (fn () => mk_batch_validator ctxt ts) 
   304     fun with_size tester k =
   305       if k > size then true
   306       else if tester k then with_size tester (k + 1) else false
   307     val (results, exec_time) = cpu_time "quickcheck batch execution" (fn () =>
   308         Option.map (map (fn test_fun => TimeLimit.timeLimit (seconds (Config.get ctxt timeout))
   309               (fn () => with_size test_fun 1) ()
   310              handle TimeLimit.TimeOut => true)) test_funs)
   311   in
   312     (results, [comp_time, exec_time])
   313   end
   314   
   315 fun test_terms ctxt ts =
   316   let
   317     val _ = map check_test_term ts
   318     val size = Config.get ctxt size
   319     val namess = map (fn t => Term.add_free_names t []) ts
   320     val (test_funs, comp_time) = cpu_time "quickcheck batch compilation" (fn () => mk_batch_tester ctxt ts) 
   321     fun with_size tester k =
   322       if k > size then NONE
   323       else case tester k of SOME ts => SOME ts | NONE => with_size tester (k + 1)
   324     val (results, exec_time) = cpu_time "quickcheck batch execution" (fn () =>
   325         Option.map (map (fn test_fun => TimeLimit.timeLimit (seconds (Config.get ctxt timeout))
   326               (fn () => with_size test_fun 1) ()
   327              handle TimeLimit.TimeOut => NONE)) test_funs)
   328   in
   329     (Option.map (map2 (fn names => Option.map (fn ts => names ~~ ts)) namess) results,
   330       [comp_time, exec_time])
   331   end
   332 
   333 (* FIXME: this function shows that many assumptions are made upon the generation *)
   334 (* In the end there is probably no generic quickcheck interface left... *)
   335 
   336 fun test_term_with_increasing_cardinality ctxt (limit_time, is_interactive) ts =
   337   let
   338     val thy = Proof_Context.theory_of ctxt
   339     fun message s = if Config.get ctxt quiet then () else Output.urgent_message s
   340     val (ts', eval_terms) = split_list ts
   341     val _ = map check_test_term ts'
   342     val names = Term.add_free_names (hd ts') []
   343     val Ts = map snd (Term.add_frees (hd ts') [])
   344     val current_result = Unsynchronized.ref empty_result
   345     fun test_card_size test_fun (card, size) =
   346       (* FIXME: why decrement size by one? *)
   347       let
   348         val (ts, timing) = cpu_time ("size " ^ string_of_int size ^ " and card " ^ string_of_int card)
   349           (fn () => fst (test_fun [card, size - 1]))
   350         val _ = add_timing timing current_result
   351       in
   352         Option.map (pair card) ts
   353       end
   354     val enumeration_card_size =
   355       if forall (fn T => Sign.of_sort thy (T,  ["Enum.enum"])) Ts then
   356         (* size does not matter *)
   357         map (rpair 0) (1 upto (length ts))
   358       else
   359         (* size does matter *)
   360         map_product pair (1 upto (length ts)) (1 upto (Config.get ctxt size))
   361         |> sort (fn ((c1, s1), (c2, s2)) => int_ord ((c1 + s1), (c2 + s2)))
   362   in
   363     limit ctxt (limit_time, is_interactive) (fn () =>
   364       let
   365         val (test_fun, comp_time) = cpu_time "quickcheck compilation" (fn () => mk_tester ctxt ts)
   366         val _ = add_timing comp_time current_result
   367       in
   368         case test_fun of
   369           NONE => !current_result
   370         | SOME test_fun =>
   371           let
   372             val _ = case get_first (test_card_size test_fun) enumeration_card_size of
   373               SOME (card, ts) => add_response names (nth eval_terms (card - 1)) (SOME ts) current_result
   374             | NONE => ()
   375           in !current_result end
   376       end)
   377       (fn () => (message "Quickcheck ran out of time"; !current_result)) ()
   378   end
   379 
   380 fun get_finite_types ctxt =
   381   fst (chop (Config.get ctxt finite_type_size)
   382     (map (Type o rpair []) ["Enum.finite_1", "Enum.finite_2", "Enum.finite_3",
   383      "Enum.finite_4", "Enum.finite_5"]))
   384 
   385 exception WELLSORTED of string
   386 
   387 fun monomorphic_term thy insts default_T =
   388   let
   389     fun subst (T as TFree (v, S)) =
   390       let
   391         val T' = AList.lookup (op =) insts v
   392           |> the_default default_T
   393       in if Sign.of_sort thy (T', S) then T'
   394         else raise (WELLSORTED ("For instantiation with default_type " ^
   395           Syntax.string_of_typ_global thy default_T ^
   396           ":\n" ^ Syntax.string_of_typ_global thy T' ^
   397           " to be substituted for variable " ^
   398           Syntax.string_of_typ_global thy T ^ " does not have sort " ^
   399           Syntax.string_of_sort_global thy S))
   400       end
   401       | subst T = T;
   402   in (map_types o map_atyps) subst end;
   403 
   404 datatype wellsorted_error = Wellsorted_Error of string | Term of term * term list
   405 
   406 fun test_goal_terms lthy (limit_time, is_interactive) insts check_goals =
   407   let
   408     fun map_goal_and_eval_terms f (check_goal, eval_terms) = (f check_goal, map f eval_terms)
   409     val thy = Proof_Context.theory_of lthy
   410     val default_insts =
   411       if Config.get lthy finite_types then (get_finite_types lthy) else (default_type lthy)
   412     val inst_goals =
   413       map (fn (check_goal, eval_terms) =>
   414         if not (null (Term.add_tfree_names check_goal [])) then
   415           map (fn T =>
   416             (pair (SOME T) o Term o apfst (Object_Logic.atomize_term thy))
   417               (map_goal_and_eval_terms (monomorphic_term thy insts T) (check_goal, eval_terms))
   418               handle WELLSORTED s => (SOME T, Wellsorted_Error s)) default_insts
   419         else
   420           [(NONE, Term (Object_Logic.atomize_term thy check_goal, eval_terms))]) check_goals
   421     val error_msg =
   422       cat_lines
   423         (maps (map_filter (fn (_, Term t) => NONE | (_, Wellsorted_Error s) => SOME s)) inst_goals)
   424     fun is_wellsorted_term (T, Term t) = SOME (T, t)
   425       | is_wellsorted_term (_, Wellsorted_Error s) = NONE
   426     val correct_inst_goals =
   427       case map (map_filter is_wellsorted_term) inst_goals of
   428         [[]] => error error_msg
   429       | xs => xs
   430     val _ = if Config.get lthy quiet then () else warning error_msg
   431     fun collect_results f [] results = results
   432       | collect_results f (t :: ts) results =
   433         let
   434           val result = f t
   435         in
   436           if found_counterexample result then
   437             (result :: results)
   438           else
   439             collect_results f ts (result :: results)
   440         end
   441     fun test_term' goal =
   442       case goal of
   443         [(NONE, t)] => test_term lthy (limit_time, is_interactive) t
   444       | ts => test_term_with_increasing_cardinality lthy (limit_time, is_interactive) (map snd ts)
   445   in
   446     if Config.get lthy finite_types then
   447       collect_results test_term' correct_inst_goals []
   448     else
   449       collect_results (test_term lthy (limit_time, is_interactive)) (maps (map snd) correct_inst_goals) []
   450   end;
   451 
   452 fun test_goal (time_limit, is_interactive) (insts, eval_terms) i state =
   453   let
   454     val lthy = Proof.context_of state;
   455     val thy = Proof.theory_of state;
   456     fun strip (Const ("all", _) $ Abs (_, _, t)) = strip t
   457       | strip t = t;
   458     val {goal = st, ...} = Proof.raw_goal state;
   459     val (gi, frees) = Logic.goal_params (prop_of st) i;
   460     val some_locale = case (Option.map #target o Named_Target.peek) lthy
   461      of NONE => NONE
   462       | SOME "" => NONE
   463       | SOME locale => SOME locale;
   464     val assms = if Config.get lthy no_assms then [] else case some_locale
   465      of NONE => Assumption.all_assms_of lthy
   466       | SOME locale => Assumption.local_assms_of lthy (Locale.init locale thy);
   467     val proto_goal = Logic.list_implies (map Thm.term_of assms, subst_bounds (frees, strip gi));
   468     val check_goals = case some_locale
   469      of NONE => [(proto_goal, eval_terms)]
   470       | SOME locale =>
   471         map (fn (_, phi) => (Morphism.term phi proto_goal, map (Morphism.term phi) eval_terms))
   472           (Locale.registrations_of (Context.Theory thy) (*FIXME*) locale);
   473   in
   474     test_goal_terms lthy (time_limit, is_interactive) insts check_goals
   475   end
   476 
   477 (* pretty printing *)
   478 
   479 fun tool_name auto = (if auto then "Auto " else "") ^ "Quickcheck"
   480 
   481 fun pretty_counterex ctxt auto NONE = Pretty.str (tool_name auto ^ " found no counterexample.")
   482   | pretty_counterex ctxt auto (SOME (cex, eval_terms)) =
   483       Pretty.chunks ((Pretty.str (tool_name auto ^ " found a counterexample:\n") ::
   484         map (fn (s, t) =>
   485           Pretty.block [Pretty.str (s ^ " ="), Pretty.brk 1, Syntax.pretty_term ctxt t]) (rev cex))
   486         @ (if null eval_terms then []
   487            else (Pretty.str ("Evaluated terms:\n") ::
   488              map (fn (t, u) =>
   489                Pretty.block [Syntax.pretty_term ctxt t, Pretty.str " =", Pretty.brk 1, Syntax.pretty_term ctxt u])
   490                (rev eval_terms))));
   491 
   492 fun pretty_report (Report {iterations = iterations, raised_match_errors = raised_match_errors,
   493     satisfied_assms = satisfied_assms, positive_concl_tests = positive_concl_tests}) =
   494   let
   495     fun pretty_stat s i = Pretty.block ([Pretty.str (s ^ ": " ^ string_of_int i)])
   496   in
   497      ([pretty_stat "iterations" iterations,
   498      pretty_stat "match exceptions" raised_match_errors]
   499      @ map_index
   500        (fn (i, n) => pretty_stat ("satisfied " ^ string_of_int (i + 1) ^ ". assumption") n)
   501        satisfied_assms
   502      @ [pretty_stat "positive conclusion tests" positive_concl_tests])
   503   end
   504 
   505 fun pretty_reports ctxt (SOME reports) =
   506   Pretty.chunks (Pretty.fbrk :: Pretty.str "Quickcheck report:" ::
   507     maps (fn (size, report) =>
   508       Pretty.str ("size " ^ string_of_int size ^ ":") :: pretty_report report @ [Pretty.brk 1])
   509       (rev reports))
   510   | pretty_reports ctxt NONE = Pretty.str ""
   511 
   512 fun pretty_timings timings =
   513   Pretty.chunks (Pretty.fbrk :: Pretty.str "timings:" ::
   514     maps (fn (label, time) =>
   515       Pretty.str (label ^ ": " ^ string_of_int time ^ " ms") :: Pretty.brk 1 :: []) (rev timings))
   516 
   517 fun pretty_counterex_and_reports ctxt auto [] =
   518     Pretty.chunks [Pretty.strs (tool_name auto ::
   519         space_explode " " "is used in a locale where no interpretation is provided."),
   520       Pretty.strs (space_explode " " "Please provide an executable interpretation for the locale.")]
   521   | pretty_counterex_and_reports ctxt auto (result :: _) =
   522     Pretty.chunks (pretty_counterex ctxt auto (response_of result) ::
   523       (* map (pretty_reports ctxt) (reports_of result) :: *)
   524       (if Config.get ctxt timing then cons (pretty_timings (timings_of result)) else I) [])
   525 
   526 (* Isar commands *)
   527 
   528 fun read_nat s = case (Library.read_int o Symbol.explode) s
   529  of (k, []) => if k >= 0 then k
   530       else error ("Not a natural number: " ^ s)
   531   | (_, _ :: _) => error ("Not a natural number: " ^ s);
   532 
   533 fun read_bool "false" = false
   534   | read_bool "true" = true
   535   | read_bool s = error ("Not a Boolean value: " ^ s)
   536 
   537 fun read_real s =
   538   case (Real.fromString s) of
   539     SOME s => s
   540   | NONE => error ("Not a real number: " ^ s)
   541 
   542 fun read_expectation "no_expectation" = No_Expectation
   543   | read_expectation "no_counterexample" = No_Counterexample
   544   | read_expectation "counterexample" = Counterexample
   545   | read_expectation s = error ("Not an expectation value: " ^ s)
   546 
   547 fun valid_tester_name genctxt = AList.defined (op =) (fst (fst (Data.get genctxt)))
   548 
   549 fun parse_tester name genctxt =
   550   if valid_tester_name genctxt name then
   551     Config.put_generic tester name genctxt
   552   else
   553     error ("Unknown tester: " ^ name)
   554 
   555 fun parse_test_param ("tester", [arg]) = parse_tester arg
   556   | parse_test_param ("size", [arg]) = Config.put_generic size (read_nat arg)
   557   | parse_test_param ("iterations", [arg]) = Config.put_generic iterations (read_nat arg)
   558   | parse_test_param ("default_type", arg) = (fn gen_ctxt =>
   559     map_test_params
   560       ((apfst o K) (map (Proof_Context.read_typ (Context.proof_of gen_ctxt)) arg)) gen_ctxt)
   561   | parse_test_param ("no_assms", [arg]) = Config.put_generic no_assms (read_bool arg)
   562   | parse_test_param ("expect", [arg]) = map_test_params ((apsnd o K) (read_expectation arg))
   563   | parse_test_param ("report", [arg]) = Config.put_generic report (read_bool arg)
   564   | parse_test_param ("quiet", [arg]) = Config.put_generic quiet (read_bool arg)
   565   | parse_test_param ("timeout", [arg]) = Config.put_generic timeout (read_real arg)
   566   | parse_test_param ("finite_types", [arg]) = Config.put_generic finite_types (read_bool arg)
   567   | parse_test_param ("finite_type_size", [arg]) =
   568     Config.put_generic finite_type_size (read_nat arg)
   569   | parse_test_param (name, _) = fn genctxt =>
   570     if valid_tester_name genctxt name then
   571       Config.put_generic tester name genctxt
   572     else error ("Unknown tester or test parameter: " ^ name);
   573 
   574 fun parse_test_param_inst (name, arg) ((insts, eval_terms), ctxt) =
   575       case try (Proof_Context.read_typ ctxt) name
   576        of SOME (TFree (v, _)) =>
   577          ((AList.update (op =) (v, Proof_Context.read_typ ctxt (the_single arg)) insts, eval_terms), ctxt)
   578         | NONE => (case name of
   579             "eval" => ((insts, eval_terms @ map (Syntax.read_term ctxt) arg), ctxt)
   580           | _ => ((insts, eval_terms), Context.proof_map (parse_test_param (name, arg)) ctxt));
   581 
   582 fun quickcheck_params_cmd args = Context.theory_map (fold parse_test_param args);
   583 
   584 fun check_expectation state results =
   585   (if exists found_counterexample results andalso expect (Proof.context_of state) = No_Counterexample
   586   then
   587     error ("quickcheck expected to find no counterexample but found one")
   588   else
   589     (if not (exists found_counterexample results) andalso expect (Proof.context_of state) = Counterexample
   590     then
   591       error ("quickcheck expected to find a counterexample but did not find one")
   592     else ()))
   593 
   594 fun gen_quickcheck args i state =
   595   state
   596   |> Proof.map_context_result (fn ctxt => fold parse_test_param_inst args (([], []), ctxt))
   597   |> (fn ((insts, eval_terms), state') => test_goal (true, true) (insts, eval_terms) i state'
   598   |> tap (check_expectation state'))
   599 
   600 fun quickcheck args i state = counterexample_of (hd (gen_quickcheck args i state))
   601 
   602 fun quickcheck_cmd args i state =
   603   gen_quickcheck args i (Toplevel.proof_of state)
   604   |> Output.urgent_message o Pretty.string_of
   605      o pretty_counterex_and_reports (Toplevel.context_of state) false;
   606 
   607 val parse_arg =
   608   Parse.name --
   609     (Scan.optional (Parse.$$$ "=" |--
   610       (((Parse.name || Parse.float_number) >> single) ||
   611         (Parse.$$$ "[" |-- Parse.list1 Parse.name --| Parse.$$$ "]"))) ["true"]);
   612 
   613 val parse_args =
   614   Parse.$$$ "[" |-- Parse.list1 parse_arg --| Parse.$$$ "]" || Scan.succeed [];
   615 
   616 val _ =
   617   Outer_Syntax.command quickcheck_paramsN "set parameters for random testing" Keyword.thy_decl
   618     (parse_args >> (fn args => Toplevel.theory (quickcheck_params_cmd args)));
   619 
   620 val _ =
   621   Outer_Syntax.improper_command quickcheckN "try to find counterexample for subgoal" Keyword.diag
   622     (parse_args -- Scan.optional Parse.nat 1
   623       >> (fn (args, i) => Toplevel.no_timing o Toplevel.keep (quickcheck_cmd args i)));
   624 
   625 (* automatic testing *)
   626 
   627 fun try_quickcheck auto state =
   628   let
   629     val ctxt = Proof.context_of state;
   630     val i = 1;
   631     val res =
   632       state
   633       |> Proof.map_context (Config.put report false #> Config.put quiet true)
   634       |> try (test_goal (false, false) ([], []) i);
   635   in
   636     case res of
   637       NONE => (unknownN, state)
   638     | SOME results =>
   639         let
   640           val msg = pretty_counterex_and_reports ctxt auto results
   641                     |> not auto ? tap (Output.urgent_message o Pretty.string_of)
   642         in
   643           if exists found_counterexample results then
   644             (genuineN,
   645              state |> (if auto then
   646                          Proof.goal_message (K (Pretty.chunks [Pretty.str "",
   647                              Pretty.mark Markup.hilite msg]))
   648                        else
   649                          I))
   650           else
   651             (noneN, state)
   652         end
   653   end
   654   |> `(fn (outcome_code, _) => outcome_code = genuineN)
   655 
   656 val setup = Try.register_tool (quickcheckN, (30, auto, try_quickcheck))
   657 
   658 end;
   659 
   660 val auto_quickcheck = Quickcheck.auto;