src/HOL/Tools/Predicate_Compile/predicate_compile_core.ML
author haftmann
Tue Oct 20 16:13:01 2009 +0200 (2009-10-20)
changeset 33037 b22e44496dc2
parent 33004 715566791eb0
child 33038 8f9594c31de4
permissions -rw-r--r--
replaced old_style infixes eq_set, subset, union, inter and variants by generic versions
bulwahn@32667
     1
(* Author: Lukas Bulwahn, TU Muenchen
bulwahn@32667
     2
bulwahn@32667
     3
(Prototype of) A compiler from predicates specified by intro/elim rules
bulwahn@32667
     4
to equations.
bulwahn@32667
     5
*)
bulwahn@32667
     6
bulwahn@32667
     7
signature PREDICATE_COMPILE_CORE =
bulwahn@32667
     8
sig
bulwahn@32668
     9
  val setup: theory -> theory
bulwahn@32668
    10
  val code_pred: bool -> string -> Proof.context -> Proof.state
bulwahn@32668
    11
  val code_pred_cmd: bool -> string -> Proof.context -> Proof.state
bulwahn@32667
    12
  type smode = (int * int list option) list
bulwahn@32667
    13
  type mode = smode option list * smode
bulwahn@32667
    14
  datatype tmode = Mode of mode * smode * tmode option list;
bulwahn@32667
    15
  (*val add_equations_of: bool -> string list -> theory -> theory *)
bulwahn@32667
    16
  val register_predicate : (thm list * thm * int) -> theory -> theory
bulwahn@32668
    17
  val register_intros : thm list -> theory -> theory
bulwahn@32667
    18
  val is_registered : theory -> string -> bool
bulwahn@32667
    19
 (* val fetch_pred_data : theory -> string -> (thm list * thm * int)  *)
bulwahn@32667
    20
  val predfun_intro_of: theory -> string -> mode -> thm
bulwahn@32667
    21
  val predfun_elim_of: theory -> string -> mode -> thm
bulwahn@32667
    22
  val strip_intro_concl: int -> term -> term * (term list * term list)
bulwahn@32667
    23
  val predfun_name_of: theory -> string -> mode -> string
bulwahn@32667
    24
  val all_preds_of : theory -> string list
bulwahn@32667
    25
  val modes_of: theory -> string -> mode list
bulwahn@32672
    26
  val sizelim_modes_of: theory -> string -> mode list
bulwahn@32672
    27
  val sizelim_function_name_of : theory -> string -> mode -> string
bulwahn@32672
    28
  val generator_modes_of: theory -> string -> mode list
bulwahn@32672
    29
  val generator_name_of : theory -> string -> mode -> string
bulwahn@32667
    30
  val string_of_mode : mode -> string
bulwahn@32667
    31
  val intros_of: theory -> string -> thm list
bulwahn@32667
    32
  val nparams_of: theory -> string -> int
bulwahn@32667
    33
  val add_intro: thm -> theory -> theory
bulwahn@32667
    34
  val set_elim: thm -> theory -> theory
bulwahn@32668
    35
  val set_nparams : string -> int -> theory -> theory
bulwahn@32667
    36
  val print_stored_rules: theory -> unit
bulwahn@32667
    37
  val print_all_modes: theory -> unit
wenzelm@32740
    38
  val do_proofs: bool Unsynchronized.ref
bulwahn@32667
    39
  val mk_casesrule : Proof.context -> int -> thm list -> term
bulwahn@32667
    40
  val analyze_compr: theory -> term -> term
wenzelm@32740
    41
  val eval_ref: (unit -> term Predicate.pred) option Unsynchronized.ref
bulwahn@32667
    42
  val add_equations : string list -> theory -> theory
bulwahn@32667
    43
  val code_pred_intros_attrib : attribute
bulwahn@32667
    44
  (* used by Quickcheck_Generator *) 
bulwahn@32667
    45
  (*val funT_of : mode -> typ -> typ
bulwahn@32667
    46
  val mk_if_pred : term -> term
bulwahn@32667
    47
  val mk_Eval : term * term -> term*)
bulwahn@32667
    48
  val mk_tupleT : typ list -> typ
bulwahn@32667
    49
(*  val mk_predT :  typ -> typ *)
bulwahn@32667
    50
  (* temporary for testing of the compilation *)
bulwahn@32667
    51
  datatype indprem = Prem of term list * term | Negprem of term list * term | Sidecond of term |
bulwahn@32667
    52
    GeneratorPrem of term list * term | Generator of (string * typ);
bulwahn@32667
    53
 (* val prepare_intrs: theory -> string list ->
bulwahn@32667
    54
    (string * typ) list * int * string list * string list * (string * mode list) list *
bulwahn@32667
    55
    (string * (term list * indprem list) list) list * (string * (int option list * int)) list*)
bulwahn@32667
    56
  datatype compilation_funs = CompilationFuns of {
bulwahn@32667
    57
    mk_predT : typ -> typ,
bulwahn@32667
    58
    dest_predT : typ -> typ,
bulwahn@32667
    59
    mk_bot : typ -> term,
bulwahn@32667
    60
    mk_single : term -> term,
bulwahn@32667
    61
    mk_bind : term * term -> term,
bulwahn@32667
    62
    mk_sup : term * term -> term,
bulwahn@32667
    63
    mk_if : term -> term,
bulwahn@32667
    64
    mk_not : term -> term,
bulwahn@32667
    65
    mk_map : typ -> typ -> term -> term -> term,
bulwahn@32667
    66
    lift_pred : term -> term
bulwahn@32667
    67
  };  
bulwahn@32667
    68
  type moded_clause = term list * (indprem * tmode) list
bulwahn@32667
    69
  type 'a pred_mode_table = (string * (mode * 'a) list) list
bulwahn@32667
    70
  val infer_modes : theory -> (string * mode list) list
bulwahn@32667
    71
    -> (string * mode list) list
bulwahn@32667
    72
    -> string list
bulwahn@32667
    73
    -> (string * (term list * indprem list) list) list
bulwahn@32667
    74
    -> (moded_clause list) pred_mode_table
bulwahn@32667
    75
  val infer_modes_with_generator : theory -> (string * mode list) list
bulwahn@32667
    76
    -> (string * mode list) list
bulwahn@32667
    77
    -> string list
bulwahn@32667
    78
    -> (string * (term list * indprem list) list) list
bulwahn@32667
    79
    -> (moded_clause list) pred_mode_table  
bulwahn@32667
    80
  (*val compile_preds : theory -> compilation_funs -> string list -> string list
bulwahn@32667
    81
    -> (string * typ) list -> (moded_clause list) pred_mode_table -> term pred_mode_table
bulwahn@32667
    82
  val rpred_create_definitions :(string * typ) list -> string * mode list
bulwahn@32667
    83
    -> theory -> theory 
bulwahn@32667
    84
  val split_smode : int list -> term list -> (term list * term list) *)
bulwahn@32667
    85
  val print_moded_clauses :
bulwahn@32667
    86
    theory -> (moded_clause list) pred_mode_table -> unit
bulwahn@32667
    87
  val print_compiled_terms : theory -> term pred_mode_table -> unit
bulwahn@32667
    88
  (*val rpred_prove_preds : theory -> term pred_mode_table -> thm pred_mode_table*)
bulwahn@32672
    89
  val pred_compfuns : compilation_funs
bulwahn@32667
    90
  val rpred_compfuns : compilation_funs
bulwahn@32667
    91
  val dest_funT : typ -> typ * typ
bulwahn@32667
    92
 (* val depending_preds_of : theory -> thm list -> string list *)
bulwahn@32667
    93
  val add_quickcheck_equations : string list -> theory -> theory
bulwahn@32667
    94
  val add_sizelim_equations : string list -> theory -> theory
bulwahn@32667
    95
  val is_inductive_predicate : theory -> string -> bool
bulwahn@32667
    96
  val terms_vs : term list -> string list
bulwahn@32667
    97
  val subsets : int -> int -> int list list
bulwahn@32667
    98
  val check_mode_clause : bool -> theory -> string list ->
bulwahn@32667
    99
    (string * mode list) list -> (string * mode list) list -> mode -> (term list * indprem list)
bulwahn@32667
   100
      -> (term list * (indprem * tmode) list) option
bulwahn@32667
   101
  val string_of_moded_prem : theory -> (indprem * tmode) -> string
bulwahn@32667
   102
  val all_modes_of : theory -> (string * mode list) list
bulwahn@32667
   103
  val all_generator_modes_of : theory -> (string * mode list) list
bulwahn@32667
   104
  val compile_clause : compilation_funs -> term option -> (term list -> term) ->
bulwahn@32667
   105
    theory -> string list -> string list -> mode -> term -> moded_clause -> term
bulwahn@32667
   106
  val preprocess_intro : theory -> thm -> thm
bulwahn@32667
   107
  val is_constrt : theory -> term -> bool
bulwahn@32667
   108
  val is_predT : typ -> bool
bulwahn@32667
   109
  val guess_nparams : typ -> int
bulwahn@32667
   110
  val cprods_subset : 'a list list -> 'a list list
bulwahn@32667
   111
end;
bulwahn@32667
   112
bulwahn@32667
   113
structure Predicate_Compile_Core : PREDICATE_COMPILE_CORE =
bulwahn@32667
   114
struct
bulwahn@32667
   115
bulwahn@32668
   116
open Predicate_Compile_Aux;
bulwahn@32667
   117
(** auxiliary **)
bulwahn@32667
   118
bulwahn@32667
   119
(* debug stuff *)
bulwahn@32667
   120
wenzelm@32950
   121
fun tracing s = (if ! Toplevel.debug then tracing s else ());
bulwahn@32667
   122
bulwahn@32667
   123
fun print_tac s = Seq.single; (*Tactical.print_tac s;*) (* (if ! Toplevel.debug then Tactical.print_tac s else Seq.single); *)
wenzelm@32950
   124
fun debug_tac msg = Seq.single; (* (fn st => (tracing msg; Seq.single st)); *)
bulwahn@32667
   125
wenzelm@32740
   126
val do_proofs = Unsynchronized.ref true;
bulwahn@32667
   127
bulwahn@32667
   128
(* reference to preprocessing of InductiveSet package *)
bulwahn@32667
   129
bulwahn@32672
   130
val ind_set_codegen_preproc = (fn thy => I) (*Inductive_Set.codegen_preproc;*)
bulwahn@32667
   131
bulwahn@32667
   132
(** fundamentals **)
bulwahn@32667
   133
bulwahn@32667
   134
(* syntactic operations *)
bulwahn@32667
   135
bulwahn@32667
   136
fun mk_eq (x, xs) =
bulwahn@32667
   137
  let fun mk_eqs _ [] = []
bulwahn@32667
   138
        | mk_eqs a (b::cs) =
bulwahn@32667
   139
            HOLogic.mk_eq (Free (a, fastype_of b), b) :: mk_eqs a cs
bulwahn@32667
   140
  in mk_eqs x xs end;
bulwahn@32667
   141
bulwahn@32667
   142
fun mk_tupleT [] = HOLogic.unitT
bulwahn@32667
   143
  | mk_tupleT Ts = foldr1 HOLogic.mk_prodT Ts;
bulwahn@32667
   144
bulwahn@32667
   145
fun dest_tupleT (Type (@{type_name Product_Type.unit}, [])) = []
bulwahn@32667
   146
  | dest_tupleT (Type (@{type_name "*"}, [T1, T2])) = T1 :: (dest_tupleT T2)
bulwahn@32667
   147
  | dest_tupleT t = [t]
bulwahn@32667
   148
bulwahn@32667
   149
fun mk_tuple [] = HOLogic.unit
bulwahn@32667
   150
  | mk_tuple ts = foldr1 HOLogic.mk_prod ts;
bulwahn@32667
   151
bulwahn@32667
   152
fun dest_tuple (Const (@{const_name Product_Type.Unity}, _)) = []
bulwahn@32667
   153
  | dest_tuple (Const (@{const_name Pair}, _) $ t1 $ t2) = t1 :: (dest_tuple t2)
bulwahn@32667
   154
  | dest_tuple t = [t]
bulwahn@32667
   155
bulwahn@32667
   156
fun mk_scomp (t, u) =
bulwahn@32667
   157
  let
bulwahn@32667
   158
    val T = fastype_of t
bulwahn@32667
   159
    val U = fastype_of u
bulwahn@32667
   160
    val [A] = binder_types T
bulwahn@32667
   161
    val D = body_type U 
bulwahn@32667
   162
  in 
bulwahn@32667
   163
    Const (@{const_name "scomp"}, T --> U --> A --> D) $ t $ u
bulwahn@32667
   164
  end;
bulwahn@32667
   165
bulwahn@32667
   166
fun dest_funT (Type ("fun",[S, T])) = (S, T)
bulwahn@32667
   167
  | dest_funT T = raise TYPE ("dest_funT", [T], [])
bulwahn@32667
   168
 
bulwahn@32667
   169
fun mk_fun_comp (t, u) =
bulwahn@32667
   170
  let
bulwahn@32667
   171
    val (_, B) = dest_funT (fastype_of t)
bulwahn@32667
   172
    val (C, A) = dest_funT (fastype_of u)
bulwahn@32667
   173
  in
bulwahn@32667
   174
    Const(@{const_name "Fun.comp"}, (A --> B) --> (C --> A) --> C --> B) $ t $ u
bulwahn@32667
   175
  end;
bulwahn@32667
   176
bulwahn@32667
   177
fun dest_randomT (Type ("fun", [@{typ Random.seed},
bulwahn@32674
   178
  Type ("*", [Type ("*", [T, @{typ "unit => Code_Evaluation.term"}]) ,@{typ Random.seed}])])) = T
bulwahn@32667
   179
  | dest_randomT T = raise TYPE ("dest_randomT", [T], [])
bulwahn@32667
   180
bulwahn@32667
   181
(* destruction of intro rules *)
bulwahn@32667
   182
bulwahn@32667
   183
(* FIXME: look for other place where this functionality was used before *)
bulwahn@32667
   184
fun strip_intro_concl nparams intro = let
bulwahn@32667
   185
  val _ $ u = Logic.strip_imp_concl intro
bulwahn@32667
   186
  val (pred, all_args) = strip_comb u
bulwahn@32667
   187
  val (params, args) = chop nparams all_args
bulwahn@32667
   188
in (pred, (params, args)) end
bulwahn@32667
   189
bulwahn@32667
   190
(** data structures **)
bulwahn@32667
   191
bulwahn@32668
   192
type smode = (int * int list option) list
bulwahn@32667
   193
type mode = smode option list * smode;
bulwahn@32667
   194
datatype tmode = Mode of mode * smode * tmode option list;
bulwahn@32667
   195
bulwahn@32667
   196
fun gen_split_smode (mk_tuple, strip_tuple) smode ts =
bulwahn@32667
   197
  let
bulwahn@32667
   198
    fun split_tuple' _ _ [] = ([], [])
bulwahn@32667
   199
    | split_tuple' is i (t::ts) =
bulwahn@32667
   200
      (if i mem is then apfst else apsnd) (cons t)
bulwahn@32667
   201
        (split_tuple' is (i+1) ts)
bulwahn@32667
   202
    fun split_tuple is t = split_tuple' is 1 (strip_tuple t)
bulwahn@32667
   203
    fun split_smode' _ _ [] = ([], [])
bulwahn@32667
   204
      | split_smode' smode i (t::ts) =
bulwahn@32667
   205
        (if i mem (map fst smode) then
bulwahn@32667
   206
          case (the (AList.lookup (op =) smode i)) of
bulwahn@32667
   207
            NONE => apfst (cons t)
bulwahn@32667
   208
            | SOME is =>
bulwahn@32667
   209
              let
bulwahn@32667
   210
                val (ts1, ts2) = split_tuple is t
bulwahn@32667
   211
                fun cons_tuple ts = if null ts then I else cons (mk_tuple ts)
bulwahn@32667
   212
                in (apfst (cons_tuple ts1)) o (apsnd (cons_tuple ts2)) end
bulwahn@32667
   213
          else apsnd (cons t))
bulwahn@32667
   214
        (split_smode' smode (i+1) ts)
bulwahn@32667
   215
  in split_smode' smode 1 ts end
bulwahn@32667
   216
bulwahn@32667
   217
val split_smode = gen_split_smode (HOLogic.mk_tuple, HOLogic.strip_tuple)   
bulwahn@32667
   218
val split_smodeT = gen_split_smode (HOLogic.mk_tupleT, HOLogic.strip_tupleT)
bulwahn@32667
   219
bulwahn@32667
   220
fun gen_split_mode split_smode (iss, is) ts =
bulwahn@32667
   221
  let
bulwahn@32667
   222
    val (t1, t2) = chop (length iss) ts 
bulwahn@32667
   223
  in (t1, split_smode is t2) end
bulwahn@32667
   224
bulwahn@32667
   225
val split_mode = gen_split_mode split_smode
bulwahn@32667
   226
val split_modeT = gen_split_mode split_smodeT
bulwahn@32667
   227
bulwahn@32667
   228
fun string_of_smode js =
bulwahn@32667
   229
    commas (map
bulwahn@32667
   230
      (fn (i, is) =>
bulwahn@32667
   231
        string_of_int i ^ (case is of NONE => ""
bulwahn@32667
   232
    | SOME is => "p" ^ enclose "[" "]" (commas (map string_of_int is)))) js)
bulwahn@32667
   233
bulwahn@32667
   234
fun string_of_mode (iss, is) = space_implode " -> " (map
bulwahn@32667
   235
  (fn NONE => "X"
bulwahn@32667
   236
    | SOME js => enclose "[" "]" (string_of_smode js))
bulwahn@32667
   237
       (iss @ [SOME is]));
bulwahn@32667
   238
bulwahn@32667
   239
fun string_of_tmode (Mode (predmode, termmode, param_modes)) =
bulwahn@32667
   240
  "predmode: " ^ (string_of_mode predmode) ^ 
bulwahn@32667
   241
  (if null param_modes then "" else
bulwahn@32667
   242
    "; " ^ "params: " ^ commas (map (the_default "NONE" o Option.map string_of_tmode) param_modes))
bulwahn@32668
   243
bulwahn@32668
   244
(* generation of case rules from user-given introduction rules *)
bulwahn@32668
   245
bulwahn@32668
   246
fun mk_casesrule ctxt nparams introrules =
bulwahn@32668
   247
  let
bulwahn@32672
   248
    val ((_, intros_th), ctxt1) = Variable.import false introrules ctxt
bulwahn@32672
   249
    val intros = map prop_of intros_th
bulwahn@32668
   250
    val (pred, (params, args)) = strip_intro_concl nparams (hd intros)
bulwahn@32672
   251
    val ([propname], ctxt2) = Variable.variant_fixes ["thesis"] ctxt1
bulwahn@32668
   252
    val prop = HOLogic.mk_Trueprop (Free (propname, HOLogic.boolT))
bulwahn@32672
   253
    val (argnames, ctxt3) = Variable.variant_fixes
bulwahn@32672
   254
      (map (fn i => "a" ^ string_of_int i) (1 upto (length args))) ctxt2
bulwahn@32668
   255
    val argvs = map2 (curry Free) argnames (map fastype_of args)
bulwahn@32668
   256
    fun mk_case intro =
bulwahn@32668
   257
      let
bulwahn@32668
   258
        val (_, (_, args)) = strip_intro_concl nparams intro
bulwahn@32668
   259
        val prems = Logic.strip_imp_prems intro
bulwahn@32668
   260
        val eqprems = map (HOLogic.mk_Trueprop o HOLogic.mk_eq) (argvs ~~ args)
bulwahn@32668
   261
        val frees = (fold o fold_aterms)
bulwahn@32668
   262
          (fn t as Free _ =>
bulwahn@32668
   263
              if member (op aconv) params t then I else insert (op aconv) t
bulwahn@32668
   264
           | _ => I) (args @ prems) []
bulwahn@32668
   265
      in fold Logic.all frees (Logic.list_implies (eqprems @ prems, prop)) end
bulwahn@32668
   266
    val assm = HOLogic.mk_Trueprop (list_comb (pred, params @ argvs))
bulwahn@32668
   267
    val cases = map mk_case intros
bulwahn@32668
   268
  in Logic.list_implies (assm :: cases, prop) end;
bulwahn@32667
   269
    
bulwahn@32668
   270
bulwahn@32667
   271
datatype indprem = Prem of term list * term | Negprem of term list * term | Sidecond of term |
bulwahn@32667
   272
  GeneratorPrem of term list * term | Generator of (string * typ);
bulwahn@32667
   273
bulwahn@32667
   274
type moded_clause = term list * (indprem * tmode) list
bulwahn@32667
   275
type 'a pred_mode_table = (string * (mode * 'a) list) list
bulwahn@32667
   276
bulwahn@32667
   277
datatype predfun_data = PredfunData of {
bulwahn@32667
   278
  name : string,
bulwahn@32667
   279
  definition : thm,
bulwahn@32667
   280
  intro : thm,
bulwahn@32667
   281
  elim : thm
bulwahn@32667
   282
};
bulwahn@32667
   283
bulwahn@32667
   284
fun rep_predfun_data (PredfunData data) = data;
bulwahn@32667
   285
fun mk_predfun_data (name, definition, intro, elim) =
bulwahn@32667
   286
  PredfunData {name = name, definition = definition, intro = intro, elim = elim}
bulwahn@32667
   287
bulwahn@32667
   288
datatype function_data = FunctionData of {
bulwahn@32667
   289
  name : string,
bulwahn@32667
   290
  equation : thm option (* is not used at all? *)
bulwahn@32667
   291
};
bulwahn@32667
   292
bulwahn@32667
   293
fun rep_function_data (FunctionData data) = data;
bulwahn@32667
   294
fun mk_function_data (name, equation) =
bulwahn@32667
   295
  FunctionData {name = name, equation = equation}
bulwahn@32667
   296
bulwahn@32667
   297
datatype pred_data = PredData of {
bulwahn@32667
   298
  intros : thm list,
bulwahn@32667
   299
  elim : thm option,
bulwahn@32667
   300
  nparams : int,
bulwahn@32667
   301
  functions : (mode * predfun_data) list,
bulwahn@32667
   302
  generators : (mode * function_data) list,
bulwahn@32667
   303
  sizelim_functions : (mode * function_data) list 
bulwahn@32667
   304
};
bulwahn@32667
   305
bulwahn@32667
   306
fun rep_pred_data (PredData data) = data;
bulwahn@32667
   307
fun mk_pred_data ((intros, elim, nparams), (functions, generators, sizelim_functions)) =
bulwahn@32667
   308
  PredData {intros = intros, elim = elim, nparams = nparams,
bulwahn@32667
   309
    functions = functions, generators = generators, sizelim_functions = sizelim_functions}
