src/HOL/Nominal/nominal_primrec.ML
author wenzelm
Tue Mar 03 18:32:01 2009 +0100 (2009-03-03)
changeset 30223 24d975352879
parent 29581 b3b33e0298eb
child 30251 7aec011818e0
permissions -rw-r--r--
renamed Binding.name_pos to Binding.make, renamed Binding.base_name to Binding.name_of, renamed Binding.map_base to Binding.map_name, added mandatory flag to Binding.qualify;
minor tuning;
berghofe@21541
     1
(*  Title:      HOL/Nominal/nominal_primrec.ML
wenzelm@29265
     2
    Author:     Norbert Voelker, FernUni Hagen
wenzelm@29265
     3
    Author:     Stefan Berghofer, TU Muenchen
berghofe@21541
     4
berghofe@21541
     5
Package for defining functions on nominal datatypes by primitive recursion.
berghofe@21541
     6
Taken from HOL/Tools/primrec_package.ML
berghofe@21541
     7
*)
berghofe@21541
     8
berghofe@21541
     9
signature NOMINAL_PRIMREC =
berghofe@21541
    10
sig
berghofe@29097
    11
  val add_primrec: term list option -> term option ->
haftmann@29581
    12
    (binding * typ option * mixfix) list ->
haftmann@29581
    13
    (binding * typ option * mixfix) list ->
berghofe@29097
    14
    (Attrib.binding * term) list -> local_theory -> Proof.state
berghofe@21541
    15
end;
berghofe@21541
    16
berghofe@21541
    17
structure NominalPrimrec : NOMINAL_PRIMREC =
berghofe@21541
    18
struct
berghofe@21541
    19
berghofe@21541
    20
open DatatypeAux;
berghofe@21541
    21
berghofe@21541
    22
exception RecError of string;
berghofe@21541
    23
berghofe@21541
    24
fun primrec_err s = error ("Nominal primrec definition error:\n" ^ s);
berghofe@29097
    25
fun primrec_eq_err lthy s eq =
berghofe@29097
    26
  primrec_err (s ^ "\nin\n" ^ quote (Syntax.string_of_term lthy eq));
berghofe@21541
    27
berghofe@21541
    28
berghofe@21541
    29
(* preprocessing of equations *)
berghofe@21541
    30
berghofe@29097
    31
fun unquantify t =
berghofe@21541
    32
  let
berghofe@29097
    33
    val (vs, Ts) = split_list (strip_qnt_vars "all" t);
berghofe@29097
    34
    val body = strip_qnt_body "all" t;
berghofe@29097
    35
    val (vs', _) = Name.variants vs (Name.make_context (fold_aterms
berghofe@29097
    36
      (fn Free (v, _) => insert (op =) v | _ => I) body []))
