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