src/HOL/Tools/Predicate_Compile/predicate_compile_core.ML
author bulwahn
Tue, 28 Sep 2010 11:59:50 +0200
changeset 39994 c2a76ec6e2d9
parent 39993 e6a370d35f45
child 39995 02fb709ab3cb
permissions -rw-r--r--
renaming use_random to use_generators in the predicate compiler
wenzelm@33264
     1
(*  Title:      HOL/Tools/Predicate_Compile/predicate_compile_core.ML
wenzelm@33264
     2
    Author:     Lukas Bulwahn, TU Muenchen
bulwahn@32667
     3
wenzelm@33264
     4
A compiler from predicates specified by intro/elim rules to equations.
bulwahn@32667
     5
*)
bulwahn@32667
     6
bulwahn@32667
     7
signature PREDICATE_COMPILE_CORE =
bulwahn@32667
     8
sig
bulwahn@36048
     9
  type mode = Predicate_Compile_Aux.mode
bulwahn@36048
    10
  type options = Predicate_Compile_Aux.options
bulwahn@36048
    11
  type compilation = Predicate_Compile_Aux.compilation
bulwahn@36048
    12
  type compilation_funs = Predicate_Compile_Aux.compilation_funs
bulwahn@36048
    13
  
bulwahn@33478
    14
  val setup : theory -> theory
bulwahn@36048
    15
  val code_pred : options -> string -> Proof.context -> Proof.state
bulwahn@36048
    16
  val code_pred_cmd : options -> string -> Proof.context -> Proof.state
bulwahn@36048
    17
  val values_cmd : string list -> mode option list option
bulwahn@36048
    18
    -> ((string option * bool) * (compilation * int list)) -> int -> string -> Toplevel.state -> unit
bulwahn@34935
    19
  val register_predicate : (string * thm list * thm) -> theory -> theory
bulwahn@33146
    20
  val register_intros : string * thm list -> theory -> theory
bulwahn@36994
    21
  val is_registered : Proof.context -> string -> bool
bulwahn@36994
    22
  val function_name_of : compilation -> Proof.context -> string -> mode -> string
bulwahn@36048
    23
  val predfun_intro_of: Proof.context -> string -> mode -> thm
bulwahn@36048
    24
  val predfun_elim_of: Proof.context -> string -> mode -> thm
bulwahn@36994
    25
  val all_preds_of : Proof.context -> string list
bulwahn@36994
    26
  val modes_of: compilation -> Proof.context -> string -> mode list
bulwahn@36994
    27
  val all_modes_of : compilation -> Proof.context -> (string * mode list) list
bulwahn@36994
    28
  val all_random_modes_of : Proof.context -> (string * mode list) list
bulwahn@36998
    29
  val intros_of : Proof.context -> string -> thm list
bulwahn@38318
    30
  val intros_graph_of : Proof.context -> thm list Graph.T
bulwahn@39767
    31
  val add_intro : string option * thm -> theory -> theory
bulwahn@33478
    32
  val set_elim : thm -> theory -> theory
bulwahn@36048
    33
  val register_alternative_function : string -> mode -> string -> theory -> theory
bulwahn@36994
    34
  val alternative_compilation_of_global : theory -> string -> mode ->
bulwahn@36994
    35
    (compilation_funs -> typ -> term) option
bulwahn@36994
    36
  val alternative_compilation_of : Proof.context -> string -> mode ->
bulwahn@36032
    37
    (compilation_funs -> typ -> term) option
bulwahn@36048
    38
  val functional_compilation : string -> mode -> compilation_funs -> typ -> term
bulwahn@36048
    39
  val force_modes_and_functions : string -> (mode * (string * bool)) list -> theory -> theory
bulwahn@36032
    40
  val force_modes_and_compilations : string ->
bulwahn@36048
    41
    (mode * ((compilation_funs -> typ -> term) * bool)) list -> theory -> theory
bulwahn@34935
    42
  val preprocess_intro : theory -> thm -> thm
bulwahn@36998
    43
  val print_stored_rules : Proof.context -> unit
bulwahn@36994
    44
  val print_all_modes : compilation -> Proof.context -> unit
bulwahn@34935
    45
  val mk_casesrule : Proof.context -> term -> thm list -> term
haftmann@39634
    46
haftmann@39634
    47
  val put_pred_result : (unit -> term Predicate.pred) -> Proof.context -> Proof.context
haftmann@39634
    48
  val put_pred_random_result : (unit -> int * int -> term Predicate.pred * (int * int)) ->
haftmann@39634
    49
    Proof.context -> Proof.context
haftmann@39634
    50
  val put_dseq_result : (unit -> term DSequence.dseq) -> Proof.context -> Proof.context
haftmann@39634
    51
  val put_dseq_random_result : (unit -> int -> int -> int * int -> term DSequence.dseq * (int * int)) ->
haftmann@39634
    52
    Proof.context -> Proof.context
haftmann@39634
    53
  val put_lseq_random_result :
haftmann@39634
    54
    (unit -> int -> int -> int * int -> int -> term Lazy_Sequence.lazy_sequence) ->
haftmann@39634
    55
    Proof.context -> Proof.context
haftmann@39634
    56
  val put_lseq_random_stats_result :
haftmann@39634
    57
    (unit -> int -> int -> int * int -> int -> (term * int) Lazy_Sequence.lazy_sequence) ->
haftmann@39634
    58
    Proof.context -> Proof.context
haftmann@39634
    59
bulwahn@33628
    60
  val code_pred_intro_attrib : attribute
bulwahn@32667
    61
  (* used by Quickcheck_Generator *) 
bulwahn@32667
    62
  (* temporary for testing of the compilation *)
bulwahn@36048
    63
  val add_equations : options -> string list -> theory -> theory
bulwahn@36048
    64
  val add_depth_limited_random_equations : options -> string list -> theory -> theory
bulwahn@36048
    65
  val add_random_dseq_equations : options -> string list -> theory -> theory
bulwahn@36048
    66
  val add_new_random_dseq_equations : options -> string list -> theory -> theory
bulwahn@33473
    67
  val mk_tracing : string -> term -> term
bulwahn@39556
    68
  val prepare_intrs : options -> Proof.context -> string list -> thm list ->
bulwahn@39183
    69
    ((string * typ) list * string list * string list * (string * mode list) list *
bulwahn@39183
    70
      (string *  (Term.term list * Predicate_Compile_Aux.indprem list) list) list)
bulwahn@39994
    71
  type mode_analysis_options =
bulwahn@39994
    72
   {use_generators : bool,
bulwahn@39994
    73
    reorder_premises : bool,
bulwahn@39994
    74
    infer_pos_and_neg_modes : bool}  
bulwahn@39183
    75
  datatype mode_derivation = Mode_App of mode_derivation * mode_derivation | Context of mode
bulwahn@39556
    76
    | Mode_Pair of mode_derivation * mode_derivation | Term of mode
bulwahn@39701
    77
  val head_mode_of : mode_derivation -> mode
bulwahn@39183
    78
  type moded_clause = term list * (Predicate_Compile_Aux.indprem * mode_derivation) list
bulwahn@39183
    79
  type 'a pred_mode_table = (string * ((bool * mode) * 'a) list) list
bulwahn@39183
    80
bulwahn@39183
    81
  val infer_modes : 
bulwahn@39500
    82
    mode_analysis_options -> options ->
bulwahn@39500
    83
     (string -> Predicate_Compile_Aux.mode list) * (string -> Predicate_Compile_Aux.mode list)
bulwahn@39500
    84
       * (string -> Predicate_Compile_Aux.mode -> bool) -> Proof.context -> (string * typ) list ->
bulwahn@39500
    85
      (string * mode list) list ->
bulwahn@39500
    86
      string list -> (string * (Term.term list * Predicate_Compile_Aux.indprem list) list) list ->
bulwahn@39500
    87
      ((moded_clause list pred_mode_table * (string * mode list) list) * string list)
bulwahn@32667
    88
end;
bulwahn@32667
    89
bulwahn@32667
    90
structure Predicate_Compile_Core : PREDICATE_COMPILE_CORE =
bulwahn@32667
    91
struct
bulwahn@32667
    92
bulwahn@32668
    93
open Predicate_Compile_Aux;
bulwahn@33144
    94
bulwahn@32667
    95
(** auxiliary **)
bulwahn@32667
    96
bulwahn@32667
    97
(* debug stuff *)
bulwahn@32667
    98
bulwahn@35886
    99
fun print_tac options s = 
bulwahn@33127
   100
  if show_proof_trace options then Tactical.print_tac s else Seq.single;
bulwahn@33127
   101
bulwahn@35885
   102
fun assert b = if not b then raise Fail "Assertion failed" else warning "Assertion holds"
bulwahn@34935
   103
bulwahn@33108
   104
datatype assertion = Max_number_of_subgoals of int
bulwahn@33108
   105
fun assert_tac (Max_number_of_subgoals i) st =
bulwahn@33108
   106
  if (nprems_of st <= i) then Seq.single st
bulwahn@35885
   107
  else raise Fail ("assert_tac: Numbers of subgoals mismatch at goal state :"
bulwahn@33108
   108
    ^ "\n" ^ Pretty.string_of (Pretty.chunks
wenzelm@39371
   109
      (Goal_Display.pretty_goals_without_context st)));
bulwahn@33108
   110
bulwahn@32667
   111
(** fundamentals **)
bulwahn@32667
   112
bulwahn@32667
   113
(* syntactic operations *)
bulwahn@32667
   114
bulwahn@32667
   115
fun mk_eq (x, xs) =
bulwahn@32667
   116
  let fun mk_eqs _ [] = []
bulwahn@32667
   117
        | mk_eqs a (b::cs) =
bulwahn@32667
   118
            HOLogic.mk_eq (Free (a, fastype_of b), b) :: mk_eqs a cs
bulwahn@32667
   119
  in mk_eqs x xs end;
bulwahn@32667
   120
bulwahn@32667
   121
fun mk_scomp (t, u) =
bulwahn@32667
   122
  let
bulwahn@32667
   123
    val T = fastype_of t
bulwahn@32667
   124
    val U = fastype_of u
bulwahn@32667
   125
    val [A] = binder_types T
bulwahn@34935
   126
    val D = body_type U                   
bulwahn@32667
   127
  in 
bulwahn@32667
   128
    Const (@{const_name "scomp"}, T --> U --> A --> D) $ t $ u
bulwahn@32667
   129
  end;
bulwahn@32667
   130
bulwahn@32667
   131
fun dest_funT (Type ("fun",[S, T])) = (S, T)
bulwahn@32667
   132
  | dest_funT T = raise TYPE ("dest_funT", [T], [])
bulwahn@32667
   133
 
bulwahn@32667
   134
fun mk_fun_comp (t, u) =
bulwahn@32667
   135
  let
bulwahn@32667
   136
    val (_, B) = dest_funT (fastype_of t)
bulwahn@32667
   137
    val (C, A) = dest_funT (fastype_of u)
bulwahn@32667
   138
  in
bulwahn@32667
   139
    Const(@{const_name "Fun.comp"}, (A --> B) --> (C --> A) --> C --> B) $ t $ u
bulwahn@32667
   140
  end;
bulwahn@32667
   141
bulwahn@32667
   142
fun dest_randomT (Type ("fun", [@{typ Random.seed},
haftmann@37678
   143
  Type (@{type_name Product_Type.prod}, [Type (@{type_name Product_Type.prod}, [T, @{typ "unit => Code_Evaluation.term"}]) ,@{typ Random.seed}])])) = T
bulwahn@32667
   144
  | dest_randomT T = raise TYPE ("dest_randomT", [T], [])
bulwahn@32667
   145
bulwahn@33473
   146
fun mk_tracing s t =
bulwahn@33473
   147
  Const(@{const_name Code_Evaluation.tracing},
bulwahn@33473
   148
    @{typ String.literal} --> (fastype_of t) --> (fastype_of t)) $ (HOLogic.mk_literal s) $ t
bulwahn@33473
   149
bulwahn@34935
   150
val strip_intro_concl = (strip_comb o HOLogic.dest_Trueprop o Logic.strip_imp_concl o prop_of)
bulwahn@32667
   151
bulwahn@34935
   152
(* derivation trees for modes of premises *)
bulwahn@34935
   153
bulwahn@34935
   154
datatype mode_derivation = Mode_App of mode_derivation * mode_derivation | Context of mode
bulwahn@34935
   155
  | Mode_Pair of mode_derivation * mode_derivation | Term of mode
bulwahn@34935
   156
bulwahn@34935
   157
fun string_of_derivation (Mode_App (m1, m2)) =
bulwahn@34935
   158
  "App (" ^ string_of_derivation m1 ^ ", " ^ string_of_derivation m2 ^ ")"
bulwahn@34935
   159
  | string_of_derivation (Mode_Pair (m1, m2)) =
bulwahn@34935
   160
  "Pair (" ^ string_of_derivation m1 ^ ", " ^ string_of_derivation m2 ^ ")"
bulwahn@34935
   161
  | string_of_derivation (Term m) = "Term (" ^ string_of_mode m ^ ")"
bulwahn@34935
   162
  | string_of_derivation (Context m) = "Context (" ^ string_of_mode m ^ ")"
bulwahn@34935
   163
bulwahn@34935
   164
fun strip_mode_derivation deriv =
bulwahn@33619
   165
  let
bulwahn@34935
   166
    fun strip (Mode_App (deriv1, deriv2)) ds = strip deriv1 (deriv2 :: ds)
bulwahn@34935
   167
      | strip deriv ds = (deriv, ds)
bulwahn@34935
   168
  in
bulwahn@34935
   169
    strip deriv []
bulwahn@34935
   170
  end
bulwahn@32667
   171
bulwahn@34935
   172
fun mode_of (Context m) = m
bulwahn@34935
   173
  | mode_of (Term m) = m
bulwahn@34935
   174
  | mode_of (Mode_App (d1, d2)) =
bulwahn@34935
   175
    (case mode_of d1 of Fun (m, m') =>
bulwahn@39423
   176
        (if eq_mode (m, mode_of d2) then m' else raise Fail "mode_of: derivation has mismatching modes")
bulwahn@39423
   177
      | _ => raise Fail "mode_of: derivation has a non-functional mode")
bulwahn@34935
   178
  | mode_of (Mode_Pair (d1, d2)) =
bulwahn@34935
   179
    Pair (mode_of d1, mode_of d2)
bulwahn@32667
   180
bulwahn@34935
   181
fun head_mode_of deriv = mode_of (fst (strip_mode_derivation deriv))
bulwahn@34935
   182
bulwahn@34935
   183
fun param_derivations_of deriv =
bulwahn@32667
   184
  let
bulwahn@34935
   185
    val (_, argument_derivs) = strip_mode_derivation deriv
bulwahn@34935
   186
    fun param_derivation (Mode_Pair (m1, m2)) =
bulwahn@34935
   187
        param_derivation m1 @ param_derivation m2
bulwahn@34935
   188
      | param_derivation (Term _) = []
bulwahn@34935
   189
      | param_derivation m = [m]
bulwahn@34935
   190
  in
bulwahn@34935
   191
    maps param_derivation argument_derivs
bulwahn@34935
   192
  end
bulwahn@32667
   193
bulwahn@34935
   194
fun collect_context_modes (Mode_App (m1, m2)) =
bulwahn@34935
   195
      collect_context_modes m1 @ collect_context_modes m2
bulwahn@34935
   196
  | collect_context_modes (Mode_Pair (m1, m2)) =
bulwahn@34935
   197
      collect_context_modes m1 @ collect_context_modes m2
bulwahn@34935
   198
  | collect_context_modes (Context m) = [m]
bulwahn@34935
   199
  | collect_context_modes (Term _) = []
bulwahn@32667
   200
bulwahn@34935
   201
(* representation of inferred clauses with modes *)
bulwahn@32667
   202
bulwahn@34935
   203
type moded_clause = term list * (indprem * mode_derivation) list
bulwahn@32668
   204
bulwahn@35324
   205
type 'a pred_mode_table = (string * ((bool * mode) * 'a) list) list
bulwahn@32667
   206
bulwahn@34935
   207
(* book-keeping *)
bulwahn@34935
   208
bulwahn@32667
   209
datatype predfun_data = PredfunData of {
bulwahn@32667
   210
  definition : thm,
bulwahn@32667
   211
  intro : thm,
bulwahn@35884
   212
  elim : thm,
bulwahn@35884
   213
  neg_intro : thm option
bulwahn@32667
   214
};
bulwahn@32667
   215
bulwahn@32667
   216
fun rep_predfun_data (PredfunData data) = data;
bulwahn@32667
   217
bulwahn@35884
   218
fun mk_predfun_data (definition, ((intro, elim), neg_intro)) =
bulwahn@35884
   219
  PredfunData {definition = definition, intro = intro, elim = elim, neg_intro = neg_intro}
bulwahn@32667
   220
bulwahn@32667
   221
datatype pred_data = PredData of {
bulwahn@39767
   222
  intros : (string option * thm) list,
bulwahn@32667
   223
  elim : thm option,
bulwahn@39881
   224
  preprocessed : bool,
bulwahn@34935
   225
  function_names : (compilation * (mode * string) list) list,
bulwahn@34935
   226
  predfun_data : (mode * predfun_data) list,
bulwahn@34935
   227
  needs_random : mode list
bulwahn@32667
   228
};
bulwahn@32667
   229
bulwahn@32667
   230
fun rep_pred_data (PredData data) = data;
bulwahn@34935
   231
bulwahn@39881
   232
fun mk_pred_data (((intros, elim), preprocessed), (function_names, (predfun_data, needs_random))) =
bulwahn@39881
   233
  PredData {intros = intros, elim = elim, preprocessed = preprocessed,
bulwahn@34935
   234
    function_names = function_names, predfun_data = predfun_data, needs_random = needs_random}
bulwahn@34935
   235
bulwahn@39881
   236
fun map_pred_data f (PredData {intros, elim, preprocessed, function_names, predfun_data, needs_random}) =
bulwahn@39881
   237
  mk_pred_data (f (((intros, elim), preprocessed), (function_names, (predfun_data, needs_random))))
bulwahn@33144
   238
bulwahn@32667
   239
fun eq_option eq (NONE, NONE) = true
bulwahn@32667
   240
  | eq_option eq (SOME x, SOME y) = eq (x, y)
bulwahn@32667
   241
  | eq_option eq _ = false
bulwahn@33144
   242
bulwahn@32667
   243
