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