src/HOL/Nominal/nominal_primrec.ML
author berghofe
Sat Dec 13 13:24:45 2008 +0100 (2008-12-13)
changeset 29097 68245155eb58
parent 29006 abe0f11cfa4e
child 29265 5b4247055bd7
permissions -rw-r--r--
Modified nominal_primrec to make it work with local theories, unified syntax
with the one used by fun(ction) and new version of primrec command.
     1 (*  Title:      HOL/Nominal/nominal_primrec.ML
     2     Author:     Stefan Berghofer, TU Muenchen and Norbert Voelker, FernUni Hagen
     3 
     4 Package for defining functions on nominal datatypes by primitive recursion.
     5 Taken from HOL/Tools/primrec_package.ML
     6 *)
     7 
     8 signature NOMINAL_PRIMREC =
     9 sig
    10   val add_primrec: term list option -> term option ->
    11     (Binding.T * typ option * mixfix) list ->
    12     (Binding.T * typ option * mixfix) list ->
    13     (Attrib.binding * term) list -> local_theory -> Proof.state
    14 end;
    15 
    16 structure NominalPrimrec : NOMINAL_PRIMREC =
    17 struct
    18 
    19 open DatatypeAux;
    20 
    21 exception RecError of string;
    22 
    23 fun primrec_err s = error ("Nominal primrec definition error:\n" ^ s);
    24 fun primrec_eq_err lthy s eq =
    25   primrec_err (s ^ "\nin\n" ^ quote (Syntax.string_of_term lthy eq));
    26 
    27 
    28 (* preprocessing of equations *)
    29 
    30 fun unquantify t =
    31   let
    32     val (vs, Ts) = split_list (strip_qnt_vars "all" t);
    33     val body = strip_qnt_body "all" t;
    34     val (vs', _) = Name.variants vs (Name.make_context (fold_aterms
    35       (fn Free (v, _) => insert (op =) v | _ => I) body []))
    36   in (curry subst_bounds (map2 (curry Free) vs' Ts |> rev) body) end;
    37 
    38 fun process_eqn lthy is_fixed spec rec_fns = 
    39   let
    40     val eq = unquantify spec;
    41     val (lhs, rhs) = 
    42       HOLogic.dest_eq (HOLogic.dest_Trueprop (Logic.strip_imp_concl eq))
    43       handle TERM _ => raise RecError "not a proper equation";
    44 
    45     val (recfun, args) = strip_comb lhs;
    46     val fname = case recfun of Free (v, _) => if is_fixed v then v
    47           else raise RecError "illegal head of function equation"
    48       | _ => raise RecError "illegal head of function equation";
    49 
    50     val (ls', rest)  = take_prefix is_Free args;
    51     val (middle, rs') = take_suffix is_Free rest;
    52     val rpos = length ls';
    53 
    54     val (constr, cargs') = if null middle then raise RecError "constructor missing"
    55       else strip_comb (hd middle);
    56     val (cname, T) = dest_Const constr
    57       handle TERM _ => raise RecError "ill-formed constructor";
    58     val (tname, _) = dest_Type (body_type T) handle TYPE _ =>
    59       raise RecError "cannot determine datatype associated with function"
    60 
    61     val (ls, cargs, rs) =
    62       (map dest_Free ls', map dest_Free cargs', 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 (op =) lfrees);
    73       check_vars "extra variables on rhs: "
    74         (map dest_Free (term_frees rhs) |> subtract (op =) lfrees
    75           |> filter_out (is_fixed o fst));
    76       case AList.lookup (op =) rec_fns fname of
    77         NONE =>
    78           (fname, (tname, rpos, [(cname, (ls, cargs, rs, rhs, eq))]))::rec_fns
    79       | SOME (_, rpos', eqns) =>
    80           if AList.defined (op =) eqns cname then
    81             raise RecError "constructor already occurred as pattern"
    82           else if rpos <> rpos' then
    83             raise RecError "position of recursive argument inconsistent"
    84           else
    85             AList.update (op =)
    86               (fname, (tname, rpos, (cname, (ls, cargs, rs, rhs, eq))::eqns))
    87               rec_fns)
    88   end
    89   handle RecError s => primrec_eq_err lthy s spec;
    90 
    91 val param_err = "Parameters must be the same for all recursive functions";
    92 
    93 fun process_fun lthy descr eqns (i, fname) (fnames, fnss) =
    94   let
    95     val (_, (tname, _, constrs)) = nth descr i;
    96 
    97     (* substitute "fname ls x rs" by "y" for (x, (_, y)) in subs *)
    98 
    99     fun subst [] t fs = (t, fs)
   100       | subst subs (Abs (a, T, t)) fs =
   101           fs
   102           |> subst subs t
   103           |-> (fn t' => pair (Abs (a, T, t')))
   104       | subst subs (t as (_ $ _)) fs =
   105           let
   106             val (f, ts) = strip_comb t;
   107           in
   108             if is_Free f
   109               andalso member (fn ((v, _), (w, _)) => v = w) eqns (dest_Free f) then
   110               let
   111                 val (fname', _) = dest_Free f;
   112                 val (_, rpos, eqns') = the (AList.lookup (op =) eqns fname');
   113                 val (ls, rs'') = chop rpos ts
   114                 val (x', rs) = case rs'' of
   115                     x' :: rs => (x', rs)
   116                   | [] => raise RecError ("not enough arguments in recursive application\n"
   117                       ^ "of function " ^ quote fname' ^ " on rhs");
   118                 val rs' = (case eqns' of
   119                     (_, (ls', _, rs', _, _)) :: _ =>
   120                       let val (rs1, rs2) = chop (length rs') rs
   121                       in
   122                         if ls = map Free ls' andalso rs1 = map Free rs' then rs2
   123                         else raise RecError param_err
   124                       end
   125                   | _ => raise RecError ("no equations for " ^ quote fname'));
   126                 val (x, xs) = strip_comb x'
   127               in case AList.lookup (op =) subs x
   128                of NONE =>
   129                     fs
   130                     |> fold_map (subst subs) ts
   131                     |-> (fn ts' => pair (list_comb (f, ts')))
   132                 | SOME (i', y) =>
   133                     fs
   134                     |> fold_map (subst subs) (xs @ rs')
   135                     ||> process_fun lthy descr eqns (i', fname')
   136                     |-> (fn ts' => pair (list_comb (y, ts')))
   137               end
   138             else
   139               fs
   140               |> fold_map (subst subs) (f :: ts)
   141               |-> (fn (f'::ts') => pair (list_comb (f', ts')))
   142           end
   143       | subst _ t fs = (t, fs);
   144 
   145     (* translate rec equations into function arguments suitable for rec comb *)
   146 
   147     fun trans eqns (cname, cargs) (fnames', fnss', fns) =
   148       (case AList.lookup (op =) eqns cname of
   149           NONE => (warning ("No equation for constructor " ^ quote cname ^
   150             "\nin definition of function " ^ quote fname);
   151               (fnames', fnss', (Const (@{const_name undefined}, dummyT))::fns))
   152         | SOME (ls, cargs', rs, rhs, eq) =>
   153             let
   154               val recs = filter (is_rec_type o snd) (cargs' ~~ cargs);
   155               val rargs = map fst recs;
   156               val subs = map (rpair dummyT o fst)
   157                 (rev (rename_wrt_term rhs rargs));
   158               val (rhs', (fnames'', fnss'')) = subst (map2 (fn (x, y) => fn z =>
   159                 (Free x, (body_index y, Free z))) recs subs) rhs (fnames', fnss')
   160                   handle RecError s => primrec_eq_err lthy s eq
   161             in (fnames'', fnss'', 
   162                 (list_abs_free (cargs' @ subs, rhs'))::fns)
   163             end)
   164 
   165   in (case AList.lookup (op =) fnames i of
   166       NONE =>
   167         if exists (fn (_, v) => fname = v) fnames 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 =) eqns fname;
   173             val (fnames', fnss', fns) = fold_rev (trans eqns') constrs
   174               ((i, fname)::fnames, fnss, []) 
   175           in
   176             (fnames', (i, (fname, ls, rs, fns))::fnss')
   177           end
   178     | SOME fname' =>
   179         if fname = fname' then (fnames, 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 (@{const_name undefined},
   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 ctxt fixes 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 raw_rhs = list_abs_free (frees,
   208       list_comb (Const (rec_name, dummyT), fs @ [Free x]))
   209     val def_name = Thm.def_name (Sign.base_name fname);
   210     val rhs = singleton (Syntax.check_terms ctxt) raw_rhs;
   211     val SOME var = get_first (fn ((b, _), mx) =>
   212       if Binding.base_name b = fname then SOME (b, mx) else NONE) fixes;
   213   in
   214     ((var, ((Binding.name def_name, []), rhs)),
   215      subst_bounds (rev (map Free frees), strip_abs_body rhs))
   216   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 prepare_spec prep_spec ctxt raw_fixes raw_spec =
   238   let
   239     val ((fixes, spec), _) = prep_spec
   240       raw_fixes (map (single o apsnd single) raw_spec) ctxt
   241   in (fixes, map (apsnd the_single) spec) end;
   242 
   243 fun gen_primrec set_group prep_spec prep_term invs fctxt raw_fixes raw_params raw_spec lthy =
   244   let
   245     val (fixes', spec) = prepare_spec prep_spec lthy (raw_fixes @ raw_params) raw_spec;
   246     val fixes = List.take (fixes', length raw_fixes);
   247     val (names_atts, spec') = split_list spec;
   248     val eqns' = map unquantify spec'
   249     val eqns = fold_rev (process_eqn lthy (fn v => Variable.is_fixed lthy v
   250       orelse exists (fn ((w, _), _) => v = Binding.base_name w) fixes)) spec' [];
   251     val dt_info = NominalPackage.get_nominal_datatypes (ProofContext.theory_of lthy);
   252     val lsrs :: lsrss = maps (fn (_, (_, _, eqns)) =>
   253       map (fn (_, (ls, _, rs, _, _)) => ls @ rs) eqns) eqns
   254     val _ =
   255       (if forall (curry eq_set lsrs) lsrss andalso forall
   256          (fn (_, (_, _, (_, (ls, _, rs, _, _)) :: eqns)) =>
   257                forall (fn (_, (ls', _, rs', _, _)) =>
   258                  ls = ls' andalso rs = rs') eqns
   259            | _ => true) eqns
   260        then () else primrec_err param_err);
   261     val tnames = distinct (op =) (map (#1 o snd) eqns);
   262     val dts = find_dts dt_info tnames tnames;
   263     val main_fns = 
   264       map (fn (tname, {index, ...}) =>
   265         (index, 
   266           (fst o the o find_first (fn (_, x) => #1 x = tname)) eqns))
   267       dts;
   268     val {descr, rec_names, rec_rewrites, ...} = 
   269       if null dts then
   270         primrec_err ("datatypes " ^ commas_quote tnames ^ "\nare not mutually recursive")
   271       else snd (hd dts);
   272     val descr = map (fn (i, (tname, args, constrs)) => (i, (tname, args,
   273       map (fn (cname, cargs) => (cname, fold (fn (dTs, dT) => fn dTs' =>
   274         dTs' @ dTs @ [dT]) cargs [])) constrs))) descr;
   275     val (fnames, fnss) = fold_rev (process_fun lthy descr eqns) main_fns ([], []);
   276     val (fs, defs) = fold_rev (get_fns fnss) (descr ~~ rec_names) ([], []);
   277     val defs' = map (make_def lthy fixes fs) defs;
   278     val names1 = map snd fnames;
   279     val names2 = map fst eqns;
   280     val _ = if gen_eq_set (op =) (names1, names2) then ()
   281       else primrec_err ("functions " ^ commas_quote names2 ^
   282         "\nare not mutually recursive");
   283     val (defs_thms, lthy') = lthy |>
   284       set_group ? LocalTheory.set_group (serial_string ()) |>
   285       fold_map (apfst (snd o snd) oo
   286         LocalTheory.define Thm.definitionK o fst) defs';
   287     val qualify = Binding.qualify
   288       (space_implode "_" (map (Sign.base_name o #1) defs));
   289     val names_atts' = map (apfst qualify) names_atts;
   290     val cert = cterm_of (ProofContext.theory_of lthy');
   291 
   292     fun mk_idx eq =
   293       let
   294         val Free (name, _) = head_of (fst (HOLogic.dest_eq (HOLogic.dest_Trueprop
   295           (Logic.strip_imp_concl eq))));
   296         val SOME i = AList.lookup op = (map swap fnames) name;
   297         val SOME (_, _, constrs) = AList.lookup op = descr i;
   298         val SOME (_, _, eqns'') = AList.lookup op = eqns name;
   299         val SOME (cname, (_, cargs, _, _, _)) = find_first
   300           (fn (_, (_, _, _, _, eq')) => eq = eq') eqns''
   301       in (i, find_index (fn (cname', _) => cname = cname') constrs, cargs) end;
   302 
   303     val rec_rewritess =
   304       unflat (map (fn (_, (_, _, constrs)) => constrs) descr) rec_rewrites;
   305     val fvars = rec_rewrites |> hd |> concl_of |> HOLogic.dest_Trueprop |>
   306       HOLogic.dest_eq |> fst |> strip_comb |> snd |> take_prefix is_Var |> fst;
   307     val (pvars, ctxtvars) = List.partition
   308       (equal HOLogic.boolT o body_type o snd)
   309       (fold_rev Term.add_vars (map Logic.strip_assums_concl
   310         (prems_of (hd rec_rewrites))) [] \\ map dest_Var fvars);
   311     val cfs = defs' |> hd |> snd |> strip_comb |> snd |>
   312       curry (List.take o swap) (length fvars) |> map cert;
   313     val invs' = (case invs of
   314         NONE => map (fn (i, _) =>
   315           Abs ("x", fastype_of (snd (nth defs' i)), HOLogic.true_const)) descr
   316       | SOME invs' => map (prep_term lthy') invs');
   317     val inst = (map cert fvars ~~ cfs) @
   318       (map (cert o Var) pvars ~~ map cert invs') @
   319       (case ctxtvars of
   320          [ctxtvar] => [(cert (Var ctxtvar),
   321            cert (the_default HOLogic.unit (Option.map (prep_term lthy') fctxt)))]
   322        | _ => []);
   323     val rec_rewrites' = map (fn eq =>
   324       let
   325         val (i, j, cargs) = mk_idx eq
   326         val th = nth (nth rec_rewritess i) j;
   327         val cargs' = th |> concl_of |> HOLogic.dest_Trueprop |>
   328           HOLogic.dest_eq |> fst |> strip_comb |> snd |> split_last |> snd |>
   329           strip_comb |> snd
   330       in (cargs, Logic.strip_imp_prems eq,
   331         Drule.cterm_instantiate (inst @
   332           (map cert cargs' ~~ map (cert o Free) cargs)) th)
   333       end) eqns';
   334 
   335     val prems = foldr1 (common_prefix op aconv) (map (prems_of o #3) rec_rewrites');
   336     val cprems = map cert prems;
   337     val asms = map Thm.assume cprems;
   338     val premss = map (fn (cargs, eprems, eqn) =>
   339       map (fn t => list_all_free (cargs, Logic.list_implies (eprems, t)))
   340         (List.drop (prems_of eqn, length prems))) rec_rewrites';
   341     val cpremss = map (map cert) premss;
   342     val asmss = map (map Thm.assume) cpremss;
   343 
   344     fun mk_eqn ((cargs, eprems, eqn), asms') =
   345       let
   346         val ceprems = map cert eprems;
   347         val asms'' = map Thm.assume ceprems;
   348         val ccargs = map (cert o Free) cargs;
   349         val asms''' = map (fn th => implies_elim_list
   350           (forall_elim_list ccargs th) asms'') asms'
   351       in
   352         implies_elim_list eqn (asms @ asms''') |>
   353         implies_intr_list ceprems |>
   354         forall_intr_list ccargs
   355       end;
   356 
   357     val rule_prems = cprems @ flat cpremss;
   358     val rule = implies_intr_list rule_prems
   359       (Conjunction.intr_balanced (map mk_eqn (rec_rewrites' ~~ asmss)));
   360 
   361     val goals = map (fn ((cargs, _, _), eqn) =>
   362       (list_all_free (cargs, eqn), [])) (rec_rewrites' ~~ eqns');
   363 
   364   in
   365     lthy' |>
   366     Variable.add_fixes (map fst lsrs) |> snd |>
   367     Proof.theorem_i NONE
   368       (fn thss => fn goal_ctxt =>
   369          let
   370            val simps = ProofContext.export goal_ctxt lthy' (flat thss);
   371            val (simps', lthy'') = fold_map (LocalTheory.note Thm.theoremK)
   372              (names_atts' ~~ map single simps) lthy'
   373          in
   374            lthy''
   375            |> LocalTheory.note Thm.theoremK ((qualify (Binding.name "simps"),
   376              [Attrib.internal (K Simplifier.simp_add)]), maps snd simps')
   377            |> snd
   378          end)
   379       [goals] |>
   380     Proof.apply (Method.Basic (fn _ => Method.RAW_METHOD (fn _ =>
   381       rewrite_goals_tac defs_thms THEN
   382       compose_tac (false, rule, length rule_prems) 1), Position.none)) |>
   383     Seq.hd
   384   end;
   385 
   386 in
   387 
   388 val add_primrec = gen_primrec false Specification.check_specification (K I);
   389 val add_primrec_cmd = gen_primrec true Specification.read_specification Syntax.read_term;
   390 
   391 end;
   392 
   393 
   394 (* outer syntax *)
   395 
   396 local structure P = OuterParse and K = OuterKeyword in
   397 
   398 val freshness_context = P.reserved "freshness_context";
   399 val invariant = P.reserved "invariant";
   400 
   401 fun unless_flag scan = Scan.unless ((freshness_context || invariant) -- P.$$$ ":") scan;
   402 
   403 val parser1 = (freshness_context -- P.$$$ ":") |-- unless_flag P.term >> SOME;
   404 val parser2 = (invariant -- P.$$$ ":") |--
   405     (Scan.repeat1 (unless_flag P.term) >> SOME) -- Scan.optional parser1 NONE ||
   406   (parser1 >> pair NONE);
   407 val options =
   408   Scan.optional (P.$$$ "(" |-- P.!!!
   409     (parser2 --| P.$$$ ")")) (NONE, NONE);
   410 
   411 fun pipe_error t = P.!!! (Scan.fail_with (K
   412   (cat_lines ["Equations must be separated by " ^ quote "|", quote t])));
   413 
   414 val statement = SpecParse.opt_thm_name ":" -- P.prop --| Scan.ahead
   415   ((P.term :-- pipe_error) || Scan.succeed ("",""));
   416 
   417 val statements = P.enum1 "|" statement;
   418 
   419 val primrec_decl = P.opt_target -- options --
   420   P.fixes -- P.for_fixes --| P.$$$ "where" -- statements;
   421 
   422 val _ =
   423   OuterSyntax.command "nominal_primrec" "define primitive recursive functions on nominal datatypes" K.thy_goal
   424     (primrec_decl >> (fn ((((opt_target, (invs, fctxt)), raw_fixes), raw_params), raw_spec) =>
   425       Toplevel.print o Toplevel.local_theory_to_proof opt_target
   426         (add_primrec_cmd invs fctxt raw_fixes raw_params raw_spec)));
   427 
   428 end;
   429 
   430 
   431 end;
   432