src/HOL/Tools/primrec_package.ML
author haftmann
Fri Oct 20 10:44:47 2006 +0200 (2006-10-20)
changeset 21064 9684dd7c81b5
parent 21022 3634641f9405
child 22101 6d13239d5f52
permissions -rw-r--r--
fold cleanup
     1 (*  Title:      HOL/Tools/primrec_package.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer, TU Muenchen and Norbert Voelker, FernUni Hagen
     4 
     5 Package for defining functions on datatypes by primitive recursion.
     6 *)
     7 
     8 signature PRIMREC_PACKAGE =
     9 sig
    10   val quiet_mode: bool ref
    11   val add_primrec: string -> ((bstring * string) * Attrib.src list) list
    12     -> theory -> thm list * theory
    13   val add_primrec_unchecked: string -> ((bstring * string) * Attrib.src list) list
    14     -> theory -> thm list * theory
    15   val add_primrec_i: string -> ((bstring * term) * attribute list) list
    16     -> theory -> thm list * theory
    17   val add_primrec_unchecked_i: string -> ((bstring * term) * attribute list) list
    18     -> theory -> thm list * theory
    19   val gen_primrec: ((bstring * attribute list) * thm list -> theory -> (bstring * thm list) * theory)
    20     -> ((bstring * attribute list) * term -> theory -> (bstring * thm) * theory)
    21     -> string -> ((bstring * attribute list) * term) list
    22     -> theory -> thm list * theory;
    23 end;
    24 
    25 structure PrimrecPackage : PRIMREC_PACKAGE =
    26 struct
    27 
    28 open DatatypeAux;
    29 
    30 exception RecError of string;
    31 
    32 fun primrec_err s = error ("Primrec definition error:\n" ^ s);
    33 fun primrec_eq_err thy s eq =
    34   primrec_err (s ^ "\nin\n" ^ quote (Sign.string_of_term thy eq));
    35 
    36 
    37 (* messages *)
    38 
    39 val quiet_mode = ref false;
    40 fun message s = if ! quiet_mode then () else writeln s;
    41 
    42 
    43 (* preprocessing of equations *)
    44 
    45 fun process_eqn thy eq rec_fns = 
    46   let
    47     val (lhs, rhs) = 
    48       if null (term_vars eq) then
    49         HOLogic.dest_eq (HOLogic.dest_Trueprop eq)
    50         handle TERM _ => raise RecError "not a proper equation"
    51       else raise RecError "illegal schematic variable(s)";
    52 
    53     val (recfun, args) = strip_comb lhs;
    54     val fnameT = dest_Const recfun handle TERM _ => 
    55       raise RecError "function is not declared as constant in theory";
    56 
    57     val (ls', rest)  = take_prefix is_Free args;
    58     val (middle, rs') = take_suffix is_Free rest;
    59     val rpos = length ls';
    60 
    61     val (constr, cargs') = if null middle then raise RecError "constructor missing"
    62       else strip_comb (hd middle);
    63     val (cname, T) = dest_Const constr
    64       handle TERM _ => raise RecError "ill-formed constructor";
    65     val (tname, _) = dest_Type (body_type T) handle TYPE _ =>
    66       raise RecError "cannot determine datatype associated with function"
    67 
    68     val (ls, cargs, rs) =
    69       (map dest_Free ls', map dest_Free cargs', map dest_Free rs')
    70       handle TERM _ => raise RecError "illegal argument in pattern";
    71     val lfrees = ls @ rs @ cargs;
    72 
    73     fun check_vars _ [] = ()
    74       | check_vars s vars = raise RecError (s ^ commas_quote (map fst vars))
    75   in
    76     if length middle > 1 then 
    77       raise RecError "more than one non-variable in pattern"
    78     else
    79      (check_vars "repeated variable names in pattern: " (duplicates (op =) lfrees);
    80       check_vars "extra variables on rhs: "
    81         (map dest_Free (term_frees rhs) \\ lfrees);
    82       case AList.lookup (op =) rec_fns fnameT of
    83         NONE =>
    84           (fnameT, (tname, rpos, [(cname, (ls, cargs, rs, rhs, eq))]))::rec_fns
    85       | SOME (_, rpos', eqns) =>
    86           if AList.defined (op =) eqns cname then
    87             raise RecError "constructor already occurred as pattern"
    88           else if rpos <> rpos' then
    89             raise RecError "position of recursive argument inconsistent"
    90           else
    91             AList.update (op =) (fnameT, (tname, rpos, (cname, (ls, cargs, rs, rhs, eq))::eqns))
    92               rec_fns)
    93   end
    94   handle RecError s => primrec_eq_err thy s eq;
    95 
    96 fun process_fun thy descr rec_eqns (i, fnameT as (fname, _)) (fnameTs, fnss) =
    97   let
    98     val (_, (tname, _, constrs)) = List.nth (descr, i);
    99 
   100     (* substitute "fname ls x rs" by "y ls rs" for (x, (_, y)) in subs *)
   101 
   102     fun subst [] t fs = (t, fs)
   103       | subst subs (Abs (a, T, t)) fs =
   104           fs
   105           |> subst subs t
   106           |-> (fn t' => pair (Abs (a, T, t')))
   107       | subst subs (t as (_ $ _)) fs =
   108           let
   109             val (f, ts) = strip_comb t;
   110           in
   111             if is_Const f andalso dest_Const f mem map fst rec_eqns then
   112               let
   113                 val fnameT' as (fname', _) = dest_Const f;
   114                 val (_, rpos, _) = the (AList.lookup (op =) rec_eqns fnameT');
   115                 val ls = Library.take (rpos, ts);
   116                 val rest = Library.drop (rpos, ts);
   117                 val (x', rs) = (hd rest, tl rest)
   118                   handle Empty => raise RecError ("not enough arguments\
   119                    \ in recursive application\nof function " ^ quote fname' ^ " on rhs");
   120                 val (x, xs) = strip_comb x'
   121               in case AList.lookup (op =) subs x
   122                of NONE =>
   123                     fs
   124                     |> fold_map (subst subs) ts
   125                     |-> (fn ts' => pair (list_comb (f, ts')))
   126                 | SOME (i', y) =>
   127                     fs
   128                     |> fold_map (subst subs) (xs @ ls @ rs)
   129                     ||> process_fun thy descr rec_eqns (i', fnameT')
   130                     |-> (fn ts' => pair (list_comb (y, ts')))
   131               end
   132             else
   133               fs
   134               |> fold_map (subst subs) (f :: ts)
   135               |-> (fn (f'::ts') => pair (list_comb (f', ts')))
   136           end
   137       | subst _ t fs = (t, fs);
   138 
   139     (* translate rec equations into function arguments suitable for rec comb *)
   140 
   141     fun trans eqns (cname, cargs) (fnameTs', fnss', fns) =
   142       (case AList.lookup (op =) eqns cname of
   143           NONE => (warning ("No equation for constructor " ^ quote cname ^
   144             "\nin definition of function " ^ quote fname);
   145               (fnameTs', fnss', (Const ("arbitrary", dummyT))::fns))
   146         | SOME (ls, cargs', rs, rhs, eq) =>
   147             let
   148               val recs = filter (is_rec_type o snd) (cargs' ~~ cargs);
   149               val rargs = map fst recs;
   150               val subs = map (rpair dummyT o fst) 
   151                 (rev (rename_wrt_term rhs rargs));
   152               val (rhs', (fnameTs'', fnss'')) = 
   153                   (subst (map (fn ((x, y), z) =>
   154                                (Free x, (body_index y, Free z)))
   155                           (recs ~~ subs)) rhs (fnameTs', fnss'))
   156                   handle RecError s => primrec_eq_err thy s eq
   157             in (fnameTs'', fnss'', 
   158                 (list_abs_free (cargs' @ subs @ ls @ rs, rhs'))::fns)
   159             end)
   160 
   161   in (case AList.lookup (op =) fnameTs i of
   162       NONE =>
   163         if exists (equal fnameT o snd) fnameTs then
   164           raise RecError ("inconsistent functions for datatype " ^ quote tname)
   165         else
   166           let
   167             val (_, _, eqns) = the (AList.lookup (op =) rec_eqns fnameT);
   168             val (fnameTs', fnss', fns) = fold_rev (trans eqns) constrs
   169               ((i, fnameT)::fnameTs, fnss, []) 
   170           in
   171             (fnameTs', (i, (fname, #1 (snd (hd eqns)), fns))::fnss')
   172           end
   173     | SOME fnameT' =>
   174         if fnameT = fnameT' then (fnameTs, fnss)
   175         else raise RecError ("inconsistent functions for datatype " ^ quote tname))
   176   end;
   177 
   178 
   179 (* prepare functions needed for definitions *)
   180 
   181 fun get_fns fns ((i : int, (tname, _, constrs)), rec_name) (fs, defs) =
   182   case AList.lookup (op =) fns i of
   183      NONE =>
   184        let
   185          val dummy_fns = map (fn (_, cargs) => Const ("arbitrary",
   186            replicate ((length cargs) + (length (List.filter is_rec_type cargs)))
   187              dummyT ---> HOLogic.unitT)) constrs;
   188          val _ = warning ("No function definition for datatype " ^ quote tname)
   189        in
   190          (dummy_fns @ fs, defs)
   191        end
   192    | SOME (fname, ls, fs') => (fs' @ fs, (fname, ls, rec_name, tname) :: defs);
   193 
   194 
   195 (* make definition *)
   196 
   197 fun make_def thy fs (fname, ls, rec_name, tname) =
   198   let
   199     val rhs = fold_rev (fn T => fn t => Abs ("", T, t))
   200                     ((map snd ls) @ [dummyT])
   201                     (list_comb (Const (rec_name, dummyT),
   202                                 fs @ map Bound (0 ::(length ls downto 1))))
   203     val defpair = (Sign.base_name fname ^ "_" ^ Sign.base_name tname ^ "_def",
   204                    Logic.mk_equals (Const (fname, dummyT), rhs))
   205   in Theory.inferT_axm thy defpair end;
   206 
   207 
   208 (* find datatypes which contain all datatypes in tnames' *)
   209 
   210 fun find_dts (dt_info : datatype_info Symtab.table) _ [] = []
   211   | find_dts dt_info tnames' (tname::tnames) =
   212       (case Symtab.lookup dt_info tname of
   213           NONE => primrec_err (quote tname ^ " is not a datatype")
   214         | SOME dt =>
   215             if tnames' subset (map (#1 o snd) (#descr dt)) then
   216               (tname, dt)::(find_dts dt_info tnames' tnames)
   217             else find_dts dt_info tnames' tnames);
   218 
   219 fun prepare_induct ({descr, induction, ...}: datatype_info) rec_eqns =
   220   let
   221     fun constrs_of (_, (_, _, cs)) =
   222       map (fn (cname:string, (_, cargs, _, _, _)) => (cname, map fst cargs)) cs;
   223     val params_of = these o AList.lookup (op =) (List.concat (map constrs_of rec_eqns));
   224   in
   225     induction
   226     |> RuleCases.rename_params (map params_of (List.concat (map (map #1 o #3 o #2) descr)))
   227     |> RuleCases.save induction
   228   end;
   229 
   230 local
   231 
   232 fun gen_primrec_i note def alt_name eqns_atts thy =
   233   let
   234     val (eqns, atts) = split_list eqns_atts;
   235     val dt_info = DatatypePackage.get_datatypes thy;
   236     val rec_eqns = fold_rev (process_eqn thy o snd) eqns [] ;
   237     val tnames = distinct (op =) (map (#1 o snd) rec_eqns);
   238     val dts = find_dts dt_info tnames tnames;
   239     val main_fns = 
   240       map (fn (tname, {index, ...}) =>
   241         (index, 
   242           (fst o the o find_first (fn f => (#1 o snd) f = tname)) rec_eqns))
   243       dts;
   244     val {descr, rec_names, rec_rewrites, ...} = 
   245       if null dts then
   246         primrec_err ("datatypes " ^ commas_quote tnames ^ "\nare not mutually recursive")
   247       else snd (hd dts);
   248     val (fnameTs, fnss) =
   249       fold_rev (process_fun thy descr rec_eqns) main_fns ([], []);
   250     val (fs, defs) = fold_rev (get_fns fnss) (descr ~~ rec_names) ([], []);
   251     val defs' = map (make_def thy fs) defs;
   252     val nameTs1 = map snd fnameTs;
   253     val nameTs2 = map fst rec_eqns;
   254     val _ = if gen_eq_set (op =) (nameTs1, nameTs2) then ()
   255             else primrec_err ("functions " ^ commas_quote (map fst nameTs2) ^
   256               "\nare not mutually recursive");
   257     val primrec_name =
   258       if alt_name = "" then (space_implode "_" (map (Sign.base_name o #1) defs)) else alt_name;
   259     val (defs_thms', thy') =
   260       thy
   261       |> Theory.add_path primrec_name
   262       |> fold_map def (map (fn (name, t) => ((name, []), t)) defs');
   263     val rewrites = (map mk_meta_eq rec_rewrites) @ map snd defs_thms';
   264     val _ = message ("Proving equations for primrec function(s) " ^
   265       commas_quote (map fst nameTs1) ^ " ...");
   266     val simps = map (fn (_, t) => Goal.prove_global thy' [] [] t
   267         (fn _ => EVERY [rewrite_goals_tac rewrites, rtac refl 1])) eqns;
   268     val (simps', thy'') =
   269       thy'
   270       |> fold_map note ((map fst eqns ~~ atts) ~~ map single simps);
   271     val simps'' = maps snd simps';
   272   in
   273     thy''
   274     |> note (("simps", [Simplifier.simp_add, RecfunCodegen.add NONE]), simps'')
   275     |> snd
   276     |> note (("induct", []), [prepare_induct (#2 (hd dts)) rec_eqns])
   277     |> snd
   278     |> Theory.parent_path
   279     |> pair simps''
   280   end;
   281 
   282 fun gen_primrec note def alt_name eqns thy =
   283   let
   284     val ((names, strings), srcss) = apfst split_list (split_list eqns);
   285     val atts = map (map (Attrib.attribute thy)) srcss;
   286     val eqn_ts = map (fn s => term_of (Thm.read_cterm thy (s, propT))
   287       handle ERROR msg => cat_error msg ("The error(s) above occurred for " ^ s)) strings;
   288     val rec_ts = map (fn eq => head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop eq)))
   289       handle TERM _ => primrec_eq_err thy "not a proper equation" eq) eqn_ts;
   290     val (_, eqn_ts') = OldInductivePackage.unify_consts thy rec_ts eqn_ts
   291   in
   292     gen_primrec_i note def alt_name (names ~~ eqn_ts' ~~ atts) thy
   293   end;
   294 
   295 fun thy_note ((name, atts), thms) =
   296   PureThy.add_thmss [((name, thms), atts)] #-> (fn [thms] => pair (name, thms));
   297 fun thy_def false ((name, atts), t) =
   298       PureThy.add_defs_i false [((name, t), atts)] #-> (fn [thm] => pair (name, thm))
   299   | thy_def true ((name, atts), t) =
   300       PureThy.add_defs_unchecked_i false [((name, t), atts)] #-> (fn [thm] => pair (name, thm));
   301 
   302 in
   303 
   304 val add_primrec = gen_primrec thy_note (thy_def false);
   305 val add_primrec_unchecked = gen_primrec thy_note (thy_def true);
   306 val add_primrec_i = gen_primrec_i thy_note (thy_def false);
   307 val add_primrec_unchecked_i = gen_primrec_i thy_note (thy_def true);
   308 fun gen_primrec note def alt_name specs =
   309   gen_primrec_i note def alt_name (map (fn ((name, t), atts) => ((name, atts), t)) specs);
   310 
   311 end; (*local*)
   312 
   313 
   314 (* outer syntax *)
   315 
   316 local structure P = OuterParse and K = OuterKeyword in
   317 
   318 val opt_unchecked_name =
   319   Scan.optional (P.$$$ "(" |-- P.!!!
   320     (((P.$$$ "unchecked" >> K true) -- Scan.optional P.name "" ||
   321       P.name >> pair false) --| P.$$$ ")")) (false, "");
   322 
   323 val primrec_decl =
   324   opt_unchecked_name -- Scan.repeat1 (P.opt_thm_name ":" -- P.prop);
   325 
   326 val primrecP =
   327   OuterSyntax.command "primrec" "define primitive recursive functions on datatypes" K.thy_decl
   328     (primrec_decl >> (fn ((unchecked, alt_name), eqns) =>
   329       Toplevel.theory (snd o
   330         (if unchecked then add_primrec_unchecked else add_primrec) alt_name
   331           (map P.triple_swap eqns))));
   332 
   333 val _ = OuterSyntax.add_parsers [primrecP];
   334 
   335 end;
   336 
   337 
   338 end;
   339