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