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