src/Tools/quickcheck.ML
author wenzelm
Mon, 25 Oct 2010 21:06:56 +0200
changeset 40392 7ee65dbffa31
parent 39880 f398f66969ce
child 40395 8728165d366e
permissions -rw-r--r--
renamed Output.priority to Output.urgent_message to emphasize its special role more clearly;
     1 (*  Title:      Tools/quickcheck.ML
     2     Author:     Stefan Berghofer, Florian Haftmann, TU Muenchen
     3 
     4 Generic counterexample search engine.
     5 *)
     6 
     7 signature QUICKCHECK =
     8 sig
     9   val setup: theory -> theory
    10   (* configuration *)
    11   val auto: bool Unsynchronized.ref
    12   val timing : bool Unsynchronized.ref
    13   datatype report = Report of
    14     { iterations : int, raised_match_errors : int,
    15       satisfied_assms : int list, positive_concl_tests : int }
    16   datatype expectation = No_Expectation | No_Counterexample | Counterexample;
    17   datatype test_params = Test_Params of
    18   { size: int, iterations: int, default_type: typ list, no_assms: bool,
    19     expect : expectation, report: bool, quiet : bool};
    20   val test_params_of: Proof.context -> test_params 
    21   val report : Proof.context -> bool
    22   val set_reporting : bool -> Context.generic -> Context.generic
    23   val add_generator:
    24     string * (Proof.context -> term -> int -> term list option * (bool list * bool))
    25       -> Context.generic -> Context.generic
    26   (* testing terms and proof states *)
    27   val gen_test_term: Proof.context -> bool -> string option -> int -> int -> term ->
    28     (string * term) list option * ((string * int) list * ((int * report list) list) option)
    29   val test_term: Proof.context -> bool -> string option -> int -> int -> term ->
    30     (string * term) list option
    31   val quickcheck: (string * string list) list -> int -> Proof.state -> (string * term) list option
    32 end;
    33 
    34 structure Quickcheck : QUICKCHECK =
    35 struct
    36 
    37 (* preferences *)
    38 
    39 val auto = Unsynchronized.ref false;
    40 
    41 val timing = Unsynchronized.ref false;
    42 
    43 val _ =
    44   ProofGeneralPgip.add_preference Preferences.category_tracing
    45   (Unsynchronized.setmp auto true (fn () =>
    46     Preferences.bool_pref auto
    47       "auto-quickcheck"
    48       "Run Quickcheck automatically.") ());
    49 
    50 (* quickcheck report *)
    51 
    52 datatype single_report = Run of bool list * bool | MatchExc
    53 
    54 datatype report = Report of
    55   { iterations : int, raised_match_errors : int,
    56     satisfied_assms : int list, positive_concl_tests : int }
    57 
    58 fun collect_single_report single_report
    59     (Report {iterations = iterations, raised_match_errors = raised_match_errors,
    60     satisfied_assms = satisfied_assms, positive_concl_tests = positive_concl_tests}) =
    61   case single_report
    62   of MatchExc =>
    63     Report {iterations = iterations + 1, raised_match_errors = raised_match_errors + 1,
    64       satisfied_assms = satisfied_assms, positive_concl_tests = positive_concl_tests}
    65    | Run (assms, concl) =>
    66     Report {iterations = iterations + 1, raised_match_errors = raised_match_errors,
    67       satisfied_assms =
    68         map2 (fn b => fn s => if b then s + 1 else s) assms
    69          (if null satisfied_assms then replicate (length assms) 0 else satisfied_assms),
    70       positive_concl_tests = if concl then positive_concl_tests + 1 else positive_concl_tests}
    71 
    72 (* expectation *)
    73 
    74 datatype expectation = No_Expectation | No_Counterexample | Counterexample; 
    75 
    76 fun merge_expectation (expect1, expect2) =
    77   if expect1 = expect2 then expect1 else No_Expectation
    78 
    79 (* quickcheck configuration -- default parameters, test generators *)
    80 
    81 datatype test_params = Test_Params of
    82   { size: int, iterations: int, default_type: typ list, no_assms: bool,
    83     expect : expectation, report: bool, quiet : bool};
    84 
    85 fun dest_test_params (Test_Params { size, iterations, default_type, no_assms, expect, report, quiet }) =
    86   ((size, iterations), ((default_type, no_assms), ((expect, report), quiet)));
    87 
    88 fun make_test_params ((size, iterations), ((default_type, no_assms), ((expect, report), quiet))) =
    89   Test_Params { size = size, iterations = iterations, default_type = default_type,
    90     no_assms = no_assms, expect = expect, report = report, quiet = quiet };
    91 
    92 fun map_test_params f (Test_Params { size, iterations, default_type, no_assms, expect, report, quiet }) =
    93   make_test_params (f ((size, iterations), ((default_type, no_assms), ((expect, report), quiet))));
    94 
    95 fun merge_test_params
    96  (Test_Params { size = size1, iterations = iterations1, default_type = default_type1,
    97     no_assms = no_assms1, expect = expect1, report = report1, quiet = quiet1 },
    98   Test_Params { size = size2, iterations = iterations2, default_type = default_type2,
    99     no_assms = no_assms2, expect = expect2, report = report2, quiet = quiet2 }) =
   100   make_test_params ((Int.max (size1, size2), Int.max (iterations1, iterations2)),
   101     ((merge (op =) (default_type1, default_type2), no_assms1 orelse no_assms2),
   102     ((merge_expectation (expect1, expect2), report1 orelse report2), quiet1 orelse quiet2)));
   103 
   104 structure Data = Generic_Data
   105 (
   106   type T =
   107     (string * (Proof.context -> term -> int -> term list option * (bool list * bool))) list
   108       * test_params;
   109   val empty = ([], Test_Params
   110     { size = 10, iterations = 100, default_type = [], no_assms = false,
   111       expect = No_Expectation, report = false, quiet = false});
   112   val extend = I;
   113   fun merge ((generators1, params1), (generators2, params2)) : T =
   114     (AList.merge (op =) (K true) (generators1, generators2),
   115       merge_test_params (params1, params2));
   116 );
   117 
   118 val test_params_of = snd o Data.get o Context.Proof;
   119 
   120 val report = snd o fst o snd o snd o dest_test_params o test_params_of
   121 
   122 fun map_report f (Test_Params { size, iterations, default_type, no_assms, expect, report, quiet }) =
   123   make_test_params ((size, iterations), ((default_type, no_assms), ((expect, f report), quiet)));
   124 
   125 fun set_reporting report = Data.map (apsnd (map_report (K report)))
   126 
   127 val add_generator = Data.map o apfst o AList.update (op =);
   128 
   129 (* generating tests *)
   130 
   131 fun mk_tester_select name ctxt =
   132   case AList.lookup (op =) ((fst o Data.get o Context.Proof) ctxt) name
   133    of NONE => error ("No such quickcheck generator: " ^ name)
   134     | SOME generator => generator ctxt;
   135 
   136 fun mk_testers ctxt t =
   137   (map snd o fst o Data.get o Context.Proof) ctxt
   138   |> map_filter (fn generator => try (generator ctxt) t);
   139 
   140 fun mk_testers_strict ctxt t =
   141   let
   142     val generators = ((map snd o fst o Data.get  o Context.Proof) ctxt)
   143     val testers = map (fn generator => Exn.capture (generator ctxt) t) generators;
   144   in if forall (is_none o Exn.get_result) testers
   145     then [(Exn.release o snd o split_last) testers]
   146     else map_filter Exn.get_result testers
   147   end;
   148 
   149 
   150 (* testing propositions *)
   151 
   152 fun prep_test_term t =
   153   let
   154     val _ = (null (Term.add_tvars t []) andalso null (Term.add_tfrees t [])) orelse
   155       error "Term to be tested contains type variables";
   156     val _ = null (Term.add_vars t []) orelse
   157       error "Term to be tested contains schematic variables";
   158     val frees = Term.add_frees t [];
   159   in (map fst frees, list_abs_free (frees, t)) end
   160 
   161 fun cpu_time description f =
   162   let
   163     val start = start_timing ()
   164     val result = Exn.capture f ()
   165     val time = Time.toMilliseconds (#cpu (end_timing start))
   166   in (Exn.release result, (description, time)) end
   167 
   168 fun gen_test_term ctxt quiet generator_name size i t =
   169   let
   170     val (names, t') = prep_test_term t;
   171     val (testers, comp_time) = cpu_time "quickcheck compilation"
   172       (fn () => (case generator_name
   173        of NONE => if quiet then mk_testers ctxt t' else mk_testers_strict ctxt t'
   174         | SOME name => [mk_tester_select name ctxt t']));
   175     fun iterate f 0 report = (NONE, report)
   176       | iterate f j report =
   177         let
   178           val (test_result, single_report) = apsnd Run (f ()) handle Match => (if quiet then ()
   179              else warning "Exception Match raised during quickcheck"; (NONE, MatchExc))
   180           val report = collect_single_report single_report report
   181         in
   182           case test_result of NONE => iterate f (j - 1) report | SOME q => (SOME q, report)
   183         end
   184     val empty_report = Report { iterations = 0, raised_match_errors = 0,
   185       satisfied_assms = [], positive_concl_tests = 0 }
   186     fun with_testers k [] = (NONE, [])
   187       | with_testers k (tester :: testers) =
   188           case iterate (fn () => tester (k - 1)) i empty_report
   189            of (NONE, report) => apsnd (cons report) (with_testers k testers)
   190             | (SOME q, report) => (SOME q, [report]);
   191     fun with_size k reports =
   192       if k > size then (NONE, reports)
   193       else
   194        (if quiet then () else Output.urgent_message ("Test data size: " ^ string_of_int k);
   195         let
   196           val (result, new_report) = with_testers k testers
   197           val reports = ((k, new_report) :: reports)
   198         in case result of NONE => with_size (k + 1) reports | SOME q => (SOME q, reports) end);
   199     val ((result, reports), exec_time) = cpu_time "quickcheck execution"
   200       (fn () => apfst
   201          (fn result => case result of NONE => NONE
   202         | SOME ts => SOME (names ~~ ts)) (with_size 1 []))
   203   in
   204     (result, ([exec_time, comp_time], if report ctxt then SOME reports else NONE))
   205   end;
   206 
   207 fun test_term ctxt quiet generator_name size i t =
   208   ctxt
   209   |> Context.proof_map (set_reporting false)
   210   |> (fn ctxt' => fst (gen_test_term ctxt' quiet generator_name size i t))
   211 
   212 exception WELLSORTED of string
   213 
   214 fun monomorphic_term thy insts default_T = 
   215   let
   216     fun subst (T as TFree (v, S)) =
   217           let
   218             val T' = AList.lookup (op =) insts v
   219               |> the_default default_T
   220           in if Sign.of_sort thy (T', S) then T'
   221             else raise (WELLSORTED ("For instantiation with default_type " ^ Syntax.string_of_typ_global thy default_T ^
   222               ":\n" ^ Syntax.string_of_typ_global thy T' ^
   223               " to be substituted for variable " ^
   224               Syntax.string_of_typ_global thy T ^ " does not have sort " ^
   225               Syntax.string_of_sort_global thy S))
   226           end
   227       | subst T = T;
   228   in (map_types o map_atyps) subst end;
   229 
   230 datatype wellsorted_error = Wellsorted_Error of string | Term of term
   231 
   232 fun test_goal quiet generator_name size iterations default_Ts no_assms insts i state =
   233   let
   234     val lthy = Proof.context_of state;
   235     val thy = Proof.theory_of state;
   236     fun strip (Const ("all", _) $ Abs (_, _, t)) = strip t
   237       | strip t = t;
   238     val {goal = st, ...} = Proof.raw_goal state;
   239     val (gi, frees) = Logic.goal_params (prop_of st) i;
   240     val some_locale = case (Option.map #target o Named_Target.peek) lthy
   241      of NONE => NONE
   242       | SOME "" => NONE
   243       | SOME locale => SOME locale;
   244     val assms = if no_assms then [] else case some_locale
   245      of NONE => Assumption.all_assms_of lthy
   246       | SOME locale => Assumption.local_assms_of lthy (Locale.init locale thy);
   247     val proto_goal = Logic.list_implies (map Thm.term_of assms, subst_bounds (frees, strip gi));
   248     val check_goals = case some_locale
   249      of NONE => [proto_goal]
   250       | SOME locale => map (fn (_, phi) => Morphism.term phi proto_goal) (Locale.registrations_of (Context.Theory thy) (*FIXME*) locale);
   251     val inst_goals = maps (fn check_goal => map (fn T =>
   252       Term ((Object_Logic.atomize_term thy o monomorphic_term thy insts T) check_goal)
   253         handle WELLSORTED s => Wellsorted_Error s) default_Ts) check_goals
   254     val error_msg = cat_lines (map_filter (fn Term t => NONE | Wellsorted_Error s => SOME s) inst_goals)
   255     val correct_inst_goals =
   256       case map_filter (fn Term t => SOME t | Wellsorted_Error s => NONE) inst_goals of
   257         [] => error error_msg
   258       | xs => xs
   259     val _ = if quiet then () else warning error_msg
   260     fun collect_results f reports [] = (NONE, rev reports)
   261       | collect_results f reports (t :: ts) =
   262         case f t of
   263           (SOME res, report) => (SOME res, rev (report :: reports))
   264         | (NONE, report) => collect_results f (report :: reports) ts
   265   in collect_results (gen_test_term lthy quiet generator_name size iterations) [] correct_inst_goals end;
   266 
   267 (* pretty printing *)
   268 
   269 fun pretty_counterex ctxt NONE = Pretty.str "Quickcheck found no counterexample."
   270   | pretty_counterex ctxt (SOME cex) =
   271       Pretty.chunks (Pretty.str "Quickcheck found a counterexample:\n" ::
   272         map (fn (s, t) =>
   273           Pretty.block [Pretty.str (s ^ " ="), Pretty.brk 1, Syntax.pretty_term ctxt t]) cex);
   274 
   275 fun pretty_report (Report {iterations = iterations, raised_match_errors = raised_match_errors,
   276     satisfied_assms = satisfied_assms, positive_concl_tests = positive_concl_tests}) =
   277   let
   278     fun pretty_stat s i = Pretty.block ([Pretty.str (s ^ ": " ^ string_of_int i)])
   279   in
   280      ([pretty_stat "iterations" iterations,
   281      pretty_stat "match exceptions" raised_match_errors]
   282      @ map_index (fn (i, n) => pretty_stat ("satisfied " ^ string_of_int (i + 1) ^ ". assumption") n)
   283        satisfied_assms
   284      @ [pretty_stat "positive conclusion tests" positive_concl_tests])
   285   end
   286 
   287 fun pretty_reports' [report] = [Pretty.chunks (pretty_report report)]
   288   | pretty_reports' reports =
   289   map_index (fn (i, report) =>
   290     Pretty.chunks (Pretty.str (string_of_int (i + 1) ^ ". generator:\n") :: pretty_report report))
   291     reports
   292 
   293 fun pretty_reports ctxt (SOME reports) =
   294   Pretty.chunks (Pretty.str "Quickcheck report:" ::
   295     maps (fn (size, reports) =>
   296       Pretty.str ("size " ^ string_of_int size ^ ":") :: pretty_reports' reports @ [Pretty.brk 1])
   297       (rev reports))
   298   | pretty_reports ctxt NONE = Pretty.str ""
   299 
   300 fun pretty_counterex_and_reports ctxt (cex, timing_and_reports) =
   301   Pretty.chunks (pretty_counterex ctxt cex :: map (pretty_reports ctxt) (map snd timing_and_reports))
   302 
   303 (* automatic testing *)
   304 
   305 fun auto_quickcheck state =
   306   if not (!auto) then
   307     (false, state)
   308   else
   309     let
   310       val ctxt = Proof.context_of state;
   311       val Test_Params {size, iterations, default_type, no_assms, ...} =
   312         (snd o Data.get o Context.Proof) ctxt;
   313       val res =
   314         state
   315         |> Proof.map_context (Context.proof_map (set_reporting false))
   316         |> try (test_goal true NONE size iterations default_type no_assms [] 1);
   317     in
   318       case res of
   319         NONE => (false, state)
   320       | SOME (NONE, report) => (false, state)
   321       | SOME (cex, report) => (true, Proof.goal_message (K (Pretty.chunks [Pretty.str "",
   322           Pretty.mark Markup.hilite (pretty_counterex ctxt cex)])) state)
   323     end
   324 
   325 val setup = Auto_Tools.register_tool ("quickcheck", auto_quickcheck)
   326 
   327 
   328 (* Isar commands *)
   329 
   330 fun read_nat s = case (Library.read_int o Symbol.explode) s
   331  of (k, []) => if k >= 0 then k
   332       else error ("Not a natural number: " ^ s)
   333   | (_, _ :: _) => error ("Not a natural number: " ^ s);
   334 
   335 fun read_bool "false" = false
   336   | read_bool "true" = true
   337   | read_bool s = error ("Not a Boolean value: " ^ s)
   338 
   339 fun read_expectation "no_expectation" = No_Expectation
   340   | read_expectation "no_counterexample" = No_Counterexample 
   341   | read_expectation "counterexample" = Counterexample
   342   | read_expectation s = error ("Not an expectation value: " ^ s)  
   343 
   344 fun parse_test_param ctxt ("size", [arg]) =
   345       (apfst o apfst o K) (read_nat arg)
   346   | parse_test_param ctxt ("iterations", [arg]) =
   347       (apfst o apsnd o K) (read_nat arg)
   348   | parse_test_param ctxt ("default_type", arg) =
   349       (apsnd o apfst o apfst o K) (map (ProofContext.read_typ ctxt) arg)
   350   | parse_test_param ctxt ("no_assms", [arg]) =
   351       (apsnd o apfst o apsnd o K) (read_bool arg)
   352   | parse_test_param ctxt ("expect", [arg]) =
   353       (apsnd o apsnd o apfst o apfst o K) (read_expectation arg)
   354   | parse_test_param ctxt ("report", [arg]) =
   355       (apsnd o apsnd o apfst o apsnd o K) (read_bool arg)
   356   | parse_test_param ctxt ("quiet", [arg]) =
   357       (apsnd o apsnd o apsnd o K) (read_bool arg)       
   358   | parse_test_param ctxt (name, _) =
   359       error ("Unknown test parameter: " ^ name);
   360 
   361 fun parse_test_param_inst ctxt ("generator", [arg]) =
   362       (apsnd o apfst o K o SOME) arg
   363   | parse_test_param_inst ctxt (name, arg) =
   364       case try (ProofContext.read_typ ctxt) name
   365        of SOME (TFree (v, _)) => (apsnd o apsnd o AList.update (op =))
   366               (v, ProofContext.read_typ ctxt (the_single arg))
   367         | _ => (apfst o parse_test_param ctxt) (name, arg);
   368 
   369 fun quickcheck_params_cmd args thy =
   370   let
   371     val ctxt = ProofContext.init_global thy
   372     val f = fold (parse_test_param ctxt) args;
   373   in
   374     thy
   375     |> (Context.theory_map o Data.map o apsnd o map_test_params) f
   376   end;
   377 
   378 fun gen_quickcheck args i state =
   379   let
   380     val ctxt = Proof.context_of state;
   381     val default_params = (dest_test_params o snd o Data.get o Context.Proof) ctxt;
   382     val f = fold (parse_test_param_inst ctxt) args;
   383     val (((size, iterations), ((default_type, no_assms), ((expect, report), quiet))), (generator_name, insts)) =
   384       f (default_params, (NONE, []));
   385   in
   386     state
   387     |> Proof.map_context (Context.proof_map (set_reporting report))
   388     |> test_goal quiet generator_name size iterations default_type no_assms insts i
   389     |> tap (fn (SOME x, _) => if expect = No_Counterexample then
   390                  error ("quickcheck expected to find no counterexample but found one") else ()
   391              | (NONE, _) => if expect = Counterexample then
   392                  error ("quickcheck expected to find a counterexample but did not find one") else ())
   393   end;
   394 
   395 fun quickcheck args i state = fst (gen_quickcheck args i state);
   396 
   397 fun quickcheck_cmd args i state =
   398   gen_quickcheck args i (Toplevel.proof_of state)
   399   |> Pretty.writeln o pretty_counterex_and_reports (Toplevel.context_of state);
   400 
   401 val parse_arg = Parse.name -- (Scan.optional (Parse.$$$ "=" |-- 
   402   ((Parse.name >> single) || (Parse.$$$ "[" |-- Parse.list1 Parse.name --| Parse.$$$ "]"))) ["true"]);
   403 
   404 val parse_args = Parse.$$$ "[" |-- Parse.list1 parse_arg --| Parse.$$$ "]"
   405   || Scan.succeed [];
   406 
   407 val _ =
   408   Outer_Syntax.command "quickcheck_params" "set parameters for random testing" Keyword.thy_decl
   409     (parse_args >> (fn args => Toplevel.theory (quickcheck_params_cmd args)));
   410 
   411 val _ =
   412   Outer_Syntax.improper_command "quickcheck" "try to find counterexample for subgoal" Keyword.diag
   413     (parse_args -- Scan.optional Parse.nat 1
   414       >> (fn (args, i) => Toplevel.no_timing o Toplevel.keep (quickcheck_cmd args i)));
   415 
   416 end;
   417 
   418 
   419 val auto_quickcheck = Quickcheck.auto;