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