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