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