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