src/HOL/BNF/Tools/bnf_fp_n2m_sugar.ML
author blanchet
Wed, 06 Nov 2013 10:35:30 +0100
changeset 55727 da9c620410f6
parent 55726 af814d24ee52
child 55728 d26b6b935a6f
permissions -rw-r--r--
take out even less aggressive generalization -- it's still too aggressive
blanchet@54440
     1
(*  Title:      HOL/BNF/Tools/bnf_fp_n2m_sugar.ML
blanchet@54440
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@54440
     3
    Copyright   2013
blanchet@54440
     4
blanchet@54440
     5
Suggared flattening of nested to mutual (co)recursion.
blanchet@54440
     6
*)
blanchet@54440
     7
blanchet@54440
     8
signature BNF_FP_N2M_SUGAR =
blanchet@54440
     9
sig
blanchet@55695
    10
  val unfold_let: term -> term
blanchet@55695
    11
  val dest_map: Proof.context -> string -> term -> term * term list
blanchet@55695
    12
blanchet@55146
    13
  val mutualize_fp_sugars: bool -> BNF_FP_Util.fp_kind -> binding list -> typ list ->
blanchet@54440
    14
    (term -> int list) -> term list list list list -> BNF_FP_Def_Sugar.fp_sugar list ->
blanchet@54883
    15
    local_theory ->
blanchet@54883
    16
    (BNF_FP_Def_Sugar.fp_sugar list
blanchet@54883
    17
     * (BNF_FP_Def_Sugar.lfp_sugar_thms option * BNF_FP_Def_Sugar.gfp_sugar_thms option))
blanchet@54883
    18
    * local_theory
blanchet@55719
    19
  val indexify_callsss: BNF_FP_Def_Sugar.fp_sugar -> (term * term list list) list ->
blanchet@55719
    20
    term list list list
blanchet@55146
    21
  val nested_to_mutual_fps: BNF_FP_Util.fp_kind -> binding list -> typ list -> (term -> int list) ->
blanchet@55146
    22
    (term * term list list) list list -> local_theory ->
blanchet@54883
    23
    (typ list * int list * BNF_FP_Def_Sugar.fp_sugar list
blanchet@54883
    24
     * (BNF_FP_Def_Sugar.lfp_sugar_thms option * BNF_FP_Def_Sugar.gfp_sugar_thms option))
blanchet@54883
    25
    * local_theory
blanchet@54440
    26
end;
blanchet@54440
    27
blanchet@54440
    28
structure BNF_FP_N2M_Sugar : BNF_FP_N2M_SUGAR =
blanchet@54440
    29
struct
blanchet@54440
    30
blanchet@55143
    31
open Ctr_Sugar
blanchet@54440
    32
open BNF_Util
blanchet@54440
    33
open BNF_Def
blanchet@54440
    34
open BNF_FP_Util
blanchet@54440
    35
open BNF_FP_Def_Sugar
blanchet@54440
    36
open BNF_FP_N2M
blanchet@54440
    37
blanchet@54440
    38
val n2mN = "n2m_"
blanchet@54440
    39
blanchet@55708
    40
type n2m_sugar = fp_sugar list * (lfp_sugar_thms option * gfp_sugar_thms option);
blanchet@55708
    41
blanchet@55708
    42
structure Data = Generic_Data
blanchet@55708
    43
(
blanchet@55708
    44
  type T = n2m_sugar Typtab.table;
blanchet@55708
    45
  val empty = Typtab.empty;
blanchet@55708
    46
  val extend = I;
blanchet@55708
    47
  val merge = Typtab.merge (eq_fst (eq_list eq_fp_sugar));
blanchet@55708
    48
);
blanchet@55708
    49
blanchet@55708
    50
fun morph_n2m_sugar phi (fp_sugars, (lfp_sugar_thms_opt, gfp_sugar_thms_opt)) =
blanchet@55708
    51
  (map (morph_fp_sugar phi) fp_sugars,
blanchet@55708
    52
   (Option.map (morph_lfp_sugar_thms phi) lfp_sugar_thms_opt,
blanchet@55708
    53
    Option.map (morph_gfp_sugar_thms phi) gfp_sugar_thms_opt));
