src/HOL/Nominal/nominal_primrec.ML
author berghofe
Fri Feb 16 19:19:19 2007 +0100 (2007-02-16)
changeset 22330 00ca68f5ce29
parent 22101 6d13239d5f52
child 22434 081a62852313
permissions -rw-r--r--
Replaced "raise RecError" by "primrec_err" in function
gen_primrec_i to prevent error message from being suppressed.
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 quiet_mode: bool ref
berghofe@21541
    12
  val add_primrec: string -> string list option -> string option ->
berghofe@21541
    13
    ((bstring * string) * Attrib.src list) list -> theory -> Proof.state
berghofe@21541
    14
  val add_primrec_unchecked: string -> string list option -> string option ->
berghofe@21541
    15
    ((bstring * string) * Attrib.src list) list -> theory -> Proof.state
berghofe@21541
    16
  val add_primrec_i: string -> term list option -> term option ->
berghofe@21541
    17
    ((bstring * term) * attribute list) list -> theory -> Proof.state
berghofe@21541
    18
  val add_primrec_unchecked_i: string -> term list option -> term option ->
berghofe@21541
    19
    ((bstring * term) * attribute list) list -> theory -> Proof.state
berghofe@21541
    20
end;
berghofe@21541
    21
berghofe@21541
    22
structure NominalPrimrec : NOMINAL_PRIMREC =
berghofe@21541
    23
struct
berghofe@21541
    24
berghofe@21541
    25
open DatatypeAux;
berghofe@21541
    26
berghofe@21541
    27
exception RecError of string;
berghofe@21541
    28
berghofe@21541
    29
fun primrec_err s = error ("Nominal primrec definition error:\n" ^ s);
berghofe@21541
    30
fun primrec_eq_err thy s eq =
berghofe@21541
    31
  primrec_err (s ^ "\nin\n" ^ quote (Sign.string_of_term thy eq));
berghofe@21541
    32
berghofe@21541
    33
berghofe@21541
    34
(* messages *)
berghofe@21541
    35
berghofe@21541
    36
val quiet_mode = ref false;
berghofe@21541
    37
fun message s = if ! quiet_mode then () else writeln s;
berghofe@21541
    38
berghofe@21541
    39
berghofe@21541
    40
(* preprocessing of equations *)
berghofe@21541
    41
berghofe@21541
    42
fun process_eqn thy eq rec_fns = 
berghofe@21541
    43
  let
berghofe@21541
    44
    val (lhs, rhs) = 
berghofe@21541
    45
      if null (term_vars eq) then
berghofe@21541
    46
        HOLogic.dest_eq (HOLogic.dest_Trueprop (Logic.strip_imp_concl eq))
berghofe@21541
    47
        handle TERM _ => raise RecError "not a proper equation"
berghofe@21541
    48
      else raise RecError "illegal schematic variable(s)";
berghofe@21541
    49
berghofe@21541
    50
    val (recfun, args) = strip_comb lhs;
berghofe@21541
    51
    val fnameT = dest_Const recfun handle TERM _ => 
berghofe@21541
    52
      raise RecError "function is not declared as constant in theory";
berghofe@21541
    53
