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