src/HOL/Tools/SMT/smt_normalize.ML
author wenzelm
Fri Mar 06 23:44:57 2015 +0100 (2015-03-06)
changeset 59632 5980e75a204e
parent 59621 291934bac95e
child 60642 48dd1cefb4ae
permissions -rw-r--r--
clarified context;
     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 *)
     6 
     7 signature SMT_NORMALIZE =
     8 sig
     9   val drop_fact_warning: Proof.context -> thm -> unit
    10   val atomize_conv: Proof.context -> conv
    11 
    12   val special_quant_table: (string * thm) list
    13   val case_bool_entry: string * thm
    14   val abs_min_max_table: (string * thm) list
    15 
    16   type extra_norm = Proof.context -> thm list * thm list -> thm list * thm list
    17   val add_extra_norm: SMT_Util.class * extra_norm -> Context.generic -> Context.generic
    18   val normalize: Proof.context -> thm list -> (int * thm) list
    19 end;
    20 
    21 structure SMT_Normalize: SMT_NORMALIZE =
    22 struct
    23 
    24 fun drop_fact_warning ctxt =
    25   SMT_Config.verbose_msg ctxt (prefix "Warning: dropping assumption: " o
    26     Display.string_of_thm ctxt)
    27 
    28 
    29 (* general theorem normalizations *)
    30 
    31 (** instantiate elimination rules **)
    32 
    33 local
    34   val (cpfalse, cfalse) = `SMT_Util.mk_cprop (Thm.cterm_of @{context} @{const False})
    35 
    36   fun inst f ct thm =
    37     let val cv = f (Drule.strip_imp_concl (Thm.cprop_of thm))
    38     in Thm.instantiate ([], [(cv, ct)]) thm end
    39 in
    40 
    41 fun instantiate_elim thm =
    42   (case Thm.concl_of thm of
    43     @{const Trueprop} $ Var (_, @{typ bool}) => inst Thm.dest_arg cfalse thm
    44   | Var _ => inst I cpfalse thm
    45   | _ => thm)
    46 
    47 end
    48 
    49 
    50 (** normalize definitions **)
    51 
    52 fun norm_def thm =
    53   (case Thm.prop_of thm of
    54     @{const Trueprop} $ (Const (@{const_name HOL.eq}, _) $ _ $ Abs _) =>
    55       norm_def (thm RS @{thm fun_cong})
    56   | Const (@{const_name Pure.eq}, _) $ _ $ Abs _ => norm_def (thm RS @{thm meta_eq_to_obj_eq})
    57   | _ => thm)
    58 
    59 
    60 (** atomization **)
    61 
    62 fun atomize_conv ctxt ct =
    63   (case Thm.term_of ct of
    64     @{const Pure.imp} $ _ $ _ =>
    65       Conv.binop_conv (atomize_conv ctxt) then_conv Conv.rewr_conv @{thm atomize_imp}
    66   | Const (@{const_name Pure.eq}, _) $ _ $ _ =>
    67       Conv.binop_conv (atomize_conv ctxt) then_conv Conv.rewr_conv @{thm atomize_eq}
    68   | Const (@{const_name Pure.all}, _) $ Abs _ =>
    69       Conv.binder_conv (atomize_conv o snd) ctxt then_conv Conv.rewr_conv @{thm atomize_all}
    70   | _ => Conv.all_conv) ct
    71 
    72 val setup_atomize =
    73   fold SMT_Builtin.add_builtin_fun_ext'' [@{const_name Pure.imp}, @{const_name Pure.eq},
    74     @{const_name Pure.all}, @{const_name Trueprop}]
    75 
    76 
    77 (** unfold special quantifiers **)
    78 
    79 val special_quant_table = [
    80   (@{const_name Ex1}, @{thm Ex1_def_raw}),
    81   (@{const_name Ball}, @{thm Ball_def_raw}),
    82   (@{const_name Bex}, @{thm Bex_def_raw})]
    83 
    84 local
    85   fun special_quant (Const (n, _)) = AList.lookup (op =) special_quant_table n
    86     | special_quant _ = NONE
    87 
    88   fun special_quant_conv _ ct =
    89     (case special_quant (Thm.term_of ct) of
    90       SOME thm => Conv.rewr_conv thm
    91     | NONE => Conv.all_conv) ct
    92 in
    93 
    94 fun unfold_special_quants_conv ctxt =
    95   SMT_Util.if_exists_conv (is_some o special_quant) (Conv.top_conv special_quant_conv ctxt)
    96 
    97 val setup_unfolded_quants = fold (SMT_Builtin.add_builtin_fun_ext'' o fst) special_quant_table
    98 
    99 end
   100 
   101 
   102 (** trigger inference **)
   103 
   104 local
   105   (*** check trigger syntax ***)
   106 
   107   fun dest_trigger (Const (@{const_name pat}, _) $ _) = SOME true
   108     | dest_trigger (Const (@{const_name nopat}, _) $ _) = SOME false
   109     | dest_trigger _ = NONE
   110 
   111   fun eq_list [] = false
   112     | eq_list (b :: bs) = forall (equal b) bs
   113 
   114   fun proper_trigger t =
   115     t
   116     |> these o try SMT_Util.dest_symb_list
   117     |> map (map_filter dest_trigger o these o try SMT_Util.dest_symb_list)
   118     |> (fn [] => false | bss => forall eq_list bss)
   119 
   120   fun proper_quant inside f t =
   121     (case t of
   122       Const (@{const_name All}, _) $ Abs (_, _, u) => proper_quant true f u
   123     | Const (@{const_name Ex}, _) $ Abs (_, _, u) => proper_quant true f u
   124     | @{const trigger} $ p $ u =>
   125         (if inside then f p else false) andalso proper_quant false f u
   126     | Abs (_, _, u) => proper_quant false f u
   127     | u1 $ u2 => proper_quant false f u1 andalso proper_quant false f u2
   128     | _ => true)
   129 
   130   fun check_trigger_error ctxt t =
   131     error ("SMT triggers must only occur under quantifier and multipatterns " ^
   132       "must have the same kind: " ^ Syntax.string_of_term ctxt t)
   133 
   134   fun check_trigger_conv ctxt ct =
   135     if proper_quant false proper_trigger (SMT_Util.term_of ct) then Conv.all_conv ct
   136     else check_trigger_error ctxt (Thm.term_of ct)
   137 
   138 
   139   (*** infer simple triggers ***)
   140 
   141   fun dest_cond_eq ct =
   142     (case Thm.term_of ct of
   143       Const (@{const_name HOL.eq}, _) $ _ $ _ => Thm.dest_binop ct
   144     | @{const HOL.implies} $ _ $ _ => dest_cond_eq (Thm.dest_arg ct)
   145     | _ => raise CTERM ("no equation", [ct]))
   146 
   147   fun get_constrs thy (Type (n, _)) = these (BNF_LFP_Compat.get_constrs thy n)
   148     | get_constrs _ _ = []
   149 
   150   fun is_constr thy (n, T) =
   151     let fun match (m, U) = m = n andalso Sign.typ_instance thy (T, U)
   152     in can (the o find_first match o get_constrs thy o Term.body_type) T end
   153 
   154   fun is_constr_pat thy t =
   155     (case Term.strip_comb t of
   156       (Free _, []) => true
   157     | (Const c, ts) => is_constr thy c andalso forall (is_constr_pat thy) ts
   158     | _ => false)
   159 
   160   fun is_simp_lhs ctxt t =
   161     (case Term.strip_comb t of
   162       (Const c, ts as _ :: _) =>
   163         not (SMT_Builtin.is_builtin_fun_ext ctxt c ts) andalso
   164         forall (is_constr_pat (Proof_Context.theory_of ctxt)) ts
   165     | _ => false)
   166 
   167   fun has_all_vars vs t =
   168     subset (op aconv) (vs, map Free (Term.add_frees t []))
   169 
   170   fun minimal_pats vs ct =
   171     if has_all_vars vs (Thm.term_of ct) then
   172       (case Thm.term_of ct of
   173         _ $ _ =>
   174           (case apply2 (minimal_pats vs) (Thm.dest_comb ct) of
   175             ([], []) => [[ct]]
   176           | (ctss, ctss') => union (eq_set (op aconvc)) ctss ctss')
   177       | _ => [])
   178     else []
   179 
   180   fun proper_mpat _ _ _ [] = false
   181     | proper_mpat thy gen u cts =
   182         let
   183           val tps = (op ~~) (`gen (map Thm.term_of cts))
   184           fun some_match u = tps |> exists (fn (t', t) =>
   185             Pattern.matches thy (t', u) andalso not (t aconv u))
   186         in not (Term.exists_subterm some_match u) end
   187 
   188   val pat = SMT_Util.mk_const_pat @{theory} @{const_name pat} SMT_Util.destT1
   189   fun mk_pat ct = Thm.apply (SMT_Util.instT' ct pat) ct
   190 
   191   fun mk_clist T =
   192     apply2 (Thm.cterm_of @{context}) (SMT_Util.symb_cons_const T, SMT_Util.symb_nil_const T)
   193   fun mk_list (ccons, cnil) f cts = fold_rev (Thm.mk_binop ccons o f) cts cnil
   194   val mk_pat_list = mk_list (mk_clist @{typ pattern})
   195   val mk_mpat_list = mk_list (mk_clist @{typ "pattern symb_list"})
   196   fun mk_trigger ctss = mk_mpat_list (mk_pat_list mk_pat) ctss
   197 
   198   val trigger_eq = mk_meta_eq @{lemma "p = trigger t p" by (simp add: trigger_def)}
   199 
   200   fun insert_trigger_conv [] ct = Conv.all_conv ct
   201     | insert_trigger_conv ctss ct =
   202         let val (ctr, cp) = Thm.dest_binop (Thm.rhs_of trigger_eq) ||> rpair ct
   203         in Thm.instantiate ([], [cp, (ctr, mk_trigger ctss)]) trigger_eq end
   204 
   205   fun infer_trigger_eq_conv outer_ctxt (ctxt, cvs) ct =
   206     let
   207       val (lhs, rhs) = dest_cond_eq ct
   208 
   209       val vs = map Thm.term_of cvs
   210       val thy = Proof_Context.theory_of ctxt
   211 
   212       fun get_mpats ct =
   213         if is_simp_lhs ctxt (Thm.term_of ct) then minimal_pats vs ct
   214         else []
   215       val gen = Variable.export_terms ctxt outer_ctxt
   216       val filter_mpats = filter (proper_mpat thy gen (Thm.term_of rhs))
   217 
   218     in insert_trigger_conv (filter_mpats (get_mpats lhs)) ct end
   219 
   220   fun has_trigger (@{const trigger} $ _ $ _) = true
   221     | has_trigger _ = false
   222 
   223   fun try_trigger_conv cv ct =
   224     if SMT_Util.under_quant has_trigger (SMT_Util.term_of ct) then Conv.all_conv ct
   225     else Conv.try_conv cv ct
   226 
   227   fun infer_trigger_conv ctxt =
   228     if Config.get ctxt SMT_Config.infer_triggers then
   229       try_trigger_conv (SMT_Util.under_quant_conv (infer_trigger_eq_conv ctxt) ctxt)
   230     else Conv.all_conv
   231 in
   232 
   233 fun trigger_conv ctxt =
   234   SMT_Util.prop_conv (check_trigger_conv ctxt then_conv infer_trigger_conv ctxt)
   235 
   236 val setup_trigger =
   237   fold SMT_Builtin.add_builtin_fun_ext''
   238     [@{const_name pat}, @{const_name nopat}, @{const_name trigger}]
   239 
   240 end
   241 
   242 
   243 (** combined general normalizations **)
   244 
   245 fun gen_normalize1_conv ctxt =
   246   atomize_conv ctxt then_conv
   247   unfold_special_quants_conv ctxt then_conv
   248   Thm.beta_conversion true then_conv
   249   trigger_conv ctxt
   250 
   251 fun gen_normalize1 ctxt =
   252   instantiate_elim #>
   253   norm_def #>
   254   Conv.fconv_rule (Thm.beta_conversion true then_conv Thm.eta_conversion) #>
   255   Drule.forall_intr_vars #>
   256   Conv.fconv_rule (gen_normalize1_conv ctxt) #>
   257   (* Z3 4.3.1 silently normalizes "P --> Q --> R" to "P & Q --> R" *)
   258   Raw_Simplifier.rewrite_rule ctxt @{thms HOL.imp_conjL[symmetric, THEN eq_reflection]}
   259 
   260 fun gen_norm1_safe ctxt (i, thm) =
   261   (case try (gen_normalize1 ctxt) thm of
   262     SOME thm' => SOME (i, thm')
   263   | NONE => (drop_fact_warning ctxt thm; NONE))
   264 
   265 fun gen_normalize ctxt iwthms = map_filter (gen_norm1_safe ctxt) iwthms
   266 
   267 
   268 (* unfolding of definitions and theory-specific rewritings *)
   269 
   270 fun expand_head_conv cv ct =
   271   (case Thm.term_of ct of
   272     _ $ _ =>
   273       Conv.fun_conv (expand_head_conv cv) then_conv
   274       Conv.try_conv (Thm.beta_conversion false)
   275   | _ => cv) ct
   276 
   277 
   278 (** rewrite bool case expressions as if expressions **)
   279 
   280 val case_bool_entry = (@{const_name "bool.case_bool"}, @{thm case_bool_if})
   281 
   282 local
   283   fun is_case_bool (Const (@{const_name "bool.case_bool"}, _)) = true
   284     | is_case_bool _ = false
   285 
   286   fun unfold_conv _ =
   287     SMT_Util.if_true_conv (is_case_bool o Term.head_of)
   288       (expand_head_conv (Conv.rewr_conv @{thm case_bool_if}))
   289 in
   290 
   291 fun rewrite_case_bool_conv ctxt =
   292   SMT_Util.if_exists_conv is_case_bool (Conv.top_conv unfold_conv ctxt)
   293 
   294 val setup_case_bool = SMT_Builtin.add_builtin_fun_ext'' @{const_name "bool.case_bool"}
   295 
   296 end
   297 
   298 
   299 (** unfold abs, min and max **)
   300 
   301 val abs_min_max_table = [
   302   (@{const_name min}, @{thm min_def_raw}),
   303   (@{const_name max}, @{thm max_def_raw}),
   304   (@{const_name abs}, @{thm abs_if_raw})]
   305 
   306 local
   307   fun abs_min_max ctxt (Const (n, Type (@{type_name fun}, [T, _]))) =
   308         (case AList.lookup (op =) abs_min_max_table n of
   309           NONE => NONE
   310         | SOME thm => if SMT_Builtin.is_builtin_typ_ext ctxt T then SOME thm else NONE)
   311     | abs_min_max _ _ = NONE
   312 
   313   fun unfold_amm_conv ctxt ct =
   314     (case abs_min_max ctxt (Term.head_of (Thm.term_of ct)) of
   315       SOME thm => expand_head_conv (Conv.rewr_conv thm)
   316     | NONE => Conv.all_conv) ct
   317 in
   318 
   319 fun unfold_abs_min_max_conv ctxt =
   320   SMT_Util.if_exists_conv (is_some o abs_min_max ctxt) (Conv.top_conv unfold_amm_conv ctxt)
   321 
   322 val setup_abs_min_max = fold (SMT_Builtin.add_builtin_fun_ext'' o fst) abs_min_max_table
   323 
   324 end
   325 
   326 
   327 (** normalize numerals **)
   328 
   329 local
   330   (*
   331     rewrite Numeral1 into 1
   332     rewrite - 0 into 0
   333   *)
   334 
   335   fun is_irregular_number (Const (@{const_name numeral}, _) $ Const (@{const_name num.One}, _)) =
   336         true
   337     | is_irregular_number (Const (@{const_name uminus}, _) $ Const (@{const_name Groups.zero}, _)) =
   338         true
   339     | is_irregular_number _ = false
   340 
   341   fun is_strange_number ctxt t = is_irregular_number t andalso SMT_Builtin.is_builtin_num ctxt t
   342 
   343   val proper_num_ss =
   344     simpset_of (put_simpset HOL_ss @{context} addsimps @{thms Num.numeral_One minus_zero})
   345 
   346   fun norm_num_conv ctxt =
   347     SMT_Util.if_conv (is_strange_number ctxt) (Simplifier.rewrite (put_simpset proper_num_ss ctxt))
   348       Conv.no_conv
   349 in
   350 
   351 fun normalize_numerals_conv ctxt =
   352   SMT_Util.if_exists_conv (is_strange_number ctxt) (Conv.top_sweep_conv norm_num_conv ctxt)
   353 
   354 end
   355 
   356 
   357 (** combined unfoldings and rewritings **)
   358 
   359 fun unfold_conv ctxt =
   360   rewrite_case_bool_conv ctxt then_conv
   361   unfold_abs_min_max_conv ctxt then_conv
   362   Thm.beta_conversion true
   363 
   364 fun unfold_polymorph ctxt = map (apsnd (Conv.fconv_rule (unfold_conv ctxt)))
   365 fun unfold_monomorph ctxt = map (apsnd (Conv.fconv_rule (normalize_numerals_conv ctxt)))
   366 
   367 
   368 (* overall normalization *)
   369 
   370 fun burrow_ids f ithms =
   371   let
   372     val (is, thms) = split_list ithms
   373     val (thms', extra_thms) = f thms
   374   in (is ~~ thms') @ map (pair ~1) extra_thms end
   375 
   376 type extra_norm = Proof.context -> thm list * thm list -> thm list * thm list
   377 
   378 structure Extra_Norms = Generic_Data
   379 (
   380   type T = extra_norm SMT_Util.dict
   381   val empty = []
   382   val extend = I
   383   fun merge data = SMT_Util.dict_merge fst data
   384 )
   385 
   386 fun add_extra_norm (cs, norm) = Extra_Norms.map (SMT_Util.dict_update (cs, norm))
   387 
   388 fun apply_extra_norms ctxt ithms =
   389   let
   390     val cs = SMT_Config.solver_class_of ctxt
   391     val es = SMT_Util.dict_lookup (Extra_Norms.get (Context.Proof ctxt)) cs
   392   in burrow_ids (fold (fn e => e ctxt) es o rpair []) ithms end
   393 
   394 local
   395   val ignored = member (op =) [@{const_name All}, @{const_name Ex},
   396     @{const_name Let}, @{const_name If}, @{const_name HOL.eq}]
   397 
   398   val schematic_consts_of =
   399     let
   400       fun collect (@{const trigger} $ p $ t) = collect_trigger p #> collect t
   401         | collect (t $ u) = collect t #> collect u
   402         | collect (Abs (_, _, t)) = collect t
   403         | collect (t as Const (n, _)) =
   404             if not (ignored n) then Monomorph.add_schematic_consts_of t else I
   405         | collect _ = I
   406       and collect_trigger t =
   407         let val dest = these o try SMT_Util.dest_symb_list
   408         in fold (fold collect_pat o dest) (dest t) end
   409       and collect_pat (Const (@{const_name pat}, _) $ t) = collect t
   410         | collect_pat (Const (@{const_name nopat}, _) $ t) = collect t
   411         | collect_pat _ = I
   412     in (fn t => collect t Symtab.empty) end
   413 in
   414 
   415 fun monomorph ctxt xthms =
   416   let val (xs, thms) = split_list xthms
   417   in
   418     map (pair 1) thms
   419     |> Monomorph.monomorph schematic_consts_of ctxt
   420     |> maps (uncurry (map o pair)) o map2 pair xs o map (map snd)
   421   end
   422 
   423 end
   424 
   425 fun normalize ctxt wthms =
   426   wthms
   427   |> map_index I
   428   |> gen_normalize ctxt
   429   |> unfold_polymorph ctxt
   430   |> monomorph ctxt
   431   |> unfold_monomorph ctxt
   432   |> apply_extra_norms ctxt
   433 
   434 val _ = Theory.setup (Context.theory_map (
   435   setup_atomize #>
   436   setup_unfolded_quants #>
   437   setup_trigger #>
   438   setup_case_bool #>
   439   setup_abs_min_max))
   440 
   441 end;