src/HOL/Tools/SMT/smt_normalize.ML
author boehmes
Wed Nov 24 13:31:12 2010 +0100 (2010-11-24)
changeset 40685 dcb27631cb45
parent 40681 872b08416fb4
child 40686 4725ed462387
permissions -rw-r--r--
instantiate elimination rules (reduces number of quantified variables, and makes such theorems better amenable for SMT solvers)
     1 (*  Title:      HOL/Tools/SMT/smt_normalize.ML
     2     Author:     Sascha Boehme, TU Muenchen
     3 
     4 Normalization steps on theorems required by SMT solvers:
     5   * simplify trivial distincts (those with less than three elements),
     6   * rewrite bool case expressions as if expressions,
     7   * normalize numerals (e.g. replace negative numerals by negated positive
     8     numerals),
     9   * embed natural numbers into integers,
    10   * add extra rules specifying types and constants which occur frequently,
    11   * fully translate into object logic, add universal closure,
    12   * monomorphize (create instances of schematic rules),
    13   * lift lambda terms,
    14   * make applications explicit for functions with varying number of arguments.
    15   * add (hypothetical definitions for) missing datatype selectors,
    16 *)
    17 
    18 signature SMT_NORMALIZE =
    19 sig
    20   type extra_norm = bool -> (int * thm) list -> Proof.context ->
    21     (int * thm) list * Proof.context
    22   val normalize: extra_norm -> bool -> (int * thm) list -> Proof.context ->
    23     (int * thm) list * Proof.context
    24   val atomize_conv: Proof.context -> conv
    25   val eta_expand_conv: (Proof.context -> conv) -> Proof.context -> conv
    26 end
    27 
    28 structure SMT_Normalize: SMT_NORMALIZE =
    29 struct
    30 
    31 structure U = SMT_Utils
    32 
    33 infix 2 ??
    34 fun (test ?? f) x = if test x then f x else x
    35 
    36 
    37 
    38 (* instantiate elimination rules *)
    39  
    40 local
    41   val (cpfalse, cfalse) = `U.mk_cprop (Thm.cterm_of @{theory} @{const False})
    42 
    43   fun inst f ct thm =
    44     let val cv = f (Drule.strip_imp_concl (Thm.cprop_of thm))
    45     in Thm.instantiate ([], [(cv, ct)]) thm end
    46 in
    47 
    48 fun instantiate_elim thm =
    49   (case Thm.concl_of thm of
    50     @{const Trueprop} $ Var (_, @{typ bool}) => inst Thm.dest_arg cfalse thm
    51   | Var _ => inst I cpfalse thm
    52   | _ => thm)
    53 
    54 end
    55 
    56 
    57 
    58 (* simplification of trivial distincts (distinct should have at least
    59    three elements in the argument list) *)
    60 
    61 local
    62   fun is_trivial_distinct (Const (@{const_name distinct}, _) $ t) =
    63         (case try HOLogic.dest_list t of
    64           SOME [] => true
    65         | SOME [_] => true
    66         | _ => false)
    67     | is_trivial_distinct _ = false
    68 
    69   val thms = map mk_meta_eq @{lemma
    70     "distinct [] = True"
    71     "distinct [x] = True"
    72     "distinct [x, y] = (x ~= y)"
    73     by simp_all}
    74   fun distinct_conv _ =
    75     U.if_true_conv is_trivial_distinct (Conv.rewrs_conv thms)
    76 in
    77 fun trivial_distinct ctxt =
    78   map (apsnd ((Term.exists_subterm is_trivial_distinct o Thm.prop_of) ??
    79     Conv.fconv_rule (Conv.top_conv distinct_conv ctxt)))
    80 end
    81 
    82 
    83 
    84 (* rewrite bool case expressions as if expressions *)
    85 
    86 local
    87   val is_bool_case = (fn
    88       Const (@{const_name "bool.bool_case"}, _) $ _ $ _ $ _ => true
    89     | _ => false)
    90 
    91   val thm = mk_meta_eq @{lemma
    92     "(case P of True => x | False => y) = (if P then x else y)" by simp}
    93   val unfold_conv = U.if_true_conv is_bool_case (Conv.rewr_conv thm)
    94 in
    95 fun rewrite_bool_cases ctxt =
    96   map (apsnd ((Term.exists_subterm is_bool_case o Thm.prop_of) ??
    97     Conv.fconv_rule (Conv.top_conv (K unfold_conv) ctxt)))
    98 end
    99 
   100 
   101 
   102 (* normalization of numerals: rewriting of negative integer numerals into
   103    positive numerals, Numeral0 into 0, Numeral1 into 1 *)
   104 
   105 local
   106   fun is_number_sort ctxt T =
   107     Sign.of_sort (ProofContext.theory_of ctxt) (T, @{sort number_ring})
   108 
   109   fun is_strange_number ctxt (t as Const (@{const_name number_of}, _) $ _) =
   110         (case try HOLogic.dest_number t of
   111           SOME (T, i) => is_number_sort ctxt T andalso i < 2
   112         | NONE => false)
   113     | is_strange_number _ _ = false
   114 
   115   val pos_numeral_ss = HOL_ss
   116     addsimps [@{thm Int.number_of_minus}, @{thm Int.number_of_Min}]
   117     addsimps [@{thm Int.number_of_Pls}, @{thm Int.numeral_1_eq_1}]
   118     addsimps @{thms Int.pred_bin_simps}
   119     addsimps @{thms Int.normalize_bin_simps}
   120     addsimps @{lemma
   121       "Int.Min = - Int.Bit1 Int.Pls"
   122       "Int.Bit0 (- Int.Pls) = - Int.Pls"
   123       "Int.Bit0 (- k) = - Int.Bit0 k"
   124       "Int.Bit1 (- k) = - Int.Bit1 (Int.pred k)"
   125       by simp_all (simp add: pred_def)}
   126 
   127   fun pos_conv ctxt = U.if_conv (is_strange_number ctxt)
   128     (Simplifier.rewrite (Simplifier.context ctxt pos_numeral_ss))
   129     Conv.no_conv
   130 in
   131 fun normalize_numerals ctxt =
   132   map (apsnd ((Term.exists_subterm (is_strange_number ctxt) o Thm.prop_of) ??
   133     Conv.fconv_rule (Conv.top_sweep_conv pos_conv ctxt)))
   134 end
   135 
   136 
   137 
   138 (* embedding of standard natural number operations into integer operations *)
   139 
   140 local
   141   val nat_embedding = map (pair ~1) @{lemma
   142     "nat (int n) = n"
   143     "i >= 0 --> int (nat i) = i"
   144     "i < 0 --> int (nat i) = 0"
   145     by simp_all}
   146 
   147   val nat_rewriting = @{lemma
   148     "0 = nat 0"
   149     "1 = nat 1"
   150     "(number_of :: int => nat) = (%i. nat (number_of i))"
   151     "int (nat 0) = 0"
   152     "int (nat 1) = 1"
   153     "op < = (%a b. int a < int b)"
   154     "op <= = (%a b. int a <= int b)"
   155     "Suc = (%a. nat (int a + 1))"
   156     "op + = (%a b. nat (int a + int b))"
   157     "op - = (%a b. nat (int a - int b))"
   158     "op * = (%a b. nat (int a * int b))"
   159     "op div = (%a b. nat (int a div int b))"
   160     "op mod = (%a b. nat (int a mod int b))"
   161     "min = (%a b. nat (min (int a) (int b)))"
   162     "max = (%a b. nat (max (int a) (int b)))"
   163     "int (nat (int a + int b)) = int a + int b"
   164     "int (nat (int a + 1)) = int a + 1"  (* special rule due to Suc above *)
   165     "int (nat (int a * int b)) = int a * int b"
   166     "int (nat (int a div int b)) = int a div int b"
   167     "int (nat (int a mod int b)) = int a mod int b"
   168     "int (nat (min (int a) (int b))) = min (int a) (int b)"
   169     "int (nat (max (int a) (int b))) = max (int a) (int b)"
   170     by (auto intro!: ext simp add: nat_mult_distrib nat_div_distrib
   171       nat_mod_distrib int_mult[symmetric] zdiv_int[symmetric]
   172       zmod_int[symmetric])}
   173 
   174   fun on_positive num f x = 
   175     (case try HOLogic.dest_number (Thm.term_of num) of
   176       SOME (_, i) => if i >= 0 then SOME (f x) else NONE
   177     | NONE => NONE)
   178 
   179   val cancel_int_nat_ss = HOL_ss
   180     addsimps [@{thm Nat_Numeral.nat_number_of}]
   181     addsimps [@{thm Nat_Numeral.int_nat_number_of}]
   182     addsimps @{thms neg_simps}
   183 
   184   val int_eq = Thm.cterm_of @{theory} @{const "==" (int)}
   185 
   186   fun cancel_int_nat_simproc _ ss ct = 
   187     let
   188       val num = Thm.dest_arg (Thm.dest_arg ct)
   189       val goal = Thm.mk_binop int_eq ct num
   190       val simpset = Simplifier.inherit_context ss cancel_int_nat_ss
   191       fun tac _ = Simplifier.simp_tac simpset 1
   192     in on_positive num (Goal.prove_internal [] goal) tac end
   193 
   194   val nat_ss = HOL_ss
   195     addsimps nat_rewriting
   196     addsimprocs [
   197       Simplifier.make_simproc {
   198         name = "cancel_int_nat_num", lhss = [@{cpat "int (nat _)"}],
   199         proc = cancel_int_nat_simproc, identifier = [] }]
   200 
   201   fun conv ctxt = Simplifier.rewrite (Simplifier.context ctxt nat_ss)
   202 
   203   val uses_nat_type = Term.exists_type (Term.exists_subtype (equal @{typ nat}))
   204   val uses_nat_int = Term.exists_subterm (member (op aconv)
   205     [@{const of_nat (int)}, @{const nat}])
   206 in
   207 fun nat_as_int ctxt =
   208   map (apsnd ((uses_nat_type o Thm.prop_of) ?? Conv.fconv_rule (conv ctxt))) #>
   209   exists (uses_nat_int o Thm.prop_of o snd) ?? append nat_embedding
   210 end
   211 
   212 
   213 
   214 (* further normalizations: beta/eta, universal closure, atomize *)
   215 
   216 val eta_expand_eq = @{lemma "f == (%x. f x)" by (rule reflexive)}
   217 
   218 fun eta_expand_conv cv ctxt =
   219   Conv.rewr_conv eta_expand_eq then_conv Conv.abs_conv (cv o snd) ctxt
   220 
   221 local
   222   val eta_conv = eta_expand_conv
   223 
   224   fun args_conv cv ct =
   225     (case Thm.term_of ct of
   226       _ $ _ => Conv.combination_conv (args_conv cv) cv
   227     | _ => Conv.all_conv) ct
   228 
   229   fun eta_args_conv cv 0 = args_conv o cv
   230     | eta_args_conv cv i = eta_conv (eta_args_conv cv (i-1))
   231 
   232   fun keep_conv ctxt = Conv.binder_conv (norm_conv o snd) ctxt
   233   and eta_binder_conv ctxt = Conv.arg_conv (eta_conv norm_conv ctxt)
   234   and keep_let_conv ctxt = Conv.combination_conv
   235     (Conv.arg_conv (norm_conv ctxt)) (Conv.abs_conv (norm_conv o snd) ctxt)
   236   and unfold_let_conv ctxt = Conv.combination_conv
   237     (Conv.arg_conv (norm_conv ctxt)) (eta_conv norm_conv ctxt)
   238   and unfold_conv thm ctxt = Conv.rewr_conv thm then_conv keep_conv ctxt
   239   and unfold_ex1_conv ctxt = unfold_conv @{thm Ex1_def} ctxt
   240   and unfold_ball_conv ctxt = unfold_conv (mk_meta_eq @{thm Ball_def}) ctxt
   241   and unfold_bex_conv ctxt = unfold_conv (mk_meta_eq @{thm Bex_def}) ctxt
   242   and norm_conv ctxt ct =
   243     (case Thm.term_of ct of
   244       Const (@{const_name All}, _) $ Abs _ => keep_conv
   245     | Const (@{const_name All}, _) $ _ => eta_binder_conv
   246     | Const (@{const_name All}, _) => eta_conv eta_binder_conv
   247     | Const (@{const_name Ex}, _) $ Abs _ => keep_conv
   248     | Const (@{const_name Ex}, _) $ _ => eta_binder_conv
   249     | Const (@{const_name Ex}, _) => eta_conv eta_binder_conv
   250     | Const (@{const_name Let}, _) $ _ $ Abs _ => keep_let_conv
   251     | Const (@{const_name Let}, _) $ _ $ _ => unfold_let_conv
   252     | Const (@{const_name Let}, _) $ _ => eta_conv unfold_let_conv
   253     | Const (@{const_name Let}, _) => eta_conv (eta_conv unfold_let_conv)
   254     | Const (@{const_name Ex1}, _) $ _ => unfold_ex1_conv
   255     | Const (@{const_name Ex1}, _) => eta_conv unfold_ex1_conv 
   256     | Const (@{const_name Ball}, _) $ _ $ _ => unfold_ball_conv
   257     | Const (@{const_name Ball}, _) $ _ => eta_conv unfold_ball_conv
   258     | Const (@{const_name Ball}, _) => eta_conv (eta_conv unfold_ball_conv)
   259     | Const (@{const_name Bex}, _) $ _ $ _ => unfold_bex_conv
   260     | Const (@{const_name Bex}, _) $ _ => eta_conv unfold_bex_conv
   261     | Const (@{const_name Bex}, _) => eta_conv (eta_conv unfold_bex_conv)
   262     | Abs _ => Conv.abs_conv (norm_conv o snd)
   263     | _ =>
   264         (case Term.strip_comb (Thm.term_of ct) of
   265           (Const (c as (_, T)), ts) =>
   266             if SMT_Builtin.is_builtin ctxt c
   267             then eta_args_conv norm_conv
   268               (length (Term.binder_types T) - length ts)
   269             else args_conv o norm_conv
   270         | _ => args_conv o norm_conv)) ctxt ct
   271 
   272   fun is_normed ctxt t =
   273     (case t of
   274       Const (@{const_name All}, _) $ Abs (_, _, u) => is_normed ctxt u
   275     | Const (@{const_name All}, _) $ _ => false
   276     | Const (@{const_name All}, _) => false
   277     | Const (@{const_name Ex}, _) $ Abs (_, _, u) => is_normed ctxt u
   278     | Const (@{const_name Ex}, _) $ _ => false
   279     | Const (@{const_name Ex}, _) => false
   280     | Const (@{const_name Let}, _) $ u1 $ Abs (_, _, u2) =>
   281         is_normed ctxt u1 andalso is_normed ctxt u2
   282     | Const (@{const_name Let}, _) $ _ $ _ => false
   283     | Const (@{const_name Let}, _) $ _ => false
   284     | Const (@{const_name Let}, _) => false
   285     | Const (@{const_name Ex1}, _) $ _ => false
   286     | Const (@{const_name Ex1}, _) => false
   287     | Const (@{const_name Ball}, _) $ _ $ _ => false
   288     | Const (@{const_name Ball}, _) $ _ => false
   289     | Const (@{const_name Ball}, _) => false
   290     | Const (@{const_name Bex}, _) $ _ $ _ => false
   291     | Const (@{const_name Bex}, _) $ _ => false
   292     | Const (@{const_name Bex}, _) => false
   293     | Abs (_, _, u) => is_normed ctxt u
   294     | _ =>
   295         (case Term.strip_comb t of
   296           (Const (c as (_, T)), ts) =>
   297             if SMT_Builtin.is_builtin ctxt c
   298             then length (Term.binder_types T) = length ts andalso
   299               forall (is_normed ctxt) ts
   300             else forall (is_normed ctxt) ts
   301         | (_, ts) => forall (is_normed ctxt) ts))
   302 in
   303 fun norm_binder_conv ctxt =
   304   U.if_conv (is_normed ctxt) Conv.all_conv (norm_conv ctxt)
   305 end
   306 
   307 fun norm_def ctxt thm =
   308   (case Thm.prop_of thm of
   309     @{const Trueprop} $ (Const (@{const_name HOL.eq}, _) $ _ $ Abs _) =>
   310       norm_def ctxt (thm RS @{thm fun_cong})
   311   | Const (@{const_name "=="}, _) $ _ $ Abs _ =>
   312       norm_def ctxt (thm RS @{thm meta_eq_to_obj_eq})
   313   | _ => thm)
   314 
   315 fun atomize_conv ctxt ct =
   316   (case Thm.term_of ct of
   317     @{const "==>"} $ _ $ _ =>
   318       Conv.binop_conv (atomize_conv ctxt) then_conv
   319       Conv.rewr_conv @{thm atomize_imp}
   320   | Const (@{const_name "=="}, _) $ _ $ _ =>
   321       Conv.binop_conv (atomize_conv ctxt) then_conv
   322       Conv.rewr_conv @{thm atomize_eq}
   323   | Const (@{const_name all}, _) $ Abs _ =>
   324       Conv.binder_conv (atomize_conv o snd) ctxt then_conv
   325       Conv.rewr_conv @{thm atomize_all}
   326   | _ => Conv.all_conv) ct
   327 
   328 fun normalize_rule ctxt =
   329   Conv.fconv_rule (
   330     (* reduce lambda abstractions, except at known binders: *)
   331     Thm.beta_conversion true then_conv
   332     Thm.eta_conversion then_conv
   333     norm_binder_conv ctxt) #>
   334   norm_def ctxt #>
   335   Drule.forall_intr_vars #>
   336   Conv.fconv_rule (atomize_conv ctxt)
   337 
   338 
   339 
   340 (* lift lambda terms into additional rules *)
   341 
   342 local
   343   fun used_vars cvs ct =
   344     let
   345       val lookup = AList.lookup (op aconv) (map (` Thm.term_of) cvs)
   346       val add = (fn SOME ct => insert (op aconvc) ct | _ => I)
   347     in Term.fold_aterms (add o lookup) (Thm.term_of ct) [] end
   348 
   349   fun apply cv thm = 
   350     let val thm' = Thm.combination thm (Thm.reflexive cv)
   351     in Thm.transitive thm' (Thm.beta_conversion false (Thm.rhs_of thm')) end
   352   fun apply_def cvs eq = Thm.symmetric (fold apply cvs eq)
   353 
   354   fun replace_lambda cvs ct (cx as (ctxt, defs)) =
   355     let
   356       val cvs' = used_vars cvs ct
   357       val ct' = fold_rev Thm.cabs cvs' ct
   358     in
   359       (case Termtab.lookup defs (Thm.term_of ct') of
   360         SOME eq => (apply_def cvs' eq, cx)
   361       | NONE =>
   362           let
   363             val {T, ...} = Thm.rep_cterm ct' and n = Name.uu
   364             val (n', ctxt') = yield_singleton Variable.variant_fixes n ctxt
   365             val cu = U.mk_cequals (U.certify ctxt (Free (n', T))) ct'
   366             val (eq, ctxt'') = yield_singleton Assumption.add_assumes cu ctxt'
   367             val defs' = Termtab.update (Thm.term_of ct', eq) defs
   368           in (apply_def cvs' eq, (ctxt'', defs')) end)
   369     end
   370 
   371   fun none ct cx = (Thm.reflexive ct, cx)
   372   fun in_comb f g ct cx =
   373     let val (cu1, cu2) = Thm.dest_comb ct
   374     in cx |> f cu1 ||>> g cu2 |>> uncurry Thm.combination end
   375   fun in_arg f = in_comb none f
   376   fun in_abs f cvs ct (ctxt, defs) =
   377     let
   378       val (n, ctxt') = yield_singleton Variable.variant_fixes Name.uu ctxt
   379       val (cv, cu) = Thm.dest_abs (SOME n) ct
   380     in  (ctxt', defs) |> f (cv :: cvs) cu |>> Thm.abstract_rule n cv end
   381 
   382   fun traverse cvs ct =
   383     (case Thm.term_of ct of
   384       Const (@{const_name All}, _) $ Abs _ => in_arg (in_abs traverse cvs)
   385     | Const (@{const_name Ex}, _) $ Abs _ => in_arg (in_abs traverse cvs)
   386     | Const (@{const_name Let}, _) $ _ $ Abs _ =>
   387         in_comb (in_arg (traverse cvs)) (in_abs traverse cvs)
   388     | Abs _ => at_lambda cvs
   389     | _ $ _ => in_comb (traverse cvs) (traverse cvs)
   390     | _ => none) ct
   391 
   392   and at_lambda cvs ct =
   393     in_abs traverse cvs ct #-> (fn thm =>
   394     replace_lambda cvs (Thm.rhs_of thm) #>> Thm.transitive thm)
   395 
   396   fun has_free_lambdas t =
   397     (case t of
   398       Const (@{const_name All}, _) $ Abs (_, _, u) => has_free_lambdas u
   399     | Const (@{const_name Ex}, _) $ Abs (_, _, u) => has_free_lambdas u
   400     | Const (@{const_name Let}, _) $ u1 $ Abs (_, _, u2) =>
   401         has_free_lambdas u1 orelse has_free_lambdas u2
   402     | Abs _ => true
   403     | u1 $ u2 => has_free_lambdas u1 orelse has_free_lambdas u2
   404     | _ => false)
   405 
   406   fun lift_lm f thm cx =
   407     if not (has_free_lambdas (Thm.prop_of thm)) then (thm, cx)
   408     else cx |> f (Thm.cprop_of thm) |>> (fn thm' => Thm.equal_elim thm' thm)
   409 in
   410 fun lift_lambdas irules ctxt =
   411   let
   412     val cx = (ctxt, Termtab.empty)
   413     val (idxs, thms) = split_list irules
   414     val (thms', (ctxt', defs)) = fold_map (lift_lm (traverse [])) thms cx
   415     val eqs = Termtab.fold (cons o normalize_rule ctxt' o snd) defs []
   416   in (map (pair ~1) eqs @ (idxs ~~ thms'), ctxt') end
   417 end
   418 
   419 
   420 
   421 (* make application explicit for functions with varying number of arguments *)
   422 
   423 local
   424   val const = prefix "c" and free = prefix "f"
   425   fun min i (e as (_, j)) = if i <> j then (true, Int.min (i, j)) else e
   426   fun add t i = Symtab.map_default (t, (false, i)) (min i)
   427   fun traverse t =
   428     (case Term.strip_comb t of
   429       (Const (n, _), ts) => add (const n) (length ts) #> fold traverse ts 
   430     | (Free (n, _), ts) => add (free n) (length ts) #> fold traverse ts
   431     | (Abs (_, _, u), ts) => fold traverse (u :: ts)
   432     | (_, ts) => fold traverse ts)
   433   fun prune tab = Symtab.fold (fn (n, (true, i)) =>
   434     Symtab.update (n, i) | _ => I) tab Symtab.empty
   435 
   436   fun binop_conv cv1 cv2 = Conv.combination_conv (Conv.arg_conv cv1) cv2
   437   fun nary_conv conv1 conv2 ct =
   438     (Conv.combination_conv (nary_conv conv1 conv2) conv2 else_conv conv1) ct
   439   fun abs_conv conv tb = Conv.abs_conv (fn (cv, cx) =>
   440     let val n = fst (Term.dest_Free (Thm.term_of cv))
   441     in conv (Symtab.update (free n, 0) tb) cx end)
   442   val fun_app_rule = @{lemma "f x == fun_app f x" by (simp add: fun_app_def)}
   443 in
   444 fun explicit_application ctxt irules =
   445   let
   446     fun sub_conv tb ctxt ct =
   447       (case Term.strip_comb (Thm.term_of ct) of
   448         (Const (n, _), ts) => app_conv tb (const n) (length ts) ctxt
   449       | (Free (n, _), ts) => app_conv tb (free n) (length ts) ctxt
   450       | (Abs _, _) => nary_conv (abs_conv sub_conv tb ctxt) (sub_conv tb ctxt)
   451       | (_, _) => nary_conv Conv.all_conv (sub_conv tb ctxt)) ct
   452     and app_conv tb n i ctxt =
   453       (case Symtab.lookup tb n of
   454         NONE => nary_conv Conv.all_conv (sub_conv tb ctxt)
   455       | SOME j => fun_app_conv tb ctxt (i - j))
   456     and fun_app_conv tb ctxt i ct = (
   457       if i = 0 then nary_conv Conv.all_conv (sub_conv tb ctxt)
   458       else
   459         Conv.rewr_conv fun_app_rule then_conv
   460         binop_conv (fun_app_conv tb ctxt (i-1)) (sub_conv tb ctxt)) ct
   461 
   462     fun needs_exp_app tab = Term.exists_subterm (fn
   463         Bound _ $ _ => true
   464       | Const (n, _) => Symtab.defined tab (const n)
   465       | Free (n, _) => Symtab.defined tab (free n)
   466       | _ => false)
   467 
   468     fun rewrite tab ctxt thm =
   469       if not (needs_exp_app tab (Thm.prop_of thm)) then thm
   470       else Conv.fconv_rule (sub_conv tab ctxt) thm
   471 
   472     val tab = prune (fold (traverse o Thm.prop_of o snd) irules Symtab.empty)
   473   in map (apsnd (rewrite tab ctxt)) irules end
   474 end
   475 
   476 
   477 
   478 (* add missing datatype selectors via hypothetical definitions *)
   479 
   480 local
   481   val add = (fn Type (n, _) => Symtab.update (n, ()) | _ => I)
   482 
   483   fun collect t =
   484     (case Term.strip_comb t of
   485       (Abs (_, T, t), _) => add T #> collect t
   486     | (Const (_, T), ts) => collects T ts
   487     | (Free (_, T), ts) => collects T ts
   488     | _ => I)
   489   and collects T ts =
   490     let val ((Ts, Us), U) = Term.strip_type T |> apfst (chop (length ts))
   491     in fold add Ts #> add (Us ---> U) #> fold collect ts end
   492 
   493   fun add_constructors thy n =
   494     (case Datatype.get_info thy n of
   495       NONE => I
   496     | SOME {descr, ...} => fold (fn (_, (_, _, cs)) => fold (fn (n, ds) =>
   497         fold (insert (op =) o pair n) (1 upto length ds)) cs) descr)
   498 
   499   fun add_selector (c as (n, i)) ctxt =
   500     (case Datatype_Selectors.lookup_selector ctxt c of
   501       SOME _ => ctxt
   502     | NONE =>
   503         let
   504           val T = Sign.the_const_type (ProofContext.theory_of ctxt) n
   505           val U = Term.body_type T --> nth (Term.binder_types T) (i-1)
   506         in
   507           ctxt
   508           |> yield_singleton Variable.variant_fixes Name.uu
   509           |>> pair ((n, T), i) o rpair U
   510           |-> Context.proof_map o Datatype_Selectors.add_selector
   511         end)
   512 in
   513 
   514 fun datatype_selectors irules ctxt =
   515   let
   516     val ns = Symtab.keys (fold (collect o Thm.prop_of o snd) irules Symtab.empty)
   517     val cs = fold (add_constructors (ProofContext.theory_of ctxt)) ns []
   518   in (irules, fold add_selector cs ctxt) end
   519     (* FIXME: also generate hypothetical definitions for the selectors *)
   520 
   521 end
   522 
   523 
   524 
   525 (* combined normalization *)
   526 
   527 type extra_norm = bool -> (int * thm) list -> Proof.context ->
   528   (int * thm) list * Proof.context
   529 
   530 fun with_context f irules ctxt = (f ctxt irules, ctxt)
   531 
   532 fun normalize extra_norm with_datatypes irules ctxt =
   533   let
   534     fun norm f ctxt' (i, thm) =
   535       if Config.get ctxt' SMT_Config.drop_bad_facts then
   536         (case try (f ctxt') thm of
   537           SOME thm' => SOME (i, thm')
   538         | NONE => (SMT_Config.verbose_msg ctxt' (prefix ("Warning: " ^
   539             "dropping assumption: ") o Display.string_of_thm ctxt') thm; NONE))
   540       else SOME (i, f ctxt' thm)
   541   in
   542     irules
   543     |> map (apsnd instantiate_elim)
   544     |> trivial_distinct ctxt
   545     |> rewrite_bool_cases ctxt
   546     |> normalize_numerals ctxt
   547     |> nat_as_int ctxt
   548     |> rpair ctxt
   549     |-> extra_norm with_datatypes
   550     |-> with_context (map_filter o norm normalize_rule)
   551     |-> SMT_Monomorph.monomorph
   552     |-> lift_lambdas
   553     |-> with_context explicit_application
   554     |-> (if with_datatypes then datatype_selectors else pair)
   555   end
   556 
   557 end