src/HOL/Tools/reification.ML
author haftmann
Fri Oct 10 19:55:32 2014 +0200 (2014-10-10)
changeset 58646 cd63a4b12a33
parent 52288 ca4932dad084
child 59058 a78612c67ec0
permissions -rw-r--r--
specialized specification: avoid trivial instances
haftmann@52286
     1
(*  Title:      HOL/Tools/reification.ML
haftmann@51726
     2
    Author:     Amine Chaieb, TU Muenchen
haftmann@51726
     3
haftmann@51726
     4
A trial for automatical reification.
haftmann@51726
     5
*)
haftmann@51726
     6
haftmann@52286
     7
signature REIFICATION =
haftmann@51726
     8
sig
haftmann@52286
     9
  val conv: Proof.context -> thm list -> conv
haftmann@52286
    10
  val tac: Proof.context -> thm list -> term option -> int -> tactic
haftmann@52286
    11
  val lift_conv: Proof.context -> conv -> term option -> int -> tactic
haftmann@52286
    12
  val dereify: Proof.context -> thm list -> conv
haftmann@51726
    13
end;
haftmann@51726
    14
haftmann@52286
    15
structure Reification : REIFICATION =
haftmann@51726
    16
struct
haftmann@51726
    17
haftmann@52275
    18
fun dest_listT (Type (@{type_name "list"}, [T])) = T;
haftmann@52275
    19
haftmann@51726
    20
val FWD = curry (op OF);
haftmann@51726
    21
haftmann@52275
    22
fun rewrite_with ctxt eqs = Simplifier.rewrite (put_simpset HOL_basic_ss ctxt addsimps eqs);
haftmann@52275
    23
haftmann@52275
    24
val pure_subst = @{lemma "x == y ==> PROP P y ==> PROP P x" by simp}
haftmann@51726
    25
haftmann@52276
    26
fun lift_conv ctxt conv some_t = Subgoal.FOCUS (fn { concl, ... } =>
haftmann@52275
    27
  let
haftmann@52275
    28
    val ct = case some_t
haftmann@52275
    29
     of NONE => Thm.dest_arg concl
haftmann@52275
    30
      | SOME t => Thm.cterm_of (Proof_Context.theory_of ctxt) t
haftmann@52275
    31
    val thm = conv ct;
haftmann@52275
    32
  in
haftmann@52275
    33
    if Thm.is_reflexive thm then no_tac
haftmann@52275
    34
    else ALLGOALS (rtac (pure_subst OF [thm]))
haftmann@52275
    35
  end) ctxt;
haftmann@51726
    36
haftmann@51726
    37
(* Make a congruence rule out of a defining equation for the interpretation
haftmann@51726
    38
haftmann@51726
    39
   th is one defining equation of f,
haftmann@51726
    40
     i.e. th is "f (Cp ?t1 ... ?tn) = P(f ?t1, .., f ?tn)" 
haftmann@51726
    41
   Cp is a constructor pattern and P is a pattern 
haftmann@51726
    42
haftmann@51726
    43
   The result is:
haftmann@51726
    44
     [|?A1 = f ?t1 ; .. ; ?An= f ?tn |] ==> P (?A1, .., ?An) = f (Cp ?t1 .. ?tn)
haftmann@51726
    45
       + the a list of names of the A1 .. An, Those are fresh in the ctxt *)
haftmann@51726
    46
haftmann@51726
    47
fun mk_congeq ctxt fs th =
haftmann@51726
    48
  let
haftmann@51726
    49
    val Const (fN, _) = th |> prop_of |> HOLogic.dest_Trueprop |> HOLogic.dest_eq
haftmann@51726
    50
      |> fst |> strip_comb |> fst;
haftmann@52273
    51
    val cert = Thm.cterm_of (Proof_Context.theory_of ctxt);
