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