src/HOL/Tools/Predicate_Compile/predicate_compile_aux.ML
author haftmann
Thu Aug 19 11:02:14 2010 +0200 (2010-08-19)
changeset 38549 d0385f2764d8
parent 37678 0040bafffdef
child 38552 6c8806696bed
permissions -rw-r--r--
use antiquotations for remaining unqualified constants in HOL
     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 "op &"}, _) $ 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 =
   433   let
   434     val T = (Sign.the_const_type thy constname)
   435   in body_type T = @{typ "bool"} end;
   436 
   437 fun is_predT (T as Type("fun", [_, _])) = (snd (strip_type T) = @{typ bool})
   438   | is_predT _ = false
   439 
   440 (*** check if a term contains only constructor functions ***)
   441 (* TODO: another copy in the core! *)
   442 (* FIXME: constructor terms are supposed to be seen in the way the code generator
   443   sees constructors.*)
   444 fun is_constrt thy =
   445   let
   446     val cnstrs = flat (maps
   447       (map (fn (_, (Tname, _, cs)) => map (apsnd (rpair Tname o length)) cs) o #descr o snd)
   448       (Symtab.dest (Datatype.get_all thy)));
   449     fun check t = (case strip_comb t of
   450         (Var _, []) => true
   451       | (Free _, []) => true
   452       | (Const (s, T), ts) => (case (AList.lookup (op =) cnstrs s, body_type T) of
   453             (SOME (i, Tname), Type (Tname', _)) => length ts = i andalso Tname = Tname' andalso forall check ts
   454           | _ => false)
   455       | _ => false)
   456   in check end;
   457 
   458 fun is_funtype (Type ("fun", [_, _])) = true
   459   | is_funtype _ = false;
   460 
   461 fun is_Type (Type _) = true
   462   | is_Type _ = false
   463 
   464 (* returns true if t is an application of an datatype constructor *)
   465 (* which then consequently would be splitted *)
   466 (* else false *)
   467 (*
   468 fun is_constructor thy t =
   469   if (is_Type (fastype_of t)) then
   470     (case DatatypePackage.get_datatype thy ((fst o dest_Type o fastype_of) t) of
   471       NONE => false
   472     | SOME info => (let
   473       val constr_consts = maps (fn (_, (_, _, constrs)) => map fst constrs) (#descr info)
   474       val (c, _) = strip_comb t
   475       in (case c of
   476         Const (name, _) => name mem_string constr_consts
   477         | _ => false) end))
   478   else false
   479 *)
   480 
   481 val is_constr = Code.is_constr o ProofContext.theory_of;
   482 
   483 fun strip_all t = (Term.strip_all_vars t, Term.strip_all_body t)
   484 
   485 fun strip_ex (Const (@{const_name "Ex"}, _) $ Abs (x, T, t)) =
   486   let
   487     val (xTs, t') = strip_ex t
   488   in
   489     ((x, T) :: xTs, t')
   490   end
   491   | strip_ex t = ([], t)
   492 
   493 fun focus_ex t nctxt =
   494   let
   495     val ((xs, Ts), t') = apfst split_list (strip_ex t) 
   496     val (xs', nctxt') = Name.variants xs nctxt;
   497     val ps' = xs' ~~ Ts;
   498     val vs = map Free ps';
   499     val t'' = Term.subst_bounds (rev vs, t');
   500   in ((ps', t''), nctxt') end;
   501 
   502 (* introduction rule combinators *)
   503 
   504 fun map_atoms f intro = 
   505   let
   506     val (literals, head) = Logic.strip_horn intro
   507     fun appl t = (case t of
   508         (@{term Not} $ t') => HOLogic.mk_not (f t')
   509       | _ => f t)
   510   in
   511     Logic.list_implies
   512       (map (HOLogic.mk_Trueprop o appl o HOLogic.dest_Trueprop) literals, head)
   513   end
   514 
   515 fun fold_atoms f intro s =
   516   let
   517     val (literals, head) = Logic.strip_horn intro
   518     fun appl t s = (case t of
   519       (@{term Not} $ t') => f t' s
   520       | _ => f t s)
   521   in fold appl (map HOLogic.dest_Trueprop literals) s end
   522 
   523 fun fold_map_atoms f intro s =
   524   let
   525     val (literals, head) = Logic.strip_horn intro
   526     fun appl t s = (case t of
   527       (@{term Not} $ t') => apfst HOLogic.mk_not (f t' s)
   528       | _ => f t s)
   529     val (literals', s') = fold_map appl (map HOLogic.dest_Trueprop literals) s
   530   in
   531     (Logic.list_implies (map HOLogic.mk_Trueprop literals', head), s')
   532   end;
   533 
   534 fun map_premises f intro =
   535   let
   536     val (premises, head) = Logic.strip_horn intro
   537   in
   538     Logic.list_implies (map f premises, head)
   539   end
   540 
   541 fun map_filter_premises f intro =
   542   let
   543     val (premises, head) = Logic.strip_horn intro
   544   in
   545     Logic.list_implies (map_filter f premises, head)
   546   end
   547 
   548 fun maps_premises f intro =
   549   let
   550     val (premises, head) = Logic.strip_horn intro
   551   in
   552     Logic.list_implies (maps f premises, head)
   553   end
   554 
   555 fun map_concl f intro =
   556   let
   557     val (premises, head) = Logic.strip_horn intro
   558   in
   559     Logic.list_implies (premises, f head)
   560   end
   561 
   562 (* combinators to apply a function to all basic parts of nested products *)
   563 
   564 fun map_products f (Const (@{const_name Pair}, T) $ t1 $ t2) =
   565   Const (@{const_name Pair}, T) $ map_products f t1 $ map_products f t2
   566   | map_products f t = f t
   567 
   568 (* split theorems of case expressions *)
   569 
   570 fun prepare_split_thm ctxt split_thm =
   571     (split_thm RS @{thm iffD2})
   572     |> Local_Defs.unfold ctxt [@{thm atomize_conjL[symmetric]},
   573       @{thm atomize_all[symmetric]}, @{thm atomize_imp[symmetric]}]
   574 
   575 fun find_split_thm thy (Const (name, T)) = Option.map #split (Datatype_Data.info_of_case thy name)
   576   | find_split_thm thy _ = NONE
   577 
   578 (* lifting term operations to theorems *)
   579 
   580 fun map_term thy f th =
   581   Skip_Proof.make_thm thy (f (prop_of th))
   582 
   583 (*
   584 fun equals_conv lhs_cv rhs_cv ct =
   585   case Thm.term_of ct of
   586     Const ("==", _) $ _ $ _ => Conv.arg_conv cv ct  
   587   | _ => error "equals_conv"  
   588 *)
   589 
   590 (* Different compilations *)
   591 
   592 datatype compilation = Pred | Depth_Limited | Random | Depth_Limited_Random | DSeq | Annotated
   593   | Pos_Random_DSeq | Neg_Random_DSeq | New_Pos_Random_DSeq | New_Neg_Random_DSeq
   594 
   595 fun negative_compilation_of Pos_Random_DSeq = Neg_Random_DSeq
   596   | negative_compilation_of Neg_Random_DSeq = Pos_Random_DSeq
   597   | negative_compilation_of New_Pos_Random_DSeq = New_Neg_Random_DSeq
   598   | negative_compilation_of New_Neg_Random_DSeq = New_Pos_Random_DSeq
   599   | negative_compilation_of c = c
   600   
   601 fun compilation_for_polarity false Pos_Random_DSeq = Neg_Random_DSeq
   602   | compilation_for_polarity false New_Pos_Random_DSeq = New_Neg_Random_DSeq
   603   | compilation_for_polarity _ c = c
   604 
   605 fun string_of_compilation c =
   606   case c of
   607     Pred => ""
   608   | Random => "random"
   609   | Depth_Limited => "depth limited"
   610   | Depth_Limited_Random => "depth limited random"
   611   | DSeq => "dseq"
   612   | Annotated => "annotated"
   613   | Pos_Random_DSeq => "pos_random dseq"
   614   | Neg_Random_DSeq => "neg_random_dseq"
   615   | New_Pos_Random_DSeq => "new_pos_random dseq"
   616   | New_Neg_Random_DSeq => "new_neg_random_dseq"
   617 
   618 val compilation_names = [("pred", Pred),
   619   ("random", Random),
   620   ("depth_limited", Depth_Limited),
   621   ("depth_limited_random", Depth_Limited_Random),
   622   (*("annotated", Annotated),*)
   623   ("dseq", DSeq), ("random_dseq", Pos_Random_DSeq),
   624   ("new_random_dseq", New_Pos_Random_DSeq)]
   625 
   626 val non_random_compilations = [Pred, Depth_Limited, DSeq, Annotated]
   627 
   628 
   629 val random_compilations = [Random, Depth_Limited_Random,
   630   Pos_Random_DSeq, Neg_Random_DSeq, New_Pos_Random_DSeq, New_Neg_Random_DSeq]
   631 
   632 (* datastructures and setup for generic compilation *)
   633 
   634 datatype compilation_funs = CompilationFuns of {
   635   mk_predT : typ -> typ,
   636   dest_predT : typ -> typ,
   637   mk_bot : typ -> term,
   638   mk_single : term -> term,
   639   mk_bind : term * term -> term,
   640   mk_sup : term * term -> term,
   641   mk_if : term -> term,
   642   mk_iterate_upto : typ -> term * term * term -> term,
   643   mk_not : term -> term,
   644   mk_map : typ -> typ -> term -> term -> term
   645 };
   646 
   647 fun mk_predT (CompilationFuns funs) = #mk_predT funs
   648 fun dest_predT (CompilationFuns funs) = #dest_predT funs
   649 fun mk_bot (CompilationFuns funs) = #mk_bot funs
   650 fun mk_single (CompilationFuns funs) = #mk_single funs
   651 fun mk_bind (CompilationFuns funs) = #mk_bind funs
   652 fun mk_sup (CompilationFuns funs) = #mk_sup funs
   653 fun mk_if (CompilationFuns funs) = #mk_if funs
   654 fun mk_iterate_upto (CompilationFuns funs) = #mk_iterate_upto funs
   655 fun mk_not (CompilationFuns funs) = #mk_not funs
   656 fun mk_map (CompilationFuns funs) = #mk_map funs
   657 
   658 (** function types and names of different compilations **)
   659 
   660 fun funT_of compfuns mode T =
   661   let
   662     val Ts = binder_types T
   663     val (inTs, outTs) = split_map_modeT (fn m => fn T => (SOME (funT_of compfuns m T), NONE)) mode Ts
   664   in
   665     inTs ---> (mk_predT compfuns (HOLogic.mk_tupleT outTs))
   666   end;
   667 
   668 (* Different options for compiler *)
   669 
   670 datatype options = Options of {  
   671   expected_modes : (string * mode list) option,
   672   proposed_modes : (string * mode list) option,
   673   proposed_names : ((string * mode) * string) list,
   674   show_steps : bool,
   675   show_proof_trace : bool,
   676   show_intermediate_results : bool,
   677   show_mode_inference : bool,
   678   show_modes : bool,
   679   show_compilation : bool,
   680   show_caught_failures : bool,
   681   skip_proof : bool,
   682   no_topmost_reordering : bool,
   683   function_flattening : bool,
   684   specialise : bool,
   685   fail_safe_function_flattening : bool,
   686   no_higher_order_predicate : string list,
   687   inductify : bool,
   688   detect_switches : bool,
   689   compilation : compilation
   690 };
   691 
   692 fun expected_modes (Options opt) = #expected_modes opt
   693 fun proposed_modes (Options opt) = #proposed_modes opt
   694 fun proposed_names (Options opt) name mode = AList.lookup (eq_pair (op =) eq_mode)
   695   (#proposed_names opt) (name, mode)
   696 
   697 fun show_steps (Options opt) = #show_steps opt
   698 fun show_intermediate_results (Options opt) = #show_intermediate_results opt
   699 fun show_proof_trace (Options opt) = #show_proof_trace opt
   700 fun show_modes (Options opt) = #show_modes opt
   701 fun show_mode_inference (Options opt) = #show_mode_inference opt
   702 fun show_compilation (Options opt) = #show_compilation opt
   703 fun show_caught_failures (Options opt) = #show_caught_failures opt
   704 
   705 fun skip_proof (Options opt) = #skip_proof opt
   706 
   707 fun function_flattening (Options opt) = #function_flattening opt
   708 fun fail_safe_function_flattening (Options opt) = #fail_safe_function_flattening opt
   709 fun specialise (Options opt) = #specialise opt
   710 fun no_topmost_reordering (Options opt) = #no_topmost_reordering opt
   711 fun no_higher_order_predicate (Options opt) = #no_higher_order_predicate opt
   712 
   713 fun is_inductify (Options opt) = #inductify opt
   714 
   715 fun compilation (Options opt) = #compilation opt
   716 
   717 fun detect_switches (Options opt) = #detect_switches opt
   718 
   719 val default_options = Options {
   720   expected_modes = NONE,
   721   proposed_modes = NONE,
   722   proposed_names = [],
   723   show_steps = false,
   724   show_intermediate_results = false,
   725   show_proof_trace = false,
   726   show_modes = false,
   727   show_mode_inference = false,
   728   show_compilation = false,
   729   show_caught_failures = false,
   730   skip_proof = true,
   731   no_topmost_reordering = false,
   732   function_flattening = false,
   733   specialise = false,
   734   fail_safe_function_flattening = false,
   735   no_higher_order_predicate = [],
   736   inductify = false,
   737   detect_switches = true,
   738   compilation = Pred
   739 }
   740 
   741 val bool_options = ["show_steps", "show_intermediate_results", "show_proof_trace", "show_modes",
   742   "show_mode_inference", "show_compilation", "skip_proof", "inductify", "no_function_flattening",
   743   "detect_switches", "specialise", "no_topmost_reordering"]
   744 
   745 fun print_step options s =
   746   if show_steps options then tracing s else ()
   747 
   748 (* simple transformations *)
   749 
   750 (** tuple processing **)
   751 
   752 fun expand_tuples thy intro =
   753   let
   754     fun rewrite_args [] (pats, intro_t, ctxt) = (pats, intro_t, ctxt)
   755       | rewrite_args (arg::args) (pats, intro_t, ctxt) = 
   756       (case HOLogic.strip_tupleT (fastype_of arg) of
   757         (Ts as _ :: _ :: _) =>
   758         let
   759           fun rewrite_arg' (Const (@{const_name Pair}, _) $ _ $ t2, Type (@{type_name Product_Type.prod}, [_, T2]))
   760             (args, (pats, intro_t, ctxt)) = rewrite_arg' (t2, T2) (args, (pats, intro_t, ctxt))
   761             | rewrite_arg' (t, Type (@{type_name Product_Type.prod}, [T1, T2])) (args, (pats, intro_t, ctxt)) =
   762               let
   763                 val ([x, y], ctxt') = Variable.variant_fixes ["x", "y"] ctxt
   764                 val pat = (t, HOLogic.mk_prod (Free (x, T1), Free (y, T2)))
   765                 val intro_t' = Pattern.rewrite_term thy [pat] [] intro_t
   766                 val args' = map (Pattern.rewrite_term thy [pat] []) args
   767               in
   768                 rewrite_arg' (Free (y, T2), T2) (args', (pat::pats, intro_t', ctxt'))
   769               end
   770             | rewrite_arg' _ (args, (pats, intro_t, ctxt)) = (args, (pats, intro_t, ctxt))
   771           val (args', (pats, intro_t', ctxt')) = rewrite_arg' (arg, fastype_of arg)
   772             (args, (pats, intro_t, ctxt))
   773         in
   774           rewrite_args args' (pats, intro_t', ctxt')
   775         end
   776       | _ => rewrite_args args (pats, intro_t, ctxt))
   777     fun rewrite_prem atom =
   778       let
   779         val (_, args) = strip_comb atom
   780       in rewrite_args args end
   781     val ctxt = ProofContext.init_global thy
   782     val (((T_insts, t_insts), [intro']), ctxt1) = Variable.import false [intro] ctxt
   783     val intro_t = prop_of intro'
   784     val concl = Logic.strip_imp_concl intro_t
   785     val (p, args) = strip_comb (HOLogic.dest_Trueprop concl)
   786     val (pats', intro_t', ctxt2) = rewrite_args args ([], intro_t, ctxt1)
   787     val (pats', intro_t', ctxt3) = 
   788       fold_atoms rewrite_prem intro_t' (pats', intro_t', ctxt2)
   789     fun rewrite_pat (ct1, ct2) =
   790       (ct1, cterm_of thy (Pattern.rewrite_term thy pats' [] (term_of ct2)))
   791     val t_insts' = map rewrite_pat t_insts
   792     val intro'' = Thm.instantiate (T_insts, t_insts') intro
   793     val [intro'''] = Variable.export ctxt3 ctxt [intro'']
   794     val intro'''' = Simplifier.full_simplify
   795       (HOL_basic_ss addsimps [@{thm fst_conv}, @{thm snd_conv}, @{thm Pair_eq}])
   796       intro'''
   797     (* splitting conjunctions introduced by Pair_eq*)
   798     fun split_conj prem =
   799       map HOLogic.mk_Trueprop (conjuncts (HOLogic.dest_Trueprop prem))
   800     val intro''''' = map_term thy (maps_premises split_conj) intro''''
   801   in
   802     intro'''''
   803   end
   804 
   805 (** eta contract higher-order arguments **)
   806 
   807 fun eta_contract_ho_arguments thy intro =
   808   let
   809     fun f atom = list_comb (apsnd ((map o map_products) Envir.eta_contract) (strip_comb atom))
   810   in
   811     map_term thy (map_concl f o map_atoms f) intro
   812   end
   813 
   814 (** remove equalities **)
   815 
   816 fun remove_equalities thy intro =
   817   let
   818     fun remove_eqs intro_t =
   819       let
   820         val (prems, concl) = Logic.strip_horn intro_t
   821         fun remove_eq (prems, concl) =
   822           let
   823             fun removable_eq prem =
   824               case try (HOLogic.dest_eq o HOLogic.dest_Trueprop) prem of
   825                 SOME (lhs, rhs) => (case lhs of
   826                   Var _ => true
   827                   | _ => (case rhs of Var _ => true | _ => false))
   828               | NONE => false
   829           in
   830             case find_first removable_eq prems of
   831               NONE => (prems, concl)
   832             | SOME eq =>
   833               let
   834                 val (lhs, rhs) = HOLogic.dest_eq (HOLogic.dest_Trueprop eq)
   835                 val prems' = remove (op =) eq prems
   836                 val subst = (case lhs of
   837                   (v as Var _) =>
   838                     (fn t => if t = v then rhs else t)
   839                 | _ => (case rhs of
   840                    (v as Var _) => (fn t => if t = v then lhs else t)))
   841               in
   842                 remove_eq (map (map_aterms subst) prems', map_aterms subst concl)
   843               end
   844           end
   845       in
   846         Logic.list_implies (remove_eq (prems, concl))
   847       end
   848   in
   849     map_term thy remove_eqs intro
   850   end
   851 
   852 (* Some last processing *)
   853 
   854 fun remove_pointless_clauses intro =
   855   if Logic.strip_imp_prems (prop_of intro) = [@{prop "False"}] then
   856     []
   857   else [intro]
   858 
   859 (* some peephole optimisations *)
   860 
   861 fun peephole_optimisation thy intro =
   862   let
   863     val process =
   864       MetaSimplifier.rewrite_rule (Predicate_Compile_Simps.get (ProofContext.init_global thy))
   865     fun process_False intro_t =
   866       if member (op =) (Logic.strip_imp_prems intro_t) @{prop "False"} then NONE else SOME intro_t
   867     fun process_True intro_t =
   868       map_filter_premises (fn p => if p = @{prop True} then NONE else SOME p) intro_t
   869   in
   870     Option.map (Skip_Proof.make_thm thy)
   871       (process_False (process_True (prop_of (process intro))))
   872   end
   873 
   874 end;