blanchet@55708
    54
blanchet@55708
    55
val transfer_n2m_sugar =
blanchet@55708
    56
  morph_n2m_sugar o Morphism.thm_morphism o Thm.transfer o Proof_Context.theory_of;
blanchet@55708
    57
blanchet@55708
    58
fun n2m_sugar_of ctxt =
blanchet@55708
    59
  Typtab.lookup (Data.get (Context.Proof ctxt))
blanchet@55708
    60
  #> Option.map (transfer_n2m_sugar ctxt);
blanchet@55708
    61
blanchet@55708
    62
fun register_n2m_sugar key n2m_sugar =
blanchet@55708
    63
  Local_Theory.declaration {syntax = false, pervasive = false}
blanchet@55708
    64
    (fn phi => Data.map (Typtab.default (key, morph_n2m_sugar phi n2m_sugar)));
blanchet@55708
    65
blanchet@55695
    66
fun unfold_let (Const (@{const_name Let}, _) $ arg1 $ arg2) = unfold_let (betapply (arg2, arg1))
blanchet@55695
    67
  | unfold_let (Const (@{const_name prod_case}, _) $ t) =
blanchet@55695
    68
    (case unfold_let t of
blanchet@55695
    69
      t' as Abs (s1, T1, Abs (s2, T2, _)) =>
blanchet@55695
    70
      let
blanchet@55695
    71
        val x = (s1 ^ s2, Term.maxidx_of_term t + 1);
blanchet@55695
    72
        val v = Var (x, HOLogic.mk_prodT (T1, T2));
blanchet@55695
    73
      in
blanchet@55695
    74
        lambda v (unfold_let (betapplys (t', [HOLogic.mk_fst v, HOLogic.mk_snd v])))
blanchet@55695
    75
      end
blanchet@55695
    76
    | _ => t)
blanchet@55695
    77
  | unfold_let (t $ u) = betapply (unfold_let t, unfold_let u)
blanchet@55695
    78
  | unfold_let (Abs (s, T, t)) = Abs (s, T, unfold_let t)
blanchet@55695
    79
  | unfold_let t = t;
blanchet@55695
    80
blanchet@55695
    81
fun mk_map_pattern ctxt s =
blanchet@55695
    82
  let
blanchet@55695
    83
    val bnf = the (bnf_of ctxt s);
blanchet@55695
    84
    val mapx = map_of_bnf bnf;
blanchet@55695
    85
    val live = live_of_bnf bnf;
blanchet@55695
    86
    val (f_Ts, _) = strip_typeN live (fastype_of mapx);
blanchet@55717
    87
    val fs = map_index (fn (i, T) => Var (("?f", i), T)) f_Ts;
blanchet@55695
    88
  in
blanchet@55695
    89
    (mapx, betapplys (mapx, fs))
blanchet@55695
    90
  end;
blanchet@55695
    91
blanchet@55695
    92
fun dest_map ctxt s call =
blanchet@55695
    93
  let
blanchet@55695
    94
    val (map0, pat) = mk_map_pattern ctxt s;
blanchet@55695
    95
    val (_, tenv) = fo_match ctxt call pat;
blanchet@55695
    96
  in
blanchet@55695
    97
    (map0, Vartab.fold_rev (fn (_, (_, f)) => cons f) tenv [])
blanchet@55695
    98
  end;
blanchet@55695
    99
blanchet@55695
   100
fun dest_abs_or_applied_map_or_ctr _ _ (Abs (_, _, t)) = (Term.dummy, [t])
blanchet@55695
   101
  | dest_abs_or_applied_map_or_ctr ctxt s (t as t1 $ _) =
blanchet@55695
   102
    (case try (dest_map ctxt s) t1 of
blanchet@55695
   103
      SOME res => res
blanchet@55695
   104
    | NONE =>
blanchet@55695
   105
      let
blanchet@55695
   106
        val thy = Proof_Context.theory_of ctxt;
blanchet@55722
   107
        val map_thms = flat (#mapss (the (fp_sugar_of ctxt s)));
blanchet@55695
   108
        val map_thms' = map (fn thm => thm RS sym RS eq_reflection) map_thms;
blanchet@55695
   109
        val t' = Raw_Simplifier.rewrite_term thy map_thms' [] t;
blanchet@55695
   110
      in
blanchet@55722
   111
        if t aconv t' then raise Fail "dest_abs_or_applied_map_or_ctr"
blanchet@55695
   112
        else dest_map ctxt s (fst (dest_comb t'))
blanchet@55695
   113
      end);
blanchet@55691
   114
blanchet@55697
   115
fun map_partition f xs =
blanchet@55697
   116
  fold_rev (fn x => fn (ys, (good, bad)) =>
blanchet@55697
   117
      case f x of SOME y => (y :: ys, (x :: good, bad)) | NONE => (ys, (good, x :: bad)))
blanchet@55697
   118
    xs ([], ([], []));
blanchet@55697
   119
blanchet@55708
   120
fun key_of_fp_eqs fp fpTs fp_eqs =
blanchet@55719
   121
  Type (fp_case fp "l" "g", fpTs @ maps (fn (x, T) => [TFree x, T]) fp_eqs);
blanchet@55708
   122
blanchet@54440
   123
(* TODO: test with sort constraints on As *)
blanchet@54440
   124
(* TODO: use right sorting order for "fp_sort" w.r.t. original BNFs (?) -- treat new variables
blanchet@54440
   125
   as deads? *)
blanchet@55697
   126
fun mutualize_fp_sugars has_nested fp bs fpTs get_indices callssss fp_sugars0 no_defs_lthy0 =
blanchet@55705
   127
  if has_nested then
blanchet@54440
   128
    let
blanchet@54440
   129
      val thy = Proof_Context.theory_of no_defs_lthy0;
blanchet@54440
   130
blanchet@54440
   131
      val qsotm = quote o Syntax.string_of_term no_defs_lthy0;
blanchet@54440
   132
blanchet@55697
   133
      fun incompatible_calls t1 t2 =
blanchet@55697
   134
        error ("Incompatible " ^ co_prefix fp ^ "recursive calls: " ^ qsotm t1 ^ " vs. " ^
blanchet@55697
   135
          qsotm t2);
blanchet@55697
   136
blanchet@54440
   137
      val b_names = map Binding.name_of bs;
blanchet@54440
   138
      val fp_b_names = map base_name_of_typ fpTs;
blanchet@54440
   139
blanchet@54440
   140
      val nn = length fpTs;
blanchet@54440
   141
wenzelm@55111
   142
      fun target_ctr_sugar_of_fp_sugar fpT ({T, index, ctr_sugars, ...} : fp_sugar) =
blanchet@54440
   143
        let
blanchet@54440
   144
          val rho = Vartab.fold (cons o apsnd snd) (Sign.typ_match thy (T, fpT) Vartab.empty) [];
blanchet@54440
   145
          val phi = Morphism.term_morphism (Term.subst_TVars rho);
blanchet@54440
   146
        in
blanchet@54440
   147
          morph_ctr_sugar phi (nth ctr_sugars index)
blanchet@54440
   148
        end;
blanchet@54440
   149
blanchet@54440
   150
      val ctr_defss = map (of_fp_sugar #ctr_defss) fp_sugars0;
blanchet@54613
   151
      val mapss = map (of_fp_sugar #mapss) fp_sugars0;
blanchet@54440
   152
      val ctr_sugars0 = map2 target_ctr_sugar_of_fp_sugar fpTs fp_sugars0;
blanchet@54440
   153
blanchet@54440
   154
      val ctrss = map #ctrs ctr_sugars0;
blanchet@54440
   155
      val ctr_Tss = map (map fastype_of) ctrss;
blanchet@54440
   156
blanchet@54440
   157
      val As' = fold (fold Term.add_tfreesT) ctr_Tss [];
blanchet@54440
   158
      val As = map TFree As';
blanchet@54440
   159
blanchet@54440
   160
      val ((Cs, Xs), no_defs_lthy) =
blanchet@54440
   161
        no_defs_lthy0
blanchet@54440
   162
        |> fold Variable.declare_typ As
blanchet@54440
   163
        |> mk_TFrees nn
blanchet@54440
   164
        ||>> variant_tfrees fp_b_names;
blanchet@54440
   165
blanchet@55697
   166
      fun check_call_dead live_call call =
blanchet@55697
   167
        if null (get_indices call) then () else incompatible_calls live_call call;
blanchet@55697
   168
blanchet@55707
   169
      fun freeze_fpTs_simple (T as Type (s, Ts)) =
blanchet@55705
   170
          (case find_index (curry (op =) T) fpTs of
blanchet@55707
   171
            ~1 => Type (s, map freeze_fpTs_simple Ts)
blanchet@55705
   172
          | kk => nth Xs kk)
blanchet@55707
   173
        | freeze_fpTs_simple T = T;
blanchet@55705
   174
blanchet@55707
   175
      fun freeze_fpTs_map (callss, (live_call :: _, dead_calls)) s Ts =
blanchet@55697
   176
        (List.app (check_call_dead live_call) dead_calls;
blanchet@55707
   177
         Type (s, map2 freeze_fpTs (flatten_type_args_of_bnf (the (bnf_of no_defs_lthy s)) []
blanchet@55697
   178
           (transpose callss)) Ts))
blanchet@55707
   179
      and freeze_fpTs calls (T as Type (s, Ts)) =
blanchet@55697
   180
          (case map_partition (try (snd o dest_map no_defs_lthy s)) calls of
blanchet@55697
   181
            ([], _) =>
blanchet@55697
   182
            (case map_partition (try (snd o dest_abs_or_applied_map_or_ctr no_defs_lthy s)) calls of
blanchet@55707
   183
              ([], _) => freeze_fpTs_simple T
blanchet@55707
   184
            | callsp => freeze_fpTs_map callsp s Ts)
blanchet@55707
   185
          | callsp => freeze_fpTs_map callsp s Ts)
blanchet@55707
   186
        | freeze_fpTs _ T = T;
blanchet@54440
   187
blanchet@54440
   188
      val ctr_Tsss = map (map binder_types) ctr_Tss;
blanchet@55707
   189
      val ctrXs_Tsss = map2 (map2 (map2 freeze_fpTs)) callssss ctr_Tsss;
blanchet@54440
   190
      val ctrXs_sum_prod_Ts = map (mk_sumTN_balanced o map HOLogic.mk_tupleT) ctrXs_Tsss;
blanchet@54440
   191
      val Ts = map (body_type o hd) ctr_Tss;
blanchet@54440
   192
blanchet@54440
   193
      val ns = map length ctr_Tsss;
blanchet@54440
   194
      val kss = map (fn n => 1 upto n) ns;
blanchet@54440
   195
      val mss = map (map length) ctr_Tsss;
blanchet@54440
   196
blanchet@54440
   197
      val fp_eqs = map dest_TFree Xs ~~ ctrXs_sum_prod_Ts;
blanchet@55708
   198
      val key = key_of_fp_eqs fp fpTs fp_eqs;
blanchet@55708
   199
    in
blanchet@55708
   200
      (case n2m_sugar_of no_defs_lthy key of
blanchet@55708
   201
        SOME n2m_sugar => (n2m_sugar, no_defs_lthy)
blanchet@55708
   202
      | NONE =>
blanchet@55708
   203
        let
blanchet@55708
   204
          val base_fp_names = Name.variant_list [] fp_b_names;
blanchet@55708
   205
          val fp_bs = map2 (fn b_name => fn base_fp_name =>
blanchet@55708
   206
              Binding.qualify true b_name (Binding.name (n2mN ^ base_fp_name)))
blanchet@55708
   207
            b_names base_fp_names;
blanchet@54440
   208
blanchet@55708
   209
          val (pre_bnfs, (fp_res as {xtor_co_iterss = xtor_co_iterss0, xtor_co_induct,
blanchet@55708
   210
                 dtor_injects, dtor_ctors, xtor_co_iter_thmss, ...}, lthy)) =
blanchet@55708
   211
            fp_bnf (construct_mutualized_fp fp fpTs fp_sugars0) fp_bs As' fp_eqs no_defs_lthy;
blanchet@54440
   212
blanchet@55708
   213
          val nesting_bnfs = nesty_bnfs lthy ctrXs_Tsss As;
blanchet@55708
   214
          val nested_bnfs = nesty_bnfs lthy ctrXs_Tsss Xs;
blanchet@54440
   215
blanchet@55708
   216
          val ((xtor_co_iterss, iters_args_types, coiters_args_types), _) =
blanchet@55708
   217
            mk_co_iters_prelims fp ctr_Tsss fpTs Cs ns mss xtor_co_iterss0 lthy;
blanchet@54440
   218
blanchet@55708
   219
          fun mk_binding b suf = Binding.suffix_name ("_" ^ suf) b;
blanchet@54440
   220
blanchet@55708
   221
          val ((co_iterss, co_iter_defss), lthy) =
blanchet@55708
   222
            fold_map2 (fn b =>
blanchet@55708
   223
              (if fp = Least_FP then define_iters [foldN, recN] (the iters_args_types)
blanchet@55708
   224
               else define_coiters [unfoldN, corecN] (the coiters_args_types))
blanchet@55708
   225
                (mk_binding b) fpTs Cs) fp_bs xtor_co_iterss lthy
blanchet@55708
   226
            |>> split_list;
blanchet@54440
   227
blanchet@55708
   228
          val rho = tvar_subst thy Ts fpTs;
blanchet@55708
   229
          val ctr_sugar_phi =
blanchet@55708
   230
            Morphism.compose (Morphism.typ_morphism (Term.typ_subst_TVars rho))
blanchet@55708
   231
              (Morphism.term_morphism (Term.subst_TVars rho));
blanchet@55708
   232
          val inst_ctr_sugar = morph_ctr_sugar ctr_sugar_phi;
blanchet@54440
   233
blanchet@55708
   234
          val ctr_sugars = map inst_ctr_sugar ctr_sugars0;
blanchet@54440
   235
blanchet@55708
   236
          val ((co_inducts, un_fold_thmss, co_rec_thmss, disc_unfold_thmss, disc_corec_thmss,
blanchet@55708
   237
                sel_unfold_thmsss, sel_corec_thmsss), fp_sugar_thms) =
blanchet@55708
   238
            if fp = Least_FP then
blanchet@55708
   239
              derive_induct_iters_thms_for_types pre_bnfs (the iters_args_types) xtor_co_induct
blanchet@55708
   240
                xtor_co_iter_thmss nesting_bnfs nested_bnfs fpTs Cs Xs ctrXs_Tsss ctrss ctr_defss
blanchet@55708
   241
                co_iterss co_iter_defss lthy
blanchet@55708
   242
              |> `(fn ((_, induct, _), (fold_thmss, rec_thmss, _)) =>
blanchet@55708
   243
                ([induct], fold_thmss, rec_thmss, [], [], [], []))
blanchet@55708
   244
              ||> (fn info => (SOME info, NONE))
blanchet@55708
   245
            else
blanchet@55708
   246
              derive_coinduct_coiters_thms_for_types pre_bnfs (the coiters_args_types)
blanchet@55708
   247
                xtor_co_induct dtor_injects dtor_ctors xtor_co_iter_thmss nesting_bnfs fpTs Cs Xs
blanchet@55708
   248
                ctrXs_Tsss kss mss ns ctr_defss ctr_sugars co_iterss co_iter_defss
blanchet@55708
   249
                (Proof_Context.export lthy no_defs_lthy) lthy
blanchet@55708
   250
              |> `(fn ((coinduct_thms_pairs, _), (unfold_thmss, corec_thmss, _),
blanchet@55708
   251
                      (disc_unfold_thmss, disc_corec_thmss, _), _,
blanchet@55708
   252
                      (sel_unfold_thmsss, sel_corec_thmsss, _)) =>
blanchet@55708
   253
                (map snd coinduct_thms_pairs, unfold_thmss, corec_thmss, disc_unfold_thmss,
blanchet@55708
   254
                 disc_corec_thmss, sel_unfold_thmsss, sel_corec_thmsss))
blanchet@55708
   255
              ||> (fn info => (NONE, SOME info));
blanchet@54440
   256
blanchet@55708
   257
          val phi = Proof_Context.export_morphism no_defs_lthy no_defs_lthy0;
blanchet@54440
   258
blanchet@55708
   259
          fun mk_target_fp_sugar (kk, T) =
blanchet@55708
   260
            {T = T, fp = fp, index = kk, pre_bnfs = pre_bnfs, nested_bnfs = nested_bnfs,
blanchet@55708
   261
             nesting_bnfs = nesting_bnfs, fp_res = fp_res, ctr_defss = ctr_defss,
blanchet@55708
   262
             ctr_sugars = ctr_sugars, co_iterss = co_iterss, mapss = mapss, co_inducts = co_inducts,
blanchet@55708
   263
             co_iter_thmsss = transpose [un_fold_thmss, co_rec_thmss],
blanchet@55708
   264
             disc_co_itersss = transpose [disc_unfold_thmss, disc_corec_thmss],
blanchet@55708
   265
             sel_co_iterssss = transpose [sel_unfold_thmsss, sel_corec_thmsss]}
blanchet@55708
   266
            |> morph_fp_sugar phi;
blanchet@54440
   267
blanchet@55708
   268
          val n2m_sugar = (map_index mk_target_fp_sugar fpTs, fp_sugar_thms);
blanchet@55708
   269
        in
blanchet@55708
   270
          (n2m_sugar, lthy |> register_n2m_sugar key n2m_sugar)
blanchet@55708
   271
        end)
blanchet@54440
   272
    end
blanchet@54440
   273
  else
blanchet@54883
   274
    ((fp_sugars0, (NONE, NONE)), no_defs_lthy0);
blanchet@54440
   275
blanchet@54440
   276
fun indexify_callsss fp_sugar callsss =
blanchet@54440
   277
  let
blanchet@54440
   278
    val {ctrs, ...} = of_fp_sugar #ctr_sugars fp_sugar;
blanchet@54440
   279
    fun do_ctr ctr =
blanchet@54440
   280
      (case AList.lookup Term.aconv_untyped callsss ctr of
blanchet@54440
   281
        NONE => replicate (num_binder_types (fastype_of ctr)) []
blanchet@55695
   282
      | SOME callss => map (map (Envir.beta_eta_contract o unfold_let)) callss);
blanchet@54440
   283
  in
blanchet@54440
   284
    map do_ctr ctrs
blanchet@54440
   285
  end;
blanchet@54440
   286
blanchet@55146
   287
fun nested_to_mutual_fps fp actual_bs actual_Ts get_indices actual_callssss0 lthy =
blanchet@54440
   288
  let
blanchet@54440
   289
    val qsoty = quote o Syntax.string_of_typ lthy;
blanchet@54440
   290
    val qsotys = space_implode " or " o map qsoty;
blanchet@54440
   291
blanchet@55705
   292
    fun duplicate_datatype T = error (qsoty T ^ " is not mutually recursive with itself");
blanchet@54440
   293
    fun not_co_datatype0 T = error (qsoty T ^ " is not a " ^ co_prefix fp ^ "datatype");
blanchet@54440
   294
    fun not_co_datatype (T as Type (s, _)) =
blanchet@54440
   295
        if fp = Least_FP andalso
blanchet@54440
   296
           is_some (Datatype_Data.get_info (Proof_Context.theory_of lthy) s) then
blanchet@54440
   297
          error (qsoty T ^ " is not a new-style datatype (cf. \"datatype_new\")")
blanchet@54440
   298
        else
blanchet@54440
   299
          not_co_datatype0 T
blanchet@54440
   300
      | not_co_datatype T = not_co_datatype0 T;
blanchet@54440
   301
    fun not_mutually_nested_rec Ts1 Ts2 =
blanchet@54440
   302
      error (qsotys Ts1 ^ " is neither mutually recursive with nor nested recursive via " ^
blanchet@54440
   303
        qsotys Ts2);
blanchet@54440
   304
blanchet@55705
   305
    val _ = (case Library.duplicates (op =) actual_Ts of [] => () | T :: _ => duplicate_datatype T);
blanchet@55705
   306
blanchet@55725
   307
    val perm_actual_Ts as Type (_, tyargs0) :: _ =
blanchet@55718
   308
      sort (prod_ord int_ord Term_Ord.typ_ord o pairself (`Term.size_of_typ)) actual_Ts;
blanchet@54440
   309
blanchet@54440
   310
    fun check_enrich_with_mutuals _ [] = []
blanchet@55725
   311
      | check_enrich_with_mutuals seen ((T as Type (T_name, tyargs)) :: Ts) =
blanchet@54440
   312
        (case fp_sugar_of lthy T_name of
blanchet@54440
   313
          SOME ({fp = fp', fp_res = {Ts = Ts', ...}, ...}) =>
blanchet@54440
   314
          if fp = fp' then
blanchet@54440
   315
            let
blanchet@55725
   316
              val mutual_Ts = map (fn Type (s, _) => Type (s, tyargs)) Ts';
blanchet@54440
   317
              val _ =
blanchet@54440
   318
                seen = [] orelse exists (exists_subtype_in seen) mutual_Ts orelse
blanchet@54440
   319
                not_mutually_nested_rec mutual_Ts seen;
blanchet@54440
   320
              val (seen', Ts') = List.partition (member (op =) mutual_Ts) Ts;
blanchet@54440
   321
            in
blanchet@54440
   322
              mutual_Ts @ check_enrich_with_mutuals (seen @ T :: seen') Ts'
blanchet@54440
   323
            end
blanchet@54440
   324
          else
blanchet@54440
   325
            not_co_datatype T
blanchet@54440
   326
        | NONE => not_co_datatype T)
blanchet@54440
   327
      | check_enrich_with_mutuals _ (T :: _) = not_co_datatype T;
blanchet@54440
   328
blanchet@54440
   329
    val perm_Ts = check_enrich_with_mutuals [] perm_actual_Ts;
blanchet@54440
   330
    val missing_Ts = perm_Ts |> subtract (op =) actual_Ts;
blanchet@54440
   331
    val Ts = actual_Ts @ missing_Ts;
blanchet@54440
   332
blanchet@54440
   333
    val nn = length Ts;
blanchet@54440
   334
    val kks = 0 upto nn - 1;
blanchet@54440
   335
blanchet@55719
   336
    val callssss0 = pad_list [] nn actual_callssss0;
blanchet@55719
   337
blanchet@54440
   338
    val common_name = mk_common_name (map Binding.name_of actual_bs);
blanchet@54440
   339
    val bs = pad_list (Binding.name common_name) nn actual_bs;
blanchet@54440
   340
blanchet@54440
   341
    fun permute xs = permute_like (op =) Ts perm_Ts xs;
blanchet@54440
   342
    fun unpermute perm_xs = permute_like (op =) perm_Ts Ts perm_xs;
blanchet@54440
   343
blanchet@54440
   344
    val perm_bs = permute bs;
blanchet@54440
   345
    val perm_kks = permute kks;
blanchet@55719
   346
    val perm_callssss0 = permute callssss0;
blanchet@54440
   347
    val perm_fp_sugars0 = map (the o fp_sugar_of lthy o fst o dest_Type) perm_Ts;
blanchet@54440
   348
blanchet@55725
   349
    val has_nested = exists (fn Type (_, tyargs) => tyargs <> tyargs0) Ts;
blanchet@55719
   350
    val perm_callssss = map2 indexify_callsss perm_fp_sugars0 perm_callssss0;
blanchet@54440
   351
blanchet@54440
   352
    val get_perm_indices = map (fn kk => find_index (curry (op =) kk) perm_kks) o get_indices;
blanchet@54440
   353
blanchet@54883
   354
    val ((perm_fp_sugars, fp_sugar_thms), lthy) =
blanchet@55727
   355
      mutualize_fp_sugars has_nested fp perm_bs perm_Ts get_perm_indices perm_callssss
blanchet@54440
   356
        perm_fp_sugars0 lthy;
blanchet@54440
   357
blanchet@54440
   358
    val fp_sugars = unpermute perm_fp_sugars;
blanchet@54440
   359
  in
blanchet@54883
   360
    ((missing_Ts, perm_kks, fp_sugars, fp_sugar_thms), lthy)
blanchet@54440
   361
  end;
blanchet@54440
   362
blanchet@54440
   363
end;