bulwahn@32667
   310
fun map_pred_data f (PredData {intros, elim, nparams, functions, generators, sizelim_functions}) =
bulwahn@32667
   311
  mk_pred_data (f ((intros, elim, nparams), (functions, generators, sizelim_functions)))
bulwahn@32667
   312
  
bulwahn@32667
   313
fun eq_option eq (NONE, NONE) = true
bulwahn@32667
   314
  | eq_option eq (SOME x, SOME y) = eq (x, y)
bulwahn@32667
   315
  | eq_option eq _ = false
bulwahn@32667
   316
  
bulwahn@32667
   317
fun eq_pred_data (PredData d1, PredData d2) = 
bulwahn@32667
   318
  eq_list (Thm.eq_thm) (#intros d1, #intros d2) andalso
bulwahn@32667
   319
  eq_option (Thm.eq_thm) (#elim d1, #elim d2) andalso
bulwahn@32667
   320
  #nparams d1 = #nparams d2
bulwahn@32667
   321
  
bulwahn@32667
   322
structure PredData = TheoryDataFun
bulwahn@32667
   323
(
bulwahn@32667
   324
  type T = pred_data Graph.T;
bulwahn@32667
   325
  val empty = Graph.empty;
bulwahn@32667
   326
  val copy = I;
bulwahn@32667
   327
  val extend = I;
bulwahn@32667
   328
  fun merge _ = Graph.merge eq_pred_data;
bulwahn@32667
   329
);
bulwahn@32667
   330
bulwahn@32667
   331
(* queries *)
bulwahn@32667
   332
bulwahn@32667
   333
fun lookup_pred_data thy name =
bulwahn@32667
   334
  Option.map rep_pred_data (try (Graph.get_node (PredData.get thy)) name)
bulwahn@32667
   335
bulwahn@32667
   336
fun the_pred_data thy name = case lookup_pred_data thy name
bulwahn@32667
   337
 of NONE => error ("No such predicate " ^ quote name)  
bulwahn@32667
   338
  | SOME data => data;
bulwahn@32667
   339
bulwahn@32667
   340
val is_registered = is_some oo lookup_pred_data 
bulwahn@32667
   341
bulwahn@32667
   342
val all_preds_of = Graph.keys o PredData.get
bulwahn@32667
   343
bulwahn@32667
   344
fun intros_of thy = map (Thm.transfer thy) o #intros o the_pred_data thy
bulwahn@32667
   345
bulwahn@32667
   346
fun the_elim_of thy name = case #elim (the_pred_data thy name)
bulwahn@32667
   347
 of NONE => error ("No elimination rule for predicate " ^ quote name)
bulwahn@32667
   348
  | SOME thm => Thm.transfer thy thm 
bulwahn@32667
   349
  
bulwahn@32667
   350
val has_elim = is_some o #elim oo the_pred_data;
bulwahn@32667
   351
bulwahn@32667
   352
val nparams_of = #nparams oo the_pred_data
bulwahn@32667
   353
bulwahn@32667
   354
val modes_of = (map fst) o #functions oo the_pred_data
bulwahn@32667
   355
bulwahn@32672
   356
val sizelim_modes_of = (map fst) o #sizelim_functions oo the_pred_data
bulwahn@32672
   357
bulwahn@32672
   358
val rpred_modes_of = (map fst) o #generators oo the_pred_data
bulwahn@32672
   359
  
bulwahn@32667
   360
fun all_modes_of thy = map (fn name => (name, modes_of thy name)) (all_preds_of thy) 
bulwahn@32667
   361
bulwahn@32667
   362
val is_compiled = not o null o #functions oo the_pred_data
bulwahn@32667
   363
bulwahn@32667
   364
fun lookup_predfun_data thy name mode =
bulwahn@32667
   365
  Option.map rep_predfun_data (AList.lookup (op =)
bulwahn@32667
   366
  (#functions (the_pred_data thy name)) mode)
bulwahn@32667
   367
bulwahn@32667
   368
fun the_predfun_data thy name mode = case lookup_predfun_data thy name mode
bulwahn@32667
   369
  of NONE => error ("No function defined for mode " ^ string_of_mode mode ^ " of predicate " ^ name)
bulwahn@32667
   370
   | SOME data => data;
bulwahn@32667
   371
bulwahn@32667
   372
val predfun_name_of = #name ooo the_predfun_data
bulwahn@32667
   373
bulwahn@32667
   374
val predfun_definition_of = #definition ooo the_predfun_data
bulwahn@32667
   375
bulwahn@32667
   376
val predfun_intro_of = #intro ooo the_predfun_data
bulwahn@32667
   377
bulwahn@32667
   378
val predfun_elim_of = #elim ooo the_predfun_data
bulwahn@32667
   379
bulwahn@32667
   380
fun lookup_generator_data thy name mode = 
bulwahn@32667
   381
  Option.map rep_function_data (AList.lookup (op =)
bulwahn@32667
   382
  (#generators (the_pred_data thy name)) mode)
bulwahn@32667
   383
  
bulwahn@32667
   384
fun the_generator_data thy name mode = case lookup_generator_data thy name mode
bulwahn@32667
   385
  of NONE => error ("No generator defined for mode " ^ string_of_mode mode ^ " of predicate " ^ name)
bulwahn@32667
   386
   | SOME data => data
bulwahn@32667
   387
bulwahn@32667
   388
val generator_name_of = #name ooo the_generator_data
bulwahn@32667
   389
bulwahn@32667
   390
val generator_modes_of = (map fst) o #generators oo the_pred_data
bulwahn@32667
   391
bulwahn@32667
   392
fun all_generator_modes_of thy =
bulwahn@32667
   393
  map (fn name => (name, generator_modes_of thy name)) (all_preds_of thy) 
bulwahn@32667
   394
bulwahn@32667
   395
fun lookup_sizelim_function_data thy name mode =
bulwahn@32667
   396
  Option.map rep_function_data (AList.lookup (op =)
bulwahn@32667
   397
  (#sizelim_functions (the_pred_data thy name)) mode)
bulwahn@32667
   398
bulwahn@32667
   399
fun the_sizelim_function_data thy name mode = case lookup_sizelim_function_data thy name mode
bulwahn@32667
   400
  of NONE => error ("No size-limited function defined for mode " ^ string_of_mode mode
bulwahn@32667
   401
    ^ " of predicate " ^ name)
bulwahn@32667
   402
   | SOME data => data
bulwahn@32667
   403
bulwahn@32667
   404
val sizelim_function_name_of = #name ooo the_sizelim_function_data
bulwahn@32667
   405
bulwahn@32667
   406
(*val generator_modes_of = (map fst) o #generators oo the_pred_data*)
bulwahn@32667
   407
     
bulwahn@32667
   408
(* diagnostic display functions *)
bulwahn@32667
   409
wenzelm@32950
   410
fun print_modes modes = tracing ("Inferred modes:\n" ^
bulwahn@32667
   411
  cat_lines (map (fn (s, ms) => s ^ ": " ^ commas (map
bulwahn@32667
   412
    string_of_mode ms)) modes));
bulwahn@32667
   413
bulwahn@32667
   414
fun print_pred_mode_table string_of_entry thy pred_mode_table =
bulwahn@32667
   415
  let
bulwahn@32667
   416
    fun print_mode pred (mode, entry) =  "mode : " ^ (string_of_mode mode)
bulwahn@32667
   417
      ^ (string_of_entry pred mode entry)  
bulwahn@32667
   418
    fun print_pred (pred, modes) =
bulwahn@32667
   419
      "predicate " ^ pred ^ ": " ^ cat_lines (map (print_mode pred) modes)
wenzelm@32950
   420
    val _ = tracing (cat_lines (map print_pred pred_mode_table))
bulwahn@32667
   421
  in () end;
bulwahn@32667
   422
bulwahn@32667
   423
fun string_of_moded_prem thy (Prem (ts, p), tmode) =
bulwahn@32667
   424
    (Syntax.string_of_term_global thy (list_comb (p, ts))) ^
bulwahn@32667
   425
    "(" ^ (string_of_tmode tmode) ^ ")"
bulwahn@32667
   426
  | string_of_moded_prem thy (GeneratorPrem (ts, p), Mode (predmode, is, _)) =
bulwahn@32667
   427
    (Syntax.string_of_term_global thy (list_comb (p, ts))) ^
bulwahn@32667
   428
    "(generator_mode: " ^ (string_of_mode predmode) ^ ")"
bulwahn@32667
   429
  | string_of_moded_prem thy (Generator (v, T), _) =
bulwahn@32667
   430
    "Generator for " ^ v ^ " of Type " ^ (Syntax.string_of_typ_global thy T)
bulwahn@32667
   431
  | string_of_moded_prem thy (Negprem (ts, p), Mode (_, is, _)) =
bulwahn@32667
   432
    (Syntax.string_of_term_global thy (list_comb (p, ts))) ^
bulwahn@32667
   433
    "(negative mode: " ^ string_of_smode is ^ ")"
bulwahn@32667
   434
  | string_of_moded_prem thy (Sidecond t, Mode (_, is, _)) =
bulwahn@32667
   435
    (Syntax.string_of_term_global thy t) ^
bulwahn@32667
   436
    "(sidecond mode: " ^ string_of_smode is ^ ")"    
bulwahn@32667
   437
  | string_of_moded_prem _ _ = error "string_of_moded_prem: unimplemented"
bulwahn@32667
   438
     
bulwahn@32667
   439
fun print_moded_clauses thy =
bulwahn@32667
   440
  let        
bulwahn@32667
   441
    fun string_of_clause pred mode clauses =
bulwahn@32667
   442
      cat_lines (map (fn (ts, prems) => (space_implode " --> "
bulwahn@32667
   443
        (map (string_of_moded_prem thy) prems)) ^ " --> " ^ pred ^ " "
bulwahn@32667
   444
        ^ (space_implode " " (map (Syntax.string_of_term_global thy) ts))) clauses)
bulwahn@32667
   445
  in print_pred_mode_table string_of_clause thy end;
bulwahn@32667
   446
bulwahn@32667
   447
fun print_compiled_terms thy =
bulwahn@32667
   448
  print_pred_mode_table (fn _ => fn _ => Syntax.string_of_term_global thy) thy
bulwahn@32667
   449
    
bulwahn@32667
   450
fun print_stored_rules thy =
bulwahn@32667
   451
  let
bulwahn@32667
   452
    val preds = (Graph.keys o PredData.get) thy
bulwahn@32667
   453
    fun print pred () = let
bulwahn@32667
   454
      val _ = writeln ("predicate: " ^ pred)
bulwahn@32667
   455
      val _ = writeln ("number of parameters: " ^ string_of_int (nparams_of thy pred))
bulwahn@32667
   456
      val _ = writeln ("introrules: ")
bulwahn@32667
   457
      val _ = fold (fn thm => fn u => writeln (Display.string_of_thm_global thy thm))
bulwahn@32667
   458
        (rev (intros_of thy pred)) ()
bulwahn@32667
   459
    in
bulwahn@32667
   460
      if (has_elim thy pred) then
bulwahn@32667
   461
        writeln ("elimrule: " ^ Display.string_of_thm_global thy (the_elim_of thy pred))
bulwahn@32667
   462
      else
bulwahn@32667
   463
        writeln ("no elimrule defined")
bulwahn@32667
   464
    end
bulwahn@32667
   465
  in
bulwahn@32667
   466
    fold print preds ()
bulwahn@32667
   467
  end;
bulwahn@32667
   468
bulwahn@32667
   469
fun print_all_modes thy =
bulwahn@32667
   470
  let
bulwahn@32667
   471
    val _ = writeln ("Inferred modes:")
bulwahn@32667
   472
    fun print (pred, modes) u =
bulwahn@32667
   473
      let
bulwahn@32667
   474
        val _ = writeln ("predicate: " ^ pred)
bulwahn@32667
   475
        val _ = writeln ("modes: " ^ (commas (map string_of_mode modes)))
bulwahn@32667
   476
      in u end  
bulwahn@32667
   477
  in
bulwahn@32667
   478
    fold print (all_modes_of thy) ()
bulwahn@32667
   479
  end
bulwahn@32667
   480
  
bulwahn@32667
   481
(** preprocessing rules **)  
bulwahn@32667
   482
bulwahn@32667
   483
fun imp_prems_conv cv ct =
bulwahn@32667
   484
  case Thm.term_of ct of
bulwahn@32667
   485
    Const ("==>", _) $ _ $ _ => Conv.combination_conv (Conv.arg_conv cv) (imp_prems_conv cv) ct
bulwahn@32667
   486
  | _ => Conv.all_conv ct
bulwahn@32667
   487
bulwahn@32667
   488
fun Trueprop_conv cv ct =
bulwahn@32667
   489
  case Thm.term_of ct of
bulwahn@32667
   490
    Const ("Trueprop", _) $ _ => Conv.arg_conv cv ct  
bulwahn@32667
   491
  | _ => error "Trueprop_conv"
bulwahn@32667
   492
bulwahn@32667
   493
fun preprocess_intro thy rule =
bulwahn@32667
   494
  Conv.fconv_rule
bulwahn@32667
   495
    (imp_prems_conv
bulwahn@32667
   496
      (Trueprop_conv (Conv.try_conv (Conv.rewr_conv (Thm.symmetric @{thm Predicate.eq_is_eq})))))
bulwahn@32667
   497
    (Thm.transfer thy rule)
bulwahn@32667
   498
bulwahn@32667
   499
fun preprocess_elim thy nparams elimrule =
bulwahn@32667
   500
  let
wenzelm@32950
   501
    val _ = tracing ("Preprocessing elimination rule "
bulwahn@32667
   502
      ^ (Display.string_of_thm_global thy elimrule))
bulwahn@32667
   503
    fun replace_eqs (Const ("Trueprop", _) $ (Const ("op =", T) $ lhs $ rhs)) =
bulwahn@32667
   504
       HOLogic.mk_Trueprop (Const (@{const_name Predicate.eq}, T) $ lhs $ rhs)
bulwahn@32667
   505
     | replace_eqs t = t
bulwahn@32667
   506
    val prems = Thm.prems_of elimrule
bulwahn@32667
   507
    val nargs = length (snd (strip_comb (HOLogic.dest_Trueprop (hd prems)))) - nparams
bulwahn@32667
   508
    fun preprocess_case t =
bulwahn@32667
   509
     let
bulwahn@32667
   510
       val params = Logic.strip_params t
bulwahn@32667
   511
       val (assums1, assums2) = chop nargs (Logic.strip_assums_hyp t)
bulwahn@32667
   512
       val assums_hyp' = assums1 @ (map replace_eqs assums2)
bulwahn@32667
   513
     in
bulwahn@32667
   514
       list_all (params, Logic.list_implies (assums_hyp', Logic.strip_assums_concl t))
bulwahn@32667
   515
     end
bulwahn@32667
   516
    val cases' = map preprocess_case (tl prems)
bulwahn@32667
   517
    val elimrule' = Logic.list_implies ((hd prems) :: cases', Thm.concl_of elimrule)
wenzelm@32950
   518
    (*val _ =  tracing ("elimrule': "^ (Syntax.string_of_term_global thy elimrule'))*)
bulwahn@32667
   519
    val bigeq = (Thm.symmetric (Conv.implies_concl_conv
bulwahn@32667
   520
      (MetaSimplifier.rewrite true [@{thm Predicate.eq_is_eq}])
bulwahn@32667
   521
        (cterm_of thy elimrule')))
bulwahn@32667
   522
    (*
wenzelm@32950
   523
    val _ = tracing ("bigeq:" ^ (Display.string_of_thm_global thy bigeq))   
bulwahn@32667
   524
    val res = 
bulwahn@32667
   525
    Thm.equal_elim bigeq elimrule
bulwahn@32667
   526
    *)
bulwahn@32667
   527
    (*
bulwahn@32667
   528
    val t = (fn {...} => mycheat_tac thy 1)
bulwahn@32667
   529
    val eq = Goal.prove (ProofContext.init thy) [] [] (Logic.mk_equals ((Thm.prop_of elimrule), elimrule')) t
bulwahn@32667
   530
    *)
wenzelm@32950
   531
    val _ = tracing "Preprocessed elimination rule"
bulwahn@32667
   532
  in
bulwahn@32667
   533
    Thm.equal_elim bigeq elimrule
bulwahn@32667
   534
  end;
bulwahn@32667
   535
bulwahn@32667
   536
(* special case: predicate with no introduction rule *)
bulwahn@32667
   537
fun noclause thy predname elim = let
bulwahn@32667
   538
  val T = (Logic.unvarifyT o Sign.the_const_type thy) predname
bulwahn@32667
   539
  val Ts = binder_types T
bulwahn@32667
   540
  val names = Name.variant_list []
bulwahn@32667
   541
        (map (fn i => "x" ^ (string_of_int i)) (1 upto (length Ts)))
bulwahn@32667
   542
  val vs = map2 (curry Free) names Ts
bulwahn@32667
   543
  val clausehd = HOLogic.mk_Trueprop (list_comb (Const (predname, T), vs))
bulwahn@32667
   544
  val intro_t = Logic.mk_implies (@{prop False}, clausehd)
bulwahn@32667
   545
  val P = HOLogic.mk_Trueprop (Free ("P", HOLogic.boolT))
bulwahn@32667
   546
  val elim_t = Logic.list_implies ([clausehd, Logic.mk_implies (@{prop False}, P)], P)
bulwahn@32667
   547
  val intro = Goal.prove (ProofContext.init thy) names [] intro_t
bulwahn@32667
   548
        (fn {...} => etac @{thm FalseE} 1)
bulwahn@32667
   549
  val elim = Goal.prove (ProofContext.init thy) ("P" :: names) [] elim_t
bulwahn@32667
   550
        (fn {...} => etac elim 1) 
bulwahn@32667
   551
in
bulwahn@32667
   552
  ([intro], elim)
bulwahn@32667
   553
end
bulwahn@32667
   554
bulwahn@32667
   555
fun fetch_pred_data thy name =
bulwahn@32667
   556
  case try (Inductive.the_inductive (ProofContext.init thy)) name of
bulwahn@32667
   557
    SOME (info as (_, result)) => 
bulwahn@32667
   558
      let
bulwahn@32667
   559
        fun is_intro_of intro =
bulwahn@32667
   560
          let
bulwahn@32667
   561
            val (const, _) = strip_comb (HOLogic.dest_Trueprop (concl_of intro))
bulwahn@32667
   562
          in (fst (dest_Const const) = name) end;      
bulwahn@32667
   563
        val intros = ind_set_codegen_preproc thy ((map (preprocess_intro thy))
bulwahn@32667
   564
          (filter is_intro_of (#intrs result)))
bulwahn@32667
   565
        val pre_elim = nth (#elims result) (find_index (fn s => s = name) (#names (fst info)))
bulwahn@32667
   566
        val nparams = length (Inductive.params_of (#raw_induct result))
bulwahn@32667
   567
        val elim = singleton (ind_set_codegen_preproc thy) (preprocess_elim thy nparams pre_elim)
bulwahn@32667
   568
        val (intros, elim) = if null intros then noclause thy name elim else (intros, elim)
bulwahn@32667
   569
      in
bulwahn@32667
   570
        mk_pred_data ((intros, SOME elim, nparams), ([], [], []))
bulwahn@32667
   571
      end                                                                    
bulwahn@32667
   572
  | NONE => error ("No such predicate: " ^ quote name)
bulwahn@32667
   573
  
bulwahn@32667
   574
(* updaters *)
bulwahn@32667
   575
bulwahn@32667
   576
fun apfst3 f (x, y, z) =  (f x, y, z)
bulwahn@32667
   577
fun apsnd3 f (x, y, z) =  (x, f y, z)
bulwahn@32667
   578
fun aptrd3 f (x, y, z) =  (x, y, f z)
bulwahn@32667
   579
bulwahn@32667
   580
fun add_predfun name mode data =
bulwahn@32667
   581
  let
bulwahn@32667
   582
    val add = (apsnd o apfst3 o cons) (mode, mk_predfun_data data)
bulwahn@32667
   583
  in PredData.map (Graph.map_node name (map_pred_data add)) end
bulwahn@32667
   584
bulwahn@32667
   585
fun is_inductive_predicate thy name =
bulwahn@32667
   586
  is_some (try (Inductive.the_inductive (ProofContext.init thy)) name)
bulwahn@32667
   587
bulwahn@32667
   588
fun depending_preds_of thy (key, value) =
bulwahn@32667
   589
  let
bulwahn@32667
   590
    val intros = (#intros o rep_pred_data) value
bulwahn@32667
   591
  in
bulwahn@32667
   592
    fold Term.add_const_names (map Thm.prop_of intros) []
bulwahn@32667
   593
      |> filter (fn c => (not (c = key)) andalso (is_inductive_predicate thy c orelse is_registered thy c))
bulwahn@32667
   594
  end;
bulwahn@32667
   595
bulwahn@32667
   596
bulwahn@32667
   597
(* code dependency graph *)
bulwahn@32667
   598
(*
bulwahn@32667
   599
fun dependencies_of thy name =
bulwahn@32667
   600
  let
bulwahn@32667
   601
    val (intros, elim, nparams) = fetch_pred_data thy name 
bulwahn@32667
   602
    val data = mk_pred_data ((intros, SOME elim, nparams), ([], [], []))
bulwahn@32667
   603
    val keys = depending_preds_of thy intros
bulwahn@32667
   604
  in
bulwahn@32667
   605
    (data, keys)
bulwahn@32667
   606
  end;
bulwahn@32667
   607
*)
bulwahn@32667
   608
(* guessing number of parameters *)
bulwahn@32667
   609
fun find_indexes pred xs =
bulwahn@32667
   610
  let
bulwahn@32667
   611
    fun find is n [] = is
bulwahn@32667
   612
      | find is n (x :: xs) = find (if pred x then (n :: is) else is) (n + 1) xs;
bulwahn@32667
   613
  in rev (find [] 0 xs) end;
bulwahn@32667
   614
bulwahn@32667
   615
fun guess_nparams T =
bulwahn@32667
   616
  let
bulwahn@32667
   617
    val argTs = binder_types T
bulwahn@32667
   618
    val nparams = fold (curry Int.max)
bulwahn@32667
   619
      (map (fn x => x + 1) (find_indexes is_predT argTs)) 0
bulwahn@32667
   620
  in nparams end;
bulwahn@32667
   621
bulwahn@32667
   622
fun add_intro thm thy = let
bulwahn@32667
   623
   val (name, T) = dest_Const (fst (strip_intro_concl 0 (prop_of thm)))
bulwahn@32667
   624
   fun cons_intro gr =
bulwahn@32667
   625
     case try (Graph.get_node gr) name of
bulwahn@32667
   626
       SOME pred_data => Graph.map_node name (map_pred_data
bulwahn@32667
   627
         (apfst (fn (intro, elim, nparams) => (thm::intro, elim, nparams)))) gr
bulwahn@32667
   628
     | NONE =>
bulwahn@32667
   629
       let
bulwahn@32667
   630
         val nparams = the_default (guess_nparams T)  (try (#nparams o rep_pred_data o (fetch_pred_data thy)) name)
bulwahn@32667
   631
       in Graph.new_node (name, mk_pred_data (([thm], NONE, nparams), ([], [], []))) gr end;
bulwahn@32667
   632
  in PredData.map cons_intro thy end
bulwahn@32667
   633
bulwahn@32667
   634
fun set_elim thm = let
bulwahn@32667
   635
    val (name, _) = dest_Const (fst 
bulwahn@32667
   636
      (strip_comb (HOLogic.dest_Trueprop (hd (prems_of thm)))))
bulwahn@32667
   637
    fun set (intros, _, nparams) = (intros, SOME thm, nparams)  
bulwahn@32667
   638
  in PredData.map (Graph.map_node name (map_pred_data (apfst set))) end
bulwahn@32667
   639
bulwahn@32667
   640
fun set_nparams name nparams = let
bulwahn@32667
   641
    fun set (intros, elim, _ ) = (intros, elim, nparams) 
bulwahn@32667
   642
  in PredData.map (Graph.map_node name (map_pred_data (apfst set))) end
bulwahn@32667
   643
    
bulwahn@32668
   644
fun register_predicate (pre_intros, pre_elim, nparams) thy =
bulwahn@32668
   645
  let
bulwahn@32667
   646
    val (name, _) = dest_Const (fst (strip_intro_concl nparams (prop_of (hd pre_intros))))
bulwahn@32667
   647
    (* preprocessing *)
bulwahn@32667
   648
    val intros = ind_set_codegen_preproc thy (map (preprocess_intro thy) pre_intros)
bulwahn@32667
   649
    val elim = singleton (ind_set_codegen_preproc thy) (preprocess_elim thy nparams pre_elim)
bulwahn@32667
   650
  in
bulwahn@32668
   651
    if not (member (op =) (Graph.keys (PredData.get thy)) name) then
bulwahn@32668
   652
      PredData.map
bulwahn@32672
   653
        (Graph.new_node (name, mk_pred_data ((intros, SOME elim, nparams), ([], [], [])))) thy
bulwahn@32668
   654
    else thy
bulwahn@32667
   655
  end
bulwahn@32667
   656
bulwahn@32668
   657
fun register_intros pre_intros thy =
bulwahn@32668
   658
  let
bulwahn@32672
   659
    val (c, T) = dest_Const (fst (strip_intro_concl 0 (prop_of (hd pre_intros))))
wenzelm@32950
   660
    val _ = tracing ("Registering introduction rules of " ^ c)
wenzelm@32950
   661
    val _ = tracing (commas (map (Display.string_of_thm_global thy) pre_intros))
bulwahn@32672
   662
    val nparams = guess_nparams T
bulwahn@32672
   663
    val pre_elim = 
wenzelm@32970
   664
      (Drule.standard o Skip_Proof.make_thm thy)
bulwahn@32672
   665
      (mk_casesrule (ProofContext.init thy) nparams pre_intros)
bulwahn@32668
   666
  in register_predicate (pre_intros, pre_elim, nparams) thy end
bulwahn@32668
   667
bulwahn@32667
   668
fun set_generator_name pred mode name = 
bulwahn@32667
   669
  let
bulwahn@32667
   670
    val set = (apsnd o apsnd3 o cons) (mode, mk_function_data (name, NONE))
bulwahn@32667
   671
  in
bulwahn@32667
   672
    PredData.map (Graph.map_node pred (map_pred_data set))
bulwahn@32667
   673
  end
bulwahn@32667
   674
bulwahn@32667
   675
fun set_sizelim_function_name pred mode name = 
bulwahn@32667
   676
  let
bulwahn@32667
   677
    val set = (apsnd o aptrd3 o cons) (mode, mk_function_data (name, NONE))
bulwahn@32667
   678
  in
bulwahn@32667
   679
    PredData.map (Graph.map_node pred (map_pred_data set))
bulwahn@32667
   680
  end
bulwahn@32667
   681
bulwahn@32667
   682
(** data structures for generic compilation for different monads **)
bulwahn@32667
   683
bulwahn@32667
   684
(* maybe rename functions more generic:
bulwahn@32667
   685
  mk_predT -> mk_monadT; dest_predT -> dest_monadT
bulwahn@32667
   686
  mk_single -> mk_return (?)
bulwahn@32667
   687
*)
bulwahn@32667
   688
datatype compilation_funs = CompilationFuns of {
bulwahn@32667
   689
  mk_predT : typ -> typ,
bulwahn@32667
   690
  dest_predT : typ -> typ,
bulwahn@32667
   691
  mk_bot : typ -> term,
bulwahn@32667
   692
  mk_single : term -> term,
bulwahn@32667
   693
  mk_bind : term * term -> term,
bulwahn@32667
   694
  mk_sup : term * term -> term,
bulwahn@32667
   695
  mk_if : term -> term,
bulwahn@32667
   696
  mk_not : term -> term,
bulwahn@32667
   697
(*  funT_of : mode -> typ -> typ, *)
bulwahn@32667
   698
(*  mk_fun_of : theory -> (string * typ) -> mode -> term, *) 
bulwahn@32667
   699
  mk_map : typ -> typ -> term -> term -> term,
bulwahn@32667
   700
  lift_pred : term -> term
bulwahn@32667
   701
};
bulwahn@32667
   702
bulwahn@32667
   703
fun mk_predT (CompilationFuns funs) = #mk_predT funs
bulwahn@32667
   704
fun dest_predT (CompilationFuns funs) = #dest_predT funs
bulwahn@32667
   705
fun mk_bot (CompilationFuns funs) = #mk_bot funs
bulwahn@32667
   706
fun mk_single (CompilationFuns funs) = #mk_single funs
bulwahn@32667
   707
fun mk_bind (CompilationFuns funs) = #mk_bind funs
bulwahn@32667
   708
fun mk_sup (CompilationFuns funs) = #mk_sup funs
bulwahn@32667
   709
fun mk_if (CompilationFuns funs) = #mk_if funs
bulwahn@32667
   710
fun mk_not (CompilationFuns funs) = #mk_not funs
bulwahn@32667
   711
(*fun funT_of (CompilationFuns funs) = #funT_of funs*)
bulwahn@32667
   712
(*fun mk_fun_of (CompilationFuns funs) = #mk_fun_of funs*)
bulwahn@32667
   713
fun mk_map (CompilationFuns funs) = #mk_map funs
bulwahn@32667
   714
fun lift_pred (CompilationFuns funs) = #lift_pred funs
bulwahn@32667
   715
bulwahn@32667
   716
fun funT_of compfuns (iss, is) T =
bulwahn@32667
   717
  let
bulwahn@32667
   718
    val Ts = binder_types T
bulwahn@32667
   719
    val (paramTs, (inargTs, outargTs)) = split_modeT (iss, is) Ts
bulwahn@32667
   720
    val paramTs' = map2 (fn NONE => I | SOME is => funT_of compfuns ([], is)) iss paramTs
bulwahn@32667
   721
  in
bulwahn@32667
   722
    (paramTs' @ inargTs) ---> (mk_predT compfuns (mk_tupleT outargTs))
bulwahn@32667
   723
  end;
bulwahn@32667
   724
bulwahn@32667
   725
fun mk_fun_of compfuns thy (name, T) mode = 
bulwahn@32667
   726
  Const (predfun_name_of thy name mode, funT_of compfuns mode T)
bulwahn@32667
   727
bulwahn@32667
   728
bulwahn@32667
   729
structure PredicateCompFuns =
bulwahn@32667
   730
struct
bulwahn@32667
   731
bulwahn@32667
   732
fun mk_predT T = Type (@{type_name "Predicate.pred"}, [T])
bulwahn@32667
   733
bulwahn@32667
   734
fun dest_predT (Type (@{type_name "Predicate.pred"}, [T])) = T
bulwahn@32667
   735
  | dest_predT T = raise TYPE ("dest_predT", [T], []);
bulwahn@32667
   736
bulwahn@32667
   737
fun mk_bot T = Const (@{const_name Orderings.bot}, mk_predT T);
bulwahn@32667
   738
bulwahn@32667
   739
fun mk_single t =
bulwahn@32667
   740
  let val T = fastype_of t
bulwahn@32667
   741
  in Const(@{const_name Predicate.single}, T --> mk_predT T) $ t end;
bulwahn@32667
   742
bulwahn@32667
   743
fun mk_bind (x, f) =
bulwahn@32667
   744
  let val T as Type ("fun", [_, U]) = fastype_of f
bulwahn@32667
   745
  in
bulwahn@32667
   746
    Const (@{const_name Predicate.bind}, fastype_of x --> T --> U) $ x $ f
bulwahn@32667
   747
  end;
bulwahn@32667
   748
bulwahn@32667
   749
val mk_sup = HOLogic.mk_binop @{const_name sup};
bulwahn@32667
   750
bulwahn@32667
   751
fun mk_if cond = Const (@{const_name Predicate.if_pred},
bulwahn@32667
   752
  HOLogic.boolT --> mk_predT HOLogic.unitT) $ cond;
bulwahn@32667
   753
bulwahn@32667
   754
fun mk_not t = let val T = mk_predT HOLogic.unitT
bulwahn@32667
   755
  in Const (@{const_name Predicate.not_pred}, T --> T) $ t end
bulwahn@32667
   756
bulwahn@32667
   757
fun mk_Enum f =
bulwahn@32667
   758
  let val T as Type ("fun", [T', _]) = fastype_of f
bulwahn@32667
   759
  in
bulwahn@32667
   760
    Const (@{const_name Predicate.Pred}, T --> mk_predT T') $ f    
bulwahn@32667
   761
  end;
bulwahn@32667
   762
bulwahn@32667
   763
fun mk_Eval (f, x) =
bulwahn@32667
   764
  let
bulwahn@32667
   765
    val T = fastype_of x
bulwahn@32667
   766
  in
bulwahn@32667
   767
    Const (@{const_name Predicate.eval}, mk_predT T --> T --> HOLogic.boolT) $ f $ x
bulwahn@32667
   768
  end;
bulwahn@32667
   769
bulwahn@32667
   770
fun mk_map T1 T2 tf tp = Const (@{const_name Predicate.map},
bulwahn@32667
   771
  (T1 --> T2) --> mk_predT T1 --> mk_predT T2) $ tf $ tp;
bulwahn@32667
   772
bulwahn@32667
   773
val lift_pred = I
bulwahn@32667
   774
bulwahn@32667
   775
val compfuns = CompilationFuns {mk_predT = mk_predT, dest_predT = dest_predT, mk_bot = mk_bot,
bulwahn@32667
   776
  mk_single = mk_single, mk_bind = mk_bind, mk_sup = mk_sup, mk_if = mk_if, mk_not = mk_not,
bulwahn@32667
   777
  mk_map = mk_map, lift_pred = lift_pred};
bulwahn@32667
   778
bulwahn@32667
   779
end;
bulwahn@32667
   780
bulwahn@32667
   781
structure RPredCompFuns =
bulwahn@32667
   782
struct
bulwahn@32667
   783
bulwahn@32667
   784
fun mk_rpredT T =
bulwahn@32667
   785
  @{typ "Random.seed"} --> HOLogic.mk_prodT (PredicateCompFuns.mk_predT T, @{typ "Random.seed"})
bulwahn@32667
   786
bulwahn@32667
   787
fun dest_rpredT (Type ("fun", [_,
bulwahn@32667
   788
  Type (@{type_name "*"}, [Type (@{type_name "Predicate.pred"}, [T]), _])])) = T
bulwahn@32667
   789
  | dest_rpredT T = raise TYPE ("dest_rpredT", [T], []); 
bulwahn@32667
   790
bulwahn@32667
   791
fun mk_bot T = Const(@{const_name RPred.bot}, mk_rpredT T)
bulwahn@32667
   792
bulwahn@32667
   793
fun mk_single t =
bulwahn@32667
   794
  let
bulwahn@32667
   795
    val T = fastype_of t
bulwahn@32667
   796
  in
bulwahn@32667
   797
    Const (@{const_name RPred.return}, T --> mk_rpredT T) $ t
bulwahn@32667
   798
  end;
bulwahn@32667
   799
bulwahn@32667
   800
fun mk_bind (x, f) =
bulwahn@32667
   801
  let
bulwahn@32667
   802
    val T as (Type ("fun", [_, U])) = fastype_of f
bulwahn@32667
   803
  in
bulwahn@32667
   804
    Const (@{const_name RPred.bind}, fastype_of x --> T --> U) $ x $ f
bulwahn@32667
   805
  end
bulwahn@32667
   806
bulwahn@32667
   807
val mk_sup = HOLogic.mk_binop @{const_name RPred.supp}
bulwahn@32667
   808
bulwahn@32667
   809
fun mk_if cond = Const (@{const_name RPred.if_rpred},
bulwahn@32667
   810
  HOLogic.boolT --> mk_rpredT HOLogic.unitT) $ cond;
bulwahn@32667
   811
bulwahn@32667
   812
fun mk_not t = error "Negation is not defined for RPred"
bulwahn@32667
   813
bulwahn@32667
   814
fun mk_map t = error "FIXME" (*FIXME*)
bulwahn@32667
   815
bulwahn@32667
   816
fun lift_pred t =
bulwahn@32667
   817
  let
bulwahn@32667
   818
    val T = PredicateCompFuns.dest_predT (fastype_of t)
bulwahn@32667
   819
    val lift_predT = PredicateCompFuns.mk_predT T --> mk_rpredT T 
bulwahn@32667
   820
  in
bulwahn@32667
   821
    Const (@{const_name "RPred.lift_pred"}, lift_predT) $ t  
bulwahn@32667
   822
  end;
bulwahn@32667
   823
bulwahn@32667
   824
val compfuns = CompilationFuns {mk_predT = mk_rpredT, dest_predT = dest_rpredT, mk_bot = mk_bot,
bulwahn@32667
   825
    mk_single = mk_single, mk_bind = mk_bind, mk_sup = mk_sup, mk_if = mk_if, mk_not = mk_not,
bulwahn@32667
   826
    mk_map = mk_map, lift_pred = lift_pred};
bulwahn@32667
   827
bulwahn@32667
   828
end;
bulwahn@32667
   829
(* for external use with interactive mode *)
bulwahn@32672
   830
val pred_compfuns = PredicateCompFuns.compfuns
bulwahn@32667
   831
val rpred_compfuns = RPredCompFuns.compfuns;
bulwahn@32667
   832
bulwahn@32667
   833
fun lift_random random =
bulwahn@32667
   834
  let
bulwahn@32667
   835
    val T = dest_randomT (fastype_of random)
bulwahn@32667
   836
  in
bulwahn@32667
   837
    Const (@{const_name lift_random}, (@{typ Random.seed} -->
bulwahn@32667
   838
      HOLogic.mk_prodT (HOLogic.mk_prodT (T, @{typ "unit => term"}), @{typ Random.seed})) --> 
bulwahn@32667
   839
      RPredCompFuns.mk_rpredT T) $ random
bulwahn@32667
   840
  end;
bulwahn@32672
   841
bulwahn@32672
   842
fun sizelim_funT_of compfuns (iss, is) T =
bulwahn@32672
   843
  let
bulwahn@32672
   844
    val Ts = binder_types T
bulwahn@32672
   845
    val (paramTs, (inargTs, outargTs)) = split_modeT (iss, is) Ts
bulwahn@32672
   846
    val paramTs' = map2 (fn SOME is => sizelim_funT_of PredicateCompFuns.compfuns ([], is) | NONE => I) iss paramTs 
bulwahn@32672
   847
  in
bulwahn@32672
   848
    (paramTs' @ inargTs @ [@{typ "code_numeral"}]) ---> (mk_predT compfuns (mk_tupleT outargTs))
bulwahn@32672
   849
  end;  
bulwahn@32672
   850
bulwahn@32672
   851
fun mk_sizelim_fun_of compfuns thy (name, T) mode =
bulwahn@32672
   852
  Const (sizelim_function_name_of thy name mode, sizelim_funT_of compfuns mode T)
bulwahn@32672
   853
  
bulwahn@32672
   854
fun mk_generator_of compfuns thy (name, T) mode = 
bulwahn@32672
   855
  Const (generator_name_of thy name mode, sizelim_funT_of compfuns mode T)
bulwahn@32672
   856
bulwahn@32667
   857
(* Mode analysis *)
bulwahn@32667
   858
bulwahn@32667
   859
(*** check if a term contains only constructor functions ***)
bulwahn@32667
   860
fun is_constrt thy =
bulwahn@32667
   861
  let
bulwahn@32667
   862
    val cnstrs = flat (maps
bulwahn@32667
   863
      (map (fn (_, (Tname, _, cs)) => map (apsnd (rpair Tname o length)) cs) o #descr o snd)
bulwahn@32667
   864
      (Symtab.dest (Datatype.get_all thy)));
bulwahn@32667
   865
    fun check t = (case strip_comb t of
bulwahn@32667
   866
        (Free _, []) => true
bulwahn@32667
   867
      | (Const (s, T), ts) => (case (AList.lookup (op =) cnstrs s, body_type T) of
bulwahn@32667
   868
            (SOME (i, Tname), Type (Tname', _)) => length ts = i andalso Tname = Tname' andalso forall check ts
bulwahn@32667
   869
          | _ => false)
bulwahn@32667
   870
      | _ => false)
bulwahn@32667
   871
  in check end;
bulwahn@32667
   872
bulwahn@32667
   873
(*** check if a type is an equality type (i.e. doesn't contain fun)
bulwahn@32667
   874
  FIXME this is only an approximation ***)
bulwahn@32667
   875
fun is_eqT (Type (s, Ts)) = s <> "fun" andalso forall is_eqT Ts
bulwahn@32667
   876
  | is_eqT _ = true;
bulwahn@32667
   877
bulwahn@32667
   878
fun term_vs tm = fold_aterms (fn Free (x, T) => cons x | _ => I) tm [];
bulwahn@32667
   879
val terms_vs = distinct (op =) o maps term_vs;
bulwahn@32667
   880
bulwahn@32667
   881
(** collect all Frees in a term (with duplicates!) **)
bulwahn@32667
   882
fun term_vTs tm =
bulwahn@32667
   883
  fold_aterms (fn Free xT => cons xT | _ => I) tm [];
bulwahn@32667
   884
bulwahn@32667
   885
(*FIXME this function should not be named merge... make it local instead*)
bulwahn@32667
   886
fun merge xs [] = xs
bulwahn@32667
   887
  | merge [] ys = ys
bulwahn@32667
   888
  | merge (x::xs) (y::ys) = if length x >= length y then x::merge xs (y::ys)
bulwahn@32667
   889
      else y::merge (x::xs) ys;
bulwahn@32667
   890
bulwahn@32667
   891
fun subsets i j = if i <= j then
bulwahn@32667
   892
       let val is = subsets (i+1) j
bulwahn@32667
   893
       in merge (map (fn ks => i::ks) is) is end
bulwahn@32667
   894
     else [[]];
bulwahn@32667
   895
     
bulwahn@32668
   896
(* FIXME: should be in library - cprod = map_prod I *)
bulwahn@32667
   897
fun cprod ([], ys) = []
bulwahn@32667
   898
  | cprod (x :: xs, ys) = map (pair x) ys @ cprod (xs, ys);
bulwahn@32667
   899
wenzelm@33004
   900
fun cprods xss = List.foldr (map op :: o cprod) [[]] xss;
bulwahn@32667
   901
bulwahn@32667
   902
fun cprods_subset [] = [[]]
bulwahn@32667
   903
  | cprods_subset (xs :: xss) =
bulwahn@32667
   904
  let
bulwahn@32667
   905
    val yss = (cprods_subset xss)
bulwahn@32667
   906
  in maps (fn ys => map (fn x => cons x ys) xs) yss @ yss end
bulwahn@32667
   907
  
bulwahn@32667
   908
(*TODO: cleanup function and put together with modes_of_term *)
bulwahn@32667
   909
(*
bulwahn@32667
   910
fun modes_of_param default modes t = let
bulwahn@32667
   911
    val (vs, t') = strip_abs t
bulwahn@32667
   912
    val b = length vs
bulwahn@32667
   913
    fun mk_modes name args = Option.map (maps (fn (m as (iss, is)) =>
bulwahn@32667
   914
        let
bulwahn@32667
   915
          val (args1, args2) =
bulwahn@32667
   916
            if length args < length iss then
bulwahn@32667
   917
              error ("Too few arguments for inductive predicate " ^ name)
bulwahn@32667
   918
            else chop (length iss) args;
bulwahn@32667
   919
          val k = length args2;
bulwahn@32667
   920
          val perm = map (fn i => (find_index_eq (Bound (b - i)) args2) + 1)
bulwahn@32667
   921
            (1 upto b)  
bulwahn@32667
   922
          val partial_mode = (1 upto k) \\ perm
bulwahn@32667
   923
        in
bulwahn@32667
   924
          if not (partial_mode subset is) then [] else
bulwahn@32667
   925
          let
bulwahn@32667
   926
            val is' = 
bulwahn@32667
   927
            (fold_index (fn (i, j) => if j mem is then cons (i + 1) else I) perm [])
bulwahn@32667
   928
            |> fold (fn i => if i > k then cons (i - k + b) else I) is
bulwahn@32667
   929
              
bulwahn@32667
   930
           val res = map (fn x => Mode (m, is', x)) (cprods (map
bulwahn@32667
   931
            (fn (NONE, _) => [NONE]
bulwahn@32667
   932
              | (SOME js, arg) => map SOME (filter
bulwahn@32667
   933
                  (fn Mode (_, js', _) => js=js') (modes_of_term modes arg)))
bulwahn@32667
   934
                    (iss ~~ args1)))
bulwahn@32667
   935
          in res end
bulwahn@32667
   936
        end)) (AList.lookup op = modes name)
bulwahn@32667
   937
  in case strip_comb t' of
bulwahn@32667
   938
    (Const (name, _), args) => the_default default (mk_modes name args)
bulwahn@32667
   939
    | (Var ((name, _), _), args) => the (mk_modes name args)
bulwahn@32667
   940
    | (Free (name, _), args) => the (mk_modes name args)
bulwahn@32667
   941
    | _ => default end
bulwahn@32667
   942
  
bulwahn@32667
   943
and
bulwahn@32667
   944
*)
bulwahn@32667
   945
fun modes_of_term modes t =
bulwahn@32667
   946
  let
bulwahn@32667
   947
    val ks = map_index (fn (i, T) => (i, NONE)) (binder_types (fastype_of t));
bulwahn@32667
   948
    val default = [Mode (([], ks), ks, [])];
bulwahn@32667
   949
    fun mk_modes name args = Option.map (maps (fn (m as (iss, is)) =>
bulwahn@32667
   950
        let
bulwahn@32667
   951
          val (args1, args2) =
bulwahn@32667
   952
            if length args < length iss then
bulwahn@32667
   953
              error ("Too few arguments for inductive predicate " ^ name)
bulwahn@32667
   954
            else chop (length iss) args;
bulwahn@32667
   955
          val k = length args2;
bulwahn@32667
   956
          val prfx = map (rpair NONE) (1 upto k)
bulwahn@32667
   957
        in
bulwahn@32667
   958
          if not (is_prefix op = prfx is) then [] else
bulwahn@32667
   959
          let val is' = List.drop (is, k)
bulwahn@32667
   960
          in map (fn x => Mode (m, is', x)) (cprods (map
bulwahn@32667
   961
            (fn (NONE, _) => [NONE]
bulwahn@32667
   962
              | (SOME js, arg) => map SOME (filter
bulwahn@32667
   963
                  (fn Mode (_, js', _) => js=js') (modes_of_term modes arg)))
bulwahn@32667
   964
                    (iss ~~ args1)))
bulwahn@32667
   965
          end
bulwahn@32667
   966
        end)) (AList.lookup op = modes name)
bulwahn@32667
   967
bulwahn@32667
   968
  in
bulwahn@32667
   969
    case strip_comb (Envir.eta_contract t) of
bulwahn@32667
   970
      (Const (name, _), args) => the_default default (mk_modes name args)
bulwahn@32667
   971
    | (Var ((name, _), _), args) => the (mk_modes name args)
bulwahn@32667
   972
    | (Free (name, _), args) => the (mk_modes name args)
bulwahn@32667
   973
    | (Abs _, []) => error "Abs at param position" (* modes_of_param default modes t *)
bulwahn@32667
   974
    | _ => default
bulwahn@32667
   975
  end
bulwahn@32667
   976
  
bulwahn@32667
   977
fun select_mode_prem thy modes vs ps =
bulwahn@32667
   978
  find_first (is_some o snd) (ps ~~ map
bulwahn@32667
   979
    (fn Prem (us, t) => find_first (fn Mode (_, is, _) =>
bulwahn@32667
   980
          let
bulwahn@32667
   981
            val (in_ts, out_ts) = split_smode is us;
bulwahn@32667
   982
            val (out_ts', in_ts') = List.partition (is_constrt thy) out_ts;
bulwahn@32667
   983
            val vTs = maps term_vTs out_ts';
bulwahn@32667
   984
            val dupTs = map snd (duplicates (op =) vTs) @
wenzelm@32952
   985
              map_filter (AList.lookup (op =) vTs) vs;
bulwahn@32667
   986
          in
haftmann@33037
   987
            gen_subset (op =) (terms_vs (in_ts @ in_ts'), vs) andalso
bulwahn@32667
   988
            forall (is_eqT o fastype_of) in_ts' andalso
haftmann@33037
   989
            gen_subset (op =) (term_vs t, vs) andalso
bulwahn@32667
   990
            forall is_eqT dupTs
bulwahn@32667
   991
          end)
bulwahn@32667
   992
            (modes_of_term modes t handle Option =>
bulwahn@32667
   993
               error ("Bad predicate: " ^ Syntax.string_of_term_global thy t))
bulwahn@32667
   994
      | Negprem (us, t) => find_first (fn Mode (_, is, _) =>
bulwahn@32667
   995
            length us = length is andalso
haftmann@33037
   996
            gen_subset (op =) (terms_vs us, vs) andalso
haftmann@33037
   997
            gen_subset (op =) (term_vs t, vs))
bulwahn@32667
   998
            (modes_of_term modes t handle Option =>
bulwahn@32667
   999
               error ("Bad predicate: " ^ Syntax.string_of_term_global thy t))
haftmann@33037
  1000
      | Sidecond t => if gen_subset (op =) (term_vs t, vs) then SOME (Mode (([], []), [], []))
bulwahn@32667
  1001
          else NONE
bulwahn@32667
  1002
      ) ps);
bulwahn@32667
  1003
bulwahn@32667
  1004
fun fold_prem f (Prem (args, _)) = fold f args
bulwahn@32667
  1005
  | fold_prem f (Negprem (args, _)) = fold f args
bulwahn@32667
  1006
  | fold_prem f (Sidecond t) = f t
bulwahn@32667
  1007
bulwahn@32667
  1008
fun all_subsets [] = [[]]
bulwahn@32667
  1009
  | all_subsets (x::xs) = let val xss' = all_subsets xs in xss' @ (map (cons x) xss') end
bulwahn@32667
  1010
bulwahn@32667
  1011
fun generator vTs v = 
bulwahn@32667
  1012
  let
bulwahn@32667
  1013
    val T = the (AList.lookup (op =) vTs v)
bulwahn@32667
  1014
  in
bulwahn@32667
  1015
    (Generator (v, T), Mode (([], []), [], []))
bulwahn@32667
  1016
  end;
bulwahn@32667
  1017
bulwahn@32668
  1018
fun gen_prem (Prem (us, t)) = GeneratorPrem (us, t)
bulwahn@32668
  1019
  | gen_prem (Negprem (us, t)) = error "it is a negated prem"
bulwahn@32668
  1020
  | gen_prem (Sidecond t) = error "it is a sidecond"
bulwahn@32667
  1021
  | gen_prem _ = error "gen_prem : invalid input for gen_prem"
bulwahn@32667
  1022
bulwahn@32667
  1023
fun param_gen_prem param_vs (p as Prem (us, t as Free (v, _))) =
bulwahn@32667
  1024
  if member (op =) param_vs v then
bulwahn@32667
  1025
    GeneratorPrem (us, t)
bulwahn@32667
  1026
  else p  
bulwahn@32667
  1027
  | param_gen_prem param_vs p = p
bulwahn@32667
  1028
  
bulwahn@32667
  1029
fun check_mode_clause with_generator thy param_vs modes gen_modes (iss, is) (ts, ps) =
bulwahn@32667
  1030
  let
bulwahn@32668
  1031
    (*
wenzelm@32950
  1032
  val _ = tracing ("param_vs:" ^ commas param_vs)
wenzelm@32950
  1033
  val _ = tracing ("iss:" ^
bulwahn@32668
  1034
    commas (map (fn is => case is of SOME is => string_of_smode is | NONE => "NONE") iss))
bulwahn@32668
  1035
    *)
wenzelm@32952
  1036
    val modes' = modes @ map_filter
bulwahn@32667
  1037
      (fn (_, NONE) => NONE | (v, SOME js) => SOME (v, [([], js)]))
bulwahn@32667
  1038
        (param_vs ~~ iss);
wenzelm@32952
  1039
    val gen_modes' = gen_modes @ map_filter
bulwahn@32667
  1040
      (fn (_, NONE) => NONE | (v, SOME js) => SOME (v, [([], js)]))
bulwahn@32667
  1041
        (param_vs ~~ iss);  
bulwahn@32667
  1042
    val vTs = distinct (op =) ((fold o fold_prem) Term.add_frees ps (fold Term.add_frees ts []))
bulwahn@32667
  1043
    val prem_vs = distinct (op =) ((fold o fold_prem) Term.add_free_names ps [])
bulwahn@32667
  1044
    fun check_mode_prems acc_ps vs [] = SOME (acc_ps, vs)
bulwahn@32667
  1045
      | check_mode_prems acc_ps vs ps = (case select_mode_prem thy modes' vs ps of
bulwahn@32667
  1046
          NONE =>
bulwahn@32667
  1047
            (if with_generator then
bulwahn@32667
  1048
              (case select_mode_prem thy gen_modes' vs ps of
bulwahn@32668
  1049
                SOME (p as Prem _, SOME mode) => check_mode_prems ((gen_prem p, mode) :: acc_ps) 
haftmann@33037
  1050
                  (case p of Prem (us, _) => gen_union (op =) (vs, terms_vs us) | _ => vs)
bulwahn@32667
  1051
                  (filter_out (equal p) ps)
bulwahn@32672
  1052
              | _ =>
bulwahn@32667
  1053
                  let 
bulwahn@32667
  1054
                    val all_generator_vs = all_subsets (prem_vs \\ vs) |> sort (int_ord o (pairself length))
bulwahn@32667
  1055
                  in
bulwahn@32667
  1056
                    case (find_first (fn generator_vs => is_some
haftmann@33037
  1057
                      (select_mode_prem thy modes' (gen_union (op =) (vs, generator_vs)) ps)) all_generator_vs) of
bulwahn@32667
  1058
                      SOME generator_vs => check_mode_prems ((map (generator vTs) generator_vs) @ acc_ps)
haftmann@33037
  1059
                        (gen_union (op =) (vs, generator_vs)) ps
bulwahn@32668
  1060
                    | NONE => let
wenzelm@32950
  1061
                    val _ = tracing ("ps:" ^ (commas
bulwahn@32668
  1062
                    (map (fn p => string_of_moded_prem thy (p, Mode (([], []), [], []))) ps)))
bulwahn@32672
  1063
                  in (*error "mode analysis failed"*)NONE end
bulwahn@32667
  1064
                  end)
bulwahn@32667
  1065
            else
bulwahn@32667
  1066
              NONE)
bulwahn@32667
  1067
        | SOME (p, SOME mode) => check_mode_prems ((if with_generator then param_gen_prem param_vs p else p, mode) :: acc_ps) 
haftmann@33037
  1068
            (case p of Prem (us, _) => gen_union (op =) (vs, terms_vs us) | _ => vs)
bulwahn@32667
  1069
            (filter_out (equal p) ps))
bulwahn@32667
  1070
    val (in_ts, in_ts') = List.partition (is_constrt thy) (fst (split_smode is ts));
bulwahn@32667
  1071
    val in_vs = terms_vs in_ts;
bulwahn@32667
  1072
    val concl_vs = terms_vs ts
bulwahn@32667
  1073
  in
bulwahn@32667
  1074
    if forall is_eqT (map snd (duplicates (op =) (maps term_vTs in_ts))) andalso
bulwahn@32667
  1075
    forall (is_eqT o fastype_of) in_ts' then
haftmann@33037
  1076
      case check_mode_prems [] (gen_union (op =) (param_vs, in_vs)) ps of
bulwahn@32667
  1077
         NONE => NONE
bulwahn@32667
  1078
       | SOME (acc_ps, vs) =>
bulwahn@32667
  1079
         if with_generator then
bulwahn@32667
  1080
           SOME (ts, (rev acc_ps) @ (map (generator vTs) (concl_vs \\ vs))) 
bulwahn@32667
  1081
         else
haftmann@33037
  1082
           if gen_subset (op =) (concl_vs, vs) then SOME (ts, rev acc_ps) else NONE
bulwahn@32667
  1083
    else NONE
bulwahn@32667
  1084
  end;
bulwahn@32667
  1085
bulwahn@32667
  1086
fun check_modes_pred with_generator thy param_vs clauses modes gen_modes (p, ms) =
bulwahn@32667
  1087
  let val SOME rs = AList.lookup (op =) clauses p
bulwahn@32667
  1088
  in (p, List.filter (fn m => case find_index
bulwahn@32667
  1089
    (is_none o check_mode_clause with_generator thy param_vs modes gen_modes m) rs of
bulwahn@32667
  1090
      ~1 => true
wenzelm@32950
  1091
    | i => (tracing ("Clause " ^ string_of_int (i + 1) ^ " of " ^
bulwahn@32667
  1092
      p ^ " violates mode " ^ string_of_mode m);
wenzelm@32950
  1093
        tracing (commas (map (Syntax.string_of_term_global thy) (fst (nth rs i)))); false)) ms)
bulwahn@32667
  1094
  end;
bulwahn@32667
  1095
bulwahn@32667
  1096
fun get_modes_pred with_generator thy param_vs clauses modes gen_modes (p, ms) =
bulwahn@32667
  1097
  let
bulwahn@32667
  1098
    val SOME rs = AList.lookup (op =) clauses p 
bulwahn@32667
  1099
  in
bulwahn@32667
  1100
    (p, map (fn m =>
bulwahn@32667
  1101
      (m, map (the o check_mode_clause with_generator thy param_vs modes gen_modes m) rs)) ms)
bulwahn@32667
  1102
  end;
bulwahn@32667
  1103
  
bulwahn@32667
  1104
fun fixp f (x : (string * mode list) list) =
bulwahn@32667
  1105
  let val y = f x
bulwahn@32667
  1106
  in if x = y then x else fixp f y end;
bulwahn@32667
  1107
bulwahn@32667
  1108
fun infer_modes thy extra_modes all_modes param_vs clauses =
bulwahn@32667
  1109
  let
bulwahn@32667
  1110
    val modes =
bulwahn@32667
  1111
      fixp (fn modes =>
bulwahn@32667
  1112
        map (check_modes_pred false thy param_vs clauses (modes @ extra_modes) []) modes)
bulwahn@32667
  1113
          all_modes
bulwahn@32667
  1114
  in
bulwahn@32667
  1115
    map (get_modes_pred false thy param_vs clauses (modes @ extra_modes) []) modes
bulwahn@32667
  1116
  end;
bulwahn@32667
  1117
bulwahn@32667
  1118
fun remove_from rem [] = []
bulwahn@32667
  1119
  | remove_from rem ((k, vs) :: xs) =
bulwahn@32667
  1120
    (case AList.lookup (op =) rem k of
bulwahn@32667
  1121
      NONE => (k, vs)
bulwahn@32667
  1122
    | SOME vs' => (k, vs \\ vs'))
bulwahn@32667
  1123
    :: remove_from rem xs
bulwahn@32667
  1124
    
bulwahn@32667
  1125
fun infer_modes_with_generator thy extra_modes all_modes param_vs clauses =
bulwahn@32667
  1126
  let
bulwahn@32667
  1127
    val prednames = map fst clauses
bulwahn@32667
  1128
    val extra_modes = all_modes_of thy
bulwahn@32667
  1129
    val gen_modes = all_generator_modes_of thy
bulwahn@32667
  1130
      |> filter_out (fn (name, _) => member (op =) prednames name)
bulwahn@32667
  1131
    val starting_modes = remove_from extra_modes all_modes 
bulwahn@32667
  1132
    val modes =
bulwahn@32667
  1133
      fixp (fn modes =>
bulwahn@32667
  1134
        map (check_modes_pred true thy param_vs clauses extra_modes (gen_modes @ modes)) modes)
bulwahn@32667
  1135
         starting_modes 
bulwahn@32667
  1136
  in
bulwahn@32667
  1137
    map (get_modes_pred true thy param_vs clauses extra_modes (gen_modes @ modes)) modes
bulwahn@32667
  1138
  end;
bulwahn@32667
  1139
bulwahn@32667
  1140
(* term construction *)
bulwahn@32667
  1141
bulwahn@32667
  1142
fun mk_v (names, vs) s T = (case AList.lookup (op =) vs s of
bulwahn@32667
  1143
      NONE => (Free (s, T), (names, (s, [])::vs))
bulwahn@32667
  1144
    | SOME xs =>
bulwahn@32667
  1145
        let
bulwahn@32667
  1146
          val s' = Name.variant names s;
bulwahn@32667
  1147
          val v = Free (s', T)
bulwahn@32667
  1148
        in
bulwahn@32667
  1149
          (v, (s'::names, AList.update (op =) (s, v::xs) vs))
bulwahn@32667
  1150
        end);
bulwahn@32667
  1151
bulwahn@32667
  1152
fun distinct_v (Free (s, T)) nvs = mk_v nvs s T
bulwahn@32667
  1153
  | distinct_v (t $ u) nvs =
bulwahn@32667
  1154
      let
bulwahn@32667
  1155
        val (t', nvs') = distinct_v t nvs;
bulwahn@32667
  1156
        val (u', nvs'') = distinct_v u nvs';
bulwahn@32667
  1157
      in (t' $ u', nvs'') end
bulwahn@32667
  1158
  | distinct_v x nvs = (x, nvs);
bulwahn@32667
  1159
bulwahn@32667
  1160
fun compile_match thy compfuns eqs eqs' out_ts success_t =
bulwahn@32667
  1161
  let
bulwahn@32667
  1162
    val eqs'' = maps mk_eq eqs @ eqs'
bulwahn@32667
  1163
    val names = fold Term.add_free_names (success_t :: eqs'' @ out_ts) [];
bulwahn@32667
  1164
    val name = Name.variant names "x";
bulwahn@32667
  1165
    val name' = Name.variant (name :: names) "y";
bulwahn@32667
  1166
    val T = mk_tupleT (map fastype_of out_ts);
bulwahn@32667
  1167
    val U = fastype_of success_t;
bulwahn@32667
  1168
    val U' = dest_predT compfuns U;
bulwahn@32667
  1169
    val v = Free (name, T);
bulwahn@32667
  1170
    val v' = Free (name', T);
bulwahn@32667
  1171
  in
bulwahn@32667
  1172
    lambda v (fst (Datatype.make_case
bulwahn@32671
  1173
      (ProofContext.init thy) DatatypeCase.Quiet [] v
bulwahn@32667
  1174
      [(mk_tuple out_ts,
bulwahn@32667
  1175
        if null eqs'' then success_t
bulwahn@32667
  1176
        else Const (@{const_name HOL.If}, HOLogic.boolT --> U --> U --> U) $
bulwahn@32667
  1177
          foldr1 HOLogic.mk_conj eqs'' $ success_t $
bulwahn@32667
  1178
            mk_bot compfuns U'),
bulwahn@32667
  1179
       (v', mk_bot compfuns U')]))
bulwahn@32667
  1180
  end;
bulwahn@32667
  1181
bulwahn@32667
  1182
(*FIXME function can be removed*)
bulwahn@32667
  1183
fun mk_funcomp f t =
bulwahn@32667
  1184
  let
bulwahn@32667
  1185
    val names = Term.add_free_names t [];
bulwahn@32667
  1186
    val Ts = binder_types (fastype_of t);
bulwahn@32667
  1187
    val vs = map Free
bulwahn@32667
  1188
      (Name.variant_list names (replicate (length Ts) "x") ~~ Ts)
bulwahn@32667
  1189
  in
bulwahn@32667
  1190
    fold_rev lambda vs (f (list_comb (t, vs)))
bulwahn@32667
  1191
  end;
bulwahn@32667
  1192
(*
bulwahn@32667
  1193
fun compile_param_ext thy compfuns modes (NONE, t) = t
bulwahn@32667
  1194
  | compile_param_ext thy compfuns modes (m as SOME (Mode ((iss, is'), is, ms)), t) =
bulwahn@32667
  1195
      let
bulwahn@32667
  1196
        val (vs, u) = strip_abs t
bulwahn@32667
  1197
        val (ivs, ovs) = split_mode is vs    
bulwahn@32667
  1198
        val (f, args) = strip_comb u
bulwahn@32667
  1199
        val (params, args') = chop (length ms) args
bulwahn@32667
  1200
        val (inargs, outargs) = split_mode is' args'
bulwahn@32667
  1201
        val b = length vs
bulwahn@32667
  1202
        val perm = map (fn i => (find_index_eq (Bound (b - i)) args') + 1) (1 upto b)
bulwahn@32667
  1203
        val outp_perm =
bulwahn@32667
  1204
          snd (split_mode is perm)
bulwahn@32667
  1205
          |> map (fn i => i - length (filter (fn x => x < i) is'))
bulwahn@32667
  1206
        val names = [] -- TODO
bulwahn@32667
  1207
        val out_names = Name.variant_list names (replicate (length outargs) "x")
bulwahn@32667
  1208
        val f' = case f of
bulwahn@32667
  1209
            Const (name, T) =>
bulwahn@32667
  1210
              if AList.defined op = modes name then
bulwahn@32667
  1211
                mk_predfun_of thy compfuns (name, T) (iss, is')
bulwahn@32667
  1212
              else error "compile param: Not an inductive predicate with correct mode"
bulwahn@32667
  1213
          | Free (name, T) => Free (name, param_funT_of compfuns T (SOME is'))
bulwahn@32667
  1214
        val outTs = dest_tupleT (dest_predT compfuns (body_type (fastype_of f')))
bulwahn@32667
  1215
        val out_vs = map Free (out_names ~~ outTs)
bulwahn@32667
  1216
        val params' = map (compile_param thy modes) (ms ~~ params)
bulwahn@32667
  1217
        val f_app = list_comb (f', params' @ inargs)
bulwahn@32667
  1218
        val single_t = (mk_single compfuns (mk_tuple (map (fn i => nth out_vs (i - 1)) outp_perm)))
bulwahn@32667
  1219
        val match_t = compile_match thy compfuns [] [] out_vs single_t
bulwahn@32667
  1220
      in list_abs (ivs,
bulwahn@32667
  1221
        mk_bind compfuns (f_app, match_t))
bulwahn@32667
  1222
      end
bulwahn@32667
  1223
  | compile_param_ext _ _ _ _ = error "compile params"
bulwahn@32667
  1224
*)
bulwahn@32667
  1225
bulwahn@32672
  1226
fun compile_param neg_in_sizelim size thy compfuns (NONE, t) = t
bulwahn@32672
  1227
  | compile_param neg_in_sizelim size thy compfuns (m as SOME (Mode ((iss, is'), is, ms)), t) =
bulwahn@32667
  1228
   let
bulwahn@32667
  1229
     val (f, args) = strip_comb (Envir.eta_contract t)
bulwahn@32667
  1230
     val (params, args') = chop (length ms) args
bulwahn@32672
  1231
     val params' = map (compile_param neg_in_sizelim size thy compfuns) (ms ~~ params)
bulwahn@32667
  1232
     val mk_fun_of = case size of NONE => mk_fun_of | SOME _ => mk_sizelim_fun_of
bulwahn@32667
  1233
     val funT_of = case size of NONE => funT_of | SOME _ => sizelim_funT_of
bulwahn@32667
  1234
     val f' =
bulwahn@32667
  1235
       case f of
bulwahn@32667
  1236
         Const (name, T) =>
bulwahn@32667
  1237
           mk_fun_of compfuns thy (name, T) (iss, is')
bulwahn@32672
  1238
       | Free (name, T) =>
bulwahn@32672
  1239
         case neg_in_sizelim of
bulwahn@32672
  1240
           SOME _ =>  Free (name, sizelim_funT_of compfuns (iss, is') T)
bulwahn@32672
  1241
         | NONE => Free (name, funT_of compfuns (iss, is') T)
bulwahn@32672
  1242
           
bulwahn@32667
  1243
       | _ => error ("PredicateCompiler: illegal parameter term")
bulwahn@32672
  1244
   in
bulwahn@32672
  1245
     (case neg_in_sizelim of SOME size_t =>
bulwahn@32672
  1246
       (fn t =>
bulwahn@32672
  1247
       let
bulwahn@32672
  1248
         val Ts = fst (split_last (binder_types (fastype_of t)))
bulwahn@32672
  1249
         val names = map (fn i => "x" ^ string_of_int i) (1 upto length Ts)
bulwahn@32672
  1250
       in
bulwahn@32672
  1251
         list_abs (names ~~ Ts, list_comb (t, (map Bound ((length Ts) - 1 downto 0)) @ [size_t]))
bulwahn@32672
  1252
       end)
bulwahn@32672
  1253
     | NONE => I)
bulwahn@32672
  1254
     (list_comb (f', params' @ args'))
bulwahn@32672
  1255
   end
bulwahn@32672
  1256
bulwahn@32672
  1257
fun compile_expr neg_in_sizelim size thy ((Mode (mode, is, ms)), t) =
bulwahn@32667
  1258
  case strip_comb t of
bulwahn@32667
  1259
    (Const (name, T), params) =>
bulwahn@32667
  1260
       let
bulwahn@32672
  1261
         val params' = map (compile_param neg_in_sizelim size thy PredicateCompFuns.compfuns) (ms ~~ params)
bulwahn@32667
  1262
         val mk_fun_of = case size of NONE => mk_fun_of | SOME _ => mk_sizelim_fun_of
bulwahn@32667
  1263
       in
bulwahn@32667
  1264
         list_comb (mk_fun_of PredicateCompFuns.compfuns thy (name, T) mode, params')
bulwahn@32667
  1265
       end
bulwahn@32667
  1266
  | (Free (name, T), args) =>
bulwahn@32667
  1267
       let 
bulwahn@32667
  1268
         val funT_of = case size of NONE => funT_of | SOME _ => sizelim_funT_of 
bulwahn@32667
  1269
       in
bulwahn@32667
  1270
         list_comb (Free (name, funT_of PredicateCompFuns.compfuns ([], is) T), args)
bulwahn@32667
  1271
       end;
bulwahn@32667
  1272
       
bulwahn@32672
  1273
fun compile_gen_expr size thy compfuns ((Mode (mode, is, ms)), t) inargs =
bulwahn@32667
  1274
  case strip_comb t of
bulwahn@32667
  1275
    (Const (name, T), params) =>
bulwahn@32667
  1276
      let
bulwahn@32672
  1277
        val params' = map (compile_param NONE size thy PredicateCompFuns.compfuns) (ms ~~ params)
bulwahn@32667
  1278
      in
bulwahn@32672
  1279
        list_comb (mk_generator_of compfuns thy (name, T) mode, params' @ inargs)
bulwahn@32667
  1280
      end
bulwahn@32672
  1281
    | (Free (name, T), params) =>
bulwahn@32672
  1282
    lift_pred compfuns
bulwahn@32672
  1283
    (list_comb (Free (name, sizelim_funT_of PredicateCompFuns.compfuns ([], is) T), params @ inargs))
bulwahn@32672
  1284
      
bulwahn@32667
  1285
          
bulwahn@32667
  1286
(** specific rpred functions -- move them to the correct place in this file *)
bulwahn@32667
  1287
bulwahn@32672
  1288
fun mk_Eval_of size ((x, T), NONE) names = (x, names)
bulwahn@32672
  1289
  | mk_Eval_of size ((x, T), SOME mode) names =
bulwahn@32672
  1290
	let
bulwahn@32672
  1291
    val Ts = binder_types T
bulwahn@32672
  1292
    (*val argnames = Name.variant_list names
bulwahn@32672
  1293
        (map (fn i => "x" ^ string_of_int i) (1 upto (length Ts)));
bulwahn@32672
  1294
    val args = map Free (argnames ~~ Ts)
bulwahn@32672
  1295
    val (inargs, outargs) = split_smode mode args*)
bulwahn@32672
  1296
		fun mk_split_lambda [] t = lambda (Free (Name.variant names "x", HOLogic.unitT)) t
bulwahn@32672
  1297
			| mk_split_lambda [x] t = lambda x t
bulwahn@32672
  1298
			| mk_split_lambda xs t =
bulwahn@32672
  1299
			let
bulwahn@32672
  1300
				fun mk_split_lambda' (x::y::[]) t = HOLogic.mk_split (lambda x (lambda y t))
bulwahn@32672
  1301
					| mk_split_lambda' (x::xs) t = HOLogic.mk_split (lambda x (mk_split_lambda' xs t))
bulwahn@32672
  1302
			in
bulwahn@32672
  1303
				mk_split_lambda' xs t
bulwahn@32672
  1304
			end;
bulwahn@32672
  1305
  	fun mk_arg (i, T) =
bulwahn@32672
  1306
		  let
bulwahn@32672
  1307
	  	  val vname = Name.variant names ("x" ^ string_of_int i)
bulwahn@32672
  1308
		    val default = Free (vname, T)
bulwahn@32672
  1309
		  in 
bulwahn@32672
  1310
		    case AList.lookup (op =) mode i of
bulwahn@32672
  1311
		      NONE => (([], [default]), [default])
bulwahn@32672
  1312
			  | SOME NONE => (([default], []), [default])
bulwahn@32672
  1313
			  | SOME (SOME pis) =>
bulwahn@32672
  1314
				  case HOLogic.strip_tupleT T of
bulwahn@32672
  1315
						[] => error "pair mode but unit tuple" (*(([default], []), [default])*)
bulwahn@32672
  1316
					| [_] => error "pair mode but not a tuple" (*(([default], []), [default])*)
bulwahn@32672
  1317
					| Ts =>
bulwahn@32672
  1318
					  let
bulwahn@32672
  1319
							val vnames = Name.variant_list names
bulwahn@32672
  1320
								(map (fn j => "x" ^ string_of_int i ^ "p" ^ string_of_int j)
bulwahn@32672
  1321
									(1 upto length Ts))
bulwahn@32672
  1322
							val args = map Free (vnames ~~ Ts)
bulwahn@32672
  1323
							fun split_args (i, arg) (ins, outs) =
bulwahn@32672
  1324
							  if member (op =) pis i then
bulwahn@32672
  1325
							    (arg::ins, outs)
bulwahn@32672
  1326
								else
bulwahn@32672
  1327
								  (ins, arg::outs)
bulwahn@32672
  1328
							val (inargs, outargs) = fold_rev split_args ((1 upto length Ts) ~~ args) ([], [])
bulwahn@32672
  1329
							fun tuple args = if null args then [] else [HOLogic.mk_tuple args]
bulwahn@32672
  1330
						in ((tuple inargs, tuple outargs), args) end
bulwahn@32672
  1331
			end
bulwahn@32672
  1332
		val (inoutargs, args) = split_list (map mk_arg (1 upto (length Ts) ~~ Ts))
bulwahn@32672
  1333
    val (inargs, outargs) = pairself flat (split_list inoutargs)
bulwahn@32672
  1334
    val size_t = case size of NONE => [] | SOME size_t => [size_t]
bulwahn@32672
  1335
		val r = PredicateCompFuns.mk_Eval (list_comb (x, inargs @ size_t), mk_tuple outargs)
bulwahn@32672
  1336
    val t = fold_rev mk_split_lambda args r
bulwahn@32672
  1337
  in
bulwahn@32672
  1338
    (t, names)
bulwahn@32672
  1339
  end;
bulwahn@32667
  1340
bulwahn@32672
  1341
fun compile_arg size thy param_vs iss arg = 
bulwahn@32672
  1342
  let
bulwahn@32672
  1343
    val funT_of = case size of NONE => funT_of | SOME _ => sizelim_funT_of
bulwahn@32672
  1344
    fun map_params (t as Free (f, T)) =
bulwahn@32672
  1345
      if member (op =) param_vs f then
bulwahn@32672
  1346
        case (the (AList.lookup (op =) (param_vs ~~ iss) f)) of
bulwahn@32672
  1347
          SOME is => let val T' = funT_of PredicateCompFuns.compfuns ([], is) T
bulwahn@32672
  1348
            in fst (mk_Eval_of size ((Free (f, T'), T), SOME is) []) end
bulwahn@32672
  1349
        | NONE => t
bulwahn@32672
  1350
      else t
bulwahn@32672
  1351
      | map_params t = t
bulwahn@32672
  1352
    in map_aterms map_params arg end
bulwahn@32672
  1353
  
bulwahn@32667
  1354
fun compile_clause compfuns size final_term thy all_vs param_vs (iss, is) inp (ts, moded_ps) =
bulwahn@32667
  1355
  let
bulwahn@32667
  1356
    fun check_constrt t (names, eqs) =
bulwahn@32667
  1357
      if is_constrt thy t then (t, (names, eqs)) else
bulwahn@32667
  1358
        let
bulwahn@32667
  1359
          val s = Name.variant names "x";
bulwahn@32667
  1360
          val v = Free (s, fastype_of t)
bulwahn@32667
  1361
        in (v, (s::names, HOLogic.mk_eq (v, t)::eqs)) end;
bulwahn@32667
  1362
bulwahn@32667
  1363
    val (in_ts, out_ts) = split_smode is ts;
bulwahn@32667
  1364
    val (in_ts', (all_vs', eqs)) =
bulwahn@32667
  1365
      fold_map check_constrt in_ts (all_vs, []);
bulwahn@32667
  1366
bulwahn@32667
  1367
    fun compile_prems out_ts' vs names [] =
bulwahn@32667
  1368
          let
bulwahn@32667
  1369
            val (out_ts'', (names', eqs')) =
bulwahn@32667
  1370
              fold_map check_constrt out_ts' (names, []);
bulwahn@32667
  1371
            val (out_ts''', (names'', constr_vs)) = fold_map distinct_v
bulwahn@32667
  1372
              out_ts'' (names', map (rpair []) vs);
bulwahn@32667
  1373
          in
bulwahn@32667
  1374
          (* termify code:
bulwahn@32667
  1375
            compile_match thy compfuns constr_vs (eqs @ eqs') out_ts'''
bulwahn@32667
  1376
              (mk_single compfuns (mk_tuple (map mk_valtermify_term out_ts)))
bulwahn@32667
  1377
           *)
bulwahn@32667
  1378
            compile_match thy compfuns constr_vs (eqs @ eqs') out_ts'''
bulwahn@32667
  1379
              (final_term out_ts)
bulwahn@32667
  1380
          end
bulwahn@32667
  1381
      | compile_prems out_ts vs names ((p, mode as Mode ((_, is), _, _)) :: ps) =
bulwahn@32667
  1382
          let
bulwahn@32667
  1383
            val vs' = distinct (op =) (flat (vs :: map term_vs out_ts));
bulwahn@32667
  1384
            val (out_ts', (names', eqs)) =
bulwahn@32667
  1385
              fold_map check_constrt out_ts (names, [])
bulwahn@32667
  1386
            val (out_ts'', (names'', constr_vs')) = fold_map distinct_v
bulwahn@32667
  1387
              out_ts' ((names', map (rpair []) vs))
bulwahn@32667
  1388
            val (compiled_clause, rest) = case p of
bulwahn@32667
  1389
               Prem (us, t) =>
bulwahn@32667
  1390
                 let
bulwahn@32667
  1391
                   val (in_ts, out_ts''') = split_smode is us;
bulwahn@32672
  1392
                   val in_ts = map (compile_arg size thy param_vs iss) in_ts
bulwahn@32667
  1393
                   val args = case size of
bulwahn@32667
  1394
                     NONE => in_ts
bulwahn@32667
  1395
                   | SOME size_t => in_ts @ [size_t]
bulwahn@32667
  1396
                   val u = lift_pred compfuns
bulwahn@32672
  1397
                     (list_comb (compile_expr NONE size thy (mode, t), args))                     
bulwahn@32667
  1398
                   val rest = compile_prems out_ts''' vs' names'' ps
bulwahn@32667
  1399
                 in
bulwahn@32667
  1400
                   (u, rest)
bulwahn@32667
  1401
                 end
bulwahn@32667
  1402
             | Negprem (us, t) =>
bulwahn@32667
  1403
                 let
bulwahn@32667
  1404
                   val (in_ts, out_ts''') = split_smode is us
bulwahn@32667
  1405
                   val u = lift_pred compfuns
bulwahn@32672
  1406
                     (mk_not PredicateCompFuns.compfuns (list_comb (compile_expr size NONE thy (mode, t), in_ts)))
bulwahn@32667
  1407
                   val rest = compile_prems out_ts''' vs' names'' ps
bulwahn@32667
  1408
                 in
bulwahn@32667
  1409
                   (u, rest)
bulwahn@32667
  1410
                 end
bulwahn@32667
  1411
             | Sidecond t =>
bulwahn@32667
  1412
                 let
bulwahn@32667
  1413
                   val rest = compile_prems [] vs' names'' ps;
bulwahn@32667
  1414
                 in
bulwahn@32667
  1415
                   (mk_if compfuns t, rest)
bulwahn@32667
  1416
                 end
bulwahn@32667
  1417
             | GeneratorPrem (us, t) =>
bulwahn@32667
  1418
                 let
bulwahn@32667
  1419
                   val (in_ts, out_ts''') = split_smode is us;
bulwahn@32667
  1420
                   val args = case size of
bulwahn@32667
  1421
                     NONE => in_ts
bulwahn@32667
  1422
                   | SOME size_t => in_ts @ [size_t]
bulwahn@32672
  1423
                   val u = compile_gen_expr size thy compfuns (mode, t) args
bulwahn@32667
  1424
                   val rest = compile_prems out_ts''' vs' names'' ps
bulwahn@32667
  1425
                 in
bulwahn@32667
  1426
                   (u, rest)
bulwahn@32667
  1427
                 end
bulwahn@32667
  1428
             | Generator (v, T) =>
bulwahn@32667
  1429
                 let
bulwahn@32672
  1430
                   val u = lift_random (HOLogic.mk_random T (the size))
bulwahn@32667
  1431
                   val rest = compile_prems [Free (v, T)]  vs' names'' ps;
bulwahn@32667
  1432
                 in
bulwahn@32667
  1433
                   (u, rest)
bulwahn@32667
  1434
                 end
bulwahn@32667
  1435
          in
bulwahn@32667
  1436
            compile_match thy compfuns constr_vs' eqs out_ts'' 
bulwahn@32667
  1437
              (mk_bind compfuns (compiled_clause, rest))
bulwahn@32667
  1438
          end
bulwahn@32667
  1439
    val prem_t = compile_prems in_ts' param_vs all_vs' moded_ps;
bulwahn@32667
  1440
  in
bulwahn@32667
  1441
    mk_bind compfuns (mk_single compfuns inp, prem_t)
bulwahn@32667
  1442
  end
bulwahn@32667
  1443
bulwahn@32667
  1444
fun compile_pred compfuns mk_fun_of use_size thy all_vs param_vs s T mode moded_cls =
bulwahn@32667
  1445
  let
bulwahn@32667
  1446
	  val (Ts1, Ts2) = chop (length (fst mode)) (binder_types T)
bulwahn@32667
  1447
    val (Us1, Us2) = split_smodeT (snd mode) Ts2
bulwahn@32667
  1448
    val funT_of = if use_size then sizelim_funT_of else funT_of
bulwahn@32672
  1449
    val Ts1' = map2 (fn NONE => I | SOME is => funT_of PredicateCompFuns.compfuns ([], is)) (fst mode) Ts1
bulwahn@32667
  1450
    val size_name = Name.variant (all_vs @ param_vs) "size"
bulwahn@32667
  1451
  	fun mk_input_term (i, NONE) =
bulwahn@32667
  1452
		    [Free (Name.variant (all_vs @ param_vs) ("x" ^ string_of_int i), nth Ts2 (i - 1))]
bulwahn@32667
  1453
		  | mk_input_term (i, SOME pis) = case HOLogic.strip_tupleT (nth Ts2 (i - 1)) of
bulwahn@32667
  1454
						   [] => error "strange unit input"
bulwahn@32667
  1455
					   | [T] => [Free (Name.variant (all_vs @ param_vs) ("x" ^ string_of_int i), nth Ts2 (i - 1))]
bulwahn@32667
  1456
						 | Ts => let
bulwahn@32667
  1457
							 val vnames = Name.variant_list (all_vs @ param_vs)
bulwahn@32667
  1458
								(map (fn j => "x" ^ string_of_int i ^ "p" ^ string_of_int j)
bulwahn@32667
  1459
									pis)
bulwahn@32667
  1460
						 in if null pis then []
bulwahn@32667
  1461
						   else [HOLogic.mk_tuple (map Free (vnames ~~ map (fn j => nth Ts (j - 1)) pis))] end
bulwahn@32667
  1462
		val in_ts = maps mk_input_term (snd mode)
bulwahn@32667
  1463
    val params = map2 (fn s => fn T => Free (s, T)) param_vs Ts1'
bulwahn@32667
  1464
    val size = Free (size_name, @{typ "code_numeral"})
bulwahn@32667
  1465
    val decr_size =
bulwahn@32667
  1466
      if use_size then
bulwahn@32667
  1467
        SOME (Const ("HOL.minus_class.minus", @{typ "code_numeral => code_numeral => code_numeral"})
bulwahn@32667
  1468
          $ size $ Const ("HOL.one_class.one", @{typ "Code_Numeral.code_numeral"}))
bulwahn@32667
  1469
      else
bulwahn@32667
  1470
        NONE
bulwahn@32667
  1471
    val cl_ts =
bulwahn@32667
  1472
      map (compile_clause compfuns decr_size (fn out_ts => mk_single compfuns (mk_tuple out_ts))
bulwahn@32667
  1473
        thy all_vs param_vs mode (mk_tuple in_ts)) moded_cls;
bulwahn@32667
  1474
    val t = foldr1 (mk_sup compfuns) cl_ts
bulwahn@32667
  1475
    val T' = mk_predT compfuns (mk_tupleT Us2)
bulwahn@32667
  1476
    val size_t = Const (@{const_name "If"}, @{typ bool} --> T' --> T' --> T')
bulwahn@32667
  1477
      $ HOLogic.mk_eq (size, @{term "0 :: code_numeral"})
bulwahn@32667
  1478
      $ mk_bot compfuns (dest_predT compfuns T') $ t
bulwahn@32667
  1479
    val fun_const = mk_fun_of compfuns thy (s, T) mode
bulwahn@32667
  1480
    val eq = if use_size then
bulwahn@32667
  1481
      (list_comb (fun_const, params @ in_ts @ [size]), size_t)
bulwahn@32667
  1482
    else
bulwahn@32667
  1483
      (list_comb (fun_const, params @ in_ts), t)
bulwahn@32667
  1484
  in
bulwahn@32667
  1485
    HOLogic.mk_Trueprop (HOLogic.mk_eq eq)
bulwahn@32667
  1486
  end;
bulwahn@32667
  1487
  
bulwahn@32667
  1488
(* special setup for simpset *)                  
bulwahn@32667
  1489
val HOL_basic_ss' = HOL_basic_ss addsimps (@{thms "HOL.simp_thms"} @ [@{thm Pair_eq}])
bulwahn@32667
  1490
  setSolver (mk_solver "all_tac_solver" (fn _ => fn _ => all_tac))
bulwahn@32667
  1491
	setSolver (mk_solver "True_solver" (fn _ => rtac @{thm TrueI}))
bulwahn@32667
  1492
bulwahn@32667
  1493
(* Definition of executable functions and their intro and elim rules *)
bulwahn@32667
  1494
bulwahn@32667
  1495
fun print_arities arities = tracing ("Arities:\n" ^
bulwahn@32667
  1496
  cat_lines (map (fn (s, (ks, k)) => s ^ ": " ^
bulwahn@32667
  1497
    space_implode " -> " (map
bulwahn@32667
  1498
      (fn NONE => "X" | SOME k' => string_of_int k')
bulwahn@32667
  1499
        (ks @ [SOME k]))) arities));
bulwahn@32667
  1500
bulwahn@32667
  1501
fun create_intro_elim_rule (mode as (iss, is)) defthm mode_id funT pred thy =
bulwahn@32667
  1502
let
bulwahn@32667
  1503
  val Ts = binder_types (fastype_of pred)
bulwahn@32667
  1504
  val funtrm = Const (mode_id, funT)
bulwahn@32667
  1505
  val (Ts1, Ts2) = chop (length iss) Ts;
bulwahn@32667
  1506
  val Ts1' = map2 (fn NONE => I | SOME is => funT_of (PredicateCompFuns.compfuns) ([], is)) iss Ts1
bulwahn@32667
  1507
	val param_names = Name.variant_list []
bulwahn@32667
  1508
    (map (fn i => "x" ^ string_of_int i) (1 upto (length Ts1)));
bulwahn@32667
  1509
  val params = map Free (param_names ~~ Ts1')
bulwahn@32667
  1510
	fun mk_args (i, T) argnames =
bulwahn@32667
  1511
    let
bulwahn@32667
  1512
		  val vname = Name.variant (param_names @ argnames) ("x" ^ string_of_int (length Ts1' + i))
bulwahn@32667
  1513
		  val default = (Free (vname, T), vname :: argnames)
bulwahn@32667
  1514
	  in
bulwahn@32667
  1515
  	  case AList.lookup (op =) is i of
bulwahn@32667
  1516
						 NONE => default
bulwahn@32667
  1517
					 | SOME NONE => default
bulwahn@32667
  1518
        	 | SOME (SOME pis) =>
bulwahn@32667
  1519
					   case HOLogic.strip_tupleT T of
bulwahn@32667
  1520
						   [] => default
bulwahn@32667
  1521
					   | [_] => default
bulwahn@32667
  1522
						 | Ts => 
bulwahn@32667
  1523
						let
bulwahn@32667
  1524
							val vnames = Name.variant_list (param_names @ argnames)
bulwahn@32667
  1525
								(map (fn j => "x" ^ string_of_int (length Ts1' + i) ^ "p" ^ string_of_int j)
bulwahn@32667
  1526
									(1 upto (length Ts)))
bulwahn@32667
  1527
						 in (HOLogic.mk_tuple (map Free (vnames ~~ Ts)), vnames  @ argnames) end
bulwahn@32667
  1528
		end
bulwahn@32667
  1529
	val (args, argnames) = fold_map mk_args (1 upto (length Ts2) ~~ Ts2) []
bulwahn@32667
  1530
  val (inargs, outargs) = split_smode is args
bulwahn@32667
  1531
  val param_names' = Name.variant_list (param_names @ argnames)
bulwahn@32667
  1532
    (map (fn i => "p" ^ string_of_int i) (1 upto (length iss)))
bulwahn@32667
  1533
  val param_vs = map Free (param_names' ~~ Ts1)
bulwahn@32672
  1534
  val (params', names) = fold_map (mk_Eval_of NONE) ((params ~~ Ts1) ~~ iss) []
bulwahn@32667
  1535
  val predpropI = HOLogic.mk_Trueprop (list_comb (pred, param_vs @ args))
bulwahn@32667
  1536
  val predpropE = HOLogic.mk_Trueprop (list_comb (pred, params' @ args))
bulwahn@32667
  1537
  val param_eqs = map (HOLogic.mk_Trueprop o HOLogic.mk_eq) (param_vs ~~ params')
bulwahn@32667
  1538
  val funargs = params @ inargs
bulwahn@32667
  1539
  val funpropE = HOLogic.mk_Trueprop (PredicateCompFuns.mk_Eval (list_comb (funtrm, funargs),
bulwahn@32667
  1540
                  if null outargs then Free("y", HOLogic.unitT) else mk_tuple outargs))
bulwahn@32667
  1541
  val funpropI = HOLogic.mk_Trueprop (PredicateCompFuns.mk_Eval (list_comb (funtrm, funargs),
bulwahn@32667
  1542
                   mk_tuple outargs))
bulwahn@32667
  1543
  val introtrm = Logic.list_implies (predpropI :: param_eqs, funpropI)
bulwahn@32667
  1544
  val simprules = [defthm, @{thm eval_pred},
bulwahn@32667
  1545
	  @{thm "split_beta"}, @{thm "fst_conv"}, @{thm "snd_conv"}, @{thm pair_collapse}]
bulwahn@32667
  1546
  val unfolddef_tac = Simplifier.asm_full_simp_tac (HOL_basic_ss addsimps simprules) 1
bulwahn@32667
  1547
  val introthm = Goal.prove (ProofContext.init thy) (argnames @ param_names @ param_names' @ ["y"]) [] introtrm (fn {...} => unfolddef_tac)
bulwahn@32667
  1548
  val P = HOLogic.mk_Trueprop (Free ("P", HOLogic.boolT));
bulwahn@32667
  1549
  val elimtrm = Logic.list_implies ([funpropE, Logic.mk_implies (predpropE, P)], P)
bulwahn@32667
  1550
  val elimthm = Goal.prove (ProofContext.init thy) (argnames @ param_names @ param_names' @ ["y", "P"]) [] elimtrm (fn {...} => unfolddef_tac)
bulwahn@32667
  1551
in
bulwahn@32667
  1552
  (introthm, elimthm)
bulwahn@32667
  1553
end;
bulwahn@32667
  1554
bulwahn@32667
  1555
fun create_constname_of_mode thy prefix name mode = 
bulwahn@32667
  1556
  let
bulwahn@32667
  1557
    fun string_of_mode mode = if null mode then "0"
bulwahn@32667
  1558
      else space_implode "_" (map (fn (i, NONE) => string_of_int i | (i, SOME pis) => string_of_int i ^ "p"
bulwahn@32667
  1559
        ^ space_implode "p" (map string_of_int pis)) mode)
bulwahn@32667
  1560
    val HOmode = space_implode "_and_"
bulwahn@32667
  1561
      (fold (fn NONE => I | SOME mode => cons (string_of_mode mode)) (fst mode) [])
bulwahn@32667
  1562
  in
bulwahn@32667
  1563
    (Sign.full_bname thy (prefix ^ (Long_Name.base_name name))) ^
bulwahn@32667
  1564
      (if HOmode = "" then "_" else "_for_" ^ HOmode ^ "_yields_") ^ (string_of_mode (snd mode))
bulwahn@32667
  1565
  end;
bulwahn@32667
  1566
bulwahn@32667
  1567
fun split_tupleT is T =
bulwahn@32667
  1568
	let
bulwahn@32667
  1569
		fun split_tuple' _ _ [] = ([], [])
bulwahn@32667
  1570
			| split_tuple' is i (T::Ts) =
bulwahn@32667
  1571
			(if i mem is then apfst else apsnd) (cons T)
bulwahn@32667
  1572
				(split_tuple' is (i+1) Ts)
bulwahn@32667
  1573
	in
bulwahn@32667
  1574
	  split_tuple' is 1 (HOLogic.strip_tupleT T)
bulwahn@32667
  1575
  end
bulwahn@32667
  1576
	
bulwahn@32667
  1577
fun mk_arg xin xout pis T =
bulwahn@32667
  1578
  let
bulwahn@32667
  1579
	  val n = length (HOLogic.strip_tupleT T)
bulwahn@32667
  1580
		val ni = length pis
bulwahn@32667
  1581
	  fun mk_proj i j t =
bulwahn@32667
  1582
		  (if i = j then I else HOLogic.mk_fst)
bulwahn@32667
  1583
			  (funpow (i - 1) HOLogic.mk_snd t)
bulwahn@32667
  1584
	  fun mk_arg' i (si, so) = if i mem pis then
bulwahn@32667
  1585
		    (mk_proj si ni xin, (si+1, so))
bulwahn@32667
  1586
		  else
bulwahn@32667
  1587
			  (mk_proj so (n - ni) xout, (si, so+1))
bulwahn@32667
  1588
	  val (args, _) = fold_map mk_arg' (1 upto n) (1, 1)
bulwahn@32667
  1589
	in
bulwahn@32667
  1590
	  HOLogic.mk_tuple args
bulwahn@32667
  1591
	end
bulwahn@32667
  1592
bulwahn@32667
  1593
fun create_definitions preds (name, modes) thy =
bulwahn@32667
  1594
  let
bulwahn@32667
  1595
    val compfuns = PredicateCompFuns.compfuns
bulwahn@32667
  1596
    val T = AList.lookup (op =) preds name |> the
bulwahn@32667
  1597
    fun create_definition (mode as (iss, is)) thy = let
bulwahn@32667
  1598
      val mode_cname = create_constname_of_mode thy "" name mode
bulwahn@32667
  1599
      val mode_cbasename = Long_Name.base_name mode_cname
bulwahn@32667
  1600
      val Ts = binder_types T
bulwahn@32667
  1601
      val (Ts1, Ts2) = chop (length iss) Ts
bulwahn@32667
  1602
      val (Us1, Us2) =  split_smodeT is Ts2
bulwahn@32667
  1603
      val Ts1' = map2 (fn NONE => I | SOME is => funT_of compfuns ([], is)) iss Ts1
bulwahn@32667
  1604
      val funT = (Ts1' @ Us1) ---> (mk_predT compfuns (mk_tupleT Us2))
bulwahn@32667
  1605
      val names = Name.variant_list []
bulwahn@32667
  1606
        (map (fn i => "x" ^ string_of_int i) (1 upto (length Ts)));
bulwahn@32667
  1607
			(* old *)
bulwahn@32667
  1608
			(*
bulwahn@32667
  1609
		  val xs = map Free (names ~~ (Ts1' @ Ts2))
bulwahn@32667
  1610
      val (xparams, xargs) = chop (length iss) xs
bulwahn@32667
  1611
      val (xins, xouts) = split_smode is xargs
bulwahn@32667
  1612
			*)
bulwahn@32667
  1613
			(* new *)
bulwahn@32667
  1614
			val param_names = Name.variant_list []
bulwahn@32667
  1615
			  (map (fn i => "x" ^ string_of_int i) (1 upto (length Ts1')))
bulwahn@32667
  1616
		  val xparams = map Free (param_names ~~ Ts1')
bulwahn@32667
  1617
      fun mk_vars (i, T) names =
bulwahn@32667
  1618
			  let
bulwahn@32667
  1619
				  val vname = Name.variant names ("x" ^ string_of_int (length Ts1' + i))
bulwahn@32667
  1620
				in
bulwahn@32667
  1621
					case AList.lookup (op =) is i of
bulwahn@32667
  1622
						 NONE => ((([], [Free (vname, T)]), Free (vname, T)), vname :: names)
bulwahn@32667
  1623
					 | SOME NONE => ((([Free (vname, T)], []), Free (vname, T)), vname :: names)
bulwahn@32667
  1624
        	 | SOME (SOME pis) =>
bulwahn@32667
  1625
					   let
bulwahn@32667
  1626
						   val (Tins, Touts) = split_tupleT pis T
bulwahn@32667
  1627
							 val name_in = Name.variant names ("x" ^ string_of_int (length Ts1' + i) ^ "in")
bulwahn@32667
  1628
							 val name_out = Name.variant names ("x" ^ string_of_int (length Ts1' + i) ^ "out")
bulwahn@32667
  1629
						   val xin = Free (name_in, HOLogic.mk_tupleT Tins)
bulwahn@32667
  1630
							 val xout = Free (name_out, HOLogic.mk_tupleT Touts)
bulwahn@32667
  1631
							 val xarg = mk_arg xin xout pis T
bulwahn@32667
  1632
						 in (((if null Tins then [] else [xin], if null Touts then [] else [xout]), xarg), name_in :: name_out :: names) end
bulwahn@32669
  1633
						 end
bulwahn@32667
  1634
   	  val (xinoutargs, names) = fold_map mk_vars ((1 upto (length Ts2)) ~~ Ts2) param_names
bulwahn@32667
  1635
      val (xinout, xargs) = split_list xinoutargs
bulwahn@32667
  1636
			val (xins, xouts) = pairself flat (split_list xinout)
bulwahn@32672
  1637
			val (xparams', names') = fold_map (mk_Eval_of NONE) ((xparams ~~ Ts1) ~~ iss) names
bulwahn@32667
  1638
      fun mk_split_lambda [] t = lambda (Free (Name.variant names' "x", HOLogic.unitT)) t
bulwahn@32667
  1639
        | mk_split_lambda [x] t = lambda x t
bulwahn@32667
  1640
        | mk_split_lambda xs t =
bulwahn@32667
  1641
        let
bulwahn@32667
  1642
          fun mk_split_lambda' (x::y::[]) t = HOLogic.mk_split (lambda x (lambda y t))
bulwahn@32667
  1643
            | mk_split_lambda' (x::xs) t = HOLogic.mk_split (lambda x (mk_split_lambda' xs t))
bulwahn@32667
  1644
        in
bulwahn@32667
  1645
          mk_split_lambda' xs t
bulwahn@32667
  1646
        end;
bulwahn@32667
  1647
      val predterm = PredicateCompFuns.mk_Enum (mk_split_lambda xouts
bulwahn@32667
  1648
        (list_comb (Const (name, T), xparams' @ xargs)))
bulwahn@32667
  1649
      val lhs = list_comb (Const (mode_cname, funT), xparams @ xins)
bulwahn@32667
  1650
      val def = Logic.mk_equals (lhs, predterm)
bulwahn@32667
  1651
      val ([definition], thy') = thy |>
bulwahn@32667
  1652
        Sign.add_consts_i [(Binding.name mode_cbasename, funT, NoSyn)] |>
bulwahn@32667
  1653
        PureThy.add_defs false [((Binding.name (mode_cbasename ^ "_def"), def), [])]
bulwahn@32667
  1654
      val (intro, elim) =
bulwahn@32667
  1655
        create_intro_elim_rule mode definition mode_cname funT (Const (name, T)) thy'
bulwahn@32667
  1656
      in thy'
bulwahn@32667
  1657
			  |> add_predfun name mode (mode_cname, definition, intro, elim)
bulwahn@32667
  1658
        |> PureThy.store_thm (Binding.name (mode_cbasename ^ "I"), intro) |> snd
bulwahn@32667
  1659
        |> PureThy.store_thm (Binding.name (mode_cbasename ^ "E"), elim)  |> snd
bulwahn@32667
  1660
        |> Theory.checkpoint
bulwahn@32667
  1661
      end;
bulwahn@32667
  1662
  in
bulwahn@32667
  1663
    fold create_definition modes thy
bulwahn@32667
  1664
  end;
bulwahn@32667
  1665
bulwahn@32667
  1666
fun sizelim_create_definitions preds (name, modes) thy =
bulwahn@32667
  1667
  let
bulwahn@32667
  1668
    val T = AList.lookup (op =) preds name |> the
bulwahn@32667
  1669
    fun create_definition mode thy =
bulwahn@32667
  1670
      let
bulwahn@32667
  1671
        val mode_cname = create_constname_of_mode thy "sizelim_" name mode
bulwahn@32667
  1672
        val funT = sizelim_funT_of PredicateCompFuns.compfuns mode T
bulwahn@32667
  1673
      in
bulwahn@32667
  1674
        thy |> Sign.add_consts_i [(Binding.name (Long_Name.base_name mode_cname), funT, NoSyn)]
bulwahn@32667
  1675
        |> set_sizelim_function_name name mode mode_cname 
bulwahn@32667
  1676
      end;
bulwahn@32667
  1677
  in
bulwahn@32667
  1678
    fold create_definition modes thy
bulwahn@32667
  1679
  end;
bulwahn@32672
  1680
bulwahn@32672
  1681
fun generator_funT_of (iss, is) T =
bulwahn@32672
  1682
  let
bulwahn@32672
  1683
    val Ts = binder_types T
bulwahn@32672
  1684
    val (paramTs, (inargTs, outargTs)) = split_modeT (iss, is) Ts
bulwahn@32672
  1685
    val paramTs' = map2 (fn SOME is => sizelim_funT_of PredicateCompFuns.compfuns ([], is) | NONE => I) iss paramTs 
bulwahn@32672
  1686
  in
bulwahn@32672
  1687
    (paramTs' @ inargTs @ [@{typ "code_numeral"}]) ---> (mk_predT RPredCompFuns.compfuns (mk_tupleT outargTs))
bulwahn@32672
  1688
  end
bulwahn@32672
  1689
bulwahn@32667
  1690
fun rpred_create_definitions preds (name, modes) thy =
bulwahn@32667
  1691
  let
bulwahn@32667
  1692
    val T = AList.lookup (op =) preds name |> the
bulwahn@32667
  1693
    fun create_definition mode thy =
bulwahn@32667
  1694
      let
bulwahn@32667
  1695
        val mode_cname = create_constname_of_mode thy "gen_" name mode
bulwahn@32672
  1696
        val funT = generator_funT_of mode T
bulwahn@32667
  1697
      in
bulwahn@32667
  1698
        thy |> Sign.add_consts_i [(Binding.name (Long_Name.base_name mode_cname), funT, NoSyn)]
bulwahn@32667
  1699
        |> set_generator_name name mode mode_cname 
bulwahn@32667
  1700
      end;
bulwahn@32667
  1701
  in
bulwahn@32667
  1702
    fold create_definition modes thy
bulwahn@32667
  1703
  end;
bulwahn@32667
  1704
  
bulwahn@32667
  1705
(* Proving equivalence of term *)
bulwahn@32667
  1706
bulwahn@32667
  1707
fun is_Type (Type _) = true
bulwahn@32667
  1708
  | is_Type _ = false
bulwahn@32667
  1709
bulwahn@32667
  1710
(* returns true if t is an application of an datatype constructor *)
bulwahn@32667
  1711
(* which then consequently would be splitted *)
bulwahn@32667
  1712
(* else false *)
bulwahn@32667
  1713
fun is_constructor thy t =
bulwahn@32667
  1714
  if (is_Type (fastype_of t)) then
bulwahn@32667
  1715
    (case Datatype.get_info thy ((fst o dest_Type o fastype_of) t) of
bulwahn@32667
  1716
      NONE => false
bulwahn@32667
  1717
    | SOME info => (let
bulwahn@32667
  1718
      val constr_consts = maps (fn (_, (_, _, constrs)) => map fst constrs) (#descr info)
bulwahn@32667
  1719
      val (c, _) = strip_comb t
bulwahn@32667
  1720
      in (case c of
bulwahn@32667
  1721
        Const (name, _) => name mem_string constr_consts
bulwahn@32667
  1722
        | _ => false) end))
bulwahn@32667
  1723
  else false
bulwahn@32667
  1724
bulwahn@32667
  1725
(* MAJOR FIXME:  prove_params should be simple
bulwahn@32667
  1726
 - different form of introrule for parameters ? *)
bulwahn@32667
  1727
fun prove_param thy (NONE, t) = TRY (rtac @{thm refl} 1)
bulwahn@32667
  1728
  | prove_param thy (m as SOME (Mode (mode, is, ms)), t) =
bulwahn@32667
  1729
  let
bulwahn@32667
  1730
    val  (f, args) = strip_comb (Envir.eta_contract t)
bulwahn@32667
  1731
    val (params, _) = chop (length ms) args
bulwahn@32667
  1732
    val f_tac = case f of
bulwahn@32667
  1733
      Const (name, T) => simp_tac (HOL_basic_ss addsimps 
bulwahn@32667
  1734
         ([@{thm eval_pred}, (predfun_definition_of thy name mode),
bulwahn@32667
  1735
         @{thm "split_eta"}, @{thm "split_beta"}, @{thm "fst_conv"},
bulwahn@32667
  1736
				 @{thm "snd_conv"}, @{thm pair_collapse}, @{thm "Product_Type.split_conv"}])) 1
bulwahn@32667
  1737
    | Free _ => TRY (rtac @{thm refl} 1)
bulwahn@32667
  1738
    | Abs _ => error "prove_param: No valid parameter term"
bulwahn@32667
  1739
  in
bulwahn@32667
  1740
    REPEAT_DETERM (etac @{thm thin_rl} 1)
bulwahn@32667
  1741
    THEN REPEAT_DETERM (rtac @{thm ext} 1)
bulwahn@32667
  1742
    THEN print_tac "prove_param"
bulwahn@32667
  1743
    THEN f_tac
bulwahn@32667
  1744
    THEN print_tac "after simplification in prove_args"
bulwahn@32667
  1745
    THEN (EVERY (map (prove_param thy) (ms ~~ params)))
bulwahn@32667
  1746
    THEN (REPEAT_DETERM (atac 1))
bulwahn@32667
  1747
  end
bulwahn@32667
  1748
bulwahn@32667
  1749
fun prove_expr thy (Mode (mode, is, ms), t, us) (premposition : int) =
bulwahn@32667
  1750
  case strip_comb t of
bulwahn@32667
  1751
    (Const (name, T), args) =>  
bulwahn@32667
  1752
      let
bulwahn@32667
  1753
        val introrule = predfun_intro_of thy name mode
bulwahn@32667
  1754
        val (args1, args2) = chop (length ms) args
bulwahn@32667
  1755
      in
bulwahn@32667
  1756
        rtac @{thm bindI} 1
bulwahn@32667
  1757
        THEN print_tac "before intro rule:"
bulwahn@32667
  1758
        (* for the right assumption in first position *)
bulwahn@32667
  1759
        THEN rotate_tac premposition 1
bulwahn@32667
  1760
        THEN debug_tac (Display.string_of_thm (ProofContext.init thy) introrule)
bulwahn@32667
  1761
        THEN rtac introrule 1
bulwahn@32667
  1762
        THEN print_tac "after intro rule"
bulwahn@32667
  1763
        (* work with parameter arguments *)
bulwahn@32667
  1764
        THEN (atac 1)
bulwahn@32667
  1765
        THEN (print_tac "parameter goal")
bulwahn@32667
  1766
        THEN (EVERY (map (prove_param thy) (ms ~~ args1)))
bulwahn@32667
  1767
        THEN (REPEAT_DETERM (atac 1))
bulwahn@32667
  1768
      end
bulwahn@32667
  1769
  | _ => rtac @{thm bindI} 1
bulwahn@32667
  1770
	  THEN asm_full_simp_tac
bulwahn@32667
  1771
		  (HOL_basic_ss' addsimps [@{thm "split_eta"}, @{thm "split_beta"}, @{thm "fst_conv"},
bulwahn@32667
  1772
				 @{thm "snd_conv"}, @{thm pair_collapse}]) 1
bulwahn@32667
  1773
	  THEN (atac 1)
bulwahn@32667
  1774
	  THEN print_tac "after prove parameter call"
bulwahn@32667
  1775
		
bulwahn@32667
  1776
bulwahn@32667
  1777
fun SOLVED tac st = FILTER (fn st' => nprems_of st' = nprems_of st - 1) tac st; 
bulwahn@32667
  1778
bulwahn@32667
  1779
fun SOLVEDALL tac st = FILTER (fn st' => nprems_of st' = 0) tac st
bulwahn@32667
  1780
bulwahn@32667
  1781
fun prove_match thy (out_ts : term list) = let
bulwahn@32667
  1782
  fun get_case_rewrite t =
bulwahn@32667
  1783
    if (is_constructor thy t) then let
bulwahn@32667
  1784
      val case_rewrites = (#case_rewrites (Datatype.the_info thy
bulwahn@32667
  1785
        ((fst o dest_Type o fastype_of) t)))
wenzelm@32952
  1786
      in case_rewrites @ maps get_case_rewrite (snd (strip_comb t)) end
bulwahn@32667
  1787
    else []
wenzelm@32952
  1788
  val simprules = @{thm "unit.cases"} :: @{thm "prod.cases"} :: maps get_case_rewrite out_ts
bulwahn@32667
  1789
(* replace TRY by determining if it necessary - are there equations when calling compile match? *)
bulwahn@32667
  1790
in
bulwahn@32667
  1791
   (* make this simpset better! *)
bulwahn@32667
  1792
  asm_full_simp_tac (HOL_basic_ss' addsimps simprules) 1
bulwahn@32667
  1793
  THEN print_tac "after prove_match:"
bulwahn@32667
  1794
  THEN (DETERM (TRY (EqSubst.eqsubst_tac (ProofContext.init thy) [0] [@{thm "HOL.if_P"}] 1
bulwahn@32667
  1795
         THEN (REPEAT_DETERM (rtac @{thm conjI} 1 THEN (SOLVED (asm_simp_tac HOL_basic_ss 1))))
bulwahn@32667
  1796
         THEN (SOLVED (asm_simp_tac HOL_basic_ss 1)))))
bulwahn@32667
  1797
  THEN print_tac "after if simplification"
bulwahn@32667
  1798
end;
bulwahn@32667
  1799
bulwahn@32667
  1800
(* corresponds to compile_fun -- maybe call that also compile_sidecond? *)
bulwahn@32667
  1801
bulwahn@32667
  1802
fun prove_sidecond thy modes t =
bulwahn@32667
  1803
  let
bulwahn@32667
  1804
    fun preds_of t nameTs = case strip_comb t of 
bulwahn@32667
  1805
      (f as Const (name, T), args) =>
bulwahn@32667
  1806
        if AList.defined (op =) modes name then (name, T) :: nameTs
bulwahn@32667
  1807
          else fold preds_of args nameTs
bulwahn@32667
  1808
      | _ => nameTs
bulwahn@32667
  1809
    val preds = preds_of t []
bulwahn@32667
  1810
    val defs = map
bulwahn@32667
  1811
      (fn (pred, T) => predfun_definition_of thy pred
bulwahn@32667
  1812
        ([], map (rpair NONE) (1 upto (length (binder_types T)))))
bulwahn@32667
  1813
        preds
bulwahn@32667
  1814
  in 
bulwahn@32667
  1815
    (* remove not_False_eq_True when simpset in prove_match is better *)
bulwahn@32667
  1816
    simp_tac (HOL_basic_ss addsimps
bulwahn@32667
  1817
      (@{thms "HOL.simp_thms"} @ (@{thm not_False_eq_True} :: @{thm eval_pred} :: defs))) 1 
bulwahn@32667
  1818
    (* need better control here! *)
bulwahn@32667
  1819
  end
bulwahn@32667
  1820
bulwahn@32667
  1821
fun prove_clause thy nargs modes (iss, is) (_, clauses) (ts, moded_ps) =
bulwahn@32667
  1822
  let
bulwahn@32667
  1823
    val (in_ts, clause_out_ts) = split_smode is ts;
bulwahn@32667
  1824
    fun prove_prems out_ts [] =
bulwahn@32667
  1825
      (prove_match thy out_ts)
bulwahn@32667
  1826
			THEN print_tac "before simplifying assumptions"
bulwahn@32667
  1827
      THEN asm_full_simp_tac HOL_basic_ss' 1
bulwahn@32667
  1828
			THEN print_tac "before single intro rule"
bulwahn@32667
  1829
      THEN (rtac (if null clause_out_ts then @{thm singleI_unit} else @{thm singleI}) 1)
bulwahn@32667
  1830
    | prove_prems out_ts ((p, mode as Mode ((iss, is), _, param_modes)) :: ps) =
bulwahn@32667
  1831
      let
bulwahn@32667
  1832
        val premposition = (find_index (equal p) clauses) + nargs
bulwahn@32667
  1833
        val rest_tac = (case p of Prem (us, t) =>
bulwahn@32667
  1834
            let
bulwahn@32667
  1835
              val (_, out_ts''') = split_smode is us
bulwahn@32667
  1836
              val rec_tac = prove_prems out_ts''' ps
bulwahn@32667
  1837
            in
bulwahn@32667
  1838
              print_tac "before clause:"
bulwahn@32667
  1839
              THEN asm_simp_tac HOL_basic_ss 1
bulwahn@32667
  1840
              THEN print_tac "before prove_expr:"
bulwahn@32667
  1841
              THEN prove_expr thy (mode, t, us) premposition
bulwahn@32667
  1842
              THEN print_tac "after prove_expr:"
bulwahn@32667
  1843
              THEN rec_tac
bulwahn@32667
  1844
            end
bulwahn@32667
  1845
          | Negprem (us, t) =>
bulwahn@32667
  1846
            let
bulwahn@32667
  1847
              val (_, out_ts''') = split_smode is us
bulwahn@32667
  1848
              val rec_tac = prove_prems out_ts''' ps
bulwahn@32667
  1849
              val name = (case strip_comb t of (Const (c, _), _) => SOME c | _ => NONE)
bulwahn@32667
  1850
              val (_, params) = strip_comb t
bulwahn@32667
  1851
            in
bulwahn@32667
  1852
              rtac @{thm bindI} 1
bulwahn@32667
  1853
              THEN (if (is_some name) then
bulwahn@32667
  1854
                  simp_tac (HOL_basic_ss addsimps [predfun_definition_of thy (the name) (iss, is)]) 1
bulwahn@32667
  1855
                  THEN rtac @{thm not_predI} 1
bulwahn@32667
  1856
                  THEN simp_tac (HOL_basic_ss addsimps [@{thm not_False_eq_True}]) 1
bulwahn@32667
  1857
                  THEN (REPEAT_DETERM (atac 1))
bulwahn@32667
  1858
                  (* FIXME: work with parameter arguments *)
bulwahn@32667
  1859
                  THEN (EVERY (map (prove_param thy) (param_modes ~~ params)))
bulwahn@32667
  1860
                else
bulwahn@32667
  1861
                  rtac @{thm not_predI'} 1)
bulwahn@32667
  1862
                  THEN simp_tac (HOL_basic_ss addsimps [@{thm not_False_eq_True}]) 1
bulwahn@32667
  1863
              THEN rec_tac
bulwahn@32667
  1864
            end
bulwahn@32667
  1865
          | Sidecond t =>
bulwahn@32667
  1866
           rtac @{thm bindI} 1
bulwahn@32667
  1867
           THEN rtac @{thm if_predI} 1
bulwahn@32667
  1868
           THEN print_tac "before sidecond:"
bulwahn@32667
  1869
           THEN prove_sidecond thy modes t
bulwahn@32667
  1870
           THEN print_tac "after sidecond:"
bulwahn@32667
  1871
           THEN prove_prems [] ps)
bulwahn@32667
  1872
      in (prove_match thy out_ts)
bulwahn@32667
  1873
          THEN rest_tac
bulwahn@32667
  1874
      end;
bulwahn@32667
  1875
    val prems_tac = prove_prems in_ts moded_ps
bulwahn@32667
  1876
  in
bulwahn@32667
  1877
    rtac @{thm bindI} 1
bulwahn@32667
  1878
    THEN rtac @{thm singleI} 1
bulwahn@32667
  1879
    THEN prems_tac
bulwahn@32667
  1880
  end;
bulwahn@32667
  1881
bulwahn@32667
  1882
fun select_sup 1 1 = []
bulwahn@32667
  1883
  | select_sup _ 1 = [rtac @{thm supI1}]
bulwahn@32667
  1884
  | select_sup n i = (rtac @{thm supI2})::(select_sup (n - 1) (i - 1));
bulwahn@32667
  1885
bulwahn@32667
  1886
fun prove_one_direction thy clauses preds modes pred mode moded_clauses =
bulwahn@32667
  1887
  let
bulwahn@32667
  1888
    val T = the (AList.lookup (op =) preds pred)
bulwahn@32667
  1889
    val nargs = length (binder_types T) - nparams_of thy pred
bulwahn@32667
  1890
    val pred_case_rule = the_elim_of thy pred
bulwahn@32667
  1891
  in
bulwahn@32667
  1892
    REPEAT_DETERM (CHANGED (rewtac @{thm "split_paired_all"}))
bulwahn@32667
  1893
		THEN print_tac "before applying elim rule"
bulwahn@32667
  1894
    THEN etac (predfun_elim_of thy pred mode) 1
bulwahn@32667
  1895
    THEN etac pred_case_rule 1
bulwahn@32667
  1896
    THEN (EVERY (map
bulwahn@32667
  1897
           (fn i => EVERY' (select_sup (length moded_clauses) i) i) 
bulwahn@32667
  1898
             (1 upto (length moded_clauses))))
bulwahn@32667
  1899
    THEN (EVERY (map2 (prove_clause thy nargs modes mode) clauses moded_clauses))
bulwahn@32667
  1900
    THEN print_tac "proved one direction"
bulwahn@32667
  1901
  end;
bulwahn@32667
  1902
bulwahn@32667
  1903
(** Proof in the other direction **)
bulwahn@32667
  1904
bulwahn@32667
  1905
fun prove_match2 thy out_ts = let
bulwahn@32667
  1906
  fun split_term_tac (Free _) = all_tac
bulwahn@32667
  1907
    | split_term_tac t =
bulwahn@32667
  1908
      if (is_constructor thy t) then let
bulwahn@32667
  1909
        val info = Datatype.the_info thy ((fst o dest_Type o fastype_of) t)
bulwahn@32667
  1910
        val num_of_constrs = length (#case_rewrites info)
bulwahn@32667
  1911
        (* special treatment of pairs -- because of fishing *)
bulwahn@32667
  1912
        val split_rules = case (fst o dest_Type o fastype_of) t of
bulwahn@32667
  1913
          "*" => [@{thm prod.split_asm}] 
bulwahn@32667
  1914
          | _ => PureThy.get_thms thy (((fst o dest_Type o fastype_of) t) ^ ".split_asm")
bulwahn@32667
  1915
        val (_, ts) = strip_comb t
bulwahn@32667
  1916
      in
bulwahn@32667
  1917
        (Splitter.split_asm_tac split_rules 1)
bulwahn@32667
  1918
(*        THEN (Simplifier.asm_full_simp_tac HOL_basic_ss 1)
bulwahn@32667
  1919
          THEN (DETERM (TRY (etac @{thm Pair_inject} 1))) *)
bulwahn@32667
  1920
        THEN (REPEAT_DETERM_N (num_of_constrs - 1) (etac @{thm botE} 1 ORELSE etac @{thm botE} 2))
bulwahn@32667
  1921
        THEN (EVERY (map split_term_tac ts))
bulwahn@32667
  1922
      end
bulwahn@32667
  1923
    else all_tac
bulwahn@32667
  1924
  in
bulwahn@32667
  1925
    split_term_tac (mk_tuple out_ts)
bulwahn@32667
  1926
    THEN (DETERM (TRY ((Splitter.split_asm_tac [@{thm "split_if_asm"}] 1) THEN (etac @{thm botE} 2))))
bulwahn@32667
  1927
  end
bulwahn@32667
  1928
bulwahn@32667
  1929
(* VERY LARGE SIMILIRATIY to function prove_param 
bulwahn@32667
  1930
-- join both functions
bulwahn@32667
  1931
*)
bulwahn@32667
  1932
(* TODO: remove function *)
bulwahn@32667
  1933
bulwahn@32667
  1934
fun prove_param2 thy (NONE, t) = all_tac 
bulwahn@32667
  1935
  | prove_param2 thy (m as SOME (Mode (mode, is, ms)), t) = let
bulwahn@32667
  1936
    val  (f, args) = strip_comb (Envir.eta_contract t)
bulwahn@32667
  1937
    val (params, _) = chop (length ms) args
bulwahn@32667
  1938
    val f_tac = case f of
bulwahn@32667
  1939
        Const (name, T) => full_simp_tac (HOL_basic_ss addsimps 
bulwahn@32667
  1940
           (@{thm eval_pred}::(predfun_definition_of thy name mode)
bulwahn@32667
  1941
           :: @{thm "Product_Type.split_conv"}::[])) 1
bulwahn@32667
  1942
      | Free _ => all_tac
bulwahn@32667
  1943
      | _ => error "prove_param2: illegal parameter term"
bulwahn@32667
  1944
  in  
bulwahn@32667
  1945
    print_tac "before simplification in prove_args:"
bulwahn@32667
  1946
    THEN f_tac
bulwahn@32667
  1947
    THEN print_tac "after simplification in prove_args"
bulwahn@32667
  1948
    THEN (EVERY (map (prove_param2 thy) (ms ~~ params)))
bulwahn@32667
  1949
  end
bulwahn@32667
  1950
bulwahn@32667
  1951
bulwahn@32667
  1952
fun prove_expr2 thy (Mode (mode, is, ms), t) = 
bulwahn@32667
  1953
  (case strip_comb t of
bulwahn@32667
  1954
    (Const (name, T), args) =>
bulwahn@32667
  1955
      etac @{thm bindE} 1
bulwahn@32667
  1956
      THEN (REPEAT_DETERM (CHANGED (rewtac @{thm "split_paired_all"})))
bulwahn@32667
  1957
      THEN print_tac "prove_expr2-before"
bulwahn@32667
  1958
      THEN (debug_tac (Syntax.string_of_term_global thy
bulwahn@32667
  1959
        (prop_of (predfun_elim_of thy name mode))))
bulwahn@32667
  1960
      THEN (etac (predfun_elim_of thy name mode) 1)
bulwahn@32667
  1961
      THEN print_tac "prove_expr2"
bulwahn@32667
  1962
      THEN (EVERY (map (prove_param2 thy) (ms ~~ args)))
bulwahn@32667
  1963
      THEN print_tac "finished prove_expr2"      
bulwahn@32667
  1964
    | _ => etac @{thm bindE} 1)
bulwahn@32667
  1965
    
bulwahn@32667
  1966
(* FIXME: what is this for? *)
bulwahn@32667
  1967
(* replace defined by has_mode thy pred *)
bulwahn@32667
  1968
(* TODO: rewrite function *)
bulwahn@32667
  1969
fun prove_sidecond2 thy modes t = let
bulwahn@32667
  1970
  fun preds_of t nameTs = case strip_comb t of 
bulwahn@32667
  1971
    (f as Const (name, T), args) =>
bulwahn@32667
  1972
      if AList.defined (op =) modes name then (name, T) :: nameTs
bulwahn@32667
  1973
        else fold preds_of args nameTs
bulwahn@32667
  1974
    | _ => nameTs
bulwahn@32667
  1975
  val preds = preds_of t []
bulwahn@32667
  1976
  val defs = map
bulwahn@32667
  1977
    (fn (pred, T) => predfun_definition_of thy pred 
bulwahn@32667
  1978
      ([], map (rpair NONE) (1 upto (length (binder_types T)))))
bulwahn@32667
  1979
      preds
bulwahn@32667
  1980
  in
bulwahn@32667
  1981
   (* only simplify the one assumption *)
bulwahn@32667
  1982
   full_simp_tac (HOL_basic_ss' addsimps @{thm eval_pred} :: defs) 1 
bulwahn@32667
  1983
   (* need better control here! *)
bulwahn@32667
  1984
   THEN print_tac "after sidecond2 simplification"
bulwahn@32667
  1985
   end
bulwahn@32667
  1986
  
bulwahn@32667
  1987
fun prove_clause2 thy modes pred (iss, is) (ts, ps) i =
bulwahn@32667
  1988
  let
bulwahn@32667
  1989
    val pred_intro_rule = nth (intros_of thy pred) (i - 1)
bulwahn@32667
  1990
    val (in_ts, clause_out_ts) = split_smode is ts;
bulwahn@32667
  1991
    fun prove_prems2 out_ts [] =
bulwahn@32667
  1992
      print_tac "before prove_match2 - last call:"
bulwahn@32667
  1993
      THEN prove_match2 thy out_ts
bulwahn@32667
  1994
      THEN print_tac "after prove_match2 - last call:"
bulwahn@32667
  1995
      THEN (etac @{thm singleE} 1)
bulwahn@32667
  1996
      THEN (REPEAT_DETERM (etac @{thm Pair_inject} 1))
bulwahn@32667
  1997
      THEN (asm_full_simp_tac HOL_basic_ss' 1)
bulwahn@32667
  1998
      THEN (REPEAT_DETERM (etac @{thm Pair_inject} 1))
bulwahn@32667
  1999
      THEN (asm_full_simp_tac HOL_basic_ss' 1)
bulwahn@32667
  2000
      THEN SOLVED (print_tac "state before applying intro rule:"
bulwahn@32667
  2001
      THEN (rtac pred_intro_rule 1)
bulwahn@32667
  2002
      (* How to handle equality correctly? *)
bulwahn@32667
  2003
      THEN (print_tac "state before assumption matching")
bulwahn@32667
  2004
      THEN (REPEAT (atac 1 ORELSE 
bulwahn@32667
  2005
         (CHANGED (asm_full_simp_tac (HOL_basic_ss' addsimps
bulwahn@32667
  2006
					 [@{thm split_eta}, @{thm "split_beta"}, @{thm "fst_conv"}, @{thm "snd_conv"}, @{thm pair_collapse}]) 1)
bulwahn@32667
  2007
          THEN print_tac "state after simp_tac:"))))
bulwahn@32667
  2008
    | prove_prems2 out_ts ((p, mode as Mode ((iss, is), _, param_modes)) :: ps) =
bulwahn@32667
  2009
      let
bulwahn@32667
  2010
        val rest_tac = (case p of
bulwahn@32667
  2011
          Prem (us, t) =>
bulwahn@32667
  2012
          let
bulwahn@32667
  2013
            val (_, out_ts''') = split_smode is us
bulwahn@32667
  2014
            val rec_tac = prove_prems2 out_ts''' ps
bulwahn@32667
  2015
          in
bulwahn@32667
  2016
            (prove_expr2 thy (mode, t)) THEN rec_tac
bulwahn@32667
  2017
          end
bulwahn@32667
  2018
        | Negprem (us, t) =>
bulwahn@32667
  2019
          let
bulwahn@32667
  2020
            val (_, out_ts''') = split_smode is us
bulwahn@32667
  2021
            val rec_tac = prove_prems2 out_ts''' ps
bulwahn@32667
  2022
            val name = (case strip_comb t of (Const (c, _), _) => SOME c | _ => NONE)
bulwahn@32667
  2023
            val (_, params) = strip_comb t
bulwahn@32667
  2024
          in
bulwahn@32667
  2025
            print_tac "before neg prem 2"
bulwahn@32667
  2026
            THEN etac @{thm bindE} 1
bulwahn@32667
  2027
            THEN (if is_some name then
bulwahn@32667
  2028
                full_simp_tac (HOL_basic_ss addsimps [predfun_definition_of thy (the name) (iss, is)]) 1 
bulwahn@32667
  2029
                THEN etac @{thm not_predE} 1
bulwahn@32667
  2030
                THEN simp_tac (HOL_basic_ss addsimps [@{thm not_False_eq_True}]) 1
bulwahn@32667
  2031
                THEN (EVERY (map (prove_param2 thy) (param_modes ~~ params)))
bulwahn@32667
  2032
              else
bulwahn@32667
  2033
                etac @{thm not_predE'} 1)
bulwahn@32667
  2034
            THEN rec_tac
bulwahn@32667
  2035
          end 
bulwahn@32667
  2036
        | Sidecond t =>
bulwahn@32667
  2037
          etac @{thm bindE} 1
bulwahn@32667
  2038
          THEN etac @{thm if_predE} 1
bulwahn@32667
  2039
          THEN prove_sidecond2 thy modes t 
bulwahn@32667
  2040
          THEN prove_prems2 [] ps)
bulwahn@32667
  2041
      in print_tac "before prove_match2:"
bulwahn@32667
  2042
         THEN prove_match2 thy out_ts
bulwahn@32667
  2043
         THEN print_tac "after prove_match2:"
bulwahn@32667
  2044
         THEN rest_tac
bulwahn@32667
  2045
      end;
bulwahn@32667
  2046
    val prems_tac = prove_prems2 in_ts ps 
bulwahn@32667
  2047
  in
bulwahn@32667
  2048
    print_tac "starting prove_clause2"
bulwahn@32667
  2049
    THEN etac @{thm bindE} 1
bulwahn@32667
  2050
    THEN (etac @{thm singleE'} 1)
bulwahn@32667
  2051
    THEN (TRY (etac @{thm Pair_inject} 1))
bulwahn@32667
  2052
    THEN print_tac "after singleE':"
bulwahn@32667
  2053
    THEN prems_tac
bulwahn@32667
  2054
  end;
bulwahn@32667
  2055
 
bulwahn@32667
  2056
fun prove_other_direction thy modes pred mode moded_clauses =
bulwahn@32667
  2057
  let
bulwahn@32667
  2058
    fun prove_clause clause i =
bulwahn@32667
  2059
      (if i < length moded_clauses then etac @{thm supE} 1 else all_tac)
bulwahn@32667
  2060
      THEN (prove_clause2 thy modes pred mode clause i)
bulwahn@32667
  2061
  in
bulwahn@32667
  2062
    (DETERM (TRY (rtac @{thm unit.induct} 1)))
bulwahn@32667
  2063
     THEN (REPEAT_DETERM (CHANGED (rewtac @{thm split_paired_all})))
bulwahn@32667
  2064
     THEN (rtac (predfun_intro_of thy pred mode) 1)
bulwahn@32667
  2065
     THEN (REPEAT_DETERM (rtac @{thm refl} 2))
bulwahn@32667
  2066
     THEN (EVERY (map2 prove_clause moded_clauses (1 upto (length moded_clauses))))
bulwahn@32667
  2067
  end;
bulwahn@32667
  2068
bulwahn@32667
  2069
(** proof procedure **)
bulwahn@32667
  2070
bulwahn@32667
  2071
fun prove_pred thy clauses preds modes pred mode (moded_clauses, compiled_term) =
bulwahn@32667
  2072
  let
bulwahn@32667
  2073
    val ctxt = ProofContext.init thy
bulwahn@32667
  2074
    val clauses = the (AList.lookup (op =) clauses pred)
bulwahn@32667
  2075
  in
bulwahn@32667
  2076
    Goal.prove ctxt (Term.add_free_names compiled_term []) [] compiled_term
bulwahn@32667
  2077
      (if !do_proofs then
bulwahn@32667
  2078
        (fn _ =>
bulwahn@32667
  2079
        rtac @{thm pred_iffI} 1
wenzelm@32966
  2080
        THEN print_tac "after pred_iffI"
bulwahn@32667
  2081
        THEN prove_one_direction thy clauses preds modes pred mode moded_clauses
bulwahn@32667
  2082
        THEN print_tac "proved one direction"
bulwahn@32667
  2083
        THEN prove_other_direction thy modes pred mode moded_clauses
bulwahn@32667
  2084
        THEN print_tac "proved other direction")
wenzelm@32970
  2085
      else fn _ => Skip_Proof.cheat_tac thy)
bulwahn@32667
  2086
  end;
bulwahn@32667
  2087
bulwahn@32667
  2088
(* composition of mode inference, definition, compilation and proof *)
bulwahn@32667
  2089
bulwahn@32667
  2090
(** auxillary combinators for table of preds and modes **)
bulwahn@32667
  2091
bulwahn@32667
  2092
fun map_preds_modes f preds_modes_table =
bulwahn@32667
  2093
  map (fn (pred, modes) =>
bulwahn@32667
  2094
    (pred, map (fn (mode, value) => (mode, f pred mode value)) modes)) preds_modes_table
bulwahn@32667
  2095
bulwahn@32667
  2096
fun join_preds_modes table1 table2 =
bulwahn@32667
  2097
  map_preds_modes (fn pred => fn mode => fn value =>
bulwahn@32667
  2098
    (value, the (AList.lookup (op =) (the (AList.lookup (op =) table2 pred)) mode))) table1
bulwahn@32667
  2099
    
bulwahn@32667
  2100
fun maps_modes preds_modes_table =
bulwahn@32667
  2101
  map (fn (pred, modes) =>
bulwahn@32667
  2102
    (pred, map (fn (mode, value) => value) modes)) preds_modes_table  
bulwahn@32667
  2103
    
bulwahn@32667
  2104
fun compile_preds compfuns mk_fun_of use_size thy all_vs param_vs preds moded_clauses =
bulwahn@32667
  2105
  map_preds_modes (fn pred => compile_pred compfuns mk_fun_of use_size thy all_vs param_vs pred
bulwahn@32667
  2106
      (the (AList.lookup (op =) preds pred))) moded_clauses  
bulwahn@32667
  2107
  
bulwahn@32667
  2108
fun prove thy clauses preds modes moded_clauses compiled_terms =
bulwahn@32667
  2109
  map_preds_modes (prove_pred thy clauses preds modes)
bulwahn@32667
  2110
    (join_preds_modes moded_clauses compiled_terms)
bulwahn@32667
  2111
bulwahn@32667
  2112
fun prove_by_skip thy _ _ _ _ compiled_terms =
wenzelm@32970
  2113
  map_preds_modes (fn pred => fn mode => fn t => Drule.standard (Skip_Proof.make_thm thy t))
bulwahn@32667
  2114
    compiled_terms
bulwahn@32667
  2115
    
bulwahn@32667
  2116
fun prepare_intrs thy prednames =
bulwahn@32667
  2117
  let
bulwahn@32667
  2118
    val intrs = maps (intros_of thy) prednames
bulwahn@32667
  2119
      |> map (Logic.unvarify o prop_of)
bulwahn@32667
  2120
    val nparams = nparams_of thy (hd prednames)
bulwahn@32667
  2121
    val extra_modes = all_modes_of thy |> filter_out (fn (name, _) => member (op =) prednames name)
bulwahn@32667
  2122
    val preds = distinct (op =) (map (dest_Const o fst o (strip_intro_concl nparams)) intrs)
bulwahn@32667
  2123
    val _ $ u = Logic.strip_imp_concl (hd intrs);
bulwahn@32667
  2124
    val params = List.take (snd (strip_comb u), nparams);
bulwahn@32667
  2125
    val param_vs = maps term_vs params
bulwahn@32667
  2126
    val all_vs = terms_vs intrs
bulwahn@32667
  2127
    fun dest_prem t =
bulwahn@32667
  2128
      (case strip_comb t of
bulwahn@32667
  2129
        (v as Free _, ts) => if v mem params then Prem (ts, v) else Sidecond t
bulwahn@32667
  2130
      | (c as Const (@{const_name Not}, _), [t]) => (case dest_prem t of          
bulwahn@32667
  2131
          Prem (ts, t) => Negprem (ts, t)
bulwahn@32667
  2132
        | Negprem _ => error ("Double negation not allowed in premise: " ^ (Syntax.string_of_term_global thy (c $ t))) 
bulwahn@32667
  2133
        | Sidecond t => Sidecond (c $ t))
bulwahn@32667
  2134
      | (c as Const (s, _), ts) =>
bulwahn@32667
  2135
        if is_registered thy s then
bulwahn@32667
  2136
          let val (ts1, ts2) = chop (nparams_of thy s) ts
bulwahn@32667
  2137
          in Prem (ts2, list_comb (c, ts1)) end
bulwahn@32667
  2138
        else Sidecond t
bulwahn@32667
  2139
      | _ => Sidecond t)
bulwahn@32667
  2140
    fun add_clause intr (clauses, arities) =
bulwahn@32667
  2141
    let
bulwahn@32667
  2142
      val _ $ t = Logic.strip_imp_concl intr;
bulwahn@32667
  2143
      val (Const (name, T), ts) = strip_comb t;
bulwahn@32667
  2144
      val (ts1, ts2) = chop nparams ts;
bulwahn@32667
  2145
      val prems = map (dest_prem o HOLogic.dest_Trueprop) (Logic.strip_imp_prems intr);
bulwahn@32667
  2146
      val (Ts, Us) = chop nparams (binder_types T)
bulwahn@32667
  2147
    in
bulwahn@32667
  2148
      (AList.update op = (name, these (AList.lookup op = clauses name) @
bulwahn@32667
  2149
        [(ts2, prems)]) clauses,
bulwahn@32667
  2150
       AList.update op = (name, (map (fn U => (case strip_type U of
bulwahn@32667
  2151
                 (Rs as _ :: _, Type ("bool", [])) => SOME (length Rs)
bulwahn@32667
  2152
               | _ => NONE)) Ts,
bulwahn@32667
  2153
             length Us)) arities)
bulwahn@32667
  2154
    end;
bulwahn@32667
  2155
    val (clauses, arities) = fold add_clause intrs ([], []);
bulwahn@32667
  2156
    fun modes_of_arities arities =
bulwahn@32667
  2157
      (map (fn (s, (ks, k)) => (s, cprod (cprods (map
bulwahn@32667
  2158
            (fn NONE => [NONE]
bulwahn@32667
  2159
              | SOME k' => map SOME (map (map (rpair NONE)) (subsets 1 k'))) ks),
bulwahn@32667
  2160
       map (map (rpair NONE)) (subsets 1 k)))) arities)
bulwahn@32667
  2161
    fun modes_of_typ T =
bulwahn@32667
  2162
      let
bulwahn@32667
  2163
        val (Ts, Us) = chop nparams (binder_types T)
bulwahn@32667
  2164
        fun all_smodes_of_typs Ts = cprods_subset (
bulwahn@32667
  2165
          map_index (fn (i, U) =>
bulwahn@32667
  2166
            case HOLogic.strip_tupleT U of
bulwahn@32667
  2167
              [] => [(i + 1, NONE)]
bulwahn@32667
  2168
            | [U] => [(i + 1, NONE)]
bulwahn@32668
  2169
            | Us =>  (i + 1, NONE) ::
bulwahn@32668
  2170
              (map (pair (i + 1) o SOME) ((subsets 1 (length Us)) \\ [[], 1 upto (length Us)])))
bulwahn@32667
  2171
          Ts)
bulwahn@32667
  2172
      in
bulwahn@32667
  2173
        cprod (cprods (map (fn T => case strip_type T of
bulwahn@32667
  2174
          (Rs as _ :: _, Type ("bool", [])) => map SOME (all_smodes_of_typs Rs) | _ => [NONE]) Ts),
bulwahn@32667
  2175
           all_smodes_of_typs Us)
bulwahn@32667
  2176
      end
bulwahn@32667
  2177
    val all_modes = map (fn (s, T) => (s, modes_of_typ T)) preds
bulwahn@32667
  2178
  in (preds, nparams, all_vs, param_vs, extra_modes, clauses, all_modes) end;
bulwahn@32667
  2179
bulwahn@32667
  2180
(** main function of predicate compiler **)
bulwahn@32667
  2181
bulwahn@32667
  2182
fun add_equations_of steps prednames thy =
bulwahn@32667
  2183
  let
wenzelm@32950
  2184
    val _ = tracing ("Starting predicate compiler for predicates " ^ commas prednames ^ "...")
wenzelm@32950
  2185
    val _ = tracing (commas (map (Display.string_of_thm_global thy) (maps (intros_of thy) prednames)))
bulwahn@32667
  2186
    val (preds, nparams, all_vs, param_vs, extra_modes, clauses, all_modes) =
bulwahn@32667
  2187
      prepare_intrs thy prednames
wenzelm@32950
  2188
    val _ = tracing "Infering modes..."
bulwahn@32667
  2189
    val moded_clauses = #infer_modes steps thy extra_modes all_modes param_vs clauses 
bulwahn@32667
  2190
    val modes = map (fn (p, mps) => (p, map fst mps)) moded_clauses
bulwahn@32667
  2191
    val _ = print_modes modes
bulwahn@32667
  2192
    val _ = print_moded_clauses thy moded_clauses
wenzelm@32950
  2193
    val _ = tracing "Defining executable functions..."
bulwahn@32667
  2194
    val thy' = fold (#create_definitions steps preds) modes thy
bulwahn@32667
  2195
      |> Theory.checkpoint
wenzelm@32950
  2196
    val _ = tracing "Compiling equations..."
bulwahn@32667
  2197
    val compiled_terms =
bulwahn@32667
  2198
      (#compile_preds steps) thy' all_vs param_vs preds moded_clauses
bulwahn@32667
  2199
    val _ = print_compiled_terms thy' compiled_terms
wenzelm@32950
  2200
    val _ = tracing "Proving equations..."
bulwahn@32667
  2201
    val result_thms = #prove steps thy' clauses preds (extra_modes @ modes)
bulwahn@32667
  2202
      moded_clauses compiled_terms
bulwahn@32667
  2203
    val qname = #qname steps
bulwahn@32667
  2204
    (* val attrib = gn thy => Attrib.attribute_i thy Code.add_eqn_attrib *)
bulwahn@32667
  2205
    val attrib = fn thy => Attrib.attribute_i thy (Attrib.internal (K (Thm.declaration_attribute
bulwahn@32667
  2206
      (fn thm => Context.mapping (Code.add_eqn thm) I))))
bulwahn@32667
  2207
    val thy'' = fold (fn (name, result_thms) => fn thy => snd (PureThy.add_thmss
bulwahn@32667
  2208
      [((Binding.qualify true (Long_Name.base_name name) (Binding.name qname), result_thms),
bulwahn@32667
  2209
        [attrib thy ])] thy))
bulwahn@32667
  2210
      (maps_modes result_thms) thy'
bulwahn@32667
  2211
      |> Theory.checkpoint
bulwahn@32667
  2212
  in
bulwahn@32667
  2213
    thy''
bulwahn@32667
  2214
  end
bulwahn@32667
  2215
bulwahn@32667
  2216
fun extend' value_of edges_of key (G, visited) =
bulwahn@32667
  2217
  let
bulwahn@32667
  2218
    val (G', v) = case try (Graph.get_node G) key of
bulwahn@32667
  2219
        SOME v => (G, v)
bulwahn@32667
  2220
      | NONE => (Graph.new_node (key, value_of key) G, value_of key)
bulwahn@32667
  2221
    val (G'', visited') = fold (extend' value_of edges_of) (edges_of (key, v) \\ visited)
bulwahn@32667
  2222
      (G', key :: visited) 
bulwahn@32667
  2223
  in
bulwahn@32667
  2224
    (fold (Graph.add_edge o (pair key)) (edges_of (key, v)) G'', visited')
bulwahn@32667
  2225
  end;
bulwahn@32667
  2226
bulwahn@32667
  2227
fun extend value_of edges_of key G = fst (extend' value_of edges_of key (G, [])) 
bulwahn@32667
  2228
  
bulwahn@32667
  2229
fun gen_add_equations steps names thy =
bulwahn@32667
  2230
  let
bulwahn@32667
  2231
    val thy' = PredData.map (fold (extend (fetch_pred_data thy) (depending_preds_of thy)) names) thy
bulwahn@32667
  2232
      |> Theory.checkpoint;
bulwahn@32667
  2233
    fun strong_conn_of gr keys =
bulwahn@32667
  2234
      Graph.strong_conn (Graph.subgraph (member (op =) (Graph.all_succs gr keys)) gr)
bulwahn@32667
  2235
    val scc = strong_conn_of (PredData.get thy') names
bulwahn@32667
  2236
    val thy'' = fold_rev
bulwahn@32667
  2237
      (fn preds => fn thy =>
bulwahn@32667
  2238
        if #are_not_defined steps thy preds then add_equations_of steps preds thy else thy)
bulwahn@32667
  2239
      scc thy' |> Theory.checkpoint
bulwahn@32667
  2240
  in thy'' end
bulwahn@32667
  2241
bulwahn@32667
  2242
(* different instantiantions of the predicate compiler *)
bulwahn@32667
  2243
bulwahn@32667
  2244
val add_equations = gen_add_equations
bulwahn@32667
  2245
  {infer_modes = infer_modes,
bulwahn@32667
  2246
  create_definitions = create_definitions,
bulwahn@32667
  2247
  compile_preds = compile_preds PredicateCompFuns.compfuns mk_fun_of false,
bulwahn@32667
  2248
  prove = prove,
bulwahn@32672
  2249
  are_not_defined = fn thy => forall (null o modes_of thy),
bulwahn@32667
  2250
  qname = "equation"}
bulwahn@32667
  2251
bulwahn@32667
  2252
val add_sizelim_equations = gen_add_equations
bulwahn@32667
  2253
  {infer_modes = infer_modes,
bulwahn@32667
  2254
  create_definitions = sizelim_create_definitions,
bulwahn@32667
  2255
  compile_preds = compile_preds PredicateCompFuns.compfuns mk_sizelim_fun_of true,
bulwahn@32667
  2256
  prove = prove_by_skip,
bulwahn@32672
  2257
  are_not_defined = fn thy => forall (null o sizelim_modes_of thy),
bulwahn@32667
  2258
  qname = "sizelim_equation"
bulwahn@32667
  2259
  }
bulwahn@32667
  2260
bulwahn@32667
  2261
val add_quickcheck_equations = gen_add_equations
bulwahn@32667
  2262
  {infer_modes = infer_modes_with_generator,
bulwahn@32667
  2263
  create_definitions = rpred_create_definitions,
bulwahn@32667
  2264
  compile_preds = compile_preds RPredCompFuns.compfuns mk_generator_of true,
bulwahn@32667
  2265
  prove = prove_by_skip,
bulwahn@32672
  2266
  are_not_defined = fn thy => forall (null o rpred_modes_of thy),
bulwahn@32667
  2267
  qname = "rpred_equation"}
bulwahn@32667
  2268
bulwahn@32667
  2269
(** user interface **)
bulwahn@32667
  2270
bulwahn@32667
  2271
(* code_pred_intro attribute *)
bulwahn@32667
  2272
bulwahn@32667
  2273
fun attrib f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
bulwahn@32667
  2274
bulwahn@32667
  2275
val code_pred_intros_attrib = attrib add_intro;
bulwahn@32667
  2276
bulwahn@32668
  2277
bulwahn@32668
  2278
(*FIXME
bulwahn@32668
  2279
- Naming of auxiliary rules necessary?
bulwahn@32668
  2280
- add default code equations P x y z = P_i_i_i x y z
bulwahn@32668
  2281
*)
bulwahn@32668
  2282
bulwahn@32668
  2283
val setup = PredData.put (Graph.empty) #>
bulwahn@32668
  2284
  Attrib.setup @{binding code_pred_intros} (Scan.succeed (attrib add_intro))
bulwahn@32668
  2285
    "adding alternative introduction rules for code generation of inductive predicates"
bulwahn@32668
  2286
(*  Attrib.setup @{binding code_ind_cases} (Scan.succeed add_elim_attrib)
bulwahn@32668
  2287
    "adding alternative elimination rules for code generation of inductive predicates";
bulwahn@32668
  2288
    *)
bulwahn@32668
  2289
  (*FIXME name discrepancy in attribs and ML code*)
bulwahn@32668
  2290
  (*FIXME intros should be better named intro*)
bulwahn@32668
  2291
  (*FIXME why distinguished attribute for cases?*)
bulwahn@32667
  2292
bulwahn@32667
  2293
(* TODO: make TheoryDataFun to GenericDataFun & remove duplication of local theory and theory *)
bulwahn@32668
  2294
fun generic_code_pred prep_const rpred raw_const lthy =
bulwahn@32667
  2295
  let
bulwahn@32667
  2296
    val thy = ProofContext.theory_of lthy
bulwahn@32667
  2297
    val const = prep_const thy raw_const
bulwahn@32667
  2298
    val lthy' = LocalTheory.theory (PredData.map
bulwahn@32667
  2299
        (extend (fetch_pred_data thy) (depending_preds_of thy) const)) lthy
bulwahn@32667
  2300
      |> LocalTheory.checkpoint
bulwahn@32667
  2301
    val thy' = ProofContext.theory_of lthy'
bulwahn@32667
  2302
    val preds = Graph.all_preds (PredData.get thy') [const] |> filter_out (has_elim thy')
bulwahn@32667
  2303
    fun mk_cases const =
bulwahn@32667
  2304
      let
bulwahn@32667
  2305
        val nparams = nparams_of thy' const
bulwahn@32667
  2306
        val intros = intros_of thy' const
bulwahn@32667
  2307
      in mk_casesrule lthy' nparams intros end  
bulwahn@32667
  2308
    val cases_rules = map mk_cases preds
bulwahn@32667
  2309
    val cases =
bulwahn@32667
  2310
      map (fn case_rule => RuleCases.Case {fixes = [],
bulwahn@32667
  2311
        assumes = [("", Logic.strip_imp_prems case_rule)],
bulwahn@32667
  2312
        binds = [], cases = []}) cases_rules
bulwahn@32667
  2313
    val case_env = map2 (fn p => fn c => (Long_Name.base_name p, SOME c)) preds cases
bulwahn@32667
  2314
    val lthy'' = lthy'
bulwahn@32667
  2315
      |> fold Variable.auto_fixes cases_rules 
bulwahn@32667
  2316
      |> ProofContext.add_cases true case_env
bulwahn@32667
  2317
    fun after_qed thms goal_ctxt =
bulwahn@32667
  2318
      let
bulwahn@32667
  2319
        val global_thms = ProofContext.export goal_ctxt
bulwahn@32667
  2320
          (ProofContext.init (ProofContext.theory_of goal_ctxt)) (map the_single thms)
bulwahn@32667
  2321
      in
bulwahn@32668
  2322
        goal_ctxt |> LocalTheory.theory (fold set_elim global_thms #>
bulwahn@32668
  2323
          (if rpred then
bulwahn@32672
  2324
            (add_equations [const] #>
bulwahn@32672
  2325
             add_sizelim_equations [const] #> add_quickcheck_equations [const])
bulwahn@32668
  2326
        else add_equations [const]))
bulwahn@32667
  2327
      end  
bulwahn@32667
  2328
  in
bulwahn@32667
  2329
    Proof.theorem_i NONE after_qed (map (single o (rpair [])) cases_rules) lthy''
bulwahn@32667
  2330
  end;
bulwahn@32667
  2331
bulwahn@32667
  2332
val code_pred = generic_code_pred (K I);
bulwahn@32667
  2333
val code_pred_cmd = generic_code_pred Code.read_const
bulwahn@32667
  2334
bulwahn@32667
  2335
(* transformation for code generation *)
bulwahn@32667
  2336
wenzelm@32740
  2337
val eval_ref = Unsynchronized.ref (NONE : (unit -> term Predicate.pred) option);
bulwahn@32667
  2338
bulwahn@32667
  2339
(*FIXME turn this into an LCF-guarded preprocessor for comprehensions*)
bulwahn@32667
  2340
fun analyze_compr thy t_compr =
bulwahn@32667
  2341
  let
bulwahn@32667
  2342
    val split = case t_compr of (Const (@{const_name Collect}, _) $ t) => t
bulwahn@32667
  2343
      | _ => error ("Not a set comprehension: " ^ Syntax.string_of_term_global thy t_compr);
bulwahn@32667
  2344
    val (body, Ts, fp) = HOLogic.strip_psplits split;
bulwahn@32667
  2345
    val (pred as Const (name, T), all_args) = strip_comb body;
bulwahn@32667
  2346
    val (params, args) = chop (nparams_of thy name) all_args;
bulwahn@32667
  2347
    val user_mode = map_filter I (map_index
bulwahn@32667
  2348
      (fn (i, t) => case t of Bound j => if j < length Ts then NONE
bulwahn@32667
  2349
        else SOME (i+1) | _ => SOME (i+1)) args); (*FIXME dangling bounds should not occur*)
bulwahn@32667
  2350
    val user_mode' = map (rpair NONE) user_mode
bulwahn@32667
  2351
    val modes = filter (fn Mode (_, is, _) => is = user_mode')
bulwahn@32667
  2352
      (modes_of_term (all_modes_of thy) (list_comb (pred, params)));
bulwahn@32667
  2353
    val m = case modes
bulwahn@32667
  2354
     of [] => error ("No mode possible for comprehension "
bulwahn@32667
  2355
                ^ Syntax.string_of_term_global thy t_compr)
bulwahn@32667
  2356
      | [m] => m
bulwahn@32667
  2357
      | m :: _ :: _ => (warning ("Multiple modes possible for comprehension "
bulwahn@32667
  2358
                ^ Syntax.string_of_term_global thy t_compr); m);
bulwahn@32667
  2359
    val (inargs, outargs) = split_smode user_mode' args;
bulwahn@32672
  2360
    val t_pred = list_comb (compile_expr NONE NONE thy (m, list_comb (pred, params)), inargs);
bulwahn@32668
  2361
    val t_eval = if null outargs then t_pred else
bulwahn@32668
  2362
      let
bulwahn@32667
  2363
        val outargs_bounds = map (fn Bound i => i) outargs;
bulwahn@32667
  2364
        val outargsTs = map (nth Ts) outargs_bounds;
bulwahn@32667
  2365
        val T_pred = HOLogic.mk_tupleT outargsTs;
bulwahn@32667
  2366
        val T_compr = HOLogic.mk_ptupleT fp Ts;
bulwahn@32667
  2367
        val arrange_bounds = map_index I outargs_bounds
bulwahn@32667
  2368
          |> sort (prod_ord (K EQUAL) int_ord)
bulwahn@32667
  2369
          |> map fst;
bulwahn@32667
  2370
        val arrange = funpow (length outargs_bounds - 1) HOLogic.mk_split
bulwahn@32667
  2371
          (Term.list_abs (map (pair "") outargsTs,
bulwahn@32667
  2372
            HOLogic.mk_ptuple fp T_compr (map Bound arrange_bounds)))
bulwahn@32667
  2373
      in mk_map PredicateCompFuns.compfuns T_pred T_compr arrange t_pred end
bulwahn@32667
  2374
  in t_eval end;
bulwahn@32667
  2375
bulwahn@32667
  2376
fun eval thy t_compr =
bulwahn@32667
  2377
  let
bulwahn@32667
  2378
    val t = analyze_compr thy t_compr;
bulwahn@32667
  2379
    val T = dest_predT PredicateCompFuns.compfuns (fastype_of t);
bulwahn@32667
  2380
    val t' = mk_map PredicateCompFuns.compfuns T HOLogic.termT (HOLogic.term_of_const T) t;
bulwahn@32668
  2381
  in (T, Code_ML.eval NONE ("Predicate_Compile_Core.eval_ref", eval_ref) Predicate.map thy t' []) end;
bulwahn@32667
  2382
bulwahn@32667
  2383
fun values ctxt k t_compr =
bulwahn@32667
  2384
  let
bulwahn@32667
  2385
    val thy = ProofContext.theory_of ctxt;
bulwahn@32667
  2386
    val (T, t) = eval thy t_compr;
bulwahn@32667
  2387
    val setT = HOLogic.mk_setT T;
bulwahn@32667
  2388
    val (ts, _) = Predicate.yieldn k t;
bulwahn@32667
  2389
    val elemsT = HOLogic.mk_set T ts;