src/HOL/Tools/Predicate_Compile/predicate_compile_aux.ML
author wenzelm
Tue Feb 10 14:48:26 2015 +0100 (2015-02-10)
changeset 59498 50b60f501b05
parent 59484 a130ae7a9398
child 59582 0fbed69ff081
permissions -rw-r--r--
proper context for resolve_tac, eresolve_tac, dresolve_tac, forward_tac etc.;
occasionally clarified use of context;
wenzelm@33265
     1
(*  Title:      HOL/Tools/Predicate_Compile/predicate_compile_aux.ML
wenzelm@33265
     2
    Author:     Lukas Bulwahn, TU Muenchen
bulwahn@33250
     3
wenzelm@33265
     4
Auxilary functions for predicate compiler.
bulwahn@33250
     5
*)
bulwahn@33250
     6
bulwahn@36047
     7
signature PREDICATE_COMPILE_AUX =
bulwahn@36047
     8
sig
bulwahn@36047
     9
  val find_indices : ('a -> bool) -> 'a list -> int list
bulwahn@36047
    10
  (* mode *)
bulwahn@36047
    11
  datatype mode = Bool | Input | Output | Pair of mode * mode | Fun of mode * mode
bulwahn@36047
    12
  val eq_mode : mode * mode -> bool
bulwahn@39311
    13
  val mode_ord: mode * mode -> order
bulwahn@36047
    14
  val list_fun_mode : mode list -> mode
bulwahn@36047
    15
  val strip_fun_mode : mode -> mode list
bulwahn@36047
    16
  val dest_fun_mode : mode -> mode list
bulwahn@36047
    17
  val dest_tuple_mode : mode -> mode list
bulwahn@36047
    18
  val all_modes_of_typ : typ -> mode list
bulwahn@36047
    19
  val all_smodes_of_typ : typ -> mode list
bulwahn@36047
    20
  val fold_map_aterms_prodT : ('a -> 'a -> 'a) -> (typ -> 'b -> 'a * 'b) -> typ -> 'b -> 'a * 'b
bulwahn@36047
    21
  val map_filter_prod : (term -> term option) -> term -> term option
bulwahn@36047
    22
  val replace_ho_args : mode -> term list -> term list -> term list
bulwahn@36047
    23
  val ho_arg_modes_of : mode -> mode list
bulwahn@36047
    24
  val ho_argsT_of : mode -> typ list -> typ list
bulwahn@36047
    25
  val ho_args_of : mode -> term list -> term list
bulwahn@39299
    26
  val ho_args_of_typ : typ -> term list -> term list
bulwahn@39299
    27
  val ho_argsT_of_typ : typ list -> typ list
bulwahn@36047
    28
  val split_map_mode : (mode -> term -> term option * term option)
bulwahn@36047
    29
    -> mode -> term list -> term list * term list
bulwahn@36047
    30
  val split_map_modeT : (mode -> typ -> typ option * typ option)
bulwahn@36047
    31
    -> mode -> typ list -> typ list * typ list
bulwahn@36047
    32
  val split_mode : mode -> term list -> term list * term list
bulwahn@40139
    33
  val split_modeT : mode -> typ list -> typ list * typ list
bulwahn@36047
    34
  val string_of_mode : mode -> string
bulwahn@36047
    35
  val ascii_string_of_mode : mode -> string
bulwahn@36047
    36
  (* premises *)
bulwahn@36047
    37
  datatype indprem = Prem of term | Negprem of term | Sidecond of term
bulwahn@36047
    38
    | Generator of (string * typ)
bulwahn@36251
    39
  val dest_indprem : indprem -> term
bulwahn@36254
    40
  val map_indprem : (term -> term) -> indprem -> indprem
bulwahn@36047
    41
  (* general syntactic functions *)
bulwahn@36047
    42
  val is_equationlike : thm -> bool
bulwahn@36047
    43
  val is_pred_equation : thm -> bool
bulwahn@36047
    44
  val is_intro : string -> thm -> bool
bulwahn@36047
    45
  val is_predT : typ -> bool
blanchet@55399
    46
  val get_constrs : theory -> (string * (int * string)) list
bulwahn@36047
    47
  val is_constrt : theory -> term -> bool
bulwahn@36047
    48
  val is_constr : Proof.context -> string -> bool
bulwahn@42094
    49
  val strip_ex : term -> (string * typ) list * term
bulwahn@36047
    50
  val focus_ex : term -> Name.context -> ((string * typ) list * term) * Name.context
bulwahn@36047
    51
  val strip_all : term -> (string * typ) list * term
bulwahn@40101
    52
  val strip_intro_concl : thm -> term * term list
bulwahn@36047
    53
  (* introduction rule combinators *)
bulwahn@36047
    54
  val map_atoms : (term -> term) -> term -> term
bulwahn@36047
    55
  val fold_atoms : (term -> 'a -> 'a) -> term -> 'a -> 'a
bulwahn@36047
    56
  val fold_map_atoms : (term -> 'a -> term * 'a) -> term -> 'a -> term * 'a
bulwahn@36047
    57
  val maps_premises : (term -> term list) -> term -> term
bulwahn@36047
    58
  val map_concl : (term -> term) -> term -> term
bulwahn@36047
    59
  val map_term : theory -> (term -> term) -> thm -> thm
bulwahn@36047
    60
  (* split theorems of case expressions *)
bulwahn@36047
    61
  val prepare_split_thm : Proof.context -> thm -> thm
bulwahn@36047
    62
  val find_split_thm : theory -> term -> thm option
bulwahn@36047
    63
  (* datastructures and setup for generic compilation *)
bulwahn@36047
    64
  datatype compilation_funs = CompilationFuns of {
bulwahn@45461
    65
    mk_monadT : typ -> typ,
bulwahn@45461
    66
    dest_monadT : typ -> typ,
bulwahn@45461
    67
    mk_empty : typ -> term,
bulwahn@36047
    68
    mk_single : term -> term,
bulwahn@36047
    69
    mk_bind : term * term -> term,
bulwahn@45461
    70
    mk_plus : term * term -> term,
bulwahn@36047
    71
    mk_if : term -> term,
bulwahn@36049
    72
    mk_iterate_upto : typ -> term * term * term -> term,
bulwahn@36047
    73
    mk_not : term -> term,
bulwahn@36047
    74
    mk_map : typ -> typ -> term -> term -> term
bulwahn@36047
    75
  };
bulwahn@45461
    76
  val mk_monadT : compilation_funs -> typ -> typ
bulwahn@45461
    77
  val dest_monadT : compilation_funs -> typ -> typ
bulwahn@45461
    78
  val mk_empty : compilation_funs -> typ -> term
bulwahn@36047
    79
  val mk_single : compilation_funs -> term -> term
bulwahn@36047
    80
  val mk_bind : compilation_funs -> term * term -> term
bulwahn@45461
    81
  val mk_plus : compilation_funs -> term * term -> term
bulwahn@36047
    82
  val mk_if : compilation_funs -> term -> term
bulwahn@36049
    83
  val mk_iterate_upto : compilation_funs -> typ -> term * term * term -> term
bulwahn@36047
    84
  val mk_not : compilation_funs -> term -> term
bulwahn@36047
    85
  val mk_map : compilation_funs -> typ -> typ -> term -> term -> term
bulwahn@36047
    86
  val funT_of : compilation_funs -> mode -> typ -> typ
bulwahn@36047
    87
  (* Different compilations *)
bulwahn@36047
    88
  datatype compilation = Pred | Depth_Limited | Random | Depth_Limited_Random | DSeq | Annotated
wenzelm@55437
    89
    | Pos_Random_DSeq | Neg_Random_DSeq | New_Pos_Random_DSeq | New_Neg_Random_DSeq
bulwahn@45450
    90
    | Pos_Generator_DSeq | Neg_Generator_DSeq | Pos_Generator_CPS | Neg_Generator_CPS
bulwahn@36047
    91
  val negative_compilation_of : compilation -> compilation
bulwahn@36047
    92
  val compilation_for_polarity : bool -> compilation -> compilation
wenzelm@55437
    93
  val is_depth_limited_compilation : compilation -> bool
bulwahn@36047
    94
  val string_of_compilation : compilation -> string
bulwahn@36047
    95
  val compilation_names : (string * compilation) list
bulwahn@36047
    96
  val non_random_compilations : compilation list
bulwahn@36047
    97
  val random_compilations : compilation list
bulwahn@36047
    98
  (* Different options for compiler *)
wenzelm@55437
    99
  datatype options = Options of {
bulwahn@36047
   100
    expected_modes : (string * mode list) option,
bulwahn@39382
   101
    proposed_modes : (string * mode list) list,
bulwahn@36047
   102
    proposed_names : ((string * mode) * string) list,
bulwahn@36047
   103
    show_steps : bool,
bulwahn@36047
   104
    show_proof_trace : bool,
bulwahn@36047
   105
    show_intermediate_results : bool,
bulwahn@36047
   106
    show_mode_inference : bool,
bulwahn@36047
   107
    show_modes : bool,
bulwahn@36047
   108
    show_compilation : bool,
bulwahn@36047
   109
    show_caught_failures : bool,
bulwahn@39383
   110
    show_invalid_clauses : bool,
bulwahn@36047
   111
    skip_proof : bool,
bulwahn@36047
   112
    no_topmost_reordering : bool,
bulwahn@36047
   113
    function_flattening : bool,
bulwahn@36047
   114
    fail_safe_function_flattening : bool,
bulwahn@36248
   115
    specialise : bool,
bulwahn@36047
   116
    no_higher_order_predicate : string list,
bulwahn@36047
   117
    inductify : bool,
bulwahn@36254
   118
    detect_switches : bool,
bulwahn@40048
   119
    smart_depth_limiting : bool,
bulwahn@36047
   120
    compilation : compilation
bulwahn@36047
   121
  };
bulwahn@36047
   122
  val expected_modes : options -> (string * mode list) option
bulwahn@39382
   123
  val proposed_modes : options -> string -> mode list option
bulwahn@36047
   124
  val proposed_names : options -> string -> mode -> string option
bulwahn@36047
   125
  val show_steps : options -> bool
bulwahn@36047
   126
  val show_proof_trace : options -> bool
bulwahn@36047
   127
  val show_intermediate_results : options -> bool
bulwahn@36047
   128
  val show_mode_inference : options -> bool
bulwahn@36047
   129
  val show_modes : options -> bool
bulwahn@36047
   130
  val show_compilation : options -> bool
bulwahn@36047
   131
  val show_caught_failures : options -> bool
bulwahn@39383
   132
  val show_invalid_clauses : options -> bool
bulwahn@36047
   133
  val skip_proof : options -> bool
bulwahn@36047
   134
  val no_topmost_reordering : options -> bool
bulwahn@36047
   135
  val function_flattening : options -> bool
bulwahn@36047
   136
  val fail_safe_function_flattening : options -> bool
bulwahn@36248
   137
  val specialise : options -> bool
bulwahn@36047
   138
  val no_higher_order_predicate : options -> string list
bulwahn@36047
   139
  val is_inductify : options -> bool
bulwahn@36254
   140
  val detect_switches : options -> bool
bulwahn@40048
   141
  val smart_depth_limiting : options -> bool
bulwahn@36047
   142
  val compilation : options -> compilation
bulwahn@36047
   143
  val default_options : options
bulwahn@36047
   144
  val bool_options : string list
bulwahn@36047
   145
  val print_step : options -> string -> unit
bulwahn@39657
   146
  (* conversions *)
bulwahn@39657
   147
  val imp_prems_conv : conv -> conv
bulwahn@36047
   148
  (* simple transformations *)
bulwahn@39787
   149
  val split_conjuncts_in_assms : Proof.context -> thm -> thm
bulwahn@40052
   150
  val dest_conjunct_prem : thm -> thm list
bulwahn@36047
   151
  val expand_tuples : theory -> thm -> thm
bulwahn@39802
   152
  val case_betapply : theory -> term -> term
bulwahn@36047
   153
  val eta_contract_ho_arguments : theory -> thm -> thm
bulwahn@36047
   154
  val remove_equalities : theory -> thm -> thm
bulwahn@36246
   155
  val remove_pointless_clauses : thm -> thm list
bulwahn@36246
   156
  val peephole_optimisation : theory -> thm -> thm option
bulwahn@40101
   157
  (* auxillary *)
bulwahn@40101
   158
  val unify_consts : theory -> term list -> term list -> (term list * term list)
bulwahn@40101
   159
  val mk_casesrule : Proof.context -> term -> thm list -> term
bulwahn@40101
   160
  val preprocess_intro : theory -> thm -> thm
wenzelm@55437
   161
bulwahn@39541
   162
  val define_quickcheck_predicate :
bulwahn@40052
   163
    term -> theory -> (((string * typ) * (string * typ) list) * thm) * theory
wenzelm@55440
   164
end
bulwahn@34948
   165
bulwahn@36047
   166
structure Predicate_Compile_Aux : PREDICATE_COMPILE_AUX =
bulwahn@33250
   167
struct
bulwahn@33250
   168
haftmann@59484
   169
val no_constr = [@{const_name STR}];
haftmann@59484
   170
bulwahn@34948
   171
(* general functions *)
bulwahn@34948
   172
bulwahn@34948
   173
fun comb_option f (SOME x1, SOME x2) = SOME (f (x1, x2))
bulwahn@34948
   174
  | comb_option f (NONE, SOME x2) = SOME x2
bulwahn@34948
   175
  | comb_option f (SOME x1, NONE) = SOME x1
bulwahn@34948
   176
  | comb_option f (NONE, NONE) = NONE
bulwahn@34948
   177
bulwahn@35885
   178
fun map2_optional f (x :: xs) (y :: ys) = f x (SOME y) :: (map2_optional f xs ys)
bulwahn@34948
   179
  | map2_optional f (x :: xs) [] = (f x NONE) :: (map2_optional f xs [])
bulwahn@34948
   180
  | map2_optional f [] [] = []
bulwahn@34948
   181
bulwahn@34948
   182
fun find_indices f xs =
haftmann@46662
   183
  map_filter (fn (i, true) => SOME i | (_, false) => NONE) (map_index (apsnd f) xs)
bulwahn@33328
   184
bulwahn@33328
   185
(* mode *)
bulwahn@33328
   186
bulwahn@34948
   187
datatype mode = Bool | Input | Output | Pair of mode * mode | Fun of mode * mode
bulwahn@33619
   188
bulwahn@33623
   189
(* equality of instantiatedness with respect to equivalences:
bulwahn@33623
   190
  Pair Input Input == Input and Pair Output Output == Output *)
bulwahn@34948
   191
fun eq_mode (Fun (m1, m2), Fun (m3, m4)) = eq_mode (m1, m3) andalso eq_mode (m2, m4)
bulwahn@34948
   192
  | eq_mode (Pair (m1, m2), Pair (m3, m4)) = eq_mode (m1, m3) andalso eq_mode (m2, m4)
bulwahn@34948
   193
  | eq_mode (Pair (m1, m2), Input) = eq_mode (m1, Input) andalso eq_mode (m2, Input)
bulwahn@34948
   194
  | eq_mode (Pair (m1, m2), Output) = eq_mode (m1, Output) andalso eq_mode (m2, Output)
bulwahn@34948
   195
  | eq_mode (Input, Pair (m1, m2)) = eq_mode (Input, m1) andalso eq_mode (Input, m2)
bulwahn@34948
   196
  | eq_mode (Output, Pair (m1, m2)) = eq_mode (Output, m1) andalso eq_mode (Output, m2)
bulwahn@34948
   197
  | eq_mode (Input, Input) = true
bulwahn@34948
   198
  | eq_mode (Output, Output) = true
bulwahn@34948
   199
  | eq_mode (Bool, Bool) = true
bulwahn@34948
   200
  | eq_mode _ = false
bulwahn@33623
   201
bulwahn@39311
   202
fun mode_ord (Input, Output) = LESS
bulwahn@39311
   203
  | mode_ord (Output, Input) = GREATER
bulwahn@39311
   204
  | mode_ord (Input, Input) = EQUAL
bulwahn@39311
   205
  | mode_ord (Output, Output) = EQUAL
bulwahn@39311
   206
  | mode_ord (Bool, Bool) = EQUAL
bulwahn@39311
   207
  | mode_ord (Pair (m1, m2), Pair (m3, m4)) = prod_ord mode_ord mode_ord ((m1, m2), (m3, m4))
bulwahn@39311
   208
  | mode_ord (Fun (m1, m2), Fun (m3, m4)) = prod_ord mode_ord mode_ord ((m1, m2), (m3, m4))
wenzelm@55437
   209
bulwahn@36035
   210
fun list_fun_mode [] = Bool
bulwahn@36035
   211
  | list_fun_mode (m :: ms) = Fun (m, list_fun_mode ms)
bulwahn@36035
   212
bulwahn@33619
   213
(* name: binder_modes? *)
bulwahn@33619
   214
fun strip_fun_mode (Fun (mode, mode')) = mode :: strip_fun_mode mode'
bulwahn@33619
   215
  | strip_fun_mode Bool = []
bulwahn@35885
   216
  | strip_fun_mode _ = raise Fail "Bad mode for strip_fun_mode"
bulwahn@33619
   217
bulwahn@36047
   218
(* name: strip_fun_mode? *)
bulwahn@33619
   219
fun dest_fun_mode (Fun (mode, mode')) = mode :: dest_fun_mode mode'
bulwahn@33619
   220
  | dest_fun_mode mode = [mode]
bulwahn@33619
   221
bulwahn@33619
   222
fun dest_tuple_mode (Pair (mode, mode')) = mode :: dest_tuple_mode mode'
bulwahn@33619
   223
  | dest_tuple_mode _ = []
bulwahn@33619
   224
wenzelm@55437
   225
fun all_modes_of_typ' (T as Type ("fun", _)) =
bulwahn@35324
   226
  let
bulwahn@35324
   227
    val (S, U) = strip_type T
bulwahn@35324
   228
  in
bulwahn@35324
   229
    if U = HOLogic.boolT then
bulwahn@35324
   230
      fold_rev (fn m1 => fn m2 => map_product (curry Fun) m1 m2)
bulwahn@35324
   231
        (map all_modes_of_typ' S) [Bool]
bulwahn@35324
   232
    else
bulwahn@35324
   233
      [Input, Output]
bulwahn@35324
   234
  end
wenzelm@55437
   235
  | all_modes_of_typ' (Type (@{type_name Product_Type.prod}, [T1, T2])) =
bulwahn@35324
   236
    map_product (curry Pair) (all_modes_of_typ' T1) (all_modes_of_typ' T2)
bulwahn@35324
   237
  | all_modes_of_typ' _ = [Input, Output]
bulwahn@35324
   238
bulwahn@35324
   239
fun all_modes_of_typ (T as Type ("fun", _)) =
bulwahn@35885
   240
    let
bulwahn@35885
   241
      val (S, U) = strip_type T
bulwahn@35885
   242
    in
bulwahn@35885
   243
      if U = @{typ bool} then
bulwahn@35885
   244
        fold_rev (fn m1 => fn m2 => map_product (curry Fun) m1 m2)
bulwahn@35885
   245
          (map all_modes_of_typ' S) [Bool]
bulwahn@35885
   246
      else
bulwahn@39192
   247
        raise Fail "Invocation of all_modes_of_typ with a non-predicate type"
bulwahn@35885
   248
    end
bulwahn@35885
   249
  | all_modes_of_typ @{typ bool} = [Bool]
haftmann@46662
   250
  | all_modes_of_typ _ =
bulwahn@39192
   251
    raise Fail "Invocation of all_modes_of_typ with a non-predicate type"
bulwahn@34948
   252
bulwahn@35324
   253
fun all_smodes_of_typ (T as Type ("fun", _)) =
bulwahn@35324
   254
  let
bulwahn@35324
   255
    val (S, U) = strip_type T
wenzelm@55437
   256
    fun all_smodes (Type (@{type_name Product_Type.prod}, [T1, T2])) =
bulwahn@35324
   257
      map_product (curry Pair) (all_smodes T1) (all_smodes T2)
bulwahn@35324
   258
      | all_smodes _ = [Input, Output]
bulwahn@35324
   259
  in
bulwahn@35324
   260
    if U = HOLogic.boolT then
bulwahn@35324
   261
      fold_rev (fn m1 => fn m2 => map_product (curry Fun) m1 m2) (map all_smodes S) [Bool]
bulwahn@35324
   262
    else
bulwahn@36047
   263
      raise Fail "invalid type for predicate"
bulwahn@35324
   264
  end
bulwahn@35885
   265
bulwahn@34948
   266
fun ho_arg_modes_of mode =
bulwahn@34948
   267
  let
bulwahn@34948
   268
    fun ho_arg_mode (m as Fun _) =  [m]
bulwahn@34948
   269
      | ho_arg_mode (Pair (m1, m2)) = ho_arg_mode m1 @ ho_arg_mode m2
bulwahn@34948
   270
      | ho_arg_mode _ = []
bulwahn@34948
   271
  in
bulwahn@34948
   272
    maps ho_arg_mode (strip_fun_mode mode)
bulwahn@34948
   273
  end
bulwahn@34948
   274
bulwahn@34948
   275
fun ho_args_of mode ts =
bulwahn@34948
   276
  let
bulwahn@34948
   277
    fun ho_arg (Fun _) (SOME t) = [t]
bulwahn@36047
   278
      | ho_arg (Fun _) NONE = raise Fail "mode and term do not match"
bulwahn@35885
   279
      | ho_arg (Pair (m1, m2)) (SOME (Const (@{const_name Pair}, _) $ t1 $ t2)) =
bulwahn@34948
   280
          ho_arg m1 (SOME t1) @ ho_arg m2 (SOME t2)
bulwahn@34948
   281
      | ho_arg (Pair (m1, m2)) NONE = ho_arg m1 NONE @ ho_arg m2 NONE
bulwahn@34948
   282
      | ho_arg _ _ = []
bulwahn@34948
   283
  in
bulwahn@34948
   284
    flat (map2_optional ho_arg (strip_fun_mode mode) ts)
bulwahn@34948
   285
  end
bulwahn@34948
   286
bulwahn@39299
   287
fun ho_args_of_typ T ts =
bulwahn@39299
   288
  let
wenzelm@55437
   289
    fun ho_arg (T as Type ("fun", [_, _])) (SOME t) =
wenzelm@55437
   290
          if body_type T = @{typ bool} then [t] else []
wenzelm@55437
   291
      | ho_arg (Type ("fun", [_, _])) NONE = raise Fail "mode and term do not match"
bulwahn@39299
   292
      | ho_arg (Type(@{type_name "Product_Type.prod"}, [T1, T2]))
bulwahn@39299
   293
         (SOME (Const (@{const_name Pair}, _) $ t1 $ t2)) =
bulwahn@39299
   294
          ho_arg T1 (SOME t1) @ ho_arg T2 (SOME t2)
bulwahn@39299
   295
      | ho_arg (Type(@{type_name "Product_Type.prod"}, [T1, T2])) NONE =
bulwahn@39299
   296
          ho_arg T1 NONE @ ho_arg T2 NONE
bulwahn@39299
   297
      | ho_arg _ _ = []
bulwahn@39299
   298
  in
bulwahn@39299
   299
    flat (map2_optional ho_arg (binder_types T) ts)
bulwahn@39299
   300
  end
bulwahn@39299
   301
bulwahn@39299
   302
fun ho_argsT_of_typ Ts =
bulwahn@39299
   303
  let
bulwahn@39312
   304
    fun ho_arg (T as Type("fun", [_,_])) = if body_type T = @{typ bool} then [T] else []
wenzelm@55437
   305
      | ho_arg (Type (@{type_name "Product_Type.prod"}, [T1, T2])) =
bulwahn@39299
   306
          ho_arg T1 @ ho_arg T2
bulwahn@39299
   307
      | ho_arg _ = []
bulwahn@39299
   308
  in
bulwahn@39299
   309
    maps ho_arg Ts
bulwahn@39299
   310
  end
wenzelm@55437
   311
bulwahn@39299
   312
bulwahn@34948
   313
(* temporary function should be replaced by unsplit_input or so? *)
bulwahn@34948
   314
fun replace_ho_args mode hoargs ts =
bulwahn@34948
   315
  let
bulwahn@34948
   316
    fun replace (Fun _, _) (arg' :: hoargs') = (arg', hoargs')
haftmann@37391
   317
      | replace (Pair (m1, m2), Const (@{const_name Pair}, T) $ t1 $ t2) hoargs =
wenzelm@55437
   318
          let
wenzelm@55437
   319
            val (t1', hoargs') = replace (m1, t1) hoargs
wenzelm@55437
   320
            val (t2', hoargs'') = replace (m2, t2) hoargs'
wenzelm@55437
   321
          in
wenzelm@55437
   322
            (Const (@{const_name Pair}, T) $ t1' $ t2', hoargs'')
wenzelm@55437
   323
          end
bulwahn@34948
   324
      | replace (_, t) hoargs = (t, hoargs)
bulwahn@34948
   325
  in
bulwahn@35885
   326
    fst (fold_map replace (strip_fun_mode mode ~~ ts) hoargs)
bulwahn@34948
   327
  end
bulwahn@34948
   328
bulwahn@34948
   329
fun ho_argsT_of mode Ts =
bulwahn@34948
   330
  let
bulwahn@34948
   331
    fun ho_arg (Fun _) T = [T]
wenzelm@55437
   332
      | ho_arg (Pair (m1, m2)) (Type (@{type_name Product_Type.prod}, [T1, T2])) =
wenzelm@55437
   333
          ho_arg m1 T1 @ ho_arg m2 T2
bulwahn@34948
   334
      | ho_arg _ _ = []
bulwahn@34948
   335
  in
bulwahn@34948
   336
    flat (map2 ho_arg (strip_fun_mode mode) Ts)
bulwahn@34948
   337
  end
bulwahn@34948
   338
bulwahn@34948
   339
(* splits mode and maps function to higher-order argument types *)
bulwahn@34948
   340
fun split_map_mode f mode ts =
bulwahn@34948
   341
  let
bulwahn@34948
   342
    fun split_arg_mode' (m as Fun _) t = f m t
haftmann@37391
   343
      | split_arg_mode' (Pair (m1, m2)) (Const (@{const_name Pair}, _) $ t1 $ t2) =
bulwahn@34948
   344
        let
bulwahn@34948
   345
          val (i1, o1) = split_arg_mode' m1 t1
bulwahn@34948
   346
          val (i2, o2) = split_arg_mode' m2 t2
bulwahn@34948
   347
        in
bulwahn@34948
   348
          (comb_option HOLogic.mk_prod (i1, i2), comb_option HOLogic.mk_prod (o1, o2))
bulwahn@34948
   349
        end
bulwahn@35324
   350
      | split_arg_mode' m t =
bulwahn@35324
   351
        if eq_mode (m, Input) then (SOME t, NONE)
bulwahn@35324
   352
        else if eq_mode (m, Output) then (NONE,  SOME t)
bulwahn@35885
   353
        else raise Fail "split_map_mode: mode and term do not match"
bulwahn@34948
   354
  in
wenzelm@59058
   355
    (apply2 (map_filter I) o split_list) (map2 split_arg_mode' (strip_fun_mode mode) ts)
bulwahn@34948
   356
  end
bulwahn@34948
   357
bulwahn@34948
   358
(* splits mode and maps function to higher-order argument types *)
bulwahn@34948
   359
fun split_map_modeT f mode Ts =
bulwahn@34948
   360
  let
bulwahn@34948
   361
    fun split_arg_mode' (m as Fun _) T = f m T
haftmann@37678
   362
      | split_arg_mode' (Pair (m1, m2)) (Type (@{type_name Product_Type.prod}, [T1, T2])) =
bulwahn@34948
   363
        let
bulwahn@34948
   364
          val (i1, o1) = split_arg_mode' m1 T1
bulwahn@34948
   365
          val (i2, o2) = split_arg_mode' m2 T2
bulwahn@34948
   366
        in
bulwahn@34948
   367
          (comb_option HOLogic.mk_prodT (i1, i2), comb_option HOLogic.mk_prodT (o1, o2))
bulwahn@34948
   368
        end
bulwahn@34948
   369
      | split_arg_mode' Input T = (SOME T, NONE)
bulwahn@34948
   370
      | split_arg_mode' Output T = (NONE,  SOME T)
bulwahn@35885
   371
      | split_arg_mode' _ _ = raise Fail "split_modeT': mode and type do not match"
bulwahn@34948
   372
  in
wenzelm@59058
   373
    (apply2 (map_filter I) o split_list) (map2 split_arg_mode' (strip_fun_mode mode) Ts)
bulwahn@34948
   374
  end
bulwahn@34948
   375
bulwahn@34948
   376
fun split_mode mode ts = split_map_mode (fn _ => fn _ => (NONE, NONE)) mode ts
bulwahn@34948
   377
haftmann@37678
   378
fun fold_map_aterms_prodT comb f (Type (@{type_name Product_Type.prod}, [T1, T2])) s =
wenzelm@55437
   379
      let
wenzelm@55437
   380
        val (x1, s') = fold_map_aterms_prodT comb f T1 s
wenzelm@55437
   381
        val (x2, s'') = fold_map_aterms_prodT comb f T2 s'
wenzelm@55437
   382
      in
wenzelm@55437
   383
        (comb x1 x2, s'')
wenzelm@55437
   384
      end
wenzelm@55437
   385
  | fold_map_aterms_prodT _ f T s = f T s
bulwahn@34948
   386
haftmann@37391
   387
fun map_filter_prod f (Const (@{const_name Pair}, _) $ t1 $ t2) =
wenzelm@55437
   388
      comb_option HOLogic.mk_prod (map_filter_prod f t1, map_filter_prod f t2)
bulwahn@34948
   389
  | map_filter_prod f t = f t
wenzelm@55437
   390
bulwahn@40139
   391
fun split_modeT mode Ts =
bulwahn@34948
   392
  let
haftmann@46662
   393
    fun split_arg_mode (Fun _) _ = ([], [])
bulwahn@40139
   394
      | split_arg_mode (Pair (m1, m2)) (Type (@{type_name Product_Type.prod}, [T1, T2])) =
wenzelm@55437
   395
          let
wenzelm@55437
   396
            val (i1, o1) = split_arg_mode m1 T1
wenzelm@55437
   397
            val (i2, o2) = split_arg_mode m2 T2
wenzelm@55437
   398
          in
wenzelm@55437
   399
            (i1 @ i2, o1 @ o2)
wenzelm@55437
   400
          end
bulwahn@40139
   401
      | split_arg_mode Input T = ([T], [])
bulwahn@40139
   402
      | split_arg_mode Output T = ([], [T])
bulwahn@40139
   403
      | split_arg_mode _ _ = raise Fail "split_modeT: mode and type do not match"
bulwahn@34948
   404
  in
wenzelm@59058
   405
    (apply2 flat o split_list) (map2 split_arg_mode (strip_fun_mode mode) Ts)
bulwahn@34948
   406
  end
bulwahn@34948
   407
bulwahn@34948
   408
fun string_of_mode mode =
bulwahn@33619
   409
  let
bulwahn@33619
   410
    fun string_of_mode1 Input = "i"
bulwahn@33619
   411
      | string_of_mode1 Output = "o"
bulwahn@33619
   412
      | string_of_mode1 Bool = "bool"
bulwahn@33619
   413
      | string_of_mode1 mode = "(" ^ (string_of_mode3 mode) ^ ")"
bulwahn@33626
   414
    and string_of_mode2 (Pair (m1, m2)) = string_of_mode3 m1 ^ " * " ^  string_of_mode2 m2
bulwahn@33619
   415
      | string_of_mode2 mode = string_of_mode1 mode
bulwahn@33619
   416
    and string_of_mode3 (Fun (m1, m2)) = string_of_mode2 m1 ^ " => " ^ string_of_mode3 m2
bulwahn@33619
   417
      | string_of_mode3 mode = string_of_mode2 mode
bulwahn@34948
   418
  in string_of_mode3 mode end
bulwahn@33619
   419
bulwahn@34948
   420
fun ascii_string_of_mode mode' =
bulwahn@33626
   421
  let
bulwahn@33626
   422
    fun ascii_string_of_mode' Input = "i"
bulwahn@33626
   423
      | ascii_string_of_mode' Output = "o"
bulwahn@33626
   424
      | ascii_string_of_mode' Bool = "b"
bulwahn@33626
   425
      | ascii_string_of_mode' (Pair (m1, m2)) =
bulwahn@33626
   426
          "P" ^ ascii_string_of_mode' m1 ^ ascii_string_of_mode'_Pair m2
wenzelm@55437
   427
      | ascii_string_of_mode' (Fun (m1, m2)) =
bulwahn@33626
   428
          "F" ^ ascii_string_of_mode' m1 ^ ascii_string_of_mode'_Fun m2 ^ "B"
bulwahn@33626
   429
    and ascii_string_of_mode'_Fun (Fun (m1, m2)) =
bulwahn@33626
   430
          ascii_string_of_mode' m1 ^ (if m2 = Bool then "" else "_" ^ ascii_string_of_mode'_Fun m2)
bulwahn@33626
   431
      | ascii_string_of_mode'_Fun Bool = "B"
bulwahn@33626
   432
      | ascii_string_of_mode'_Fun m = ascii_string_of_mode' m
bulwahn@33626
   433
    and ascii_string_of_mode'_Pair (Pair (m1, m2)) =
bulwahn@33626
   434
          ascii_string_of_mode' m1 ^ ascii_string_of_mode'_Pair m2
bulwahn@33626
   435
      | ascii_string_of_mode'_Pair m = ascii_string_of_mode' m
bulwahn@33626
   436
  in ascii_string_of_mode'_Fun mode' end
bulwahn@33626
   437
wenzelm@55437
   438
bulwahn@34948
   439
(* premises *)
bulwahn@33619
   440
wenzelm@55437
   441
datatype indprem =
wenzelm@55437
   442
  Prem of term | Negprem of term | Sidecond of term | Generator of (string * typ)
bulwahn@33619
   443
bulwahn@36251
   444
fun dest_indprem (Prem t) = t
bulwahn@36251
   445
  | dest_indprem (Negprem t) = t
bulwahn@36251
   446
  | dest_indprem (Sidecond t) = t
bulwahn@36251
   447
  | dest_indprem (Generator _) = raise Fail "cannot destruct generator"
bulwahn@36251
   448
bulwahn@36254
   449
fun map_indprem f (Prem t) = Prem (f t)
bulwahn@36254
   450
  | map_indprem f (Negprem t) = Negprem (f t)
bulwahn@36254
   451
  | map_indprem f (Sidecond t) = Sidecond (f t)
bulwahn@36254
   452
  | map_indprem f (Generator (v, T)) = Generator (dest_Free (f (Free (v, T))))
bulwahn@36254
   453
wenzelm@55437
   454
bulwahn@33250
   455
(* general syntactic functions *)
bulwahn@33250
   456
wenzelm@56245
   457
fun is_equationlike_term (Const (@{const_name Pure.eq}, _) $ _ $ _) = true
wenzelm@55437
   458
  | is_equationlike_term
wenzelm@55437
   459
      (Const (@{const_name Trueprop}, _) $ (Const (@{const_name HOL.eq}, _) $ _ $ _)) = true
bulwahn@33250
   460
  | is_equationlike_term _ = false
wenzelm@55437
   461
wenzelm@55437
   462
val is_equationlike = is_equationlike_term o prop_of
bulwahn@33250
   463
wenzelm@56245
   464
fun is_pred_equation_term (Const (@{const_name Pure.eq}, _) $ u $ v) =
wenzelm@55437
   465
      (fastype_of u = @{typ bool}) andalso (fastype_of v = @{typ bool})
bulwahn@33250
   466
  | is_pred_equation_term _ = false
wenzelm@55437
   467
wenzelm@55437
   468
val is_pred_equation = is_pred_equation_term o prop_of
bulwahn@33250
   469
bulwahn@33250
   470
fun is_intro_term constname t =
wenzelm@55437
   471
  the_default false (try (fn t =>
wenzelm@55437
   472
    case fst (strip_comb (HOLogic.dest_Trueprop (Logic.strip_imp_concl t))) of
wenzelm@55437
   473
      Const (c, _) => c = constname
wenzelm@55437
   474
    | _ => false) t)
wenzelm@55437
   475
bulwahn@33250
   476
fun is_intro constname t = is_intro_term constname (prop_of t)
bulwahn@33250
   477
wenzelm@40844
   478
fun is_predT (T as Type("fun", [_, _])) = (body_type T = @{typ bool})
bulwahn@33250
   479
  | is_predT _ = false
bulwahn@33250
   480
blanchet@55399
   481
fun get_constrs thy =
blanchet@55399
   482
  let
blanchet@55399
   483
    val ctxt = Proof_Context.init_global thy
blanchet@55399
   484
  in
blanchet@55399
   485
    Ctr_Sugar.ctr_sugars_of ctxt
blanchet@55399
   486
    |> maps (map_filter (try dest_Const) o #ctrs)
blanchet@55399
   487
    |> map (apsnd (fn T => (BNF_Util.num_binder_types T, fst (dest_Type (body_type T)))))
blanchet@55399
   488
  end
blanchet@55399
   489
bulwahn@33250
   490
(*** check if a term contains only constructor functions ***)
bulwahn@34948
   491
(* TODO: another copy in the core! *)
bulwahn@33623
   492
(* FIXME: constructor terms are supposed to be seen in the way the code generator
bulwahn@33623
   493
  sees constructors.*)
bulwahn@33250
   494
fun is_constrt thy =
bulwahn@33250
   495
  let
blanchet@55399
   496
    val cnstrs = get_constrs thy
wenzelm@55437
   497
    fun check t =
wenzelm@55437
   498
      (case strip_comb t of
bulwahn@36032
   499
        (Var _, []) => true
bulwahn@36032
   500
      | (Free _, []) => true
wenzelm@55437
   501
      | (Const (s, T), ts) =>
wenzelm@55437
   502
          (case (AList.lookup (op =) cnstrs s, body_type T) of
wenzelm@55437
   503
            (SOME (i, Tname), Type (Tname', _)) =>
wenzelm@55437
   504
              length ts = i andalso Tname = Tname' andalso forall check ts
bulwahn@33250
   505
          | _ => false)
bulwahn@33250
   506
      | _ => false)
wenzelm@55437
   507
  in check end
bulwahn@34948
   508
haftmann@59484
   509
fun is_constr ctxt c =
haftmann@59484
   510
  not (member (op =) no_constr c) andalso Code.is_constr (Proof_Context.theory_of ctxt) c;
bulwahn@34948
   511
bulwahn@36047
   512
fun strip_all t = (Term.strip_all_vars t, Term.strip_all_body t)
bulwahn@36047
   513
haftmann@38558
   514
fun strip_ex (Const (@{const_name Ex}, _) $ Abs (x, T, t)) =
wenzelm@55437
   515
      let
wenzelm@55437
   516
        val (xTs, t') = strip_ex t
wenzelm@55437
   517
      in
wenzelm@55437
   518
        ((x, T) :: xTs, t')
wenzelm@55437
   519
      end
bulwahn@33250
   520
  | strip_ex t = ([], t)
bulwahn@33250
   521
bulwahn@33250
   522
fun focus_ex t nctxt =
bulwahn@33250
   523
  let
wenzelm@55437
   524
    val ((xs, Ts), t') = apfst split_list (strip_ex t)
wenzelm@43326
   525
    val (xs', nctxt') = fold_map Name.variant xs nctxt;
bulwahn@33250
   526
    val ps' = xs' ~~ Ts;
bulwahn@33250
   527
    val vs = map Free ps';
bulwahn@33250
   528
    val t'' = Term.subst_bounds (rev vs, t');
wenzelm@55437
   529
  in ((ps', t''), nctxt') end
bulwahn@33250
   530
wenzelm@55437
   531
val strip_intro_concl = strip_comb o HOLogic.dest_Trueprop o Logic.strip_imp_concl o prop_of
wenzelm@55437
   532
wenzelm@55437
   533
bulwahn@33250
   534
(* introduction rule combinators *)
bulwahn@33250
   535
wenzelm@55437
   536
fun map_atoms f intro =
bulwahn@33250
   537
  let
bulwahn@33250
   538
    val (literals, head) = Logic.strip_horn intro
wenzelm@55437
   539
    fun appl t =
wenzelm@55437
   540
      (case t of
bulwahn@35885
   541
        (@{term Not} $ t') => HOLogic.mk_not (f t')
bulwahn@33250
   542
      | _ => f t)
bulwahn@33250
   543
  in
bulwahn@33250
   544
    Logic.list_implies
bulwahn@33250
   545
      (map (HOLogic.mk_Trueprop o appl o HOLogic.dest_Trueprop) literals, head)
bulwahn@33250
   546
  end
bulwahn@33250
   547
bulwahn@33250
   548
fun fold_atoms f intro s =
bulwahn@33250
   549
  let
haftmann@46662
   550
    val (literals, _) = Logic.strip_horn intro
wenzelm@55437
   551
    fun appl t s =
wenzelm@55437
   552
      (case t of
wenzelm@55437
   553
        (@{term Not} $ t') => f t' s
bulwahn@33250
   554
      | _ => f t s)
bulwahn@33250
   555
  in fold appl (map HOLogic.dest_Trueprop literals) s end
bulwahn@33250
   556
bulwahn@33250
   557
fun fold_map_atoms f intro s =
bulwahn@33250
   558
  let
bulwahn@33250
   559
    val (literals, head) = Logic.strip_horn intro
wenzelm@55437
   560
    fun appl t s =
wenzelm@55437
   561
      (case t of
wenzelm@55437
   562
        (@{term Not} $ t') => apfst HOLogic.mk_not (f t' s)
bulwahn@33250
   563
      | _ => f t s)
bulwahn@33250
   564
    val (literals', s') = fold_map appl (map HOLogic.dest_Trueprop literals) s
bulwahn@33250
   565
  in
bulwahn@33250
   566
    (Logic.list_implies (map HOLogic.mk_Trueprop literals', head), s')
bulwahn@33250
   567
  end;
bulwahn@33250
   568
bulwahn@36246
   569
fun map_filter_premises f intro =
bulwahn@36246
   570
  let
bulwahn@36246
   571
    val (premises, head) = Logic.strip_horn intro
bulwahn@36246
   572
  in
bulwahn@36246
   573
    Logic.list_implies (map_filter f premises, head)
bulwahn@36246
   574
  end
bulwahn@36246
   575
bulwahn@33250
   576
fun maps_premises f intro =
bulwahn@33250
   577
  let
bulwahn@33250
   578
    val (premises, head) = Logic.strip_horn intro
bulwahn@33250
   579
  in
bulwahn@33250
   580
    Logic.list_implies (maps f premises, head)
bulwahn@33250
   581
  end
bulwahn@35324
   582
bulwahn@35875
   583
fun map_concl f intro =
bulwahn@35875
   584
  let
bulwahn@35875
   585
    val (premises, head) = Logic.strip_horn intro
bulwahn@35875
   586
  in
bulwahn@35875
   587
    Logic.list_implies (premises, f head)
bulwahn@35875
   588
  end
bulwahn@35875
   589
wenzelm@55437
   590
bulwahn@35875
   591
(* combinators to apply a function to all basic parts of nested products *)
bulwahn@35875
   592
haftmann@37391
   593
fun map_products f (Const (@{const_name Pair}, T) $ t1 $ t2) =
haftmann@37391
   594
  Const (@{const_name Pair}, T) $ map_products f t1 $ map_products f t2
bulwahn@35875
   595
  | map_products f t = f t
bulwahn@35324
   596
wenzelm@55437
   597
bulwahn@35324
   598
(* split theorems of case expressions *)
bulwahn@35324
   599
bulwahn@35324
   600
fun prepare_split_thm ctxt split_thm =
bulwahn@35324
   601
    (split_thm RS @{thm iffD2})
wenzelm@35624
   602
    |> Local_Defs.unfold ctxt [@{thm atomize_conjL[symmetric]},
bulwahn@35324
   603
      @{thm atomize_all[symmetric]}, @{thm atomize_imp[symmetric]}]
bulwahn@35324
   604
blanchet@55399
   605
fun find_split_thm thy (Const (name, _)) =
blanchet@55399
   606
    Option.map #split (Ctr_Sugar.ctr_sugar_of_case (Proof_Context.init_global thy) name)
wenzelm@55437
   607
  | find_split_thm _ _ = NONE
wenzelm@55437
   608
bulwahn@35324
   609
bulwahn@33250
   610
(* lifting term operations to theorems *)
bulwahn@33250
   611
bulwahn@33250
   612
fun map_term thy f th =
bulwahn@33250
   613
  Skip_Proof.make_thm thy (f (prop_of th))
bulwahn@33250
   614
bulwahn@33250
   615
(*
bulwahn@33250
   616
fun equals_conv lhs_cv rhs_cv ct =
bulwahn@33250
   617
  case Thm.term_of ct of
wenzelm@56245
   618
    Const (@{const_name Pure.eq}, _) $ _ $ _ => Conv.arg_conv cv ct
wenzelm@55437
   619
  | _ => error "equals_conv"
bulwahn@33250
   620
*)
bulwahn@33250
   621
wenzelm@55437
   622
bulwahn@36038
   623
(* Different compilations *)
bulwahn@33250
   624
bulwahn@35881
   625
datatype compilation = Pred | Depth_Limited | Random | Depth_Limited_Random | DSeq | Annotated
bulwahn@40051
   626
  | Pos_Random_DSeq | Neg_Random_DSeq | New_Pos_Random_DSeq | New_Neg_Random_DSeq |
bulwahn@45450
   627
    Pos_Generator_DSeq | Neg_Generator_DSeq | Pos_Generator_CPS | Neg_Generator_CPS
bulwahn@35324
   628
bulwahn@35324
   629
fun negative_compilation_of Pos_Random_DSeq = Neg_Random_DSeq
bulwahn@35324
   630
  | negative_compilation_of Neg_Random_DSeq = Pos_Random_DSeq
bulwahn@36018
   631
  | negative_compilation_of New_Pos_Random_DSeq = New_Neg_Random_DSeq
bulwahn@36018
   632
  | negative_compilation_of New_Neg_Random_DSeq = New_Pos_Random_DSeq
bulwahn@40051
   633
  | negative_compilation_of Pos_Generator_DSeq = Neg_Generator_DSeq
bulwahn@45450
   634
  | negative_compilation_of Neg_Generator_DSeq = Pos_Generator_DSeq
bulwahn@45450
   635
  | negative_compilation_of Pos_Generator_CPS = Neg_Generator_CPS
wenzelm@55437
   636
  | negative_compilation_of Neg_Generator_CPS = Pos_Generator_CPS
bulwahn@35324
   637
  | negative_compilation_of c = c
wenzelm@55437
   638
bulwahn@35324
   639
fun compilation_for_polarity false Pos_Random_DSeq = Neg_Random_DSeq
bulwahn@36018
   640
  | compilation_for_polarity false New_Pos_Random_DSeq = New_Neg_Random_DSeq
bulwahn@35324
   641
  | compilation_for_polarity _ c = c
bulwahn@34948
   642
bulwahn@40049
   643
fun is_depth_limited_compilation c =
bulwahn@40051
   644
  (c = New_Pos_Random_DSeq) orelse (c = New_Neg_Random_DSeq) orelse
bulwahn@40051
   645
  (c = Pos_Generator_DSeq) orelse (c = Pos_Generator_DSeq)
bulwahn@40049
   646
bulwahn@35885
   647
fun string_of_compilation c =
wenzelm@55437
   648
  (case c of
bulwahn@34948
   649
    Pred => ""
bulwahn@34948
   650
  | Random => "random"
bulwahn@34948
   651
  | Depth_Limited => "depth limited"
bulwahn@35881
   652
  | Depth_Limited_Random => "depth limited random"
bulwahn@34948
   653
  | DSeq => "dseq"
bulwahn@34948
   654
  | Annotated => "annotated"
bulwahn@35324
   655
  | Pos_Random_DSeq => "pos_random dseq"
bulwahn@35324
   656
  | Neg_Random_DSeq => "neg_random_dseq"
bulwahn@36018
   657
  | New_Pos_Random_DSeq => "new_pos_random dseq"
bulwahn@36018
   658
  | New_Neg_Random_DSeq => "new_neg_random_dseq"
bulwahn@40051
   659
  | Pos_Generator_DSeq => "pos_generator_dseq"
bulwahn@40051
   660
  | Neg_Generator_DSeq => "neg_generator_dseq"
bulwahn@45450
   661
  | Pos_Generator_CPS => "pos_generator_cps"
wenzelm@55437
   662
  | Neg_Generator_CPS => "neg_generator_cps")
wenzelm@55437
   663
wenzelm@55437
   664
val compilation_names =
wenzelm@55437
   665
 [("pred", Pred),
bulwahn@36018
   666
  ("random", Random),
bulwahn@36018
   667
  ("depth_limited", Depth_Limited),
bulwahn@36018
   668
  ("depth_limited_random", Depth_Limited_Random),
bulwahn@36018
   669
  (*("annotated", Annotated),*)
bulwahn@40054
   670
  ("dseq", DSeq),
bulwahn@40054
   671
  ("random_dseq", Pos_Random_DSeq),
bulwahn@40051
   672
  ("new_random_dseq", New_Pos_Random_DSeq),
bulwahn@45450
   673
  ("generator_dseq", Pos_Generator_DSeq),
bulwahn@45450
   674
  ("generator_cps", Pos_Generator_CPS)]
bulwahn@36038
   675
bulwahn@36038
   676
val non_random_compilations = [Pred, Depth_Limited, DSeq, Annotated]
bulwahn@36038
   677
bulwahn@36038
   678
bulwahn@36038
   679
val random_compilations = [Random, Depth_Limited_Random,
bulwahn@48221
   680
  Pos_Random_DSeq, Neg_Random_DSeq, New_Pos_Random_DSeq, New_Neg_Random_DSeq,
bulwahn@48221
   681
  Pos_Generator_CPS, Neg_Generator_CPS]
bulwahn@36038
   682
wenzelm@55437
   683
bulwahn@36046
   684
(* datastructures and setup for generic compilation *)
bulwahn@36046
   685
bulwahn@36046
   686
datatype compilation_funs = CompilationFuns of {
bulwahn@45461
   687
  mk_monadT : typ -> typ,
bulwahn@45461
   688
  dest_monadT : typ -> typ,
bulwahn@45461
   689
  mk_empty : typ -> term,
bulwahn@36046
   690
  mk_single : term -> term,
bulwahn@36046
   691
  mk_bind : term * term -> term,
bulwahn@45461
   692
  mk_plus : term * term -> term,
bulwahn@36046
   693
  mk_if : term -> term,
bulwahn@36049
   694
  mk_iterate_upto : typ -> term * term * term -> term,
bulwahn@36046
   695
  mk_not : term -> term,
bulwahn@36046
   696
  mk_map : typ -> typ -> term -> term -> term
wenzelm@55437
   697
}
bulwahn@36038
   698
bulwahn@45461
   699
fun mk_monadT (CompilationFuns funs) = #mk_monadT funs
bulwahn@45461
   700
fun dest_monadT (CompilationFuns funs) = #dest_monadT funs
bulwahn@45461
   701
fun mk_empty (CompilationFuns funs) = #mk_empty funs
bulwahn@36046
   702
fun mk_single (CompilationFuns funs) = #mk_single funs
bulwahn@36046
   703
fun mk_bind (CompilationFuns funs) = #mk_bind funs
bulwahn@45461
   704
fun mk_plus (CompilationFuns funs) = #mk_plus funs
bulwahn@36046
   705
fun mk_if (CompilationFuns funs) = #mk_if funs
bulwahn@36049
   706
fun mk_iterate_upto (CompilationFuns funs) = #mk_iterate_upto funs
bulwahn@36046
   707
fun mk_not (CompilationFuns funs) = #mk_not funs
bulwahn@36046
   708
fun mk_map (CompilationFuns funs) = #mk_map funs
bulwahn@36046
   709
wenzelm@55437
   710
bulwahn@36046
   711
(** function types and names of different compilations **)
bulwahn@36046
   712
bulwahn@36046
   713
fun funT_of compfuns mode T =
bulwahn@36046
   714
  let
bulwahn@36046
   715
    val Ts = binder_types T
wenzelm@55437
   716
    val (inTs, outTs) =
wenzelm@55437
   717
      split_map_modeT (fn m => fn T => (SOME (funT_of compfuns m T), NONE)) mode Ts
bulwahn@36046
   718
  in
bulwahn@45461
   719
    inTs ---> (mk_monadT compfuns (HOLogic.mk_tupleT outTs))
wenzelm@55437
   720
  end
wenzelm@55437
   721
bulwahn@36046
   722
bulwahn@36046
   723
(* Different options for compiler *)
bulwahn@34948
   724
wenzelm@55437
   725
datatype options = Options of {
bulwahn@34948
   726
  expected_modes : (string * mode list) option,
bulwahn@39382
   727
  proposed_modes : (string * mode list) list,
bulwahn@34948
   728
  proposed_names : ((string * mode) * string) list,
bulwahn@33250
   729
  show_steps : bool,
bulwahn@33250
   730
  show_proof_trace : bool,
bulwahn@33250
   731
  show_intermediate_results : bool,
bulwahn@33251
   732
  show_mode_inference : bool,
bulwahn@33251
   733
  show_modes : bool,
bulwahn@33250
   734
  show_compilation : bool,
bulwahn@35324
   735
  show_caught_failures : bool,
bulwahn@39383
   736
  show_invalid_clauses : bool,
bulwahn@33250
   737
  skip_proof : bool,
bulwahn@35324
   738
  no_topmost_reordering : bool,
bulwahn@35324
   739
  function_flattening : bool,
bulwahn@36248
   740
  specialise : bool,
bulwahn@35324
   741
  fail_safe_function_flattening : bool,
bulwahn@35324
   742
  no_higher_order_predicate : string list,
bulwahn@33250
   743
  inductify : bool,
bulwahn@36254
   744
  detect_switches : bool,
bulwahn@40048
   745
  smart_depth_limiting : bool,
bulwahn@34948
   746
  compilation : compilation
wenzelm@55437
   747
}
bulwahn@33250
   748
bulwahn@33250
   749
fun expected_modes (Options opt) = #expected_modes opt
bulwahn@39382
   750
fun proposed_modes (Options opt) = AList.lookup (op =) (#proposed_modes opt)
bulwahn@34948
   751
fun proposed_names (Options opt) name mode = AList.lookup (eq_pair (op =) eq_mode)
bulwahn@33623
   752
  (#proposed_names opt) (name, mode)
bulwahn@33620
   753
bulwahn@33250
   754
fun show_steps (Options opt) = #show_steps opt
bulwahn@33250
   755
fun show_intermediate_results (Options opt) = #show_intermediate_results opt
bulwahn@33250
   756
fun show_proof_trace (Options opt) = #show_proof_trace opt
bulwahn@33251
   757
fun show_modes (Options opt) = #show_modes opt
bulwahn@33251
   758
fun show_mode_inference (Options opt) = #show_mode_inference opt
bulwahn@33250
   759
fun show_compilation (Options opt) = #show_compilation opt
bulwahn@35324
   760
fun show_caught_failures (Options opt) = #show_caught_failures opt
bulwahn@39383
   761
fun show_invalid_clauses (Options opt) = #show_invalid_clauses opt
bulwahn@33250
   762
fun skip_proof (Options opt) = #skip_proof opt
bulwahn@33250
   763
bulwahn@35324
   764
fun function_flattening (Options opt) = #function_flattening opt
bulwahn@35324
   765
fun fail_safe_function_flattening (Options opt) = #fail_safe_function_flattening opt
bulwahn@36248
   766
fun specialise (Options opt) = #specialise opt
bulwahn@35324
   767
fun no_topmost_reordering (Options opt) = #no_topmost_reordering opt
bulwahn@35324
   768
fun no_higher_order_predicate (Options opt) = #no_higher_order_predicate opt
bulwahn@35324
   769
bulwahn@33250
   770
fun is_inductify (Options opt) = #inductify opt
bulwahn@34948
   771
bulwahn@34948
   772
fun compilation (Options opt) = #compilation opt
bulwahn@33250
   773
bulwahn@36254
   774
fun detect_switches (Options opt) = #detect_switches opt
bulwahn@36254
   775
bulwahn@40048
   776
fun smart_depth_limiting (Options opt) = #smart_depth_limiting opt
bulwahn@40048
   777
bulwahn@33250
   778
val default_options = Options {
bulwahn@33250
   779
  expected_modes = NONE,
bulwahn@39382
   780
  proposed_modes = [],
bulwahn@33623
   781
  proposed_names = [],
bulwahn@33250
   782
  show_steps = false,
bulwahn@33250
   783
  show_intermediate_results = false,
bulwahn@33250
   784
  show_proof_trace = false,
bulwahn@33251
   785
  show_modes = false,
bulwahn@33250
   786
  show_mode_inference = false,
bulwahn@33250
   787
  show_compilation = false,
bulwahn@35324
   788
  show_caught_failures = false,
bulwahn@39383
   789
  show_invalid_clauses = false,
bulwahn@34948
   790
  skip_proof = true,
bulwahn@35324
   791
  no_topmost_reordering = false,
bulwahn@35324
   792
  function_flattening = false,
bulwahn@36248
   793
  specialise = false,
bulwahn@35324
   794
  fail_safe_function_flattening = false,
bulwahn@35324
   795
  no_higher_order_predicate = [],
bulwahn@33250
   796
  inductify = false,
bulwahn@36254
   797
  detect_switches = true,
bulwahn@40048
   798
  smart_depth_limiting = false,
bulwahn@34948
   799
  compilation = Pred
bulwahn@33250
   800
}
bulwahn@33250
   801
bulwahn@34948
   802
val bool_options = ["show_steps", "show_intermediate_results", "show_proof_trace", "show_modes",
bulwahn@39383
   803
  "show_mode_inference", "show_compilation", "show_invalid_clauses", "skip_proof", "inductify",
bulwahn@40048
   804
  "no_function_flattening", "detect_switches", "specialise", "no_topmost_reordering",
bulwahn@40048
   805
  "smart_depth_limiting"]
bulwahn@34948
   806
bulwahn@33250
   807
fun print_step options s =
bulwahn@33250
   808
  if show_steps options then tracing s else ()
bulwahn@33250
   809
wenzelm@55437
   810
bulwahn@36047
   811
(* simple transformations *)
bulwahn@36047
   812
bulwahn@36047
   813
(** tuple processing **)
bulwahn@33250
   814
bulwahn@39657
   815
fun rewrite_args [] (pats, intro_t, ctxt) = (pats, intro_t, ctxt)
wenzelm@55437
   816
  | rewrite_args (arg::args) (pats, intro_t, ctxt) =
wenzelm@55437
   817
      (case HOLogic.strip_tupleT (fastype_of arg) of
wenzelm@55437
   818
        (_ :: _ :: _) =>
wenzelm@55437
   819
        let
wenzelm@55437
   820
          fun rewrite_arg'
wenzelm@55437
   821
                (Const (@{const_name Pair}, _) $ _ $ t2, Type (@{type_name Product_Type.prod}, [_, T2]))
wenzelm@55437
   822
                (args, (pats, intro_t, ctxt)) =
wenzelm@55437
   823
                rewrite_arg' (t2, T2) (args, (pats, intro_t, ctxt))
wenzelm@55437
   824
            | rewrite_arg'
wenzelm@55437
   825
                (t, Type (@{type_name Product_Type.prod}, [T1, T2])) (args, (pats, intro_t, ctxt)) =
wenzelm@55437
   826
                let
wenzelm@55437
   827
                  val thy = Proof_Context.theory_of ctxt
wenzelm@55437
   828
                  val ([x, y], ctxt') = Variable.variant_fixes ["x", "y"] ctxt
wenzelm@55437
   829
                  val pat = (t, HOLogic.mk_prod (Free (x, T1), Free (y, T2)))
wenzelm@55437
   830
                  val intro_t' = Pattern.rewrite_term thy [pat] [] intro_t
wenzelm@55437
   831
                  val args' = map (Pattern.rewrite_term thy [pat] []) args
wenzelm@55437
   832
                in
wenzelm@55437
   833
                  rewrite_arg' (Free (y, T2), T2) (args', (pat::pats, intro_t', ctxt'))
wenzelm@55437
   834
                end
wenzelm@55437
   835
            | rewrite_arg' _ (args, (pats, intro_t, ctxt)) = (args, (pats, intro_t, ctxt))
wenzelm@55437
   836
          val (args', (pats, intro_t', ctxt')) =
wenzelm@55437
   837
            rewrite_arg' (arg, fastype_of arg) (args, (pats, intro_t, ctxt))
wenzelm@55437
   838
        in
wenzelm@55437
   839
          rewrite_args args' (pats, intro_t', ctxt')
wenzelm@55437
   840
        end
bulwahn@39657
   841
  | _ => rewrite_args args (pats, intro_t, ctxt))
bulwahn@39657
   842
bulwahn@39657
   843
fun rewrite_prem atom =
bulwahn@39657
   844
  let
bulwahn@39657
   845
    val (_, args) = strip_comb atom
bulwahn@39657
   846
  in rewrite_args args end
bulwahn@39657
   847
bulwahn@39787
   848
fun split_conjuncts_in_assms ctxt th =
bulwahn@39787
   849
  let
wenzelm@55437
   850
    val ((_, [fixed_th]), ctxt') = Variable.import false [th] ctxt
bulwahn@39787
   851
    fun split_conjs i nprems th =
bulwahn@39787
   852
      if i > nprems then th
bulwahn@39787
   853
      else
wenzelm@55437
   854
        (case try Drule.RSN (@{thm conjI}, (i, th)) of
wenzelm@55437
   855
          SOME th' => split_conjs i (nprems + 1) th'
wenzelm@55437
   856
        | NONE => split_conjs (i + 1) nprems th)
bulwahn@39787
   857
  in
wenzelm@55437
   858
    singleton (Variable.export ctxt' ctxt)
wenzelm@55437
   859
      (split_conjs 1 (Thm.nprems_of fixed_th) fixed_th)
bulwahn@39787
   860
  end
bulwahn@40052
   861
bulwahn@40052
   862
fun dest_conjunct_prem th =
wenzelm@55437
   863
  (case HOLogic.dest_Trueprop (prop_of th) of
haftmann@46662
   864
    (Const (@{const_name HOL.conj}, _) $ _ $ _) =>
bulwahn@40052
   865
      dest_conjunct_prem (th RS @{thm conjunct1})
bulwahn@40052
   866
        @ dest_conjunct_prem (th RS @{thm conjunct2})
wenzelm@55437
   867
   | _ => [th])
bulwahn@40052
   868
bulwahn@33250
   869
fun expand_tuples thy intro =
bulwahn@33250
   870
  let
wenzelm@42361
   871
    val ctxt = Proof_Context.init_global thy
bulwahn@33250
   872
    val (((T_insts, t_insts), [intro']), ctxt1) = Variable.import false [intro] ctxt
bulwahn@33250
   873
    val intro_t = prop_of intro'
bulwahn@33250
   874
    val concl = Logic.strip_imp_concl intro_t
haftmann@46662
   875
    val (_, args) = strip_comb (HOLogic.dest_Trueprop concl)
bulwahn@33250
   876
    val (pats', intro_t', ctxt2) = rewrite_args args ([], intro_t, ctxt1)
haftmann@46662
   877
    val (pats', _, ctxt3) = fold_atoms rewrite_prem intro_t' (pats', intro_t', ctxt2)
bulwahn@33250
   878
    fun rewrite_pat (ct1, ct2) =
bulwahn@33250
   879
      (ct1, cterm_of thy (Pattern.rewrite_term thy pats' [] (term_of ct2)))
bulwahn@33250
   880
    val t_insts' = map rewrite_pat t_insts
bulwahn@33250
   881
    val intro'' = Thm.instantiate (T_insts, t_insts') intro
bulwahn@33250
   882
    val [intro'''] = Variable.export ctxt3 ctxt [intro'']
wenzelm@51717
   883
    val intro'''' =
wenzelm@51717
   884
      Simplifier.full_simplify
wenzelm@51717
   885
        (put_simpset HOL_basic_ss ctxt
wenzelm@51717
   886
          addsimps [@{thm fst_conv}, @{thm snd_conv}, @{thm Pair_eq}])
bulwahn@33250
   887
      intro'''
bulwahn@33250
   888
    (* splitting conjunctions introduced by Pair_eq*)
bulwahn@39787
   889
    val intro''''' = split_conjuncts_in_assms ctxt intro''''
bulwahn@33250
   890
  in
bulwahn@33250
   891
    intro'''''
bulwahn@33250
   892
  end
bulwahn@33250
   893
wenzelm@55437
   894
bulwahn@39802
   895
(** making case distributivity rules **)
bulwahn@39802
   896
(*** this should be part of the datatype package ***)
bulwahn@39802
   897
blanchet@55399
   898
fun datatype_name_of_case_name thy =
blanchet@55399
   899
  Ctr_Sugar.ctr_sugar_of_case (Proof_Context.init_global thy)
blanchet@55399
   900
  #> the #> #ctrs #> hd #> fastype_of #> body_type #> dest_Type #> fst
bulwahn@39802
   901
blanchet@55399
   902
fun make_case_comb thy Tcon =
bulwahn@39802
   903
  let
blanchet@55399
   904
    val ctxt = Proof_Context.init_global thy
blanchet@55399
   905
    val SOME {casex, ...} = Ctr_Sugar.ctr_sugar_of ctxt Tcon
blanchet@55399
   906
    val casex' = Type.legacy_freeze casex
blanchet@55399
   907
    val Ts = BNF_Util.binder_fun_types (fastype_of casex')
bulwahn@39802
   908
  in
blanchet@55399
   909
    list_comb (casex', map_index (fn (j, T) => Free ("f" ^ string_of_int j,  T)) Ts)
bulwahn@39802
   910
  end
bulwahn@39802
   911
blanchet@55399
   912
fun make_case_distrib thy Tcon =
bulwahn@39802
   913
  let
blanchet@55399
   914
    val comb = make_case_comb thy Tcon;
blanchet@55399
   915
    val Type ("fun", [T, T']) = fastype_of comb;
blanchet@55399
   916
    val (Const (case_name, _), fs) = strip_comb comb
blanchet@55399
   917
    val used = Term.add_tfree_names comb []
wenzelm@56254
   918
    val U = TFree (singleton (Name.variant_list used) "'t", @{sort type})
blanchet@55399
   919
    val x = Free ("x", T)
blanchet@55399
   920
    val f = Free ("f", T' --> U)
blanchet@55399
   921
    fun apply_f f' =
blanchet@55399
   922
      let
blanchet@55399
   923
        val Ts = binder_types (fastype_of f')
blanchet@55399
   924
        val bs = map Bound ((length Ts - 1) downto 0)
blanchet@55399
   925
      in
blanchet@55399
   926
        fold_rev absdummy Ts (f $ (list_comb (f', bs)))
blanchet@55399
   927
      end
blanchet@55399
   928
    val fs' = map apply_f fs
blanchet@55399
   929
    val case_c' = Const (case_name, (map fastype_of fs') @ [T] ---> U)
bulwahn@39802
   930
  in
blanchet@55399
   931
    HOLogic.mk_eq (f $ (comb $ x), list_comb (case_c', fs') $ x)
bulwahn@39802
   932
  end
bulwahn@39802
   933
blanchet@55399
   934
fun case_rewrite thy Tcon =
blanchet@55399
   935
  (Drule.export_without_context o Skip_Proof.make_thm thy o HOLogic.mk_Trueprop)
blanchet@55399
   936
    (make_case_distrib thy Tcon)
blanchet@55399
   937
blanchet@55399
   938
fun instantiated_case_rewrite thy Tcon =
bulwahn@39802
   939
  let
blanchet@55399
   940
    val th = case_rewrite thy Tcon
wenzelm@42361
   941
    val ctxt = Proof_Context.init_global thy
wenzelm@56259
   942
    val f = fst (strip_comb (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop (prop_of th)))))
blanchet@55399
   943
    val Type ("fun", [uninst_T, uninst_T']) = fastype_of f
wenzelm@56259
   944
    val ([yname], ctxt') = Variable.add_fixes ["y"] ctxt
wenzelm@56259
   945
    val T' = TFree ("'t'", @{sort type})
wenzelm@56259
   946
    val U = TFree ("'u", @{sort type})
blanchet@55399
   947
    val y = Free (yname, U)
blanchet@55399
   948
    val f' = absdummy (U --> T') (Bound 0 $ y)
blanchet@55399
   949
    val th' = Thm.certify_instantiate
blanchet@55399
   950
      ([(dest_TVar uninst_T, U --> T'), (dest_TVar uninst_T', T')],
blanchet@55399
   951
       [((fst (dest_Var f), (U --> T') --> T'), f')]) th
wenzelm@56259
   952
    val [th'] = Variable.export (Variable.declare_thm th' ctxt') ctxt [th']
blanchet@55399
   953
  in
blanchet@55399
   954
    th'
blanchet@55399
   955
  end
bulwahn@39802
   956
bulwahn@39802
   957
fun case_betapply thy t =
bulwahn@39802
   958
  let
bulwahn@39802
   959
    val case_name = fst (dest_Const (fst (strip_comb t)))
blanchet@55399
   960
    val Tcon = datatype_name_of_case_name thy case_name
blanchet@55399
   961
    val th = instantiated_case_rewrite thy Tcon
bulwahn@39802
   962
  in
blanchet@55399
   963
    Raw_Simplifier.rewrite_term thy [th RS @{thm eq_reflection}] [] t
bulwahn@39802
   964
  end
bulwahn@39802
   965
wenzelm@55437
   966
bulwahn@39657
   967
(*** conversions ***)
bulwahn@39657
   968
bulwahn@39657
   969
fun imp_prems_conv cv ct =
wenzelm@55437
   970
  (case Thm.term_of ct of
wenzelm@56245
   971
    Const (@{const_name Pure.imp}, _) $ _ $ _ =>
wenzelm@56245
   972
      Conv.combination_conv (Conv.arg_conv cv) (imp_prems_conv cv) ct
wenzelm@55437
   973
  | _ => Conv.all_conv ct)
wenzelm@55437
   974
bulwahn@39657
   975
bulwahn@36047
   976
(** eta contract higher-order arguments **)
bulwahn@35875
   977
bulwahn@35875
   978
fun eta_contract_ho_arguments thy intro =
bulwahn@35875
   979
  let
bulwahn@35875
   980
    fun f atom = list_comb (apsnd ((map o map_products) Envir.eta_contract) (strip_comb atom))
bulwahn@35875
   981
  in
bulwahn@35875
   982
    map_term thy (map_concl f o map_atoms f) intro
bulwahn@35875
   983
  end
bulwahn@35875
   984
wenzelm@55437
   985
bulwahn@36047
   986
(** remove equalities **)
bulwahn@36022
   987
bulwahn@36022
   988
fun remove_equalities thy intro =
bulwahn@36022
   989
  let
bulwahn@36022
   990
    fun remove_eqs intro_t =
bulwahn@36022
   991
      let
bulwahn@36022
   992
        val (prems, concl) = Logic.strip_horn intro_t
bulwahn@36022
   993
        fun remove_eq (prems, concl) =
bulwahn@36022
   994
          let
bulwahn@36022
   995
            fun removable_eq prem =
wenzelm@55437
   996
              (case try (HOLogic.dest_eq o HOLogic.dest_Trueprop) prem of
wenzelm@55437
   997
                SOME (lhs, rhs) =>
wenzelm@55437
   998
                  (case lhs of
wenzelm@55437
   999
                    Var _ => true
bulwahn@36022
  1000
                  | _ => (case rhs of Var _ => true | _ => false))
wenzelm@55437
  1001
              | NONE => false)
bulwahn@36022
  1002
          in
wenzelm@55437
  1003
            (case find_first removable_eq prems of
bulwahn@36022
  1004
              NONE => (prems, concl)
bulwahn@36022
  1005
            | SOME eq =>
wenzelm@55437
  1006
                let
wenzelm@55437
  1007
                  val (lhs, rhs) = HOLogic.dest_eq (HOLogic.dest_Trueprop eq)
wenzelm@55437
  1008
                  val prems' = remove (op =) eq prems
wenzelm@55437
  1009
                  val subst =
wenzelm@55437
  1010
                    (case lhs of
wenzelm@55437
  1011
                      (v as Var _) =>
wenzelm@55437
  1012
                        (fn t => if t = v then rhs else t)
wenzelm@55437
  1013
                    | _ => (case rhs of (v as Var _) => (fn t => if t = v then lhs else t)))
wenzelm@55437
  1014
                in
wenzelm@55437
  1015
                  remove_eq (map (map_aterms subst) prems', map_aterms subst concl)
wenzelm@55437
  1016
                end)
bulwahn@36022
  1017
          end
bulwahn@36022
  1018
      in
bulwahn@36022
  1019
        Logic.list_implies (remove_eq (prems, concl))
bulwahn@36022
  1020
      end
bulwahn@36022
  1021
  in
bulwahn@36022
  1022
    map_term thy remove_eqs intro
bulwahn@36022
  1023
  end
bulwahn@35875
  1024
wenzelm@55437
  1025
bulwahn@36246
  1026
(* Some last processing *)
bulwahn@36246
  1027
bulwahn@36246
  1028
fun remove_pointless_clauses intro =
bulwahn@36246
  1029
  if Logic.strip_imp_prems (prop_of intro) = [@{prop "False"}] then
bulwahn@36246
  1030
    []
bulwahn@36246
  1031
  else [intro]
bulwahn@36246
  1032
wenzelm@55437
  1033
bulwahn@36246
  1034
(* some peephole optimisations *)
bulwahn@36246
  1035
bulwahn@36246
  1036
fun peephole_optimisation thy intro =
bulwahn@36246
  1037
  let
wenzelm@54742
  1038
    val ctxt = Proof_Context.init_global thy  (* FIXME proper context!? *)
wenzelm@36610
  1039
    val process =
wenzelm@57962
  1040
      rewrite_rule ctxt (Named_Theorems.get ctxt @{named_theorems code_pred_simp})
bulwahn@36246
  1041
    fun process_False intro_t =
wenzelm@55437
  1042
      if member (op =) (Logic.strip_imp_prems intro_t) @{prop "False"}
wenzelm@55437
  1043
      then NONE else SOME intro_t
bulwahn@36246
  1044
    fun process_True intro_t =
bulwahn@36246
  1045
      map_filter_premises (fn p => if p = @{prop True} then NONE else SOME p) intro_t
bulwahn@36246
  1046
  in
bulwahn@36246
  1047
    Option.map (Skip_Proof.make_thm thy)
bulwahn@36246
  1048
      (process_False (process_True (prop_of (process intro))))
bulwahn@36246
  1049
  end
bulwahn@36246
  1050
bulwahn@40101
  1051
bulwahn@40101
  1052
(* importing introduction rules *)
bulwahn@40101
  1053
bulwahn@40101
  1054
fun import_intros inp_pred [] ctxt =
wenzelm@55437
  1055
      let
wenzelm@55437
  1056
        val ([outp_pred], ctxt') = Variable.import_terms true [inp_pred] ctxt
wenzelm@55437
  1057
        val T = fastype_of outp_pred
wenzelm@55437
  1058
        val paramTs = ho_argsT_of_typ (binder_types T)
wenzelm@55437
  1059
        val (param_names, _) = Variable.variant_fixes
wenzelm@55437
  1060
          (map (fn i => "p" ^ (string_of_int i)) (1 upto (length paramTs))) ctxt'
wenzelm@55437
  1061
        val params = map2 (curry Free) param_names paramTs
wenzelm@55437
  1062
      in
wenzelm@55437
  1063
        (((outp_pred, params), []), ctxt')
wenzelm@55437
  1064
      end
bulwahn@40101
  1065
  | import_intros inp_pred (th :: ths) ctxt =
wenzelm@55437
  1066
      let
wenzelm@55437
  1067
        val ((_, [th']), ctxt') = Variable.import true [th] ctxt
wenzelm@55437
  1068
        val thy = Proof_Context.theory_of ctxt'
wenzelm@55437
  1069
        val (pred, args) = strip_intro_concl th'
wenzelm@55437
  1070
        val T = fastype_of pred
wenzelm@55437
  1071
        val ho_args = ho_args_of_typ T args
wenzelm@55437
  1072
        fun subst_of (pred', pred) =
wenzelm@55437
  1073
          let
wenzelm@55437
  1074
            val subst = Sign.typ_match thy (fastype_of pred', fastype_of pred) Vartab.empty
wenzelm@55437
  1075
              handle Type.TYPE_MATCH =>
wenzelm@55437
  1076
                error ("Type mismatch of predicate " ^ fst (dest_Const pred) ^
wenzelm@55437
  1077
                  " (trying to match " ^ Syntax.string_of_typ ctxt (fastype_of pred') ^
wenzelm@55437
  1078
                  " and " ^ Syntax.string_of_typ ctxt (fastype_of pred) ^ ")" ^
wenzelm@55437
  1079
                  " in " ^ Display.string_of_thm ctxt th)
wenzelm@55437
  1080
          in map (fn (indexname, (s, T)) => ((indexname, s), T)) (Vartab.dest subst) end
wenzelm@55437
  1081
        fun instantiate_typ th =
wenzelm@55437
  1082
          let
wenzelm@55437
  1083
            val (pred', _) = strip_intro_concl th
wenzelm@55437
  1084
            val _ =
wenzelm@55437
  1085
              if not (fst (dest_Const pred) = fst (dest_Const pred')) then
wenzelm@55437
  1086
                raise Fail "Trying to instantiate another predicate"
wenzelm@55437
  1087
              else ()
wenzelm@55437
  1088
          in Thm.certify_instantiate (subst_of (pred', pred), []) th end
wenzelm@55437
  1089
        fun instantiate_ho_args th =
wenzelm@55437
  1090
          let
wenzelm@55437
  1091
            val (_, args') =
wenzelm@55437
  1092
              (strip_comb o HOLogic.dest_Trueprop o Logic.strip_imp_concl o prop_of) th
wenzelm@55437
  1093
            val ho_args' = map dest_Var (ho_args_of_typ T args')
wenzelm@55437
  1094
          in Thm.certify_instantiate ([], ho_args' ~~ ho_args) th end
wenzelm@55437
  1095
        val outp_pred =
wenzelm@55437
  1096
          Term_Subst.instantiate (subst_of (inp_pred, pred), []) inp_pred
wenzelm@55437
  1097
        val ((_, ths'), ctxt1) =
wenzelm@55437
  1098
          Variable.import false (map (instantiate_typ #> instantiate_ho_args) ths) ctxt'
wenzelm@55437
  1099
      in
wenzelm@55437
  1100
        (((outp_pred, ho_args), th' :: ths'), ctxt1)
wenzelm@55437
  1101
      end
wenzelm@55437
  1102
wenzelm@55437
  1103
bulwahn@40101
  1104
(* generation of case rules from user-given introduction rules *)
bulwahn@40101
  1105
bulwahn@40101
  1106
fun mk_args2 (Type (@{type_name Product_Type.prod}, [T1, T2])) st =
wenzelm@55437
  1107
      let
wenzelm@55437
  1108
        val (t1, st') = mk_args2 T1 st
wenzelm@55437
  1109
        val (t2, st'') = mk_args2 T2 st'
wenzelm@55437
  1110
      in
wenzelm@55437
  1111
        (HOLogic.mk_prod (t1, t2), st'')
wenzelm@55437
  1112
      end
wenzelm@55437
  1113
  (*| mk_args2 (T as Type ("fun", _)) (params, ctxt) =
bulwahn@40101
  1114
    let
bulwahn@40101
  1115
      val (S, U) = strip_type T
bulwahn@40101
  1116
    in
bulwahn@40101
  1117
      if U = HOLogic.boolT then
bulwahn@40101
  1118
        (hd params, (tl params, ctxt))
bulwahn@40101
  1119
      else
bulwahn@40101
  1120
        let
bulwahn@40101
  1121
          val ([x], ctxt') = Variable.variant_fixes ["x"] ctxt
bulwahn@40101
  1122
        in
bulwahn@40101
  1123
          (Free (x, T), (params, ctxt'))
bulwahn@40101
  1124
        end
bulwahn@40101
  1125
    end*)
bulwahn@40101
  1126
  | mk_args2 T (params, ctxt) =
wenzelm@55437
  1127
      let
wenzelm@55437
  1128
        val ([x], ctxt') = Variable.variant_fixes ["x"] ctxt
wenzelm@55437
  1129
      in
wenzelm@55437
  1130
        (Free (x, T), (params, ctxt'))
wenzelm@55437
  1131
      end
bulwahn@40101
  1132
bulwahn@40101
  1133
fun mk_casesrule ctxt pred introrules =
bulwahn@40101
  1134
  let
bulwahn@40101
  1135
    (* TODO: can be simplified if parameters are not treated specially ? *)
bulwahn@40101
  1136
    val (((pred, params), intros_th), ctxt1) = import_intros pred introrules ctxt
bulwahn@40101
  1137
    (* TODO: distinct required ? -- test case with more than one parameter! *)
bulwahn@40101
  1138
    val params = distinct (op aconv) params
bulwahn@40101
  1139
    val intros = map prop_of intros_th
bulwahn@40101
  1140
    val ([propname], ctxt2) = Variable.variant_fixes ["thesis"] ctxt1
bulwahn@40101
  1141
    val prop = HOLogic.mk_Trueprop (Free (propname, HOLogic.boolT))
bulwahn@40101
  1142
    val argsT = binder_types (fastype_of pred)
bulwahn@40101
  1143
    (* TODO: can be simplified if parameters are not treated specially ? <-- see uncommented code! *)
bulwahn@40101
  1144
    val (argvs, _) = fold_map mk_args2 argsT (params, ctxt2)
bulwahn@40101
  1145
    fun mk_case intro =
bulwahn@40101
  1146
      let
bulwahn@40101
  1147
        val (_, args) = (strip_comb o HOLogic.dest_Trueprop o Logic.strip_imp_concl) intro
bulwahn@40101
  1148
        val prems = Logic.strip_imp_prems intro
bulwahn@40101
  1149
        val eqprems =
bulwahn@40101
  1150
          map2 (HOLogic.mk_Trueprop oo (curry HOLogic.mk_eq)) argvs args
bulwahn@40101
  1151
        val frees = map Free (fold Term.add_frees (args @ prems) [])
bulwahn@40101
  1152
      in fold Logic.all frees (Logic.list_implies (eqprems @ prems, prop)) end
bulwahn@40101
  1153
    val assm = HOLogic.mk_Trueprop (list_comb (pred, argvs))
bulwahn@40101
  1154
    val cases = map mk_case intros
bulwahn@40101
  1155
  in Logic.list_implies (assm :: cases, prop) end;
wenzelm@55437
  1156
bulwahn@40101
  1157
bulwahn@40101
  1158
(* unifying constants to have the same type variables *)
bulwahn@40101
  1159
bulwahn@40101
  1160
fun unify_consts thy cs intr_ts =
wenzelm@55437
  1161
  let
bulwahn@40101
  1162
     val add_term_consts_2 = fold_aterms (fn Const c => insert (op =) c | _ => I);
bulwahn@40101
  1163
     fun varify (t, (i, ts)) =
bulwahn@40101
  1164
       let val t' = map_types (Logic.incr_tvar (i + 1)) (#2 (Type.varify_global [] t))
wenzelm@55437
  1165
       in (maxidx_of_term t', t' :: ts) end
wenzelm@55437
  1166
     val (i, cs') = List.foldr varify (~1, []) cs
wenzelm@55437
  1167
     val (i', intr_ts') = List.foldr varify (i, []) intr_ts
wenzelm@55437
  1168
     val rec_consts = fold add_term_consts_2 cs' []
wenzelm@55437
  1169
     val intr_consts = fold add_term_consts_2 intr_ts' []
bulwahn@40101
  1170
     fun unify (cname, cT) =
bulwahn@40101
  1171
       let val consts = map snd (filter (fn c => fst c = cname) intr_consts)
wenzelm@55437
  1172
       in fold (Sign.typ_unify thy) ((replicate (length consts) cT) ~~ consts) end
wenzelm@55437
  1173
     val (env, _) = fold unify rec_consts (Vartab.empty, i')
bulwahn@40101
  1174
     val subst = map_types (Envir.norm_type env)
bulwahn@40101
  1175
   in (map subst cs', map subst intr_ts')
wenzelm@55437
  1176
   end handle Type.TUNIFY =>
wenzelm@55437
  1177
     (warning "Occurrences of recursive constant have non-unifiable types"; (cs, intr_ts))
wenzelm@55437
  1178
bulwahn@40101
  1179
bulwahn@40101
  1180
(* preprocessing rules *)
bulwahn@40101
  1181
bulwahn@40101
  1182
fun preprocess_equality thy rule =
bulwahn@40101
  1183
  Conv.fconv_rule
bulwahn@40101
  1184
    (imp_prems_conv
wenzelm@51314
  1185
      (HOLogic.Trueprop_conv
wenzelm@51314
  1186
        (Conv.try_conv (Conv.rewr_conv (Thm.symmetric @{thm Predicate.eq_is_eq})))))
bulwahn@40101
  1187
    (Thm.transfer thy rule)
bulwahn@40101
  1188
bulwahn@40101
  1189
fun preprocess_intro thy = expand_tuples thy #> preprocess_equality thy
bulwahn@40101
  1190
wenzelm@55437
  1191
bulwahn@39541
  1192
(* defining a quickcheck predicate *)
bulwahn@39541
  1193
bulwahn@39541
  1194
fun strip_imp_prems (Const(@{const_name HOL.implies}, _) $ A $ B) = A :: strip_imp_prems B
bulwahn@39541
  1195
  | strip_imp_prems _ = [];
bulwahn@39541
  1196
haftmann@46662
  1197
fun strip_imp_concl (Const(@{const_name HOL.implies}, _) $ _ $ B) = strip_imp_concl B
haftmann@46662
  1198
  | strip_imp_concl A = A;
bulwahn@39541
  1199
wenzelm@55437
  1200
fun strip_horn A = (strip_imp_prems A, strip_imp_concl A)
bulwahn@39541
  1201
bulwahn@39541
  1202
fun define_quickcheck_predicate t thy =
bulwahn@39541
  1203
  let
bulwahn@39541
  1204
    val (vs, t') = strip_abs t
wenzelm@51552
  1205
    val vs' = Variable.variant_frees (Proof_Context.init_global thy) [] vs (* FIXME proper context!? *)
bulwahn@39541
  1206
    val t'' = subst_bounds (map Free (rev vs'), t')
bulwahn@39541
  1207
    val (prems, concl) = strip_horn t''
bulwahn@39541
  1208
    val constname = "quickcheck"
bulwahn@39541
  1209
    val full_constname = Sign.full_bname thy constname
bulwahn@39541
  1210
    val constT = map snd vs' ---> @{typ bool}
wenzelm@56239
  1211
    val thy1 = Sign.add_consts [(Binding.name constname, constT, NoSyn)] thy
bulwahn@39541
  1212
    val const = Const (full_constname, constT)
wenzelm@55437
  1213
    val t =
wenzelm@55437
  1214
      Logic.list_implies
wenzelm@55437
  1215
        (map HOLogic.mk_Trueprop (prems @ [HOLogic.mk_not concl]),
wenzelm@55437
  1216
          HOLogic.mk_Trueprop (list_comb (const, map Free vs')))
wenzelm@51552
  1217
    val intro =
wenzelm@51552
  1218
      Goal.prove (Proof_Context.init_global thy1) (map fst vs') [] t
wenzelm@59498
  1219
        (fn {context = ctxt, ...} => ALLGOALS (Skip_Proof.cheat_tac ctxt))
bulwahn@39541
  1220
  in
bulwahn@39541
  1221
    ((((full_constname, constT), vs'), intro), thy1)
bulwahn@39541
  1222
  end
bulwahn@39541
  1223
wenzelm@55437
  1224
end