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