src/HOL/Tools/Quickcheck/narrowing_generators.ML
author bulwahn
Mon Dec 05 12:36:20 2011 +0100 (2011-12-05)
changeset 45763 3bb2bdf654f7
parent 45760 3b5a735897c3
child 45765 cb6ddee6a463
permissions -rw-r--r--
random reporting compilation returns if counterexample is genuine or potentially spurious, and takes genuine_only option as argument
     1 (*  Title:      HOL/Tools/Quickcheck/narrowing_generators.ML
     2     Author:     Lukas Bulwahn, TU Muenchen
     3 
     4 Narrowing-based counterexample generation.
     5 *)
     6 
     7 signature NARROWING_GENERATORS =
     8 sig
     9   val allow_existentials : bool Config.T
    10   val finite_functions : bool Config.T
    11   val overlord : bool Config.T
    12   val active : bool Config.T
    13   val test_term: Proof.context -> term * term list -> Quickcheck.result
    14   datatype counterexample = Universal_Counterexample of (term * counterexample)
    15     | Existential_Counterexample of (term * counterexample) list
    16     | Empty_Assignment
    17   val put_counterexample: (unit -> (bool * term list) option) -> Proof.context -> Proof.context
    18   val put_existential_counterexample : (unit -> counterexample option) -> Proof.context -> Proof.context
    19   val setup: theory -> theory
    20 end;
    21 
    22 structure Narrowing_Generators : NARROWING_GENERATORS =
    23 struct
    24 
    25 (* configurations *)
    26 
    27 val allow_existentials = Attrib.setup_config_bool @{binding quickcheck_allow_existentials} (K true)
    28 val finite_functions = Attrib.setup_config_bool @{binding quickcheck_finite_functions} (K true)
    29 val overlord = Attrib.setup_config_bool @{binding quickcheck_narrowing_overlord} (K false)
    30 
    31 (* partial_term_of instances *)
    32 
    33 fun mk_partial_term_of (x, T) =
    34   Const (@{const_name Quickcheck_Narrowing.partial_term_of_class.partial_term_of},
    35     Term.itselfT T --> @{typ narrowing_term} --> @{typ Code_Evaluation.term})
    36       $ Const ("TYPE", Term.itselfT T) $ x
    37 
    38 (** formal definition **)
    39 
    40 fun add_partial_term_of tyco raw_vs thy =
    41   let
    42     val vs = map (fn (v, _) => (v, @{sort typerep})) raw_vs;
    43     val ty = Type (tyco, map TFree vs);
    44     val lhs = Const (@{const_name partial_term_of},
    45         Term.itselfT ty --> @{typ narrowing_term} --> @{typ Code_Evaluation.term})
    46       $ Free ("x", Term.itselfT ty) $ Free ("t", @{typ narrowing_term});
    47     val rhs = @{term "undefined :: Code_Evaluation.term"};
    48     val eq = HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, rhs));
    49     fun triv_name_of t = (fst o dest_Free o fst o strip_comb o fst
    50       o HOLogic.dest_eq o HOLogic.dest_Trueprop) t ^ "_triv";
    51   in
    52     thy
    53     |> Class.instantiation ([tyco], vs, @{sort partial_term_of})
    54     |> `(fn lthy => Syntax.check_term lthy eq)
    55     |-> (fn eq => Specification.definition (NONE, ((Binding.name (triv_name_of eq), []), eq)))
    56     |> snd
    57     |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
    58   end;
    59 
    60 fun ensure_partial_term_of (tyco, (raw_vs, _)) thy =
    61   let
    62     val need_inst = not (can (Sorts.mg_domain (Sign.classes_of thy) tyco) @{sort partial_term_of})
    63       andalso can (Sorts.mg_domain (Sign.classes_of thy) tyco) @{sort typerep};
    64   in if need_inst then add_partial_term_of tyco raw_vs thy else thy end;
    65 
    66 
    67 (** code equations for datatypes **)
    68 
    69 fun mk_partial_term_of_eq thy ty (i, (c, (_, tys))) =
    70   let
    71     val frees = map Free (Name.invent_names Name.context "a" (map (K @{typ narrowing_term}) tys))
    72     val narrowing_term = @{term "Quickcheck_Narrowing.Ctr"} $ HOLogic.mk_number @{typ code_int} i
    73       $ (HOLogic.mk_list @{typ narrowing_term} (rev frees))
    74     val rhs = fold (fn u => fn t => @{term "Code_Evaluation.App"} $ t $ u)
    75         (map mk_partial_term_of (frees ~~ tys))
    76         (@{term "Code_Evaluation.Const"} $ HOLogic.mk_literal c $ HOLogic.mk_typerep (tys ---> ty))
    77     val insts =
    78       map (SOME o Thm.cterm_of thy o Logic.unvarify_types_global o Logic.varify_global)
    79         [Free ("ty", Term.itselfT ty), narrowing_term, rhs]
    80     val cty = Thm.ctyp_of thy ty;
    81   in
    82     @{thm partial_term_of_anything}
    83     |> Drule.instantiate' [SOME cty] insts
    84     |> Thm.varifyT_global
    85   end
    86 
    87 fun add_partial_term_of_code tyco raw_vs raw_cs thy =
    88   let
    89     val algebra = Sign.classes_of thy;
    90     val vs = map (fn (v, sort) =>
    91       (v, curry (Sorts.inter_sort algebra) @{sort typerep} sort)) raw_vs;
    92     val ty = Type (tyco, map TFree vs);
    93     val cs = (map o apsnd o apsnd o map o map_atyps)
    94       (fn TFree (v, _) => TFree (v, (the o AList.lookup (op =) vs) v)) raw_cs;
    95     val const = AxClass.param_of_inst thy (@{const_name partial_term_of}, tyco);
    96     val var_insts =
    97       map (SOME o Thm.cterm_of thy o Logic.unvarify_types_global o Logic.varify_global)
    98         [Free ("ty", Term.itselfT ty), @{term "Quickcheck_Narrowing.Var p tt"},
    99           @{term "Code_Evaluation.Free (STR ''_'')"} $ HOLogic.mk_typerep ty];
   100     val var_eq =
   101       @{thm partial_term_of_anything}
   102       |> Drule.instantiate' [SOME (Thm.ctyp_of thy ty)] var_insts
   103       |> Thm.varifyT_global
   104     val eqs = var_eq :: map_index (mk_partial_term_of_eq thy ty) cs;
   105  in
   106     thy
   107     |> Code.del_eqns const
   108     |> fold Code.add_eqn eqs
   109   end;
   110 
   111 fun ensure_partial_term_of_code (tyco, (raw_vs, cs)) thy =
   112   let
   113     val has_inst = can (Sorts.mg_domain (Sign.classes_of thy) tyco) @{sort partial_term_of};
   114   in if has_inst then add_partial_term_of_code tyco raw_vs cs thy else thy end;
   115 
   116 
   117 (* narrowing generators *)
   118 
   119 (** narrowing specific names and types **)
   120 
   121 exception FUNCTION_TYPE;
   122 
   123 val narrowingN = "narrowing";
   124 
   125 fun narrowingT T =
   126   @{typ Quickcheck_Narrowing.code_int} --> Type (@{type_name Quickcheck_Narrowing.cons}, [T])
   127 
   128 fun mk_empty T = Const (@{const_name Quickcheck_Narrowing.empty}, narrowingT T)
   129 
   130 fun mk_cons c T = Const (@{const_name Quickcheck_Narrowing.cons}, T --> narrowingT T) $ Const (c, T)
   131 
   132 fun mk_apply (T, t) (U, u) =
   133   let
   134     val (_, U') = dest_funT U
   135   in
   136     (U', Const (@{const_name Quickcheck_Narrowing.apply},
   137       narrowingT U --> narrowingT T --> narrowingT U') $ u $ t)
   138   end
   139   
   140 fun mk_sum (t, u) =
   141   let
   142     val T = fastype_of t
   143   in
   144     Const (@{const_name Quickcheck_Narrowing.sum}, T --> T --> T) $ t $ u
   145   end
   146 
   147 (** deriving narrowing instances **)
   148 
   149 fun mk_equations descr vs tycos narrowings (Ts, Us) =
   150   let
   151     fun mk_call T =
   152       (T, Const (@{const_name "Quickcheck_Narrowing.narrowing_class.narrowing"}, narrowingT T))
   153     fun mk_aux_call fTs (k, _) (tyco, Ts) =
   154       let
   155         val T = Type (tyco, Ts)
   156         val _ = if not (null fTs) then raise FUNCTION_TYPE else ()
   157       in
   158         (T, nth narrowings k)
   159       end
   160     fun mk_consexpr simpleT (c, xs) =
   161       let
   162         val Ts = map fst xs
   163       in snd (fold mk_apply xs (Ts ---> simpleT, mk_cons c (Ts ---> simpleT))) end
   164     fun mk_rhs exprs = foldr1 mk_sum exprs
   165     val rhss =
   166       Datatype_Aux.interpret_construction descr vs
   167         { atyp = mk_call, dtyp = mk_aux_call }
   168       |> (map o apfst) Type
   169       |> map (fn (T, cs) => map (mk_consexpr T) cs)
   170       |> map mk_rhs
   171     val lhss = narrowings
   172     val eqs = map (HOLogic.mk_Trueprop o HOLogic.mk_eq) (lhss ~~ rhss)
   173   in
   174     eqs
   175   end
   176     
   177 fun contains_recursive_type_under_function_types xs =
   178   exists (fn (_, (_, _, cs)) => cs |> exists (snd #> exists (fn dT =>
   179     (case Datatype_Aux.strip_dtyp dT of (_ :: _, Datatype.DtRec _) => true | _ => false)))) xs
   180 
   181 fun instantiate_narrowing_datatype config descr vs tycos prfx (names, auxnames) (Ts, Us) thy =
   182   let
   183     val _ = Datatype_Aux.message config "Creating narrowing generators ...";
   184     val narrowingsN = map (prefix (narrowingN ^ "_")) (names @ auxnames);
   185   in
   186     if not (contains_recursive_type_under_function_types descr) then
   187       thy
   188       |> Class.instantiation (tycos, vs, @{sort narrowing})
   189       |> Quickcheck_Common.define_functions
   190         (fn narrowings => mk_equations descr vs tycos narrowings (Ts, Us), NONE)
   191         prfx [] narrowingsN (map narrowingT (Ts @ Us))
   192       |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
   193     else
   194       thy
   195   end;
   196 
   197 (* testing framework *)
   198 
   199 val target = "Haskell_Quickcheck"
   200 
   201 (** invocation of Haskell interpreter **)
   202 
   203 val narrowing_engine =
   204   Context.>>> (Context.map_theory_result
   205     (Thy_Load.use_file (Path.explode "Tools/Quickcheck/Narrowing_Engine.hs")))
   206 
   207 val pnf_narrowing_engine =
   208   Context.>>> (Context.map_theory_result
   209     (Thy_Load.use_file (Path.explode "Tools/Quickcheck/PNF_Narrowing_Engine.hs")))
   210 
   211 fun exec verbose code =
   212   ML_Context.exec (fn () => Secure.use_text ML_Env.local_context (0, "generated code") verbose code)
   213 
   214 fun with_overlord_dir name f =
   215   let
   216     val path =
   217       Path.append (Path.explode "$ISABELLE_HOME_USER") (Path.basic (name ^ serial_string ()))
   218     val _ = Isabelle_System.mkdirs path;
   219   in Exn.release (Exn.capture f path) end;
   220 
   221 fun elapsed_time description e =
   222   let val ({elapsed, ...}, result) = Timing.timing e ()
   223   in (result, (description, Time.toMilliseconds elapsed)) end
   224   
   225 fun value (contains_existentials, ((genuine_only, quiet), size)) ctxt cookie (code, value_name) =
   226   let
   227     val ((is_genuine, counterexample_of), (get, put, put_ml)) = cookie
   228     fun message s = if quiet then () else Output.urgent_message s
   229     val current_size = Unsynchronized.ref 0
   230     val current_result = Unsynchronized.ref Quickcheck.empty_result 
   231     fun excipit () =
   232       "Quickcheck ran out of time while testing at size " ^ string_of_int (!current_size)
   233     val tmp_prefix = "Quickcheck_Narrowing"
   234     val with_tmp_dir =
   235       if Config.get ctxt overlord then with_overlord_dir else Isabelle_System.with_tmp_dir 
   236     fun run in_path = 
   237       let
   238         val code_file = Path.append in_path (Path.basic "Generated_Code.hs")
   239         val narrowing_engine_file = Path.append in_path (Path.basic "Narrowing_Engine.hs")
   240         val main_file = Path.append in_path (Path.basic "Main.hs")
   241         val main = "module Main where {\n\n" ^
   242           "import System;\n" ^
   243           "import Narrowing_Engine;\n" ^
   244           "import Generated_Code;\n\n" ^
   245           "main = getArgs >>= \\[potential, size] -> " ^
   246           "Narrowing_Engine.depthCheck (read potential) (read size) (Generated_Code.value ())\n\n" ^
   247           "}\n"
   248         val code' = prefix "module Generated_Code where {\n\ndata Typerep = Typerep String [Typerep];\n"
   249           (unprefix "module Generated_Code where {" code)
   250         val _ = File.write code_file code'
   251         val _ = File.write narrowing_engine_file
   252           (if contains_existentials then pnf_narrowing_engine else narrowing_engine)
   253         val _ = File.write main_file main
   254         val executable = File.shell_path (Path.append in_path (Path.basic "isabelle_quickcheck_narrowing"))
   255         val cmd = "exec \"$ISABELLE_GHC\" " ^ Code_Haskell.language_params ^ " " ^
   256           (space_implode " " (map File.shell_path [code_file, narrowing_engine_file, main_file])) ^
   257           " -o " ^ executable ^ ";"
   258         val (result, compilation_time) =
   259           elapsed_time "Haskell compilation" (fn () => Isabelle_System.bash cmd) 
   260         val _ = Quickcheck.add_timing compilation_time current_result
   261         fun haskell_string_of_bool v = if v then "True" else "False"
   262         val _ = if Isabelle_System.bash cmd <> 0 then error "Compilation with GHC failed" else ()
   263         fun with_size genuine_only k =
   264           if k > size then
   265             (NONE, !current_result)
   266           else
   267             let
   268               val _ = message ("[Quickcheck-narrowing] Test data size: " ^ string_of_int k)
   269               val _ = current_size := k
   270               val ((response, _), timing) = elapsed_time ("execution of size " ^ string_of_int k)
   271                 (fn () => Isabelle_System.bash_output
   272                   (executable ^ " " ^ haskell_string_of_bool genuine_only ^ " " ^ string_of_int k))
   273               val _ = Quickcheck.add_timing timing current_result
   274             in
   275               if response = "NONE\n" then
   276                 with_size genuine_only (k + 1)
   277               else
   278                 let
   279                   val output_value = the_default "NONE"
   280                     (try (snd o split_last o filter_out (fn s => s = "") o split_lines) response)
   281                     |> translate_string (fn s => if s = "\\" then "\\\\" else s)
   282                   val ml_code = "\nval _ = Context.set_thread_data (SOME (Context.map_proof (" ^ put_ml
   283                     ^ " (fn () => " ^ output_value ^ ")) (ML_Context.the_generic_context ())))";
   284                   val ctxt' = ctxt
   285                     |> put (fn () => error ("Bad evaluation for " ^ quote put_ml))
   286                     |> Context.proof_map (exec false ml_code);                 
   287                   val counterexample = get ctxt' ()
   288                 in
   289                   if is_genuine counterexample then
   290                     (counterexample, !current_result)
   291                   else
   292                     let
   293                       val cex = Option.map (rpair []) (counterexample_of counterexample)
   294                     in
   295                       (Output.urgent_message (Pretty.string_of (Quickcheck.pretty_counterex ctxt false cex));
   296                       Output.urgent_message "Quickcheck continues to find a genuine counterexample...";
   297                       with_size true (k + 1))
   298                     end
   299                end
   300             end 
   301       in with_size genuine_only 0 end
   302   in
   303     with_tmp_dir tmp_prefix run
   304   end;
   305 
   306 fun dynamic_value_strict opts cookie thy postproc t =
   307   let
   308     val ctxt = Proof_Context.init_global thy
   309     fun evaluator naming program ((_, vs_ty), t) deps =
   310       Exn.interruptible_capture (value opts ctxt cookie)
   311         (Code_Target.evaluator thy target naming program deps (vs_ty, t));    
   312   in Exn.release (Code_Thingol.dynamic_value thy (Exn.map_result o postproc) evaluator t) end;
   313 
   314 (** counterexample generator **)
   315   
   316 structure Counterexample = Proof_Data
   317 (
   318   type T = unit -> (bool * term list) option
   319   fun init _ () = error "Counterexample"
   320 )
   321 
   322 datatype counterexample = Universal_Counterexample of (term * counterexample)
   323   | Existential_Counterexample of (term * counterexample) list
   324   | Empty_Assignment
   325   
   326 fun map_counterexample f Empty_Assignment = Empty_Assignment
   327   | map_counterexample f (Universal_Counterexample (t, c)) =
   328       Universal_Counterexample (f t, map_counterexample f c)
   329   | map_counterexample f (Existential_Counterexample cs) =
   330       Existential_Counterexample (map (fn (t, c) => (f t, map_counterexample f c)) cs)
   331 
   332 structure Existential_Counterexample = Proof_Data
   333 (
   334   type T = unit -> counterexample option
   335   fun init _ () = error "Counterexample"
   336 )
   337 
   338 val put_existential_counterexample = Existential_Counterexample.put
   339 
   340 val put_counterexample = Counterexample.put
   341 
   342 fun finitize_functions (xTs, t) =
   343   let
   344     val (names, boundTs) = split_list xTs
   345     fun mk_eval_ffun dT rT =
   346       Const (@{const_name "Quickcheck_Narrowing.eval_ffun"}, 
   347         Type (@{type_name "Quickcheck_Narrowing.ffun"}, [dT, rT]) --> dT --> rT)
   348     fun mk_eval_cfun dT rT =
   349       Const (@{const_name "Quickcheck_Narrowing.eval_cfun"}, 
   350         Type (@{type_name "Quickcheck_Narrowing.cfun"}, [rT]) --> dT --> rT)
   351     fun eval_function (T as Type (@{type_name fun}, [dT, rT])) =
   352       let
   353         val (rt', rT') = eval_function rT
   354       in
   355         case dT of
   356           Type (@{type_name fun}, _) =>
   357             (fn t => absdummy dT (rt' (mk_eval_cfun dT rT' $ incr_boundvars 1 t $ Bound 0)),
   358               Type (@{type_name "Quickcheck_Narrowing.cfun"}, [rT']))
   359         | _ =>
   360             (fn t => absdummy dT (rt' (mk_eval_ffun dT rT' $ incr_boundvars 1 t $ Bound 0)),
   361               Type (@{type_name "Quickcheck_Narrowing.ffun"}, [dT, rT']))
   362       end
   363       | eval_function T = (I, T)
   364     val (tt, boundTs') = split_list (map eval_function boundTs)
   365     val t' = subst_bounds (map2 (fn f => fn x => f x) (rev tt) (map_index (Bound o fst) boundTs), t)
   366   in
   367     (names ~~ boundTs', t')
   368   end
   369 
   370 fun dest_ffun (Type (@{type_name "Quickcheck_Narrowing.ffun"}, [dT, rT])) = (dT, rT)
   371 
   372 fun eval_finite_functions (Const (@{const_name "Quickcheck_Narrowing.ffun.Constant"}, T) $ value) =
   373     absdummy (fst (dest_ffun (body_type T))) (eval_finite_functions value)
   374   | eval_finite_functions (Const (@{const_name "Quickcheck_Narrowing.ffun.Update"}, T) $ a $ b $ f) =
   375     let
   376       val (T1, T2) = dest_ffun (body_type T)
   377     in
   378       Quickcheck_Common.mk_fun_upd T1 T2
   379         (eval_finite_functions a, eval_finite_functions b) (eval_finite_functions f)
   380     end
   381   | eval_finite_functions t = t
   382 
   383 (** tester **)
   384 
   385 val rewrs =
   386     map (swap o HOLogic.dest_eq o HOLogic.dest_Trueprop o Thm.prop_of)
   387       (@{thms all_simps} @ @{thms ex_simps})
   388     @ map (HOLogic.dest_eq o HOLogic.dest_Trueprop o Thm.prop_of)
   389         [@{thm iff_conv_conj_imp}, @{thm not_ex}, @{thm not_all}]
   390 
   391 fun make_pnf_term thy t = Pattern.rewrite_term thy rewrs [] t
   392 
   393 fun strip_quantifiers (Const (@{const_name Ex}, _) $ Abs (x, T, t)) =
   394     apfst (cons (@{const_name Ex}, (x, T))) (strip_quantifiers t)
   395   | strip_quantifiers (Const (@{const_name All}, _) $ Abs (x, T, t)) =
   396     apfst (cons (@{const_name All}, (x, T))) (strip_quantifiers t)
   397   | strip_quantifiers t = ([], t)
   398 
   399 fun contains_existentials t = exists (fn (Q, _) => Q = @{const_name Ex}) (fst (strip_quantifiers t))
   400 
   401 fun mk_property qs t =
   402   let
   403     fun enclose (@{const_name Ex}, (x, T)) t =
   404         Const (@{const_name Quickcheck_Narrowing.exists}, (T --> @{typ property}) --> @{typ property})
   405           $ Abs (x, T, t)
   406       | enclose (@{const_name All}, (x, T)) t =
   407         Const (@{const_name Quickcheck_Narrowing.all}, (T --> @{typ property}) --> @{typ property})
   408           $ Abs (x, T, t)
   409   in
   410     fold_rev enclose qs (@{term Quickcheck_Narrowing.Property} $ t)
   411   end
   412 
   413 fun mk_case_term ctxt p ((@{const_name Ex}, (x, T)) :: qs') (Existential_Counterexample cs) =
   414     Datatype.make_case ctxt Datatype_Case.Quiet [] (Free (x, T)) (map (fn (t, c) =>
   415       (t, mk_case_term ctxt (p - 1) qs' c)) cs)
   416   | mk_case_term ctxt p ((@{const_name All}, (x, T)) :: qs') (Universal_Counterexample (t, c)) =
   417     if p = 0 then t else mk_case_term ctxt (p - 1) qs' c
   418 
   419 val post_process = (perhaps (try Quickcheck_Common.post_process_term)) o eval_finite_functions
   420 
   421 fun mk_terms ctxt qs result =
   422   let
   423     val
   424       ps = filter (fn (_, (@{const_name All}, _)) => true | _ => false) (map_index I qs)
   425     in
   426       map (fn (p, (_, (x, T))) => (x, mk_case_term ctxt p qs result)) ps
   427       |> map (apsnd post_process)
   428     end
   429   
   430 fun test_term ctxt (t, eval_terms) =
   431   let
   432     fun dest_result (Quickcheck.Result r) = r 
   433     val opts =
   434       ((Config.get ctxt Quickcheck.genuine_only, Config.get ctxt Quickcheck.quiet),
   435         Config.get ctxt Quickcheck.size)
   436     val thy = Proof_Context.theory_of ctxt
   437     val t' = fold_rev (fn (x, T) => fn t => HOLogic.mk_all (x, T, t)) (Term.add_frees t []) t
   438     val pnf_t = make_pnf_term thy t'
   439   in
   440     if Config.get ctxt allow_existentials andalso contains_existentials pnf_t then
   441       let
   442         fun wrap f (qs, t) =
   443           let val (qs1, qs2) = split_list qs in
   444           apfst (map2 pair qs1) (f (qs2, t)) end
   445         val finitize = if Config.get ctxt finite_functions then wrap finitize_functions else I
   446         val (qs, prop_t) = finitize (strip_quantifiers pnf_t)
   447         val (counterexample, result) = dynamic_value_strict (true, opts)
   448           ((K true, fn _ => error ""), (Existential_Counterexample.get, Existential_Counterexample.put,
   449             "Narrowing_Generators.put_existential_counterexample"))
   450           thy (apfst o Option.map o map_counterexample) (mk_property qs prop_t)
   451       in
   452         Quickcheck.Result
   453          {counterexample = Option.map (pair true o mk_terms ctxt qs) counterexample,
   454           evaluation_terms = Option.map (K []) counterexample,
   455           timings = #timings (dest_result result), reports = #reports (dest_result result)}
   456       end
   457     else
   458       let
   459         val frees = Term.add_frees t []
   460         val t' = fold_rev absfree frees t
   461         fun wrap f t = list_abs (f (strip_abs t))
   462         val finitize = if Config.get ctxt finite_functions then wrap finitize_functions else I
   463         fun ensure_testable t =
   464           Const (@{const_name Quickcheck_Narrowing.ensure_testable}, fastype_of t --> fastype_of t) $ t
   465         fun is_genuine (SOME (true, _)) = true 
   466           | is_genuine _ = false
   467         val counterexample_of = Option.map (apsnd (curry (op ~~) (map fst frees) o map post_process))
   468         val (counterexample, result) = dynamic_value_strict (false, opts)
   469           ((is_genuine, counterexample_of),
   470             (Counterexample.get, Counterexample.put, "Narrowing_Generators.put_counterexample"))
   471           thy (apfst o Option.map o apsnd o map) (ensure_testable (finitize t'))
   472       in
   473         Quickcheck.Result
   474          {counterexample = counterexample_of counterexample,
   475           evaluation_terms = Option.map (K []) counterexample,
   476           timings = #timings (dest_result result), reports = #reports (dest_result result)}
   477       end
   478   end;
   479 
   480 fun test_goals ctxt _ insts goals =
   481   if (not (getenv "ISABELLE_GHC" = "")) then
   482     let
   483       val correct_inst_goals = Quickcheck_Common.instantiate_goals ctxt insts goals
   484     in
   485       Quickcheck_Common.collect_results (test_term ctxt) (maps (map snd) correct_inst_goals) []
   486     end
   487   else
   488     (if Config.get ctxt Quickcheck.quiet then () else Output.urgent_message
   489       ("Environment variable ISABELLE_GHC is not set. To use narrowing-based quickcheck, please set "
   490         ^ "this variable to your GHC Haskell compiler in your settings file. "
   491         ^ "To deactivate narrowing-based quickcheck, set quickcheck_narrowing_active to false.");
   492       [Quickcheck.empty_result])
   493 
   494 (* setup *)
   495 
   496 val active = Attrib.setup_config_bool @{binding quickcheck_narrowing_active} (K true);
   497 
   498 val setup =
   499   Code.datatype_interpretation ensure_partial_term_of
   500   #> Code.datatype_interpretation ensure_partial_term_of_code
   501   #> Datatype.interpretation (Quickcheck_Common.ensure_sort_datatype
   502     (((@{sort typerep}, @{sort term_of}), @{sort narrowing}), instantiate_narrowing_datatype))
   503   #> Context.theory_map (Quickcheck.add_tester ("narrowing", (active, test_goals)))
   504     
   505 end;