src/HOL/Tools/Quickcheck/narrowing_generators.ML
author haftmann
Sun Feb 23 10:33:43 2014 +0100 (2014-02-23)
changeset 55676 fb46f1c379b5
parent 55147 bce3dbc11f95
child 55684 ee49b4f7edc8
permissions -rw-r--r--
avoid ad-hoc patching of generated code
     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 _ = map (uncurry File.write) (includes @
   251           [(narrowing_engine_file, if contains_existentials then pnf_narrowing_engine else narrowing_engine),
   252            (code_file, code), (main_file, main)])
   253         val executable = File.shell_path (Path.append in_path (Path.basic "isabelle_quickcheck_narrowing"))
   254         val cmd = "exec \"$ISABELLE_GHC\" " ^ Code_Haskell.language_params ^ " " ^
   255           ghc_options ^ " " ^
   256           (space_implode " " (map File.shell_path (map fst includes @ [code_file, narrowing_engine_file, main_file]))) ^
   257           " -o " ^ executable ^ ";"
   258         val (_, 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 _ = verbose_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                       (message (Pretty.string_of (Quickcheck.pretty_counterex ctxt false cex));
   296                       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 program ((_, vs_ty), t) deps =
   310       Exn.interruptible_capture (value opts ctxt cookie)
   311         (Code_Target.evaluator thy target 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 (* FIXME just one data slot (record) per program unit *)
   317 structure Counterexample = Proof_Data
   318 (
   319   type T = unit -> (bool * term list) option
   320   fun init _ () = error "Counterexample"
   321 )
   322 
   323 datatype counterexample = Universal_Counterexample of (term * counterexample)
   324   | Existential_Counterexample of (term * counterexample) list
   325   | Empty_Assignment
   326   
   327 fun map_counterexample f Empty_Assignment = Empty_Assignment
   328   | map_counterexample f (Universal_Counterexample (t, c)) =
   329       Universal_Counterexample (f t, map_counterexample f c)
   330   | map_counterexample f (Existential_Counterexample cs) =
   331       Existential_Counterexample (map (fn (t, c) => (f t, map_counterexample f c)) cs)
   332 
   333 (* FIXME just one data slot (record) per program unit *)
   334 structure Existential_Counterexample = Proof_Data
   335 (
   336   type T = unit -> counterexample option
   337   fun init _ () = error "Counterexample"
   338 )
   339 
   340 val put_existential_counterexample = Existential_Counterexample.put
   341 
   342 val put_counterexample = Counterexample.put
   343 
   344 fun finitize_functions (xTs, t) =
   345   let
   346     val (names, boundTs) = split_list xTs
   347     fun mk_eval_ffun dT rT =
   348       Const (@{const_name "Quickcheck_Narrowing.eval_ffun"}, 
   349         Type (@{type_name "Quickcheck_Narrowing.ffun"}, [dT, rT]) --> dT --> rT)
   350     fun mk_eval_cfun dT rT =
   351       Const (@{const_name "Quickcheck_Narrowing.eval_cfun"}, 
   352         Type (@{type_name "Quickcheck_Narrowing.cfun"}, [rT]) --> dT --> rT)
   353     fun eval_function (Type (@{type_name fun}, [dT, rT])) =
   354       let
   355         val (rt', rT') = eval_function rT
   356       in
   357         case dT of
   358           Type (@{type_name fun}, _) =>
   359             (fn t => absdummy dT (rt' (mk_eval_cfun dT rT' $ incr_boundvars 1 t $ Bound 0)),
   360               Type (@{type_name "Quickcheck_Narrowing.cfun"}, [rT']))
   361         | _ =>
   362             (fn t => absdummy dT (rt' (mk_eval_ffun dT rT' $ incr_boundvars 1 t $ Bound 0)),
   363               Type (@{type_name "Quickcheck_Narrowing.ffun"}, [dT, rT']))
   364       end
   365       | eval_function (T as Type (@{type_name prod}, [fT, sT])) =
   366         let
   367           val (ft', fT') = eval_function fT
   368           val (st', sT') = eval_function sT
   369           val T' = Type (@{type_name prod}, [fT', sT'])
   370           val map_const = Const (@{const_name map_pair}, (fT' --> fT) --> (sT' --> sT) --> T' --> T)
   371           fun apply_dummy T t = absdummy T (t (Bound 0))
   372         in
   373           (fn t => list_comb (map_const, [apply_dummy fT' ft', apply_dummy sT' st', t]), T')
   374         end
   375       | eval_function T = (I, T)
   376     val (tt, boundTs') = split_list (map eval_function boundTs)
   377     val t' = subst_bounds (map2 (fn f => fn x => f x) (rev tt) (map_index (Bound o fst) boundTs), t)
   378   in
   379     (names ~~ boundTs', t')
   380   end
   381 
   382 fun dest_ffun (Type (@{type_name "Quickcheck_Narrowing.ffun"}, [dT, rT])) = (dT, rT)
   383 
   384 fun eval_finite_functions (Const (@{const_name "Quickcheck_Narrowing.ffun.Constant"}, T) $ value) =
   385     absdummy (fst (dest_ffun (body_type T))) (eval_finite_functions value)
   386   | eval_finite_functions (Const (@{const_name "Quickcheck_Narrowing.ffun.Update"}, T) $ a $ b $ f) =
   387     let
   388       val (T1, T2) = dest_ffun (body_type T)
   389     in
   390       Quickcheck_Common.mk_fun_upd T1 T2
   391         (eval_finite_functions a, eval_finite_functions b) (eval_finite_functions f)
   392     end
   393   | eval_finite_functions t = t
   394 
   395 (** tester **)
   396 
   397 val rewrs =
   398     map (swap o HOLogic.dest_eq o HOLogic.dest_Trueprop o Thm.prop_of)
   399       (@{thms all_simps} @ @{thms ex_simps})
   400     @ map (HOLogic.dest_eq o HOLogic.dest_Trueprop o Thm.prop_of)
   401         [@{thm iff_conv_conj_imp}, @{thm not_ex}, @{thm not_all},
   402          @{thm meta_eq_to_obj_eq [OF Ex1_def]}]
   403 
   404 fun make_pnf_term thy t = Pattern.rewrite_term thy rewrs [] t
   405 
   406 fun strip_quantifiers (Const (@{const_name Ex}, _) $ Abs (x, T, t)) =
   407     apfst (cons (@{const_name Ex}, (x, T))) (strip_quantifiers t)
   408   | strip_quantifiers (Const (@{const_name All}, _) $ Abs (x, T, t)) =
   409     apfst (cons (@{const_name All}, (x, T))) (strip_quantifiers t)
   410   | strip_quantifiers t = ([], t)
   411 
   412 fun contains_existentials t = exists (fn (Q, _) => Q = @{const_name Ex}) (fst (strip_quantifiers t))
   413 
   414 fun mk_property qs t =
   415   let
   416     fun enclose (@{const_name Ex}, (x, T)) t =
   417         Const (@{const_name Quickcheck_Narrowing.exists}, (T --> @{typ property}) --> @{typ property})
   418           $ Abs (x, T, t)
   419       | enclose (@{const_name All}, (x, T)) t =
   420         Const (@{const_name Quickcheck_Narrowing.all}, (T --> @{typ property}) --> @{typ property})
   421           $ Abs (x, T, t)
   422   in
   423     fold_rev enclose qs (@{term Quickcheck_Narrowing.Property} $ t)
   424   end
   425 
   426 fun mk_case_term ctxt p ((@{const_name Ex}, (x, T)) :: qs') (Existential_Counterexample cs) =
   427     Case_Translation.make_case ctxt Case_Translation.Quiet Name.context (Free (x, T)) (map (fn (t, c) =>
   428       (t, mk_case_term ctxt (p - 1) qs' c)) cs)
   429   | mk_case_term ctxt p ((@{const_name All}, _) :: qs') (Universal_Counterexample (t, c)) =
   430     if p = 0 then t else mk_case_term ctxt (p - 1) qs' c
   431 
   432 val post_process = (perhaps (try Quickcheck_Common.post_process_term)) o eval_finite_functions
   433 
   434 fun mk_terms ctxt qs result =
   435   let
   436     val
   437       ps = filter (fn (_, (@{const_name All}, _)) => true | _ => false) (map_index I qs)
   438     in
   439       map (fn (p, (_, (x, _))) => (x, mk_case_term ctxt p qs result)) ps
   440       |> map (apsnd post_process)
   441     end
   442   
   443 fun test_term ctxt catch_code_errors (t, _) =
   444   let
   445     fun dest_result (Quickcheck.Result r) = r 
   446     val opts =
   447       ((Config.get ctxt Quickcheck.genuine_only,
   448        (Config.get ctxt Quickcheck.quiet, Config.get ctxt Quickcheck.verbose)),
   449         Config.get ctxt Quickcheck.size)
   450     val thy = Proof_Context.theory_of ctxt
   451     val t' = fold_rev (fn (x, T) => fn t => HOLogic.mk_all (x, T, t)) (Term.add_frees t []) t
   452     val pnf_t = make_pnf_term thy t'
   453   in
   454     if Config.get ctxt allow_existentials andalso contains_existentials pnf_t then
   455       let
   456         fun wrap f (qs, t) =
   457           let val (qs1, qs2) = split_list qs in
   458           apfst (map2 pair qs1) (f (qs2, t)) end
   459         val finitize = if Config.get ctxt finite_functions then wrap finitize_functions else I
   460         val (qs, prop_t) = finitize (strip_quantifiers pnf_t)
   461         val act = if catch_code_errors then try else (fn f => SOME o f)
   462         val execute = dynamic_value_strict (true, opts)
   463           ((K true, fn _ => error ""), (Existential_Counterexample.get, Existential_Counterexample.put,
   464             "Narrowing_Generators.put_existential_counterexample"))
   465           thy (apfst o Option.map o map_counterexample)
   466       in  
   467         case act execute (mk_property qs prop_t) of 
   468           SOME (counterexample, result) => Quickcheck.Result
   469             {counterexample = Option.map (pair true o mk_terms ctxt qs) counterexample,
   470             evaluation_terms = Option.map (K []) counterexample,
   471             timings = #timings (dest_result result), reports = #reports (dest_result result)}
   472         | NONE =>
   473           (Quickcheck.message ctxt ("Conjecture is not executable with Quickcheck-narrowing");
   474            Quickcheck.empty_result)
   475       end
   476     else
   477       let
   478         val frees = Term.add_frees t []
   479         val t' = fold_rev absfree frees t
   480         fun wrap f t = uncurry (fold_rev Term.abs) (f (strip_abs t))
   481         val finitize = if Config.get ctxt finite_functions then wrap finitize_functions else I
   482         fun ensure_testable t =
   483           Const (@{const_name Quickcheck_Narrowing.ensure_testable}, fastype_of t --> fastype_of t) $ t
   484         fun is_genuine (SOME (true, _)) = true 
   485           | is_genuine _ = false
   486         val counterexample_of = Option.map (apsnd (curry (op ~~) (map fst frees) o map post_process))
   487         val act = if catch_code_errors then try else (fn f => SOME o f)
   488         val execute = dynamic_value_strict (false, opts)
   489           ((is_genuine, counterexample_of),
   490             (Counterexample.get, Counterexample.put, "Narrowing_Generators.put_counterexample"))
   491           thy (apfst o Option.map o apsnd o map)
   492       in
   493         case act execute (ensure_testable (finitize t')) of 
   494           SOME (counterexample, result) =>
   495             Quickcheck.Result
   496              {counterexample = counterexample_of counterexample,
   497               evaluation_terms = Option.map (K []) counterexample,
   498               timings = #timings (dest_result result),
   499               reports = #reports (dest_result result)}
   500         | NONE =>
   501           (Quickcheck.message ctxt ("Conjecture is not executable with Quickcheck-narrowing");
   502            Quickcheck.empty_result)
   503       end
   504   end;
   505 
   506 fun test_goals ctxt catch_code_errors insts goals =
   507   if (not (getenv "ISABELLE_GHC" = "")) then
   508     let
   509       val _ = Quickcheck.message ctxt ("Testing conjecture with Quickcheck-narrowing...")
   510       val correct_inst_goals = Quickcheck_Common.instantiate_goals ctxt insts goals
   511     in
   512       Quickcheck_Common.collect_results (test_term ctxt catch_code_errors)
   513         (maps (map snd) correct_inst_goals) []
   514     end
   515   else
   516     (if Config.get ctxt Quickcheck.quiet then () else Output.urgent_message
   517       ("Environment variable ISABELLE_GHC is not set. To use narrowing-based quickcheck, please set "
   518         ^ "this variable to your GHC Haskell compiler in your settings file. "
   519         ^ "To deactivate narrowing-based quickcheck, set quickcheck_narrowing_active to false.");
   520       [Quickcheck.empty_result])
   521 
   522 (* setup *)
   523 
   524 val active = Attrib.setup_config_bool @{binding quickcheck_narrowing_active} (K false);
   525 
   526 val setup =
   527   Code.datatype_interpretation ensure_partial_term_of
   528   #> Code.datatype_interpretation ensure_partial_term_of_code
   529   #> Quickcheck_Common.datatype_interpretation (@{sort narrowing}, instantiate_narrowing_datatype)
   530   #> Context.theory_map (Quickcheck.add_tester ("narrowing", (active, test_goals)))
   531     
   532 end;