src/HOL/Tools/SMT/smt_normalize.ML
author wenzelm
Sun Jul 05 15:02:30 2015 +0200 (2015-07-05)
changeset 60642 48dd1cefb4ae
parent 59632 5980e75a204e
child 61033 fd7fe96ca7b9
permissions -rw-r--r--
simplified Thm.instantiate and derivatives: the LHS refers to non-certified variables -- this merely serves as index into already certified structures (or is ignored);
     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 ([], [(dest_Var (Thm.term_of 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
   203           val (ctr, cp) = Thm.dest_binop (Thm.rhs_of trigger_eq) ||> rpair ct
   204           val inst = map (apfst (dest_Var o Thm.term_of)) [cp, (ctr, mk_trigger ctss)]
   205         in Thm.instantiate ([], inst) trigger_eq end
   206 
   207   fun infer_trigger_eq_conv outer_ctxt (ctxt, cvs) ct =
   208     let
   209       val (lhs, rhs) = dest_cond_eq ct
   210 
   211       val vs = map Thm.term_of cvs
   212       val thy = Proof_Context.theory_of ctxt
   213 
   214       fun get_mpats ct =
   215         if is_simp_lhs ctxt (Thm.term_of ct) then minimal_pats vs ct
   216         else []
   217       val gen = Variable.export_terms ctxt outer_ctxt
   218       val filter_mpats = filter (proper_mpat thy gen (Thm.term_of rhs))
   219 
   220     in insert_trigger_conv (filter_mpats (get_mpats lhs)) ct end
   221 
   222   fun has_trigger (@{const trigger} $ _ $ _) = true
   223     | has_trigger _ = false
   224 
   225   fun try_trigger_conv cv ct =
   226     if SMT_Util.under_quant has_trigger (SMT_Util.term_of ct) then Conv.all_conv ct
   227     else Conv.try_conv cv ct
   228 
   229   fun infer_trigger_conv ctxt =
   230     if Config.get ctxt SMT_Config.infer_triggers then
   231       try_trigger_conv (SMT_Util.under_quant_conv (infer_trigger_eq_conv ctxt) ctxt)
   232     else Conv.all_conv
   233 in
   234 
   235 fun trigger_conv ctxt =
   236   SMT_Util.prop_conv (check_trigger_conv ctxt then_conv infer_trigger_conv ctxt)
   237 
   238 val setup_trigger =
   239   fold SMT_Builtin.add_builtin_fun_ext''
   240     [@{const_name pat}, @{const_name nopat}, @{const_name trigger}]
   241 
   242 end
   243 
   244 
   245 (** combined general normalizations **)
   246 
   247 fun gen_normalize1_conv ctxt =
   248   atomize_conv ctxt then_conv
   249   unfold_special_quants_conv ctxt then_conv
   250   Thm.beta_conversion true then_conv
   251   trigger_conv ctxt
   252 
   253 fun gen_normalize1 ctxt =
   254   instantiate_elim #>
   255   norm_def #>
   256   Conv.fconv_rule (Thm.beta_conversion true then_conv Thm.eta_conversion) #>
   257   Drule.forall_intr_vars #>
   258   Conv.fconv_rule (gen_normalize1_conv ctxt) #>
   259   (* Z3 4.3.1 silently normalizes "P --> Q --> R" to "P & Q --> R" *)
   260   Raw_Simplifier.rewrite_rule ctxt @{thms HOL.imp_conjL[symmetric, THEN eq_reflection]}
   261 
   262 fun gen_norm1_safe ctxt (i, thm) =
   263   (case try (gen_normalize1 ctxt) thm of
   264     SOME thm' => SOME (i, thm')
   265   | NONE => (drop_fact_warning ctxt thm; NONE))
   266 
   267 fun gen_normalize ctxt iwthms = map_filter (gen_norm1_safe ctxt) iwthms
   268 
   269 
   270 (* unfolding of definitions and theory-specific rewritings *)
   271 
   272 fun expand_head_conv cv ct =
   273   (case Thm.term_of ct of
   274     _ $ _ =>
   275       Conv.fun_conv (expand_head_conv cv) then_conv
   276       Conv.try_conv (Thm.beta_conversion false)
   277   | _ => cv) ct
   278 
   279 
   280 (** rewrite bool case expressions as if expressions **)
   281 
   282 val case_bool_entry = (@{const_name "bool.case_bool"}, @{thm case_bool_if})
   283 
   284 local
   285   fun is_case_bool (Const (@{const_name "bool.case_bool"}, _)) = true
   286     | is_case_bool _ = false
   287 
   288   fun unfold_conv _ =
   289     SMT_Util.if_true_conv (is_case_bool o Term.head_of)
   290       (expand_head_conv (Conv.rewr_conv @{thm case_bool_if}))
   291 in
   292 
   293 fun rewrite_case_bool_conv ctxt =
   294   SMT_Util.if_exists_conv is_case_bool (Conv.top_conv unfold_conv ctxt)
   295 
   296 val setup_case_bool = SMT_Builtin.add_builtin_fun_ext'' @{const_name "bool.case_bool"}
   297 
   298 end
   299 
   300 
   301 (** unfold abs, min and max **)
   302 
   303 val abs_min_max_table = [
   304   (@{const_name min}, @{thm min_def_raw}),
   305   (@{const_name max}, @{thm max_def_raw}),
   306   (@{const_name abs}, @{thm abs_if_raw})]
   307 
   308 local
   309   fun abs_min_max ctxt (Const (n, Type (@{type_name fun}, [T, _]))) =
   310         (case AList.lookup (op =) abs_min_max_table n of
   311           NONE => NONE
   312         | SOME thm => if SMT_Builtin.is_builtin_typ_ext ctxt T then SOME thm else NONE)
   313     | abs_min_max _ _ = NONE
   314 
   315   fun unfold_amm_conv ctxt ct =
   316     (case abs_min_max ctxt (Term.head_of (Thm.term_of ct)) of
   317       SOME thm => expand_head_conv (Conv.rewr_conv thm)
   318     | NONE => Conv.all_conv) ct
   319 in
   320 
   321 fun unfold_abs_min_max_conv ctxt =
   322   SMT_Util.if_exists_conv (is_some o abs_min_max ctxt) (Conv.top_conv unfold_amm_conv ctxt)
   323 
   324 val setup_abs_min_max = fold (SMT_Builtin.add_builtin_fun_ext'' o fst) abs_min_max_table
   325 
   326 end
   327 
   328 
   329 (** normalize numerals **)
   330 
   331 local
   332   (*
   333     rewrite Numeral1 into 1
   334     rewrite - 0 into 0
   335   *)
   336 
   337   fun is_irregular_number (Const (@{const_name numeral}, _) $ Const (@{const_name num.One}, _)) =
   338         true
   339     | is_irregular_number (Const (@{const_name uminus}, _) $ Const (@{const_name Groups.zero}, _)) =
   340         true
   341     | is_irregular_number _ = false
   342 
   343   fun is_strange_number ctxt t = is_irregular_number t andalso SMT_Builtin.is_builtin_num ctxt t
   344 
   345   val proper_num_ss =
   346     simpset_of (put_simpset HOL_ss @{context} addsimps @{thms Num.numeral_One minus_zero})
   347 
   348   fun norm_num_conv ctxt =
   349     SMT_Util.if_conv (is_strange_number ctxt) (Simplifier.rewrite (put_simpset proper_num_ss ctxt))
   350       Conv.no_conv
   351 in
   352 
   353 fun normalize_numerals_conv ctxt =
   354   SMT_Util.if_exists_conv (is_strange_number ctxt) (Conv.top_sweep_conv norm_num_conv ctxt)
   355 
   356 end
   357 
   358 
   359 (** combined unfoldings and rewritings **)
   360 
   361 fun unfold_conv ctxt =
   362   rewrite_case_bool_conv ctxt then_conv
   363   unfold_abs_min_max_conv ctxt then_conv
   364   Thm.beta_conversion true
   365 
   366 fun unfold_polymorph ctxt = map (apsnd (Conv.fconv_rule (unfold_conv ctxt)))
   367 fun unfold_monomorph ctxt = map (apsnd (Conv.fconv_rule (normalize_numerals_conv ctxt)))
   368 
   369 
   370 (* overall normalization *)
   371 
   372 fun burrow_ids f ithms =
   373   let
   374     val (is, thms) = split_list ithms
   375     val (thms', extra_thms) = f thms
   376   in (is ~~ thms') @ map (pair ~1) extra_thms end
   377 
   378 type extra_norm = Proof.context -> thm list * thm list -> thm list * thm list
   379 
   380 structure Extra_Norms = Generic_Data
   381 (
   382   type T = extra_norm SMT_Util.dict
   383   val empty = []
   384   val extend = I
   385   fun merge data = SMT_Util.dict_merge fst data
   386 )
   387 
   388 fun add_extra_norm (cs, norm) = Extra_Norms.map (SMT_Util.dict_update (cs, norm))
   389 
   390 fun apply_extra_norms ctxt ithms =
   391   let
   392     val cs = SMT_Config.solver_class_of ctxt
   393     val es = SMT_Util.dict_lookup (Extra_Norms.get (Context.Proof ctxt)) cs
   394   in burrow_ids (fold (fn e => e ctxt) es o rpair []) ithms end
   395 
   396 local
   397   val ignored = member (op =) [@{const_name All}, @{const_name Ex},
   398     @{const_name Let}, @{const_name If}, @{const_name HOL.eq}]
   399 
   400   val schematic_consts_of =
   401     let
   402       fun collect (@{const trigger} $ p $ t) = collect_trigger p #> collect t
   403         | collect (t $ u) = collect t #> collect u
   404         | collect (Abs (_, _, t)) = collect t
   405         | collect (t as Const (n, _)) =
   406             if not (ignored n) then Monomorph.add_schematic_consts_of t else I
   407         | collect _ = I
   408       and collect_trigger t =
   409         let val dest = these o try SMT_Util.dest_symb_list
   410         in fold (fold collect_pat o dest) (dest t) end
   411       and collect_pat (Const (@{const_name pat}, _) $ t) = collect t
   412         | collect_pat (Const (@{const_name nopat}, _) $ t) = collect t
   413         | collect_pat _ = I
   414     in (fn t => collect t Symtab.empty) end
   415 in
   416 
   417 fun monomorph ctxt xthms =
   418   let val (xs, thms) = split_list xthms
   419   in
   420     map (pair 1) thms
   421     |> Monomorph.monomorph schematic_consts_of ctxt
   422     |> maps (uncurry (map o pair)) o map2 pair xs o map (map snd)
   423   end
   424 
   425 end
   426 
   427 fun normalize ctxt wthms =
   428   wthms
   429   |> map_index I
   430   |> gen_normalize ctxt
   431   |> unfold_polymorph ctxt
   432   |> monomorph ctxt
   433   |> unfold_monomorph ctxt
   434   |> apply_extra_norms ctxt
   435 
   436 val _ = Theory.setup (Context.theory_map (
   437   setup_atomize #>
   438   setup_unfolded_quants #>
   439   setup_trigger #>
   440   setup_case_bool #>
   441   setup_abs_min_max))
   442 
   443 end;