haftmann@51726
    52
    val ((_, [th']), ctxt') = Variable.import true [th] ctxt;
haftmann@51726
    53
    val (lhs, rhs) = HOLogic.dest_eq (HOLogic.dest_Trueprop (Thm.prop_of th'));
haftmann@51726
    54
    fun add_fterms (t as t1 $ t2) =
haftmann@51726
    55
          if exists (fn f => Term.could_unify (t |> strip_comb |> fst, f)) fs
haftmann@51726
    56
          then insert (op aconv) t
haftmann@51726
    57
          else add_fterms t1 #> add_fterms t2
haftmann@51726
    58
      | add_fterms (t as Abs _) =
haftmann@51726
    59
          if exists_Const (fn (c, _) => c = fN) t
haftmann@51726
    60
          then K [t]
haftmann@51726
    61
          else K []
haftmann@51726
    62
      | add_fterms _ = I;
haftmann@51726
    63
    val fterms = add_fterms rhs [];
haftmann@51726
    64
    val (xs, ctxt'') = Variable.variant_fixes (replicate (length fterms) "x") ctxt';
haftmann@51726
    65
    val tys = map fastype_of fterms;
haftmann@51726
    66
    val vs = map Free (xs ~~ tys);
haftmann@51726
    67
    val env = fterms ~~ vs; (*FIXME*)
haftmann@51726
    68
    fun replace_fterms (t as t1 $ t2) =
haftmann@51726
    69
        (case AList.lookup (op aconv) env t of
haftmann@51726
    70
            SOME v => v
haftmann@51726
    71
          | NONE => replace_fterms t1 $ replace_fterms t2)
haftmann@51726
    72
      | replace_fterms t =
haftmann@51726
    73
        (case AList.lookup (op aconv) env t of
haftmann@51726
    74
            SOME v => v
haftmann@51726
    75
          | NONE => t);
haftmann@51726
    76
    fun mk_def (Abs (x, xT, t), v) =
haftmann@51726
    77
          HOLogic.mk_Trueprop (HOLogic.all_const xT $ Abs (x, xT, HOLogic.mk_eq (v $ Bound 0, t)))
haftmann@51726
    78
      | mk_def (t, v) = HOLogic.mk_Trueprop (HOLogic.mk_eq (v, t));
haftmann@51726
    79
    fun tryext x =
haftmann@51726
    80
      (x RS @{lemma "(\<forall>x. f x = g x) \<Longrightarrow> f = g" by blast} handle THM _ => x);
haftmann@51726
    81
    val cong =
haftmann@51726
    82
      (Goal.prove ctxt'' [] (map mk_def env)
haftmann@51726
    83
        (HOLogic.mk_Trueprop (HOLogic.mk_eq (lhs, replace_fterms rhs)))
haftmann@51726
    84
        (fn {context, prems, ...} =>
haftmann@51726
    85
          Local_Defs.unfold_tac context (map tryext prems) THEN rtac th' 1)) RS sym;
haftmann@51726
    86
    val (cong' :: vars') =
haftmann@51726
    87
      Variable.export ctxt'' ctxt (cong :: map (Drule.mk_term o cert) vs);
haftmann@51726
    88
    val vs' = map (fst o fst o Term.dest_Var o Thm.term_of o Drule.dest_term) vars';
haftmann@51726
    89
haftmann@51726
    90
  in (vs', cong') end;
haftmann@51726
    91
haftmann@51726
    92
(* congs is a list of pairs (P,th) where th is a theorem for
haftmann@51726
    93
     [| f p1 = A1; ...; f pn = An|] ==> f (C p1 .. pn) = P *)
haftmann@51726
    94
haftmann@51726
    95
fun rearrange congs =
haftmann@51726
    96
  let
haftmann@51726
    97
    fun P (_, th) =
haftmann@51726
    98
      let val @{term "Trueprop"} $ (Const (@{const_name HOL.eq}, _) $ l $ _) = concl_of th
haftmann@51726
    99
      in can dest_Var l end;
haftmann@51726
   100
    val (yes, no) = List.partition P congs;
haftmann@51726
   101
  in no @ yes end;
haftmann@51726
   102
haftmann@52275
   103
fun dereify ctxt eqs =
haftmann@52275
   104
  rewrite_with ctxt (eqs @ @{thms nth_Cons_0 nth_Cons_Suc});
haftmann@52275
   105
haftmann@52288
   106
fun index_of t bds =
haftmann@52288
   107
  let
haftmann@52288
   108
    val tt = HOLogic.listT (fastype_of t);
haftmann@52288
   109
  in
haftmann@52288
   110
    (case AList.lookup Type.could_unify bds tt of
haftmann@52288
   111
        NONE => error "index_of: type not found in environements!"
haftmann@52288
   112
      | SOME (tbs, tats) =>
haftmann@52288
   113
          let
haftmann@52288
   114
            val i = find_index (fn t' => t' = t) tats;
haftmann@52288
   115
            val j = find_index (fn t' => t' = t) tbs;
haftmann@52288
   116
          in
haftmann@52288
   117
            if j = ~1 then
haftmann@52288
   118
              if i = ~1
haftmann@52288
   119
              then (length tbs + length tats, AList.update Type.could_unify (tt, (tbs, tats @ [t])) bds)
haftmann@52288
   120
              else (i, bds)
haftmann@52288
   121
            else (j, bds)
haftmann@52288
   122
          end)
haftmann@52288
   123
  end;
haftmann@52288
   124
haftmann@52288
   125
(* Generic decomp for reification : matches the actual term with the
haftmann@52288
   126
   rhs of one cong rule. The result of the matching guides the
haftmann@52288
   127
   proof synthesis: The matches of the introduced Variables A1 .. An are
haftmann@52288
   128
   processed recursively
haftmann@52288
   129
   The rest is instantiated in the cong rule,i.e. no reification is needed *)
haftmann@52288
   130
haftmann@52288
   131
(* da is the decomposition for atoms, ie. it returns ([],g) where g
haftmann@52288
   132
   returns the right instance f (AtC n) = t , where AtC is the Atoms
haftmann@52288
   133
   constructor and n is the number of the atom corresponding to t *)
haftmann@52288
   134
fun decomp_reify da cgns (ct, ctxt) bds =
haftmann@51726
   135
  let
haftmann@52288
   136
    val thy = Proof_Context.theory_of ctxt;
haftmann@52288
   137
    val cert = cterm_of thy;
haftmann@52288
   138
    val certT = ctyp_of thy;
haftmann@52288
   139
    fun tryabsdecomp (ct, ctxt) bds =
haftmann@52288
   140
      (case Thm.term_of ct of
haftmann@52288
   141
        Abs (_, xT, ta) =>
haftmann@52288
   142
          let
haftmann@52288
   143
            val ([raw_xn], ctxt') = Variable.variant_fixes ["x"] ctxt;
haftmann@52288
   144
            val (xn, ta) = Syntax_Trans.variant_abs (raw_xn, xT, ta);  (* FIXME !? *)
haftmann@52288
   145
            val x = Free (xn, xT);
haftmann@52288
   146
            val cx = cert x;
haftmann@52288
   147
            val cta = cert ta;
haftmann@52288
   148
            val bds = (case AList.lookup Type.could_unify bds (HOLogic.listT xT) of
haftmann@52288
   149
                NONE => error "tryabsdecomp: Type not found in the Environement"
haftmann@52288
   150
              | SOME (bsT, atsT) => AList.update Type.could_unify (HOLogic.listT xT,
haftmann@52288
   151
                  (x :: bsT, atsT)) bds);
haftmann@52288
   152
           in (([(cta, ctxt')],
haftmann@52288
   153
                fn ([th], bds) =>
haftmann@52288
   154
                  (hd (Variable.export ctxt' ctxt [(Thm.forall_intr cx th) COMP allI]),
haftmann@52288
   155
                   let
haftmann@52288
   156
                     val (bsT, asT) = the (AList.lookup Type.could_unify bds (HOLogic.listT xT));
haftmann@52288
   157
                   in
haftmann@52288
   158
                     AList.update Type.could_unify (HOLogic.listT xT, (tl bsT, asT)) bds
haftmann@52288
   159
                   end)),
haftmann@52288
   160
               bds)
haftmann@52288
   161
           end
haftmann@52288
   162
       | _ => da (ct, ctxt) bds)
haftmann@52288
   163
  in
haftmann@52288
   164
    (case cgns of
haftmann@52288
   165
      [] => tryabsdecomp (ct, ctxt) bds
haftmann@52288
   166
    | ((vns, cong) :: congs) =>
haftmann@52288
   167
        (let
haftmann@52288
   168
          val (tyenv, tmenv) =
haftmann@52288
   169
            Pattern.match thy
haftmann@52288
   170
              ((fst o HOLogic.dest_eq o HOLogic.dest_Trueprop) (concl_of cong), Thm.term_of ct)
haftmann@52288
   171
              (Vartab.empty, Vartab.empty);
haftmann@52288
   172
          val (fnvs, invs) = List.partition (fn ((vn, _),_) => member (op =) vns vn) (Vartab.dest tmenv);
haftmann@52288
   173
          val (fts, its) =
haftmann@52288
   174
            (map (snd o snd) fnvs,
haftmann@52288
   175
             map (fn ((vn, vi), (tT, t)) => (cert (Var ((vn, vi), tT)), cert t)) invs);
haftmann@52288
   176
          val ctyenv = map (fn ((vn, vi), (s, ty)) => (certT (TVar((vn, vi), s)), certT ty)) (Vartab.dest tyenv);
haftmann@52288
   177
        in
haftmann@52288
   178
          ((map cert fts ~~ replicate (length fts) ctxt,
haftmann@52288
   179
             apfst (FWD (Drule.instantiate_normalize (ctyenv, its) cong))), bds)
haftmann@52288
   180
        end handle Pattern.MATCH => decomp_reify da congs (ct, ctxt) bds))
haftmann@52288
   181
  end;
haftmann@52288
   182
haftmann@52288
   183
fun get_nths (t as (Const (@{const_name "List.nth"}, _) $ vs $ n)) =
haftmann@52288
   184
      AList.update (op aconv) (t, (vs, n))
haftmann@52288
   185
  | get_nths (t1 $ t2) = get_nths t1 #> get_nths t2
haftmann@52288
   186
  | get_nths (Abs (_, _, t')) = get_nths t'
haftmann@52288
   187
  | get_nths _ = I;
haftmann@52288
   188
haftmann@52288
   189
fun tryeqs [] (ct, ctxt) bds = error "Cannot find the atoms equation"
haftmann@52288
   190
  | tryeqs (eq :: eqs) (ct, ctxt) bds = ((
haftmann@51726
   191
      let
haftmann@52288
   192
        val rhs = eq |> prop_of |> HOLogic.dest_Trueprop  |> HOLogic.dest_eq |> snd;
haftmann@52288
   193
        val nths = get_nths rhs [];
haftmann@52288
   194
        val (vss, _) = fold_rev (fn (_, (vs, n)) => fn (vss, ns) =>
haftmann@52288
   195
          (insert (op aconv) vs vss, insert (op aconv) n ns)) nths ([], []);
haftmann@52288
   196
        val (vsns, ctxt') = Variable.variant_fixes (replicate (length vss) "vs") ctxt;
haftmann@52288
   197
        val (xns, ctxt'') = Variable.variant_fixes (replicate (length nths) "x") ctxt';
haftmann@52288
   198
        val thy = Proof_Context.theory_of ctxt'';
haftmann@51726
   199
        val cert = cterm_of thy;
haftmann@52273
   200
        val certT = ctyp_of thy;
haftmann@52288
   201
        val vsns_map = vss ~~ vsns;
haftmann@52288
   202
        val xns_map = fst (split_list nths) ~~ xns;
haftmann@52288
   203
        val subst = map (fn (nt, xn) => (nt, Var ((xn, 0), fastype_of nt))) xns_map;
haftmann@52288
   204
        val rhs_P = subst_free subst rhs;
haftmann@52288
   205
        val (tyenv, tmenv) = Pattern.match thy (rhs_P, Thm.term_of ct) (Vartab.empty, Vartab.empty);
haftmann@52288
   206
        val sbst = Envir.subst_term (tyenv, tmenv);
haftmann@52288
   207
        val sbsT = Envir.subst_type tyenv;
haftmann@52288
   208
        val subst_ty = map (fn (n, (s, t)) =>
haftmann@52288
   209
          (certT (TVar (n, s)), certT t)) (Vartab.dest tyenv)
haftmann@52288
   210
        val tml = Vartab.dest tmenv;
haftmann@52288
   211
        val (subst_ns, bds) = fold_map
haftmann@52288
   212
          (fn (Const _ $ _ $ n, Var (xn0, _)) => fn bds =>
haftmann@52288
   213
            let
haftmann@52288
   214
              val name = snd (the (AList.lookup (op =) tml xn0));
haftmann@52288
   215
              val (idx, bds) = index_of name bds;
haftmann@52288
   216
            in ((cert n, idx |> (HOLogic.mk_nat #> cert)), bds) end) subst bds;
haftmann@52288
   217
        val subst_vs =
haftmann@51726
   218
          let
haftmann@52288
   219
            fun h (Const _ $ (vs as Var (_, lT)) $ _, Var (_, T)) =
haftmann@51726
   220
              let
haftmann@52288
   221
                val cns = sbst (Const (@{const_name "List.Cons"}, T --> lT --> lT));
haftmann@52288
   222
                val lT' = sbsT lT;
haftmann@52288
   223
                val (bsT, _) = the (AList.lookup Type.could_unify bds lT);
haftmann@52288
   224
                val vsn = the (AList.lookup (op =) vsns_map vs);
haftmann@52288
   225
                val cvs = cert (fold_rev (fn x => fn xs => cns $ x $xs) bsT (Free (vsn, lT')));
haftmann@52288
   226
              in (cert vs, cvs) end;
haftmann@52288
   227
          in map h subst end;
haftmann@52288
   228
        val cts = map (fn ((vn, vi), (tT, t)) => (cert (Var ((vn, vi), tT)), cert t))
haftmann@52288
   229
          (fold (AList.delete (fn (((a : string), _), (b, _)) => a = b))
haftmann@52288
   230
            (map (fn n => (n, 0)) xns) tml);
haftmann@52288
   231
        val substt =
haftmann@52288
   232
          let
haftmann@52288
   233
            val ih = Drule.cterm_rule (Thm.instantiate (subst_ty, []));
haftmann@52288
   234
          in map (pairself ih) (subst_ns @ subst_vs @ cts) end;
haftmann@52288
   235
        val th = (Drule.instantiate_normalize (subst_ty, substt) eq) RS sym;
haftmann@52288
   236
      in (hd (Variable.export ctxt'' ctxt [th]), bds) end)
haftmann@52288
   237
      handle Pattern.MATCH => tryeqs eqs (ct, ctxt) bds);
haftmann@52288
   238
haftmann@52288
   239
(* looks for the atoms equation and instantiates it with the right number *)
haftmann@51726
   240
haftmann@52288
   241
fun mk_decompatom eqs (ct, ctxt) bds = (([], fn (_, bds) =>
haftmann@52288
   242
  let
haftmann@52288
   243
    val tT = fastype_of (Thm.term_of ct);
haftmann@52288
   244
    fun isat eq =
haftmann@51726
   245
      let
haftmann@52288
   246
        val rhs = eq |> prop_of |> HOLogic.dest_Trueprop |> HOLogic.dest_eq |> snd;
haftmann@52288
   247
      in exists_Const
haftmann@52288
   248
        (fn (n, ty) => n = @{const_name "List.nth"}
haftmann@52288
   249
          andalso AList.defined Type.could_unify bds (domain_type ty)) rhs
haftmann@52288
   250
          andalso Type.could_unify (fastype_of rhs, tT)
haftmann@52288
   251
      end;
haftmann@52288
   252
  in tryeqs (filter isat eqs) (ct, ctxt) bds end), bds);
haftmann@52288
   253
haftmann@52288
   254
(* Generic reification procedure: *)
haftmann@52288
   255
(* creates all needed cong rules and then just uses the theorem synthesis *)
haftmann@51726
   256
haftmann@52288
   257
fun mk_congs ctxt eqs =
haftmann@52288
   258
  let
haftmann@52288
   259
    val fs = fold_rev (fn eq => insert (op =) (eq |> prop_of |> HOLogic.dest_Trueprop
haftmann@52288
   260
      |> HOLogic.dest_eq |> fst |> strip_comb
haftmann@52288
   261
      |> fst)) eqs [];
haftmann@52288
   262
    val tys = fold_rev (fn f => fold (insert (op =)) (f |> fastype_of |> binder_types |> tl)) fs [];
haftmann@52288
   263
    val (vs, ctxt') = Variable.variant_fixes (replicate (length tys) "vs") ctxt;
haftmann@52288
   264
    val cert = cterm_of (Proof_Context.theory_of ctxt');
haftmann@52288
   265
    val subst =
haftmann@52288
   266
      the o AList.lookup (op =) (map2 (fn T => fn v => (T, cert (Free (v, T)))) tys vs);
haftmann@52288
   267
    fun prep_eq eq =
haftmann@52288
   268
      let
haftmann@52288
   269
        val (_, _ :: vs) = eq |> prop_of |> HOLogic.dest_Trueprop
haftmann@52288
   270
          |> HOLogic.dest_eq |> fst |> strip_comb;
haftmann@52288
   271
        val subst = map_filter (fn (v as Var (_, T)) => SOME (cert v, subst T)
haftmann@52288
   272
          | _ => NONE) vs;
haftmann@52288
   273
      in Thm.instantiate ([], subst) eq end;
haftmann@52288
   274
    val (ps, congs) = map_split (mk_congeq ctxt' fs o prep_eq) eqs;
haftmann@52288
   275
    val bds = AList.make (K ([], [])) tys;
haftmann@52288
   276
  in (ps ~~ Variable.export ctxt' ctxt congs, bds) end
haftmann@52288
   277
haftmann@52288
   278
fun conv ctxt eqs ct =
haftmann@52288
   279
  let
haftmann@51726
   280
    val (congs, bds) = mk_congs ctxt eqs;
haftmann@51726
   281
    val congs = rearrange congs;
haftmann@52275
   282
    val (th, bds') = apfst mk_eq (divide_and_conquer' (decomp_reify (mk_decompatom eqs) congs) (ct, ctxt) bds);
haftmann@52273
   283
    fun is_list_var (Var (_, t)) = can dest_listT t
haftmann@52273
   284
      | is_list_var _ = false;
haftmann@52275
   285
    val vars = th |> prop_of |> Logic.dest_equals |> snd
haftmann@52273
   286
      |> strip_comb |> snd |> filter is_list_var;
haftmann@51726
   287
    val cert = cterm_of (Proof_Context.theory_of ctxt);
haftmann@52275
   288
    val vs = map (fn v as Var (_, T) =>
haftmann@52275
   289
      (v, the (AList.lookup Type.could_unify bds' T) |> snd |> HOLogic.mk_list (dest_listT T))) vars;
haftmann@52275
   290
    val th' = Drule.instantiate_normalize ([], (map o pairself) cert vs) th;
haftmann@52275
   291
    val th'' = Thm.symmetric (dereify ctxt [] (Thm.lhs_of th'));
haftmann@52275
   292
  in Thm.transitive th'' th' end;
haftmann@51726
   293
haftmann@52286
   294
fun tac ctxt eqs =
haftmann@52286
   295
  lift_conv ctxt (conv ctxt eqs);
haftmann@51726
   296
haftmann@52276
   297
end;