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