src/HOL/SMT/Tools/smt_normalize.ML
author wenzelm
Tue Sep 29 16:24:36 2009 +0200 (2009-09-29)
changeset 32740 9dd0a2f83429
parent 32618 42865636d006
child 33010 39f73a59e855
permissions -rw-r--r--
explicit indication of Unsynchronized.ref;
     1 (*  Title:      HOL/SMT/Tools/smt_normalize.ML
     2     Author:     Sascha Boehme, TU Muenchen
     3 
     4 Normalization steps on theorems required by SMT solvers:
     5   * unfold trivial let expressions,
     6   * replace negative numerals by negated positive numerals,
     7   * embed natural numbers into integers,
     8   * add extra rules specifying types and constants which occur frequently,
     9   * lift lambda terms,
    10   * make applications explicit for functions with varying number of arguments,
    11   * fully translate into object logic, add universal closure. 
    12 *)
    13 
    14 signature SMT_NORMALIZE =
    15 sig
    16   val normalize_rule: Proof.context -> thm -> thm
    17   val instantiate_free: Thm.cterm * Thm.cterm -> thm -> thm
    18   val discharge_definition: Thm.cterm -> thm -> thm
    19 
    20   val trivial_let: Proof.context -> thm list -> thm list
    21   val positive_numerals: Proof.context -> thm list -> thm list
    22   val nat_as_int: Proof.context -> thm list -> thm list
    23   val unfold_defs: bool Config.T
    24   val add_pair_rules: Proof.context -> thm list -> thm list
    25   val add_fun_upd_rules: Proof.context -> thm list -> thm list
    26   val add_abs_min_max_rules: Proof.context -> thm list -> thm list
    27 
    28   datatype config =
    29     RewriteTrivialLets |
    30     RewriteNegativeNumerals |
    31     RewriteNaturalNumbers |
    32     AddPairRules |
    33     AddFunUpdRules |
    34     AddAbsMinMaxRules
    35 
    36   val normalize: config list -> Proof.context -> thm list ->
    37     Thm.cterm list * thm list
    38 
    39   val setup: theory -> theory
    40 end
    41 
    42 structure SMT_Normalize: SMT_NORMALIZE =
    43 struct
    44 
    45 val norm_binder_conv = Conv.try_conv (More_Conv.rewrs_conv [
    46   @{lemma "All P == ALL x. P x" by (rule reflexive)},
    47   @{lemma "Ex P == EX x. P x" by (rule reflexive)},
    48   @{lemma "Let c P == let x = c in P x" by (rule reflexive)}])
    49 
    50 fun cert ctxt = Thm.cterm_of (ProofContext.theory_of ctxt)
    51 
    52 fun norm_meta_def cv thm = 
    53   let val thm' = Thm.combination thm (Thm.reflexive cv)
    54   in Thm.transitive thm' (Thm.beta_conversion false (Thm.rhs_of thm')) end
    55 
    56 fun norm_def ctxt thm =
    57   (case Thm.prop_of thm of
    58     Const (@{const_name "=="}, _) $ _ $ Abs (_, T, _) =>
    59       let val v = Var ((Name.uu, #maxidx (Thm.rep_thm thm) + 1), T)
    60       in norm_def ctxt (norm_meta_def (cert ctxt v) thm) end
    61   | @{term Trueprop} $ (Const (@{const_name "op ="}, _) $ _ $ Abs _) =>
    62       norm_def ctxt (thm RS @{thm fun_cong})
    63   | _ => thm)
    64 
    65 fun normalize_rule ctxt =
    66   Conv.fconv_rule (
    67     Thm.beta_conversion true then_conv
    68     Thm.eta_conversion then_conv
    69     More_Conv.bottom_conv (K norm_binder_conv) ctxt) #>
    70   norm_def ctxt #>
    71   Drule.forall_intr_vars #>
    72   Conv.fconv_rule ObjectLogic.atomize
    73 
    74 fun instantiate_free (cv, ct) thm =
    75   if Term.exists_subterm (equal (Thm.term_of cv)) (Thm.prop_of thm)
    76   then Thm.forall_elim ct (Thm.forall_intr cv thm)
    77   else thm
    78 
    79 fun discharge_definition ct thm =
    80   let val (cv, cu) = Thm.dest_equals ct
    81   in
    82     Thm.implies_intr ct thm
    83     |> instantiate_free (cv, cu)
    84     |> (fn thm => Thm.implies_elim thm (Thm.reflexive cu))
    85   end
    86 
    87 fun if_conv c cv1 cv2 ct = (if c (Thm.term_of ct) then cv1 else cv2) ct
    88 fun if_true_conv c cv = if_conv c cv Conv.all_conv
    89 
    90 
    91 (* simplification of trivial let expressions (whose bound variables occur at
    92    most once) *)
    93 
    94 local
    95   fun count i (Bound j) = if j = i then 1 else 0
    96     | count i (t $ u) = count i t + count i u
    97     | count i (Abs (_, _, t)) = count (i + 1) t
    98     | count _ _ = 0
    99 
   100   fun is_trivial_let (Const (@{const_name Let}, _) $ _ $ Abs (_, _, t)) =
   101         (count 0 t <= 1)
   102     | is_trivial_let _ = false
   103 
   104   fun let_conv _ = if_true_conv is_trivial_let (Conv.rewr_conv @{thm Let_def})
   105 
   106   fun cond_let_conv ctxt = if_true_conv (Term.exists_subterm is_trivial_let)
   107     (More_Conv.top_conv let_conv ctxt)
   108 in
   109 fun trivial_let ctxt = map (Conv.fconv_rule (cond_let_conv ctxt))
   110 end
   111 
   112 
   113 (* rewriting of negative integer numerals into positive numerals *)
   114 
   115 local
   116   fun neg_numeral @{term Int.Min} = true
   117     | neg_numeral _ = false
   118   fun is_number_sort thy T = Sign.of_sort thy (T, @{sort number_ring})
   119   fun is_neg_number ctxt (Const (@{const_name number_of}, T) $ t) =
   120         Term.exists_subterm neg_numeral t andalso
   121         is_number_sort (ProofContext.theory_of ctxt) (Term.body_type T)
   122     | is_neg_number _ _ = false
   123   fun has_neg_number ctxt = Term.exists_subterm (is_neg_number ctxt)
   124 
   125   val pos_numeral_ss = HOL_ss
   126     addsimps [@{thm Int.number_of_minus}, @{thm Int.number_of_Min}]
   127     addsimps [@{thm Int.numeral_1_eq_1}]
   128     addsimps @{thms Int.pred_bin_simps}
   129     addsimps @{thms Int.normalize_bin_simps}
   130     addsimps @{lemma
   131       "Int.Min = - Int.Bit1 Int.Pls"
   132       "Int.Bit0 (- Int.Pls) = - Int.Pls"
   133       "Int.Bit0 (- k) = - Int.Bit0 k"
   134       "Int.Bit1 (- k) = - Int.Bit1 (Int.pred k)"
   135       by simp_all (simp add: pred_def)}
   136 
   137   fun pos_conv ctxt = if_conv (is_neg_number ctxt)
   138     (Simplifier.rewrite (Simplifier.context ctxt pos_numeral_ss))
   139     Conv.no_conv
   140 
   141   fun cond_pos_conv ctxt = if_true_conv (has_neg_number ctxt)
   142     (More_Conv.top_sweep_conv pos_conv ctxt)
   143 in
   144 fun positive_numerals ctxt = map (Conv.fconv_rule (cond_pos_conv ctxt))
   145 end
   146 
   147 
   148 (* embedding of standard natural number operations into integer operations *)
   149 
   150 local
   151   val nat_embedding = @{lemma
   152     "nat (int n) = n"
   153     "i >= 0 --> int (nat i) = i"
   154     "i < 0 --> int (nat i) = 0"
   155     by simp_all}
   156 
   157   val nat_rewriting = @{lemma
   158     "0 = nat 0"
   159     "1 = nat 1"
   160     "number_of i = nat (number_of i)"
   161     "int (nat 0) = 0"
   162     "int (nat 1) = 1"
   163     "a < b = (int a < int b)"
   164     "a <= b = (int a <= int b)"
   165     "Suc a = nat (int a + 1)"
   166     "a + b = nat (int a + int b)"
   167     "a - b = nat (int a - int b)"
   168     "a * b = nat (int a * int b)"
   169     "a div b = nat (int a div int b)"
   170     "a mod b = nat (int a mod int b)"
   171     "int (nat (int a + int b)) = int a + int b"
   172     "int (nat (int a * int b)) = int a * int b"
   173     "int (nat (int a div int b)) = int a div int b"
   174     "int (nat (int a mod int b)) = int a mod int b"
   175     by (simp add: nat_mult_distrib nat_div_distrib nat_mod_distrib
   176       int_mult[symmetric] zdiv_int[symmetric] zmod_int[symmetric])+}
   177 
   178   fun on_positive num f x = 
   179     (case try HOLogic.dest_number (Thm.term_of num) of
   180       SOME (_, i) => if i >= 0 then SOME (f x) else NONE
   181     | NONE => NONE)
   182 
   183   val cancel_int_nat_ss = HOL_ss
   184     addsimps [@{thm Nat_Numeral.nat_number_of}]
   185     addsimps [@{thm Nat_Numeral.int_nat_number_of}]
   186     addsimps @{thms neg_simps}
   187 
   188   fun cancel_int_nat_simproc _ ss ct = 
   189     let
   190       val num = Thm.dest_arg (Thm.dest_arg ct)
   191       val goal = Thm.mk_binop @{cterm "op == :: int => _"} ct num
   192       val simpset = Simplifier.inherit_context ss cancel_int_nat_ss
   193       fun tac _ = Simplifier.simp_tac simpset 1
   194     in on_positive num (Goal.prove_internal [] goal) tac end
   195 
   196   val nat_ss = HOL_ss
   197     addsimps nat_rewriting
   198     addsimprocs [Simplifier.make_simproc {
   199       name = "cancel_int_nat_num", lhss = [@{cpat "int (nat _)"}],
   200       proc = cancel_int_nat_simproc, identifier = [] }]
   201 
   202   fun conv ctxt = Simplifier.rewrite (Simplifier.context ctxt nat_ss)
   203 
   204   val uses_nat_type = Term.exists_type (Term.exists_subtype (equal @{typ nat}))
   205 in
   206 fun nat_as_int ctxt thms =
   207   let
   208     fun norm thm uses_nat =
   209       if not (uses_nat_type (Thm.prop_of thm)) then (thm, uses_nat)
   210       else (Conv.fconv_rule (conv ctxt) thm, true)
   211     val (thms', uses_nat) = fold_map norm thms false
   212   in if uses_nat then nat_embedding @ thms' else thms' end
   213 end
   214 
   215 
   216 (* include additional rules *)
   217 
   218 val (unfold_defs, unfold_defs_setup) =
   219   Attrib.config_bool "smt_unfold_defs" true
   220 
   221 local
   222   val pair_rules = [@{thm fst_conv}, @{thm snd_conv}, @{thm pair_collapse}]
   223 
   224   val pair_type = (fn Type (@{type_name "*"}, _) => true | _ => false)
   225   val exists_pair_type = Term.exists_type (Term.exists_subtype pair_type)
   226 
   227   val fun_upd_rules = [@{thm fun_upd_same}, @{thm fun_upd_apply}]
   228   val is_fun_upd = (fn Const (@{const_name fun_upd}, _) => true | _ => false)
   229   val exists_fun_upd = Term.exists_subterm is_fun_upd
   230 in
   231 fun add_pair_rules _ thms =
   232   thms
   233   |> exists (exists_pair_type o Thm.prop_of) thms ? append pair_rules
   234 
   235 fun add_fun_upd_rules _ thms =
   236   thms
   237   |> exists (exists_fun_upd o Thm.prop_of) thms ? append fun_upd_rules
   238 end
   239 
   240 
   241 local
   242   fun mk_entry t thm = (Term.head_of t, (thm, thm RS @{thm eq_reflection}))
   243   fun prepare_def thm =
   244     (case HOLogic.dest_Trueprop (Thm.prop_of thm) of
   245       Const (@{const_name "op ="}, _) $ t $ _ => mk_entry t thm
   246     | t => raise TERM ("prepare_def", [t]))
   247 
   248   val defs = map prepare_def [
   249     @{thm abs_if[where 'a = int]}, @{thm abs_if[where 'a = real]},
   250     @{thm min_def[where 'a = int]}, @{thm min_def[where 'a = real]},
   251     @{thm max_def[where 'a = int]}, @{thm max_def[where 'a = real]}]
   252 
   253   fun add_sym t = if AList.defined (op =) defs t then insert (op =) t else I
   254   fun add_syms thms = fold (Term.fold_aterms add_sym o Thm.prop_of) thms []
   255 
   256   fun unfold_conv ctxt ct =
   257     (case AList.lookup (op =) defs (Term.head_of (Thm.term_of ct)) of
   258       SOME (_, eq) => Conv.rewr_conv eq
   259     | NONE => Conv.all_conv) ct
   260 in
   261 fun add_abs_min_max_rules ctxt thms =
   262   if Config.get ctxt unfold_defs
   263   then map (Conv.fconv_rule (More_Conv.bottom_conv unfold_conv ctxt)) thms
   264   else map fst (map_filter (AList.lookup (op =) defs) (add_syms thms)) @ thms
   265 end
   266 
   267 
   268 (* lift lambda terms into additional rules *)
   269 
   270 local
   271   val meta_eq = @{cpat "op =="}
   272   val meta_eqT = hd (Thm.dest_ctyp (Thm.ctyp_of_term meta_eq))
   273   fun inst_meta cT = Thm.instantiate_cterm ([(meta_eqT, cT)], []) meta_eq
   274   fun mk_meta_eq ct cu = Thm.mk_binop (inst_meta (Thm.ctyp_of_term ct)) ct cu
   275 
   276   fun lambda_conv conv =
   277     let
   278       fun sub_conv cvs ctxt ct =
   279         (case Thm.term_of ct of
   280           Const (@{const_name All}, _) $ Abs _ => quant_conv cvs ctxt
   281         | Const (@{const_name Ex}, _) $ Abs _ => quant_conv cvs ctxt
   282         | Const _ $ Abs _ => Conv.arg_conv (at_lambda_conv cvs ctxt)
   283         | Const (@{const_name Let}, _) $ _ $ Abs _ => Conv.combination_conv
   284             (Conv.arg_conv (sub_conv cvs ctxt)) (abs_conv cvs ctxt)
   285         | Abs _ => at_lambda_conv cvs ctxt
   286         | _ $ _ => Conv.comb_conv (sub_conv cvs ctxt)
   287         | _ => Conv.all_conv) ct
   288       and abs_conv cvs = Conv.abs_conv (fn (cv, cx) => sub_conv (cv::cvs) cx)
   289       and quant_conv cvs ctxt = Conv.arg_conv (abs_conv cvs ctxt)
   290       and at_lambda_conv cvs ctxt = abs_conv cvs ctxt then_conv conv cvs ctxt
   291     in sub_conv [] end
   292 
   293   fun used_vars cvs ct =
   294     let
   295       val lookup = AList.lookup (op aconv) (map (` Thm.term_of) cvs)
   296       val add = (fn (SOME ct) => insert (op aconvc) ct | _ => I)
   297     in Term.fold_aterms (add o lookup) (Thm.term_of ct) [] end
   298 
   299   val rev_int_fst_ord = rev_order o int_ord o pairself fst
   300   fun ordered_values tab =
   301     Termtab.fold (fn (_, x) => OrdList.insert rev_int_fst_ord x) tab []
   302     |> map snd
   303 in
   304 fun lift_lambdas ctxt thms =
   305   let
   306     val declare_frees = fold (Thm.fold_terms Term.declare_term_frees)
   307     val names = Unsynchronized.ref (declare_frees thms (Name.make_context []))
   308     val fresh_name = Unsynchronized.change_result names o yield_singleton Name.variants
   309 
   310     val defs = Unsynchronized.ref (Termtab.empty : (int * thm) Termtab.table)
   311     fun add_def t thm = Unsynchronized.change defs (Termtab.update (t, (serial (), thm)))
   312     fun make_def cvs eq = Thm.symmetric (fold norm_meta_def cvs eq)
   313     fun def_conv cvs ctxt ct =
   314       let
   315         val cvs' = used_vars cvs ct
   316         val ct' = fold Thm.cabs cvs' ct
   317       in
   318         (case Termtab.lookup (!defs) (Thm.term_of ct') of
   319           SOME (_, eq) => make_def cvs' eq
   320         | NONE =>
   321             let
   322               val {t, T, ...} = Thm.rep_cterm ct'
   323               val eq = mk_meta_eq (cert ctxt (Free (fresh_name "", T))) ct'
   324               val thm = Thm.assume eq
   325             in (add_def t thm; make_def cvs' thm) end)
   326       end
   327     val thms' = map (Conv.fconv_rule (lambda_conv def_conv ctxt)) thms
   328     val eqs = ordered_values (!defs)
   329   in
   330     (maps (#hyps o Thm.crep_thm) eqs, map (normalize_rule ctxt) eqs @ thms')
   331   end
   332 end
   333 
   334 
   335 (* make application explicit for functions with varying number of arguments *)
   336 
   337 local
   338   val const = prefix "c" and free = prefix "f"
   339   fun min i (e as (_, j)) = if i <> j then (true, Int.min (i, j)) else e
   340   fun add t i = Symtab.map_default (t, (false, i)) (min i)
   341   fun traverse t =
   342     (case Term.strip_comb t of
   343       (Const (n, _), ts) => add (const n) (length ts) #> fold traverse ts 
   344     | (Free (n, _), ts) => add (free n) (length ts) #> fold traverse ts
   345     | (Abs (_, _, u), ts) => fold traverse (u :: ts)
   346     | (_, ts) => fold traverse ts)
   347   val prune = (fn (n, (true, i)) => Symtab.update (n, i) | _ => I)
   348   fun prune_tab tab = Symtab.fold prune tab Symtab.empty
   349 
   350   fun binop_conv cv1 cv2 = Conv.combination_conv (Conv.arg_conv cv1) cv2
   351   fun nary_conv conv1 conv2 ct =
   352     (Conv.combination_conv (nary_conv conv1 conv2) conv2 else_conv conv1) ct
   353   fun abs_conv conv tb = Conv.abs_conv (fn (cv, cx) =>
   354     let val n = fst (Term.dest_Free (Thm.term_of cv))
   355     in conv (Symtab.update (free n, 0) tb) cx end)
   356   val apply_rule = @{lemma "f x == apply f x" by (simp add: apply_def)}
   357 in
   358 fun explicit_application ctxt thms =
   359   let
   360     fun sub_conv tb ctxt ct =
   361       (case Term.strip_comb (Thm.term_of ct) of
   362         (Const (n, _), ts) => app_conv tb (const n) (length ts) ctxt
   363       | (Free (n, _), ts) => app_conv tb (free n) (length ts) ctxt
   364       | (Abs _, ts) => nary_conv (abs_conv sub_conv tb ctxt) (sub_conv tb ctxt)
   365       | (_, ts) => nary_conv Conv.all_conv (sub_conv tb ctxt)) ct
   366     and app_conv tb n i ctxt =
   367       (case Symtab.lookup tb n of
   368         NONE => nary_conv Conv.all_conv (sub_conv tb ctxt)
   369       | SOME j => apply_conv tb ctxt (i - j))
   370     and apply_conv tb ctxt i ct = (
   371       if i = 0 then nary_conv Conv.all_conv (sub_conv tb ctxt)
   372       else
   373         Conv.rewr_conv apply_rule then_conv
   374         binop_conv (apply_conv tb ctxt (i-1)) (sub_conv tb ctxt)) ct
   375 
   376     val tab = prune_tab (fold (traverse o Thm.prop_of) thms Symtab.empty)
   377   in map (Conv.fconv_rule (sub_conv tab ctxt)) thms end
   378 end
   379 
   380 
   381 (* combined normalization *)
   382 
   383 datatype config =
   384   RewriteTrivialLets |
   385   RewriteNegativeNumerals |
   386   RewriteNaturalNumbers |
   387   AddPairRules |
   388   AddFunUpdRules |
   389   AddAbsMinMaxRules
   390 
   391 fun normalize config ctxt thms =
   392   let fun if_enabled c f = member (op =) config c ? f ctxt
   393   in
   394     thms
   395     |> if_enabled RewriteTrivialLets trivial_let
   396     |> if_enabled RewriteNegativeNumerals positive_numerals
   397     |> if_enabled RewriteNaturalNumbers nat_as_int
   398     |> if_enabled AddPairRules add_pair_rules
   399     |> if_enabled AddFunUpdRules add_fun_upd_rules
   400     |> if_enabled AddAbsMinMaxRules add_abs_min_max_rules
   401     |> map (normalize_rule ctxt)
   402     |> lift_lambdas ctxt
   403     |> apsnd (explicit_application ctxt)
   404   end
   405 
   406 val setup = unfold_defs_setup
   407 
   408 end