src/HOL/BNF/Tools/bnf_fp_rec_sugar.ML
author blanchet
Fri Aug 30 14:17:19 2013 +0200 (2013-08-30)
changeset 53329 c31c0c311cf0
parent 53310 8af01463b2d3
child 53335 585b2fee55e5
permissions -rw-r--r--
more canonical naming
blanchet@53303
     1
(*  Title:      HOL/BNF/Tools/bnf_fp_rec_sugar.ML
blanchet@53303
     2
    Author:     Lorenz Panny, TU Muenchen
blanchet@53303
     3
    Copyright   2013
blanchet@53303
     4
blanchet@53303
     5
Recursor and corecursor sugar.
blanchet@53303
     6
*)
blanchet@53303
     7
blanchet@53303
     8
signature BNF_FP_REC_SUGAR =
blanchet@53303
     9
sig
blanchet@53303
    10
  val add_primrec_cmd: (binding * string option * mixfix) list ->
blanchet@53303
    11
    (Attrib.binding * string) list -> local_theory -> local_theory;
blanchet@53310
    12
  val add_primcorec_cmd: bool ->
blanchet@53310
    13
    (binding * string option * mixfix) list * (Attrib.binding * string) list -> Proof.context ->
blanchet@53310
    14
    Proof.state
blanchet@53303
    15
end;
blanchet@53303
    16
blanchet@53303
    17
structure BNF_FP_Rec_Sugar : BNF_FP_REC_SUGAR =
blanchet@53303
    18
struct
blanchet@53303
    19
blanchet@53303
    20
open BNF_Util
blanchet@53303
    21
open BNF_FP_Util
blanchet@53303
    22
open BNF_FP_Rec_Sugar_Util
blanchet@53303
    23
open BNF_FP_Rec_Sugar_Tactics
blanchet@53303
    24
blanchet@53303
    25
exception Primrec_Error of string * term list;
blanchet@53303
    26
blanchet@53303
    27
fun primrec_error str = raise Primrec_Error (str, []);
blanchet@53303
    28
fun primrec_error_eqn str eqn = raise Primrec_Error (str, [eqn]);
blanchet@53303
    29
fun primrec_error_eqns str eqns = raise Primrec_Error (str, eqns);
blanchet@53303
    30
blanchet@53303
    31
