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