src/HOL/Tools/transfer.ML
author wenzelm
Sat Dec 14 17:28:05 2013 +0100 (2013-12-14)
changeset 54742 7a86358a3c0b
parent 53649 96814d676c49
child 54883 dd04a8b654fc
permissions -rw-r--r--
proper context for basic Simplifier operations: rewrite_rule, rewrite_goals_rule, rewrite_goals_tac etc.;
clarified tool context in some boundary cases;
     1 (*  Title:      HOL/Tools/transfer.ML
     2     Author:     Brian Huffman, TU Muenchen
     3     Author:     Ondrej Kuncar, TU Muenchen
     4 
     5 Generic theorem transfer method.
     6 *)
     7 
     8 signature TRANSFER =
     9 sig
    10   val bottom_rewr_conv: thm list -> conv
    11   val top_rewr_conv: thm list -> conv
    12 
    13   val prep_conv: conv
    14   val get_transfer_raw: Proof.context -> thm list
    15   val get_relator_eq: Proof.context -> thm list
    16   val get_sym_relator_eq: Proof.context -> thm list
    17   val get_relator_eq_raw: Proof.context -> thm list
    18   val get_relator_domain: Proof.context -> thm list
    19   val get_compound_lhs: Proof.context -> (term * thm) Item_Net.T
    20   val get_compound_rhs: Proof.context -> (term * thm) Item_Net.T
    21   val transfer_add: attribute
    22   val transfer_del: attribute
    23   val transfer_raw_add: thm -> Context.generic -> Context.generic
    24   val transfer_raw_del: thm -> Context.generic -> Context.generic
    25   val transferred_attribute: thm list -> attribute
    26   val untransferred_attribute: thm list -> attribute
    27   val transfer_domain_add: attribute
    28   val transfer_domain_del: attribute
    29   val transfer_rule_of_term: Proof.context -> bool -> term -> thm
    30   val transfer_rule_of_lhs: Proof.context -> term -> thm
    31   val transfer_tac: bool -> Proof.context -> int -> tactic
    32   val transfer_prover_tac: Proof.context -> int -> tactic
    33   val gen_frees_tac: (string * typ) list -> Proof.context -> int -> tactic
    34   val setup: theory -> theory
    35 end
    36 
    37 structure Transfer : TRANSFER =
    38 struct
    39 
    40 (** Theory Data **)
    41 
    42 val compound_xhs_empty_net = Item_Net.init (Thm.eq_thm_prop o pairself snd) (single o fst);
    43 
    44 structure Data = Generic_Data
    45 (
    46   type T =
    47     { transfer_raw : thm Item_Net.T,
    48       known_frees : (string * typ) list,
    49       compound_lhs : (term * thm) Item_Net.T,
    50       compound_rhs : (term * thm) Item_Net.T,
    51       relator_eq : thm Item_Net.T,
    52       relator_eq_raw : thm Item_Net.T,
    53       relator_domain : thm Item_Net.T }
    54   val empty =
    55     { transfer_raw = Thm.intro_rules,
    56       known_frees = [],
    57       compound_lhs = compound_xhs_empty_net,
    58       compound_rhs = compound_xhs_empty_net,
    59       relator_eq = Thm.full_rules,
    60       relator_eq_raw = Thm.full_rules,
    61       relator_domain = Thm.full_rules }
    62   val extend = I
    63   fun merge
    64     ( { transfer_raw = t1, known_frees = k1,
    65         compound_lhs = l1,
    66         compound_rhs = c1, relator_eq = r1,
    67         relator_eq_raw = rw1, relator_domain = rd1 },
    68       { transfer_raw = t2, known_frees = k2,
    69         compound_lhs = l2,
    70         compound_rhs = c2, relator_eq = r2,
    71         relator_eq_raw = rw2, relator_domain = rd2 } ) =
    72     { transfer_raw = Item_Net.merge (t1, t2),
    73       known_frees = Library.merge (op =) (k1, k2),
    74       compound_lhs = Item_Net.merge (l1, l2),
    75       compound_rhs = Item_Net.merge (c1, c2),
    76       relator_eq = Item_Net.merge (r1, r2),
    77       relator_eq_raw = Item_Net.merge (rw1, rw2),
    78       relator_domain = Item_Net.merge (rd1, rd2) }
    79 )
    80 
    81 fun get_transfer_raw ctxt = ctxt
    82   |> (Item_Net.content o #transfer_raw o Data.get o Context.Proof)
    83 
    84 fun get_known_frees ctxt = ctxt
    85   |> (#known_frees o Data.get o Context.Proof)
    86 
    87 fun get_compound_lhs ctxt = ctxt
    88   |> (#compound_lhs o Data.get o Context.Proof)
    89 
    90 fun get_compound_rhs ctxt = ctxt
    91   |> (#compound_rhs o Data.get o Context.Proof)
    92 
    93 fun get_relator_eq ctxt = ctxt
    94   |> (Item_Net.content o #relator_eq o Data.get o Context.Proof)
    95   |> map safe_mk_meta_eq
    96 
    97 fun get_sym_relator_eq ctxt = ctxt
    98   |> (Item_Net.content o #relator_eq o Data.get o Context.Proof)
    99   |> map (Thm.symmetric o safe_mk_meta_eq)
   100 
   101 fun get_relator_eq_raw ctxt = ctxt
   102   |> (Item_Net.content o #relator_eq_raw o Data.get o Context.Proof)
   103 
   104 fun get_relator_domain ctxt = ctxt
   105   |> (Item_Net.content o #relator_domain o Data.get o Context.Proof)
   106 
   107 fun map_data f1 f2 f3 f4 f5 f6 f7
   108   { transfer_raw, known_frees, compound_lhs, compound_rhs,
   109     relator_eq, relator_eq_raw, relator_domain } =
   110   { transfer_raw = f1 transfer_raw,
   111     known_frees = f2 known_frees,
   112     compound_lhs = f3 compound_lhs,
   113     compound_rhs = f4 compound_rhs,
   114     relator_eq = f5 relator_eq,
   115     relator_eq_raw = f6 relator_eq_raw,
   116     relator_domain = f7 relator_domain }
   117 
   118 fun map_transfer_raw   f = map_data f I I I I I I
   119 fun map_known_frees    f = map_data I f I I I I I
   120 fun map_compound_lhs   f = map_data I I f I I I I
   121 fun map_compound_rhs   f = map_data I I I f I I I
   122 fun map_relator_eq     f = map_data I I I I f I I
   123 fun map_relator_eq_raw f = map_data I I I I I f I
   124 fun map_relator_domain f = map_data I I I I I I f
   125 
   126 fun add_transfer_thm thm = Data.map
   127   (map_transfer_raw (Item_Net.update thm) o
   128    map_compound_lhs
   129      (case HOLogic.dest_Trueprop (Thm.concl_of thm) of
   130         Const (@{const_name Rel}, _) $ _ $ (lhs as (_ $ _)) $ _ =>
   131           Item_Net.update (lhs, thm)
   132       | _ => I) o
   133    map_compound_rhs
   134      (case HOLogic.dest_Trueprop (Thm.concl_of thm) of
   135         Const (@{const_name Rel}, _) $ _ $ _ $ (rhs as (_ $ _)) =>
   136           Item_Net.update (rhs, thm)
   137       | _ => I) o
   138    map_known_frees (Term.add_frees (Thm.concl_of thm)))
   139 
   140 fun del_transfer_thm thm = Data.map 
   141   (map_transfer_raw (Item_Net.remove thm) o
   142    map_compound_lhs
   143      (case HOLogic.dest_Trueprop (Thm.concl_of thm) of
   144         Const (@{const_name Rel}, _) $ _ $ (lhs as (_ $ _)) $ _ =>
   145           Item_Net.remove (lhs, thm)
   146       | _ => I) o
   147    map_compound_rhs
   148      (case HOLogic.dest_Trueprop (Thm.concl_of thm) of
   149         Const (@{const_name Rel}, _) $ _ $ _ $ (rhs as (_ $ _)) =>
   150           Item_Net.remove (rhs, thm)
   151       | _ => I))
   152 
   153 fun transfer_raw_add thm ctxt = add_transfer_thm thm ctxt
   154 fun transfer_raw_del thm ctxt = del_transfer_thm thm ctxt
   155 
   156 (** Conversions **)
   157 
   158 fun bottom_rewr_conv rewrs = Conv.bottom_conv (K (Conv.try_conv (Conv.rewrs_conv rewrs))) @{context}
   159 fun top_rewr_conv rewrs = Conv.top_conv (K (Conv.try_conv (Conv.rewrs_conv rewrs))) @{context}
   160 
   161 fun transfer_rel_conv conv = 
   162   Conv.concl_conv ~1 (HOLogic.Trueprop_conv (Conv.fun2_conv (Conv.arg_conv conv)))
   163 
   164 val Rel_rule = Thm.symmetric @{thm Rel_def}
   165 
   166 fun dest_funcT cT =
   167   (case Thm.dest_ctyp cT of [T, U] => (T, U)
   168     | _ => raise TYPE ("dest_funcT", [Thm.typ_of cT], []))
   169 
   170 fun Rel_conv ct =
   171   let val (cT, cT') = dest_funcT (Thm.ctyp_of_term ct)
   172       val (cU, _) = dest_funcT cT'
   173   in Drule.instantiate' [SOME cT, SOME cU] [SOME ct] Rel_rule end
   174 
   175 (* Conversion to preprocess a transfer rule *)
   176 fun safe_Rel_conv ct =
   177   Conv.try_conv (HOLogic.Trueprop_conv (Conv.fun_conv (Conv.fun_conv Rel_conv))) ct
   178 
   179 fun prep_conv ct = (
   180       Conv.implies_conv safe_Rel_conv prep_conv
   181       else_conv
   182       safe_Rel_conv
   183       else_conv
   184       Conv.all_conv) ct
   185 
   186 (** Replacing explicit equalities with is_equality premises **)
   187 
   188 fun mk_is_equality t =
   189   Const (@{const_name is_equality}, Term.fastype_of t --> HOLogic.boolT) $ t
   190 
   191 val is_equality_lemma =
   192   @{lemma "(!!R. is_equality R ==> PROP (P R)) == PROP (P (op =))"
   193     by (unfold is_equality_def, rule, drule meta_spec,
   194       erule meta_mp, rule refl, simp)}
   195 
   196 fun gen_abstract_equalities ctxt (dest : term -> term * (term -> term)) thm =
   197   let
   198     val thy = Thm.theory_of_thm thm
   199     val prop = Thm.prop_of thm
   200     val (t, mk_prop') = dest prop
   201     (* Only consider "op =" at non-base types *)
   202     fun is_eq (Const (@{const_name HOL.eq}, Type ("fun", [T, _]))) =
   203         (case T of Type (_, []) => false | _ => true)
   204       | is_eq _ = false
   205     val add_eqs = Term.fold_aterms (fn t => if is_eq t then insert (op =) t else I)
   206     val eq_consts = rev (add_eqs t [])
   207     val eqTs = map (snd o dest_Const) eq_consts
   208     val used = Term.add_free_names prop []
   209     val names = map (K "") eqTs |> Name.variant_list used
   210     val frees = map Free (names ~~ eqTs)
   211     val prems = map (HOLogic.mk_Trueprop o mk_is_equality) frees
   212     val prop1 = mk_prop' (Term.subst_atomic (eq_consts ~~ frees) t)
   213     val prop2 = fold Logic.all frees (Logic.list_implies (prems, prop1))
   214     val cprop = Thm.cterm_of thy prop2
   215     val equal_thm = Raw_Simplifier.rewrite ctxt false [is_equality_lemma] cprop
   216     fun forall_elim thm = Thm.forall_elim_vars (Thm.maxidx_of thm + 1) thm
   217   in
   218     forall_elim (thm COMP (equal_thm COMP @{thm equal_elim_rule2}))
   219   end
   220     handle TERM _ => thm
   221 
   222 fun abstract_equalities_transfer ctxt thm =
   223   let
   224     fun dest prop =
   225       let
   226         val prems = Logic.strip_imp_prems prop
   227         val concl = HOLogic.dest_Trueprop (Logic.strip_imp_concl prop)
   228         val ((rel, x), y) = apfst Term.dest_comb (Term.dest_comb concl)
   229       in
   230         (rel, fn rel' =>
   231           Logic.list_implies (prems, HOLogic.mk_Trueprop (rel' $ x $ y)))
   232       end
   233     val contracted_eq_thm = 
   234       Conv.fconv_rule (transfer_rel_conv (bottom_rewr_conv (get_relator_eq ctxt))) thm
   235       handle CTERM _ => thm
   236   in
   237     gen_abstract_equalities ctxt dest contracted_eq_thm
   238   end
   239 
   240 fun abstract_equalities_relator_eq ctxt rel_eq_thm =
   241   gen_abstract_equalities ctxt (fn x => (x, I))
   242     (rel_eq_thm RS @{thm is_equality_def [THEN iffD2]})
   243 
   244 fun abstract_equalities_domain ctxt thm =
   245   let
   246     fun dest prop =
   247       let
   248         val prems = Logic.strip_imp_prems prop
   249         val concl = HOLogic.dest_Trueprop (Logic.strip_imp_concl prop)
   250         val ((eq, dom), y) = apfst Term.dest_comb (Term.dest_comb concl)
   251       in
   252         (dom, fn dom' => Logic.list_implies (prems, HOLogic.mk_Trueprop (eq $ dom' $ y)))
   253       end
   254     fun transfer_rel_conv conv = 
   255       Conv.concl_conv ~1 (HOLogic.Trueprop_conv (Conv.arg1_conv (Conv.arg_conv conv)))
   256     val contracted_eq_thm = 
   257       Conv.fconv_rule (transfer_rel_conv (bottom_rewr_conv (get_relator_eq ctxt))) thm
   258   in
   259     gen_abstract_equalities ctxt dest contracted_eq_thm
   260   end 
   261 
   262 
   263 (** Replacing explicit Domainp predicates with Domainp assumptions **)
   264 
   265 fun mk_Domainp_assm (T, R) =
   266   HOLogic.mk_eq ((Const (@{const_name Domainp}, Term.fastype_of T --> Term.fastype_of R) $ T), R)
   267 
   268 val Domainp_lemma =
   269   @{lemma "(!!R. Domainp T = R ==> PROP (P R)) == PROP (P (Domainp T))"
   270     by (rule, drule meta_spec,
   271       erule meta_mp, rule refl, simp)}
   272 
   273 fun fold_Domainp f (t as Const (@{const_name Domainp},_) $ (Var (_,_))) = f t
   274   | fold_Domainp f (t $ u) = fold_Domainp f t #> fold_Domainp f u
   275   | fold_Domainp f (Abs (_, _, t)) = fold_Domainp f t
   276   | fold_Domainp _ _ = I
   277 
   278 fun subst_terms tab t = 
   279   let
   280     val t' = Termtab.lookup tab t
   281   in
   282     case t' of
   283       SOME t' => t'
   284       | NONE => 
   285         (case t of
   286           u $ v => (subst_terms tab u) $ (subst_terms tab v)
   287           | Abs (a, T, t) => Abs (a, T, subst_terms tab t)
   288           | t => t)
   289   end
   290 
   291 fun gen_abstract_domains ctxt (dest : term -> term * (term -> term)) thm =
   292   let
   293     val thy = Thm.theory_of_thm thm
   294     val prop = Thm.prop_of thm
   295     val (t, mk_prop') = dest prop
   296     val Domainp_tms = rev (fold_Domainp (fn t => insert op= t) t [])
   297     val Domainp_Ts = map (snd o dest_funT o snd o dest_Const o fst o dest_comb) Domainp_tms
   298     val used = Term.add_free_names t []
   299     val rels = map (snd o dest_comb) Domainp_tms
   300     val rel_names = map (fst o fst o dest_Var) rels
   301     val names = map (fn name => ("D" ^ name)) rel_names |> Name.variant_list used
   302     val frees = map Free (names ~~ Domainp_Ts)
   303     val prems = map (HOLogic.mk_Trueprop o mk_Domainp_assm) (rels ~~ frees);
   304     val t' = subst_terms (fold Termtab.update (Domainp_tms ~~ frees) Termtab.empty) t
   305     val prop1 = fold Logic.all frees (Logic.list_implies (prems, mk_prop' t'))
   306     val prop2 = Logic.list_rename_params (rev names) prop1
   307     val cprop = Thm.cterm_of thy prop2
   308     val equal_thm = Raw_Simplifier.rewrite ctxt false [Domainp_lemma] cprop
   309     fun forall_elim thm = Thm.forall_elim_vars (Thm.maxidx_of thm + 1) thm;
   310   in
   311     forall_elim (thm COMP (equal_thm COMP @{thm equal_elim_rule2}))
   312   end
   313     handle TERM _ => thm
   314 
   315 fun abstract_domains_transfer ctxt thm =
   316   let
   317     fun dest prop =
   318       let
   319         val prems = Logic.strip_imp_prems prop
   320         val concl = HOLogic.dest_Trueprop (Logic.strip_imp_concl prop)
   321         val ((rel, x), y) = apfst Term.dest_comb (Term.dest_comb concl)
   322       in
   323         (x, fn x' =>
   324           Logic.list_implies (prems, HOLogic.mk_Trueprop (rel $ x' $ y)))
   325       end
   326   in
   327     gen_abstract_domains ctxt dest thm
   328   end
   329 
   330 fun detect_transfer_rules thm =
   331   let
   332     fun is_transfer_rule tm = case (HOLogic.dest_Trueprop tm) of
   333       (Const (@{const_name HOL.eq}, _)) $ ((Const (@{const_name Domainp}, _)) $ _) $ _ => false
   334       | _ $ _ $ _ => true
   335       | _ => false
   336     fun safe_transfer_rule_conv ctm =
   337       if is_transfer_rule (term_of ctm) then safe_Rel_conv ctm else Conv.all_conv ctm
   338   in
   339     Conv.fconv_rule (Conv.prems_conv ~1 safe_transfer_rule_conv) thm
   340   end
   341 
   342 (** Adding transfer domain rules **)
   343 
   344 fun add_transfer_domain_thm thm ctxt = 
   345   (add_transfer_thm o abstract_equalities_domain (Context.proof_of ctxt) o detect_transfer_rules) thm ctxt
   346 
   347 fun del_transfer_domain_thm thm ctxt = 
   348   (del_transfer_thm o abstract_equalities_domain (Context.proof_of ctxt) o detect_transfer_rules) thm ctxt
   349 
   350 (** Transfer proof method **)
   351 
   352 val post_simps =
   353   @{thms transfer_forall_eq [symmetric]
   354     transfer_implies_eq [symmetric] transfer_bforall_unfold}
   355 
   356 fun gen_frees_tac keepers ctxt = SUBGOAL (fn (t, i) =>
   357   let
   358     val keepers = keepers @ get_known_frees ctxt
   359     val vs = rev (Term.add_frees t [])
   360     val vs' = filter_out (member (op =) keepers) vs
   361   in
   362     Induct.arbitrary_tac ctxt 0 vs' i
   363   end)
   364 
   365 fun mk_relT (T, U) = T --> U --> HOLogic.boolT
   366 
   367 fun mk_Rel t =
   368   let val T = fastype_of t
   369   in Const (@{const_name Transfer.Rel}, T --> T) $ t end
   370 
   371 fun transfer_rule_of_terms (prj : typ * typ -> typ) ctxt tab t u =
   372   let
   373     val thy = Proof_Context.theory_of ctxt
   374     (* precondition: prj(T,U) must consist of only TFrees and type "fun" *)
   375     fun rel (T as Type ("fun", [T1, T2])) (U as Type ("fun", [U1, U2])) =
   376         let
   377           val r1 = rel T1 U1
   378           val r2 = rel T2 U2
   379           val rT = fastype_of r1 --> fastype_of r2 --> mk_relT (T, U)
   380         in
   381           Const (@{const_name fun_rel}, rT) $ r1 $ r2
   382         end
   383       | rel T U =
   384         let
   385           val (a, _) = dest_TFree (prj (T, U))
   386         in
   387           Free (the (AList.lookup (op =) tab a), mk_relT (T, U))
   388         end
   389     fun zip _ thms (Bound i) (Bound _) = (nth thms i, [])
   390       | zip ctxt thms (Abs (x, T, t)) (Abs (y, U, u)) =
   391         let
   392           val ([x', y'], ctxt') = Variable.variant_fixes [x, y] ctxt
   393           val prop = mk_Rel (rel T U) $ Free (x', T) $ Free (y', U)
   394           val cprop = Thm.cterm_of thy (HOLogic.mk_Trueprop prop)
   395           val thm0 = Thm.assume cprop
   396           val (thm1, hyps) = zip ctxt' (thm0 :: thms) t u
   397           val ((r1, x), y) = apfst Thm.dest_comb (Thm.dest_comb (Thm.dest_arg cprop))
   398           val r2 = Thm.dest_fun2 (Thm.dest_arg (cprop_of thm1))
   399           val (a1, (b1, _)) = apsnd dest_funcT (dest_funcT (ctyp_of_term r1))
   400           val (a2, (b2, _)) = apsnd dest_funcT (dest_funcT (ctyp_of_term r2))
   401           val tinsts = [SOME a1, SOME b1, SOME a2, SOME b2]
   402           val insts = [SOME (Thm.dest_arg r1), SOME (Thm.dest_arg r2)]
   403           val rule = Drule.instantiate' tinsts insts @{thm Rel_abs}
   404           val thm2 = Thm.forall_intr x (Thm.forall_intr y (Thm.implies_intr cprop thm1))
   405         in
   406           (thm2 COMP rule, hyps)
   407         end
   408       | zip ctxt thms (f $ t) (g $ u) =
   409         let
   410           val (thm1, hyps1) = zip ctxt thms f g
   411           val (thm2, hyps2) = zip ctxt thms t u
   412         in
   413           (thm2 RS (thm1 RS @{thm Rel_app}), hyps1 @ hyps2)
   414         end
   415       | zip _ _ t u =
   416         let
   417           val T = fastype_of t
   418           val U = fastype_of u
   419           val prop = mk_Rel (rel T U) $ t $ u
   420           val cprop = Thm.cterm_of thy (HOLogic.mk_Trueprop prop)
   421         in
   422           (Thm.assume cprop, [cprop])
   423         end
   424     val r = mk_Rel (rel (fastype_of t) (fastype_of u))
   425     val goal = HOLogic.mk_Trueprop (r $ t $ u)
   426     val rename = Thm.trivial (cterm_of thy goal)
   427     val (thm, hyps) = zip ctxt [] t u
   428   in
   429     Drule.implies_intr_list hyps (thm RS rename)
   430   end
   431 
   432 (* create a lambda term of the same shape as the given term *)
   433 fun skeleton (is_atom : term -> bool) ctxt t =
   434   let
   435     fun dummy ctxt =
   436       let
   437         val (c, ctxt) = yield_singleton Variable.variant_fixes "a" ctxt
   438       in
   439         (Free (c, dummyT), ctxt)
   440       end
   441     fun go (Bound i) ctxt = (Bound i, ctxt)
   442       | go (Abs (x, _, t)) ctxt =
   443         let
   444           val (t', ctxt) = go t ctxt
   445         in
   446           (Abs (x, dummyT, t'), ctxt)
   447         end
   448       | go (tu as (t $ u)) ctxt =
   449         if is_atom tu andalso not (Term.is_open tu) then dummy ctxt else
   450         let
   451           val (t', ctxt) = go t ctxt
   452           val (u', ctxt) = go u ctxt
   453         in
   454           (t' $ u', ctxt)
   455         end
   456       | go _ ctxt = dummy ctxt
   457   in
   458     go t ctxt |> fst |> Syntax.check_term ctxt |>
   459       map_types (map_type_tfree (fn (a, _) => TFree (a, HOLogic.typeS)))
   460   end
   461 
   462 (** Monotonicity analysis **)
   463 
   464 (* TODO: Put extensible table in theory data *)
   465 val monotab =
   466   Symtab.make
   467     [(@{const_name transfer_implies}, [~1, 1]),
   468      (@{const_name transfer_forall}, [1])(*,
   469      (@{const_name implies}, [~1, 1]),
   470      (@{const_name All}, [1])*)]
   471 
   472 (*
   473 Function bool_insts determines the set of boolean-relation variables
   474 that can be instantiated to implies, rev_implies, or iff.
   475 
   476 Invariants: bool_insts p (t, u) requires that
   477   u :: _ => _ => ... => bool, and
   478   t is a skeleton of u
   479 *)
   480 fun bool_insts p (t, u) =
   481   let
   482     fun strip2 (t1 $ t2, u1 $ u2, tus) =
   483         strip2 (t1, u1, (t2, u2) :: tus)
   484       | strip2 x = x
   485     fun or3 ((a, b, c), (x, y, z)) = (a orelse x, b orelse y, c orelse z)
   486     fun go Ts p (Abs (_, T, t), Abs (_, _, u)) tab = go (T :: Ts) p (t, u) tab
   487       | go Ts p (t, u) tab =
   488         let
   489           val (a, _) = dest_TFree (Term.body_type (Term.fastype_of1 (Ts, t)))
   490           val (_, tf, tus) = strip2 (t, u, [])
   491           val ps_opt = case tf of Const (c, _) => Symtab.lookup monotab c | _ => NONE
   492           val tab1 =
   493             case ps_opt of
   494               SOME ps =>
   495               let
   496                 val ps' = map (fn x => p * x) (take (length tus) ps)
   497               in
   498                 fold I (map2 (go Ts) ps' tus) tab
   499               end
   500             | NONE => tab
   501           val tab2 = Symtab.make [(a, (p >= 0, p <= 0, is_none ps_opt))]
   502         in
   503           Symtab.join (K or3) (tab1, tab2)
   504         end
   505     val tab = go [] p (t, u) Symtab.empty
   506     fun f (a, (true, false, false)) = SOME (a, @{const implies})
   507       | f (a, (false, true, false)) = SOME (a, @{const rev_implies})
   508       | f (a, (true, true, _))      = SOME (a, HOLogic.eq_const HOLogic.boolT)
   509       | f _                         = NONE
   510   in
   511     map_filter f (Symtab.dest tab)
   512   end
   513 
   514 fun retrieve_terms t net = map fst (Item_Net.retrieve net t)
   515   
   516 fun matches_list ctxt term = 
   517   is_some o find_first (fn pat => Pattern.matches (Proof_Context.theory_of ctxt) (pat, term))
   518 
   519 fun transfer_rule_of_term ctxt equiv t : thm =
   520   let
   521     val compound_rhs = get_compound_rhs ctxt
   522     fun is_rhs t = compound_rhs |> retrieve_terms t |> matches_list ctxt t
   523     val s = skeleton is_rhs ctxt t
   524     val frees = map fst (Term.add_frees s [])
   525     val tfrees = map fst (Term.add_tfrees s [])
   526     fun prep a = "R" ^ Library.unprefix "'" a
   527     val (rnames, ctxt') = Variable.variant_fixes (map prep tfrees) ctxt
   528     val tab = tfrees ~~ rnames
   529     fun prep a = the (AList.lookup (op =) tab a)
   530     val thm = transfer_rule_of_terms fst ctxt' tab s t
   531     val binsts = bool_insts (if equiv then 0 else 1) (s, t)
   532     val cbool = @{ctyp bool}
   533     val relT = @{typ "bool => bool => bool"}
   534     val idx = Thm.maxidx_of thm + 1
   535     val thy = Proof_Context.theory_of ctxt
   536     fun tinst (a, _) = (ctyp_of thy (TVar ((a, idx), HOLogic.typeS)), cbool)
   537     fun inst (a, t) = (cterm_of thy (Var (Name.clean_index (prep a, idx), relT)), cterm_of thy t)
   538   in
   539     thm
   540       |> Thm.generalize (tfrees, rnames @ frees) idx
   541       |> Thm.instantiate (map tinst binsts, map inst binsts)
   542   end
   543 
   544 fun transfer_rule_of_lhs ctxt t : thm =
   545   let
   546     val compound_lhs = get_compound_lhs ctxt
   547     fun is_lhs t = compound_lhs |> retrieve_terms t |> matches_list ctxt t
   548     val s = skeleton is_lhs ctxt t
   549     val frees = map fst (Term.add_frees s [])
   550     val tfrees = map fst (Term.add_tfrees s [])
   551     fun prep a = "R" ^ Library.unprefix "'" a
   552     val (rnames, ctxt') = Variable.variant_fixes (map prep tfrees) ctxt
   553     val tab = tfrees ~~ rnames
   554     fun prep a = the (AList.lookup (op =) tab a)
   555     val thm = transfer_rule_of_terms snd ctxt' tab t s
   556     val binsts = bool_insts 1 (s, t)
   557     val cbool = @{ctyp bool}
   558     val relT = @{typ "bool => bool => bool"}
   559     val idx = Thm.maxidx_of thm + 1
   560     val thy = Proof_Context.theory_of ctxt
   561     fun tinst (a, _) = (ctyp_of thy (TVar ((a, idx), HOLogic.typeS)), cbool)
   562     fun inst (a, t) = (cterm_of thy (Var (Name.clean_index (prep a, idx), relT)), cterm_of thy t)
   563   in
   564     thm
   565       |> Thm.generalize (tfrees, rnames @ frees) idx
   566       |> Thm.instantiate (map tinst binsts, map inst binsts)
   567   end
   568 
   569 fun eq_tac eq_rules = TRY o REPEAT_ALL_NEW (resolve_tac eq_rules) THEN_ALL_NEW rtac @{thm is_equality_eq}
   570 
   571 fun transfer_tac equiv ctxt i =
   572   let
   573     val pre_simps = @{thms transfer_forall_eq transfer_implies_eq}
   574     val start_rule =
   575       if equiv then @{thm transfer_start} else @{thm transfer_start'}
   576     val rules = get_transfer_raw ctxt
   577     val eq_rules = get_relator_eq_raw ctxt
   578     (* allow unsolved subgoals only for standard transfer method, not for transfer' *)
   579     val end_tac = if equiv then K all_tac else K no_tac
   580     val err_msg = "Transfer failed to convert goal to an object-logic formula"
   581     fun main_tac (t, i) =
   582       rtac start_rule i THEN
   583       (rtac (transfer_rule_of_term ctxt equiv (HOLogic.dest_Trueprop t))
   584         THEN_ALL_NEW
   585           (SOLVED' (REPEAT_ALL_NEW (resolve_tac rules) THEN_ALL_NEW (DETERM o eq_tac eq_rules))
   586             ORELSE' end_tac)) (i + 1)
   587         handle TERM (_, ts) => raise TERM (err_msg, ts)
   588   in
   589     EVERY
   590       [rewrite_goal_tac ctxt pre_simps i THEN
   591        SUBGOAL main_tac i,
   592        (* FIXME: rewrite_goal_tac does unwanted eta-contraction *)
   593        rewrite_goal_tac ctxt post_simps i,
   594        Goal.norm_hhf_tac ctxt i]
   595   end
   596 
   597 fun transfer_prover_tac ctxt = SUBGOAL (fn (t, i) =>
   598   let
   599     val rhs = (snd o Term.dest_comb o HOLogic.dest_Trueprop) t
   600     val rule1 = transfer_rule_of_term ctxt false rhs
   601     val rules = get_transfer_raw ctxt
   602     val eq_rules = get_relator_eq_raw ctxt
   603     val expand_eq_in_rel = transfer_rel_conv (top_rewr_conv [@{thm fun_rel_eq[symmetric,THEN eq_reflection]}])
   604   in
   605     EVERY
   606       [CONVERSION prep_conv i,
   607        rtac @{thm transfer_prover_start} i,
   608        ((rtac rule1 ORELSE' (CONVERSION expand_eq_in_rel THEN' rtac rule1))
   609         THEN_ALL_NEW
   610          (REPEAT_ALL_NEW (resolve_tac rules) THEN_ALL_NEW (DETERM o eq_tac eq_rules))) (i+1),
   611        rtac @{thm refl} i]
   612   end)
   613 
   614 (** Transfer attribute **)
   615 
   616 fun transferred ctxt extra_rules thm =
   617   let
   618     val start_rule = @{thm transfer_start}
   619     val start_rule' = @{thm transfer_start'}
   620     val rules = extra_rules @ get_transfer_raw ctxt
   621     val eq_rules = get_relator_eq_raw ctxt
   622     val err_msg = "Transfer failed to convert goal to an object-logic formula"
   623     val pre_simps = @{thms transfer_forall_eq transfer_implies_eq}
   624     val thm1 = Drule.forall_intr_vars thm
   625     val instT = rev (Term.add_tvars (Thm.full_prop_of thm1) [])
   626                 |> map (fn v as ((a, _), S) => (v, TFree (a, S)))
   627     val thm2 = thm1
   628       |> Thm.certify_instantiate (instT, [])
   629       |> Raw_Simplifier.rewrite_rule ctxt pre_simps
   630     val ctxt' = Variable.declare_names (Thm.full_prop_of thm2) ctxt
   631     val t = HOLogic.dest_Trueprop (Thm.concl_of thm2)
   632     val rule = transfer_rule_of_lhs ctxt' t
   633     val tac =
   634       resolve_tac [thm2 RS start_rule', thm2 RS start_rule] 1 THEN
   635       (rtac rule
   636         THEN_ALL_NEW
   637           (SOLVED' (REPEAT_ALL_NEW (resolve_tac rules)
   638             THEN_ALL_NEW (DETERM o eq_tac eq_rules)))) 1
   639         handle TERM (_, ts) => raise TERM (err_msg, ts)
   640     val thm3 = Goal.prove_internal [] @{cpat "Trueprop ?P"} (K tac)
   641     val tnames = map (fst o dest_TFree o snd) instT
   642   in
   643     thm3
   644       |> Raw_Simplifier.rewrite_rule ctxt' post_simps
   645       |> Raw_Simplifier.norm_hhf
   646       |> Drule.generalize (tnames, [])
   647       |> Drule.zero_var_indexes
   648   end
   649 (*
   650     handle THM _ => thm
   651 *)
   652 
   653 fun untransferred ctxt extra_rules thm =
   654   let
   655     val start_rule = @{thm untransfer_start}
   656     val rules = extra_rules @ get_transfer_raw ctxt
   657     val eq_rules = get_relator_eq_raw ctxt
   658     val err_msg = "Transfer failed to convert goal to an object-logic formula"
   659     val pre_simps = @{thms transfer_forall_eq transfer_implies_eq}
   660     val thm1 = Drule.forall_intr_vars thm
   661     val instT = rev (Term.add_tvars (Thm.full_prop_of thm1) [])
   662                 |> map (fn v as ((a, _), S) => (v, TFree (a, S)))
   663     val thm2 = thm1
   664       |> Thm.certify_instantiate (instT, [])
   665       |> Raw_Simplifier.rewrite_rule ctxt pre_simps
   666     val ctxt' = Variable.declare_names (Thm.full_prop_of thm2) ctxt
   667     val t = HOLogic.dest_Trueprop (Thm.concl_of thm2)
   668     val rule = transfer_rule_of_term ctxt' true t
   669     val tac =
   670       rtac (thm2 RS start_rule) 1 THEN
   671       (rtac rule
   672         THEN_ALL_NEW
   673           (SOLVED' (REPEAT_ALL_NEW (resolve_tac rules)
   674             THEN_ALL_NEW (DETERM o eq_tac eq_rules)))) 1
   675         handle TERM (_, ts) => raise TERM (err_msg, ts)
   676     val thm3 = Goal.prove_internal [] @{cpat "Trueprop ?P"} (K tac)
   677     val tnames = map (fst o dest_TFree o snd) instT
   678   in
   679     thm3
   680       |> Raw_Simplifier.rewrite_rule ctxt' post_simps
   681       |> Raw_Simplifier.norm_hhf
   682       |> Drule.generalize (tnames, [])
   683       |> Drule.zero_var_indexes
   684   end
   685 
   686 (** Methods and attributes **)
   687 
   688 val free = Args.context -- Args.term >> (fn (_, Free v) => v | (ctxt, t) =>
   689   error ("Bad free variable: " ^ Syntax.string_of_term ctxt t))
   690 
   691 val fixing = Scan.optional (Scan.lift (Args.$$$ "fixing" -- Args.colon)
   692   |-- Scan.repeat free) []
   693 
   694 fun transfer_method equiv : (Proof.context -> Proof.method) context_parser =
   695   fixing >> (fn vs => fn ctxt =>
   696     SIMPLE_METHOD' (gen_frees_tac vs ctxt THEN' transfer_tac equiv ctxt))
   697 
   698 val transfer_prover_method : (Proof.context -> Proof.method) context_parser =
   699   Scan.succeed (fn ctxt => SIMPLE_METHOD' (transfer_prover_tac ctxt))
   700 
   701 (* Attribute for transfer rules *)
   702 
   703 fun prep_rule ctxt = 
   704   abstract_domains_transfer ctxt o abstract_equalities_transfer ctxt o Conv.fconv_rule prep_conv
   705 
   706 val transfer_add =
   707   Thm.declaration_attribute (fn thm => fn ctxt => 
   708     (add_transfer_thm o prep_rule (Context.proof_of ctxt)) thm ctxt)
   709 
   710 val transfer_del =
   711   Thm.declaration_attribute (fn thm => fn ctxt => 
   712     (del_transfer_thm o prep_rule (Context.proof_of ctxt)) thm ctxt)
   713 
   714 val transfer_attribute =
   715   Attrib.add_del transfer_add transfer_del
   716 
   717 (* Attributes for transfer domain rules *)
   718 
   719 val transfer_domain_add = Thm.declaration_attribute add_transfer_domain_thm
   720 
   721 val transfer_domain_del = Thm.declaration_attribute del_transfer_domain_thm
   722 
   723 val transfer_domain_attribute =
   724   Attrib.add_del transfer_domain_add transfer_domain_del
   725 
   726 (* Attributes for transferred rules *)
   727 
   728 fun transferred_attribute thms = Thm.rule_attribute
   729   (fn context => transferred (Context.proof_of context) thms)
   730 
   731 fun untransferred_attribute thms = Thm.rule_attribute
   732   (fn context => untransferred (Context.proof_of context) thms)
   733 
   734 val transferred_attribute_parser =
   735   Attrib.thms >> transferred_attribute
   736 
   737 val untransferred_attribute_parser =
   738   Attrib.thms >> untransferred_attribute
   739 
   740 (* Theory setup *)
   741 
   742 val relator_eq_setup =
   743   let
   744     val name = @{binding relator_eq}
   745     fun add_thm thm context = context
   746       |> Data.map (map_relator_eq (Item_Net.update thm))
   747       |> Data.map (map_relator_eq_raw
   748           (Item_Net.update (abstract_equalities_relator_eq (Context.proof_of context) thm)))
   749     fun del_thm thm context = context
   750       |> Data.map (map_relator_eq (Item_Net.remove thm))
   751       |> Data.map (map_relator_eq_raw
   752           (Item_Net.remove (abstract_equalities_relator_eq (Context.proof_of context) thm)))
   753     val add = Thm.declaration_attribute add_thm
   754     val del = Thm.declaration_attribute del_thm
   755     val text = "declaration of relator equality rule (used by transfer method)"
   756     val content = Item_Net.content o #relator_eq o Data.get
   757   in
   758     Attrib.setup name (Attrib.add_del add del) text
   759     #> Global_Theory.add_thms_dynamic (name, content)
   760   end
   761 
   762 val relator_domain_setup =
   763   let
   764     val name = @{binding relator_domain}
   765     fun add_thm thm = Data.map (map_relator_domain (Item_Net.update thm))
   766       #> add_transfer_domain_thm thm
   767     fun del_thm thm = Data.map (map_relator_domain (Item_Net.remove thm))
   768       #> del_transfer_domain_thm thm
   769     val add = Thm.declaration_attribute add_thm
   770     val del = Thm.declaration_attribute del_thm
   771     val text = "declaration of relator domain rule (used by transfer method)"
   772     val content = Item_Net.content o #relator_domain o Data.get
   773   in
   774     Attrib.setup name (Attrib.add_del add del) text
   775     #> Global_Theory.add_thms_dynamic (name, content)
   776   end
   777 
   778 
   779 val setup =
   780   relator_eq_setup
   781   #> relator_domain_setup
   782   #> Attrib.setup @{binding transfer_rule} transfer_attribute
   783      "transfer rule for transfer method"
   784   #> Global_Theory.add_thms_dynamic
   785      (@{binding transfer_raw}, Item_Net.content o #transfer_raw o Data.get)
   786   #> Attrib.setup @{binding transfer_domain_rule} transfer_domain_attribute
   787      "transfer domain rule for transfer method"
   788   #> Attrib.setup @{binding transferred} transferred_attribute_parser
   789      "raw theorem transferred to abstract theorem using transfer rules"
   790   #> Attrib.setup @{binding untransferred} untransferred_attribute_parser
   791      "abstract theorem transferred to raw theorem using transfer rules"
   792   #> Global_Theory.add_thms_dynamic
   793      (@{binding relator_eq_raw}, Item_Net.content o #relator_eq_raw o Data.get)
   794   #> Method.setup @{binding transfer} (transfer_method true)
   795      "generic theorem transfer method"
   796   #> Method.setup @{binding transfer'} (transfer_method false)
   797      "generic theorem transfer method"
   798   #> Method.setup @{binding transfer_prover} transfer_prover_method
   799      "for proving transfer rules"
   800 
   801 end