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