src/HOL/Tools/Predicate_Compile/predicate_compile_core.ML
author bulwahn
Wed Mar 31 16:44:41 2010 +0200 (2010-03-31)
changeset 36056 0c128c2c310d
parent 36048 1d2faa488166
child 36247 bcf23027bca2
permissions -rw-r--r--
made smlnj happy
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@36048
     9
  type mode = Predicate_Compile_Aux.mode
bulwahn@36048
    10
  type options = Predicate_Compile_Aux.options
bulwahn@36048
    11
  type compilation = Predicate_Compile_Aux.compilation
bulwahn@36048
    12
  type compilation_funs = Predicate_Compile_Aux.compilation_funs
bulwahn@36048
    13
  
bulwahn@33478
    14
  val setup : theory -> theory
bulwahn@36048
    15
  val code_pred : options -> string -> Proof.context -> Proof.state
bulwahn@36048
    16
  val code_pred_cmd : options -> string -> Proof.context -> Proof.state
bulwahn@36048
    17
  val values_cmd : string list -> mode option list option
bulwahn@36048
    18
    -> ((string option * bool) * (compilation * int list)) -> int -> string -> Toplevel.state -> unit
bulwahn@34948
    19
  val register_predicate : (string * thm list * thm) -> theory -> theory
bulwahn@33146
    20
  val register_intros : string * thm list -> theory -> theory
bulwahn@32667
    21
  val is_registered : theory -> string -> bool
bulwahn@36048
    22
  val function_name_of : compilation -> theory -> string -> mode -> string
bulwahn@36048
    23
  val predfun_intro_of: Proof.context -> string -> mode -> thm
bulwahn@36048
    24
  val predfun_elim_of: Proof.context -> string -> mode -> thm
bulwahn@32667
    25
  val all_preds_of : theory -> string list
bulwahn@36048
    26
  val modes_of: compilation -> theory -> string -> mode list
bulwahn@36048
    27
  val all_modes_of : compilation -> theory -> (string * mode list) list
bulwahn@36048
    28
  val all_random_modes_of : theory -> (string * mode list) list
bulwahn@33478
    29
  val intros_of : theory -> string -> thm list
bulwahn@33478
    30
  val add_intro : thm -> theory -> theory
bulwahn@33478
    31
  val set_elim : thm -> theory -> theory
bulwahn@36048
    32
  val register_alternative_function : string -> mode -> string -> theory -> theory
bulwahn@36048
    33
  val alternative_compilation_of : theory -> string -> mode ->
bulwahn@36038
    34
    (compilation_funs -> typ -> term) option
bulwahn@36048
    35
  val functional_compilation : string -> mode -> compilation_funs -> typ -> term
bulwahn@36048
    36
  val force_modes_and_functions : string -> (mode * (string * bool)) list -> theory -> theory
bulwahn@36038
    37
  val force_modes_and_compilations : string ->
bulwahn@36048
    38
    (mode * ((compilation_funs -> typ -> term) * bool)) list -> theory -> theory
bulwahn@34948
    39
  val preprocess_intro : theory -> thm -> thm
bulwahn@33478
    40
  val print_stored_rules : theory -> unit
bulwahn@36048
    41
  val print_all_modes : compilation -> theory -> unit
bulwahn@34948
    42
  val mk_casesrule : Proof.context -> term -> thm list -> term
bulwahn@33137
    43
  val eval_ref : (unit -> term Predicate.pred) option Unsynchronized.ref
bulwahn@33482
    44
  val random_eval_ref : (unit -> int * int -> term Predicate.pred * (int * int))
bulwahn@33482
    45
    option Unsynchronized.ref
bulwahn@34948
    46
  val dseq_eval_ref : (unit -> term DSequence.dseq) option Unsynchronized.ref
bulwahn@34948
    47
  val random_dseq_eval_ref : (unit -> int -> int -> int * int -> term DSequence.dseq * (int * int))
bulwahn@34948
    48
    option Unsynchronized.ref
bulwahn@36020
    49
  val new_random_dseq_eval_ref :
bulwahn@36020
    50
    (unit -> int -> int -> int * int -> int -> term Lazy_Sequence.lazy_sequence)
bulwahn@36020
    51
      option Unsynchronized.ref
bulwahn@36027
    52
  val new_random_dseq_stats_eval_ref :
bulwahn@36027
    53
    (unit -> int -> int -> int * int -> int -> (term * int) Lazy_Sequence.lazy_sequence)
bulwahn@36027
    54
      option Unsynchronized.ref
bulwahn@33628
    55
  val code_pred_intro_attrib : attribute
bulwahn@32667
    56
  (* used by Quickcheck_Generator *) 
bulwahn@32667
    57
  (* temporary for testing of the compilation *)
bulwahn@36048
    58
  val add_equations : options -> string list -> theory -> theory
bulwahn@36048
    59
  val add_depth_limited_random_equations : options -> string list -> theory -> theory
bulwahn@36048
    60
  val add_random_dseq_equations : options -> string list -> theory -> theory
bulwahn@36048
    61
  val add_new_random_dseq_equations : options -> string list -> theory -> theory
bulwahn@33473
    62
  val mk_tracing : string -> term -> term
bulwahn@32667
    63
end;
bulwahn@32667
    64
bulwahn@32667
    65
structure Predicate_Compile_Core : PREDICATE_COMPILE_CORE =
bulwahn@32667
    66
struct
bulwahn@32667
    67
bulwahn@32668
    68
open Predicate_Compile_Aux;
bulwahn@33144
    69
bulwahn@32667
    70
(** auxiliary **)
bulwahn@32667
    71
bulwahn@32667
    72
(* debug stuff *)
bulwahn@32667
    73
bulwahn@35886
    74
fun print_tac options s = 
bulwahn@33127
    75
  if show_proof_trace options then Tactical.print_tac s else Seq.single;
bulwahn@33127
    76
bulwahn@35885
    77
fun assert b = if not b then raise Fail "Assertion failed" else warning "Assertion holds"
bulwahn@34948
    78
bulwahn@33108
    79
datatype assertion = Max_number_of_subgoals of int
bulwahn@33108
    80
fun assert_tac (Max_number_of_subgoals i) st =
bulwahn@33108
    81
  if (nprems_of st <= i) then Seq.single st
bulwahn@35885
    82
  else raise Fail ("assert_tac: Numbers of subgoals mismatch at goal state :"
bulwahn@33108
    83
    ^ "\n" ^ Pretty.string_of (Pretty.chunks
bulwahn@33108
    84
      (Goal_Display.pretty_goals_without_context (! Goal_Display.goals_limit) st)));
bulwahn@33108
    85
bulwahn@32667
    86
(** fundamentals **)
bulwahn@32667
    87
bulwahn@32667
    88
(* syntactic operations *)
bulwahn@32667
    89
bulwahn@32667
    90
fun mk_eq (x, xs) =
bulwahn@32667
    91
  let fun mk_eqs _ [] = []
bulwahn@32667
    92
        | mk_eqs a (b::cs) =
bulwahn@32667
    93
            HOLogic.mk_eq (Free (a, fastype_of b), b) :: mk_eqs a cs
bulwahn@32667
    94
  in mk_eqs x xs end;
bulwahn@32667
    95
bulwahn@32667
    96
fun mk_scomp (t, u) =
bulwahn@32667
    97
  let
bulwahn@32667
    98
    val T = fastype_of t
bulwahn@32667
    99
    val U = fastype_of u
bulwahn@32667
   100
    val [A] = binder_types T
bulwahn@34948
   101
    val D = body_type U                   
bulwahn@32667
   102
  in 
bulwahn@32667
   103
    Const (@{const_name "scomp"}, T --> U --> A --> D) $ t $ u
bulwahn@32667
   104
  end;
bulwahn@32667
   105
bulwahn@32667
   106
fun dest_funT (Type ("fun",[S, T])) = (S, T)
bulwahn@32667
   107
  | dest_funT T = raise TYPE ("dest_funT", [T], [])
bulwahn@32667
   108
 
bulwahn@32667
   109
fun mk_fun_comp (t, u) =
bulwahn@32667
   110
  let
bulwahn@32667
   111
    val (_, B) = dest_funT (fastype_of t)
bulwahn@32667
   112
    val (C, A) = dest_funT (fastype_of u)
bulwahn@32667
   113
  in
bulwahn@32667
   114
    Const(@{const_name "Fun.comp"}, (A --> B) --> (C --> A) --> C --> B) $ t $ u
bulwahn@32667
   115
  end;
bulwahn@32667
   116
bulwahn@32667
   117
fun dest_randomT (Type ("fun", [@{typ Random.seed},
bulwahn@32674
   118
  Type ("*", [Type ("*", [T, @{typ "unit => Code_Evaluation.term"}]) ,@{typ Random.seed}])])) = T
bulwahn@32667
   119
  | dest_randomT T = raise TYPE ("dest_randomT", [T], [])
bulwahn@32667
   120
bulwahn@33473
   121
fun mk_tracing s t =
bulwahn@33473
   122
  Const(@{const_name Code_Evaluation.tracing},
bulwahn@33473
   123
    @{typ String.literal} --> (fastype_of t) --> (fastype_of t)) $ (HOLogic.mk_literal s) $ t
bulwahn@33473
   124
bulwahn@34948
   125
val strip_intro_concl = (strip_comb o HOLogic.dest_Trueprop o Logic.strip_imp_concl o prop_of)
bulwahn@34948
   126
bulwahn@34948
   127
(* derivation trees for modes of premises *)
bulwahn@34948
   128
bulwahn@34948
   129
datatype mode_derivation = Mode_App of mode_derivation * mode_derivation | Context of mode
bulwahn@34948
   130
  | Mode_Pair of mode_derivation * mode_derivation | Term of mode
bulwahn@32667
   131
bulwahn@34948
   132
fun string_of_derivation (Mode_App (m1, m2)) =
bulwahn@34948
   133
  "App (" ^ string_of_derivation m1 ^ ", " ^ string_of_derivation m2 ^ ")"
bulwahn@34948
   134
  | string_of_derivation (Mode_Pair (m1, m2)) =
bulwahn@34948
   135
  "Pair (" ^ string_of_derivation m1 ^ ", " ^ string_of_derivation m2 ^ ")"
bulwahn@34948
   136
  | string_of_derivation (Term m) = "Term (" ^ string_of_mode m ^ ")"
bulwahn@34948
   137
  | string_of_derivation (Context m) = "Context (" ^ string_of_mode m ^ ")"
bulwahn@32667
   138
bulwahn@34948
   139
fun strip_mode_derivation deriv =
bulwahn@32667
   140
  let
bulwahn@34948
   141
    fun strip (Mode_App (deriv1, deriv2)) ds = strip deriv1 (deriv2 :: ds)
bulwahn@34948
   142
      | strip deriv ds = (deriv, ds)
bulwahn@34948
   143
  in
bulwahn@34948
   144
    strip deriv []
bulwahn@34948
   145
  end
bulwahn@34948
   146
bulwahn@34948
   147
fun mode_of (Context m) = m
bulwahn@34948
   148
  | mode_of (Term m) = m
bulwahn@34948
   149
  | mode_of (Mode_App (d1, d2)) =
bulwahn@34948
   150
    (case mode_of d1 of Fun (m, m') =>
bulwahn@35885
   151
        (if eq_mode (m, mode_of d2) then m' else raise Fail "mode_of")
bulwahn@35885
   152
      | _ => raise Fail "mode_of2")
bulwahn@34948
   153
  | mode_of (Mode_Pair (d1, d2)) =
bulwahn@34948
   154
    Pair (mode_of d1, mode_of d2)
bulwahn@34948
   155
bulwahn@34948
   156
fun head_mode_of deriv = mode_of (fst (strip_mode_derivation deriv))
bulwahn@32667
   157
bulwahn@34948
   158
fun param_derivations_of deriv =
bulwahn@32667
   159
  let
bulwahn@34948
   160
    val (_, argument_derivs) = strip_mode_derivation deriv
bulwahn@34948
   161
    fun param_derivation (Mode_Pair (m1, m2)) =
bulwahn@34948
   162
        param_derivation m1 @ param_derivation m2
bulwahn@34948
   163
      | param_derivation (Term _) = []
bulwahn@34948
   164
      | param_derivation m = [m]
bulwahn@34948
   165
  in
bulwahn@34948
   166
    maps param_derivation argument_derivs
bulwahn@34948
   167
  end
bulwahn@32667
   168
bulwahn@34948
   169
fun collect_context_modes (Mode_App (m1, m2)) =
bulwahn@34948
   170
      collect_context_modes m1 @ collect_context_modes m2
bulwahn@34948
   171
  | collect_context_modes (Mode_Pair (m1, m2)) =
bulwahn@34948
   172
      collect_context_modes m1 @ collect_context_modes m2
bulwahn@34948
   173
  | collect_context_modes (Context m) = [m]
bulwahn@34948
   174
  | collect_context_modes (Term _) = []
bulwahn@32668
   175
bulwahn@34948
   176
(* representation of inferred clauses with modes *)
bulwahn@32667
   177
bulwahn@34948
   178
type moded_clause = term list * (indprem * mode_derivation) list
bulwahn@34948
   179
bulwahn@35324
   180
type 'a pred_mode_table = (string * ((bool * mode) * 'a) list) list
bulwahn@32667
   181
bulwahn@34948
   182
(* book-keeping *)
bulwahn@34948
   183
bulwahn@32667
   184
datatype predfun_data = PredfunData of {
bulwahn@32667
   185
  definition : thm,
bulwahn@32667
   186
  intro : thm,
bulwahn@35884
   187
  elim : thm,
bulwahn@35884
   188
  neg_intro : thm option
bulwahn@32667
   189
};
bulwahn@32667
   190
bulwahn@32667
   191
fun rep_predfun_data (PredfunData data) = data;
bulwahn@32667
   192
bulwahn@35884
   193
fun mk_predfun_data (definition, ((intro, elim), neg_intro)) =
bulwahn@35884
   194
  PredfunData {definition = definition, intro = intro, elim = elim, neg_intro = neg_intro}
bulwahn@32667
   195
bulwahn@32667
   196
datatype pred_data = PredData of {
bulwahn@32667
   197
  intros : thm list,
bulwahn@32667
   198
  elim : thm option,
bulwahn@34948
   199
  function_names : (compilation * (mode * string) list) list,
bulwahn@34948
   200
  predfun_data : (mode * predfun_data) list,
bulwahn@34948
   201
  needs_random : mode list
bulwahn@32667
   202
};
bulwahn@32667
   203
bulwahn@32667
   204
fun rep_pred_data (PredData data) = data;
bulwahn@34948
   205
bulwahn@35887
   206
fun mk_pred_data ((intros, elim), (function_names, (predfun_data, needs_random))) =
bulwahn@34948
   207
  PredData {intros = intros, elim = elim,
bulwahn@34948
   208
    function_names = function_names, predfun_data = predfun_data, needs_random = needs_random}
bulwahn@34948
   209
bulwahn@34948
   210
fun map_pred_data f (PredData {intros, elim, function_names, predfun_data, needs_random}) =
bulwahn@35887
   211
  mk_pred_data (f ((intros, elim), (function_names, (predfun_data, needs_random))))
bulwahn@33144
   212
bulwahn@32667
   213
fun eq_option eq (NONE, NONE) = true
bulwahn@32667
   214
  | eq_option eq (SOME x, SOME y) = eq (x, y)
bulwahn@32667
   215
  | eq_option eq _ = false
bulwahn@33144
   216
bulwahn@32667
   217
