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