fun eq_pred_data (PredData d1, PredData d2) = 
bulwahn@39767
   244
  eq_list (eq_pair (op =) Thm.eq_thm) (#intros d1, #intros d2) andalso
bulwahn@35885
   245
  eq_option Thm.eq_thm (#elim d1, #elim d2)
bulwahn@33144
   246
wenzelm@33522
   247
structure PredData = Theory_Data
bulwahn@32667
   248
(
bulwahn@32667
   249
  type T = pred_data Graph.T;
bulwahn@32667
   250
  val empty = Graph.empty;
bulwahn@32667
   251
  val extend = I;
wenzelm@33522
   252
  val merge = Graph.merge eq_pred_data;
bulwahn@32667
   253
);
bulwahn@32667
   254
bulwahn@32667
   255
(* queries *)
bulwahn@32667
   256
bulwahn@36998
   257
fun lookup_pred_data ctxt name =
bulwahn@36998
   258
  Option.map rep_pred_data (try (Graph.get_node (PredData.get (ProofContext.theory_of ctxt))) name)
bulwahn@32667
   259
bulwahn@36998
   260
fun the_pred_data ctxt name = case lookup_pred_data ctxt name
bulwahn@32667
   261
 of NONE => error ("No such predicate " ^ quote name)  
bulwahn@32667
   262
  | SOME data => data;
bulwahn@32667
   263
bulwahn@36998
   264
val is_registered = is_some oo lookup_pred_data
bulwahn@32667
   265
bulwahn@36994
   266
val all_preds_of = Graph.keys o PredData.get o ProofContext.theory_of
bulwahn@32667
   267
bulwahn@39767
   268
val intros_of = map snd o #intros oo the_pred_data
bulwahn@39767
   269
bulwahn@39767
   270
val names_of = map fst o #intros oo the_pred_data
bulwahn@32667
   271
bulwahn@36998
   272
fun the_elim_of ctxt name = case #elim (the_pred_data ctxt name)
bulwahn@32667
   273
 of NONE => error ("No elimination rule for predicate " ^ quote name)
bulwahn@36998
   274
  | SOME thm => thm
bulwahn@32667
   275
  
bulwahn@36998
   276
val has_elim = is_some o #elim oo the_pred_data
bulwahn@32667
   277
bulwahn@36994
   278
fun function_names_of compilation ctxt name =
bulwahn@36998
   279
  case AList.lookup (op =) (#function_names (the_pred_data ctxt name)) compilation of
bulwahn@34935
   280
    NONE => error ("No " ^ string_of_compilation compilation
bulwahn@34935
   281
      ^ "functions defined for predicate " ^ quote name)
bulwahn@34935
   282
  | SOME fun_names => fun_names
bulwahn@32667
   283
bulwahn@36994
   284
fun function_name_of compilation ctxt name mode =
bulwahn@35324
   285
  case AList.lookup eq_mode
bulwahn@36994
   286
    (function_names_of compilation ctxt name) mode of
bulwahn@34935
   287
    NONE => error ("No " ^ string_of_compilation compilation
bulwahn@36013
   288
      ^ " function defined for mode " ^ string_of_mode mode ^ " of predicate " ^ quote name)
bulwahn@34935
   289
  | SOME function_name => function_name
bulwahn@32667
   290
bulwahn@36994
   291
fun modes_of compilation ctxt name = map fst (function_names_of compilation ctxt name)
bulwahn@32667
   292
bulwahn@36994
   293
fun all_modes_of compilation ctxt =
bulwahn@36994
   294
  map_filter (fn name => Option.map (pair name) (try (modes_of compilation ctxt) name))
bulwahn@36994
   295
    (all_preds_of ctxt)
bulwahn@34935
   296
bulwahn@34935
   297
val all_random_modes_of = all_modes_of Random
bulwahn@34935
   298
bulwahn@36998
   299
fun defined_functions compilation ctxt name = case lookup_pred_data ctxt name of
bulwahn@36992
   300
    NONE => false
bulwahn@36992
   301
  | SOME data => AList.defined (op =) (#function_names data) compilation
bulwahn@32667
   302
bulwahn@36994
   303
fun needs_random ctxt s m =
bulwahn@36998
   304
  member (op =) (#needs_random (the_pred_data ctxt s)) m
bulwahn@36994
   305
bulwahn@36998
   306
fun lookup_predfun_data ctxt name mode =
bulwahn@33483
   307
  Option.map rep_predfun_data
bulwahn@36998
   308
    (AList.lookup (op =) (#predfun_data (the_pred_data ctxt name)) mode)
bulwahn@32667
   309
bulwahn@36998
   310
fun the_predfun_data ctxt name mode =
bulwahn@36998
   311
  case lookup_predfun_data ctxt name mode of
bulwahn@34935
   312
    NONE => error ("No function defined for mode " ^ string_of_mode mode ^
bulwahn@34935
   313
      " of predicate " ^ name)
bulwahn@34935
   314
  | SOME data => data;
bulwahn@32667
   315
bulwahn@36998
   316
val predfun_definition_of = #definition ooo the_predfun_data
bulwahn@32667
   317
bulwahn@36998
   318
val predfun_intro_of = #intro ooo the_predfun_data
bulwahn@32667
   319
bulwahn@36998
   320
val predfun_elim_of = #elim ooo the_predfun_data
bulwahn@32667
   321
bulwahn@36998
   322
val predfun_neg_intro_of = #neg_intro ooo the_predfun_data
bulwahn@35884
   323
bulwahn@38318
   324
val intros_graph_of =
bulwahn@39767
   325
  Graph.map (K (map snd o #intros o rep_pred_data)) o PredData.get o ProofContext.theory_of
bulwahn@38318
   326
bulwahn@32667
   327
(* diagnostic display functions *)
bulwahn@32667
   328
bulwahn@36995
   329
fun print_modes options modes =
bulwahn@33243
   330
  if show_modes options then
bulwahn@33326
   331
    tracing ("Inferred modes:\n" ^
bulwahn@33243
   332
      cat_lines (map (fn (s, ms) => s ^ ": " ^ commas (map
bulwahn@35324
   333
        (fn (p, m) => string_of_mode m ^ (if p then "pos" else "neg")) ms)) modes))
bulwahn@33243
   334
  else ()
bulwahn@32667
   335
bulwahn@36995
   336
fun print_pred_mode_table string_of_entry pred_mode_table =
bulwahn@32667
   337
  let
bulwahn@35324
   338
    fun print_mode pred ((pol, mode), entry) =  "mode : " ^ string_of_mode mode
bulwahn@33619
   339
      ^ string_of_entry pred mode entry
bulwahn@32667
   340
    fun print_pred (pred, modes) =
bulwahn@32667
   341
      "predicate " ^ pred ^ ": " ^ cat_lines (map (print_mode pred) modes)
bulwahn@33326
   342
    val _ = tracing (cat_lines (map print_pred pred_mode_table))
bulwahn@32667
   343
  in () end;
bulwahn@32667
   344
bulwahn@36994
   345
fun string_of_prem ctxt (Prem t) =
bulwahn@36994
   346
    (Syntax.string_of_term ctxt t) ^ "(premise)"
bulwahn@36994
   347
  | string_of_prem ctxt (Negprem t) =
bulwahn@36994
   348
    (Syntax.string_of_term ctxt (HOLogic.mk_not t)) ^ "(negative premise)"
bulwahn@36994
   349
  | string_of_prem ctxt (Sidecond t) =
bulwahn@36994
   350
    (Syntax.string_of_term ctxt t) ^ "(sidecondition)"
bulwahn@36994
   351
  | string_of_prem ctxt _ = raise Fail "string_of_prem: unexpected input"
bulwahn@33130
   352
bulwahn@36994
   353
fun string_of_clause ctxt pred (ts, prems) =
bulwahn@33130
   354
  (space_implode " --> "
bulwahn@36994
   355
  (map (string_of_prem ctxt) prems)) ^ " --> " ^ pred ^ " "
bulwahn@36994
   356
   ^ (space_implode " " (map (Syntax.string_of_term ctxt) ts))
bulwahn@33130
   357
bulwahn@36996
   358
fun print_compiled_terms options ctxt =
bulwahn@33139
   359
  if show_compilation options then
bulwahn@36996
   360
    print_pred_mode_table (fn _ => fn _ => Syntax.string_of_term ctxt)
bulwahn@33139
   361
  else K ()
bulwahn@33139
   362
bulwahn@36998
   363
fun print_stored_rules ctxt =
bulwahn@32667
   364
  let
bulwahn@36998
   365
    val preds = Graph.keys (PredData.get (ProofContext.theory_of ctxt))
bulwahn@32667
   366
    fun print pred () = let
bulwahn@32667
   367
      val _ = writeln ("predicate: " ^ pred)
bulwahn@32667
   368
      val _ = writeln ("introrules: ")
bulwahn@36998
   369
      val _ = fold (fn thm => fn u => writeln (Display.string_of_thm ctxt thm))
bulwahn@36998
   370
        (rev (intros_of ctxt pred)) ()
bulwahn@32667
   371
    in
bulwahn@36998
   372
      if (has_elim ctxt pred) then
bulwahn@36998
   373
        writeln ("elimrule: " ^ Display.string_of_thm ctxt (the_elim_of ctxt pred))
bulwahn@32667
   374
      else
bulwahn@32667
   375
        writeln ("no elimrule defined")
bulwahn@32667
   376
    end
bulwahn@32667
   377
  in
bulwahn@32667
   378
    fold print preds ()
bulwahn@32667
   379
  end;
bulwahn@32667
   380
bulwahn@36994
   381
fun print_all_modes compilation ctxt =
bulwahn@32667
   382
  let
bulwahn@32667
   383
    val _ = writeln ("Inferred modes:")
bulwahn@32667
   384
    fun print (pred, modes) u =
bulwahn@32667
   385
      let
bulwahn@32667
   386
        val _ = writeln ("predicate: " ^ pred)
bulwahn@34935
   387
        val _ = writeln ("modes: " ^ (commas (map string_of_mode modes)))
bulwahn@33619
   388
      in u end
bulwahn@32667
   389
  in
bulwahn@36994
   390
    fold print (all_modes_of compilation ctxt) ()
bulwahn@32667
   391
  end
bulwahn@33129
   392
bulwahn@33132
   393
(* validity checks *)
bulwahn@33132
   394
bulwahn@33752
   395
fun check_expected_modes preds options modes =
bulwahn@33752
   396
  case expected_modes options of
bulwahn@33752
   397
    SOME (s, ms) => (case AList.lookup (op =) modes s of
bulwahn@33752
   398
      SOME modes =>
bulwahn@33752
   399
        let
bulwahn@35324
   400
          val modes' = map snd modes
bulwahn@33752
   401
        in
bulwahn@34935
   402
          if not (eq_set eq_mode (ms, modes')) then
bulwahn@33752
   403
            error ("expected modes were not inferred:\n"
bulwahn@34935
   404
            ^ "  inferred modes for " ^ s ^ ": " ^ commas (map string_of_mode modes')  ^ "\n"
bulwahn@34935
   405
            ^ "  expected modes for " ^ s ^ ": " ^ commas (map string_of_mode ms))
bulwahn@33752
   406
          else ()
bulwahn@33752
   407
        end
bulwahn@33752
   408
      | NONE => ())
bulwahn@33752
   409
  | NONE => ()
bulwahn@33752
   410
bulwahn@39431
   411
fun check_proposed_modes preds options modes errors =
bulwahn@39628
   412
  map (fn (s, _) => case proposed_modes options s of
bulwahn@39628
   413
    SOME ms => (case AList.lookup (op =) modes s of
bulwahn@33752
   414
      SOME inferred_ms =>
bulwahn@33752
   415
        let
bulwahn@39431
   416
          val preds_without_modes = map fst (filter (null o snd) modes)
bulwahn@35324
   417
          val modes' = map snd inferred_ms
bulwahn@33752
   418
        in
bulwahn@34935
   419
          if not (eq_set eq_mode (ms, modes')) then
bulwahn@33752
   420
            error ("expected modes were not inferred:\n"
bulwahn@34935
   421
            ^ "  inferred modes for " ^ s ^ ": " ^ commas (map string_of_mode modes')  ^ "\n"
bulwahn@34935
   422
            ^ "  expected modes for " ^ s ^ ": " ^ commas (map string_of_mode ms) ^ "\n"
bulwahn@39629
   423
            ^ (if show_invalid_clauses options then
bulwahn@39629
   424
            ("For the following clauses, the following modes could not be inferred: " ^ "\n"
bulwahn@39629
   425
            ^ cat_lines errors) else "") ^
bulwahn@33752
   426
            (if not (null preds_without_modes) then
bulwahn@33752
   427
              "\n" ^ "No mode inferred for the predicates " ^ commas preds_without_modes
bulwahn@33752
   428
            else ""))
bulwahn@33752
   429
          else ()
bulwahn@33752
   430
        end
bulwahn@33752
   431
      | NONE => ())
bulwahn@39628
   432
  | NONE => ()) preds
bulwahn@33132
   433
bulwahn@39875
   434
fun check_matches_type ctxt predname T ms =
bulwahn@39875
   435
  let
bulwahn@39875
   436
    fun check (m as Fun (m1, m2)) (Type("fun", [T1,T2])) = check m1 T1 andalso check m2 T2
bulwahn@39894
   437
      | check m (T as Type("fun", _)) =
bulwahn@39894
   438
        if body_type T = @{typ bool} then false else (m = Input orelse m = Output)
bulwahn@39875
   439
      | check (Pair (m1, m2)) (Type (@{type_name Product_Type.prod}, [T1, T2])) =
bulwahn@39875
   440
          check m1 T1 andalso check m2 T2 
bulwahn@39875
   441
      | check Input T = true
bulwahn@39875
   442
      | check Output T = true
bulwahn@39875
   443
      | check Bool @{typ bool} = true
bulwahn@39875
   444
      | check _ _ = false
bulwahn@39875
   445
    val _ = map
bulwahn@39875
   446
      (fn mode =>
bulwahn@39875
   447
        if (forall (uncurry check) (strip_fun_mode mode ~~ binder_types T)) then ()
bulwahn@39875
   448
        else error (string_of_mode mode ^ " is not a valid mode for " ^ Syntax.string_of_typ ctxt T
bulwahn@39875
   449
        ^ " at predicate " ^ predname)) ms
bulwahn@39875
   450
  in
bulwahn@39875
   451
    ms
bulwahn@39875
   452
  end
bulwahn@39875
   453
bulwahn@39875
   454
bulwahn@33144
   455
(* importing introduction rules *)
bulwahn@33129
   456
bulwahn@33129
   457
fun unify_consts thy cs intr_ts =
bulwahn@33129
   458
  (let
bulwahn@33129
   459
     val add_term_consts_2 = fold_aterms (fn Const c => insert (op =) c | _ => I);
bulwahn@33129
   460
     fun varify (t, (i, ts)) =
wenzelm@35845
   461
       let val t' = map_types (Logic.incr_tvar (i + 1)) (#2 (Type.varify_global [] t))
bulwahn@33129
   462
       in (maxidx_of_term t', t'::ts) end;
bulwahn@33150
   463
     val (i, cs') = List.foldr varify (~1, []) cs;
bulwahn@33150
   464
     val (i', intr_ts') = List.foldr varify (i, []) intr_ts;
bulwahn@33129
   465
     val rec_consts = fold add_term_consts_2 cs' [];
bulwahn@33129
   466
     val intr_consts = fold add_term_consts_2 intr_ts' [];
bulwahn@33129
   467
     fun unify (cname, cT) =
wenzelm@33325
   468
       let val consts = map snd (filter (fn c => fst c = cname) intr_consts)
bulwahn@33129
   469
       in fold (Sign.typ_unify thy) ((replicate (length consts) cT) ~~ consts) end;
bulwahn@33129
   470
     val (env, _) = fold unify rec_consts (Vartab.empty, i');
bulwahn@33129
   471
     val subst = map_types (Envir.norm_type env)
bulwahn@33129
   472
   in (map subst cs', map subst intr_ts')
bulwahn@33129
   473
   end) handle Type.TUNIFY =>
bulwahn@33129
   474
     (warning "Occurrences of recursive constant have non-unifiable types"; (cs, intr_ts));
bulwahn@33129
   475
bulwahn@34935
   476
fun import_intros inp_pred [] ctxt =
bulwahn@33146
   477
  let
bulwahn@34935
   478
    val ([outp_pred], ctxt') = Variable.import_terms true [inp_pred] ctxt
bulwahn@34935
   479
    val T = fastype_of outp_pred
bulwahn@39532
   480
    val paramTs = ho_argsT_of_typ (binder_types T)
bulwahn@34935
   481
    val (param_names, ctxt'') = Variable.variant_fixes
bulwahn@34935
   482
      (map (fn i => "p" ^ (string_of_int i)) (1 upto (length paramTs))) ctxt'
bulwahn@33629
   483
    val params = map2 (curry Free) param_names paramTs
bulwahn@34935
   484
  in
bulwahn@34935
   485
    (((outp_pred, params), []), ctxt')
bulwahn@34935
   486
  end
bulwahn@34935
   487
  | import_intros inp_pred (th :: ths) ctxt =
bulwahn@33129
   488
    let
bulwahn@34935
   489
      val ((_, [th']), ctxt') = Variable.import true [th] ctxt
bulwahn@33129
   490
      val thy = ProofContext.theory_of ctxt'
bulwahn@34935
   491
      val (pred, args) = strip_intro_concl th'
bulwahn@34935
   492
      val T = fastype_of pred
bulwahn@39532
   493
      val ho_args = ho_args_of_typ T args
bulwahn@33146
   494
      fun subst_of (pred', pred) =
bulwahn@33146
   495
        let
bulwahn@33146
   496
          val subst = Sign.typ_match thy (fastype_of pred', fastype_of pred) Vartab.empty
wenzelm@39933
   497
            handle Type.TYPE_MATCH => error ("Type mismatch of predicate " ^ fst (dest_Const pred)
bulwahn@39877
   498
            ^ " (trying to match " ^ Syntax.string_of_typ ctxt (fastype_of pred')
bulwahn@39877
   499
            ^ " and " ^ Syntax.string_of_typ ctxt (fastype_of pred) ^ ")"
bulwahn@39877
   500
            ^ " in " ^ Display.string_of_thm ctxt th)
bulwahn@33146
   501
        in map (fn (indexname, (s, T)) => ((indexname, s), T)) (Vartab.dest subst) end
bulwahn@33129
   502
      fun instantiate_typ th =
bulwahn@33129
   503
        let
bulwahn@34935
   504
          val (pred', _) = strip_intro_concl th
bulwahn@33129
   505
          val _ = if not (fst (dest_Const pred) = fst (dest_Const pred')) then
bulwahn@35885
   506
            raise Fail "Trying to instantiate another predicate" else ()
bulwahn@33146
   507
        in Thm.certify_instantiate (subst_of (pred', pred), []) th end;
bulwahn@33129
   508
      fun instantiate_ho_args th =
bulwahn@33129
   509
        let
bulwahn@34935
   510
          val (_, args') = (strip_comb o HOLogic.dest_Trueprop o Logic.strip_imp_concl o prop_of) th
bulwahn@39532
   511
          val ho_args' = map dest_Var (ho_args_of_typ T args')
bulwahn@34935
   512
        in Thm.certify_instantiate ([], ho_args' ~~ ho_args) th end
bulwahn@33146
   513
      val outp_pred =
bulwahn@33146
   514
        Term_Subst.instantiate (subst_of (inp_pred, pred), []) inp_pred
bulwahn@33129
   515
      val ((_, ths'), ctxt1) =
bulwahn@33129
   516
        Variable.import false (map (instantiate_typ #> instantiate_ho_args) ths) ctxt'
bulwahn@33129
   517
    in
bulwahn@34935
   518
      (((outp_pred, ho_args), th' :: ths'), ctxt1)
bulwahn@33129
   519
    end
bulwahn@33129
   520
bulwahn@33129
   521
(* generation of case rules from user-given introduction rules *)
bulwahn@33129
   522
haftmann@37678
   523
fun mk_args2 (Type (@{type_name Product_Type.prod}, [T1, T2])) st =
bulwahn@34935
   524
    let
bulwahn@34935
   525
      val (t1, st') = mk_args2 T1 st
bulwahn@34935
   526
      val (t2, st'') = mk_args2 T2 st'
bulwahn@34935
   527
    in
bulwahn@34935
   528
      (HOLogic.mk_prod (t1, t2), st'')
bulwahn@34935
   529
    end
bulwahn@35884
   530
  (*| mk_args2 (T as Type ("fun", _)) (params, ctxt) = 
bulwahn@34935
   531
    let
bulwahn@34935
   532
      val (S, U) = strip_type T
bulwahn@34935
   533
    in
bulwahn@34935
   534
      if U = HOLogic.boolT then
bulwahn@34935
   535
        (hd params, (tl params, ctxt))
bulwahn@34935
   536
      else
bulwahn@34935
   537
        let
bulwahn@34935
   538
          val ([x], ctxt') = Variable.variant_fixes ["x"] ctxt
bulwahn@34935
   539
        in
bulwahn@34935
   540
          (Free (x, T), (params, ctxt'))
bulwahn@34935
   541
        end
bulwahn@35884
   542
    end*)
bulwahn@34935
   543
  | mk_args2 T (params, ctxt) =
bulwahn@34935
   544
    let
bulwahn@34935
   545
      val ([x], ctxt') = Variable.variant_fixes ["x"] ctxt
bulwahn@34935
   546
    in
bulwahn@34935
   547
      (Free (x, T), (params, ctxt'))
bulwahn@34935
   548
    end
bulwahn@35884
   549
bulwahn@34935
   550
fun mk_casesrule ctxt pred introrules =
bulwahn@33129
   551
  let
bulwahn@35884
   552
    (* TODO: can be simplified if parameters are not treated specially ? *)
bulwahn@34935
   553
    val (((pred, params), intros_th), ctxt1) = import_intros pred introrules ctxt
bulwahn@35884
   554
    (* TODO: distinct required ? -- test case with more than one parameter! *)
bulwahn@35884
   555
    val params = distinct (op aconv) params
bulwahn@33129
   556
    val intros = map prop_of intros_th
bulwahn@33129
   557
    val ([propname], ctxt2) = Variable.variant_fixes ["thesis"] ctxt1
bulwahn@33129
   558
    val prop = HOLogic.mk_Trueprop (Free (propname, HOLogic.boolT))
bulwahn@34935
   559
    val argsT = binder_types (fastype_of pred)
bulwahn@35884
   560
    (* TODO: can be simplified if parameters are not treated specially ? <-- see uncommented code! *)
bulwahn@34935
   561
    val (argvs, _) = fold_map mk_args2 argsT (params, ctxt2)
bulwahn@33129
   562
    fun mk_case intro =
bulwahn@33129
   563
      let
bulwahn@34935
   564
        val (_, args) = (strip_comb o HOLogic.dest_Trueprop o Logic.strip_imp_concl) intro
bulwahn@33129
   565
        val prems = Logic.strip_imp_prems intro
bulwahn@35884
   566
        val eqprems =
bulwahn@35884
   567
          map2 (HOLogic.mk_Trueprop oo (curry HOLogic.mk_eq)) argvs args
bulwahn@35884
   568
        val frees = map Free (fold Term.add_frees (args @ prems) [])
bulwahn@33129
   569
      in fold Logic.all frees (Logic.list_implies (eqprems @ prems, prop)) end
bulwahn@34935
   570
    val assm = HOLogic.mk_Trueprop (list_comb (pred, argvs))
bulwahn@33129
   571
    val cases = map mk_case intros
bulwahn@33129
   572
  in Logic.list_implies (assm :: cases, prop) end;
bulwahn@33129
   573
bulwahn@35884
   574
fun dest_conjunct_prem th =
bulwahn@35884
   575
  case HOLogic.dest_Trueprop (prop_of th) of
haftmann@39028
   576
    (Const (@{const_name HOL.conj}, _) $ t $ t') =>
bulwahn@35884
   577
      dest_conjunct_prem (th RS @{thm conjunct1})
bulwahn@35884
   578
        @ dest_conjunct_prem (th RS @{thm conjunct2})
bulwahn@35884
   579
    | _ => [th]
bulwahn@35884
   580
bulwahn@35884
   581
fun prove_casesrule ctxt (pred, (pre_cases_rule, nparams)) cases_rule =
bulwahn@35884
   582
  let
bulwahn@35884
   583
    val thy = ProofContext.theory_of ctxt
bulwahn@35884
   584
    val nargs = length (binder_types (fastype_of pred))
bulwahn@35884
   585
    fun PEEK f dependent_tactic st = dependent_tactic (f st) st
bulwahn@35884
   586
    fun meta_eq_of th = th RS @{thm eq_reflection}
bulwahn@35884
   587
    val tuple_rew_rules = map meta_eq_of [@{thm fst_conv}, @{thm snd_conv}, @{thm Pair_eq}]
bulwahn@35884
   588
    fun instantiate i n {context = ctxt, params = p, prems = prems,
bulwahn@35884
   589
      asms = a, concl = cl, schematics = s}  =
bulwahn@35884
   590
      let
bulwahn@36503
   591
        fun term_pair_of (ix, (ty,t)) = (Var (ix,ty), t)
bulwahn@36503
   592
        fun inst_of_matches tts = fold (Pattern.match thy) tts (Vartab.empty, Vartab.empty)
bulwahn@36503
   593
          |> snd |> Vartab.dest |> map (pairself (cterm_of thy) o term_pair_of)
bulwahn@35884
   594
        val (cases, (eqs, prems)) = apsnd (chop (nargs - nparams)) (chop n prems)
bulwahn@35884
   595
        val case_th = MetaSimplifier.simplify true
bulwahn@36502
   596
          (@{thm Predicate.eq_is_eq} :: map meta_eq_of eqs) (nth cases (i - 1))
bulwahn@35884
   597
        val prems' = maps (dest_conjunct_prem o MetaSimplifier.simplify true tuple_rew_rules) prems
bulwahn@35884
   598
        val pats = map (swap o HOLogic.dest_eq o HOLogic.dest_Trueprop) (take nargs (prems_of case_th))
bulwahn@36503
   599
        val case_th' = Thm.instantiate ([], inst_of_matches pats) case_th
bulwahn@36503
   600
          OF (replicate nargs @{thm refl})
bulwahn@36503
   601
        val thesis =
bulwahn@36503
   602
          Thm.instantiate ([], inst_of_matches (prems_of case_th' ~~ map prop_of prems')) case_th'
bulwahn@36503
   603
            OF prems'
bulwahn@35884
   604
      in
bulwahn@35884
   605
        (rtac thesis 1)
bulwahn@35884
   606
      end
bulwahn@35884
   607
    val tac =
bulwahn@35884
   608
      etac pre_cases_rule 1
bulwahn@35884
   609
      THEN
bulwahn@35884
   610
      (PEEK nprems_of
bulwahn@35884
   611
        (fn n =>
bulwahn@35884
   612
          ALLGOALS (fn i =>
bulwahn@35884
   613
            MetaSimplifier.rewrite_goal_tac [@{thm split_paired_all}] i
bulwahn@35884
   614
            THEN (SUBPROOF (instantiate i n) ctxt i))))
bulwahn@35884
   615
  in
bulwahn@35884
   616
    Goal.prove ctxt (Term.add_free_names cases_rule []) [] cases_rule (fn _ => tac)
bulwahn@35884
   617
  end
bulwahn@35884
   618
bulwahn@34935
   619
(** preprocessing rules **)
bulwahn@32667
   620
bulwahn@32667
   621
fun Trueprop_conv cv ct =
bulwahn@32667
   622
  case Thm.term_of ct of
haftmann@38783
   623
    Const (@{const_name Trueprop}, _) $ _ => Conv.arg_conv cv ct  
bulwahn@35885
   624
  | _ => raise Fail "Trueprop_conv"
bulwahn@32667
   625
bulwahn@39881
   626
fun preprocess_equality thy rule =
bulwahn@32667
   627
  Conv.fconv_rule
bulwahn@32667
   628
    (imp_prems_conv
bulwahn@32667
   629
      (Trueprop_conv (Conv.try_conv (Conv.rewr_conv (Thm.symmetric @{thm Predicate.eq_is_eq})))))
bulwahn@32667
   630
    (Thm.transfer thy rule)
bulwahn@32667
   631
bulwahn@39881
   632
fun preprocess_intro thy = expand_tuples thy #> preprocess_equality thy
bulwahn@39881
   633
bulwahn@39882
   634
(* fetching introduction rules or registering introduction rules *)
bulwahn@32667
   635
bulwahn@35887
   636
val no_compilation = ([], ([], []))
bulwahn@33483
   637
bulwahn@36998
   638
fun fetch_pred_data ctxt name =
bulwahn@36998
   639
  case try (Inductive.the_inductive ctxt) name of
bulwahn@32667
   640
    SOME (info as (_, result)) => 
bulwahn@32667
   641
      let
bulwahn@32667
   642
        fun is_intro_of intro =
bulwahn@32667
   643
          let
bulwahn@32667
   644
            val (const, _) = strip_comb (HOLogic.dest_Trueprop (concl_of intro))
bulwahn@36998
   645
          in (fst (dest_Const const) = name) end;
bulwahn@36998
   646
        val thy = ProofContext.theory_of ctxt
bulwahn@39881
   647
        val intros = map (preprocess_intro thy) (filter is_intro_of (#intrs result))
bulwahn@33146
   648
        val index = find_index (fn s => s = name) (#names (fst info))
bulwahn@33146
   649
        val pre_elim = nth (#elims result) index
bulwahn@33146
   650
        val pred = nth (#preds result) index
bulwahn@39881
   651
        val elim_t = mk_casesrule ctxt pred intros
bulwahn@35884
   652
        val nparams = length (Inductive.params_of (#raw_induct result))
bulwahn@39881
   653
        val elim = prove_casesrule ctxt (pred, (pre_elim, nparams)) elim_t
bulwahn@32667
   654
      in
bulwahn@39881
   655
        mk_pred_data (((map (pair NONE) intros, SOME elim), true), no_compilation)
bulwahn@33483
   656
      end
bulwahn@32667
   657
  | NONE => error ("No such predicate: " ^ quote name)
bulwahn@33124
   658
bulwahn@34935
   659
fun add_predfun_data name mode data =
bulwahn@32667
   660
  let
bulwahn@35887
   661
    val add = (apsnd o apsnd o apfst) (cons (mode, mk_predfun_data data))
bulwahn@32667
   662
  in PredData.map (Graph.map_node name (map_pred_data add)) end
bulwahn@32667
   663
bulwahn@36994
   664
fun is_inductive_predicate ctxt name =
bulwahn@36994
   665
  is_some (try (Inductive.the_inductive ctxt) name)
bulwahn@32667
   666
bulwahn@36994
   667
fun depending_preds_of ctxt (key, value) =
bulwahn@32667
   668
  let
bulwahn@39767
   669
    val intros = map (Thm.prop_of o snd) ((#intros o rep_pred_data) value)
bulwahn@32667
   670
  in
bulwahn@39767
   671
    fold Term.add_const_names intros []
bulwahn@39881
   672
      |> (fn cs =>
bulwahn@39881
   673
        if member (op =) cs @{const_name "HOL.eq"} then
bulwahn@39881
   674
          insert (op =) @{const_name Predicate.eq} cs
bulwahn@39881
   675
        else cs)
bulwahn@33482
   676
      |> filter (fn c => (not (c = key)) andalso
bulwahn@36994
   677
        (is_inductive_predicate ctxt c orelse is_registered ctxt c))
bulwahn@32667
   678
  end;
bulwahn@32667
   679
bulwahn@39767
   680
fun add_intro (opt_case_name, thm) thy =
bulwahn@33629
   681
  let
bulwahn@34935
   682
    val (name, T) = dest_Const (fst (strip_intro_concl thm))
bulwahn@33629
   683
    fun cons_intro gr =
bulwahn@32667
   684
     case try (Graph.get_node gr) name of
bulwahn@32667
   685
       SOME pred_data => Graph.map_node name (map_pred_data
bulwahn@39881
   686
         (apfst (apfst (apfst (fn intros => intros @ [(opt_case_name, thm)]))))) gr
bulwahn@39881
   687
     | NONE => Graph.new_node (name, mk_pred_data ((([(opt_case_name, thm)], NONE), false), no_compilation)) gr
bulwahn@32667
   688
  in PredData.map cons_intro thy end
bulwahn@32667
   689
bulwahn@33629
   690
fun set_elim thm =
bulwahn@33629
   691
  let
bulwahn@32667
   692
    val (name, _) = dest_Const (fst 
bulwahn@32667
   693
      (strip_comb (HOLogic.dest_Trueprop (hd (prems_of thm)))))
bulwahn@39881
   694
  in PredData.map (Graph.map_node name (map_pred_data (apfst (apfst (apsnd (K (SOME thm))))))) end
bulwahn@32667
   695
bulwahn@39881
   696
fun register_predicate (constname, intros, elim) thy =
bulwahn@33629
   697
  let
bulwahn@39881
   698
    val named_intros = map (pair NONE) intros
bulwahn@32667
   699
  in
bulwahn@33146
   700
    if not (member (op =) (Graph.keys (PredData.get thy)) constname) then
bulwahn@32668
   701
      PredData.map
bulwahn@33482
   702
        (Graph.new_node (constname,
bulwahn@39881
   703
          mk_pred_data (((named_intros, SOME elim), false), no_compilation))) thy
bulwahn@32668
   704
    else thy
bulwahn@32667
   705
  end
bulwahn@32667
   706
bulwahn@33146
   707
fun register_intros (constname, pre_intros) thy =
bulwahn@32668
   708
  let
bulwahn@33146
   709
    val T = Sign.the_const_type thy constname
bulwahn@34935
   710
    fun constname_of_intro intr = fst (dest_Const (fst (strip_intro_concl intr)))
bulwahn@33146
   711
    val _ = if not (forall (fn intr => constname_of_intro intr = constname) pre_intros) then
bulwahn@33146
   712
      error ("register_intros: Introduction rules of different constants are used\n" ^
bulwahn@33146
   713
        "expected rules for " ^ constname ^ ", but received rules for " ^
bulwahn@33146
   714
          commas (map constname_of_intro pre_intros))
bulwahn@33146
   715
      else ()
bulwahn@33146
   716
    val pred = Const (constname, T)
bulwahn@32672
   717
    val pre_elim = 
wenzelm@35021
   718
      (Drule.export_without_context o Skip_Proof.make_thm thy)
wenzelm@36633
   719
      (mk_casesrule (ProofContext.init_global thy) pred pre_intros)
bulwahn@34935
   720
  in register_predicate (constname, pre_intros, pre_elim) thy end
bulwahn@32668
   721
bulwahn@34935
   722
fun defined_function_of compilation pred =
bulwahn@32667
   723
  let
bulwahn@35887
   724
    val set = (apsnd o apfst) (cons (compilation, []))
bulwahn@32667
   725
  in
bulwahn@32667
   726
    PredData.map (Graph.map_node pred (map_pred_data set))
bulwahn@32667
   727
  end
bulwahn@32667
   728
bulwahn@34935
   729
fun set_function_name compilation pred mode name =
bulwahn@32667
   730
  let
bulwahn@35887
   731
    val set = (apsnd o apfst)
bulwahn@34935
   732
      (AList.map_default (op =) (compilation, [(mode, name)]) (cons (mode, name)))
bulwahn@33473
   733
  in
bulwahn@33473
   734
    PredData.map (Graph.map_node pred (map_pred_data set))
bulwahn@33473
   735
  end
bulwahn@33473
   736
bulwahn@34935
   737
fun set_needs_random name modes =
bulwahn@33473
   738
  let
bulwahn@35887
   739
    val set = (apsnd o apsnd o apsnd) (K modes)
bulwahn@32667
   740
  in
bulwahn@34935
   741
    PredData.map (Graph.map_node name (map_pred_data set))
bulwahn@32667
   742
  end
bulwahn@32667
   743
bulwahn@36032
   744
(* registration of alternative function names *)
bulwahn@36032
   745
bulwahn@36032
   746
structure Alt_Compilations_Data = Theory_Data
bulwahn@36032
   747
(
bulwahn@36032
   748
  type T = (mode * (compilation_funs -> typ -> term)) list Symtab.table;
bulwahn@36032
   749
  val empty = Symtab.empty;
bulwahn@36032
   750
  val extend = I;
wenzelm@39034
   751
  fun merge data : T = Symtab.merge (K true) data;
bulwahn@36032
   752
);
bulwahn@36032
   753
bulwahn@36994
   754
fun alternative_compilation_of_global thy pred_name mode =
bulwahn@36032
   755
  AList.lookup eq_mode (Symtab.lookup_list (Alt_Compilations_Data.get thy) pred_name) mode
bulwahn@36032
   756
bulwahn@36994
   757
fun alternative_compilation_of ctxt pred_name mode =
bulwahn@36994
   758
  AList.lookup eq_mode
bulwahn@36994
   759
    (Symtab.lookup_list (Alt_Compilations_Data.get (ProofContext.theory_of ctxt)) pred_name) mode
bulwahn@36994
   760
bulwahn@36032
   761
fun force_modes_and_compilations pred_name compilations =
bulwahn@36032
   762
  let
bulwahn@36032
   763
    (* thm refl is a dummy thm *)
bulwahn@36032
   764
    val modes = map fst compilations
bulwahn@36032
   765
    val (needs_random, non_random_modes) = pairself (map fst)
bulwahn@36032
   766
      (List.partition (fn (m, (fun_name, random)) => random) compilations)
bulwahn@36032
   767
    val non_random_dummys = map (rpair "dummy") non_random_modes
bulwahn@36032
   768
    val all_dummys = map (rpair "dummy") modes
bulwahn@36032
   769
    val dummy_function_names = map (rpair all_dummys) Predicate_Compile_Aux.random_compilations
bulwahn@36032
   770
      @ map (rpair non_random_dummys) Predicate_Compile_Aux.non_random_compilations
bulwahn@36032
   771
    val alt_compilations = map (apsnd fst) compilations
bulwahn@36032
   772
  in
bulwahn@36032
   773
    PredData.map (Graph.new_node
bulwahn@39881
   774
      (pred_name, mk_pred_data ((([], SOME @{thm refl}), true), (dummy_function_names, ([], needs_random)))))
bulwahn@36032
   775
    #> Alt_Compilations_Data.map (Symtab.insert (K false) (pred_name, alt_compilations))
bulwahn@36032
   776
  end
bulwahn@36032
   777
bulwahn@36032
   778
fun functional_compilation fun_name mode compfuns T =
bulwahn@36032
   779
  let
bulwahn@36032
   780
    val (inpTs, outpTs) = split_map_modeT (fn _ => fn T => (SOME T, NONE))
bulwahn@36032
   781
      mode (binder_types T)
bulwahn@36032
   782
    val bs = map (pair "x") inpTs
bulwahn@36032
   783
    val bounds = map Bound (rev (0 upto (length bs) - 1))
bulwahn@36032
   784
    val f = Const (fun_name, inpTs ---> HOLogic.mk_tupleT outpTs)
bulwahn@36032
   785
  in list_abs (bs, mk_single compfuns (list_comb (f, bounds))) end
bulwahn@36032
   786
bulwahn@36032
   787
fun register_alternative_function pred_name mode fun_name =
bulwahn@36032
   788
  Alt_Compilations_Data.map (Symtab.insert_list (eq_pair eq_mode (K false))
bulwahn@36032
   789
    (pred_name, (mode, functional_compilation fun_name mode)))
bulwahn@36032
   790
bulwahn@36032
   791
fun force_modes_and_functions pred_name fun_names =
bulwahn@36032
   792
  force_modes_and_compilations pred_name
bulwahn@36032
   793
    (map (fn (mode, (fun_name, random)) => (mode, (functional_compilation fun_name mode, random)))
bulwahn@36032
   794
    fun_names)
bulwahn@36032
   795
bulwahn@36013
   796
(* compilation modifiers *)
bulwahn@36013
   797
bulwahn@36013
   798
structure Comp_Mod =
bulwahn@36013
   799
struct
bulwahn@36013
   800
bulwahn@36013
   801
datatype comp_modifiers = Comp_Modifiers of
bulwahn@36013
   802
{
bulwahn@36013
   803
  compilation : compilation,
bulwahn@36013
   804
  function_name_prefix : string,
bulwahn@36013
   805
  compfuns : compilation_funs,
bulwahn@36013
   806
  mk_random : typ -> term list -> term,
bulwahn@36013
   807
  modify_funT : typ -> typ,
bulwahn@36013
   808
  additional_arguments : string list -> term list,
bulwahn@36013
   809
  wrap_compilation : compilation_funs -> string -> typ -> mode -> term list -> term -> term,
bulwahn@36013
   810
  transform_additional_arguments : indprem -> term list -> term list
bulwahn@36013
   811
}
bulwahn@36013
   812
bulwahn@36013
   813
fun dest_comp_modifiers (Comp_Modifiers c) = c
bulwahn@36013
   814
bulwahn@36013
   815
val compilation = #compilation o dest_comp_modifiers
bulwahn@36013
   816
val function_name_prefix = #function_name_prefix o dest_comp_modifiers
bulwahn@36013
   817
val compfuns = #compfuns o dest_comp_modifiers
bulwahn@36013
   818
bulwahn@36013
   819
val mk_random = #mk_random o dest_comp_modifiers
bulwahn@36013
   820
val funT_of' = funT_of o compfuns
bulwahn@36013
   821
val modify_funT = #modify_funT o dest_comp_modifiers
bulwahn@36013
   822
fun funT_of comp mode = modify_funT comp o funT_of' comp mode
bulwahn@36013
   823
bulwahn@36013
   824
val additional_arguments = #additional_arguments o dest_comp_modifiers
bulwahn@36013
   825
val wrap_compilation = #wrap_compilation o dest_comp_modifiers
bulwahn@36013
   826
val transform_additional_arguments = #transform_additional_arguments o dest_comp_modifiers
bulwahn@36013
   827
bulwahn@36013
   828
end;
bulwahn@36013
   829
bulwahn@36013
   830
val depth_limited_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36013
   831
  {
bulwahn@36013
   832
  compilation = Depth_Limited,
bulwahn@36013
   833
  function_name_prefix = "depth_limited_",
bulwahn@36013
   834
  compfuns = PredicateCompFuns.compfuns,
bulwahn@36013
   835
  mk_random = (fn _ => error "no random generation"),
bulwahn@36013
   836
  additional_arguments = fn names =>
bulwahn@36013
   837
    let
bulwahn@36013
   838
      val depth_name = Name.variant names "depth"
bulwahn@36013
   839
    in [Free (depth_name, @{typ code_numeral})] end,
bulwahn@36013
   840
  modify_funT = (fn T => let val (Ts, U) = strip_type T
bulwahn@36013
   841
  val Ts' = [@{typ code_numeral}] in (Ts @ Ts') ---> U end),
bulwahn@36013
   842
  wrap_compilation =
bulwahn@36013
   843
    fn compfuns => fn s => fn T => fn mode => fn additional_arguments => fn compilation =>
bulwahn@36013
   844
    let
bulwahn@36013
   845
      val [depth] = additional_arguments
bulwahn@36013
   846
      val (_, Ts) = split_modeT' mode (binder_types T)
bulwahn@36013
   847
      val T' = mk_predT compfuns (HOLogic.mk_tupleT Ts)
bulwahn@36013
   848
      val if_const = Const (@{const_name "If"}, @{typ bool} --> T' --> T' --> T')
bulwahn@36013
   849
    in
bulwahn@36013
   850
      if_const $ HOLogic.mk_eq (depth, @{term "0 :: code_numeral"})
bulwahn@36013
   851
        $ mk_bot compfuns (dest_predT compfuns T')
bulwahn@36013
   852
        $ compilation
bulwahn@36013
   853
    end,
bulwahn@36013
   854
  transform_additional_arguments =
bulwahn@36013
   855
    fn prem => fn additional_arguments =>
bulwahn@36013
   856
    let
bulwahn@36013
   857
      val [depth] = additional_arguments
bulwahn@36013
   858
      val depth' =
bulwahn@36013
   859
        Const (@{const_name Groups.minus}, @{typ "code_numeral => code_numeral => code_numeral"})
bulwahn@36013
   860
          $ depth $ Const (@{const_name Groups.one}, @{typ "Code_Numeral.code_numeral"})
bulwahn@36013
   861
    in [depth'] end
bulwahn@36013
   862
  }
bulwahn@36013
   863
bulwahn@36013
   864
val random_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36013
   865
  {
bulwahn@36013
   866
  compilation = Random,
bulwahn@36013
   867
  function_name_prefix = "random_",
bulwahn@36013
   868
  compfuns = PredicateCompFuns.compfuns,
bulwahn@36013
   869
  mk_random = (fn T => fn additional_arguments =>
bulwahn@36013
   870
  list_comb (Const(@{const_name Quickcheck.iter},
bulwahn@36013
   871
  [@{typ code_numeral}, @{typ code_numeral}, @{typ Random.seed}] ---> 
bulwahn@36013
   872
    PredicateCompFuns.mk_predT T), additional_arguments)),
bulwahn@36013
   873
  modify_funT = (fn T =>
bulwahn@36013
   874
    let
bulwahn@36013
   875
      val (Ts, U) = strip_type T
bulwahn@36013
   876
      val Ts' = [@{typ code_numeral}, @{typ code_numeral}, @{typ "code_numeral * code_numeral"}]
bulwahn@36013
   877
    in (Ts @ Ts') ---> U end),
bulwahn@36013
   878
  additional_arguments = (fn names =>
bulwahn@36013
   879
    let
bulwahn@36013
   880
      val [nrandom, size, seed] = Name.variant_list names ["nrandom", "size", "seed"]
bulwahn@36013
   881
    in
bulwahn@36013
   882
      [Free (nrandom, @{typ code_numeral}), Free (size, @{typ code_numeral}),
bulwahn@36013
   883
        Free (seed, @{typ "code_numeral * code_numeral"})]
bulwahn@36013
   884
    end),
bulwahn@36013
   885
  wrap_compilation = K (K (K (K (K I))))
bulwahn@36013
   886
    : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
bulwahn@36013
   887
  transform_additional_arguments = K I : (indprem -> term list -> term list)
bulwahn@36013
   888
  }
bulwahn@36013
   889
bulwahn@36013
   890
val depth_limited_random_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36013
   891
  {
bulwahn@36013
   892
  compilation = Depth_Limited_Random,
bulwahn@36013
   893
  function_name_prefix = "depth_limited_random_",
bulwahn@36013
   894
  compfuns = PredicateCompFuns.compfuns,
bulwahn@36013
   895
  mk_random = (fn T => fn additional_arguments =>
bulwahn@36013
   896
  list_comb (Const(@{const_name Quickcheck.iter},
bulwahn@36013
   897
  [@{typ code_numeral}, @{typ code_numeral}, @{typ Random.seed}] ---> 
bulwahn@36013
   898
    PredicateCompFuns.mk_predT T), tl additional_arguments)),
bulwahn@36013
   899
  modify_funT = (fn T =>
bulwahn@36013
   900
    let
bulwahn@36013
   901
      val (Ts, U) = strip_type T
bulwahn@36013
   902
      val Ts' = [@{typ code_numeral}, @{typ code_numeral}, @{typ code_numeral},
bulwahn@36013
   903
        @{typ "code_numeral * code_numeral"}]
bulwahn@36013
   904
    in (Ts @ Ts') ---> U end),
bulwahn@36013
   905
  additional_arguments = (fn names =>
bulwahn@36013
   906
    let
bulwahn@36013
   907
      val [depth, nrandom, size, seed] = Name.variant_list names ["depth", "nrandom", "size", "seed"]
bulwahn@36013
   908
    in
bulwahn@36013
   909
      [Free (depth, @{typ code_numeral}), Free (nrandom, @{typ code_numeral}),
bulwahn@36013
   910
        Free (size, @{typ code_numeral}), Free (seed, @{typ "code_numeral * code_numeral"})]
bulwahn@36013
   911
    end),
bulwahn@36013
   912
  wrap_compilation =
bulwahn@36013
   913
  fn compfuns => fn s => fn T => fn mode => fn additional_arguments => fn compilation =>
bulwahn@36013
   914
    let
bulwahn@36013
   915
      val depth = hd (additional_arguments)
bulwahn@36013
   916
      val (_, Ts) = split_map_modeT (fn m => fn T => (SOME (funT_of compfuns m T), NONE))
bulwahn@36013
   917
        mode (binder_types T)
bulwahn@36013
   918
      val T' = mk_predT compfuns (HOLogic.mk_tupleT Ts)
bulwahn@36013
   919
      val if_const = Const (@{const_name "If"}, @{typ bool} --> T' --> T' --> T')
bulwahn@36013
   920
    in
bulwahn@36013
   921
      if_const $ HOLogic.mk_eq (depth, @{term "0 :: code_numeral"})
bulwahn@36013
   922
        $ mk_bot compfuns (dest_predT compfuns T')
bulwahn@36013
   923
        $ compilation
bulwahn@36013
   924
    end,
bulwahn@36013
   925
  transform_additional_arguments =
bulwahn@36013
   926
    fn prem => fn additional_arguments =>
bulwahn@36013
   927
    let
bulwahn@36013
   928
      val [depth, nrandom, size, seed] = additional_arguments
bulwahn@36013
   929
      val depth' =
bulwahn@36013
   930
        Const (@{const_name Groups.minus}, @{typ "code_numeral => code_numeral => code_numeral"})
bulwahn@36013
   931
          $ depth $ Const (@{const_name Groups.one}, @{typ "Code_Numeral.code_numeral"})
bulwahn@36013
   932
    in [depth', nrandom, size, seed] end
bulwahn@36013
   933
}
bulwahn@36013
   934
bulwahn@36013
   935
val predicate_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36013
   936
  {
bulwahn@36013
   937
  compilation = Pred,
bulwahn@36013
   938
  function_name_prefix = "",
bulwahn@36013
   939
  compfuns = PredicateCompFuns.compfuns,
bulwahn@36013
   940
  mk_random = (fn _ => error "no random generation"),
bulwahn@36013
   941
  modify_funT = I,
bulwahn@36013
   942
  additional_arguments = K [],
bulwahn@36013
   943
  wrap_compilation = K (K (K (K (K I))))
bulwahn@36013
   944
   : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
bulwahn@36013
   945
  transform_additional_arguments = K I : (indprem -> term list -> term list)
bulwahn@36013
   946
  }
bulwahn@36013
   947
bulwahn@36013
   948
val annotated_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36013
   949
  {
bulwahn@36013
   950
  compilation = Annotated,
bulwahn@36013
   951
  function_name_prefix = "annotated_",
bulwahn@36013
   952
  compfuns = PredicateCompFuns.compfuns,
bulwahn@36013
   953
  mk_random = (fn _ => error "no random generation"),
bulwahn@36013
   954
  modify_funT = I,
bulwahn@36013
   955
  additional_arguments = K [],
bulwahn@36013
   956
  wrap_compilation =
bulwahn@36013
   957
    fn compfuns => fn s => fn T => fn mode => fn additional_arguments => fn compilation =>
bulwahn@36013
   958
      mk_tracing ("calling predicate " ^ s ^
bulwahn@36013
   959
        " with mode " ^ string_of_mode mode) compilation,
bulwahn@36013
   960
  transform_additional_arguments = K I : (indprem -> term list -> term list)
bulwahn@36013
   961
  }
bulwahn@36013
   962
bulwahn@36013
   963
val dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36013
   964
  {
bulwahn@36013
   965
  compilation = DSeq,
bulwahn@36013
   966
  function_name_prefix = "dseq_",
bulwahn@36013
   967
  compfuns = DSequence_CompFuns.compfuns,
bulwahn@36013
   968
  mk_random = (fn _ => error "no random generation"),
bulwahn@36013
   969
  modify_funT = I,
bulwahn@36013
   970
  additional_arguments = K [],
bulwahn@36013
   971
  wrap_compilation = K (K (K (K (K I))))
bulwahn@36013
   972
   : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
bulwahn@36013
   973
  transform_additional_arguments = K I : (indprem -> term list -> term list)
bulwahn@36013
   974
  }
bulwahn@36013
   975
bulwahn@36013
   976
val pos_random_dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36013
   977
  {
bulwahn@36013
   978
  compilation = Pos_Random_DSeq,
bulwahn@36013
   979
  function_name_prefix = "random_dseq_",
bulwahn@36013
   980
  compfuns = Random_Sequence_CompFuns.compfuns,
bulwahn@36013
   981
  mk_random = (fn T => fn additional_arguments =>
bulwahn@36013
   982
  let
bulwahn@36013
   983
    val random = Const ("Quickcheck.random_class.random",
bulwahn@36013
   984
      @{typ code_numeral} --> @{typ Random.seed} -->
bulwahn@36013
   985
        HOLogic.mk_prodT (HOLogic.mk_prodT (T, @{typ "unit => term"}), @{typ Random.seed}))
bulwahn@36013
   986
  in
bulwahn@36013
   987
    Const ("Random_Sequence.Random", (@{typ code_numeral} --> @{typ Random.seed} -->
bulwahn@36013
   988
      HOLogic.mk_prodT (HOLogic.mk_prodT (T, @{typ "unit => term"}), @{typ Random.seed})) -->
bulwahn@36013
   989
      Random_Sequence_CompFuns.mk_random_dseqT T) $ random
bulwahn@36013
   990
  end),
bulwahn@36013
   991
bulwahn@36013
   992
  modify_funT = I,
bulwahn@36013
   993
  additional_arguments = K [],
bulwahn@36013
   994
  wrap_compilation = K (K (K (K (K I))))
bulwahn@36013
   995
   : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
bulwahn@36013
   996
  transform_additional_arguments = K I : (indprem -> term list -> term list)
bulwahn@36013
   997
  }
bulwahn@36013
   998
bulwahn@36013
   999
val neg_random_dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36013
  1000
  {
bulwahn@36013
  1001
  compilation = Neg_Random_DSeq,
bulwahn@36013
  1002
  function_name_prefix = "random_dseq_neg_",
bulwahn@36013
  1003
  compfuns = Random_Sequence_CompFuns.compfuns,
bulwahn@36013
  1004
  mk_random = (fn _ => error "no random generation"),
bulwahn@36013
  1005
  modify_funT = I,
bulwahn@36013
  1006
  additional_arguments = K [],
bulwahn@36013
  1007
  wrap_compilation = K (K (K (K (K I))))
bulwahn@36013
  1008
   : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
bulwahn@36013
  1009
  transform_additional_arguments = K I : (indprem -> term list -> term list)
bulwahn@36013
  1010
  }
bulwahn@36013
  1011
bulwahn@36013
  1012
bulwahn@36013
  1013
val new_pos_random_dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36013
  1014
  {
bulwahn@36013
  1015
  compilation = New_Pos_Random_DSeq,
bulwahn@36013
  1016
  function_name_prefix = "new_random_dseq_",
bulwahn@36013
  1017
  compfuns = New_Pos_Random_Sequence_CompFuns.compfuns,
bulwahn@36013
  1018
  mk_random = (fn T => fn additional_arguments =>
bulwahn@36013
  1019
  let
bulwahn@36013
  1020
    val random = Const ("Quickcheck.random_class.random",
bulwahn@36013
  1021
      @{typ code_numeral} --> @{typ Random.seed} -->
bulwahn@36013
  1022
        HOLogic.mk_prodT (HOLogic.mk_prodT (T, @{typ "unit => term"}), @{typ Random.seed}))
bulwahn@36013
  1023
  in
bulwahn@36013
  1024
    Const ("New_Random_Sequence.Random", (@{typ code_numeral} --> @{typ Random.seed} -->
bulwahn@36013
  1025
      HOLogic.mk_prodT (HOLogic.mk_prodT (T, @{typ "unit => term"}), @{typ Random.seed})) -->
bulwahn@36013
  1026
      New_Pos_Random_Sequence_CompFuns.mk_pos_random_dseqT T) $ random
bulwahn@36013
  1027
  end),
bulwahn@36013
  1028
  modify_funT = I,
bulwahn@36013
  1029
  additional_arguments = K [],
bulwahn@36013
  1030
  wrap_compilation = K (K (K (K (K I))))
bulwahn@36013
  1031
   : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
bulwahn@36013
  1032
  transform_additional_arguments = K I : (indprem -> term list -> term list)
bulwahn@36013
  1033
  }
bulwahn@36013
  1034
bulwahn@36013
  1035
val new_neg_random_dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
bulwahn@36013
  1036
  {
bulwahn@36013
  1037
  compilation = New_Neg_Random_DSeq,
bulwahn@36013
  1038
  function_name_prefix = "new_random_dseq_neg_",
bulwahn@36013
  1039
  compfuns = New_Neg_Random_Sequence_CompFuns.compfuns,
bulwahn@36013
  1040
  mk_random = (fn _ => error "no random generation"),
bulwahn@36013
  1041
  modify_funT = I,
bulwahn@36013
  1042
  additional_arguments = K [],
bulwahn@36013
  1043
  wrap_compilation = K (K (K (K (K I))))
bulwahn@36013
  1044
   : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
bulwahn@36013
  1045
  transform_additional_arguments = K I : (indprem -> term list -> term list)
bulwahn@36013
  1046
  }
bulwahn@36013
  1047
bulwahn@36013
  1048
fun negative_comp_modifiers_of comp_modifiers =
bulwahn@36013
  1049
    (case Comp_Mod.compilation comp_modifiers of
bulwahn@36013
  1050
      Pos_Random_DSeq => neg_random_dseq_comp_modifiers
bulwahn@36013
  1051
    | Neg_Random_DSeq => pos_random_dseq_comp_modifiers
bulwahn@36013
  1052
    | New_Pos_Random_DSeq => new_neg_random_dseq_comp_modifiers
bulwahn@36013
  1053
    | New_Neg_Random_DSeq => new_pos_random_dseq_comp_modifiers
bulwahn@36013
  1054
    | c => comp_modifiers)
bulwahn@36013
  1055
bulwahn@34935
  1056
(** mode analysis **)
bulwahn@32672
  1057
bulwahn@39994
  1058
type mode_analysis_options =
bulwahn@39994
  1059
  {use_generators : bool,
bulwahn@39994
  1060
  reorder_premises : bool,
bulwahn@39994
  1061
  infer_pos_and_neg_modes : bool}
bulwahn@35324
  1062
bulwahn@32667
  1063
fun is_constrt thy =
bulwahn@32667
  1064
  let
bulwahn@32667
  1065
    val cnstrs = flat (maps
bulwahn@32667
  1066
      (map (fn (_, (Tname, _, cs)) => map (apsnd (rpair Tname o length)) cs) o #descr o snd)
bulwahn@32667
  1067
      (Symtab.dest (Datatype.get_all thy)));
bulwahn@32667
  1068
    fun check t = (case strip_comb t of
bulwahn@32667
  1069
        (Free _, []) => true
bulwahn@32667
  1070
      | (Const (s, T), ts) => (case (AList.lookup (op =) cnstrs s, body_type T) of
bulwahn@33482
  1071
            (SOME (i, Tname), Type (Tname', _)) =>
bulwahn@33482
  1072
              length ts = i andalso Tname = Tname' andalso forall check ts
bulwahn@32667
  1073
          | _ => false)
bulwahn@32667
  1074
      | _ => false)
bulwahn@32667
  1075
  in check end;
bulwahn@32667
  1076
bulwahn@32667
  1077
(*** check if a type is an equality type (i.e. doesn't contain fun)
bulwahn@32667
  1078
  FIXME this is only an approximation ***)
bulwahn@32667
  1079
fun is_eqT (Type (s, Ts)) = s <> "fun" andalso forall is_eqT Ts
bulwahn@32667
  1080
  | is_eqT _ = true;
bulwahn@32667
  1081
bulwahn@32667
  1082
fun term_vs tm = fold_aterms (fn Free (x, T) => cons x | _ => I) tm [];
bulwahn@32667
  1083
val terms_vs = distinct (op =) o maps term_vs;
bulwahn@32667
  1084
bulwahn@32667
  1085
(** collect all Frees in a term (with duplicates!) **)
bulwahn@32667
  1086
fun term_vTs tm =
bulwahn@32667
  1087
  fold_aterms (fn Free xT => cons xT | _ => I) tm [];
bulwahn@32667
  1088
bulwahn@33138
  1089
fun subsets i j =
bulwahn@33138
  1090
  if i <= j then
bulwahn@33138
  1091
    let
bulwahn@33138
  1092
      fun merge xs [] = xs
bulwahn@33138
  1093
        | merge [] ys = ys
bulwahn@33138
  1094
        | merge (x::xs) (y::ys) = if length x >= length y then x::merge xs (y::ys)
bulwahn@33138
  1095
            else y::merge (x::xs) ys;
bulwahn@33138
  1096
      val is = subsets (i+1) j
bulwahn@33138
  1097
    in merge (map (fn ks => i::ks) is) is end
bulwahn@33138
  1098
  else [[]];
bulwahn@32667
  1099
bulwahn@35324
  1100
fun print_failed_mode options thy modes p (pol, m) rs is =
bulwahn@33130
  1101
  if show_mode_inference options then
bulwahn@33130
  1102
    let
bulwahn@33752
  1103
      val _ = tracing ("Clauses " ^ commas (map (fn i => string_of_int (i + 1)) is) ^ " of " ^
bulwahn@34935
  1104
        p ^ " violates mode " ^ string_of_mode m)
bulwahn@33130
  1105
    in () end
bulwahn@33130
  1106
  else ()
bulwahn@33130
  1107
bulwahn@35324
  1108
fun error_of p (pol, m) is =
bulwahn@35885
  1109
  "  Clauses " ^ commas (map (fn i => string_of_int (i + 1)) is) ^ " of " ^
bulwahn@35885
  1110
        p ^ " violates mode " ^ string_of_mode m
bulwahn@33752
  1111
bulwahn@34935
  1112
fun is_all_input mode =
bulwahn@34935
  1113
  let
bulwahn@34935
  1114
    fun is_all_input' (Fun _) = true
bulwahn@34935
  1115
      | is_all_input' (Pair (m1, m2)) = is_all_input' m1 andalso is_all_input' m2
bulwahn@34935
  1116
      | is_all_input' Input = true
bulwahn@34935
  1117
      | is_all_input' Output = false
bulwahn@34935
  1118
  in
bulwahn@34935
  1119
    forall is_all_input' (strip_fun_mode mode)
bulwahn@34935
  1120
  end
bulwahn@33752
  1121
bulwahn@34935
  1122
fun all_input_of T =
bulwahn@33146
  1123
  let
bulwahn@34935
  1124
    val (Ts, U) = strip_type T
haftmann@37678
  1125
    fun input_of (Type (@{type_name Product_Type.prod}, [T1, T2])) = Pair (input_of T1, input_of T2)
bulwahn@34935
  1126
      | input_of _ = Input
bulwahn@34935
  1127
  in
bulwahn@34935
  1128
    if U = HOLogic.boolT then
bulwahn@34935
  1129
      fold_rev (curry Fun) (map input_of Ts) Bool
bulwahn@34935
  1130
    else
bulwahn@35885
  1131
      raise Fail "all_input_of: not a predicate"
bulwahn@34935
  1132
  end
bulwahn@34935
  1133
bulwahn@39421
  1134
fun find_least ord xs =
bulwahn@39421
  1135
  let
bulwahn@39421
  1136
    fun find' x y = (case y of NONE => SOME x | SOME y' => if ord (x, y') = LESS then SOME x else y) 
bulwahn@39421
  1137
  in
bulwahn@39421
  1138
    fold find' xs NONE
bulwahn@39421
  1139
  end
bulwahn@39421
  1140
  
bulwahn@34935
  1141
fun term_vs tm = fold_aterms (fn Free (x, T) => cons x | _ => I) tm [];
bulwahn@34935
  1142
val terms_vs = distinct (op =) o maps term_vs;
bulwahn@34935
  1143
bulwahn@34935
  1144
fun input_mode T =
bulwahn@34935
  1145
  let
bulwahn@34935
  1146
    val (Ts, U) = strip_type T
bulwahn@34935
  1147
  in
bulwahn@34935
  1148
    fold_rev (curry Fun) (map (K Input) Ts) Input
bulwahn@34935
  1149
  end
bulwahn@34935
  1150
bulwahn@34935
  1151
fun output_mode T =
bulwahn@34935
  1152
  let
bulwahn@34935
  1153
    val (Ts, U) = strip_type T
bulwahn@34935
  1154
  in
bulwahn@34935
  1155
    fold_rev (curry Fun) (map (K Output) Ts) Output
bulwahn@34935
  1156
  end
bulwahn@34935
  1157
bulwahn@35891
  1158
fun is_invertible_function ctxt (Const (f, _)) = is_constr ctxt f
bulwahn@35891
  1159
  | is_invertible_function ctxt _ = false
bulwahn@34935
  1160
bulwahn@35891
  1161
fun non_invertible_subterms ctxt (t as Free _) = []
bulwahn@35891
  1162
  | non_invertible_subterms ctxt t = 
bulwahn@35891
  1163
  let
bulwahn@35891
  1164
    val (f, args) = strip_comb t
bulwahn@35891
  1165
  in
bulwahn@35891
  1166
    if is_invertible_function ctxt f then
bulwahn@35891
  1167
      maps (non_invertible_subterms ctxt) args
bulwahn@34935
  1168
    else
bulwahn@34935
  1169
      [t]
bulwahn@35891
  1170
  end
bulwahn@34935
  1171
bulwahn@35891
  1172
fun collect_non_invertible_subterms ctxt (f as Free _) (names, eqs) = (f, (names, eqs))
bulwahn@35891
  1173
  | collect_non_invertible_subterms ctxt t (names, eqs) =
bulwahn@34935
  1174
    case (strip_comb t) of (f, args) =>
bulwahn@35891
  1175
      if is_invertible_function ctxt f then
bulwahn@34935
  1176
          let
bulwahn@34935
  1177
            val (args', (names', eqs')) =
bulwahn@35891
  1178
              fold_map (collect_non_invertible_subterms ctxt) args (names, eqs)
bulwahn@34935
  1179
          in
bulwahn@34935
  1180
            (list_comb (f, args'), (names', eqs'))
bulwahn@34935
  1181
          end
bulwahn@34935
  1182
        else
bulwahn@34935
  1183
          let
bulwahn@34935
  1184
            val s = Name.variant names "x"
bulwahn@34935
  1185
            val v = Free (s, fastype_of t)
bulwahn@34935
  1186
          in
bulwahn@34935
  1187
            (v, (s :: names, HOLogic.mk_eq (v, t) :: eqs))
bulwahn@34935
  1188
          end
bulwahn@34935
  1189
(*
bulwahn@34935
  1190
  if is_constrt thy t then (t, (names, eqs)) else
bulwahn@34935
  1191
    let
bulwahn@34935
  1192
      val s = Name.variant names "x"
bulwahn@34935
  1193
      val v = Free (s, fastype_of t)
bulwahn@34935
  1194
    in (v, (s::names, HOLogic.mk_eq (v, t)::eqs)) end;
bulwahn@34935
  1195
*)
bulwahn@34935
  1196
bulwahn@36994
  1197
fun is_possible_output ctxt vs t =
bulwahn@34935
  1198
  forall
bulwahn@34935
  1199
    (fn t => is_eqT (fastype_of t) andalso forall (member (op =) vs) (term_vs t))
bulwahn@36994
  1200
      (non_invertible_subterms ctxt t)
bulwahn@35324
  1201
  andalso
bulwahn@35324
  1202
    (forall (is_eqT o snd)
bulwahn@35324
  1203
      (inter (fn ((f', _), f) => f = f') vs (Term.add_frees t [])))
bulwahn@34935
  1204
bulwahn@35891
  1205
fun vars_of_destructable_term ctxt (Free (x, _)) = [x]
bulwahn@35891
  1206
  | vars_of_destructable_term ctxt t =
bulwahn@35891
  1207
  let
bulwahn@35891
  1208
    val (f, args) = strip_comb t
bulwahn@35891
  1209
  in
bulwahn@35891
  1210
    if is_invertible_function ctxt f then
bulwahn@35891
  1211
      maps (vars_of_destructable_term ctxt) args
bulwahn@34935
  1212
    else
bulwahn@34935
  1213
      []
bulwahn@35891
  1214
  end
bulwahn@34935
  1215
bulwahn@36994
  1216
fun is_constructable vs t = forall (member (op =) vs) (term_vs t)
bulwahn@34935
  1217
bulwahn@34935
  1218
fun missing_vars vs t = subtract (op =) vs (term_vs t)
bulwahn@34935
  1219
haftmann@37366
  1220
fun output_terms (Const (@{const_name Pair}, _) $ t1 $ t2, Mode_Pair (d1, d2)) =
bulwahn@35324
  1221
    output_terms (t1, d1)  @ output_terms (t2, d2)
bulwahn@35324
  1222
  | output_terms (t1 $ t2, Mode_App (d1, d2)) =
bulwahn@35324
  1223
    output_terms (t1, d1)  @ output_terms (t2, d2)
bulwahn@35324
  1224
  | output_terms (t, Term Output) = [t]
bulwahn@35324
  1225
  | output_terms _ = []
bulwahn@35324
  1226
bulwahn@35324
  1227
fun lookup_mode modes (Const (s, T)) =
bulwahn@35324
  1228
   (case (AList.lookup (op =) modes s) of
bulwahn@35324
  1229
      SOME ms => SOME (map (fn m => (Context m, [])) ms)
bulwahn@35324
  1230
    | NONE => NONE)
bulwahn@35324
  1231
  | lookup_mode modes (Free (x, _)) =
bulwahn@35324
  1232
    (case (AList.lookup (op =) modes x) of
bulwahn@35324
  1233
      SOME ms => SOME (map (fn m => (Context m , [])) ms)
bulwahn@35324
  1234
    | NONE => NONE)
bulwahn@35324
  1235
haftmann@37366
  1236
fun derivations_of (ctxt : Proof.context) modes vs (Const (@{const_name Pair}, _) $ t1 $ t2) (Pair (m1, m2)) =
bulwahn@34935
  1237
    map_product
bulwahn@34935
  1238
      (fn (m1, mvars1) => fn (m2, mvars2) => (Mode_Pair (m1, m2), union (op =) mvars1 mvars2))
bulwahn@36994
  1239
        (derivations_of ctxt modes vs t1 m1) (derivations_of ctxt modes vs t2 m2)
bulwahn@36994
  1240
  | derivations_of ctxt modes vs t (m as Fun _) =
bulwahn@35324
  1241
    (*let
bulwahn@35324
  1242
      val (p, args) = strip_comb t
bulwahn@35324
  1243
    in
bulwahn@35324
  1244
      (case lookup_mode modes p of
bulwahn@35324
  1245
        SOME ms => map_filter (fn (Context m, []) => let
bulwahn@35324
  1246
          val ms = strip_fun_mode m
bulwahn@35324
  1247
          val (argms, restms) = chop (length args) ms
bulwahn@35324
  1248
          val m' = fold_rev (curry Fun) restms Bool
bulwahn@35324
  1249
        in
bulwahn@35324
  1250
          if forall (fn m => eq_mode (Input, m)) argms andalso eq_mode (m', mode) then
bulwahn@35324
  1251
            SOME (fold (curry Mode_App) (map Term argms) (Context m), missing_vars vs t)
bulwahn@35324
  1252
          else NONE
bulwahn@35324
  1253
        end) ms
bulwahn@35324
  1254
      | NONE => (if is_all_input mode then [(Context mode, [])] else []))
bulwahn@35324
  1255
    end*)
bulwahn@36994
  1256
    (case try (all_derivations_of ctxt modes vs) t  of
bulwahn@35324
  1257
      SOME derivs =>
bulwahn@35324
  1258
        filter (fn (d, mvars) => eq_mode (mode_of d, m) andalso null (output_terms (t, d))) derivs
bulwahn@35324
  1259
    | NONE => (if is_all_input m then [(Context m, [])] else []))
bulwahn@36994
  1260
  | derivations_of ctxt modes vs t m =
bulwahn@35324
  1261
    if eq_mode (m, Input) then
bulwahn@35324
  1262
      [(Term Input, missing_vars vs t)]
bulwahn@35324
  1263
    else if eq_mode (m, Output) then
bulwahn@36994
  1264
      (if is_possible_output ctxt vs t then [(Term Output, [])] else [])
bulwahn@35324
  1265
    else []
haftmann@37366
  1266
and all_derivations_of ctxt modes vs (Const (@{const_name Pair}, _) $ t1 $ t2) =
bulwahn@34935
  1267
  let
bulwahn@36994
  1268
    val derivs1 = all_derivations_of ctxt modes vs t1
bulwahn@36994
  1269
    val derivs2 = all_derivations_of ctxt modes vs t2
bulwahn@34935
  1270
  in
bulwahn@34935
  1271
    map_product
bulwahn@34935
  1272
      (fn (m1, mvars1) => fn (m2, mvars2) => (Mode_Pair (m1, m2), union (op =) mvars1 mvars2))
bulwahn@34935
  1273
        derivs1 derivs2
bulwahn@34935
  1274
  end
bulwahn@36994
  1275
  | all_derivations_of ctxt modes vs (t1 $ t2) =
bulwahn@34935
  1276
  let
bulwahn@36994
  1277
    val derivs1 = all_derivations_of ctxt modes vs t1
bulwahn@34935
  1278
  in
bulwahn@34935
  1279
    maps (fn (d1, mvars1) =>
bulwahn@34935
  1280
      case mode_of d1 of
bulwahn@34935
  1281
        Fun (m', _) => map (fn (d2, mvars2) =>
bulwahn@36994
  1282
          (Mode_App (d1, d2), union (op =) mvars1 mvars2)) (derivations_of ctxt modes vs t2 m')
bulwahn@39423
  1283
        | _ => raise Fail "all_derivations_of: derivation has an unexpected non-functional mode") derivs1
bulwahn@34935
  1284
  end
bulwahn@36994
  1285
  | all_derivations_of _ modes vs (Const (s, T)) = the (lookup_mode modes (Const (s, T)))
bulwahn@36994
  1286
  | all_derivations_of _ modes vs (Free (x, T)) = the (lookup_mode modes (Free (x, T)))
bulwahn@39423
  1287
  | all_derivations_of _ modes vs _ = raise Fail "all_derivations_of: unexpected term"
bulwahn@34935
  1288
bulwahn@34935
  1289
fun rev_option_ord ord (NONE, NONE) = EQUAL
bulwahn@34935
  1290
  | rev_option_ord ord (NONE, SOME _) = GREATER
bulwahn@34935
  1291
  | rev_option_ord ord (SOME _, NONE) = LESS
bulwahn@34935
  1292
  | rev_option_ord ord (SOME x, SOME y) = ord (x, y)
bulwahn@34935
  1293
bulwahn@34935
  1294
fun random_mode_in_deriv modes t deriv =
bulwahn@34935
  1295
  case try dest_Const (fst (strip_comb t)) of
bulwahn@34935
  1296
    SOME (s, _) =>
bulwahn@34935
  1297
      (case AList.lookup (op =) modes s of
bulwahn@34935
  1298
        SOME ms =>
bulwahn@35324
  1299
          (case AList.lookup (op =) (map (fn ((p, m), r) => (m, r)) ms) (head_mode_of deriv) of
bulwahn@34935
  1300
            SOME r => r
bulwahn@34935
  1301
          | NONE => false)
bulwahn@34935
  1302
      | NONE => false)
bulwahn@34935
  1303
  | NONE => false
bulwahn@34935
  1304
bulwahn@34935
  1305
fun number_of_output_positions mode =
bulwahn@34935
  1306
  let
bulwahn@34935
  1307
    val args = strip_fun_mode mode
bulwahn@34935
  1308
    fun contains_output (Fun _) = false
bulwahn@34935
  1309
      | contains_output Input = false
bulwahn@34935
  1310
      | contains_output Output = true
bulwahn@34935
  1311
      | contains_output (Pair (m1, m2)) = contains_output m1 orelse contains_output m2
bulwahn@34935
  1312
  in
bulwahn@34935
  1313
    length (filter contains_output args)
bulwahn@34935
  1314
  end
bulwahn@34935
  1315
bulwahn@34935
  1316
fun lex_ord ord1 ord2 (x, x') =
bulwahn@34935
  1317
  case ord1 (x, x') of
bulwahn@34935
  1318
    EQUAL => ord2 (x, x')
bulwahn@34935
  1319
  | ord => ord
bulwahn@34935
  1320
bulwahn@36247
  1321
fun lexl_ord [] (x, x') = EQUAL
bulwahn@36247
  1322
  | lexl_ord (ord :: ords') (x, x') =
bulwahn@36247
  1323
    case ord (x, x') of
bulwahn@36247
  1324
      EQUAL => lexl_ord ords' (x, x')
bulwahn@36247
  1325
    | ord => ord
bulwahn@36247
  1326
bulwahn@36994
  1327
fun deriv_ord' ctxt pol pred modes t1 t2 ((deriv1, mvars1), (deriv2, mvars2)) =
bulwahn@34935
  1328
  let
bulwahn@36247
  1329
    (* prefer functional modes if it is a function *)
bulwahn@36247
  1330
    fun fun_ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2)) =
bulwahn@36247
  1331
      let
bulwahn@36247
  1332
        fun is_functional t mode =
bulwahn@36247
  1333
          case try (fst o dest_Const o fst o strip_comb) t of
bulwahn@36247
  1334
            NONE => false
bulwahn@36994
  1335
          | SOME c => is_some (alternative_compilation_of ctxt c mode)
bulwahn@36247
  1336
      in
bulwahn@36247
  1337
        case (is_functional t1 (head_mode_of deriv1), is_functional t2 (head_mode_of deriv2)) of
bulwahn@36247
  1338
          (true, true) => EQUAL
bulwahn@36247
  1339
        | (true, false) => LESS
bulwahn@36247
  1340
        | (false, true) => GREATER
bulwahn@36247
  1341
        | (false, false) => EQUAL
bulwahn@36247
  1342
      end
bulwahn@36022
  1343
    (* prefer modes without requirement for generating random values *)
bulwahn@34935
  1344
    fun mvars_ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2)) =
bulwahn@34935
  1345
      int_ord (length mvars1, length mvars2)
bulwahn@36022
  1346
    (* prefer non-random modes *)
bulwahn@34935
  1347
    fun random_mode_ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2)) =
bulwahn@34935
  1348
      int_ord (if random_mode_in_deriv modes t1 deriv1 then 1 else 0,
bulwahn@39993
  1349
               if random_mode_in_deriv modes t2 deriv2 then 1 else 0)
bulwahn@36022
  1350
    (* prefer modes with more input and less output *)
bulwahn@34935
  1351
    fun output_mode_ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2)) =
bulwahn@34935
  1352
      int_ord (number_of_output_positions (head_mode_of deriv1),
bulwahn@34935
  1353
        number_of_output_positions (head_mode_of deriv2))
bulwahn@36022
  1354
    (* prefer recursive calls *)
bulwahn@36022
  1355
    fun is_rec_premise t =
bulwahn@36022
  1356
      case fst (strip_comb t) of Const (c, T) => c = pred | _ => false
bulwahn@36022
  1357
    fun recursive_ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2)) =
bulwahn@36022
  1358
      int_ord (if is_rec_premise t1 then 0 else 1,
bulwahn@36022
  1359
        if is_rec_premise t2 then 0 else 1)
bulwahn@36247
  1360
    val ord = lexl_ord [mvars_ord, fun_ord, random_mode_ord, output_mode_ord, recursive_ord]
bulwahn@34935
  1361
  in
bulwahn@36022
  1362
    ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2))
bulwahn@34935
  1363
  end
bulwahn@34935
  1364
bulwahn@36994
  1365
fun deriv_ord ctxt pol pred modes t = deriv_ord' ctxt pol pred modes t t
bulwahn@34935
  1366
bulwahn@36247
  1367
fun premise_ord thy pol pred modes ((prem1, a1), (prem2, a2)) =
bulwahn@36258
  1368
  rev_option_ord (deriv_ord' thy pol pred modes (dest_indprem prem1) (dest_indprem prem2)) (a1, a2)
bulwahn@34935
  1369
bulwahn@34935
  1370
fun print_mode_list modes =
bulwahn@34935
  1371
  tracing ("modes: " ^ (commas (map (fn (s, ms) => s ^ ": " ^
bulwahn@34935
  1372
    commas (map (fn (m, r) => string_of_mode m ^ (if r then " random " else " not ")) ms)) modes)))
bulwahn@34935
  1373
bulwahn@36994
  1374
fun select_mode_prem (mode_analysis_options : mode_analysis_options) (ctxt : Proof.context) pred
bulwahn@36022
  1375
  pol (modes, (pos_modes, neg_modes)) vs ps =
bulwahn@34935
  1376
  let
bulwahn@39421
  1377
    fun choose_mode_of_prem (Prem t) =
bulwahn@39421
  1378
          find_least (deriv_ord ctxt pol pred modes t) (all_derivations_of ctxt pos_modes vs t)
bulwahn@35324
  1379
      | choose_mode_of_prem (Sidecond t) = SOME (Context Bool, missing_vars vs t)
bulwahn@39421
  1380
      | choose_mode_of_prem (Negprem t) = find_least (deriv_ord ctxt (not pol) pred modes t)
bulwahn@36247
  1381
          (filter (fn (d, missing_vars) => is_all_input (head_mode_of d))
bulwahn@39421
  1382
             (all_derivations_of ctxt neg_modes vs t))
bulwahn@39423
  1383
      | choose_mode_of_prem p = raise Fail ("choose_mode_of_prem: unexpected premise " ^ string_of_prem ctxt p)
bulwahn@34935
  1384
  in
bulwahn@35324
  1385
    if #reorder_premises mode_analysis_options then
bulwahn@39421
  1386
      find_least (premise_ord ctxt pol pred modes) (ps ~~ map choose_mode_of_prem ps)
bulwahn@35324
  1387
    else
bulwahn@35324
  1388
      SOME (hd ps, choose_mode_of_prem (hd ps))
bulwahn@34935
  1389
  end
bulwahn@34935
  1390
bulwahn@36994
  1391
fun check_mode_clause' (mode_analysis_options : mode_analysis_options) ctxt pred param_vs (modes :
bulwahn@35324
  1392
  (string * ((bool * mode) * bool) list) list) ((pol, mode) : bool * mode) (ts, ps) =
bulwahn@34935
  1393
  let
bulwahn@36258
  1394
    val vTs = distinct (op =) (fold Term.add_frees (map dest_indprem ps) (fold Term.add_frees ts []))
bulwahn@35324
  1395
    val modes' = modes @ (param_vs ~~ map (fn x => [((true, x), false), ((false, x), false)]) (ho_arg_modes_of mode))
bulwahn@35324
  1396
    fun retrieve_modes_of_pol pol = map (fn (s, ms) =>
bulwahn@35324
  1397
      (s, map_filter (fn ((p, m), r) => if p = pol then SOME m else NONE | _ => NONE) ms))
bulwahn@35324
  1398
    val (pos_modes', neg_modes') =
bulwahn@35324
  1399
      if #infer_pos_and_neg_modes mode_analysis_options then
bulwahn@35324
  1400
        (retrieve_modes_of_pol pol modes', retrieve_modes_of_pol (not pol) modes')
bulwahn@35324
  1401
      else
bulwahn@35324
  1402
        let
bulwahn@35324
  1403
          val modes = map (fn (s, ms) => (s, map (fn ((p, m), r) => m) ms)) modes'
bulwahn@35324
  1404
        in (modes, modes) end
bulwahn@35324
  1405
    val (in_ts, out_ts) = split_mode mode ts
bulwahn@39872
  1406
    val in_vs = union (op =) param_vs (maps (vars_of_destructable_term ctxt) in_ts)
bulwahn@34935
  1407
    val out_vs = terms_vs out_ts
bulwahn@35324
  1408
    fun known_vs_after p vs = (case p of
bulwahn@35324
  1409
        Prem t => union (op =) vs (term_vs t)
bulwahn@35324
  1410
      | Sidecond t => union (op =) vs (term_vs t)
bulwahn@35324
  1411
      | Negprem t => union (op =) vs (term_vs t)
bulwahn@39423
  1412
      | _ => raise Fail "unexpected premise")
bulwahn@34935
  1413
    fun check_mode_prems acc_ps rnd vs [] = SOME (acc_ps, vs, rnd)
bulwahn@34935
  1414
      | check_mode_prems acc_ps rnd vs ps =
bulwahn@35324
  1415
        (case
bulwahn@36994
  1416
          (select_mode_prem mode_analysis_options ctxt pred pol (modes', (pos_modes', neg_modes')) vs ps) of
bulwahn@35324
  1417
          SOME (p, SOME (deriv, [])) => check_mode_prems ((p, deriv) :: acc_ps) rnd
bulwahn@35324
  1418
            (known_vs_after p vs) (filter_out (equal p) ps)
bulwahn@34935
  1419
        | SOME (p, SOME (deriv, missing_vars)) =>
bulwahn@39994
  1420
          if #use_generators mode_analysis_options andalso pol then
bulwahn@34935
  1421
            check_mode_prems ((p, deriv) :: (map
bulwahn@35324
  1422
              (fn v => (Generator (v, the (AList.lookup (op =) vTs v)), Term Output))
bulwahn@35324
  1423
                (distinct (op =) missing_vars))
bulwahn@35324
  1424
                @ acc_ps) true (known_vs_after p vs) (filter_out (equal p) ps)
bulwahn@34935
  1425
          else NONE
bulwahn@34935
  1426
        | SOME (p, NONE) => NONE
bulwahn@34935
  1427
        | NONE => NONE)
bulwahn@34935
  1428
  in
bulwahn@34935
  1429
    case check_mode_prems [] false in_vs ps of
bulwahn@34935
  1430
      NONE => NONE
bulwahn@34935
  1431
    | SOME (acc_ps, vs, rnd) =>
bulwahn@36994
  1432
      if forall (is_constructable vs) (in_ts @ out_ts) then
bulwahn@34935
  1433
        SOME (ts, rev acc_ps, rnd)
bulwahn@34935
  1434
      else
bulwahn@39994
  1435
        if #use_generators mode_analysis_options andalso pol then
bulwahn@34935
  1436
          let
bulwahn@35324
  1437
             val generators = map
bulwahn@34935
  1438
              (fn v => (Generator (v, the (AList.lookup (op =) vTs v)), Term Output))
bulwahn@35324
  1439
                (subtract (op =) vs (terms_vs (in_ts @ out_ts)))
bulwahn@34935
  1440
          in
bulwahn@34935
  1441
            SOME (ts, rev (generators @ acc_ps), true)
bulwahn@34935
  1442
          end
bulwahn@34935
  1443
        else
bulwahn@34935
  1444
          NONE
bulwahn@34935
  1445
  end
bulwahn@34935
  1446
bulwahn@34935
  1447
datatype result = Success of bool | Error of string
bulwahn@34935
  1448
bulwahn@35324
  1449
fun check_modes_pred' mode_analysis_options options thy param_vs clauses modes (p, (ms : ((bool * mode) * bool) list)) =
bulwahn@34935
  1450
  let
bulwahn@34935
  1451
    fun split xs =
bulwahn@34935
  1452
      let
bulwahn@34935
  1453
        fun split' [] (ys, zs) = (rev ys, rev zs)
bulwahn@34935
  1454
          | split' ((m, Error z) :: xs) (ys, zs) = split' xs (ys, z :: zs)
bulwahn@35324
  1455
          | split' (((m : bool * mode), Success rnd) :: xs) (ys, zs) = split' xs ((m, rnd) :: ys, zs)
bulwahn@34935
  1456
       in
bulwahn@34935
  1457
         split' xs ([], [])
bulwahn@34935
  1458
       end
bulwahn@34935
  1459
    val rs = these (AList.lookup (op =) clauses p)
bulwahn@34935
  1460
    fun check_mode m =
bulwahn@34935
  1461
      let
bulwahn@35324
  1462
        val res = Output.cond_timeit false "work part of check_mode for one mode" (fn _ => 
bulwahn@36022
  1463
          map (check_mode_clause' mode_analysis_options thy p param_vs modes m) rs)
bulwahn@34935
  1464
      in
bulwahn@35324
  1465
        Output.cond_timeit false "aux part of check_mode for one mode" (fn _ => 
bulwahn@34935
  1466
        case find_indices is_none res of
bulwahn@34935
  1467
          [] => Success (exists (fn SOME (_, _, true) => true | _ => false) res)
bulwahn@35324
  1468
        | is => (print_failed_mode options thy modes p m rs is; Error (error_of p m is)))
bulwahn@34935
  1469
      end
bulwahn@35324
  1470
    val _ = if show_mode_inference options then
bulwahn@35324
  1471
        tracing ("checking " ^ string_of_int (length ms) ^ " modes ...")
bulwahn@35324
  1472
      else ()
bulwahn@35324
  1473
    val res = Output.cond_timeit false "check_mode" (fn _ => map (fn (m, _) => (m, check_mode m)) ms)
bulwahn@34935
  1474
    val (ms', errors) = split res
bulwahn@33752
  1475
  in
bulwahn@35324
  1476
    ((p, (ms' : ((bool * mode) * bool) list)), errors)
bulwahn@32667
  1477
  end;
bulwahn@32667
  1478
bulwahn@35324
  1479
fun get_modes_pred' mode_analysis_options thy param_vs clauses modes (p, ms) =
bulwahn@32667
  1480
  let
bulwahn@34935
  1481
    val rs = these (AList.lookup (op =) clauses p)
bulwahn@32667
  1482
  in
bulwahn@34935
  1483
    (p, map (fn (m, rnd) =>
bulwahn@35324
  1484
      (m, map
bulwahn@35324
  1485
        ((fn (ts, ps, rnd) => (ts, ps)) o the o
bulwahn@36022
  1486
          check_mode_clause' mode_analysis_options thy p param_vs modes m) rs)) ms)
bulwahn@32667
  1487
  end;
bulwahn@33137
  1488
bulwahn@35324
  1489
fun fixp f (x : (string * ((bool * mode) * bool) list) list) =
bulwahn@32667
  1490
  let val y = f x
bulwahn@32667
  1491
  in if x = y then x else fixp f y end;
bulwahn@32667
  1492
bulwahn@35324
  1493
fun fixp_with_state f (x : (string * ((bool * mode) * bool) list) list, state) =
bulwahn@33752
  1494
  let
bulwahn@33752
  1495
    val (y, state') = f (x, state)
bulwahn@33752
  1496
  in
bulwahn@33752
  1497
    if x = y then (y, state') else fixp_with_state f (y, state')
bulwahn@33752
  1498
  end
bulwahn@33752
  1499
bulwahn@35324
  1500
fun string_of_ext_mode ((pol, mode), rnd) =
bulwahn@35324
  1501
  string_of_mode mode ^ "(" ^ (if pol then "pos" else "neg") ^ ", "
bulwahn@35324
  1502
  ^ (if rnd then "rnd" else "nornd") ^ ")"
bulwahn@35324
  1503
bulwahn@35324
  1504
fun print_extra_modes options modes =
bulwahn@35324
  1505
  if show_mode_inference options then
bulwahn@35324
  1506
    tracing ("Modes of inferred predicates: " ^
bulwahn@35324
  1507
      cat_lines (map (fn (s, ms) => s ^ ": " ^ commas (map string_of_ext_mode ms)) modes))
bulwahn@35324
  1508
  else ()
bulwahn@35324
  1509
bulwahn@39500
  1510
fun infer_modes mode_analysis_options options (lookup_mode, lookup_neg_mode, needs_random) ctxt
bulwahn@39500
  1511
  preds all_modes param_vs clauses =
bulwahn@32667
  1512
  let
bulwahn@35324
  1513
    fun appair f (x1, x2) (y1, y2) = (f x1 y1, f x2 y2)
bulwahn@36994
  1514
    fun add_needs_random s (false, m) = ((false, m), false)
bulwahn@39500
  1515
      | add_needs_random s (true, m) = ((true, m), needs_random s m)
bulwahn@36994
  1516
    fun add_polarity_and_random_bit s b ms = map (fn m => add_needs_random s (b, m)) ms
bulwahn@35324
  1517
    val prednames = map fst preds
bulwahn@35324
  1518
    (* extramodes contains all modes of all constants, should we only use the necessary ones
bulwahn@35324
  1519
       - what is the impact on performance? *)
bulwahn@36251
  1520
    fun predname_of (Prem t) =
bulwahn@36251
  1521
        (case try dest_Const (fst (strip_comb t)) of SOME (c, _) => insert (op =) c | NONE => I)
bulwahn@36251
  1522
      | predname_of (Negprem t) =
bulwahn@36251
  1523
        (case try dest_Const (fst (strip_comb t)) of SOME (c, _) => insert (op =) c | NONE => I)
bulwahn@36251
  1524
      | predname_of _ = I
bulwahn@36251
  1525
    val relevant_prednames = fold (fn (_, clauses') =>
bulwahn@36251
  1526
      fold (fn (_, ps) => fold Term.add_const_names (map dest_indprem ps)) clauses') clauses []
bulwahn@39500
  1527
      |> filter_out (fn name => member (op =) prednames name)
bulwahn@35324
  1528
    val extra_modes =
bulwahn@35324
  1529
      if #infer_pos_and_neg_modes mode_analysis_options then
bulwahn@33752
  1530
        let
bulwahn@35324
  1531
          val pos_extra_modes =
bulwahn@39500
  1532
            map_filter (fn name => Option.map (pair name) (try lookup_mode name))
bulwahn@36251
  1533
            relevant_prednames
bulwahn@35324
  1534
          val neg_extra_modes =
bulwahn@39500
  1535
            map_filter (fn name => Option.map (pair name) (try lookup_neg_mode name))
bulwahn@39500
  1536
              relevant_prednames
bulwahn@35324
  1537
        in
bulwahn@35324
  1538
          map (fn (s, ms) => (s, (add_polarity_and_random_bit s true ms)
bulwahn@35324
  1539
                @ add_polarity_and_random_bit s false (the (AList.lookup (op =) neg_extra_modes s))))
bulwahn@35324
  1540
            pos_extra_modes
bulwahn@35324
  1541
        end
bulwahn@35324
  1542
      else
bulwahn@35324
  1543
        map (fn (s, ms) => (s, (add_polarity_and_random_bit s true ms)))
bulwahn@39500
  1544
          (map_filter (fn name => Option.map (pair name) (try lookup_mode name))
bulwahn@39500
  1545
            relevant_prednames)
bulwahn@35324
  1546
    val _ = print_extra_modes options extra_modes
bulwahn@35324
  1547
    val start_modes =
bulwahn@35324
  1548
      if #infer_pos_and_neg_modes mode_analysis_options then
bulwahn@35324
  1549
        map (fn (s, ms) => (s, map (fn m => ((true, m), false)) ms @
bulwahn@35324
  1550
          (map (fn m => ((false, m), false)) ms))) all_modes
bulwahn@35324
  1551
      else
bulwahn@35324
  1552
        map (fn (s, ms) => (s, map (fn m => ((true, m), false)) ms)) all_modes
bulwahn@35324
  1553
    fun iteration modes = map
bulwahn@36994
  1554
      (check_modes_pred' mode_analysis_options options ctxt param_vs clauses
bulwahn@36022
  1555
        (modes @ extra_modes)) modes
bulwahn@35324
  1556
    val ((modes : (string * ((bool * mode) * bool) list) list), errors) =
bulwahn@35324
  1557
      Output.cond_timeit false "Fixpount computation of mode analysis" (fn () =>
bulwahn@39629
  1558
      if show_invalid_clauses options then
bulwahn@35324
  1559
        fixp_with_state (fn (modes, errors) =>
bulwahn@35324
  1560
          let
bulwahn@35324
  1561
            val (modes', new_errors) = split_list (iteration modes)
bulwahn@35324
  1562
          in (modes', errors @ flat new_errors) end) (start_modes, [])
bulwahn@35324
  1563
        else
bulwahn@35324
  1564
          (fixp (fn modes => map fst (iteration modes)) start_modes, []))
bulwahn@36994
  1565
    val moded_clauses = map (get_modes_pred' mode_analysis_options ctxt param_vs clauses
bulwahn@35324
  1566
      (modes @ extra_modes)) modes
bulwahn@39500
  1567
    val need_random = fold (fn (s, ms) => if member (op =) (map fst preds) s then
bulwahn@39500
  1568
      cons (s, (map_filter (fn ((true, m), true) => SOME m | _ => NONE) ms)) else I)
bulwahn@39500
  1569
      modes []
bulwahn@32667
  1570
  in
bulwahn@39500
  1571
    ((moded_clauses, need_random), errors)
bulwahn@32667
  1572
  end;
bulwahn@32667
  1573
bulwahn@32667
  1574
(* term construction *)
bulwahn@32667
  1575
bulwahn@32667
  1576
fun mk_v (names, vs) s T = (case AList.lookup (op =) vs s of
bulwahn@32667
  1577
      NONE => (Free (s, T), (names, (s, [])::vs))
bulwahn@32667
  1578
    | SOME xs =>
bulwahn@32667
  1579
        let
bulwahn@32667
  1580
          val s' = Name.variant names s;
bulwahn@32667
  1581
          val v = Free (s', T)
bulwahn@32667
  1582
        in
bulwahn@32667
  1583
          (v, (s'::names, AList.update (op =) (s, v::xs) vs))
bulwahn@32667
  1584
        end);
bulwahn@32667
  1585
bulwahn@32667
  1586
fun distinct_v (Free (s, T)) nvs = mk_v nvs s T
bulwahn@32667
  1587
  | distinct_v (t $ u) nvs =
bulwahn@32667
  1588
      let
bulwahn@32667
  1589
        val (t', nvs') = distinct_v t nvs;
bulwahn@32667
  1590
        val (u', nvs'') = distinct_v u nvs';
bulwahn@32667
  1591
      in (t' $ u', nvs'') end
bulwahn@32667
  1592
  | distinct_v x nvs = (x, nvs);
bulwahn@32667
  1593
bulwahn@39872
  1594
bulwahn@33147
  1595
(** specific rpred functions -- move them to the correct place in this file *)
bulwahn@39872
  1596
fun mk_Eval_of (P as (Free (f, _)), T) mode =
bulwahn@39872
  1597
let
bulwahn@39872
  1598
  fun mk_bounds (Type (@{type_name Product_Type.prod}, [T1, T2])) i =
bulwahn@39872
  1599
    let
bulwahn@39872
  1600
      val (bs2, i') = mk_bounds T2 i 
bulwahn@39872
  1601
      val (bs1, i'') = mk_bounds T1 i'
bulwahn@39872
  1602
    in
bulwahn@39872
  1603
      (HOLogic.pair_const T1 T2 $ bs1 $ bs2, i'' + 1)
bulwahn@39872
  1604
    end
bulwahn@39872
  1605
    | mk_bounds T i = (Bound i, i + 1)
bulwahn@39872
  1606
  fun mk_prod ((t1, T1), (t2, T2)) = (HOLogic.pair_const T1 T2 $ t1 $ t2, HOLogic.mk_prodT (T1, T2))
bulwahn@39872
  1607
  fun mk_tuple [] = (HOLogic.unit, HOLogic.unitT)
bulwahn@39872
  1608
    | mk_tuple tTs = foldr1 mk_prod tTs;
bulwahn@39872
  1609
  fun mk_split_abs (T as Type (@{type_name Product_Type.prod}, [T1, T2])) t = absdummy (T, HOLogic.split_const (T1, T2, @{typ bool}) $ (mk_split_abs T1 (mk_split_abs T2 t)))
bulwahn@39872
  1610
    | mk_split_abs T t = absdummy (T, t)
bulwahn@39872
  1611
  val args = rev (fst (fold_map mk_bounds (rev (binder_types T)) 0))
bulwahn@39872
  1612
  val (inargs, outargs) = split_mode mode args
bulwahn@39872
  1613
  val (inTs, outTs) = split_map_modeT (fn _ => fn T => (SOME T, NONE)) mode (binder_types T)
bulwahn@39872
  1614
  val inner_term = PredicateCompFuns.mk_Eval (list_comb (P, inargs), fst (mk_tuple (outargs ~~ outTs)))
bulwahn@39872
  1615
in
bulwahn@39872
  1616
  fold_rev mk_split_abs (binder_types T) inner_term  
bulwahn@39872
  1617
end
bulwahn@33147
  1618
bulwahn@39872
  1619
fun compile_arg compilation_modifiers additional_arguments ctxt param_modes arg = 
bulwahn@33147
  1620
  let
bulwahn@33147
  1621
    fun map_params (t as Free (f, T)) =
bulwahn@39872
  1622
      (case (AList.lookup (op =) param_modes f) of
bulwahn@39872
  1623
          SOME mode =>
bulwahn@33147
  1624
            let
bulwahn@39872
  1625
              val T' = Comp_Mod.funT_of compilation_modifiers mode T
bulwahn@39872
  1626
            in
bulwahn@39872
  1627
              mk_Eval_of (Free (f, T'), T) mode
bulwahn@39872
  1628
            end
bulwahn@39872
  1629
        | NONE => t)
bulwahn@33147
  1630
      | map_params t = t
bulwahn@39872
  1631
  in
bulwahn@39872
  1632
    map_aterms map_params arg
bulwahn@39872
  1633
  end
bulwahn@33147
  1634
bulwahn@39872
  1635
fun compile_match compilation_modifiers additional_arguments ctxt param_modes
bulwahn@39872
  1636
      eqs eqs' out_ts success_t =
bulwahn@32667
  1637
  let
bulwahn@36013
  1638
    val compfuns = Comp_Mod.compfuns compilation_modifiers
bulwahn@32667
  1639
    val eqs'' = maps mk_eq eqs @ eqs'
bulwahn@33147
  1640
    val eqs'' =
bulwahn@39872
  1641
      map (compile_arg compilation_modifiers additional_arguments ctxt param_modes) eqs''
bulwahn@32667
  1642
    val names = fold Term.add_free_names (success_t :: eqs'' @ out_ts) [];
bulwahn@32667
  1643
    val name = Name.variant names "x";
bulwahn@32667
  1644
    val name' = Name.variant (name :: names) "y";
bulwahn@33148
  1645
    val T = HOLogic.mk_tupleT (map fastype_of out_ts);
bulwahn@32667
  1646
    val U = fastype_of success_t;
bulwahn@36254
  1647
    val U' = dest_predT compfuns U;
bulwahn@32667
  1648
    val v = Free (name, T);
bulwahn@32667
  1649
    val v' = Free (name', T);
bulwahn@32667
  1650
  in
bulwahn@35891
  1651
    lambda v (fst (Datatype.make_case ctxt Datatype_Case.Quiet [] v
bulwahn@33148
  1652
      [(HOLogic.mk_tuple out_ts,
bulwahn@32667
  1653
        if null eqs'' then success_t
bulwahn@32667
  1654
        else Const (@{const_name HOL.If}, HOLogic.boolT --> U --> U --> U) $
bulwahn@32667
  1655
          foldr1 HOLogic.mk_conj eqs'' $ success_t $
bulwahn@32667
  1656
            mk_bot compfuns U'),
bulwahn@32667
  1657
       (v', mk_bot compfuns U')]))
bulwahn@32667
  1658
  end;
bulwahn@32667
  1659
bulwahn@35891
  1660
fun string_of_tderiv ctxt (t, deriv) = 
bulwahn@35324
  1661
  (case (t, deriv) of
bulwahn@35324
  1662
    (t1 $ t2, Mode_App (deriv1, deriv2)) =>
bulwahn@35891
  1663
      string_of_tderiv ctxt (t1, deriv1) ^ " $ " ^ string_of_tderiv ctxt (t2, deriv2)
haftmann@37366
  1664
  | (Const (@{const_name Pair}, _) $ t1 $ t2, Mode_Pair (deriv1, deriv2)) =>
bulwahn@35891
  1665
    "(" ^ string_of_tderiv ctxt (t1, deriv1) ^ ", " ^ string_of_tderiv ctxt (t2, deriv2) ^ ")"
bulwahn@35891
  1666
  | (t, Term Input) => Syntax.string_of_term ctxt t ^ "[Input]"
bulwahn@35891
  1667
  | (t, Term Output) => Syntax.string_of_term ctxt t ^ "[Output]"
bulwahn@35891
  1668
  | (t, Context m) => Syntax.string_of_term ctxt t ^ "[" ^ string_of_mode m ^ "]")
bulwahn@35324
  1669
bulwahn@39872
  1670
fun compile_expr compilation_modifiers ctxt (t, deriv) param_modes additional_arguments =
bulwahn@32667
  1671
  let
bulwahn@36013
  1672
    val compfuns = Comp_Mod.compfuns compilation_modifiers
bulwahn@34935
  1673
    fun expr_of (t, deriv) =
bulwahn@34935
  1674
      (case (t, deriv) of
bulwahn@39872
  1675
        (t, Term Input) => SOME (compile_arg compilation_modifiers additional_arguments ctxt param_modes t)
bulwahn@34935
  1676
      | (t, Term Output) => NONE
bulwahn@34935
  1677
      | (Const (name, T), Context mode) =>
bulwahn@36994
  1678
        (case alternative_compilation_of ctxt name mode of
bulwahn@36032
  1679
          SOME alt_comp => SOME (alt_comp compfuns T)
bulwahn@36028
  1680
        | NONE =>
bulwahn@36028
  1681
          SOME (Const (function_name_of (Comp_Mod.compilation compilation_modifiers)
bulwahn@36994
  1682
            ctxt name mode,
bulwahn@36028
  1683
            Comp_Mod.funT_of compilation_modifiers mode T)))
bulwahn@34935
  1684
      | (Free (s, T), Context m) =>
bulwahn@34935
  1685
        SOME (Free (s, Comp_Mod.funT_of compilation_modifiers m T))
bulwahn@34935
  1686
      | (t, Context m) =>
bulwahn@34935
  1687
        let
bulwahn@34935
  1688
          val bs = map (pair "x") (binder_types (fastype_of t))
bulwahn@34935
  1689
          val bounds = map Bound (rev (0 upto (length bs) - 1))
bulwahn@34935
  1690
        in SOME (list_abs (bs, mk_if compfuns (list_comb (t, bounds)))) end
haftmann@37366
  1691
      | (Const (@{const_name Pair}, _) $ t1 $ t2, Mode_Pair (d1, d2)) =>
bulwahn@34935
  1692
        (case (expr_of (t1, d1), expr_of (t2, d2)) of
bulwahn@34935
  1693
          (NONE, NONE) => NONE
bulwahn@34935
  1694
        | (NONE, SOME t) => SOME t
bulwahn@34935
  1695
        | (SOME t, NONE) => SOME t
bulwahn@34935
  1696
        | (SOME t1, SOME t2) => SOME (HOLogic.mk_prod (t1, t2)))
bulwahn@34935
  1697
      | (t1 $ t2, Mode_App (deriv1, deriv2)) =>
bulwahn@34935
  1698
        (case (expr_of (t1, deriv1), expr_of (t2, deriv2)) of
bulwahn@34935
  1699
          (SOME t, NONE) => SOME t
bulwahn@34935
  1700
         | (SOME t, SOME u) => SOME (t $ u)
bulwahn@34935
  1701
         | _ => error "something went wrong here!"))
bulwahn@32667
  1702
  in
bulwahn@35879
  1703
    list_comb (the (expr_of (t, deriv)), additional_arguments)
bulwahn@34935
  1704
  end
bulwahn@33145
  1705
bulwahn@39872
  1706
fun compile_clause compilation_modifiers ctxt all_vs param_modes additional_arguments
bulwahn@39872
  1707
  inp (in_ts, out_ts) moded_ps =
bulwahn@32667
  1708
  let
bulwahn@36013
  1709
    val compfuns = Comp_Mod.compfuns compilation_modifiers
bulwahn@36013
  1710
    val compile_match = compile_match compilation_modifiers
bulwahn@39872
  1711
      additional_arguments ctxt param_modes
bulwahn@32667
  1712
    val (in_ts', (all_vs', eqs)) =
bulwahn@35891
  1713
      fold_map (collect_non_invertible_subterms ctxt) in_ts (all_vs, []);
bulwahn@32667
  1714
    fun compile_prems out_ts' vs names [] =
bulwahn@32667
  1715
          let
bulwahn@32667
  1716
            val (out_ts'', (names', eqs')) =
bulwahn@35891
  1717
              fold_map (collect_non_invertible_subterms ctxt) out_ts' (names, []);
bulwahn@32667
  1718
            val (out_ts''', (names'', constr_vs)) = fold_map distinct_v
bulwahn@32667
  1719
              out_ts'' (names', map (rpair []) vs);
bulwahn@32667
  1720
          in
bulwahn@33147
  1721
            compile_match constr_vs (eqs @ eqs') out_ts'''
bulwahn@33148
  1722
              (mk_single compfuns (HOLogic.mk_tuple out_ts))
bulwahn@32667
  1723
          end
bulwahn@34935
  1724
      | compile_prems out_ts vs names ((p, deriv) :: ps) =
bulwahn@32667
  1725
          let
bulwahn@32667
  1726
            val vs' = distinct (op =) (flat (vs :: map term_vs out_ts));
bulwahn@32667
  1727
            val (out_ts', (names', eqs)) =
bulwahn@35891
  1728
              fold_map (collect_non_invertible_subterms ctxt) out_ts (names, [])
bulwahn@32667
  1729
            val (out_ts'', (names'', constr_vs')) = fold_map distinct_v
bulwahn@32667
  1730
              out_ts' ((names', map (rpair []) vs))
bulwahn@34935
  1731
            val mode = head_mode_of deriv
bulwahn@33143
  1732
            val additional_arguments' =
bulwahn@33330
  1733
              Comp_Mod.transform_additional_arguments compilation_modifiers p additional_arguments
bulwahn@32667
  1734
            val (compiled_clause, rest) = case p of
bulwahn@34935
  1735
               Prem t =>
bulwahn@32667
  1736
                 let
bulwahn@33138
  1737
                   val u =
bulwahn@39872
  1738
                     compile_expr compilation_modifiers ctxt (t, deriv) param_modes additional_arguments'
bulwahn@34935
  1739
                   val (_, out_ts''') = split_mode mode (snd (strip_comb t))
bulwahn@32667
  1740
                   val rest = compile_prems out_ts''' vs' names'' ps
bulwahn@32667
  1741
                 in
bulwahn@32667
  1742
                   (u, rest)
bulwahn@32667
  1743
                 end
bulwahn@34935
  1744
             | Negprem t =>
bulwahn@32667
  1745
                 let
bulwahn@36013
  1746
                   val neg_compilation_modifiers =
bulwahn@36013
  1747
                     negative_comp_modifiers_of compilation_modifiers
bulwahn@33143
  1748
                   val u = mk_not compfuns
bulwahn@39872
  1749
                     (compile_expr neg_compilation_modifiers ctxt (t, deriv) param_modes additional_arguments')
bulwahn@34935
  1750
                   val (_, out_ts''') = split_mode mode (snd (strip_comb t))
bulwahn@32667
  1751
                   val rest = compile_prems out_ts''' vs' names'' ps
bulwahn@32667
  1752
                 in
bulwahn@32667
  1753
                   (u, rest)
bulwahn@32667
  1754
                 end
bulwahn@32667
  1755
             | Sidecond t =>
bulwahn@32667
  1756
                 let
bulwahn@36013
  1757
                   val t = compile_arg compilation_modifiers additional_arguments
bulwahn@39872
  1758
                     ctxt param_modes t
bulwahn@32667
  1759
                   val rest = compile_prems [] vs' names'' ps;
bulwahn@32667
  1760
                 in
bulwahn@32667
  1761
                   (mk_if compfuns t, rest)
bulwahn@32667
  1762
                 end
bulwahn@32667
  1763
             | Generator (v, T) =>
bulwahn@32667
  1764
                 let
bulwahn@35880
  1765
                   val u = Comp_Mod.mk_random compilation_modifiers T additional_arguments
bulwahn@32667
  1766
                   val rest = compile_prems [Free (v, T)]  vs' names'' ps;
bulwahn@32667
  1767
                 in
bulwahn@32667
  1768
                   (u, rest)
bulwahn@32667
  1769
                 end
bulwahn@32667
  1770
          in
bulwahn@33147
  1771
            compile_match constr_vs' eqs out_ts''
bulwahn@32667
  1772
              (mk_bind compfuns (compiled_clause, rest))
bulwahn@32667
  1773
          end
bulwahn@39872
  1774
    val prem_t = compile_prems in_ts' (map fst param_modes) all_vs' moded_ps;
bulwahn@32667
  1775
  in
bulwahn@32667
  1776
    mk_bind compfuns (mk_single compfuns inp, prem_t)
bulwahn@32667
  1777
  end
bulwahn@32667
  1778
bulwahn@36254
  1779
(* switch detection *)
bulwahn@36254
  1780
bulwahn@36254
  1781
(** argument position of an inductive predicates and the executable functions **)
bulwahn@36254
  1782
bulwahn@36254
  1783
type position = int * int list
bulwahn@36254
  1784
bulwahn@36254
  1785
fun input_positions_pair Input = [[]]
bulwahn@36254
  1786
  | input_positions_pair Output = []
bulwahn@36254
  1787
  | input_positions_pair (Fun _) = []
bulwahn@36254
  1788
  | input_positions_pair (Pair (m1, m2)) =
bulwahn@36254
  1789
    map (cons 1) (input_positions_pair m1) @ map (cons 2) (input_positions_pair m2)
bulwahn@36254
  1790
bulwahn@36254
  1791
fun input_positions_of_mode mode = flat (map_index
bulwahn@36254
  1792
   (fn (i, Input) => [(i, [])]
bulwahn@36254
  1793
   | (_, Output) => []
bulwahn@36254
  1794
   | (_, Fun _) => []
bulwahn@36254
  1795
   | (i, m as Pair (m1, m2)) => map (pair i) (input_positions_pair m))
bulwahn@36254
  1796
     (Predicate_Compile_Aux.strip_fun_mode mode))
bulwahn@36254
  1797
bulwahn@36254
  1798
fun argument_position_pair mode [] = []
bulwahn@36254
  1799
  | argument_position_pair (Pair (Fun _, m2)) (2 :: is) = argument_position_pair m2 is
bulwahn@36254
  1800
  | argument_position_pair (Pair (m1, m2)) (i :: is) =
bulwahn@36254
  1801
    (if eq_mode (m1, Output) andalso i = 2 then
bulwahn@36254
  1802
      argument_position_pair m2 is
bulwahn@36254
  1803
    else if eq_mode (m2, Output) andalso i = 1 then
bulwahn@36254
  1804
      argument_position_pair m1 is
bulwahn@36254
  1805
    else (i :: argument_position_pair (if i = 1 then m1 else m2) is))
bulwahn@36254
  1806
bulwahn@36254
  1807
fun argument_position_of mode (i, is) =
bulwahn@36254
  1808
  (i - (length (filter (fn Output => true | Fun _ => true | _ => false)
bulwahn@36254
  1809
    (List.take (strip_fun_mode mode, i)))),
bulwahn@36254
  1810
  argument_position_pair (nth (strip_fun_mode mode) i) is)
bulwahn@36254
  1811
bulwahn@36254
  1812
fun nth_pair [] t = t
bulwahn@36254
  1813
  | nth_pair (1 :: is) (Const (@{const_name Pair}, _) $ t1 $ _) = nth_pair is t1
bulwahn@36254
  1814
  | nth_pair (2 :: is) (Const (@{const_name Pair}, _) $ _ $ t2) = nth_pair is t2
bulwahn@36254
  1815
  | nth_pair _ _ = raise Fail "unexpected input for nth_tuple"
bulwahn@36254
  1816
bulwahn@36254
  1817
(** switch detection analysis **)
bulwahn@36254
  1818
bulwahn@36996
  1819
fun find_switch_test ctxt (i, is) (ts, prems) =
bulwahn@36254
  1820
  let
bulwahn@36254
  1821
    val t = nth_pair is (nth ts i)
bulwahn@36254
  1822
    val T = fastype_of t
bulwahn@36254
  1823
  in
bulwahn@36254
  1824
    case T of
bulwahn@36254
  1825
      TFree _ => NONE
bulwahn@36254
  1826
    | Type (Tcon, _) =>
bulwahn@36996
  1827
      (case Datatype_Data.get_constrs (ProofContext.theory_of ctxt) Tcon of
bulwahn@36254
  1828
        NONE => NONE
bulwahn@36254
  1829
      | SOME cs =>
bulwahn@36254
  1830
        (case strip_comb t of
bulwahn@36254
  1831
          (Var _, []) => NONE
bulwahn@36254
  1832
        | (Free _, []) => NONE
bulwahn@36254
  1833
        | (Const (c, T), _) => if AList.defined (op =) cs c then SOME (c, T) else NONE))
bulwahn@36254
  1834
  end
bulwahn@36254
  1835
bulwahn@36996
  1836
fun partition_clause ctxt pos moded_clauses =
bulwahn@36254
  1837
  let
bulwahn@36254
  1838
    fun insert_list eq (key, value) = AList.map_default eq (key, []) (cons value)
bulwahn@36254
  1839
    fun find_switch_test' moded_clause (cases, left) =
bulwahn@36996
  1840
      case find_switch_test ctxt pos moded_clause of
bulwahn@36254
  1841
        SOME (c, T) => (insert_list (op =) ((c, T), moded_clause) cases, left)
bulwahn@36254
  1842
      | NONE => (cases, moded_clause :: left)
bulwahn@36254
  1843
  in
bulwahn@36254
  1844
    fold find_switch_test' moded_clauses ([], [])
bulwahn@36254
  1845
  end
bulwahn@36254
  1846
bulwahn@36254
  1847
datatype switch_tree =
bulwahn@36254
  1848
  Atom of moded_clause list | Node of (position * ((string * typ) * switch_tree) list) * switch_tree
bulwahn@36254
  1849
bulwahn@36996
  1850
fun mk_switch_tree ctxt mode moded_clauses =
bulwahn@36254
  1851
  let
bulwahn@36254
  1852
    fun select_best_switch moded_clauses input_position best_switch =
bulwahn@36254
  1853
      let
bulwahn@36254
  1854
        val ord = option_ord (rev_order o int_ord o (pairself (length o snd o snd)))
bulwahn@36996
  1855
        val partition = partition_clause ctxt input_position moded_clauses
bulwahn@36254
  1856
        val switch = if (length (fst partition) > 1) then SOME (input_position, partition) else NONE
bulwahn@36254
  1857
      in
bulwahn@36254
  1858
        case ord (switch, best_switch) of LESS => best_switch
bulwahn@36254
  1859
          | EQUAL => best_switch | GREATER => switch
bulwahn@36254
  1860
      end
bulwahn@36254
  1861
    fun detect_switches moded_clauses =
bulwahn@36254
  1862
      case fold (select_best_switch moded_clauses) (input_positions_of_mode mode) NONE of
bulwahn@36254
  1863
        SOME (best_pos, (switched_on, left_clauses)) =>
bulwahn@36254
  1864
          Node ((best_pos, map (apsnd detect_switches) switched_on),
bulwahn@36254
  1865
            detect_switches left_clauses)
bulwahn@36254
  1866
      | NONE => Atom moded_clauses
bulwahn@36254
  1867
  in
bulwahn@36254
  1868
    detect_switches moded_clauses
bulwahn@36254
  1869
  end
bulwahn@36254
  1870
bulwahn@36254
  1871
(** compilation of detected switches **)
bulwahn@36254
  1872
bulwahn@36254
  1873
fun destruct_constructor_pattern (pat, obj) =
bulwahn@36254
  1874
  (case strip_comb pat of
bulwahn@36254
  1875
    (f as Free _, []) => cons (pat, obj)
bulwahn@36254
  1876
  | (Const (c, T), pat_args) =>
bulwahn@36254
  1877
    (case strip_comb obj of
bulwahn@36254
  1878
      (Const (c', T'), obj_args) =>
bulwahn@36254
  1879
        (if c = c' andalso T = T' then
bulwahn@36254
  1880
          fold destruct_constructor_pattern (pat_args ~~ obj_args)
bulwahn@36254
  1881
        else raise Fail "pattern and object mismatch")
bulwahn@36254
  1882
    | _ => raise Fail "unexpected object")
bulwahn@36254
  1883
  | _ => raise Fail "unexpected pattern")
bulwahn@36254
  1884
bulwahn@36254
  1885
bulwahn@39872
  1886
fun compile_switch compilation_modifiers ctxt all_vs param_modes additional_arguments mode
bulwahn@36254
  1887
  in_ts' outTs switch_tree =
bulwahn@36254
  1888
  let
bulwahn@36254
  1889
    val compfuns = Comp_Mod.compfuns compilation_modifiers
bulwahn@36254
  1890
    val thy = ProofContext.theory_of ctxt
bulwahn@36254
  1891
    fun compile_switch_tree _ _ (Atom []) = NONE
bulwahn@36254
  1892
      | compile_switch_tree all_vs ctxt_eqs (Atom moded_clauses) =
bulwahn@36254
  1893
        let
bulwahn@36254
  1894
          val in_ts' = map (Pattern.rewrite_term thy ctxt_eqs []) in_ts'
bulwahn@36254
  1895
          fun compile_clause' (ts, moded_ps) =
bulwahn@36254
  1896
            let
bulwahn@36254
  1897
              val (ts, out_ts) = split_mode mode ts
bulwahn@36254
  1898
              val subst = fold destruct_constructor_pattern (in_ts' ~~ ts) []
bulwahn@36254
  1899
              val (fsubst, pat') = List.partition (fn (_, Free _) => true | _ => false) subst
bulwahn@36254
  1900
              val moded_ps' = (map o apfst o map_indprem)
bulwahn@36254
  1901
                (Pattern.rewrite_term thy (map swap fsubst) []) moded_ps
bulwahn@36254
  1902
              val inp = HOLogic.mk_tuple (map fst pat')
bulwahn@36254
  1903
              val in_ts' = map (Pattern.rewrite_term thy (map swap fsubst) []) (map snd pat')
bulwahn@36254
  1904
              val out_ts' = map (Pattern.rewrite_term thy (map swap fsubst) []) out_ts
bulwahn@36254
  1905
            in
bulwahn@39872
  1906
              compile_clause compilation_modifiers ctxt all_vs param_modes additional_arguments
bulwahn@39872
  1907
                inp (in_ts', out_ts') moded_ps'
bulwahn@36254
  1908
            end
bulwahn@36254
  1909
        in SOME (foldr1 (mk_sup compfuns) (map compile_clause' moded_clauses)) end
bulwahn@36254
  1910
    | compile_switch_tree all_vs ctxt_eqs (Node ((position, switched_clauses), left_clauses)) =
bulwahn@36254
  1911
      let
bulwahn@36254
  1912
        val (i, is) = argument_position_of mode position
bulwahn@36254
  1913
        val inp_var = nth_pair is (nth in_ts' i)
bulwahn@36254
  1914
        val x = Name.variant all_vs "x"
bulwahn@36254
  1915
        val xt = Free (x, fastype_of inp_var)
bulwahn@36254
  1916
        fun compile_single_case ((c, T), switched) =
bulwahn@36254
  1917
          let
bulwahn@36254
  1918
            val Ts = binder_types T
bulwahn@36254
  1919
            val argnames = Name.variant_list (x :: all_vs)
bulwahn@36254
  1920
              (map (fn i => "c" ^ string_of_int i) (1 upto length Ts))
bulwahn@36254
  1921
            val args = map2 (curry Free) argnames Ts
bulwahn@36254
  1922
            val pattern = list_comb (Const (c, T), args)
bulwahn@36254
  1923
            val ctxt_eqs' = (inp_var, pattern) :: ctxt_eqs
bulwahn@36254
  1924
            val compilation = the_default (mk_bot compfuns (HOLogic.mk_tupleT outTs))
bulwahn@36254
  1925
              (compile_switch_tree (argnames @ x :: all_vs) ctxt_eqs' switched)
bulwahn@36254
  1926
        in
bulwahn@36254
  1927
          (pattern, compilation)
bulwahn@36254
  1928
        end
bulwahn@36254
  1929
        val switch = fst (Datatype.make_case ctxt Datatype_Case.Quiet [] inp_var
bulwahn@36254
  1930
          ((map compile_single_case switched_clauses) @
bulwahn@36254
  1931
            [(xt, mk_bot compfuns (HOLogic.mk_tupleT outTs))]))
bulwahn@36254
  1932
      in
bulwahn@36254
  1933
        case compile_switch_tree all_vs ctxt_eqs left_clauses of
bulwahn@36254
  1934
          NONE => SOME switch
bulwahn@36254
  1935
        | SOME left_comp => SOME (mk_sup compfuns (switch, left_comp))
bulwahn@36254
  1936
      end
bulwahn@36254
  1937
  in
bulwahn@36254
  1938
    compile_switch_tree all_vs [] switch_tree
bulwahn@36254
  1939
  end
bulwahn@36254
  1940
bulwahn@36254
  1941
(* compilation of predicates *)
bulwahn@36254
  1942
bulwahn@36996
  1943
fun compile_pred options compilation_modifiers ctxt all_vs param_vs s T (pol, mode) moded_cls =
bulwahn@32667
  1944
  let
bulwahn@36014
  1945
    val compilation_modifiers = if pol then compilation_modifiers else
bulwahn@36014
  1946
      negative_comp_modifiers_of compilation_modifiers
bulwahn@35879
  1947
    val additional_arguments = Comp_Mod.additional_arguments compilation_modifiers
bulwahn@33482
  1948
      (all_vs @ param_vs)
bulwahn@34935
  1949
    val compfuns = Comp_Mod.compfuns compilation_modifiers
bulwahn@34935
  1950
    fun is_param_type (T as Type ("fun",[_ , T'])) =
bulwahn@34935
  1951
      is_some (try (dest_predT compfuns) T) orelse is_param_type T'
bulwahn@34935
  1952
      | is_param_type T = is_some (try (dest_predT compfuns) T)
bulwahn@34935
  1953
    val (inpTs, outTs) = split_map_modeT (fn m => fn T => (SOME (funT_of compfuns m T), NONE)) mode
bulwahn@34935
  1954
      (binder_types T)
bulwahn@34935
  1955
    val predT = mk_predT compfuns (HOLogic.mk_tupleT outTs)
bulwahn@34935
  1956
    val funT = Comp_Mod.funT_of compilation_modifiers mode T
bulwahn@34935
  1957
    val (in_ts, _) = fold_map (fold_map_aterms_prodT (curry HOLogic.mk_prod)
bulwahn@34935
  1958
      (fn T => fn (param_vs, names) =>
bulwahn@36012
  1959
        if is_param_type T then
bulwahn@34935
  1960
          (Free (hd param_vs, T), (tl param_vs, names))
bulwahn@34935
  1961
        else
bulwahn@34935
  1962
          let
bulwahn@34935
  1963
            val new = Name.variant names "x"
bulwahn@34935
  1964
          in (Free (new, T), (param_vs, new :: names)) end)) inpTs
bulwahn@34935
  1965
        (param_vs, (all_vs @ param_vs))
bulwahn@34935
  1966
    val in_ts' = map_filter (map_filter_prod
bulwahn@34935
  1967
      (fn t as Free (x, _) => if member (op =) param_vs x then NONE else SOME t | t => SOME t)) in_ts
bulwahn@39872
  1968
    val param_modes = param_vs ~~ ho_arg_modes_of mode
bulwahn@36254
  1969
    val compilation =
bulwahn@36254
  1970
      if detect_switches options then
bulwahn@36254
  1971
        the_default (mk_bot compfuns (HOLogic.mk_tupleT outTs))
bulwahn@39872
  1972
          (compile_switch compilation_modifiers ctxt all_vs param_modes additional_arguments mode
bulwahn@39872
  1973
            in_ts' outTs (mk_switch_tree ctxt mode moded_cls))
bulwahn@36254
  1974
      else
bulwahn@36254
  1975
        let
bulwahn@36254
  1976
          val cl_ts =
bulwahn@36254
  1977
            map (fn (ts, moded_prems) => 
bulwahn@39872
  1978
              compile_clause compilation_modifiers ctxt all_vs param_modes additional_arguments
bulwahn@39872
  1979
                (HOLogic.mk_tuple in_ts') (split_mode mode ts) moded_prems) moded_cls;
bulwahn@36254
  1980
        in
bulwahn@36254
  1981
          Comp_Mod.wrap_compilation compilation_modifiers compfuns s T mode additional_arguments
bulwahn@36254
  1982
            (if null cl_ts then
bulwahn@36254
  1983
              mk_bot compfuns (HOLogic.mk_tupleT outTs)
bulwahn@36254
  1984
            else
bulwahn@36254
  1985
              foldr1 (mk_sup compfuns) cl_ts)
bulwahn@36254
  1986
        end
bulwahn@33143
  1987
    val fun_const =
bulwahn@35891
  1988
      Const (function_name_of (Comp_Mod.compilation compilation_modifiers)
bulwahn@36994
  1989
      ctxt s mode, funT)
bulwahn@32667
  1990
  in
bulwahn@33143
  1991
    HOLogic.mk_Trueprop
bulwahn@34935
  1992
      (HOLogic.mk_eq (list_comb (fun_const, in_ts @ additional_arguments), compilation))
bulwahn@32667
  1993
  end;
bulwahn@33143
  1994
bulwahn@36254
  1995
(** special setup for simpset **)
haftmann@34961
  1996
val HOL_basic_ss' = HOL_basic_ss addsimps (@{thms HOL.simp_thms} @ [@{thm Pair_eq}])
bulwahn@32667
  1997
  setSolver (mk_solver "all_tac_solver" (fn _ => fn _ => all_tac))
wenzelm@33268
  1998
  setSolver (mk_solver "True_solver" (fn _ => rtac @{thm TrueI}))
bulwahn@32667
  1999
bulwahn@32667
  2000
(* Definition of executable functions and their intro and elim rules *)
bulwahn@32667
  2001
bulwahn@32667
  2002
fun print_arities arities = tracing ("Arities:\n" ^
bulwahn@32667
  2003
  cat_lines (map (fn (s, (ks, k)) => s ^ ": " ^
bulwahn@32667
  2004
    space_implode " -> " (map
bulwahn@32667
  2005
      (fn NONE => "X" | SOME k' => string_of_int k')
bulwahn@32667
  2006
        (ks @ [SOME k]))) arities));
bulwahn@32667
  2007
bulwahn@34935
  2008
fun split_lambda (x as Free _) t = lambda x t
haftmann@37366
  2009
  | split_lambda (Const (@{const_name Pair}, _) $ t1 $ t2) t =
bulwahn@34935
  2010
    HOLogic.mk_split (split_lambda t1 (split_lambda t2 t))
bulwahn@34935
  2011
  | split_lambda (Const ("Product_Type.Unity", _)) t = Abs ("x", HOLogic.unitT, t)
bulwahn@34935
  2012
  | split_lambda t _ = raise (TERM ("split_lambda", [t]))
bulwahn@34935
  2013
haftmann@37591
  2014
fun strip_split_abs (Const (@{const_name prod_case}, _) $ t) = strip_split_abs t
bulwahn@34935
  2015
  | strip_split_abs (Abs (_, _, t)) = strip_split_abs t
bulwahn@34935
  2016
  | strip_split_abs t = t
bulwahn@34935
  2017
haftmann@37678
  2018
fun mk_args is_eval (m as Pair (m1, m2), T as Type (@{type_name Product_Type.prod}, [T1, T2])) names =
bulwahn@35324
  2019
    if eq_mode (m, Input) orelse eq_mode (m, Output) then
bulwahn@35324
  2020
      let
bulwahn@35324
  2021
        val x = Name.variant names "x"
bulwahn@35324
  2022
      in
bulwahn@35324
  2023
        (Free (x, T), x :: names)
bulwahn@35324
  2024
      end
bulwahn@35324
  2025
    else
bulwahn@35324
  2026
      let
bulwahn@35324
  2027
        val (t1, names') = mk_args is_eval (m1, T1) names
bulwahn@35324
  2028
        val (t2, names'') = mk_args is_eval (m2, T2) names'
bulwahn@35324
  2029
      in
bulwahn@35324
  2030
        (HOLogic.mk_prod (t1, t2), names'')
bulwahn@35324
  2031
      end
bulwahn@34935
  2032
  | mk_args is_eval ((m as Fun _), T) names =
bulwahn@34935
  2033
    let
bulwahn@34935
  2034
      val funT = funT_of PredicateCompFuns.compfuns m T
bulwahn@34935
  2035
      val x = Name.variant names "x"
bulwahn@34935
  2036
      val (args, _) = fold_map (mk_args is_eval) (strip_fun_mode m ~~ binder_types T) (x :: names)
bulwahn@34935
  2037
      val (inargs, outargs) = split_map_mode (fn _ => fn t => (SOME t, NONE)) m args
bulwahn@34935
  2038
      val t = fold_rev split_lambda args (PredicateCompFuns.mk_Eval
bulwahn@34935
  2039
        (list_comb (Free (x, funT), inargs), HOLogic.mk_tuple outargs))
bulwahn@34935
  2040
    in
bulwahn@34935
  2041
      (if is_eval then t else Free (x, funT), x :: names)
bulwahn@34935
  2042
    end
bulwahn@34935
  2043
  | mk_args is_eval (_, T) names =
bulwahn@34935
  2044
    let
bulwahn@34935
  2045
      val x = Name.variant names "x"
bulwahn@34935
  2046
    in
bulwahn@34935
  2047
      (Free (x, T), x :: names)
bulwahn@34935
  2048
    end
bulwahn@34935
  2049
bulwahn@36994
  2050
fun create_intro_elim_rule ctxt mode defthm mode_id funT pred =
bulwahn@34935
  2051
  let
bulwahn@34935
  2052
    val funtrm = Const (mode_id, funT)
bulwahn@34935
  2053
    val Ts = binder_types (fastype_of pred)
bulwahn@34935
  2054
    val (args, argnames) = fold_map (mk_args true) (strip_fun_mode mode ~~ Ts) []
bulwahn@34935
  2055
    fun strip_eval _ t =
bulwahn@34935
  2056
      let
bulwahn@34935
  2057
        val t' = strip_split_abs t
bulwahn@34935
  2058
        val (r, _) = PredicateCompFuns.dest_Eval t'
bulwahn@34935
  2059
      in (SOME (fst (strip_comb r)), NONE) end
bulwahn@34935
  2060
    val (inargs, outargs) = split_map_mode strip_eval mode args
bulwahn@34935
  2061
    val eval_hoargs = ho_args_of mode args
bulwahn@34935
  2062
    val hoargTs = ho_argsT_of mode Ts
bulwahn@34935
  2063
    val hoarg_names' =
bulwahn@34935
  2064
      Name.variant_list argnames ((map (fn i => "x" ^ string_of_int i)) (1 upto (length hoargTs)))
bulwahn@34935
  2065
    val hoargs' = map2 (curry Free) hoarg_names' hoargTs
bulwahn@34935
  2066
    val args' = replace_ho_args mode hoargs' args
bulwahn@34935
  2067
    val predpropI = HOLogic.mk_Trueprop (list_comb (pred, args'))
bulwahn@34935
  2068
    val predpropE = HOLogic.mk_Trueprop (list_comb (pred, args))
bulwahn@34935
  2069
    val param_eqs = map2 (HOLogic.mk_Trueprop oo (curry HOLogic.mk_eq)) eval_hoargs hoargs'
bulwahn@34935
  2070
    val funpropE = HOLogic.mk_Trueprop (PredicateCompFuns.mk_Eval (list_comb (funtrm, inargs),
bulwahn@34935
  2071
                    if null outargs then Free("y", HOLogic.unitT) else HOLogic.mk_tuple outargs))
bulwahn@34935
  2072
    val funpropI = HOLogic.mk_Trueprop (PredicateCompFuns.mk_Eval (list_comb (funtrm, inargs),
bulwahn@34935
  2073
                     HOLogic.mk_tuple outargs))
bulwahn@34935
  2074
    val introtrm = Logic.list_implies (predpropI :: param_eqs, funpropI)
bulwahn@34935
  2075
    val simprules = [defthm, @{thm eval_pred},
bulwahn@34935
  2076
      @{thm "split_beta"}, @{thm "fst_conv"}, @{thm "snd_conv"}, @{thm pair_collapse}]
bulwahn@34935
  2077
    val unfolddef_tac = Simplifier.asm_full_simp_tac (HOL_basic_ss addsimps simprules) 1
bulwahn@36994
  2078
    val introthm = Goal.prove ctxt
bulwahn@34935
  2079
      (argnames @ hoarg_names' @ ["y"]) [] introtrm (fn _ => unfolddef_tac)
bulwahn@34935
  2080
    val P = HOLogic.mk_Trueprop (Free ("P", HOLogic.boolT));
bulwahn@34935
  2081
    val elimtrm = Logic.list_implies ([funpropE, Logic.mk_implies (predpropE, P)], P)
bulwahn@36994
  2082
    val elimthm = Goal.prove ctxt
bulwahn@34935
  2083
      (argnames @ ["y", "P"]) [] elimtrm (fn _ => unfolddef_tac)
bulwahn@35884
  2084
    val opt_neg_introthm =
bulwahn@35884
  2085
      if is_all_input mode then
bulwahn@35884
  2086
        let
bulwahn@35884
  2087
          val neg_predpropI = HOLogic.mk_Trueprop (HOLogic.mk_not (list_comb (pred, args')))
bulwahn@35884
  2088
          val neg_funpropI =
bulwahn@35884
  2089
            HOLogic.mk_Trueprop (PredicateCompFuns.mk_Eval
bulwahn@35884
  2090
              (PredicateCompFuns.mk_not (list_comb (funtrm, inargs)), HOLogic.unit))
bulwahn@35884
  2091
          val neg_introtrm = Logic.list_implies (neg_predpropI :: param_eqs, neg_funpropI)
bulwahn@35884
  2092
          val tac =
bulwahn@35884
  2093
            Simplifier.asm_full_simp_tac (HOL_basic_ss addsimps
bulwahn@35884
  2094
              (@{thm if_False} :: @{thm Predicate.not_pred_eq} :: simprules)) 1
bulwahn@35884
  2095
            THEN rtac @{thm Predicate.singleI} 1
bulwahn@36994
  2096
        in SOME (Goal.prove ctxt (argnames @ hoarg_names') []
bulwahn@35884
  2097
            neg_introtrm (fn _ => tac))
bulwahn@35884
  2098
        end
bulwahn@35884
  2099
      else NONE
bulwahn@34935
  2100
  in
bulwahn@35884
  2101
    ((introthm, elimthm), opt_neg_introthm)
bulwahn@34935
  2102
  end
bulwahn@32667
  2103
bulwahn@33620
  2104
fun create_constname_of_mode options thy prefix name T mode = 
bulwahn@32667
  2105
  let
bulwahn@33626
  2106
    val system_proposal = prefix ^ (Long_Name.base_name name)
bulwahn@34935
  2107
      ^ "_" ^ ascii_string_of_mode mode
bulwahn@34935
  2108
    val name = the_default system_proposal (proposed_names options name mode)
bulwahn@32667
  2109
  in
bulwahn@33620
  2110
    Sign.full_bname thy name
bulwahn@32667
  2111
  end;
bulwahn@32667
  2112
bulwahn@33620
  2113
fun create_definitions options preds (name, modes) thy =
bulwahn@32667
  2114
  let
bulwahn@32667
  2115
    val compfuns = PredicateCompFuns.compfuns
bulwahn@32667
  2116
    val T = AList.lookup (op =) preds name |> the
bulwahn@34935
  2117
    fun create_definition mode thy =
bulwahn@33752
  2118
      let
bulwahn@33752
  2119
        val mode_cname = create_constname_of_mode options thy "" name T mode
bulwahn@33752
  2120
        val mode_cbasename = Long_Name.base_name mode_cname
bulwahn@34935
  2121
        val funT = funT_of compfuns mode T
bulwahn@34935
  2122
        val (args, _) = fold_map (mk_args true) ((strip_fun_mode mode) ~~ (binder_types T)) []
bulwahn@34935
  2123
        fun strip_eval m t =
bulwahn@33752
  2124
          let
bulwahn@34935
  2125
            val t' = strip_split_abs t
bulwahn@34935
  2126
            val (r, _) = PredicateCompFuns.dest_Eval t'
bulwahn@34935
  2127
          in (SOME (fst (strip_comb r)), NONE) end
bulwahn@34935
  2128
        val (inargs, outargs) = split_map_mode strip_eval mode args
bulwahn@34935
  2129
        val predterm = fold_rev split_lambda inargs
bulwahn@34935
  2130
          (PredicateCompFuns.mk_Enum (split_lambda (HOLogic.mk_tuple outargs)
bulwahn@34935
  2131
            (list_comb (Const (name, T), args))))
bulwahn@34935
  2132
        val lhs = Const (mode_cname, funT)
bulwahn@33752
  2133
        val def = Logic.mk_equals (lhs, predterm)
bulwahn@33752
  2134
        val ([definition], thy') = thy |>
bulwahn@33752
  2135
          Sign.add_consts_i [(Binding.name mode_cbasename, funT, NoSyn)] |>
wenzelm@39814
  2136
          Global_Theory.add_defs false [((Binding.name (mode_cbasename ^ "_def"), def), [])]
bulwahn@36994
  2137
        val ctxt' = ProofContext.init_global thy'
bulwahn@35884
  2138
        val rules as ((intro, elim), _) =
bulwahn@36994
  2139
          create_intro_elim_rule ctxt' mode definition mode_cname funT (Const (name, T))
bulwahn@33752
  2140
        in thy'
bulwahn@34935
  2141
          |> set_function_name Pred name mode mode_cname
bulwahn@35884
  2142
          |> add_predfun_data name mode (definition, rules)
wenzelm@39814
  2143
          |> Global_Theory.store_thm (Binding.name (mode_cbasename ^ "I"), intro) |> snd
wenzelm@39814
  2144
          |> Global_Theory.store_thm (Binding.name (mode_cbasename ^ "E"), elim)  |> snd
bulwahn@33752
  2145
          |> Theory.checkpoint
bulwahn@32667
  2146
        end;
bulwahn@32667
  2147
  in
bulwahn@34935
  2148
    thy |> defined_function_of Pred name |> fold create_definition modes
bulwahn@32667
  2149
  end;
bulwahn@32667
  2150
bulwahn@33620
  2151
fun define_functions comp_modifiers compfuns options preds (name, modes) thy =
bulwahn@32667
  2152
  let
bulwahn@32667
  2153
    val T = AList.lookup (op =) preds name |> the
bulwahn@32667
  2154
    fun create_definition mode thy =
bulwahn@32667
  2155
      let
bulwahn@33485
  2156
        val function_name_prefix = Comp_Mod.function_name_prefix comp_modifiers
bulwahn@33620
  2157
        val mode_cname = create_constname_of_mode options thy function_name_prefix name T mode
bulwahn@34935
  2158
        val funT = Comp_Mod.funT_of comp_modifiers mode T
bulwahn@32667
  2159
      in
bulwahn@32667
  2160
        thy |> Sign.add_consts_i [(Binding.name (Long_Name.base_name mode_cname), funT, NoSyn)]
bulwahn@34935
  2161
        |> set_function_name (Comp_Mod.compilation comp_modifiers) name mode mode_cname
bulwahn@32667
  2162
      end;
bulwahn@32667
  2163
  in
bulwahn@34935
  2164
    thy
bulwahn@34935
  2165
    |> defined_function_of (Comp_Mod.compilation comp_modifiers) name
bulwahn@34935
  2166
    |> fold create_definition modes
bulwahn@32667
  2167
  end;
bulwahn@32672
  2168
bulwahn@32667
  2169
(* Proving equivalence of term *)
bulwahn@32667
  2170
bulwahn@32667
  2171
fun is_Type (Type _) = true
bulwahn@32667
  2172
  | is_Type _ = false
bulwahn@32667
  2173
bulwahn@32667
  2174
(* returns true if t is an application of an datatype constructor *)
bulwahn@32667
  2175
(* which then consequently would be splitted *)
bulwahn@32667
  2176
(* else false *)
bulwahn@32667
  2177
fun is_constructor thy t =
bulwahn@32667
  2178
  if (is_Type (fastype_of t)) then
bulwahn@32667
  2179
    (case Datatype.get_info thy ((fst o dest_Type o fastype_of) t) of
bulwahn@32667
  2180
      NONE => false
bulwahn@32667
  2181
    | SOME info => (let
bulwahn@32667
  2182
      val constr_consts = maps (fn (_, (_, _, constrs)) => map fst constrs) (#descr info)
bulwahn@32667
  2183
      val (c, _) = strip_comb t
bulwahn@32667
  2184
      in (case c of
haftmann@36677
  2185
        Const (name, _) => member (op =) constr_consts name
bulwahn@32667
  2186
        | _ => false) end))
bulwahn@32667
  2187
  else false
bulwahn@32667
  2188
bulwahn@32667
  2189
(* MAJOR FIXME:  prove_params should be simple
bulwahn@32667
  2190
 - different form of introrule for parameters ? *)
bulwahn@34935
  2191
bulwahn@35888
  2192
fun prove_param options ctxt nargs t deriv =
bulwahn@32667
  2193
  let
bulwahn@32667
  2194
    val  (f, args) = strip_comb (Envir.eta_contract t)
bulwahn@34935
  2195
    val mode = head_mode_of deriv
bulwahn@34935
  2196
    val param_derivations = param_derivations_of deriv
bulwahn@34935
  2197
    val ho_args = ho_args_of mode args
bulwahn@32667
  2198
    val f_tac = case f of
bulwahn@32667
  2199
      Const (name, T) => simp_tac (HOL_basic_ss addsimps 
bulwahn@35888
  2200
         [@{thm eval_pred}, predfun_definition_of ctxt name mode,
bulwahn@35884
  2201
         @{thm split_eta}, @{thm split_beta}, @{thm fst_conv},
bulwahn@35884
  2202
         @{thm snd_conv}, @{thm pair_collapse}, @{thm Product_Type.split_conv}]) 1
bulwahn@35884
  2203
    | Free _ =>
bulwahn@35888
  2204
      Subgoal.FOCUS_PREMS (fn {context = ctxt, params = params, prems, asms, concl, schematics} =>
bulwahn@35884
  2205
        let
bulwahn@35884
  2206
          val prems' = maps dest_conjunct_prem (take nargs prems)
bulwahn@35884
  2207
        in
bulwahn@35884
  2208
          MetaSimplifier.rewrite_goal_tac
bulwahn@35884
  2209
            (map (fn th => th RS @{thm sym} RS @{thm eq_reflection}) prems') 1
bulwahn@35888
  2210
        end) ctxt 1
bulwahn@35884
  2211
    | Abs _ => raise Fail "prove_param: No valid parameter term"
bulwahn@32667
  2212
  in
bulwahn@33753
  2213
    REPEAT_DETERM (rtac @{thm ext} 1)
bulwahn@35886
  2214
    THEN print_tac options "prove_param"
bulwahn@35884
  2215
    THEN f_tac 
bulwahn@35886
  2216
    THEN print_tac options "after prove_param"
bulwahn@32667
  2217
    THEN (REPEAT_DETERM (atac 1))
bulwahn@35888
  2218
    THEN (EVERY (map2 (prove_param options ctxt nargs) ho_args param_derivations))
bulwahn@35884
  2219
    THEN REPEAT_DETERM (rtac @{thm refl} 1)
bulwahn@32667
  2220
  end
bulwahn@32667
  2221
bulwahn@35888
  2222
fun prove_expr options ctxt nargs (premposition : int) (t, deriv) =
bulwahn@32667
  2223
  case strip_comb t of
bulwahn@34935
  2224
    (Const (name, T), args) =>
bulwahn@32667
  2225
      let
bulwahn@34935
  2226
        val mode = head_mode_of deriv
bulwahn@35888
  2227
        val introrule = predfun_intro_of ctxt name mode
bulwahn@34935
  2228
        val param_derivations = param_derivations_of deriv
bulwahn@34935
  2229
        val ho_args = ho_args_of mode args
bulwahn@32667
  2230
      in
bulwahn@35886
  2231
        print_tac options "before intro rule:"
bulwahn@35884
  2232
        THEN rtac introrule 1
bulwahn@35886
  2233
        THEN print_tac options "after intro rule"
bulwahn@32667
  2234
        (* for the right assumption in first position *)
bulwahn@32667
  2235
        THEN rotate_tac premposition 1
bulwahn@33753
  2236
        THEN atac 1
bulwahn@35886
  2237
        THEN print_tac options "parameter goal"
bulwahn@35884
  2238
        (* work with parameter arguments *)
bulwahn@35888
  2239
        THEN (EVERY (map2 (prove_param options ctxt nargs) ho_args param_derivations))
bulwahn@32667
  2240
        THEN (REPEAT_DETERM (atac 1))
bulwahn@32667
  2241
      end
bulwahn@35884
  2242
  | (Free _, _) =>
bulwahn@35886
  2243
    print_tac options "proving parameter call.."
bulwahn@35888
  2244
    THEN Subgoal.FOCUS_PREMS (fn {context = ctxt, params, prems, asms, concl, schematics} =>
bulwahn@35884
  2245
        let
bulwahn@35884
  2246
          val param_prem = nth prems premposition
bulwahn@35884
  2247
          val (param, _) = strip_comb (HOLogic.dest_Trueprop (prop_of param_prem))
bulwahn@35884
  2248
          val prems' = maps dest_conjunct_prem (take nargs prems)
bulwahn@35884
  2249
          fun param_rewrite prem =
bulwahn@35884
  2250
            param = snd (HOLogic.dest_eq (HOLogic.dest_Trueprop (prop_of prem)))
bulwahn@35884
  2251
          val SOME rew_eq = find_first param_rewrite prems'
bulwahn@35884
  2252
          val param_prem' = MetaSimplifier.rewrite_rule
bulwahn@35884
  2253
            (map (fn th => th RS @{thm eq_reflection})
bulwahn@35884
  2254
              [rew_eq RS @{thm sym}, @{thm split_beta}, @{thm fst_conv}, @{thm snd_conv}])
bulwahn@35884
  2255
            param_prem
bulwahn@35884
  2256
        in
bulwahn@35884
  2257
          rtac param_prem' 1
bulwahn@35888
  2258
        end) ctxt 1
bulwahn@35886
  2259
    THEN print_tac options "after prove parameter call"
bulwahn@32667
  2260
bulwahn@34935
  2261
fun SOLVED tac st = FILTER (fn st' => nprems_of st' = nprems_of st - 1) tac st;
bulwahn@32667
  2262
bulwahn@32667
  2263
fun SOLVEDALL tac st = FILTER (fn st' => nprems_of st' = 0) tac st
bulwahn@32667
  2264
bulwahn@35888
  2265
fun check_format ctxt st =
bulwahn@34935
  2266
  let
bulwahn@34935
  2267
    val concl' = Logic.strip_assums_concl (hd (prems_of st))
bulwahn@34935
  2268
    val concl = HOLogic.dest_Trueprop concl'
bulwahn@34935
  2269
    val expr = fst (strip_comb (fst (PredicateCompFuns.dest_Eval concl)))
bulwahn@34935
  2270
    fun valid_expr (Const (@{const_name Predicate.bind}, _)) = true
bulwahn@34935
  2271
      | valid_expr (Const (@{const_name Predicate.single}, _)) = true
bulwahn@34935
  2272
      | valid_expr _ = false
bulwahn@34935
  2273
  in
bulwahn@34935
  2274
    if valid_expr expr then
bulwahn@34935
  2275
      ((*tracing "expression is valid";*) Seq.single st)
bulwahn@34935
  2276
    else
bulwahn@34935
  2277
      ((*tracing "expression is not valid";*) Seq.empty) (*error "check_format: wrong format"*)
bulwahn@34935
  2278
  end
bulwahn@34935
  2279
bulwahn@35888
  2280
fun prove_match options ctxt out_ts =
bulwahn@34935
  2281
  let
bulwahn@35888
  2282
    val thy = ProofContext.theory_of ctxt
bulwahn@34935
  2283
    fun get_case_rewrite t =
bulwahn@34935
  2284
      if (is_constructor thy t) then let
bulwahn@34935
  2285
        val case_rewrites = (#case_rewrites (Datatype.the_info thy
bulwahn@34935
  2286
          ((fst o dest_Type o fastype_of) t)))
bulwahn@39424
  2287
        in fold (union Thm.eq_thm) (case_rewrites :: map get_case_rewrite (snd (strip_comb t))) [] end
bulwahn@34935
  2288
      else []
bulwahn@39424
  2289
    val simprules = insert Thm.eq_thm @{thm "unit.cases"} (insert Thm.eq_thm @{thm "prod.cases"}
bulwahn@39424
  2290
      (fold (union Thm.eq_thm) (map get_case_rewrite out_ts) []))
bulwahn@34935
  2291
  (* replace TRY by determining if it necessary - are there equations when calling compile match? *)
bulwahn@34935
  2292
  in
bulwahn@34935
  2293
     (* make this simpset better! *)
bulwahn@34935
  2294
    asm_full_simp_tac (HOL_basic_ss' addsimps simprules) 1
bulwahn@35886
  2295
    THEN print_tac options "after prove_match:"
bulwahn@35888
  2296
    THEN (DETERM (TRY (EqSubst.eqsubst_tac ctxt [0] [@{thm HOL.if_P}] 1
bulwahn@34935
  2297
           THEN (REPEAT_DETERM (rtac @{thm conjI} 1 THEN (SOLVED (asm_simp_tac HOL_basic_ss' 1))))
bulwahn@35886
  2298
           THEN print_tac options "if condition to be solved:"
bulwahn@35886
  2299
           THEN (SOLVED (asm_simp_tac HOL_basic_ss' 1 THEN print_tac options "after if simp; in SOLVED:"))
bulwahn@34935
  2300
           THEN check_format thy
bulwahn@35886
  2301
           THEN print_tac options "after if simplification - a TRY block")))
bulwahn@35886
  2302
    THEN print_tac options "after if simplification"
bulwahn@34935
  2303
  end;
bulwahn@32667
  2304
bulwahn@32667
  2305
(* corresponds to compile_fun -- maybe call that also compile_sidecond? *)
bulwahn@32667
  2306
bulwahn@35888
  2307
fun prove_sidecond ctxt t =
bulwahn@32667
  2308
  let
bulwahn@32667
  2309
    fun preds_of t nameTs = case strip_comb t of 
bulwahn@32667
  2310
      (f as Const (name, T), args) =>
bulwahn@36994
  2311
        if is_registered ctxt name then (name, T) :: nameTs
bulwahn@32667
  2312
          else fold preds_of args nameTs
bulwahn@32667
  2313
      | _ => nameTs
bulwahn@32667
  2314
    val preds = preds_of t []
bulwahn@32667
  2315
    val defs = map
bulwahn@35888
  2316
      (fn (pred, T) => predfun_definition_of ctxt pred
bulwahn@34935
  2317
        (all_input_of T))
bulwahn@32667
  2318
        preds
bulwahn@32667
  2319
  in 
bulwahn@32667
  2320
    simp_tac (HOL_basic_ss addsimps
bulwahn@39873
  2321
      (@{thms HOL.simp_thms} @ (@{thm eval_pred} :: defs))) 1 
bulwahn@32667
  2322
    (* need better control here! *)
bulwahn@32667
  2323
  end
bulwahn@32667
  2324
bulwahn@35888
  2325
fun prove_clause options ctxt nargs mode (_, clauses) (ts, moded_ps) =
bulwahn@32667
  2326
  let
bulwahn@34935
  2327
    val (in_ts, clause_out_ts) = split_mode mode ts;
bulwahn@32667
  2328
    fun prove_prems out_ts [] =
bulwahn@35888
  2329
      (prove_match options ctxt out_ts)
bulwahn@35886
  2330
      THEN print_tac options "before simplifying assumptions"
bulwahn@32667
  2331
      THEN asm_full_simp_tac HOL_basic_ss' 1
bulwahn@35886
  2332
      THEN print_tac options "before single intro rule"
bulwahn@32667
  2333
      THEN (rtac (if null clause_out_ts then @{thm singleI_unit} else @{thm singleI}) 1)
bulwahn@34935
  2334
    | prove_prems out_ts ((p, deriv) :: ps) =
bulwahn@32667
  2335
      let
bulwahn@32667
  2336
        val premposition = (find_index (equal p) clauses) + nargs
bulwahn@34935
  2337
        val mode = head_mode_of deriv
bulwahn@34935
  2338
        val rest_tac =
bulwahn@34935
  2339
          rtac @{thm bindI} 1
bulwahn@34935
  2340
          THEN (case p of Prem t =>
bulwahn@32667
  2341
            let
bulwahn@34935
  2342
              val (_, us) = strip_comb t
bulwahn@34935
  2343
              val (_, out_ts''') = split_mode mode us
bulwahn@32667
  2344
              val rec_tac = prove_prems out_ts''' ps
bulwahn@32667
  2345
            in
bulwahn@35886
  2346
              print_tac options "before clause:"
bulwahn@34935
  2347
              (*THEN asm_simp_tac HOL_basic_ss 1*)
bulwahn@35886
  2348
              THEN print_tac options "before prove_expr:"
bulwahn@35888
  2349
              THEN prove_expr options ctxt nargs premposition (t, deriv)
bulwahn@35886
  2350
              THEN print_tac options "after prove_expr:"
bulwahn@32667
  2351
              THEN rec_tac
bulwahn@32667
  2352
            end
bulwahn@34935
  2353
          | Negprem t =>
bulwahn@32667
  2354
            let
bulwahn@34935
  2355
              val (t, args) = strip_comb t
bulwahn@34935
  2356
              val (_, out_ts''') = split_mode mode args
bulwahn@32667
  2357
              val rec_tac = prove_prems out_ts''' ps
bulwahn@32667
  2358
              val name = (case strip_comb t of (Const (c, _), _) => SOME c | _ => NONE)
bulwahn@35884
  2359
              val neg_intro_rule =
bulwahn@35888
  2360
                Option.map (fn name =>
bulwahn@35888
  2361
                  the (predfun_neg_intro_of ctxt name mode)) name
bulwahn@34935
  2362
              val param_derivations = param_derivations_of deriv
bulwahn@34935
  2363
              val params = ho_args_of mode args
bulwahn@32667
  2364
            in
bulwahn@35886
  2365
              print_tac options "before prove_neg_expr:"
bulwahn@34935
  2366
              THEN full_simp_tac (HOL_basic_ss addsimps
bulwahn@34935
  2367
                [@{thm split_eta}, @{thm split_beta}, @{thm fst_conv},
bulwahn@34935
  2368
                 @{thm snd_conv}, @{thm pair_collapse}, @{thm Product_Type.split_conv}]) 1
bulwahn@32667
  2369
              THEN (if (is_some name) then
bulwahn@35886
  2370
                  print_tac options "before applying not introduction rule"
bulwahn@35884
  2371
                  THEN rotate_tac premposition 1
bulwahn@35884
  2372
                  THEN etac (the neg_intro_rule) 1
bulwahn@35884
  2373
                  THEN rotate_tac (~premposition) 1
bulwahn@35886
  2374
                  THEN print_tac options "after applying not introduction rule"
bulwahn@35888
  2375
                  THEN (EVERY (map2 (prove_param options ctxt nargs) params param_derivations))
bulwahn@34935
  2376
                  THEN (REPEAT_DETERM (atac 1))
bulwahn@32667
  2377
                else
bulwahn@35884
  2378
                  rtac @{thm not_predI'} 1
bulwahn@35884
  2379
                  (* test: *)
bulwahn@35884
  2380
                  THEN dtac @{thm sym} 1
bulwahn@35884
  2381
                  THEN asm_full_simp_tac (HOL_basic_ss addsimps [@{thm not_False_eq_True}]) 1)
bulwahn@32667
  2382
                  THEN simp_tac (HOL_basic_ss addsimps [@{thm not_False_eq_True}]) 1
bulwahn@32667
  2383
              THEN rec_tac
bulwahn@32667
  2384
            end
bulwahn@32667
  2385
          | Sidecond t =>
bulwahn@34935
  2386
           rtac @{thm if_predI} 1
bulwahn@35886
  2387
           THEN print_tac options "before sidecond:"
bulwahn@35888
  2388
           THEN prove_sidecond ctxt t
bulwahn@35886
  2389
           THEN print_tac options "after sidecond:"
bulwahn@32667
  2390
           THEN prove_prems [] ps)
bulwahn@35888
  2391
      in (prove_match options ctxt out_ts)
bulwahn@32667
  2392
          THEN rest_tac
bulwahn@32667
  2393
      end;
bulwahn@32667
  2394
    val prems_tac = prove_prems in_ts moded_ps
bulwahn@32667
  2395
  in
bulwahn@35886
  2396
    print_tac options "Proving clause..."
bulwahn@33146
  2397
    THEN rtac @{thm bindI} 1
bulwahn@32667
  2398
    THEN rtac @{thm singleI} 1
bulwahn@32667
  2399
    THEN prems_tac
bulwahn@32667
  2400
  end;
bulwahn@32667
  2401
bulwahn@32667
  2402
fun select_sup 1 1 = []
bulwahn@32667
  2403
  | select_sup _ 1 = [rtac @{thm supI1}]
bulwahn@32667
  2404
  | select_sup n i = (rtac @{thm supI2})::(select_sup (n - 1) (i - 1));
bulwahn@32667
  2405
bulwahn@35888
  2406
fun prove_one_direction options ctxt clauses preds pred mode moded_clauses =
bulwahn@32667
  2407
  let
bulwahn@32667
  2408
    val T = the (AList.lookup (op =) preds pred)
bulwahn@34935
  2409
    val nargs = length (binder_types T)
bulwahn@36998
  2410
    val pred_case_rule = the_elim_of ctxt pred
bulwahn@32667
  2411
  in
bulwahn@32667
  2412
    REPEAT_DETERM (CHANGED (rewtac @{thm "split_paired_all"}))
bulwahn@35886
  2413
    THEN print_tac options "before applying elim rule"
bulwahn@35888
  2414
    THEN etac (predfun_elim_of ctxt pred mode) 1
bulwahn@32667
  2415
    THEN etac pred_case_rule 1
bulwahn@35886
  2416
    THEN print_tac options "after applying elim rule"
bulwahn@32667
  2417
    THEN (EVERY (map
bulwahn@32667
  2418
           (fn i => EVERY' (select_sup (length moded_clauses) i) i) 
bulwahn@32667
  2419
             (1 upto (length moded_clauses))))
bulwahn@35888
  2420
    THEN (EVERY (map2 (prove_clause options ctxt nargs mode) clauses moded_clauses))
bulwahn@35886
  2421
    THEN print_tac options "proved one direction"
bulwahn@32667
  2422
  end;
bulwahn@32667
  2423
bulwahn@32667
  2424
(** Proof in the other direction **)
bulwahn@32667
  2425
bulwahn@35888
  2426
fun prove_match2 options ctxt out_ts =
bulwahn@35888
  2427
  let
bulwahn@35888
  2428
    val thy = ProofContext.theory_of ctxt
bulwahn@35888
  2429
    fun split_term_tac (Free _) = all_tac
bulwahn@35888
  2430
      | split_term_tac t =
bulwahn@35888
  2431
        if (is_constructor thy t) then
bulwahn@35888
  2432
          let
bulwahn@35888
  2433
            val info = Datatype.the_info thy ((fst o dest_Type o fastype_of) t)
bulwahn@35888
  2434
            val num_of_constrs = length (#case_rewrites info)
bulwahn@35888
  2435
            val (_, ts) = strip_comb t
bulwahn@35888
  2436
          in
bulwahn@35889
  2437
            print_tac options ("Term " ^ (Syntax.string_of_term ctxt t) ^ 
bulwahn@35889
  2438
              "splitting with rules \n" ^ Display.string_of_thm ctxt (#split_asm info))
bulwahn@35889
  2439
            THEN TRY ((Splitter.split_asm_tac [#split_asm info] 1)
bulwahn@35889
  2440
              THEN (print_tac options "after splitting with split_asm rules")
bulwahn@35888
  2441
            (* THEN (Simplifier.asm_full_simp_tac HOL_basic_ss 1)
bulwahn@35888
  2442
              THEN (DETERM (TRY (etac @{thm Pair_inject} 1)))*)
bulwahn@35888
  2443
              THEN (REPEAT_DETERM_N (num_of_constrs - 1)
bulwahn@35888
  2444
                (etac @{thm botE} 1 ORELSE etac @{thm botE} 2)))
bulwahn@35888
  2445
            THEN (assert_tac (Max_number_of_subgoals 2))
bulwahn@35888
  2446
            THEN (EVERY (map split_term_tac ts))
bulwahn@35888
  2447
          end
bulwahn@35888
  2448
      else all_tac
bulwahn@32667
  2449
  in
bulwahn@33148
  2450
    split_term_tac (HOLogic.mk_tuple out_ts)
bulwahn@33482
  2451
    THEN (DETERM (TRY ((Splitter.split_asm_tac [@{thm "split_if_asm"}] 1)
bulwahn@33482
  2452
    THEN (etac @{thm botE} 2))))
bulwahn@32667
  2453
  end
bulwahn@32667
  2454
bulwahn@32667
  2455
(* VERY LARGE SIMILIRATIY to function prove_param 
bulwahn@32667
  2456
-- join both functions
bulwahn@32667
  2457
*)
bulwahn@32667
  2458
(* TODO: remove function *)
bulwahn@32667
  2459
bulwahn@35888
  2460
fun prove_param2 options ctxt t deriv =
bulwahn@33629
  2461
  let
bulwahn@34935
  2462
    val (f, args) = strip_comb (Envir.eta_contract t)
bulwahn@34935
  2463
    val mode = head_mode_of deriv
bulwahn@34935
  2464
    val param_derivations = param_derivations_of deriv
bulwahn@34935
  2465
    val ho_args = ho_args_of mode args
bulwahn@32667
  2466
    val f_tac = case f of
bulwahn@32667
  2467
        Const (name, T) => full_simp_tac (HOL_basic_ss addsimps 
bulwahn@35888
  2468
           (@{thm eval_pred}::(predfun_definition_of ctxt name mode)
bulwahn@32667
  2469
           :: @{thm "Product_Type.split_conv"}::[])) 1
bulwahn@32667
  2470
      | Free _ => all_tac
bulwahn@32667
  2471
      | _ => error "prove_param2: illegal parameter term"
bulwahn@33629
  2472
  in
bulwahn@35886
  2473
    print_tac options "before simplification in prove_args:"
bulwahn@32667
  2474
    THEN f_tac
bulwahn@35886
  2475
    THEN print_tac options "after simplification in prove_args"
bulwahn@35888
  2476
    THEN EVERY (map2 (prove_param2 options ctxt) ho_args param_derivations)
bulwahn@32667
  2477
  end
bulwahn@32667
  2478
bulwahn@35888
  2479
fun prove_expr2 options ctxt (t, deriv) = 
bulwahn@34935
  2480
  (case strip_comb t of
bulwahn@34935
  2481
      (Const (name, T), args) =>
bulwahn@34935
  2482
        let
bulwahn@34935
  2483
          val mode = head_mode_of deriv
bulwahn@34935
  2484
          val param_derivations = param_derivations_of deriv
bulwahn@34935
  2485
          val ho_args = ho_args_of mode args
bulwahn@34935
  2486
        in
bulwahn@34935
  2487
          etac @{thm bindE} 1
bulwahn@34935
  2488
          THEN (REPEAT_DETERM (CHANGED (rewtac @{thm "split_paired_all"})))
bulwahn@35886
  2489
          THEN print_tac options "prove_expr2-before"
bulwahn@35888
  2490
          THEN etac (predfun_elim_of ctxt name mode) 1
bulwahn@35886
  2491
          THEN print_tac options "prove_expr2"
bulwahn@35888
  2492
          THEN (EVERY (map2 (prove_param2 options ctxt) ho_args param_derivations))
bulwahn@35886
  2493
          THEN print_tac options "finished prove_expr2"
bulwahn@34935
  2494
        end
bulwahn@34935
  2495
      | _ => etac @{thm bindE} 1)
bulwahn@32667
  2496
bulwahn@35888
  2497
fun prove_sidecond2 options ctxt t = let
bulwahn@32667
  2498
  fun preds_of t nameTs = case strip_comb t of 
bulwahn@32667
  2499
    (f as Const (name, T), args) =>
bulwahn@36994
  2500
      if is_registered ctxt name then (name, T) :: nameTs
bulwahn@32667
  2501
        else fold preds_of args nameTs
bulwahn@32667
  2502
    | _ => nameTs
bulwahn@32667
  2503
  val preds = preds_of t []
bulwahn@32667
  2504
  val defs = map
bulwahn@35888
  2505
    (fn (pred, T) => predfun_definition_of ctxt pred 
bulwahn@34935
  2506
      (all_input_of T))
bulwahn@32667
  2507
      preds
bulwahn@32667
  2508
  in
bulwahn@32667
  2509
   (* only simplify the one assumption *)
bulwahn@32667
  2510
   full_simp_tac (HOL_basic_ss' addsimps @{thm eval_pred} :: defs) 1 
bulwahn@32667
  2511
   (* need better control here! *)
bulwahn@35886
  2512
   THEN print_tac options "after sidecond2 simplification"
bulwahn@32667
  2513
   end
bulwahn@32667
  2514
  
bulwahn@35888
  2515
fun prove_clause2 options ctxt pred mode (ts, ps) i =
bulwahn@32667
  2516
  let
bulwahn@36998
  2517
    val pred_intro_rule = nth (intros_of ctxt pred) (i - 1)
bulwahn@34935
  2518
    val (in_ts, clause_out_ts) = split_mode mode ts;
haftmann@37540
  2519
    val split_ss = HOL_basic_ss' addsimps [@{thm split_eta}, @{thm split_beta},
haftmann@37540
  2520
      @{thm fst_conv}, @{thm snd_conv}, @{thm pair_collapse}]
bulwahn@32667
  2521
    fun prove_prems2 out_ts [] =
bulwahn@35886
  2522
      print_tac options "before prove_match2 - last call:"
bulwahn@35888
  2523
      THEN prove_match2 options ctxt out_ts
bulwahn@35886
  2524
      THEN print_tac options "after prove_match2 - last call:"
bulwahn@32667
  2525
      THEN (etac @{thm singleE} 1)
bulwahn@32667
  2526
      THEN (REPEAT_DETERM (etac @{thm Pair_inject} 1))
bulwahn@32667
  2527
      THEN (asm_full_simp_tac HOL_basic_ss' 1)
bulwahn@32667
  2528
      THEN (REPEAT_DETERM (etac @{thm Pair_inject} 1))
bulwahn@32667
  2529
      THEN (asm_full_simp_tac HOL_basic_ss' 1)
bulwahn@35886
  2530
      THEN SOLVED (print_tac options "state before applying intro rule:"
haftmann@37540
  2531
      THEN (rtac pred_intro_rule
bulwahn@32667
  2532
      (* How to handle equality correctly? *)
haftmann@37540
  2533
      THEN_ALL_NEW (K (print_tac options "state before assumption matching")
haftmann@37555
  2534
      THEN' (atac ORELSE' ((CHANGED o asm_full_simp_tac split_ss) THEN' (TRY o atac)))
haftmann@37555
  2535
        THEN' (K (print_tac options "state after pre-simplification:"))
haftmann@37540
  2536
      THEN' (K (print_tac options "state after assumption matching:")))) 1)
bulwahn@34935
  2537
    | prove_prems2 out_ts ((p, deriv) :: ps) =
bulwahn@32667
  2538
      let
bulwahn@34935
  2539
        val mode = head_mode_of deriv
bulwahn@32667
  2540
        val rest_tac = (case p of
bulwahn@34935
  2541
          Prem t =>
bulwahn@32667
  2542
          let
bulwahn@34935
  2543
            val (_, us) = strip_comb t
bulwahn@34935
  2544
            val (_, out_ts''') = split_mode mode us
bulwahn@32667
  2545
            val rec_tac = prove_prems2 out_ts''' ps
bulwahn@32667
  2546
          in
bulwahn@35888
  2547
            (prove_expr2 options ctxt (t, deriv)) THEN rec_tac
bulwahn@32667
  2548
          end
bulwahn@34935
  2549
        | Negprem t =>
bulwahn@32667
  2550
          let
bulwahn@34935
  2551
            val (_, args) = strip_comb t
bulwahn@34935
  2552
            val (_, out_ts''') = split_mode mode args
bulwahn@32667
  2553
            val rec_tac = prove_prems2 out_ts''' ps
bulwahn@32667
  2554
            val name = (case strip_comb t of (Const (c, _), _) => SOME c | _ => NONE)
bulwahn@34935
  2555
            val param_derivations = param_derivations_of deriv
bulwahn@34935
  2556
            val ho_args = ho_args_of mode args
bulwahn@32667
  2557
          in
bulwahn@35886
  2558
            print_tac options "before neg prem 2"
bulwahn@32667
  2559
            THEN etac @{thm bindE} 1
bulwahn@32667
  2560
            THEN (if is_some name then
bulwahn@33482
  2561
                full_simp_tac (HOL_basic_ss addsimps
bulwahn@35888
  2562
                  [predfun_definition_of ctxt (the name) mode]) 1
bulwahn@32667
  2563
                THEN etac @{thm not_predE} 1
bulwahn@32667
  2564
                THEN simp_tac (HOL_basic_ss addsimps [@{thm not_False_eq_True}]) 1
bulwahn@35888
  2565
                THEN (EVERY (map2 (prove_param2 options ctxt) ho_args param_derivations))
bulwahn@32667
  2566
              else
bulwahn@32667
  2567
                etac @{thm not_predE'} 1)
bulwahn@32667
  2568
            THEN rec_tac
bulwahn@32667
  2569
          end 
bulwahn@32667
  2570
        | Sidecond t =>
bulwahn@32667
  2571
          etac @{thm bindE} 1
bulwahn@32667
  2572
          THEN etac @{thm if_predE} 1
bulwahn@35888
  2573
          THEN prove_sidecond2 options ctxt t
bulwahn@32667
  2574
          THEN prove_prems2 [] ps)
bulwahn@35886
  2575
      in print_tac options "before prove_match2:"
bulwahn@35888
  2576
         THEN prove_match2 options ctxt out_ts
bulwahn@35886
  2577
         THEN print_tac options "after prove_match2:"
bulwahn@32667
  2578
         THEN rest_tac
bulwahn@32667
  2579
      end;
bulwahn@32667
  2580
    val prems_tac = prove_prems2 in_ts ps 
bulwahn@32667
  2581
  in
bulwahn@35886
  2582
    print_tac options "starting prove_clause2"
bulwahn@32667
  2583
    THEN etac @{thm bindE} 1
bulwahn@32667
  2584
    THEN (etac @{thm singleE'} 1)
bulwahn@32667
  2585
    THEN (TRY (etac @{thm Pair_inject} 1))
bulwahn@35886
  2586
    THEN print_tac options "after singleE':"
bulwahn@32667
  2587
    THEN prems_tac
bulwahn@32667
  2588
  end;
bulwahn@32667
  2589
 
bulwahn@35888
  2590
fun prove_other_direction options ctxt pred mode moded_clauses =
bulwahn@32667
  2591
  let
bulwahn@32667
  2592
    fun prove_clause clause i =
bulwahn@32667
  2593
      (if i < length moded_clauses then etac @{thm supE} 1 else all_tac)
bulwahn@35888
  2594
      THEN (prove_clause2 options ctxt pred mode clause i)
bulwahn@32667
  2595
  in
bulwahn@32667
  2596
    (DETERM (TRY (rtac @{thm unit.induct} 1)))
bulwahn@32667
  2597
     THEN (REPEAT_DETERM (CHANGED (rewtac @{thm split_paired_all})))
bulwahn@35888
  2598
     THEN (rtac (predfun_intro_of ctxt pred mode) 1)
bulwahn@32667
  2599
     THEN (REPEAT_DETERM (rtac @{thm refl} 2))
bulwahn@33146
  2600
     THEN (if null moded_clauses then
bulwahn@33146
  2601
         etac @{thm botE} 1
bulwahn@33146
  2602
       else EVERY (map2 prove_clause moded_clauses (1 upto (length moded_clauses))))
bulwahn@32667
  2603
  end;
bulwahn@32667
  2604
bulwahn@32667
  2605
(** proof procedure **)
bulwahn@32667
  2606
bulwahn@35324
  2607
fun prove_pred options thy clauses preds pred (pol, mode) (moded_clauses, compiled_term) =
bulwahn@32667
  2608
  let
wenzelm@36633
  2609
    val ctxt = ProofContext.init_global thy
bulwahn@33146
  2610
    val clauses = case AList.lookup (op =) clauses pred of SOME rs => rs | NONE => []
bulwahn@32667
  2611
  in
bulwahn@32667
  2612
    Goal.prove ctxt (Term.add_free_names compiled_term []) [] compiled_term
bulwahn@33143
  2613
      (if not (skip_proof options) then
bulwahn@32667
  2614
        (fn _ =>
bulwahn@32667
  2615
        rtac @{thm pred_iffI} 1
bulwahn@35886
  2616
        THEN print_tac options "after pred_iffI"
bulwahn@35888
  2617
        THEN prove_one_direction options ctxt clauses preds pred mode moded_clauses
bulwahn@35886
  2618
        THEN print_tac options "proved one direction"
bulwahn@35888
  2619
        THEN prove_other_direction options ctxt pred mode moded_clauses
bulwahn@35886
  2620
        THEN print_tac options "proved other direction")
bulwahn@33150
  2621
      else (fn _ => Skip_Proof.cheat_tac thy))
bulwahn@32667
  2622
  end;
bulwahn@32667
  2623
bulwahn@32667
  2624
(* composition of mode inference, definition, compilation and proof *)
bulwahn@32667
  2625
bulwahn@32667
  2626
(** auxillary combinators for table of preds and modes **)
bulwahn@32667
  2627
bulwahn@32667
  2628
fun map_preds_modes f preds_modes_table =
bulwahn@32667
  2629
  map (fn (pred, modes) =>
bulwahn@32667
  2630
    (pred, map (fn (mode, value) => (mode, f pred mode value)) modes)) preds_modes_table
bulwahn@32667
  2631
bulwahn@32667
  2632
fun join_preds_modes table1 table2 =
bulwahn@32667
  2633
  map_preds_modes (fn pred => fn mode => fn value =>
bulwahn@32667
  2634
    (value, the (AList.lookup (op =) (the (AList.lookup (op =) table2 pred)) mode))) table1
bulwahn@36254
  2635
bulwahn@32667
  2636
fun maps_modes preds_modes_table =
bulwahn@32667
  2637
  map (fn (pred, modes) =>
bulwahn@34935
  2638
    (pred, map (fn (mode, value) => value) modes)) preds_modes_table
bulwahn@36254
  2639
bulwahn@36996
  2640
fun compile_preds options comp_modifiers ctxt all_vs param_vs preds moded_clauses =
bulwahn@36996
  2641
  map_preds_modes (fn pred => compile_pred options comp_modifiers ctxt all_vs param_vs pred
bulwahn@33143
  2642
      (the (AList.lookup (op =) preds pred))) moded_clauses
bulwahn@33143
  2643
bulwahn@35324
  2644
fun prove options thy clauses preds moded_clauses compiled_terms =
bulwahn@35324
  2645
  map_preds_modes (prove_pred options thy clauses preds)
bulwahn@32667
  2646
    (join_preds_modes moded_clauses compiled_terms)
bulwahn@32667
  2647
bulwahn@35324
  2648
fun prove_by_skip options thy _ _ _ compiled_terms =
wenzelm@35021
  2649
  map_preds_modes
wenzelm@35021
  2650
    (fn pred => fn mode => fn t => Drule.export_without_context (Skip_Proof.make_thm thy t))
bulwahn@32667
  2651
    compiled_terms
bulwahn@33106
  2652
bulwahn@33376
  2653
(* preparation of introduction rules into special datastructures *)
bulwahn@36994
  2654
fun dest_prem ctxt params t =
bulwahn@33106
  2655
  (case strip_comb t of
bulwahn@34935
  2656
    (v as Free _, ts) => if member (op =) params v then Prem t else Sidecond t
bulwahn@36994
  2657
  | (c as Const (@{const_name Not}, _), [t]) => (case dest_prem ctxt params t of
bulwahn@34935
  2658
      Prem t => Negprem t
bulwahn@33482
  2659
    | Negprem _ => error ("Double negation not allowed in premise: " ^
bulwahn@36994
  2660
        Syntax.string_of_term ctxt (c $ t)) 
bulwahn@33106
  2661
    | Sidecond t => Sidecond (c $ t))
bulwahn@33106
  2662
  | (c as Const (s, _), ts) =>
bulwahn@36994
  2663
    if is_registered ctxt s then Prem t else Sidecond t
bulwahn@33106
  2664
  | _ => Sidecond t)
bulwahn@34935
  2665
bulwahn@39556
  2666
fun prepare_intrs options ctxt prednames intros =
bulwahn@32667
  2667
  let
bulwahn@39556
  2668
    val thy = ProofContext.theory_of ctxt
bulwahn@33126
  2669
    val intrs = map prop_of intros
bulwahn@33146
  2670
    val preds = map (fn c => Const (c, Sign.the_const_type thy c)) prednames
bulwahn@33146
  2671
    val (preds, intrs) = unify_consts thy preds intrs
bulwahn@36994
  2672
    val ([preds, intrs], _) = fold_burrow (Variable.import_terms false) [preds, intrs] ctxt
bulwahn@33126
  2673
    val preds = map dest_Const preds
bulwahn@34935
  2674
    val all_vs = terms_vs intrs
bulwahn@39431
  2675
    fun generate_modes s T =
bulwahn@39431
  2676
      if member (op =) (no_higher_order_predicate options) s then
bulwahn@39431
  2677
        all_smodes_of_typ T
bulwahn@39431
  2678
      else
bulwahn@39431
  2679
        all_modes_of_typ T
bulwahn@35324
  2680
    val all_modes = 
bulwahn@35324
  2681
      map (fn (s, T) =>
bulwahn@39628
  2682
        (s, case proposed_modes options s of
bulwahn@39875
  2683
            SOME ms => check_matches_type ctxt s T ms
bulwahn@39431
  2684
          | NONE => generate_modes s T)) preds
bulwahn@34935
  2685
    val params =
bulwahn@34935
  2686
      case intrs of
bulwahn@33146
  2687
        [] =>
bulwahn@33146
  2688
          let
bulwahn@34935
  2689
            val T = snd (hd preds)
bulwahn@34935
  2690
            val paramTs =
bulwahn@39532
  2691
              ho_argsT_of_typ (binder_types T)
bulwahn@33482
  2692
            val param_names = Name.variant_list [] (map (fn i => "p" ^ string_of_int i)
bulwahn@33482
  2693
              (1 upto length paramTs))
bulwahn@34935
  2694
          in
bulwahn@34935
  2695
            map2 (curry Free) param_names paramTs
bulwahn@34935
  2696
          end
bulwahn@35324
  2697
      | (intr :: _) =>
bulwahn@35324
  2698
        let
bulwahn@35324
  2699
          val (p, args) = strip_comb (HOLogic.dest_Trueprop (Logic.strip_imp_concl intr)) 
bulwahn@35324
  2700
        in
bulwahn@39628
  2701
          ho_args_of_typ (snd (dest_Const p)) args
bulwahn@35324
  2702
        end
bulwahn@34935
  2703
    val param_vs = map (fst o dest_Free) params
bulwahn@34935
  2704
    fun add_clause intr clauses =
bulwahn@32667
  2705
      let
bulwahn@34935
  2706
        val (Const (name, T), ts) = strip_comb (HOLogic.dest_Trueprop (Logic.strip_imp_concl intr))
bulwahn@36994
  2707
        val prems = map (dest_prem ctxt params o HOLogic.dest_Trueprop) (Logic.strip_imp_prems intr)
bulwahn@32667
  2708
      in
bulwahn@34935
  2709
        AList.update op = (name, these (AList.lookup op = clauses name) @
bulwahn@34935
  2710
          [(ts, prems)]) clauses
bulwahn@34935
  2711
      end;
bulwahn@34935
  2712
    val clauses = fold add_clause intrs []
bulwahn@34935
  2713
  in
bulwahn@35324
  2714
    (preds, all_vs, param_vs, all_modes, clauses)
bulwahn@34935
  2715
  end;
bulwahn@32667
  2716
bulwahn@33376
  2717
(* sanity check of introduction rules *)
bulwahn@34935
  2718
(* TODO: rethink check with new modes *)
bulwahn@34935
  2719
(*
bulwahn@33106
  2720
fun check_format_of_intro_rule thy intro =
bulwahn@33106
  2721
  let
bulwahn@33106
  2722
    val concl = Logic.strip_imp_concl (prop_of intro)
bulwahn@33106
  2723
    val (p, args) = strip_comb (HOLogic.dest_Trueprop concl)
bulwahn@33629
  2724
    val params = fst (chop (nparams_of thy (fst (dest_Const p))) args)
bulwahn@33106
  2725
    fun check_arg arg = case HOLogic.strip_tupleT (fastype_of arg) of
bulwahn@33106
  2726
      (Ts as _ :: _ :: _) =>
bulwahn@33629
  2727
        if length (HOLogic.strip_tuple arg) = length Ts then
bulwahn@33629
  2728
          true
bulwahn@33114
  2729
        else
bulwahn@33629
  2730
          error ("Format of introduction rule is invalid: tuples must be expanded:"
bulwahn@33629
  2731
          ^ (Syntax.string_of_term_global thy arg) ^ " in " ^
bulwahn@33629
  2732
          (Display.string_of_thm_global thy intro)) 
bulwahn@33106
  2733
      | _ => true
bulwahn@33106
  2734
    val prems = Logic.strip_imp_prems (prop_of intro)
bulwahn@34935
  2735
    fun check_prem (Prem t) = forall check_arg args
bulwahn@34935
  2736
      | check_prem (Negprem t) = forall check_arg args
bulwahn@33106
  2737
      | check_prem _ = true
bulwahn@33106
  2738
  in
bulwahn@33106
  2739
    forall check_arg args andalso
bulwahn@33106
  2740
    forall (check_prem o dest_prem thy params o HOLogic.dest_Trueprop) prems
bulwahn@33106
  2741
  end
bulwahn@34935
  2742
*)
bulwahn@33124
  2743
(*
bulwahn@33124
  2744
fun check_intros_elim_match thy prednames =
bulwahn@33124
  2745
  let
bulwahn@33124
  2746
    fun check predname =
bulwahn@33124
  2747
      let
bulwahn@33124
  2748
        val intros = intros_of thy predname
bulwahn@33124
  2749
        val elim = the_elim_of thy predname
bulwahn@33124
  2750
        val nparams = nparams_of thy predname
bulwahn@33124
  2751
        val elim' =
wenzelm@35021
  2752
          (Drule.export_without_context o Skip_Proof.make_thm thy)
wenzelm@36633
  2753
          (mk_casesrule (ProofContext.init_global thy) nparams intros)
bulwahn@33124
  2754
      in
bulwahn@33124
  2755
        if not (Thm.equiv_thm (elim, elim')) then
bulwahn@33124
  2756
          error "Introduction and elimination rules do not match!"
bulwahn@33124
  2757
        else true
bulwahn@33124
  2758
      end
bulwahn@33124
  2759
  in forall check prednames end
bulwahn@33124
  2760
*)
bulwahn@33113
  2761
bulwahn@33376
  2762
(* create code equation *)
bulwahn@33376
  2763
bulwahn@36998
  2764
fun add_code_equations ctxt preds result_thmss =
bulwahn@33376
  2765
  let
bulwahn@33629
  2766
    fun add_code_equation (predname, T) (pred, result_thms) =
bulwahn@33376
  2767
      let
bulwahn@34935
  2768
        val full_mode = fold_rev (curry Fun) (map (K Input) (binder_types T)) Bool
bulwahn@33376
  2769
      in
bulwahn@36994
  2770
        if member (op =) (modes_of Pred ctxt predname) full_mode then
bulwahn@33376
  2771
          let
bulwahn@33376
  2772
            val Ts = binder_types T
bulwahn@33376
  2773
            val arg_names = Name.variant_list []
bulwahn@33376
  2774
              (map (fn i => "x" ^ string_of_int i) (1 upto length Ts))
bulwahn@33629
  2775
            val args = map2 (curry Free) arg_names Ts
bulwahn@36994
  2776
            val predfun = Const (function_name_of Pred ctxt predname full_mode,
bulwahn@33376
  2777
              Ts ---> PredicateCompFuns.mk_predT @{typ unit})
bulwahn@33754
  2778
            val rhs = @{term Predicate.holds} $ (list_comb (predfun, args))
bulwahn@33376
  2779
            val eq_term = HOLogic.mk_Trueprop
bulwahn@33376
  2780
              (HOLogic.mk_eq (list_comb (Const (predname, T), args), rhs))
bulwahn@35888
  2781
            val def = predfun_definition_of ctxt predname full_mode
wenzelm@33448
  2782
            val tac = fn _ => Simplifier.simp_tac
bulwahn@33754
  2783
              (HOL_basic_ss addsimps [def, @{thm holds_eq}, @{thm eval_pred}]) 1
bulwahn@35888
  2784
            val eq = Goal.prove ctxt arg_names [] eq_term tac
bulwahn@33376
  2785
          in
bulwahn@33376
  2786
            (pred, result_thms @ [eq])
bulwahn@33376
  2787
          end
bulwahn@33376
  2788
        else
bulwahn@33376
  2789
          (pred, result_thms)
bulwahn@33376
  2790
      end
bulwahn@33376
  2791
  in
bulwahn@33629
  2792
    map2 add_code_equation preds result_thmss
bulwahn@33376
  2793
  end
bulwahn@33376
  2794
bulwahn@32667
  2795
(** main function of predicate compiler **)
bulwahn@32667
  2796
bulwahn@33330
  2797
datatype steps = Steps of
bulwahn@33330
  2798
  {
bulwahn@35324
  2799
  define_functions : options -> (string * typ) list -> string * (bool * mode) list -> theory -> theory,
bulwahn@35324
  2800
  prove : options -> theory -> (string * (term list * indprem list) list) list -> (string * typ) list
bulwahn@33330
  2801
    -> moded_clause list pred_mode_table -> term pred_mode_table -> thm pred_mode_table,
bulwahn@36998
  2802
  add_code_equations : Proof.context -> (string * typ) list
bulwahn@33376
  2803
    -> (string * thm list) list -> (string * thm list) list,
bulwahn@34935
  2804
  comp_modifiers : Comp_Mod.comp_modifiers,
bulwahn@39994
  2805
  use_generators : bool,
bulwahn@33330
  2806
  qname : bstring
bulwahn@33330
  2807
  }
bulwahn@33330
  2808
bulwahn@35324
  2809
fun add_equations_of steps mode_analysis_options options prednames thy =
bulwahn@32667
  2810
  let
bulwahn@33330
  2811
    fun dest_steps (Steps s) = s
bulwahn@35879
  2812
    val compilation = Comp_Mod.compilation (#comp_modifiers (dest_steps steps))
bulwahn@36998
  2813
    val ctxt = ProofContext.init_global thy
bulwahn@33482
  2814
    val _ = print_step options
bulwahn@35879
  2815
      ("Starting predicate compiler (compilation: " ^ string_of_compilation compilation
bulwahn@35879
  2816
        ^ ") for predicates " ^ commas prednames ^ "...")
bulwahn@33124
  2817
      (*val _ = check_intros_elim_match thy prednames*)
bulwahn@33114
  2818
      (*val _ = map (check_format_of_intro_rule thy) (maps (intros_of thy) prednames)*)
bulwahn@35324
  2819
    val _ =
bulwahn@35324
  2820
      if show_intermediate_results options then
bulwahn@36998
  2821
        tracing (commas (map (Display.string_of_thm ctxt) (maps (intros_of ctxt) prednames)))
bulwahn@35324
  2822
      else ()
bulwahn@35324
  2823
    val (preds, all_vs, param_vs, all_modes, clauses) =
bulwahn@39556
  2824
      prepare_intrs options ctxt prednames (maps (intros_of ctxt) prednames)
bulwahn@33123
  2825
    val _ = print_step options "Infering modes..."
bulwahn@39500
  2826
    val (lookup_mode, lookup_neg_mode, needs_random) = (modes_of compilation ctxt,
bulwahn@39500
  2827
      modes_of (negative_compilation_of compilation) ctxt, needs_random ctxt)
bulwahn@39500
  2828
    val ((moded_clauses, needs_random), errors) =
bulwahn@37000
  2829
      Output.cond_timeit (!Quickcheck.timing) "Infering modes"
bulwahn@36251
  2830
      (fn _ => infer_modes mode_analysis_options
bulwahn@39500
  2831
        options (lookup_mode, lookup_neg_mode, needs_random) ctxt preds all_modes param_vs clauses)
bulwahn@39500
  2832
    val thy' = fold (fn (s, ms) => set_needs_random s ms) needs_random thy
bulwahn@33132
  2833
    val modes = map (fn (p, mps) => (p, map fst mps)) moded_clauses
bulwahn@33619
  2834
    val _ = check_expected_modes preds options modes
bulwahn@39431
  2835
    val _ = check_proposed_modes preds options modes errors
bulwahn@36995
  2836
    val _ = print_modes options modes
bulwahn@33123
  2837
    val _ = print_step options "Defining executable functions..."
bulwahn@36252
  2838
    val thy'' =
bulwahn@36261
  2839
      Output.cond_timeit (!Quickcheck.timing) "Defining executable functions..."
bulwahn@36252
  2840
      (fn _ => fold (#define_functions (dest_steps steps) options preds) modes thy'
bulwahn@36252
  2841
      |> Theory.checkpoint)
bulwahn@36996
  2842
    val ctxt'' = ProofContext.init_global thy''
bulwahn@33123
  2843
    val _ = print_step options "Compiling equations..."
bulwahn@32667
  2844
    val compiled_terms =
bulwahn@36261
  2845
      Output.cond_timeit (!Quickcheck.timing) "Compiling equations...." (fn _ =>
bulwahn@36254
  2846
        compile_preds options
bulwahn@36996
  2847
          (#comp_modifiers (dest_steps steps)) ctxt'' all_vs param_vs preds moded_clauses)
bulwahn@36996
  2848
    val _ = print_compiled_terms options ctxt'' compiled_terms
bulwahn@33123
  2849
    val _ = print_step options "Proving equations..."
bulwahn@35324
  2850
    val result_thms =
bulwahn@36261
  2851
      Output.cond_timeit (!Quickcheck.timing) "Proving equations...." (fn _ =>
bulwahn@36252
  2852
      #prove (dest_steps steps) options thy'' clauses preds moded_clauses compiled_terms)
bulwahn@36998
  2853
    val result_thms' = #add_code_equations (dest_steps steps) ctxt'' preds
bulwahn@33376
  2854
      (maps_modes result_thms)
bulwahn@33330
  2855
    val qname = #qname (dest_steps steps)
bulwahn@32667
  2856
    val attrib = fn thy => Attrib.attribute_i thy (Attrib.internal (K (Thm.declaration_attribute
bulwahn@32667
  2857
      (fn thm => Context.mapping (Code.add_eqn thm) I))))
bulwahn@36252
  2858
    val thy''' =
bulwahn@36261
  2859
      Output.cond_timeit (!Quickcheck.timing) "Setting code equations...." (fn _ =>
wenzelm@39814
  2860
      fold (fn (name, result_thms) => fn thy => snd (Global_Theory.add_thmss
bulwahn@32667
  2861
      [((Binding.qualify true (Long_Name.base_name name) (Binding.name qname), result_thms),
bulwahn@32667
  2862
        [attrib thy ])] thy))
bulwahn@36252
  2863
      result_thms' thy'' |> Theory.checkpoint)
bulwahn@32667
  2864
  in
bulwahn@34935
  2865
    thy'''
bulwahn@32667
  2866
  end
bulwahn@32667
  2867
bulwahn@32667
  2868
fun extend' value_of edges_of key (G, visited) =
bulwahn@32667
  2869
  let
bulwahn@32667
  2870
    val (G', v) = case try (Graph.get_node G) key of
bulwahn@32667
  2871
        SOME v => (G, v)
bulwahn@32667
  2872
      | NONE => (Graph.new_node (key, value_of key) G, value_of key)
bulwahn@33482
  2873
    val (G'', visited') = fold (extend' value_of edges_of)
bulwahn@33482
  2874
      (subtract (op =) visited (edges_of (key, v)))
bulwahn@33326
  2875
      (G', key :: visited)
bulwahn@32667
  2876
  in
bulwahn@32667
  2877
    (fold (Graph.add_edge o (pair key)) (edges_of (key, v)) G'', visited')
bulwahn@32667
  2878
  end;
bulwahn@32667
  2879
bulwahn@32667
  2880
fun extend value_of edges_of key G = fst (extend' value_of edges_of key (G, [])) 
bulwahn@32667
  2881
  
bulwahn@33132
  2882
fun gen_add_equations steps options names thy =
bulwahn@32667
  2883
  let
bulwahn@33330
  2884
    fun dest_steps (Steps s) = s
bulwahn@34935
  2885
    val defined = defined_functions (Comp_Mod.compilation (#comp_modifiers (dest_steps steps)))
bulwahn@36994
  2886
    val ctxt = ProofContext.init_global thy
bulwahn@33482
  2887
    val thy' = thy
bulwahn@36998
  2888
      |> PredData.map (fold (extend (fetch_pred_data ctxt) (depending_preds_of ctxt)) names)
bulwahn@32667
  2889
      |> Theory.checkpoint;
bulwahn@32667
  2890
    fun strong_conn_of gr keys =
bulwahn@32667
  2891
      Graph.strong_conn (Graph.subgraph (member (op =) (Graph.all_succs gr keys)) gr)
bulwahn@32667
  2892
    val scc = strong_conn_of (PredData.get thy') names
bulwahn@39881
  2893
    fun preprocess name thy =
bulwahn@39881
  2894
      PredData.map (Graph.map_node name (map_pred_data (apfst (fn (rules, preprocessed) =>
bulwahn@39881
  2895
        if preprocessed then (rules, preprocessed)
bulwahn@39881
  2896
        else
bulwahn@39881
  2897
          let
bulwahn@39881
  2898
            val (named_intros, SOME elim) = rules
bulwahn@39881
  2899
            val named_intros' = map (apsnd (preprocess_intro thy)) named_intros
bulwahn@39881
  2900
            val pred = Const (name, Sign.the_const_type thy name)
bulwahn@39881
  2901
            val ctxt = ProofContext.init_global thy
bulwahn@39881
  2902
            val elim_t = mk_casesrule ctxt pred (map snd named_intros')
bulwahn@39881
  2903
            val nparams = (case try (Inductive.the_inductive ctxt) name of
bulwahn@39881
  2904
                SOME (_, result) => length (Inductive.params_of (#raw_induct result))
bulwahn@39881
  2905
              | NONE => 0)
bulwahn@39881
  2906
            val elim' = prove_casesrule ctxt (pred, (elim, 0)) elim_t
bulwahn@39881
  2907
          in
bulwahn@39881
  2908
            ((named_intros', SOME elim'), true)
bulwahn@39881
  2909
          end))))
bulwahn@39881
  2910
        thy
bulwahn@39881
  2911
    val thy'' = fold preprocess (flat scc) thy'
bulwahn@39881
  2912
    val thy''' = fold_rev
bulwahn@32667
  2913
      (fn preds => fn thy =>
bulwahn@36994
  2914
        if not (forall (defined (ProofContext.init_global thy)) preds) then
bulwahn@35324
  2915
          let
bulwahn@39994
  2916
            val mode_analysis_options = {use_generators = #use_generators (dest_steps steps),
bulwahn@35324
  2917
              reorder_premises =
bulwahn@35324
  2918
                not (no_topmost_reordering options andalso not (null (inter (op =) preds names))),
bulwahn@39994
  2919
              infer_pos_and_neg_modes = #use_generators (dest_steps steps)}
bulwahn@35324
  2920
          in
bulwahn@35324
  2921
            add_equations_of steps mode_analysis_options options preds thy
bulwahn@35324
  2922
          end
bulwahn@33483
  2923
        else thy)
bulwahn@39881
  2924
      scc thy'' |> Theory.checkpoint
bulwahn@39881
  2925
  in thy''' end
bulwahn@35879
  2926
bulwahn@34935
  2927
val add_equations = gen_add_equations
bulwahn@35324
  2928
  (Steps {
bulwahn@35324
  2929
  define_functions =
bulwahn@35324
  2930
    fn options => fn preds => fn (s, modes) =>
bulwahn@35324
  2931
      create_definitions
bulwahn@35324
  2932
      options preds (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
bulwahn@34935
  2933
  prove = prove,
bulwahn@34935
  2934
  add_code_equations = add_code_equations,
bulwahn@34935
  2935
  comp_modifiers = predicate_comp_modifiers,
bulwahn@39994
  2936
  use_generators = false,
bulwahn@34935
  2937
  qname = "equation"})
bulwahn@33143
  2938
bulwahn@33134
  2939
val add_depth_limited_equations = gen_add_equations
bulwahn@35879
  2940
  (Steps {
bulwahn@35879
  2941
  define_functions =
bulwahn@35879
  2942
    fn options => fn preds => fn (s, modes) =>
bulwahn@35879
  2943
    define_functions depth_limited_comp_modifiers PredicateCompFuns.compfuns
bulwahn@35879
  2944
    options preds (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
bulwahn@32667
  2945
  prove = prove_by_skip,
bulwahn@34935
  2946
  add_code_equations = K (K I),
bulwahn@35879
  2947
  comp_modifiers = depth_limited_comp_modifiers,
bulwahn@39994
  2948
  use_generators = false,
bulwahn@33330
  2949
  qname = "depth_limited_equation"})
bulwahn@35879
  2950
bulwahn@33473
  2951
val add_annotated_equations = gen_add_equations
bulwahn@35324
  2952
  (Steps {
bulwahn@35324
  2953
  define_functions =
bulwahn@35324
  2954
    fn options => fn preds => fn (s, modes) =>
bulwahn@35324
  2955
      define_functions annotated_comp_modifiers PredicateCompFuns.compfuns options preds
bulwahn@35324
  2956
      (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
bulwahn@33473
  2957
  prove = prove_by_skip,
bulwahn@34935
  2958
  add_code_equations = K (K I),
bulwahn@34935
  2959
  comp_modifiers = annotated_comp_modifiers,
bulwahn@39994
  2960
  use_generators = false,
bulwahn@33473
  2961
  qname = "annotated_equation"})
bulwahn@35880
  2962
bulwahn@35880
  2963
val add_random_equations = gen_add_equations
bulwahn@35880
  2964
  (Steps {
bulwahn@35880
  2965
  define_functions =
bulwahn@35880
  2966
    fn options => fn preds => fn (s, modes) =>
bulwahn@35880
  2967
      define_functions random_comp_modifiers PredicateCompFuns.compfuns options preds
bulwahn@35880
  2968
      (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
bulwahn@35880
  2969
  comp_modifiers = random_comp_modifiers,
bulwahn@32667
  2970
  prove = prove_by_skip,
bulwahn@34935
  2971
  add_code_equations = K (K I),
bulwahn@39994
  2972
  use_generators = true,
bulwahn@33375
  2973
  qname = "random_equation"})
bulwahn@35880
  2974
bulwahn@35881
  2975
val add_depth_limited_random_equations = gen_add_equations
bulwahn@35881
  2976
  (Steps {
bulwahn@35881
  2977
  define_functions =
bulwahn@35881
  2978
    fn options => fn preds => fn (s, modes) =>
bulwahn@35881
  2979
      define_functions depth_limited_random_comp_modifiers PredicateCompFuns.compfuns options preds
bulwahn@35881
  2980
      (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
bulwahn@35881
  2981
  comp_modifiers = depth_limited_random_comp_modifiers,
bulwahn@35881
  2982
  prove = prove_by_skip,
bulwahn@35881
  2983
  add_code_equations = K (K I),
bulwahn@39994
  2984
  use_generators = true,
bulwahn@35881
  2985
  qname = "depth_limited_random_equation"})
bulwahn@35881
  2986
bulwahn@34935
  2987
val add_dseq_equations = gen_add_equations
bulwahn@35324
  2988
  (Steps {
bulwahn@35324
  2989
  define_functions =
bulwahn@35324
  2990
  fn options => fn preds => fn (s, modes) =>
bulwahn@35324
  2991
    define_functions dseq_comp_modifiers DSequence_CompFuns.compfuns
bulwahn@35324
  2992
    options preds (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
bulwahn@34935
  2993
  prove = prove_by_skip,
bulwahn@34935
  2994
  add_code_equations = K (K I),
bulwahn@34935
  2995
  comp_modifiers = dseq_comp_modifiers,
bulwahn@39994
  2996
  use_generators = false,
bulwahn@34935
  2997
  qname = "dseq_equation"})
bulwahn@34935
  2998
bulwahn@34935
  2999
val add_random_dseq_equations = gen_add_equations
bulwahn@35324
  3000
  (Steps {
bulwahn@35324
  3001
  define_functions =
bulwahn@35324
  3002
    fn options => fn preds => fn (s, modes) =>
bulwahn@35324
  3003
    let
bulwahn@35324
  3004
      val pos_modes = map_filter (fn (true, m) => SOME m | _ => NONE) modes
bulwahn@35324
  3005
      val neg_modes = map_filter (fn (false, m) => SOME m | _ => NONE) modes
bulwahn@35324
  3006
    in define_functions pos_random_dseq_comp_modifiers Random_Sequence_CompFuns.compfuns
bulwahn@35324
  3007
      options preds (s, pos_modes)
bulwahn@35324
  3008
      #> define_functions neg_random_dseq_comp_modifiers Random_Sequence_CompFuns.compfuns
bulwahn@35324
  3009
      options preds (s, neg_modes)
bulwahn@35324
  3010
    end,
bulwahn@34935
  3011
  prove = prove_by_skip,
bulwahn@34935
  3012
  add_code_equations = K (K I),
bulwahn@35324
  3013
  comp_modifiers = pos_random_dseq_comp_modifiers,
bulwahn@39994
  3014
  use_generators = true,
bulwahn@34935
  3015
  qname = "random_dseq_equation"})
bulwahn@34935
  3016
bulwahn@36012
  3017
val add_new_random_dseq_equations = gen_add_equations
bulwahn@36012
  3018
  (Steps {
bulwahn@36012
  3019
  define_functions =
bulwahn@36012
  3020
    fn options => fn preds => fn (s, modes) =>
bulwahn@36012
  3021
    let
bulwahn@36012
  3022
      val pos_modes = map_filter (fn (true, m) => SOME m | _ => NONE) modes
bulwahn@36012
  3023
      val neg_modes = map_filter (fn (false, m) => SOME m | _ => NONE) modes
bulwahn@36012
  3024
    in define_functions new_pos_random_dseq_comp_modifiers New_Pos_Random_Sequence_CompFuns.compfuns
bulwahn@36012
  3025
      options preds (s, pos_modes)
bulwahn@36012
  3026
      #> define_functions new_neg_random_dseq_comp_modifiers New_Neg_Random_Sequence_CompFuns.compfuns
bulwahn@36012
  3027
      options preds (s, neg_modes)
bulwahn@36012
  3028
    end,
bulwahn@36012
  3029
  prove = prove_by_skip,
bulwahn@36012
  3030
  add_code_equations = K (K I),
bulwahn@36012
  3031
  comp_modifiers = new_pos_random_dseq_comp_modifiers,
bulwahn@39994
  3032
  use_generators = true,
bulwahn@36012
  3033
  qname = "new_random_dseq_equation"})
bulwahn@32667
  3034
bulwahn@32667
  3035
(** user interface **)
bulwahn@32667
  3036
bulwahn@32667
  3037
(* code_pred_intro attribute *)
bulwahn@32667
  3038
bulwahn@39767
  3039
fun attrib' f opt_case_name =
bulwahn@39767
  3040
  Thm.declaration_attribute (fn thm => Context.mapping (f (opt_case_name, thm)) I);
bulwahn@32667
  3041
bulwahn@39767
  3042
val code_pred_intro_attrib = attrib' add_intro NONE;
bulwahn@32667
  3043
bulwahn@32668
  3044
bulwahn@32668
  3045
(*FIXME
bulwahn@32668
  3046
- Naming of auxiliary rules necessary?
bulwahn@32668
  3047
*)
bulwahn@32668
  3048
bulwahn@32668
  3049
val setup = PredData.put (Graph.empty) #>
bulwahn@39767
  3050
  Attrib.setup @{binding code_pred_intro} (Scan.lift (Scan.option Args.name) >> attrib' add_intro)
bulwahn@32668
  3051
    "adding alternative introduction rules for code generation of inductive predicates"
bulwahn@32667
  3052
wenzelm@33522
  3053
(* TODO: make Theory_Data to Generic_Data & remove duplication of local theory and theory *)
wenzelm@39032
  3054
(* FIXME ... this is important to avoid changing the background theory below *)
bulwahn@33132
  3055
fun generic_code_pred prep_const options raw_const lthy =
bulwahn@32667
  3056
  let
bulwahn@32667
  3057
    val thy = ProofContext.theory_of lthy
bulwahn@32667
  3058
    val const = prep_const thy raw_const
bulwahn@36994
  3059
    val ctxt = ProofContext.init_global thy
wenzelm@39032
  3060
    val lthy' = Local_Theory.background_theory (PredData.map
bulwahn@36998
  3061
        (extend (fetch_pred_data ctxt) (depending_preds_of ctxt) const)) lthy
bulwahn@32667
  3062
    val thy' = ProofContext.theory_of lthy'
bulwahn@36998
  3063
    val ctxt' = ProofContext.init_global thy'
bulwahn@36998
  3064
    val preds = Graph.all_succs (PredData.get thy') [const] |> filter_out (has_elim ctxt')
bulwahn@32667
  3065
    fun mk_cases const =
bulwahn@32667
  3066
      let
bulwahn@39532
  3067
        val T = Sign.the_const_type thy' const
bulwahn@33146
  3068
        val pred = Const (const, T)
bulwahn@36998
  3069
        val intros = intros_of ctxt' const
bulwahn@34935
  3070
      in mk_casesrule lthy' pred intros end  
bulwahn@32667
  3071
    val cases_rules = map mk_cases preds
bulwahn@32667
  3072
    val cases =
bulwahn@39767
  3073
      map2 (fn pred_name => fn case_rule => Rule_Cases.Case {fixes = [],
bulwahn@39876
  3074
        assumes = ("that", tl (Logic.strip_imp_prems case_rule))
bulwahn@39767
  3075
          :: (map_filter (fn (fact_name, fact) => Option.map (rpair [fact]) fact_name)
bulwahn@39876
  3076
            ((SOME (Long_Name.base_name pred_name ^ ".prems") :: names_of ctxt' pred_name) ~~ Logic.strip_imp_prems case_rule)),
bulwahn@39767
  3077
        binds = [], cases = []}) preds cases_rules
bulwahn@32667
  3078
    val case_env = map2 (fn p => fn c => (Long_Name.base_name p, SOME c)) preds cases
bulwahn@32667
  3079
    val lthy'' = lthy'
bulwahn@39767
  3080
      |> fold Variable.auto_fixes cases_rules
bulwahn@32667
  3081
      |> ProofContext.add_cases true case_env
bulwahn@32667
  3082
    fun after_qed thms goal_ctxt =
bulwahn@32667
  3083
      let
bulwahn@32667
  3084
        val global_thms = ProofContext.export goal_ctxt
wenzelm@36633
  3085
          (ProofContext.init_global (ProofContext.theory_of goal_ctxt)) (map the_single thms)
bulwahn@32667
  3086
      in
wenzelm@39032
  3087
        goal_ctxt |> Local_Theory.background_theory (fold set_elim global_thms #>
bulwahn@34935
  3088
          ((case compilation options of
bulwahn@34935
  3089
             Pred => add_equations
bulwahn@34935
  3090
           | DSeq => add_dseq_equations
bulwahn@35879
  3091
           | Pos_Random_DSeq => add_random_dseq_equations
bulwahn@35879
  3092
           | Depth_Limited => add_depth_limited_equations
bulwahn@35880
  3093
           | Random => add_random_equations
bulwahn@35881
  3094
           | Depth_Limited_Random => add_depth_limited_random_equations
bulwahn@36012
  3095
           | New_Pos_Random_DSeq => add_new_random_dseq_equations
bulwahn@34935
  3096
           | compilation => error ("Compilation not supported")
bulwahn@34935
  3097
           ) options [const]))
bulwahn@33144
  3098
      end
bulwahn@32667
  3099
  in
wenzelm@36334
  3100
    Proof.theorem NONE after_qed (map (single o (rpair [])) cases_rules) lthy''
bulwahn@32667
  3101
  end;
bulwahn@32667
  3102
bulwahn@32667
  3103
val code_pred = generic_code_pred (K I);
bulwahn@32667
  3104
val code_pred_cmd = generic_code_pred Code.read_const
bulwahn@32667
  3105
bulwahn@32667
  3106
(* transformation for code generation *)
bulwahn@32667
  3107
haftmann@39634
  3108
structure Pred_Result = Proof_Data (
haftmann@39634
  3109
  type T = unit -> term Predicate.pred
haftmann@39634
  3110
  fun init _ () = error "Pred_Result"
haftmann@39634
  3111
);
haftmann@39634
  3112
val put_pred_result = Pred_Result.put;
haftmann@39634
  3113
haftmann@39634
  3114
structure Pred_Random_Result = Proof_Data (
haftmann@39634
  3115
  type T = unit -> int * int -> term Predicate.pred * (int * int)
haftmann@39634
  3116
  fun init _ () = error "Pred_Random_Result"
haftmann@39634
  3117
);
haftmann@39634
  3118
val put_pred_random_result = Pred_Random_Result.put;
haftmann@39634
  3119
haftmann@39634
  3120
structure Dseq_Result = Proof_Data (
haftmann@39634
  3121
  type T = unit -> term DSequence.dseq
haftmann@39634
  3122
  fun init _ () = error "Dseq_Result"
haftmann@39634
  3123
);
haftmann@39634
  3124
val put_dseq_result = Dseq_Result.put;
haftmann@39634
  3125
haftmann@39634
  3126
structure Dseq_Random_Result = Proof_Data (
haftmann@39634
  3127
  type T = unit -> int -> int -> int * int -> term DSequence.dseq * (int * int)
haftmann@39634
  3128
  fun init _ () = error "Dseq_Random_Result"
haftmann@39634
  3129
);
haftmann@39634
  3130
val put_dseq_random_result = Dseq_Random_Result.put;
haftmann@39634
  3131
haftmann@39634
  3132
structure Lseq_Random_Result = Proof_Data (
haftmann@39634
  3133
  type T = unit -> int -> int -> int * int -> int -> term Lazy_Sequence.lazy_sequence
haftmann@39634
  3134
  fun init _ () = error "Lseq_Random_Result"
haftmann@39634
  3135
);
haftmann@39634
  3136
val put_lseq_random_result = Lseq_Random_Result.put;
haftmann@39634
  3137
haftmann@39634
  3138
structure Lseq_Random_Stats_Result = Proof_Data (
haftmann@39634
  3139
  type T = unit -> int -> int -> int * int -> int -> (term * int) Lazy_Sequence.lazy_sequence
haftmann@39634
  3140
  fun init _ () = error "Lseq_Random_Stats_Result"
haftmann@39634
  3141
);
haftmann@39634
  3142
val put_lseq_random_stats_result = Lseq_Random_Stats_Result.put;
bulwahn@32667
  3143
bulwahn@32667
  3144
(*FIXME turn this into an LCF-guarded preprocessor for comprehensions*)
bulwahn@36994
  3145
fun analyze_compr ctxt compfuns param_user_modes (compilation, arguments) t_compr =
bulwahn@32667
  3146
  let
bulwahn@34935
  3147
    val all_modes_of = all_modes_of compilation
bulwahn@32667
  3148
    val split = case t_compr of (Const (@{const_name Collect}, _) $ t) => t
bulwahn@36994
  3149
      | _ => error ("Not a set comprehension: " ^ Syntax.string_of_term ctxt t_compr);
bulwahn@32667
  3150
    val (body, Ts, fp) = HOLogic.strip_psplits split;
bulwahn@34935
  3151
    val output_names = Name.variant_list (Term.add_free_names body [])
bulwahn@34935
  3152
      (map (fn i => "x" ^ string_of_int i) (1 upto length Ts))
haftmann@34950
  3153
    val output_frees = map2 (curry Free) output_names (rev Ts)
bulwahn@34935
  3154
    val body = subst_bounds (output_frees, body)
haftmann@34950
  3155
    val T_compr = HOLogic.mk_ptupleT fp Ts
bulwahn@34935
  3156
    val output_tuple = HOLogic.mk_ptuple fp T_compr (rev output_frees)
bulwahn@36025
  3157
    val (pred as Const (name, T), all_args) =
bulwahn@36025
  3158
      case strip_comb body of
bulwahn@36025
  3159
        (Const (name, T), all_args) => (Const (name, T), all_args)
bulwahn@36994
  3160
      | (head, _) => error ("Not a constant: " ^ Syntax.string_of_term ctxt head)
bulwahn@34935
  3161
  in
bulwahn@36994
  3162
    if defined_functions compilation ctxt name then
bulwahn@32668
  3163
      let
haftmann@37366
  3164
        fun extract_mode (Const (@{const_name Pair}, _) $ t1 $ t2) = Pair (extract_mode t1, extract_mode t2)
bulwahn@34935
  3165
          | extract_mode (Free (x, _)) = if member (op =) output_names x then Output else Input
bulwahn@34935
  3166
          | extract_mode _ = Input
bulwahn@34935
  3167
        val user_mode = fold_rev (curry Fun) (map extract_mode all_args) Bool
bulwahn@34935
  3168
        fun valid modes1 modes2 =
bulwahn@34935
  3169
          case int_ord (length modes1, length modes2) of
bulwahn@34935
  3170
            GREATER => error "Not enough mode annotations"
bulwahn@34935
  3171
          | LESS => error "Too many mode annotations"
bulwahn@34935
  3172
          | EQUAL => forall (fn (m, NONE) => true | (m, SOME m2) => eq_mode (m, m2))
bulwahn@34935
  3173
            (modes1 ~~ modes2)
bulwahn@34935
  3174
        fun mode_instance_of (m1, m2) =
bulwahn@34935
  3175
          let
bulwahn@34935
  3176
            fun instance_of (Fun _, Input) = true
bulwahn@34935
  3177
              | instance_of (Input, Input) = true
bulwahn@34935
  3178
              | instance_of (Output, Output) = true
bulwahn@34935
  3179
              | instance_of (Pair (m1, m2), Pair (m1', m2')) =
bulwahn@34935
  3180
                  instance_of  (m1, m1') andalso instance_of (m2, m2')
bulwahn@34935
  3181
              | instance_of (Pair (m1, m2), Input) =
bulwahn@34935
  3182
                  instance_of (m1, Input) andalso instance_of (m2, Input)
bulwahn@34935
  3183
              | instance_of (Pair (m1, m2), Output) =
bulwahn@34935
  3184
                  instance_of (m1, Output) andalso instance_of (m2, Output)
bulwahn@36993
  3185
              | instance_of (Input, Pair (m1, m2)) =
bulwahn@36993
  3186
                  instance_of (Input, m1) andalso instance_of (Input, m2)
bulwahn@36993
  3187
              | instance_of (Output, Pair (m1, m2)) =
bulwahn@36993
  3188
                  instance_of (Output, m1) andalso instance_of (Output, m2)
bulwahn@34935
  3189
              | instance_of _ = false
bulwahn@34935
  3190
          in forall instance_of (strip_fun_mode m1 ~~ strip_fun_mode m2) end
bulwahn@36994
  3191
        val derivs = all_derivations_of ctxt (all_modes_of ctxt) [] body
bulwahn@34935
  3192
          |> filter (fn (d, missing_vars) =>
bulwahn@34935
  3193
            let
bulwahn@34935
  3194
              val (p_mode :: modes) = collect_context_modes d
bulwahn@34935
  3195
            in
bulwahn@34935
  3196
              null missing_vars andalso
bulwahn@34935
  3197
              mode_instance_of (p_mode, user_mode) andalso
bulwahn@34935
  3198
              the_default true (Option.map (valid modes) param_user_modes)
bulwahn@34935
  3199
            end)
bulwahn@34935
  3200
          |> map fst
bulwahn@34935
  3201
        val deriv = case derivs of
bulwahn@34935
  3202
            [] => error ("No mode possible for comprehension "
bulwahn@36994
  3203
                    ^ Syntax.string_of_term ctxt t_compr)
bulwahn@34935
  3204
          | [d] => d
bulwahn@34935
  3205
          | d :: _ :: _ => (warning ("Multiple modes possible for comprehension "
bulwahn@36994
  3206
                    ^ Syntax.string_of_term ctxt t_compr); d);
bulwahn@34935
  3207
        val (_, outargs) = split_mode (head_mode_of deriv) all_args
bulwahn@34935
  3208
        val additional_arguments =
bulwahn@34935
  3209
          case compilation of
bulwahn@34935
  3210
            Pred => []
bulwahn@35880
  3211
          | Random => map (HOLogic.mk_number @{typ "code_numeral"}) arguments @
bulwahn@35880
  3212
            [@{term "(1, 1) :: code_numeral * code_numeral"}]
bulwahn@34935
  3213
          | Annotated => []
bulwahn@35879
  3214
          | Depth_Limited => [HOLogic.mk_number @{typ "code_numeral"} (hd arguments)]
bulwahn@35881
  3215
          | Depth_Limited_Random => map (HOLogic.mk_number @{typ "code_numeral"}) arguments @
bulwahn@35881
  3216
            [@{term "(1, 1) :: code_numeral * code_numeral"}]
bulwahn@34935
  3217
          | DSeq => []
bulwahn@35879
  3218
          | Pos_Random_DSeq => []
bulwahn@36014
  3219
          | New_Pos_Random_DSeq => []
bulwahn@34935
  3220
        val comp_modifiers =
bulwahn@34935
  3221
          case compilation of
bulwahn@34935
  3222
            Pred => predicate_comp_modifiers
bulwahn@35879
  3223
          | Random => random_comp_modifiers
bulwahn@34935
  3224
          | Depth_Limited => depth_limited_comp_modifiers
bulwahn@35881
  3225
          | Depth_Limited_Random => depth_limited_random_comp_modifiers
bulwahn@35879
  3226
          (*| Annotated => annotated_comp_modifiers*)
bulwahn@34935
  3227
          | DSeq => dseq_comp_modifiers
bulwahn@35879
  3228
          | Pos_Random_DSeq => pos_random_dseq_comp_modifiers
bulwahn@36014
  3229
          | New_Pos_Random_DSeq => new_pos_random_dseq_comp_modifiers
bulwahn@36994
  3230
        val t_pred = compile_expr comp_modifiers ctxt
bulwahn@39872
  3231
          (body, deriv) [] additional_arguments;
bulwahn@34935
  3232
        val T_pred = dest_predT compfuns (fastype_of t_pred)
bulwahn@34935
  3233
        val arrange = split_lambda (HOLogic.mk_tuple outargs) output_tuple
bulwahn@34935
  3234
      in
bulwahn@34935
  3235
        if null outargs then t_pred else mk_map compfuns T_pred T_compr arrange t_pred
bulwahn@34935
  3236
      end
bulwahn@34935
  3237
    else
bulwahn@34935
  3238
      error "Evaluation with values is not possible because compilation with code_pred was not invoked"
bulwahn@34935
  3239
  end
bulwahn@32667
  3240
bulwahn@36994
  3241
fun eval ctxt stats param_user_modes (options as (compilation, arguments)) k t_compr =
bulwahn@32667
  3242
  let
bulwahn@36021
  3243
    fun count xs x =
bulwahn@36021
  3244
      let
bulwahn@36021
  3245
        fun count' i [] = i
bulwahn@36021
  3246
          | count' i (x' :: xs) = if x = x' then count' (i + 1) xs else count' i xs
bulwahn@36021
  3247
      in count' 0 xs end
bulwahn@36021
  3248
    fun accumulate xs = map (fn x => (x, count xs x)) (sort int_ord (distinct (op =) xs))
bulwahn@34935
  3249
    val compfuns =
bulwahn@34935
  3250
      case compilation of
bulwahn@35880
  3251
        Random => PredicateCompFuns.compfuns
bulwahn@34935
  3252
      | DSeq => DSequence_CompFuns.compfuns
bulwahn@35324
  3253
      | Pos_Random_DSeq => Random_Sequence_CompFuns.compfuns
bulwahn@36014
  3254
      | New_Pos_Random_DSeq => New_Pos_Random_Sequence_CompFuns.compfuns
bulwahn@34935
  3255
      | _ => PredicateCompFuns.compfuns
bulwahn@36994
  3256
    val t = analyze_compr ctxt compfuns param_user_modes options t_compr;
bulwahn@33137
  3257
    val T = dest_predT compfuns (fastype_of t);
bulwahn@36021
  3258
    val t' =
bulwahn@36021
  3259
      if stats andalso compilation = New_Pos_Random_DSeq then
bulwahn@36021
  3260
        mk_map compfuns T (HOLogic.mk_prodT (HOLogic.termT, @{typ code_numeral}))
bulwahn@36021
  3261
          (absdummy (T, HOLogic.mk_prod (HOLogic.term_of_const T $ Bound 0,
bulwahn@36021
  3262
            @{term Code_Numeral.of_nat} $ (HOLogic.size_const T $ Bound 0)))) t
bulwahn@36021
  3263
      else
bulwahn@36021
  3264
        mk_map compfuns T HOLogic.termT (HOLogic.term_of_const T) t
bulwahn@36994
  3265
    val thy = ProofContext.theory_of ctxt
bulwahn@36021
  3266
    val (ts, statistics) =
bulwahn@34935
  3267
      case compilation of
bulwahn@35880
  3268
       (* Random =>
bulwahn@34935
  3269
          fst (Predicate.yieldn k
bulwahn@34935
  3270
          (Code_Eval.eval NONE ("Predicate_Compile_Core.random_eval_ref", random_eval_ref)
bulwahn@33137
  3271
            (fn proc => fn g => fn s => g s |>> Predicate.map proc) thy t' []
bulwahn@35880
  3272
            |> Random_Engine.run))*)
bulwahn@35880
  3273
        Pos_Random_DSeq =>
bulwahn@34935
  3274
          let
bulwahn@34935
  3275
            val [nrandom, size, depth] = arguments
bulwahn@34935
  3276
          in
bulwahn@36021
  3277
            rpair NONE (fst (DSequence.yieldn k
haftmann@39711
  3278
              (Code_Runtime.dynamic_value_strict (Dseq_Random_Result.get, put_dseq_random_result, "Predicate_Compile_Core.put_dseq_random_result")
haftmann@39711
  3279
                thy NONE (fn proc => fn g => fn nrandom => fn size => fn s => g nrandom size s |>> DSequence.map proc)
haftmann@39711
  3280
                  t' [] nrandom size
bulwahn@34935
  3281
                |> Random_Engine.run)
bulwahn@36021
  3282
              depth true))
bulwahn@34935
  3283
          end
bulwahn@34935
  3284
      | DSeq =>
bulwahn@36021
  3285
          rpair NONE (fst (DSequence.yieldn k
haftmann@39711
  3286
            (Code_Runtime.dynamic_value_strict (Dseq_Result.get, put_dseq_result, "Predicate_Compile_Core.put_dseq_result")
haftmann@39711
  3287
              thy NONE DSequence.map t' []) (the_single arguments) true))
bulwahn@36014
  3288
      | New_Pos_Random_DSeq =>
bulwahn@36014
  3289
          let
bulwahn@36014
  3290
            val [nrandom, size, depth] = arguments
bulwahn@36014
  3291
            val seed = Random_Engine.next_seed ()
bulwahn@36014
  3292
          in
bulwahn@36021
  3293
            if stats then
bulwahn@36021
  3294
              apsnd (SOME o accumulate) (split_list
bulwahn@36021
  3295
              (fst (Lazy_Sequence.yieldn k
haftmann@39711
  3296
                (Code_Runtime.dynamic_value_strict
haftmann@39634
  3297
                  (Lseq_Random_Stats_Result.get, put_lseq_random_stats_result, "Predicate_Compile_Core.put_lseq_random_stats_result")
haftmann@39711
  3298
                  thy NONE
bulwahn@36021
  3299
                  (fn proc => fn g => fn nrandom => fn size => fn s => fn depth => g nrandom size s depth
haftmann@36533
  3300
                    |> Lazy_Sequence.mapa (apfst proc))
haftmann@39711
  3301
                    t' [] nrandom size seed depth))))
bulwahn@36021
  3302
            else rpair NONE
bulwahn@36021
  3303
              (fst (Lazy_Sequence.yieldn k
haftmann@39711
  3304
                (Code_Runtime.dynamic_value_strict
haftmann@39634
  3305
                  (Lseq_Random_Result.get, put_lseq_random_result, "Predicate_Compile_Core.put_lseq_random_result")
haftmann@39711
  3306
                  thy NONE 
bulwahn@36021
  3307
                  (fn proc => fn g => fn nrandom => fn size => fn s => fn depth => g nrandom size s depth
haftmann@36533
  3308
                    |> Lazy_Sequence.mapa proc)
haftmann@39711
  3309
                    t' [] nrandom size seed depth)))
bulwahn@36014
  3310
          end
bulwahn@34935
  3311
      | _ =>
bulwahn@36021
  3312
          rpair NONE (fst (Predicate.yieldn k
haftmann@39711
  3313
            (Code_Runtime.dynamic_value_strict (Pred_Result.get, put_pred_result, "Predicate_Compile_Core.put_pred_result")
haftmann@39711
  3314
              thy NONE Predicate.map t' [])))
bulwahn@36021
  3315
  in ((T, ts), statistics) end;
bulwahn@36021
  3316
bulwahn@36021
  3317
fun values ctxt param_user_modes ((raw_expected, stats), comp_options) k t_compr =
bulwahn@32667
  3318
  let
bulwahn@36994
  3319
    val ((T, ts), statistics) = eval ctxt stats param_user_modes comp_options k t_compr
bulwahn@34935
  3320
    val setT = HOLogic.mk_setT T
bulwahn@34935
  3321
    val elems = HOLogic.mk_set T ts
bulwahn@33476
  3322
    val cont = Free ("...", setT)
bulwahn@34935
  3323
    (* check expected values *)
bulwahn@34935
  3324
    val () =
bulwahn@34935
  3325
      case raw_expected of
bulwahn@34935
  3326
        NONE => ()
bulwahn@34935
  3327
      | SOME s =>
bulwahn@34935
  3328
        if eq_set (op =) (HOLogic.dest_set (Syntax.read_term ctxt s), ts) then ()
bulwahn@34935
  3329
        else
bulwahn@34935
  3330
          error ("expected and computed values do not match:\n" ^
bulwahn@34935
  3331
            "expected values: " ^ Syntax.string_of_term ctxt (Syntax.read_term ctxt s) ^ "\n" ^
bulwahn@34935
  3332
            "computed values: " ^ Syntax.string_of_term ctxt elems ^ "\n")
bulwahn@34935
  3333
  in
bulwahn@36021
  3334
    (if k = ~1 orelse length ts < k then elems
bulwahn@36021
  3335
    else Const (@{const_abbrev Set.union}, setT --> setT --> setT) $ elems $ cont, statistics)
bulwahn@32667
  3336
  end;
bulwahn@33623
  3337
bulwahn@33479
  3338
fun values_cmd print_modes param_user_modes options k raw_t state =
bulwahn@32667
  3339
  let
bulwahn@34935
  3340
    val ctxt = Toplevel.context_of state
bulwahn@34935
  3341
    val t = Syntax.read_term ctxt raw_t
bulwahn@36021
  3342
    val (t', stats) = values ctxt param_user_modes options k t
bulwahn@34935
  3343
    val ty' = Term.type_of t'
bulwahn@34935
  3344
    val ctxt' = Variable.auto_fixes t' ctxt
bulwahn@36021
  3345
    val pretty_stat =
bulwahn@36021
  3346
      case stats of
bulwahn@36021
  3347
          NONE => []
bulwahn@36021
  3348
        | SOME xs =>
bulwahn@36021
  3349
          let
bulwahn@36021
  3350
            val total = fold (curry (op +)) (map snd xs) 0
bulwahn@36021
  3351
            fun pretty_entry (s, n) =
bulwahn@36021
  3352
              [Pretty.str "size", Pretty.brk 1,
bulwahn@36021
  3353
               Pretty.str (string_of_int s), Pretty.str ":", Pretty.brk 1,
bulwahn@36021
  3354
               Pretty.str (string_of_int n), Pretty.fbrk]
bulwahn@36021
  3355
          in
bulwahn@36021
  3356
            [Pretty.fbrk, Pretty.str "Statistics:", Pretty.fbrk,
bulwahn@36021
  3357
             Pretty.str "total:", Pretty.brk 1, Pretty.str (string_of_int total), Pretty.fbrk]
bulwahn@36021
  3358
             @ maps pretty_entry xs
bulwahn@36021
  3359
          end
wenzelm@37154
  3360
    val p = Print_Mode.with_modes print_modes (fn () =>
bulwahn@36021
  3361
      Pretty.block ([Pretty.quote (Syntax.pretty_term ctxt' t'), Pretty.fbrk,
bulwahn@36021
  3362
        Pretty.str "::", Pretty.brk 1, Pretty.quote (Syntax.pretty_typ ctxt' ty')]
bulwahn@36021
  3363
        @ pretty_stat)) ();
bulwahn@32667
  3364
  in Pretty.writeln p end;
bulwahn@32667
  3365
bulwahn@32667
  3366
end;