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