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