src/HOL/Nominal/nominal_primrec.ML
author wenzelm
Sat Mar 29 13:03:07 2008 +0100 (2008-03-29)
changeset 26476 4e78281b3273
parent 25557 ea6b11021e79
child 26939 1035c89b4c02
permissions -rw-r--r--
eliminated quiete_mode ref (unused);
berghofe@21541
     1
(*  Title:      HOL/Nominal/nominal_primrec.ML
berghofe@21541
     2
    ID:         $Id$
berghofe@21541
     3
    Author:     Stefan Berghofer, TU Muenchen and Norbert Voelker, FernUni Hagen
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@21541
    11
  val add_primrec: string -> string list option -> string option ->
berghofe@21541
    12
    ((bstring * string) * Attrib.src list) list -> theory -> Proof.state
berghofe@21541
    13
  val add_primrec_unchecked: string -> string list option -> string option ->
berghofe@21541
    14
    ((bstring * string) * Attrib.src list) list -> theory -> Proof.state
berghofe@21541
    15
  val add_primrec_i: string -> term list option -> term option ->
berghofe@21541
    16
    ((bstring * term) * attribute list) list -> theory -> Proof.state
berghofe@21541
    17
  val add_primrec_unchecked_i: string -> term list option -> term option ->
berghofe@21541
    18
    ((bstring * term) * attribute list) list -> 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@21541
    29
fun primrec_eq_err thy s eq =
berghofe@21541
    30
  primrec_err (s ^ "\nin\n" ^ quote (Sign.string_of_term thy eq));
berghofe@21541
    31
berghofe@21541
    32
berghofe@21541
    33
(* preprocessing of equations *)
berghofe@21541
    34
berghofe@21541
    35
fun process_eqn thy eq rec_fns = 
berghofe@21541
    36
  let
berghofe@21541
    37
    val (lhs, rhs) = 
berghofe@21541
    38
      if null (term_vars eq) then
berghofe@21541
    39
        HOLogic.dest_eq (HOLogic.dest_Trueprop (Logic.strip_imp_concl eq))
berghofe@21541
    40
        handle TERM _ => raise RecError "not a proper equation"
berghofe@21541
    41
      else raise RecError "illegal schematic variable(s)";
berghofe@21541
    42
berghofe@21541
    43
    val (recfun, args) = strip_comb lhs;
berghofe@21541
    44
    val fnameT = dest_Const recfun handle TERM _ => 
berghofe@21541
    45
      raise RecError "function is not declared as constant in theory";
berghofe@21541
    46
berghofe@21541
    47
    val (ls', rest)  = take_prefix is_Free args;
berghofe@21541
    48
    val (middle, rs') = take_suffix is_Free rest;
berghofe@21541
    49
    val rpos = length ls';
berghofe@21541
    50
berghofe@21541
    51
    val (constr, cargs') = if null middle then raise RecError "constructor missing"
berghofe@21541
    52
      else strip_comb (hd middle);
berghofe@21541
    53
    val (cname, T) = dest_Const constr
berghofe@21541
    54
      handle TERM _ => raise RecError "ill-formed constructor";
berghofe@21541
    55
    val (tname, _) = dest_Type (body_type T) handle TYPE _ =>
berghofe@21541
    56
      raise RecError "cannot determine datatype associated with function"
berghofe@21541
    57
berghofe@21541
    58
    val (ls, cargs, rs) =
berghofe@21541
    59
      (map dest_Free ls', map dest_Free cargs', map dest_Free rs')
berghofe@21541
    60
      handle TERM _ => raise RecError "illegal argument in pattern";
berghofe@21541
    61
    val lfrees = ls @ rs @ cargs;
berghofe@21541
    62
berghofe@21541
    63
    fun check_vars _ [] = ()
berghofe@21541
    64
      | check_vars s vars = raise RecError (s ^ commas_quote (map fst vars))
berghofe@21541
    65
  in
berghofe@21541
    66
    if length middle > 1 then 
berghofe@21541
    67
      raise RecError "more than one non-variable in pattern"
berghofe@21541
    68
    else
berghofe@21541
    69
     (check_vars "repeated variable names in pattern: " (duplicates (op =) lfrees);
berghofe@21541
    70
      check_vars "extra variables on rhs: "
berghofe@21541
    71
        (map dest_Free (term_frees rhs) \\ lfrees);
berghofe@21541
    72
      case AList.lookup (op =) rec_fns fnameT of
berghofe@21541
    73
        NONE =>
berghofe@21541
    74
          (fnameT, (tname, rpos, [(cname, (ls, cargs, rs, rhs, eq))]))::rec_fns
berghofe@21541
    75
      | SOME (_, rpos', eqns) =>
berghofe@21541
    76
          if AList.defined (op =) eqns cname then
berghofe@21541
    77
            raise RecError "constructor already occurred as pattern"
berghofe@21541
    78
          else if rpos <> rpos' then
berghofe@21541
    79
            raise RecError "position of recursive argument inconsistent"
berghofe@21541
    80
          else
berghofe@21541
    81
            AList.update (op =) (fnameT, (tname, rpos, (cname, (ls, cargs, rs, rhs, eq))::eqns))
berghofe@21541
    82
              rec_fns)
berghofe@21541
    83
  end
berghofe@21541
    84
  handle RecError s => primrec_eq_err thy s eq;
berghofe@21541
    85
berghofe@21541
    86
val param_err = "Parameters must be the same for all recursive functions";
berghofe@21541
    87
berghofe@21541
    88
fun process_fun thy descr rec_eqns (i, fnameT as (fname, _)) (fnameTs, fnss) =
berghofe@21541
    89
  let
berghofe@21541
    90
    val (_, (tname, _, constrs)) = List.nth (descr, i);
berghofe@21541
    91
berghofe@21541
    92
    (* substitute "fname ls x rs" by "y" for (x, (_, y)) in subs *)
berghofe@21541
    93
berghofe@21541
    94
    fun subst [] t fs = (t, fs)
berghofe@21541
    95
      | subst subs (Abs (a, T, t)) fs =
berghofe@21541
    96
          fs
berghofe@21541
    97
          |> subst subs t
berghofe@21541
    98
          |-> (fn t' => pair (Abs (a, T, t')))
berghofe@21541
    99
      | subst subs (t as (_ $ _)) fs =
berghofe@21541
   100
          let
berghofe@21541
   101
            val (f, ts) = strip_comb t;
berghofe@21541
   102
          in
berghofe@21541
   103
            if is_Const f andalso dest_Const f mem map fst rec_eqns then
berghofe@21541
   104
              let
berghofe@21541
   105
                val fnameT' as (fname', _) = dest_Const f;
berghofe@21541
   106
                val (_, rpos, eqns) = the (AList.lookup (op =) rec_eqns fnameT');
berghofe@21541
   107
                val ls = Library.take (rpos, ts);
berghofe@21541
   108
                val rest = Library.drop (rpos, ts);
berghofe@21541
   109
                val (x', rs) = (hd rest, tl rest)
berghofe@21541
   110
                  handle Empty => raise RecError ("not enough arguments\
berghofe@21541
   111
                   \ in recursive application\nof function " ^ quote fname' ^ " on rhs");
berghofe@23006
   112
                val rs' = (case eqns of
berghofe@21541
   113
                    (_, (ls', _, rs', _, _)) :: _ =>
berghofe@23006
   114
                      let val (rs1, rs2) = chop (length rs') rs
berghofe@23006
   115
                      in
berghofe@23006
   116
                        if ls = map Free ls' andalso rs1 = map Free rs' then rs2
berghofe@23006
   117
                        else raise RecError param_err
berghofe@23006
   118
                      end
berghofe@23006
   119
                  | _ => raise RecError ("no equations for " ^ quote fname'));
berghofe@21541
   120
                val (x, xs) = strip_comb x'
berghofe@21541
   121
              in case AList.lookup (op =) subs x
berghofe@21541
   122
               of NONE =>
berghofe@21541
   123
                    fs
berghofe@21541
   124
                    |> fold_map (subst subs) ts
berghofe@21541
   125
                    |-> (fn ts' => pair (list_comb (f, ts')))
berghofe@21541
   126
                | SOME (i', y) =>
berghofe@21541
   127
                    fs
berghofe@23006
   128
                    |> fold_map (subst subs) (xs @ rs')
berghofe@21541
   129
                    ||> process_fun thy descr rec_eqns (i', fnameT')
berghofe@21541
   130
                    |-> (fn ts' => pair (list_comb (y, ts')))
berghofe@21541
   131
              end
berghofe@21541
   132
            else
berghofe@21541
   133
              fs
berghofe@21541
   134
              |> fold_map (subst subs) (f :: ts)
berghofe@21541
   135
              |-> (fn (f'::ts') => pair (list_comb (f', ts')))
berghofe@21541
   136
          end
berghofe@21541
   137
      | subst _ t fs = (t, fs);
berghofe@21541
   138
berghofe@21541
   139
    (* translate rec equations into function arguments suitable for rec comb *)
berghofe@21541
   140
berghofe@21541
   141
    fun trans eqns (cname, cargs) (fnameTs', fnss', fns) =
berghofe@21541
   142
      (case AList.lookup (op =) eqns cname of
berghofe@21541
   143
          NONE => (warning ("No equation for constructor " ^ quote cname ^
berghofe@21541
   144
            "\nin definition of function " ^ quote fname);
berghofe@21541
   145
              (fnameTs', fnss', (Const ("arbitrary", dummyT))::fns))
berghofe@21541
   146
        | SOME (ls, cargs', rs, rhs, eq) =>
berghofe@21541
   147
            let
berghofe@21541
   148
              val recs = filter (is_rec_type o snd) (cargs' ~~ cargs);
berghofe@21541
   149
              val rargs = map fst recs;
berghofe@21541
   150
              val subs = map (rpair dummyT o fst) 
berghofe@21541
   151
                (rev (rename_wrt_term rhs rargs));
berghofe@21541
   152
              val (rhs', (fnameTs'', fnss'')) = 
berghofe@21541
   153
                  (subst (map (fn ((x, y), z) =>
berghofe@21541
   154
                               (Free x, (body_index y, Free z)))
berghofe@21541
   155
                          (recs ~~ subs)) rhs (fnameTs', fnss'))
berghofe@21541
   156
                  handle RecError s => primrec_eq_err thy s eq
berghofe@21541
   157
            in (fnameTs'', fnss'', 
berghofe@21541
   158
                (list_abs_free (cargs' @ subs, rhs'))::fns)
berghofe@21541
   159
            end)
berghofe@21541
   160
berghofe@21541
   161
  in (case AList.lookup (op =) fnameTs i of
berghofe@21541
   162
      NONE =>
berghofe@21541
   163
        if exists (equal fnameT o snd) fnameTs then
berghofe@21541
   164
          raise RecError ("inconsistent functions for datatype " ^ quote tname)
berghofe@21541
   165
        else
berghofe@21541
   166
          let
berghofe@21541
   167
            val SOME (_, _, eqns as (_, (ls, _, rs, _, _)) :: _) =
berghofe@21541
   168
              AList.lookup (op =) rec_eqns fnameT;
berghofe@21541
   169
            val (fnameTs', fnss', fns) = fold_rev (trans eqns) constrs
berghofe@21541
   170
              ((i, fnameT)::fnameTs, fnss, []) 
berghofe@21541
   171
          in
berghofe@21541
   172
            (fnameTs', (i, (fname, ls, rs, fns))::fnss')
berghofe@21541
   173
          end
berghofe@21541
   174
    | SOME fnameT' =>
berghofe@21541
   175
        if fnameT = fnameT' then (fnameTs, fnss)
berghofe@21541
   176
        else raise RecError ("inconsistent functions for datatype " ^ quote tname))
berghofe@21541
   177
  end;
berghofe@21541
   178
berghofe@21541
   179
berghofe@21541
   180
(* prepare functions needed for definitions *)
berghofe@21541
   181
berghofe@21541
   182
fun get_fns fns ((i : int, (tname, _, constrs)), rec_name) (fs, defs) =
berghofe@21541
   183
  case AList.lookup (op =) fns i of
berghofe@21541
   184
     NONE =>
berghofe@21541
   185
       let
berghofe@21541
   186
         val dummy_fns = map (fn (_, cargs) => Const ("arbitrary",
berghofe@21541
   187
           replicate ((length cargs) + (length (List.filter is_rec_type cargs)))
berghofe@21541
   188
             dummyT ---> HOLogic.unitT)) constrs;
berghofe@21541
   189
         val _ = warning ("No function definition for datatype " ^ quote tname)
berghofe@21541
   190
       in
berghofe@21541
   191
         (dummy_fns @ fs, defs)
berghofe@21541
   192
       end
berghofe@21541
   193
   | SOME (fname, ls, rs, fs') => (fs' @ fs, (fname, ls, rs, rec_name, tname) :: defs);
berghofe@21541
   194
berghofe@21541
   195
berghofe@21541
   196
(* make definition *)
berghofe@21541
   197
berghofe@21541
   198
fun make_def thy fs (fname, ls, rs, rec_name, tname) =
berghofe@21541
   199
  let
berghofe@21541
   200
    val used = map fst (fold Term.add_frees fs []);
berghofe@21541
   201
    val x = (Name.variant used "x", dummyT);
berghofe@21541
   202
    val frees = ls @ x :: rs;
berghofe@21541
   203
    val rhs = list_abs_free (frees,
berghofe@21541
   204
      list_comb (Const (rec_name, dummyT), fs @ [Free x]))
wenzelm@22692
   205
    val def_name = Sign.base_name fname ^ "_" ^ Sign.base_name tname ^ "_def";
wenzelm@22692
   206
    val def_prop as _ $ _ $ t =
wenzelm@24493
   207
      singleton (Syntax.check_terms (ProofContext.init thy))
wenzelm@22728
   208
        (Logic.mk_equals (Const (fname, dummyT), rhs));
wenzelm@22692
   209
  in ((def_name, def_prop), subst_bounds (rev (map Free frees), strip_abs_body t)) end;
berghofe@21541
   210
berghofe@21541
   211
berghofe@21541
   212
(* find datatypes which contain all datatypes in tnames' *)
berghofe@21541
   213
berghofe@21541
   214
fun find_dts (dt_info : NominalPackage.nominal_datatype_info Symtab.table) _ [] = []
berghofe@21541
   215
  | find_dts dt_info tnames' (tname::tnames) =
berghofe@21541
   216
      (case Symtab.lookup dt_info tname of
berghofe@21541
   217
          NONE => primrec_err (quote tname ^ " is not a nominal datatype")
berghofe@21541
   218
        | SOME dt =>
berghofe@21541
   219
            if tnames' subset (map (#1 o snd) (#descr dt)) then
berghofe@21541
   220
              (tname, dt)::(find_dts dt_info tnames' tnames)
berghofe@21541
   221
            else find_dts dt_info tnames' tnames);
berghofe@21541
   222
berghofe@21541
   223
fun common_prefix eq ([], _) = []
berghofe@21541
   224
  | common_prefix eq (_, []) = []
berghofe@21541
   225
  | common_prefix eq (x :: xs, y :: ys) =
berghofe@21541
   226
      if eq (x, y) then x :: common_prefix eq (xs, ys) else [];
berghofe@21541
   227
berghofe@21541
   228
local
berghofe@21541
   229
berghofe@21541
   230
fun gen_primrec_i note def alt_name invs fctxt eqns_atts thy =
berghofe@21541
   231
  let
berghofe@21541
   232
    val (eqns, atts) = split_list eqns_atts;
berghofe@21541
   233
    val dt_info = NominalPackage.get_nominal_datatypes thy;
berghofe@21541
   234
    val rec_eqns = fold_rev (process_eqn thy o snd) eqns [];
berghofe@21541
   235
    val lsrs :: lsrss = maps (fn (_, (_, _, eqns)) =>
berghofe@21541
   236
      map (fn (_, (ls, _, rs, _, _)) => ls @ rs) eqns) rec_eqns
berghofe@21541
   237
    val _ =
berghofe@21541
   238
      (if forall (curry eq_set lsrs) lsrss andalso forall
berghofe@21541
   239
         (fn (_, (_, _, (_, (ls, _, rs, _, _)) :: eqns)) =>
berghofe@21541
   240
               forall (fn (_, (ls', _, rs', _, _)) =>
berghofe@21541
   241
                 ls = ls' andalso rs = rs') eqns
berghofe@21541
   242
           | _ => true) rec_eqns
berghofe@22330
   243
       then () else primrec_err param_err);
berghofe@21541
   244
    val tnames = distinct (op =) (map (#1 o snd) rec_eqns);
berghofe@21541
   245
    val dts = find_dts dt_info tnames tnames;
berghofe@21541
   246
    val main_fns = 
berghofe@21541
   247
      map (fn (tname, {index, ...}) =>
berghofe@21541
   248
        (index, 
berghofe@21541
   249
          (fst o the o find_first (fn f => (#1 o snd) f = tname)) rec_eqns))
berghofe@21541
   250
      dts;
berghofe@21541
   251
    val {descr, rec_names, rec_rewrites, ...} = 
berghofe@21541
   252
      if null dts then
berghofe@21541
   253
        primrec_err ("datatypes " ^ commas_quote tnames ^ "\nare not mutually recursive")
berghofe@21541
   254
      else snd (hd dts);
berghofe@22434
   255
    val descr = map (fn (i, (tname, args, constrs)) => (i, (tname, args,
berghofe@22434
   256
      map (fn (cname, cargs) => (cname, fold (fn (dTs, dT) => fn dTs' =>
berghofe@22434
   257
        dTs' @ dTs @ [dT]) cargs [])) constrs))) descr;
berghofe@21541
   258
    val (fnameTs, fnss) =
berghofe@21541
   259
      fold_rev (process_fun thy descr rec_eqns) main_fns ([], []);
berghofe@21541
   260
    val (fs, defs) = fold_rev (get_fns fnss) (descr ~~ rec_names) ([], []);
berghofe@21541
   261
    val defs' = map (make_def thy fs) defs;
berghofe@21541
   262
    val nameTs1 = map snd fnameTs;
berghofe@21541
   263
    val nameTs2 = map fst rec_eqns;
berghofe@21541
   264
    val _ = if gen_eq_set (op =) (nameTs1, nameTs2) then ()
berghofe@21541
   265
            else primrec_err ("functions " ^ commas_quote (map fst nameTs2) ^
berghofe@21541
   266
              "\nare not mutually recursive");
berghofe@21541
   267
    val primrec_name =
berghofe@21541
   268
      if alt_name = "" then (space_implode "_" (map (Sign.base_name o #1) defs)) else alt_name;
berghofe@21541
   269
    val (defs_thms', thy') =
berghofe@21541
   270
      thy
wenzelm@24712
   271
      |> Sign.add_path primrec_name
berghofe@21541
   272
      |> fold_map def (map (fn ((name, t), _) => ((name, []), t)) defs');
berghofe@21541
   273
    val cert = cterm_of thy';
berghofe@21541
   274
berghofe@21541
   275
    fun mk_idx eq =
berghofe@21541
   276
      let
berghofe@21541
   277
        val Const c = head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop
berghofe@21541
   278
          (Logic.strip_imp_concl eq))));
berghofe@21541
   279
        val SOME i = AList.lookup op = (map swap fnameTs) c;
berghofe@21541
   280
        val SOME (_, _, constrs) = AList.lookup op = descr i;
berghofe@21541
   281
        val SOME (_, _, eqns) = AList.lookup op = rec_eqns c;
berghofe@21541
   282
        val SOME (cname, (_, cargs, _, _, _)) = find_first
berghofe@21541
   283
          (fn (_, (_, _, _, _, eq')) => eq = eq') eqns
berghofe@21541
   284
      in (i, find_index (fn (cname', _) => cname = cname') constrs, cargs) end;
berghofe@21541
   285
berghofe@21541
   286
    val rec_rewritess =
berghofe@21541
   287
      unflat (map (fn (_, (_, _, constrs)) => constrs) descr) rec_rewrites;
berghofe@21541
   288
    val fvars = rec_rewrites |> hd |> concl_of |> HOLogic.dest_Trueprop |>
berghofe@21541
   289
      HOLogic.dest_eq |> fst |> strip_comb |> snd |> take_prefix is_Var |> fst;
berghofe@21541
   290
    val (pvars, ctxtvars) = List.partition
berghofe@21541
   291
      (equal HOLogic.boolT o body_type o snd)
berghofe@22434
   292
      (fold_rev Term.add_vars (map Logic.strip_assums_concl
berghofe@21541
   293
        (prems_of (hd rec_rewrites))) [] \\ map dest_Var fvars);
berghofe@21541
   294
    val cfs = defs' |> hd |> snd |> strip_comb |> snd |>
berghofe@21541
   295
      curry (List.take o swap) (length fvars) |> map cert;
berghofe@21541
   296
    val invs' = (case invs of
berghofe@21541
   297
        NONE => map (fn (i, _) =>
berghofe@21541
   298
          let
berghofe@21541
   299
            val SOME (_, T) = AList.lookup op = fnameTs i
berghofe@21541
   300
            val (Ts, U) = strip_type T
berghofe@21541
   301
          in
berghofe@21541
   302
            Abs ("x", List.drop (Ts, length lsrs + 1) ---> U, HOLogic.true_const)
berghofe@21541
   303
          end) descr
berghofe@21541
   304
      | SOME invs' => invs');
berghofe@21541
   305
    val inst = (map cert fvars ~~ cfs) @
berghofe@21541
   306
      (map (cert o Var) pvars ~~ map cert invs') @
berghofe@21541
   307
      (case ctxtvars of
berghofe@21541
   308
         [ctxtvar] => [(cert (Var ctxtvar), cert (the_default HOLogic.unit fctxt))]
berghofe@21541
   309
       | _ => []);
berghofe@21541
   310
    val rec_rewrites' = map (fn (_, eq) =>
berghofe@21541
   311
      let
berghofe@21541
   312
        val (i, j, cargs) = mk_idx eq
berghofe@21541
   313
        val th = nth (nth rec_rewritess i) j;
berghofe@21541
   314
        val cargs' = th |> concl_of |> HOLogic.dest_Trueprop |>
berghofe@21541
   315
          HOLogic.dest_eq |> fst |> strip_comb |> snd |> split_last |> snd |>
berghofe@21541
   316
          strip_comb |> snd
berghofe@21541
   317
      in (cargs, Logic.strip_imp_prems eq,
berghofe@21541
   318
        Drule.cterm_instantiate (inst @
berghofe@21541
   319
          (map (cterm_of thy') cargs' ~~ map (cterm_of thy' o Free) cargs)) th)
berghofe@21541
   320
      end) eqns;
berghofe@21541
   321
berghofe@21541
   322
    val prems = foldr1 (common_prefix op aconv) (map (prems_of o #3) rec_rewrites');
berghofe@21541
   323
    val cprems = map cert prems;
berghofe@21541
   324
    val asms = map Thm.assume cprems;
berghofe@21541
   325
    val premss = map (fn (cargs, eprems, eqn) =>
berghofe@21541
   326
      map (fn t => list_all_free (cargs, Logic.list_implies (eprems, t)))
berghofe@21541
   327
        (List.drop (prems_of eqn, length prems))) rec_rewrites';
berghofe@21541
   328
    val cpremss = map (map cert) premss;
berghofe@21541
   329
    val asmss = map (map Thm.assume) cpremss;
berghofe@21541
   330
berghofe@21541
   331
    fun mk_eqn ((cargs, eprems, eqn), asms') =
berghofe@21541
   332
      let
berghofe@21541
   333
        val ceprems = map cert eprems;
berghofe@21541
   334
        val asms'' = map Thm.assume ceprems;
berghofe@21541
   335
        val ccargs = map (cert o Free) cargs;
berghofe@21541
   336
        val asms''' = map (fn th => implies_elim_list
berghofe@21541
   337
          (forall_elim_list ccargs th) asms'') asms'
berghofe@21541
   338
      in
berghofe@21541
   339
        implies_elim_list eqn (asms @ asms''') |>
berghofe@21541
   340
        implies_intr_list ceprems |>
berghofe@21541
   341
        forall_intr_list ccargs
berghofe@21541
   342
      end;
berghofe@21541
   343
berghofe@21541
   344
    val rule_prems = cprems @ flat cpremss;
berghofe@21541
   345
    val rule = implies_intr_list rule_prems
wenzelm@23418
   346
      (Conjunction.intr_balanced (map mk_eqn (rec_rewrites' ~~ asmss)));
berghofe@21541
   347
berghofe@21541
   348
    val goals = map (fn ((cargs, _, _), (_, eqn)) =>
berghofe@21541
   349
      (list_all_free (cargs, eqn), [])) (rec_rewrites' ~~ eqns);
berghofe@21541
   350
berghofe@21541
   351
  in
berghofe@21541
   352
    thy' |>
berghofe@21541
   353
    ProofContext.init |>
berghofe@21541
   354
    Proof.theorem_i NONE
berghofe@21541
   355
      (fn thss => ProofContext.theory (fn thy =>
berghofe@21541
   356
         let
nipkow@21618
   357
           val simps = map standard (flat thss);
berghofe@21541
   358
           val (simps', thy') =
berghofe@21541
   359
             fold_map note ((map fst eqns ~~ atts) ~~ map single simps) thy;
berghofe@21541
   360
           val simps'' = maps snd simps'
berghofe@21541
   361
         in
berghofe@21541
   362
           thy'
berghofe@21541
   363
           |> note (("simps", [Simplifier.simp_add]), simps'')
berghofe@21541
   364
           |> snd
wenzelm@24712
   365
           |> Sign.parent_path
berghofe@21541
   366
         end))
berghofe@21541
   367
      [goals] |>
wenzelm@23351
   368
    Proof.apply (Method.Basic (fn _ => Method.RAW_METHOD (fn _ =>
berghofe@21541
   369
      rewrite_goals_tac (map snd defs_thms') THEN
wenzelm@23351
   370
      compose_tac (false, rule, length rule_prems) 1), Position.none)) |>
berghofe@21541
   371
    Seq.hd
berghofe@21541
   372
  end;
berghofe@21541
   373
berghofe@21541
   374
fun gen_primrec note def alt_name invs fctxt eqns thy =
berghofe@21541
   375
  let
berghofe@21541
   376
    val ((names, strings), srcss) = apfst split_list (split_list eqns);
berghofe@21541
   377
    val atts = map (map (Attrib.attribute thy)) srcss;
wenzelm@24707
   378
    val eqn_ts = map (fn s => Syntax.read_prop_global thy s
berghofe@21541
   379
      handle ERROR msg => cat_error msg ("The error(s) above occurred for " ^ s)) strings;
berghofe@21541
   380
    val rec_ts = map (fn eq => head_of (fst (HOLogic.dest_eq
berghofe@21541
   381
      (HOLogic.dest_Trueprop (Logic.strip_imp_concl eq))))
berghofe@21541
   382
      handle TERM _ => primrec_eq_err thy "not a proper equation" eq) eqn_ts;
haftmann@25557
   383
    val (_, eqn_ts') = OldPrimrecPackage.unify_consts thy rec_ts eqn_ts
berghofe@21541
   384
  in
berghofe@21541
   385
    gen_primrec_i note def alt_name
wenzelm@24707
   386
      (Option.map (map (Syntax.read_term_global thy)) invs)
wenzelm@24707
   387
      (Option.map (Syntax.read_term_global thy) fctxt)
berghofe@21541
   388
      (names ~~ eqn_ts' ~~ atts) thy
berghofe@21541
   389
  end;
berghofe@21541
   390
berghofe@21541
   391
fun thy_note ((name, atts), thms) =
berghofe@21541
   392
  PureThy.add_thmss [((name, thms), atts)] #-> (fn [thms] => pair (name, thms));
berghofe@21541
   393
fun thy_def false ((name, atts), t) =
berghofe@21541
   394
      PureThy.add_defs_i false [((name, t), atts)] #-> (fn [thm] => pair (name, thm))
berghofe@21541
   395
  | thy_def true ((name, atts), t) =
berghofe@21541
   396
      PureThy.add_defs_unchecked_i false [((name, t), atts)] #-> (fn [thm] => pair (name, thm));
berghofe@21541
   397
berghofe@21541
   398
in
berghofe@21541
   399
berghofe@21541
   400
val add_primrec = gen_primrec thy_note (thy_def false);
berghofe@21541
   401
val add_primrec_unchecked = gen_primrec thy_note (thy_def true);
berghofe@21541
   402
val add_primrec_i = gen_primrec_i thy_note (thy_def false);
berghofe@21541
   403
val add_primrec_unchecked_i = gen_primrec_i thy_note (thy_def true);
berghofe@21541
   404
berghofe@21541
   405
end; (*local*)
berghofe@21541
   406
berghofe@21541
   407
berghofe@21541
   408
(* outer syntax *)
berghofe@21541
   409
berghofe@21541
   410
local structure P = OuterParse and K = OuterKeyword in
berghofe@21541
   411
wenzelm@24906
   412
val freshness_context = P.reserved "freshness_context";
wenzelm@24906
   413
val invariant = P.reserved "invariant";
wenzelm@24867
   414
wenzelm@24906
   415
fun unless_flag scan = Scan.unless ((freshness_context || invariant) -- P.$$$ ":") scan;
wenzelm@24906
   416
wenzelm@24906
   417
val parser1 = (freshness_context -- P.$$$ ":") |-- unless_flag P.term >> SOME;
wenzelm@24906
   418
val parser2 = (invariant -- P.$$$ ":") |--
wenzelm@24906
   419
    (Scan.repeat1 (unless_flag P.term) >> SOME) -- Scan.optional parser1 NONE ||
berghofe@21541
   420
  (parser1 >> pair NONE);
berghofe@21541
   421
val parser3 =
wenzelm@24906
   422
  unless_flag P.name -- Scan.optional parser2 (NONE, NONE) ||
berghofe@21541
   423
  (parser2 >> pair "");
berghofe@21541
   424
val parser4 =
berghofe@21541
   425
  (P.$$$ "unchecked" >> K true) -- Scan.optional parser3 ("", (NONE, NONE)) ||
berghofe@21541
   426
  (parser3 >> pair false);
berghofe@21541
   427
val options =
berghofe@21541
   428
  Scan.optional (P.$$$ "(" |-- P.!!!
berghofe@21541
   429
    (parser4 --| P.$$$ ")")) (false, ("", (NONE, NONE)));
berghofe@21541
   430
berghofe@21541
   431
val primrec_decl =
wenzelm@22101
   432
  options -- Scan.repeat1 (SpecParse.opt_thm_name ":" -- P.prop);
berghofe@21541
   433
wenzelm@24867
   434
val _ =
berghofe@21541
   435
  OuterSyntax.command "nominal_primrec" "define primitive recursive functions on nominal datatypes" K.thy_goal
berghofe@21541
   436
    (primrec_decl >> (fn ((unchecked, (alt_name, (invs, fctxt))), eqns) =>
berghofe@21767
   437
      Toplevel.print o Toplevel.theory_to_proof
berghofe@21541
   438
        ((if unchecked then add_primrec_unchecked else add_primrec) alt_name invs fctxt
berghofe@21541
   439
          (map P.triple_swap eqns))));
berghofe@21541
   440
berghofe@21541
   441
end;
berghofe@21541
   442
berghofe@21541
   443
berghofe@21541
   444
end;
berghofe@21541
   445