src/HOL/Tools/Predicate_Compile/predicate_compile_aux.ML
author bulwahn
Wed Sep 29 10:33:15 2010 +0200 (2010-09-29)
changeset 39787 a44f6b11cdc4
parent 39658 b3644e40f661
child 39802 7cadad6a18cc
permissions -rw-r--r--
adding splitting of conjuncts in assumptions as forward rule on theorems; replacing term transformation for splitting conjuncts by theorem transformation; removing obsolete functions; tuned
     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 focus_ex : term -> Name.context -> ((string * typ) list * term) * Name.context
    55   val strip_all : term -> (string * typ) list * term
    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_predT : typ -> typ,
    69     dest_predT : typ -> typ,
    70     mk_bot : typ -> term,
    71     mk_single : term -> term,
    72     mk_bind : term * term -> term,
    73     mk_sup : 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_predT : compilation_funs -> typ -> typ
    80   val dest_predT : compilation_funs -> typ -> typ
    81   val mk_bot : compilation_funs -> typ -> term
    82   val mk_single : compilation_funs -> term -> term
    83   val mk_bind : compilation_funs -> term * term -> term
    84   val mk_sup : 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   val negative_compilation_of : compilation -> compilation
    94   val compilation_for_polarity : bool -> compilation -> compilation
    95   val string_of_compilation : compilation -> string
    96   val compilation_names : (string * compilation) list
    97   val non_random_compilations : compilation list
    98   val random_compilations : compilation list
    99   (* Different options for compiler *)
   100   datatype options = Options of {  
   101     expected_modes : (string * mode list) option,
   102     proposed_modes : (string * mode list) list,
   103     proposed_names : ((string * mode) * string) list,
   104     show_steps : bool,
   105     show_proof_trace : bool,
   106     show_intermediate_results : bool,
   107     show_mode_inference : bool,
   108     show_modes : bool,
   109     show_compilation : bool,
   110     show_caught_failures : bool,
   111     show_invalid_clauses : bool,
   112     skip_proof : bool,
   113     no_topmost_reordering : bool,
   114     function_flattening : bool,
   115     fail_safe_function_flattening : bool,
   116     specialise : bool,
   117     no_higher_order_predicate : string list,
   118     inductify : bool,
   119     detect_switches : bool,
   120     compilation : compilation
   121   };
   122   val expected_modes : options -> (string * mode list) option
   123   val proposed_modes : options -> string -> mode list option
   124   val proposed_names : options -> string -> mode -> string option
   125   val show_steps : options -> bool
   126   val show_proof_trace : options -> bool
   127   val show_intermediate_results : options -> bool
   128   val show_mode_inference : options -> bool
   129   val show_modes : options -> bool
   130   val show_compilation : options -> bool
   131   val show_caught_failures : options -> bool
   132   val show_invalid_clauses : options -> bool
   133   val skip_proof : options -> bool
   134   val no_topmost_reordering : options -> bool
   135   val function_flattening : options -> bool
   136   val fail_safe_function_flattening : options -> bool
   137   val specialise : options -> bool
   138   val no_higher_order_predicate : options -> string list
   139   val is_inductify : options -> bool
   140   val detect_switches : options -> bool
   141   val compilation : options -> compilation
   142   val default_options : options
   143   val bool_options : string list
   144   val print_step : options -> string -> unit
   145   (* conversions *)
   146   val imp_prems_conv : conv -> conv
   147   (* simple transformations *)
   148   val split_conjuncts_in_assms : Proof.context -> thm -> thm
   149   val expand_tuples : theory -> thm -> thm
   150   val eta_contract_ho_arguments : theory -> thm -> thm
   151   val remove_equalities : theory -> thm -> thm
   152   val remove_pointless_clauses : thm -> thm list
   153   val peephole_optimisation : theory -> thm -> thm option
   154   val define_quickcheck_predicate :
   155     term -> theory -> (((string * typ) * (string * typ) list) * thm) * theory 
   156 end;
   157 
   158 structure Predicate_Compile_Aux : PREDICATE_COMPILE_AUX =
   159 struct
   160 
   161 (* general functions *)
   162 
   163 fun apfst3 f (x, y, z) = (f x, y, z)
   164 fun apsnd3 f (x, y, z) = (x, f y, z)
   165 fun aptrd3 f (x, y, z) = (x, y, f z)
   166 
   167 fun comb_option f (SOME x1, SOME x2) = SOME (f (x1, x2))
   168   | comb_option f (NONE, SOME x2) = SOME x2
   169   | comb_option f (SOME x1, NONE) = SOME x1
   170   | comb_option f (NONE, NONE) = NONE
   171 
   172 fun map2_optional f (x :: xs) (y :: ys) = f x (SOME y) :: (map2_optional f xs ys)
   173   | map2_optional f (x :: xs) [] = (f x NONE) :: (map2_optional f xs [])
   174   | map2_optional f [] [] = []
   175 
   176 fun find_indices f xs =
   177   map_filter (fn (i, true) => SOME i | (i, false) => NONE) (map_index (apsnd f) xs)
   178 
   179 fun assert check = if check then () else raise Fail "Assertion failed!"
   180 
   181 (* mode *)
   182 
   183 datatype mode = Bool | Input | Output | Pair of mode * mode | Fun of mode * mode
   184 
   185 (* equality of instantiatedness with respect to equivalences:
   186   Pair Input Input == Input and Pair Output Output == Output *)
   187 fun eq_mode (Fun (m1, m2), Fun (m3, m4)) = eq_mode (m1, m3) andalso eq_mode (m2, m4)
   188   | eq_mode (Pair (m1, m2), Pair (m3, m4)) = eq_mode (m1, m3) andalso eq_mode (m2, m4)
   189   | eq_mode (Pair (m1, m2), Input) = eq_mode (m1, Input) andalso eq_mode (m2, Input)
   190   | eq_mode (Pair (m1, m2), Output) = eq_mode (m1, Output) andalso eq_mode (m2, Output)
   191   | eq_mode (Input, Pair (m1, m2)) = eq_mode (Input, m1) andalso eq_mode (Input, m2)
   192   | eq_mode (Output, Pair (m1, m2)) = eq_mode (Output, m1) andalso eq_mode (Output, m2)
   193   | eq_mode (Input, Input) = true
   194   | eq_mode (Output, Output) = true
   195   | eq_mode (Bool, Bool) = true
   196   | eq_mode _ = false
   197 
   198 fun mode_ord (Input, Output) = LESS
   199   | mode_ord (Output, Input) = GREATER
   200   | mode_ord (Input, Input) = EQUAL
   201   | mode_ord (Output, Output) = EQUAL
   202   | mode_ord (Bool, Bool) = EQUAL
   203   | mode_ord (Pair (m1, m2), Pair (m3, m4)) = prod_ord mode_ord mode_ord ((m1, m2), (m3, m4))
   204   | mode_ord (Fun (m1, m2), Fun (m3, m4)) = prod_ord mode_ord mode_ord ((m1, m2), (m3, m4))
   205  
   206 fun list_fun_mode [] = Bool
   207   | list_fun_mode (m :: ms) = Fun (m, list_fun_mode ms)
   208 
   209 (* name: binder_modes? *)
   210 fun strip_fun_mode (Fun (mode, mode')) = mode :: strip_fun_mode mode'
   211   | strip_fun_mode Bool = []
   212   | strip_fun_mode _ = raise Fail "Bad mode for strip_fun_mode"
   213 
   214 (* name: strip_fun_mode? *)
   215 fun dest_fun_mode (Fun (mode, mode')) = mode :: dest_fun_mode mode'
   216   | dest_fun_mode mode = [mode]
   217 
   218 fun dest_tuple_mode (Pair (mode, mode')) = mode :: dest_tuple_mode mode'
   219   | dest_tuple_mode _ = []
   220 
   221 fun all_modes_of_typ' (T as Type ("fun", _)) = 
   222   let
   223     val (S, U) = strip_type T
   224   in
   225     if U = HOLogic.boolT then
   226       fold_rev (fn m1 => fn m2 => map_product (curry Fun) m1 m2)
   227         (map all_modes_of_typ' S) [Bool]
   228     else
   229       [Input, Output]
   230   end
   231   | all_modes_of_typ' (Type (@{type_name Product_Type.prod}, [T1, T2])) = 
   232     map_product (curry Pair) (all_modes_of_typ' T1) (all_modes_of_typ' T2)
   233   | all_modes_of_typ' _ = [Input, Output]
   234 
   235 fun all_modes_of_typ (T as Type ("fun", _)) =
   236     let
   237       val (S, U) = strip_type T
   238     in
   239       if U = @{typ bool} then
   240         fold_rev (fn m1 => fn m2 => map_product (curry Fun) m1 m2)
   241           (map all_modes_of_typ' S) [Bool]
   242       else
   243         raise Fail "Invocation of all_modes_of_typ with a non-predicate type"
   244     end
   245   | all_modes_of_typ @{typ bool} = [Bool]
   246   | all_modes_of_typ T =
   247     raise Fail "Invocation of all_modes_of_typ with a non-predicate type"
   248 
   249 fun all_smodes_of_typ (T as Type ("fun", _)) =
   250   let
   251     val (S, U) = strip_type T
   252     fun all_smodes (Type (@{type_name Product_Type.prod}, [T1, T2])) = 
   253       map_product (curry Pair) (all_smodes T1) (all_smodes T2)
   254       | all_smodes _ = [Input, Output]
   255   in
   256     if U = HOLogic.boolT then
   257       fold_rev (fn m1 => fn m2 => map_product (curry Fun) m1 m2) (map all_smodes S) [Bool]
   258     else
   259       raise Fail "invalid type for predicate"
   260   end
   261 
   262 fun ho_arg_modes_of mode =
   263   let
   264     fun ho_arg_mode (m as Fun _) =  [m]
   265       | ho_arg_mode (Pair (m1, m2)) = ho_arg_mode m1 @ ho_arg_mode m2
   266       | ho_arg_mode _ = []
   267   in
   268     maps ho_arg_mode (strip_fun_mode mode)
   269   end
   270 
   271 fun ho_args_of mode ts =
   272   let
   273     fun ho_arg (Fun _) (SOME t) = [t]
   274       | ho_arg (Fun _) NONE = raise Fail "mode and term do not match"
   275       | ho_arg (Pair (m1, m2)) (SOME (Const (@{const_name Pair}, _) $ t1 $ t2)) =
   276           ho_arg m1 (SOME t1) @ ho_arg m2 (SOME t2)
   277       | ho_arg (Pair (m1, m2)) NONE = ho_arg m1 NONE @ ho_arg m2 NONE
   278       | ho_arg _ _ = []
   279   in
   280     flat (map2_optional ho_arg (strip_fun_mode mode) ts)
   281   end
   282 
   283 fun ho_args_of_typ T ts =
   284   let
   285     fun ho_arg (T as Type("fun", [_,_])) (SOME t) = if body_type T = @{typ bool} then [t] else []
   286       | ho_arg (Type("fun", [_,_])) NONE = raise Fail "mode and term do not match"
   287       | ho_arg (Type(@{type_name "Product_Type.prod"}, [T1, T2]))
   288          (SOME (Const (@{const_name Pair}, _) $ t1 $ t2)) =
   289           ho_arg T1 (SOME t1) @ ho_arg T2 (SOME t2)
   290       | ho_arg (Type(@{type_name "Product_Type.prod"}, [T1, T2])) NONE =
   291           ho_arg T1 NONE @ ho_arg T2 NONE
   292       | ho_arg _ _ = []
   293   in
   294     flat (map2_optional ho_arg (binder_types T) ts)
   295   end
   296 
   297 fun ho_argsT_of_typ Ts =
   298   let
   299     fun ho_arg (T as Type("fun", [_,_])) = if body_type T = @{typ bool} then [T] else []
   300       | ho_arg (Type(@{type_name "Product_Type.prod"}, [T1, T2])) =
   301           ho_arg T1 @ ho_arg T2
   302       | ho_arg _ = []
   303   in
   304     maps ho_arg Ts
   305   end
   306   
   307 
   308 (* temporary function should be replaced by unsplit_input or so? *)
   309 fun replace_ho_args mode hoargs ts =
   310   let
   311     fun replace (Fun _, _) (arg' :: hoargs') = (arg', hoargs')
   312       | replace (Pair (m1, m2), Const (@{const_name Pair}, T) $ t1 $ t2) hoargs =
   313         let
   314           val (t1', hoargs') = replace (m1, t1) hoargs
   315           val (t2', hoargs'') = replace (m2, t2) hoargs'
   316         in
   317           (Const (@{const_name Pair}, T) $ t1' $ t2', hoargs'')
   318         end
   319       | replace (_, t) hoargs = (t, hoargs)
   320   in
   321     fst (fold_map replace (strip_fun_mode mode ~~ ts) hoargs)
   322   end
   323 
   324 fun ho_argsT_of mode Ts =
   325   let
   326     fun ho_arg (Fun _) T = [T]
   327       | ho_arg (Pair (m1, m2)) (Type (@{type_name Product_Type.prod}, [T1, T2])) = ho_arg m1 T1 @ ho_arg m2 T2
   328       | ho_arg _ _ = []
   329   in
   330     flat (map2 ho_arg (strip_fun_mode mode) Ts)
   331   end
   332 
   333 (* splits mode and maps function to higher-order argument types *)
   334 fun split_map_mode f mode ts =
   335   let
   336     fun split_arg_mode' (m as Fun _) t = f m t
   337       | split_arg_mode' (Pair (m1, m2)) (Const (@{const_name Pair}, _) $ t1 $ t2) =
   338         let
   339           val (i1, o1) = split_arg_mode' m1 t1
   340           val (i2, o2) = split_arg_mode' m2 t2
   341         in
   342           (comb_option HOLogic.mk_prod (i1, i2), comb_option HOLogic.mk_prod (o1, o2))
   343         end
   344       | split_arg_mode' m t =
   345         if eq_mode (m, Input) then (SOME t, NONE)
   346         else if eq_mode (m, Output) then (NONE,  SOME t)
   347         else raise Fail "split_map_mode: mode and term do not match"
   348   in
   349     (pairself (map_filter I) o split_list) (map2 split_arg_mode' (strip_fun_mode mode) ts)
   350   end
   351 
   352 (* splits mode and maps function to higher-order argument types *)
   353 fun split_map_modeT f mode Ts =
   354   let
   355     fun split_arg_mode' (m as Fun _) T = f m T
   356       | split_arg_mode' (Pair (m1, m2)) (Type (@{type_name Product_Type.prod}, [T1, T2])) =
   357         let
   358           val (i1, o1) = split_arg_mode' m1 T1
   359           val (i2, o2) = split_arg_mode' m2 T2
   360         in
   361           (comb_option HOLogic.mk_prodT (i1, i2), comb_option HOLogic.mk_prodT (o1, o2))
   362         end
   363       | split_arg_mode' Input T = (SOME T, NONE)
   364       | split_arg_mode' Output T = (NONE,  SOME T)
   365       | split_arg_mode' _ _ = raise Fail "split_modeT': mode and type do not match"
   366   in
   367     (pairself (map_filter I) o split_list) (map2 split_arg_mode' (strip_fun_mode mode) Ts)
   368   end
   369 
   370 fun split_mode mode ts = split_map_mode (fn _ => fn _ => (NONE, NONE)) mode ts
   371 
   372 fun fold_map_aterms_prodT comb f (Type (@{type_name Product_Type.prod}, [T1, T2])) s =
   373   let
   374     val (x1, s') = fold_map_aterms_prodT comb f T1 s
   375     val (x2, s'') = fold_map_aterms_prodT comb f T2 s'
   376   in
   377     (comb x1 x2, s'')
   378   end
   379   | fold_map_aterms_prodT comb f T s = f T s
   380 
   381 fun map_filter_prod f (Const (@{const_name Pair}, _) $ t1 $ t2) =
   382   comb_option HOLogic.mk_prod (map_filter_prod f t1, map_filter_prod f t2)
   383   | map_filter_prod f t = f t
   384 
   385 (* obviously, split_mode' and split_modeT' do not match? where does that cause problems? *)
   386   
   387 fun split_modeT' mode Ts =
   388   let
   389     fun split_arg_mode' (Fun _) T = ([], [])
   390       | split_arg_mode' (Pair (m1, m2)) (Type (@{type_name Product_Type.prod}, [T1, T2])) =
   391         let
   392           val (i1, o1) = split_arg_mode' m1 T1
   393           val (i2, o2) = split_arg_mode' m2 T2
   394         in
   395           (i1 @ i2, o1 @ o2)
   396         end
   397       | split_arg_mode' Input T = ([T], [])
   398       | split_arg_mode' Output T = ([], [T])
   399       | split_arg_mode' _ _ = raise Fail "split_modeT': mode and type do not match"
   400   in
   401     (pairself flat o split_list) (map2 split_arg_mode' (strip_fun_mode mode) Ts)
   402   end
   403 
   404 fun string_of_mode mode =
   405   let
   406     fun string_of_mode1 Input = "i"
   407       | string_of_mode1 Output = "o"
   408       | string_of_mode1 Bool = "bool"
   409       | string_of_mode1 mode = "(" ^ (string_of_mode3 mode) ^ ")"
   410     and string_of_mode2 (Pair (m1, m2)) = string_of_mode3 m1 ^ " * " ^  string_of_mode2 m2
   411       | string_of_mode2 mode = string_of_mode1 mode
   412     and string_of_mode3 (Fun (m1, m2)) = string_of_mode2 m1 ^ " => " ^ string_of_mode3 m2
   413       | string_of_mode3 mode = string_of_mode2 mode
   414   in string_of_mode3 mode end
   415 
   416 fun ascii_string_of_mode mode' =
   417   let
   418     fun ascii_string_of_mode' Input = "i"
   419       | ascii_string_of_mode' Output = "o"
   420       | ascii_string_of_mode' Bool = "b"
   421       | ascii_string_of_mode' (Pair (m1, m2)) =
   422           "P" ^ ascii_string_of_mode' m1 ^ ascii_string_of_mode'_Pair m2
   423       | ascii_string_of_mode' (Fun (m1, m2)) = 
   424           "F" ^ ascii_string_of_mode' m1 ^ ascii_string_of_mode'_Fun m2 ^ "B"
   425     and ascii_string_of_mode'_Fun (Fun (m1, m2)) =
   426           ascii_string_of_mode' m1 ^ (if m2 = Bool then "" else "_" ^ ascii_string_of_mode'_Fun m2)
   427       | ascii_string_of_mode'_Fun Bool = "B"
   428       | ascii_string_of_mode'_Fun m = ascii_string_of_mode' m
   429     and ascii_string_of_mode'_Pair (Pair (m1, m2)) =
   430           ascii_string_of_mode' m1 ^ ascii_string_of_mode'_Pair m2
   431       | ascii_string_of_mode'_Pair m = ascii_string_of_mode' m
   432   in ascii_string_of_mode'_Fun mode' end
   433 
   434 (* premises *)
   435 
   436 datatype indprem = Prem of term | Negprem of term | Sidecond of term
   437   | Generator of (string * typ);
   438 
   439 fun dest_indprem (Prem t) = t
   440   | dest_indprem (Negprem t) = t
   441   | dest_indprem (Sidecond t) = t
   442   | dest_indprem (Generator _) = raise Fail "cannot destruct generator"
   443 
   444 fun map_indprem f (Prem t) = Prem (f t)
   445   | map_indprem f (Negprem t) = Negprem (f t)
   446   | map_indprem f (Sidecond t) = Sidecond (f t)
   447   | map_indprem f (Generator (v, T)) = Generator (dest_Free (f (Free (v, T))))
   448 
   449 (* general syntactic functions *)
   450 
   451 (*Like dest_conj, but flattens conjunctions however nested*)
   452 fun conjuncts_aux (Const (@{const_name HOL.conj}, _) $ t $ t') conjs = conjuncts_aux t (conjuncts_aux t' conjs)
   453   | conjuncts_aux t conjs = t::conjs;
   454 
   455 fun conjuncts t = conjuncts_aux t [];
   456 
   457 fun is_equationlike_term (Const ("==", _) $ _ $ _) = true
   458   | is_equationlike_term (Const (@{const_name Trueprop}, _) $ (Const (@{const_name HOL.eq}, _) $ _ $ _)) = true
   459   | is_equationlike_term _ = false
   460   
   461 val is_equationlike = is_equationlike_term o prop_of 
   462 
   463 fun is_pred_equation_term (Const ("==", _) $ u $ v) =
   464   (fastype_of u = @{typ bool}) andalso (fastype_of v = @{typ bool})
   465   | is_pred_equation_term _ = false
   466   
   467 val is_pred_equation = is_pred_equation_term o prop_of 
   468 
   469 fun is_intro_term constname t =
   470   the_default false (try (fn t => case fst (strip_comb (HOLogic.dest_Trueprop (Logic.strip_imp_concl t))) of
   471     Const (c, _) => c = constname
   472   | _ => false) t)
   473   
   474 fun is_intro constname t = is_intro_term constname (prop_of t)
   475 
   476 fun is_pred thy constname = (body_type (Sign.the_const_type thy constname) = HOLogic.boolT);
   477 
   478 fun is_predT (T as Type("fun", [_, _])) = (snd (strip_type T) = @{typ bool})
   479   | is_predT _ = false
   480 
   481 (*** check if a term contains only constructor functions ***)
   482 (* TODO: another copy in the core! *)
   483 (* FIXME: constructor terms are supposed to be seen in the way the code generator
   484   sees constructors.*)
   485 fun is_constrt thy =
   486   let
   487     val cnstrs = flat (maps
   488       (map (fn (_, (Tname, _, cs)) => map (apsnd (rpair Tname o length)) cs) o #descr o snd)
   489       (Symtab.dest (Datatype.get_all thy)));
   490     fun check t = (case strip_comb t of
   491         (Var _, []) => true
   492       | (Free _, []) => true
   493       | (Const (s, T), ts) => (case (AList.lookup (op =) cnstrs s, body_type T) of
   494             (SOME (i, Tname), Type (Tname', _)) => length ts = i andalso Tname = Tname' andalso forall check ts
   495           | _ => false)
   496       | _ => false)
   497   in check end;
   498 
   499 fun is_funtype (Type ("fun", [_, _])) = true
   500   | is_funtype _ = false;
   501 
   502 fun is_Type (Type _) = true
   503   | is_Type _ = false
   504 
   505 (* returns true if t is an application of an datatype constructor *)
   506 (* which then consequently would be splitted *)
   507 (* else false *)
   508 (*
   509 fun is_constructor thy t =
   510   if (is_Type (fastype_of t)) then
   511     (case DatatypePackage.get_datatype thy ((fst o dest_Type o fastype_of) t) of
   512       NONE => false
   513     | SOME info => (let
   514       val constr_consts = maps (fn (_, (_, _, constrs)) => map fst constrs) (#descr info)
   515       val (c, _) = strip_comb t
   516       in (case c of
   517         Const (name, _) => name mem_string constr_consts
   518         | _ => false) end))
   519   else false
   520 *)
   521 
   522 val is_constr = Code.is_constr o ProofContext.theory_of;
   523 
   524 fun strip_all t = (Term.strip_all_vars t, Term.strip_all_body t)
   525 
   526 fun strip_ex (Const (@{const_name Ex}, _) $ Abs (x, T, t)) =
   527   let
   528     val (xTs, t') = strip_ex t
   529   in
   530     ((x, T) :: xTs, t')
   531   end
   532   | strip_ex t = ([], t)
   533 
   534 fun focus_ex t nctxt =
   535   let
   536     val ((xs, Ts), t') = apfst split_list (strip_ex t) 
   537     val (xs', nctxt') = Name.variants xs nctxt;
   538     val ps' = xs' ~~ Ts;
   539     val vs = map Free ps';
   540     val t'' = Term.subst_bounds (rev vs, t');
   541   in ((ps', t''), nctxt') end;
   542 
   543 (* introduction rule combinators *)
   544 
   545 fun map_atoms f intro = 
   546   let
   547     val (literals, head) = Logic.strip_horn intro
   548     fun appl t = (case t of
   549         (@{term Not} $ t') => HOLogic.mk_not (f t')
   550       | _ => f t)
   551   in
   552     Logic.list_implies
   553       (map (HOLogic.mk_Trueprop o appl o HOLogic.dest_Trueprop) literals, head)
   554   end
   555 
   556 fun fold_atoms f intro s =
   557   let
   558     val (literals, head) = Logic.strip_horn intro
   559     fun appl t s = (case t of
   560       (@{term Not} $ t') => f t' s
   561       | _ => f t s)
   562   in fold appl (map HOLogic.dest_Trueprop literals) s end
   563 
   564 fun fold_map_atoms f intro s =
   565   let
   566     val (literals, head) = Logic.strip_horn intro
   567     fun appl t s = (case t of
   568       (@{term Not} $ t') => apfst HOLogic.mk_not (f t' s)
   569       | _ => f t s)
   570     val (literals', s') = fold_map appl (map HOLogic.dest_Trueprop literals) s
   571   in
   572     (Logic.list_implies (map HOLogic.mk_Trueprop literals', head), s')
   573   end;
   574 
   575 fun map_premises f intro =
   576   let
   577     val (premises, head) = Logic.strip_horn intro
   578   in
   579     Logic.list_implies (map f premises, head)
   580   end
   581 
   582 fun map_filter_premises f intro =
   583   let
   584     val (premises, head) = Logic.strip_horn intro
   585   in
   586     Logic.list_implies (map_filter f premises, head)
   587   end
   588 
   589 fun maps_premises f intro =
   590   let
   591     val (premises, head) = Logic.strip_horn intro
   592   in
   593     Logic.list_implies (maps f premises, head)
   594   end
   595 
   596 fun map_concl f intro =
   597   let
   598     val (premises, head) = Logic.strip_horn intro
   599   in
   600     Logic.list_implies (premises, f head)
   601   end
   602 
   603 (* combinators to apply a function to all basic parts of nested products *)
   604 
   605 fun map_products f (Const (@{const_name Pair}, T) $ t1 $ t2) =
   606   Const (@{const_name Pair}, T) $ map_products f t1 $ map_products f t2
   607   | map_products f t = f t
   608 
   609 (* split theorems of case expressions *)
   610 
   611 fun prepare_split_thm ctxt split_thm =
   612     (split_thm RS @{thm iffD2})
   613     |> Local_Defs.unfold ctxt [@{thm atomize_conjL[symmetric]},
   614       @{thm atomize_all[symmetric]}, @{thm atomize_imp[symmetric]}]
   615 
   616 fun find_split_thm thy (Const (name, T)) = Option.map #split (Datatype_Data.info_of_case thy name)
   617   | find_split_thm thy _ = NONE
   618 
   619 (* lifting term operations to theorems *)
   620 
   621 fun map_term thy f th =
   622   Skip_Proof.make_thm thy (f (prop_of th))
   623 
   624 (*
   625 fun equals_conv lhs_cv rhs_cv ct =
   626   case Thm.term_of ct of
   627     Const ("==", _) $ _ $ _ => Conv.arg_conv cv ct  
   628   | _ => error "equals_conv"  
   629 *)
   630 
   631 (* Different compilations *)
   632 
   633 datatype compilation = Pred | Depth_Limited | Random | Depth_Limited_Random | DSeq | Annotated
   634   | Pos_Random_DSeq | Neg_Random_DSeq | New_Pos_Random_DSeq | New_Neg_Random_DSeq
   635 
   636 fun negative_compilation_of Pos_Random_DSeq = Neg_Random_DSeq
   637   | negative_compilation_of Neg_Random_DSeq = Pos_Random_DSeq
   638   | negative_compilation_of New_Pos_Random_DSeq = New_Neg_Random_DSeq
   639   | negative_compilation_of New_Neg_Random_DSeq = New_Pos_Random_DSeq
   640   | negative_compilation_of c = c
   641   
   642 fun compilation_for_polarity false Pos_Random_DSeq = Neg_Random_DSeq
   643   | compilation_for_polarity false New_Pos_Random_DSeq = New_Neg_Random_DSeq
   644   | compilation_for_polarity _ c = c
   645 
   646 fun string_of_compilation c =
   647   case c of
   648     Pred => ""
   649   | Random => "random"
   650   | Depth_Limited => "depth limited"
   651   | Depth_Limited_Random => "depth limited random"
   652   | DSeq => "dseq"
   653   | Annotated => "annotated"
   654   | Pos_Random_DSeq => "pos_random dseq"
   655   | Neg_Random_DSeq => "neg_random_dseq"
   656   | New_Pos_Random_DSeq => "new_pos_random dseq"
   657   | New_Neg_Random_DSeq => "new_neg_random_dseq"
   658 
   659 val compilation_names = [("pred", Pred),
   660   ("random", Random),
   661   ("depth_limited", Depth_Limited),
   662   ("depth_limited_random", Depth_Limited_Random),
   663   (*("annotated", Annotated),*)
   664   ("dseq", DSeq), ("random_dseq", Pos_Random_DSeq),
   665   ("new_random_dseq", New_Pos_Random_DSeq)]
   666 
   667 val non_random_compilations = [Pred, Depth_Limited, DSeq, Annotated]
   668 
   669 
   670 val random_compilations = [Random, Depth_Limited_Random,
   671   Pos_Random_DSeq, Neg_Random_DSeq, New_Pos_Random_DSeq, New_Neg_Random_DSeq]
   672 
   673 (* datastructures and setup for generic compilation *)
   674 
   675 datatype compilation_funs = CompilationFuns of {
   676   mk_predT : typ -> typ,
   677   dest_predT : typ -> typ,
   678   mk_bot : typ -> term,
   679   mk_single : term -> term,
   680   mk_bind : term * term -> term,
   681   mk_sup : term * term -> term,
   682   mk_if : term -> term,
   683   mk_iterate_upto : typ -> term * term * term -> term,
   684   mk_not : term -> term,
   685   mk_map : typ -> typ -> term -> term -> term
   686 };
   687 
   688 fun mk_predT (CompilationFuns funs) = #mk_predT funs
   689 fun dest_predT (CompilationFuns funs) = #dest_predT funs
   690 fun mk_bot (CompilationFuns funs) = #mk_bot funs
   691 fun mk_single (CompilationFuns funs) = #mk_single funs
   692 fun mk_bind (CompilationFuns funs) = #mk_bind funs
   693 fun mk_sup (CompilationFuns funs) = #mk_sup funs
   694 fun mk_if (CompilationFuns funs) = #mk_if funs
   695 fun mk_iterate_upto (CompilationFuns funs) = #mk_iterate_upto funs
   696 fun mk_not (CompilationFuns funs) = #mk_not funs
   697 fun mk_map (CompilationFuns funs) = #mk_map funs
   698 
   699 (** function types and names of different compilations **)
   700 
   701 fun funT_of compfuns mode T =
   702   let
   703     val Ts = binder_types T
   704     val (inTs, outTs) = split_map_modeT (fn m => fn T => (SOME (funT_of compfuns m T), NONE)) mode Ts
   705   in
   706     inTs ---> (mk_predT compfuns (HOLogic.mk_tupleT outTs))
   707   end;
   708 
   709 (* Different options for compiler *)
   710 
   711 datatype options = Options of {  
   712   expected_modes : (string * mode list) option,
   713   proposed_modes : (string * mode list) list,
   714   proposed_names : ((string * mode) * string) list,
   715   show_steps : bool,
   716   show_proof_trace : bool,
   717   show_intermediate_results : bool,
   718   show_mode_inference : bool,
   719   show_modes : bool,
   720   show_compilation : bool,
   721   show_caught_failures : bool,
   722   show_invalid_clauses : bool,
   723   skip_proof : bool,
   724   no_topmost_reordering : bool,
   725   function_flattening : bool,
   726   specialise : bool,
   727   fail_safe_function_flattening : bool,
   728   no_higher_order_predicate : string list,
   729   inductify : bool,
   730   detect_switches : bool,
   731   compilation : compilation
   732 };
   733 
   734 fun expected_modes (Options opt) = #expected_modes opt
   735 fun proposed_modes (Options opt) = AList.lookup (op =) (#proposed_modes opt)
   736 fun proposed_names (Options opt) name mode = AList.lookup (eq_pair (op =) eq_mode)
   737   (#proposed_names opt) (name, mode)
   738 
   739 fun show_steps (Options opt) = #show_steps opt
   740 fun show_intermediate_results (Options opt) = #show_intermediate_results opt
   741 fun show_proof_trace (Options opt) = #show_proof_trace opt
   742 fun show_modes (Options opt) = #show_modes opt
   743 fun show_mode_inference (Options opt) = #show_mode_inference opt
   744 fun show_compilation (Options opt) = #show_compilation opt
   745 fun show_caught_failures (Options opt) = #show_caught_failures opt
   746 fun show_invalid_clauses (Options opt) = #show_invalid_clauses opt
   747 fun skip_proof (Options opt) = #skip_proof opt
   748 
   749 fun function_flattening (Options opt) = #function_flattening opt
   750 fun fail_safe_function_flattening (Options opt) = #fail_safe_function_flattening opt
   751 fun specialise (Options opt) = #specialise opt
   752 fun no_topmost_reordering (Options opt) = #no_topmost_reordering opt
   753 fun no_higher_order_predicate (Options opt) = #no_higher_order_predicate opt
   754 
   755 fun is_inductify (Options opt) = #inductify opt
   756 
   757 fun compilation (Options opt) = #compilation opt
   758 
   759 fun detect_switches (Options opt) = #detect_switches opt
   760 
   761 val default_options = Options {
   762   expected_modes = NONE,
   763   proposed_modes = [],
   764   proposed_names = [],
   765   show_steps = false,
   766   show_intermediate_results = false,
   767   show_proof_trace = false,
   768   show_modes = false,
   769   show_mode_inference = false,
   770   show_compilation = false,
   771   show_caught_failures = false,
   772   show_invalid_clauses = false,
   773   skip_proof = true,
   774   no_topmost_reordering = false,
   775   function_flattening = false,
   776   specialise = false,
   777   fail_safe_function_flattening = false,
   778   no_higher_order_predicate = [],
   779   inductify = false,
   780   detect_switches = true,
   781   compilation = Pred
   782 }
   783 
   784 val bool_options = ["show_steps", "show_intermediate_results", "show_proof_trace", "show_modes",
   785   "show_mode_inference", "show_compilation", "show_invalid_clauses", "skip_proof", "inductify",
   786   "no_function_flattening", "detect_switches", "specialise", "no_topmost_reordering"]
   787 
   788 fun print_step options s =
   789   if show_steps options then tracing s else ()
   790 
   791 (* simple transformations *)
   792 
   793 (** tuple processing **)
   794 
   795 fun rewrite_args [] (pats, intro_t, ctxt) = (pats, intro_t, ctxt)
   796   | rewrite_args (arg::args) (pats, intro_t, ctxt) = 
   797     (case HOLogic.strip_tupleT (fastype_of arg) of
   798       (Ts as _ :: _ :: _) =>
   799       let
   800         fun rewrite_arg' (Const (@{const_name Pair}, _) $ _ $ t2, Type (@{type_name Product_Type.prod}, [_, T2]))
   801           (args, (pats, intro_t, ctxt)) = rewrite_arg' (t2, T2) (args, (pats, intro_t, ctxt))
   802           | rewrite_arg' (t, Type (@{type_name Product_Type.prod}, [T1, T2])) (args, (pats, intro_t, ctxt)) =
   803             let
   804               val thy = ProofContext.theory_of ctxt
   805               val ([x, y], ctxt') = Variable.variant_fixes ["x", "y"] ctxt
   806               val pat = (t, HOLogic.mk_prod (Free (x, T1), Free (y, T2)))
   807               val intro_t' = Pattern.rewrite_term thy [pat] [] intro_t
   808               val args' = map (Pattern.rewrite_term thy [pat] []) args
   809             in
   810               rewrite_arg' (Free (y, T2), T2) (args', (pat::pats, intro_t', ctxt'))
   811             end
   812           | rewrite_arg' _ (args, (pats, intro_t, ctxt)) = (args, (pats, intro_t, ctxt))
   813         val (args', (pats, intro_t', ctxt')) = rewrite_arg' (arg, fastype_of arg)
   814           (args, (pats, intro_t, ctxt))
   815       in
   816         rewrite_args args' (pats, intro_t', ctxt')
   817       end
   818   | _ => rewrite_args args (pats, intro_t, ctxt))
   819 
   820 fun rewrite_prem atom =
   821   let
   822     val (_, args) = strip_comb atom
   823   in rewrite_args args end
   824 
   825 fun split_conjuncts_in_assms ctxt th =
   826   let
   827     val ((_, [fixed_th]), ctxt') = Variable.import false [th] ctxt 
   828     fun split_conjs i nprems th =
   829       if i > nprems then th
   830       else
   831         case try Drule.RSN (@{thm conjI}, (i, th)) of
   832           SOME th' => split_conjs i (nprems+1) th'
   833         | NONE => split_conjs (i+1) nprems th
   834   in
   835     singleton (Variable.export ctxt' ctxt) (split_conjs 1 (Thm.nprems_of fixed_th) fixed_th)
   836   end
   837   
   838 fun expand_tuples thy intro =
   839   let
   840     val ctxt = ProofContext.init_global thy
   841     val (((T_insts, t_insts), [intro']), ctxt1) = Variable.import false [intro] ctxt
   842     val intro_t = prop_of intro'
   843     val concl = Logic.strip_imp_concl intro_t
   844     val (p, args) = strip_comb (HOLogic.dest_Trueprop concl)
   845     val (pats', intro_t', ctxt2) = rewrite_args args ([], intro_t, ctxt1)
   846     val (pats', intro_t', ctxt3) = 
   847       fold_atoms rewrite_prem intro_t' (pats', intro_t', ctxt2)
   848     fun rewrite_pat (ct1, ct2) =
   849       (ct1, cterm_of thy (Pattern.rewrite_term thy pats' [] (term_of ct2)))
   850     val t_insts' = map rewrite_pat t_insts
   851     val intro'' = Thm.instantiate (T_insts, t_insts') intro
   852     val [intro'''] = Variable.export ctxt3 ctxt [intro'']
   853     val intro'''' = Simplifier.full_simplify
   854       (HOL_basic_ss addsimps [@{thm fst_conv}, @{thm snd_conv}, @{thm Pair_eq}])
   855       intro'''
   856     (* splitting conjunctions introduced by Pair_eq*)
   857     val intro''''' = split_conjuncts_in_assms ctxt intro''''
   858   in
   859     intro'''''
   860   end
   861 
   862 (*** conversions ***)
   863 
   864 fun imp_prems_conv cv ct =
   865   case Thm.term_of ct of
   866     Const ("==>", _) $ _ $ _ => Conv.combination_conv (Conv.arg_conv cv) (imp_prems_conv cv) ct
   867   | _ => Conv.all_conv ct
   868 
   869 fun all_params_conv cv ctxt ct =
   870   if Logic.is_all (Thm.term_of ct)
   871   then Conv.arg_conv (Conv.abs_conv (all_params_conv cv o #2) ctxt) ct
   872   else cv ctxt ct;
   873   
   874 (** eta contract higher-order arguments **)
   875 
   876 fun eta_contract_ho_arguments thy intro =
   877   let
   878     fun f atom = list_comb (apsnd ((map o map_products) Envir.eta_contract) (strip_comb atom))
   879   in
   880     map_term thy (map_concl f o map_atoms f) intro
   881   end
   882 
   883 (** remove equalities **)
   884 
   885 fun remove_equalities thy intro =
   886   let
   887     fun remove_eqs intro_t =
   888       let
   889         val (prems, concl) = Logic.strip_horn intro_t
   890         fun remove_eq (prems, concl) =
   891           let
   892             fun removable_eq prem =
   893               case try (HOLogic.dest_eq o HOLogic.dest_Trueprop) prem of
   894                 SOME (lhs, rhs) => (case lhs of
   895                   Var _ => true
   896                   | _ => (case rhs of Var _ => true | _ => false))
   897               | NONE => false
   898           in
   899             case find_first removable_eq prems of
   900               NONE => (prems, concl)
   901             | SOME eq =>
   902               let
   903                 val (lhs, rhs) = HOLogic.dest_eq (HOLogic.dest_Trueprop eq)
   904                 val prems' = remove (op =) eq prems
   905                 val subst = (case lhs of
   906                   (v as Var _) =>
   907                     (fn t => if t = v then rhs else t)
   908                 | _ => (case rhs of
   909                    (v as Var _) => (fn t => if t = v then lhs else t)))
   910               in
   911                 remove_eq (map (map_aterms subst) prems', map_aterms subst concl)
   912               end
   913           end
   914       in
   915         Logic.list_implies (remove_eq (prems, concl))
   916       end
   917   in
   918     map_term thy remove_eqs intro
   919   end
   920 
   921 (* Some last processing *)
   922 
   923 fun remove_pointless_clauses intro =
   924   if Logic.strip_imp_prems (prop_of intro) = [@{prop "False"}] then
   925     []
   926   else [intro]
   927 
   928 (* some peephole optimisations *)
   929 
   930 fun peephole_optimisation thy intro =
   931   let
   932     val process =
   933       MetaSimplifier.rewrite_rule (Predicate_Compile_Simps.get (ProofContext.init_global thy))
   934     fun process_False intro_t =
   935       if member (op =) (Logic.strip_imp_prems intro_t) @{prop "False"} then NONE else SOME intro_t
   936     fun process_True intro_t =
   937       map_filter_premises (fn p => if p = @{prop True} then NONE else SOME p) intro_t
   938   in
   939     Option.map (Skip_Proof.make_thm thy)
   940       (process_False (process_True (prop_of (process intro))))
   941   end
   942 
   943 (* defining a quickcheck predicate *)
   944 
   945 fun strip_imp_prems (Const(@{const_name HOL.implies}, _) $ A $ B) = A :: strip_imp_prems B
   946   | strip_imp_prems _ = [];
   947 
   948 fun strip_imp_concl (Const(@{const_name HOL.implies}, _) $ A $ B) = strip_imp_concl B
   949   | strip_imp_concl A = A : term;
   950 
   951 fun strip_horn A = (strip_imp_prems A, strip_imp_concl A);
   952 
   953 fun define_quickcheck_predicate t thy =
   954   let
   955     val (vs, t') = strip_abs t
   956     val vs' = Variable.variant_frees (ProofContext.init_global thy) [] vs
   957     val t'' = subst_bounds (map Free (rev vs'), t')
   958     val (prems, concl) = strip_horn t''
   959     val constname = "quickcheck"
   960     val full_constname = Sign.full_bname thy constname
   961     val constT = map snd vs' ---> @{typ bool}
   962     val thy1 = Sign.add_consts_i [(Binding.name constname, constT, NoSyn)] thy
   963     val const = Const (full_constname, constT)
   964     val t = Logic.list_implies
   965       (map HOLogic.mk_Trueprop (prems @ [HOLogic.mk_not concl]),
   966        HOLogic.mk_Trueprop (list_comb (const, map Free vs')))
   967     val tac = fn _ => Skip_Proof.cheat_tac thy1
   968     val intro = Goal.prove (ProofContext.init_global thy1) (map fst vs') [] t tac
   969   in
   970     ((((full_constname, constT), vs'), intro), thy1)
   971   end
   972 
   973 end;