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