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