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