src/HOL/Nominal/nominal_primrec.ML
author wenzelm
Sun Apr 15 14:31:49 2007 +0200 (2007-04-15)
changeset 22692 1e057a3f087d
parent 22434 081a62852313
child 22709 9ab51bac6287
permissions -rw-r--r--
proper ProofContext.infer_types;
     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 _ = (case eqns of
   120                     (_, (ls', _, rs', _, _)) :: _ =>
   121                       if ls = map Free ls' andalso rs = map Free rs' then ()
   122                       else raise RecError param_err
   123                   | _ => ());
   124                 val (x, xs) = strip_comb x'
   125               in case AList.lookup (op =) subs x
   126                of NONE =>
   127                     fs
   128                     |> fold_map (subst subs) ts
   129                     |-> (fn ts' => pair (list_comb (f, ts')))
   130                 | SOME (i', y) =>
   131                     fs
   132                     |> fold_map (subst subs) xs
   133                     ||> process_fun thy descr rec_eqns (i', fnameT')
   134                     |-> (fn ts' => pair (list_comb (y, ts')))
   135               end
   136             else
   137               fs
   138               |> fold_map (subst subs) (f :: ts)
   139               |-> (fn (f'::ts') => pair (list_comb (f', ts')))
   140           end
   141       | subst _ t fs = (t, fs);
   142 
   143     (* translate rec equations into function arguments suitable for rec comb *)
   144 
   145     fun trans eqns (cname, cargs) (fnameTs', fnss', fns) =
   146       (case AList.lookup (op =) eqns cname of
   147           NONE => (warning ("No equation for constructor " ^ quote cname ^
   148             "\nin definition of function " ^ quote fname);
   149               (fnameTs', fnss', (Const ("arbitrary", dummyT))::fns))
   150         | SOME (ls, cargs', rs, rhs, eq) =>
   151             let
   152               val recs = filter (is_rec_type o snd) (cargs' ~~ cargs);
   153               val rargs = map fst recs;
   154               val subs = map (rpair dummyT o fst) 
   155                 (rev (rename_wrt_term rhs rargs));
   156               val (rhs', (fnameTs'', fnss'')) = 
   157                   (subst (map (fn ((x, y), z) =>
   158                                (Free x, (body_index y, Free z)))
   159                           (recs ~~ subs)) rhs (fnameTs', fnss'))
   160                   handle RecError s => primrec_eq_err thy s eq
   161             in (fnameTs'', fnss'', 
   162                 (list_abs_free (cargs' @ subs, rhs'))::fns)
   163             end)
   164 
   165   in (case AList.lookup (op =) fnameTs i of
   166       NONE =>
   167         if exists (equal fnameT o snd) fnameTs then
   168           raise RecError ("inconsistent functions for datatype " ^ quote tname)
   169         else
   170           let
   171             val SOME (_, _, eqns as (_, (ls, _, rs, _, _)) :: _) =
   172               AList.lookup (op =) rec_eqns fnameT;
   173             val (fnameTs', fnss', fns) = fold_rev (trans eqns) constrs
   174               ((i, fnameT)::fnameTs, fnss, []) 
   175           in
   176             (fnameTs', (i, (fname, ls, rs, fns))::fnss')
   177           end
   178     | SOME fnameT' =>
   179         if fnameT = fnameT' then (fnameTs, fnss)
   180         else raise RecError ("inconsistent functions for datatype " ^ quote tname))
   181   end;
   182 
   183 
   184 (* prepare functions needed for definitions *)
   185 
   186 fun get_fns fns ((i : int, (tname, _, constrs)), rec_name) (fs, defs) =
   187   case AList.lookup (op =) fns i of
   188      NONE =>
   189        let
   190          val dummy_fns = map (fn (_, cargs) => Const ("arbitrary",
   191            replicate ((length cargs) + (length (List.filter is_rec_type cargs)))
   192              dummyT ---> HOLogic.unitT)) constrs;
   193          val _ = warning ("No function definition for datatype " ^ quote tname)
   194        in
   195          (dummy_fns @ fs, defs)
   196        end
   197    | SOME (fname, ls, rs, fs') => (fs' @ fs, (fname, ls, rs, rec_name, tname) :: defs);
   198 
   199 
   200 (* make definition *)
   201 
   202 fun make_def thy fs (fname, ls, rs, rec_name, tname) =
   203   let
   204     val used = map fst (fold Term.add_frees fs []);
   205     val x = (Name.variant used "x", dummyT);
   206     val frees = ls @ x :: rs;
   207     val rhs = list_abs_free (frees,
   208       list_comb (Const (rec_name, dummyT), fs @ [Free x]))
   209     val def_name = Sign.base_name fname ^ "_" ^ Sign.base_name tname ^ "_def";
   210     val def_prop as _ $ _ $ t =
   211       singleton (ProofContext.infer_types (ProofContext.init thy))
   212         (Logic.mk_equals (Const (fname, dummyT), rhs), propT) |> #1;
   213   in ((def_name, def_prop), subst_bounds (rev (map Free frees), strip_abs_body t)) end;
   214 
   215 
   216 (* find datatypes which contain all datatypes in tnames' *)
   217 
   218 fun find_dts (dt_info : NominalPackage.nominal_datatype_info Symtab.table) _ [] = []
   219   | find_dts dt_info tnames' (tname::tnames) =
   220       (case Symtab.lookup dt_info tname of
   221           NONE => primrec_err (quote tname ^ " is not a nominal datatype")
   222         | SOME dt =>
   223             if tnames' subset (map (#1 o snd) (#descr dt)) then
   224               (tname, dt)::(find_dts dt_info tnames' tnames)
   225             else find_dts dt_info tnames' tnames);
   226 
   227 fun common_prefix eq ([], _) = []
   228   | common_prefix eq (_, []) = []
   229   | common_prefix eq (x :: xs, y :: ys) =
   230       if eq (x, y) then x :: common_prefix eq (xs, ys) else [];
   231 
   232 local
   233 
   234 fun gen_primrec_i note def alt_name invs fctxt eqns_atts thy =
   235   let
   236     val (eqns, atts) = split_list eqns_atts;
   237     val dt_info = NominalPackage.get_nominal_datatypes thy;
   238     val rec_eqns = fold_rev (process_eqn thy o snd) eqns [];
   239     val lsrs :: lsrss = maps (fn (_, (_, _, eqns)) =>
   240       map (fn (_, (ls, _, rs, _, _)) => ls @ rs) eqns) rec_eqns
   241     val _ =
   242       (if forall (curry eq_set lsrs) lsrss andalso forall
   243          (fn (_, (_, _, (_, (ls, _, rs, _, _)) :: eqns)) =>
   244                forall (fn (_, (ls', _, rs', _, _)) =>
   245                  ls = ls' andalso rs = rs') eqns
   246            | _ => true) rec_eqns
   247        then () else primrec_err param_err);
   248     val tnames = distinct (op =) (map (#1 o snd) rec_eqns);
   249     val dts = find_dts dt_info tnames tnames;
   250     val main_fns = 
   251       map (fn (tname, {index, ...}) =>
   252         (index, 
   253           (fst o the o find_first (fn f => (#1 o snd) f = tname)) rec_eqns))
   254       dts;
   255     val {descr, rec_names, rec_rewrites, ...} = 
   256       if null dts then
   257         primrec_err ("datatypes " ^ commas_quote tnames ^ "\nare not mutually recursive")
   258       else snd (hd dts);
   259     val descr = map (fn (i, (tname, args, constrs)) => (i, (tname, args,
   260       map (fn (cname, cargs) => (cname, fold (fn (dTs, dT) => fn dTs' =>
   261         dTs' @ dTs @ [dT]) cargs [])) constrs))) descr;
   262     val (fnameTs, fnss) =
   263       fold_rev (process_fun thy descr rec_eqns) main_fns ([], []);
   264     val (fs, defs) = fold_rev (get_fns fnss) (descr ~~ rec_names) ([], []);
   265     val defs' = map (make_def thy fs) defs;
   266     val nameTs1 = map snd fnameTs;
   267     val nameTs2 = map fst rec_eqns;
   268     val _ = if gen_eq_set (op =) (nameTs1, nameTs2) then ()
   269             else primrec_err ("functions " ^ commas_quote (map fst nameTs2) ^
   270               "\nare not mutually recursive");
   271     val primrec_name =
   272       if alt_name = "" then (space_implode "_" (map (Sign.base_name o #1) defs)) else alt_name;
   273     val (defs_thms', thy') =
   274       thy
   275       |> Theory.add_path primrec_name
   276       |> fold_map def (map (fn ((name, t), _) => ((name, []), t)) defs');
   277     val cert = cterm_of thy';
   278 
   279     fun mk_idx eq =
   280       let
   281         val Const c = head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop
   282           (Logic.strip_imp_concl eq))));
   283         val SOME i = AList.lookup op = (map swap fnameTs) c;
   284         val SOME (_, _, constrs) = AList.lookup op = descr i;
   285         val SOME (_, _, eqns) = AList.lookup op = rec_eqns c;
   286         val SOME (cname, (_, cargs, _, _, _)) = find_first
   287           (fn (_, (_, _, _, _, eq')) => eq = eq') eqns
   288       in (i, find_index (fn (cname', _) => cname = cname') constrs, cargs) end;
   289 
   290     val rec_rewritess =
   291       unflat (map (fn (_, (_, _, constrs)) => constrs) descr) rec_rewrites;
   292     val fvars = rec_rewrites |> hd |> concl_of |> HOLogic.dest_Trueprop |>
   293       HOLogic.dest_eq |> fst |> strip_comb |> snd |> take_prefix is_Var |> fst;
   294     val (pvars, ctxtvars) = List.partition
   295       (equal HOLogic.boolT o body_type o snd)
   296       (fold_rev Term.add_vars (map Logic.strip_assums_concl
   297         (prems_of (hd rec_rewrites))) [] \\ map dest_Var fvars);
   298     val cfs = defs' |> hd |> snd |> strip_comb |> snd |>
   299       curry (List.take o swap) (length fvars) |> map cert;
   300     val invs' = (case invs of
   301         NONE => map (fn (i, _) =>
   302           let
   303             val SOME (_, T) = AList.lookup op = fnameTs i
   304             val (Ts, U) = strip_type T
   305           in
   306             Abs ("x", List.drop (Ts, length lsrs + 1) ---> U, HOLogic.true_const)
   307           end) descr
   308       | SOME invs' => invs');
   309     val inst = (map cert fvars ~~ cfs) @
   310       (map (cert o Var) pvars ~~ map cert invs') @
   311       (case ctxtvars of
   312          [ctxtvar] => [(cert (Var ctxtvar), cert (the_default HOLogic.unit fctxt))]
   313        | _ => []);
   314     val rec_rewrites' = map (fn (_, eq) =>
   315       let
   316         val (i, j, cargs) = mk_idx eq
   317         val th = nth (nth rec_rewritess i) j;
   318         val cargs' = th |> concl_of |> HOLogic.dest_Trueprop |>
   319           HOLogic.dest_eq |> fst |> strip_comb |> snd |> split_last |> snd |>
   320           strip_comb |> snd
   321       in (cargs, Logic.strip_imp_prems eq,
   322         Drule.cterm_instantiate (inst @
   323           (map (cterm_of thy') cargs' ~~ map (cterm_of thy' o Free) cargs)) th)
   324       end) eqns;
   325 
   326     val prems = foldr1 (common_prefix op aconv) (map (prems_of o #3) rec_rewrites');
   327     val cprems = map cert prems;
   328     val asms = map Thm.assume cprems;
   329     val premss = map (fn (cargs, eprems, eqn) =>
   330       map (fn t => list_all_free (cargs, Logic.list_implies (eprems, t)))
   331         (List.drop (prems_of eqn, length prems))) rec_rewrites';
   332     val cpremss = map (map cert) premss;
   333     val asmss = map (map Thm.assume) cpremss;
   334 
   335     fun mk_eqn ((cargs, eprems, eqn), asms') =
   336       let
   337         val ceprems = map cert eprems;
   338         val asms'' = map Thm.assume ceprems;
   339         val ccargs = map (cert o Free) cargs;
   340         val asms''' = map (fn th => implies_elim_list
   341           (forall_elim_list ccargs th) asms'') asms'
   342       in
   343         implies_elim_list eqn (asms @ asms''') |>
   344         implies_intr_list ceprems |>
   345         forall_intr_list ccargs
   346       end;
   347 
   348     val rule_prems = cprems @ flat cpremss;
   349     val rule = implies_intr_list rule_prems
   350       (foldr1 (uncurry Conjunction.intr) (map mk_eqn (rec_rewrites' ~~ asmss)));
   351 
   352     val goals = map (fn ((cargs, _, _), (_, eqn)) =>
   353       (list_all_free (cargs, eqn), [])) (rec_rewrites' ~~ eqns);
   354 
   355   in
   356     thy' |>
   357     ProofContext.init |>
   358     Proof.theorem_i NONE
   359       (fn thss => ProofContext.theory (fn thy =>
   360          let
   361            val simps = map standard (flat thss);
   362            val (simps', thy') =
   363              fold_map note ((map fst eqns ~~ atts) ~~ map single simps) thy;
   364            val simps'' = maps snd simps'
   365          in
   366            thy'
   367            |> note (("simps", [Simplifier.simp_add]), simps'')
   368            |> snd
   369            |> Theory.parent_path
   370          end))
   371       [goals] |>
   372     Proof.apply (Method.Basic (fn ctxt => Method.RAW_METHOD (fn ths =>
   373       rewrite_goals_tac (map snd defs_thms') THEN
   374       compose_tac (false, rule, length rule_prems) 1))) |>
   375     Seq.hd
   376   end;
   377 
   378 fun gen_primrec note def alt_name invs fctxt eqns thy =
   379   let
   380     fun readt T s = term_of (Thm.read_cterm thy (s, T));
   381     val ((names, strings), srcss) = apfst split_list (split_list eqns);
   382     val atts = map (map (Attrib.attribute thy)) srcss;
   383     val eqn_ts = map (fn s => readt propT s
   384       handle ERROR msg => cat_error msg ("The error(s) above occurred for " ^ s)) strings;
   385     val rec_ts = map (fn eq => head_of (fst (HOLogic.dest_eq
   386       (HOLogic.dest_Trueprop (Logic.strip_imp_concl eq))))
   387       handle TERM _ => primrec_eq_err thy "not a proper equation" eq) eqn_ts;
   388     val (_, eqn_ts') = OldInductivePackage.unify_consts thy rec_ts eqn_ts
   389   in
   390     gen_primrec_i note def alt_name
   391       (Option.map (map (readt TypeInfer.logicT)) invs)
   392       (Option.map (readt TypeInfer.logicT) fctxt)
   393       (names ~~ eqn_ts' ~~ atts) thy
   394   end;
   395 
   396 fun thy_note ((name, atts), thms) =
   397   PureThy.add_thmss [((name, thms), atts)] #-> (fn [thms] => pair (name, thms));
   398 fun thy_def false ((name, atts), t) =
   399       PureThy.add_defs_i false [((name, t), atts)] #-> (fn [thm] => pair (name, thm))
   400   | thy_def true ((name, atts), t) =
   401       PureThy.add_defs_unchecked_i false [((name, t), atts)] #-> (fn [thm] => pair (name, thm));
   402 
   403 in
   404 
   405 val add_primrec = gen_primrec thy_note (thy_def false);
   406 val add_primrec_unchecked = gen_primrec thy_note (thy_def true);
   407 val add_primrec_i = gen_primrec_i thy_note (thy_def false);
   408 val add_primrec_unchecked_i = gen_primrec_i thy_note (thy_def true);
   409 
   410 end; (*local*)
   411 
   412 
   413 (* outer syntax *)
   414 
   415 local structure P = OuterParse and K = OuterKeyword in
   416 
   417 val parser1 = P.$$$ "freshness_context" |-- P.$$$ ":" |-- (P.term >> SOME);
   418 val parser2 =
   419   P.$$$ "invariant" |-- P.$$$ ":" |--
   420     (Scan.repeat1 P.term >> SOME) -- Scan.optional parser1 NONE ||
   421   (parser1 >> pair NONE);
   422 val parser3 =
   423   P.name -- Scan.optional parser2 (NONE, NONE) ||
   424   (parser2 >> pair "");
   425 val parser4 =
   426   (P.$$$ "unchecked" >> K true) -- Scan.optional parser3 ("", (NONE, NONE)) ||
   427   (parser3 >> pair false);
   428 val options =
   429   Scan.optional (P.$$$ "(" |-- P.!!!
   430     (parser4 --| P.$$$ ")")) (false, ("", (NONE, NONE)));
   431 
   432 val primrec_decl =
   433   options -- Scan.repeat1 (SpecParse.opt_thm_name ":" -- P.prop);
   434 
   435 val primrecP =
   436   OuterSyntax.command "nominal_primrec" "define primitive recursive functions on nominal datatypes" K.thy_goal
   437     (primrec_decl >> (fn ((unchecked, (alt_name, (invs, fctxt))), eqns) =>
   438       Toplevel.print o Toplevel.theory_to_proof
   439         ((if unchecked then add_primrec_unchecked else add_primrec) alt_name invs fctxt
   440           (map P.triple_swap eqns))));
   441 
   442 val _ = OuterSyntax.add_parsers [primrecP];
   443 val _ = OuterSyntax.add_keywords ["invariant", "freshness_context"];
   444 
   445 end;
   446 
   447 
   448 end;
   449