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