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