src/HOL/Nominal/nominal_primrec.ML
author berghofe
Fri May 18 11:12:03 2007 +0200 (2007-05-18)
changeset 23006 c46abff9a7a0
parent 22728 ecbbdf50df2f
child 23351 3702086a15a3
permissions -rw-r--r--
Fixed bug in subst causing primrec functions returning functions
to be rejected.
     1 (*  Title:      HOL/Nominal/nominal_primrec.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer, TU Muenchen and Norbert Voelker, FernUni Hagen
     4 
     5 Package for defining functions on nominal datatypes by primitive recursion.
     6 Taken from HOL/Tools/primrec_package.ML
     7 *)
     8 
     9 signature NOMINAL_PRIMREC =
    10 sig
    11   val quiet_mode: bool ref
    12   val add_primrec: string -> string list option -> string option ->
    13     ((bstring * string) * Attrib.src list) list -> theory -> Proof.state
    14   val add_primrec_unchecked: string -> string list option -> string option ->
    15     ((bstring * string) * Attrib.src list) list -> theory -> Proof.state
    16   val add_primrec_i: string -> term list option -> term option ->
    17     ((bstring * term) * attribute list) list -> theory -> Proof.state
    18   val add_primrec_unchecked_i: string -> term list option -> term option ->
    19     ((bstring * term) * attribute list) list -> theory -> Proof.state
    20 end;
    21 
    22 structure NominalPrimrec : NOMINAL_PRIMREC =
    23 struct
    24 
    25 open DatatypeAux;
    26 
    27 exception RecError of string;
    28 
    29 fun primrec_err s = error ("Nominal primrec definition error:\n" ^ s);
    30 fun primrec_eq_err thy s eq =
    31   primrec_err (s ^ "\nin\n" ^ quote (Sign.string_of_term thy eq));
    32 
    33 
    34 (* messages *)
    35 
    36 val quiet_mode = ref false;
    37 fun message s = if ! quiet_mode then () else writeln s;
    38 
    39 
    40 (* preprocessing of equations *)
    41 
    42 fun process_eqn thy eq rec_fns = 
    43   let
    44     val (lhs, rhs) = 
    45       if null (term_vars eq) then
    46         HOLogic.dest_eq (HOLogic.dest_Trueprop (Logic.strip_imp_concl eq))
    47         handle TERM _ => raise RecError "not a proper equation"
    48       else raise RecError "illegal schematic variable(s)";
    49 
    50     val (recfun, args) = strip_comb lhs;
    51     val fnameT = dest_Const recfun handle TERM _ => 
    52       raise RecError "function is not declared as constant in theory";
    53 
    54     val (ls', rest)  = take_prefix is_Free args;
    55     val (middle, rs') = take_suffix is_Free rest;
    56     val rpos = length ls';
    57 
    58     val (constr, cargs') = if null middle then raise RecError "constructor missing"
    59       else strip_comb (hd middle);
    60     val (cname, T) = dest_Const constr
    61       handle TERM _ => raise RecError "ill-formed constructor";
    62     val (tname, _) = dest_Type (body_type T) handle TYPE _ =>
    63       raise RecError "cannot determine datatype associated with function"
    64 
    65     val (ls, cargs, rs) =
    66       (map dest_Free ls', map dest_Free cargs', 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 thy s eq;
    92 
    93 val param_err = "Parameters must be the same for all recursive functions";
    94 
    95 fun process_fun thy descr rec_eqns (i, fnameT as (fname, _)) (fnameTs, fnss) =
    96   let
    97     val (_, (tname, _, constrs)) = List.nth (descr, i);
    98 
    99     (* substitute "fname ls x rs" by "y" for (x, (_, y)) in subs *)
   100 
   101     fun subst [] t fs = (t, fs)
   102       | subst subs (Abs (a, T, t)) fs =
   103           fs
   104           |> subst subs t
   105           |-> (fn t' => pair (Abs (a, T, t')))
   106       | subst subs (t as (_ $ _)) fs =
   107           let
   108             val (f, ts) = strip_comb t;
   109           in
   110             if is_Const f andalso dest_Const f mem map fst rec_eqns then
   111               let
   112                 val fnameT' as (fname', _) = dest_Const f;
   113                 val (_, rpos, eqns) = the (AList.lookup (op =) rec_eqns fnameT');
   114                 val ls = Library.take (rpos, ts);
   115                 val rest = Library.drop (rpos, ts);
   116                 val (x', rs) = (hd rest, tl rest)
   117                   handle Empty => raise RecError ("not enough arguments\
   118                    \ in recursive application\nof function " ^ quote fname' ^ " on rhs");
   119                 val rs' = (case eqns of
   120                     (_, (ls', _, rs', _, _)) :: _ =>
   121                       let val (rs1, rs2) = chop (length rs') rs
   122                       in
   123                         if ls = map Free ls' andalso rs1 = map Free rs' then rs2
   124                         else raise RecError param_err
   125                       end
   126                   | _ => raise RecError ("no equations for " ^ quote fname'));
   127                 val (x, xs) = strip_comb x'
   128               in case AList.lookup (op =) subs x
   129                of NONE =>
   130                     fs
   131                     |> fold_map (subst subs) ts
   132                     |-> (fn ts' => pair (list_comb (f, ts')))
   133                 | SOME (i', y) =>
   134                     fs
   135                     |> fold_map (subst subs) (xs @ rs')
   136                     ||> process_fun thy descr rec_eqns (i', fnameT')
   137                     |-> (fn ts' => pair (list_comb (y, ts')))
   138               end
   139             else
   140               fs
   141               |> fold_map (subst subs) (f :: ts)
   142               |-> (fn (f'::ts') => pair (list_comb (f', ts')))
   143           end
   144       | subst _ t fs = (t, fs);
   145 
   146     (* translate rec equations into function arguments suitable for rec comb *)
   147 
   148     fun trans eqns (cname, cargs) (fnameTs', fnss', fns) =
   149       (case AList.lookup (op =) eqns cname of
   150           NONE => (warning ("No equation for constructor " ^ quote cname ^
   151             "\nin definition of function " ^ quote fname);
   152               (fnameTs', fnss', (Const ("arbitrary", dummyT))::fns))
   153         | SOME (ls, cargs', rs, rhs, eq) =>
   154             let
   155               val recs = filter (is_rec_type o snd) (cargs' ~~ cargs);
   156               val rargs = map fst recs;
   157               val subs = map (rpair dummyT o fst) 
   158                 (rev (rename_wrt_term rhs rargs));
   159               val (rhs', (fnameTs'', fnss'')) = 
   160                   (subst (map (fn ((x, y), z) =>
   161                                (Free x, (body_index y, Free z)))
   162                           (recs ~~ subs)) rhs (fnameTs', fnss'))
   163                   handle RecError s => primrec_eq_err thy s eq
   164             in (fnameTs'', fnss'', 
   165                 (list_abs_free (cargs' @ subs, rhs'))::fns)
   166             end)
   167 
   168   in (case AList.lookup (op =) fnameTs i of
   169       NONE =>
   170         if exists (equal fnameT o snd) fnameTs then
   171           raise RecError ("inconsistent functions for datatype " ^ quote tname)
   172         else
   173           let
   174             val SOME (_, _, eqns as (_, (ls, _, rs, _, _)) :: _) =
   175               AList.lookup (op =) rec_eqns fnameT;
   176             val (fnameTs', fnss', fns) = fold_rev (trans eqns) constrs
   177               ((i, fnameT)::fnameTs, fnss, []) 
   178           in
   179             (fnameTs', (i, (fname, ls, rs, fns))::fnss')
   180           end
   181     | SOME fnameT' =>
   182         if fnameT = fnameT' then (fnameTs, fnss)
   183         else raise RecError ("inconsistent functions for datatype " ^ quote tname))
   184   end;
   185 
   186 
   187 (* prepare functions needed for definitions *)
   188 
   189 fun get_fns fns ((i : int, (tname, _, constrs)), rec_name) (fs, defs) =
   190   case AList.lookup (op =) fns i of
   191      NONE =>
   192        let
   193          val dummy_fns = map (fn (_, cargs) => Const ("arbitrary",
   194            replicate ((length cargs) + (length (List.filter is_rec_type cargs)))
   195              dummyT ---> HOLogic.unitT)) constrs;
   196          val _ = warning ("No function definition for datatype " ^ quote tname)
   197        in
   198          (dummy_fns @ fs, defs)
   199        end
   200    | SOME (fname, ls, rs, fs') => (fs' @ fs, (fname, ls, rs, rec_name, tname) :: defs);
   201 
   202 
   203 (* make definition *)
   204 
   205 fun make_def thy fs (fname, ls, rs, rec_name, tname) =
   206   let
   207     val used = map fst (fold Term.add_frees fs []);
   208     val x = (Name.variant used "x", dummyT);
   209     val frees = ls @ x :: rs;
   210     val rhs = list_abs_free (frees,
   211       list_comb (Const (rec_name, dummyT), fs @ [Free x]))
   212     val def_name = Sign.base_name fname ^ "_" ^ Sign.base_name tname ^ "_def";
   213     val def_prop as _ $ _ $ t =
   214       singleton (ProofContext.infer_types (ProofContext.init thy))
   215         (Logic.mk_equals (Const (fname, dummyT), rhs));
   216   in ((def_name, def_prop), subst_bounds (rev (map Free frees), strip_abs_body t)) end;
   217 
   218 
   219 (* find datatypes which contain all datatypes in tnames' *)
   220 
   221 fun find_dts (dt_info : NominalPackage.nominal_datatype_info Symtab.table) _ [] = []
   222   | find_dts dt_info tnames' (tname::tnames) =
   223       (case Symtab.lookup dt_info tname of
   224           NONE => primrec_err (quote tname ^ " is not a nominal datatype")
   225         | SOME dt =>
   226             if tnames' subset (map (#1 o snd) (#descr dt)) then
   227               (tname, dt)::(find_dts dt_info tnames' tnames)
   228             else find_dts dt_info tnames' tnames);
   229 
   230 fun common_prefix eq ([], _) = []
   231   | common_prefix eq (_, []) = []
   232   | common_prefix eq (x :: xs, y :: ys) =
   233       if eq (x, y) then x :: common_prefix eq (xs, ys) else [];
   234 
   235 local
   236 
   237 fun gen_primrec_i note def alt_name invs fctxt eqns_atts thy =
   238   let
   239     val (eqns, atts) = split_list eqns_atts;
   240     val dt_info = NominalPackage.get_nominal_datatypes thy;
   241     val rec_eqns = fold_rev (process_eqn thy o snd) eqns [];
   242     val lsrs :: lsrss = maps (fn (_, (_, _, eqns)) =>
   243       map (fn (_, (ls, _, rs, _, _)) => ls @ rs) eqns) rec_eqns
   244     val _ =
   245       (if forall (curry eq_set lsrs) lsrss andalso forall
   246          (fn (_, (_, _, (_, (ls, _, rs, _, _)) :: eqns)) =>
   247                forall (fn (_, (ls', _, rs', _, _)) =>
   248                  ls = ls' andalso rs = rs') eqns
   249            | _ => true) rec_eqns
   250        then () else primrec_err param_err);
   251     val tnames = distinct (op =) (map (#1 o snd) rec_eqns);
   252     val dts = find_dts dt_info tnames tnames;
   253     val main_fns = 
   254       map (fn (tname, {index, ...}) =>
   255         (index, 
   256           (fst o the o find_first (fn f => (#1 o snd) f = tname)) rec_eqns))
   257       dts;
   258     val {descr, rec_names, rec_rewrites, ...} = 
   259       if null dts then
   260         primrec_err ("datatypes " ^ commas_quote tnames ^ "\nare not mutually recursive")
   261       else snd (hd dts);
   262     val descr = map (fn (i, (tname, args, constrs)) => (i, (tname, args,
   263       map (fn (cname, cargs) => (cname, fold (fn (dTs, dT) => fn dTs' =>
   264         dTs' @ dTs @ [dT]) cargs [])) constrs))) descr;
   265     val (fnameTs, fnss) =
   266       fold_rev (process_fun thy descr rec_eqns) main_fns ([], []);
   267     val (fs, defs) = fold_rev (get_fns fnss) (descr ~~ rec_names) ([], []);
   268     val defs' = map (make_def thy fs) defs;
   269     val nameTs1 = map snd fnameTs;
   270     val nameTs2 = map fst rec_eqns;
   271     val _ = if gen_eq_set (op =) (nameTs1, nameTs2) then ()
   272             else primrec_err ("functions " ^ commas_quote (map fst nameTs2) ^
   273               "\nare not mutually recursive");
   274     val primrec_name =
   275       if alt_name = "" then (space_implode "_" (map (Sign.base_name o #1) defs)) else alt_name;
   276     val (defs_thms', thy') =
   277       thy
   278       |> Theory.add_path primrec_name
   279       |> fold_map def (map (fn ((name, t), _) => ((name, []), t)) defs');
   280     val cert = cterm_of thy';
   281 
   282     fun mk_idx eq =
   283       let
   284         val Const c = head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop
   285           (Logic.strip_imp_concl eq))));
   286         val SOME i = AList.lookup op = (map swap fnameTs) c;
   287         val SOME (_, _, constrs) = AList.lookup op = descr i;
   288         val SOME (_, _, eqns) = AList.lookup op = rec_eqns c;
   289         val SOME (cname, (_, cargs, _, _, _)) = find_first
   290           (fn (_, (_, _, _, _, eq')) => eq = eq') eqns
   291       in (i, find_index (fn (cname', _) => cname = cname') constrs, cargs) end;
   292 
   293     val rec_rewritess =
   294       unflat (map (fn (_, (_, _, constrs)) => constrs) descr) rec_rewrites;
   295     val fvars = rec_rewrites |> hd |> concl_of |> HOLogic.dest_Trueprop |>
   296       HOLogic.dest_eq |> fst |> strip_comb |> snd |> take_prefix is_Var |> fst;
   297     val (pvars, ctxtvars) = List.partition
   298       (equal HOLogic.boolT o body_type o snd)
   299       (fold_rev Term.add_vars (map Logic.strip_assums_concl
   300         (prems_of (hd rec_rewrites))) [] \\ map dest_Var fvars);
   301     val cfs = defs' |> hd |> snd |> strip_comb |> snd |>
   302       curry (List.take o swap) (length fvars) |> map cert;
   303     val invs' = (case invs of
   304         NONE => map (fn (i, _) =>
   305           let
   306             val SOME (_, T) = AList.lookup op = fnameTs i
   307             val (Ts, U) = strip_type T
   308           in
   309             Abs ("x", List.drop (Ts, length lsrs + 1) ---> U, HOLogic.true_const)
   310           end) descr
   311       | SOME invs' => invs');
   312     val inst = (map cert fvars ~~ cfs) @
   313       (map (cert o Var) pvars ~~ map cert invs') @
   314       (case ctxtvars of
   315          [ctxtvar] => [(cert (Var ctxtvar), cert (the_default HOLogic.unit fctxt))]
   316        | _ => []);
   317     val rec_rewrites' = map (fn (_, eq) =>
   318       let
   319         val (i, j, cargs) = mk_idx eq
   320         val th = nth (nth rec_rewritess i) j;
   321         val cargs' = th |> concl_of |> HOLogic.dest_Trueprop |>
   322           HOLogic.dest_eq |> fst |> strip_comb |> snd |> split_last |> snd |>
   323           strip_comb |> snd
   324       in (cargs, Logic.strip_imp_prems eq,
   325         Drule.cterm_instantiate (inst @
   326           (map (cterm_of thy') cargs' ~~ map (cterm_of thy' o Free) cargs)) th)
   327       end) eqns;
   328 
   329     val prems = foldr1 (common_prefix op aconv) (map (prems_of o #3) rec_rewrites');
   330     val cprems = map cert prems;
   331     val asms = map Thm.assume cprems;
   332     val premss = map (fn (cargs, eprems, eqn) =>
   333       map (fn t => list_all_free (cargs, Logic.list_implies (eprems, t)))
   334         (List.drop (prems_of eqn, length prems))) rec_rewrites';
   335     val cpremss = map (map cert) premss;
   336     val asmss = map (map Thm.assume) cpremss;
   337 
   338     fun mk_eqn ((cargs, eprems, eqn), asms') =
   339       let
   340         val ceprems = map cert eprems;
   341         val asms'' = map Thm.assume ceprems;
   342         val ccargs = map (cert o Free) cargs;
   343         val asms''' = map (fn th => implies_elim_list
   344           (forall_elim_list ccargs th) asms'') asms'
   345       in
   346         implies_elim_list eqn (asms @ asms''') |>
   347         implies_intr_list ceprems |>
   348         forall_intr_list ccargs
   349       end;
   350 
   351     val rule_prems = cprems @ flat cpremss;
   352     val rule = implies_intr_list rule_prems
   353       (foldr1 (uncurry Conjunction.intr) (map mk_eqn (rec_rewrites' ~~ asmss)));
   354 
   355     val goals = map (fn ((cargs, _, _), (_, eqn)) =>
   356       (list_all_free (cargs, eqn), [])) (rec_rewrites' ~~ eqns);
   357 
   358   in
   359     thy' |>
   360     ProofContext.init |>
   361     Proof.theorem_i NONE
   362       (fn thss => ProofContext.theory (fn thy =>
   363          let
   364            val simps = map standard (flat thss);
   365            val (simps', thy') =
   366              fold_map note ((map fst eqns ~~ atts) ~~ map single simps) thy;
   367            val simps'' = maps snd simps'
   368          in
   369            thy'
   370            |> note (("simps", [Simplifier.simp_add]), simps'')
   371            |> snd
   372            |> Theory.parent_path
   373          end))
   374       [goals] |>
   375     Proof.apply (Method.Basic (fn ctxt => Method.RAW_METHOD (fn ths =>
   376       rewrite_goals_tac (map snd defs_thms') THEN
   377       compose_tac (false, rule, length rule_prems) 1))) |>
   378     Seq.hd
   379   end;
   380 
   381 fun gen_primrec note def alt_name invs fctxt eqns thy =
   382   let
   383     fun readt T s = term_of (Thm.read_cterm thy (s, T));
   384     val ((names, strings), srcss) = apfst split_list (split_list eqns);
   385     val atts = map (map (Attrib.attribute thy)) srcss;
   386     val eqn_ts = map (fn s => readt propT s
   387       handle ERROR msg => cat_error msg ("The error(s) above occurred for " ^ s)) strings;
   388     val rec_ts = map (fn eq => head_of (fst (HOLogic.dest_eq
   389       (HOLogic.dest_Trueprop (Logic.strip_imp_concl eq))))
   390       handle TERM _ => primrec_eq_err thy "not a proper equation" eq) eqn_ts;
   391     val (_, eqn_ts') = OldInductivePackage.unify_consts thy rec_ts eqn_ts
   392   in
   393     gen_primrec_i note def alt_name
   394       (Option.map (map (readt dummyT)) invs)
   395       (Option.map (readt dummyT) fctxt)
   396       (names ~~ eqn_ts' ~~ atts) thy
   397   end;
   398 
   399 fun thy_note ((name, atts), thms) =
   400   PureThy.add_thmss [((name, thms), atts)] #-> (fn [thms] => pair (name, thms));
   401 fun thy_def false ((name, atts), t) =
   402       PureThy.add_defs_i false [((name, t), atts)] #-> (fn [thm] => pair (name, thm))
   403   | thy_def true ((name, atts), t) =
   404       PureThy.add_defs_unchecked_i false [((name, t), atts)] #-> (fn [thm] => pair (name, thm));
   405 
   406 in
   407 
   408 val add_primrec = gen_primrec thy_note (thy_def false);
   409 val add_primrec_unchecked = gen_primrec thy_note (thy_def true);
   410 val add_primrec_i = gen_primrec_i thy_note (thy_def false);
   411 val add_primrec_unchecked_i = gen_primrec_i thy_note (thy_def true);
   412 
   413 end; (*local*)
   414 
   415 
   416 (* outer syntax *)
   417 
   418 local structure P = OuterParse and K = OuterKeyword in
   419 
   420 val parser1 = P.$$$ "freshness_context" |-- P.$$$ ":" |-- (P.term >> SOME);
   421 val parser2 =
   422   P.$$$ "invariant" |-- P.$$$ ":" |--
   423     (Scan.repeat1 P.term >> SOME) -- Scan.optional parser1 NONE ||
   424   (parser1 >> pair NONE);
   425 val parser3 =
   426   P.name -- Scan.optional parser2 (NONE, NONE) ||
   427   (parser2 >> pair "");
   428 val parser4 =
   429   (P.$$$ "unchecked" >> K true) -- Scan.optional parser3 ("", (NONE, NONE)) ||
   430   (parser3 >> pair false);
   431 val options =
   432   Scan.optional (P.$$$ "(" |-- P.!!!
   433     (parser4 --| P.$$$ ")")) (false, ("", (NONE, NONE)));
   434 
   435 val primrec_decl =
   436   options -- Scan.repeat1 (SpecParse.opt_thm_name ":" -- P.prop);
   437 
   438 val primrecP =
   439   OuterSyntax.command "nominal_primrec" "define primitive recursive functions on nominal datatypes" K.thy_goal
   440     (primrec_decl >> (fn ((unchecked, (alt_name, (invs, fctxt))), eqns) =>
   441       Toplevel.print o Toplevel.theory_to_proof
   442         ((if unchecked then add_primrec_unchecked else add_primrec) alt_name invs fctxt
   443           (map P.triple_swap eqns))));
   444 
   445 val _ = OuterSyntax.add_parsers [primrecP];
   446 val _ = OuterSyntax.add_keywords ["invariant", "freshness_context"];
   447 
   448 end;
   449 
   450 
   451 end;
   452