src/HOL/Tools/Quickcheck/narrowing_generators.ML
author bulwahn
Thu Mar 31 11:17:52 2011 +0200 (2011-03-31)
changeset 42184 1d4fae76ba5e
parent 42159 234ec7011e5d
child 42214 9ca13615c619
permissions -rw-r--r--
adapting Quickcheck_Narrowing (overseen in 234ec7011e5d); commenting out some examples temporarily
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@41905
     9
  val compile_generator_expr:
bulwahn@42184
    10
    Proof.context -> (term * term list) list -> int list -> term list option * Quickcheck.report option
bulwahn@41905
    11
  val put_counterexample: (unit -> term list option) -> Proof.context -> Proof.context
bulwahn@42023
    12
  val finite_functions : bool Config.T
bulwahn@41905
    13
  val setup: theory -> theory
bulwahn@41905
    14
end;
bulwahn@41905
    15
bulwahn@41930
    16
structure Narrowing_Generators : NARROWING_GENERATORS =
bulwahn@41905
    17
struct
bulwahn@41905
    18
bulwahn@42023
    19
(* configurations *)
bulwahn@42023
    20
bulwahn@42023
    21
val (finite_functions, setup_finite_functions) =
bulwahn@42023
    22
  Attrib.config_bool "quickcheck_finite_functions" (K true)
bulwahn@42023
    23
bulwahn@42023
    24
bulwahn@41963
    25
fun mk_undefined T = Const(@{const_name undefined}, T)
bulwahn@41963
    26
bulwahn@41963
    27
(* narrowing specific names and types *)
bulwahn@41963
    28
bulwahn@41963
    29
exception FUNCTION_TYPE;
bulwahn@41963
    30
bulwahn@41963
    31
val narrowingN = "narrowing";
bulwahn@41963
    32
bulwahn@41963
    33
fun narrowingT T =
bulwahn@41963
    34
  @{typ Quickcheck_Narrowing.code_int} --> Type (@{type_name Quickcheck_Narrowing.cons}, [T])
bulwahn@41963
    35
bulwahn@41963
    36
fun mk_empty T = Const (@{const_name Quickcheck_Narrowing.empty}, narrowingT T)
bulwahn@41963
    37
bulwahn@41963
    38
fun mk_cons c T = Const (@{const_name Quickcheck_Narrowing.cons}, T --> narrowingT T) $ Const (c, T)
bulwahn@41963
    39
bulwahn@41963
    40
fun mk_apply (T, t) (U, u) =
bulwahn@41963
    41
  let
