src/HOL/HOLCF/Tools/fixrec.ML
author huffman
Sat Nov 27 16:08:10 2010 -0800 (2010-11-27)
changeset 40774 0437dbc127b3
parent 40327 src/HOLCF/Tools/fixrec.ML@1dfdbd66093a
child 40832 4352ca878c41
permissions -rw-r--r--
moved directory src/HOLCF to src/HOL/HOLCF;
added HOLCF theories to src/HOL/IsaMakefile;
     1 (*  Title:      HOLCF/Tools/fixrec.ML
     2     Author:     Amber Telfer and Brian Huffman
     3 
     4 Recursive function definition package for HOLCF.
     5 *)
     6 
     7 signature FIXREC =
     8 sig
     9   val add_fixrec: (binding * typ option * mixfix) list
    10     -> (bool * (Attrib.binding * term)) list -> local_theory -> local_theory
    11   val add_fixrec_cmd: (binding * string option * mixfix) list
    12     -> (bool * (Attrib.binding * string)) list -> local_theory -> local_theory
    13   val add_matchers: (string * string) list -> theory -> theory
    14   val fixrec_simp_tac: Proof.context -> int -> tactic
    15   val setup: theory -> theory
    16 end;
    17 
    18 structure Fixrec :> FIXREC =
    19 struct
    20 
    21 open HOLCF_Library;
    22 
    23 infixr 6 ->>;
    24 infix -->>;
    25 infix 9 `;
    26 
    27 val def_cont_fix_eq = @{thm def_cont_fix_eq};
    28 val def_cont_fix_ind = @{thm def_cont_fix_ind};
    29 
    30 fun fixrec_err s = error ("fixrec definition error:\n" ^ s);
    31 fun fixrec_eq_err thy s eq =
    32   fixrec_err (s ^ "\nin\n" ^ quote (Syntax.string_of_term_global thy eq));
    33 
    34 (*************************************************************************)
    35 (***************************** building types ****************************)
    36 (*************************************************************************)
    37 
    38 local
    39 
    40 fun binder_cfun (Type(@{type_name cfun},[T, U])) = T :: binder_cfun U
    41   | binder_cfun (Type(@{type_name "fun"},[T, U])) = T :: binder_cfun U
    42   | binder_cfun _   =  [];
    43 
    44 fun body_cfun (Type(@{type_name cfun},[T, U])) = body_cfun U
    45   | body_cfun (Type(@{type_name "fun"},[T, U])) = body_cfun U
    46   | body_cfun T   =  T;
    47 
    48 fun strip_cfun T : typ list * typ =
    49   (binder_cfun T, body_cfun T);
    50 
    51 in
    52 
    53 fun matcherT (T, U) =
    54   body_cfun T ->> (binder_cfun T -->> U) ->> U;
    55 
    56 end
    57 
    58 (*************************************************************************)
    59 (***************************** building terms ****************************)
    60 (*************************************************************************)
    61 
    62 val mk_trp = HOLogic.mk_Trueprop;
    63 
    64 (* splits a cterm into the right and lefthand sides of equality *)
    65 fun dest_eqs t = HOLogic.dest_eq (HOLogic.dest_Trueprop t);
    66 
    67 (* similar to Thm.head_of, but for continuous application *)
    68 fun chead_of (Const(@{const_name Rep_cfun},_)$f$t) = chead_of f
    69   | chead_of u = u;
    70 
    71 infix 0 ==;  val (op ==) = Logic.mk_equals;
    72 infix 1 ===; val (op ===) = HOLogic.mk_eq;
    73 
    74 fun mk_mplus (t, u) =
    75   let val mT = Term.fastype_of t
    76   in Const(@{const_name Fixrec.mplus}, mT ->> mT ->> mT) ` t ` u end;
    77 
    78 fun mk_run t =
    79   let
    80     val mT = Term.fastype_of t
    81     val T = dest_matchT mT
    82     val run = Const(@{const_name Fixrec.run}, mT ->> T)
    83   in
    84     case t of
    85       Const(@{const_name Rep_cfun}, _) $
    86         Const(@{const_name Fixrec.succeed}, _) $ u => u
    87     | _ => run ` t
    88   end;
    89 
    90 
    91 (*************************************************************************)
    92 (************* fixed-point definitions and unfolding theorems ************)
    93 (*************************************************************************)
    94 
    95 structure FixrecUnfoldData = Generic_Data
    96 (
    97   type T = thm Symtab.table;
    98   val empty = Symtab.empty;
    99   val extend = I;
   100   fun merge data : T = Symtab.merge (K true) data;
   101 );
   102 
   103 local
   104 
   105 fun name_of (Const (n, T)) = n
   106   | name_of (Free (n, T)) = n
   107   | name_of t = raise TERM ("Fixrec.add_unfold: lhs not a constant", [t]);
   108 
   109 val lhs_name =
   110   name_of o head_of o fst o HOLogic.dest_eq o HOLogic.dest_Trueprop o prop_of;
   111 
   112 in
   113 
   114 val add_unfold : attribute =
   115   Thm.declaration_attribute
   116     (fn th => FixrecUnfoldData.map (Symtab.insert (K true) (lhs_name th, th)));
   117 
   118 end
   119 
   120 fun add_fixdefs
   121   (fixes : ((binding * typ) * mixfix) list)
   122   (spec : (Attrib.binding * term) list)
   123   (lthy : local_theory) =
   124   let
   125     val thy = ProofContext.theory_of lthy;
   126     val names = map (Binding.name_of o fst o fst) fixes;
   127     val all_names = space_implode "_" names;
   128     val (lhss, rhss) = ListPair.unzip (map (dest_eqs o snd) spec);
   129     val functional = lambda_tuple lhss (mk_tuple rhss);
   130     val fixpoint = mk_fix (mk_cabs functional);
   131 
   132     val cont_thm =
   133       let
   134         val prop = mk_trp (mk_cont functional);
   135         fun err _ = error (
   136           "Continuity proof failed; please check that cont2cont rules\n" ^
   137           "or simp rules are configured for all non-HOLCF constants.\n" ^
   138           "The error occurred for the goal statement:\n" ^
   139           Syntax.string_of_term lthy prop);
   140         val rules = Cont2ContData.get lthy;
   141         val fast_tac = SOLVED' (REPEAT_ALL_NEW (match_tac rules));
   142         val slow_tac = SOLVED' (simp_tac (simpset_of lthy));
   143         val tac = fast_tac 1 ORELSE slow_tac 1 ORELSE err;
   144       in
   145         Goal.prove lthy [] [] prop (K tac)
   146       end;
   147 
   148     fun one_def (l as Free(n,_)) r =
   149           let val b = Long_Name.base_name n
   150           in ((Binding.name (b^"_def"), []), r) end
   151       | one_def _ _ = fixrec_err "fixdefs: lhs not of correct form";
   152     fun defs [] _ = []
   153       | defs (l::[]) r = [one_def l r]
   154       | defs (l::ls) r = one_def l (mk_fst r) :: defs ls (mk_snd r);
   155     val fixdefs = defs lhss fixpoint;
   156     val (fixdef_thms : (term * (string * thm)) list, lthy) = lthy
   157       |> fold_map Local_Theory.define (map (apfst fst) fixes ~~ fixdefs);
   158     fun pair_equalI (thm1, thm2) = @{thm Pair_equalI} OF [thm1, thm2];
   159     val tuple_fixdef_thm = foldr1 pair_equalI (map (snd o snd) fixdef_thms);
   160     val P = Var (("P", 0), map Term.fastype_of lhss ---> HOLogic.boolT);
   161     val predicate = lambda_tuple lhss (list_comb (P, lhss));
   162     val tuple_induct_thm = (def_cont_fix_ind OF [tuple_fixdef_thm, cont_thm])
   163       |> Drule.instantiate' [] [SOME (Thm.cterm_of thy predicate)]
   164       |> Local_Defs.unfold lthy @{thms split_paired_all split_conv split_strict};
   165     val tuple_unfold_thm = (def_cont_fix_eq OF [tuple_fixdef_thm, cont_thm])
   166       |> Local_Defs.unfold lthy @{thms split_conv};
   167     fun unfolds [] thm = []
   168       | unfolds (n::[]) thm = [(n, thm)]
   169       | unfolds (n::ns) thm = let
   170           val thmL = thm RS @{thm Pair_eqD1};
   171           val thmR = thm RS @{thm Pair_eqD2};
   172         in (n, thmL) :: unfolds ns thmR end;
   173     val unfold_thms = unfolds names tuple_unfold_thm;
   174     val induct_note : Attrib.binding * Thm.thm list =
   175       let
   176         val thm_name = Binding.qualify true all_names (Binding.name "induct");
   177       in
   178         ((thm_name, []), [tuple_induct_thm])
   179       end;
   180     fun unfold_note (name, thm) : Attrib.binding * Thm.thm list =
   181       let
   182         val thm_name = Binding.qualify true name (Binding.name "unfold");
   183         val src = Attrib.internal (K add_unfold);
   184       in
   185         ((thm_name, [src]), [thm])
   186       end;
   187     val (thmss, lthy) = lthy
   188       |> fold_map Local_Theory.note (induct_note :: map unfold_note unfold_thms);
   189   in
   190     (lthy, names, fixdef_thms, map snd unfold_thms)
   191   end;
   192 
   193 (*************************************************************************)
   194 (*********** monadic notation and pattern matching compilation ***********)
   195 (*************************************************************************)
   196 
   197 structure FixrecMatchData = Theory_Data
   198 (
   199   type T = string Symtab.table;
   200   val empty = Symtab.empty;
   201   val extend = I;
   202   fun merge data = Symtab.merge (K true) data;
   203 );
   204 
   205 (* associate match functions with pattern constants *)
   206 fun add_matchers ms = FixrecMatchData.map (fold Symtab.update ms);
   207 
   208 fun taken_names (t : term) : bstring list =
   209   let
   210     fun taken (Const(a,_), bs) = insert (op =) (Long_Name.base_name a) bs
   211       | taken (Free(a,_) , bs) = insert (op =) a bs
   212       | taken (f $ u     , bs) = taken (f, taken (u, bs))
   213       | taken (Abs(a,_,t), bs) = taken (t, insert (op =) a bs)
   214       | taken (_         , bs) = bs;
   215   in
   216     taken (t, [])
   217   end;
   218 
   219 (* builds a monadic term for matching a pattern *)
   220 (* returns (rhs, free variable, used varnames) *)
   221 fun compile_pat match_name pat rhs taken =
   222   let
   223     fun comp_pat p rhs taken =
   224       if is_Free p then (rhs, p, taken)
   225       else comp_con (fastype_of p) p rhs [] taken
   226     (* compiles a monadic term for a constructor pattern *)
   227     and comp_con T p rhs vs taken =
   228       case p of
   229         Const(@{const_name Rep_cfun},_) $ f $ x =>
   230           let val (rhs', v, taken') = comp_pat x rhs taken
   231           in comp_con T f rhs' (v::vs) taken' end
   232       | f $ x =>
   233           let val (rhs', v, taken') = comp_pat x rhs taken
   234           in comp_con T f rhs' (v::vs) taken' end
   235       | Const (c, cT) =>
   236           let
   237             val n = Name.variant taken "v"
   238             val v = Free(n, T)
   239             val m = Const(match_name c, matcherT (cT, fastype_of rhs))
   240             val k = big_lambdas vs rhs
   241           in
   242             (m`v`k, v, n::taken)
   243           end
   244       | _ => raise TERM ("fixrec: invalid pattern ", [p])
   245   in
   246     comp_pat pat rhs taken
   247   end;
   248 
   249 (* builds a monadic term for matching a function definition pattern *)
   250 (* returns (constant, (vars, matcher)) *)
   251 fun compile_lhs match_name pat rhs vs taken =
   252   case pat of
   253     Const(@{const_name Rep_cfun}, _) $ f $ x =>
   254       let val (rhs', v, taken') = compile_pat match_name x rhs taken;
   255       in compile_lhs match_name f rhs' (v::vs) taken' end
   256   | Free(_,_) => (pat, (vs, rhs))
   257   | Const(_,_) => (pat, (vs, rhs))
   258   | _ => fixrec_err ("invalid function pattern: "
   259                     ^ ML_Syntax.print_term pat);
   260 
   261 fun strip_alls t =
   262   if Logic.is_all t then strip_alls (snd (Logic.dest_all t)) else t;
   263 
   264 fun compile_eq match_name eq =
   265   let
   266     val (lhs,rhs) = dest_eqs (Logic.strip_imp_concl (strip_alls eq));
   267   in
   268     compile_lhs match_name lhs (mk_succeed rhs) [] (taken_names eq)
   269   end;
   270 
   271 (* this is the pattern-matching compiler function *)
   272 fun compile_eqs match_name eqs =
   273   let
   274     val (consts, matchers) =
   275       ListPair.unzip (map (compile_eq match_name) eqs);
   276     val const =
   277         case distinct (op =) consts of
   278           [n] => n
   279         | _ => fixrec_err "all equations in block must define the same function";
   280     val vars =
   281         case distinct (op = o pairself length) (map fst matchers) of
   282           [vars] => vars
   283         | _ => fixrec_err "all equations in block must have the same arity";
   284     (* rename so all matchers use same free variables *)
   285     fun rename (vs, t) = Term.subst_free (filter_out (op =) (vs ~~ vars)) t;
   286     val rhs = big_lambdas vars (mk_run (foldr1 mk_mplus (map rename matchers)));
   287   in
   288     mk_trp (const === rhs)
   289   end;
   290 
   291 (*************************************************************************)
   292 (********************** Proving associated theorems **********************)
   293 (*************************************************************************)
   294 
   295 fun eta_tac i = CONVERSION Thm.eta_conversion i;
   296 
   297 fun fixrec_simp_tac ctxt =
   298   let
   299     val tab = FixrecUnfoldData.get (Context.Proof ctxt);
   300     val ss = Simplifier.simpset_of ctxt;
   301     fun concl t =
   302       if Logic.is_all t then concl (snd (Logic.dest_all t))
   303       else HOLogic.dest_Trueprop (Logic.strip_imp_concl t);
   304     fun tac (t, i) =
   305       let
   306         val (c, T) =
   307             (dest_Const o head_of o chead_of o fst o HOLogic.dest_eq o concl) t;
   308         val unfold_thm = the (Symtab.lookup tab c);
   309         val rule = unfold_thm RS @{thm ssubst_lhs};
   310       in
   311         CHANGED (rtac rule i THEN eta_tac i THEN asm_simp_tac ss i)
   312       end
   313   in
   314     SUBGOAL (fn ti => the_default no_tac (try tac ti))
   315   end;
   316 
   317 (* proves a block of pattern matching equations as theorems, using unfold *)
   318 fun make_simps ctxt (unfold_thm, eqns : (Attrib.binding * term) list) =
   319   let
   320     val ss = Simplifier.simpset_of ctxt;
   321     val rule = unfold_thm RS @{thm ssubst_lhs};
   322     val tac = rtac rule 1 THEN eta_tac 1 THEN asm_simp_tac ss 1;
   323     fun prove_term t = Goal.prove ctxt [] [] t (K tac);
   324     fun prove_eqn (bind, eqn_t) = (bind, prove_term eqn_t);
   325   in
   326     map prove_eqn eqns
   327   end;
   328 
   329 (*************************************************************************)
   330 (************************* Main fixrec function **************************)
   331 (*************************************************************************)
   332 
   333 local
   334 (* code adapted from HOL/Tools/primrec.ML *)
   335 
   336 fun gen_fixrec
   337   prep_spec
   338   (raw_fixes : (binding * 'a option * mixfix) list)
   339   (raw_spec' : (bool * (Attrib.binding * 'b)) list)
   340   (lthy : local_theory) =
   341   let
   342     val (skips, raw_spec) = ListPair.unzip raw_spec';
   343     val (fixes : ((binding * typ) * mixfix) list,
   344          spec : (Attrib.binding * term) list) =
   345           fst (prep_spec raw_fixes raw_spec lthy);
   346     val chead_of_spec =
   347       chead_of o fst o dest_eqs o Logic.strip_imp_concl o strip_alls o snd;
   348     fun name_of (Free (n, _)) = n
   349       | name_of t = fixrec_err ("unknown term");
   350     val all_names = map (name_of o chead_of_spec) spec;
   351     val names = distinct (op =) all_names;
   352     fun block_of_name n =
   353       map_filter
   354         (fn (m,eq) => if m = n then SOME eq else NONE)
   355         (all_names ~~ (spec ~~ skips));
   356     val blocks = map block_of_name names;
   357 
   358     val matcher_tab = FixrecMatchData.get (ProofContext.theory_of lthy);
   359     fun match_name c =
   360       case Symtab.lookup matcher_tab c of SOME m => m
   361         | NONE => fixrec_err ("unknown pattern constructor: " ^ c);
   362 
   363     val matches = map (compile_eqs match_name) (map (map (snd o fst)) blocks);
   364     val spec' = map (pair Attrib.empty_binding) matches;
   365     val (lthy, cnames, fixdef_thms, unfold_thms) =
   366       add_fixdefs fixes spec' lthy;
   367 
   368     val blocks' = map (map fst o filter_out snd) blocks;
   369     val simps : (Attrib.binding * thm) list list =
   370       map (make_simps lthy) (unfold_thms ~~ blocks');
   371     fun mk_bind n : Attrib.binding =
   372      (Binding.qualify true n (Binding.name "simps"),
   373        [Attrib.internal (K Simplifier.simp_add)]);
   374     val simps1 : (Attrib.binding * thm list) list =
   375       map (fn (n,xs) => (mk_bind n, map snd xs)) (names ~~ simps);
   376     val simps2 : (Attrib.binding * thm list) list =
   377       map (apsnd (fn thm => [thm])) (flat simps);
   378     val (_, lthy) = lthy
   379       |> fold_map Local_Theory.note (simps1 @ simps2);
   380   in
   381     lthy
   382   end;
   383 
   384 in
   385 
   386 val add_fixrec = gen_fixrec Specification.check_spec;
   387 val add_fixrec_cmd = gen_fixrec Specification.read_spec;
   388 
   389 end; (* local *)
   390 
   391 
   392 (*************************************************************************)
   393 (******************************** Parsers ********************************)
   394 (*************************************************************************)
   395 
   396 val opt_thm_name' : (bool * Attrib.binding) parser =
   397   Parse.$$$ "(" -- Parse.$$$ "unchecked" -- Parse.$$$ ")" >> K (true, Attrib.empty_binding)
   398     || Parse_Spec.opt_thm_name ":" >> pair false;
   399 
   400 val spec' : (bool * (Attrib.binding * string)) parser =
   401   opt_thm_name' -- Parse.prop >> (fn ((a, b), c) => (a, (b, c)));
   402 
   403 val alt_specs' : (bool * (Attrib.binding * string)) list parser =
   404   let val unexpected = Scan.ahead (Parse.name || Parse.$$$ "[" || Parse.$$$ "(");
   405   in Parse.enum1 "|" (spec' --| Scan.option (unexpected -- Parse.!!! (Parse.$$$ "|"))) end;
   406 
   407 val _ =
   408   Outer_Syntax.local_theory "fixrec" "define recursive functions (HOLCF)" Keyword.thy_decl
   409     (Parse.fixes -- (Parse.where_ |-- Parse.!!! alt_specs')
   410       >> (fn (fixes, specs) => add_fixrec_cmd fixes specs));
   411 
   412 val setup =
   413   Method.setup @{binding fixrec_simp}
   414     (Scan.succeed (SIMPLE_METHOD' o fixrec_simp_tac))
   415     "pattern prover for fixrec constants";
   416 
   417 end;