berghofe@21541
    54
    val (ls', rest)  = take_prefix is_Free args;
berghofe@21541
    55
    val (middle, rs') = take_suffix is_Free rest;
berghofe@21541
    56
    val rpos = length ls';
berghofe@21541
    57
berghofe@21541
    58
    val (constr, cargs') = if null middle then raise RecError "constructor missing"
berghofe@21541
    59
      else strip_comb (hd middle);
berghofe@21541
    60
    val (cname, T) = dest_Const constr
berghofe@21541
    61
      handle TERM _ => raise RecError "ill-formed constructor";
berghofe@21541
    62
    val (tname, _) = dest_Type (body_type T) handle TYPE _ =>
berghofe@21541
    63
      raise RecError "cannot determine datatype associated with function"
berghofe@21541
    64
berghofe@21541
    65
    val (ls, cargs, rs) =
berghofe@21541
    66
      (map dest_Free ls', map dest_Free cargs', map dest_Free rs')
berghofe@21541
    67
      handle TERM _ => raise RecError "illegal argument in pattern";
berghofe@21541
    68
    val lfrees = ls @ rs @ cargs;
berghofe@21541
    69
berghofe@21541
    70
    fun check_vars _ [] = ()
berghofe@21541
    71
      | check_vars s vars = raise RecError (s ^ commas_quote (map fst vars))
berghofe@21541
    72
  in
berghofe@21541
    73
    if length middle > 1 then 
berghofe@21541
    74
      raise RecError "more than one non-variable in pattern"
berghofe@21541
    75
    else
berghofe@21541
    76
     (check_vars "repeated variable names in pattern: " (duplicates (op =) lfrees);
berghofe@21541
    77
      check_vars "extra variables on rhs: "
berghofe@21541
    78
        (map dest_Free (term_frees rhs) \\ lfrees);
berghofe@21541
    79
      case AList.lookup (op =) rec_fns fnameT of
berghofe@21541
    80
        NONE =>
berghofe@21541
    81
          (fnameT, (tname, rpos, [(cname, (ls, cargs, rs, rhs, eq))]))::rec_fns
berghofe@21541
    82
      | SOME (_, rpos', eqns) =>
berghofe@21541
    83
          if AList.defined (op =) eqns cname then
berghofe@21541
    84
            raise RecError "constructor already occurred as pattern"
berghofe@21541
    85
          else if rpos <> rpos' then
berghofe@21541
    86
            raise RecError "position of recursive argument inconsistent"
berghofe@21541
    87
          else
berghofe@21541
    88
            AList.update (op =) (fnameT, (tname, rpos, (cname, (ls, cargs, rs, rhs, eq))::eqns))
berghofe@21541
    89
              rec_fns)
berghofe@21541
    90
  end
berghofe@21541
    91
  handle RecError s => primrec_eq_err thy s eq;
berghofe@21541
    92
berghofe@21541
    93
val param_err = "Parameters must be the same for all recursive functions";
berghofe@21541
    94
berghofe@21541
    95
fun process_fun thy descr rec_eqns (i, fnameT as (fname, _)) (fnameTs, fnss) =
berghofe@21541
    96
  let
berghofe@21541
    97
    val (_, (tname, _, constrs)) = List.nth (descr, i);
berghofe@21541
    98
berghofe@21541
    99
    (* substitute "fname ls x rs" by "y" for (x, (_, y)) in subs *)
berghofe@21541
   100
berghofe@21541
   101
    fun subst [] t fs = (t, fs)
berghofe@21541
   102
      | subst subs (Abs (a, T, t)) fs =
berghofe@21541
   103
          fs
berghofe@21541
   104
          |> subst subs t
berghofe@21541
   105
          |-> (fn t' => pair (Abs (a, T, t')))
berghofe@21541
   106
      | subst subs (t as (_ $ _)) fs =
berghofe@21541
   107
          let
berghofe@21541
   108
            val (f, ts) = strip_comb t;
berghofe@21541
   109
          in
berghofe@21541
   110
            if is_Const f andalso dest_Const f mem map fst rec_eqns then
berghofe@21541
   111
              let
berghofe@21541
   112
                val fnameT' as (fname', _) = dest_Const f;
berghofe@21541
   113
                val (_, rpos, eqns) = the (AList.lookup (op =) rec_eqns fnameT');
berghofe@21541
   114
                val ls = Library.take (rpos, ts);
berghofe@21541
   115
                val rest = Library.drop (rpos, ts);
berghofe@21541
   116
                val (x', rs) = (hd rest, tl rest)
berghofe@21541
   117
                  handle Empty => raise RecError ("not enough arguments\
berghofe@21541
   118
                   \ in recursive application\nof function " ^ quote fname' ^ " on rhs");
berghofe@21541
   119
                val _ = (case eqns of
berghofe@21541
   120
                    (_, (ls', _, rs', _, _)) :: _ =>
berghofe@21541
   121
                      if ls = map Free ls' andalso rs = map Free rs' then ()
berghofe@21541
   122
                      else raise RecError param_err
berghofe@21541
   123
                  | _ => ());
berghofe@21541
   124
                val (x, xs) = strip_comb x'
berghofe@21541
   125
              in case AList.lookup (op =) subs x
berghofe@21541
   126
               of NONE =>
berghofe@21541
   127
                    fs
berghofe@21541
   128
                    |> fold_map (subst subs) ts
berghofe@21541
   129
                    |-> (fn ts' => pair (list_comb (f, ts')))
berghofe@21541
   130
                | SOME (i', y) =>
berghofe@21541
   131
                    fs
berghofe@21541
   132
                    |> fold_map (subst subs) xs
berghofe@21541
   133
                    ||> process_fun thy descr rec_eqns (i', fnameT')
berghofe@21541
   134
                    |-> (fn ts' => pair (list_comb (y, ts')))
berghofe@21541
   135
              end
berghofe@21541
   136
            else
berghofe@21541
   137
              fs
berghofe@21541
   138
              |> fold_map (subst subs) (f :: ts)
berghofe@21541
   139
              |-> (fn (f'::ts') => pair (list_comb (f', ts')))
berghofe@21541
   140
          end
berghofe@21541
   141
      | subst _ t fs = (t, fs);
berghofe@21541
   142
berghofe@21541
   143
    (* translate rec equations into function arguments suitable for rec comb *)
berghofe@21541
   144
berghofe@21541
   145
    fun trans eqns (cname, cargs) (fnameTs', fnss', fns) =
berghofe@21541
   146
      (case AList.lookup (op =) eqns cname of
berghofe@21541
   147
          NONE => (warning ("No equation for constructor " ^ quote cname ^
berghofe@21541
   148
            "\nin definition of function " ^ quote fname);
berghofe@21541
   149
              (fnameTs', fnss', (Const ("arbitrary", dummyT))::fns))
berghofe@21541
   150
        | SOME (ls, cargs', rs, rhs, eq) =>
berghofe@21541
   151
            let
berghofe@21541
   152
              val recs = filter (is_rec_type o snd) (cargs' ~~ cargs);
berghofe@21541
   153
              val rargs = map fst recs;
berghofe@21541
   154
              val subs = map (rpair dummyT o fst) 
berghofe@21541
   155
                (rev (rename_wrt_term rhs rargs));
berghofe@21541
   156
              val (rhs', (fnameTs'', fnss'')) = 
berghofe@21541
   157
                  (subst (map (fn ((x, y), z) =>
berghofe@21541
   158
                               (Free x, (body_index y, Free z)))
berghofe@21541
   159
                          (recs ~~ subs)) rhs (fnameTs', fnss'))
berghofe@21541
   160
                  handle RecError s => primrec_eq_err thy s eq
berghofe@21541
   161
            in (fnameTs'', fnss'', 
berghofe@21541
   162
                (list_abs_free (cargs' @ subs, rhs'))::fns)
berghofe@21541
   163
            end)
berghofe@21541
   164
berghofe@21541
   165
  in (case AList.lookup (op =) fnameTs i of
berghofe@21541
   166
      NONE =>
berghofe@21541
   167
        if exists (equal fnameT o snd) fnameTs then
berghofe@21541
   168
          raise RecError ("inconsistent functions for datatype " ^ quote tname)
berghofe@21541
   169
        else
berghofe@21541
   170
          let
berghofe@21541
   171
            val SOME (_, _, eqns as (_, (ls, _, rs, _, _)) :: _) =
berghofe@21541
   172
              AList.lookup (op =) rec_eqns fnameT;
berghofe@21541
   173
            val (fnameTs', fnss', fns) = fold_rev (trans eqns) constrs
berghofe@21541
   174
              ((i, fnameT)::fnameTs, fnss, []) 
berghofe@21541
   175
          in
berghofe@21541
   176
            (fnameTs', (i, (fname, ls, rs, fns))::fnss')
berghofe@21541
   177
          end
berghofe@21541
   178
    | SOME fnameT' =>
berghofe@21541
   179
        if fnameT = fnameT' then (fnameTs, fnss)
berghofe@21541
   180
        else raise RecError ("inconsistent functions for datatype " ^ quote tname))
berghofe@21541
   181
  end;
berghofe@21541
   182
berghofe@21541
   183
berghofe@21541
   184
(* prepare functions needed for definitions *)
berghofe@21541
   185
berghofe@21541
   186
fun get_fns fns ((i : int, (tname, _, constrs)), rec_name) (fs, defs) =
berghofe@21541
   187
  case AList.lookup (op =) fns i of
berghofe@21541
   188
     NONE =>
berghofe@21541
   189
       let
berghofe@21541
   190
         val dummy_fns = map (fn (_, cargs) => Const ("arbitrary",
berghofe@21541
   191
           replicate ((length cargs) + (length (List.filter is_rec_type cargs)))
berghofe@21541
   192
             dummyT ---> HOLogic.unitT)) constrs;
berghofe@21541
   193
         val _ = warning ("No function definition for datatype " ^ quote tname)
berghofe@21541
   194
       in
berghofe@21541
   195
         (dummy_fns @ fs, defs)
berghofe@21541
   196
       end
berghofe@21541
   197
   | SOME (fname, ls, rs, fs') => (fs' @ fs, (fname, ls, rs, rec_name, tname) :: defs);
berghofe@21541
   198
berghofe@21541
   199
berghofe@21541
   200
(* make definition *)
berghofe@21541
   201
berghofe@21541
   202
fun make_def thy fs (fname, ls, rs, rec_name, tname) =
berghofe@21541
   203
  let
berghofe@21541
   204
    val used = map fst (fold Term.add_frees fs []);
berghofe@21541
   205
    val x = (Name.variant used "x", dummyT);
berghofe@21541
   206
    val frees = ls @ x :: rs;
berghofe@21541
   207
    val rhs = list_abs_free (frees,
berghofe@21541
   208
      list_comb (Const (rec_name, dummyT), fs @ [Free x]))
berghofe@21541
   209
    val defpair = (Sign.base_name fname ^ "_" ^ Sign.base_name tname ^ "_def",
berghofe@21541
   210
                   Logic.mk_equals (Const (fname, dummyT), rhs));
berghofe@21541
   211
    val defpair' as (_, _ $ _ $ t) = Theory.inferT_axm thy defpair
berghofe@21541
   212
  in (defpair', subst_bounds (rev (map Free frees), strip_abs_body t)) end;
berghofe@21541
   213
berghofe@21541
   214
berghofe@21541
   215
(* find datatypes which contain all datatypes in tnames' *)
berghofe@21541
   216
berghofe@21541
   217
fun find_dts (dt_info : NominalPackage.nominal_datatype_info Symtab.table) _ [] = []
berghofe@21541
   218
  | find_dts dt_info tnames' (tname::tnames) =
berghofe@21541
   219
      (case Symtab.lookup dt_info tname of
berghofe@21541
   220
          NONE => primrec_err (quote tname ^ " is not a nominal datatype")
berghofe@21541
   221
        | SOME dt =>
berghofe@21541
   222
            if tnames' subset (map (#1 o snd) (#descr dt)) then
berghofe@21541
   223
              (tname, dt)::(find_dts dt_info tnames' tnames)
berghofe@21541
   224
            else find_dts dt_info tnames' tnames);
berghofe@21541
   225
berghofe@21541
   226
fun common_prefix eq ([], _) = []
berghofe@21541
   227
  | common_prefix eq (_, []) = []
berghofe@21541
   228
  | common_prefix eq (x :: xs, y :: ys) =
berghofe@21541
   229
      if eq (x, y) then x :: common_prefix eq (xs, ys) else [];
berghofe@21541
   230
berghofe@21541
   231
local
berghofe@21541
   232
berghofe@21541
   233
fun gen_primrec_i note def alt_name invs fctxt eqns_atts thy =
berghofe@21541
   234
  let
berghofe@21541
   235
    val (eqns, atts) = split_list eqns_atts;
berghofe@21541
   236
    val dt_info = NominalPackage.get_nominal_datatypes thy;
berghofe@21541
   237
    val rec_eqns = fold_rev (process_eqn thy o snd) eqns [];
berghofe@21541
   238
    val lsrs :: lsrss = maps (fn (_, (_, _, eqns)) =>
berghofe@21541
   239
      map (fn (_, (ls, _, rs, _, _)) => ls @ rs) eqns) rec_eqns
berghofe@21541
   240
    val _ =
berghofe@21541
   241
      (if forall (curry eq_set lsrs) lsrss andalso forall
berghofe@21541
   242
         (fn (_, (_, _, (_, (ls, _, rs, _, _)) :: eqns)) =>
berghofe@21541
   243
               forall (fn (_, (ls', _, rs', _, _)) =>
berghofe@21541
   244
                 ls = ls' andalso rs = rs') eqns
berghofe@21541
   245
           | _ => true) rec_eqns
berghofe@22330
   246
       then () else primrec_err param_err);
berghofe@21541
   247
    val tnames = distinct (op =) (map (#1 o snd) rec_eqns);
berghofe@21541
   248
    val dts = find_dts dt_info tnames tnames;
berghofe@21541
   249
    val main_fns = 
berghofe@21541
   250
      map (fn (tname, {index, ...}) =>
berghofe@21541
   251
        (index, 
berghofe@21541
   252
          (fst o the o find_first (fn f => (#1 o snd) f = tname)) rec_eqns))
berghofe@21541
   253
      dts;
berghofe@21541
   254
    val {descr, rec_names, rec_rewrites, ...} = 
berghofe@21541
   255
      if null dts then
berghofe@21541
   256
        primrec_err ("datatypes " ^ commas_quote tnames ^ "\nare not mutually recursive")
berghofe@21541
   257
      else snd (hd dts);
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
berghofe@21541
   271
      |> Theory.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@21541
   292
      (fold 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
berghofe@21541
   346
      (foldr1 (uncurry Conjunction.intr) (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
berghofe@21541
   365
           |> Theory.parent_path
berghofe@21541
   366
         end))
berghofe@21541
   367
      [goals] |>
berghofe@21541
   368
    Proof.apply (Method.Basic (fn ctxt => Method.RAW_METHOD (fn ths =>
berghofe@21541
   369
      rewrite_goals_tac (map snd defs_thms') THEN
berghofe@21541
   370
      compose_tac (false, rule, length rule_prems) 1))) |>
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
    fun readt T s = term_of (Thm.read_cterm thy (s, T));
berghofe@21541
   377
    val ((names, strings), srcss) = apfst split_list (split_list eqns);
berghofe@21541
   378
    val atts = map (map (Attrib.attribute thy)) srcss;
berghofe@21541
   379
    val eqn_ts = map (fn s => readt propT s
berghofe@21541
   380
      handle ERROR msg => cat_error msg ("The error(s) above occurred for " ^ s)) strings;
berghofe@21541
   381
    val rec_ts = map (fn eq => head_of (fst (HOLogic.dest_eq
berghofe@21541
   382
      (HOLogic.dest_Trueprop (Logic.strip_imp_concl eq))))
berghofe@21541
   383
      handle TERM _ => primrec_eq_err thy "not a proper equation" eq) eqn_ts;
berghofe@21541
   384
    val (_, eqn_ts') = OldInductivePackage.unify_consts thy rec_ts eqn_ts
berghofe@21541
   385
  in
berghofe@21541
   386
    gen_primrec_i note def alt_name
berghofe@21541
   387
      (Option.map (map (readt TypeInfer.logicT)) invs)
berghofe@21541
   388
      (Option.map (readt TypeInfer.logicT) fctxt)
berghofe@21541
   389
      (names ~~ eqn_ts' ~~ atts) thy
berghofe@21541
   390
  end;
berghofe@21541
   391
berghofe@21541
   392
fun thy_note ((name, atts), thms) =
berghofe@21541
   393
  PureThy.add_thmss [((name, thms), atts)] #-> (fn [thms] => pair (name, thms));
berghofe@21541
   394
fun thy_def false ((name, atts), t) =
berghofe@21541
   395
      PureThy.add_defs_i false [((name, t), atts)] #-> (fn [thm] => pair (name, thm))
berghofe@21541
   396
  | thy_def true ((name, atts), t) =
berghofe@21541
   397
      PureThy.add_defs_unchecked_i false [((name, t), atts)] #-> (fn [thm] => pair (name, thm));
berghofe@21541
   398
berghofe@21541
   399
in
berghofe@21541
   400
berghofe@21541
   401
val add_primrec = gen_primrec thy_note (thy_def false);
berghofe@21541
   402
val add_primrec_unchecked = gen_primrec thy_note (thy_def true);
berghofe@21541
   403
val add_primrec_i = gen_primrec_i thy_note (thy_def false);
berghofe@21541
   404
val add_primrec_unchecked_i = gen_primrec_i thy_note (thy_def true);
berghofe@21541
   405
berghofe@21541
   406
end; (*local*)
berghofe@21541
   407
berghofe@21541
   408
berghofe@21541
   409
(* outer syntax *)
berghofe@21541
   410
berghofe@21541
   411
local structure P = OuterParse and K = OuterKeyword in
berghofe@21541
   412
berghofe@21541
   413
val parser1 = P.$$$ "freshness_context" |-- P.$$$ ":" |-- (P.term >> SOME);
berghofe@21541
   414
val parser2 =
berghofe@21541
   415
  P.$$$ "invariant" |-- P.$$$ ":" |--
berghofe@21541
   416
    (Scan.repeat1 P.term >> SOME) -- Scan.optional parser1 NONE ||
berghofe@21541
   417
  (parser1 >> pair NONE);
berghofe@21541
   418
val parser3 =
berghofe@21541
   419
  P.name -- Scan.optional parser2 (NONE, NONE) ||
berghofe@21541
   420
  (parser2 >> pair "");
berghofe@21541
   421
val parser4 =
berghofe@21541
   422
  (P.$$$ "unchecked" >> K true) -- Scan.optional parser3 ("", (NONE, NONE)) ||
berghofe@21541
   423
  (parser3 >> pair false);
berghofe@21541
   424
val options =
berghofe@21541
   425
  Scan.optional (P.$$$ "(" |-- P.!!!
berghofe@21541
   426
    (parser4 --| P.$$$ ")")) (false, ("", (NONE, NONE)));
berghofe@21541
   427
berghofe@21541
   428
val primrec_decl =
wenzelm@22101
   429
  options -- Scan.repeat1 (SpecParse.opt_thm_name ":" -- P.prop);
berghofe@21541
   430
berghofe@21541
   431
val primrecP =
berghofe@21541
   432
  OuterSyntax.command "nominal_primrec" "define primitive recursive functions on nominal datatypes" K.thy_goal
berghofe@21541
   433
    (primrec_decl >> (fn ((unchecked, (alt_name, (invs, fctxt))), eqns) =>
berghofe@21767
   434
      Toplevel.print o Toplevel.theory_to_proof
berghofe@21541
   435
        ((if unchecked then add_primrec_unchecked else add_primrec) alt_name invs fctxt
berghofe@21541
   436
          (map P.triple_swap eqns))));
berghofe@21541
   437
berghofe@21541
   438
val _ = OuterSyntax.add_parsers [primrecP];
berghofe@21541
   439
val _ = OuterSyntax.add_keywords ["invariant", "freshness_context"];
berghofe@21541
   440
berghofe@21541
   441
end;
berghofe@21541
   442
berghofe@21541
   443
berghofe@21541
   444
end;
berghofe@21541
   445