src/HOL/Nominal/nominal_primrec.ML
changeset 21541 ea881fbe0489
child 21618 1cbb1134cb6c
equal deleted inserted replaced
21540:f3faed8276e6 21541:ea881fbe0489
       
     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 defpair = (Sign.base_name fname ^ "_" ^ Sign.base_name tname ^ "_def",
       
   210                    Logic.mk_equals (Const (fname, dummyT), rhs));
       
   211     val defpair' as (_, _ $ _ $ t) = Theory.inferT_axm thy defpair
       
   212   in (defpair', subst_bounds (rev (map Free frees), strip_abs_body t)) end;
       
   213 
       
   214 
       
   215 (* find datatypes which contain all datatypes in tnames' *)
       
   216 
       
   217 fun find_dts (dt_info : NominalPackage.nominal_datatype_info Symtab.table) _ [] = []
       
   218   | find_dts dt_info tnames' (tname::tnames) =
       
   219       (case Symtab.lookup dt_info tname of
       
   220           NONE => primrec_err (quote tname ^ " is not a nominal datatype")
       
   221         | SOME dt =>
       
   222             if tnames' subset (map (#1 o snd) (#descr dt)) then
       
   223               (tname, dt)::(find_dts dt_info tnames' tnames)
       
   224             else find_dts dt_info tnames' tnames);
       
   225 
       
   226 fun common_prefix eq ([], _) = []
       
   227   | common_prefix eq (_, []) = []
       
   228   | common_prefix eq (x :: xs, y :: ys) =
       
   229       if eq (x, y) then x :: common_prefix eq (xs, ys) else [];
       
   230 
       
   231 local
       
   232 
       
   233 fun gen_primrec_i note def alt_name invs fctxt eqns_atts thy =
       
   234   let
       
   235     val (eqns, atts) = split_list eqns_atts;
       
   236     val dt_info = NominalPackage.get_nominal_datatypes thy;
       
   237     val rec_eqns = fold_rev (process_eqn thy o snd) eqns [];
       
   238     val lsrs :: lsrss = maps (fn (_, (_, _, eqns)) =>
       
   239       map (fn (_, (ls, _, rs, _, _)) => ls @ rs) eqns) rec_eqns
       
   240     val _ =
       
   241       (if forall (curry eq_set lsrs) lsrss andalso forall
       
   242          (fn (_, (_, _, (_, (ls, _, rs, _, _)) :: eqns)) =>
       
   243                forall (fn (_, (ls', _, rs', _, _)) =>
       
   244                  ls = ls' andalso rs = rs') eqns
       
   245            | _ => true) rec_eqns
       
   246        then () else raise RecError param_err);
       
   247     val tnames = distinct (op =) (map (#1 o snd) rec_eqns);
       
   248     val dts = find_dts dt_info tnames tnames;
       
   249     val main_fns = 
       
   250       map (fn (tname, {index, ...}) =>
       
   251         (index, 
       
   252           (fst o the o find_first (fn f => (#1 o snd) f = tname)) rec_eqns))
       
   253       dts;
       
   254     val {descr, rec_names, rec_rewrites, ...} = 
       
   255       if null dts then
       
   256         primrec_err ("datatypes " ^ commas_quote tnames ^ "\nare not mutually recursive")
       
   257       else snd (hd dts);
       
   258     val (fnameTs, fnss) =
       
   259       fold_rev (process_fun thy descr rec_eqns) main_fns ([], []);
       
   260     val (fs, defs) = fold_rev (get_fns fnss) (descr ~~ rec_names) ([], []);
       
   261     val defs' = map (make_def thy fs) defs;
       
   262     val nameTs1 = map snd fnameTs;
       
   263     val nameTs2 = map fst rec_eqns;
       
   264     val _ = if gen_eq_set (op =) (nameTs1, nameTs2) then ()
       
   265             else primrec_err ("functions " ^ commas_quote (map fst nameTs2) ^
       
   266               "\nare not mutually recursive");
       
   267     val primrec_name =
       
   268       if alt_name = "" then (space_implode "_" (map (Sign.base_name o #1) defs)) else alt_name;
       
   269     val (defs_thms', thy') =
       
   270       thy
       
   271       |> Theory.add_path primrec_name
       
   272       |> fold_map def (map (fn ((name, t), _) => ((name, []), t)) defs');
       
   273     val cert = cterm_of thy';
       
   274 
       
   275     fun mk_idx eq =
       
   276       let
       
   277         val Const c = head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop
       
   278           (Logic.strip_imp_concl eq))));
       
   279         val SOME i = AList.lookup op = (map swap fnameTs) c;
       
   280         val SOME (_, _, constrs) = AList.lookup op = descr i;
       
   281         val SOME (_, _, eqns) = AList.lookup op = rec_eqns c;
       
   282         val SOME (cname, (_, cargs, _, _, _)) = find_first
       
   283           (fn (_, (_, _, _, _, eq')) => eq = eq') eqns
       
   284       in (i, find_index (fn (cname', _) => cname = cname') constrs, cargs) end;
       
   285 
       
   286     val rec_rewritess =
       
   287       unflat (map (fn (_, (_, _, constrs)) => constrs) descr) rec_rewrites;
       
   288     val fvars = rec_rewrites |> hd |> concl_of |> HOLogic.dest_Trueprop |>
       
   289       HOLogic.dest_eq |> fst |> strip_comb |> snd |> take_prefix is_Var |> fst;
       
   290     val (pvars, ctxtvars) = List.partition
       
   291       (equal HOLogic.boolT o body_type o snd)
       
   292       (fold Term.add_vars (map Logic.strip_assums_concl
       
   293         (prems_of (hd rec_rewrites))) [] \\ map dest_Var fvars);
       
   294     val cfs = defs' |> hd |> snd |> strip_comb |> snd |>
       
   295       curry (List.take o swap) (length fvars) |> map cert;
       
   296     val invs' = (case invs of
       
   297         NONE => map (fn (i, _) =>
       
   298           let
       
   299             val SOME (_, T) = AList.lookup op = fnameTs i
       
   300             val (Ts, U) = strip_type T
       
   301           in
       
   302             Abs ("x", List.drop (Ts, length lsrs + 1) ---> U, HOLogic.true_const)
       
   303           end) descr
       
   304       | SOME invs' => invs');
       
   305     val inst = (map cert fvars ~~ cfs) @
       
   306       (map (cert o Var) pvars ~~ map cert invs') @
       
   307       (case ctxtvars of
       
   308          [ctxtvar] => [(cert (Var ctxtvar), cert (the_default HOLogic.unit fctxt))]
       
   309        | _ => []);
       
   310     val rec_rewrites' = map (fn (_, eq) =>
       
   311       let
       
   312         val (i, j, cargs) = mk_idx eq
       
   313         val th = nth (nth rec_rewritess i) j;
       
   314         val cargs' = th |> concl_of |> HOLogic.dest_Trueprop |>
       
   315           HOLogic.dest_eq |> fst |> strip_comb |> snd |> split_last |> snd |>
       
   316           strip_comb |> snd
       
   317       in (cargs, Logic.strip_imp_prems eq,
       
   318         Drule.cterm_instantiate (inst @
       
   319           (map (cterm_of thy') cargs' ~~ map (cterm_of thy' o Free) cargs)) th)
       
   320       end) eqns;
       
   321 
       
   322     val prems = foldr1 (common_prefix op aconv) (map (prems_of o #3) rec_rewrites');
       
   323     val cprems = map cert prems;
       
   324     val asms = map Thm.assume cprems;
       
   325     val premss = map (fn (cargs, eprems, eqn) =>
       
   326       map (fn t => list_all_free (cargs, Logic.list_implies (eprems, t)))
       
   327         (List.drop (prems_of eqn, length prems))) rec_rewrites';
       
   328     val cpremss = map (map cert) premss;
       
   329     val asmss = map (map Thm.assume) cpremss;
       
   330 
       
   331     fun mk_eqn ((cargs, eprems, eqn), asms') =
       
   332       let
       
   333         val ceprems = map cert eprems;
       
   334         val asms'' = map Thm.assume ceprems;
       
   335         val ccargs = map (cert o Free) cargs;
       
   336         val asms''' = map (fn th => implies_elim_list
       
   337           (forall_elim_list ccargs th) asms'') asms'
       
   338       in
       
   339         implies_elim_list eqn (asms @ asms''') |>
       
   340         implies_intr_list ceprems |>
       
   341         forall_intr_list ccargs
       
   342       end;
       
   343 
       
   344     val rule_prems = cprems @ flat cpremss;
       
   345     val rule = implies_intr_list rule_prems
       
   346       (foldr1 (uncurry Conjunction.intr) (map mk_eqn (rec_rewrites' ~~ asmss)));
       
   347 
       
   348     val goals = map (fn ((cargs, _, _), (_, eqn)) =>
       
   349       (list_all_free (cargs, eqn), [])) (rec_rewrites' ~~ eqns);
       
   350 
       
   351   in
       
   352     thy' |>
       
   353     ProofContext.init |>
       
   354     Proof.theorem_i NONE
       
   355       (fn thss => ProofContext.theory (fn thy =>
       
   356          let
       
   357            val simps = flat thss;
       
   358            val (simps', thy') =
       
   359              fold_map note ((map fst eqns ~~ atts) ~~ map single simps) thy;
       
   360            val simps'' = maps snd simps'
       
   361          in
       
   362            thy'
       
   363            |> note (("simps", [Simplifier.simp_add]), simps'')
       
   364            |> snd
       
   365            |> Theory.parent_path
       
   366          end))
       
   367       [goals] |>
       
   368     Proof.apply (Method.Basic (fn ctxt => Method.RAW_METHOD (fn ths =>
       
   369       rewrite_goals_tac (map snd defs_thms') THEN
       
   370       compose_tac (false, rule, length rule_prems) 1))) |>
       
   371     Seq.hd
       
   372   end;
       
   373 
       
   374 fun gen_primrec note def alt_name invs fctxt eqns thy =
       
   375   let
       
   376     fun readt T s = term_of (Thm.read_cterm thy (s, T));
       
   377     val ((names, strings), srcss) = apfst split_list (split_list eqns);
       
   378     val atts = map (map (Attrib.attribute thy)) srcss;
       
   379     val eqn_ts = map (fn s => readt propT s
       
   380       handle ERROR msg => cat_error msg ("The error(s) above occurred for " ^ s)) strings;
       
   381     val rec_ts = map (fn eq => head_of (fst (HOLogic.dest_eq
       
   382       (HOLogic.dest_Trueprop (Logic.strip_imp_concl eq))))
       
   383       handle TERM _ => primrec_eq_err thy "not a proper equation" eq) eqn_ts;
       
   384     val (_, eqn_ts') = OldInductivePackage.unify_consts thy rec_ts eqn_ts
       
   385   in
       
   386     gen_primrec_i note def alt_name
       
   387       (Option.map (map (readt TypeInfer.logicT)) invs)
       
   388       (Option.map (readt TypeInfer.logicT) fctxt)
       
   389       (names ~~ eqn_ts' ~~ atts) thy
       
   390   end;
       
   391 
       
   392 fun thy_note ((name, atts), thms) =
       
   393   PureThy.add_thmss [((name, thms), atts)] #-> (fn [thms] => pair (name, thms));
       
   394 fun thy_def false ((name, atts), t) =
       
   395       PureThy.add_defs_i false [((name, t), atts)] #-> (fn [thm] => pair (name, thm))
       
   396   | thy_def true ((name, atts), t) =
       
   397       PureThy.add_defs_unchecked_i false [((name, t), atts)] #-> (fn [thm] => pair (name, thm));
       
   398 
       
   399 in
       
   400 
       
   401 val add_primrec = gen_primrec thy_note (thy_def false);
       
   402 val add_primrec_unchecked = gen_primrec thy_note (thy_def true);
       
   403 val add_primrec_i = gen_primrec_i thy_note (thy_def false);
       
   404 val add_primrec_unchecked_i = gen_primrec_i thy_note (thy_def true);
       
   405 
       
   406 end; (*local*)
       
   407 
       
   408 
       
   409 (* outer syntax *)
       
   410 
       
   411 local structure P = OuterParse and K = OuterKeyword in
       
   412 
       
   413 val parser1 = P.$$$ "freshness_context" |-- P.$$$ ":" |-- (P.term >> SOME);
       
   414 val parser2 =
       
   415   P.$$$ "invariant" |-- P.$$$ ":" |--
       
   416     (Scan.repeat1 P.term >> SOME) -- Scan.optional parser1 NONE ||
       
   417   (parser1 >> pair NONE);
       
   418 val parser3 =
       
   419   P.name -- Scan.optional parser2 (NONE, NONE) ||
       
   420   (parser2 >> pair "");
       
   421 val parser4 =
       
   422   (P.$$$ "unchecked" >> K true) -- Scan.optional parser3 ("", (NONE, NONE)) ||
       
   423   (parser3 >> pair false);
       
   424 val options =
       
   425   Scan.optional (P.$$$ "(" |-- P.!!!
       
   426     (parser4 --| P.$$$ ")")) (false, ("", (NONE, NONE)));
       
   427 
       
   428 val primrec_decl =
       
   429   options -- Scan.repeat1 (P.opt_thm_name ":" -- P.prop);
       
   430 
       
   431 val primrecP =
       
   432   OuterSyntax.command "nominal_primrec" "define primitive recursive functions on nominal datatypes" K.thy_goal
       
   433     (primrec_decl >> (fn ((unchecked, (alt_name, (invs, fctxt))), eqns) =>
       
   434       Toplevel.theory_to_proof
       
   435         ((if unchecked then add_primrec_unchecked else add_primrec) alt_name invs fctxt
       
   436           (map P.triple_swap eqns))));
       
   437 
       
   438 val _ = OuterSyntax.add_parsers [primrecP];
       
   439 val _ = OuterSyntax.add_keywords ["invariant", "freshness_context"];
       
   440 
       
   441 end;
       
   442 
       
   443 
       
   444 end;
       
   445