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