src/HOL/Nominal/nominal_primrec.ML
author wenzelm
Sun May 18 15:04:09 2008 +0200 (2008-05-18)
changeset 26939 1035c89b4c02
parent 26476 4e78281b3273
child 27691 ce171cbd4b93
permissions -rw-r--r--
moved global pretty/string_of functions from Sign to Syntax;
     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 add_primrec: string -> string list option -> string option ->
    12     ((bstring * string) * Attrib.src list) list -> theory -> Proof.state
    13   val add_primrec_unchecked: string -> string list option -> string option ->
    14     ((bstring * string) * Attrib.src list) list -> theory -> Proof.state
    15   val add_primrec_i: string -> term list option -> term option ->
    16     ((bstring * term) * attribute list) list -> theory -> Proof.state
    17   val add_primrec_unchecked_i: string -> term list option -> term option ->
    18     ((bstring * term) * attribute list) list -> theory -> Proof.state
    19 end;
    20 
    21 structure NominalPrimrec : NOMINAL_PRIMREC =
    22 struct
    23 
    24 open DatatypeAux;
    25 
    26 exception RecError of string;
    27 
    28 fun primrec_err s = error ("Nominal primrec definition error:\n" ^ s);
    29 fun primrec_eq_err thy s eq =
    30   primrec_err (s ^ "\nin\n" ^ quote (Syntax.string_of_term_global thy eq));
    31 
    32 
    33 (* preprocessing of equations *)
    34 
    35 fun process_eqn thy eq rec_fns = 
    36   let
    37     val (lhs, rhs) = 
    38       if null (term_vars eq) then
    39         HOLogic.dest_eq (HOLogic.dest_Trueprop (Logic.strip_imp_concl eq))
    40         handle TERM _ => raise RecError "not a proper equation"
    41       else raise RecError "illegal schematic variable(s)";
    42 
    43     val (recfun, args) = strip_comb lhs;
    44     val fnameT = dest_Const recfun handle TERM _ => 
    45       raise RecError "function is not declared as constant in theory";
    46 
    47     val (ls', rest)  = take_prefix is_Free args;
    48     val (middle, rs') = take_suffix is_Free rest;
    49     val rpos = length ls';
    50 
    51     val (constr, cargs') = if null middle then raise RecError "constructor missing"
    52       else strip_comb (hd middle);
    53     val (cname, T) = dest_Const constr
    54       handle TERM _ => raise RecError "ill-formed constructor";
    55     val (tname, _) = dest_Type (body_type T) handle TYPE _ =>
    56       raise RecError "cannot determine datatype associated with function"
    57 
    58     val (ls, cargs, rs) =
    59       (map dest_Free ls', map dest_Free cargs', map dest_Free rs')
    60       handle TERM _ => raise RecError "illegal argument in pattern";
    61     val lfrees = ls @ rs @ cargs;
    62 
    63     fun check_vars _ [] = ()
    64       | check_vars s vars = raise RecError (s ^ commas_quote (map fst vars))
    65   in
    66     if length middle > 1 then 
    67       raise RecError "more than one non-variable in pattern"
    68     else
    69      (check_vars "repeated variable names in pattern: " (duplicates (op =) lfrees);
    70       check_vars "extra variables on rhs: "
    71         (map dest_Free (term_frees rhs) \\ lfrees);
    72       case AList.lookup (op =) rec_fns fnameT of
    73         NONE =>
    74           (fnameT, (tname, rpos, [(cname, (ls, cargs, rs, rhs, eq))]))::rec_fns
    75       | SOME (_, rpos', eqns) =>
    76           if AList.defined (op =) eqns cname then
    77             raise RecError "constructor already occurred as pattern"
    78           else if rpos <> rpos' then
    79             raise RecError "position of recursive argument inconsistent"
    80           else
    81             AList.update (op =) (fnameT, (tname, rpos, (cname, (ls, cargs, rs, rhs, eq))::eqns))
    82               rec_fns)
    83   end
    84   handle RecError s => primrec_eq_err thy s eq;
    85 
    86 val param_err = "Parameters must be the same for all recursive functions";
    87 
    88 fun process_fun thy descr rec_eqns (i, fnameT as (fname, _)) (fnameTs, fnss) =
    89   let
    90     val (_, (tname, _, constrs)) = List.nth (descr, i);
    91 
    92     (* substitute "fname ls x rs" by "y" for (x, (_, y)) in subs *)
    93 
    94     fun subst [] t fs = (t, fs)
    95       | subst subs (Abs (a, T, t)) fs =
    96           fs
    97           |> subst subs t
    98           |-> (fn t' => pair (Abs (a, T, t')))
    99       | subst subs (t as (_ $ _)) fs =
   100           let
   101             val (f, ts) = strip_comb t;
   102           in
   103             if is_Const f andalso dest_Const f mem map fst rec_eqns then
   104               let
   105                 val fnameT' as (fname', _) = dest_Const f;
   106                 val (_, rpos, eqns) = the (AList.lookup (op =) rec_eqns fnameT');
   107                 val ls = Library.take (rpos, ts);
   108                 val rest = Library.drop (rpos, ts);
   109                 val (x', rs) = (hd rest, tl rest)
   110                   handle Empty => raise RecError ("not enough arguments\
   111                    \ in recursive application\nof function " ^ quote fname' ^ " on rhs");
   112                 val rs' = (case eqns of
   113                     (_, (ls', _, rs', _, _)) :: _ =>
   114                       let val (rs1, rs2) = chop (length rs') rs
   115                       in
   116                         if ls = map Free ls' andalso rs1 = map Free rs' then rs2
   117                         else raise RecError param_err
   118                       end
   119                   | _ => raise RecError ("no equations for " ^ quote fname'));
   120                 val (x, xs) = strip_comb x'
   121               in case AList.lookup (op =) subs x
   122                of NONE =>
   123                     fs
   124                     |> fold_map (subst subs) ts
   125                     |-> (fn ts' => pair (list_comb (f, ts')))
   126                 | SOME (i', y) =>
   127                     fs
   128                     |> fold_map (subst subs) (xs @ rs')
   129                     ||> process_fun thy descr rec_eqns (i', fnameT')
   130                     |-> (fn ts' => pair (list_comb (y, ts')))
   131               end
   132             else
   133               fs
   134               |> fold_map (subst subs) (f :: ts)
   135               |-> (fn (f'::ts') => pair (list_comb (f', ts')))
   136           end
   137       | subst _ t fs = (t, fs);
   138 
   139     (* translate rec equations into function arguments suitable for rec comb *)
   140 
   141     fun trans eqns (cname, cargs) (fnameTs', fnss', fns) =
   142       (case AList.lookup (op =) eqns cname of
   143           NONE => (warning ("No equation for constructor " ^ quote cname ^
   144             "\nin definition of function " ^ quote fname);
   145               (fnameTs', fnss', (Const ("arbitrary", dummyT))::fns))
   146         | SOME (ls, cargs', rs, rhs, eq) =>
   147             let
   148               val recs = filter (is_rec_type o snd) (cargs' ~~ cargs);
   149               val rargs = map fst recs;
   150               val subs = map (rpair dummyT o fst) 
   151                 (rev (rename_wrt_term rhs rargs));
   152               val (rhs', (fnameTs'', fnss'')) = 
   153                   (subst (map (fn ((x, y), z) =>
   154                                (Free x, (body_index y, Free z)))
   155                           (recs ~~ subs)) rhs (fnameTs', fnss'))
   156                   handle RecError s => primrec_eq_err thy s eq
   157             in (fnameTs'', fnss'', 
   158                 (list_abs_free (cargs' @ subs, rhs'))::fns)
   159             end)
   160 
   161   in (case AList.lookup (op =) fnameTs i of
   162       NONE =>
   163         if exists (equal fnameT o snd) fnameTs then
   164           raise RecError ("inconsistent functions for datatype " ^ quote tname)
   165         else
   166           let
   167             val SOME (_, _, eqns as (_, (ls, _, rs, _, _)) :: _) =
   168               AList.lookup (op =) rec_eqns fnameT;
   169             val (fnameTs', fnss', fns) = fold_rev (trans eqns) constrs
   170               ((i, fnameT)::fnameTs, fnss, []) 
   171           in
   172             (fnameTs', (i, (fname, ls, rs, fns))::fnss')
   173           end
   174     | SOME fnameT' =>
   175         if fnameT = fnameT' then (fnameTs, fnss)
   176         else raise RecError ("inconsistent functions for datatype " ^ quote tname))
   177   end;
   178 
   179 
   180 (* prepare functions needed for definitions *)
   181 
   182 fun get_fns fns ((i : int, (tname, _, constrs)), rec_name) (fs, defs) =
   183   case AList.lookup (op =) fns i of
   184      NONE =>
   185        let
   186          val dummy_fns = map (fn (_, cargs) => Const ("arbitrary",
   187            replicate ((length cargs) + (length (List.filter is_rec_type cargs)))
   188              dummyT ---> HOLogic.unitT)) constrs;
   189          val _ = warning ("No function definition for datatype " ^ quote tname)
   190        in
   191          (dummy_fns @ fs, defs)
   192        end
   193    | SOME (fname, ls, rs, fs') => (fs' @ fs, (fname, ls, rs, rec_name, tname) :: defs);
   194 
   195 
   196 (* make definition *)
   197 
   198 fun make_def thy fs (fname, ls, rs, rec_name, tname) =
   199   let
   200     val used = map fst (fold Term.add_frees fs []);
   201     val x = (Name.variant used "x", dummyT);
   202     val frees = ls @ x :: rs;
   203     val rhs = list_abs_free (frees,
   204       list_comb (Const (rec_name, dummyT), fs @ [Free x]))
   205     val def_name = Sign.base_name fname ^ "_" ^ Sign.base_name tname ^ "_def";
   206     val def_prop as _ $ _ $ t =
   207       singleton (Syntax.check_terms (ProofContext.init thy))
   208         (Logic.mk_equals (Const (fname, dummyT), rhs));
   209   in ((def_name, def_prop), subst_bounds (rev (map Free frees), strip_abs_body t)) end;
   210 
   211 
   212 (* find datatypes which contain all datatypes in tnames' *)
   213 
   214 fun find_dts (dt_info : NominalPackage.nominal_datatype_info Symtab.table) _ [] = []
   215   | find_dts dt_info tnames' (tname::tnames) =
   216       (case Symtab.lookup dt_info tname of
   217           NONE => primrec_err (quote tname ^ " is not a nominal datatype")
   218         | SOME dt =>
   219             if tnames' subset (map (#1 o snd) (#descr dt)) then
   220               (tname, dt)::(find_dts dt_info tnames' tnames)
   221             else find_dts dt_info tnames' tnames);
   222 
   223 fun common_prefix eq ([], _) = []
   224   | common_prefix eq (_, []) = []
   225   | common_prefix eq (x :: xs, y :: ys) =
   226       if eq (x, y) then x :: common_prefix eq (xs, ys) else [];
   227 
   228 local
   229 
   230 fun gen_primrec_i note def alt_name invs fctxt eqns_atts thy =
   231   let
   232     val (eqns, atts) = split_list eqns_atts;
   233     val dt_info = NominalPackage.get_nominal_datatypes thy;
   234     val rec_eqns = fold_rev (process_eqn thy o snd) eqns [];
   235     val lsrs :: lsrss = maps (fn (_, (_, _, eqns)) =>
   236       map (fn (_, (ls, _, rs, _, _)) => ls @ rs) eqns) rec_eqns
   237     val _ =
   238       (if forall (curry eq_set lsrs) lsrss andalso forall
   239          (fn (_, (_, _, (_, (ls, _, rs, _, _)) :: eqns)) =>
   240                forall (fn (_, (ls', _, rs', _, _)) =>
   241                  ls = ls' andalso rs = rs') eqns
   242            | _ => true) rec_eqns
   243        then () else primrec_err param_err);
   244     val tnames = distinct (op =) (map (#1 o snd) rec_eqns);
   245     val dts = find_dts dt_info tnames tnames;
   246     val main_fns = 
   247       map (fn (tname, {index, ...}) =>
   248         (index, 
   249           (fst o the o find_first (fn f => (#1 o snd) f = tname)) rec_eqns))
   250       dts;
   251     val {descr, rec_names, rec_rewrites, ...} = 
   252       if null dts then
   253         primrec_err ("datatypes " ^ commas_quote tnames ^ "\nare not mutually recursive")
   254       else snd (hd dts);
   255     val descr = map (fn (i, (tname, args, constrs)) => (i, (tname, args,
   256       map (fn (cname, cargs) => (cname, fold (fn (dTs, dT) => fn dTs' =>
   257         dTs' @ dTs @ [dT]) cargs [])) constrs))) descr;
   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       |> Sign.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_rev 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       (Conjunction.intr_balanced (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 = map standard (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            |> Sign.parent_path
   366          end))
   367       [goals] |>
   368     Proof.apply (Method.Basic (fn _ => Method.RAW_METHOD (fn _ =>
   369       rewrite_goals_tac (map snd defs_thms') THEN
   370       compose_tac (false, rule, length rule_prems) 1), Position.none)) |>
   371     Seq.hd
   372   end;
   373 
   374 fun gen_primrec note def alt_name invs fctxt eqns thy =
   375   let
   376     val ((names, strings), srcss) = apfst split_list (split_list eqns);
   377     val atts = map (map (Attrib.attribute thy)) srcss;
   378     val eqn_ts = map (fn s => Syntax.read_prop_global thy s
   379       handle ERROR msg => cat_error msg ("The error(s) above occurred for " ^ s)) strings;
   380     val rec_ts = map (fn eq => head_of (fst (HOLogic.dest_eq
   381       (HOLogic.dest_Trueprop (Logic.strip_imp_concl eq))))
   382       handle TERM _ => primrec_eq_err thy "not a proper equation" eq) eqn_ts;
   383     val (_, eqn_ts') = OldPrimrecPackage.unify_consts thy rec_ts eqn_ts
   384   in
   385     gen_primrec_i note def alt_name
   386       (Option.map (map (Syntax.read_term_global thy)) invs)
   387       (Option.map (Syntax.read_term_global thy) fctxt)
   388       (names ~~ eqn_ts' ~~ atts) thy
   389   end;
   390 
   391 fun thy_note ((name, atts), thms) =
   392   PureThy.add_thmss [((name, thms), atts)] #-> (fn [thms] => pair (name, thms));
   393 fun thy_def false ((name, atts), t) =
   394       PureThy.add_defs_i false [((name, t), atts)] #-> (fn [thm] => pair (name, thm))
   395   | thy_def true ((name, atts), t) =
   396       PureThy.add_defs_unchecked_i false [((name, t), atts)] #-> (fn [thm] => pair (name, thm));
   397 
   398 in
   399 
   400 val add_primrec = gen_primrec thy_note (thy_def false);
   401 val add_primrec_unchecked = gen_primrec thy_note (thy_def true);
   402 val add_primrec_i = gen_primrec_i thy_note (thy_def false);
   403 val add_primrec_unchecked_i = gen_primrec_i thy_note (thy_def true);
   404 
   405 end; (*local*)
   406 
   407 
   408 (* outer syntax *)
   409 
   410 local structure P = OuterParse and K = OuterKeyword in
   411 
   412 val freshness_context = P.reserved "freshness_context";
   413 val invariant = P.reserved "invariant";
   414 
   415 fun unless_flag scan = Scan.unless ((freshness_context || invariant) -- P.$$$ ":") scan;
   416 
   417 val parser1 = (freshness_context -- P.$$$ ":") |-- unless_flag P.term >> SOME;
   418 val parser2 = (invariant -- P.$$$ ":") |--
   419     (Scan.repeat1 (unless_flag P.term) >> SOME) -- Scan.optional parser1 NONE ||
   420   (parser1 >> pair NONE);
   421 val parser3 =
   422   unless_flag P.name -- Scan.optional parser2 (NONE, NONE) ||
   423   (parser2 >> pair "");
   424 val parser4 =
   425   (P.$$$ "unchecked" >> K true) -- Scan.optional parser3 ("", (NONE, NONE)) ||
   426   (parser3 >> pair false);
   427 val options =
   428   Scan.optional (P.$$$ "(" |-- P.!!!
   429     (parser4 --| P.$$$ ")")) (false, ("", (NONE, NONE)));
   430 
   431 val primrec_decl =
   432   options -- Scan.repeat1 (SpecParse.opt_thm_name ":" -- P.prop);
   433 
   434 val _ =
   435   OuterSyntax.command "nominal_primrec" "define primitive recursive functions on nominal datatypes" K.thy_goal
   436     (primrec_decl >> (fn ((unchecked, (alt_name, (invs, fctxt))), eqns) =>
   437       Toplevel.print o Toplevel.theory_to_proof
   438         ((if unchecked then add_primrec_unchecked else add_primrec) alt_name invs fctxt
   439           (map P.triple_swap eqns))));
   440 
   441 end;
   442 
   443 
   444 end;
   445