src/Tools/quickcheck.ML
author blanchet
Tue Feb 09 16:05:49 2010 +0100 (2010-02-09)
changeset 35077 c1dac8ace020
parent 34948 2d5f2a9f7601
child 35324 c9f428269b38
permissions -rw-r--r--
make Quickcheck identify itself, so people don't submit bug reports to me thinking that it was Nitpick
     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 auto: bool Unsynchronized.ref
    10   val timing : bool Unsynchronized.ref
    11   val test_term: Proof.context -> bool -> string option -> int -> int -> term ->
    12     (string * term) list option
    13   val add_generator: string * (Proof.context -> term -> int -> term list option) -> theory -> theory
    14   val setup: theory -> theory
    15   val quickcheck: (string * string) list -> int -> Proof.state -> (string * term) list option
    16 end;
    17 
    18 structure Quickcheck : QUICKCHECK =
    19 struct
    20 
    21 (* preferences *)
    22 
    23 val auto = Unsynchronized.ref false;
    24 
    25 val timing = Unsynchronized.ref false;
    26 
    27 val _ =
    28   ProofGeneralPgip.add_preference Preferences.category_tracing
    29   (setmp_CRITICAL auto true (fn () =>
    30     Preferences.bool_pref auto
    31       "auto-quickcheck"
    32       "Whether to run Quickcheck automatically.") ());
    33 
    34 
    35 (* quickcheck configuration -- default parameters, test generators *)
    36 
    37 datatype test_params = Test_Params of
    38   { size: int, iterations: int, default_type: typ option, no_assms: bool };
    39 
    40 fun dest_test_params (Test_Params { size, iterations, default_type, no_assms }) =
    41   ((size, iterations), (default_type, no_assms));
    42 fun make_test_params ((size, iterations), (default_type, no_assms)) =
    43   Test_Params { size = size, iterations = iterations, default_type = default_type,
    44                 no_assms = no_assms };
    45 fun map_test_params f (Test_Params { size, iterations, default_type, no_assms }) =
    46   make_test_params (f ((size, iterations), (default_type, no_assms)));
    47 fun merge_test_params (Test_Params { size = size1, iterations = iterations1, default_type = default_type1,
    48                                      no_assms = no_assms1 },
    49   Test_Params { size = size2, iterations = iterations2, default_type = default_type2,
    50                 no_assms = no_assms2 }) =
    51   make_test_params ((Int.max (size1, size2), Int.max (iterations1, iterations2)),
    52     (case default_type1 of NONE => default_type2 | _ => default_type1, no_assms1 orelse no_assms2));
    53 
    54 structure Data = Theory_Data
    55 (
    56   type T = (string * (Proof.context -> term -> int -> term list option)) list
    57     * test_params;
    58   val empty = ([], Test_Params { size = 10, iterations = 100, default_type = NONE, no_assms = false });
    59   val extend = I;
    60   fun merge ((generators1, params1), (generators2, params2)) : T =
    61     (AList.merge (op =) (K true) (generators1, generators2),
    62       merge_test_params (params1, params2));
    63 );
    64 
    65 val add_generator = Data.map o apfst o AList.update (op =);
    66 
    67 
    68 (* generating tests *)
    69 
    70 fun mk_tester_select name ctxt =
    71   case AList.lookup (op =) ((fst o Data.get o ProofContext.theory_of) ctxt) name
    72    of NONE => error ("No such quickcheck generator: " ^ name)
    73     | SOME generator => generator ctxt;
    74 
    75 fun mk_testers ctxt t =
    76   (map snd o fst o Data.get o ProofContext.theory_of) ctxt
    77   |> map_filter (fn generator => try (generator ctxt) t);
    78 
    79 fun mk_testers_strict ctxt t =
    80   let
    81     val generators = ((map snd o fst o Data.get o ProofContext.theory_of) ctxt)
    82     val testers = map (fn generator => Exn.capture (generator ctxt) t) generators;
    83   in if forall (is_none o Exn.get_result) testers
    84     then [(Exn.release o snd o split_last) testers]
    85     else map_filter Exn.get_result testers
    86   end;
    87 
    88 
    89 (* testing propositions *)
    90 
    91 fun prep_test_term t =
    92   let
    93     val _ = (null (Term.add_tvars t []) andalso null (Term.add_tfrees t [])) orelse
    94       error "Term to be tested contains type variables";
    95     val _ = null (Term.add_vars t []) orelse
    96       error "Term to be tested contains schematic variables";
    97     val frees = Term.add_frees t [];
    98   in (map fst frees, list_abs_free (frees, t)) end
    99 
   100 fun test_term ctxt quiet generator_name size i t =
   101   let
   102     val (names, t') = prep_test_term t;
   103     val testers = (*cond_timeit (!timing) "quickcheck compilation"
   104       (fn () => *)(case generator_name
   105        of NONE => if quiet then mk_testers ctxt t' else mk_testers_strict ctxt t'
   106         | SOME name => [mk_tester_select name ctxt t']);
   107     fun iterate f 0 = NONE
   108       | iterate f j = case f () handle Match => (if quiet then ()
   109              else warning "Exception Match raised during quickcheck"; NONE)
   110           of NONE => iterate f (j - 1) | SOME q => SOME q;
   111     fun with_testers k [] = NONE
   112       | with_testers k (tester :: testers) =
   113           case iterate (fn () => tester (k - 1)) i
   114            of NONE => with_testers k testers
   115             | SOME q => SOME q;
   116     fun with_size k = if k > size then NONE
   117       else (if quiet then () else priority ("Test data size: " ^ string_of_int k);
   118         case with_testers k testers
   119          of NONE => with_size (k + 1) | SOME q => SOME q);
   120   in
   121     cond_timeit (!timing) "quickcheck execution"
   122     (fn () => case with_size 1
   123       of NONE => NONE
   124       | SOME ts => SOME (names ~~ ts))
   125   end;
   126 
   127 fun monomorphic_term thy insts default_T = 
   128   let
   129     fun subst (T as TFree (v, S)) =
   130           let
   131             val T' = AList.lookup (op =) insts v
   132               |> the_default (the_default T default_T)
   133           in if Sign.of_sort thy (T, S) then T'
   134             else error ("Type " ^ Syntax.string_of_typ_global thy T ^
   135               " to be substituted for variable " ^
   136               Syntax.string_of_typ_global thy T ^ "\ndoes not have sort " ^
   137               Syntax.string_of_sort_global thy S)
   138           end
   139       | subst T = T;
   140   in (map_types o map_atyps) subst end;
   141 
   142 fun test_goal quiet generator_name size iterations default_T no_assms insts i assms state =
   143   let
   144     val ctxt = Proof.context_of state;
   145     val thy = Proof.theory_of state;
   146     fun strip (Const ("all", _) $ Abs (_, _, t)) = strip t
   147       | strip t = t;
   148     val {goal = st, ...} = Proof.raw_goal state;
   149     val (gi, frees) = Logic.goal_params (prop_of st) i;
   150     val gi' = Logic.list_implies (if no_assms then [] else assms,
   151                                   subst_bounds (frees, strip gi))
   152       |> monomorphic_term thy insts default_T
   153       |> ObjectLogic.atomize_term thy;
   154   in test_term ctxt quiet generator_name size iterations gi' end;
   155 
   156 fun pretty_counterex ctxt NONE = Pretty.str "Quickcheck found no counterexample."
   157   | pretty_counterex ctxt (SOME cex) =
   158       Pretty.chunks (Pretty.str "Quickcheck found a counterexample:\n" ::
   159         map (fn (s, t) =>
   160           Pretty.block [Pretty.str (s ^ " ="), Pretty.brk 1, Syntax.pretty_term ctxt t]) cex);
   161 
   162 
   163 (* automatic testing *)
   164 
   165 fun auto_quickcheck state =
   166   if not (!auto) then
   167     (false, state)
   168   else
   169     let
   170       val ctxt = Proof.context_of state;
   171       val assms = map term_of (Assumption.all_assms_of ctxt);
   172       val Test_Params { size, iterations, default_type, no_assms } =
   173         (snd o Data.get o Proof.theory_of) state;
   174       val res =
   175         try (test_goal true NONE size iterations default_type no_assms [] 1 assms) state;
   176     in
   177       case res of
   178         NONE => (false, state)
   179       | SOME NONE => (false, state)
   180       | SOME cex => (true, Proof.goal_message (K (Pretty.chunks [Pretty.str "",
   181           Pretty.mark Markup.hilite (pretty_counterex ctxt cex)])) state)
   182     end
   183 
   184 val setup = Auto_Counterexample.register_tool ("quickcheck", auto_quickcheck)
   185 
   186 
   187 (* Isar commands *)
   188 
   189 fun read_nat s = case (Library.read_int o Symbol.explode) s
   190  of (k, []) => if k >= 0 then k
   191       else error ("Not a natural number: " ^ s)
   192   | (_, _ :: _) => error ("Not a natural number: " ^ s);
   193 fun read_bool "false" = false
   194   | read_bool "true" = true
   195   | read_bool s = error ("Not a Boolean value: " ^ s)
   196 
   197 fun parse_test_param ctxt ("size", arg) =
   198       (apfst o apfst o K) (read_nat arg)
   199   | parse_test_param ctxt ("iterations", arg) =
   200       (apfst o apsnd o K) (read_nat arg)
   201   | parse_test_param ctxt ("default_type", arg) =
   202       (apsnd o apfst o K o SOME) (ProofContext.read_typ ctxt arg)
   203   | parse_test_param ctxt ("no_assms", arg) =
   204       (apsnd o apsnd o K) (read_bool arg)
   205   | parse_test_param ctxt (name, _) =
   206       error ("Unknown test parameter: " ^ name);
   207 
   208 fun parse_test_param_inst ctxt ("generator", arg) =
   209       (apsnd o apfst o K o SOME) arg
   210   | parse_test_param_inst ctxt (name, arg) =
   211       case try (ProofContext.read_typ ctxt) name
   212        of SOME (TFree (v, _)) => (apsnd o apsnd o AList.update (op =))
   213               (v, ProofContext.read_typ ctxt arg)
   214         | _ => (apfst o parse_test_param ctxt) (name, arg);
   215 
   216 fun quickcheck_params_cmd args thy =
   217   let
   218     val ctxt = ProofContext.init thy;
   219     val f = fold (parse_test_param ctxt) args;
   220   in
   221     thy
   222     |> (Data.map o apsnd o map_test_params) f
   223   end;
   224 
   225 fun quickcheck args i state =
   226   let
   227     val thy = Proof.theory_of state;
   228     val ctxt = Proof.context_of state;
   229     val assms = map term_of (Assumption.all_assms_of ctxt);
   230     val default_params = (dest_test_params o snd o Data.get) thy;
   231     val f = fold (parse_test_param_inst ctxt) args;
   232     val (((size, iterations), (default_type, no_assms)), (generator_name, insts)) =
   233       f (default_params, (NONE, []));
   234   in
   235     test_goal false generator_name size iterations default_type no_assms insts i assms state
   236   end;
   237 
   238 fun quickcheck_cmd args i state =
   239   quickcheck args i (Toplevel.proof_of state)
   240   |> Pretty.writeln o pretty_counterex (Toplevel.context_of state);
   241 
   242 local structure P = OuterParse and K = OuterKeyword in
   243 
   244 val parse_arg = P.name -- (Scan.optional (P.$$$ "=" |-- P.name) "true")
   245 
   246 val parse_args = P.$$$ "[" |-- P.list1 parse_arg --| P.$$$ "]"
   247   || Scan.succeed [];
   248 
   249 val _ = OuterSyntax.command "quickcheck_params" "set parameters for random testing" K.thy_decl
   250   (parse_args >> (fn args => Toplevel.theory (quickcheck_params_cmd args)));
   251 
   252 val _ = OuterSyntax.improper_command "quickcheck" "try to find counterexample for subgoal" K.diag
   253   (parse_args -- Scan.optional P.nat 1
   254     >> (fn (args, i) => Toplevel.no_timing o Toplevel.keep (quickcheck_cmd args i)));
   255 
   256 end; (*local*)
   257 
   258 end;
   259 
   260 
   261 val auto_quickcheck = Quickcheck.auto;