src/HOLCF/Tools/Domain/domain_theorems.ML
author huffman
Mon Mar 08 12:21:07 2010 -0800 (2010-03-08)
changeset 35658 3d8da9fac424
parent 35657 0537c34c6067
child 35659 a78bc1930a7a
permissions -rw-r--r--
pass take_info as an argument to comp_theorems
     1 (*  Title:      HOLCF/Tools/Domain/domain_theorems.ML
     2     Author:     David von Oheimb
     3     Author:     Brian Huffman
     4 
     5 Proof generator for domain command.
     6 *)
     7 
     8 val HOLCF_ss = @{simpset};
     9 
    10 signature DOMAIN_THEOREMS =
    11 sig
    12   val theorems:
    13     Domain_Library.eq * Domain_Library.eq list
    14     -> typ * (binding * (bool * binding option * typ) list * mixfix) list
    15     -> Domain_Take_Proofs.iso_info
    16     -> theory -> thm list * theory;
    17 
    18   val comp_theorems :
    19       bstring * Domain_Library.eq list ->
    20       Domain_Take_Proofs.take_info ->
    21       Domain_Take_Proofs.take_induct_info ->
    22       theory -> thm list * theory
    23 
    24   val quiet_mode: bool Unsynchronized.ref;
    25   val trace_domain: bool Unsynchronized.ref;
    26 end;
    27 
    28 structure Domain_Theorems :> DOMAIN_THEOREMS =
    29 struct
    30 
    31 val quiet_mode = Unsynchronized.ref false;
    32 val trace_domain = Unsynchronized.ref false;
    33 
    34 fun message s = if !quiet_mode then () else writeln s;
    35 fun trace s = if !trace_domain then tracing s else ();
    36 
    37 open Domain_Library;
    38 infixr 0 ===>;
    39 infixr 0 ==>;
    40 infix 0 == ; 
    41 infix 1 ===;
    42 infix 1 ~= ;
    43 infix 1 <<;
    44 infix 1 ~<<;
    45 infix 9 `   ;
    46 infix 9 `% ;
    47 infix 9 `%%;
    48 infixr 9 oo;
    49 
    50 (* ----- general proof facilities ------------------------------------------- *)
    51 
    52 fun legacy_infer_term thy t =
    53   let val ctxt = ProofContext.set_mode ProofContext.mode_schematic (ProofContext.init thy)
    54   in singleton (Syntax.check_terms ctxt) (Sign.intern_term thy t) end;
    55 
    56 fun pg'' thy defs t tacs =
    57   let
    58     val t' = legacy_infer_term thy t;
    59     val asms = Logic.strip_imp_prems t';
    60     val prop = Logic.strip_imp_concl t';
    61     fun tac {prems, context} =
    62       rewrite_goals_tac defs THEN
    63       EVERY (tacs {prems = map (rewrite_rule defs) prems, context = context})
    64   in Goal.prove_global thy [] asms prop tac end;
    65 
    66 fun pg' thy defs t tacsf =
    67   let
    68     fun tacs {prems, context} =
    69       if null prems then tacsf context
    70       else cut_facts_tac prems 1 :: tacsf context;
    71   in pg'' thy defs t tacs end;
    72 
    73 (* FIXME!!!!!!!!! *)
    74 (* We should NEVER re-parse variable names as strings! *)
    75 (* The names can conflict with existing constants or other syntax! *)
    76 fun case_UU_tac ctxt rews i v =
    77   InductTacs.case_tac ctxt (v^"=UU") i THEN
    78   asm_simp_tac (HOLCF_ss addsimps rews) i;
    79 
    80 (* ----- general proofs ----------------------------------------------------- *)
    81 
    82 val all2E = @{lemma "!x y . P x y ==> (P x y ==> R) ==> R" by simp}
    83 
    84 fun theorems
    85     (((dname, _), cons) : eq, eqs : eq list)
    86     (dom_eqn : typ * (binding * (bool * binding option * typ) list * mixfix) list)
    87     (iso_info : Domain_Take_Proofs.iso_info)
    88     (thy : theory) =
    89 let
    90 
    91 val _ = message ("Proving isomorphism properties of domain "^dname^" ...");
    92 val map_tab = Domain_Take_Proofs.get_map_tab thy;
    93 
    94 
    95 (* ----- getting the axioms and definitions --------------------------------- *)
    96 
    97 val ax_abs_iso = #abs_inverse iso_info;
    98 val ax_rep_iso = #rep_inverse iso_info;
    99 
   100 val abs_const = #abs_const iso_info;
   101 val rep_const = #rep_const iso_info;
   102 
   103 local
   104   fun ga s dn = PureThy.get_thm thy (dn ^ "." ^ s);
   105 in
   106   val ax_take_0      = ga "take_0" dname;
   107   val ax_take_Suc    = ga "take_Suc" dname;
   108   val ax_take_strict = ga "take_strict" dname;
   109 end; (* local *)
   110 
   111 (* ----- define constructors ------------------------------------------------ *)
   112 
   113 val (result, thy) =
   114   Domain_Constructors.add_domain_constructors
   115     (Long_Name.base_name dname) (snd dom_eqn) iso_info thy;
   116 
   117 val con_appls = #con_betas result;
   118 val {exhaust, casedist, ...} = result;
   119 val {con_compacts, con_rews, inverts, injects, dist_les, dist_eqs, ...} = result;
   120 val {sel_rews, ...} = result;
   121 val when_rews = #cases result;
   122 val when_strict = hd when_rews;
   123 val dis_rews = #dis_rews result;
   124 val mat_rews = #match_rews result;
   125 val pat_rews = #pat_rews result;
   126 
   127 (* ----- theorems concerning the isomorphism -------------------------------- *)
   128 
   129 val pg = pg' thy;
   130 
   131 val retraction_strict = @{thm retraction_strict};
   132 val abs_strict = ax_rep_iso RS (allI RS retraction_strict);
   133 val rep_strict = ax_abs_iso RS (allI RS retraction_strict);
   134 val iso_rews = map Drule.export_without_context [ax_abs_iso, ax_rep_iso, abs_strict, rep_strict];
   135 
   136 (* ----- theorems concerning one induction step ----------------------------- *)
   137 
   138 local
   139   fun dc_take dn = %%:(dn^"_take");
   140   val dnames = map (fst o fst) eqs;
   141   val deflation_thms = Domain_Take_Proofs.get_deflation_thms thy;
   142   fun get_deflation_take dn = PureThy.get_thm thy (dn ^ ".deflation_take");
   143   val axs_deflation_take = map get_deflation_take dnames;
   144 
   145   fun copy_of_dtyp tab r dt =
   146       if Datatype_Aux.is_rec_type dt then copy tab r dt else ID
   147   and copy tab r (Datatype_Aux.DtRec i) = r i
   148     | copy tab r (Datatype_Aux.DtTFree a) = ID
   149     | copy tab r (Datatype_Aux.DtType (c, ds)) =
   150       case Symtab.lookup tab c of
   151         SOME f => list_ccomb (%%:f, map (copy_of_dtyp tab r) ds)
   152       | NONE => (warning ("copy_of_dtyp: unknown type constructor " ^ c); ID);
   153 
   154   fun one_take_app (con, args) =
   155     let
   156       fun mk_take n = dc_take (List.nth (dnames, n)) $ %:"n";
   157       fun one_rhs arg =
   158           if Datatype_Aux.is_rec_type (dtyp_of arg)
   159           then copy_of_dtyp map_tab
   160                  mk_take (dtyp_of arg) ` (%# arg)
   161           else (%# arg);
   162       val lhs = (dc_take dname $ (%%:"Suc" $ %:"n"))`(con_app con args);
   163       val rhs = con_app2 con one_rhs args;
   164       val goal = mk_trp (lhs === rhs);
   165       val rules =
   166           [ax_take_Suc, ax_abs_iso, @{thm cfcomp2}]
   167           @ @{thms take_con_rules ID1 deflation_strict}
   168           @ deflation_thms @ axs_deflation_take;
   169       val tacs = [simp_tac (HOL_basic_ss addsimps rules) 1];
   170     in pg con_appls goal (K tacs) end;
   171   val take_apps = map one_take_app cons;
   172 in
   173   val take_rews = ax_take_0 :: ax_take_strict :: take_apps;
   174 end;
   175 
   176 val case_ns =
   177     "bottom" :: map (fn (b,_,_) => Binding.name_of b) (snd dom_eqn);
   178 
   179 in
   180   thy
   181     |> Sign.add_path (Long_Name.base_name dname)
   182     |> snd o PureThy.add_thmss [
   183         ((Binding.name "iso_rews"  , iso_rews    ), [Simplifier.simp_add]),
   184         ((Binding.name "exhaust"   , [exhaust]   ), []),
   185         ((Binding.name "casedist"  , [casedist]  ),
   186          [Rule_Cases.case_names case_ns, Induct.cases_type dname]),
   187         ((Binding.name "when_rews" , when_rews   ), [Simplifier.simp_add]),
   188         ((Binding.name "compacts"  , con_compacts), [Simplifier.simp_add]),
   189         ((Binding.name "con_rews"  , con_rews    ),
   190          [Simplifier.simp_add, Fixrec.fixrec_simp_add]),
   191         ((Binding.name "sel_rews"  , sel_rews    ), [Simplifier.simp_add]),
   192         ((Binding.name "dis_rews"  , dis_rews    ), [Simplifier.simp_add]),
   193         ((Binding.name "pat_rews"  , pat_rews    ), [Simplifier.simp_add]),
   194         ((Binding.name "dist_les"  , dist_les    ), [Simplifier.simp_add]),
   195         ((Binding.name "dist_eqs"  , dist_eqs    ), [Simplifier.simp_add]),
   196         ((Binding.name "inverts"   , inverts     ), [Simplifier.simp_add]),
   197         ((Binding.name "injects"   , injects     ), [Simplifier.simp_add]),
   198         ((Binding.name "take_rews" , take_rews   ), [Simplifier.simp_add]),
   199         ((Binding.name "match_rews", mat_rews    ),
   200          [Simplifier.simp_add, Fixrec.fixrec_simp_add])]
   201     |> Sign.parent_path
   202     |> pair (iso_rews @ when_rews @ con_rews @ sel_rews @ dis_rews @
   203         pat_rews @ dist_les @ dist_eqs)
   204 end; (* let *)
   205 
   206 (******************************************************************************)
   207 (****************************** induction rules *******************************)
   208 (******************************************************************************)
   209 
   210 fun prove_induction
   211     (comp_dnam, eqs : eq list)
   212     (take_lemmas : thm list)
   213     (axs_reach : thm list)
   214     (take_rews : thm list)
   215     (take_info : Domain_Take_Proofs.take_info)
   216     (thy : theory) =
   217 let
   218   val dnames = map (fst o fst) eqs;
   219   val conss  = map  snd        eqs;
   220   fun dc_take dn = %%:(dn^"_take");
   221   val x_name = idx_name dnames "x"; 
   222   val P_name = idx_name dnames "P";
   223   val pg = pg' thy;
   224 
   225   local
   226     fun ga s dn = PureThy.get_thm thy (dn ^ "." ^ s);
   227     fun gts s dn = PureThy.get_thms thy (dn ^ "." ^ s);
   228   in
   229     val axs_rep_iso = map (ga "rep_iso") dnames;
   230     val axs_abs_iso = map (ga "abs_iso") dnames;
   231     val axs_chain_take = map (ga "chain_take") dnames;
   232     val lub_take_thms = map (ga "lub_take") dnames;
   233     val axs_finite_def = map (ga "finite_def") dnames;
   234     val cases = map (ga  "casedist" ) dnames;
   235     val con_rews  = maps (gts "con_rews" ) dnames;
   236   end;
   237 
   238   val {take_0_thms, take_Suc_thms, ...} = take_info;
   239 
   240   fun one_con p (con, args) =
   241     let
   242       val P_names = map P_name (1 upto (length dnames));
   243       val vns = Name.variant_list P_names (map vname args);
   244       val nonlazy_vns = map snd (filter_out (is_lazy o fst) (args ~~ vns));
   245       fun ind_hyp arg = %:(P_name (1 + rec_of arg)) $ bound_arg args arg;
   246       val t1 = mk_trp (%:p $ con_app2 con (bound_arg args) args);
   247       val t2 = lift ind_hyp (filter is_rec args, t1);
   248       val t3 = lift_defined (bound_arg vns) (nonlazy_vns, t2);
   249     in Library.foldr mk_All (vns, t3) end;
   250 
   251   fun one_eq ((p, cons), concl) =
   252     mk_trp (%:p $ UU) ===> Logic.list_implies (map (one_con p) cons, concl);
   253 
   254   fun ind_term concf = Library.foldr one_eq
   255     (mapn (fn n => fn x => (P_name n, x)) 1 conss,
   256      mk_trp (foldr1 mk_conj (mapn concf 1 dnames)));
   257   val take_ss = HOL_ss addsimps (@{thm Rep_CFun_strict1} :: take_rews);
   258   fun quant_tac ctxt i = EVERY
   259     (mapn (fn n => fn _ => res_inst_tac ctxt [(("x", 0), x_name n)] spec i) 1 dnames);
   260 
   261   fun ind_prems_tac prems = EVERY
   262     (maps (fn cons =>
   263       (resolve_tac prems 1 ::
   264         maps (fn (_,args) => 
   265           resolve_tac prems 1 ::
   266           map (K(atac 1)) (nonlazy args) @
   267           map (K(atac 1)) (filter is_rec args))
   268         cons))
   269       conss);
   270   local 
   271     (* check whether every/exists constructor of the n-th part of the equation:
   272        it has a possibly indirectly recursive argument that isn't/is possibly 
   273        indirectly lazy *)
   274     fun rec_to quant nfn rfn ns lazy_rec (n,cons) = quant (exists (fn arg => 
   275           is_rec arg andalso not(rec_of arg mem ns) andalso
   276           ((rec_of arg =  n andalso nfn(lazy_rec orelse is_lazy arg)) orelse 
   277             rec_of arg <> n andalso rec_to quant nfn rfn (rec_of arg::ns) 
   278               (lazy_rec orelse is_lazy arg) (n, (List.nth(conss,rec_of arg))))
   279           ) o snd) cons;
   280     fun all_rec_to ns  = rec_to forall not all_rec_to  ns;
   281     fun warn (n,cons) =
   282       if all_rec_to [] false (n,cons)
   283       then (warning ("domain "^List.nth(dnames,n)^" is empty!"); true)
   284       else false;
   285     fun lazy_rec_to ns = rec_to exists I  lazy_rec_to ns;
   286 
   287   in
   288     val n__eqs = mapn (fn n => fn (_,cons) => (n,cons)) 0 eqs;
   289     val is_emptys = map warn n__eqs;
   290     val is_finite = forall (not o lazy_rec_to [] false) n__eqs;
   291     val _ = if is_finite
   292             then message ("Proving finiteness rule for domain "^comp_dnam^" ...")
   293             else ();
   294   end;
   295   val _ = trace " Proving finite_ind...";
   296   val finite_ind =
   297     let
   298       fun concf n dn = %:(P_name n) $ (dc_take dn $ %:"n" `%(x_name n));
   299       val goal = ind_term concf;
   300 
   301       fun tacf {prems, context} =
   302         let
   303           val tacs1 = [
   304             quant_tac context 1,
   305             simp_tac HOL_ss 1,
   306             InductTacs.induct_tac context [[SOME "n"]] 1,
   307             simp_tac (take_ss addsimps prems) 1,
   308             TRY (safe_tac HOL_cs)];
   309           fun arg_tac arg =
   310                         (* FIXME! case_UU_tac *)
   311             case_UU_tac context (prems @ con_rews) 1
   312               (List.nth (dnames, rec_of arg) ^ "_take n$" ^ vname arg);
   313           fun con_tacs (con, args) = 
   314             asm_simp_tac take_ss 1 ::
   315             map arg_tac (filter is_nonlazy_rec args) @
   316             [resolve_tac prems 1] @
   317             map (K (atac 1)) (nonlazy args) @
   318             map (K (etac spec 1)) (filter is_rec args);
   319           fun cases_tacs (cons, cases) =
   320             res_inst_tac context [(("y", 0), "x")] cases 1 ::
   321             asm_simp_tac (take_ss addsimps prems) 1 ::
   322             maps con_tacs cons;
   323         in
   324           tacs1 @ maps cases_tacs (conss ~~ cases)
   325         end;
   326     in pg'' thy [] goal tacf
   327        handle ERROR _ => (warning "Proof of finite_ind failed."; TrueI)
   328     end;
   329 
   330 (* ----- theorems concerning finiteness and induction ----------------------- *)
   331 
   332   val global_ctxt = ProofContext.init thy;
   333 
   334   val _ = trace " Proving finites, ind...";
   335   val (finites, ind) =
   336   (
   337     if is_finite
   338     then (* finite case *)
   339       let
   340         val decisive_lemma =
   341           let
   342             val iso_locale_thms =
   343                 map2 (fn x => fn y => @{thm iso.intro} OF [x, y])
   344                 axs_abs_iso axs_rep_iso;
   345             val decisive_abs_rep_thms =
   346                 map (fn x => @{thm decisive_abs_rep} OF [x])
   347                 iso_locale_thms;
   348             val n = Free ("n", @{typ nat});
   349             fun mk_decisive t = %%: @{const_name decisive} $ t;
   350             fun f dn = mk_decisive (dc_take dn $ n);
   351             val goal = mk_trp (foldr1 mk_conj (map f dnames));
   352             val rules0 = @{thm decisive_bottom} :: take_0_thms;
   353             val rules1 =
   354                 take_Suc_thms @ decisive_abs_rep_thms
   355                 @ @{thms decisive_ID decisive_ssum_map decisive_sprod_map};
   356             val tacs = [
   357                 rtac @{thm nat.induct} 1,
   358                 simp_tac (HOL_ss addsimps rules0) 1,
   359                 asm_simp_tac (HOL_ss addsimps rules1) 1];
   360           in pg [] goal (K tacs) end;
   361         fun take_enough dn = mk_ex ("n",dc_take dn $ Bound 0 ` %:"x" === %:"x");
   362         fun one_finite (dn, decisive_thm) =
   363           let
   364             val goal = mk_trp (%%:(dn^"_finite") $ %:"x");
   365             val tacs = [
   366                 rtac @{thm lub_ID_finite} 1,
   367                 resolve_tac axs_chain_take 1,
   368                 resolve_tac lub_take_thms 1,
   369                 rtac decisive_thm 1];
   370           in pg axs_finite_def goal (K tacs) end;
   371 
   372         val _ = trace " Proving finites";
   373         val finites = map one_finite (dnames ~~ atomize global_ctxt decisive_lemma);
   374         val _ = trace " Proving ind";
   375         val ind =
   376           let
   377             fun concf n dn = %:(P_name n) $ %:(x_name n);
   378             fun tacf {prems, context} =
   379               let
   380                 fun finite_tacs (finite, fin_ind) = [
   381                   rtac(rewrite_rule axs_finite_def finite RS exE)1,
   382                   etac subst 1,
   383                   rtac fin_ind 1,
   384                   ind_prems_tac prems];
   385               in
   386                 TRY (safe_tac HOL_cs) ::
   387                 maps finite_tacs (finites ~~ atomize global_ctxt finite_ind)
   388               end;
   389           in pg'' thy [] (ind_term concf) tacf end;
   390       in (finites, ind) end (* let *)
   391 
   392     else (* infinite case *)
   393       let
   394         fun one_finite n dn =
   395           read_instantiate global_ctxt [(("P", 0), dn ^ "_finite " ^ x_name n)] excluded_middle;
   396         val finites = mapn one_finite 1 dnames;
   397 
   398         val goal =
   399           let
   400             fun one_adm n _ = mk_trp (mk_adm (%:(P_name n)));
   401             fun concf n dn = %:(P_name n) $ %:(x_name n);
   402           in Logic.list_implies (mapn one_adm 1 dnames, ind_term concf) end;
   403         val cont_rules =
   404             @{thms cont_id cont_const cont2cont_Rep_CFun
   405                    cont2cont_fst cont2cont_snd};
   406         val subgoal =
   407           let fun p n dn = %:(P_name n) $ (dc_take dn $ Bound 0 `%(x_name n));
   408           in mk_trp (mk_all ("n", foldr1 mk_conj (mapn p 1 dnames))) end;
   409         val subgoal' = legacy_infer_term thy subgoal;
   410         fun tacf {prems, context} =
   411           let
   412             val subtac =
   413                 EVERY [rtac allI 1, rtac finite_ind 1, ind_prems_tac prems];
   414             val subthm = Goal.prove context [] [] subgoal' (K subtac);
   415           in
   416             map (fn ax_reach => rtac (ax_reach RS subst) 1) axs_reach @ [
   417             cut_facts_tac (subthm :: take (length dnames) prems) 1,
   418             REPEAT (rtac @{thm conjI} 1 ORELSE
   419                     EVERY [etac @{thm admD [OF _ ch2ch_Rep_CFunL]} 1,
   420                            resolve_tac axs_chain_take 1,
   421                            asm_simp_tac HOL_basic_ss 1])
   422             ]
   423           end;
   424         val ind = (pg'' thy [] goal tacf
   425           handle ERROR _ =>
   426             (warning "Cannot prove infinite induction rule"; TrueI)
   427                   );
   428       in (finites, ind) end
   429   )
   430       handle THM _ =>
   431              (warning "Induction proofs failed (THM raised)."; ([], TrueI))
   432            | ERROR _ =>
   433              (warning "Cannot prove induction rule"; ([], TrueI));
   434 
   435 val case_ns =
   436   let
   437     val bottoms =
   438         if length dnames = 1 then ["bottom"] else
   439         map (fn s => "bottom_" ^ Long_Name.base_name s) dnames;
   440     fun one_eq bot (_,cons) =
   441           bot :: map (fn (c,_) => Long_Name.base_name c) cons;
   442   in flat (map2 one_eq bottoms eqs) end;
   443 
   444 val inducts = Project_Rule.projections (ProofContext.init thy) ind;
   445 fun ind_rule (dname, rule) =
   446     ((Binding.empty, [rule]),
   447      [Rule_Cases.case_names case_ns, Induct.induct_type dname]);
   448 
   449 val induct_failed = (Thm.prop_of ind = Thm.prop_of TrueI);
   450 
   451 in thy |> Sign.add_path comp_dnam
   452        |> snd o PureThy.add_thmss [
   453            ((Binding.name "finites"    , finites     ), []),
   454            ((Binding.name "finite_ind" , [finite_ind]), []),
   455            ((Binding.name "ind"        , [ind]       ), [])]
   456        |> (if induct_failed then I
   457            else snd o PureThy.add_thmss (map ind_rule (dnames ~~ inducts)))
   458        |> Sign.parent_path
   459 end; (* prove_induction *)
   460 
   461 (******************************************************************************)
   462 (************************ bisimulation and coinduction ************************)
   463 (******************************************************************************)
   464 
   465 fun prove_coinduction
   466     (comp_dnam, eqs : eq list)
   467     (take_lemmas : thm list)
   468     (thy : theory) : theory =
   469 let
   470 
   471 val dnames = map (fst o fst) eqs;
   472 val comp_dname = Sign.full_bname thy comp_dnam;
   473 fun dc_take dn = %%:(dn^"_take");
   474 val x_name = idx_name dnames "x"; 
   475 val n_eqs = length eqs;
   476 
   477 val take_rews =
   478     maps (fn dn => PureThy.get_thms thy (dn ^ ".take_rews")) dnames;
   479 
   480 (* ----- define bisimulation predicate -------------------------------------- *)
   481 
   482 local
   483   open HOLCF_Library
   484   val dtypes  = map (Type o fst) eqs;
   485   val relprod = mk_tupleT (map (fn tp => tp --> tp --> boolT) dtypes);
   486   val bisim_bind = Binding.name (comp_dnam ^ "_bisim");
   487   val bisim_type = relprod --> boolT;
   488 in
   489   val (bisim_const, thy) =
   490       Sign.declare_const ((bisim_bind, bisim_type), NoSyn) thy;
   491 end;
   492 
   493 local
   494 
   495   fun legacy_infer_term thy t =
   496       singleton (Syntax.check_terms (ProofContext.init thy)) (Sign.intern_term thy t);
   497   fun legacy_infer_prop thy t = legacy_infer_term thy (TypeInfer.constrain propT t);
   498   fun infer_props thy = map (apsnd (legacy_infer_prop thy));
   499   fun add_defs_i x = PureThy.add_defs false (map Thm.no_attributes x);
   500   fun add_defs_infer defs thy = add_defs_i (infer_props thy defs) thy;
   501 
   502   val comp_dname = Sign.full_bname thy comp_dnam;
   503   val dnames = map (fst o fst) eqs;
   504   val x_name = idx_name dnames "x"; 
   505 
   506   fun one_con (con, args) =
   507     let
   508       val nonrec_args = filter_out is_rec args;
   509       val    rec_args = filter is_rec args;
   510       val    recs_cnt = length rec_args;
   511       val allargs     = nonrec_args @ rec_args
   512                         @ map (upd_vname (fn s=> s^"'")) rec_args;
   513       val allvns      = map vname allargs;
   514       fun vname_arg s arg = if is_rec arg then vname arg^s else vname arg;
   515       val vns1        = map (vname_arg "" ) args;
   516       val vns2        = map (vname_arg "'") args;
   517       val allargs_cnt = length nonrec_args + 2*recs_cnt;
   518       val rec_idxs    = (recs_cnt-1) downto 0;
   519       val nonlazy_idxs = map snd (filter_out (fn (arg,_) => is_lazy arg)
   520                                              (allargs~~((allargs_cnt-1) downto 0)));
   521       fun rel_app i ra = proj (Bound(allargs_cnt+2)) eqs (rec_of ra) $ 
   522                               Bound (2*recs_cnt-i) $ Bound (recs_cnt-i);
   523       val capps =
   524           List.foldr
   525             mk_conj
   526             (mk_conj(
   527              Bound(allargs_cnt+1)===list_ccomb(%%:con,map (bound_arg allvns) vns1),
   528              Bound(allargs_cnt+0)===list_ccomb(%%:con,map (bound_arg allvns) vns2)))
   529             (mapn rel_app 1 rec_args);
   530     in
   531       List.foldr
   532         mk_ex
   533         (Library.foldr mk_conj
   534                        (map (defined o Bound) nonlazy_idxs,capps)) allvns
   535     end;
   536   fun one_comp n (_,cons) =
   537       mk_all (x_name(n+1),
   538       mk_all (x_name(n+1)^"'",
   539       mk_imp (proj (Bound 2) eqs n $ Bound 1 $ Bound 0,
   540       foldr1 mk_disj (mk_conj(Bound 1 === UU,Bound 0 === UU)
   541                       ::map one_con cons))));
   542   val bisim_eqn =
   543       %%:(comp_dname^"_bisim") ==
   544          mk_lam("R", foldr1 mk_conj (mapn one_comp 0 eqs));
   545 
   546 in
   547   val ([ax_bisim_def], thy) =
   548       thy
   549         |> Sign.add_path comp_dnam
   550         |> add_defs_infer [(Binding.name "bisim_def", bisim_eqn)]
   551         ||> Sign.parent_path;
   552 end; (* local *)
   553 
   554 (* ----- theorem concerning coinduction ------------------------------------- *)
   555 
   556 local
   557   val pg = pg' thy;
   558   val xs = mapn (fn n => K (x_name n)) 1 dnames;
   559   fun bnd_arg n i = Bound(2*(n_eqs - n)-i-1);
   560   val take_ss = HOL_ss addsimps (@{thm Rep_CFun_strict1} :: take_rews);
   561   val sproj = prj (fn s => K("fst("^s^")")) (fn s => K("snd("^s^")"));
   562   val _ = trace " Proving coind_lemma...";
   563   val coind_lemma =
   564     let
   565       fun mk_prj n _ = proj (%:"R") eqs n $ bnd_arg n 0 $ bnd_arg n 1;
   566       fun mk_eqn n dn =
   567         (dc_take dn $ %:"n" ` bnd_arg n 0) ===
   568         (dc_take dn $ %:"n" ` bnd_arg n 1);
   569       fun mk_all2 (x,t) = mk_all (x, mk_all (x^"'", t));
   570       val goal =
   571         mk_trp (mk_imp (%%:(comp_dname^"_bisim") $ %:"R",
   572           Library.foldr mk_all2 (xs,
   573             Library.foldr mk_imp (mapn mk_prj 0 dnames,
   574               foldr1 mk_conj (mapn mk_eqn 0 dnames)))));
   575       fun x_tacs ctxt n x = [
   576         rotate_tac (n+1) 1,
   577         etac all2E 1,
   578         eres_inst_tac ctxt [(("P", 1), sproj "R" eqs n^" "^x^" "^x^"'")] (mp RS disjE) 1,
   579         TRY (safe_tac HOL_cs),
   580         REPEAT (CHANGED (asm_simp_tac take_ss 1))];
   581       fun tacs ctxt = [
   582         rtac impI 1,
   583         InductTacs.induct_tac ctxt [[SOME "n"]] 1,
   584         simp_tac take_ss 1,
   585         safe_tac HOL_cs] @
   586         flat (mapn (x_tacs ctxt) 0 xs);
   587     in pg [ax_bisim_def] goal tacs end;
   588 in
   589   val _ = trace " Proving coind...";
   590   val coind = 
   591     let
   592       fun mk_prj n x = mk_trp (proj (%:"R") eqs n $ %:x $ %:(x^"'"));
   593       fun mk_eqn x = %:x === %:(x^"'");
   594       val goal =
   595         mk_trp (%%:(comp_dname^"_bisim") $ %:"R") ===>
   596           Logic.list_implies (mapn mk_prj 0 xs,
   597             mk_trp (foldr1 mk_conj (map mk_eqn xs)));
   598       val tacs =
   599         TRY (safe_tac HOL_cs) ::
   600         maps (fn take_lemma => [
   601           rtac take_lemma 1,
   602           cut_facts_tac [coind_lemma] 1,
   603           fast_tac HOL_cs 1])
   604         take_lemmas;
   605     in pg [] goal (K tacs) end;
   606 end; (* local *)
   607 
   608 in thy |> Sign.add_path comp_dnam
   609        |> snd o PureThy.add_thmss [((Binding.name "coind", [coind]), [])]
   610        |> Sign.parent_path
   611 end; (* let *)
   612 
   613 fun comp_theorems
   614     (comp_dnam : string, eqs : eq list)
   615     (take_info : Domain_Take_Proofs.take_info)
   616     (take_induct_info : Domain_Take_Proofs.take_induct_info)
   617     (thy : theory) =
   618 let
   619 val map_tab = Domain_Take_Proofs.get_map_tab thy;
   620 
   621 val dnames = map (fst o fst) eqs;
   622 val comp_dname = Sign.full_bname thy comp_dnam;
   623 
   624 (* ----- getting the composite axiom and definitions ------------------------ *)
   625 
   626 (* Test for indirect recursion *)
   627 local
   628   fun indirect_arg arg =
   629       rec_of arg = ~1 andalso Datatype_Aux.is_rec_type (dtyp_of arg);
   630   fun indirect_con (_, args) = exists indirect_arg args;
   631   fun indirect_eq (_, cons) = exists indirect_con cons;
   632 in
   633   val is_indirect = exists indirect_eq eqs;
   634   val _ =
   635       if is_indirect
   636       then message "Indirect recursion detected, skipping proofs of (co)induction rules"
   637       else message ("Proving induction properties of domain "^comp_dname^" ...");
   638 end;
   639 
   640 (* theorems about take *)
   641 
   642 val take_lemmas = #take_lemma_thms take_induct_info;
   643 val axs_reach = #reach_thms take_induct_info;
   644 
   645 val take_rews =
   646     maps (fn dn => PureThy.get_thms thy (dn ^ ".take_rews")) dnames;
   647 
   648 (* prove induction rules, unless definition is indirect recursive *)
   649 val thy =
   650     if is_indirect then thy else
   651     prove_induction (comp_dnam, eqs) take_lemmas axs_reach take_rews take_info thy;
   652 
   653 val thy =
   654     if is_indirect then thy else
   655     prove_coinduction (comp_dnam, eqs) take_lemmas thy;
   656 
   657 in
   658   (take_rews, thy)
   659 end; (* let *)
   660 end; (* struct *)