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