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