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