fun eq_pred_data (PredData d1, PredData d2) = 
bulwahn@35885
   218
  eq_list Thm.eq_thm (#intros d1, #intros d2) andalso
bulwahn@35885
   219
  eq_option Thm.eq_thm (#elim d1, #elim d2)
bulwahn@33144
   220
wenzelm@33522
   221
structure PredData = Theory_Data
bulwahn@32667
   222
(
bulwahn@32667
   223
  type T = pred_data Graph.T;
bulwahn@32667
   224
  val empty = Graph.empty;
bulwahn@32667
   225
  val extend = I;
wenzelm@33522
   226
  val merge = Graph.merge eq_pred_data;
bulwahn@32667
   227
);
bulwahn@32667
   228
bulwahn@32667
   229
(* queries *)
bulwahn@32667
   230
bulwahn@32667
   231
fun lookup_pred_data thy name =
bulwahn@32667
   232
  Option.map rep_pred_data (try (Graph.get_node (PredData.get thy)) name)
bulwahn@32667
   233
bulwahn@32667
   234
fun the_pred_data thy name = case lookup_pred_data thy name
bulwahn@32667
   235
 of NONE => error ("No such predicate " ^ quote name)  
bulwahn@32667
   236
  | SOME data => data;
bulwahn@32667
   237
bulwahn@34948
   238
val is_registered = is_some oo lookup_pred_data
bulwahn@32667
   239
bulwahn@32667
   240
val all_preds_of = Graph.keys o PredData.get
bulwahn@32667
   241
bulwahn@32667
   242
fun intros_of thy = map (Thm.transfer thy) o #intros o the_pred_data thy
bulwahn@32667
   243
bulwahn@32667
   244
fun the_elim_of thy name = case #elim (the_pred_data thy name)
bulwahn@32667
   245
 of NONE => error ("No elimination rule for predicate " ^ quote name)
bulwahn@35888
   246
  | SOME thm => Thm.transfer thy thm
bulwahn@32667
   247
  
bulwahn@32667
   248
val has_elim = is_some o #elim oo the_pred_data;
bulwahn@32667
   249
bulwahn@34948
   250
fun function_names_of compilation thy name =
bulwahn@34948
   251
  case AList.lookup (op =) (#function_names (the_pred_data thy name)) compilation of
bulwahn@34948
   252
    NONE => error ("No " ^ string_of_compilation compilation
bulwahn@34948
   253
      ^ "functions defined for predicate " ^ quote name)
bulwahn@34948
   254
  | SOME fun_names => fun_names
bulwahn@32667
   255
bulwahn@36019
   256
fun function_name_of compilation thy name mode =
bulwahn@35324
   257
  case AList.lookup eq_mode
bulwahn@36019
   258
    (function_names_of compilation thy name) mode of
bulwahn@34948
   259
    NONE => error ("No " ^ string_of_compilation compilation
bulwahn@36019
   260
      ^ " function defined for mode " ^ string_of_mode mode ^ " of predicate " ^ quote name)
bulwahn@34948
   261
  | SOME function_name => function_name
bulwahn@34948
   262
bulwahn@34948
   263
fun modes_of compilation thy name = map fst (function_names_of compilation thy name)
bulwahn@32667
   264
bulwahn@34948
   265
fun all_modes_of compilation thy =
bulwahn@34948
   266
  map_filter (fn name => Option.map (pair name) (try (modes_of compilation thy) name))
bulwahn@34948
   267
    (all_preds_of thy)
bulwahn@34948
   268
bulwahn@34948
   269
val all_random_modes_of = all_modes_of Random
bulwahn@34948
   270
bulwahn@34948
   271
fun defined_functions compilation thy name =
bulwahn@34948
   272
  AList.defined (op =) (#function_names (the_pred_data thy name)) compilation
bulwahn@32667
   273
bulwahn@32667
   274
fun lookup_predfun_data thy name mode =
bulwahn@33483
   275
  Option.map rep_predfun_data
bulwahn@34948
   276
    (AList.lookup (op =) (#predfun_data (the_pred_data thy name)) mode)
bulwahn@32667
   277
bulwahn@34948
   278
fun the_predfun_data thy name mode =
bulwahn@34948
   279
  case lookup_predfun_data thy name mode of
bulwahn@34948
   280
    NONE => error ("No function defined for mode " ^ string_of_mode mode ^
bulwahn@34948
   281
      " of predicate " ^ name)
bulwahn@34948
   282
  | SOME data => data;
bulwahn@32667
   283
bulwahn@35888
   284
val predfun_definition_of = #definition ooo the_predfun_data o ProofContext.theory_of
bulwahn@32667
   285
bulwahn@35888
   286
val predfun_intro_of = #intro ooo the_predfun_data o ProofContext.theory_of
bulwahn@32667
   287
bulwahn@35888
   288
val predfun_elim_of = #elim ooo the_predfun_data o ProofContext.theory_of
bulwahn@32667
   289
bulwahn@35888
   290
val predfun_neg_intro_of = #neg_intro ooo the_predfun_data o ProofContext.theory_of
bulwahn@35884
   291
bulwahn@32667
   292
(* diagnostic display functions *)
bulwahn@32667
   293
bulwahn@33619
   294
fun print_modes options thy modes =
bulwahn@33251
   295
  if show_modes options then
bulwahn@33326
   296
    tracing ("Inferred modes:\n" ^
bulwahn@33251
   297
      cat_lines (map (fn (s, ms) => s ^ ": " ^ commas (map
bulwahn@35324
   298
        (fn (p, m) => string_of_mode m ^ (if p then "pos" else "neg")) ms)) modes))
bulwahn@33251
   299
  else ()
bulwahn@32667
   300
bulwahn@32667
   301
fun print_pred_mode_table string_of_entry thy pred_mode_table =
bulwahn@32667
   302
  let
bulwahn@35324
   303
    fun print_mode pred ((pol, mode), entry) =  "mode : " ^ string_of_mode mode
bulwahn@33619
   304
      ^ string_of_entry pred mode entry
bulwahn@32667
   305
    fun print_pred (pred, modes) =
bulwahn@32667
   306
      "predicate " ^ pred ^ ": " ^ cat_lines (map (print_mode pred) modes)
bulwahn@33326
   307
    val _ = tracing (cat_lines (map print_pred pred_mode_table))
bulwahn@32667
   308
  in () end;
bulwahn@32667
   309
bulwahn@34948
   310
fun string_of_prem thy (Prem t) =
bulwahn@34948
   311
    (Syntax.string_of_term_global thy t) ^ "(premise)"
bulwahn@34948
   312
  | string_of_prem thy (Negprem t) =
bulwahn@34948
   313
    (Syntax.string_of_term_global thy (HOLogic.mk_not t)) ^ "(negative premise)"
bulwahn@33130
   314
  | string_of_prem thy (Sidecond t) =
bulwahn@33130
   315
    (Syntax.string_of_term_global thy t) ^ "(sidecondition)"
bulwahn@35885
   316
  | string_of_prem thy _ = raise Fail "string_of_prem: unexpected input"
bulwahn@33130
   317
bulwahn@33130
   318
fun string_of_clause thy pred (ts, prems) =
bulwahn@33130
   319
  (space_implode " --> "
bulwahn@33130
   320
  (map (string_of_prem thy) prems)) ^ " --> " ^ pred ^ " "
bulwahn@33130
   321
   ^ (space_implode " " (map (Syntax.string_of_term_global thy) ts))
bulwahn@33130
   322
bulwahn@33139
   323
fun print_compiled_terms options thy =
bulwahn@33139
   324
  if show_compilation options then
bulwahn@33139
   325
    print_pred_mode_table (fn _ => fn _ => Syntax.string_of_term_global thy) thy
bulwahn@33139
   326
  else K ()
bulwahn@33139
   327
bulwahn@32667
   328
fun print_stored_rules thy =
bulwahn@32667
   329
  let
bulwahn@32667
   330
    val preds = (Graph.keys o PredData.get) thy
bulwahn@32667
   331
    fun print pred () = let
bulwahn@32667
   332
      val _ = writeln ("predicate: " ^ pred)
bulwahn@32667
   333
      val _ = writeln ("introrules: ")
bulwahn@32667
   334
      val _ = fold (fn thm => fn u => writeln (Display.string_of_thm_global thy thm))
bulwahn@32667
   335
        (rev (intros_of thy pred)) ()
bulwahn@32667
   336
    in
bulwahn@32667
   337
      if (has_elim thy pred) then
bulwahn@32667
   338
        writeln ("elimrule: " ^ Display.string_of_thm_global thy (the_elim_of thy pred))
bulwahn@32667
   339
      else
bulwahn@32667
   340
        writeln ("no elimrule defined")
bulwahn@32667
   341
    end
bulwahn@32667
   342
  in
bulwahn@32667
   343
    fold print preds ()
bulwahn@32667
   344
  end;
bulwahn@32667
   345
bulwahn@34948
   346
fun print_all_modes compilation thy =
bulwahn@32667
   347
  let
bulwahn@32667
   348
    val _ = writeln ("Inferred modes:")
bulwahn@32667
   349
    fun print (pred, modes) u =
bulwahn@32667
   350
      let
bulwahn@32667
   351
        val _ = writeln ("predicate: " ^ pred)
bulwahn@34948
   352
        val _ = writeln ("modes: " ^ (commas (map string_of_mode modes)))
bulwahn@33619
   353
      in u end
bulwahn@32667
   354
  in
bulwahn@34948
   355
    fold print (all_modes_of compilation thy) ()
bulwahn@32667
   356
  end
bulwahn@33129
   357
bulwahn@33132
   358
(* validity checks *)
bulwahn@33752
   359
(* EXPECTED MODE and PROPOSED_MODE are largely the same; define a clear semantics for those! *)
bulwahn@33132
   360
bulwahn@33752
   361
fun check_expected_modes preds options modes =
bulwahn@33752
   362
  case expected_modes options of
bulwahn@33752
   363
    SOME (s, ms) => (case AList.lookup (op =) modes s of
bulwahn@33752
   364
      SOME modes =>
bulwahn@33752
   365
        let
bulwahn@35324
   366
          val modes' = map snd modes
bulwahn@33752
   367
        in
bulwahn@34948
   368
          if not (eq_set eq_mode (ms, modes')) then
bulwahn@33752
   369
            error ("expected modes were not inferred:\n"
bulwahn@34948
   370
            ^ "  inferred modes for " ^ s ^ ": " ^ commas (map string_of_mode modes')  ^ "\n"
bulwahn@34948
   371
            ^ "  expected modes for " ^ s ^ ": " ^ commas (map string_of_mode ms))
bulwahn@33752
   372
          else ()
bulwahn@33752
   373
        end
bulwahn@33752
   374
      | NONE => ())
bulwahn@33752
   375
  | NONE => ()
bulwahn@33752
   376
bulwahn@33752
   377
fun check_proposed_modes preds options modes extra_modes errors =
bulwahn@33752
   378
  case proposed_modes options of
bulwahn@33752
   379
    SOME (s, ms) => (case AList.lookup (op =) modes s of
bulwahn@33752
   380
      SOME inferred_ms =>
bulwahn@33752
   381
        let
bulwahn@33752
   382
          val preds_without_modes = map fst (filter (null o snd) (modes @ extra_modes))
bulwahn@35324
   383
          val modes' = map snd inferred_ms
bulwahn@33752
   384
        in
bulwahn@34948
   385
          if not (eq_set eq_mode (ms, modes')) then
bulwahn@33752
   386
            error ("expected modes were not inferred:\n"
bulwahn@34948
   387
            ^ "  inferred modes for " ^ s ^ ": " ^ commas (map string_of_mode modes')  ^ "\n"
bulwahn@34948
   388
            ^ "  expected modes for " ^ s ^ ": " ^ commas (map string_of_mode ms) ^ "\n"
bulwahn@33752
   389
            ^ "For the following clauses, the following modes could not be inferred: " ^ "\n"
bulwahn@33752
   390
            ^ cat_lines errors ^
bulwahn@33752
   391
            (if not (null preds_without_modes) then
bulwahn@33752
   392
              "\n" ^ "No mode inferred for the predicates " ^ commas preds_without_modes
bulwahn@33752
   393
            else ""))
bulwahn@33752
   394
          else ()
bulwahn@33752
   395
        end
bulwahn@33752
   396
      | NONE => ())
bulwahn@33752
   397
  | NONE => ()
bulwahn@33132
   398
bulwahn@33144
   399
(* importing introduction rules *)
bulwahn@33129
   400
bulwahn@33129
   401
fun unify_consts thy cs intr_ts =
bulwahn@33129
   402
  (let
bulwahn@33129
   403
     val add_term_consts_2 = fold_aterms (fn Const c => insert (op =) c | _ => I);
bulwahn@33129
   404
     fun varify (t, (i, ts)) =
wenzelm@35845
   405
       let val t' = map_types (Logic.incr_tvar (i + 1)) (#2 (Type.varify_global [] t))
bulwahn@33129
   406
       in (maxidx_of_term t', t'::ts) end;
bulwahn@33150
   407
     val (i, cs') = List.foldr varify (~1, []) cs;
bulwahn@33150
   408
     val (i', intr_ts') = List.foldr varify (i, []) intr_ts;
bulwahn@33129
   409
     val rec_consts = fold add_term_consts_2 cs' [];
bulwahn@33129
   410
     val intr_consts = fold add_term_consts_2 intr_ts' [];
bulwahn@33129
   411
     fun unify (cname, cT) =
wenzelm@33317
   412
       let val consts = map snd (filter (fn c => fst c = cname) intr_consts)
bulwahn@33129
   413
       in fold (Sign.typ_unify thy) ((replicate (length consts) cT) ~~ consts) end;
bulwahn@33129
   414
     val (env, _) = fold unify rec_consts (Vartab.empty, i');
bulwahn@33129
   415
     val subst = map_types (Envir.norm_type env)
bulwahn@33129
   416
   in (map subst cs', map subst intr_ts')
bulwahn@33129
   417
   end) handle Type.TUNIFY =>
bulwahn@33129
   418
     (warning "Occurrences of recursive constant have non-unifiable types"; (cs, intr_ts));
bulwahn@33129
   419
bulwahn@34948
   420
fun import_intros inp_pred [] ctxt =
bulwahn@33146
   421
  let
bulwahn@34948
   422
    val ([outp_pred], ctxt') = Variable.import_terms true [inp_pred] ctxt
bulwahn@34948
   423
    val T = fastype_of outp_pred
bulwahn@34948
   424
    (* TODO: put in a function for this next line! *)
bulwahn@34948
   425
    val paramTs = ho_argsT_of (hd (all_modes_of_typ T)) (binder_types T)
bulwahn@34948
   426
    val (param_names, ctxt'') = Variable.variant_fixes
bulwahn@34948
   427
      (map (fn i => "p" ^ (string_of_int i)) (1 upto (length paramTs))) ctxt'
bulwahn@33629
   428
    val params = map2 (curry Free) param_names paramTs
bulwahn@34948
   429
  in
bulwahn@34948
   430
    (((outp_pred, params), []), ctxt')
bulwahn@34948
   431
  end
bulwahn@34948
   432
  | import_intros inp_pred (th :: ths) ctxt =
bulwahn@33129
   433
    let
bulwahn@34948
   434
      val ((_, [th']), ctxt') = Variable.import true [th] ctxt
bulwahn@33129
   435
      val thy = ProofContext.theory_of ctxt'
bulwahn@34948
   436
      val (pred, args) = strip_intro_concl th'
bulwahn@34948
   437
      val T = fastype_of pred
bulwahn@34948
   438
      val ho_args = ho_args_of (hd (all_modes_of_typ T)) args
bulwahn@33146
   439
      fun subst_of (pred', pred) =
bulwahn@33146
   440
        let
bulwahn@33146
   441
          val subst = Sign.typ_match thy (fastype_of pred', fastype_of pred) Vartab.empty
bulwahn@33146
   442
        in map (fn (indexname, (s, T)) => ((indexname, s), T)) (Vartab.dest subst) end
bulwahn@33129
   443
      fun instantiate_typ th =
bulwahn@33129
   444
        let
bulwahn@34948
   445
          val (pred', _) = strip_intro_concl th
bulwahn@33129
   446
          val _ = if not (fst (dest_Const pred) = fst (dest_Const pred')) then
bulwahn@35885
   447
            raise Fail "Trying to instantiate another predicate" else ()
bulwahn@33146
   448
        in Thm.certify_instantiate (subst_of (pred', pred), []) th end;
bulwahn@33129
   449
      fun instantiate_ho_args th =
bulwahn@33129
   450
        let
bulwahn@34948
   451
          val (_, args') = (strip_comb o HOLogic.dest_Trueprop o Logic.strip_imp_concl o prop_of) th
bulwahn@34948
   452
          val ho_args' = map dest_Var (ho_args_of (hd (all_modes_of_typ T)) args')
bulwahn@34948
   453
        in Thm.certify_instantiate ([], ho_args' ~~ ho_args) th end
bulwahn@33146
   454
      val outp_pred =
bulwahn@33146
   455
        Term_Subst.instantiate (subst_of (inp_pred, pred), []) inp_pred
bulwahn@33129
   456
      val ((_, ths'), ctxt1) =
bulwahn@33129
   457
        Variable.import false (map (instantiate_typ #> instantiate_ho_args) ths) ctxt'
bulwahn@33129
   458
    in
bulwahn@34948
   459
      (((outp_pred, ho_args), th' :: ths'), ctxt1)
bulwahn@33129
   460
    end
bulwahn@33129
   461
bulwahn@33129
   462
(* generation of case rules from user-given introduction rules *)
bulwahn@33129
   463
bulwahn@34948
   464
fun mk_args2 (Type ("*", [T1, T2])) st =
bulwahn@34948
   465
    let
bulwahn@34948
   466
      val (t1, st') = mk_args2 T1 st
bulwahn@34948
   467
      val (t2, st'') = mk_args2 T2 st'
bulwahn@34948
   468
    in
bulwahn@34948
   469
      (HOLogic.mk_prod (t1, t2), st'')
bulwahn@34948
   470
    end
bulwahn@35884
   471
  (*| mk_args2 (T as Type ("fun", _)) (params, ctxt) = 
bulwahn@34948
   472
    let
bulwahn@34948
   473
      val (S, U) = strip_type T
bulwahn@34948
   474
    in
bulwahn@34948
   475
      if U = HOLogic.boolT then
bulwahn@34948
   476
        (hd params, (tl params, ctxt))
bulwahn@34948
   477
      else
bulwahn@34948
   478
        let
bulwahn@34948
   479
          val ([x], ctxt') = Variable.variant_fixes ["x"] ctxt
bulwahn@34948
   480
        in
bulwahn@34948
   481
          (Free (x, T), (params, ctxt'))
bulwahn@34948
   482
        end
bulwahn@35884
   483
    end*)
bulwahn@34948
   484
  | mk_args2 T (params, ctxt) =
bulwahn@34948
   485
    let
bulwahn@34948
   486
      val ([x], ctxt') = Variable.variant_fixes ["x"] ctxt
bulwahn@34948
   487
    in
bulwahn@34948
   488
      (Free (x, T), (params, ctxt'))
bulwahn@34948
   489
    end
bulwahn@35884
   490
bulwahn@34948
   491
fun mk_casesrule ctxt pred introrules =
bulwahn@33129
   492
  let
bulwahn@35884
   493
    (* TODO: can be simplified if parameters are not treated specially ? *)
bulwahn@34948
   494
    val (((pred, params), intros_th), ctxt1) = import_intros pred introrules ctxt
bulwahn@35884
   495
    (* TODO: distinct required ? -- test case with more than one parameter! *)
bulwahn@35884
   496
    val params = distinct (op aconv) params
bulwahn@33129
   497
    val intros = map prop_of intros_th
bulwahn@33129
   498
    val ([propname], ctxt2) = Variable.variant_fixes ["thesis"] ctxt1
bulwahn@33129
   499
    val prop = HOLogic.mk_Trueprop (Free (propname, HOLogic.boolT))
bulwahn@34948
   500
    val argsT = binder_types (fastype_of pred)
bulwahn@35884
   501
    (* TODO: can be simplified if parameters are not treated specially ? <-- see uncommented code! *)
bulwahn@34948
   502
    val (argvs, _) = fold_map mk_args2 argsT (params, ctxt2)
bulwahn@33129
   503
    fun mk_case intro =
bulwahn@33129
   504
      let
bulwahn@34948
   505
        val (_, args) = (strip_comb o HOLogic.dest_Trueprop o Logic.strip_imp_concl) intro
bulwahn@33129
   506
        val prems = Logic.strip_imp_prems intro
bulwahn@35884
   507
        val eqprems =
bulwahn@35884
   508
          map2 (HOLogic.mk_Trueprop oo (curry HOLogic.mk_eq)) argvs args
bulwahn@35884
   509
        val frees = map Free (fold Term.add_frees (args @ prems) [])
bulwahn@33129
   510
      in fold Logic.all frees (Logic.list_implies (eqprems @ prems, prop)) end
bulwahn@34948
   511
    val assm = HOLogic.mk_Trueprop (list_comb (pred, argvs))
bulwahn@33129
   512
    val cases = map mk_case intros
bulwahn@33129
   513
  in Logic.list_implies (assm :: cases, prop) end;
bulwahn@33129
   514
bulwahn@35884
   515
fun dest_conjunct_prem th =
bulwahn@35884
   516
  case HOLogic.dest_Trueprop (prop_of th) of
bulwahn@35884
   517
    (Const ("op &", _) $ t $ t') =>
bulwahn@35884
   518
      dest_conjunct_prem (th RS @{thm conjunct1})
bulwahn@35884
   519
        @ dest_conjunct_prem (th RS @{thm conjunct2})
bulwahn@35884
   520
    | _ => [th]
bulwahn@35884
   521
bulwahn@35884
   522
fun prove_casesrule ctxt (pred, (pre_cases_rule, nparams)) cases_rule =
bulwahn@35884
   523
  let
bulwahn@35884
   524
    val thy = ProofContext.theory_of ctxt
bulwahn@35884
   525
    val nargs = length (binder_types (fastype_of pred))
bulwahn@35884
   526
    fun PEEK f dependent_tactic st = dependent_tactic (f st) st
bulwahn@35884
   527
    fun meta_eq_of th = th RS @{thm eq_reflection}
bulwahn@35884
   528
    val tuple_rew_rules = map meta_eq_of [@{thm fst_conv}, @{thm snd_conv}, @{thm Pair_eq}]
bulwahn@35884
   529
    fun instantiate i n {context = ctxt, params = p, prems = prems,
bulwahn@35884
   530
      asms = a, concl = cl, schematics = s}  =
bulwahn@35884
   531
      let
bulwahn@35884
   532
        val (cases, (eqs, prems)) = apsnd (chop (nargs - nparams)) (chop n prems)
bulwahn@35884
   533
        val case_th = MetaSimplifier.simplify true
bulwahn@35884
   534
        (@{thm Predicate.eq_is_eq} :: map meta_eq_of eqs)
bulwahn@35884
   535
          (nth cases (i - 1))
bulwahn@35884
   536
        val prems' = maps (dest_conjunct_prem o MetaSimplifier.simplify true tuple_rew_rules) prems
bulwahn@35884
   537
        val pats = map (swap o HOLogic.dest_eq o HOLogic.dest_Trueprop) (take nargs (prems_of case_th))
bulwahn@35884
   538
        val (_, tenv) = fold (Pattern.match thy) pats (Vartab.empty, Vartab.empty)
bulwahn@35884
   539
        fun term_pair_of (ix, (ty,t)) = (Var (ix,ty), t)
bulwahn@35884
   540
        val inst = map (pairself (cterm_of thy) o term_pair_of) (Vartab.dest tenv)
bulwahn@35884
   541
        val thesis = Thm.instantiate ([], inst) case_th OF (replicate nargs @{thm refl}) OF prems'
bulwahn@35884
   542
      in
bulwahn@35884
   543
        (rtac thesis 1)
bulwahn@35884
   544
      end
bulwahn@35884
   545
    val tac =
bulwahn@35884
   546
      etac pre_cases_rule 1
bulwahn@35884
   547
      THEN
bulwahn@35884
   548
      (PEEK nprems_of
bulwahn@35884
   549
        (fn n =>
bulwahn@35884
   550
          ALLGOALS (fn i =>
bulwahn@35884
   551
            MetaSimplifier.rewrite_goal_tac [@{thm split_paired_all}] i
bulwahn@35884
   552
            THEN (SUBPROOF (instantiate i n) ctxt i))))
bulwahn@35884
   553
  in
bulwahn@35884
   554
    Goal.prove ctxt (Term.add_free_names cases_rule []) [] cases_rule (fn _ => tac)
bulwahn@35884
   555
  end
bulwahn@35884
   556
bulwahn@34948
   557
(** preprocessing rules **)
bulwahn@32667
   558
bulwahn@32667
   559
fun imp_prems_conv cv ct =
bulwahn@32667
   560
  case Thm.term_of ct of
bulwahn@32667
   561
    Const ("==>", _) $ _ $ _ => Conv.combination_conv (Conv.arg_conv cv) (imp_prems_conv cv) ct
bulwahn@32667
   562
  | _ => Conv.all_conv ct
bulwahn@32667
   563
bulwahn@32667
   564
fun Trueprop_conv cv ct =
bulwahn@32667
   565
  case Thm.term_of ct of
bulwahn@32667
   566
    Const ("Trueprop", _) $ _ => Conv.arg_conv cv ct  
bulwahn@35885
   567
  | _ => raise Fail "Trueprop_conv"
bulwahn@32667
   568
bulwahn@32667
   569
fun preprocess_intro thy rule =
bulwahn@32667
   570
  Conv.fconv_rule
bulwahn@32667
   571
    (imp_prems_conv
bulwahn@32667
   572
      (Trueprop_conv (Conv.try_conv (Conv.rewr_conv (Thm.symmetric @{thm Predicate.eq_is_eq})))))
bulwahn@32667
   573
    (Thm.transfer thy rule)
bulwahn@32667
   574
bulwahn@34948
   575
fun preprocess_elim thy elimrule =
bulwahn@32667
   576
  let
bulwahn@32667
   577
    fun replace_eqs (Const ("Trueprop", _) $ (Const ("op =", T) $ lhs $ rhs)) =
bulwahn@32667
   578
       HOLogic.mk_Trueprop (Const (@{const_name Predicate.eq}, T) $ lhs $ rhs)
bulwahn@32667
   579
     | replace_eqs t = t
bulwahn@33128
   580
    val ctxt = ProofContext.init thy
bulwahn@33128
   581
    val ((_, [elimrule]), ctxt') = Variable.import false [elimrule] ctxt
bulwahn@33128
   582
    val prems = Thm.prems_of elimrule
bulwahn@34948
   583
    val nargs = length (snd (strip_comb (HOLogic.dest_Trueprop (hd prems))))
bulwahn@32667
   584
    fun preprocess_case t =
bulwahn@33128
   585
      let
bulwahn@32667
   586
       val params = Logic.strip_params t
bulwahn@32667
   587
       val (assums1, assums2) = chop nargs (Logic.strip_assums_hyp t)
bulwahn@32667
   588
       val assums_hyp' = assums1 @ (map replace_eqs assums2)
bulwahn@33128
   589
      in
bulwahn@32667
   590
       list_all (params, Logic.list_implies (assums_hyp', Logic.strip_assums_concl t))
bulwahn@33128
   591
      end
bulwahn@32667
   592
    val cases' = map preprocess_case (tl prems)
bulwahn@32667
   593
    val elimrule' = Logic.list_implies ((hd prems) :: cases', Thm.concl_of elimrule)
bulwahn@32667
   594
    val bigeq = (Thm.symmetric (Conv.implies_concl_conv
bulwahn@32667
   595
      (MetaSimplifier.rewrite true [@{thm Predicate.eq_is_eq}])
bulwahn@32667
   596
        (cterm_of thy elimrule')))
bulwahn@35884
   597
    val tac = (fn _ => Skip_Proof.cheat_tac thy)
bulwahn@33109
   598
    val eq = Goal.prove ctxt' [] [] (Logic.mk_equals ((Thm.prop_of elimrule), elimrule')) tac
bulwahn@32667
   599
  in
bulwahn@33109
   600
    Thm.equal_elim eq elimrule |> singleton (Variable.export ctxt' ctxt)
bulwahn@32667
   601
  end;
bulwahn@32667
   602
bulwahn@33124
   603
fun expand_tuples_elim th = th
bulwahn@33124
   604
bulwahn@35887
   605
val no_compilation = ([], ([], []))
bulwahn@33483
   606
bulwahn@32667
   607
fun fetch_pred_data thy name =
bulwahn@32667
   608
  case try (Inductive.the_inductive (ProofContext.init thy)) name of
bulwahn@32667
   609
    SOME (info as (_, result)) => 
bulwahn@32667
   610
      let
bulwahn@32667
   611
        fun is_intro_of intro =
bulwahn@32667
   612
          let
bulwahn@32667
   613
            val (const, _) = strip_comb (HOLogic.dest_Trueprop (concl_of intro))
bulwahn@32667
   614
          in (fst (dest_Const const) = name) end;      
bulwahn@33752
   615
        val intros =
bulwahn@33124
   616
          (map (expand_tuples thy #> preprocess_intro thy) (filter is_intro_of (#intrs result)))
bulwahn@33146
   617
        val index = find_index (fn s => s = name) (#names (fst info))
bulwahn@33146
   618
        val pre_elim = nth (#elims result) index
bulwahn@33146
   619
        val pred = nth (#preds result) index
bulwahn@35884
   620
        val nparams = length (Inductive.params_of (#raw_induct result))
bulwahn@35884
   621
        val ctxt = ProofContext.init thy
bulwahn@35884
   622
        val elim_t = mk_casesrule ctxt pred intros
bulwahn@33124
   623
        val elim =
bulwahn@35884
   624
          prove_casesrule ctxt (pred, (pre_elim, nparams)) elim_t
bulwahn@32667
   625
      in
bulwahn@34948
   626
        mk_pred_data ((intros, SOME elim), no_compilation)
bulwahn@33483
   627
      end
bulwahn@32667
   628
  | NONE => error ("No such predicate: " ^ quote name)
bulwahn@33124
   629
bulwahn@34948
   630
fun add_predfun_data name mode data =
bulwahn@32667
   631
  let
bulwahn@35887
   632
    val add = (apsnd o apsnd o apfst) (cons (mode, mk_predfun_data data))
bulwahn@32667
   633
  in PredData.map (Graph.map_node name (map_pred_data add)) end
bulwahn@32667
   634
bulwahn@32667
   635
fun is_inductive_predicate thy name =
bulwahn@32667
   636
  is_some (try (Inductive.the_inductive (ProofContext.init thy)) name)
bulwahn@32667
   637
bulwahn@32667
   638
fun depending_preds_of thy (key, value) =
bulwahn@32667
   639
  let
bulwahn@32667
   640
    val intros = (#intros o rep_pred_data) value
bulwahn@32667
   641
  in
bulwahn@32667
   642
    fold Term.add_const_names (map Thm.prop_of intros) []
bulwahn@33482
   643
      |> filter (fn c => (not (c = key)) andalso
bulwahn@33482
   644
        (is_inductive_predicate thy c orelse is_registered thy c))
bulwahn@32667
   645
  end;
bulwahn@32667
   646
bulwahn@33629
   647
fun add_intro thm thy =
bulwahn@33629
   648
  let
bulwahn@34948
   649
    val (name, T) = dest_Const (fst (strip_intro_concl thm))
bulwahn@33629
   650
    fun cons_intro gr =
bulwahn@32667
   651
     case try (Graph.get_node gr) name of
bulwahn@32667
   652
       SOME pred_data => Graph.map_node name (map_pred_data
bulwahn@34948
   653
         (apfst (fn (intros, elim) => (intros @ [thm], elim)))) gr
bulwahn@34948
   654
     | NONE => Graph.new_node (name, mk_pred_data (([thm], NONE), no_compilation)) gr
bulwahn@32667
   655
  in PredData.map cons_intro thy end
bulwahn@32667
   656
bulwahn@33629
   657
fun set_elim thm =
bulwahn@33629
   658
  let
bulwahn@32667
   659
    val (name, _) = dest_Const (fst 
bulwahn@32667
   660
      (strip_comb (HOLogic.dest_Trueprop (hd (prems_of thm)))))
bulwahn@34948
   661
    fun set (intros, _) = (intros, SOME thm)
bulwahn@32667
   662
  in PredData.map (Graph.map_node name (map_pred_data (apfst set))) end
bulwahn@32667
   663
bulwahn@34948
   664
fun register_predicate (constname, pre_intros, pre_elim) thy =
bulwahn@33629
   665
  let
bulwahn@33752
   666
    val intros = map (preprocess_intro thy) pre_intros
bulwahn@34948
   667
    val elim = preprocess_elim thy pre_elim
bulwahn@32667
   668
  in
bulwahn@33146
   669
    if not (member (op =) (Graph.keys (PredData.get thy)) constname) then
bulwahn@32668
   670
      PredData.map
bulwahn@33482
   671
        (Graph.new_node (constname,
bulwahn@34948
   672
          mk_pred_data ((intros, SOME elim), no_compilation))) thy
bulwahn@32668
   673
    else thy
bulwahn@32667
   674
  end
bulwahn@32667
   675
bulwahn@33146
   676
fun register_intros (constname, pre_intros) thy =
bulwahn@32668
   677
  let
bulwahn@33146
   678
    val T = Sign.the_const_type thy constname
bulwahn@34948
   679
    fun constname_of_intro intr = fst (dest_Const (fst (strip_intro_concl intr)))
bulwahn@33146
   680
    val _ = if not (forall (fn intr => constname_of_intro intr = constname) pre_intros) then
bulwahn@33146
   681
      error ("register_intros: Introduction rules of different constants are used\n" ^
bulwahn@33146
   682
        "expected rules for " ^ constname ^ ", but received rules for " ^
bulwahn@33146
   683
          commas (map constname_of_intro pre_intros))
bulwahn@33146
   684
      else ()
bulwahn@33146
   685
    val pred = Const (constname, T)
bulwahn@32672
   686
    val pre_elim = 
wenzelm@35021
   687
      (Drule.export_without_context o Skip_Proof.make_thm thy)
bulwahn@34948
   688
      (mk_casesrule (ProofContext.init thy) pred pre_intros)
bulwahn@34948
   689
  in register_predicate (constname, pre_intros, pre_elim) thy end
bulwahn@32668
   690
bulwahn@34948
   691
fun defined_function_of compilation pred =
bulwahn@32667
   692
  let
bulwahn@35887
   693
    val set = (apsnd o apfst) (cons (compilation, []))
bulwahn@32667
   694
  in
bulwahn@32667
   695
    PredData.map (Graph.map_node pred (map_pred_data set))
bulwahn@32667
   696
  end
bulwahn@32667
   697
bulwahn@34948
   698
fun set_function_name compilation pred mode name =
bulwahn@32667
   699
  let
bulwahn@35887
   700
    val set = (apsnd o apfst)
bulwahn@34948
   701
      (AList.map_default (op =) (compilation, [(mode, name)]) (cons (mode, name)))
bulwahn@33473
   702
  in
bulwahn@33473
   703
    PredData.map (Graph.map_node pred (map_pred_data set))
bulwahn@33473
   704
  end
bulwahn@33473
   705
bulwahn@34948
   706
fun set_needs_random name modes =
bulwahn@33473
   707
  let
bulwahn@35887
   708
    val set = (apsnd o apsnd o apsnd) (K modes)
bulwahn@32667
   709
  in
bulwahn@34948
   710
    PredData.map (Graph.map_node name (map_pred_data set))
bulwahn@32667
   711
  end
bulwahn@32667
   712
bulwahn@36038
   713
(* registration of alternative function names *)
bulwahn@36038
   714
bulwahn@36038
   715
structure Alt_Compilations_Data = Theory_Data
bulwahn@36038
   716
(
bulwahn@36038
   717
  type T = (mode * (compilation_funs -> typ -> term)) list Symtab.table;
bulwahn@36038
   718
  val empty = Symtab.empty;
bulwahn@36038
   719
  val extend = I;
bulwahn@36056
   720
  val merge = Symtab.merge ((K true)
bulwahn@36056
   721
    : ((mode * (compilation_funs -> typ -> term)) list *
bulwahn@36056
   722
      (mode * (compilation_funs -> typ -> term)) list -> bool));
bulwahn@36038
   723
);
bulwahn@36038
   724
bulwahn@36038
   725
fun alternative_compilation_of thy pred_name mode =
bulwahn@36038
   726
  AList.lookup eq_mode (Symtab.lookup_list (Alt_Compilations_Data.get thy) pred_name) mode
bulwahn@36038
   727
bulwahn@36038
   728
fun force_modes_and_compilations pred_name compilations =
bulwahn@36038
   729
  let
bulwahn@36038
   730
    (* thm refl is a dummy thm *)
bulwahn@36038
   731
    val modes = map fst compilations
bulwahn@36038
   732
    val (needs_random, non_random_modes) = pairself (map fst)
bulwahn@36038
   733
      (List.partition (fn (m, (fun_name, random)) => random) compilations)
bulwahn@36038
   734
    val non_random_dummys = map (rpair "dummy") non_random_modes
bulwahn@36038
   735
    val all_dummys = map (rpair "dummy") modes
bulwahn@36038
   736
    val dummy_function_names = map (rpair all_dummys) Predicate_Compile_Aux.random_compilations
bulwahn@36038
   737
      @ map (rpair non_random_dummys) Predicate_Compile_Aux.non_random_compilations
bulwahn@36038
   738
    val alt_compilations = map (apsnd fst) compilations
bulwahn@36038
   739
  in
bulwahn@36038
   740
    PredData.map (Graph.new_node
bulwahn@36038
   741
      (pred_name, mk_pred_data (([], SOME @{thm refl}), (dummy_function_names, ([], needs_random)))))
bulwahn@36038
   742
    #> Alt_Compilations_Data.map (Symtab.insert (K false) (pred_name, alt_compilations))
bulwahn@36038
   743
  end
bulwahn@36038
   744
bulwahn@36038
   745
fun functional_compilation fun_name mode compfuns T =
bulwahn@36038
   746
  let
bulwahn@36038
   747
    val (inpTs, outpTs) = split_map_modeT (fn _ => fn T => (SOME T, NONE))
bulwahn@36038
   748
      mode (binder_types T)
bulwahn@36038
   749
    val bs = map (pair "x") inpTs
bulwahn@36038
   750
    val bounds = map Bound (rev (0 upto (length bs) - 1))
bulwahn@36038
   751
    val f = Const (fun_name, inpTs ---> HOLogic.mk_tupleT outpTs)
bulwahn@36038
   752
  in list_abs (bs, mk_single compfuns (list_comb (f, bounds))) end
bulwahn@36038
   753
bulwahn@36038
   754
fun register_alternative_function pred_name mode fun_name =
bulwahn@36038
   755
  Alt_Compilations_Data.map (Symtab.insert_list (eq_pair eq_mode (K false))
bulwahn@36038
   756
    (pred_name, (mode, functional_compilation fun_name mode)))
bulwahn@36038
   757
bulwahn@36038
   758
fun force_modes_and_functions pred_name fun_names =
bulwahn@36038
   759
  force_modes_and_compilations pred_name
bulwahn@36038
   760
    (map (fn (mode, (fun_name, random)) => (mode, (functional_compilation fun_name mode, random)))
bulwahn@36038
   761
    fun_names)
bulwahn@36038
   762
bulwahn@36019
   763
(* compilation modifiers *)
bulwahn@36019
   764
bulwahn@36019
   765
structure Comp_Mod =
bulwahn@36019
   766
struct
bulwahn@36019
   767
bulwahn@36019
   768
datatype comp_modifiers = Comp_Modifiers of
bulwahn@36019
   769
{
bulwahn@36019
   770
  compilation : compilation,
bulwahn@36019
   771
  function_name_prefix : string,
bulwahn@36019
   772
  compfuns : compilation_funs,
bulwahn@36019
   773
  mk_random : typ -> term list -> term,
bulwahn@36019
   774
  modify_funT : typ -> typ,
bulwahn@36019
   775
  additional_arguments : string list -> term list,
bulwahn@36019
   776
  wrap_compilation : compilation_funs -> string -> typ -> mode -> term list -> term -> term,
bulwahn@36019
   777
  transform_additional_arguments : indprem -> term list -> term list
bulwahn@36019
   778
}
bulwahn@36019
   779
bulwahn@36019
   780
fun dest_comp_modifiers (Comp_Modifiers c) = c
bulwahn@36019
   781
bulwahn@36019
   782
val compilation = #compilation o dest_comp_modifiers
bulwahn@36019
   783
val function_name_prefix = #function_name_prefix o dest_comp_modifiers
bulwahn@36019
   784
val compfuns = #compfuns o dest_comp_modifiers
bulwahn@36019
   785
bulwahn@36019
   786
val mk_random = #mk_random o dest_comp_modifiers
bulwahn@36019
   787
val funT_of' = funT_of o compfuns
bulwahn@36019
   788
val modify_funT = #modify_funT o dest_comp_modifiers
bulwahn@36019
   789
fun funT_of comp mode = modify_funT comp o funT_of' comp mode
bulwahn@36019
   790
bulwahn@36019
   791
val additional_arguments = #additional_arguments o dest_comp_modifiers
bulwahn@36019
   792
val wrap_compilation = #wrap_compilation o dest_comp_modifiers
bulwahn@36019
   793
val transform_additional_arguments = #transform_additional_arguments o dest_comp_modifiers
bulwahn@36019
   794
bulwahn@36019
   795
end;
bulwahn@36019
   796
bulwahn@36019
   797
val depth_limited_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36019
   798
  {
bulwahn@36019
   799
  compilation = Depth_Limited,
bulwahn@36019
   800
  function_name_prefix = "depth_limited_",
bulwahn@36019
   801
  compfuns = PredicateCompFuns.compfuns,
bulwahn@36019
   802
  mk_random = (fn _ => error "no random generation"),
bulwahn@36019
   803
  additional_arguments = fn names =>
bulwahn@36019
   804
    let
bulwahn@36019
   805
      val depth_name = Name.variant names "depth"
bulwahn@36019
   806
    in [Free (depth_name, @{typ code_numeral})] end,
bulwahn@36019
   807
  modify_funT = (fn T => let val (Ts, U) = strip_type T
bulwahn@36019
   808
  val Ts' = [@{typ code_numeral}] in (Ts @ Ts') ---> U end),
bulwahn@36019
   809
  wrap_compilation =
bulwahn@36019
   810
    fn compfuns => fn s => fn T => fn mode => fn additional_arguments => fn compilation =>
bulwahn@36019
   811
    let
bulwahn@36019
   812
      val [depth] = additional_arguments
bulwahn@36019
   813
      val (_, Ts) = split_modeT' mode (binder_types T)
bulwahn@36019
   814
      val T' = mk_predT compfuns (HOLogic.mk_tupleT Ts)
bulwahn@36019
   815
      val if_const = Const (@{const_name "If"}, @{typ bool} --> T' --> T' --> T')
bulwahn@36019
   816
    in
bulwahn@36019
   817
      if_const $ HOLogic.mk_eq (depth, @{term "0 :: code_numeral"})
bulwahn@36019
   818
        $ mk_bot compfuns (dest_predT compfuns T')
bulwahn@36019
   819
        $ compilation
bulwahn@36019
   820
    end,
bulwahn@36019
   821
  transform_additional_arguments =
bulwahn@36019
   822
    fn prem => fn additional_arguments =>
bulwahn@36019
   823
    let
bulwahn@36019
   824
      val [depth] = additional_arguments
bulwahn@36019
   825
      val depth' =
bulwahn@36019
   826
        Const (@{const_name Groups.minus}, @{typ "code_numeral => code_numeral => code_numeral"})
bulwahn@36019
   827
          $ depth $ Const (@{const_name Groups.one}, @{typ "Code_Numeral.code_numeral"})
bulwahn@36019
   828
    in [depth'] end
bulwahn@36019
   829
  }
bulwahn@36019
   830
bulwahn@36019
   831
val random_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36019
   832
  {
bulwahn@36019
   833
  compilation = Random,
bulwahn@36019
   834
  function_name_prefix = "random_",
bulwahn@36019
   835
  compfuns = PredicateCompFuns.compfuns,
bulwahn@36019
   836
  mk_random = (fn T => fn additional_arguments =>
bulwahn@36019
   837
  list_comb (Const(@{const_name Quickcheck.iter},
bulwahn@36019
   838
  [@{typ code_numeral}, @{typ code_numeral}, @{typ Random.seed}] ---> 
bulwahn@36019
   839
    PredicateCompFuns.mk_predT T), additional_arguments)),
bulwahn@36019
   840
  modify_funT = (fn T =>
bulwahn@36019
   841
    let
bulwahn@36019
   842
      val (Ts, U) = strip_type T
bulwahn@36019
   843
      val Ts' = [@{typ code_numeral}, @{typ code_numeral}, @{typ "code_numeral * code_numeral"}]
bulwahn@36019
   844
    in (Ts @ Ts') ---> U end),
bulwahn@36019
   845
  additional_arguments = (fn names =>
bulwahn@36019
   846
    let
bulwahn@36019
   847
      val [nrandom, size, seed] = Name.variant_list names ["nrandom", "size", "seed"]
bulwahn@36019
   848
    in
bulwahn@36019
   849
      [Free (nrandom, @{typ code_numeral}), Free (size, @{typ code_numeral}),
bulwahn@36019
   850
        Free (seed, @{typ "code_numeral * code_numeral"})]
bulwahn@36019
   851
    end),
bulwahn@36019
   852
  wrap_compilation = K (K (K (K (K I))))
bulwahn@36019
   853
    : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
bulwahn@36019
   854
  transform_additional_arguments = K I : (indprem -> term list -> term list)
bulwahn@36019
   855
  }
bulwahn@36019
   856
bulwahn@36019
   857
val depth_limited_random_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36019
   858
  {
bulwahn@36019
   859
  compilation = Depth_Limited_Random,
bulwahn@36019
   860
  function_name_prefix = "depth_limited_random_",
bulwahn@36019
   861
  compfuns = PredicateCompFuns.compfuns,
bulwahn@36019
   862
  mk_random = (fn T => fn additional_arguments =>
bulwahn@36019
   863
  list_comb (Const(@{const_name Quickcheck.iter},
bulwahn@36019
   864
  [@{typ code_numeral}, @{typ code_numeral}, @{typ Random.seed}] ---> 
bulwahn@36019
   865
    PredicateCompFuns.mk_predT T), tl additional_arguments)),
bulwahn@36019
   866
  modify_funT = (fn T =>
bulwahn@36019
   867
    let
bulwahn@36019
   868
      val (Ts, U) = strip_type T
bulwahn@36019
   869
      val Ts' = [@{typ code_numeral}, @{typ code_numeral}, @{typ code_numeral},
bulwahn@36019
   870
        @{typ "code_numeral * code_numeral"}]
bulwahn@36019
   871
    in (Ts @ Ts') ---> U end),
bulwahn@36019
   872
  additional_arguments = (fn names =>
bulwahn@36019
   873
    let
bulwahn@36019
   874
      val [depth, nrandom, size, seed] = Name.variant_list names ["depth", "nrandom", "size", "seed"]
bulwahn@36019
   875
    in
bulwahn@36019
   876
      [Free (depth, @{typ code_numeral}), Free (nrandom, @{typ code_numeral}),
bulwahn@36019
   877
        Free (size, @{typ code_numeral}), Free (seed, @{typ "code_numeral * code_numeral"})]
bulwahn@36019
   878
    end),
bulwahn@36019
   879
  wrap_compilation =
bulwahn@36019
   880
  fn compfuns => fn s => fn T => fn mode => fn additional_arguments => fn compilation =>
bulwahn@36019
   881
    let
bulwahn@36019
   882
      val depth = hd (additional_arguments)
bulwahn@36019
   883
      val (_, Ts) = split_map_modeT (fn m => fn T => (SOME (funT_of compfuns m T), NONE))
bulwahn@36019
   884
        mode (binder_types T)
bulwahn@36019
   885
      val T' = mk_predT compfuns (HOLogic.mk_tupleT Ts)
bulwahn@36019
   886
      val if_const = Const (@{const_name "If"}, @{typ bool} --> T' --> T' --> T')
bulwahn@36019
   887
    in
bulwahn@36019
   888
      if_const $ HOLogic.mk_eq (depth, @{term "0 :: code_numeral"})
bulwahn@36019
   889
        $ mk_bot compfuns (dest_predT compfuns T')
bulwahn@36019
   890
        $ compilation
bulwahn@36019
   891
    end,
bulwahn@36019
   892
  transform_additional_arguments =
bulwahn@36019
   893
    fn prem => fn additional_arguments =>
bulwahn@36019
   894
    let
bulwahn@36019
   895
      val [depth, nrandom, size, seed] = additional_arguments
bulwahn@36019
   896
      val depth' =
bulwahn@36019
   897
        Const (@{const_name Groups.minus}, @{typ "code_numeral => code_numeral => code_numeral"})
bulwahn@36019
   898
          $ depth $ Const (@{const_name Groups.one}, @{typ "Code_Numeral.code_numeral"})
bulwahn@36019
   899
    in [depth', nrandom, size, seed] end
bulwahn@36019
   900
}
bulwahn@36019
   901
bulwahn@36019
   902
val predicate_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36019
   903
  {
bulwahn@36019
   904
  compilation = Pred,
bulwahn@36019
   905
  function_name_prefix = "",
bulwahn@36019
   906
  compfuns = PredicateCompFuns.compfuns,
bulwahn@36019
   907
  mk_random = (fn _ => error "no random generation"),
bulwahn@36019
   908
  modify_funT = I,
bulwahn@36019
   909
  additional_arguments = K [],
bulwahn@36019
   910
  wrap_compilation = K (K (K (K (K I))))
bulwahn@36019
   911
   : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
bulwahn@36019
   912
  transform_additional_arguments = K I : (indprem -> term list -> term list)
bulwahn@36019
   913
  }
bulwahn@36019
   914
bulwahn@36019
   915
val annotated_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36019
   916
  {
bulwahn@36019
   917
  compilation = Annotated,
bulwahn@36019
   918
  function_name_prefix = "annotated_",
bulwahn@36019
   919
  compfuns = PredicateCompFuns.compfuns,
bulwahn@36019
   920
  mk_random = (fn _ => error "no random generation"),
bulwahn@36019
   921
  modify_funT = I,
bulwahn@36019
   922
  additional_arguments = K [],
bulwahn@36019
   923
  wrap_compilation =
bulwahn@36019
   924
    fn compfuns => fn s => fn T => fn mode => fn additional_arguments => fn compilation =>
bulwahn@36019
   925
      mk_tracing ("calling predicate " ^ s ^
bulwahn@36019
   926
        " with mode " ^ string_of_mode mode) compilation,
bulwahn@36019
   927
  transform_additional_arguments = K I : (indprem -> term list -> term list)
bulwahn@36019
   928
  }
bulwahn@36019
   929
bulwahn@36019
   930
val dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36019
   931
  {
bulwahn@36019
   932
  compilation = DSeq,
bulwahn@36019
   933
  function_name_prefix = "dseq_",
bulwahn@36019
   934
  compfuns = DSequence_CompFuns.compfuns,
bulwahn@36019
   935
  mk_random = (fn _ => error "no random generation"),
bulwahn@36019
   936
  modify_funT = I,
bulwahn@36019
   937
  additional_arguments = K [],
bulwahn@36019
   938
  wrap_compilation = K (K (K (K (K I))))
bulwahn@36019
   939
   : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
bulwahn@36019
   940
  transform_additional_arguments = K I : (indprem -> term list -> term list)
bulwahn@36019
   941
  }
bulwahn@36019
   942
bulwahn@36019
   943
val pos_random_dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36019
   944
  {
bulwahn@36019
   945
  compilation = Pos_Random_DSeq,
bulwahn@36019
   946
  function_name_prefix = "random_dseq_",
bulwahn@36019
   947
  compfuns = Random_Sequence_CompFuns.compfuns,
bulwahn@36019
   948
  mk_random = (fn T => fn additional_arguments =>
bulwahn@36019
   949
  let
bulwahn@36019
   950
    val random = Const ("Quickcheck.random_class.random",
bulwahn@36019
   951
      @{typ code_numeral} --> @{typ Random.seed} -->
bulwahn@36019
   952
        HOLogic.mk_prodT (HOLogic.mk_prodT (T, @{typ "unit => term"}), @{typ Random.seed}))
bulwahn@36019
   953
  in
bulwahn@36019
   954
    Const ("Random_Sequence.Random", (@{typ code_numeral} --> @{typ Random.seed} -->
bulwahn@36019
   955
      HOLogic.mk_prodT (HOLogic.mk_prodT (T, @{typ "unit => term"}), @{typ Random.seed})) -->
bulwahn@36019
   956
      Random_Sequence_CompFuns.mk_random_dseqT T) $ random
bulwahn@36019
   957
  end),
bulwahn@36019
   958
bulwahn@36019
   959
  modify_funT = I,
bulwahn@36019
   960
  additional_arguments = K [],
bulwahn@36019
   961
  wrap_compilation = K (K (K (K (K I))))
bulwahn@36019
   962
   : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
bulwahn@36019
   963
  transform_additional_arguments = K I : (indprem -> term list -> term list)
bulwahn@36019
   964
  }
bulwahn@36019
   965
bulwahn@36019
   966
val neg_random_dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36019
   967
  {
bulwahn@36019
   968
  compilation = Neg_Random_DSeq,
bulwahn@36019
   969
  function_name_prefix = "random_dseq_neg_",
bulwahn@36019
   970
  compfuns = Random_Sequence_CompFuns.compfuns,
bulwahn@36019
   971
  mk_random = (fn _ => error "no random generation"),
bulwahn@36019
   972
  modify_funT = I,
bulwahn@36019
   973
  additional_arguments = K [],
bulwahn@36019
   974
  wrap_compilation = K (K (K (K (K I))))
bulwahn@36019
   975
   : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
bulwahn@36019
   976
  transform_additional_arguments = K I : (indprem -> term list -> term list)
bulwahn@36019
   977
  }
bulwahn@36019
   978
bulwahn@36019
   979
bulwahn@36019
   980
val new_pos_random_dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36019
   981
  {
bulwahn@36019
   982
  compilation = New_Pos_Random_DSeq,
bulwahn@36019
   983
  function_name_prefix = "new_random_dseq_",
bulwahn@36019
   984
  compfuns = New_Pos_Random_Sequence_CompFuns.compfuns,
bulwahn@36019
   985
  mk_random = (fn T => fn additional_arguments =>
bulwahn@36019
   986
  let
bulwahn@36019
   987
    val random = Const ("Quickcheck.random_class.random",
bulwahn@36019
   988
      @{typ code_numeral} --> @{typ Random.seed} -->
bulwahn@36019
   989
        HOLogic.mk_prodT (HOLogic.mk_prodT (T, @{typ "unit => term"}), @{typ Random.seed}))
bulwahn@36019
   990
  in
bulwahn@36019
   991
    Const ("New_Random_Sequence.Random", (@{typ code_numeral} --> @{typ Random.seed} -->
bulwahn@36019
   992
      HOLogic.mk_prodT (HOLogic.mk_prodT (T, @{typ "unit => term"}), @{typ Random.seed})) -->
bulwahn@36019
   993
      New_Pos_Random_Sequence_CompFuns.mk_pos_random_dseqT T) $ random
bulwahn@36019
   994
  end),
bulwahn@36019
   995
  modify_funT = I,
bulwahn@36019
   996
  additional_arguments = K [],
bulwahn@36019
   997
  wrap_compilation = K (K (K (K (K I))))
bulwahn@36019
   998
   : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
bulwahn@36019
   999
  transform_additional_arguments = K I : (indprem -> term list -> term list)
bulwahn@36019
  1000
  }
bulwahn@36019
  1001
bulwahn@36019
  1002
val new_neg_random_dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36019
  1003
  {
bulwahn@36019
  1004
  compilation = New_Neg_Random_DSeq,
bulwahn@36019
  1005
  function_name_prefix = "new_random_dseq_neg_",
bulwahn@36019
  1006
  compfuns = New_Neg_Random_Sequence_CompFuns.compfuns,
bulwahn@36019
  1007
  mk_random = (fn _ => error "no random generation"),
bulwahn@36019
  1008
  modify_funT = I,
bulwahn@36019
  1009
  additional_arguments = K [],
bulwahn@36019
  1010
  wrap_compilation = K (K (K (K (K I))))
bulwahn@36019
  1011
   : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
bulwahn@36019
  1012
  transform_additional_arguments = K I : (indprem -> term list -> term list)
bulwahn@36019
  1013
  }
bulwahn@36019
  1014
bulwahn@36019
  1015
fun negative_comp_modifiers_of comp_modifiers =
bulwahn@36019
  1016
    (case Comp_Mod.compilation comp_modifiers of
bulwahn@36019
  1017
      Pos_Random_DSeq => neg_random_dseq_comp_modifiers
bulwahn@36019
  1018
    | Neg_Random_DSeq => pos_random_dseq_comp_modifiers
bulwahn@36019
  1019
    | New_Pos_Random_DSeq => new_neg_random_dseq_comp_modifiers
bulwahn@36019
  1020
    | New_Neg_Random_DSeq => new_pos_random_dseq_comp_modifiers
bulwahn@36019
  1021
    | c => comp_modifiers)
bulwahn@36019
  1022
bulwahn@34948
  1023
(** mode analysis **)
bulwahn@32672
  1024
bulwahn@35411
  1025
type mode_analysis_options = {use_random : bool, reorder_premises : bool, infer_pos_and_neg_modes : bool}
bulwahn@35324
  1026
bulwahn@32667
  1027
fun is_constrt thy =
bulwahn@32667
  1028
  let
bulwahn@32667
  1029
    val cnstrs = flat (maps
bulwahn@32667
  1030
      (map (fn (_, (Tname, _, cs)) => map (apsnd (rpair Tname o length)) cs) o #descr o snd)
bulwahn@32667
  1031
      (Symtab.dest (Datatype.get_all thy)));
bulwahn@32667
  1032
    fun check t = (case strip_comb t of
bulwahn@32667
  1033
        (Free _, []) => true
bulwahn@32667
  1034
      | (Const (s, T), ts) => (case (AList.lookup (op =) cnstrs s, body_type T) of
bulwahn@33482
  1035
            (SOME (i, Tname), Type (Tname', _)) =>
bulwahn@33482
  1036
              length ts = i andalso Tname = Tname' andalso forall check ts
bulwahn@32667
  1037
          | _ => false)
bulwahn@32667
  1038
      | _ => false)
bulwahn@32667
  1039
  in check end;
bulwahn@32667
  1040
bulwahn@32667
  1041
(*** check if a type is an equality type (i.e. doesn't contain fun)
bulwahn@32667
  1042
  FIXME this is only an approximation ***)
bulwahn@32667
  1043
fun is_eqT (Type (s, Ts)) = s <> "fun" andalso forall is_eqT Ts
bulwahn@32667
  1044
  | is_eqT _ = true;
bulwahn@32667
  1045
bulwahn@32667
  1046
fun term_vs tm = fold_aterms (fn Free (x, T) => cons x | _ => I) tm [];
bulwahn@32667
  1047
val terms_vs = distinct (op =) o maps term_vs;
bulwahn@32667
  1048
bulwahn@32667
  1049
(** collect all Frees in a term (with duplicates!) **)
bulwahn@32667
  1050
fun term_vTs tm =
bulwahn@32667
  1051
  fold_aterms (fn Free xT => cons xT | _ => I) tm [];
bulwahn@32667
  1052
bulwahn@33138
  1053
fun subsets i j =
bulwahn@33138
  1054
  if i <= j then
bulwahn@33138
  1055
    let
bulwahn@33138
  1056
      fun merge xs [] = xs
bulwahn@33138
  1057
        | merge [] ys = ys
bulwahn@33138
  1058
        | merge (x::xs) (y::ys) = if length x >= length y then x::merge xs (y::ys)
bulwahn@33138
  1059
            else y::merge (x::xs) ys;
bulwahn@33138
  1060
      val is = subsets (i+1) j
bulwahn@33138
  1061
    in merge (map (fn ks => i::ks) is) is end
bulwahn@33138
  1062
  else [[]];
bulwahn@32667
  1063
bulwahn@35324
  1064
fun print_failed_mode options thy modes p (pol, 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@34948
  1068
        p ^ " violates mode " ^ string_of_mode m)
bulwahn@33130
  1069
    in () end
bulwahn@33130
  1070
  else ()
bulwahn@33130
  1071
bulwahn@35324
  1072
fun error_of p (pol, m) is =
bulwahn@35885
  1073
  "  Clauses " ^ commas (map (fn i => string_of_int (i + 1)) is) ^ " of " ^
bulwahn@35885
  1074
        p ^ " violates mode " ^ string_of_mode m
bulwahn@34948
  1075
bulwahn@34948
  1076
fun is_all_input mode =
bulwahn@34948
  1077
  let
bulwahn@34948
  1078
    fun is_all_input' (Fun _) = true
bulwahn@34948
  1079
      | is_all_input' (Pair (m1, m2)) = is_all_input' m1 andalso is_all_input' m2
bulwahn@34948
  1080
      | is_all_input' Input = true
bulwahn@34948
  1081
      | is_all_input' Output = false
bulwahn@34948
  1082
  in
bulwahn@34948
  1083
    forall is_all_input' (strip_fun_mode mode)
bulwahn@34948
  1084
  end
bulwahn@34948
  1085
bulwahn@34948
  1086
fun all_input_of T =
bulwahn@34948
  1087
  let
bulwahn@34948
  1088
    val (Ts, U) = strip_type T
bulwahn@34948
  1089
    fun input_of (Type ("*", [T1, T2])) = Pair (input_of T1, input_of T2)
bulwahn@34948
  1090
      | input_of _ = Input
bulwahn@34948
  1091
  in
bulwahn@34948
  1092
    if U = HOLogic.boolT then
bulwahn@34948
  1093
      fold_rev (curry Fun) (map input_of Ts) Bool
bulwahn@34948
  1094
    else
bulwahn@35885
  1095
      raise Fail "all_input_of: not a predicate"
bulwahn@34948
  1096
  end
bulwahn@34948
  1097
bulwahn@34948
  1098
fun partial_hd [] = NONE
bulwahn@34948
  1099
  | partial_hd (x :: xs) = SOME x
bulwahn@34948
  1100
bulwahn@34948
  1101
fun term_vs tm = fold_aterms (fn Free (x, T) => cons x | _ => I) tm [];
bulwahn@34948
  1102
val terms_vs = distinct (op =) o maps term_vs;
bulwahn@34948
  1103
bulwahn@34948
  1104
fun input_mode T =
bulwahn@34948
  1105
  let
bulwahn@34948
  1106
    val (Ts, U) = strip_type T
bulwahn@34948
  1107
  in
bulwahn@34948
  1108
    fold_rev (curry Fun) (map (K Input) Ts) Input
bulwahn@34948
  1109
  end
bulwahn@34948
  1110
bulwahn@34948
  1111
fun output_mode T =
bulwahn@34948
  1112
  let
bulwahn@34948
  1113
    val (Ts, U) = strip_type T
bulwahn@34948
  1114
  in
bulwahn@34948
  1115
    fold_rev (curry Fun) (map (K Output) Ts) Output
bulwahn@34948
  1116
  end
bulwahn@34948
  1117
bulwahn@35891
  1118
fun is_invertible_function ctxt (Const (f, _)) = is_constr ctxt f
bulwahn@35891
  1119
  | is_invertible_function ctxt _ = false
bulwahn@34948
  1120
bulwahn@35891
  1121
fun non_invertible_subterms ctxt (t as Free _) = []
bulwahn@35891
  1122
  | non_invertible_subterms ctxt t = 
bulwahn@35891
  1123
  let
bulwahn@35891
  1124
    val (f, args) = strip_comb t
bulwahn@35891
  1125
  in
bulwahn@35891
  1126
    if is_invertible_function ctxt f then
bulwahn@35891
  1127
      maps (non_invertible_subterms ctxt) args
bulwahn@34948
  1128
    else
bulwahn@34948
  1129
      [t]
bulwahn@35891
  1130
  end
bulwahn@33752
  1131
bulwahn@35891
  1132
fun collect_non_invertible_subterms ctxt (f as Free _) (names, eqs) = (f, (names, eqs))
bulwahn@35891
  1133
  | collect_non_invertible_subterms ctxt t (names, eqs) =
bulwahn@34948
  1134
    case (strip_comb t) of (f, args) =>
bulwahn@35891
  1135
      if is_invertible_function ctxt f then
bulwahn@34948
  1136
          let
bulwahn@34948
  1137
            val (args', (names', eqs')) =
bulwahn@35891
  1138
              fold_map (collect_non_invertible_subterms ctxt) args (names, eqs)
bulwahn@34948
  1139
          in
bulwahn@34948
  1140
            (list_comb (f, args'), (names', eqs'))
bulwahn@34948
  1141
          end
bulwahn@34948
  1142
        else
bulwahn@34948
  1143
          let
bulwahn@34948
  1144
            val s = Name.variant names "x"
bulwahn@34948
  1145
            val v = Free (s, fastype_of t)
bulwahn@34948
  1146
          in
bulwahn@34948
  1147
            (v, (s :: names, HOLogic.mk_eq (v, t) :: eqs))
bulwahn@34948
  1148
          end
bulwahn@34948
  1149
(*
bulwahn@34948
  1150
  if is_constrt thy t then (t, (names, eqs)) else
bulwahn@34948
  1151
    let
bulwahn@34948
  1152
      val s = Name.variant names "x"
bulwahn@34948
  1153
      val v = Free (s, fastype_of t)
bulwahn@34948
  1154
    in (v, (s::names, HOLogic.mk_eq (v, t)::eqs)) end;
bulwahn@34948
  1155
*)
bulwahn@34948
  1156
bulwahn@34948
  1157
fun is_possible_output thy vs t =
bulwahn@34948
  1158
  forall
bulwahn@34948
  1159
    (fn t => is_eqT (fastype_of t) andalso forall (member (op =) vs) (term_vs t))
bulwahn@35891
  1160
      (non_invertible_subterms (ProofContext.init thy) t)
bulwahn@35324
  1161
  andalso
bulwahn@35324
  1162
    (forall (is_eqT o snd)
bulwahn@35324
  1163
      (inter (fn ((f', _), f) => f = f') vs (Term.add_frees t [])))
bulwahn@33752
  1164
bulwahn@35891
  1165
fun vars_of_destructable_term ctxt (Free (x, _)) = [x]
bulwahn@35891
  1166
  | vars_of_destructable_term ctxt t =
bulwahn@35891
  1167
  let
bulwahn@35891
  1168
    val (f, args) = strip_comb t
bulwahn@35891
  1169
  in
bulwahn@35891
  1170
    if is_invertible_function ctxt f then
bulwahn@35891
  1171
      maps (vars_of_destructable_term ctxt) args
bulwahn@34948
  1172
    else
bulwahn@34948
  1173
      []
bulwahn@35891
  1174
  end
bulwahn@34948
  1175
bulwahn@34948
  1176
fun is_constructable thy vs t = forall (member (op =) vs) (term_vs t)
bulwahn@34948
  1177
bulwahn@34948
  1178
fun missing_vars vs t = subtract (op =) vs (term_vs t)
bulwahn@34948
  1179
bulwahn@35324
  1180
fun output_terms (Const ("Pair", _) $ t1 $ t2, Mode_Pair (d1, d2)) =
bulwahn@35324
  1181
    output_terms (t1, d1)  @ output_terms (t2, d2)
bulwahn@35324
  1182
  | output_terms (t1 $ t2, Mode_App (d1, d2)) =
bulwahn@35324
  1183
    output_terms (t1, d1)  @ output_terms (t2, d2)
bulwahn@35324
  1184
  | output_terms (t, Term Output) = [t]
bulwahn@35324
  1185
  | output_terms _ = []
bulwahn@35324
  1186
bulwahn@35324
  1187
fun lookup_mode modes (Const (s, T)) =
bulwahn@35324
  1188
   (case (AList.lookup (op =) modes s) of
bulwahn@35324
  1189
      SOME ms => SOME (map (fn m => (Context m, [])) ms)
bulwahn@35324
  1190
    | NONE => NONE)
bulwahn@35324
  1191
  | lookup_mode modes (Free (x, _)) =
bulwahn@35324
  1192
    (case (AList.lookup (op =) modes x) of
bulwahn@35324
  1193
      SOME ms => SOME (map (fn m => (Context m , [])) ms)
bulwahn@35324
  1194
    | NONE => NONE)
bulwahn@35324
  1195
bulwahn@35891
  1196
fun derivations_of (thy : theory) modes vs (Const ("Pair", _) $ t1 $ t2) (Pair (m1, m2)) =
bulwahn@34948
  1197
    map_product
bulwahn@34948
  1198
      (fn (m1, mvars1) => fn (m2, mvars2) => (Mode_Pair (m1, m2), union (op =) mvars1 mvars2))
bulwahn@34948
  1199
        (derivations_of thy modes vs t1 m1) (derivations_of thy modes vs t2 m2)
bulwahn@35324
  1200
  | derivations_of thy modes vs t (m as Fun _) =
bulwahn@35324
  1201
    (*let
bulwahn@35324
  1202
      val (p, args) = strip_comb t
bulwahn@35324
  1203
    in
bulwahn@35324
  1204
      (case lookup_mode modes p of
bulwahn@35324
  1205
        SOME ms => map_filter (fn (Context m, []) => let
bulwahn@35324
  1206
          val ms = strip_fun_mode m
bulwahn@35324
  1207
          val (argms, restms) = chop (length args) ms
bulwahn@35324
  1208
          val m' = fold_rev (curry Fun) restms Bool
bulwahn@35324
  1209
        in
bulwahn@35324
  1210
          if forall (fn m => eq_mode (Input, m)) argms andalso eq_mode (m', mode) then
bulwahn@35324
  1211
            SOME (fold (curry Mode_App) (map Term argms) (Context m), missing_vars vs t)
bulwahn@35324
  1212
          else NONE
bulwahn@35324
  1213
        end) ms
bulwahn@35324
  1214
      | NONE => (if is_all_input mode then [(Context mode, [])] else []))
bulwahn@35324
  1215
    end*)
bulwahn@35324
  1216
    (case try (all_derivations_of thy modes vs) t  of
bulwahn@35324
  1217
      SOME derivs =>
bulwahn@35324
  1218
        filter (fn (d, mvars) => eq_mode (mode_of d, m) andalso null (output_terms (t, d))) derivs
bulwahn@35324
  1219
    | NONE => (if is_all_input m then [(Context m, [])] else []))
bulwahn@34948
  1220
  | derivations_of thy modes vs t m =
bulwahn@35324
  1221
    if eq_mode (m, Input) then
bulwahn@35324
  1222
      [(Term Input, missing_vars vs t)]
bulwahn@35324
  1223
    else if eq_mode (m, Output) then
bulwahn@35324
  1224
      (if is_possible_output thy vs t then [(Term Output, [])] else [])
bulwahn@35324
  1225
    else []
bulwahn@34948
  1226
and all_derivations_of thy modes vs (Const ("Pair", _) $ t1 $ t2) =
bulwahn@34948
  1227
  let
bulwahn@34948
  1228
    val derivs1 = all_derivations_of thy modes vs t1
bulwahn@34948
  1229
    val derivs2 = all_derivations_of thy modes vs t2
bulwahn@34948
  1230
  in
bulwahn@34948
  1231
    map_product
bulwahn@34948
  1232
      (fn (m1, mvars1) => fn (m2, mvars2) => (Mode_Pair (m1, m2), union (op =) mvars1 mvars2))
bulwahn@34948
  1233
        derivs1 derivs2
bulwahn@34948
  1234
  end
bulwahn@34948
  1235
  | all_derivations_of thy modes vs (t1 $ t2) =
bulwahn@33146
  1236
  let
bulwahn@34948
  1237
    val derivs1 = all_derivations_of thy modes vs t1
bulwahn@34948
  1238
  in
bulwahn@34948
  1239
    maps (fn (d1, mvars1) =>
bulwahn@34948
  1240
      case mode_of d1 of
bulwahn@34948
  1241
        Fun (m', _) => map (fn (d2, mvars2) =>
bulwahn@34948
  1242
          (Mode_App (d1, d2), union (op =) mvars1 mvars2)) (derivations_of thy modes vs t2 m')
bulwahn@35885
  1243
        | _ => raise Fail "Something went wrong") derivs1
bulwahn@34948
  1244
  end
bulwahn@35324
  1245
  | all_derivations_of thy modes vs (Const (s, T)) = the (lookup_mode modes (Const (s, T)))
bulwahn@35324
  1246
  | all_derivations_of thy modes vs (Free (x, T)) = the (lookup_mode modes (Free (x, T)))
bulwahn@35885
  1247
  | all_derivations_of _ modes vs _ = raise Fail "all_derivations_of"
bulwahn@34948
  1248
bulwahn@34948
  1249
fun rev_option_ord ord (NONE, NONE) = EQUAL
bulwahn@34948
  1250
  | rev_option_ord ord (NONE, SOME _) = GREATER
bulwahn@34948
  1251
  | rev_option_ord ord (SOME _, NONE) = LESS
bulwahn@34948
  1252
  | rev_option_ord ord (SOME x, SOME y) = ord (x, y)
bulwahn@34948
  1253
bulwahn@34948
  1254
fun term_of_prem (Prem t) = t
bulwahn@34948
  1255
  | term_of_prem (Negprem t) = t
bulwahn@34948
  1256
  | term_of_prem (Sidecond t) = t
bulwahn@34948
  1257
bulwahn@34948
  1258
fun random_mode_in_deriv modes t deriv =
bulwahn@34948
  1259
  case try dest_Const (fst (strip_comb t)) of
bulwahn@34948
  1260
    SOME (s, _) =>
bulwahn@34948
  1261
      (case AList.lookup (op =) modes s of
bulwahn@34948
  1262
        SOME ms =>
bulwahn@35324
  1263
          (case AList.lookup (op =) (map (fn ((p, m), r) => (m, r)) ms) (head_mode_of deriv) of
bulwahn@34948
  1264
            SOME r => r
bulwahn@34948
  1265
          | NONE => false)
bulwahn@34948
  1266
      | NONE => false)
bulwahn@34948
  1267
  | NONE => false
bulwahn@34948
  1268
bulwahn@34948
  1269
fun number_of_output_positions mode =
bulwahn@34948
  1270
  let
bulwahn@34948
  1271
    val args = strip_fun_mode mode
bulwahn@34948
  1272
    fun contains_output (Fun _) = false
bulwahn@34948
  1273
      | contains_output Input = false
bulwahn@34948
  1274
      | contains_output Output = true
bulwahn@34948
  1275
      | contains_output (Pair (m1, m2)) = contains_output m1 orelse contains_output m2
bulwahn@34948
  1276
  in
bulwahn@34948
  1277
    length (filter contains_output args)
bulwahn@34948
  1278
  end
bulwahn@34948
  1279
bulwahn@34948
  1280
fun lex_ord ord1 ord2 (x, x') =
bulwahn@34948
  1281
  case ord1 (x, x') of
bulwahn@34948
  1282
    EQUAL => ord2 (x, x')
bulwahn@34948
  1283
  | ord => ord
bulwahn@34948
  1284
bulwahn@36028
  1285
fun deriv_ord2' thy pred modes t1 t2 ((deriv1, mvars1), (deriv2, mvars2)) =
bulwahn@34948
  1286
  let
bulwahn@36028
  1287
    (* prefer modes without requirement for generating random values *)
bulwahn@34948
  1288
    fun mvars_ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2)) =
bulwahn@34948
  1289
      int_ord (length mvars1, length mvars2)
bulwahn@36028
  1290
    (* prefer non-random modes *)
bulwahn@34948
  1291
    fun random_mode_ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2)) =
bulwahn@34948
  1292
      int_ord (if random_mode_in_deriv modes t1 deriv1 then 1 else 0,
bulwahn@34948
  1293
        if random_mode_in_deriv modes t1 deriv1 then 1 else 0)
bulwahn@36028
  1294
    (* prefer modes with more input and less output *)
bulwahn@34948
  1295
    fun output_mode_ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2)) =
bulwahn@34948
  1296
      int_ord (number_of_output_positions (head_mode_of deriv1),
bulwahn@34948
  1297
        number_of_output_positions (head_mode_of deriv2))
bulwahn@36028
  1298
    (* prefer recursive calls *)
bulwahn@36028
  1299
    fun is_rec_premise t =
bulwahn@36028
  1300
      case fst (strip_comb t) of Const (c, T) => c = pred | _ => false
bulwahn@36028
  1301
    fun recursive_ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2)) =
bulwahn@36028
  1302
      int_ord (if is_rec_premise t1 then 0 else 1,
bulwahn@36028
  1303
        if is_rec_premise t2 then 0 else 1)
bulwahn@36028
  1304
    val ord = lex_ord mvars_ord (lex_ord random_mode_ord (lex_ord output_mode_ord recursive_ord))
bulwahn@34948
  1305
  in
bulwahn@36028
  1306
    ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2))
bulwahn@34948
  1307
  end
bulwahn@34948
  1308
bulwahn@36028
  1309
fun deriv_ord2 thy pred modes t = deriv_ord2' thy pred modes t t
bulwahn@34948
  1310
bulwahn@34948
  1311
fun deriv_ord ((deriv1, mvars1), (deriv2, mvars2)) =
bulwahn@34948
  1312
  int_ord (length mvars1, length mvars2)
bulwahn@34948
  1313
bulwahn@36028
  1314
fun premise_ord thy pred modes ((prem1, a1), (prem2, a2)) =
bulwahn@36028
  1315
  rev_option_ord (deriv_ord2' thy pred modes (term_of_prem prem1) (term_of_prem prem2)) (a1, a2)
bulwahn@34948
  1316
bulwahn@34948
  1317
fun print_mode_list modes =
bulwahn@34948
  1318
  tracing ("modes: " ^ (commas (map (fn (s, ms) => s ^ ": " ^
bulwahn@34948
  1319
    commas (map (fn (m, r) => string_of_mode m ^ (if r then " random " else " not ")) ms)) modes)))
bulwahn@34948
  1320
bulwahn@36028
  1321
fun select_mode_prem (mode_analysis_options : mode_analysis_options) (thy : theory) pred
bulwahn@36028
  1322
  pol (modes, (pos_modes, neg_modes)) vs ps =
bulwahn@34948
  1323
  let
bulwahn@35324
  1324
    fun choose_mode_of_prem (Prem t) = partial_hd
bulwahn@36028
  1325
        (sort (deriv_ord2 thy pred modes t) (all_derivations_of thy pos_modes vs t))
bulwahn@35324
  1326
      | choose_mode_of_prem (Sidecond t) = SOME (Context Bool, missing_vars vs t)
bulwahn@35324
  1327
      | choose_mode_of_prem (Negprem t) = partial_hd
bulwahn@36028
  1328
          (sort (deriv_ord2 thy pred modes t) (filter (fn (d, missing_vars) => is_all_input (head_mode_of d))
bulwahn@35324
  1329
             (all_derivations_of thy neg_modes vs t)))
bulwahn@35885
  1330
      | choose_mode_of_prem p = raise Fail ("choose_mode_of_prem: " ^ string_of_prem thy p)
bulwahn@34948
  1331
  in
bulwahn@35324
  1332
    if #reorder_premises mode_analysis_options then
bulwahn@36028
  1333
      partial_hd (sort (premise_ord thy pred modes) (ps ~~ map choose_mode_of_prem ps))
bulwahn@35324
  1334
    else
bulwahn@35324
  1335
      SOME (hd ps, choose_mode_of_prem (hd ps))
bulwahn@34948
  1336
  end
bulwahn@34948
  1337
bulwahn@36028
  1338
fun check_mode_clause' (mode_analysis_options : mode_analysis_options) thy pred param_vs (modes :
bulwahn@35324
  1339
  (string * ((bool * mode) * bool) list) list) ((pol, mode) : bool * mode) (ts, ps) =
bulwahn@34948
  1340
  let
bulwahn@34948
  1341
    val vTs = distinct (op =) (fold Term.add_frees (map term_of_prem ps) (fold Term.add_frees ts []))
bulwahn@35324
  1342
    val modes' = modes @ (param_vs ~~ map (fn x => [((true, x), false), ((false, x), false)]) (ho_arg_modes_of mode))
bulwahn@35324
  1343
    fun retrieve_modes_of_pol pol = map (fn (s, ms) =>
bulwahn@35324
  1344
      (s, map_filter (fn ((p, m), r) => if p = pol then SOME m else NONE | _ => NONE) ms))
bulwahn@35324
  1345
    val (pos_modes', neg_modes') =
bulwahn@35324
  1346
      if #infer_pos_and_neg_modes mode_analysis_options then
bulwahn@35324
  1347
        (retrieve_modes_of_pol pol modes', retrieve_modes_of_pol (not pol) modes')
bulwahn@35324
  1348
      else
bulwahn@35324
  1349
        let
bulwahn@35324
  1350
          val modes = map (fn (s, ms) => (s, map (fn ((p, m), r) => m) ms)) modes'
bulwahn@35324
  1351
        in (modes, modes) end
bulwahn@35324
  1352
    val (in_ts, out_ts) = split_mode mode ts
bulwahn@35891
  1353
    val in_vs = maps (vars_of_destructable_term (ProofContext.init thy)) in_ts
bulwahn@34948
  1354
    val out_vs = terms_vs out_ts
bulwahn@35324
  1355
    fun known_vs_after p vs = (case p of
bulwahn@35324
  1356
        Prem t => union (op =) vs (term_vs t)
bulwahn@35324
  1357
      | Sidecond t => union (op =) vs (term_vs t)
bulwahn@35324
  1358
      | Negprem t => union (op =) vs (term_vs t)
bulwahn@35885
  1359
      | _ => raise Fail "I do not know")
bulwahn@34948
  1360
    fun check_mode_prems acc_ps rnd vs [] = SOME (acc_ps, vs, rnd)
bulwahn@34948
  1361
      | check_mode_prems acc_ps rnd vs ps =
bulwahn@35324
  1362
        (case
bulwahn@36028
  1363
          (select_mode_prem mode_analysis_options thy pred pol (modes', (pos_modes', neg_modes')) vs ps) of
bulwahn@35324
  1364
          SOME (p, SOME (deriv, [])) => check_mode_prems ((p, deriv) :: acc_ps) rnd
bulwahn@35324
  1365
            (known_vs_after p vs) (filter_out (equal p) ps)
bulwahn@34948
  1366
        | SOME (p, SOME (deriv, missing_vars)) =>
bulwahn@35324
  1367
          if #use_random mode_analysis_options andalso pol then
bulwahn@34948
  1368
            check_mode_prems ((p, deriv) :: (map
bulwahn@35324
  1369
              (fn v => (Generator (v, the (AList.lookup (op =) vTs v)), Term Output))
bulwahn@35324
  1370
                (distinct (op =) missing_vars))
bulwahn@35324
  1371
                @ acc_ps) true (known_vs_after p vs) (filter_out (equal p) ps)
bulwahn@34948
  1372
          else NONE
bulwahn@34948
  1373
        | SOME (p, NONE) => NONE
bulwahn@34948
  1374
        | NONE => NONE)
bulwahn@34948
  1375
  in
bulwahn@34948
  1376
    case check_mode_prems [] false in_vs ps of
bulwahn@34948
  1377
      NONE => NONE
bulwahn@34948
  1378
    | SOME (acc_ps, vs, rnd) =>
bulwahn@34948
  1379
      if forall (is_constructable thy vs) (in_ts @ out_ts) then
bulwahn@34948
  1380
        SOME (ts, rev acc_ps, rnd)
bulwahn@34948
  1381
      else
bulwahn@35324
  1382
        if #use_random mode_analysis_options andalso pol then
bulwahn@34948
  1383
          let
bulwahn@35324
  1384
             val generators = map
bulwahn@34948
  1385
              (fn v => (Generator (v, the (AList.lookup (op =) vTs v)), Term Output))
bulwahn@35324
  1386
                (subtract (op =) vs (terms_vs (in_ts @ out_ts)))
bulwahn@34948
  1387
          in
bulwahn@34948
  1388
            SOME (ts, rev (generators @ acc_ps), true)
bulwahn@34948
  1389
          end
bulwahn@34948
  1390
        else
bulwahn@34948
  1391
          NONE
bulwahn@34948
  1392
  end
bulwahn@34948
  1393
bulwahn@34948
  1394
datatype result = Success of bool | Error of string
bulwahn@34948
  1395
bulwahn@35324
  1396
fun check_modes_pred' mode_analysis_options options thy param_vs clauses modes (p, (ms : ((bool * mode) * bool) list)) =
bulwahn@34948
  1397
  let
bulwahn@34948
  1398
    fun split xs =
bulwahn@34948
  1399
      let
bulwahn@34948
  1400
        fun split' [] (ys, zs) = (rev ys, rev zs)
bulwahn@34948
  1401
          | split' ((m, Error z) :: xs) (ys, zs) = split' xs (ys, z :: zs)
bulwahn@35324
  1402
          | split' (((m : bool * mode), Success rnd) :: xs) (ys, zs) = split' xs ((m, rnd) :: ys, zs)
bulwahn@34948
  1403
       in
bulwahn@34948
  1404
         split' xs ([], [])
bulwahn@34948
  1405
       end
bulwahn@34948
  1406
    val rs = these (AList.lookup (op =) clauses p)
bulwahn@34948
  1407
    fun check_mode m =
bulwahn@34948
  1408
      let
bulwahn@35324
  1409
        val res = Output.cond_timeit false "work part of check_mode for one mode" (fn _ => 
bulwahn@36028
  1410
          map (check_mode_clause' mode_analysis_options thy p param_vs modes m) rs)
bulwahn@34948
  1411
      in
bulwahn@35324
  1412
        Output.cond_timeit false "aux part of check_mode for one mode" (fn _ => 
bulwahn@34948
  1413
        case find_indices is_none res of
bulwahn@34948
  1414
          [] => Success (exists (fn SOME (_, _, true) => true | _ => false) res)
bulwahn@35324
  1415
        | is => (print_failed_mode options thy modes p m rs is; Error (error_of p m is)))
bulwahn@34948
  1416
      end
bulwahn@35324
  1417
    val _ = if show_mode_inference options then
bulwahn@35324
  1418
        tracing ("checking " ^ string_of_int (length ms) ^ " modes ...")
bulwahn@35324
  1419
      else ()
bulwahn@35324
  1420
    val res = Output.cond_timeit false "check_mode" (fn _ => map (fn (m, _) => (m, check_mode m)) ms)
bulwahn@34948
  1421
    val (ms', errors) = split res
bulwahn@33752
  1422
  in
bulwahn@35324
  1423
    ((p, (ms' : ((bool * mode) * bool) list)), errors)
bulwahn@32667
  1424
  end;
bulwahn@32667
  1425
bulwahn@35324
  1426
fun get_modes_pred' mode_analysis_options thy param_vs clauses modes (p, ms) =
bulwahn@32667
  1427
  let
bulwahn@34948
  1428
    val rs = these (AList.lookup (op =) clauses p)
bulwahn@32667
  1429
  in
bulwahn@34948
  1430
    (p, map (fn (m, rnd) =>
bulwahn@35324
  1431
      (m, map
bulwahn@35324
  1432
        ((fn (ts, ps, rnd) => (ts, ps)) o the o
bulwahn@36028
  1433
          check_mode_clause' mode_analysis_options thy p param_vs modes m) rs)) ms)
bulwahn@32667
  1434
  end;
bulwahn@33137
  1435
bulwahn@35324
  1436
fun fixp f (x : (string * ((bool * mode) * bool) list) list) =
bulwahn@32667
  1437
  let val y = f x
bulwahn@32667
  1438
  in if x = y then x else fixp f y end;
bulwahn@32667
  1439
bulwahn@35324
  1440
fun fixp_with_state f (x : (string * ((bool * mode) * bool) list) list, state) =
bulwahn@33752
  1441
  let
bulwahn@33752
  1442
    val (y, state') = f (x, state)
bulwahn@33752
  1443
  in
bulwahn@33752
  1444
    if x = y then (y, state') else fixp_with_state f (y, state')
bulwahn@33752
  1445
  end
bulwahn@33752
  1446
bulwahn@35324
  1447
fun string_of_ext_mode ((pol, mode), rnd) =
bulwahn@35324
  1448
  string_of_mode mode ^ "(" ^ (if pol then "pos" else "neg") ^ ", "
bulwahn@35324
  1449
  ^ (if rnd then "rnd" else "nornd") ^ ")"
bulwahn@35324
  1450
bulwahn@35324
  1451
fun print_extra_modes options modes =
bulwahn@35324
  1452
  if show_mode_inference options then
bulwahn@35324
  1453
    tracing ("Modes of inferred predicates: " ^
bulwahn@35324
  1454
      cat_lines (map (fn (s, ms) => s ^ ": " ^ commas (map string_of_ext_mode ms)) modes))
bulwahn@35324
  1455
  else ()
bulwahn@35324
  1456
bulwahn@35324
  1457
fun infer_modes mode_analysis_options options compilation preds all_modes param_vs clauses thy =
bulwahn@32667
  1458
  let
bulwahn@35324
  1459
    val collect_errors = false
bulwahn@35324
  1460
    fun appair f (x1, x2) (y1, y2) = (f x1 y1, f x2 y2)
bulwahn@35324
  1461
    fun needs_random s (false, m) = ((false, m), false)
bulwahn@35324
  1462
      | needs_random s (true, m) = ((true, m), member (op =) (#needs_random (the_pred_data thy s)) m)
bulwahn@35324
  1463
    fun add_polarity_and_random_bit s b ms = map (fn m => needs_random s (b, m)) ms
bulwahn@35324
  1464
    val prednames = map fst preds
bulwahn@35324
  1465
    (* extramodes contains all modes of all constants, should we only use the necessary ones
bulwahn@35324
  1466
       - what is the impact on performance? *)
bulwahn@35324
  1467
    val extra_modes =
bulwahn@35324
  1468
      if #infer_pos_and_neg_modes mode_analysis_options then
bulwahn@33752
  1469
        let
bulwahn@35324
  1470
          val pos_extra_modes =
bulwahn@35324
  1471
            all_modes_of compilation thy |> filter_out (fn (name, _) => member (op =) prednames name)
bulwahn@35324
  1472
          val neg_extra_modes =
bulwahn@35324
  1473
            all_modes_of (negative_compilation_of compilation) thy
bulwahn@35324
  1474
            |> filter_out (fn (name, _) => member (op =) prednames name)
bulwahn@35324
  1475
        in
bulwahn@35324
  1476
          map (fn (s, ms) => (s, (add_polarity_and_random_bit s true ms)
bulwahn@35324
  1477
                @ add_polarity_and_random_bit s false (the (AList.lookup (op =) neg_extra_modes s))))
bulwahn@35324
  1478
            pos_extra_modes
bulwahn@35324
  1479
        end
bulwahn@35324
  1480
      else
bulwahn@35324
  1481
        map (fn (s, ms) => (s, (add_polarity_and_random_bit s true ms)))
bulwahn@35324
  1482
          (all_modes_of compilation thy |> filter_out (fn (name, _) => member (op =) prednames name))
bulwahn@35324
  1483
    val _ = print_extra_modes options extra_modes
bulwahn@35324
  1484
    val start_modes =
bulwahn@35324
  1485
      if #infer_pos_and_neg_modes mode_analysis_options then
bulwahn@35324
  1486
        map (fn (s, ms) => (s, map (fn m => ((true, m), false)) ms @
bulwahn@35324
  1487
          (map (fn m => ((false, m), false)) ms))) all_modes
bulwahn@35324
  1488
      else
bulwahn@35324
  1489
        map (fn (s, ms) => (s, map (fn m => ((true, m), false)) ms)) all_modes
bulwahn@35324
  1490
    fun iteration modes = map
bulwahn@36028
  1491
      (check_modes_pred' mode_analysis_options options thy param_vs clauses
bulwahn@36028
  1492
        (modes @ extra_modes)) modes
bulwahn@35324
  1493
    val ((modes : (string * ((bool * mode) * bool) list) list), errors) =
bulwahn@35324
  1494
      Output.cond_timeit false "Fixpount computation of mode analysis" (fn () =>
bulwahn@35324
  1495
      if collect_errors then
bulwahn@35324
  1496
        fixp_with_state (fn (modes, errors) =>
bulwahn@35324
  1497
          let
bulwahn@35324
  1498
            val (modes', new_errors) = split_list (iteration modes)
bulwahn@35324
  1499
          in (modes', errors @ flat new_errors) end) (start_modes, [])
bulwahn@35324
  1500
        else
bulwahn@35324
  1501
          (fixp (fn modes => map fst (iteration modes)) start_modes, []))
bulwahn@35324
  1502
    val moded_clauses = map (get_modes_pred' mode_analysis_options thy param_vs clauses
bulwahn@35324
  1503
      (modes @ extra_modes)) modes
bulwahn@34948
  1504
    val thy' = fold (fn (s, ms) => if member (op =) (map fst preds) s then
bulwahn@35324
  1505
      set_needs_random s (map_filter (fn ((true, m), true) => SOME m | _ => NONE) ms) else I)
bulwahn@35324
  1506
      modes thy
bulwahn@35324
  1507
bulwahn@32667
  1508
  in
bulwahn@35324
  1509
    ((moded_clauses, errors), thy')
bulwahn@32667
  1510
  end;
bulwahn@32667
  1511
bulwahn@32667
  1512
(* term construction *)
bulwahn@32667
  1513
bulwahn@32667
  1514
fun mk_v (names, vs) s T = (case AList.lookup (op =) vs s of
bulwahn@32667
  1515
      NONE => (Free (s, T), (names, (s, [])::vs))
bulwahn@32667
  1516
    | SOME xs =>
bulwahn@32667
  1517
        let
bulwahn@32667
  1518
          val s' = Name.variant names s;
bulwahn@32667
  1519
          val v = Free (s', T)
bulwahn@32667
  1520
        in
bulwahn@32667
  1521
          (v, (s'::names, AList.update (op =) (s, v::xs) vs))
bulwahn@32667
  1522
        end);
bulwahn@32667
  1523
bulwahn@32667
  1524
fun distinct_v (Free (s, T)) nvs = mk_v nvs s T
bulwahn@32667
  1525
  | distinct_v (t $ u) nvs =
bulwahn@32667
  1526
      let
bulwahn@32667
  1527
        val (t', nvs') = distinct_v t nvs;
bulwahn@32667
  1528
        val (u', nvs'') = distinct_v u nvs';
bulwahn@32667
  1529
      in (t' $ u', nvs'') end
bulwahn@32667
  1530
  | distinct_v x nvs = (x, nvs);
bulwahn@32667
  1531
bulwahn@33147
  1532
(** specific rpred functions -- move them to the correct place in this file *)
bulwahn@33147
  1533
bulwahn@33147
  1534
fun mk_Eval_of additional_arguments ((x, T), NONE) names = (x, names)
bulwahn@33147
  1535
  | mk_Eval_of additional_arguments ((x, T), SOME mode) names =
wenzelm@33268
  1536
  let
bulwahn@33147
  1537
    val Ts = binder_types T
wenzelm@33268
  1538
    fun mk_split_lambda [] t = lambda (Free (Name.variant names "x", HOLogic.unitT)) t
wenzelm@33268
  1539
      | mk_split_lambda [x] t = lambda x t
wenzelm@33268
  1540
      | mk_split_lambda xs t =
wenzelm@33268
  1541
      let
wenzelm@33268
  1542
        fun mk_split_lambda' (x::y::[]) t = HOLogic.mk_split (lambda x (lambda y t))
wenzelm@33268
  1543
          | mk_split_lambda' (x::xs) t = HOLogic.mk_split (lambda x (mk_split_lambda' xs t))
wenzelm@33268
  1544
      in
wenzelm@33268
  1545
        mk_split_lambda' xs t
wenzelm@33268
  1546
      end;
wenzelm@33268
  1547
    fun mk_arg (i, T) =
wenzelm@33268
  1548
      let
wenzelm@33268
  1549
        val vname = Name.variant names ("x" ^ string_of_int i)
wenzelm@33268
  1550
        val default = Free (vname, T)
wenzelm@33268
  1551
      in 
wenzelm@33268
  1552
        case AList.lookup (op =) mode i of
wenzelm@33268
  1553
          NONE => (([], [default]), [default])
wenzelm@33268
  1554
        | SOME NONE => (([default], []), [default])
wenzelm@33268
  1555
        | SOME (SOME pis) =>
wenzelm@33268
  1556
          case HOLogic.strip_tupleT T of
wenzelm@33268
  1557
            [] => error "pair mode but unit tuple" (*(([default], []), [default])*)
wenzelm@33268
  1558
          | [_] => error "pair mode but not a tuple" (*(([default], []), [default])*)
wenzelm@33268
  1559
          | Ts =>
wenzelm@33268
  1560
            let
wenzelm@33268
  1561
              val vnames = Name.variant_list names
wenzelm@33268
  1562
                (map (fn j => "x" ^ string_of_int i ^ "p" ^ string_of_int j)
wenzelm@33268
  1563
                  (1 upto length Ts))
bulwahn@33629
  1564
              val args = map2 (curry Free) vnames Ts
wenzelm@33268
  1565
              fun split_args (i, arg) (ins, outs) =
wenzelm@33268
  1566
                if member (op =) pis i then
wenzelm@33268
  1567
                  (arg::ins, outs)
wenzelm@33268
  1568
                else
wenzelm@33268
  1569
                  (ins, arg::outs)
wenzelm@33268
  1570
              val (inargs, outargs) = fold_rev split_args ((1 upto length Ts) ~~ args) ([], [])
wenzelm@33268
  1571
              fun tuple args = if null args then [] else [HOLogic.mk_tuple args]
wenzelm@33268
  1572
            in ((tuple inargs, tuple outargs), args) end
wenzelm@33268
  1573
      end
wenzelm@33268
  1574
    val (inoutargs, args) = split_list (map mk_arg (1 upto (length Ts) ~~ Ts))
bulwahn@33147
  1575
    val (inargs, outargs) = pairself flat (split_list inoutargs)
wenzelm@33268
  1576
    val r = PredicateCompFuns.mk_Eval 
bulwahn@33148
  1577
      (list_comb (x, inargs @ additional_arguments), HOLogic.mk_tuple outargs)
bulwahn@33147
  1578
    val t = fold_rev mk_split_lambda args r
bulwahn@33147
  1579
  in
bulwahn@33147
  1580
    (t, names)
bulwahn@33147
  1581
  end;
bulwahn@33147
  1582
bulwahn@34948
  1583
(* TODO: uses param_vs -- change necessary for compilation with new modes *)
bulwahn@36019
  1584
fun compile_arg compilation_modifiers additional_arguments ctxt param_vs iss arg = 
bulwahn@33147
  1585
  let
bulwahn@33147
  1586
    fun map_params (t as Free (f, T)) =
bulwahn@33147
  1587
      if member (op =) param_vs f then
bulwahn@34948
  1588
        case (AList.lookup (op =) (param_vs ~~ iss) f) of
bulwahn@33147
  1589
          SOME is =>
bulwahn@33147
  1590
            let
bulwahn@34948
  1591
              val _ = error "compile_arg: A parameter in a input position -- do we have a test case?"
bulwahn@34948
  1592
              val T' = Comp_Mod.funT_of compilation_modifiers is T
bulwahn@34948
  1593
            in t(*fst (mk_Eval_of additional_arguments ((Free (f, T'), T), is) [])*) end
bulwahn@33147
  1594
        | NONE => t
bulwahn@33147
  1595
      else t
bulwahn@33147
  1596
      | map_params t = t
bulwahn@33147
  1597
    in map_aterms map_params arg end
bulwahn@33147
  1598
bulwahn@36019
  1599
fun compile_match compilation_modifiers additional_arguments
bulwahn@35891
  1600
  param_vs iss ctxt eqs eqs' out_ts success_t =
bulwahn@32667
  1601
  let
bulwahn@36019
  1602
    val compfuns = Comp_Mod.compfuns compilation_modifiers
bulwahn@32667
  1603
    val eqs'' = maps mk_eq eqs @ eqs'
bulwahn@33147
  1604
    val eqs'' =
bulwahn@36019
  1605
      map (compile_arg compilation_modifiers additional_arguments ctxt param_vs iss) eqs''
bulwahn@32667
  1606
    val names = fold Term.add_free_names (success_t :: eqs'' @ out_ts) [];
bulwahn@32667
  1607
    val name = Name.variant names "x";
bulwahn@32667
  1608
    val name' = Name.variant (name :: names) "y";
bulwahn@33148
  1609
    val T = HOLogic.mk_tupleT (map fastype_of out_ts);
bulwahn@32667
  1610
    val U = fastype_of success_t;
bulwahn@36038
  1611
    val U' = dest_predT compfuns U;        
bulwahn@32667
  1612
    val v = Free (name, T);
bulwahn@32667
  1613
    val v' = Free (name', T);
bulwahn@32667
  1614
  in
bulwahn@35891
  1615
    lambda v (fst (Datatype.make_case ctxt Datatype_Case.Quiet [] v
bulwahn@33148
  1616
      [(HOLogic.mk_tuple out_ts,
bulwahn@32667
  1617
        if null eqs'' then success_t
bulwahn@32667
  1618
        else Const (@{const_name HOL.If}, HOLogic.boolT --> U --> U --> U) $
bulwahn@32667
  1619
          foldr1 HOLogic.mk_conj eqs'' $ success_t $
bulwahn@32667
  1620
            mk_bot compfuns U'),
bulwahn@32667
  1621
       (v', mk_bot compfuns U')]))
bulwahn@32667
  1622
  end;
bulwahn@32667
  1623
bulwahn@35891
  1624
fun string_of_tderiv ctxt (t, deriv) = 
bulwahn@35324
  1625
  (case (t, deriv) of
bulwahn@35324
  1626
    (t1 $ t2, Mode_App (deriv1, deriv2)) =>
bulwahn@35891
  1627
      string_of_tderiv ctxt (t1, deriv1) ^ " $ " ^ string_of_tderiv ctxt (t2, deriv2)
bulwahn@35324
  1628
  | (Const ("Pair", _) $ t1 $ t2, Mode_Pair (deriv1, deriv2)) =>
bulwahn@35891
  1629
    "(" ^ string_of_tderiv ctxt (t1, deriv1) ^ ", " ^ string_of_tderiv ctxt (t2, deriv2) ^ ")"
bulwahn@35891
  1630
  | (t, Term Input) => Syntax.string_of_term ctxt t ^ "[Input]"
bulwahn@35891
  1631
  | (t, Term Output) => Syntax.string_of_term ctxt t ^ "[Output]"
bulwahn@35891
  1632
  | (t, Context m) => Syntax.string_of_term ctxt t ^ "[" ^ string_of_mode m ^ "]")
bulwahn@35324
  1633
bulwahn@36020
  1634
fun compile_expr compilation_modifiers ctxt (t, deriv) additional_arguments =
bulwahn@32667
  1635
  let
bulwahn@36019
  1636
    val compfuns = Comp_Mod.compfuns compilation_modifiers
bulwahn@34948
  1637
    fun expr_of (t, deriv) =
bulwahn@34948
  1638
      (case (t, deriv) of
bulwahn@34948
  1639
        (t, Term Input) => SOME t
bulwahn@34948
  1640
      | (t, Term Output) => NONE
bulwahn@34948
  1641
      | (Const (name, T), Context mode) =>
bulwahn@36038
  1642
        (case alternative_compilation_of (ProofContext.theory_of ctxt) name mode of
bulwahn@36038
  1643
          SOME alt_comp => SOME (alt_comp compfuns T)
bulwahn@36034
  1644
        | NONE =>
bulwahn@36034
  1645
          SOME (Const (function_name_of (Comp_Mod.compilation compilation_modifiers)
bulwahn@36034
  1646
            (ProofContext.theory_of ctxt) name mode,
bulwahn@36034
  1647
            Comp_Mod.funT_of compilation_modifiers mode T)))
bulwahn@34948
  1648
      | (Free (s, T), Context m) =>
bulwahn@34948
  1649
        SOME (Free (s, Comp_Mod.funT_of compilation_modifiers m T))
bulwahn@34948
  1650
      | (t, Context m) =>
bulwahn@34948
  1651
        let
bulwahn@34948
  1652
          val bs = map (pair "x") (binder_types (fastype_of t))
bulwahn@34948
  1653
          val bounds = map Bound (rev (0 upto (length bs) - 1))
bulwahn@34948
  1654
        in SOME (list_abs (bs, mk_if compfuns (list_comb (t, bounds)))) end
bulwahn@34948
  1655
      | (Const ("Pair", _) $ t1 $ t2, Mode_Pair (d1, d2)) =>
bulwahn@34948
  1656
        (case (expr_of (t1, d1), expr_of (t2, d2)) of
bulwahn@34948
  1657
          (NONE, NONE) => NONE
bulwahn@34948
  1658
        | (NONE, SOME t) => SOME t
bulwahn@34948
  1659
        | (SOME t, NONE) => SOME t
bulwahn@34948
  1660
        | (SOME t1, SOME t2) => SOME (HOLogic.mk_prod (t1, t2)))
bulwahn@34948
  1661
      | (t1 $ t2, Mode_App (deriv1, deriv2)) =>
bulwahn@34948
  1662
        (case (expr_of (t1, deriv1), expr_of (t2, deriv2)) of
bulwahn@34948
  1663
          (SOME t, NONE) => SOME t
bulwahn@34948
  1664
         | (SOME t, SOME u) => SOME (t $ u)
bulwahn@34948
  1665
         | _ => error "something went wrong here!"))
bulwahn@32667
  1666
  in
bulwahn@35879
  1667
    list_comb (the (expr_of (t, deriv)), additional_arguments)
bulwahn@34948
  1668
  end
bulwahn@33145
  1669
bulwahn@36019
  1670
fun compile_clause compilation_modifiers ctxt all_vs param_vs additional_arguments
bulwahn@36020
  1671
  mode inp (ts, moded_ps) =
bulwahn@32667
  1672
  let
bulwahn@36019
  1673
    val compfuns = Comp_Mod.compfuns compilation_modifiers
bulwahn@34948
  1674
    val iss = ho_arg_modes_of mode
bulwahn@36019
  1675
    val compile_match = compile_match compilation_modifiers
bulwahn@35891
  1676
      additional_arguments param_vs iss ctxt
bulwahn@34948
  1677
    val (in_ts, out_ts) = split_mode mode ts;
bulwahn@32667
  1678
    val (in_ts', (all_vs', eqs)) =
bulwahn@35891
  1679
      fold_map (collect_non_invertible_subterms ctxt) in_ts (all_vs, []);
bulwahn@32667
  1680
    fun compile_prems out_ts' vs names [] =
bulwahn@32667
  1681
          let
bulwahn@32667
  1682
            val (out_ts'', (names', eqs')) =
bulwahn@35891
  1683
              fold_map (collect_non_invertible_subterms ctxt) out_ts' (names, []);
bulwahn@32667
  1684
            val (out_ts''', (names'', constr_vs)) = fold_map distinct_v
bulwahn@32667
  1685
              out_ts'' (names', map (rpair []) vs);
bulwahn@32667
  1686
          in
bulwahn@33147
  1687
            compile_match constr_vs (eqs @ eqs') out_ts'''
bulwahn@33148
  1688
              (mk_single compfuns (HOLogic.mk_tuple out_ts))
bulwahn@32667
  1689
          end
bulwahn@34948
  1690
      | compile_prems out_ts vs names ((p, deriv) :: ps) =
bulwahn@32667
  1691
          let
bulwahn@32667
  1692
            val vs' = distinct (op =) (flat (vs :: map term_vs out_ts));
bulwahn@32667
  1693
            val (out_ts', (names', eqs)) =
bulwahn@35891
  1694
              fold_map (collect_non_invertible_subterms ctxt) out_ts (names, [])
bulwahn@32667
  1695
            val (out_ts'', (names'', constr_vs')) = fold_map distinct_v
bulwahn@32667
  1696
              out_ts' ((names', map (rpair []) vs))
bulwahn@34948
  1697
            val mode = head_mode_of deriv
bulwahn@33143
  1698
            val additional_arguments' =
bulwahn@33330
  1699
              Comp_Mod.transform_additional_arguments compilation_modifiers p additional_arguments
bulwahn@32667
  1700
            val (compiled_clause, rest) = case p of
bulwahn@34948
  1701
               Prem t =>
bulwahn@32667
  1702
                 let
bulwahn@33138
  1703
                   val u =
bulwahn@36020
  1704
                     compile_expr compilation_modifiers ctxt (t, deriv) additional_arguments'
bulwahn@34948
  1705
                   val (_, out_ts''') = split_mode mode (snd (strip_comb t))
bulwahn@32667
  1706
                   val rest = compile_prems out_ts''' vs' names'' ps
bulwahn@32667
  1707
                 in
bulwahn@32667
  1708
                   (u, rest)
bulwahn@32667
  1709
                 end
bulwahn@34948
  1710
             | Negprem t =>
bulwahn@32667
  1711
                 let
bulwahn@36019
  1712
                   val neg_compilation_modifiers =
bulwahn@36019
  1713
                     negative_comp_modifiers_of compilation_modifiers
bulwahn@33143
  1714
                   val u = mk_not compfuns
bulwahn@36020
  1715
                     (compile_expr neg_compilation_modifiers ctxt (t, deriv) additional_arguments')
bulwahn@34948
  1716
                   val (_, out_ts''') = split_mode mode (snd (strip_comb t))
bulwahn@32667
  1717
                   val rest = compile_prems out_ts''' vs' names'' ps
bulwahn@32667
  1718
                 in
bulwahn@32667
  1719
                   (u, rest)
bulwahn@32667
  1720
                 end
bulwahn@32667
  1721
             | Sidecond t =>
bulwahn@32667
  1722
                 let
bulwahn@36019
  1723
                   val t = compile_arg compilation_modifiers additional_arguments
bulwahn@35891
  1724
                     ctxt param_vs iss t
bulwahn@32667
  1725
                   val rest = compile_prems [] vs' names'' ps;
bulwahn@32667
  1726
                 in
bulwahn@32667
  1727
                   (mk_if compfuns t, rest)
bulwahn@32667
  1728
                 end
bulwahn@32667
  1729
             | Generator (v, T) =>
bulwahn@32667
  1730
                 let
bulwahn@35880
  1731
                   val u = Comp_Mod.mk_random compilation_modifiers T additional_arguments
bulwahn@32667
  1732
                   val rest = compile_prems [Free (v, T)]  vs' names'' ps;
bulwahn@32667
  1733
                 in
bulwahn@32667
  1734
                   (u, rest)
bulwahn@32667
  1735
                 end
bulwahn@32667
  1736
          in
bulwahn@33147
  1737
            compile_match constr_vs' eqs out_ts''
bulwahn@32667
  1738
              (mk_bind compfuns (compiled_clause, rest))
bulwahn@32667
  1739
          end
bulwahn@32667
  1740
    val prem_t = compile_prems in_ts' param_vs all_vs' moded_ps;
bulwahn@32667
  1741
  in
bulwahn@32667
  1742
    mk_bind compfuns (mk_single compfuns inp, prem_t)
bulwahn@32667
  1743
  end
bulwahn@32667
  1744
bulwahn@35324
  1745
fun compile_pred compilation_modifiers thy all_vs param_vs s T (pol, mode) moded_cls =
bulwahn@32667
  1746
  let
bulwahn@35891
  1747
    val ctxt = ProofContext.init thy
bulwahn@36020
  1748
    val compilation_modifiers = if pol then compilation_modifiers else
bulwahn@36020
  1749
      negative_comp_modifiers_of compilation_modifiers
bulwahn@35879
  1750
    val additional_arguments = Comp_Mod.additional_arguments compilation_modifiers
bulwahn@33482
  1751
      (all_vs @ param_vs)
bulwahn@34948
  1752
    val compfuns = Comp_Mod.compfuns compilation_modifiers
bulwahn@34948
  1753
    fun is_param_type (T as Type ("fun",[_ , T'])) =
bulwahn@34948
  1754
      is_some (try (dest_predT compfuns) T) orelse is_param_type T'
bulwahn@34948
  1755
      | is_param_type T = is_some (try (dest_predT compfuns) T)
bulwahn@34948
  1756
    val (inpTs, outTs) = split_map_modeT (fn m => fn T => (SOME (funT_of compfuns m T), NONE)) mode
bulwahn@34948
  1757
      (binder_types T)
bulwahn@34948
  1758
    val predT = mk_predT compfuns (HOLogic.mk_tupleT outTs)
bulwahn@34948
  1759
    val funT = Comp_Mod.funT_of compilation_modifiers mode T
bulwahn@34948
  1760
    
bulwahn@34948
  1761
    val (in_ts, _) = fold_map (fold_map_aterms_prodT (curry HOLogic.mk_prod)
bulwahn@34948
  1762
      (fn T => fn (param_vs, names) =>
bulwahn@36018
  1763
        if is_param_type T then
bulwahn@34948
  1764
          (Free (hd param_vs, T), (tl param_vs, names))
bulwahn@34948
  1765
        else
bulwahn@34948
  1766
          let
bulwahn@34948
  1767
            val new = Name.variant names "x"
bulwahn@34948
  1768
          in (Free (new, T), (param_vs, new :: names)) end)) inpTs
bulwahn@34948
  1769
        (param_vs, (all_vs @ param_vs))
bulwahn@34948
  1770
    val in_ts' = map_filter (map_filter_prod
bulwahn@34948
  1771
      (fn t as Free (x, _) => if member (op =) param_vs x then NONE else SOME t | t => SOME t)) in_ts
bulwahn@32667
  1772
    val cl_ts =
bulwahn@36019
  1773
      map (compile_clause compilation_modifiers
bulwahn@36020
  1774
        ctxt all_vs param_vs additional_arguments mode (HOLogic.mk_tuple in_ts')) moded_cls;
bulwahn@33482
  1775
    val compilation = Comp_Mod.wrap_compilation compilation_modifiers compfuns
bulwahn@33482
  1776
      s T mode additional_arguments
bulwahn@33146
  1777
      (if null cl_ts then
bulwahn@34948
  1778
        mk_bot compfuns (HOLogic.mk_tupleT outTs)
bulwahn@33146
  1779
      else foldr1 (mk_sup compfuns) cl_ts)
bulwahn@33143
  1780
    val fun_const =
bulwahn@35891
  1781
      Const (function_name_of (Comp_Mod.compilation compilation_modifiers)
bulwahn@36019
  1782
      (ProofContext.theory_of ctxt) s mode, funT)
bulwahn@32667
  1783
  in
bulwahn@33143
  1784
    HOLogic.mk_Trueprop
bulwahn@34948
  1785
      (HOLogic.mk_eq (list_comb (fun_const, in_ts @ additional_arguments), compilation))
bulwahn@32667
  1786
  end;
bulwahn@33143
  1787
bulwahn@32667
  1788
(* special setup for simpset *)                  
haftmann@34974
  1789
val HOL_basic_ss' = HOL_basic_ss addsimps (@{thms HOL.simp_thms} @ [@{thm Pair_eq}])
bulwahn@32667
  1790
  setSolver (mk_solver "all_tac_solver" (fn _ => fn _ => all_tac))
wenzelm@33268
  1791
  setSolver (mk_solver "True_solver" (fn _ => rtac @{thm TrueI}))
bulwahn@32667
  1792
bulwahn@32667
  1793
(* Definition of executable functions and their intro and elim rules *)
bulwahn@32667
  1794
bulwahn@32667
  1795
fun print_arities arities = tracing ("Arities:\n" ^
bulwahn@32667
  1796
  cat_lines (map (fn (s, (ks, k)) => s ^ ": " ^
bulwahn@32667
  1797
    space_implode " -> " (map
bulwahn@32667
  1798
      (fn NONE => "X" | SOME k' => string_of_int k')
bulwahn@32667
  1799
        (ks @ [SOME k]))) arities));
bulwahn@32667
  1800
bulwahn@34948
  1801
fun split_lambda (x as Free _) t = lambda x t
bulwahn@34948
  1802
  | split_lambda (Const ("Pair", _) $ t1 $ t2) t =
bulwahn@34948
  1803
    HOLogic.mk_split (split_lambda t1 (split_lambda t2 t))
bulwahn@34948
  1804
  | split_lambda (Const ("Product_Type.Unity", _)) t = Abs ("x", HOLogic.unitT, t)
bulwahn@34948
  1805
  | split_lambda t _ = raise (TERM ("split_lambda", [t]))
bulwahn@34948
  1806
bulwahn@34948
  1807
fun strip_split_abs (Const ("split", _) $ t) = strip_split_abs t
bulwahn@34948
  1808
  | strip_split_abs (Abs (_, _, t)) = strip_split_abs t
bulwahn@34948
  1809
  | strip_split_abs t = t
bulwahn@34948
  1810
bulwahn@35324
  1811
fun mk_args is_eval (m as Pair (m1, m2), T as Type ("*", [T1, T2])) names =
bulwahn@35324
  1812
    if eq_mode (m, Input) orelse eq_mode (m, Output) then
bulwahn@35324
  1813
      let
bulwahn@35324
  1814
        val x = Name.variant names "x"
bulwahn@35324
  1815
      in
bulwahn@35324
  1816
        (Free (x, T), x :: names)
bulwahn@35324
  1817
      end
bulwahn@35324
  1818
    else
bulwahn@35324
  1819
      let
bulwahn@35324
  1820
        val (t1, names') = mk_args is_eval (m1, T1) names
bulwahn@35324
  1821
        val (t2, names'') = mk_args is_eval (m2, T2) names'
bulwahn@35324
  1822
      in
bulwahn@35324
  1823
        (HOLogic.mk_prod (t1, t2), names'')
bulwahn@35324
  1824
      end
bulwahn@34948
  1825
  | mk_args is_eval ((m as Fun _), T) names =
bulwahn@34948
  1826
    let
bulwahn@34948
  1827
      val funT = funT_of PredicateCompFuns.compfuns m T
bulwahn@34948
  1828
      val x = Name.variant names "x"
bulwahn@34948
  1829
      val (args, _) = fold_map (mk_args is_eval) (strip_fun_mode m ~~ binder_types T) (x :: names)
bulwahn@34948
  1830
      val (inargs, outargs) = split_map_mode (fn _ => fn t => (SOME t, NONE)) m args
bulwahn@34948
  1831
      val t = fold_rev split_lambda args (PredicateCompFuns.mk_Eval
bulwahn@34948
  1832
        (list_comb (Free (x, funT), inargs), HOLogic.mk_tuple outargs))
bulwahn@34948
  1833
    in
bulwahn@34948
  1834
      (if is_eval then t else Free (x, funT), x :: names)
bulwahn@34948
  1835
    end
bulwahn@34948
  1836
  | mk_args is_eval (_, T) names =
bulwahn@34948
  1837
    let
bulwahn@34948
  1838
      val x = Name.variant names "x"
wenzelm@33268
  1839
    in
bulwahn@34948
  1840
      (Free (x, T), x :: names)
wenzelm@33268
  1841
    end
bulwahn@34948
  1842
bulwahn@34948
  1843
fun create_intro_elim_rule mode defthm mode_id funT pred thy =
bulwahn@34948
  1844
  let
bulwahn@34948
  1845
    val funtrm = Const (mode_id, funT)
bulwahn@34948
  1846
    val Ts = binder_types (fastype_of pred)
bulwahn@34948
  1847
    val (args, argnames) = fold_map (mk_args true) (strip_fun_mode mode ~~ Ts) []
bulwahn@34948
  1848
    fun strip_eval _ t =
bulwahn@34948
  1849
      let
bulwahn@34948
  1850
        val t' = strip_split_abs t
bulwahn@34948
  1851
        val (r, _) = PredicateCompFuns.dest_Eval t'
bulwahn@34948
  1852
      in (SOME (fst (strip_comb r)), NONE) end
bulwahn@34948
  1853
    val (inargs, outargs) = split_map_mode strip_eval mode args
bulwahn@34948
  1854
    val eval_hoargs = ho_args_of mode args
bulwahn@34948
  1855
    val hoargTs = ho_argsT_of mode Ts
bulwahn@34948
  1856
    val hoarg_names' =
bulwahn@34948
  1857
      Name.variant_list argnames ((map (fn i => "x" ^ string_of_int i)) (1 upto (length hoargTs)))
bulwahn@34948
  1858
    val hoargs' = map2 (curry Free) hoarg_names' hoargTs
bulwahn@34948
  1859
    val args' = replace_ho_args mode hoargs' args
bulwahn@34948
  1860
    val predpropI = HOLogic.mk_Trueprop (list_comb (pred, args'))
bulwahn@34948
  1861
    val predpropE = HOLogic.mk_Trueprop (list_comb (pred, args))
bulwahn@34948
  1862
    val param_eqs = map2 (HOLogic.mk_Trueprop oo (curry HOLogic.mk_eq)) eval_hoargs hoargs'
bulwahn@34948
  1863
    val funpropE = HOLogic.mk_Trueprop (PredicateCompFuns.mk_Eval (list_comb (funtrm, inargs),
bulwahn@34948
  1864
                    if null outargs then Free("y", HOLogic.unitT) else HOLogic.mk_tuple outargs))
bulwahn@34948
  1865
    val funpropI = HOLogic.mk_Trueprop (PredicateCompFuns.mk_Eval (list_comb (funtrm, inargs),
bulwahn@34948
  1866
                     HOLogic.mk_tuple outargs))
bulwahn@34948
  1867
    val introtrm = Logic.list_implies (predpropI :: param_eqs, funpropI)
bulwahn@34948
  1868
    val simprules = [defthm, @{thm eval_pred},
bulwahn@34948
  1869
      @{thm "split_beta"}, @{thm "fst_conv"}, @{thm "snd_conv"}, @{thm pair_collapse}]
bulwahn@34948
  1870
    val unfolddef_tac = Simplifier.asm_full_simp_tac (HOL_basic_ss addsimps simprules) 1
bulwahn@34948
  1871
    val introthm = Goal.prove (ProofContext.init thy)
bulwahn@34948
  1872
      (argnames @ hoarg_names' @ ["y"]) [] introtrm (fn _ => unfolddef_tac)
bulwahn@34948
  1873
    val P = HOLogic.mk_Trueprop (Free ("P", HOLogic.boolT));
bulwahn@34948
  1874
    val elimtrm = Logic.list_implies ([funpropE, Logic.mk_implies (predpropE, P)], P)
bulwahn@34948
  1875
    val elimthm = Goal.prove (ProofContext.init thy)
bulwahn@34948
  1876
      (argnames @ ["y", "P"]) [] elimtrm (fn _ => unfolddef_tac)
bulwahn@35884
  1877
    val opt_neg_introthm =
bulwahn@35884
  1878
      if is_all_input mode then
bulwahn@35884
  1879
        let
bulwahn@35884
  1880
          val neg_predpropI = HOLogic.mk_Trueprop (HOLogic.mk_not (list_comb (pred, args')))
bulwahn@35884
  1881
          val neg_funpropI =
bulwahn@35884
  1882
            HOLogic.mk_Trueprop (PredicateCompFuns.mk_Eval
bulwahn@35884
  1883
              (PredicateCompFuns.mk_not (list_comb (funtrm, inargs)), HOLogic.unit))
bulwahn@35884
  1884
          val neg_introtrm = Logic.list_implies (neg_predpropI :: param_eqs, neg_funpropI)
bulwahn@35884
  1885
          val tac =
bulwahn@35884
  1886
            Simplifier.asm_full_simp_tac (HOL_basic_ss addsimps
bulwahn@35884
  1887
              (@{thm if_False} :: @{thm Predicate.not_pred_eq} :: simprules)) 1
bulwahn@35884
  1888
            THEN rtac @{thm Predicate.singleI} 1
bulwahn@35884
  1889
        in SOME (Goal.prove (ProofContext.init thy) (argnames @ hoarg_names') []
bulwahn@35884
  1890
            neg_introtrm (fn _ => tac))
bulwahn@35884
  1891
        end
bulwahn@35884
  1892
      else NONE
bulwahn@34948
  1893
  in
bulwahn@35884
  1894
    ((introthm, elimthm), opt_neg_introthm)
bulwahn@34948
  1895
  end
bulwahn@32667
  1896
bulwahn@33620
  1897
fun create_constname_of_mode options thy prefix name T mode = 
bulwahn@32667
  1898
  let
bulwahn@33626
  1899
    val system_proposal = prefix ^ (Long_Name.base_name name)
bulwahn@34948
  1900
      ^ "_" ^ ascii_string_of_mode mode
bulwahn@34948
  1901
    val name = the_default system_proposal (proposed_names options name mode)
bulwahn@32667
  1902
  in
bulwahn@33620
  1903
    Sign.full_bname thy name
bulwahn@32667
  1904
  end;
bulwahn@32667
  1905
bulwahn@33620
  1906
fun create_definitions options preds (name, modes) thy =
bulwahn@32667
  1907
  let
bulwahn@32667
  1908
    val compfuns = PredicateCompFuns.compfuns
bulwahn@32667
  1909
    val T = AList.lookup (op =) preds name |> the
bulwahn@34948
  1910
    fun create_definition mode thy =
bulwahn@33752
  1911
      let
bulwahn@33752
  1912
        val mode_cname = create_constname_of_mode options thy "" name T mode
bulwahn@33752
  1913
        val mode_cbasename = Long_Name.base_name mode_cname
bulwahn@34948
  1914
        val funT = funT_of compfuns mode T
bulwahn@34948
  1915
        val (args, _) = fold_map (mk_args true) ((strip_fun_mode mode) ~~ (binder_types T)) []
bulwahn@34948
  1916
        fun strip_eval m t =
bulwahn@33752
  1917
          let
bulwahn@34948
  1918
            val t' = strip_split_abs t
bulwahn@34948
  1919
            val (r, _) = PredicateCompFuns.dest_Eval t'
bulwahn@34948
  1920
          in (SOME (fst (strip_comb r)), NONE) end
bulwahn@34948
  1921
        val (inargs, outargs) = split_map_mode strip_eval mode args
bulwahn@34948
  1922
        val predterm = fold_rev split_lambda inargs
bulwahn@34948
  1923
          (PredicateCompFuns.mk_Enum (split_lambda (HOLogic.mk_tuple outargs)
bulwahn@34948
  1924
            (list_comb (Const (name, T), args))))
bulwahn@34948
  1925
        val lhs = Const (mode_cname, funT)
bulwahn@33752
  1926
        val def = Logic.mk_equals (lhs, predterm)
bulwahn@33752
  1927
        val ([definition], thy') = thy |>
bulwahn@33752
  1928
          Sign.add_consts_i [(Binding.name mode_cbasename, funT, NoSyn)] |>
bulwahn@33752
  1929
          PureThy.add_defs false [((Binding.name (mode_cbasename ^ "_def"), def), [])]
bulwahn@35884
  1930
        val rules as ((intro, elim), _) =
bulwahn@33752
  1931
          create_intro_elim_rule mode definition mode_cname funT (Const (name, T)) thy'
bulwahn@33752
  1932
        in thy'
bulwahn@34948
  1933
          |> set_function_name Pred name mode mode_cname
bulwahn@35884
  1934
          |> add_predfun_data name mode (definition, rules)
bulwahn@33752
  1935
          |> PureThy.store_thm (Binding.name (mode_cbasename ^ "I"), intro) |> snd
bulwahn@33752
  1936
          |> PureThy.store_thm (Binding.name (mode_cbasename ^ "E"), elim)  |> snd
bulwahn@33752
  1937
          |> Theory.checkpoint
bulwahn@32667
  1938
        end;
bulwahn@32667
  1939
  in
bulwahn@34948
  1940
    thy |> defined_function_of Pred name |> fold create_definition modes
bulwahn@32667
  1941
  end;
bulwahn@32667
  1942
bulwahn@33620
  1943
fun define_functions comp_modifiers compfuns options preds (name, modes) thy =
bulwahn@32667
  1944
  let
bulwahn@32667
  1945
    val T = AList.lookup (op =) preds name |> the
bulwahn@32667
  1946
    fun create_definition mode thy =
bulwahn@32667
  1947
      let
bulwahn@33485
  1948
        val function_name_prefix = Comp_Mod.function_name_prefix comp_modifiers
bulwahn@33620
  1949
        val mode_cname = create_constname_of_mode options thy function_name_prefix name T mode
bulwahn@34948
  1950
        val funT = Comp_Mod.funT_of comp_modifiers mode T
bulwahn@32667
  1951
      in
bulwahn@32667
  1952
        thy |> Sign.add_consts_i [(Binding.name (Long_Name.base_name mode_cname), funT, NoSyn)]
bulwahn@34948
  1953
        |> set_function_name (Comp_Mod.compilation comp_modifiers) name mode mode_cname
bulwahn@32667
  1954
      end;
bulwahn@32667
  1955
  in
bulwahn@34948
  1956
    thy
bulwahn@34948
  1957
    |> defined_function_of (Comp_Mod.compilation comp_modifiers) name
bulwahn@34948
  1958
    |> fold create_definition modes
bulwahn@32667
  1959
  end;
bulwahn@32672
  1960
bulwahn@32667
  1961
(* Proving equivalence of term *)
bulwahn@32667
  1962
bulwahn@32667
  1963
fun is_Type (Type _) = true
bulwahn@32667
  1964
  | is_Type _ = false
bulwahn@32667
  1965
bulwahn@32667
  1966
(* returns true if t is an application of an datatype constructor *)
bulwahn@32667
  1967
(* which then consequently would be splitted *)
bulwahn@32667
  1968
(* else false *)
bulwahn@32667
  1969
fun is_constructor thy t =
bulwahn@32667
  1970
  if (is_Type (fastype_of t)) then
bulwahn@32667
  1971
    (case Datatype.get_info thy ((fst o dest_Type o fastype_of) t) of
bulwahn@32667
  1972
      NONE => false
bulwahn@32667
  1973
    | SOME info => (let
bulwahn@32667
  1974
      val constr_consts = maps (fn (_, (_, _, constrs)) => map fst constrs) (#descr info)
bulwahn@32667
  1975
      val (c, _) = strip_comb t
bulwahn@32667
  1976
      in (case c of
bulwahn@32667
  1977
        Const (name, _) => name mem_string constr_consts
bulwahn@32667
  1978
        | _ => false) end))
bulwahn@32667
  1979
  else false
bulwahn@32667
  1980
bulwahn@32667
  1981
(* MAJOR FIXME:  prove_params should be simple
bulwahn@32667
  1982
 - different form of introrule for parameters ? *)
bulwahn@34948
  1983
bulwahn@35888
  1984
fun prove_param options ctxt nargs t deriv =
bulwahn@32667
  1985
  let
bulwahn@32667
  1986
    val  (f, args) = strip_comb (Envir.eta_contract t)
bulwahn@34948
  1987
    val mode = head_mode_of deriv
bulwahn@34948
  1988
    val param_derivations = param_derivations_of deriv
bulwahn@34948
  1989
    val ho_args = ho_args_of mode args
bulwahn@32667
  1990
    val f_tac = case f of
bulwahn@32667
  1991
      Const (name, T) => simp_tac (HOL_basic_ss addsimps 
bulwahn@35888
  1992
         [@{thm eval_pred}, predfun_definition_of ctxt name mode,
bulwahn@35884
  1993
         @{thm split_eta}, @{thm split_beta}, @{thm fst_conv},
bulwahn@35884
  1994
         @{thm snd_conv}, @{thm pair_collapse}, @{thm Product_Type.split_conv}]) 1
bulwahn@35884
  1995
    | Free _ =>
bulwahn@35888
  1996
      Subgoal.FOCUS_PREMS (fn {context = ctxt, params = params, prems, asms, concl, schematics} =>
bulwahn@35884
  1997
        let
bulwahn@35884
  1998
          val prems' = maps dest_conjunct_prem (take nargs prems)
bulwahn@35884
  1999
        in
bulwahn@35884
  2000
          MetaSimplifier.rewrite_goal_tac
bulwahn@35884
  2001
            (map (fn th => th RS @{thm sym} RS @{thm eq_reflection}) prems') 1
bulwahn@35888
  2002
        end) ctxt 1
bulwahn@35884
  2003
    | Abs _ => raise Fail "prove_param: No valid parameter term"
bulwahn@32667
  2004
  in
bulwahn@33753
  2005
    REPEAT_DETERM (rtac @{thm ext} 1)
bulwahn@35886
  2006
    THEN print_tac options "prove_param"
bulwahn@35884
  2007
    THEN f_tac 
bulwahn@35886
  2008
    THEN print_tac options "after prove_param"
bulwahn@32667
  2009
    THEN (REPEAT_DETERM (atac 1))
bulwahn@35888
  2010
    THEN (EVERY (map2 (prove_param options ctxt nargs) ho_args param_derivations))
bulwahn@35884
  2011
    THEN REPEAT_DETERM (rtac @{thm refl} 1)
bulwahn@32667
  2012
  end
bulwahn@32667
  2013
bulwahn@35888
  2014
fun prove_expr options ctxt nargs (premposition : int) (t, deriv) =
bulwahn@32667
  2015
  case strip_comb t of
bulwahn@34948
  2016
    (Const (name, T), args) =>
bulwahn@32667
  2017
      let
bulwahn@34948
  2018
        val mode = head_mode_of deriv
bulwahn@35888
  2019
        val introrule = predfun_intro_of ctxt name mode
bulwahn@34948
  2020
        val param_derivations = param_derivations_of deriv
bulwahn@34948
  2021
        val ho_args = ho_args_of mode args
bulwahn@32667
  2022
      in
bulwahn@35886
  2023
        print_tac options "before intro rule:"
bulwahn@35884
  2024
        THEN rtac introrule 1
bulwahn@35886
  2025
        THEN print_tac options "after intro rule"
bulwahn@32667
  2026
        (* for the right assumption in first position *)
bulwahn@32667
  2027
        THEN rotate_tac premposition 1
bulwahn@33753
  2028
        THEN atac 1
bulwahn@35886
  2029
        THEN print_tac options "parameter goal"
bulwahn@35884
  2030
        (* work with parameter arguments *)
bulwahn@35888
  2031
        THEN (EVERY (map2 (prove_param options ctxt nargs) ho_args param_derivations))
bulwahn@32667
  2032
        THEN (REPEAT_DETERM (atac 1))
bulwahn@32667
  2033
      end
bulwahn@35884
  2034
  | (Free _, _) =>
bulwahn@35886
  2035
    print_tac options "proving parameter call.."
bulwahn@35888
  2036
    THEN Subgoal.FOCUS_PREMS (fn {context = ctxt, params, prems, asms, concl, schematics} =>
bulwahn@35884
  2037
        let
bulwahn@35884
  2038
          val param_prem = nth prems premposition
bulwahn@35884
  2039
          val (param, _) = strip_comb (HOLogic.dest_Trueprop (prop_of param_prem))
bulwahn@35884
  2040
          val prems' = maps dest_conjunct_prem (take nargs prems)
bulwahn@35884
  2041
          fun param_rewrite prem =
bulwahn@35884
  2042
            param = snd (HOLogic.dest_eq (HOLogic.dest_Trueprop (prop_of prem)))
bulwahn@35884
  2043
          val SOME rew_eq = find_first param_rewrite prems'
bulwahn@35884
  2044
          val param_prem' = MetaSimplifier.rewrite_rule
bulwahn@35884
  2045
            (map (fn th => th RS @{thm eq_reflection})
bulwahn@35884
  2046
              [rew_eq RS @{thm sym}, @{thm split_beta}, @{thm fst_conv}, @{thm snd_conv}])
bulwahn@35884
  2047
            param_prem
bulwahn@35884
  2048
        in
bulwahn@35884
  2049
          rtac param_prem' 1
bulwahn@35888
  2050
        end) ctxt 1
bulwahn@35886
  2051
    THEN print_tac options "after prove parameter call"
bulwahn@34948
  2052
bulwahn@34948
  2053
fun SOLVED tac st = FILTER (fn st' => nprems_of st' = nprems_of st - 1) tac st;
bulwahn@32667
  2054
bulwahn@32667
  2055
fun SOLVEDALL tac st = FILTER (fn st' => nprems_of st' = 0) tac st
bulwahn@32667
  2056
bulwahn@35888
  2057
fun check_format ctxt st =
bulwahn@34948
  2058
  let
bulwahn@34948
  2059
    val concl' = Logic.strip_assums_concl (hd (prems_of st))
bulwahn@34948
  2060
    val concl = HOLogic.dest_Trueprop concl'
bulwahn@34948
  2061
    val expr = fst (strip_comb (fst (PredicateCompFuns.dest_Eval concl)))
bulwahn@34948
  2062
    fun valid_expr (Const (@{const_name Predicate.bind}, _)) = true
bulwahn@34948
  2063
      | valid_expr (Const (@{const_name Predicate.single}, _)) = true
bulwahn@34948
  2064
      | valid_expr _ = false
bulwahn@34948
  2065
  in
bulwahn@34948
  2066
    if valid_expr expr then
bulwahn@34948
  2067
      ((*tracing "expression is valid";*) Seq.single st)
bulwahn@34948
  2068
    else
bulwahn@34948
  2069
      ((*tracing "expression is not valid";*) Seq.empty) (*error "check_format: wrong format"*)
bulwahn@34948
  2070
  end
bulwahn@34948
  2071
bulwahn@35888
  2072
fun prove_match options ctxt out_ts =
bulwahn@34948
  2073
  let
bulwahn@35888
  2074
    val thy = ProofContext.theory_of ctxt
bulwahn@34948
  2075
    fun get_case_rewrite t =
bulwahn@34948
  2076
      if (is_constructor thy t) then let
bulwahn@34948
  2077
        val case_rewrites = (#case_rewrites (Datatype.the_info thy
bulwahn@34948
  2078
          ((fst o dest_Type o fastype_of) t)))
bulwahn@34948
  2079
        in case_rewrites @ maps get_case_rewrite (snd (strip_comb t)) end
bulwahn@34948
  2080
      else []
bulwahn@34948
  2081
    val simprules = @{thm "unit.cases"} :: @{thm "prod.cases"} :: maps get_case_rewrite out_ts
bulwahn@34948
  2082
  (* replace TRY by determining if it necessary - are there equations when calling compile match? *)
bulwahn@34948
  2083
  in
bulwahn@34948
  2084
     (* make this simpset better! *)
bulwahn@34948
  2085
    asm_full_simp_tac (HOL_basic_ss' addsimps simprules) 1
bulwahn@35886
  2086
    THEN print_tac options "after prove_match:"
bulwahn@35888
  2087
    THEN (DETERM (TRY (EqSubst.eqsubst_tac ctxt [0] [@{thm HOL.if_P}] 1
bulwahn@34948
  2088
           THEN (REPEAT_DETERM (rtac @{thm conjI} 1 THEN (SOLVED (asm_simp_tac HOL_basic_ss' 1))))
bulwahn@35886
  2089
           THEN print_tac options "if condition to be solved:"
bulwahn@35886
  2090
           THEN (SOLVED (asm_simp_tac HOL_basic_ss' 1 THEN print_tac options "after if simp; in SOLVED:"))
bulwahn@34948
  2091
           THEN check_format thy
bulwahn@35886
  2092
           THEN print_tac options "after if simplification - a TRY block")))
bulwahn@35886
  2093
    THEN print_tac options "after if simplification"
bulwahn@34948
  2094
  end;
bulwahn@32667
  2095
bulwahn@32667
  2096
(* corresponds to compile_fun -- maybe call that also compile_sidecond? *)
bulwahn@32667
  2097
bulwahn@35888
  2098
fun prove_sidecond ctxt t =
bulwahn@32667
  2099
  let
bulwahn@35888
  2100
    val thy = ProofContext.theory_of ctxt
bulwahn@32667
  2101
    fun preds_of t nameTs = case strip_comb t of 
bulwahn@32667
  2102
      (f as Const (name, T), args) =>
bulwahn@35324
  2103
        if is_registered thy name then (name, T) :: nameTs
bulwahn@32667
  2104
          else fold preds_of args nameTs