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