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