src/HOL/Tools/Predicate_Compile/predicate_compile_aux.ML
author wenzelm
Fri Mar 21 20:33:56 2014 +0100 (2014-03-21)
changeset 56245 84fc7dfa3cd4
parent 56239 17df7145a871
child 56254 a2dd9200854d
permissions -rw-r--r--
more qualified names;
     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   (* mode *)
    15   datatype mode = Bool | Input | Output | Pair of mode * mode | Fun of mode * mode
    16   val eq_mode : mode * mode -> bool
    17   val mode_ord: mode * mode -> order
    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 ho_args_of_typ : typ -> term list -> term list
    31   val ho_argsT_of_typ : typ list -> typ list
    32   val split_map_mode : (mode -> term -> term option * term option)
    33     -> mode -> term list -> term list * term list
    34   val split_map_modeT : (mode -> typ -> typ option * typ option)
    35     -> mode -> typ list -> typ list * typ list
    36   val split_mode : mode -> term list -> term list * term list
    37   val split_modeT : mode -> typ list -> typ list * typ list
    38   val string_of_mode : mode -> string
    39   val ascii_string_of_mode : mode -> string
    40   (* premises *)
    41   datatype indprem = Prem of term | Negprem of term | Sidecond of term
    42     | Generator of (string * typ)
    43   val dest_indprem : indprem -> term
    44   val map_indprem : (term -> term) -> indprem -> indprem
    45   (* general syntactic functions *)
    46   val is_equationlike : thm -> bool
    47   val is_pred_equation : thm -> bool
    48   val is_intro : string -> thm -> bool
    49   val is_predT : typ -> bool
    50   val get_constrs : theory -> (string * (int * string)) list
    51   val is_constrt : theory -> term -> bool
    52   val is_constr : Proof.context -> string -> bool
    53   val strip_ex : term -> (string * typ) list * term
    54   val focus_ex : term -> Name.context -> ((string * typ) list * term) * Name.context
    55   val strip_all : term -> (string * typ) list * term
    56   val strip_intro_concl : thm -> term * term list
    57   (* introduction rule combinators *)
    58   val map_atoms : (term -> term) -> term -> term
    59   val fold_atoms : (term -> 'a -> 'a) -> term -> 'a -> 'a
    60   val fold_map_atoms : (term -> 'a -> term * 'a) -> term -> 'a -> term * 'a
    61   val maps_premises : (term -> term list) -> term -> term
    62   val map_concl : (term -> term) -> term -> term
    63   val map_term : theory -> (term -> term) -> thm -> thm
    64   (* split theorems of case expressions *)
    65   val prepare_split_thm : Proof.context -> thm -> thm
    66   val find_split_thm : theory -> term -> thm option
    67   (* datastructures and setup for generic compilation *)
    68   datatype compilation_funs = CompilationFuns of {
    69     mk_monadT : typ -> typ,
    70     dest_monadT : typ -> typ,
    71     mk_empty : typ -> term,
    72     mk_single : term -> term,
    73     mk_bind : term * term -> term,
    74     mk_plus : term * term -> term,
    75     mk_if : term -> term,
    76     mk_iterate_upto : typ -> term * term * term -> term,
    77     mk_not : term -> term,
    78     mk_map : typ -> typ -> term -> term -> term
    79   };
    80   val mk_monadT : compilation_funs -> typ -> typ
    81   val dest_monadT : compilation_funs -> typ -> typ
    82   val mk_empty : compilation_funs -> typ -> term
    83   val mk_single : compilation_funs -> term -> term
    84   val mk_bind : compilation_funs -> term * term -> term
    85   val mk_plus : compilation_funs -> term * term -> term
    86   val mk_if : compilation_funs -> term -> term
    87   val mk_iterate_upto : compilation_funs -> typ -> term * term * term -> term
    88   val mk_not : compilation_funs -> term -> term
    89   val mk_map : compilation_funs -> typ -> typ -> term -> term -> term
    90   val funT_of : compilation_funs -> mode -> typ -> typ
    91   (* Different compilations *)
    92   datatype compilation = Pred | Depth_Limited | Random | Depth_Limited_Random | DSeq | Annotated
    93     | Pos_Random_DSeq | Neg_Random_DSeq | New_Pos_Random_DSeq | New_Neg_Random_DSeq
    94     | Pos_Generator_DSeq | Neg_Generator_DSeq | Pos_Generator_CPS | Neg_Generator_CPS
    95   val negative_compilation_of : compilation -> compilation
    96   val compilation_for_polarity : bool -> compilation -> compilation
    97   val is_depth_limited_compilation : compilation -> bool
    98   val string_of_compilation : compilation -> string
    99   val compilation_names : (string * compilation) list
   100   val non_random_compilations : compilation list
   101   val random_compilations : compilation list
   102   (* Different options for compiler *)
   103   datatype options = Options of {
   104     expected_modes : (string * mode list) option,
   105     proposed_modes : (string * mode list) list,
   106     proposed_names : ((string * mode) * string) list,
   107     show_steps : bool,
   108     show_proof_trace : bool,
   109     show_intermediate_results : bool,
   110     show_mode_inference : bool,
   111     show_modes : bool,
   112     show_compilation : bool,
   113     show_caught_failures : bool,
   114     show_invalid_clauses : bool,
   115     skip_proof : bool,
   116     no_topmost_reordering : bool,
   117     function_flattening : bool,
   118     fail_safe_function_flattening : bool,
   119     specialise : bool,
   120     no_higher_order_predicate : string list,
   121     inductify : bool,
   122     detect_switches : bool,
   123     smart_depth_limiting : bool,
   124     compilation : compilation
   125   };
   126   val expected_modes : options -> (string * mode list) option
   127   val proposed_modes : options -> string -> mode list option
   128   val proposed_names : options -> string -> mode -> string option
   129   val show_steps : options -> bool
   130   val show_proof_trace : options -> bool
   131   val show_intermediate_results : options -> bool
   132   val show_mode_inference : options -> bool
   133   val show_modes : options -> bool
   134   val show_compilation : options -> bool
   135   val show_caught_failures : options -> bool
   136   val show_invalid_clauses : options -> bool
   137   val skip_proof : options -> bool
   138   val no_topmost_reordering : options -> bool
   139   val function_flattening : options -> bool
   140   val fail_safe_function_flattening : options -> bool
   141   val specialise : options -> bool
   142   val no_higher_order_predicate : options -> string list
   143   val is_inductify : options -> bool
   144   val detect_switches : options -> bool
   145   val smart_depth_limiting : options -> bool
   146   val compilation : options -> compilation
   147   val default_options : options
   148   val bool_options : string list
   149   val print_step : options -> string -> unit
   150   (* conversions *)
   151   val imp_prems_conv : conv -> conv
   152   (* simple transformations *)
   153   val split_conjuncts_in_assms : Proof.context -> thm -> thm
   154   val dest_conjunct_prem : thm -> thm list
   155   val expand_tuples : theory -> thm -> thm
   156   val case_betapply : theory -> term -> term
   157   val eta_contract_ho_arguments : theory -> thm -> thm
   158   val remove_equalities : theory -> thm -> thm
   159   val remove_pointless_clauses : thm -> thm list
   160   val peephole_optimisation : theory -> thm -> thm option
   161   (* auxillary *)
   162   val unify_consts : theory -> term list -> term list -> (term list * term list)
   163   val mk_casesrule : Proof.context -> term -> thm list -> term
   164   val preprocess_intro : theory -> thm -> thm
   165 
   166   val define_quickcheck_predicate :
   167     term -> theory -> (((string * typ) * (string * typ) list) * thm) * theory
   168 end
   169 
   170 structure Predicate_Compile_Aux : PREDICATE_COMPILE_AUX =
   171 struct
   172 
   173 (* general functions *)
   174 
   175 fun apfst3 f (x, y, z) = (f x, y, z)
   176 fun apsnd3 f (x, y, z) = (x, f y, z)
   177 fun aptrd3 f (x, y, z) = (x, y, f z)
   178 
   179 fun comb_option f (SOME x1, SOME x2) = SOME (f (x1, x2))
   180   | comb_option f (NONE, SOME x2) = SOME x2
   181   | comb_option f (SOME x1, NONE) = SOME x1
   182   | comb_option f (NONE, NONE) = NONE
   183 
   184 fun map2_optional f (x :: xs) (y :: ys) = f x (SOME y) :: (map2_optional f xs ys)
   185   | map2_optional f (x :: xs) [] = (f x NONE) :: (map2_optional f xs [])
   186   | map2_optional f [] [] = []
   187 
   188 fun find_indices f xs =
   189   map_filter (fn (i, true) => SOME i | (_, false) => NONE) (map_index (apsnd f) xs)
   190 
   191 (* mode *)
   192 
   193 datatype mode = Bool | Input | Output | Pair of mode * mode | Fun of mode * mode
   194 
   195 (* equality of instantiatedness with respect to equivalences:
   196   Pair Input Input == Input and Pair Output Output == Output *)
   197 fun eq_mode (Fun (m1, m2), Fun (m3, m4)) = eq_mode (m1, m3) andalso eq_mode (m2, m4)
   198   | eq_mode (Pair (m1, m2), Pair (m3, m4)) = eq_mode (m1, m3) andalso eq_mode (m2, m4)
   199   | eq_mode (Pair (m1, m2), Input) = eq_mode (m1, Input) andalso eq_mode (m2, Input)
   200   | eq_mode (Pair (m1, m2), Output) = eq_mode (m1, Output) andalso eq_mode (m2, Output)
   201   | eq_mode (Input, Pair (m1, m2)) = eq_mode (Input, m1) andalso eq_mode (Input, m2)
   202   | eq_mode (Output, Pair (m1, m2)) = eq_mode (Output, m1) andalso eq_mode (Output, m2)
   203   | eq_mode (Input, Input) = true
   204   | eq_mode (Output, Output) = true
   205   | eq_mode (Bool, Bool) = true
   206   | eq_mode _ = false
   207 
   208 fun mode_ord (Input, Output) = LESS
   209   | mode_ord (Output, Input) = GREATER
   210   | mode_ord (Input, Input) = EQUAL
   211   | mode_ord (Output, Output) = EQUAL
   212   | mode_ord (Bool, Bool) = EQUAL
   213   | mode_ord (Pair (m1, m2), Pair (m3, m4)) = prod_ord mode_ord mode_ord ((m1, m2), (m3, m4))
   214   | mode_ord (Fun (m1, m2), Fun (m3, m4)) = prod_ord mode_ord mode_ord ((m1, m2), (m3, m4))
   215 
   216 fun list_fun_mode [] = Bool
   217   | list_fun_mode (m :: ms) = Fun (m, list_fun_mode ms)
   218 
   219 (* name: binder_modes? *)
   220 fun strip_fun_mode (Fun (mode, mode')) = mode :: strip_fun_mode mode'
   221   | strip_fun_mode Bool = []
   222   | strip_fun_mode _ = raise Fail "Bad mode for strip_fun_mode"
   223 
   224 (* name: strip_fun_mode? *)
   225 fun dest_fun_mode (Fun (mode, mode')) = mode :: dest_fun_mode mode'
   226   | dest_fun_mode mode = [mode]
   227 
   228 fun dest_tuple_mode (Pair (mode, mode')) = mode :: dest_tuple_mode mode'
   229   | dest_tuple_mode _ = []
   230 
   231 fun all_modes_of_typ' (T as Type ("fun", _)) =
   232   let
   233     val (S, U) = strip_type T
   234   in
   235     if U = HOLogic.boolT then
   236       fold_rev (fn m1 => fn m2 => map_product (curry Fun) m1 m2)
   237         (map all_modes_of_typ' S) [Bool]
   238     else
   239       [Input, Output]
   240   end
   241   | all_modes_of_typ' (Type (@{type_name Product_Type.prod}, [T1, T2])) =
   242     map_product (curry Pair) (all_modes_of_typ' T1) (all_modes_of_typ' T2)
   243   | all_modes_of_typ' _ = [Input, Output]
   244 
   245 fun all_modes_of_typ (T as Type ("fun", _)) =
   246     let
   247       val (S, U) = strip_type T
   248     in
   249       if U = @{typ bool} then
   250         fold_rev (fn m1 => fn m2 => map_product (curry Fun) m1 m2)
   251           (map all_modes_of_typ' S) [Bool]
   252       else
   253         raise Fail "Invocation of all_modes_of_typ with a non-predicate type"
   254     end
   255   | all_modes_of_typ @{typ bool} = [Bool]
   256   | all_modes_of_typ _ =
   257     raise Fail "Invocation of all_modes_of_typ with a non-predicate type"
   258 
   259 fun all_smodes_of_typ (T as Type ("fun", _)) =
   260   let
   261     val (S, U) = strip_type T
   262     fun all_smodes (Type (@{type_name Product_Type.prod}, [T1, T2])) =
   263       map_product (curry Pair) (all_smodes T1) (all_smodes T2)
   264       | all_smodes _ = [Input, Output]
   265   in
   266     if U = HOLogic.boolT then
   267       fold_rev (fn m1 => fn m2 => map_product (curry Fun) m1 m2) (map all_smodes S) [Bool]
   268     else
   269       raise Fail "invalid type for predicate"
   270   end
   271 
   272 fun ho_arg_modes_of mode =
   273   let
   274     fun ho_arg_mode (m as Fun _) =  [m]
   275       | ho_arg_mode (Pair (m1, m2)) = ho_arg_mode m1 @ ho_arg_mode m2
   276       | ho_arg_mode _ = []
   277   in
   278     maps ho_arg_mode (strip_fun_mode mode)
   279   end
   280 
   281 fun ho_args_of mode ts =
   282   let
   283     fun ho_arg (Fun _) (SOME t) = [t]
   284       | ho_arg (Fun _) NONE = raise Fail "mode and term do not match"
   285       | ho_arg (Pair (m1, m2)) (SOME (Const (@{const_name Pair}, _) $ t1 $ t2)) =
   286           ho_arg m1 (SOME t1) @ ho_arg m2 (SOME t2)
   287       | ho_arg (Pair (m1, m2)) NONE = ho_arg m1 NONE @ ho_arg m2 NONE
   288       | ho_arg _ _ = []
   289   in
   290     flat (map2_optional ho_arg (strip_fun_mode mode) ts)
   291   end
   292 
   293 fun ho_args_of_typ T ts =
   294   let
   295     fun ho_arg (T as Type ("fun", [_, _])) (SOME t) =
   296           if body_type T = @{typ bool} then [t] else []
   297       | ho_arg (Type ("fun", [_, _])) NONE = raise Fail "mode and term do not match"
   298       | ho_arg (Type(@{type_name "Product_Type.prod"}, [T1, T2]))
   299          (SOME (Const (@{const_name Pair}, _) $ t1 $ t2)) =
   300           ho_arg T1 (SOME t1) @ ho_arg T2 (SOME t2)
   301       | ho_arg (Type(@{type_name "Product_Type.prod"}, [T1, T2])) NONE =
   302           ho_arg T1 NONE @ ho_arg T2 NONE
   303       | ho_arg _ _ = []
   304   in
   305     flat (map2_optional ho_arg (binder_types T) ts)
   306   end
   307 
   308 fun ho_argsT_of_typ Ts =
   309   let
   310     fun ho_arg (T as Type("fun", [_,_])) = if body_type T = @{typ bool} then [T] else []
   311       | ho_arg (Type (@{type_name "Product_Type.prod"}, [T1, T2])) =
   312           ho_arg T1 @ ho_arg T2
   313       | ho_arg _ = []
   314   in
   315     maps ho_arg Ts
   316   end
   317 
   318 
   319 (* temporary function should be replaced by unsplit_input or so? *)
   320 fun replace_ho_args mode hoargs ts =
   321   let
   322     fun replace (Fun _, _) (arg' :: hoargs') = (arg', hoargs')
   323       | replace (Pair (m1, m2), Const (@{const_name Pair}, T) $ t1 $ t2) hoargs =
   324           let
   325             val (t1', hoargs') = replace (m1, t1) hoargs
   326             val (t2', hoargs'') = replace (m2, t2) hoargs'
   327           in
   328             (Const (@{const_name Pair}, T) $ t1' $ t2', hoargs'')
   329           end
   330       | replace (_, t) hoargs = (t, hoargs)
   331   in
   332     fst (fold_map replace (strip_fun_mode mode ~~ ts) hoargs)
   333   end
   334 
   335 fun ho_argsT_of mode Ts =
   336   let
   337     fun ho_arg (Fun _) T = [T]
   338       | ho_arg (Pair (m1, m2)) (Type (@{type_name Product_Type.prod}, [T1, T2])) =
   339           ho_arg m1 T1 @ ho_arg m2 T2
   340       | ho_arg _ _ = []
   341   in
   342     flat (map2 ho_arg (strip_fun_mode mode) Ts)
   343   end
   344 
   345 (* splits mode and maps function to higher-order argument types *)
   346 fun split_map_mode f mode ts =
   347   let
   348     fun split_arg_mode' (m as Fun _) t = f m t
   349       | split_arg_mode' (Pair (m1, m2)) (Const (@{const_name Pair}, _) $ t1 $ t2) =
   350         let
   351           val (i1, o1) = split_arg_mode' m1 t1
   352           val (i2, o2) = split_arg_mode' m2 t2
   353         in
   354           (comb_option HOLogic.mk_prod (i1, i2), comb_option HOLogic.mk_prod (o1, o2))
   355         end
   356       | split_arg_mode' m t =
   357         if eq_mode (m, Input) then (SOME t, NONE)
   358         else if eq_mode (m, Output) then (NONE,  SOME t)
   359         else raise Fail "split_map_mode: mode and term do not match"
   360   in
   361     (pairself (map_filter I) o split_list) (map2 split_arg_mode' (strip_fun_mode mode) ts)
   362   end
   363 
   364 (* splits mode and maps function to higher-order argument types *)
   365 fun split_map_modeT f mode Ts =
   366   let
   367     fun split_arg_mode' (m as Fun _) T = f m T
   368       | split_arg_mode' (Pair (m1, m2)) (Type (@{type_name Product_Type.prod}, [T1, T2])) =
   369         let
   370           val (i1, o1) = split_arg_mode' m1 T1
   371           val (i2, o2) = split_arg_mode' m2 T2
   372         in
   373           (comb_option HOLogic.mk_prodT (i1, i2), comb_option HOLogic.mk_prodT (o1, o2))
   374         end
   375       | split_arg_mode' Input T = (SOME T, NONE)
   376       | split_arg_mode' Output T = (NONE,  SOME T)
   377       | split_arg_mode' _ _ = raise Fail "split_modeT': mode and type do not match"
   378   in
   379     (pairself (map_filter I) o split_list) (map2 split_arg_mode' (strip_fun_mode mode) Ts)
   380   end
   381 
   382 fun split_mode mode ts = split_map_mode (fn _ => fn _ => (NONE, NONE)) mode ts
   383 
   384 fun fold_map_aterms_prodT comb f (Type (@{type_name Product_Type.prod}, [T1, T2])) s =
   385       let
   386         val (x1, s') = fold_map_aterms_prodT comb f T1 s
   387         val (x2, s'') = fold_map_aterms_prodT comb f T2 s'
   388       in
   389         (comb x1 x2, s'')
   390       end
   391   | fold_map_aterms_prodT _ f T s = f T s
   392 
   393 fun map_filter_prod f (Const (@{const_name Pair}, _) $ t1 $ t2) =
   394       comb_option HOLogic.mk_prod (map_filter_prod f t1, map_filter_prod f t2)
   395   | map_filter_prod f t = f t
   396 
   397 fun split_modeT mode Ts =
   398   let
   399     fun split_arg_mode (Fun _) _ = ([], [])
   400       | split_arg_mode (Pair (m1, m2)) (Type (@{type_name Product_Type.prod}, [T1, T2])) =
   401           let
   402             val (i1, o1) = split_arg_mode m1 T1
   403             val (i2, o2) = split_arg_mode m2 T2
   404           in
   405             (i1 @ i2, o1 @ o2)
   406           end
   407       | split_arg_mode Input T = ([T], [])
   408       | split_arg_mode Output T = ([], [T])
   409       | split_arg_mode _ _ = raise Fail "split_modeT: mode and type do not match"
   410   in
   411     (pairself flat o split_list) (map2 split_arg_mode (strip_fun_mode mode) Ts)
   412   end
   413 
   414 fun string_of_mode mode =
   415   let
   416     fun string_of_mode1 Input = "i"
   417       | string_of_mode1 Output = "o"
   418       | string_of_mode1 Bool = "bool"
   419       | string_of_mode1 mode = "(" ^ (string_of_mode3 mode) ^ ")"
   420     and string_of_mode2 (Pair (m1, m2)) = string_of_mode3 m1 ^ " * " ^  string_of_mode2 m2
   421       | string_of_mode2 mode = string_of_mode1 mode
   422     and string_of_mode3 (Fun (m1, m2)) = string_of_mode2 m1 ^ " => " ^ string_of_mode3 m2
   423       | string_of_mode3 mode = string_of_mode2 mode
   424   in string_of_mode3 mode end
   425 
   426 fun ascii_string_of_mode mode' =
   427   let
   428     fun ascii_string_of_mode' Input = "i"
   429       | ascii_string_of_mode' Output = "o"
   430       | ascii_string_of_mode' Bool = "b"
   431       | ascii_string_of_mode' (Pair (m1, m2)) =
   432           "P" ^ ascii_string_of_mode' m1 ^ ascii_string_of_mode'_Pair m2
   433       | ascii_string_of_mode' (Fun (m1, m2)) =
   434           "F" ^ ascii_string_of_mode' m1 ^ ascii_string_of_mode'_Fun m2 ^ "B"
   435     and ascii_string_of_mode'_Fun (Fun (m1, m2)) =
   436           ascii_string_of_mode' m1 ^ (if m2 = Bool then "" else "_" ^ ascii_string_of_mode'_Fun m2)
   437       | ascii_string_of_mode'_Fun Bool = "B"
   438       | ascii_string_of_mode'_Fun m = ascii_string_of_mode' m
   439     and ascii_string_of_mode'_Pair (Pair (m1, m2)) =
   440           ascii_string_of_mode' m1 ^ ascii_string_of_mode'_Pair m2
   441       | ascii_string_of_mode'_Pair m = ascii_string_of_mode' m
   442   in ascii_string_of_mode'_Fun mode' end
   443 
   444 
   445 (* premises *)
   446 
   447 datatype indprem =
   448   Prem of term | Negprem of term | Sidecond of term | Generator of (string * typ)
   449 
   450 fun dest_indprem (Prem t) = t
   451   | dest_indprem (Negprem t) = t
   452   | dest_indprem (Sidecond t) = t
   453   | dest_indprem (Generator _) = raise Fail "cannot destruct generator"
   454 
   455 fun map_indprem f (Prem t) = Prem (f t)
   456   | map_indprem f (Negprem t) = Negprem (f t)
   457   | map_indprem f (Sidecond t) = Sidecond (f t)
   458   | map_indprem f (Generator (v, T)) = Generator (dest_Free (f (Free (v, T))))
   459 
   460 
   461 (* general syntactic functions *)
   462 
   463 fun is_equationlike_term (Const (@{const_name Pure.eq}, _) $ _ $ _) = true
   464   | is_equationlike_term
   465       (Const (@{const_name Trueprop}, _) $ (Const (@{const_name HOL.eq}, _) $ _ $ _)) = true
   466   | is_equationlike_term _ = false
   467 
   468 val is_equationlike = is_equationlike_term o prop_of
   469 
   470 fun is_pred_equation_term (Const (@{const_name Pure.eq}, _) $ u $ v) =
   471       (fastype_of u = @{typ bool}) andalso (fastype_of v = @{typ bool})
   472   | is_pred_equation_term _ = false
   473 
   474 val is_pred_equation = is_pred_equation_term o prop_of
   475 
   476 fun is_intro_term constname t =
   477   the_default false (try (fn t =>
   478     case fst (strip_comb (HOLogic.dest_Trueprop (Logic.strip_imp_concl t))) of
   479       Const (c, _) => c = constname
   480     | _ => false) t)
   481 
   482 fun is_intro constname t = is_intro_term constname (prop_of t)
   483 
   484 fun is_predT (T as Type("fun", [_, _])) = (body_type T = @{typ bool})
   485   | is_predT _ = false
   486 
   487 fun get_constrs thy =
   488   let
   489     val ctxt = Proof_Context.init_global thy
   490   in
   491     Ctr_Sugar.ctr_sugars_of ctxt
   492     |> maps (map_filter (try dest_Const) o #ctrs)
   493     |> map (apsnd (fn T => (BNF_Util.num_binder_types T, fst (dest_Type (body_type T)))))
   494   end
   495 
   496 (*** check if a term contains only constructor functions ***)
   497 (* TODO: another copy in the core! *)
   498 (* FIXME: constructor terms are supposed to be seen in the way the code generator
   499   sees constructors.*)
   500 fun is_constrt thy =
   501   let
   502     val cnstrs = get_constrs thy
   503     fun check t =
   504       (case strip_comb t of
   505         (Var _, []) => true
   506       | (Free _, []) => true
   507       | (Const (s, T), ts) =>
   508           (case (AList.lookup (op =) cnstrs s, body_type T) of
   509             (SOME (i, Tname), Type (Tname', _)) =>
   510               length ts = i andalso Tname = Tname' andalso forall check ts
   511           | _ => false)
   512       | _ => false)
   513   in check end
   514 
   515 val is_constr = Code.is_constr o Proof_Context.theory_of
   516 
   517 fun strip_all t = (Term.strip_all_vars t, Term.strip_all_body t)
   518 
   519 fun strip_ex (Const (@{const_name Ex}, _) $ Abs (x, T, t)) =
   520       let
   521         val (xTs, t') = strip_ex t
   522       in
   523         ((x, T) :: xTs, t')
   524       end
   525   | strip_ex t = ([], t)
   526 
   527 fun focus_ex t nctxt =
   528   let
   529     val ((xs, Ts), t') = apfst split_list (strip_ex t)
   530     val (xs', nctxt') = fold_map Name.variant xs nctxt;
   531     val ps' = xs' ~~ Ts;
   532     val vs = map Free ps';
   533     val t'' = Term.subst_bounds (rev vs, t');
   534   in ((ps', t''), nctxt') end
   535 
   536 val strip_intro_concl = strip_comb o HOLogic.dest_Trueprop o Logic.strip_imp_concl o prop_of
   537 
   538 
   539 (* introduction rule combinators *)
   540 
   541 fun map_atoms f intro =
   542   let
   543     val (literals, head) = Logic.strip_horn intro
   544     fun appl t =
   545       (case t of
   546         (@{term Not} $ t') => HOLogic.mk_not (f t')
   547       | _ => f t)
   548   in
   549     Logic.list_implies
   550       (map (HOLogic.mk_Trueprop o appl o HOLogic.dest_Trueprop) literals, head)
   551   end
   552 
   553 fun fold_atoms f intro s =
   554   let
   555     val (literals, _) = Logic.strip_horn intro
   556     fun appl t s =
   557       (case t of
   558         (@{term Not} $ t') => f t' s
   559       | _ => f t s)
   560   in fold appl (map HOLogic.dest_Trueprop literals) s end
   561 
   562 fun fold_map_atoms f intro s =
   563   let
   564     val (literals, head) = Logic.strip_horn intro
   565     fun appl t s =
   566       (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_filter_premises f intro =
   575   let
   576     val (premises, head) = Logic.strip_horn intro
   577   in
   578     Logic.list_implies (map_filter f premises, head)
   579   end
   580 
   581 fun maps_premises f intro =
   582   let
   583     val (premises, head) = Logic.strip_horn intro
   584   in
   585     Logic.list_implies (maps f premises, head)
   586   end
   587 
   588 fun map_concl f intro =
   589   let
   590     val (premises, head) = Logic.strip_horn intro
   591   in
   592     Logic.list_implies (premises, f head)
   593   end
   594 
   595 
   596 (* combinators to apply a function to all basic parts of nested products *)
   597 
   598 fun map_products f (Const (@{const_name Pair}, T) $ t1 $ t2) =
   599   Const (@{const_name Pair}, T) $ map_products f t1 $ map_products f t2
   600   | map_products f t = f t
   601 
   602 
   603 (* split theorems of case expressions *)
   604 
   605 fun prepare_split_thm ctxt split_thm =
   606     (split_thm RS @{thm iffD2})
   607     |> Local_Defs.unfold ctxt [@{thm atomize_conjL[symmetric]},
   608       @{thm atomize_all[symmetric]}, @{thm atomize_imp[symmetric]}]
   609 
   610 fun find_split_thm thy (Const (name, _)) =
   611     Option.map #split (Ctr_Sugar.ctr_sugar_of_case (Proof_Context.init_global thy) name)
   612   | find_split_thm _ _ = NONE
   613 
   614 
   615 (* lifting term operations to theorems *)
   616 
   617 fun map_term thy f th =
   618   Skip_Proof.make_thm thy (f (prop_of th))
   619 
   620 (*
   621 fun equals_conv lhs_cv rhs_cv ct =
   622   case Thm.term_of ct of
   623     Const (@{const_name Pure.eq}, _) $ _ $ _ => Conv.arg_conv cv ct
   624   | _ => error "equals_conv"
   625 *)
   626 
   627 
   628 (* Different compilations *)
   629 
   630 datatype compilation = Pred | Depth_Limited | Random | Depth_Limited_Random | DSeq | Annotated
   631   | Pos_Random_DSeq | Neg_Random_DSeq | New_Pos_Random_DSeq | New_Neg_Random_DSeq |
   632     Pos_Generator_DSeq | Neg_Generator_DSeq | Pos_Generator_CPS | Neg_Generator_CPS
   633 
   634 fun negative_compilation_of Pos_Random_DSeq = Neg_Random_DSeq
   635   | negative_compilation_of Neg_Random_DSeq = Pos_Random_DSeq
   636   | negative_compilation_of New_Pos_Random_DSeq = New_Neg_Random_DSeq
   637   | negative_compilation_of New_Neg_Random_DSeq = New_Pos_Random_DSeq
   638   | negative_compilation_of Pos_Generator_DSeq = Neg_Generator_DSeq
   639   | negative_compilation_of Neg_Generator_DSeq = Pos_Generator_DSeq
   640   | negative_compilation_of Pos_Generator_CPS = Neg_Generator_CPS
   641   | negative_compilation_of Neg_Generator_CPS = Pos_Generator_CPS
   642   | negative_compilation_of c = c
   643 
   644 fun compilation_for_polarity false Pos_Random_DSeq = Neg_Random_DSeq
   645   | compilation_for_polarity false New_Pos_Random_DSeq = New_Neg_Random_DSeq
   646   | compilation_for_polarity _ c = c
   647 
   648 fun is_depth_limited_compilation c =
   649   (c = New_Pos_Random_DSeq) orelse (c = New_Neg_Random_DSeq) orelse
   650   (c = Pos_Generator_DSeq) orelse (c = Pos_Generator_DSeq)
   651 
   652 fun string_of_compilation c =
   653   (case c of
   654     Pred => ""
   655   | Random => "random"
   656   | Depth_Limited => "depth limited"
   657   | Depth_Limited_Random => "depth limited random"
   658   | DSeq => "dseq"
   659   | Annotated => "annotated"
   660   | Pos_Random_DSeq => "pos_random dseq"
   661   | Neg_Random_DSeq => "neg_random_dseq"
   662   | New_Pos_Random_DSeq => "new_pos_random dseq"
   663   | New_Neg_Random_DSeq => "new_neg_random_dseq"
   664   | Pos_Generator_DSeq => "pos_generator_dseq"
   665   | Neg_Generator_DSeq => "neg_generator_dseq"
   666   | Pos_Generator_CPS => "pos_generator_cps"
   667   | Neg_Generator_CPS => "neg_generator_cps")
   668 
   669 val compilation_names =
   670  [("pred", Pred),
   671   ("random", Random),
   672   ("depth_limited", Depth_Limited),
   673   ("depth_limited_random", Depth_Limited_Random),
   674   (*("annotated", Annotated),*)
   675   ("dseq", DSeq),
   676   ("random_dseq", Pos_Random_DSeq),
   677   ("new_random_dseq", New_Pos_Random_DSeq),
   678   ("generator_dseq", Pos_Generator_DSeq),
   679   ("generator_cps", Pos_Generator_CPS)]
   680 
   681 val non_random_compilations = [Pred, Depth_Limited, DSeq, Annotated]
   682 
   683 
   684 val random_compilations = [Random, Depth_Limited_Random,
   685   Pos_Random_DSeq, Neg_Random_DSeq, New_Pos_Random_DSeq, New_Neg_Random_DSeq,
   686   Pos_Generator_CPS, Neg_Generator_CPS]
   687 
   688 
   689 (* datastructures and setup for generic compilation *)
   690 
   691 datatype compilation_funs = CompilationFuns of {
   692   mk_monadT : typ -> typ,
   693   dest_monadT : typ -> typ,
   694   mk_empty : typ -> term,
   695   mk_single : term -> term,
   696   mk_bind : term * term -> term,
   697   mk_plus : term * term -> term,
   698   mk_if : term -> term,
   699   mk_iterate_upto : typ -> term * term * term -> term,
   700   mk_not : term -> term,
   701   mk_map : typ -> typ -> term -> term -> term
   702 }
   703 
   704 fun mk_monadT (CompilationFuns funs) = #mk_monadT funs
   705 fun dest_monadT (CompilationFuns funs) = #dest_monadT funs
   706 fun mk_empty (CompilationFuns funs) = #mk_empty funs
   707 fun mk_single (CompilationFuns funs) = #mk_single funs
   708 fun mk_bind (CompilationFuns funs) = #mk_bind funs
   709 fun mk_plus (CompilationFuns funs) = #mk_plus funs
   710 fun mk_if (CompilationFuns funs) = #mk_if funs
   711 fun mk_iterate_upto (CompilationFuns funs) = #mk_iterate_upto funs
   712 fun mk_not (CompilationFuns funs) = #mk_not funs
   713 fun mk_map (CompilationFuns funs) = #mk_map funs
   714 
   715 
   716 (** function types and names of different compilations **)
   717 
   718 fun funT_of compfuns mode T =
   719   let
   720     val Ts = binder_types T
   721     val (inTs, outTs) =
   722       split_map_modeT (fn m => fn T => (SOME (funT_of compfuns m T), NONE)) mode Ts
   723   in
   724     inTs ---> (mk_monadT compfuns (HOLogic.mk_tupleT outTs))
   725   end
   726 
   727 
   728 (* Different options for compiler *)
   729 
   730 datatype options = Options of {
   731   expected_modes : (string * mode list) option,
   732   proposed_modes : (string * mode list) list,
   733   proposed_names : ((string * mode) * string) list,
   734   show_steps : bool,
   735   show_proof_trace : bool,
   736   show_intermediate_results : bool,
   737   show_mode_inference : bool,
   738   show_modes : bool,
   739   show_compilation : bool,
   740   show_caught_failures : bool,
   741   show_invalid_clauses : bool,
   742   skip_proof : bool,
   743   no_topmost_reordering : bool,
   744   function_flattening : bool,
   745   specialise : bool,
   746   fail_safe_function_flattening : bool,
   747   no_higher_order_predicate : string list,
   748   inductify : bool,
   749   detect_switches : bool,
   750   smart_depth_limiting : bool,
   751   compilation : compilation
   752 }
   753 
   754 fun expected_modes (Options opt) = #expected_modes opt
   755 fun proposed_modes (Options opt) = AList.lookup (op =) (#proposed_modes opt)
   756 fun proposed_names (Options opt) name mode = AList.lookup (eq_pair (op =) eq_mode)
   757   (#proposed_names opt) (name, mode)
   758 
   759 fun show_steps (Options opt) = #show_steps opt
   760 fun show_intermediate_results (Options opt) = #show_intermediate_results opt
   761 fun show_proof_trace (Options opt) = #show_proof_trace opt
   762 fun show_modes (Options opt) = #show_modes opt
   763 fun show_mode_inference (Options opt) = #show_mode_inference opt
   764 fun show_compilation (Options opt) = #show_compilation opt
   765 fun show_caught_failures (Options opt) = #show_caught_failures opt
   766 fun show_invalid_clauses (Options opt) = #show_invalid_clauses opt
   767 fun skip_proof (Options opt) = #skip_proof opt
   768 
   769 fun function_flattening (Options opt) = #function_flattening opt
   770 fun fail_safe_function_flattening (Options opt) = #fail_safe_function_flattening opt
   771 fun specialise (Options opt) = #specialise opt
   772 fun no_topmost_reordering (Options opt) = #no_topmost_reordering opt
   773 fun no_higher_order_predicate (Options opt) = #no_higher_order_predicate opt
   774 
   775 fun is_inductify (Options opt) = #inductify opt
   776 
   777 fun compilation (Options opt) = #compilation opt
   778 
   779 fun detect_switches (Options opt) = #detect_switches opt
   780 
   781 fun smart_depth_limiting (Options opt) = #smart_depth_limiting opt
   782 
   783 val default_options = Options {
   784   expected_modes = NONE,
   785   proposed_modes = [],
   786   proposed_names = [],
   787   show_steps = false,
   788   show_intermediate_results = false,
   789   show_proof_trace = false,
   790   show_modes = false,
   791   show_mode_inference = false,
   792   show_compilation = false,
   793   show_caught_failures = false,
   794   show_invalid_clauses = false,
   795   skip_proof = true,
   796   no_topmost_reordering = false,
   797   function_flattening = false,
   798   specialise = false,
   799   fail_safe_function_flattening = false,
   800   no_higher_order_predicate = [],
   801   inductify = false,
   802   detect_switches = true,
   803   smart_depth_limiting = false,
   804   compilation = Pred
   805 }
   806 
   807 val bool_options = ["show_steps", "show_intermediate_results", "show_proof_trace", "show_modes",
   808   "show_mode_inference", "show_compilation", "show_invalid_clauses", "skip_proof", "inductify",
   809   "no_function_flattening", "detect_switches", "specialise", "no_topmost_reordering",
   810   "smart_depth_limiting"]
   811 
   812 fun print_step options s =
   813   if show_steps options then tracing s else ()
   814 
   815 
   816 (* simple transformations *)
   817 
   818 (** tuple processing **)
   819 
   820 fun rewrite_args [] (pats, intro_t, ctxt) = (pats, intro_t, ctxt)
   821   | rewrite_args (arg::args) (pats, intro_t, ctxt) =
   822       (case HOLogic.strip_tupleT (fastype_of arg) of
   823         (_ :: _ :: _) =>
   824         let
   825           fun rewrite_arg'
   826                 (Const (@{const_name Pair}, _) $ _ $ t2, Type (@{type_name Product_Type.prod}, [_, T2]))
   827                 (args, (pats, intro_t, ctxt)) =
   828                 rewrite_arg' (t2, T2) (args, (pats, intro_t, ctxt))
   829             | rewrite_arg'
   830                 (t, Type (@{type_name Product_Type.prod}, [T1, T2])) (args, (pats, intro_t, ctxt)) =
   831                 let
   832                   val thy = Proof_Context.theory_of ctxt
   833                   val ([x, y], ctxt') = Variable.variant_fixes ["x", "y"] ctxt
   834                   val pat = (t, HOLogic.mk_prod (Free (x, T1), Free (y, T2)))
   835                   val intro_t' = Pattern.rewrite_term thy [pat] [] intro_t
   836                   val args' = map (Pattern.rewrite_term thy [pat] []) args
   837                 in
   838                   rewrite_arg' (Free (y, T2), T2) (args', (pat::pats, intro_t', ctxt'))
   839                 end
   840             | rewrite_arg' _ (args, (pats, intro_t, ctxt)) = (args, (pats, intro_t, ctxt))
   841           val (args', (pats, intro_t', ctxt')) =
   842             rewrite_arg' (arg, fastype_of arg) (args, (pats, intro_t, ctxt))
   843         in
   844           rewrite_args args' (pats, intro_t', ctxt')
   845         end
   846   | _ => rewrite_args args (pats, intro_t, ctxt))
   847 
   848 fun rewrite_prem atom =
   849   let
   850     val (_, args) = strip_comb atom
   851   in rewrite_args args end
   852 
   853 fun split_conjuncts_in_assms ctxt th =
   854   let
   855     val ((_, [fixed_th]), ctxt') = Variable.import false [th] ctxt
   856     fun split_conjs i nprems th =
   857       if i > nprems then th
   858       else
   859         (case try Drule.RSN (@{thm conjI}, (i, th)) of
   860           SOME th' => split_conjs i (nprems + 1) th'
   861         | NONE => split_conjs (i + 1) nprems th)
   862   in
   863     singleton (Variable.export ctxt' ctxt)
   864       (split_conjs 1 (Thm.nprems_of fixed_th) fixed_th)
   865   end
   866 
   867 fun dest_conjunct_prem th =
   868   (case HOLogic.dest_Trueprop (prop_of th) of
   869     (Const (@{const_name HOL.conj}, _) $ _ $ _) =>
   870       dest_conjunct_prem (th RS @{thm conjunct1})
   871         @ dest_conjunct_prem (th RS @{thm conjunct2})
   872    | _ => [th])
   873 
   874 fun expand_tuples thy intro =
   875   let
   876     val ctxt = Proof_Context.init_global thy
   877     val (((T_insts, t_insts), [intro']), ctxt1) = Variable.import false [intro] ctxt
   878     val intro_t = prop_of intro'
   879     val concl = Logic.strip_imp_concl intro_t
   880     val (_, args) = strip_comb (HOLogic.dest_Trueprop concl)
   881     val (pats', intro_t', ctxt2) = rewrite_args args ([], intro_t, ctxt1)
   882     val (pats', _, ctxt3) = fold_atoms rewrite_prem intro_t' (pats', intro_t', ctxt2)
   883     fun rewrite_pat (ct1, ct2) =
   884       (ct1, cterm_of thy (Pattern.rewrite_term thy pats' [] (term_of ct2)))
   885     val t_insts' = map rewrite_pat t_insts
   886     val intro'' = Thm.instantiate (T_insts, t_insts') intro
   887     val [intro'''] = Variable.export ctxt3 ctxt [intro'']
   888     val intro'''' =
   889       Simplifier.full_simplify
   890         (put_simpset HOL_basic_ss ctxt
   891           addsimps [@{thm fst_conv}, @{thm snd_conv}, @{thm Pair_eq}])
   892       intro'''
   893     (* splitting conjunctions introduced by Pair_eq*)
   894     val intro''''' = split_conjuncts_in_assms ctxt intro''''
   895   in
   896     intro'''''
   897   end
   898 
   899 
   900 (** making case distributivity rules **)
   901 (*** this should be part of the datatype package ***)
   902 
   903 fun datatype_name_of_case_name thy =
   904   Ctr_Sugar.ctr_sugar_of_case (Proof_Context.init_global thy)
   905   #> the #> #ctrs #> hd #> fastype_of #> body_type #> dest_Type #> fst
   906 
   907 fun make_case_comb thy Tcon =
   908   let
   909     val ctxt = Proof_Context.init_global thy
   910     val SOME {casex, ...} = Ctr_Sugar.ctr_sugar_of ctxt Tcon
   911     val casex' = Type.legacy_freeze casex
   912     val Ts = BNF_Util.binder_fun_types (fastype_of casex')
   913   in
   914     list_comb (casex', map_index (fn (j, T) => Free ("f" ^ string_of_int j,  T)) Ts)
   915   end
   916 
   917 fun make_case_distrib thy Tcon =
   918   let
   919     val comb = make_case_comb thy Tcon;
   920     val Type ("fun", [T, T']) = fastype_of comb;
   921     val (Const (case_name, _), fs) = strip_comb comb
   922     val used = Term.add_tfree_names comb []
   923     val U = TFree (singleton (Name.variant_list used) "'t", HOLogic.typeS)
   924     val x = Free ("x", T)
   925     val f = Free ("f", T' --> U)
   926     fun apply_f f' =
   927       let
   928         val Ts = binder_types (fastype_of f')
   929         val bs = map Bound ((length Ts - 1) downto 0)
   930       in
   931         fold_rev absdummy Ts (f $ (list_comb (f', bs)))
   932       end
   933     val fs' = map apply_f fs
   934     val case_c' = Const (case_name, (map fastype_of fs') @ [T] ---> U)
   935   in
   936     HOLogic.mk_eq (f $ (comb $ x), list_comb (case_c', fs') $ x)
   937   end
   938 
   939 fun case_rewrite thy Tcon =
   940   (Drule.export_without_context o Skip_Proof.make_thm thy o HOLogic.mk_Trueprop)
   941     (make_case_distrib thy Tcon)
   942 
   943 fun instantiated_case_rewrite thy Tcon =
   944   let
   945     val th = case_rewrite thy Tcon
   946     val ctxt = Proof_Context.init_global thy
   947     val f = (fst (strip_comb (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop (prop_of th))))))
   948     val Type ("fun", [uninst_T, uninst_T']) = fastype_of f
   949     val ([_, tname', uname, yname], ctxt') = Variable.add_fixes ["'t", "'t'", "'u", "y"] ctxt
   950     val T' = TFree (tname', HOLogic.typeS)
   951     val U = TFree (uname, HOLogic.typeS)
   952     val y = Free (yname, U)
   953     val f' = absdummy (U --> T') (Bound 0 $ y)
   954     val th' = Thm.certify_instantiate
   955       ([(dest_TVar uninst_T, U --> T'), (dest_TVar uninst_T', T')],
   956        [((fst (dest_Var f), (U --> T') --> T'), f')]) th
   957     val [th'] = Variable.export ctxt' ctxt [th']
   958   in
   959     th'
   960   end
   961 
   962 fun case_betapply thy t =
   963   let
   964     val case_name = fst (dest_Const (fst (strip_comb t)))
   965     val Tcon = datatype_name_of_case_name thy case_name
   966     val th = instantiated_case_rewrite thy Tcon
   967   in
   968     Raw_Simplifier.rewrite_term thy [th RS @{thm eq_reflection}] [] t
   969   end
   970 
   971 
   972 (*** conversions ***)
   973 
   974 fun imp_prems_conv cv ct =
   975   (case Thm.term_of ct of
   976     Const (@{const_name Pure.imp}, _) $ _ $ _ =>
   977       Conv.combination_conv (Conv.arg_conv cv) (imp_prems_conv cv) ct
   978   | _ => Conv.all_conv ct)
   979 
   980 
   981 (** eta contract higher-order arguments **)
   982 
   983 fun eta_contract_ho_arguments thy intro =
   984   let
   985     fun f atom = list_comb (apsnd ((map o map_products) Envir.eta_contract) (strip_comb atom))
   986   in
   987     map_term thy (map_concl f o map_atoms f) intro
   988   end
   989 
   990 
   991 (** remove equalities **)
   992 
   993 fun remove_equalities thy intro =
   994   let
   995     fun remove_eqs intro_t =
   996       let
   997         val (prems, concl) = Logic.strip_horn intro_t
   998         fun remove_eq (prems, concl) =
   999           let
  1000             fun removable_eq prem =
  1001               (case try (HOLogic.dest_eq o HOLogic.dest_Trueprop) prem of
  1002                 SOME (lhs, rhs) =>
  1003                   (case lhs of
  1004                     Var _ => true
  1005                   | _ => (case rhs of Var _ => true | _ => false))
  1006               | NONE => false)
  1007           in
  1008             (case find_first removable_eq prems of
  1009               NONE => (prems, concl)
  1010             | SOME eq =>
  1011                 let
  1012                   val (lhs, rhs) = HOLogic.dest_eq (HOLogic.dest_Trueprop eq)
  1013                   val prems' = remove (op =) eq prems
  1014                   val subst =
  1015                     (case lhs of
  1016                       (v as Var _) =>
  1017                         (fn t => if t = v then rhs else t)
  1018                     | _ => (case rhs of (v as Var _) => (fn t => if t = v then lhs else t)))
  1019                 in
  1020                   remove_eq (map (map_aterms subst) prems', map_aterms subst concl)
  1021                 end)
  1022           end
  1023       in
  1024         Logic.list_implies (remove_eq (prems, concl))
  1025       end
  1026   in
  1027     map_term thy remove_eqs intro
  1028   end
  1029 
  1030 
  1031 (* Some last processing *)
  1032 
  1033 fun remove_pointless_clauses intro =
  1034   if Logic.strip_imp_prems (prop_of intro) = [@{prop "False"}] then
  1035     []
  1036   else [intro]
  1037 
  1038 
  1039 (* some peephole optimisations *)
  1040 
  1041 fun peephole_optimisation thy intro =
  1042   let
  1043     val ctxt = Proof_Context.init_global thy  (* FIXME proper context!? *)
  1044     val process =
  1045       rewrite_rule ctxt (Predicate_Compile_Simps.get ctxt)
  1046     fun process_False intro_t =
  1047       if member (op =) (Logic.strip_imp_prems intro_t) @{prop "False"}
  1048       then NONE else SOME intro_t
  1049     fun process_True intro_t =
  1050       map_filter_premises (fn p => if p = @{prop True} then NONE else SOME p) intro_t
  1051   in
  1052     Option.map (Skip_Proof.make_thm thy)
  1053       (process_False (process_True (prop_of (process intro))))
  1054   end
  1055 
  1056 
  1057 (* importing introduction rules *)
  1058 
  1059 fun import_intros inp_pred [] ctxt =
  1060       let
  1061         val ([outp_pred], ctxt') = Variable.import_terms true [inp_pred] ctxt
  1062         val T = fastype_of outp_pred
  1063         val paramTs = ho_argsT_of_typ (binder_types T)
  1064         val (param_names, _) = Variable.variant_fixes
  1065           (map (fn i => "p" ^ (string_of_int i)) (1 upto (length paramTs))) ctxt'
  1066         val params = map2 (curry Free) param_names paramTs
  1067       in
  1068         (((outp_pred, params), []), ctxt')
  1069       end
  1070   | import_intros inp_pred (th :: ths) ctxt =
  1071       let
  1072         val ((_, [th']), ctxt') = Variable.import true [th] ctxt
  1073         val thy = Proof_Context.theory_of ctxt'
  1074         val (pred, args) = strip_intro_concl th'
  1075         val T = fastype_of pred
  1076         val ho_args = ho_args_of_typ T args
  1077         fun subst_of (pred', pred) =
  1078           let
  1079             val subst = Sign.typ_match thy (fastype_of pred', fastype_of pred) Vartab.empty
  1080               handle Type.TYPE_MATCH =>
  1081                 error ("Type mismatch of predicate " ^ fst (dest_Const pred) ^
  1082                   " (trying to match " ^ Syntax.string_of_typ ctxt (fastype_of pred') ^
  1083                   " and " ^ Syntax.string_of_typ ctxt (fastype_of pred) ^ ")" ^
  1084                   " in " ^ Display.string_of_thm ctxt th)
  1085           in map (fn (indexname, (s, T)) => ((indexname, s), T)) (Vartab.dest subst) end
  1086         fun instantiate_typ th =
  1087           let
  1088             val (pred', _) = strip_intro_concl th
  1089             val _ =
  1090               if not (fst (dest_Const pred) = fst (dest_Const pred')) then
  1091                 raise Fail "Trying to instantiate another predicate"
  1092               else ()
  1093           in Thm.certify_instantiate (subst_of (pred', pred), []) th end
  1094         fun instantiate_ho_args th =
  1095           let
  1096             val (_, args') =
  1097               (strip_comb o HOLogic.dest_Trueprop o Logic.strip_imp_concl o prop_of) th
  1098             val ho_args' = map dest_Var (ho_args_of_typ T args')
  1099           in Thm.certify_instantiate ([], ho_args' ~~ ho_args) th end
  1100         val outp_pred =
  1101           Term_Subst.instantiate (subst_of (inp_pred, pred), []) inp_pred
  1102         val ((_, ths'), ctxt1) =
  1103           Variable.import false (map (instantiate_typ #> instantiate_ho_args) ths) ctxt'
  1104       in
  1105         (((outp_pred, ho_args), th' :: ths'), ctxt1)
  1106       end
  1107 
  1108 
  1109 (* generation of case rules from user-given introduction rules *)
  1110 
  1111 fun mk_args2 (Type (@{type_name Product_Type.prod}, [T1, T2])) st =
  1112       let
  1113         val (t1, st') = mk_args2 T1 st
  1114         val (t2, st'') = mk_args2 T2 st'
  1115       in
  1116         (HOLogic.mk_prod (t1, t2), st'')
  1117       end
  1118   (*| mk_args2 (T as Type ("fun", _)) (params, ctxt) =
  1119     let
  1120       val (S, U) = strip_type T
  1121     in
  1122       if U = HOLogic.boolT then
  1123         (hd params, (tl params, ctxt))
  1124       else
  1125         let
  1126           val ([x], ctxt') = Variable.variant_fixes ["x"] ctxt
  1127         in
  1128           (Free (x, T), (params, ctxt'))
  1129         end
  1130     end*)
  1131   | mk_args2 T (params, ctxt) =
  1132       let
  1133         val ([x], ctxt') = Variable.variant_fixes ["x"] ctxt
  1134       in
  1135         (Free (x, T), (params, ctxt'))
  1136       end
  1137 
  1138 fun mk_casesrule ctxt pred introrules =
  1139   let
  1140     (* TODO: can be simplified if parameters are not treated specially ? *)
  1141     val (((pred, params), intros_th), ctxt1) = import_intros pred introrules ctxt
  1142     (* TODO: distinct required ? -- test case with more than one parameter! *)
  1143     val params = distinct (op aconv) params
  1144     val intros = map prop_of intros_th
  1145     val ([propname], ctxt2) = Variable.variant_fixes ["thesis"] ctxt1
  1146     val prop = HOLogic.mk_Trueprop (Free (propname, HOLogic.boolT))
  1147     val argsT = binder_types (fastype_of pred)
  1148     (* TODO: can be simplified if parameters are not treated specially ? <-- see uncommented code! *)
  1149     val (argvs, _) = fold_map mk_args2 argsT (params, ctxt2)
  1150     fun mk_case intro =
  1151       let
  1152         val (_, args) = (strip_comb o HOLogic.dest_Trueprop o Logic.strip_imp_concl) intro
  1153         val prems = Logic.strip_imp_prems intro
  1154         val eqprems =
  1155           map2 (HOLogic.mk_Trueprop oo (curry HOLogic.mk_eq)) argvs args
  1156         val frees = map Free (fold Term.add_frees (args @ prems) [])
  1157       in fold Logic.all frees (Logic.list_implies (eqprems @ prems, prop)) end
  1158     val assm = HOLogic.mk_Trueprop (list_comb (pred, argvs))
  1159     val cases = map mk_case intros
  1160   in Logic.list_implies (assm :: cases, prop) end;
  1161 
  1162 
  1163 (* unifying constants to have the same type variables *)
  1164 
  1165 fun unify_consts thy cs intr_ts =
  1166   let
  1167      val add_term_consts_2 = fold_aterms (fn Const c => insert (op =) c | _ => I);
  1168      fun varify (t, (i, ts)) =
  1169        let val t' = map_types (Logic.incr_tvar (i + 1)) (#2 (Type.varify_global [] t))
  1170        in (maxidx_of_term t', t' :: ts) end
  1171      val (i, cs') = List.foldr varify (~1, []) cs
  1172      val (i', intr_ts') = List.foldr varify (i, []) intr_ts
  1173      val rec_consts = fold add_term_consts_2 cs' []
  1174      val intr_consts = fold add_term_consts_2 intr_ts' []
  1175      fun unify (cname, cT) =
  1176        let val consts = map snd (filter (fn c => fst c = cname) intr_consts)
  1177        in fold (Sign.typ_unify thy) ((replicate (length consts) cT) ~~ consts) end
  1178      val (env, _) = fold unify rec_consts (Vartab.empty, i')
  1179      val subst = map_types (Envir.norm_type env)
  1180    in (map subst cs', map subst intr_ts')
  1181    end handle Type.TUNIFY =>
  1182      (warning "Occurrences of recursive constant have non-unifiable types"; (cs, intr_ts))
  1183 
  1184 
  1185 (* preprocessing rules *)
  1186 
  1187 fun preprocess_equality thy rule =
  1188   Conv.fconv_rule
  1189     (imp_prems_conv
  1190       (HOLogic.Trueprop_conv
  1191         (Conv.try_conv (Conv.rewr_conv (Thm.symmetric @{thm Predicate.eq_is_eq})))))
  1192     (Thm.transfer thy rule)
  1193 
  1194 fun preprocess_intro thy = expand_tuples thy #> preprocess_equality thy
  1195 
  1196 
  1197 (* defining a quickcheck predicate *)
  1198 
  1199 fun strip_imp_prems (Const(@{const_name HOL.implies}, _) $ A $ B) = A :: strip_imp_prems B
  1200   | strip_imp_prems _ = [];
  1201 
  1202 fun strip_imp_concl (Const(@{const_name HOL.implies}, _) $ _ $ B) = strip_imp_concl B
  1203   | strip_imp_concl A = A;
  1204 
  1205 fun strip_horn A = (strip_imp_prems A, strip_imp_concl A)
  1206 
  1207 fun define_quickcheck_predicate t thy =
  1208   let
  1209     val (vs, t') = strip_abs t
  1210     val vs' = Variable.variant_frees (Proof_Context.init_global thy) [] vs (* FIXME proper context!? *)
  1211     val t'' = subst_bounds (map Free (rev vs'), t')
  1212     val (prems, concl) = strip_horn t''
  1213     val constname = "quickcheck"
  1214     val full_constname = Sign.full_bname thy constname
  1215     val constT = map snd vs' ---> @{typ bool}
  1216     val thy1 = Sign.add_consts [(Binding.name constname, constT, NoSyn)] thy
  1217     val const = Const (full_constname, constT)
  1218     val t =
  1219       Logic.list_implies
  1220         (map HOLogic.mk_Trueprop (prems @ [HOLogic.mk_not concl]),
  1221           HOLogic.mk_Trueprop (list_comb (const, map Free vs')))
  1222     val intro =
  1223       Goal.prove (Proof_Context.init_global thy1) (map fst vs') [] t
  1224         (fn _ => ALLGOALS Skip_Proof.cheat_tac)
  1225   in
  1226     ((((full_constname, constT), vs'), intro), thy1)
  1227   end
  1228 
  1229 end