bulwahn@41963
    42
    val (_, U') = dest_funT U
bulwahn@41963
    43
  in
bulwahn@41963
    44
    (U', Const (@{const_name Quickcheck_Narrowing.apply},
bulwahn@41963
    45
      narrowingT U --> narrowingT T --> narrowingT U') $ u $ t)
bulwahn@41963
    46
  end
bulwahn@41963
    47
  
bulwahn@41963
    48
fun mk_sum (t, u) =
bulwahn@41963
    49
  let
bulwahn@41963
    50
    val T = fastype_of t
bulwahn@41963
    51
  in
bulwahn@41963
    52
    Const (@{const_name Quickcheck_Narrowing.sum}, T --> T --> T) $ t $ u
bulwahn@41963
    53
  end
bulwahn@41963
    54
bulwahn@41963
    55
(* creating narrowing instances *)
bulwahn@41963
    56
bulwahn@41963
    57
fun mk_equations descr vs tycos narrowings (Ts, Us) =
bulwahn@41963
    58
  let
bulwahn@41963
    59
    fun mk_call T =
bulwahn@41963
    60
      let
bulwahn@41963
    61
        val narrowing =
bulwahn@41963
    62
          Const (@{const_name "Quickcheck_Narrowing.narrowing_class.narrowing"}, narrowingT T)
bulwahn@41963
    63
      in
bulwahn@41963
    64
        (T, narrowing)
bulwahn@41963
    65
      end
bulwahn@41963
    66
    fun mk_aux_call fTs (k, _) (tyco, Ts) =
bulwahn@41963
    67
      let
bulwahn@41963
    68
        val T = Type (tyco, Ts)
bulwahn@41963
    69
        val _ = if not (null fTs) then raise FUNCTION_TYPE else ()
bulwahn@41963
    70
      in
bulwahn@41963
    71
        (T, nth narrowings k)
bulwahn@41963
    72
      end
bulwahn@41963
    73
    fun mk_consexpr simpleT (c, xs) =
bulwahn@41963
    74
      let
bulwahn@41963
    75
        val Ts = map fst xs
bulwahn@41963
    76
      in snd (fold mk_apply xs (Ts ---> simpleT, mk_cons c (Ts ---> simpleT))) end
bulwahn@41963
    77
    fun mk_rhs exprs = foldr1 mk_sum exprs
bulwahn@41963
    78
    val rhss =
bulwahn@41963
    79
      Datatype_Aux.interpret_construction descr vs
bulwahn@41963
    80
        { atyp = mk_call, dtyp = mk_aux_call }
bulwahn@41963
    81
      |> (map o apfst) Type
bulwahn@41963
    82
      |> map (fn (T, cs) => map (mk_consexpr T) cs)
bulwahn@41963
    83
      |> map mk_rhs
bulwahn@41963
    84
    val lhss = narrowings
bulwahn@41963
    85
    val eqs = map (HOLogic.mk_Trueprop o HOLogic.mk_eq) (lhss ~~ rhss)
bulwahn@41963
    86
  in
bulwahn@41963
    87
    eqs
bulwahn@41963
    88
  end
bulwahn@41963
    89
bulwahn@41963
    90
bulwahn@41963
    91
fun instantiate_narrowing_datatype config descr vs tycos prfx (names, auxnames) (Ts, Us) thy =
bulwahn@41963
    92
  let
bulwahn@41963
    93
    val _ = Datatype_Aux.message config "Creating narrowing generators ...";
bulwahn@41963
    94
    val narrowingsN = map (prefix (narrowingN ^ "_")) (names @ auxnames);
bulwahn@41963
    95
  in
bulwahn@41963
    96
    thy
bulwahn@41963
    97
    |> Class.instantiation (tycos, vs, @{sort narrowing})
bulwahn@41963
    98
    |> (fold_map (fn (name, T) => Local_Theory.define
bulwahn@41963
    99
          ((Binding.conceal (Binding.name name), NoSyn),
bulwahn@41963
   100
            (apfst Binding.conceal Attrib.empty_binding, mk_undefined (narrowingT T)))
bulwahn@41963
   101
        #> apfst fst) (narrowingsN ~~ (Ts @ Us))
bulwahn@41963
   102
      #> (fn (narrowings, lthy) =>
bulwahn@41963
   103
        let
bulwahn@41963
   104
          val eqs_t = mk_equations descr vs tycos narrowings (Ts, Us)
bulwahn@41963
   105
          val eqs = map (fn eq => Goal.prove lthy ["f", "i"] [] eq
bulwahn@41963
   106
            (fn _ => Skip_Proof.cheat_tac (ProofContext.theory_of lthy))) eqs_t
bulwahn@41963
   107
        in
bulwahn@41963
   108
          fold (fn (name, eq) => Local_Theory.note
bulwahn@41963
   109
          ((Binding.conceal (Binding.qualify true prfx
bulwahn@41963
   110
             (Binding.qualify true name (Binding.name "simps"))),
bulwahn@41963
   111
             Code.add_default_eqn_attrib :: map (Attrib.internal o K)
bulwahn@41963
   112
               [Simplifier.simp_add, Nitpick_Simps.add]), [eq]) #> snd) (narrowingsN ~~ eqs) lthy
bulwahn@41963
   113
        end))
bulwahn@41963
   114
    |> Class.prove_instantiation_exit (K (Class.intro_classes_tac []))
bulwahn@41963
   115
  end;
bulwahn@41963
   116
bulwahn@41963
   117
(* testing framework *)
bulwahn@41963
   118
bulwahn@41930
   119
val target = "Haskell"
bulwahn@41930
   120
bulwahn@41905
   121
(* invocation of Haskell interpreter *)
bulwahn@41905
   122
bulwahn@41930
   123
val narrowing_engine = File.read (Path.explode "~~/src/HOL/Tools/Quickcheck/Narrowing_Engine.hs")
bulwahn@41905
   124
bulwahn@41905
   125
fun exec verbose code =
bulwahn@41905
   126
  ML_Context.exec (fn () => Secure.use_text ML_Env.local_context (0, "generated code") verbose code)
bulwahn@41905
   127
bulwahn@42019
   128
fun value ctxt (get, put, put_ml) (code, value) size =
bulwahn@41905
   129
  let
bulwahn@41930
   130
    val tmp_prefix = "Quickcheck_Narrowing"
bulwahn@41905
   131
    fun run in_path = 
bulwahn@41905
   132
      let
bulwahn@41905
   133
        val code_file = Path.append in_path (Path.basic "Code.hs")
bulwahn@41930
   134
        val narrowing_engine_file = Path.append in_path (Path.basic "Narrowing_Engine.hs")
bulwahn@41905
   135
        val main_file = Path.append in_path (Path.basic "Main.hs")
bulwahn@41905
   136
        val main = "module Main where {\n\n" ^
bulwahn@41933
   137
          "import Narrowing_Engine;\n" ^
bulwahn@41905
   138
          "import Code;\n\n" ^
bulwahn@42090
   139
          "main = Narrowing_Engine.depthCheck " ^ string_of_int size ^ " (Code.value ())\n\n" ^
bulwahn@41905
   140
          "}\n"
bulwahn@41909
   141
        val code' = prefix "module Code where {\n\ndata Typerep = Typerep String [Typerep];\n"
bulwahn@41909
   142
          (unprefix "module Code where {" code)
bulwahn@41909
   143
        val _ = File.write code_file code'
bulwahn@41930
   144
        val _ = File.write narrowing_engine_file narrowing_engine
bulwahn@41905
   145
        val _ = File.write main_file main
wenzelm@41946
   146
        val executable = File.shell_path (Path.append in_path (Path.basic "isa_lsc"))
wenzelm@42039
   147
        val cmd = "( exec \"$ISABELLE_GHC\" -fglasgow-exts " ^
wenzelm@41946
   148
          (space_implode " " (map File.shell_path [code_file, narrowing_engine_file, main_file])) ^
wenzelm@42039
   149
          " -o " ^ executable ^ "; ) && " ^ executable
bulwahn@41905
   150
      in
bulwahn@41905
   151
        bash_output cmd
bulwahn@41930
   152
      end
bulwahn@41909
   153
    val result = Isabelle_System.with_tmp_dir tmp_prefix run
bulwahn@41905
   154
    val output_value = the_default "NONE"
bulwahn@41905
   155
      (try (snd o split_last o filter_out (fn s => s = "") o split_lines o fst) result)
bulwahn@42020
   156
      |> translate_string (fn s => if s = "\\" then "\\\\" else s)
bulwahn@41905
   157
    val ml_code = "\nval _ = Context.set_thread_data (SOME (Context.map_proof (" ^ put_ml
bulwahn@41905
   158
      ^ " (fn () => " ^ output_value ^ ")) (ML_Context.the_generic_context ())))";
bulwahn@41905
   159
    val ctxt' = ctxt
bulwahn@41905
   160
      |> put (fn () => error ("Bad evaluation for " ^ quote put_ml))
bulwahn@41905
   161
      |> Context.proof_map (exec false ml_code);
bulwahn@41905
   162
  in get ctxt' () end;
bulwahn@41905
   163
bulwahn@42019
   164
fun evaluation cookie thy evaluator vs_t args size =
bulwahn@41905
   165
  let
bulwahn@41905
   166
    val ctxt = ProofContext.init_global thy;
bulwahn@41905
   167
    val (program_code, value_name) = evaluator vs_t;
bulwahn@41905
   168
    val value_code = space_implode " "
bulwahn@41905
   169
      (value_name :: "()" :: map (enclose "(" ")") args);
bulwahn@42019
   170
  in Exn.interruptible_capture (value ctxt cookie (program_code, value_code)) size end;
bulwahn@41905
   171
bulwahn@42019
   172
fun dynamic_value_strict cookie thy postproc t args size =
bulwahn@41905
   173
  let
bulwahn@41905
   174
    fun evaluator naming program ((_, vs_ty), t) deps =
bulwahn@42019
   175
      evaluation cookie thy (Code_Target.evaluator thy target naming program deps) (vs_ty, t) args size;
bulwahn@41905
   176
  in Exn.release (Code_Thingol.dynamic_value thy (Exn.map_result o postproc) evaluator t) end;
bulwahn@41905
   177
bulwahn@41905
   178
(* counterexample generator *)
bulwahn@41905
   179
  
bulwahn@41932
   180
structure Counterexample = Proof_Data
bulwahn@41905
   181
(
bulwahn@41905
   182
  type T = unit -> term list option
bulwahn@41936
   183
  fun init _ () = error "Counterexample"
bulwahn@41905
   184
)
bulwahn@41905
   185
bulwahn@42024
   186
val put_counterexample = Counterexample.put
bulwahn@42023
   187
bulwahn@42024
   188
fun finitize_functions t =
bulwahn@42024
   189
  let
bulwahn@42024
   190
    val ((names, Ts), t') = apfst split_list (strip_abs t)
bulwahn@42024
   191
    fun mk_eval_ffun dT rT =
bulwahn@42024
   192
      Const (@{const_name "Quickcheck_Narrowing.eval_ffun"}, 
bulwahn@42024
   193
        Type (@{type_name "Quickcheck_Narrowing.ffun"}, [dT, rT]) --> dT --> rT)
bulwahn@42024
   194
    fun mk_eval_cfun dT rT =
bulwahn@42024
   195
      Const (@{const_name "Quickcheck_Narrowing.eval_cfun"}, 
bulwahn@42024
   196
        Type (@{type_name "Quickcheck_Narrowing.cfun"}, [rT]) --> dT --> rT)
bulwahn@42024
   197
    fun eval_function (T as Type (@{type_name fun}, [dT, rT])) =
bulwahn@42024
   198
      let
bulwahn@42024
   199
        val (rt', rT') = eval_function rT
bulwahn@42024
   200
      in
bulwahn@42024
   201
        case dT of
bulwahn@42024
   202
          Type (@{type_name fun}, _) =>
bulwahn@42024
   203
            (fn t => absdummy (dT, rt' (mk_eval_cfun dT rT' $ incr_boundvars 1 t $ Bound 0)),
bulwahn@42024
   204
            Type (@{type_name "Quickcheck_Narrowing.cfun"}, [rT']))
bulwahn@42024
   205
        | _ => (fn t => absdummy (dT, rt' (mk_eval_ffun dT rT' $ incr_boundvars 1 t $ Bound 0)),
bulwahn@42024
   206
            Type (@{type_name "Quickcheck_Narrowing.ffun"}, [dT, rT']))
bulwahn@42024
   207
      end
bulwahn@42024
   208
      | eval_function T = (I, T)
bulwahn@42024
   209
    val (tt, Ts') = split_list (map eval_function Ts)
bulwahn@42024
   210
    val t'' = subst_bounds (map2 (fn f => fn x => f x) (rev tt) (map_index (Bound o fst) Ts), t')
bulwahn@42024
   211
  in
bulwahn@42024
   212
    list_abs (names ~~ Ts', t'')
bulwahn@42024
   213
  end
bulwahn@42023
   214
bulwahn@42184
   215
fun compile_generator_expr ctxt [(t, eval_terms)] [_, size] =
bulwahn@41905
   216
  let
bulwahn@41905
   217
    val thy = ProofContext.theory_of ctxt
bulwahn@42028
   218
    val t' = list_abs_free (Term.add_frees t [], t)
bulwahn@42028
   219
    val t'' = if Config.get ctxt finite_functions then finitize_functions t' else t'
bulwahn@41905
   220
    fun ensure_testable t =
bulwahn@41930
   221
      Const (@{const_name Quickcheck_Narrowing.ensure_testable}, fastype_of t --> fastype_of t) $ t
bulwahn@42023
   222
    val result = dynamic_value_strict
bulwahn@41932
   223
      (Counterexample.get, Counterexample.put, "Narrowing_Generators.put_counterexample")
bulwahn@42184
   224
      thy (Option.map o map) (ensure_testable t'') [] size
bulwahn@41905
   225
  in
bulwahn@42023
   226
    (result, NONE)
bulwahn@41905
   227
  end;
bulwahn@41905
   228
bulwahn@41905
   229
bulwahn@41905
   230
val setup =
bulwahn@41963
   231
  Datatype.interpretation
bulwahn@41963
   232
    (Quickcheck_Common.ensure_sort_datatype (@{sort narrowing}, instantiate_narrowing_datatype))
bulwahn@42023
   233
  #> setup_finite_functions
bulwahn@41963
   234
  #> Context.theory_map
bulwahn@41936
   235
    (Quickcheck.add_generator ("narrowing", compile_generator_expr))
bulwahn@41905
   236
    
bulwahn@41905
   237
end;