src/HOL/Tools/SMT/smt_translate.ML
author boehmes
Mon Nov 22 15:45:43 2010 +0100 (2010-11-22)
changeset 40663 e080c9e68752
parent 40579 98ebd2300823
child 40664 e023788a91a1
permissions -rw-r--r--
share and use more utility functions;
slightly reduced complexity for Z3 proof rule 'rewrite'
     1 (*  Title:      HOL/Tools/SMT/smt_translate.ML
     2     Author:     Sascha Boehme, TU Muenchen
     3 
     4 Translate theorems into an SMT intermediate format and serialize them.
     5 *)
     6 
     7 signature SMT_TRANSLATE =
     8 sig
     9   (* intermediate term structure *)
    10   datatype squant = SForall | SExists
    11   datatype 'a spattern = SPat of 'a list | SNoPat of 'a list
    12   datatype sterm =
    13     SVar of int |
    14     SApp of string * sterm list |
    15     SLet of string * sterm * sterm |
    16     SQua of squant * string list * sterm spattern list * sterm
    17 
    18   (* configuration options *)
    19   type prefixes = {sort_prefix: string, func_prefix: string}
    20   type header = Proof.context -> term list -> string list
    21   type strict = {
    22     is_builtin_conn: string * typ -> bool,
    23     is_builtin_pred: Proof.context -> string * typ -> bool,
    24     is_builtin_distinct: bool}
    25   type builtins = {
    26     builtin_typ: Proof.context -> typ -> string option,
    27     builtin_num: Proof.context -> typ -> int -> string option,
    28     builtin_fun: Proof.context -> string * typ -> term list ->
    29       (string * term list) option,
    30     has_datatypes: bool }
    31   type sign = {
    32     header: string list,
    33     sorts: string list,
    34     dtyps: (string * (string * (string * string) list) list) list list,
    35     funcs: (string * (string list * string)) list }
    36   type config = {
    37     prefixes: prefixes,
    38     header: header,
    39     strict: strict option,
    40     builtins: builtins,
    41     serialize: string list -> sign -> sterm list -> string }
    42   type recon = {
    43     typs: typ Symtab.table,
    44     terms: term Symtab.table,
    45     unfolds: thm list,
    46     assms: (int * thm) list }
    47 
    48   val translate: config -> Proof.context -> string list -> (int * thm) list ->
    49     string * recon
    50 end
    51 
    52 structure SMT_Translate: SMT_TRANSLATE =
    53 struct
    54 
    55 structure U = SMT_Utils
    56 
    57 
    58 (* intermediate term structure *)
    59 
    60 datatype squant = SForall | SExists
    61 
    62 datatype 'a spattern = SPat of 'a list | SNoPat of 'a list
    63 
    64 datatype sterm =
    65   SVar of int |
    66   SApp of string * sterm list |
    67   SLet of string * sterm * sterm |
    68   SQua of squant * string list * sterm spattern list * sterm
    69 
    70 
    71 
    72 (* configuration options *)
    73 
    74 type prefixes = {sort_prefix: string, func_prefix: string}
    75 
    76 type header = Proof.context -> term list -> string list
    77 
    78 type strict = {
    79   is_builtin_conn: string * typ -> bool,
    80   is_builtin_pred: Proof.context -> string * typ -> bool,
    81   is_builtin_distinct: bool}
    82 
    83 type builtins = {
    84   builtin_typ: Proof.context -> typ -> string option,
    85   builtin_num: Proof.context -> typ -> int -> string option,
    86   builtin_fun: Proof.context -> string * typ -> term list ->
    87     (string * term list) option,
    88   has_datatypes: bool }
    89 
    90 type sign = {
    91   header: string list,
    92   sorts: string list,
    93   dtyps: (string * (string * (string * string) list) list) list list,
    94   funcs: (string * (string list * string)) list }
    95 
    96 type config = {
    97   prefixes: prefixes,
    98   header: header,
    99   strict: strict option,
   100   builtins: builtins,
   101   serialize: string list -> sign -> sterm list -> string }
   102 
   103 type recon = {
   104   typs: typ Symtab.table,
   105   terms: term Symtab.table,
   106   unfolds: thm list,
   107   assms: (int * thm) list }
   108 
   109 
   110 
   111 (* utility functions *)
   112 
   113 val quantifier = (fn
   114     @{const_name All} => SOME SForall
   115   | @{const_name Ex} => SOME SExists
   116   | _ => NONE)
   117 
   118 fun group_quant qname Ts (t as Const (q, _) $ Abs (_, T, u)) =
   119       if q = qname then group_quant qname (T :: Ts) u else (Ts, t)
   120   | group_quant _ Ts t = (Ts, t)
   121 
   122 fun dest_pat (Const (@{const_name pat}, _) $ t) = (t, true)
   123   | dest_pat (Const (@{const_name nopat}, _) $ t) = (t, false)
   124   | dest_pat t = raise TERM ("dest_pat", [t])
   125 
   126 fun dest_pats [] = I
   127   | dest_pats ts =
   128       (case map dest_pat ts |> split_list ||> distinct (op =) of
   129         (ps, [true]) => cons (SPat ps)
   130       | (ps, [false]) => cons (SNoPat ps)
   131       | _ => raise TERM ("dest_pats", ts))
   132 
   133 fun dest_trigger (@{const trigger} $ tl $ t) =
   134       (rev (fold (dest_pats o HOLogic.dest_list) (HOLogic.dest_list tl) []), t)
   135   | dest_trigger t = ([], t)
   136 
   137 fun dest_quant qn T t = quantifier qn |> Option.map (fn q =>
   138   let
   139     val (Ts, u) = group_quant qn [T] t
   140     val (ps, b) = dest_trigger u
   141   in (q, rev Ts, ps, b) end)
   142 
   143 fun fold_map_pat f (SPat ts) = fold_map f ts #>> SPat
   144   | fold_map_pat f (SNoPat ts) = fold_map f ts #>> SNoPat
   145 
   146 fun prop_of thm = HOLogic.dest_Trueprop (Thm.prop_of thm)
   147 
   148 
   149 
   150 (* enforce a strict separation between formulas and terms *)
   151 
   152 val term_eq_rewr = @{lemma "term_eq x y == x = y" by (simp add: term_eq_def)}
   153 
   154 val term_bool = @{lemma "~(term_eq True False)" by (simp add: term_eq_def)}
   155 val term_bool' = Simplifier.rewrite_rule [term_eq_rewr] term_bool
   156 
   157 
   158 val needs_rewrite = Thm.prop_of #> Term.exists_subterm (fn
   159     Const (@{const_name Let}, _) => true
   160   | @{const HOL.eq (bool)} $ _ $ @{const True} => true
   161   | Const (@{const_name If}, _) $ _ $ @{const True} $ @{const False} => true
   162   | _ => false)
   163 
   164 val rewrite_rules = [
   165   Let_def,
   166   @{lemma "P = True == P" by (rule eq_reflection) simp},
   167   @{lemma "if P then True else False == P" by (rule eq_reflection) simp}]
   168 
   169 fun rewrite ctxt = Simplifier.full_rewrite
   170   (Simplifier.context ctxt empty_ss addsimps rewrite_rules)
   171 
   172 fun normalize ctxt thm =
   173   if needs_rewrite thm then Conv.fconv_rule (rewrite ctxt) thm else thm
   174 
   175 val unfold_rules = term_eq_rewr :: rewrite_rules
   176 
   177 
   178 val revert_types =
   179   let
   180     fun revert @{typ prop} = @{typ bool}
   181       | revert (Type (n, Ts)) = Type (n, map revert Ts)
   182       | revert T = T
   183   in Term.map_types revert end
   184 
   185 
   186 fun strictify {is_builtin_conn, is_builtin_pred, is_builtin_distinct} ctxt =
   187   let
   188     fun is_builtin_conn' (@{const_name True}, _) = false
   189       | is_builtin_conn' (@{const_name False}, _) = false
   190       | is_builtin_conn' c = is_builtin_conn c
   191 
   192     val propT = @{typ prop} and boolT = @{typ bool}
   193     val as_propT = (fn @{typ bool} => propT | T => T)
   194     fun mapTs f g = Term.strip_type #> (fn (Ts, T) => map f Ts ---> g T)
   195     fun conn (n, T) = (n, mapTs as_propT as_propT T)
   196     fun pred (n, T) = (n, mapTs I as_propT T)
   197 
   198     val term_eq = @{const HOL.eq (bool)} |> Term.dest_Const |> pred
   199     fun as_term t = Const term_eq $ t $ @{const True}
   200 
   201     val if_term = Const (@{const_name If}, [propT, boolT, boolT] ---> boolT)
   202     fun wrap_in_if t = if_term $ t $ @{const True} $ @{const False}
   203 
   204     fun in_list T f t = HOLogic.mk_list T (map f (HOLogic.dest_list t))
   205 
   206     fun in_term t =
   207       (case Term.strip_comb t of
   208         (c as Const (@{const_name If}, _), [t1, t2, t3]) =>
   209           c $ in_form t1 $ in_term t2 $ in_term t3
   210       | (h as Const c, ts) =>
   211           if is_builtin_conn' (conn c) orelse is_builtin_pred ctxt (pred c)
   212           then wrap_in_if (in_form t)
   213           else Term.list_comb (h, map in_term ts)
   214       | (h as Free _, ts) => Term.list_comb (h, map in_term ts)
   215       | _ => t)
   216 
   217     and in_pat ((c as Const (@{const_name pat}, _)) $ t) = c $ in_term t
   218       | in_pat ((c as Const (@{const_name nopat}, _)) $ t) = c $ in_term t
   219       | in_pat t = raise TERM ("in_pat", [t])
   220 
   221     and in_pats ps =
   222       in_list @{typ "pattern list"} (in_list @{typ pattern} in_pat) ps
   223 
   224     and in_trig ((c as @{const trigger}) $ p $ t) = c $ in_pats p $ in_form t
   225       | in_trig t = in_form t
   226 
   227     and in_form t =
   228       (case Term.strip_comb t of
   229         (q as Const (qn, _), [Abs (n, T, t')]) =>
   230           if is_some (quantifier qn) then q $ Abs (n, T, in_trig t')
   231           else as_term (in_term t)
   232       | (Const (c as (@{const_name SMT.distinct}, T)), [t']) =>
   233           if is_builtin_distinct then Const (pred c) $ in_list T in_term t'
   234           else as_term (in_term t)
   235       | (Const c, ts) =>
   236           if is_builtin_conn (conn c)
   237           then Term.list_comb (Const (conn c), map in_form ts)
   238           else if is_builtin_pred ctxt (pred c)
   239           then Term.list_comb (Const (pred c), map in_term ts)
   240           else as_term (in_term t)
   241       | _ => as_term (in_term t))
   242   in
   243     map (apsnd (normalize ctxt)) #> (fn irules =>
   244     ((unfold_rules, (~1, term_bool') :: irules),
   245      map (in_form o prop_of o snd) ((~1, term_bool) :: irules)))
   246   end
   247 
   248 
   249 
   250 (* translation from Isabelle terms into SMT intermediate terms *)
   251 
   252 val empty_context = (1, Typtab.empty, [], 1, Termtab.empty)
   253 
   254 fun make_sign header (_, typs, dtyps, _, terms) = {
   255   header = header,
   256   sorts = Typtab.fold (fn (_, (n, true)) => cons n | _ => I) typs [],
   257   funcs = Termtab.fold (fn (_, (n, SOME ss)) => cons (n,ss) | _ => I) terms [],
   258   dtyps = rev dtyps }
   259 
   260 fun make_recon (unfolds, assms) (_, typs, _, _, terms) = {
   261   typs = Symtab.make (map (apfst fst o swap) (Typtab.dest typs)),
   262     (*FIXME: don't drop the datatype information! *)
   263   terms = Symtab.make (map (fn (t, (n, _)) => (n, t)) (Termtab.dest terms)),
   264   unfolds = unfolds,
   265   assms = assms }
   266 
   267 fun string_of_index pre i = pre ^ string_of_int i
   268 
   269 fun new_typ sort_prefix proper T (Tidx, typs, dtyps, idx, terms) =
   270   let val s = string_of_index sort_prefix Tidx
   271   in (s, (Tidx+1, Typtab.update (T, (s, proper)) typs, dtyps, idx, terms)) end
   272 
   273 fun lookup_typ (_, typs, _, _, _) = Typtab.lookup typs
   274 
   275 fun fresh_typ T f cx =
   276   (case lookup_typ cx T of
   277     SOME (s, _) => (s, cx)
   278   | NONE => f T cx)
   279 
   280 fun new_fun func_prefix t ss (Tidx, typs, dtyps, idx, terms) =
   281   let
   282     val f = string_of_index func_prefix idx
   283     val terms' = Termtab.update (revert_types t, (f, ss)) terms
   284   in (f, (Tidx, typs, dtyps, idx+1, terms')) end
   285 
   286 fun fresh_fun func_prefix t ss (cx as (_, _, _, _, terms)) =
   287   (case Termtab.lookup terms t of
   288     SOME (f, _) => (f, cx)
   289   | NONE => new_fun func_prefix t ss cx)
   290 
   291 fun mk_type (_, Tfs) (d as Datatype.DtTFree _) = the (AList.lookup (op =) Tfs d)
   292   | mk_type Ts (Datatype.DtType (n, ds)) = Type (n, map (mk_type Ts) ds)
   293   | mk_type (Tds, _) (Datatype.DtRec i) = nth Tds i
   294 
   295 fun mk_selector ctxt Ts T n (i, d) =
   296   (case Datatype_Selectors.lookup_selector ctxt (n, i+1) of
   297     NONE => raise Fail ("missing selector for datatype constructor " ^ quote n)
   298   | SOME m => mk_type Ts d |> (fn U => (Const (m, T --> U), U)))
   299 
   300 fun mk_constructor ctxt Ts T (n, args) =
   301   let val (sels, Us) = split_list (map_index (mk_selector ctxt Ts T n) args)
   302   in (Const (n, Us ---> T), sels) end
   303 
   304 fun lookup_datatype ctxt n Ts =
   305   if member (op =) [@{type_name bool}, @{type_name nat}] n then NONE
   306   else
   307     Datatype.get_info (ProofContext.theory_of ctxt) n
   308     |> Option.map (fn {descr, ...} =>
   309          let
   310            val Tds = map (fn (_, (tn, _, _)) => Type (tn, Ts))
   311              (sort (int_ord o pairself fst) descr)
   312            val Tfs = (case hd descr of (_, (_, tfs, _)) => tfs ~~ Ts)
   313          in
   314            descr |> map (fn (i, (_, _, cs)) =>
   315              (nth Tds i, map (mk_constructor ctxt (Tds, Tfs) (nth Tds i)) cs))
   316          end)
   317 
   318 fun relaxed irules = (([], irules), map (prop_of o snd) irules)
   319 
   320 fun with_context header f (ths, ts) =
   321   let val (us, context) = fold_map f ts empty_context
   322   in ((make_sign (header ts) context, us), make_recon ths context) end
   323 
   324 
   325 fun translate {prefixes, strict, header, builtins, serialize} ctxt comments =
   326   let
   327     val {sort_prefix, func_prefix} = prefixes
   328     val {builtin_typ, builtin_num, builtin_fun, has_datatypes} = builtins
   329 
   330     fun transT (T as TFree _) = fresh_typ T (new_typ sort_prefix true)
   331       | transT (T as TVar _) = (fn _ => raise TYPE ("smt_translate", [T], []))
   332       | transT (T as Type (n, Ts)) =
   333           (case builtin_typ ctxt T of
   334             SOME n => pair n
   335           | NONE => fresh_typ T (fn _ => fn cx =>
   336               if not has_datatypes then new_typ sort_prefix true T cx
   337               else
   338                 (case lookup_datatype ctxt n Ts of
   339                   NONE => new_typ sort_prefix true T cx
   340                 | SOME dts =>
   341                     let val cx' = new_dtyps dts cx 
   342                     in (fst (the (lookup_typ cx' T)), cx') end)))
   343 
   344     and new_dtyps dts cx =
   345       let
   346         fun new_decl i t =
   347           let val (Ts, T) = U.dest_funT i (Term.fastype_of t)
   348           in
   349             fold_map transT Ts ##>> transT T ##>>
   350             new_fun func_prefix t NONE #>> swap
   351           end
   352         fun new_dtyp_decl (con, sels) =
   353           new_decl (length sels) con ##>> fold_map (new_decl 1) sels #>>
   354           (fn ((con', _), sels') => (con', map (apsnd snd) sels'))
   355       in
   356         cx
   357         |> fold_map (new_typ sort_prefix false o fst) dts
   358         ||>> fold_map (fold_map new_dtyp_decl o snd) dts
   359         |-> (fn (ss, decls) => fn (Tidx, typs, dtyps, idx, terms) =>
   360               (Tidx, typs, (ss ~~ decls) :: dtyps, idx, terms))
   361       end
   362 
   363     fun app n ts = SApp (n, ts)
   364 
   365     fun trans t =
   366       (case Term.strip_comb t of
   367         (Const (qn, _), [Abs (_, T, t1)]) =>
   368           (case dest_quant qn T t1 of
   369             SOME (q, Ts, ps, b) =>
   370               fold_map transT Ts ##>> fold_map (fold_map_pat trans) ps ##>>
   371               trans b #>> (fn ((Ts', ps'), b') => SQua (q, Ts', ps', b'))
   372           | NONE => raise TERM ("intermediate", [t]))
   373       | (Const (@{const_name Let}, _), [t1, Abs (_, T, t2)]) =>
   374           transT T ##>> trans t1 ##>> trans t2 #>>
   375           (fn ((U, u1), u2) => SLet (U, u1, u2))
   376       | (h as Const (c as (@{const_name SMT.distinct}, T)), [t1]) =>
   377           (case builtin_fun ctxt c (HOLogic.dest_list t1) of
   378             SOME (n, ts) => fold_map trans ts #>> app n
   379           | NONE => transs h T [t1])
   380       | (h as Const (c as (_, T)), ts) =>
   381           (case try HOLogic.dest_number t of
   382             SOME (T, i) =>
   383               (case builtin_num ctxt T i of
   384                 SOME n => pair (SApp (n, []))
   385               | NONE => transs t T [])
   386           | NONE =>
   387               (case builtin_fun ctxt c ts of
   388                 SOME (n, ts') => fold_map trans ts' #>> app n
   389               | NONE => transs h T ts))
   390       | (h as Free (_, T), ts) => transs h T ts
   391       | (Bound i, []) => pair (SVar i)
   392       | _ => raise TERM ("smt_translate", [t]))
   393 
   394     and transs t T ts =
   395       let val (Us, U) = U.dest_funT (length ts) T
   396       in
   397         fold_map transT Us ##>> transT U #-> (fn Up =>
   398         fresh_fun func_prefix t (SOME Up) ##>> fold_map trans ts #>> SApp)
   399       end
   400   in
   401     (case strict of SOME strct => strictify strct ctxt | NONE => relaxed) #>
   402     with_context (header ctxt) trans #>> uncurry (serialize comments)
   403   end
   404 
   405 end