fun finds eq = fold_map (fn x => List.partition (curry eq x) #>> pair x);
blanchet@53303
    32
blanchet@53303
    33
val simp_attrs = @{attributes [simp]};
blanchet@53303
    34
blanchet@53303
    35
blanchet@53310
    36
blanchet@53310
    37
(* Primrec *)
blanchet@53310
    38
blanchet@53303
    39
type eqn_data = {
blanchet@53303
    40
  fun_name: string,
blanchet@53303
    41
  rec_type: typ,
blanchet@53303
    42
  ctr: term,
blanchet@53303
    43
  ctr_args: term list,
blanchet@53303
    44
  left_args: term list,
blanchet@53303
    45
  right_args: term list,
blanchet@53303
    46
  res_type: typ,
blanchet@53303
    47
  rhs_term: term,
blanchet@53303
    48
  user_eqn: term
blanchet@53303
    49
};
blanchet@53303
    50
blanchet@53303
    51
fun permute_args n t = list_comb (t, map Bound (0 :: (n downto 1)))
blanchet@53304
    52
  |> fold (K (fn u => Abs (Name.uu, dummyT, u))) (0 upto n);
blanchet@53303
    53
blanchet@53303
    54
fun dissect_eqn lthy fun_names eqn' =
blanchet@53303
    55
  let
blanchet@53303
    56
    val eqn = subst_bounds (strip_qnt_vars @{const_name all} eqn' |> map Free |> rev,
blanchet@53303
    57
        strip_qnt_body @{const_name all} eqn') |> HOLogic.dest_Trueprop
blanchet@53303
    58
        handle TERM _ =>
blanchet@53303
    59
          primrec_error_eqn "malformed function equation (expected \"lhs = rhs\")" eqn';
blanchet@53303
    60
    val (lhs, rhs) = HOLogic.dest_eq eqn
blanchet@53303
    61
        handle TERM _ =>
blanchet@53303
    62
          primrec_error_eqn "malformed function equation (expected \"lhs = rhs\")" eqn';
blanchet@53303
    63
    val (fun_name, args) = strip_comb lhs
blanchet@53303
    64
      |>> (fn x => if is_Free x then fst (dest_Free x)
blanchet@53303
    65
          else primrec_error_eqn "malformed function equation (does not start with free)" eqn);
blanchet@53303
    66
    val (left_args, rest) = take_prefix is_Free args;
blanchet@53303
    67
    val (nonfrees, right_args) = take_suffix is_Free rest;
blanchet@53303
    68
    val _ = length nonfrees = 1 orelse if length nonfrees = 0 then
blanchet@53303
    69
      primrec_error_eqn "constructor pattern missing in left-hand side" eqn else
blanchet@53303
    70
      primrec_error_eqn "more than one non-variable argument in left-hand side" eqn;
blanchet@53303
    71
    val _ = member (op =) fun_names fun_name orelse
blanchet@53303
    72
      primrec_error_eqn "malformed function equation (does not start with function name)" eqn
blanchet@53303
    73
blanchet@53303
    74
    val (ctr, ctr_args) = strip_comb (the_single nonfrees);
blanchet@53303
    75
    val _ = try (num_binder_types o fastype_of) ctr = SOME (length ctr_args) orelse
blanchet@53303
    76
      primrec_error_eqn "partially applied constructor in pattern" eqn;
blanchet@53303
    77
    val _ = let val d = duplicates (op =) (left_args @ ctr_args @ right_args) in null d orelse
blanchet@53303
    78
      primrec_error_eqn ("duplicate variable \"" ^ Syntax.string_of_term lthy (hd d) ^
blanchet@53303
    79
        "\" in left-hand side") eqn end;
blanchet@53303
    80
    val _ = forall is_Free ctr_args orelse
blanchet@53303
    81
      primrec_error_eqn "non-primitive pattern in left-hand side" eqn;
blanchet@53303
    82
    val _ =
blanchet@53303
    83
      let val b = fold_aterms (fn x as Free (v, _) =>
blanchet@53303
    84
        if (not (member (op =) (left_args @ ctr_args @ right_args) x) andalso
blanchet@53303
    85
        not (member (op =) fun_names v) andalso
blanchet@53303
    86
        not (Variable.is_fixed lthy v)) then cons x else I | _ => I) rhs []
blanchet@53303
    87
      in
blanchet@53303
    88
        null b orelse
blanchet@53303
    89
        primrec_error_eqn ("extra variable(s) in right-hand side: " ^
blanchet@53303
    90
          commas (map (Syntax.string_of_term lthy) b)) eqn
blanchet@53303
    91
      end;
blanchet@53303
    92
  in
blanchet@53303
    93
    {fun_name = fun_name,
blanchet@53303
    94
     rec_type = body_type (type_of ctr),
blanchet@53303
    95
     ctr = ctr,
blanchet@53303
    96
     ctr_args = ctr_args,
blanchet@53303
    97
     left_args = left_args,
blanchet@53303
    98
     right_args = right_args,
blanchet@53303
    99
     res_type = map fastype_of (left_args @ right_args) ---> fastype_of rhs,
blanchet@53303
   100
     rhs_term = rhs,
blanchet@53303
   101
     user_eqn = eqn'}
blanchet@53303
   102
  end;
blanchet@53303
   103
blanchet@53303
   104
(* substitutes (f ls x rs) by (y ls rs) for all f: get_idx f \<ge> 0, (x,y) \<in> substs *)
blanchet@53303
   105
fun subst_direct_calls get_idx get_ctr_pos substs = 
blanchet@53303
   106
  let
blanchet@53303
   107
    fun subst (Abs (v, T, b)) = Abs (v, T, subst b)
blanchet@53303
   108
      | subst t =
blanchet@53303
   109
        let
blanchet@53303
   110
          val (f, args) = strip_comb t;
blanchet@53303
   111
          val idx = get_idx f;
blanchet@53303
   112
          val ctr_pos  = if idx >= 0 then get_ctr_pos idx else ~1;
blanchet@53303
   113
        in
blanchet@53303
   114
          if idx < 0 then
blanchet@53303
   115
            list_comb (f, map subst args)
blanchet@53303
   116
          else if ctr_pos >= length args then
blanchet@53303
   117
            primrec_error_eqn "too few arguments in recursive call" t
blanchet@53303
   118
          else
blanchet@53303
   119
            let
blanchet@53303
   120
              val (key, repl) = the (find_first (equal (nth args ctr_pos) o fst) substs)
blanchet@53303
   121
                handle Option.Option => primrec_error_eqn
blanchet@53303
   122
                  "recursive call not directly applied to constructor argument" t;
blanchet@53303
   123
            in
blanchet@53303
   124
              remove (op =) key args |> map subst |> curry list_comb repl
blanchet@53303
   125
            end
blanchet@53303
   126
        end
blanchet@53303
   127
  in subst end;
blanchet@53303
   128
blanchet@53303
   129
(* FIXME get rid of funs_data or get_indices *)
blanchet@53303
   130
fun rewrite_map_arg funs_data get_indices y rec_type res_type =
blanchet@53303
   131
  let
blanchet@53303
   132
    val pT = HOLogic.mk_prodT (rec_type, res_type);
blanchet@53303
   133
    val fstx = fst_const pT;
blanchet@53303
   134
    val sndx = snd_const pT;
blanchet@53303
   135
blanchet@53303
   136
    val SOME ({fun_name, left_args, ...} :: _) =
blanchet@53303
   137
      find_first (equal rec_type o #rec_type o hd) funs_data;
blanchet@53303
   138
    val ctr_pos = length left_args;
blanchet@53303
   139
blanchet@53303
   140
    fun subst _ d (t as Bound d') = t |> d = d' ? curry (op $) fstx
blanchet@53303
   141
      | subst l d (Abs (v, T, b)) = Abs (v, if d < 0 then pT else T, subst l (d + 1) b)
blanchet@53303
   142
      | subst l d t =
blanchet@53303
   143
        let val (u, vs) = strip_comb t in
blanchet@53303
   144
          if try (fst o dest_Free) u = SOME fun_name then
blanchet@53303
   145
            if l andalso length vs = ctr_pos then
blanchet@53303
   146
              list_comb (sndx |> permute_args ctr_pos, vs)
blanchet@53303
   147
            else if length vs <= ctr_pos then
blanchet@53303
   148
              primrec_error_eqn "too few arguments in recursive call" t
blanchet@53303
   149
            else if nth vs ctr_pos |> member (op =) [y, Bound d] then
blanchet@53303
   150
              list_comb (sndx $ nth vs ctr_pos, nth_drop ctr_pos vs |> map (subst false d))
blanchet@53303
   151
            else
blanchet@53303
   152
              primrec_error_eqn "recursive call not directly applied to constructor argument" t
blanchet@53303
   153
          else if try (fst o dest_Const) u = SOME @{const_name comp} then
blanchet@53303
   154
            (hd vs |> get_indices |> null orelse
blanchet@53303
   155
              primrec_error_eqn "recursive call not directly applied to constructor argument" t;
blanchet@53303
   156
            list_comb
blanchet@53303
   157
              (u |> map_types (strip_type #>> (fn Ts => Ts
blanchet@53303
   158
                   |> nth_map (length Ts - 1) (K pT)
blanchet@53303
   159
                   |> nth_map (length Ts - 2) (strip_type #>> nth_map 0 (K pT) #> (op --->)))
blanchet@53303
   160
                 #> (op --->)),
blanchet@53303
   161
              nth_map 1 (subst l d) vs))
blanchet@53303
   162
          else
blanchet@53303
   163
            list_comb (u, map (subst false d) vs)
blanchet@53303
   164
        end
blanchet@53303
   165
  in
blanchet@53303
   166
    subst true ~1
blanchet@53303
   167
  end;
blanchet@53303
   168
blanchet@53303
   169
(* FIXME get rid of funs_data or get_indices *)
blanchet@53303
   170
fun subst_indirect_call lthy funs_data get_indices (y, y') =
blanchet@53303
   171
  let
blanchet@53303
   172
    fun massage massage_map_arg bound_Ts =
blanchet@53303
   173
      massage_indirect_rec_call lthy (not o null o get_indices) massage_map_arg bound_Ts y y';
blanchet@53303
   174
    fun subst bound_Ts (t as _ $ _) =
blanchet@53303
   175
        let
blanchet@53303
   176
          val (f', args') = strip_comb t;
blanchet@53303
   177
          val fun_arg_idx = find_index (exists_subterm (not o null o get_indices)) args';
blanchet@53303
   178
          val arg_idx = find_index (exists_subterm (equal y)) args';
blanchet@53303
   179
          val (f, args) = chop (arg_idx + 1) args' |>> curry list_comb f';
blanchet@53303
   180
          val _ = fun_arg_idx < 0 orelse arg_idx >= 0 orelse
blanchet@53303
   181
            primrec_error_eqn "recursive call not applied to constructor argument" t;
blanchet@53303
   182
        in
blanchet@53303
   183
          if fun_arg_idx <> arg_idx andalso fun_arg_idx >= 0 then
blanchet@53303
   184
            if nth args' arg_idx = y then
blanchet@53303
   185
              list_comb (massage (rewrite_map_arg funs_data get_indices y) bound_Ts f, args)
blanchet@53303
   186
            else
blanchet@53303
   187
              primrec_error_eqn "recursive call not directly applied to constructor argument" f
blanchet@53303
   188
          else
blanchet@53303
   189
            list_comb (f', map (subst bound_Ts) args')
blanchet@53303
   190
        end
blanchet@53303
   191
      | subst bound_Ts (Abs (v, T, b)) = Abs (v, T, subst (T :: bound_Ts) b)
blanchet@53303
   192
      | subst bound_Ts t = t |> t = y ? massage (K I |> K) bound_Ts;
blanchet@53303
   193
  in subst [] end;
blanchet@53303
   194
blanchet@53303
   195
fun build_rec_arg lthy get_indices funs_data ctr_spec maybe_eqn_data =
blanchet@53303
   196
  if is_some maybe_eqn_data then
blanchet@53303
   197
    let
blanchet@53303
   198
      val eqn_data = the maybe_eqn_data;
blanchet@53303
   199
      val t = #rhs_term eqn_data;
blanchet@53303
   200
      val ctr_args = #ctr_args eqn_data;
blanchet@53303
   201
blanchet@53303
   202
      val calls = #calls ctr_spec;
blanchet@53303
   203
      val n_args = fold (curry (op +) o (fn Direct_Rec _ => 2 | _ => 1)) calls 0;
blanchet@53303
   204
blanchet@53303
   205
      val no_calls' = tag_list 0 calls
blanchet@53303
   206
        |> map_filter (try (apsnd (fn No_Rec n => n | Direct_Rec (n, _) => n)));
blanchet@53303
   207
      val direct_calls' = tag_list 0 calls
blanchet@53303
   208
        |> map_filter (try (apsnd (fn Direct_Rec (_, n) => n)));
blanchet@53303
   209
      val indirect_calls' = tag_list 0 calls
blanchet@53303
   210
        |> map_filter (try (apsnd (fn Indirect_Rec n => n)));
blanchet@53303
   211
blanchet@53303
   212
      fun make_direct_type T = dummyT; (* FIXME? *)
blanchet@53303
   213
blanchet@53303
   214
      val rec_res_type_list = map (fn (x :: _) => (#rec_type x, #res_type x)) funs_data;
blanchet@53303
   215
blanchet@53303
   216
      fun make_indirect_type (Type (Tname, Ts)) = Type (Tname, Ts |> map (fn T =>
blanchet@53303
   217
        let val maybe_res_type = AList.lookup (op =) rec_res_type_list T in
blanchet@53303
   218
          if is_some maybe_res_type
blanchet@53303
   219
          then HOLogic.mk_prodT (T, the maybe_res_type)
blanchet@53303
   220
          else make_indirect_type T end))
blanchet@53303
   221
        | make_indirect_type T = T;
blanchet@53303
   222
blanchet@53303
   223
      val args = replicate n_args ("", dummyT)
blanchet@53303
   224
        |> Term.rename_wrt_term t
blanchet@53303
   225
        |> map Free
blanchet@53303
   226
        |> fold (fn (ctr_arg_idx, arg_idx) =>
blanchet@53303
   227
            nth_map arg_idx (K (nth ctr_args ctr_arg_idx)))
blanchet@53303
   228
          no_calls'
blanchet@53303
   229
        |> fold (fn (ctr_arg_idx, arg_idx) =>
blanchet@53303
   230
            nth_map arg_idx (K (nth ctr_args ctr_arg_idx |> map_types make_direct_type)))
blanchet@53303
   231
          direct_calls'
blanchet@53303
   232
        |> fold (fn (ctr_arg_idx, arg_idx) =>
blanchet@53303
   233
            nth_map arg_idx (K (nth ctr_args ctr_arg_idx |> map_types make_indirect_type)))
blanchet@53303
   234
          indirect_calls';
blanchet@53303
   235
blanchet@53303
   236
      val direct_calls = map (apfst (nth ctr_args) o apsnd (nth args)) direct_calls';
blanchet@53303
   237
      val indirect_calls = map (apfst (nth ctr_args) o apsnd (nth args)) indirect_calls';
blanchet@53303
   238
blanchet@53303
   239
      val get_idx = (fn Free (v, _) => find_index (equal v o #fun_name o hd) funs_data | _ => ~1);
blanchet@53303
   240
blanchet@53303
   241
      val t' = t
blanchet@53303
   242
        |> fold (subst_indirect_call lthy funs_data get_indices) indirect_calls
blanchet@53303
   243
        |> subst_direct_calls get_idx (length o #left_args o hd o nth funs_data) direct_calls;
blanchet@53303
   244
blanchet@53303
   245
      val abstractions = map dest_Free (args @ #left_args eqn_data @ #right_args eqn_data);
blanchet@53303
   246
    in
blanchet@53303
   247
      t' |> fold_rev absfree abstractions
blanchet@53303
   248
    end
blanchet@53303
   249
  else Const (@{const_name undefined}, dummyT)
blanchet@53303
   250
blanchet@53303
   251
fun build_defs lthy bs funs_data rec_specs get_indices =
blanchet@53303
   252
  let
blanchet@53303
   253
    val n_funs = length funs_data;
blanchet@53303
   254
blanchet@53303
   255
    val ctr_spec_eqn_data_list' =
blanchet@53303
   256
      (take n_funs rec_specs |> map #ctr_specs) ~~ funs_data
blanchet@53303
   257
      |> maps (uncurry (finds (fn (x, y) => #ctr x = #ctr y))
blanchet@53303
   258
          ##> (fn x => null x orelse
blanchet@53303
   259
            primrec_error_eqns "excess equations in definition" (map #rhs_term x)) #> fst);
blanchet@53303
   260
    val _ = ctr_spec_eqn_data_list' |> map (fn (_, x) => length x <= 1 orelse
blanchet@53303
   261
      primrec_error_eqns ("multiple equations for constructor") (map #user_eqn x));
blanchet@53303
   262
blanchet@53303
   263
    val ctr_spec_eqn_data_list =
blanchet@53303
   264
      ctr_spec_eqn_data_list' @ (drop n_funs rec_specs |> maps #ctr_specs |> map (rpair []));
blanchet@53303
   265
blanchet@53303
   266
    val recs = take n_funs rec_specs |> map #recx;
blanchet@53303
   267
    val rec_args = ctr_spec_eqn_data_list
blanchet@53303
   268
      |> sort ((op <) o pairself (#offset o fst) |> make_ord)
blanchet@53303
   269
      |> map (uncurry (build_rec_arg lthy get_indices funs_data) o apsnd (try the_single));
blanchet@53303
   270
    val ctr_poss = map (fn x =>
blanchet@53303
   271
      if length (distinct ((op =) o pairself (length o #left_args)) x) <> 1 then
blanchet@53303
   272
        primrec_error ("inconstant constructor pattern position for function " ^
blanchet@53303
   273
          quote (#fun_name (hd x)))
blanchet@53303
   274
      else
blanchet@53303
   275
        hd x |> #left_args |> length) funs_data;
blanchet@53303
   276
  in
blanchet@53303
   277
    (recs, ctr_poss)
blanchet@53303
   278
    |-> map2 (fn recx => fn ctr_pos => list_comb (recx, rec_args) |> permute_args ctr_pos)
blanchet@53303
   279
    |> Syntax.check_terms lthy
blanchet@53303
   280
    |> map2 (fn b => fn t => ((b, NoSyn), ((Binding.map_name Thm.def_name b, []), t))) bs
blanchet@53303
   281
  end;
blanchet@53303
   282
blanchet@53303
   283
fun find_rec_calls get_indices eqn_data =
blanchet@53303
   284
  let
blanchet@53303
   285
    fun find (Abs (_, _, b)) ctr_arg = find b ctr_arg
blanchet@53303
   286
      | find (t as _ $ _) ctr_arg =
blanchet@53303
   287
        let
blanchet@53303
   288
          val (f', args') = strip_comb t;
blanchet@53303
   289
          val n = find_index (equal ctr_arg) args';
blanchet@53303
   290
        in
blanchet@53303
   291
          if n < 0 then
blanchet@53303
   292
            find f' ctr_arg @ maps (fn x => find x ctr_arg) args'
blanchet@53303
   293
          else
blanchet@53303
   294
            let val (f, args) = chop n args' |>> curry list_comb f' in
blanchet@53303
   295
              if exists_subterm (not o null o get_indices) f then
blanchet@53303
   296
                f :: maps (fn x => find x ctr_arg) args
blanchet@53303
   297
              else
blanchet@53303
   298
                find f ctr_arg @ maps (fn x => find x ctr_arg) args
blanchet@53303
   299
            end
blanchet@53303
   300
        end
blanchet@53303
   301
      | find _ _ = [];
blanchet@53303
   302
  in
blanchet@53303
   303
    map (find (#rhs_term eqn_data)) (#ctr_args eqn_data)
blanchet@53303
   304
    |> (fn [] => NONE | callss => SOME (#ctr eqn_data, callss))
blanchet@53303
   305
  end;
blanchet@53303
   306
blanchet@53303
   307
fun add_primrec fixes specs lthy =
blanchet@53303
   308
  let
blanchet@53303
   309
    val bs = map (fst o fst) fixes;
blanchet@53303
   310
    val fun_names = map Binding.name_of bs;
blanchet@53303
   311
    val eqns_data = map (snd #> dissect_eqn lthy fun_names) specs;
blanchet@53303
   312
    val funs_data = eqns_data
blanchet@53303
   313
      |> partition_eq ((op =) o pairself #fun_name)
blanchet@53303
   314
      |> finds (fn (x, y) => x = #fun_name (hd y)) fun_names |> fst
blanchet@53303
   315
      |> map (fn (x, y) => the_single y handle List.Empty =>
blanchet@53303
   316
          primrec_error ("missing equations for function " ^ quote x));
blanchet@53303
   317
blanchet@53303
   318
    fun get_indices t = map (fst #>> Binding.name_of #> Free) fixes
blanchet@53303
   319
      |> map_index (fn (i, v) => if exists_subterm (equal v) t then SOME i else NONE)
blanchet@53303
   320
      |> map_filter I;
blanchet@53303
   321
blanchet@53303
   322
    val arg_Ts = map (#rec_type o hd) funs_data;
blanchet@53303
   323
    val res_Ts = map (#res_type o hd) funs_data;
blanchet@53303
   324
    val callssss = funs_data
blanchet@53303
   325
      |> map (partition_eq ((op =) o pairself #ctr))
blanchet@53303
   326
      |> map (maps (map_filter (find_rec_calls get_indices)));
blanchet@53303
   327
blanchet@53303
   328
    val ((nontriv, rec_specs, _, induct_thm, induct_thms), lthy') =
blanchet@53303
   329
      rec_specs_of bs arg_Ts res_Ts get_indices callssss lthy;
blanchet@53303
   330
blanchet@53303
   331
    val actual_nn = length funs_data;
blanchet@53303
   332
blanchet@53303
   333
    val _ = let val ctrs = (maps (map #ctr o #ctr_specs) rec_specs) in
blanchet@53303
   334
      map (fn {ctr, user_eqn, ...} => member (op =) ctrs ctr orelse
blanchet@53303
   335
        primrec_error_eqn ("argument " ^ quote (Syntax.string_of_term lthy' ctr) ^
blanchet@53303
   336
          " is not a constructor in left-hand side") user_eqn) eqns_data end;
blanchet@53303
   337
blanchet@53303
   338
    val defs = build_defs lthy' bs funs_data rec_specs get_indices;
blanchet@53303
   339
blanchet@53329
   340
    fun prove def_thms' {ctr_specs, nested_map_idents, nested_map_comps, ...} induct_thm fun_data
blanchet@53303
   341
        lthy =
blanchet@53303
   342
      let
blanchet@53303
   343
        val fun_name = #fun_name (hd fun_data);
blanchet@53303
   344
        val def_thms = map (snd o snd) def_thms';
blanchet@53303
   345
        val simp_thms = finds (fn (x, y) => #ctr x = #ctr y) fun_data ctr_specs
blanchet@53303
   346
          |> fst
blanchet@53303
   347
          |> map_filter (try (fn (x, [y]) =>
blanchet@53303
   348
            (#user_eqn x, length (#left_args x) + length (#right_args x), #rec_thm y)))
blanchet@53303
   349
          |> map (fn (user_eqn, num_extra_args, rec_thm) =>
blanchet@53329
   350
            mk_primrec_tac lthy num_extra_args nested_map_idents nested_map_comps def_thms rec_thm
blanchet@53303
   351
            |> K |> Goal.prove lthy [] [] user_eqn)
blanchet@53303
   352
blanchet@53303
   353
        val notes =
blanchet@53303
   354
          [(inductN, if actual_nn > 1 then [induct_thm] else [], []),
blanchet@53303
   355
           (simpsN, simp_thms, simp_attrs)]
blanchet@53303
   356
          |> filter_out (null o #2)
blanchet@53303
   357
          |> map (fn (thmN, thms, attrs) =>
blanchet@53303
   358
            ((Binding.qualify true fun_name (Binding.name thmN), attrs), [(thms, [])]));
blanchet@53303
   359
      in
blanchet@53303
   360
        lthy |> Local_Theory.notes notes
blanchet@53303
   361
      end;
blanchet@53303
   362
blanchet@53303
   363
    val common_name = mk_common_name fun_names;
blanchet@53303
   364
blanchet@53303
   365
    val common_notes =
blanchet@53303
   366
      [(inductN, if nontriv andalso actual_nn > 1 then [induct_thm] else [], [])]
blanchet@53303
   367
      |> filter_out (null o #2)
blanchet@53303
   368
      |> map (fn (thmN, thms, attrs) =>
blanchet@53303
   369
        ((Binding.qualify true common_name (Binding.name thmN), attrs), [(thms, [])]));
blanchet@53303
   370
  in
blanchet@53303
   371
    lthy'
blanchet@53303
   372
    |> fold_map Local_Theory.define defs
blanchet@53303
   373
    |-> (fn def_thms' => fold_map3 (prove def_thms') (take actual_nn rec_specs)
blanchet@53303
   374
      (take actual_nn induct_thms) funs_data)
blanchet@53303
   375
    |> snd
blanchet@53303
   376
    |> Local_Theory.notes common_notes |> snd
blanchet@53303
   377
  end;
blanchet@53303
   378
blanchet@53303
   379
fun add_primrec_cmd raw_fixes raw_specs lthy =
blanchet@53303
   380
  let
blanchet@53303
   381
    val _ = let val d = duplicates (op =) (map (Binding.name_of o #1) raw_fixes) in null d orelse
blanchet@53303
   382
      primrec_error ("duplicate function name(s): " ^ commas d) end;
blanchet@53303
   383
    val (fixes, specs) = fst (Specification.read_spec raw_fixes raw_specs lthy);
blanchet@53303
   384
  in
blanchet@53303
   385
    add_primrec fixes specs lthy
blanchet@53303
   386
      handle ERROR str => primrec_error str
blanchet@53303
   387
  end
blanchet@53303
   388
  handle Primrec_Error (str, eqns) =>
blanchet@53303
   389
    if null eqns
blanchet@53303
   390
    then error ("primrec_new error:\n  " ^ str)
blanchet@53303
   391
    else error ("primrec_new error:\n  " ^ str ^ "\nin\n  " ^
blanchet@53303
   392
      space_implode "\n  " (map (quote o Syntax.string_of_term lthy) eqns))
blanchet@53303
   393
blanchet@53303
   394
blanchet@53303
   395
blanchet@53310
   396
(* Primcorec *)
blanchet@53303
   397
blanchet@53303
   398
type co_eqn_data_dtr_disc = {
blanchet@53303
   399
  fun_name: string,
blanchet@53303
   400
  ctr_no: int,
blanchet@53303
   401
  cond: term,
blanchet@53303
   402
  user_eqn: term
blanchet@53303
   403
};
blanchet@53303
   404
type co_eqn_data_dtr_sel = {
blanchet@53303
   405
  fun_name: string,
blanchet@53303
   406
  ctr_no: int,
blanchet@53303
   407
  sel_no: int,
blanchet@53303
   408
  fun_args: term list,
blanchet@53303
   409
  rhs_term: term,
blanchet@53303
   410
  user_eqn: term
blanchet@53303
   411
};
blanchet@53303
   412
datatype co_eqn_data =
blanchet@53303
   413
  Dtr_Disc of co_eqn_data_dtr_disc |
blanchet@53303
   414
  Dtr_Sel of co_eqn_data_dtr_sel
blanchet@53303
   415
blanchet@53303
   416
fun co_dissect_eqn_disc sequential fun_name_corec_spec_list eqn' imp_lhs' imp_rhs matched_conds_ps =
blanchet@53303
   417
  let
blanchet@53303
   418
    fun find_subterm p = let (* FIXME \<exists>? *)
blanchet@53303
   419
      fun f (t as u $ v) =
blanchet@53303
   420
        fold_rev (curry merge_options) [if p t then SOME t else NONE, f u, f v] NONE
blanchet@53303
   421
        | f t = if p t then SOME t else NONE
blanchet@53303
   422
      in f end;
blanchet@53303
   423
blanchet@53303
   424
    val fun_name = imp_rhs
blanchet@53303
   425
      |> perhaps (try HOLogic.dest_not)
blanchet@53303
   426
      |> `(try (fst o dest_Free o head_of o snd o dest_comb))
blanchet@53303
   427
      ||> (try (fst o dest_Free o head_of o fst o HOLogic.dest_eq))
blanchet@53303
   428
      |> the o merge_options;
blanchet@53303
   429
    val corec_spec = the (AList.lookup (op =) fun_name_corec_spec_list fun_name)
blanchet@53303
   430
      handle Option.Option => primrec_error_eqn "malformed discriminator equation" imp_rhs;
blanchet@53303
   431
blanchet@53303
   432
    val discs = #ctr_specs corec_spec |> map #disc;
blanchet@53303
   433
    val ctrs = #ctr_specs corec_spec |> map #ctr;
blanchet@53303
   434
    val n_ctrs = length ctrs;
blanchet@53303
   435
    val not_disc = head_of imp_rhs = @{term Not};
blanchet@53303
   436
    val _ = not_disc andalso n_ctrs <> 2 andalso
blanchet@53303
   437
      primrec_error_eqn "\<not>ed discriminator for a type with \<noteq> 2 constructors" imp_rhs;
blanchet@53303
   438
    val disc = find_subterm (member (op =) discs o head_of) imp_rhs;
blanchet@53303
   439
    val eq_ctr0 = imp_rhs |> perhaps (try (HOLogic.dest_not)) |> try (HOLogic.dest_eq #> snd)
blanchet@53303
   440
        |> (fn SOME t => let val n = find_index (equal t) ctrs in
blanchet@53303
   441
          if n >= 0 then SOME n else NONE end | _ => NONE);
blanchet@53303
   442
    val _ = is_some disc orelse is_some eq_ctr0 orelse
blanchet@53303
   443
      primrec_error_eqn "no discriminator in equation" imp_rhs;
blanchet@53303
   444
    val ctr_no' =
blanchet@53303
   445
      if is_none disc then the eq_ctr0 else find_index (equal (head_of (the disc))) discs;
blanchet@53303
   446
    val ctr_no = if not_disc then 1 - ctr_no' else ctr_no';
blanchet@53303
   447
    val fun_args = if is_none disc
blanchet@53303
   448
      then imp_rhs |> perhaps (try HOLogic.dest_not) |> HOLogic.dest_eq |> fst |> strip_comb |> snd
blanchet@53303
   449
      else the disc |> the_single o snd o strip_comb
blanchet@53303
   450
        |> (fn t => if try (fst o dest_Free o head_of) t = SOME fun_name
blanchet@53303
   451
          then snd (strip_comb t) else []);
blanchet@53303
   452
blanchet@53303
   453
    val mk_conjs = try (foldr1 HOLogic.mk_conj) #> the_default @{const True};
blanchet@53303
   454
    val mk_disjs = try (foldr1 HOLogic.mk_disj) #> the_default @{const False};
blanchet@53303
   455
    val catch_all = try (fst o dest_Free o the_single) imp_lhs' = SOME Name.uu_;
blanchet@53303
   456
    val matched_conds = filter (equal fun_name o fst) matched_conds_ps |> map snd;
blanchet@53303
   457
    val imp_lhs = mk_conjs imp_lhs';
blanchet@53303
   458
    val cond =
blanchet@53303
   459
      if catch_all then
blanchet@53303
   460
        if null matched_conds then fold_rev absfree (map dest_Free fun_args) @{const True} else
blanchet@53303
   461
          (strip_abs_vars (hd matched_conds),
blanchet@53303
   462
            mk_disjs (map strip_abs_body matched_conds) |> HOLogic.mk_not)
blanchet@53303
   463
          |-> fold_rev (fn (v, T) => fn u => Abs (v, T, u))
blanchet@53303
   464
      else if sequential then
blanchet@53303
   465
        HOLogic.mk_conj (HOLogic.mk_not (mk_disjs (map strip_abs_body matched_conds)), imp_lhs)
blanchet@53303
   466
        |> fold_rev absfree (map dest_Free fun_args)
blanchet@53303
   467
      else
blanchet@53303
   468
        imp_lhs |> fold_rev absfree (map dest_Free fun_args);
blanchet@53303
   469
    val matched_cond =
blanchet@53303
   470
      if sequential then fold_rev absfree (map dest_Free fun_args) imp_lhs else cond;
blanchet@53303
   471
blanchet@53303
   472
    val matched_conds_ps' = if catch_all
blanchet@53303
   473
      then (fun_name, cond) :: filter (not_equal fun_name o fst) matched_conds_ps
blanchet@53303
   474
      else (fun_name, matched_cond) :: matched_conds_ps;
blanchet@53303
   475
  in
blanchet@53303
   476
    (Dtr_Disc {
blanchet@53303
   477
      fun_name = fun_name,
blanchet@53303
   478
      ctr_no = ctr_no,
blanchet@53303
   479
      cond = cond,
blanchet@53303
   480
      user_eqn = eqn'
blanchet@53303
   481
    }, matched_conds_ps')
blanchet@53303
   482
  end;
blanchet@53303
   483
blanchet@53303
   484
fun co_dissect_eqn_sel fun_name_corec_spec_list eqn' eqn =
blanchet@53303
   485
  let
blanchet@53303
   486
    val (lhs, rhs) = HOLogic.dest_eq eqn
blanchet@53303
   487
      handle TERM _ =>
blanchet@53303
   488
        primrec_error_eqn "malformed function equation (expected \"lhs = rhs\")" eqn;
blanchet@53303
   489
    val sel = head_of lhs;
blanchet@53303
   490
    val (fun_name, fun_args) = dest_comb lhs |> snd |> strip_comb |> apfst (fst o dest_Free)
blanchet@53303
   491
      handle TERM _ =>
blanchet@53303
   492
        primrec_error_eqn "malformed selector argument in left-hand side" eqn;
blanchet@53303
   493
    val corec_spec = the (AList.lookup (op =) fun_name_corec_spec_list fun_name)
blanchet@53303
   494
      handle Option.Option => primrec_error_eqn "malformed selector argument in left-hand side" eqn;
blanchet@53303
   495
    val ((ctr_spec, ctr_no), sel) = #ctr_specs corec_spec
blanchet@53303
   496
      |> the o get_index (try (the o find_first (equal sel) o #sels))
blanchet@53303
   497
      |>> `(nth (#ctr_specs corec_spec));
blanchet@53303
   498
    val sel_no = find_index (equal sel) (#sels ctr_spec);
blanchet@53303
   499
  in
blanchet@53303
   500
    Dtr_Sel {
blanchet@53303
   501
      fun_name = fun_name,
blanchet@53303
   502
      ctr_no = ctr_no,
blanchet@53303
   503
      sel_no = sel_no,
blanchet@53303
   504
      fun_args = fun_args,
blanchet@53303
   505
      rhs_term = rhs,
blanchet@53303
   506
      user_eqn = eqn'
blanchet@53303
   507
    }
blanchet@53303
   508
  end;
blanchet@53303
   509
blanchet@53303
   510
fun co_dissect_eqn_ctr sequential fun_name_corec_spec_list eqn' imp_lhs' imp_rhs matched_conds_ps =
blanchet@53303
   511
  let 
blanchet@53303
   512
    val (lhs, rhs) = HOLogic.dest_eq imp_rhs;
blanchet@53303
   513
    val fun_name = head_of lhs |> fst o dest_Free;
blanchet@53303
   514
    val corec_spec = the (AList.lookup (op =) fun_name_corec_spec_list fun_name);
blanchet@53303
   515
    val (ctr, ctr_args) = strip_comb rhs;
blanchet@53303
   516
    val ctr_spec = the (find_first (equal ctr o #ctr) (#ctr_specs corec_spec))
blanchet@53303
   517
      handle Option.Option => primrec_error_eqn "not a constructor" ctr;
blanchet@53303
   518
    val disc_imp_rhs = betapply (#disc ctr_spec, lhs);
blanchet@53303
   519
    val (eqn_data_disc, matched_conds_ps') = co_dissect_eqn_disc
blanchet@53303
   520
        sequential fun_name_corec_spec_list eqn' imp_lhs' disc_imp_rhs matched_conds_ps;
blanchet@53303
   521
blanchet@53303
   522
    val sel_imp_rhss = (#sels ctr_spec ~~ ctr_args)
blanchet@53303
   523
      |> map (fn (sel, ctr_arg) => HOLogic.mk_eq (betapply (sel, lhs), ctr_arg));
blanchet@53303
   524
blanchet@53303
   525
val _ = warning ("reduced\n    " ^ Syntax.string_of_term @{context} imp_rhs ^ "\nto\n    \<cdot> " ^
blanchet@53303
   526
 Syntax.string_of_term @{context} disc_imp_rhs ^ "\n    \<cdot> " ^
blanchet@53303
   527
 space_implode "\n    \<cdot> " (map (Syntax.string_of_term @{context}) sel_imp_rhss));
blanchet@53303
   528
blanchet@53303
   529
    val eqns_data_sel =
blanchet@53303
   530
      map (co_dissect_eqn_sel fun_name_corec_spec_list @{const True}(*###*)) sel_imp_rhss;
blanchet@53303
   531
  in
blanchet@53303
   532
    (eqn_data_disc :: eqns_data_sel, matched_conds_ps')
blanchet@53303
   533
  end;
blanchet@53303
   534
blanchet@53303
   535
fun co_dissect_eqn sequential fun_name_corec_spec_list eqn' matched_conds_ps =
blanchet@53303
   536
  let
blanchet@53303
   537
    val eqn = subst_bounds (strip_qnt_vars @{const_name all} eqn' |> map Free |> rev,
blanchet@53303
   538
        strip_qnt_body @{const_name all} eqn')
blanchet@53303
   539
        handle TERM _ => primrec_error_eqn "malformed function equation" eqn';
blanchet@53303
   540
    val (imp_lhs', imp_rhs) =
blanchet@53303
   541
      (map HOLogic.dest_Trueprop (Logic.strip_imp_prems eqn),
blanchet@53303
   542
       HOLogic.dest_Trueprop (Logic.strip_imp_concl eqn));
blanchet@53303
   543
blanchet@53303
   544
    val head = imp_rhs
blanchet@53303
   545
      |> perhaps (try HOLogic.dest_not) |> perhaps (try (fst o HOLogic.dest_eq))
blanchet@53303
   546
      |> head_of;
blanchet@53303
   547
blanchet@53303
   548
    val maybe_rhs = imp_rhs |> perhaps (try (HOLogic.dest_not)) |> try (snd o HOLogic.dest_eq);
blanchet@53303
   549
blanchet@53303
   550
    val fun_names = map fst fun_name_corec_spec_list;
blanchet@53303
   551
    val discs = maps (#ctr_specs o snd) fun_name_corec_spec_list |> map #disc;
blanchet@53303
   552
    val sels = maps (#ctr_specs o snd) fun_name_corec_spec_list |> maps #sels;
blanchet@53303
   553
    val ctrs = maps (#ctr_specs o snd) fun_name_corec_spec_list |> map #ctr;
blanchet@53303
   554
  in
blanchet@53303
   555
    if member (op =) discs head orelse
blanchet@53303
   556
      is_some maybe_rhs andalso
blanchet@53303
   557
        member (op =) (filter (null o binder_types o fastype_of) ctrs) (the maybe_rhs) then
blanchet@53303
   558
      co_dissect_eqn_disc sequential fun_name_corec_spec_list eqn' imp_lhs' imp_rhs matched_conds_ps
blanchet@53303
   559
      |>> single
blanchet@53303
   560
    else if member (op =) sels head then
blanchet@53303
   561
      ([co_dissect_eqn_sel fun_name_corec_spec_list eqn' imp_rhs], matched_conds_ps)
blanchet@53303
   562
    else if is_Free head andalso member (op =) fun_names (fst (dest_Free head)) then
blanchet@53303
   563
      co_dissect_eqn_ctr sequential fun_name_corec_spec_list eqn' imp_lhs' imp_rhs matched_conds_ps
blanchet@53303
   564
    else
blanchet@53303
   565
      primrec_error_eqn "malformed function equation" eqn
blanchet@53303
   566
  end;
blanchet@53303
   567
blanchet@53303
   568
fun build_corec_args_discs ctr_specs disc_eqns =
blanchet@53303
   569
  let
blanchet@53303
   570
    val conds = map #cond disc_eqns;
blanchet@53303
   571
    val args =
blanchet@53303
   572
      if length ctr_specs = 1 then []
blanchet@53303
   573
      else if length disc_eqns = length ctr_specs then
blanchet@53303
   574
        fst (split_last conds)
blanchet@53303
   575
      else if length disc_eqns = length ctr_specs - 1 then
blanchet@53303
   576
        let val n = 0 upto length ctr_specs - 1
blanchet@53303
   577
            |> the o find_first (fn idx => not (exists (equal idx o #ctr_no) disc_eqns)) (*###*) in
blanchet@53303
   578
          if n = length ctr_specs - 1 then
blanchet@53303
   579
            conds
blanchet@53303
   580
          else
blanchet@53303
   581
            split_last conds
blanchet@53303
   582
            ||> (fn t => fold_rev absfree (strip_abs_vars t) (strip_abs_body t |> HOLogic.mk_not))
blanchet@53303
   583
            |>> chop n
blanchet@53303
   584
            |> (fn ((l, r), x) => l @ (x :: r))
blanchet@53303
   585
        end
blanchet@53303
   586
      else
blanchet@53303
   587
        0 upto length ctr_specs - 1
blanchet@53303
   588
        |> map (fn idx => find_first (equal idx o #ctr_no) disc_eqns
blanchet@53303
   589
          |> Option.map #cond
blanchet@53303
   590
          |> the_default (Const (@{const_name undefined}, dummyT)))
blanchet@53303
   591
        |> fst o split_last;
blanchet@53303
   592
    fun finish t =
blanchet@53303
   593
      let val n = length (fastype_of t |> binder_types) in
blanchet@53303
   594
        if t = Const (@{const_name undefined}, dummyT) then t
blanchet@53303
   595
        else if n = 0 then Abs (Name.uu_, @{typ unit}, t)
blanchet@53303
   596
        else if n = 1 then t
blanchet@53303
   597
        else Const (@{const_name prod_case}, dummyT) $ t
blanchet@53303
   598
      end;
blanchet@53303
   599
  in
blanchet@53303
   600
    map finish args
blanchet@53303
   601
  end;
blanchet@53303
   602
blanchet@53303
   603
fun build_corec_args_sel sel_eqns ctr_spec =
blanchet@53303
   604
  let
blanchet@53303
   605
    (* FIXME *)
blanchet@53303
   606
    val n_args = fold (curry (op +)) (map (fn Direct_Corec _ => 3 | _ => 1) (#calls ctr_spec)) 0;
blanchet@53303
   607
  in
blanchet@53303
   608
    replicate n_args (Const (@{const_name undefined}, dummyT))
blanchet@53303
   609
  end;
blanchet@53303
   610
blanchet@53303
   611
fun co_build_defs lthy sequential bs arg_Tss fun_name_corec_spec_list eqns_data =
blanchet@53303
   612
  let
blanchet@53303
   613
    val fun_names = map Binding.name_of bs;
blanchet@53303
   614
blanchet@53303
   615
(*    fun group _ [] = [] (* FIXME \<exists>? *)
blanchet@53303
   616
      | group eq (x :: xs) =
blanchet@53303
   617
        let val (xs', ys) = List.partition (eq x) xs in (x :: xs') :: group eq ys end;*)
blanchet@53303
   618
    val disc_eqnss = map_filter (try (fn Dtr_Disc x => x)) eqns_data
blanchet@53303
   619
      |> partition_eq ((op =) o pairself #fun_name)
blanchet@53303
   620
      |> finds (fn (x, ({fun_name, ...} :: _)) => x = fun_name) fun_names |> fst
blanchet@53303
   621
      |> map (sort ((op <) o pairself #ctr_no |> make_ord) o flat o snd);
blanchet@53303
   622
blanchet@53303
   623
    val _ = disc_eqnss |> map (fn x =>
blanchet@53303
   624
      let val d = duplicates ((op =) o pairself #ctr_no) x in null d orelse
blanchet@53303
   625
        primrec_error_eqns "excess discriminator equations in definition"
blanchet@53303
   626
          (maps (fn t => filter (equal (#ctr_no t) o #ctr_no) x) d |> map #user_eqn) end);
blanchet@53303
   627
blanchet@53303
   628
val _ = warning ("disc_eqnss:\n    \<cdot> " ^ space_implode "\n    \<cdot> " (map @{make_string} disc_eqnss));
blanchet@53303
   629
blanchet@53303
   630
    val sel_eqnss = map_filter (try (fn Dtr_Sel x => x)) eqns_data
blanchet@53303
   631
      |> partition_eq ((op =) o pairself #fun_name)
blanchet@53303
   632
      |> finds (fn (x, ({fun_name, ...} :: _)) => x = fun_name) fun_names |> fst
blanchet@53303
   633
      |> map (sort ((op <) o pairself #ctr_no |> make_ord) o flat o snd);
blanchet@53303
   634
blanchet@53303
   635
val _ = warning ("sel_eqnss:\n    \<cdot> " ^ space_implode "\n    \<cdot> " (map @{make_string} sel_eqnss));
blanchet@53303
   636
blanchet@53303
   637
    fun splice (xs :: xss) (ys :: yss) = xs @ ys @ splice xss yss (* FIXME \<exists>? *)
blanchet@53303
   638
      | splice xss yss = flat xss @ flat yss;
blanchet@53303
   639
    val corecs = map (#corec o snd) fun_name_corec_spec_list;
blanchet@53303
   640
    val corec_args = (map snd fun_name_corec_spec_list ~~ disc_eqnss ~~ sel_eqnss)
blanchet@53303
   641
      |> maps (fn (({ctr_specs, ...}, disc_eqns), sel_eqns) =>
blanchet@53303
   642
        splice (build_corec_args_discs ctr_specs disc_eqns |> map single)
blanchet@53303
   643
          (map (build_corec_args_sel sel_eqns) ctr_specs));
blanchet@53303
   644
blanchet@53303
   645
val _ = warning ("corecursor arguments:\n    \<cdot> " ^
blanchet@53303
   646
 space_implode "\n    \<cdot> " (map (Syntax.string_of_term @{context}) corec_args));
blanchet@53303
   647
blanchet@53303
   648
    fun uneq_pairs_rev xs = xs (* FIXME \<exists>? *)
blanchet@53303
   649
      |> these o try (split_last #> (fn (ys, y) => uneq_pairs_rev ys @ map (pair y) ys));
blanchet@53303
   650
    val proof_obligations = if sequential then [] else
blanchet@53303
   651
      maps (uneq_pairs_rev o map #cond) disc_eqnss
blanchet@53303
   652
      |> map (fn (x, y) => ((strip_abs_body x, strip_abs_body y), strip_abs_vars x))
blanchet@53303
   653
      |> map (apfst (apsnd HOLogic.mk_not #> pairself HOLogic.mk_Trueprop
blanchet@53303
   654
        #> apfst (curry (op $) @{const ==>}) #> (op $)))
blanchet@53303
   655
      |> map (fn (t, abs_vars) => fold_rev (fn (v, T) => fn u =>
blanchet@53303
   656
          Const (@{const_name all}, (T --> @{typ prop}) --> @{typ prop}) $
blanchet@53303
   657
            Abs (v, T, u)) abs_vars t);
blanchet@53303
   658
blanchet@53303
   659
    fun currys Ts t = if length Ts <= 1 then t else
blanchet@53303
   660
      t $ foldr1 (fn (u, v) => HOLogic.pair_const dummyT dummyT $ u $ v)
blanchet@53303
   661
        (length Ts - 1 downto 0 |> map Bound)
blanchet@53304
   662
      |> fold_rev (fn T => fn u => Abs (Name.uu, T, u)) Ts;
blanchet@53303
   663
  in
blanchet@53303
   664
    map (list_comb o rpair corec_args) corecs
blanchet@53303
   665
    |> map2 (fn Ts => fn t => if length Ts = 0 then t $ HOLogic.unit else t) arg_Tss
blanchet@53303
   666
    |> map2 currys arg_Tss
blanchet@53303
   667
    |> Syntax.check_terms lthy
blanchet@53303
   668
    |> map2 (fn b => fn t => ((b, NoSyn), ((Binding.map_name Thm.def_name b, []), t))) bs
blanchet@53303
   669
    |> rpair proof_obligations
blanchet@53303
   670
  end;
blanchet@53303
   671
blanchet@53303
   672
fun add_primcorec sequential fixes specs lthy =
blanchet@53303
   673
  let
blanchet@53303
   674
    val bs = map (fst o fst) fixes;
blanchet@53303
   675
    val (arg_Ts, res_Ts) = map (strip_type o snd o fst #>> HOLogic.mk_tupleT) fixes |> split_list;
blanchet@53303
   676
blanchet@53303
   677
    (* copied from primrec_new *)
blanchet@53303
   678
    fun get_indices t = map (fst #>> Binding.name_of #> Free) fixes
blanchet@53303
   679
      |> map_index (fn (i, v) => if exists_subterm (equal v) t then SOME i else NONE)
blanchet@53303
   680
      |> map_filter I;
blanchet@53303
   681
blanchet@53303
   682
    val callssss = []; (* FIXME *)
blanchet@53303
   683
blanchet@53303
   684
    val ((nontriv, corec_specs, _, coinduct_thm, strong_co_induct_thm, coinduct_thmss,
blanchet@53303
   685
          strong_coinduct_thmss), lthy') =
blanchet@53303
   686
      corec_specs_of bs arg_Ts res_Ts get_indices callssss lthy;
blanchet@53303
   687
blanchet@53303
   688
    val fun_names = map Binding.name_of bs;
blanchet@53303
   689
blanchet@53303
   690
    val fun_name_corec_spec_list = (fun_names ~~ res_Ts, corec_specs)
blanchet@53303
   691
      |> uncurry (finds (fn ((v, T), {corec, ...}) => T = body_type (fastype_of corec))) |> fst
blanchet@53303
   692
      |> map (apfst fst #> apsnd the_single); (*###*)
blanchet@53303
   693
blanchet@53303
   694
    val (eqns_data, _) =
blanchet@53303
   695
      fold_map (co_dissect_eqn sequential fun_name_corec_spec_list) (map snd specs) []
blanchet@53303
   696
      |>> flat;
blanchet@53303
   697
blanchet@53303
   698
    val (defs, proof_obligations) =
blanchet@53303
   699
      co_build_defs lthy' sequential bs (map (binder_types o snd o fst) fixes)
blanchet@53303
   700
        fun_name_corec_spec_list eqns_data;
blanchet@53303
   701
  in
blanchet@53303
   702
    lthy'
blanchet@53303
   703
    |> fold_map Local_Theory.define defs |> snd
blanchet@53303
   704
    |> Proof.theorem NONE (K I) [map (rpair []) proof_obligations]
blanchet@53303
   705
    |> Proof.refine (Method.primitive_text I)
blanchet@53303
   706
    |> Seq.hd
blanchet@53303
   707
  end
blanchet@53303
   708
blanchet@53303
   709
fun add_primcorec_cmd seq (raw_fixes, raw_specs) lthy =
blanchet@53303
   710
  let
blanchet@53303
   711
    val (fixes, specs) = fst (Specification.read_spec raw_fixes raw_specs lthy);
blanchet@53303
   712
  in
blanchet@53303
   713
    add_primcorec seq fixes specs lthy
blanchet@53303
   714
    handle ERROR str => primrec_error str
blanchet@53303
   715
  end
blanchet@53303
   716
  handle Primrec_Error (str, eqns) =>
blanchet@53303
   717
    if null eqns
blanchet@53303
   718
    then error ("primcorec error:\n  " ^ str)
blanchet@53303
   719
    else error ("primcorec error:\n  " ^ str ^ "\nin\n  " ^
blanchet@53303
   720
      space_implode "\n  " (map (quote o Syntax.string_of_term lthy) eqns))
blanchet@53303
   721
blanchet@53303
   722
end;