src/HOL/BNF/Tools/bnf_gfp_rec_sugar.ML
author blanchet
Mon Nov 04 16:53:43 2013 +0100 (2013-11-04)
changeset 54246 8fdb4dc08ed1
parent 54243 src/HOL/BNF/Tools/bnf_fp_rec_sugar.ML@a596292be9a8
child 54271 113990e513fb
permissions -rw-r--r--
split 'primrec_new' and 'primcorec' code (to ease bootstrapping, e.g. dependency on datatype 'String' in 'primcorec')
blanchet@54246
     1
(*  Title:      HOL/BNF/Tools/bnf_gfp_rec_sugar.ML
blanchet@53303
     2
    Author:     Lorenz Panny, TU Muenchen
blanchet@54246
     3
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@53303
     4
    Copyright   2013
blanchet@53303
     5
blanchet@54246
     6
Corecursor sugar.
blanchet@53303
     7
*)
blanchet@53303
     8
blanchet@54246
     9
signature BNF_GFP_REC_SUGAR =
blanchet@53303
    10
sig
blanchet@53753
    11
  val add_primcorecursive_cmd: bool ->
panny@53831
    12
    (binding * string option * mixfix) list * ((Attrib.binding * string) * string option) list ->
panny@53831
    13
    Proof.context -> Proof.state
panny@53822
    14
  val add_primcorec_cmd: bool ->
panny@53831
    15
    (binding * string option * mixfix) list * ((Attrib.binding * string) * string option) list ->
panny@53831
    16
    local_theory -> local_theory
blanchet@53303
    17
end;
blanchet@53303
    18
blanchet@54246
    19
structure BNF_GFP_Rec_Sugar : BNF_GFP_REC_SUGAR =
blanchet@53303
    20
struct
blanchet@53303
    21
blanchet@54246
    22
open Ctr_Sugar
blanchet@53303
    23
open BNF_Util
blanchet@54246
    24
open BNF_Def
blanchet@53303
    25
open BNF_FP_Util
blanchet@54246
    26
open BNF_FP_Def_Sugar
blanchet@54243
    27
open BNF_FP_N2M_Sugar
blanchet@53303
    28
open BNF_FP_Rec_Sugar_Util
blanchet@54246
    29
open BNF_GFP_Rec_Sugar_Tactics
blanchet@53303
    30
blanchet@54246
    31
val codeN = "code"
blanchet@54246
    32
val ctrN = "ctr"
blanchet@54246
    33
val discN = "disc"
blanchet@54246
    34
val selN = "sel"
blanchet@53791
    35
blanchet@54145
    36
val nitpicksimp_attrs = @{attributes [nitpick_simp]};
blanchet@53794
    37
val simp_attrs = @{attributes [simp]};
blanchet@54145
    38
val code_nitpicksimp_attrs = Code.add_default_eqn_attrib :: nitpicksimp_attrs;
blanchet@54246
    39
blanchet@54246
    40
exception Primcorec_Error of string * term list;
blanchet@54246
    41
blanchet@54246
    42
fun primcorec_error str = raise Primcorec_Error (str, []);
blanchet@54246
    43
fun primcorec_error_eqn str eqn = raise Primcorec_Error (str, [eqn]);
blanchet@54246
    44
fun primcorec_error_eqns str eqns = raise Primcorec_Error (str, eqns);
blanchet@54246
    45
blanchet@54246
    46
datatype corec_call =
blanchet@54246
    47
  Dummy_No_Corec of int |
blanchet@54246
    48
  No_Corec of int |
blanchet@54246
    49
  Mutual_Corec of int * int * int |
blanchet@54246
    50
  Nested_Corec of int;
blanchet@54246
    51
blanchet@54246
    52
type basic_corec_ctr_spec =
blanchet@54246
    53
  {ctr: term,
blanchet@54246
    54
   disc: term,
blanchet@54246
    55
   sels: term list};
blanchet@54246
    56
blanchet@54246
    57
type corec_ctr_spec =
blanchet@54246
    58
  {ctr: term,
blanchet@54246
    59
   disc: term,
blanchet@54246
    60
   sels: term list,
blanchet@54246
    61
   pred: int option,
blanchet@54246
    62
   calls: corec_call list,
blanchet@54246
    63
   discI: thm,
blanchet@54246
    64
   sel_thms: thm list,
blanchet@54246
    65
   collapse: thm,
blanchet@54246
    66
   corec_thm: thm,
blanchet@54246
    67
   disc_corec: thm,
blanchet@54246
    68
   sel_corecs: thm list};
blanchet@54246
    69
blanchet@54246
    70
type corec_spec =
blanchet@54246
    71
  {corec: term,
blanchet@54246
    72
   nested_maps: thm list,
blanchet@54246
    73
   nested_map_idents: thm list,
blanchet@54246
    74
   nested_map_comps: thm list,
blanchet@54246
    75
   ctr_specs: corec_ctr_spec list};
blanchet@54246
    76
blanchet@54246
    77
exception AINT_NO_MAP of term;
blanchet@54246
    78
blanchet@54246
    79
fun not_codatatype ctxt T =
blanchet@54246
    80
  error ("Not a codatatype: " ^ Syntax.string_of_typ ctxt T);
blanchet@54246
    81
fun ill_formed_corec_call ctxt t =
blanchet@54246
    82
  error ("Ill-formed corecursive call: " ^ quote (Syntax.string_of_term ctxt t));
blanchet@54246
    83
fun invalid_map ctxt t =
blanchet@54246
    84
  error ("Invalid map function in " ^ quote (Syntax.string_of_term ctxt t));
blanchet@54246
    85
fun unexpected_corec_call ctxt t =
blanchet@54246
    86
  error ("Unexpected corecursive call: " ^ quote (Syntax.string_of_term ctxt t));
blanchet@54246
    87
blanchet@54246
    88
val mk_conjs = try (foldr1 HOLogic.mk_conj) #> the_default @{const True};
blanchet@54246
    89
val mk_disjs = try (foldr1 HOLogic.mk_disj) #> the_default @{const False};
blanchet@54246
    90
blanchet@54246
    91
val conjuncts_s = filter_out (curry (op =) @{const True}) o HOLogic.conjuncts;
blanchet@54246
    92
blanchet@54246
    93
fun s_not @{const True} = @{const False}
blanchet@54246
    94
  | s_not @{const False} = @{const True}
blanchet@54246
    95
  | s_not (@{const Not} $ t) = t
blanchet@54246
    96
  | s_not (@{const conj} $ t $ u) = @{const disj} $ s_not t $ s_not u
blanchet@54246
    97
  | s_not (@{const disj} $ t $ u) = @{const conj} $ s_not t $ s_not u
blanchet@54246
    98
  | s_not t = @{const Not} $ t;
blanchet@54246
    99
blanchet@54246
   100
val s_not_conj = conjuncts_s o s_not o mk_conjs;
blanchet@54246
   101
blanchet@54246
   102
fun propagate_unit_pos u cs = if member (op aconv) cs u then [@{const False}] else cs;
blanchet@54246
   103
blanchet@54246
   104
fun propagate_unit_neg not_u cs = remove (op aconv) not_u cs;
blanchet@54246
   105
blanchet@54246
   106
