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