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