src/HOL/Tools/primrec_package.ML
author wenzelm
Tue Sep 02 14:10:45 2008 +0200 (2008-09-02)
changeset 28083 103d9282a946
parent 27301 bf7d82193a2e
child 28084 a05ca48ef263
permissions -rw-r--r--
explicit type Name.binding for higher-specification elements;
berghofe@5719
     1
(*  Title:      HOL/Tools/primrec_package.ML
berghofe@5178
     2
    ID:         $Id$
haftmann@25557
     3
    Author:     Stefan Berghofer, TU Muenchen; Norbert Voelker, FernUni Hagen;
haftmann@25557
     4
                Florian Haftmann, TU Muenchen
berghofe@5178
     5
wenzelm@6359
     6
Package for defining functions on datatypes by primitive recursion.
berghofe@5178
     7
*)
berghofe@5178
     8
berghofe@5178
     9
signature PRIMREC_PACKAGE =
berghofe@5178
    10
sig
wenzelm@28083
    11
  val add_primrec: (Name.binding * typ option * mixfix) list ->
wenzelm@28083
    12
    ((Name.binding * Attrib.src list) * term) list -> local_theory -> thm list * local_theory
wenzelm@28083
    13
  val add_primrec_global: (Name.binding * typ option * mixfix) list ->
wenzelm@28083
    14
    ((Name.binding * Attrib.src list) * term) list -> theory -> thm list * theory
berghofe@26679
    15
  val add_primrec_overloaded: (string * (string * typ) * bool) list ->
wenzelm@28083
    16
    (Name.binding * typ option * mixfix) list ->
wenzelm@28083
    17
    ((Name.binding * Attrib.src list) * term) list -> theory -> thm list * theory
berghofe@5178
    18
end;
berghofe@5178
    19
berghofe@5178
    20
structure PrimrecPackage : PRIMREC_PACKAGE =
berghofe@5178
    21
struct
berghofe@5178
    22
berghofe@5178
    23
open DatatypeAux;
berghofe@5178
    24
haftmann@25557
    25
exception PrimrecError of string * term option;
wenzelm@6359
    26
haftmann@25557
    27
fun primrec_error msg = raise PrimrecError (msg, NONE);
haftmann@25557
    28
fun primrec_error_eqn msg eqn = raise PrimrecError (msg, SOME eqn);
berghofe@23765
    29
haftmann@25557
    30
fun message s = if ! Toplevel.debug then () else writeln s;
berghofe@23765
    31
berghofe@23765
    32
berghofe@5178
    33
(* preprocessing of equations *)
berghofe@5178
    34
haftmann@25559
    35
fun process_eqn is_fixed spec rec_fns =
berghofe@5178
    36
  let
haftmann@25566
    37
    val (vs, Ts) = split_list (strip_qnt_vars "all" spec);
haftmann@25557
    38
    val body = strip_qnt_body "all" spec;
haftmann@25566
    39
    val (vs', _) = Name.variants vs (Name.make_context (fold_aterms
haftmann@25566
    40
      (fn Free (v, _) => insert (op =) v | _ => I) body []));
