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