fun propagate_units css =
blanchet@54246
   107
  (case List.partition (can the_single) css of
blanchet@54246
   108
     ([], _) => css
blanchet@54246
   109
   | ([u] :: uss, css') =>
blanchet@54246
   110
     [u] :: propagate_units (map (propagate_unit_neg (s_not u))
blanchet@54246
   111
       (map (propagate_unit_pos u) (uss @ css'))));
blanchet@54246
   112
blanchet@54246
   113
fun s_conjs cs =
blanchet@54246
   114
  if member (op aconv) cs @{const False} then @{const False}
blanchet@54246
   115
  else mk_conjs (remove (op aconv) @{const True} cs);
blanchet@54246
   116
blanchet@54246
   117
fun s_disjs ds =
blanchet@54246
   118
  if member (op aconv) ds @{const True} then @{const True}
blanchet@54246
   119
  else mk_disjs (remove (op aconv) @{const False} ds);
blanchet@54246
   120
blanchet@54246
   121
fun s_dnf css0 =
blanchet@54246
   122
  let val css = propagate_units css0 in
blanchet@54246
   123
    if null css then
blanchet@54246
   124
      [@{const False}]
blanchet@54246
   125
    else if exists null css then
blanchet@54246
   126
      []
blanchet@54246
   127
    else
blanchet@54246
   128
      map (fn c :: cs => (c, cs)) css
blanchet@54246
   129
      |> AList.coalesce (op =)
blanchet@54246
   130
      |> map (fn (c, css) => c :: s_dnf css)
blanchet@54246
   131
      |> (fn [cs] => cs | css => [s_disjs (map s_conjs css)])
blanchet@54246
   132
  end;
blanchet@54246
   133
blanchet@54246
   134
fun fold_rev_let_if_case ctxt f bound_Ts t =
blanchet@54246
   135
  let
blanchet@54246
   136
    val thy = Proof_Context.theory_of ctxt;
blanchet@53794
   137
blanchet@54246
   138
    fun fld conds t =
blanchet@54246
   139
      (case Term.strip_comb t of
blanchet@54246
   140
        (Const (@{const_name Let}, _), [_, _]) => fld conds (unfold_let t)
blanchet@54246
   141
      | (Const (@{const_name If}, _), [cond, then_branch, else_branch]) =>
blanchet@54246
   142
        fld (conds @ conjuncts_s cond) then_branch o fld (conds @ s_not_conj [cond]) else_branch
blanchet@54246
   143
      | (Const (c, _), args as _ :: _ :: _) =>
blanchet@54246
   144
        let val n = num_binder_types (Sign.the_const_type thy c) - 1 in
blanchet@54246
   145
          if n >= 0 andalso n < length args then
blanchet@54246
   146
            (case fastype_of1 (bound_Ts, nth args n) of
blanchet@54246
   147
              Type (s, Ts) =>
blanchet@54246
   148
              (case dest_case ctxt s Ts t of
blanchet@54246
   149
                NONE => apsnd (f conds t)
blanchet@54246
   150
              | SOME (conds', branches) =>
blanchet@54246
   151
                apfst (cons s) o fold_rev (uncurry fld)
blanchet@54246
   152
                  (map (append conds o conjuncts_s) conds' ~~ branches))
blanchet@54246
   153
            | _ => apsnd (f conds t))
blanchet@54246
   154
          else
blanchet@54246
   155
            apsnd (f conds t)
blanchet@54246
   156
        end
blanchet@54246
   157
      | _ => apsnd (f conds t))
blanchet@54246
   158
  in
blanchet@54246
   159
    fld [] t o pair []
blanchet@54246
   160
  end;
blanchet@54246
   161
blanchet@54246
   162
fun case_of ctxt = ctr_sugar_of ctxt #> Option.map (fst o dest_Const o #casex);
blanchet@54246
   163
blanchet@54246
   164
fun massage_let_if_case ctxt has_call massage_leaf =
blanchet@54246
   165
  let
blanchet@54246
   166
    val thy = Proof_Context.theory_of ctxt;
blanchet@54246
   167
blanchet@54246
   168
    fun check_no_call t = if has_call t then unexpected_corec_call ctxt t else ();
blanchet@54246
   169
blanchet@54246
   170
    fun massage_abs bound_Ts 0 t = massage_rec bound_Ts t
blanchet@54246
   171
      | massage_abs bound_Ts m (Abs (s, T, t)) = Abs (s, T, massage_abs (T :: bound_Ts) (m - 1) t)
blanchet@54246
   172
      | massage_abs bound_Ts m t =
blanchet@54246
   173
        let val T = domain_type (fastype_of1 (bound_Ts, t)) in
blanchet@54246
   174
          Abs (Name.uu, T, massage_abs (T :: bound_Ts) (m - 1) (incr_boundvars 1 t $ Bound 0))
blanchet@54246
   175
        end
blanchet@54246
   176
    and massage_rec bound_Ts t =
blanchet@54246
   177
      let val typof = curry fastype_of1 bound_Ts in
blanchet@54246
   178
        (case Term.strip_comb t of
blanchet@54246
   179
          (Const (@{const_name Let}, _), [_, _]) => massage_rec bound_Ts (unfold_let t)
blanchet@54246
   180
        | (Const (@{const_name If}, _), obj :: (branches as [_, _])) =>
blanchet@54246
   181
          let val branches' = map (massage_rec bound_Ts) branches in
blanchet@54246
   182
            Term.list_comb (If_const (typof (hd branches')) $ tap check_no_call obj, branches')
blanchet@54246
   183
          end
blanchet@54246
   184
        | (Const (c, _), args as _ :: _ :: _) =>
blanchet@54246
   185
          (case try strip_fun_type (Sign.the_const_type thy c) of
blanchet@54246
   186
            SOME (gen_branch_Ts, gen_body_fun_T) =>
blanchet@54246
   187
            let
blanchet@54246
   188
              val gen_branch_ms = map num_binder_types gen_branch_Ts;
blanchet@54246
   189
              val n = length gen_branch_ms;
blanchet@54246
   190
            in
blanchet@54246
   191
              if n < length args then
blanchet@54246
   192
                (case gen_body_fun_T of
blanchet@54246
   193
                  Type (_, [Type (T_name, _), _]) =>
blanchet@54246
   194
                  if case_of ctxt T_name = SOME c then
blanchet@54246
   195
                    let
blanchet@54246
   196
                      val (branches, obj_leftovers) = chop n args;
blanchet@54246
   197
                      val branches' = map2 (massage_abs bound_Ts) gen_branch_ms branches;
blanchet@54246
   198
                      val branch_Ts' = map typof branches';
blanchet@54246
   199
                      val body_T' = snd (strip_typeN (hd gen_branch_ms) (hd branch_Ts'));
blanchet@54246
   200
                      val casex' = Const (c, branch_Ts' ---> map typof obj_leftovers ---> body_T');
blanchet@54246
   201
                    in
blanchet@54246
   202
                      Term.list_comb (casex', branches' @ tap (List.app check_no_call) obj_leftovers)
blanchet@54246
   203
                    end
blanchet@54246
   204
                  else
blanchet@54246
   205
                    massage_leaf bound_Ts t
blanchet@54246
   206
                | _ => massage_leaf bound_Ts t)
blanchet@54246
   207
              else
blanchet@54246
   208
                massage_leaf bound_Ts t
blanchet@54246
   209
            end
blanchet@54246
   210
          | NONE => massage_leaf bound_Ts t)
blanchet@54246
   211
        | _ => massage_leaf bound_Ts t)
blanchet@54246
   212
      end
blanchet@54246
   213
  in
blanchet@54246
   214
    massage_rec
blanchet@54246
   215
  end;
blanchet@54246
   216
blanchet@54246
   217
val massage_mutual_corec_call = massage_let_if_case;
blanchet@54246
   218
blanchet@54246
   219
fun curried_type (Type (@{type_name fun}, [Type (@{type_name prod}, Ts), T])) = Ts ---> T;
blanchet@54246
   220
blanchet@54246
   221
fun massage_nested_corec_call ctxt has_call raw_massage_call bound_Ts U t =
blanchet@54246
   222
  let
blanchet@54246
   223
    fun check_no_call t = if has_call t then unexpected_corec_call ctxt t else ();
blanchet@54246
   224
blanchet@54246
   225
    val build_map_Inl = build_map ctxt (uncurry Inl_const o dest_sumT o snd);
blanchet@54246
   226
blanchet@54246
   227
    fun massage_mutual_call bound_Ts U T t =
blanchet@54246
   228
      if has_call t then
blanchet@54246
   229
        (case try dest_sumT U of
blanchet@54246
   230
          SOME (U1, U2) => if U1 = T then raw_massage_call bound_Ts T U2 t else invalid_map ctxt t
blanchet@54246
   231
        | NONE => invalid_map ctxt t)
blanchet@54246
   232
      else
blanchet@54246
   233
        build_map_Inl (T, U) $ t;
blanchet@54246
   234
blanchet@54246
   235
    fun massage_mutual_fun bound_Ts U T t =
blanchet@54246
   236
      (case t of
blanchet@54246
   237
        Const (@{const_name comp}, _) $ t1 $ t2 =>
blanchet@54246
   238
        mk_comp bound_Ts (massage_mutual_fun bound_Ts U T t1, tap check_no_call t2)
blanchet@54246
   239
      | _ =>
blanchet@54246
   240
        let
blanchet@54246
   241
          val var = Var ((Name.uu, Term.maxidx_of_term t + 1),
blanchet@54246
   242
            domain_type (fastype_of1 (bound_Ts, t)));
blanchet@54246
   243
        in
blanchet@54246
   244
          Term.lambda var (massage_mutual_call bound_Ts U T (t $ var))
blanchet@54246
   245
        end);
blanchet@53303
   246
blanchet@54246
   247
    fun massage_map bound_Ts (Type (_, Us)) (Type (s, Ts)) t =
blanchet@54246
   248
        (case try (dest_map ctxt s) t of
blanchet@54246
   249
          SOME (map0, fs) =>
blanchet@54246
   250
          let
blanchet@54246
   251
            val Type (_, dom_Ts) = domain_type (fastype_of1 (bound_Ts, t));
blanchet@54246
   252
            val map' = mk_map (length fs) dom_Ts Us map0;
blanchet@54246
   253
            val fs' =
blanchet@54246
   254
              map_flattened_map_args ctxt s (map3 (massage_map_or_map_arg bound_Ts) Us Ts) fs;
blanchet@54246
   255
          in
blanchet@54246
   256
            Term.list_comb (map', fs')
blanchet@54246
   257
          end
blanchet@54246
   258
        | NONE => raise AINT_NO_MAP t)
blanchet@54246
   259
      | massage_map _ _ _ t = raise AINT_NO_MAP t
blanchet@54246
   260
    and massage_map_or_map_arg bound_Ts U T t =
blanchet@54246
   261
      if T = U then
blanchet@54246
   262
        tap check_no_call t
blanchet@54246
   263
      else
blanchet@54246
   264
        massage_map bound_Ts U T t
blanchet@54246
   265
        handle AINT_NO_MAP _ => massage_mutual_fun bound_Ts U T t;
blanchet@54246
   266
blanchet@54246
   267
    fun massage_call bound_Ts U T =
blanchet@54246
   268
      massage_let_if_case ctxt has_call (fn bound_Ts => fn t =>
blanchet@54246
   269
        if has_call t then
blanchet@54246
   270
          (case U of
blanchet@54246
   271
            Type (s, Us) =>
blanchet@54246
   272
            (case try (dest_ctr ctxt s) t of
blanchet@54246
   273
              SOME (f, args) =>
blanchet@54246
   274
              let
blanchet@54246
   275
                val typof = curry fastype_of1 bound_Ts;
blanchet@54246
   276
                val f' = mk_ctr Us f
blanchet@54246
   277
                val f'_T = typof f';
blanchet@54246
   278
                val arg_Ts = map typof args;
blanchet@54246
   279
              in
blanchet@54246
   280
                Term.list_comb (f', map3 (massage_call bound_Ts) (binder_types f'_T) arg_Ts args)
blanchet@54246
   281
              end
blanchet@54246
   282
            | NONE =>
blanchet@54246
   283
              (case t of
blanchet@54246
   284
                Const (@{const_name prod_case}, _) $ t' =>
blanchet@54246
   285
                let
blanchet@54246
   286
                  val U' = curried_type U;
blanchet@54246
   287
                  val T' = curried_type T;
blanchet@54246
   288
                in
blanchet@54246
   289
                  Const (@{const_name prod_case}, U' --> U) $ massage_call bound_Ts U' T' t'
blanchet@54246
   290
                end
blanchet@54246
   291
              | t1 $ t2 =>
blanchet@54246
   292
                (if has_call t2 then
blanchet@54246
   293
                  massage_mutual_call bound_Ts U T t
blanchet@54246
   294
                else
blanchet@54246
   295
                  massage_map bound_Ts U T t1 $ t2
blanchet@54246
   296
                  handle AINT_NO_MAP _ => massage_mutual_call bound_Ts U T t)
blanchet@54246
   297
              | Abs (s, T', t') =>
blanchet@54246
   298
                Abs (s, T', massage_call (T' :: bound_Ts) (range_type U) (range_type T) t')
blanchet@54246
   299
              | _ => massage_mutual_call bound_Ts U T t))
blanchet@54246
   300
          | _ => ill_formed_corec_call ctxt t)
blanchet@54246
   301
        else
blanchet@54246
   302
          build_map_Inl (T, U) $ t) bound_Ts;
blanchet@54246
   303
blanchet@54246
   304
    val T = fastype_of1 (bound_Ts, t);
blanchet@54246
   305
  in
blanchet@54246
   306
    if has_call t then massage_call bound_Ts U T t else build_map_Inl (T, U) $ t
blanchet@54246
   307
  end;
blanchet@54246
   308
blanchet@54246
   309
val fold_rev_corec_call = fold_rev_let_if_case;
blanchet@54246
   310
blanchet@54246
   311
fun expand_to_ctr_term ctxt s Ts t =
blanchet@54246
   312
  (case ctr_sugar_of ctxt s of
blanchet@54246
   313
    SOME {ctrs, casex, ...} =>
blanchet@54246
   314
    Term.list_comb (mk_case Ts (Type (s, Ts)) casex, map (mk_ctr Ts) ctrs) $ t
blanchet@54246
   315
  | NONE => raise Fail "expand_to_ctr_term");
blanchet@54246
   316
blanchet@54246
   317
fun expand_corec_code_rhs ctxt has_call bound_Ts t =
blanchet@54246
   318
  (case fastype_of1 (bound_Ts, t) of
blanchet@54246
   319
    Type (s, Ts) =>
blanchet@54246
   320
    massage_let_if_case ctxt has_call (fn _ => fn t =>
blanchet@54246
   321
      if can (dest_ctr ctxt s) t then t else expand_to_ctr_term ctxt s Ts t) bound_Ts t
blanchet@54246
   322
  | _ => raise Fail "expand_corec_code_rhs");
blanchet@54246
   323
blanchet@54246
   324
fun massage_corec_code_rhs ctxt massage_ctr =
blanchet@54246
   325
  massage_let_if_case ctxt (K false)
blanchet@54246
   326
    (fn bound_Ts => uncurry (massage_ctr bound_Ts) o Term.strip_comb);
blanchet@54246
   327
blanchet@54246
   328
fun fold_rev_corec_code_rhs ctxt f =
blanchet@54246
   329
  snd ooo fold_rev_let_if_case ctxt (fn conds => uncurry (f conds) o Term.strip_comb);
blanchet@54246
   330
blanchet@54246
   331
fun case_thms_of_term ctxt bound_Ts t =
blanchet@54246
   332
  let
blanchet@54246
   333
    val (caseT_names, _) = fold_rev_let_if_case ctxt (K (K I)) bound_Ts t ();
blanchet@54246
   334
    val ctr_sugars = map (the o ctr_sugar_of ctxt) caseT_names;
blanchet@54246
   335
  in
blanchet@54246
   336
    (maps #distincts ctr_sugars, maps #discIs ctr_sugars, maps #sel_splits ctr_sugars,
blanchet@54246
   337
     maps #sel_split_asms ctr_sugars)
blanchet@54246
   338
  end;
blanchet@54246
   339
blanchet@54246
   340
fun basic_corec_specs_of ctxt res_T =
blanchet@54246
   341
  (case res_T of
blanchet@54246
   342
    Type (T_name, _) =>
blanchet@54246
   343
    (case Ctr_Sugar.ctr_sugar_of ctxt T_name of
blanchet@54246
   344
      NONE => not_codatatype ctxt res_T
blanchet@54246
   345
    | SOME {ctrs, discs, selss, ...} =>
blanchet@54246
   346
      let
blanchet@54246
   347
        val thy = Proof_Context.theory_of ctxt;
blanchet@54246
   348
        val gfpT = body_type (fastype_of (hd ctrs));
blanchet@54246
   349
        val As_rho = tvar_subst thy [gfpT] [res_T];
blanchet@54246
   350
        val substA = Term.subst_TVars As_rho;
blanchet@54246
   351
blanchet@54246
   352
        fun mk_spec ctr disc sels = {ctr = substA ctr, disc = substA disc, sels = map substA sels};
blanchet@54246
   353
      in
blanchet@54246
   354
        map3 mk_spec ctrs discs selss
blanchet@54246
   355
      end)
blanchet@54246
   356
  | _ => not_codatatype ctxt res_T);
blanchet@53303
   357
blanchet@54246
   358
(*FIXME: remove special cases for product and sum once they are registered as datatypes*)
blanchet@54246
   359
fun map_thms_of_typ ctxt (Type (s, _)) =
blanchet@54246
   360
    if s = @{type_name prod} then
blanchet@54246
   361
      @{thms map_pair_simp}
blanchet@54246
   362
    else if s = @{type_name sum} then
blanchet@54246
   363
      @{thms sum_map.simps}
blanchet@54246
   364
    else
blanchet@54246
   365
      (case fp_sugar_of ctxt s of
blanchet@54246
   366
        SOME {index, mapss, ...} => nth mapss index
blanchet@54246
   367
      | NONE => [])
blanchet@54246
   368
  | map_thms_of_typ _ _ = [];
blanchet@54246
   369
blanchet@54246
   370
fun corec_specs_of bs arg_Ts res_Ts get_indices callssss0 lthy =
blanchet@54246
   371
  let
blanchet@54246
   372
    val thy = Proof_Context.theory_of lthy;
blanchet@54246
   373
blanchet@54246
   374
    val ((missing_res_Ts, perm0_kks,
blanchet@54246
   375
          fp_sugars as {nested_bnfs, fp_res = {xtor_co_iterss = dtor_coiters1 :: _, ...},
blanchet@54246
   376
            co_inducts = coinduct_thms, ...} :: _, (_, gfp_sugar_thms)), lthy') =
blanchet@54246
   377
      nested_to_mutual_fps Greatest_FP bs res_Ts get_indices callssss0 lthy;
blanchet@54246
   378
blanchet@54246
   379
    val perm_fp_sugars = sort (int_ord o pairself #index) fp_sugars;
blanchet@54246
   380
blanchet@54246
   381
    val indices = map #index fp_sugars;
blanchet@54246
   382
    val perm_indices = map #index perm_fp_sugars;
blanchet@54246
   383
blanchet@54246
   384
    val perm_ctrss = map (#ctrs o of_fp_sugar #ctr_sugars) perm_fp_sugars;
blanchet@54246
   385
    val perm_ctr_Tsss = map (map (binder_types o fastype_of)) perm_ctrss;
blanchet@54246
   386
    val perm_gfpTs = map (body_type o fastype_of o hd) perm_ctrss;
blanchet@54246
   387
blanchet@54246
   388
    val nn0 = length res_Ts;
blanchet@54246
   389
    val nn = length perm_gfpTs;
blanchet@54246
   390
    val kks = 0 upto nn - 1;
blanchet@54246
   391
    val perm_ns = map length perm_ctr_Tsss;
blanchet@54246
   392
blanchet@54246
   393
    val perm_Cs = map (domain_type o body_fun_type o fastype_of o co_rec_of o
blanchet@54246
   394
      of_fp_sugar (#xtor_co_iterss o #fp_res)) perm_fp_sugars;
blanchet@54246
   395
    val (perm_p_Tss, (perm_q_Tssss, _, perm_f_Tssss, _)) =
blanchet@54246
   396
      mk_coiter_fun_arg_types perm_ctr_Tsss perm_Cs perm_ns (co_rec_of dtor_coiters1);
blanchet@54246
   397
blanchet@54246
   398
    val (perm_p_hss, h) = indexedd perm_p_Tss 0;
blanchet@54246
   399
    val (perm_q_hssss, h') = indexedddd perm_q_Tssss h;
blanchet@54246
   400
    val (perm_f_hssss, _) = indexedddd perm_f_Tssss h';
blanchet@54246
   401
blanchet@54246
   402
    val fun_arg_hs =
blanchet@54246
   403
      flat (map3 flat_corec_preds_predsss_gettersss perm_p_hss perm_q_hssss perm_f_hssss);
blanchet@54246
   404
blanchet@54246
   405
    fun unpermute0 perm0_xs = permute_like (op =) perm0_kks kks perm0_xs;
blanchet@54246
   406
    fun unpermute perm_xs = permute_like (op =) perm_indices indices perm_xs;
blanchet@54246
   407
blanchet@54246
   408
    val coinduct_thmss = map (unpermute0 o conj_dests nn) coinduct_thms;
blanchet@54246
   409
blanchet@54246
   410
    val p_iss = map (map (find_index_eq fun_arg_hs)) (unpermute perm_p_hss);
blanchet@54246
   411
    val q_issss = map (map (map (map (find_index_eq fun_arg_hs)))) (unpermute perm_q_hssss);
blanchet@54246
   412
    val f_issss = map (map (map (map (find_index_eq fun_arg_hs)))) (unpermute perm_f_hssss);
panny@53358
   413
blanchet@54246
   414
    val f_Tssss = unpermute perm_f_Tssss;
blanchet@54246
   415
    val gfpTs = unpermute perm_gfpTs;
blanchet@54246
   416
    val Cs = unpermute perm_Cs;
blanchet@54246
   417
blanchet@54246
   418
    val As_rho = tvar_subst thy (take nn0 gfpTs) res_Ts;
blanchet@54246
   419
    val Cs_rho = map (fst o dest_TVar) Cs ~~ pad_list HOLogic.unitT nn arg_Ts;
blanchet@54246
   420
blanchet@54246
   421
    val substA = Term.subst_TVars As_rho;
blanchet@54246
   422
    val substAT = Term.typ_subst_TVars As_rho;
blanchet@54246
   423
    val substCT = Term.typ_subst_TVars Cs_rho;
blanchet@54246
   424
blanchet@54246
   425
    val perm_Cs' = map substCT perm_Cs;
blanchet@54246
   426
blanchet@54246
   427
    fun call_of nullary [] [g_i] [Type (@{type_name fun}, [_, T])] =
blanchet@54246
   428
        (if exists_subtype_in Cs T then Nested_Corec
blanchet@54246
   429
         else if nullary then Dummy_No_Corec
blanchet@54246
   430
         else No_Corec) g_i
blanchet@54246
   431
      | call_of _ [q_i] [g_i, g_i'] _ = Mutual_Corec (q_i, g_i, g_i');
blanchet@54246
   432
blanchet@54246
   433
    fun mk_ctr_spec ctr disc sels p_ho q_iss f_iss f_Tss discI sel_thms collapse corec_thm
blanchet@54246
   434
        disc_corec sel_corecs =
blanchet@54246
   435
      let val nullary = not (can dest_funT (fastype_of ctr)) in
blanchet@54246
   436
        {ctr = substA ctr, disc = substA disc, sels = map substA sels, pred = p_ho,
blanchet@54246
   437
         calls = map3 (call_of nullary) q_iss f_iss f_Tss, discI = discI, sel_thms = sel_thms,
blanchet@54246
   438
         collapse = collapse, corec_thm = corec_thm, disc_corec = disc_corec,
blanchet@54246
   439
         sel_corecs = sel_corecs}
blanchet@54246
   440
      end;
blanchet@54246
   441
blanchet@54246
   442
    fun mk_ctr_specs index (ctr_sugars : ctr_sugar list) p_is q_isss f_isss f_Tsss coiter_thmsss
blanchet@54246
   443
        disc_coitersss sel_coiterssss =
blanchet@54246
   444
      let
blanchet@54246
   445
        val ctrs = #ctrs (nth ctr_sugars index);
blanchet@54246
   446
        val discs = #discs (nth ctr_sugars index);
blanchet@54246
   447
        val selss = #selss (nth ctr_sugars index);
blanchet@54246
   448
        val p_ios = map SOME p_is @ [NONE];
blanchet@54246
   449
        val discIs = #discIs (nth ctr_sugars index);
blanchet@54246
   450
        val sel_thmss = #sel_thmss (nth ctr_sugars index);
blanchet@54246
   451
        val collapses = #collapses (nth ctr_sugars index);
blanchet@54246
   452
        val corec_thms = co_rec_of (nth coiter_thmsss index);
blanchet@54246
   453
        val disc_corecs = co_rec_of (nth disc_coitersss index);
blanchet@54246
   454
        val sel_corecss = co_rec_of (nth sel_coiterssss index);
blanchet@54246
   455
      in
blanchet@54246
   456
        map13 mk_ctr_spec ctrs discs selss p_ios q_isss f_isss f_Tsss discIs sel_thmss collapses
blanchet@54246
   457
          corec_thms disc_corecs sel_corecss
blanchet@54246
   458
      end;
blanchet@54246
   459
blanchet@54246
   460
    fun mk_spec ({T, index, ctr_sugars, co_iterss = coiterss, co_iter_thmsss = coiter_thmsss,
blanchet@54246
   461
          disc_co_itersss = disc_coitersss, sel_co_iterssss = sel_coiterssss, ...} : fp_sugar)
blanchet@54246
   462
        p_is q_isss f_isss f_Tsss =
blanchet@54246
   463
      {corec = mk_co_iter thy Greatest_FP (substAT T) perm_Cs' (co_rec_of (nth coiterss index)),
blanchet@54246
   464
       nested_maps = maps (map_thms_of_typ lthy o T_of_bnf) nested_bnfs,
blanchet@54246
   465
       nested_map_idents = map (unfold_thms lthy @{thms id_def} o map_id0_of_bnf) nested_bnfs,
blanchet@54246
   466
       nested_map_comps = map map_comp_of_bnf nested_bnfs,
blanchet@54246
   467
       ctr_specs = mk_ctr_specs index ctr_sugars p_is q_isss f_isss f_Tsss coiter_thmsss
blanchet@54246
   468
         disc_coitersss sel_coiterssss};
blanchet@54246
   469
  in
blanchet@54246
   470
    ((is_some gfp_sugar_thms, map5 mk_spec fp_sugars p_iss q_issss f_issss f_Tssss, missing_res_Ts,
blanchet@54246
   471
      co_induct_of coinduct_thms, strong_co_induct_of coinduct_thms, co_induct_of coinduct_thmss,
blanchet@54246
   472
      strong_co_induct_of coinduct_thmss), lthy')
blanchet@54246
   473
  end;
blanchet@54246
   474
panny@53357
   475
val const_name = try (fn Const (v, _) => v);
panny@53358
   476
val undef_const = Const (@{const_name undefined}, dummyT);
panny@53357
   477
panny@53401
   478
val abs_tuple = HOLogic.tupled_lambda o HOLogic.mk_tuple;
panny@53720
   479
fun abstract vs =
panny@53720
   480
  let fun a n (t $ u) = a n t $ a n u
panny@53720
   481
        | a n (Abs (v, T, b)) = Abs (v, T, a (n + 1) b)
panny@53720
   482
        | a n t = let val idx = find_index (equal t) vs in
panny@53720
   483
            if idx < 0 then t else Bound (n + idx) end
panny@53720
   484
  in a 0 end;
panny@53735
   485
fun mk_prod1 Ts (t, u) = HOLogic.pair_const (fastype_of1 (Ts, t)) (fastype_of1 (Ts, u)) $ t $ u;
panny@53735
   486
fun mk_tuple1 Ts = the_default HOLogic.unit o try (foldr1 (mk_prod1 Ts));
blanchet@53303
   487
blanchet@54153
   488
type coeqn_data_disc = {
blanchet@53303
   489
  fun_name: string,
panny@53720
   490
  fun_T: typ,
panny@53401
   491
  fun_args: term list,
panny@53720
   492
  ctr: term,
panny@53341
   493
  ctr_no: int, (*###*)
panny@53720
   494
  disc: term,
panny@53654
   495
  prems: term list,
panny@53822
   496
  auto_gen: bool,
panny@54097
   497
  maybe_ctr_rhs: term option,
panny@54097
   498
  maybe_code_rhs: term option,
blanchet@53303
   499
  user_eqn: term
blanchet@53303
   500
};
blanchet@54001
   501
blanchet@54153
   502
type coeqn_data_sel = {
blanchet@53303
   503
  fun_name: string,
panny@53720
   504
  fun_T: typ,
panny@53401
   505
  fun_args: term list,
panny@53341
   506
  ctr: term,
panny@53341
   507
  sel: term,
blanchet@53303
   508
  rhs_term: term,
blanchet@53303
   509
  user_eqn: term
blanchet@53303
   510
};
blanchet@54001
   511
blanchet@54153
   512
datatype coeqn_data =
blanchet@54153
   513
  Disc of coeqn_data_disc |
blanchet@54153
   514
  Sel of coeqn_data_sel;
blanchet@53303
   515
panny@54160
   516
fun dissect_coeqn_disc seq fun_names (basic_ctr_specss : basic_corec_ctr_spec list list)
panny@54160
   517
    maybe_ctr_rhs maybe_code_rhs prems' concl matchedsss =
blanchet@53303
   518
  let
blanchet@53303
   519
    fun find_subterm p = let (* FIXME \<exists>? *)
panny@53401
   520
      fun f (t as u $ v) = if p t then SOME t else merge_options (f u, f v)
blanchet@53303
   521
        | f t = if p t then SOME t else NONE
blanchet@53303
   522
      in f end;
blanchet@53303
   523
panny@53654
   524
    val applied_fun = concl
panny@53654
   525
      |> find_subterm (member ((op =) o apsnd SOME) fun_names o try (fst o dest_Free o head_of))
panny@53654
   526
      |> the
blanchet@54246
   527
      handle Option.Option => primcorec_error_eqn "malformed discriminator formula" concl;
panny@53720
   528
    val ((fun_name, fun_T), fun_args) = strip_comb applied_fun |>> dest_Free;
blanchet@54209
   529
    val SOME basic_ctr_specs = AList.lookup (op =) (fun_names ~~ basic_ctr_specss) fun_name;
blanchet@53303
   530
panny@54160
   531
    val discs = map #disc basic_ctr_specs;
panny@54160
   532
    val ctrs = map #ctr basic_ctr_specs;
panny@53654
   533
    val not_disc = head_of concl = @{term Not};
panny@53401
   534
    val _ = not_disc andalso length ctrs <> 2 andalso
blanchet@54246
   535
      primcorec_error_eqn "negated discriminator for a type with \<noteq> 2 constructors" concl;
panny@54160
   536
    val disc' = find_subterm (member (op =) discs o head_of) concl;
blanchet@54209
   537
    val eq_ctr0 = concl |> perhaps (try HOLogic.dest_not) |> try (HOLogic.dest_eq #> snd)
blanchet@53303
   538
        |> (fn SOME t => let val n = find_index (equal t) ctrs in
blanchet@53303
   539
          if n >= 0 then SOME n else NONE end | _ => NONE);
panny@54160
   540
    val _ = is_some disc' orelse is_some eq_ctr0 orelse
blanchet@54246
   541
      primcorec_error_eqn "no discriminator in equation" concl;
blanchet@53303
   542
    val ctr_no' =
panny@54160
   543
      if is_none disc' then the eq_ctr0 else find_index (equal (head_of (the disc'))) discs;
blanchet@53303
   544
    val ctr_no = if not_disc then 1 - ctr_no' else ctr_no';
panny@54160
   545
    val {ctr, disc, ...} = nth basic_ctr_specs ctr_no;
panny@53654
   546
panny@53654
   547
    val catch_all = try (fst o dest_Free o the_single) prems' = SOME Name.uu_;
panny@53720
   548
    val matchedss = AList.lookup (op =) matchedsss fun_name |> the_default [];
panny@53720
   549
    val prems = map (abstract (List.rev fun_args)) prems';
panny@53720
   550
    val real_prems =
blanchet@54067
   551
      (if catch_all orelse seq then maps s_not_conj matchedss else []) @
panny@53654
   552
      (if catch_all then [] else prems);
blanchet@53303
   553
panny@53720
   554
    val matchedsss' = AList.delete (op =) fun_name matchedsss
panny@54065
   555
      |> cons (fun_name, if seq then matchedss @ [prems] else matchedss @ [real_prems]);
blanchet@53303
   556
panny@53654
   557
    val user_eqn =
panny@54097
   558
      (real_prems, concl)
panny@54097
   559
      |>> map HOLogic.mk_Trueprop ||> HOLogic.mk_Trueprop o abstract (List.rev fun_args)
panny@54097
   560
      |> curry Logic.list_all (map dest_Free fun_args) o Logic.list_implies;
blanchet@53303
   561
  in
panny@53341
   562
    (Disc {
blanchet@53303
   563
      fun_name = fun_name,
panny@53720
   564
      fun_T = fun_T,
panny@53401
   565
      fun_args = fun_args,
panny@53720
   566
      ctr = ctr,
blanchet@53303
   567
      ctr_no = ctr_no,
panny@54160
   568
      disc = disc,
panny@53654
   569
      prems = real_prems,
panny@53822
   570
      auto_gen = catch_all,
panny@54097
   571
      maybe_ctr_rhs = maybe_ctr_rhs,
panny@54097
   572
      maybe_code_rhs = maybe_code_rhs,
panny@53654
   573
      user_eqn = user_eqn
panny@53720
   574
    }, matchedsss')
blanchet@53303
   575
  end;
blanchet@53303
   576
blanchet@54209
   577
fun dissect_coeqn_sel fun_names (basic_ctr_specss : basic_corec_ctr_spec list list) eqn'
blanchet@54209
   578
    maybe_of_spec eqn =
blanchet@53303
   579
  let
blanchet@53303
   580
    val (lhs, rhs) = HOLogic.dest_eq eqn
blanchet@53303
   581
      handle TERM _ =>
blanchet@54246
   582
        primcorec_error_eqn "malformed function equation (expected \"lhs = rhs\")" eqn;
blanchet@53303
   583
    val sel = head_of lhs;
panny@53720
   584
    val ((fun_name, fun_T), fun_args) = dest_comb lhs |> snd |> strip_comb |> apfst dest_Free
blanchet@53303
   585
      handle TERM _ =>
blanchet@54246
   586
        primcorec_error_eqn "malformed selector argument in left-hand side" eqn;
panny@54160
   587
    val basic_ctr_specs = the (AList.lookup (op =) (fun_names ~~ basic_ctr_specss) fun_name)
blanchet@54246
   588
      handle Option.Option => primcorec_error_eqn "malformed selector argument in left-hand side" eqn;
panny@54160
   589
    val {ctr, ...} =
blanchet@54209
   590
      (case maybe_of_spec of
blanchet@54209
   591
        SOME of_spec => the (find_first (equal of_spec o #ctr) basic_ctr_specs)
blanchet@54209
   592
      | NONE => filter (exists (equal sel) o #sels) basic_ctr_specs |> the_single
blanchet@54246
   593
          handle List.Empty => primcorec_error_eqn "ambiguous selector - use \"of\"" eqn);
panny@53654
   594
    val user_eqn = drop_All eqn';
blanchet@53303
   595
  in
panny@53341
   596
    Sel {
blanchet@53303
   597
      fun_name = fun_name,
panny@53720
   598
      fun_T = fun_T,
panny@53401
   599
      fun_args = fun_args,
panny@54160
   600
      ctr = ctr,
panny@53341
   601
      sel = sel,
blanchet@53303
   602
      rhs_term = rhs,
panny@53654
   603
      user_eqn = user_eqn
blanchet@53303
   604
    }
blanchet@53303
   605
  end;
blanchet@53303
   606
panny@54160
   607
fun dissect_coeqn_ctr seq fun_names (basic_ctr_specss : basic_corec_ctr_spec list list) eqn'
panny@54160
   608
    maybe_code_rhs prems concl matchedsss =
blanchet@53910
   609
  let
panny@54065
   610
    val (lhs, rhs) = HOLogic.dest_eq concl;
panny@54097
   611
    val (fun_name, fun_args) = strip_comb lhs |>> fst o dest_Free;
blanchet@54209
   612
    val SOME basic_ctr_specs = AList.lookup (op =) (fun_names ~~ basic_ctr_specss) fun_name;
blanchet@54074
   613
    val (ctr, ctr_args) = strip_comb (unfold_let rhs);
panny@54160
   614
    val {disc, sels, ...} = the (find_first (equal ctr o #ctr) basic_ctr_specs)
blanchet@54246
   615
      handle Option.Option => primcorec_error_eqn "not a constructor" ctr;
panny@53341
   616
panny@54065
   617
    val disc_concl = betapply (disc, lhs);
panny@54160
   618
    val (maybe_eqn_data_disc, matchedsss') = if length basic_ctr_specs = 1
panny@53720
   619
      then (NONE, matchedsss)
panny@54160
   620
      else apfst SOME (dissect_coeqn_disc seq fun_names basic_ctr_specss
panny@54097
   621
          (SOME (abstract (List.rev fun_args) rhs)) maybe_code_rhs prems disc_concl matchedsss);
blanchet@53303
   622
blanchet@54159
   623
    val sel_concls = sels ~~ ctr_args
blanchet@53303
   624
      |> map (fn (sel, ctr_arg) => HOLogic.mk_eq (betapply (sel, lhs), ctr_arg));
blanchet@53303
   625
blanchet@53856
   626
(*
panny@54065
   627
val _ = tracing ("reduced\n    " ^ Syntax.string_of_term @{context} concl ^ "\nto\n    \<cdot> " ^
panny@54065
   628
 (is_some maybe_eqn_data_disc ? K (Syntax.string_of_term @{context} disc_concl ^ "\n    \<cdot> ")) "" ^
panny@54097
   629
 space_implode "\n    \<cdot> " (map (Syntax.string_of_term @{context}) sel_concls) ^
panny@54097
   630
 "\nfor premise(s)\n    \<cdot> " ^
panny@54097
   631
 space_implode "\n    \<cdot> " (map (Syntax.string_of_term @{context}) prems));
blanchet@53856
   632
*)
blanchet@53303
   633
panny@54160
   634
    val eqns_data_sel =
panny@54160
   635
      map (dissect_coeqn_sel fun_names basic_ctr_specss eqn' (SOME ctr)) sel_concls;
blanchet@53303
   636
  in
panny@53720
   637
    (the_list maybe_eqn_data_disc @ eqns_data_sel, matchedsss')
blanchet@53303
   638
  end;
blanchet@53303
   639
panny@54160
   640
fun dissect_coeqn_code lthy has_call fun_names basic_ctr_specss eqn' concl matchedsss =
panny@54065
   641
  let
panny@54065
   642
    val (lhs, (rhs', rhs)) = HOLogic.dest_eq concl ||> `(expand_corec_code_rhs lthy has_call []);
panny@54097
   643
    val (fun_name, fun_args) = strip_comb lhs |>> fst o dest_Free;
blanchet@54209
   644
    val SOME basic_ctr_specs = AList.lookup (op =) (fun_names ~~ basic_ctr_specss) fun_name;
panny@54065
   645
panny@54065
   646
    val cond_ctrs = fold_rev_corec_code_rhs lthy (fn cs => fn ctr => fn _ =>
panny@54160
   647
        if member ((op =) o apsnd #ctr) basic_ctr_specs ctr
panny@54065
   648
        then cons (ctr, cs)
blanchet@54246
   649
        else primcorec_error_eqn "not a constructor" ctr) [] rhs' []
panny@54065
   650
      |> AList.group (op =);
panny@54065
   651
blanchet@54068
   652
    val ctr_premss = (case cond_ctrs of [_] => [[]] | _ => map (s_dnf o snd) cond_ctrs);
panny@54065
   653
    val ctr_concls = cond_ctrs |> map (fn (ctr, _) =>
panny@54065
   654
        binder_types (fastype_of ctr)
panny@54065
   655
        |> map_index (fn (n, T) => massage_corec_code_rhs lthy (fn _ => fn ctr' => fn args =>
panny@54065
   656
          if ctr' = ctr then nth args n else Const (@{const_name undefined}, T)) [] rhs')
panny@54065
   657
        |> curry list_comb ctr
panny@54065
   658
        |> curry HOLogic.mk_eq lhs);
panny@54065
   659
  in
panny@54160
   660
    fold_map2 (dissect_coeqn_ctr false fun_names basic_ctr_specss eqn'
panny@54097
   661
        (SOME (abstract (List.rev fun_args) rhs)))
panny@54097
   662
      ctr_premss ctr_concls matchedsss
panny@54065
   663
  end;
panny@54065
   664
panny@54160
   665
fun dissect_coeqn lthy seq has_call fun_names (basic_ctr_specss : basic_corec_ctr_spec list list)
blanchet@54209
   666
    eqn' maybe_of_spec matchedsss =
blanchet@53303
   667
  let
panny@53654
   668
    val eqn = drop_All eqn'
blanchet@54246
   669
      handle TERM _ => primcorec_error_eqn "malformed function equation" eqn';
panny@54065
   670
    val (prems, concl) = Logic.strip_horn eqn
panny@53341
   671
      |> apfst (map HOLogic.dest_Trueprop) o apsnd HOLogic.dest_Trueprop;
blanchet@53303
   672
panny@54065
   673
    val head = concl
blanchet@53303
   674
      |> perhaps (try HOLogic.dest_not) |> perhaps (try (fst o HOLogic.dest_eq))
blanchet@53303
   675
      |> head_of;
blanchet@53303
   676
blanchet@54209
   677
    val maybe_rhs = concl |> perhaps (try HOLogic.dest_not) |> try (snd o HOLogic.dest_eq);
blanchet@53303
   678
panny@54160
   679
    val discs = maps (map #disc) basic_ctr_specss;
panny@54160
   680
    val sels = maps (maps #sels) basic_ctr_specss;
panny@54160
   681
    val ctrs = maps (map #ctr) basic_ctr_specss;
blanchet@53303
   682
  in
blanchet@53303
   683
    if member (op =) discs head orelse
blanchet@53303
   684
      is_some maybe_rhs andalso
blanchet@53303
   685
        member (op =) (filter (null o binder_types o fastype_of) ctrs) (the maybe_rhs) then
panny@54160
   686
      dissect_coeqn_disc seq fun_names basic_ctr_specss NONE NONE prems concl matchedsss
blanchet@53303
   687
      |>> single
blanchet@53303
   688
    else if member (op =) sels head then
blanchet@54209
   689
      ([dissect_coeqn_sel fun_names basic_ctr_specss eqn' maybe_of_spec concl], matchedsss)
panny@54065
   690
    else if is_Free head andalso member (op =) fun_names (fst (dest_Free head)) andalso
blanchet@54074
   691
      member (op =) ctrs (head_of (unfold_let (the maybe_rhs))) then
panny@54160
   692
      dissect_coeqn_ctr seq fun_names basic_ctr_specss eqn' NONE prems concl matchedsss
panny@54065
   693
    else if is_Free head andalso member (op =) fun_names (fst (dest_Free head)) andalso
panny@54065
   694
      null prems then
panny@54160
   695
      dissect_coeqn_code lthy has_call fun_names basic_ctr_specss eqn' concl matchedsss
panny@54065
   696
      |>> flat
blanchet@53303
   697
    else
blanchet@54246
   698
      primcorec_error_eqn "malformed function equation" eqn
blanchet@53303
   699
  end;
blanchet@53303
   700
blanchet@54002
   701
fun build_corec_arg_disc (ctr_specs : corec_ctr_spec list)
blanchet@54153
   702
    ({fun_args, ctr_no, prems, ...} : coeqn_data_disc) =
panny@53654
   703
  if is_none (#pred (nth ctr_specs ctr_no)) then I else
blanchet@54068
   704
    s_conjs prems
panny@53654
   705
    |> curry subst_bounds (List.rev fun_args)
panny@53654
   706
    |> HOLogic.tupled_lambda (HOLogic.mk_tuple fun_args)
panny@53654
   707
    |> K |> nth_map (the (#pred (nth ctr_specs ctr_no)));
blanchet@53303
   708
blanchet@54153
   709
fun build_corec_arg_no_call (sel_eqns : coeqn_data_sel list) sel =
panny@53720
   710
  find_first (equal sel o #sel) sel_eqns
panny@53720
   711
  |> try (fn SOME {fun_args, rhs_term, ...} => abs_tuple fun_args rhs_term)
panny@53720
   712
  |> the_default undef_const
panny@53411
   713
  |> K;
panny@53360
   714
blanchet@54153
   715
fun build_corec_args_mutual_call lthy has_call (sel_eqns : coeqn_data_sel list) sel =
blanchet@54208
   716
  (case find_first (equal sel o #sel) sel_eqns of
blanchet@54208
   717
    NONE => (I, I, I)
blanchet@54208
   718
  | SOME {fun_args, rhs_term, ... } =>
panny@53876
   719
    let
panny@54097
   720
      val bound_Ts = List.rev (map fastype_of fun_args);
blanchet@54207
   721
      fun rewrite_stop _ t = if has_call t then @{term False} else @{term True};
blanchet@54207
   722
      fun rewrite_end _ t = if has_call t then undef_const else t;
blanchet@54207
   723
      fun rewrite_cont bound_Ts t =
panny@53899
   724
        if has_call t then mk_tuple1 bound_Ts (snd (strip_comb t)) else undef_const;
blanchet@54102
   725
      fun massage f _ = massage_mutual_corec_call lthy has_call f bound_Ts rhs_term
panny@54097
   726
        |> abs_tuple fun_args;
panny@53876
   727
    in
blanchet@54207
   728
      (massage rewrite_stop, massage rewrite_end, massage rewrite_cont)
blanchet@54208
   729
    end);
panny@53360
   730
blanchet@54153
   731
fun build_corec_arg_nested_call lthy has_call (sel_eqns : coeqn_data_sel list) sel =
blanchet@54208
   732
  (case find_first (equal sel o #sel) sel_eqns of
blanchet@54208
   733
    NONE => I
blanchet@54208
   734
  | SOME {fun_args, rhs_term, ...} =>
panny@53899
   735
    let
panny@54097
   736
      val bound_Ts = List.rev (map fastype_of fun_args);
panny@53899
   737
      fun rewrite bound_Ts U T (Abs (v, V, b)) = Abs (v, V, rewrite (V :: bound_Ts) U T b)
panny@53899
   738
        | rewrite bound_Ts U T (t as _ $ _) =
panny@53899
   739
          let val (u, vs) = strip_comb t in
panny@53899
   740
            if is_Free u andalso has_call u then
panny@53899
   741
              Inr_const U T $ mk_tuple1 bound_Ts vs
panny@54215
   742
            else if const_name u = SOME @{const_name prod_case} then
panny@53899
   743
              map (rewrite bound_Ts U T) vs |> chop 1 |>> HOLogic.mk_split o the_single |> list_comb
panny@53899
   744
            else
panny@53899
   745
              list_comb (rewrite bound_Ts U T u, map (rewrite bound_Ts U T) vs)
panny@53899
   746
          end
panny@53899
   747
        | rewrite _ U T t =
panny@53899
   748
          if is_Free t andalso has_call t then Inr_const U T $ HOLogic.unit else t;
panny@53899
   749
      fun massage t =
panny@54097
   750
        rhs_term
blanchet@54102
   751
        |> massage_nested_corec_call lthy has_call rewrite bound_Ts (range_type (fastype_of t))
panny@53735
   752
        |> abs_tuple fun_args;
panny@53899
   753
    in
panny@53899
   754
      massage
blanchet@54208
   755
    end);
panny@53360
   756
blanchet@54153
   757
fun build_corec_args_sel lthy has_call (all_sel_eqns : coeqn_data_sel list)
blanchet@54002
   758
    (ctr_spec : corec_ctr_spec) =
blanchet@54208
   759
  (case filter (equal (#ctr ctr_spec) o #ctr) all_sel_eqns of
blanchet@54208
   760
    [] => I
blanchet@54208
   761
  | sel_eqns =>
blanchet@54208
   762
    let
blanchet@54208
   763
      val sel_call_list = #sels ctr_spec ~~ #calls ctr_spec;
blanchet@54208
   764
      val no_calls' = map_filter (try (apsnd (fn No_Corec n => n))) sel_call_list;
blanchet@54208
   765
      val mutual_calls' = map_filter (try (apsnd (fn Mutual_Corec n => n))) sel_call_list;
blanchet@54208
   766
      val nested_calls' = map_filter (try (apsnd (fn Nested_Corec n => n))) sel_call_list;
blanchet@54208
   767
    in
blanchet@54208
   768
      I
blanchet@54208
   769
      #> fold (fn (sel, n) => nth_map n (build_corec_arg_no_call sel_eqns sel)) no_calls'
blanchet@54208
   770
      #> fold (fn (sel, (q, g, h)) =>
blanchet@54208
   771
        let val (fq, fg, fh) = build_corec_args_mutual_call lthy has_call sel_eqns sel in
blanchet@54208
   772
          nth_map q fq o nth_map g fg o nth_map h fh end) mutual_calls'
blanchet@54208
   773
      #> fold (fn (sel, n) => nth_map n
blanchet@54208
   774
        (build_corec_arg_nested_call lthy has_call sel_eqns sel)) nested_calls'
blanchet@54208
   775
    end);
blanchet@53303
   776
blanchet@54153
   777
fun build_codefs lthy bs mxs has_call arg_Tss (corec_specs : corec_spec list)
blanchet@54153
   778
    (disc_eqnss : coeqn_data_disc list list) (sel_eqnss : coeqn_data_sel list list) =
panny@53654
   779
  let
panny@54160
   780
    val corecs = map #corec corec_specs;
panny@54160
   781
    val ctr_specss = map #ctr_specs corec_specs;
panny@53360
   782
    val corec_args = hd corecs
panny@53360
   783
      |> fst o split_last o binder_types o fastype_of
panny@53360
   784
      |> map (Const o pair @{const_name undefined})
panny@53720
   785
      |> fold2 (fold o build_corec_arg_disc) ctr_specss disc_eqnss
panny@53360
   786
      |> fold2 (fold o build_corec_args_sel lthy has_call) sel_eqnss ctr_specss;
panny@53735
   787
    fun currys [] t = t
panny@53735
   788
      | currys Ts t = t $ mk_tuple1 (List.rev Ts) (map Bound (length Ts - 1 downto 0))
panny@53735
   789
          |> fold_rev (Term.abs o pair Name.uu) Ts;
panny@53401
   790
blanchet@53856
   791
(*
panny@53360
   792
val _ = tracing ("corecursor arguments:\n    \<cdot> " ^
panny@53411
   793
 space_implode "\n    \<cdot> " (map (Syntax.string_of_term lthy) corec_args));
blanchet@53856
   794
*)
blanchet@53303
   795
panny@53654
   796
    val exclss' =
panny@53720
   797
      disc_eqnss
panny@53822
   798
      |> map (map (fn x => (#fun_args x, #ctr_no x, #prems x, #auto_gen x))
panny@53654
   799
        #> fst o (fn xs => fold_map (fn x => fn ys => ((x, ys), ys @ [x])) xs [])
panny@53654
   800
        #> maps (uncurry (map o pair)
panny@53822
   801
          #> map (fn ((fun_args, c, x, a), (_, c', y, a')) =>
blanchet@54068
   802
              ((c, c', a orelse a'), (x, s_not (s_conjs y)))
panny@53654
   803
            ||> apfst (map HOLogic.mk_Trueprop) o apsnd HOLogic.mk_Trueprop
panny@53654
   804
            ||> Logic.list_implies
panny@53654
   805
            ||> curry Logic.list_all (map dest_Free fun_args))))
blanchet@53303
   806
  in
blanchet@53303
   807
    map (list_comb o rpair corec_args) corecs
blanchet@53303
   808
    |> map2 (fn Ts => fn t => if length Ts = 0 then t $ HOLogic.unit else t) arg_Tss
blanchet@53303
   809
    |> map2 currys arg_Tss
blanchet@53303
   810
    |> Syntax.check_terms lthy
blanchet@54155
   811
    |> map3 (fn b => fn mx => fn t => ((b, mx), ((Binding.conceal (Thm.def_binding b), []), t)))
blanchet@54155
   812
      bs mxs
panny@53654
   813
    |> rpair exclss'
blanchet@53303
   814
  end;
blanchet@53303
   815
blanchet@54002
   816
fun mk_real_disc_eqns fun_binding arg_Ts ({ctr_specs, ...} : corec_spec)
blanchet@54153
   817
    (sel_eqns : coeqn_data_sel list) (disc_eqns : coeqn_data_disc list) =
panny@53720
   818
  if length disc_eqns <> length ctr_specs - 1 then disc_eqns else
panny@53720
   819
    let
panny@53720
   820
      val n = 0 upto length ctr_specs
panny@53720
   821
        |> the o find_first (fn idx => not (exists (equal idx o #ctr_no) disc_eqns));
panny@53722
   822
      val fun_args = (try (#fun_args o hd) disc_eqns, try (#fun_args o hd) sel_eqns)
panny@53722
   823
        |> the_default (map (curry Free Name.uu) arg_Ts) o merge_options;
panny@53720
   824
      val extra_disc_eqn = {
panny@53720
   825
        fun_name = Binding.name_of fun_binding,
panny@53720
   826
        fun_T = arg_Ts ---> body_type (fastype_of (#ctr (hd ctr_specs))),
panny@53722
   827
        fun_args = fun_args,
panny@53720
   828
        ctr = #ctr (nth ctr_specs n),
panny@53720
   829
        ctr_no = n,
panny@53720
   830
        disc = #disc (nth ctr_specs n),
blanchet@54067
   831
        prems = maps (s_not_conj o #prems) disc_eqns,
panny@53822
   832
        auto_gen = true,
panny@54097
   833
        maybe_ctr_rhs = NONE,
panny@54097
   834
        maybe_code_rhs = NONE,
panny@53720
   835
        user_eqn = undef_const};
panny@53720
   836
    in
panny@53720
   837
      chop n disc_eqns ||> cons extra_disc_eqn |> (op @)
panny@53720
   838
    end;
panny@53720
   839
blanchet@54243
   840
fun find_corec_calls ctxt has_call basic_ctr_specs ({ctr, sel, rhs_term, ...} : coeqn_data_sel) =
panny@54160
   841
  let
panny@54160
   842
    val sel_no = find_first (equal ctr o #ctr) basic_ctr_specs
panny@54160
   843
      |> find_index (equal sel) o #sels o the;
blanchet@54243
   844
    fun find t = if has_call t then snd (fold_rev_corec_call ctxt (K cons) [] t []) else [];
panny@54160
   845
  in
panny@54160
   846
    find rhs_term
panny@54160
   847
    |> K |> nth_map sel_no |> AList.map_entry (op =) ctr
panny@54160
   848
  end;
panny@54160
   849
blanchet@54209
   850
fun add_primcorec_ursive maybe_tac seq fixes specs maybe_of_specs lthy =
blanchet@53303
   851
  let
traytel@53352
   852
    val (bs, mxs) = map_split (apfst fst) fixes;
blanchet@53303
   853
    val (arg_Ts, res_Ts) = map (strip_type o snd o fst #>> HOLogic.mk_tupleT) fixes |> split_list;
blanchet@53303
   854
panny@54160
   855
    val fun_names = map Binding.name_of bs;
panny@54160
   856
    val basic_ctr_specss = map (basic_corec_specs_of lthy) res_Ts;
panny@54160
   857
    val has_call = exists_subterm (map (fst #>> Binding.name_of #> Free) fixes |> member (op =));
panny@54160
   858
    val eqns_data =
panny@54160
   859
      fold_map2 (dissect_coeqn lthy seq has_call fun_names basic_ctr_specss) (map snd specs)
blanchet@54209
   860
        maybe_of_specs []
panny@54160
   861
      |> flat o fst;
panny@54160
   862
panny@54160
   863
    val callssss =
panny@54160
   864
      map_filter (try (fn Sel x => x)) eqns_data
panny@54160
   865
      |> partition_eq ((op =) o pairself #fun_name)
panny@54160
   866
      |> fst o finds (fn (x, ({fun_name, ...} :: _)) => x = fun_name) fun_names
panny@54161
   867
      |> map (flat o snd)
blanchet@54243
   868
      |> map2 (fold o find_corec_calls lthy has_call) basic_ctr_specss
panny@54160
   869
      |> map2 (curry (op |>)) (map (map (fn {ctr, sels, ...} =>
panny@54160
   870
        (ctr, map (K []) sels))) basic_ctr_specss);
panny@54160
   871
panny@54160
   872
(*
panny@54160
   873
val _ = tracing ("callssss = " ^ @{make_string} callssss);
panny@54160
   874
*)
blanchet@53303
   875
blanchet@53830
   876
    val ((n2m, corec_specs', _, coinduct_thm, strong_coinduct_thm, coinduct_thms,
blanchet@53797
   877
          strong_coinduct_thms), lthy') =
blanchet@53794
   878
      corec_specs_of bs arg_Ts res_Ts (get_indices fixes) callssss lthy;
blanchet@53830
   879
    val actual_nn = length bs;
blanchet@53830
   880
    val corec_specs = take actual_nn corec_specs'; (*###*)
blanchet@54178
   881
    val ctr_specss = map #ctr_specs corec_specs;
blanchet@53303
   882
panny@53720
   883
    val disc_eqnss' = map_filter (try (fn Disc x => x)) eqns_data
panny@53654
   884
      |> partition_eq ((op =) o pairself #fun_name)
panny@53720
   885
      |> fst o finds (fn (x, ({fun_name, ...} :: _)) => x = fun_name) fun_names
panny@53654
   886
      |> map (sort ((op <) o pairself #ctr_no |> make_ord) o flat o snd);
panny@53720
   887
    val _ = disc_eqnss' |> map (fn x =>
panny@53720
   888
      let val d = duplicates ((op =) o pairself #ctr_no) x in null d orelse
blanchet@54246
   889
        primcorec_error_eqns "excess discriminator formula in definition"
panny@53720
   890
          (maps (fn t => filter (equal (#ctr_no t) o #ctr_no) x) d |> map #user_eqn) end);
panny@53654
   891
panny@53654
   892
    val sel_eqnss = map_filter (try (fn Sel x => x)) eqns_data
panny@53654
   893
      |> partition_eq ((op =) o pairself #fun_name)
panny@53720
   894
      |> fst o finds (fn (x, ({fun_name, ...} :: _)) => x = fun_name) fun_names
panny@53654
   895
      |> map (flat o snd);
panny@53654
   896
panny@53360
   897
    val arg_Tss = map (binder_types o snd o fst) fixes;
panny@53722
   898
    val disc_eqnss = map5 mk_real_disc_eqns bs arg_Tss corec_specs sel_eqnss disc_eqnss';
panny@53654
   899
    val (defs, exclss') =
blanchet@54153
   900
      build_codefs lthy' bs mxs has_call arg_Tss corec_specs disc_eqnss sel_eqnss;
panny@53654
   901
blanchet@53923
   902
    fun excl_tac (c, c', a) =
blanchet@54177
   903
      if a orelse c = c' orelse seq then SOME (K (HEADGOAL (mk_primcorec_assumption_tac lthy [])))
blanchet@54177
   904
      else maybe_tac;
panny@53822
   905
blanchet@53856
   906
(*
panny@53822
   907
val _ = tracing ("exclusiveness properties:\n    \<cdot> " ^
panny@53822
   908
 space_implode "\n    \<cdot> " (maps (map (Syntax.string_of_term lthy o snd)) exclss'));
blanchet@53856
   909
*)
panny@53822
   910
panny@53822
   911
    val exclss'' = exclss' |> map (map (fn (idx, t) =>
blanchet@54177
   912
      (idx, (Option.map (Goal.prove lthy [] [] t #> Thm.close_derivation) (excl_tac idx), t))));
panny@53654
   913
    val taut_thmss = map (map (apsnd (the o fst)) o filter (is_some o fst o snd)) exclss'';
blanchet@54180
   914
    val (goal_idxss, goalss) = exclss''
panny@53654
   915
      |> map (map (apsnd (rpair [] o snd)) o filter (is_none o fst o snd))
panny@53654
   916
      |> split_list o map split_list;
panny@53654
   917
panny@53654
   918
    fun prove thmss' def_thms' lthy =
panny@53654
   919
      let
panny@53654
   920
        val def_thms = map (snd o snd) def_thms';
panny@53654
   921
blanchet@54180
   922
        val exclss' = map (op ~~) (goal_idxss ~~ thmss');
panny@53654
   923
        fun mk_exclsss excls n =
panny@53654
   924
          (excls, map (fn k => replicate k [TrueI] @ replicate (n - k) []) (0 upto n - 1))
panny@53822
   925
          |-> fold (fn ((c, c', _), thm) => nth_map c (nth_map c' (K [thm])));
panny@53654
   926
        val exclssss = (exclss' ~~ taut_thmss |> map (op @), fun_names ~~ corec_specs)
panny@53654
   927
          |-> map2 (fn excls => fn (_, {ctr_specs, ...}) => mk_exclsss excls (length ctr_specs));
panny@53654
   928
blanchet@54002
   929
        fun prove_disc ({ctr_specs, ...} : corec_spec) exclsss
blanchet@54153
   930
            ({fun_name, fun_T, fun_args, ctr_no, prems, ...} : coeqn_data_disc) =
panny@53722
   931
          if Term.aconv_untyped (#disc (nth ctr_specs ctr_no), @{term "\<lambda>x. x = x"}) then [] else
panny@53720
   932
            let
panny@53722
   933
              val {disc_corec, ...} = nth ctr_specs ctr_no;
panny@53720
   934
              val k = 1 + ctr_no;
panny@53720
   935
              val m = length prems;
panny@53720
   936
              val t =
panny@53720
   937
                list_comb (Free (fun_name, fun_T), map Bound (length fun_args - 1 downto 0))
panny@53720
   938
                |> curry betapply (#disc (nth ctr_specs ctr_no)) (*###*)
panny@53720
   939
                |> HOLogic.mk_Trueprop
panny@53720
   940
                |> curry Logic.list_implies (map HOLogic.mk_Trueprop prems)
panny@53720
   941
                |> curry Logic.list_all (map dest_Free fun_args);
panny@53720
   942
            in
panny@54097
   943
              if prems = [@{term False}] then [] else
panny@53720
   944
              mk_primcorec_disc_tac lthy def_thms disc_corec k m exclsss
panny@53720
   945
              |> K |> Goal.prove lthy [] [] t
blanchet@54176
   946
              |> Thm.close_derivation
panny@53720
   947
              |> pair (#disc (nth ctr_specs ctr_no))
panny@53720
   948
              |> single
panny@53720
   949
            end;
panny@53720
   950
blanchet@54002
   951
        fun prove_sel ({nested_maps, nested_map_idents, nested_map_comps, ctr_specs, ...}
blanchet@54153
   952
            : corec_spec) (disc_eqns : coeqn_data_disc list) exclsss
blanchet@54153
   953
            ({fun_name, fun_T, fun_args, ctr, sel, rhs_term, ...} : coeqn_data_sel) =
panny@53654
   954
          let
blanchet@53909
   955
            val SOME ctr_spec = find_first (equal ctr o #ctr) ctr_specs;
panny@53720
   956
            val ctr_no = find_index (equal ctr o #ctr) ctr_specs;
blanchet@54067
   957
            val prems = the_default (maps (s_not_conj o #prems) disc_eqns)
panny@53720
   958
                (find_first (equal ctr_no o #ctr_no) disc_eqns |> Option.map #prems);
panny@53720
   959
            val sel_corec = find_index (equal sel) (#sels ctr_spec)
panny@53720
   960
              |> nth (#sel_corecs ctr_spec);
panny@53654
   961
            val k = 1 + ctr_no;
panny@53654
   962
            val m = length prems;
panny@53654
   963
            val t =
panny@53720
   964
              list_comb (Free (fun_name, fun_T), map Bound (length fun_args - 1 downto 0))
panny@53720
   965
              |> curry betapply sel
panny@53720
   966
              |> rpair (abstract (List.rev fun_args) rhs_term)
panny@53720
   967
              |> HOLogic.mk_Trueprop o HOLogic.mk_eq
panny@53654
   968
              |> curry Logic.list_implies (map HOLogic.mk_Trueprop prems)
panny@53720
   969
              |> curry Logic.list_all (map dest_Free fun_args);
blanchet@53925
   970
            val (distincts, _, sel_splits, sel_split_asms) = case_thms_of_term lthy [] rhs_term;
panny@53654
   971
          in
blanchet@53918
   972
            mk_primcorec_sel_tac lthy def_thms distincts sel_splits sel_split_asms nested_maps
blanchet@53910
   973
              nested_map_idents nested_map_comps sel_corec k m exclsss
panny@53654
   974
            |> K |> Goal.prove lthy [] [] t
blanchet@54176
   975
            |> Thm.close_derivation
panny@53720
   976
            |> pair sel
panny@53654
   977
          end;
panny@53654
   978
blanchet@54153
   979
        fun prove_ctr disc_alist sel_alist (disc_eqns : coeqn_data_disc list)
blanchet@54153
   980
            (sel_eqns : coeqn_data_sel list) ({ctr, disc, sels, collapse, ...} : corec_ctr_spec) =
panny@54097
   981
          (* don't try to prove theorems when some sel_eqns are missing *)
panny@53720
   982
          if not (exists (equal ctr o #ctr) disc_eqns)
panny@53722
   983
              andalso not (exists (equal ctr o #ctr) sel_eqns)
panny@54097
   984
            orelse
panny@53720
   985
              filter (equal ctr o #ctr) sel_eqns
panny@53720
   986
              |> fst o finds ((op =) o apsnd #sel) sels
panny@53720
   987
              |> exists (null o snd)
panny@53720
   988
          then [] else
panny@53720
   989
            let
panny@54097
   990
              val (fun_name, fun_T, fun_args, prems, maybe_rhs) =
panny@53722
   991
                (find_first (equal ctr o #ctr) disc_eqns, find_first (equal ctr o #ctr) sel_eqns)
panny@54097
   992
                |>> Option.map (fn x => (#fun_name x, #fun_T x, #fun_args x, #prems x,
panny@54097
   993
                  #maybe_ctr_rhs x))
panny@54097
   994
                ||> Option.map (fn x => (#fun_name x, #fun_T x, #fun_args x, [], NONE))
panny@53722
   995
                |> the o merge_options;
panny@53720
   996
              val m = length prems;
panny@54097
   997
              val t = (if is_some maybe_rhs then the maybe_rhs else
panny@54097
   998
                  filter (equal ctr o #ctr) sel_eqns
panny@54097
   999
                  |> fst o finds ((op =) o apsnd #sel) sels
panny@54097
  1000
                  |> map (snd #> (fn [x] => (List.rev (#fun_args x), #rhs_term x)) #-> abstract)
panny@54097
  1001
                  |> curry list_comb ctr)
panny@53720
  1002
                |> curry HOLogic.mk_eq (list_comb (Free (fun_name, fun_T),
panny@53720
  1003
                  map Bound (length fun_args - 1 downto 0)))
panny@53720
  1004
                |> HOLogic.mk_Trueprop
panny@53720
  1005
                |> curry Logic.list_implies (map HOLogic.mk_Trueprop prems)
panny@53720
  1006
                |> curry Logic.list_all (map dest_Free fun_args);
blanchet@53791
  1007
              val maybe_disc_thm = AList.lookup (op =) disc_alist disc;
blanchet@53791
  1008
              val sel_thms = map snd (filter (member (op =) sels o fst) sel_alist);
panny@53720
  1009
            in
panny@54097
  1010
              if prems = [@{term False}] then [] else
panny@54097
  1011
                mk_primcorec_ctr_of_dtr_tac lthy m collapse maybe_disc_thm sel_thms
panny@54097
  1012
                |> K |> Goal.prove lthy [] [] t
blanchet@54176
  1013
                |> Thm.close_derivation
panny@54097
  1014
                |> pair ctr
panny@54097
  1015
                |> single
panny@53876
  1016
            end;
panny@53720
  1017
blanchet@54178
  1018
        fun prove_code disc_eqns sel_eqns ctr_alist ctr_specs =
panny@54098
  1019
          let
panny@54097
  1020
            val (fun_name, fun_T, fun_args, maybe_rhs) =
panny@54097
  1021
              (find_first (member (op =) (map #ctr ctr_specs) o #ctr) disc_eqns,
panny@54097
  1022
               find_first (member (op =) (map #ctr ctr_specs) o #ctr) sel_eqns)
panny@54097
  1023
              |>> Option.map (fn x => (#fun_name x, #fun_T x, #fun_args x, #maybe_code_rhs x))
panny@54097
  1024
              ||> Option.map (fn x => (#fun_name x, #fun_T x, #fun_args x, NONE))
panny@54097
  1025
              |> the o merge_options;
panny@54097
  1026
blanchet@54173
  1027
            val bound_Ts = List.rev (map fastype_of fun_args);
blanchet@54173
  1028
panny@54120
  1029
            val lhs = list_comb (Free (fun_name, fun_T), map Bound (length fun_args - 1 downto 0));
blanchet@54173
  1030
            val maybe_rhs_info =
blanchet@54173
  1031
              (case maybe_rhs of
blanchet@54173
  1032
                SOME rhs =>
blanchet@54173
  1033
                let
blanchet@54173
  1034
                  val raw_rhs = expand_corec_code_rhs lthy has_call bound_Ts rhs;
blanchet@54173
  1035
                  val cond_ctrs =
blanchet@54173
  1036
                    fold_rev_corec_code_rhs lthy (K oo (cons oo pair)) bound_Ts raw_rhs [];
blanchet@54173
  1037
                  val ctr_thms = map (the o AList.lookup (op =) ctr_alist o snd) cond_ctrs;
blanchet@54173
  1038
                in SOME (rhs, raw_rhs, ctr_thms) end
blanchet@54173
  1039
              | NONE =>
blanchet@54173
  1040
                let
blanchet@54173
  1041
                  fun prove_code_ctr {ctr, sels, ...} =
blanchet@54173
  1042
                    if not (exists (equal ctr o fst) ctr_alist) then NONE else
blanchet@54173
  1043
                      let
blanchet@54173
  1044
                        val prems = find_first (equal ctr o #ctr) disc_eqns
blanchet@54173
  1045
                          |> Option.map #prems |> the_default [];
blanchet@54173
  1046
                        val t =
blanchet@54173
  1047
                          filter (equal ctr o #ctr) sel_eqns
blanchet@54173
  1048
                          |> fst o finds ((op =) o apsnd #sel) sels
blanchet@54173
  1049
                          |> map (snd #> (fn [x] => (List.rev (#fun_args x), #rhs_term x))
blanchet@54173
  1050
                            #-> abstract)
blanchet@54173
  1051
                          |> curry list_comb ctr;
blanchet@54173
  1052
                      in
blanchet@54173
  1053
                        SOME (prems, t)
blanchet@54173
  1054
                      end;
blanchet@54173
  1055
                  val maybe_ctr_conds_argss = map prove_code_ctr ctr_specs;
blanchet@54173
  1056
                in
blanchet@54173
  1057
                  if exists is_none maybe_ctr_conds_argss then NONE else
panny@54097
  1058
                    let
blanchet@54173
  1059
                      val rhs = fold_rev (fn SOME (prems, u) => fn t => mk_If (s_conjs prems) u t)
blanchet@54173
  1060
                        maybe_ctr_conds_argss
blanchet@54173
  1061
                        (Const (@{const_name Code.abort}, @{typ String.literal} -->
blanchet@54173
  1062
                            (@{typ unit} --> body_type fun_T) --> body_type fun_T) $
blanchet@54178
  1063
                          HOLogic.mk_literal fun_name $
blanchet@54173
  1064
                          absdummy @{typ unit} (incr_boundvars 1 lhs));
blanchet@54173
  1065
                    in SOME (rhs, rhs, map snd ctr_alist) end
blanchet@54173
  1066
                end);
panny@54097
  1067
          in
blanchet@54173
  1068
            (case maybe_rhs_info of
blanchet@54173
  1069
              NONE => []
blanchet@54173
  1070
            | SOME (rhs, raw_rhs, ctr_thms) =>
panny@54097
  1071
              let
panny@54097
  1072
                val ms = map (Logic.count_prems o prop_of) ctr_thms;
blanchet@54172
  1073
                val (raw_t, t) = (raw_rhs, rhs)
blanchet@54172
  1074
                  |> pairself
blanchet@54172
  1075
                    (curry HOLogic.mk_eq (list_comb (Free (fun_name, fun_T),
blanchet@54172
  1076
                      map Bound (length fun_args - 1 downto 0)))
blanchet@54172
  1077
                    #> HOLogic.mk_Trueprop
blanchet@54172
  1078
                    #> curry Logic.list_all (map dest_Free fun_args));
panny@54098
  1079
                val (distincts, discIs, sel_splits, sel_split_asms) =
blanchet@54172
  1080
                  case_thms_of_term lthy bound_Ts raw_rhs;
panny@54098
  1081
blanchet@54172
  1082
                val raw_code_thm = mk_primcorec_raw_code_of_ctr_tac lthy distincts discIs sel_splits
panny@54097
  1083
                    sel_split_asms ms ctr_thms
blanchet@54176
  1084
                  |> K |> Goal.prove lthy [] [] raw_t
blanchet@54176
  1085
                  |> Thm.close_derivation;
blanchet@54172
  1086
              in
blanchet@54174
  1087
                mk_primcorec_code_of_raw_code_tac lthy distincts sel_splits raw_code_thm
blanchet@54172
  1088
                |> K |> Goal.prove lthy [] [] t
blanchet@54176
  1089
                |> Thm.close_derivation
blanchet@54172
  1090
                |> single
blanchet@54173
  1091
              end)
blanchet@54173
  1092
          end;
panny@54097
  1093
blanchet@53791
  1094
        val disc_alists = map3 (maps oo prove_disc) corec_specs exclssss disc_eqnss;
blanchet@53791
  1095
        val sel_alists = map4 (map ooo prove_sel) corec_specs disc_eqnss exclssss sel_eqnss;
blanchet@53791
  1096
        val disc_thmss = map (map snd) disc_alists;
blanchet@53791
  1097
        val sel_thmss = map (map snd) sel_alists;
panny@54097
  1098
panny@54097
  1099
        val ctr_alists = map5 (maps oooo prove_ctr) disc_alists sel_alists disc_eqnss sel_eqnss
blanchet@54178
  1100
          ctr_specss;
panny@54097
  1101
        val ctr_thmss = map (map snd) ctr_alists;
panny@54097
  1102
blanchet@54178
  1103
        val code_thmss = map4 prove_code disc_eqnss sel_eqnss ctr_alists ctr_specss;
blanchet@53791
  1104
blanchet@54030
  1105
        val simp_thmss = map2 append disc_thmss sel_thmss
blanchet@53795
  1106
blanchet@53797
  1107
        val common_name = mk_common_name fun_names;
blanchet@53797
  1108
blanchet@53791
  1109
        val notes =
blanchet@53830
  1110
          [(coinductN, map (if n2m then single else K []) coinduct_thms, []),
blanchet@54145
  1111
           (codeN, code_thmss, code_nitpicksimp_attrs),
blanchet@53797
  1112
           (ctrN, ctr_thmss, []),
blanchet@53791
  1113
           (discN, disc_thmss, simp_attrs),
blanchet@53795
  1114
           (selN, sel_thmss, simp_attrs),
blanchet@53797
  1115
           (simpsN, simp_thmss, []),
blanchet@53830
  1116
           (strong_coinductN, map (if n2m then single else K []) strong_coinduct_thms, [])]
blanchet@53791
  1117
          |> maps (fn (thmN, thmss, attrs) =>
blanchet@53791
  1118
            map2 (fn fun_name => fn thms =>
blanchet@53791
  1119
                ((Binding.qualify true fun_name (Binding.name thmN), attrs), [(thms, [])]))
blanchet@53830
  1120
              fun_names (take actual_nn thmss))
blanchet@53791
  1121
          |> filter_out (null o fst o hd o snd);
blanchet@53797
  1122
blanchet@53797
  1123
        val common_notes =
blanchet@53830
  1124
          [(coinductN, if n2m then [coinduct_thm] else [], []),
blanchet@53830
  1125
           (strong_coinductN, if n2m then [strong_coinduct_thm] else [], [])]
blanchet@53797
  1126
          |> filter_out (null o #2)
blanchet@53797
  1127
          |> map (fn (thmN, thms, attrs) =>
blanchet@53797
  1128
            ((Binding.qualify true common_name (Binding.name thmN), attrs), [(thms, [])]));
panny@53654
  1129
      in
blanchet@54030
  1130
        lthy |> Local_Theory.notes (notes @ common_notes) |> snd
panny@53654
  1131
      end;
panny@53822
  1132
panny@53822
  1133
    fun after_qed thmss' = fold_map Local_Theory.define defs #-> prove thmss';
blanchet@53303
  1134
  in
blanchet@54177
  1135
    (goalss, after_qed, lthy')
panny@53822
  1136
  end;
blanchet@53303
  1137
blanchet@54177
  1138
fun add_primcorec_ursive_cmd maybe_tac seq (raw_fixes, raw_specs') lthy =
blanchet@53303
  1139
  let
blanchet@54209
  1140
    val (raw_specs, maybe_of_specs) =
blanchet@54209
  1141
      split_list raw_specs' ||> map (Option.map (Syntax.read_term lthy));
panny@53831
  1142
    val ((fixes, specs), _) = Specification.read_spec raw_fixes raw_specs lthy;
blanchet@53303
  1143
  in
blanchet@54209
  1144
    add_primcorec_ursive maybe_tac seq fixes specs maybe_of_specs lthy
blanchet@54246
  1145
    handle ERROR str => primcorec_error str
blanchet@53303
  1146
  end
blanchet@54246
  1147
  handle Primcorec_Error (str, eqns) =>
blanchet@53303
  1148
    if null eqns
blanchet@53303
  1149
    then error ("primcorec error:\n  " ^ str)
blanchet@53303
  1150
    else error ("primcorec error:\n  " ^ str ^ "\nin\n  " ^
panny@53822
  1151
      space_implode "\n  " (map (quote o Syntax.string_of_term lthy) eqns));
panny@53822
  1152
blanchet@54177
  1153
val add_primcorecursive_cmd = (fn (goalss, after_qed, lthy) =>
blanchet@54177
  1154
  lthy
blanchet@54177
  1155
  |> Proof.theorem NONE after_qed goalss
blanchet@54177
  1156
  |> Proof.refine (Method.primitive_text I)
blanchet@54177
  1157
  |> Seq.hd) ooo add_primcorec_ursive_cmd NONE;
blanchet@54177
  1158
blanchet@54177
  1159
val add_primcorec_cmd = (fn (goalss, after_qed, lthy) =>
blanchet@54177
  1160
  lthy
blanchet@54177
  1161
  |> after_qed (map (fn [] => []
blanchet@54246
  1162
      | _ => primcorec_error "need exclusiveness proofs - use primcorecursive instead of primcorec")
blanchet@54177
  1163
    goalss)) ooo add_primcorec_ursive_cmd (SOME (fn {context = ctxt, ...} => auto_tac ctxt));
blanchet@53303
  1164
blanchet@53303
  1165
end;