haftmann@25566
    41
    val eqn = curry subst_bounds (map2 (curry Free) vs' Ts |> rev) body;
haftmann@25557
    42
    val (lhs, rhs) = HOLogic.dest_eq (HOLogic.dest_Trueprop eqn)
haftmann@25557
    43
      handle TERM _ => primrec_error "not a proper equation";
berghofe@5178
    44
    val (recfun, args) = strip_comb lhs;
haftmann@25557
    45
    val fname = case recfun of Free (v, _) => if is_fixed v then v
haftmann@25557
    46
          else primrec_error "illegal head of function equation"
haftmann@25557
    47
      | _ => primrec_error "illegal head of function equation";
berghofe@5178
    48
berghofe@5178
    49
    val (ls', rest)  = take_prefix is_Free args;
berghofe@5178
    50
    val (middle, rs') = take_suffix is_Free rest;
berghofe@5178
    51
    val rpos = length ls';
berghofe@5178
    52
haftmann@25557
    53
    val (constr, cargs') = if null middle then primrec_error "constructor missing"
berghofe@5178
    54
      else strip_comb (hd middle);
berghofe@5178
    55
    val (cname, T) = dest_Const constr
haftmann@25557
    56
      handle TERM _ => primrec_error "ill-formed constructor";
berghofe@7016
    57
    val (tname, _) = dest_Type (body_type T) handle TYPE _ =>
haftmann@25557
    58
      primrec_error "cannot determine datatype associated with function"
berghofe@5178
    59
haftmann@20176
    60
    val (ls, cargs, rs) =
haftmann@20176
    61
      (map dest_Free ls', map dest_Free cargs', map dest_Free rs')
haftmann@25557
    62
      handle TERM _ => primrec_error "illegal argument in pattern";
berghofe@5178
    63
    val lfrees = ls @ rs @ cargs;
berghofe@5178
    64
berghofe@12474
    65
    fun check_vars _ [] = ()
haftmann@25557
    66
      | check_vars s vars = primrec_error (s ^ commas_quote (map fst vars)) eqn;
berghofe@5178
    67
  in
wenzelm@22692
    68
    if length middle > 1 then
haftmann@25557
    69
      primrec_error "more than one non-variable in pattern"
berghofe@12474
    70
    else
wenzelm@18964
    71
     (check_vars "repeated variable names in pattern: " (duplicates (op =) lfrees);
berghofe@12474
    72
      check_vars "extra variables on rhs: "
haftmann@25557
    73
        (map dest_Free (term_frees rhs) |> subtract (op =) lfrees
haftmann@25559
    74
          |> filter_out (is_fixed o fst));
haftmann@25557
    75
      case AList.lookup (op =) rec_fns fname of
skalberg@15531
    76
        NONE =>
haftmann@25557
    77
          (fname, (tname, rpos, [(cname, (ls, cargs, rs, rhs, eqn))]))::rec_fns
skalberg@15531
    78
      | SOME (_, rpos', eqns) =>
wenzelm@17184
    79
          if AList.defined (op =) eqns cname then
haftmann@25557
    80
            primrec_error "constructor already occurred as pattern"
berghofe@5178
    81
          else if rpos <> rpos' then
haftmann@25557
    82
            primrec_error "position of recursive argument inconsistent"
berghofe@5178
    83
          else
haftmann@25557
    84
            AList.update (op =)
haftmann@25557
    85
              (fname, (tname, rpos, (cname, (ls, cargs, rs, rhs, eqn))::eqns))
haftmann@17314
    86
              rec_fns)
haftmann@25557
    87
  end handle PrimrecError (msg, NONE) => primrec_error_eqn msg spec;
berghofe@5178
    88
haftmann@25557
    89
fun process_fun descr eqns (i, fname) (fnames, fnss) =
berghofe@5178
    90
  let
haftmann@25557
    91
    val (_, (tname, _, constrs)) = nth descr i;
berghofe@5178
    92
berghofe@5178
    93
    (* substitute "fname ls x rs" by "y ls rs" for (x, (_, y)) in subs *)
berghofe@5178
    94
haftmann@21064
    95
    fun subst [] t fs = (t, fs)
haftmann@21064
    96
      | subst subs (Abs (a, T, t)) fs =
haftmann@21064
    97
          fs
haftmann@21064
    98
          |> subst subs t
haftmann@21064
    99
          |-> (fn t' => pair (Abs (a, T, t')))
haftmann@21064
   100
      | subst subs (t as (_ $ _)) fs =
haftmann@21064
   101
          let
haftmann@21064
   102
            val (f, ts) = strip_comb t;
berghofe@5178
   103
          in
haftmann@25557
   104
            if is_Free f
haftmann@25557
   105
              andalso member (fn ((v, _), (w, _)) => v = w) eqns (dest_Free f) then
berghofe@5178
   106
              let
haftmann@25557
   107
                val (fname', _) = dest_Free f;
haftmann@25557
   108
                val (_, rpos, _) = the (AList.lookup (op =) eqns fname');
haftmann@27301
   109
                val (ls, rs) = chop rpos ts
haftmann@27301
   110
                val (x', rs') = case rs
haftmann@27301
   111
                 of x' :: rs => (x', rs)
haftmann@27301
   112
                  | [] => primrec_error ("not enough arguments in recursive application\n"
haftmann@27301
   113
                      ^ "of function " ^ quote fname' ^ " on rhs");
haftmann@27301
   114
                val (x, xs) = strip_comb x';
haftmann@21064
   115
              in case AList.lookup (op =) subs x
haftmann@21064
   116
               of NONE =>
haftmann@21064
   117
                    fs
haftmann@21064
   118
                    |> fold_map (subst subs) ts
haftmann@21064
   119
                    |-> (fn ts' => pair (list_comb (f, ts')))
haftmann@21064
   120
                | SOME (i', y) =>
haftmann@21064
   121
                    fs
haftmann@27301
   122
                    |> fold_map (subst subs) (xs @ ls @ rs')
haftmann@25557
   123
                    ||> process_fun descr eqns (i', fname')
haftmann@21064
   124
                    |-> (fn ts' => pair (list_comb (y, ts')))
berghofe@5178
   125
              end
berghofe@5178
   126
            else
haftmann@21064
   127
              fs
haftmann@21064
   128
              |> fold_map (subst subs) (f :: ts)
haftmann@21064
   129
              |-> (fn (f'::ts') => pair (list_comb (f', ts')))
berghofe@5178
   130
          end
haftmann@21064
   131
      | subst _ t fs = (t, fs);
berghofe@5178
   132
berghofe@5178
   133
    (* translate rec equations into function arguments suitable for rec comb *)
berghofe@5178
   134
haftmann@25557
   135
    fun trans eqns (cname, cargs) (fnames', fnss', fns) =
wenzelm@17184
   136
      (case AList.lookup (op =) eqns cname of
skalberg@15531
   137
          NONE => (warning ("No equation for constructor " ^ quote cname ^
wenzelm@6427
   138
            "\nin definition of function " ^ quote fname);
haftmann@25557
   139
              (fnames', fnss', (Const ("HOL.undefined", dummyT))::fns))
skalberg@15531
   140
        | SOME (ls, cargs', rs, rhs, eq) =>
berghofe@5178
   141
            let
haftmann@21064
   142
              val recs = filter (is_rec_type o snd) (cargs' ~~ cargs);
berghofe@5178
   143
              val rargs = map fst recs;
wenzelm@22692
   144
              val subs = map (rpair dummyT o fst)
haftmann@20176
   145
                (rev (rename_wrt_term rhs rargs));
haftmann@27301
   146
              val (rhs', (fnames'', fnss'')) = subst (map2 (fn (x, y) => fn z =>
haftmann@27301
   147
                (Free x, (body_index y, Free z))) recs subs) rhs (fnames', fnss')
haftmann@25557
   148
                  handle PrimrecError (s, NONE) => primrec_error_eqn s eq
haftmann@25557
   149
            in (fnames'', fnss'',
haftmann@20176
   150
                (list_abs_free (cargs' @ subs @ ls @ rs, rhs'))::fns)
berghofe@5178
   151
            end)
berghofe@5178
   152
haftmann@25557
   153
  in (case AList.lookup (op =) fnames i of
skalberg@15531
   154
      NONE =>
haftmann@25557
   155
        if exists (fn (_, v) => fname = v) fnames then
haftmann@25557
   156
          primrec_error ("inconsistent functions for datatype " ^ quote tname)
berghofe@5178
   157
        else
berghofe@5178
   158
          let
haftmann@25557
   159
            val (_, _, eqns) = the (AList.lookup (op =) eqns fname);
haftmann@25557
   160
            val (fnames', fnss', fns) = fold_rev (trans eqns) constrs
haftmann@25557
   161
              ((i, fname)::fnames, fnss, [])
berghofe@5178
   162
          in
haftmann@25557
   163
            (fnames', (i, (fname, #1 (snd (hd eqns)), fns))::fnss')
berghofe@5178
   164
          end
haftmann@25557
   165
    | SOME fname' =>
haftmann@25557
   166
        if fname = fname' then (fnames, fnss)
haftmann@25557
   167
        else primrec_error ("inconsistent functions for datatype " ^ quote tname))
berghofe@5178
   168
  end;
berghofe@5178
   169
wenzelm@6359
   170
berghofe@5178
   171
(* prepare functions needed for definitions *)
berghofe@5178
   172
haftmann@21064
   173
fun get_fns fns ((i : int, (tname, _, constrs)), rec_name) (fs, defs) =
wenzelm@17184
   174
  case AList.lookup (op =) fns i of
skalberg@15531
   175
     NONE =>
berghofe@5178
   176
       let
haftmann@22480
   177
         val dummy_fns = map (fn (_, cargs) => Const ("HOL.undefined",
skalberg@15570
   178
           replicate ((length cargs) + (length (List.filter is_rec_type cargs)))
berghofe@5178
   179
             dummyT ---> HOLogic.unitT)) constrs;
wenzelm@6427
   180
         val _ = warning ("No function definition for datatype " ^ quote tname)
berghofe@5178
   181
       in
berghofe@5178
   182
         (dummy_fns @ fs, defs)
berghofe@5178
   183
       end
haftmann@21064
   184
   | SOME (fname, ls, fs') => (fs' @ fs, (fname, ls, rec_name, tname) :: defs);
berghofe@5178
   185
wenzelm@6359
   186
berghofe@5178
   187
(* make definition *)
berghofe@5178
   188
haftmann@25557
   189
fun make_def ctxt fixes fs (fname, ls, rec_name, tname) =
berghofe@5178
   190
  let
haftmann@25557
   191
    val raw_rhs = fold_rev (fn T => fn t => Abs ("", T, t))
wenzelm@28083
   192
                    (map snd ls @ [dummyT])
haftmann@20176
   193
                    (list_comb (Const (rec_name, dummyT),
wenzelm@28083
   194
                                fs @ map Bound (0 :: (length ls downto 1))))
haftmann@25557
   195
    val def_name = Thm.def_name (Sign.base_name fname);
haftmann@25557
   196
    val rhs = singleton (Syntax.check_terms ctxt) raw_rhs;
wenzelm@28083
   197
    val SOME var = get_first (fn ((b, _), mx) =>
wenzelm@28083
   198
      if Name.name_of b = fname then SOME (b, mx) else NONE) fixes;
wenzelm@28083
   199
  in (var, ((Name.binding def_name, []), rhs)) end;
berghofe@5178
   200
wenzelm@6359
   201
berghofe@5178
   202
(* find datatypes which contain all datatypes in tnames' *)
berghofe@5178
   203
berghofe@5178
   204
fun find_dts (dt_info : datatype_info Symtab.table) _ [] = []
berghofe@5178
   205
  | find_dts dt_info tnames' (tname::tnames) =
wenzelm@17412
   206
      (case Symtab.lookup dt_info tname of
haftmann@25557
   207
          NONE => primrec_error (quote tname ^ " is not a datatype")
skalberg@15531
   208
        | SOME dt =>
berghofe@5178
   209
            if tnames' subset (map (#1 o snd) (#descr dt)) then
berghofe@5178
   210
              (tname, dt)::(find_dts dt_info tnames' tnames)
berghofe@5178
   211
            else find_dts dt_info tnames' tnames);
berghofe@5178
   212
haftmann@25557
   213
haftmann@25557
   214
(* primrec definition *)
haftmann@25557
   215
haftmann@20841
   216
local
haftmann@20841
   217
haftmann@25557
   218
fun prepare_spec prep_spec ctxt raw_fixes raw_spec =
haftmann@25557
   219
  let
haftmann@25559
   220
    val ((fixes, spec), _) = prep_spec
haftmann@25559
   221
      raw_fixes (map (single o apsnd single) raw_spec) ctxt
haftmann@25559
   222
  in (fixes, map (apsnd the_single) spec) end;
haftmann@25557
   223
haftmann@25566
   224
fun prove_spec ctxt names rec_rewrites defs =
haftmann@25557
   225
  let
haftmann@25557
   226
    val rewrites = map mk_meta_eq rec_rewrites @ map (snd o snd) defs;
haftmann@25557
   227
    fun tac _ = EVERY [rewrite_goals_tac rewrites, rtac refl 1];
haftmann@25566
   228
    val _ = message ("Proving equations for primrec function(s) " ^ commas_quote names);
wenzelm@28083
   229
  in map (fn (a, t) => (a, [Goal.prove ctxt [] [] t tac])) end;
haftmann@25557
   230
wenzelm@26129
   231
fun gen_primrec set_group prep_spec raw_fixes raw_spec lthy =
berghofe@5178
   232
  let
haftmann@25557
   233
    val (fixes, spec) = prepare_spec prep_spec lthy raw_fixes raw_spec;
haftmann@25559
   234
    val eqns = fold_rev (process_eqn (fn v => Variable.is_fixed lthy v
wenzelm@28083
   235
      orelse exists (fn ((w, _), _) => v = Name.name_of w) fixes) o snd) spec [];
haftmann@25557
   236
    val tnames = distinct (op =) (map (#1 o snd) eqns);
wenzelm@28083
   237
    val dts = find_dts (DatatypePackage.get_datatypes (ProofContext.theory_of lthy)) tnames tnames;
haftmann@25557
   238
    val main_fns = map (fn (tname, {index, ...}) =>
haftmann@25557
   239
      (index, (fst o the o find_first (fn (_, x) => #1 x = tname)) eqns)) dts;
wenzelm@22692
   240
    val {descr, rec_names, rec_rewrites, ...} =
haftmann@25557
   241
      if null dts then primrec_error
haftmann@25557
   242
        ("datatypes " ^ commas_quote tnames ^ "\nare not mutually recursive")
haftmann@18362
   243
      else snd (hd dts);
haftmann@25557
   244
    val (fnames, fnss) = fold_rev (process_fun descr eqns) main_fns ([], []);
haftmann@21064
   245
    val (fs, defs) = fold_rev (get_fns fnss) (descr ~~ rec_names) ([], []);
haftmann@25566
   246
    val names1 = map snd fnames;
haftmann@25566
   247
    val names2 = map fst eqns;
haftmann@25566
   248
    val _ = if gen_eq_set (op =) (names1, names2) then ()
haftmann@25566
   249
      else primrec_error ("functions " ^ commas_quote names2 ^
haftmann@25557
   250
        "\nare not mutually recursive");
haftmann@25557
   251
    val qualify = NameSpace.qualified
haftmann@25557
   252
      (space_implode "_" (map (Sign.base_name o #1) defs));
wenzelm@28083
   253
    val spec' = (map o apfst o apfst o Name.map_name) qualify spec;
haftmann@25570
   254
    val simp_atts = map (Attrib.internal o K)
haftmann@25570
   255
      [Simplifier.simp_add, RecfunCodegen.add NONE];
berghofe@8480
   256
  in
haftmann@25557
   257
    lthy
wenzelm@26129
   258
    |> set_group ? LocalTheory.set_group (serial_string ())
haftmann@25557
   259
    |> fold_map (LocalTheory.define Thm.definitionK o make_def lthy fixes fs) defs
haftmann@26556
   260
    |-> (fn defs => `(fn ctxt => prove_spec ctxt names1 rec_rewrites defs spec'))
haftmann@25557
   261
    |-> (fn simps => fold_map (LocalTheory.note Thm.theoremK) simps)
haftmann@25557
   262
    |-> (fn simps' => LocalTheory.note Thm.theoremK
wenzelm@28083
   263
          ((Name.binding (qualify "simps"), simp_atts), maps snd simps'))
haftmann@25604
   264
    |>> snd
haftmann@25557
   265
  end handle PrimrecError (msg, some_eqn) =>
haftmann@25557
   266
    error ("Primrec definition error:\n" ^ msg ^ (case some_eqn
haftmann@25557
   267
     of SOME eqn => "\nin\n" ^ quote (Syntax.string_of_term lthy eqn)
haftmann@25557
   268
      | NONE => ""));
haftmann@20841
   269
haftmann@20841
   270
in
haftmann@20841
   271
wenzelm@26129
   272
val add_primrec = gen_primrec false Specification.check_specification;
wenzelm@26129
   273
val add_primrec_cmd = gen_primrec true Specification.read_specification;
haftmann@20841
   274
wenzelm@22692
   275
end;
wenzelm@19688
   276
berghofe@26679
   277
fun add_primrec_global fixes specs thy =
berghofe@26679
   278
  let
berghofe@26679
   279
    val lthy = TheoryTarget.init NONE thy;
berghofe@26679
   280
    val (simps, lthy') = add_primrec fixes specs lthy;
berghofe@26679
   281
    val simps' = ProofContext.export lthy' lthy simps;
berghofe@26679
   282
  in (simps', ProofContext.theory_of (LocalTheory.exit lthy')) end;
berghofe@26679
   283
berghofe@26679
   284
fun add_primrec_overloaded ops fixes specs thy =
berghofe@26679
   285
  let
berghofe@26679
   286
    val lthy = TheoryTarget.overloading ops thy;
berghofe@26679
   287
    val (simps, lthy') = add_primrec fixes specs lthy;
berghofe@26679
   288
    val simps' = ProofContext.export lthy' lthy simps;
berghofe@26679
   289
  in (simps', ProofContext.theory_of (LocalTheory.exit lthy')) end;
berghofe@26679
   290
berghofe@5178
   291
wenzelm@6359
   292
(* outer syntax *)
wenzelm@6359
   293
wenzelm@17057
   294
local structure P = OuterParse and K = OuterKeyword in
wenzelm@6359
   295
wenzelm@19688
   296
val opt_unchecked_name =
wenzelm@19688
   297
  Scan.optional (P.$$$ "(" |-- P.!!!
wenzelm@19688
   298
    (((P.$$$ "unchecked" >> K true) -- Scan.optional P.name "" ||
wenzelm@19688
   299
      P.name >> pair false) --| P.$$$ ")")) (false, "");
wenzelm@19688
   300
haftmann@25557
   301
val old_primrec_decl =
wenzelm@28083
   302
  opt_unchecked_name -- Scan.repeat1 ((SpecParse.opt_thm_name ":" >> apfst Name.name_of) -- P.prop);
wenzelm@6359
   303
haftmann@25557
   304
fun pipe_error t = P.!!! (Scan.fail_with (K
haftmann@25557
   305
  (cat_lines ["Equations must be separated by " ^ quote "|", quote t])));
haftmann@25557
   306
haftmann@25557
   307
val statement = SpecParse.opt_thm_name ":" -- P.prop --| Scan.ahead
haftmann@25557
   308
  ((P.term :-- pipe_error) || Scan.succeed ("",""));
haftmann@25557
   309
haftmann@25557
   310
val statements = P.enum1 "|" statement;
haftmann@25557
   311
haftmann@25557
   312
val primrec_decl = P.opt_target -- P.fixes --| P.$$$ "where" -- statements;
haftmann@25557
   313
wenzelm@24867
   314
val _ =
wenzelm@6723
   315
  OuterSyntax.command "primrec" "define primitive recursive functions on datatypes" K.thy_decl
haftmann@25557
   316
    ((primrec_decl >> (fn ((opt_target, raw_fixes), raw_spec) =>
haftmann@25557
   317
      Toplevel.local_theory opt_target (add_primrec_cmd raw_fixes raw_spec #> snd)))
haftmann@25557
   318
    || (old_primrec_decl >> (fn ((unchecked, alt_name), eqns) =>
haftmann@20176
   319
      Toplevel.theory (snd o
haftmann@25557
   320
        (if unchecked then OldPrimrecPackage.add_primrec_unchecked else OldPrimrecPackage.add_primrec) alt_name
haftmann@25557
   321
          (map P.triple_swap eqns)))));
wenzelm@6359
   322
berghofe@5178
   323
end;
wenzelm@6384
   324
wenzelm@6384
   325
end;