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