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