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