berghofe@29097
    37
  in (curry subst_bounds (map2 (curry Free) vs' Ts |> rev) body) end;
berghofe@29097
    38
berghofe@29097
    39
fun process_eqn lthy is_fixed spec rec_fns = 
berghofe@29097
    40
  let
berghofe@29097
    41
    val eq = unquantify spec;
berghofe@21541
    42
    val (lhs, rhs) = 
berghofe@29097
    43
      HOLogic.dest_eq (HOLogic.dest_Trueprop (Logic.strip_imp_concl eq))
berghofe@29097
    44
      handle TERM _ => raise RecError "not a proper equation";
berghofe@21541
    45
berghofe@21541
    46
    val (recfun, args) = strip_comb lhs;
berghofe@29097
    47
    val fname = case recfun of Free (v, _) => if is_fixed v then v
berghofe@29097
    48
          else raise RecError "illegal head of function equation"
berghofe@29097
    49
      | _ => raise RecError "illegal head of function equation";
berghofe@21541
    50
berghofe@21541
    51
    val (ls', rest)  = take_prefix is_Free args;
berghofe@21541
    52
    val (middle, rs') = take_suffix is_Free rest;
berghofe@21541
    53
    val rpos = length ls';
berghofe@21541
    54
berghofe@21541
    55
    val (constr, cargs') = if null middle then raise RecError "constructor missing"
berghofe@21541
    56
      else strip_comb (hd middle);
berghofe@21541
    57
    val (cname, T) = dest_Const constr
berghofe@21541
    58
      handle TERM _ => raise RecError "ill-formed constructor";
berghofe@21541
    59
    val (tname, _) = dest_Type (body_type T) handle TYPE _ =>
berghofe@21541
    60
      raise RecError "cannot determine datatype associated with function"
berghofe@21541
    61
berghofe@21541
    62
    val (ls, cargs, rs) =
berghofe@21541
    63
      (map dest_Free ls', map dest_Free cargs', map dest_Free rs')
berghofe@21541
    64
      handle TERM _ => raise RecError "illegal argument in pattern";
berghofe@21541
    65
    val lfrees = ls @ rs @ cargs;
berghofe@21541
    66
berghofe@21541
    67
    fun check_vars _ [] = ()
berghofe@21541
    68
      | check_vars s vars = raise RecError (s ^ commas_quote (map fst vars))
berghofe@21541
    69
  in
berghofe@21541
    70
    if length middle > 1 then 
berghofe@21541
    71
      raise RecError "more than one non-variable in pattern"
berghofe@21541
    72
    else
berghofe@21541
    73
     (check_vars "repeated variable names in pattern: " (duplicates (op =) lfrees);
berghofe@21541
    74
      check_vars "extra variables on rhs: "
wenzelm@29265
    75
        (map dest_Free (OldTerm.term_frees rhs) |> subtract (op =) lfrees
berghofe@29097
    76
          |> filter_out (is_fixed o fst));
berghofe@29097
    77
      case AList.lookup (op =) rec_fns fname of
berghofe@21541
    78
        NONE =>
berghofe@29097
    79
          (fname, (tname, rpos, [(cname, (ls, cargs, rs, rhs, eq))]))::rec_fns
berghofe@21541
    80
      | SOME (_, rpos', eqns) =>
berghofe@21541
    81
          if AList.defined (op =) eqns cname then
berghofe@21541
    82
            raise RecError "constructor already occurred as pattern"
berghofe@21541
    83
          else if rpos <> rpos' then
berghofe@21541
    84
            raise RecError "position of recursive argument inconsistent"
berghofe@21541
    85
          else
berghofe@29097
    86
            AList.update (op =)
berghofe@29097
    87
              (fname, (tname, rpos, (cname, (ls, cargs, rs, rhs, eq))::eqns))
berghofe@21541
    88
              rec_fns)
berghofe@21541
    89
  end
berghofe@29097
    90
  handle RecError s => primrec_eq_err lthy s spec;
berghofe@21541
    91
berghofe@21541
    92
val param_err = "Parameters must be the same for all recursive functions";
berghofe@21541
    93
berghofe@29097
    94
fun process_fun lthy descr eqns (i, fname) (fnames, fnss) =
berghofe@21541
    95
  let
berghofe@29097
    96
    val (_, (tname, _, constrs)) = nth descr i;
berghofe@21541
    97
berghofe@21541
    98
    (* substitute "fname ls x rs" by "y" for (x, (_, y)) in subs *)
berghofe@21541
    99
berghofe@21541
   100
    fun subst [] t fs = (t, fs)
berghofe@21541
   101
      | subst subs (Abs (a, T, t)) fs =
berghofe@21541
   102
          fs
berghofe@21541
   103
          |> subst subs t
berghofe@21541
   104
          |-> (fn t' => pair (Abs (a, T, t')))
berghofe@21541
   105
      | subst subs (t as (_ $ _)) fs =
berghofe@21541
   106
          let
berghofe@21541
   107
            val (f, ts) = strip_comb t;
berghofe@21541
   108
          in
berghofe@29097
   109
            if is_Free f
berghofe@29097
   110
              andalso member (fn ((v, _), (w, _)) => v = w) eqns (dest_Free f) then
berghofe@21541
   111
              let
berghofe@29097
   112
                val (fname', _) = dest_Free f;
berghofe@29097
   113
                val (_, rpos, eqns') = the (AList.lookup (op =) eqns fname');
berghofe@29097
   114
                val (ls, rs'') = chop rpos ts
berghofe@29097
   115
                val (x', rs) = case rs'' of
berghofe@29097
   116
                    x' :: rs => (x', rs)
berghofe@29097
   117
                  | [] => raise RecError ("not enough arguments in recursive application\n"
berghofe@29097
   118
                      ^ "of function " ^ quote fname' ^ " on rhs");
berghofe@29097
   119
                val rs' = (case eqns' of
berghofe@21541
   120
                    (_, (ls', _, rs', _, _)) :: _ =>
berghofe@23006
   121
                      let val (rs1, rs2) = chop (length rs') rs
berghofe@23006
   122
                      in
berghofe@23006
   123
                        if ls = map Free ls' andalso rs1 = map Free rs' then rs2
berghofe@23006
   124
                        else raise RecError param_err
berghofe@23006
   125
                      end
berghofe@23006
   126
                  | _ => raise RecError ("no equations for " ^ quote fname'));
berghofe@21541
   127
                val (x, xs) = strip_comb x'
berghofe@21541
   128
              in case AList.lookup (op =) subs x
berghofe@21541
   129
               of NONE =>
berghofe@21541
   130
                    fs
berghofe@21541
   131
                    |> fold_map (subst subs) ts
berghofe@21541
   132
                    |-> (fn ts' => pair (list_comb (f, ts')))
berghofe@21541
   133
                | SOME (i', y) =>
berghofe@21541
   134
                    fs
berghofe@23006
   135
                    |> fold_map (subst subs) (xs @ rs')
berghofe@29097
   136
                    ||> process_fun lthy descr eqns (i', fname')
berghofe@21541
   137
                    |-> (fn ts' => pair (list_comb (y, ts')))
berghofe@21541
   138
              end
berghofe@21541
   139
            else
berghofe@21541
   140
              fs
berghofe@21541
   141
              |> fold_map (subst subs) (f :: ts)
berghofe@21541
   142
              |-> (fn (f'::ts') => pair (list_comb (f', ts')))
berghofe@21541
   143
          end
berghofe@21541
   144
      | subst _ t fs = (t, fs);
berghofe@21541
   145
berghofe@21541
   146
    (* translate rec equations into function arguments suitable for rec comb *)
berghofe@21541
   147
berghofe@29097
   148
    fun trans eqns (cname, cargs) (fnames', fnss', fns) =
berghofe@21541
   149
      (case AList.lookup (op =) eqns cname of
berghofe@21541
   150
          NONE => (warning ("No equation for constructor " ^ quote cname ^
berghofe@21541
   151
            "\nin definition of function " ^ quote fname);
berghofe@29097
   152
              (fnames', fnss', (Const (@{const_name undefined}, dummyT))::fns))
berghofe@21541
   153
        | SOME (ls, cargs', rs, rhs, eq) =>
berghofe@21541
   154
            let
berghofe@21541
   155
              val recs = filter (is_rec_type o snd) (cargs' ~~ cargs);
berghofe@21541
   156
              val rargs = map fst recs;
berghofe@29097
   157
              val subs = map (rpair dummyT o fst)
wenzelm@29276
   158
                (rev (Term.rename_wrt_term rhs rargs));
berghofe@29097
   159
              val (rhs', (fnames'', fnss'')) = subst (map2 (fn (x, y) => fn z =>
berghofe@29097
   160
                (Free x, (body_index y, Free z))) recs subs) rhs (fnames', fnss')
berghofe@29097
   161
                  handle RecError s => primrec_eq_err lthy s eq
berghofe@29097
   162
            in (fnames'', fnss'', 
berghofe@21541
   163
                (list_abs_free (cargs' @ subs, rhs'))::fns)
berghofe@21541
   164
            end)
berghofe@21541
   165
berghofe@29097
   166
  in (case AList.lookup (op =) fnames i of
berghofe@21541
   167
      NONE =>
berghofe@29097
   168
        if exists (fn (_, v) => fname = v) fnames then
berghofe@21541
   169
          raise RecError ("inconsistent functions for datatype " ^ quote tname)
berghofe@21541
   170
        else
berghofe@21541
   171
          let
berghofe@29097
   172
            val SOME (_, _, eqns' as (_, (ls, _, rs, _, _)) :: _) =
berghofe@29097
   173
              AList.lookup (op =) eqns fname;
berghofe@29097
   174
            val (fnames', fnss', fns) = fold_rev (trans eqns') constrs
berghofe@29097
   175
              ((i, fname)::fnames, fnss, []) 
berghofe@21541
   176
          in
berghofe@29097
   177
            (fnames', (i, (fname, ls, rs, fns))::fnss')
berghofe@21541
   178
          end
berghofe@29097
   179
    | SOME fname' =>
berghofe@29097
   180
        if fname = fname' then (fnames, fnss)
berghofe@21541
   181
        else raise RecError ("inconsistent functions for datatype " ^ quote tname))
berghofe@21541
   182
  end;
berghofe@21541
   183
berghofe@21541
   184
berghofe@21541
   185
(* prepare functions needed for definitions *)
berghofe@21541
   186
berghofe@21541
   187
fun get_fns fns ((i : int, (tname, _, constrs)), rec_name) (fs, defs) =
berghofe@21541
   188
  case AList.lookup (op =) fns i of
berghofe@21541
   189
     NONE =>
berghofe@21541
   190
       let
haftmann@28524
   191
         val dummy_fns = map (fn (_, cargs) => Const (@{const_name undefined},
berghofe@21541
   192
           replicate ((length cargs) + (length (List.filter is_rec_type cargs)))
berghofe@21541
   193
             dummyT ---> HOLogic.unitT)) constrs;
berghofe@21541
   194
         val _ = warning ("No function definition for datatype " ^ quote tname)
berghofe@21541
   195
       in
berghofe@21541
   196
         (dummy_fns @ fs, defs)
berghofe@21541
   197
       end
berghofe@21541
   198
   | SOME (fname, ls, rs, fs') => (fs' @ fs, (fname, ls, rs, rec_name, tname) :: defs);
berghofe@21541
   199
berghofe@21541
   200
berghofe@21541
   201
(* make definition *)
berghofe@21541
   202
berghofe@29097
   203
fun make_def ctxt fixes fs (fname, ls, rs, rec_name, tname) =
berghofe@21541
   204
  let
berghofe@21541
   205
    val used = map fst (fold Term.add_frees fs []);
berghofe@21541
   206
    val x = (Name.variant used "x", dummyT);
berghofe@21541
   207
    val frees = ls @ x :: rs;
berghofe@29097
   208
    val raw_rhs = list_abs_free (frees,
berghofe@21541
   209
      list_comb (Const (rec_name, dummyT), fs @ [Free x]))
berghofe@29097
   210
    val def_name = Thm.def_name (Sign.base_name fname);
berghofe@29097
   211
    val rhs = singleton (Syntax.check_terms ctxt) raw_rhs;
berghofe@29097
   212
    val SOME var = get_first (fn ((b, _), mx) =>
wenzelm@30223
   213
      if Binding.name_of b = fname then SOME (b, mx) else NONE) fixes;
berghofe@29097
   214
  in
berghofe@29097
   215
    ((var, ((Binding.name def_name, []), rhs)),
berghofe@29097
   216
     subst_bounds (rev (map Free frees), strip_abs_body rhs))
berghofe@29097
   217
  end;
berghofe@21541
   218
berghofe@21541
   219
berghofe@21541
   220
(* find datatypes which contain all datatypes in tnames' *)
berghofe@21541
   221
berghofe@21541
   222
fun find_dts (dt_info : NominalPackage.nominal_datatype_info Symtab.table) _ [] = []
berghofe@21541
   223
  | find_dts dt_info tnames' (tname::tnames) =
berghofe@21541
   224
      (case Symtab.lookup dt_info tname of
berghofe@21541
   225
          NONE => primrec_err (quote tname ^ " is not a nominal datatype")
berghofe@21541
   226
        | SOME dt =>
berghofe@21541
   227
            if tnames' subset (map (#1 o snd) (#descr dt)) then
berghofe@21541
   228
              (tname, dt)::(find_dts dt_info tnames' tnames)
berghofe@21541
   229
            else find_dts dt_info tnames' tnames);
berghofe@21541
   230
berghofe@21541
   231
fun common_prefix eq ([], _) = []
berghofe@21541
   232
  | common_prefix eq (_, []) = []
berghofe@21541
   233
  | common_prefix eq (x :: xs, y :: ys) =
berghofe@21541
   234
      if eq (x, y) then x :: common_prefix eq (xs, ys) else [];
berghofe@21541
   235
berghofe@21541
   236
local
berghofe@21541
   237
berghofe@29097
   238
fun prepare_spec prep_spec ctxt raw_fixes raw_spec =
berghofe@29097
   239
  let
berghofe@29097
   240
    val ((fixes, spec), _) = prep_spec
berghofe@29097
   241
      raw_fixes (map (single o apsnd single) raw_spec) ctxt
berghofe@29097
   242
  in (fixes, map (apsnd the_single) spec) end;
berghofe@29097
   243
berghofe@29097
   244
fun gen_primrec set_group prep_spec prep_term invs fctxt raw_fixes raw_params raw_spec lthy =
berghofe@21541
   245
  let
berghofe@29097
   246
    val (fixes', spec) = prepare_spec prep_spec lthy (raw_fixes @ raw_params) raw_spec;
berghofe@29097
   247
    val fixes = List.take (fixes', length raw_fixes);
berghofe@29097
   248
    val (names_atts, spec') = split_list spec;
berghofe@29097
   249
    val eqns' = map unquantify spec'
berghofe@29097
   250
    val eqns = fold_rev (process_eqn lthy (fn v => Variable.is_fixed lthy v
wenzelm@30223
   251
      orelse exists (fn ((w, _), _) => v = Binding.name_of w) fixes)) spec' [];
berghofe@29097
   252
    val dt_info = NominalPackage.get_nominal_datatypes (ProofContext.theory_of lthy);
berghofe@21541
   253
    val lsrs :: lsrss = maps (fn (_, (_, _, eqns)) =>
berghofe@29097
   254
      map (fn (_, (ls, _, rs, _, _)) => ls @ rs) eqns) eqns
berghofe@21541
   255
    val _ =
berghofe@21541
   256
      (if forall (curry eq_set lsrs) lsrss andalso forall
berghofe@21541
   257
         (fn (_, (_, _, (_, (ls, _, rs, _, _)) :: eqns)) =>
berghofe@21541
   258
               forall (fn (_, (ls', _, rs', _, _)) =>
berghofe@21541
   259
                 ls = ls' andalso rs = rs') eqns
berghofe@29097
   260
           | _ => true) eqns
berghofe@22330
   261
       then () else primrec_err param_err);
berghofe@29097
   262
    val tnames = distinct (op =) (map (#1 o snd) eqns);
berghofe@21541
   263
    val dts = find_dts dt_info tnames tnames;
berghofe@21541
   264
    val main_fns = 
berghofe@21541
   265
      map (fn (tname, {index, ...}) =>
berghofe@21541
   266
        (index, 
berghofe@29097
   267
          (fst o the o find_first (fn (_, x) => #1 x = tname)) eqns))
berghofe@21541
   268
      dts;
berghofe@21541
   269
    val {descr, rec_names, rec_rewrites, ...} = 
berghofe@21541
   270
      if null dts then
berghofe@21541
   271
        primrec_err ("datatypes " ^ commas_quote tnames ^ "\nare not mutually recursive")
berghofe@21541
   272
      else snd (hd dts);
berghofe@22434
   273
    val descr = map (fn (i, (tname, args, constrs)) => (i, (tname, args,
berghofe@22434
   274
      map (fn (cname, cargs) => (cname, fold (fn (dTs, dT) => fn dTs' =>
berghofe@22434
   275
        dTs' @ dTs @ [dT]) cargs [])) constrs))) descr;
berghofe@29097
   276
    val (fnames, fnss) = fold_rev (process_fun lthy descr eqns) main_fns ([], []);
berghofe@21541
   277
    val (fs, defs) = fold_rev (get_fns fnss) (descr ~~ rec_names) ([], []);
berghofe@29097
   278
    val defs' = map (make_def lthy fixes fs) defs;
berghofe@29097
   279
    val names1 = map snd fnames;
berghofe@29097
   280
    val names2 = map fst eqns;
berghofe@29097
   281
    val _ = if gen_eq_set (op =) (names1, names2) then ()
berghofe@29097
   282
      else primrec_err ("functions " ^ commas_quote names2 ^
berghofe@29097
   283
        "\nare not mutually recursive");
berghofe@29097
   284
    val (defs_thms, lthy') = lthy |>
berghofe@29097
   285
      set_group ? LocalTheory.set_group (serial_string ()) |>
berghofe@29097
   286
      fold_map (apfst (snd o snd) oo
berghofe@29097
   287
        LocalTheory.define Thm.definitionK o fst) defs';
wenzelm@30223
   288
    val qualify = Binding.qualify false
berghofe@29097
   289
      (space_implode "_" (map (Sign.base_name o #1) defs));
berghofe@29097
   290
    val names_atts' = map (apfst qualify) names_atts;
berghofe@29097
   291
    val cert = cterm_of (ProofContext.theory_of lthy');
berghofe@21541
   292
berghofe@21541
   293
    fun mk_idx eq =
berghofe@21541
   294
      let
berghofe@29097
   295
        val Free (name, _) = head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop
berghofe@21541
   296
          (Logic.strip_imp_concl eq))));
berghofe@29097
   297
        val SOME i = AList.lookup op = (map swap fnames) name;
berghofe@21541
   298
        val SOME (_, _, constrs) = AList.lookup op = descr i;
berghofe@29097
   299
        val SOME (_, _, eqns'') = AList.lookup op = eqns name;
berghofe@21541
   300
        val SOME (cname, (_, cargs, _, _, _)) = find_first
berghofe@29097
   301
          (fn (_, (_, _, _, _, eq')) => eq = eq') eqns''
berghofe@21541
   302
      in (i, find_index (fn (cname', _) => cname = cname') constrs, cargs) end;
berghofe@21541
   303
berghofe@21541
   304
    val rec_rewritess =
berghofe@21541
   305
      unflat (map (fn (_, (_, _, constrs)) => constrs) descr) rec_rewrites;
berghofe@21541
   306
    val fvars = rec_rewrites |> hd |> concl_of |> HOLogic.dest_Trueprop |>
berghofe@21541
   307
      HOLogic.dest_eq |> fst |> strip_comb |> snd |> take_prefix is_Var |> fst;
berghofe@21541
   308
    val (pvars, ctxtvars) = List.partition
berghofe@21541
   309
      (equal HOLogic.boolT o body_type o snd)
berghofe@22434
   310
      (fold_rev Term.add_vars (map Logic.strip_assums_concl
berghofe@21541
   311
        (prems_of (hd rec_rewrites))) [] \\ map dest_Var fvars);
berghofe@21541
   312
    val cfs = defs' |> hd |> snd |> strip_comb |> snd |>
berghofe@21541
   313
      curry (List.take o swap) (length fvars) |> map cert;
berghofe@21541
   314
    val invs' = (case invs of
berghofe@21541
   315
        NONE => map (fn (i, _) =>
berghofe@29097
   316
          Abs ("x", fastype_of (snd (nth defs' i)), HOLogic.true_const)) descr
berghofe@29097
   317
      | SOME invs' => map (prep_term lthy') invs');
berghofe@21541
   318
    val inst = (map cert fvars ~~ cfs) @
berghofe@21541
   319
      (map (cert o Var) pvars ~~ map cert invs') @
berghofe@21541
   320
      (case ctxtvars of
berghofe@29097
   321
         [ctxtvar] => [(cert (Var ctxtvar),
berghofe@29097
   322
           cert (the_default HOLogic.unit (Option.map (prep_term lthy') fctxt)))]
berghofe@21541
   323
       | _ => []);
berghofe@29097
   324
    val rec_rewrites' = map (fn eq =>
berghofe@21541
   325
      let
berghofe@21541
   326
        val (i, j, cargs) = mk_idx eq
berghofe@21541
   327
        val th = nth (nth rec_rewritess i) j;
berghofe@21541
   328
        val cargs' = th |> concl_of |> HOLogic.dest_Trueprop |>
berghofe@21541
   329
          HOLogic.dest_eq |> fst |> strip_comb |> snd |> split_last |> snd |>
berghofe@21541
   330
          strip_comb |> snd
berghofe@21541
   331
      in (cargs, Logic.strip_imp_prems eq,
berghofe@21541
   332
        Drule.cterm_instantiate (inst @
berghofe@29097
   333
          (map cert cargs' ~~ map (cert o Free) cargs)) th)
berghofe@29097
   334
      end) eqns';
berghofe@21541
   335
berghofe@21541
   336
    val prems = foldr1 (common_prefix op aconv) (map (prems_of o #3) rec_rewrites');
berghofe@21541
   337
    val cprems = map cert prems;
berghofe@21541
   338
    val asms = map Thm.assume cprems;
berghofe@21541
   339
    val premss = map (fn (cargs, eprems, eqn) =>
berghofe@21541
   340
      map (fn t => list_all_free (cargs, Logic.list_implies (eprems, t)))
berghofe@21541
   341
        (List.drop (prems_of eqn, length prems))) rec_rewrites';
berghofe@21541
   342
    val cpremss = map (map cert) premss;
berghofe@21541
   343
    val asmss = map (map Thm.assume) cpremss;
berghofe@21541
   344
berghofe@21541
   345
    fun mk_eqn ((cargs, eprems, eqn), asms') =
berghofe@21541
   346
      let
berghofe@21541
   347
        val ceprems = map cert eprems;
berghofe@21541
   348
        val asms'' = map Thm.assume ceprems;
berghofe@21541
   349
        val ccargs = map (cert o Free) cargs;
berghofe@21541
   350
        val asms''' = map (fn th => implies_elim_list
berghofe@21541
   351
          (forall_elim_list ccargs th) asms'') asms'
berghofe@21541
   352
      in
berghofe@21541
   353
        implies_elim_list eqn (asms @ asms''') |>
berghofe@21541
   354
        implies_intr_list ceprems |>
berghofe@21541
   355
        forall_intr_list ccargs
berghofe@21541
   356
      end;
berghofe@21541
   357
berghofe@21541
   358
    val rule_prems = cprems @ flat cpremss;
berghofe@21541
   359
    val rule = implies_intr_list rule_prems
wenzelm@23418
   360
      (Conjunction.intr_balanced (map mk_eqn (rec_rewrites' ~~ asmss)));
berghofe@21541
   361
berghofe@29097
   362
    val goals = map (fn ((cargs, _, _), eqn) =>
berghofe@29097
   363
      (list_all_free (cargs, eqn), [])) (rec_rewrites' ~~ eqns');
berghofe@21541
   364
berghofe@21541
   365
  in
berghofe@29097
   366
    lthy' |>
berghofe@29097
   367
    Variable.add_fixes (map fst lsrs) |> snd |>
berghofe@21541
   368
    Proof.theorem_i NONE
berghofe@29097
   369
      (fn thss => fn goal_ctxt =>
berghofe@21541
   370
         let
berghofe@29097
   371
           val simps = ProofContext.export goal_ctxt lthy' (flat thss);
berghofe@29097
   372
           val (simps', lthy'') = fold_map (LocalTheory.note Thm.theoremK)
berghofe@29097
   373
             (names_atts' ~~ map single simps) lthy'
berghofe@21541
   374
         in
berghofe@29097
   375
           lthy''
berghofe@29097
   376
           |> LocalTheory.note Thm.theoremK ((qualify (Binding.name "simps"),
berghofe@29097
   377
             [Attrib.internal (K Simplifier.simp_add)]), maps snd simps')
berghofe@21541
   378
           |> snd
berghofe@29097
   379
         end)
berghofe@21541
   380
      [goals] |>
wenzelm@23351
   381
    Proof.apply (Method.Basic (fn _ => Method.RAW_METHOD (fn _ =>
berghofe@29097
   382
      rewrite_goals_tac defs_thms THEN
wenzelm@23351
   383
      compose_tac (false, rule, length rule_prems) 1), Position.none)) |>
berghofe@21541
   384
    Seq.hd
berghofe@21541
   385
  end;
berghofe@21541
   386
berghofe@21541
   387
in
berghofe@21541
   388
berghofe@29097
   389
val add_primrec = gen_primrec false Specification.check_specification (K I);
berghofe@29097
   390
val add_primrec_cmd = gen_primrec true Specification.read_specification Syntax.read_term;
berghofe@21541
   391
berghofe@29097
   392
end;
berghofe@21541
   393
berghofe@21541
   394
berghofe@21541
   395
(* outer syntax *)
berghofe@21541
   396
berghofe@21541
   397
local structure P = OuterParse and K = OuterKeyword in
berghofe@21541
   398
wenzelm@24906
   399
val freshness_context = P.reserved "freshness_context";
wenzelm@24906
   400
val invariant = P.reserved "invariant";
wenzelm@24867
   401
wenzelm@24906
   402
fun unless_flag scan = Scan.unless ((freshness_context || invariant) -- P.$$$ ":") scan;
wenzelm@24906
   403
wenzelm@24906
   404
val parser1 = (freshness_context -- P.$$$ ":") |-- unless_flag P.term >> SOME;
wenzelm@24906
   405
val parser2 = (invariant -- P.$$$ ":") |--
wenzelm@24906
   406
    (Scan.repeat1 (unless_flag P.term) >> SOME) -- Scan.optional parser1 NONE ||
berghofe@21541
   407
  (parser1 >> pair NONE);
berghofe@21541
   408
val options =
berghofe@21541
   409
  Scan.optional (P.$$$ "(" |-- P.!!!
berghofe@29097
   410
    (parser2 --| P.$$$ ")")) (NONE, NONE);
berghofe@29097
   411
berghofe@29097
   412
fun pipe_error t = P.!!! (Scan.fail_with (K
berghofe@29097
   413
  (cat_lines ["Equations must be separated by " ^ quote "|", quote t])));
berghofe@21541
   414
berghofe@29097
   415
val statement = SpecParse.opt_thm_name ":" -- P.prop --| Scan.ahead
berghofe@29097
   416
  ((P.term :-- pipe_error) || Scan.succeed ("",""));
berghofe@29097
   417
berghofe@29097
   418
val statements = P.enum1 "|" statement;
berghofe@29097
   419
berghofe@29097
   420
val primrec_decl = P.opt_target -- options --
berghofe@29097
   421
  P.fixes -- P.for_fixes --| P.$$$ "where" -- statements;
berghofe@21541
   422
wenzelm@24867
   423
val _ =
berghofe@21541
   424
  OuterSyntax.command "nominal_primrec" "define primitive recursive functions on nominal datatypes" K.thy_goal
berghofe@29097
   425
    (primrec_decl >> (fn ((((opt_target, (invs, fctxt)), raw_fixes), raw_params), raw_spec) =>
berghofe@29097
   426
      Toplevel.print o Toplevel.local_theory_to_proof opt_target
berghofe@29097
   427
        (add_primrec_cmd invs fctxt raw_fixes raw_params raw_spec)));
berghofe@21541
   428
berghofe@21541
   429
end;
berghofe@21541
   430
berghofe@21541
   431
berghofe@21541
   432
end;
berghofe@21541
   433